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": " :file-input-key (gensym \"wdl-uploader-\"))\n (",
"end": 5358,
"score": 0.8422654867172241,
"start": 5345,
"tag": "KEY",
"value": "wdl-uploader-"
}
] |
src/cljs/main/broadfcui/page/method_repo/create_method.cljs
|
epam/firecloud-ui
| 0 |
(ns broadfcui.page.method-repo.create-method
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.codemirror :refer [CodeMirror]]
[broadfcui.common.components :as comps]
[broadfcui.common.input :as input]
[broadfcui.common.links :as links]
[broadfcui.common.style :as style]
[broadfcui.components.buttons :as buttons]
[broadfcui.components.modals :as modals]
[broadfcui.endpoints :as endpoints]
[broadfcui.utils :as utils]
))
(defn- build-info [{:keys [duplicate snapshot]}]
(cond duplicate (merge {:header "Clone Method"
:name (str (:name duplicate) "_copy")
:ok-text "Create New Method"}
(select-keys duplicate [:synopsis :documentation :payload]))
snapshot (merge {:header "Edit Method"
:ok-text "Save As New Snapshot"
:locked #{:namespace :name}
:edit-mode? true}
(select-keys snapshot [:namespace :name :snapshotId :synopsis :documentation :payload]))
:else {:header "Create New Method"
:ok-text "Upload"}))
(defn- build-new-entity-id [get-parsed-response]
(let [{:keys [namespace name snapshotId]} (get-parsed-response)]
(assoc (utils/restructure namespace name) :snapshot-id snapshotId)))
(react/defc CreateMethodDialog
{:component-will-mount
(fn [{:keys [props locals]}]
(swap! locals assoc :info (build-info props)))
:render
(fn [{:keys [props state refs locals this]}]
(let [{:keys [info]} @locals]
[modals/OKCancelForm
{:header (:header info)
:dismiss (:dismiss props)
:get-first-element-dom-node #(react/find-dom-node (@refs "namespace"))
:get-last-element-dom-node #(react/find-dom-node (@refs "ok-button"))
:content
(react/create-element
[:div {:style {:width "80vw"}}
(when-let [banner (:banner @state)]
[comps/Blocker {:banner banner}])
[:div {:style {:display "flex" :justifyContent "space-between"}}
[:div {:style {:flex "1 0 auto" :marginRight "1em"}}
(style/create-form-label "Namespace")
[input/TextField {:data-test-id "namespace-field"
:ref "namespace" :style {:width "100%"}
:defaultValue (:namespace info)
:disabled (contains? (:locked info) :namespace)
:predicates [(input/nonempty "Method namespace")
(input/alphanumeric_-period "Method namespace")]}]
(style/create-textfield-hint input/hint-alphanumeric_-period)]
[:div {:style {:flex "1 0 auto"}}
(style/create-form-label "Name")
[input/TextField {:data-test-id "name-field"
:ref "name" :style {:autoFocus true :width "100%"}
:defaultValue (:name info)
:disabled (contains? (:locked info) :name)
:predicates [(input/nonempty "Method name")
(input/alphanumeric_-period "Method name")]}]
(style/create-textfield-hint input/hint-alphanumeric_-period)]]
;;GAWB-1897 removes Type field and makes all MC types "Workflow" until "Task" type is supported
(style/create-form-label "Synopsis (optional, 80 characters max)")
(style/create-text-field {:data-test-id "synopsis-field"
:ref "synopsis"
:defaultValue (:synopsis info)
:maxLength 80
:style {:width "100%"}})
(style/create-form-label "Documentation (optional)")
(style/create-text-area {:data-test-id "documentation-field"
:ref "documentation"
:defaultValue (:documentation info)
:style {:width "100%"}
:rows 5})
;; This key is changed every time a file is selected causing React to completely replace the
;; element. Otherwise, if a user selects the same file (even after having modified it), the
;; browser will not fire the onChange event.
[:input {:key (:file-input-key @state)
:type "file"
:ref "wdl-uploader"
:style {:display "none"}
:onChange (fn [e]
(let [file (-> e .-target .-files (aget 0))
reader (js/FileReader.)]
(when file
(set! (.-onload reader)
#(let [text (.-result reader)]
(swap! state assoc
:file-name (.-name file)
:file-contents text
:file-input-key (gensym "wdl-uploader-"))
(this :-set-wdl-text text)))
(.readAsText reader file))))}]
(style/create-form-label
(let [{:keys [file-name]
{:strs [undo redo]} :undo-history} @state
[undo? redo?] (map pos? [undo redo])
link (fn [label enabled?]
(if enabled?
(links/create-internal {:onClick #((@refs "wdl-editor") :call-method label)
:style {:color (:text-light style/colors)
:backgroundColor "white"
:padding "0 6px"
:border style/standard-line}}
(string/capitalize label))
[:span {:style {:color (:text-lighter style/colors)
:padding "0 6px"
:border style/standard-line}}
(string/capitalize label)]))]
[:div {:style {:display "flex" :alignItems "baseline" :width "100%"}}
[:span {:style {:paddingRight "1em"}} "WDL"]
(links/create-internal {:onClick #(.click (@refs "wdl-uploader"))} "Load from file...")
(when file-name
[:span {}
[:span {:style {:padding "0 1em 0 25px"}} (str "Selected: " file-name)]
(links/create-internal {:onClick #(this :-set-wdl-text (:file-contents @state))} "Reset to file")])
[:span {:style {:flex "1 0 auto"}}]
(link "undo" undo?)
(link "redo" redo?)]))
[:style {} ".CodeMirror {height: 300px}"]
[CodeMirror {:data-test-id "wdl-field"
:ref "wdl-editor" :text (:payload info) :read-only? false
:initialize (fn [self]
(self :add-listener "change"
#(swap! state assoc :undo-history
(js->clj (self :call-method "historySize")))))}]
[:div {:style {:padding "0.25rem"}}]
(style/create-form-label "Snapshot Comment (optional)")
(style/create-text-area {:data-test-id "snapshot-comment-field"
:ref "snapshot-comment"
:defaultValue (:snapshot-comment info)
:style {:width "100%"}
:rows 1})
(when (:edit-mode? info)
[comps/Checkbox {:ref "redact-checkbox"
:label (str "Redact Snapshot " (:snapshotId info))}])
[comps/ErrorViewer {:error (:upload-error @state)}]
(style/create-validation-error-message (:validation-errors @state))])
:ok-button (react/create-element
[buttons/Button {:data-test-id "ok-button"
:ref "ok-button"
:text (:ok-text info)
:onClick #(this :-create-method)}])}]))
:-set-wdl-text
(fn [{:keys [refs]} text]
((@refs "wdl-editor") :call-method "setValue" text))
:-create-method
(fn [{:keys [state locals refs this]}]
(let [[namespace name & fails] (input/get-and-validate refs "namespace" "name")
[synopsis documentation snapshotComment] (common/get-text refs "synopsis" "documentation" "snapshot-comment")
wdl ((@refs "wdl-editor") :call-method "getValue")
fails (or fails (when (string/blank? wdl) ["Please enter the WDL payload"]))]
(swap! state assoc :validation-errors fails)
(when-not fails
(swap! state assoc :banner "Uploading...")
(if (:edit-mode? (:info @locals))
(let [{:keys [snapshotId]} (:info @locals)
redact? ((@refs "redact-checkbox") :checked?)]
(endpoints/call-ajax-orch
{:endpoint (endpoints/create-new-method-snapshot namespace name snapshotId redact?)
:payload (assoc (utils/restructure synopsis documentation snapshotComment) :payload wdl)
:headers utils/content-type=json
:on-done
(fn [{:keys [success? status-code get-parsed-response]}]
(if success?
(this :-complete
(build-new-entity-id get-parsed-response)
(when (= 206 status-code) "Method successfully copied, but error while redacting."))
(swap! state assoc :banner nil :upload-error (get-parsed-response false))))}))
(endpoints/call-ajax-orch
{:endpoint endpoints/post-method
:payload (assoc (utils/restructure namespace name synopsis documentation snapshotComment)
:payload wdl :entityType "Workflow")
:headers utils/content-type=json
:on-done
(fn [{:keys [success? get-parsed-response]}]
(if success?
(this :-complete (build-new-entity-id get-parsed-response))
(swap! state assoc :banner nil :upload-error (get-parsed-response false))))})))))
:-complete
(fn [{:keys [props]} new-entity-id & [error-message]]
((:dismiss props))
((:on-created props) :method new-entity-id)
(when error-message
(comps/push-error error-message)))})
|
74894
|
(ns broadfcui.page.method-repo.create-method
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.codemirror :refer [CodeMirror]]
[broadfcui.common.components :as comps]
[broadfcui.common.input :as input]
[broadfcui.common.links :as links]
[broadfcui.common.style :as style]
[broadfcui.components.buttons :as buttons]
[broadfcui.components.modals :as modals]
[broadfcui.endpoints :as endpoints]
[broadfcui.utils :as utils]
))
(defn- build-info [{:keys [duplicate snapshot]}]
(cond duplicate (merge {:header "Clone Method"
:name (str (:name duplicate) "_copy")
:ok-text "Create New Method"}
(select-keys duplicate [:synopsis :documentation :payload]))
snapshot (merge {:header "Edit Method"
:ok-text "Save As New Snapshot"
:locked #{:namespace :name}
:edit-mode? true}
(select-keys snapshot [:namespace :name :snapshotId :synopsis :documentation :payload]))
:else {:header "Create New Method"
:ok-text "Upload"}))
(defn- build-new-entity-id [get-parsed-response]
(let [{:keys [namespace name snapshotId]} (get-parsed-response)]
(assoc (utils/restructure namespace name) :snapshot-id snapshotId)))
(react/defc CreateMethodDialog
{:component-will-mount
(fn [{:keys [props locals]}]
(swap! locals assoc :info (build-info props)))
:render
(fn [{:keys [props state refs locals this]}]
(let [{:keys [info]} @locals]
[modals/OKCancelForm
{:header (:header info)
:dismiss (:dismiss props)
:get-first-element-dom-node #(react/find-dom-node (@refs "namespace"))
:get-last-element-dom-node #(react/find-dom-node (@refs "ok-button"))
:content
(react/create-element
[:div {:style {:width "80vw"}}
(when-let [banner (:banner @state)]
[comps/Blocker {:banner banner}])
[:div {:style {:display "flex" :justifyContent "space-between"}}
[:div {:style {:flex "1 0 auto" :marginRight "1em"}}
(style/create-form-label "Namespace")
[input/TextField {:data-test-id "namespace-field"
:ref "namespace" :style {:width "100%"}
:defaultValue (:namespace info)
:disabled (contains? (:locked info) :namespace)
:predicates [(input/nonempty "Method namespace")
(input/alphanumeric_-period "Method namespace")]}]
(style/create-textfield-hint input/hint-alphanumeric_-period)]
[:div {:style {:flex "1 0 auto"}}
(style/create-form-label "Name")
[input/TextField {:data-test-id "name-field"
:ref "name" :style {:autoFocus true :width "100%"}
:defaultValue (:name info)
:disabled (contains? (:locked info) :name)
:predicates [(input/nonempty "Method name")
(input/alphanumeric_-period "Method name")]}]
(style/create-textfield-hint input/hint-alphanumeric_-period)]]
;;GAWB-1897 removes Type field and makes all MC types "Workflow" until "Task" type is supported
(style/create-form-label "Synopsis (optional, 80 characters max)")
(style/create-text-field {:data-test-id "synopsis-field"
:ref "synopsis"
:defaultValue (:synopsis info)
:maxLength 80
:style {:width "100%"}})
(style/create-form-label "Documentation (optional)")
(style/create-text-area {:data-test-id "documentation-field"
:ref "documentation"
:defaultValue (:documentation info)
:style {:width "100%"}
:rows 5})
;; This key is changed every time a file is selected causing React to completely replace the
;; element. Otherwise, if a user selects the same file (even after having modified it), the
;; browser will not fire the onChange event.
[:input {:key (:file-input-key @state)
:type "file"
:ref "wdl-uploader"
:style {:display "none"}
:onChange (fn [e]
(let [file (-> e .-target .-files (aget 0))
reader (js/FileReader.)]
(when file
(set! (.-onload reader)
#(let [text (.-result reader)]
(swap! state assoc
:file-name (.-name file)
:file-contents text
:file-input-key (gensym "<KEY>"))
(this :-set-wdl-text text)))
(.readAsText reader file))))}]
(style/create-form-label
(let [{:keys [file-name]
{:strs [undo redo]} :undo-history} @state
[undo? redo?] (map pos? [undo redo])
link (fn [label enabled?]
(if enabled?
(links/create-internal {:onClick #((@refs "wdl-editor") :call-method label)
:style {:color (:text-light style/colors)
:backgroundColor "white"
:padding "0 6px"
:border style/standard-line}}
(string/capitalize label))
[:span {:style {:color (:text-lighter style/colors)
:padding "0 6px"
:border style/standard-line}}
(string/capitalize label)]))]
[:div {:style {:display "flex" :alignItems "baseline" :width "100%"}}
[:span {:style {:paddingRight "1em"}} "WDL"]
(links/create-internal {:onClick #(.click (@refs "wdl-uploader"))} "Load from file...")
(when file-name
[:span {}
[:span {:style {:padding "0 1em 0 25px"}} (str "Selected: " file-name)]
(links/create-internal {:onClick #(this :-set-wdl-text (:file-contents @state))} "Reset to file")])
[:span {:style {:flex "1 0 auto"}}]
(link "undo" undo?)
(link "redo" redo?)]))
[:style {} ".CodeMirror {height: 300px}"]
[CodeMirror {:data-test-id "wdl-field"
:ref "wdl-editor" :text (:payload info) :read-only? false
:initialize (fn [self]
(self :add-listener "change"
#(swap! state assoc :undo-history
(js->clj (self :call-method "historySize")))))}]
[:div {:style {:padding "0.25rem"}}]
(style/create-form-label "Snapshot Comment (optional)")
(style/create-text-area {:data-test-id "snapshot-comment-field"
:ref "snapshot-comment"
:defaultValue (:snapshot-comment info)
:style {:width "100%"}
:rows 1})
(when (:edit-mode? info)
[comps/Checkbox {:ref "redact-checkbox"
:label (str "Redact Snapshot " (:snapshotId info))}])
[comps/ErrorViewer {:error (:upload-error @state)}]
(style/create-validation-error-message (:validation-errors @state))])
:ok-button (react/create-element
[buttons/Button {:data-test-id "ok-button"
:ref "ok-button"
:text (:ok-text info)
:onClick #(this :-create-method)}])}]))
:-set-wdl-text
(fn [{:keys [refs]} text]
((@refs "wdl-editor") :call-method "setValue" text))
:-create-method
(fn [{:keys [state locals refs this]}]
(let [[namespace name & fails] (input/get-and-validate refs "namespace" "name")
[synopsis documentation snapshotComment] (common/get-text refs "synopsis" "documentation" "snapshot-comment")
wdl ((@refs "wdl-editor") :call-method "getValue")
fails (or fails (when (string/blank? wdl) ["Please enter the WDL payload"]))]
(swap! state assoc :validation-errors fails)
(when-not fails
(swap! state assoc :banner "Uploading...")
(if (:edit-mode? (:info @locals))
(let [{:keys [snapshotId]} (:info @locals)
redact? ((@refs "redact-checkbox") :checked?)]
(endpoints/call-ajax-orch
{:endpoint (endpoints/create-new-method-snapshot namespace name snapshotId redact?)
:payload (assoc (utils/restructure synopsis documentation snapshotComment) :payload wdl)
:headers utils/content-type=json
:on-done
(fn [{:keys [success? status-code get-parsed-response]}]
(if success?
(this :-complete
(build-new-entity-id get-parsed-response)
(when (= 206 status-code) "Method successfully copied, but error while redacting."))
(swap! state assoc :banner nil :upload-error (get-parsed-response false))))}))
(endpoints/call-ajax-orch
{:endpoint endpoints/post-method
:payload (assoc (utils/restructure namespace name synopsis documentation snapshotComment)
:payload wdl :entityType "Workflow")
:headers utils/content-type=json
:on-done
(fn [{:keys [success? get-parsed-response]}]
(if success?
(this :-complete (build-new-entity-id get-parsed-response))
(swap! state assoc :banner nil :upload-error (get-parsed-response false))))})))))
:-complete
(fn [{:keys [props]} new-entity-id & [error-message]]
((:dismiss props))
((:on-created props) :method new-entity-id)
(when error-message
(comps/push-error error-message)))})
| true |
(ns broadfcui.page.method-repo.create-method
(:require
[dmohs.react :as react]
[clojure.string :as string]
[broadfcui.common :as common]
[broadfcui.common.codemirror :refer [CodeMirror]]
[broadfcui.common.components :as comps]
[broadfcui.common.input :as input]
[broadfcui.common.links :as links]
[broadfcui.common.style :as style]
[broadfcui.components.buttons :as buttons]
[broadfcui.components.modals :as modals]
[broadfcui.endpoints :as endpoints]
[broadfcui.utils :as utils]
))
(defn- build-info [{:keys [duplicate snapshot]}]
(cond duplicate (merge {:header "Clone Method"
:name (str (:name duplicate) "_copy")
:ok-text "Create New Method"}
(select-keys duplicate [:synopsis :documentation :payload]))
snapshot (merge {:header "Edit Method"
:ok-text "Save As New Snapshot"
:locked #{:namespace :name}
:edit-mode? true}
(select-keys snapshot [:namespace :name :snapshotId :synopsis :documentation :payload]))
:else {:header "Create New Method"
:ok-text "Upload"}))
(defn- build-new-entity-id [get-parsed-response]
(let [{:keys [namespace name snapshotId]} (get-parsed-response)]
(assoc (utils/restructure namespace name) :snapshot-id snapshotId)))
(react/defc CreateMethodDialog
{:component-will-mount
(fn [{:keys [props locals]}]
(swap! locals assoc :info (build-info props)))
:render
(fn [{:keys [props state refs locals this]}]
(let [{:keys [info]} @locals]
[modals/OKCancelForm
{:header (:header info)
:dismiss (:dismiss props)
:get-first-element-dom-node #(react/find-dom-node (@refs "namespace"))
:get-last-element-dom-node #(react/find-dom-node (@refs "ok-button"))
:content
(react/create-element
[:div {:style {:width "80vw"}}
(when-let [banner (:banner @state)]
[comps/Blocker {:banner banner}])
[:div {:style {:display "flex" :justifyContent "space-between"}}
[:div {:style {:flex "1 0 auto" :marginRight "1em"}}
(style/create-form-label "Namespace")
[input/TextField {:data-test-id "namespace-field"
:ref "namespace" :style {:width "100%"}
:defaultValue (:namespace info)
:disabled (contains? (:locked info) :namespace)
:predicates [(input/nonempty "Method namespace")
(input/alphanumeric_-period "Method namespace")]}]
(style/create-textfield-hint input/hint-alphanumeric_-period)]
[:div {:style {:flex "1 0 auto"}}
(style/create-form-label "Name")
[input/TextField {:data-test-id "name-field"
:ref "name" :style {:autoFocus true :width "100%"}
:defaultValue (:name info)
:disabled (contains? (:locked info) :name)
:predicates [(input/nonempty "Method name")
(input/alphanumeric_-period "Method name")]}]
(style/create-textfield-hint input/hint-alphanumeric_-period)]]
;;GAWB-1897 removes Type field and makes all MC types "Workflow" until "Task" type is supported
(style/create-form-label "Synopsis (optional, 80 characters max)")
(style/create-text-field {:data-test-id "synopsis-field"
:ref "synopsis"
:defaultValue (:synopsis info)
:maxLength 80
:style {:width "100%"}})
(style/create-form-label "Documentation (optional)")
(style/create-text-area {:data-test-id "documentation-field"
:ref "documentation"
:defaultValue (:documentation info)
:style {:width "100%"}
:rows 5})
;; This key is changed every time a file is selected causing React to completely replace the
;; element. Otherwise, if a user selects the same file (even after having modified it), the
;; browser will not fire the onChange event.
[:input {:key (:file-input-key @state)
:type "file"
:ref "wdl-uploader"
:style {:display "none"}
:onChange (fn [e]
(let [file (-> e .-target .-files (aget 0))
reader (js/FileReader.)]
(when file
(set! (.-onload reader)
#(let [text (.-result reader)]
(swap! state assoc
:file-name (.-name file)
:file-contents text
:file-input-key (gensym "PI:KEY:<KEY>END_PI"))
(this :-set-wdl-text text)))
(.readAsText reader file))))}]
(style/create-form-label
(let [{:keys [file-name]
{:strs [undo redo]} :undo-history} @state
[undo? redo?] (map pos? [undo redo])
link (fn [label enabled?]
(if enabled?
(links/create-internal {:onClick #((@refs "wdl-editor") :call-method label)
:style {:color (:text-light style/colors)
:backgroundColor "white"
:padding "0 6px"
:border style/standard-line}}
(string/capitalize label))
[:span {:style {:color (:text-lighter style/colors)
:padding "0 6px"
:border style/standard-line}}
(string/capitalize label)]))]
[:div {:style {:display "flex" :alignItems "baseline" :width "100%"}}
[:span {:style {:paddingRight "1em"}} "WDL"]
(links/create-internal {:onClick #(.click (@refs "wdl-uploader"))} "Load from file...")
(when file-name
[:span {}
[:span {:style {:padding "0 1em 0 25px"}} (str "Selected: " file-name)]
(links/create-internal {:onClick #(this :-set-wdl-text (:file-contents @state))} "Reset to file")])
[:span {:style {:flex "1 0 auto"}}]
(link "undo" undo?)
(link "redo" redo?)]))
[:style {} ".CodeMirror {height: 300px}"]
[CodeMirror {:data-test-id "wdl-field"
:ref "wdl-editor" :text (:payload info) :read-only? false
:initialize (fn [self]
(self :add-listener "change"
#(swap! state assoc :undo-history
(js->clj (self :call-method "historySize")))))}]
[:div {:style {:padding "0.25rem"}}]
(style/create-form-label "Snapshot Comment (optional)")
(style/create-text-area {:data-test-id "snapshot-comment-field"
:ref "snapshot-comment"
:defaultValue (:snapshot-comment info)
:style {:width "100%"}
:rows 1})
(when (:edit-mode? info)
[comps/Checkbox {:ref "redact-checkbox"
:label (str "Redact Snapshot " (:snapshotId info))}])
[comps/ErrorViewer {:error (:upload-error @state)}]
(style/create-validation-error-message (:validation-errors @state))])
:ok-button (react/create-element
[buttons/Button {:data-test-id "ok-button"
:ref "ok-button"
:text (:ok-text info)
:onClick #(this :-create-method)}])}]))
:-set-wdl-text
(fn [{:keys [refs]} text]
((@refs "wdl-editor") :call-method "setValue" text))
:-create-method
(fn [{:keys [state locals refs this]}]
(let [[namespace name & fails] (input/get-and-validate refs "namespace" "name")
[synopsis documentation snapshotComment] (common/get-text refs "synopsis" "documentation" "snapshot-comment")
wdl ((@refs "wdl-editor") :call-method "getValue")
fails (or fails (when (string/blank? wdl) ["Please enter the WDL payload"]))]
(swap! state assoc :validation-errors fails)
(when-not fails
(swap! state assoc :banner "Uploading...")
(if (:edit-mode? (:info @locals))
(let [{:keys [snapshotId]} (:info @locals)
redact? ((@refs "redact-checkbox") :checked?)]
(endpoints/call-ajax-orch
{:endpoint (endpoints/create-new-method-snapshot namespace name snapshotId redact?)
:payload (assoc (utils/restructure synopsis documentation snapshotComment) :payload wdl)
:headers utils/content-type=json
:on-done
(fn [{:keys [success? status-code get-parsed-response]}]
(if success?
(this :-complete
(build-new-entity-id get-parsed-response)
(when (= 206 status-code) "Method successfully copied, but error while redacting."))
(swap! state assoc :banner nil :upload-error (get-parsed-response false))))}))
(endpoints/call-ajax-orch
{:endpoint endpoints/post-method
:payload (assoc (utils/restructure namespace name synopsis documentation snapshotComment)
:payload wdl :entityType "Workflow")
:headers utils/content-type=json
:on-done
(fn [{:keys [success? get-parsed-response]}]
(if success?
(this :-complete (build-new-entity-id get-parsed-response))
(swap! state assoc :banner nil :upload-error (get-parsed-response false))))})))))
:-complete
(fn [{:keys [props]} new-entity-id & [error-message]]
((:dismiss props))
((:on-created props) :method new-entity-id)
(when error-message
(comps/push-error error-message)))})
|
[
{
"context": "; tags.clj (clojure-firefly)\n;; Copyright (c) 2014 Austin Zheng\n;; Released under the terms of the MIT License\n\n(",
"end": 64,
"score": 0.9997090101242065,
"start": 52,
"tag": "NAME",
"value": "Austin Zheng"
}
] |
src/clojure_blog/tags.clj
|
austinzheng/clojure-firefly
| 1 |
;; tags.clj (clojure-firefly)
;; Copyright (c) 2014 Austin Zheng
;; Released under the terms of the MIT License
(ns clojure-blog.tags
(:require
[clojure-blog.routes :as r]
[clojure.string :as s]
[ring.util.codec :as codec]))
(defn tag-valid? [tag]
"Return whether a potential tag value is valid for further operations"
(and
(string? tag)
(> (count tag) 0)))
(defn remove-empty [tags-list]
(filter tag-valid? tags-list))
(defn split-raw-tags [raw-tags]
"Split a raw string containing comma-separated tags into a list of tags, excepting empty or blank tags"
(remove-empty (s/split raw-tags #"\s*,\s*")))
(defn join-tags [tags-list]
"Join a list of tags into a single string, with tags separated by commas"
(if (= 0 (count tags-list))
""
(s/join ", " tags-list)))
(defn tags-html-for-tags [tags-list]
"Given a list of tags, turn it into HTML appropriate for the tags system"
(if (or (nil? tags-list) (= 0 (count tags-list)))
"(No tags)"
(let [
preceding-tags (butlast tags-list)
last-tag (last tags-list)
formatted-preceding (reduce str (map #(reduce str ["<a href=\"" (r/blog-posts-for-tag-route (codec/url-encode %)) "\">" % "</a>, "]) preceding-tags))
formatted-last (reduce str ["<a href=\"" (r/blog-posts-for-tag-route (codec/url-encode last-tag)) "\">" last-tag "</a>"])]
(reduce str ["Tags: " formatted-preceding formatted-last]))))
|
43034
|
;; tags.clj (clojure-firefly)
;; Copyright (c) 2014 <NAME>
;; Released under the terms of the MIT License
(ns clojure-blog.tags
(:require
[clojure-blog.routes :as r]
[clojure.string :as s]
[ring.util.codec :as codec]))
(defn tag-valid? [tag]
"Return whether a potential tag value is valid for further operations"
(and
(string? tag)
(> (count tag) 0)))
(defn remove-empty [tags-list]
(filter tag-valid? tags-list))
(defn split-raw-tags [raw-tags]
"Split a raw string containing comma-separated tags into a list of tags, excepting empty or blank tags"
(remove-empty (s/split raw-tags #"\s*,\s*")))
(defn join-tags [tags-list]
"Join a list of tags into a single string, with tags separated by commas"
(if (= 0 (count tags-list))
""
(s/join ", " tags-list)))
(defn tags-html-for-tags [tags-list]
"Given a list of tags, turn it into HTML appropriate for the tags system"
(if (or (nil? tags-list) (= 0 (count tags-list)))
"(No tags)"
(let [
preceding-tags (butlast tags-list)
last-tag (last tags-list)
formatted-preceding (reduce str (map #(reduce str ["<a href=\"" (r/blog-posts-for-tag-route (codec/url-encode %)) "\">" % "</a>, "]) preceding-tags))
formatted-last (reduce str ["<a href=\"" (r/blog-posts-for-tag-route (codec/url-encode last-tag)) "\">" last-tag "</a>"])]
(reduce str ["Tags: " formatted-preceding formatted-last]))))
| true |
;; tags.clj (clojure-firefly)
;; Copyright (c) 2014 PI:NAME:<NAME>END_PI
;; Released under the terms of the MIT License
(ns clojure-blog.tags
(:require
[clojure-blog.routes :as r]
[clojure.string :as s]
[ring.util.codec :as codec]))
(defn tag-valid? [tag]
"Return whether a potential tag value is valid for further operations"
(and
(string? tag)
(> (count tag) 0)))
(defn remove-empty [tags-list]
(filter tag-valid? tags-list))
(defn split-raw-tags [raw-tags]
"Split a raw string containing comma-separated tags into a list of tags, excepting empty or blank tags"
(remove-empty (s/split raw-tags #"\s*,\s*")))
(defn join-tags [tags-list]
"Join a list of tags into a single string, with tags separated by commas"
(if (= 0 (count tags-list))
""
(s/join ", " tags-list)))
(defn tags-html-for-tags [tags-list]
"Given a list of tags, turn it into HTML appropriate for the tags system"
(if (or (nil? tags-list) (= 0 (count tags-list)))
"(No tags)"
(let [
preceding-tags (butlast tags-list)
last-tag (last tags-list)
formatted-preceding (reduce str (map #(reduce str ["<a href=\"" (r/blog-posts-for-tag-route (codec/url-encode %)) "\">" % "</a>, "]) preceding-tags))
formatted-last (reduce str ["<a href=\"" (r/blog-posts-for-tag-route (codec/url-encode last-tag)) "\">" last-tag "</a>"])]
(reduce str ["Tags: " formatted-preceding formatted-last]))))
|
[
{
"context": ";; Copyright 2020, Di Sera Luca\n;; Contacts: [email protected]\n;; ",
"end": 31,
"score": 0.9998846054077148,
"start": 19,
"tag": "NAME",
"value": "Di Sera Luca"
},
{
"context": " Copyright 2020, Di Sera Luca\n;; Contacts: [email protected]\n;; https://github.com/diseraluc",
"end": 74,
"score": 0.9999313354492188,
"start": 53,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "gmail.com\n;; https://github.com/diseraluca\n;; https://www.linkedin.com/in/",
"end": 125,
"score": 0.9997027516365051,
"start": 115,
"tag": "USERNAME",
"value": "diseraluca"
},
{
"context": "\n;; https://www.linkedin.com/in/luca-di-sera-200023167\n;;\n;; This code is licensed under the MIT License",
"end": 197,
"score": 0.9994822144508362,
"start": 175,
"tag": "USERNAME",
"value": "luca-di-sera-200023167"
},
{
"context": "MiB\nInstalled Size : 139.32 MiB\nPackager : Luca Di Sera\nBuild Date : Thu 12 Mar 2020 05:55:10 P",
"end": 1131,
"score": 0.8600124716758728,
"start": 1124,
"tag": "NAME",
"value": "Luca Di"
},
{
"context": "d Size : 139.32 MiB\nPackager : Luca Di Sera\nBuild Date : Thu 12 Mar 2020 05:55:10 PM CET",
"end": 1136,
"score": 0.8209582567214966,
"start": 1135,
"tag": "NAME",
"value": "a"
}
] |
pmal/test/pmal/backend/packages/packagemanagers/pacman_test.clj
|
diseraluca/pmal
| 0 |
;; Copyright 2020, Di Sera Luca
;; Contacts: [email protected]
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.backend.packages.packagemanagers.pacman-test
(:require [clojure.test :refer :all]
[clojure.string :refer [split-lines]]
[pmal.backend.packages.packagemanagers.pacman :refer :all]
[pmal.backend.packages.types :refer [PackageManager]])
(:import (pmal.backend.packages.packagemanagers.pacman pacman)))
(def package-details
"Repository : test
Name : testpackage
Version : 9.3.0-1
Description : A test package
Architecture : x86_64
URL : htts://www.bogus.url/
Licenses : Unknown
Groups : Unknown
Provides : None
Depends On : None
Optional Deps : None
Conflicts With : None
Replaces : None
Download Size : 29.84 MiB
Installed Size : 139.32 MiB
Packager : Luca Di Sera
Build Date : Thu 12 Mar 2020 05:55:10 PM CET
Validated By : MD5 Sum SHA-256 Sum Signature")
;; TODO: Add tests that describe the format of a detail line.
(deftest test-parse-detail-line
(is (= "data"
(parse-detail-line "tag : data "))
"parse-detail-line returns the data of the detail line, i.e the part of the string that is after the colon with trailing and leading spaces stripped."))
(deftest test-get-detail-line
(let [detail-lines [
"tag1 : data1"
"tag2 : data2"
"tag3 : data3"
]]
(is (= (second detail-lines)
(get-detail-line ::tag2 detail-lines))
"get-detail-line returns the line that starts with the given tag.")))
(deftest test-parse-details
(let [parsed (parse-details package-details)]
(is (map? parsed)
"Given a correctly formed details string, parse-details returns a mapped structure.")
(testing "The mapped structure returned by parse-details provides information about the described package."
(is (contains? parsed :name)
"The mapped structure contains the 'name' key.")
(is (= (parse-detail ::Name (split-lines package-details))
(:name parsed))
"The 'name' key contains the data of the line of the details string that has tag 'Name'.")
(is (contains? parsed :description)
"The mapped structure contains the 'description' key.")
(is (= (parse-detail ::Description (split-lines package-details))
(:description parsed))
"The 'description' key contains the data of the line of the details string that has tag 'Description'."))))
(deftest test-pacman
(is (satisfies? PackageManager (pacman.))
"The pacman type satisfies the PackageManager protocol."))
(deftest test-package-manager
(is (instance? pacman package-manager)
"package-manager returns an instance of the pacman PackageManager."))
|
87173
|
;; Copyright 2020, <NAME>
;; Contacts: <EMAIL>
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.backend.packages.packagemanagers.pacman-test
(:require [clojure.test :refer :all]
[clojure.string :refer [split-lines]]
[pmal.backend.packages.packagemanagers.pacman :refer :all]
[pmal.backend.packages.types :refer [PackageManager]])
(:import (pmal.backend.packages.packagemanagers.pacman pacman)))
(def package-details
"Repository : test
Name : testpackage
Version : 9.3.0-1
Description : A test package
Architecture : x86_64
URL : htts://www.bogus.url/
Licenses : Unknown
Groups : Unknown
Provides : None
Depends On : None
Optional Deps : None
Conflicts With : None
Replaces : None
Download Size : 29.84 MiB
Installed Size : 139.32 MiB
Packager : <NAME> Ser<NAME>
Build Date : Thu 12 Mar 2020 05:55:10 PM CET
Validated By : MD5 Sum SHA-256 Sum Signature")
;; TODO: Add tests that describe the format of a detail line.
(deftest test-parse-detail-line
(is (= "data"
(parse-detail-line "tag : data "))
"parse-detail-line returns the data of the detail line, i.e the part of the string that is after the colon with trailing and leading spaces stripped."))
(deftest test-get-detail-line
(let [detail-lines [
"tag1 : data1"
"tag2 : data2"
"tag3 : data3"
]]
(is (= (second detail-lines)
(get-detail-line ::tag2 detail-lines))
"get-detail-line returns the line that starts with the given tag.")))
(deftest test-parse-details
(let [parsed (parse-details package-details)]
(is (map? parsed)
"Given a correctly formed details string, parse-details returns a mapped structure.")
(testing "The mapped structure returned by parse-details provides information about the described package."
(is (contains? parsed :name)
"The mapped structure contains the 'name' key.")
(is (= (parse-detail ::Name (split-lines package-details))
(:name parsed))
"The 'name' key contains the data of the line of the details string that has tag 'Name'.")
(is (contains? parsed :description)
"The mapped structure contains the 'description' key.")
(is (= (parse-detail ::Description (split-lines package-details))
(:description parsed))
"The 'description' key contains the data of the line of the details string that has tag 'Description'."))))
(deftest test-pacman
(is (satisfies? PackageManager (pacman.))
"The pacman type satisfies the PackageManager protocol."))
(deftest test-package-manager
(is (instance? pacman package-manager)
"package-manager returns an instance of the pacman PackageManager."))
| true |
;; Copyright 2020, PI:NAME:<NAME>END_PI
;; Contacts: PI:EMAIL:<EMAIL>END_PI
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.backend.packages.packagemanagers.pacman-test
(:require [clojure.test :refer :all]
[clojure.string :refer [split-lines]]
[pmal.backend.packages.packagemanagers.pacman :refer :all]
[pmal.backend.packages.types :refer [PackageManager]])
(:import (pmal.backend.packages.packagemanagers.pacman pacman)))
(def package-details
"Repository : test
Name : testpackage
Version : 9.3.0-1
Description : A test package
Architecture : x86_64
URL : htts://www.bogus.url/
Licenses : Unknown
Groups : Unknown
Provides : None
Depends On : None
Optional Deps : None
Conflicts With : None
Replaces : None
Download Size : 29.84 MiB
Installed Size : 139.32 MiB
Packager : PI:NAME:<NAME>END_PI SerPI:NAME:<NAME>END_PI
Build Date : Thu 12 Mar 2020 05:55:10 PM CET
Validated By : MD5 Sum SHA-256 Sum Signature")
;; TODO: Add tests that describe the format of a detail line.
(deftest test-parse-detail-line
(is (= "data"
(parse-detail-line "tag : data "))
"parse-detail-line returns the data of the detail line, i.e the part of the string that is after the colon with trailing and leading spaces stripped."))
(deftest test-get-detail-line
(let [detail-lines [
"tag1 : data1"
"tag2 : data2"
"tag3 : data3"
]]
(is (= (second detail-lines)
(get-detail-line ::tag2 detail-lines))
"get-detail-line returns the line that starts with the given tag.")))
(deftest test-parse-details
(let [parsed (parse-details package-details)]
(is (map? parsed)
"Given a correctly formed details string, parse-details returns a mapped structure.")
(testing "The mapped structure returned by parse-details provides information about the described package."
(is (contains? parsed :name)
"The mapped structure contains the 'name' key.")
(is (= (parse-detail ::Name (split-lines package-details))
(:name parsed))
"The 'name' key contains the data of the line of the details string that has tag 'Name'.")
(is (contains? parsed :description)
"The mapped structure contains the 'description' key.")
(is (= (parse-detail ::Description (split-lines package-details))
(:description parsed))
"The 'description' key contains the data of the line of the details string that has tag 'Description'."))))
(deftest test-pacman
(is (satisfies? PackageManager (pacman.))
"The pacman type satisfies the PackageManager protocol."))
(deftest test-package-manager
(is (instance? pacman package-manager)
"package-manager returns an instance of the pacman PackageManager."))
|
[
{
"context": ":use [overtone.live]))\n\n;;Examples translated from Tim Blechmann's Masters Thesis: http://tim.klingt.org/publicati",
"end": 90,
"score": 0.9998518228530884,
"start": 77,
"tag": "NAME",
"value": "Tim Blechmann"
}
] |
examples/supernova.clj
|
rosejn/overtone
| 4 |
(ns examples.supernova
(:use [overtone.live]))
;;Examples translated from Tim Blechmann's Masters Thesis: http://tim.klingt.org/publications/tim_blechmann_supernova.pdf
;;Listing 1.1
;;SynthDef(\sweep, { arg duration = 10, amp = 0.01, freq_base = 1000, freq_target = 1100;
;;var freq = Line.kr(freq_base , freq_target , duration); var sine = SinOsc.ar(freq); var env = EnvGen.kr(Env.linen(0.1, duration - 0.5, 0.4, amp),
;;doneAction: 2);
;; Out.ar(0, sine * env); }).add;
(defsynth sweep-sin [duration 10 amp 0.01 freq-base 1000 freq-target 1100]
(let [freq (line:kr freq-base freq-target duration)
sine (sin-osc freq)
env (env-gen:kr (lin-env 0.1 (- duration 0.5) 0.4 amp) :action FREE)]
(out 0 (* sine env))))
;;Listing 1.2
;;
;; ~r = Routine({ Synth(\sweep, [\duration, 10,
;;\amp, -12.dbamp, \freq_base , 1000, \freq_target , 1100]);
;;1.0.wait; Synth(\sweep, [\duration, 9,
;;\amp, -9.dbamp, \freq_base , 1000, \freq_target , 200]);
;;1.5.wait; Synth(\sweep, [\duration, 7.5,
;;\amp, -18.dbamp, \freq_base , 1000, \freq_target , 10000]);
;;}); ~r.play // run the routine
(let [t (+ 25 (now))]
(at t (sweep-sin :duration 10
:amp (db->amp -12)
:freq-base 1000
:freq-target 1100))
(at (+ 1000 t) (sweep-sin :duration 9
:amp (db->amp -9)
:freq-base 1000
:freq-target 200))
(at (+ 2500 t) (sweep-sin :duration 7.5
:amp (db->amp -18)
:freq-base 1000
:freq-target 10000)))
|
106363
|
(ns examples.supernova
(:use [overtone.live]))
;;Examples translated from <NAME>'s Masters Thesis: http://tim.klingt.org/publications/tim_blechmann_supernova.pdf
;;Listing 1.1
;;SynthDef(\sweep, { arg duration = 10, amp = 0.01, freq_base = 1000, freq_target = 1100;
;;var freq = Line.kr(freq_base , freq_target , duration); var sine = SinOsc.ar(freq); var env = EnvGen.kr(Env.linen(0.1, duration - 0.5, 0.4, amp),
;;doneAction: 2);
;; Out.ar(0, sine * env); }).add;
(defsynth sweep-sin [duration 10 amp 0.01 freq-base 1000 freq-target 1100]
(let [freq (line:kr freq-base freq-target duration)
sine (sin-osc freq)
env (env-gen:kr (lin-env 0.1 (- duration 0.5) 0.4 amp) :action FREE)]
(out 0 (* sine env))))
;;Listing 1.2
;;
;; ~r = Routine({ Synth(\sweep, [\duration, 10,
;;\amp, -12.dbamp, \freq_base , 1000, \freq_target , 1100]);
;;1.0.wait; Synth(\sweep, [\duration, 9,
;;\amp, -9.dbamp, \freq_base , 1000, \freq_target , 200]);
;;1.5.wait; Synth(\sweep, [\duration, 7.5,
;;\amp, -18.dbamp, \freq_base , 1000, \freq_target , 10000]);
;;}); ~r.play // run the routine
(let [t (+ 25 (now))]
(at t (sweep-sin :duration 10
:amp (db->amp -12)
:freq-base 1000
:freq-target 1100))
(at (+ 1000 t) (sweep-sin :duration 9
:amp (db->amp -9)
:freq-base 1000
:freq-target 200))
(at (+ 2500 t) (sweep-sin :duration 7.5
:amp (db->amp -18)
:freq-base 1000
:freq-target 10000)))
| true |
(ns examples.supernova
(:use [overtone.live]))
;;Examples translated from PI:NAME:<NAME>END_PI's Masters Thesis: http://tim.klingt.org/publications/tim_blechmann_supernova.pdf
;;Listing 1.1
;;SynthDef(\sweep, { arg duration = 10, amp = 0.01, freq_base = 1000, freq_target = 1100;
;;var freq = Line.kr(freq_base , freq_target , duration); var sine = SinOsc.ar(freq); var env = EnvGen.kr(Env.linen(0.1, duration - 0.5, 0.4, amp),
;;doneAction: 2);
;; Out.ar(0, sine * env); }).add;
(defsynth sweep-sin [duration 10 amp 0.01 freq-base 1000 freq-target 1100]
(let [freq (line:kr freq-base freq-target duration)
sine (sin-osc freq)
env (env-gen:kr (lin-env 0.1 (- duration 0.5) 0.4 amp) :action FREE)]
(out 0 (* sine env))))
;;Listing 1.2
;;
;; ~r = Routine({ Synth(\sweep, [\duration, 10,
;;\amp, -12.dbamp, \freq_base , 1000, \freq_target , 1100]);
;;1.0.wait; Synth(\sweep, [\duration, 9,
;;\amp, -9.dbamp, \freq_base , 1000, \freq_target , 200]);
;;1.5.wait; Synth(\sweep, [\duration, 7.5,
;;\amp, -18.dbamp, \freq_base , 1000, \freq_target , 10000]);
;;}); ~r.play // run the routine
(let [t (+ 25 (now))]
(at t (sweep-sin :duration 10
:amp (db->amp -12)
:freq-base 1000
:freq-target 1100))
(at (+ 1000 t) (sweep-sin :duration 9
:amp (db->amp -9)
:freq-base 1000
:freq-target 200))
(at (+ 2500 t) (sweep-sin :duration 7.5
:amp (db->amp -18)
:freq-base 1000
:freq-target 10000)))
|
[
{
"context": "e-name user-id-cache}}\n :token \"ABC-1\"}]\n (testing \"sids\"\n (is (= [\"sid-1\" \"si",
"end": 904,
"score": 0.7169674038887024,
"start": 899,
"tag": "KEY",
"value": "ABC-1"
}
] |
search-app/test/cmr/search/test/api/request_context_user_augmenter.clj
|
sxu123/Common-Metadata-Repository
| 0 |
(ns cmr.search.test.api.request-context-user-augmenter
"Tests to verify functionality in cmr.search.api.request-context-user-augmenter namespace."
(:require
[clojure.test :refer :all]
[cmr.common.cache :as cache]
[cmr.search.api.request-context-user-augmenter :as context-augmenter]
[cmr.common.util :as util]))
(deftest token-and-user-id-context-cache
(let [token-sid-cache (context-augmenter/create-token-sid-cache)
user-id-cache (context-augmenter/create-token-user-id-cache)]
(cache/set-value token-sid-cache "ABC-1" {:sids ["sid-1" "sid-2"]})
(cache/set-value user-id-cache "ABC-1" "user-id-1")
(testing "Retrieve values from cache with token"
(let [context {:system {:caches {context-augmenter/token-sid-cache-name token-sid-cache
context-augmenter/token-user-id-cache-name user-id-cache}}
:token "ABC-1"}]
(testing "sids"
(is (= ["sid-1" "sid-2"] (#'context-augmenter/context->sids context))))
(testing "user-id"
(is (= "user-id-1" (#'context-augmenter/context->user-id context))))))
(testing "Token required message"
(let [context {:system {:caches {context-augmenter/token-sid-cache-name token-sid-cache
context-augmenter/token-user-id-cache-name user-id-cache}}}]
(try
(#'context-augmenter/context->user-id context "Token required")
(catch clojure.lang.ExceptionInfo e
(is (= "Token required" (first (:errors (ex-data e)))))))))))
|
83000
|
(ns cmr.search.test.api.request-context-user-augmenter
"Tests to verify functionality in cmr.search.api.request-context-user-augmenter namespace."
(:require
[clojure.test :refer :all]
[cmr.common.cache :as cache]
[cmr.search.api.request-context-user-augmenter :as context-augmenter]
[cmr.common.util :as util]))
(deftest token-and-user-id-context-cache
(let [token-sid-cache (context-augmenter/create-token-sid-cache)
user-id-cache (context-augmenter/create-token-user-id-cache)]
(cache/set-value token-sid-cache "ABC-1" {:sids ["sid-1" "sid-2"]})
(cache/set-value user-id-cache "ABC-1" "user-id-1")
(testing "Retrieve values from cache with token"
(let [context {:system {:caches {context-augmenter/token-sid-cache-name token-sid-cache
context-augmenter/token-user-id-cache-name user-id-cache}}
:token "<KEY>"}]
(testing "sids"
(is (= ["sid-1" "sid-2"] (#'context-augmenter/context->sids context))))
(testing "user-id"
(is (= "user-id-1" (#'context-augmenter/context->user-id context))))))
(testing "Token required message"
(let [context {:system {:caches {context-augmenter/token-sid-cache-name token-sid-cache
context-augmenter/token-user-id-cache-name user-id-cache}}}]
(try
(#'context-augmenter/context->user-id context "Token required")
(catch clojure.lang.ExceptionInfo e
(is (= "Token required" (first (:errors (ex-data e)))))))))))
| true |
(ns cmr.search.test.api.request-context-user-augmenter
"Tests to verify functionality in cmr.search.api.request-context-user-augmenter namespace."
(:require
[clojure.test :refer :all]
[cmr.common.cache :as cache]
[cmr.search.api.request-context-user-augmenter :as context-augmenter]
[cmr.common.util :as util]))
(deftest token-and-user-id-context-cache
(let [token-sid-cache (context-augmenter/create-token-sid-cache)
user-id-cache (context-augmenter/create-token-user-id-cache)]
(cache/set-value token-sid-cache "ABC-1" {:sids ["sid-1" "sid-2"]})
(cache/set-value user-id-cache "ABC-1" "user-id-1")
(testing "Retrieve values from cache with token"
(let [context {:system {:caches {context-augmenter/token-sid-cache-name token-sid-cache
context-augmenter/token-user-id-cache-name user-id-cache}}
:token "PI:KEY:<KEY>END_PI"}]
(testing "sids"
(is (= ["sid-1" "sid-2"] (#'context-augmenter/context->sids context))))
(testing "user-id"
(is (= "user-id-1" (#'context-augmenter/context->user-id context))))))
(testing "Token required message"
(let [context {:system {:caches {context-augmenter/token-sid-cache-name token-sid-cache
context-augmenter/token-user-id-cache-name user-id-cache}}}]
(try
(#'context-augmenter/context->user-id context "Token required")
(catch clojure.lang.ExceptionInfo e
(is (= "Token required" (first (:errors (ex-data e)))))))))))
|
[
{
"context": "oc \"Syntax highlighting test file\"\n :author \"Markus Brenneis\"}\n highlighting)\n\n(defn something-else [f xs]\n",
"end": 113,
"score": 0.9998853802680969,
"start": 98,
"tag": "NAME",
"value": "Markus Brenneis"
}
] |
autotests/input/clojure.clj
|
dawidsowa/syntax-highlighting
| 5 |
; Test file, released under MIT License
(ns ^{:doc "Syntax highlighting test file"
:author "Markus Brenneis"}
highlighting)
(defn something-else [f xs]
#_(map #(apply f (% [%])) (cons 1 xs))
(map #(apply f (% xs)) (cons 1 xs))
#_[1 '(2)]
xs)
(def foo [\a \b \n \ucafe \o123 \n
\newline \tab \space \formfeed \backspace])
(def fizz {#{\a \b}
#{\n \newline}})
(def fizz' #{{\a \b}
{\n \newline}})
(defn bar [xs]
(as-> xs <>
(cons :a <>)
(map #(%1 %2) <>) ; TODO improve
(into <> [:konjure.logic.specs/numShips])))
(def x-2-y
#_"do \" sth"
(domonad set-m
[x #{1.1, (+ -2 +4)}
y #{1.1, (- -2.0 4.0)}]
(*' x y)))
(def bases
(and (= -1 -1N)
(= 1/4 -2.5e-1)
(= -1/2 -0.5M)
(= -0x1Ab -0X1ab)
(= +2r101010 25R1h)
(= 39r13 42R10))) ; FIXME this one is not correct
(def ^{:private true}
(= (last #{#{}}) #{{#{}}}))
(def s "#repl\n")
(def r #"repl")
(defn- stuff!
[a]
"This is no \"documentation\"!"
(= (class #'+) (class #'foo))
(let [+ -] [(+ a 1) (@#'+ a 1)]))
(defn- throwIllegalArgumentException!
"Throws an \"IllegalArgumentException\" or
a js/Error."
[message]
#?(:clj (throw (IllegalArgumentException. message))
:cljs (throw (js/Error. message))))
(defmacro let-fn "a nonsense macro" [one-binding & body]
`(+ 1 ~(inc' 1))
(let [[identifier & fn-body] one-binding]
`(let [~identifier (fn ~identifier ~@fn-body)]
~@body `a#)))
(def state (atom [(= false true) nil]))
(defn something-cool [] (first @state))
(defn- something-different [] (first (into @state [12])))
(defn- instance-getfield [this k] (@(.state this) k))
|
103459
|
; Test file, released under MIT License
(ns ^{:doc "Syntax highlighting test file"
:author "<NAME>"}
highlighting)
(defn something-else [f xs]
#_(map #(apply f (% [%])) (cons 1 xs))
(map #(apply f (% xs)) (cons 1 xs))
#_[1 '(2)]
xs)
(def foo [\a \b \n \ucafe \o123 \n
\newline \tab \space \formfeed \backspace])
(def fizz {#{\a \b}
#{\n \newline}})
(def fizz' #{{\a \b}
{\n \newline}})
(defn bar [xs]
(as-> xs <>
(cons :a <>)
(map #(%1 %2) <>) ; TODO improve
(into <> [:konjure.logic.specs/numShips])))
(def x-2-y
#_"do \" sth"
(domonad set-m
[x #{1.1, (+ -2 +4)}
y #{1.1, (- -2.0 4.0)}]
(*' x y)))
(def bases
(and (= -1 -1N)
(= 1/4 -2.5e-1)
(= -1/2 -0.5M)
(= -0x1Ab -0X1ab)
(= +2r101010 25R1h)
(= 39r13 42R10))) ; FIXME this one is not correct
(def ^{:private true}
(= (last #{#{}}) #{{#{}}}))
(def s "#repl\n")
(def r #"repl")
(defn- stuff!
[a]
"This is no \"documentation\"!"
(= (class #'+) (class #'foo))
(let [+ -] [(+ a 1) (@#'+ a 1)]))
(defn- throwIllegalArgumentException!
"Throws an \"IllegalArgumentException\" or
a js/Error."
[message]
#?(:clj (throw (IllegalArgumentException. message))
:cljs (throw (js/Error. message))))
(defmacro let-fn "a nonsense macro" [one-binding & body]
`(+ 1 ~(inc' 1))
(let [[identifier & fn-body] one-binding]
`(let [~identifier (fn ~identifier ~@fn-body)]
~@body `a#)))
(def state (atom [(= false true) nil]))
(defn something-cool [] (first @state))
(defn- something-different [] (first (into @state [12])))
(defn- instance-getfield [this k] (@(.state this) k))
| true |
; Test file, released under MIT License
(ns ^{:doc "Syntax highlighting test file"
:author "PI:NAME:<NAME>END_PI"}
highlighting)
(defn something-else [f xs]
#_(map #(apply f (% [%])) (cons 1 xs))
(map #(apply f (% xs)) (cons 1 xs))
#_[1 '(2)]
xs)
(def foo [\a \b \n \ucafe \o123 \n
\newline \tab \space \formfeed \backspace])
(def fizz {#{\a \b}
#{\n \newline}})
(def fizz' #{{\a \b}
{\n \newline}})
(defn bar [xs]
(as-> xs <>
(cons :a <>)
(map #(%1 %2) <>) ; TODO improve
(into <> [:konjure.logic.specs/numShips])))
(def x-2-y
#_"do \" sth"
(domonad set-m
[x #{1.1, (+ -2 +4)}
y #{1.1, (- -2.0 4.0)}]
(*' x y)))
(def bases
(and (= -1 -1N)
(= 1/4 -2.5e-1)
(= -1/2 -0.5M)
(= -0x1Ab -0X1ab)
(= +2r101010 25R1h)
(= 39r13 42R10))) ; FIXME this one is not correct
(def ^{:private true}
(= (last #{#{}}) #{{#{}}}))
(def s "#repl\n")
(def r #"repl")
(defn- stuff!
[a]
"This is no \"documentation\"!"
(= (class #'+) (class #'foo))
(let [+ -] [(+ a 1) (@#'+ a 1)]))
(defn- throwIllegalArgumentException!
"Throws an \"IllegalArgumentException\" or
a js/Error."
[message]
#?(:clj (throw (IllegalArgumentException. message))
:cljs (throw (js/Error. message))))
(defmacro let-fn "a nonsense macro" [one-binding & body]
`(+ 1 ~(inc' 1))
(let [[identifier & fn-body] one-binding]
`(let [~identifier (fn ~identifier ~@fn-body)]
~@body `a#)))
(def state (atom [(= false true) nil]))
(defn something-cool [] (first @state))
(defn- something-different [] (first (into @state [12])))
(defn- instance-getfield [this k] (@(.state this) k))
|
[
{
"context": "RSS\"]]\n [:li [:a {:href \"http://twitter.com/jonoflayham\"} \"Twitter\"]]\n [:li [:a {:href \"https://git",
"end": 2564,
"score": 0.9996293187141418,
"start": 2553,
"tag": "USERNAME",
"value": "jonoflayham"
},
{
"context": "ter\"]]\n [:li [:a {:href \"https://github.com/jonoflayham\"} \"Github\"]]]]\n\n [:div#main content]\n\n [:",
"end": 2633,
"score": 0.9996152520179749,
"start": 2622,
"tag": "USERNAME",
"value": "jonoflayham"
},
{
"context": "\n \"Web site copyright © \" (t/year (t/now)) \" Jon Woods | \"\n [:span.credit \"Powered b",
"end": 2781,
"score": 0.9977978467941284,
"start": 2772,
"tag": "NAME",
"value": "Jon Woods"
},
{
"context": "redit \"Powered by \" [:a {:href \"http://github.com/gilbertw1/blog-gen\"} \" a Little Side Project\"]\n \" &n",
"end": 2874,
"score": 0.9987130761146545,
"start": 2865,
"tag": "USERNAME",
"value": "gilbertw1"
},
{
"context": "stly themed with \" [:a {:href \"https://github.com/TheChymera/Koenigspress\"} \"Königspress\"]]]]]))\n\n(defn post [",
"end": 3000,
"score": 0.9558277130126953,
"start": 2990,
"tag": "USERNAME",
"value": "TheChymera"
},
{
"context": "\"}\n ; (str \"var disqus_shortname = 'bryangilbertsblog';\n ; var disqus_url = 'http:/",
"end": 3651,
"score": 0.9904367923736572,
"start": 3634,
"tag": "USERNAME",
"value": "bryangilbertsblog"
}
] |
src/blog_gen/layout.clj
|
jonoflayham/blog-gen
| 0 |
(ns blog-gen.layout
(:require [clojure.string :as str]
[hiccup.page :refer [html5]]
[optimus.link :as link]
[clj-time.format :as tf]
[clj-time.core :as t]))
(defn monthf [date]
(tf/unparse (tf/formatter "MMM") date))
(defn dayf [date]
(tf/unparse (tf/formatter "dd") date))
(defn yearf [date]
(tf/unparse (tf/formatter "yyyy") date))
(defn date-ordinal-suffix [day-number]
(let [suffixes ["th" "st" "nd" "rd"]]
(condp > day-number
4 (get suffixes day-number)
20 "th"
(date-ordinal-suffix (mod day-number 10)))))
(defn main [request title content]
(html5
[:head
(when-let [uri (:uri request)]
[:link {:rel "canonical" :href (str "http://jonoflayham.com" uri)}])
[:meta {:name "HandheldFriendly" :content "True"}]
[:meta {:name "MobileOptimized" :content "320"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
[:meta {:charset "utf-8"}]
[:title "Loose Typing" (if title (str " - " title))]
[:link {:rel "stylesheet" :href (link/file-path request "/css/theme.css")}]
[:link {:rel "stylesheet" :href (link/file-path request "/css/zenburn-custom.css")}]
[:link {:href "http://fonts.googleapis.com/css?family=Poller+One" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Germania+One" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Fontdiner+Swanky" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Lato" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Cardo" :rel "stylesheet" :type "text/css"}]]
;[:script "
; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
; (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
; m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
; })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
;
; ga('create', 'UA-42597902-1', 'bryangilbert.com');
; ga('send', 'pageview');"]
[:body
[:header {:role "banner"}
[:hgroup
[:h1
[:a {:href "/"} "Loose Typing"]]]]
[:nav {:role "navigation"}
[:ul.main-navigation
[:li [:a {:href "/"} "Blog"]]
[:li [:a {:href "/archive/"} "Archive"]]
[:li [:a {:href "/atom.xml"} "RSS"]]
[:li [:a {:href "http://twitter.com/jonoflayham"} "Twitter"]]
[:li [:a {:href "https://github.com/jonoflayham"} "Github"]]]]
[:div#main content]
[:footer {:role "contentinfo"}
[:p
"Web site copyright © " (t/year (t/now)) " Jon Woods | "
[:span.credit "Powered by " [:a {:href "http://github.com/gilbertw1/blog-gen"} " a Little Side Project"]
" | Mostly themed with " [:a {:href "https://github.com/TheChymera/Koenigspress"} "Königspress"]]]]]))
(defn post [request {:keys [title tags date path disqus-path content]}]
(main request title
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title title]
(when date
[:p.meta
[:time {:datetime date} (dayf date) " " (monthf date) " " (yearf date)]])]
[:div.body.entry-content content]
;[:section
; [:h1 "Comments"
; [:div#disqus_thread {:aria-live "polite"}]
; [:script {:type "text/javascript"}
; (str "var disqus_shortname = 'bryangilbertsblog';
; var disqus_url = 'http://bryangilbert.com" disqus-path "';
; (function() {
; var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
; })();")]
; [:noscript "Please enable JavaScript to view the " [:a {:href "http://disqus.com/?ref_noscript"} "comments powered by Disqus."]]
; [:a.dsq-brlink {:href "http://disqus.com"} "comments powered by " [:span.logo-disqus "Disqus"]]]]
]]))
(defn redirect [request page]
(html5
[:head
[:meta {:http-equiv "refresh" :content (str "0; url=" page)}]]))
(defn home [request posts]
(let [{:keys [title tags date path disqus-path content]} (->> posts (sort-by :date) reverse first)]
(main request nil
[:div#content
[:div.blog-index
[:article
[:header
[:h1.entry-title [:a {:href path} title]]
(when date
[:p.meta
[:time {:datetime date} (dayf date) " " (monthf date) " " (yearf date)]])]
[:div.body.entry-content content]
[:div.pagination
[:a {:href "/archive/"} "Blog Archive"]]]]])))
(defn- make-tag-link [tag]
[:a {:href (str "/tags/" tag)} tag])
(defn- make-tag-links [tags]
(reduce #(conj %1 ", " (make-tag-link %2)) (make-tag-link (first tags)) (rest tags)))
(defn- archive-post [{:keys [title date tags path]}]
[:article
[:h1 [:a {:href path} title]]
[:time {:datetime date}
[:span.day (dayf date)] " "
[:span.month (monthf date)] " "
[:span.year (yearf date)]]
(when (not-empty tags)
[:span.categories "Tags: " (make-tag-links tags)])])
(defn- archive-group [[year posts]]
(let [sorted-posts (reverse (sort-by :path posts))]
(cons
[:h2 year]
(map archive-post sorted-posts))))
(defn archive-like [request posts title]
(let [post-groups (->> posts (group-by #(t/year (:date %))) (sort-by first) reverse)]
(main request title
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title title]]
[:div.body.entry-content
[:div#blog-archives
(map archive-group post-groups)]]]])))
(defn archive [request posts]
(archive-like request posts "Archive"))
(defn tag [request posts tag]
(archive-like request posts tag))
(defn tag-post [{:keys [path title]}]
[:article
[:h1 [:a {:href path} title]]])
(defn tag-entry [tag posts]
(let [sorted-posts (reverse (sort-by :path posts))]
(cons
[:h2 tag]
(map tag-post sorted-posts))))
(defn tags [request posts]
(let [unique-tags (->> posts (map :tags) flatten distinct sort)]
(main request "Tags"
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title "Tags"]]
[:div.body.entry-content
[:div#blog-archives
(map #(tag-entry % posts) unique-tags)]]]])))
|
75316
|
(ns blog-gen.layout
(:require [clojure.string :as str]
[hiccup.page :refer [html5]]
[optimus.link :as link]
[clj-time.format :as tf]
[clj-time.core :as t]))
(defn monthf [date]
(tf/unparse (tf/formatter "MMM") date))
(defn dayf [date]
(tf/unparse (tf/formatter "dd") date))
(defn yearf [date]
(tf/unparse (tf/formatter "yyyy") date))
(defn date-ordinal-suffix [day-number]
(let [suffixes ["th" "st" "nd" "rd"]]
(condp > day-number
4 (get suffixes day-number)
20 "th"
(date-ordinal-suffix (mod day-number 10)))))
(defn main [request title content]
(html5
[:head
(when-let [uri (:uri request)]
[:link {:rel "canonical" :href (str "http://jonoflayham.com" uri)}])
[:meta {:name "HandheldFriendly" :content "True"}]
[:meta {:name "MobileOptimized" :content "320"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
[:meta {:charset "utf-8"}]
[:title "Loose Typing" (if title (str " - " title))]
[:link {:rel "stylesheet" :href (link/file-path request "/css/theme.css")}]
[:link {:rel "stylesheet" :href (link/file-path request "/css/zenburn-custom.css")}]
[:link {:href "http://fonts.googleapis.com/css?family=Poller+One" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Germania+One" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Fontdiner+Swanky" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Lato" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Cardo" :rel "stylesheet" :type "text/css"}]]
;[:script "
; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
; (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
; m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
; })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
;
; ga('create', 'UA-42597902-1', 'bryangilbert.com');
; ga('send', 'pageview');"]
[:body
[:header {:role "banner"}
[:hgroup
[:h1
[:a {:href "/"} "Loose Typing"]]]]
[:nav {:role "navigation"}
[:ul.main-navigation
[:li [:a {:href "/"} "Blog"]]
[:li [:a {:href "/archive/"} "Archive"]]
[:li [:a {:href "/atom.xml"} "RSS"]]
[:li [:a {:href "http://twitter.com/jonoflayham"} "Twitter"]]
[:li [:a {:href "https://github.com/jonoflayham"} "Github"]]]]
[:div#main content]
[:footer {:role "contentinfo"}
[:p
"Web site copyright © " (t/year (t/now)) " <NAME> | "
[:span.credit "Powered by " [:a {:href "http://github.com/gilbertw1/blog-gen"} " a Little Side Project"]
" | Mostly themed with " [:a {:href "https://github.com/TheChymera/Koenigspress"} "Königspress"]]]]]))
(defn post [request {:keys [title tags date path disqus-path content]}]
(main request title
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title title]
(when date
[:p.meta
[:time {:datetime date} (dayf date) " " (monthf date) " " (yearf date)]])]
[:div.body.entry-content content]
;[:section
; [:h1 "Comments"
; [:div#disqus_thread {:aria-live "polite"}]
; [:script {:type "text/javascript"}
; (str "var disqus_shortname = 'bryangilbertsblog';
; var disqus_url = 'http://bryangilbert.com" disqus-path "';
; (function() {
; var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
; })();")]
; [:noscript "Please enable JavaScript to view the " [:a {:href "http://disqus.com/?ref_noscript"} "comments powered by Disqus."]]
; [:a.dsq-brlink {:href "http://disqus.com"} "comments powered by " [:span.logo-disqus "Disqus"]]]]
]]))
(defn redirect [request page]
(html5
[:head
[:meta {:http-equiv "refresh" :content (str "0; url=" page)}]]))
(defn home [request posts]
(let [{:keys [title tags date path disqus-path content]} (->> posts (sort-by :date) reverse first)]
(main request nil
[:div#content
[:div.blog-index
[:article
[:header
[:h1.entry-title [:a {:href path} title]]
(when date
[:p.meta
[:time {:datetime date} (dayf date) " " (monthf date) " " (yearf date)]])]
[:div.body.entry-content content]
[:div.pagination
[:a {:href "/archive/"} "Blog Archive"]]]]])))
(defn- make-tag-link [tag]
[:a {:href (str "/tags/" tag)} tag])
(defn- make-tag-links [tags]
(reduce #(conj %1 ", " (make-tag-link %2)) (make-tag-link (first tags)) (rest tags)))
(defn- archive-post [{:keys [title date tags path]}]
[:article
[:h1 [:a {:href path} title]]
[:time {:datetime date}
[:span.day (dayf date)] " "
[:span.month (monthf date)] " "
[:span.year (yearf date)]]
(when (not-empty tags)
[:span.categories "Tags: " (make-tag-links tags)])])
(defn- archive-group [[year posts]]
(let [sorted-posts (reverse (sort-by :path posts))]
(cons
[:h2 year]
(map archive-post sorted-posts))))
(defn archive-like [request posts title]
(let [post-groups (->> posts (group-by #(t/year (:date %))) (sort-by first) reverse)]
(main request title
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title title]]
[:div.body.entry-content
[:div#blog-archives
(map archive-group post-groups)]]]])))
(defn archive [request posts]
(archive-like request posts "Archive"))
(defn tag [request posts tag]
(archive-like request posts tag))
(defn tag-post [{:keys [path title]}]
[:article
[:h1 [:a {:href path} title]]])
(defn tag-entry [tag posts]
(let [sorted-posts (reverse (sort-by :path posts))]
(cons
[:h2 tag]
(map tag-post sorted-posts))))
(defn tags [request posts]
(let [unique-tags (->> posts (map :tags) flatten distinct sort)]
(main request "Tags"
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title "Tags"]]
[:div.body.entry-content
[:div#blog-archives
(map #(tag-entry % posts) unique-tags)]]]])))
| true |
(ns blog-gen.layout
(:require [clojure.string :as str]
[hiccup.page :refer [html5]]
[optimus.link :as link]
[clj-time.format :as tf]
[clj-time.core :as t]))
(defn monthf [date]
(tf/unparse (tf/formatter "MMM") date))
(defn dayf [date]
(tf/unparse (tf/formatter "dd") date))
(defn yearf [date]
(tf/unparse (tf/formatter "yyyy") date))
(defn date-ordinal-suffix [day-number]
(let [suffixes ["th" "st" "nd" "rd"]]
(condp > day-number
4 (get suffixes day-number)
20 "th"
(date-ordinal-suffix (mod day-number 10)))))
(defn main [request title content]
(html5
[:head
(when-let [uri (:uri request)]
[:link {:rel "canonical" :href (str "http://jonoflayham.com" uri)}])
[:meta {:name "HandheldFriendly" :content "True"}]
[:meta {:name "MobileOptimized" :content "320"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]
[:meta {:charset "utf-8"}]
[:title "Loose Typing" (if title (str " - " title))]
[:link {:rel "stylesheet" :href (link/file-path request "/css/theme.css")}]
[:link {:rel "stylesheet" :href (link/file-path request "/css/zenburn-custom.css")}]
[:link {:href "http://fonts.googleapis.com/css?family=Poller+One" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Germania+One" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Fontdiner+Swanky" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Lato" :rel "stylesheet" :type "text/css"}]
[:link {:href "http://fonts.googleapis.com/css?family=Cardo" :rel "stylesheet" :type "text/css"}]]
;[:script "
; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
; (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
; m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
; })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
;
; ga('create', 'UA-42597902-1', 'bryangilbert.com');
; ga('send', 'pageview');"]
[:body
[:header {:role "banner"}
[:hgroup
[:h1
[:a {:href "/"} "Loose Typing"]]]]
[:nav {:role "navigation"}
[:ul.main-navigation
[:li [:a {:href "/"} "Blog"]]
[:li [:a {:href "/archive/"} "Archive"]]
[:li [:a {:href "/atom.xml"} "RSS"]]
[:li [:a {:href "http://twitter.com/jonoflayham"} "Twitter"]]
[:li [:a {:href "https://github.com/jonoflayham"} "Github"]]]]
[:div#main content]
[:footer {:role "contentinfo"}
[:p
"Web site copyright © " (t/year (t/now)) " PI:NAME:<NAME>END_PI | "
[:span.credit "Powered by " [:a {:href "http://github.com/gilbertw1/blog-gen"} " a Little Side Project"]
" | Mostly themed with " [:a {:href "https://github.com/TheChymera/Koenigspress"} "Königspress"]]]]]))
(defn post [request {:keys [title tags date path disqus-path content]}]
(main request title
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title title]
(when date
[:p.meta
[:time {:datetime date} (dayf date) " " (monthf date) " " (yearf date)]])]
[:div.body.entry-content content]
;[:section
; [:h1 "Comments"
; [:div#disqus_thread {:aria-live "polite"}]
; [:script {:type "text/javascript"}
; (str "var disqus_shortname = 'bryangilbertsblog';
; var disqus_url = 'http://bryangilbert.com" disqus-path "';
; (function() {
; var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
; })();")]
; [:noscript "Please enable JavaScript to view the " [:a {:href "http://disqus.com/?ref_noscript"} "comments powered by Disqus."]]
; [:a.dsq-brlink {:href "http://disqus.com"} "comments powered by " [:span.logo-disqus "Disqus"]]]]
]]))
(defn redirect [request page]
(html5
[:head
[:meta {:http-equiv "refresh" :content (str "0; url=" page)}]]))
(defn home [request posts]
(let [{:keys [title tags date path disqus-path content]} (->> posts (sort-by :date) reverse first)]
(main request nil
[:div#content
[:div.blog-index
[:article
[:header
[:h1.entry-title [:a {:href path} title]]
(when date
[:p.meta
[:time {:datetime date} (dayf date) " " (monthf date) " " (yearf date)]])]
[:div.body.entry-content content]
[:div.pagination
[:a {:href "/archive/"} "Blog Archive"]]]]])))
(defn- make-tag-link [tag]
[:a {:href (str "/tags/" tag)} tag])
(defn- make-tag-links [tags]
(reduce #(conj %1 ", " (make-tag-link %2)) (make-tag-link (first tags)) (rest tags)))
(defn- archive-post [{:keys [title date tags path]}]
[:article
[:h1 [:a {:href path} title]]
[:time {:datetime date}
[:span.day (dayf date)] " "
[:span.month (monthf date)] " "
[:span.year (yearf date)]]
(when (not-empty tags)
[:span.categories "Tags: " (make-tag-links tags)])])
(defn- archive-group [[year posts]]
(let [sorted-posts (reverse (sort-by :path posts))]
(cons
[:h2 year]
(map archive-post sorted-posts))))
(defn archive-like [request posts title]
(let [post-groups (->> posts (group-by #(t/year (:date %))) (sort-by first) reverse)]
(main request title
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title title]]
[:div.body.entry-content
[:div#blog-archives
(map archive-group post-groups)]]]])))
(defn archive [request posts]
(archive-like request posts "Archive"))
(defn tag [request posts tag]
(archive-like request posts tag))
(defn tag-post [{:keys [path title]}]
[:article
[:h1 [:a {:href path} title]]])
(defn tag-entry [tag posts]
(let [sorted-posts (reverse (sort-by :path posts))]
(cons
[:h2 tag]
(map tag-post sorted-posts))))
(defn tags [request posts]
(let [unique-tags (->> posts (map :tags) flatten distinct sort)]
(main request "Tags"
[:div#content
[:article.hentry {:role "article"}
[:header
[:h1.entry-title "Tags"]]
[:div.body.entry-content
[:div#blog-archives
(map #(tag-entry % posts) unique-tags)]]]])))
|
[
{
"context": ";; Copyright 2016 David Sarginson\n\n;; Licensed under the Apache License, Version 2.",
"end": 33,
"score": 0.9998515844345093,
"start": 18,
"tag": "NAME",
"value": "David Sarginson"
}
] |
test/clj/tdd_trainer/stats/snapshot_stats_test.clj
|
ShaolinSarg/tdd-trainer
| 1 |
;; Copyright 2016 David Sarginson
;; 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 tdd-trainer.stats.snapshot-stats-test
(:require [clojure.test :refer :all]
[midje.sweet :refer :all]
[clj-time.core :as t]
[tdd-trainer.stats.snapshot-stats :refer :all]))
(def session-start (t/date-time 2016 6 6 22 11 00))
(def snapshots [{:snapshot-timestamp (t/date-time 2016 6 6 22 11 12)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 12 12)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 12 52)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 14 52)}])
(def session {:session-id 111 :start-time session-start :snapshots snapshots})
(deftest save-time-tests
(facts "about `snapshot-gaps`"
(fact "it should return the difference between each snapshot in seconds"
(snapshot-gaps session-start snapshots) => [12 60 40 120]))
(facts "about `average-snapshot-gap`"
(fact "it should return the average snapshot gap"
(average-snapshot-gap [12 60 40 120]) => 58.0M))
(facts "about `standard-deviation-gaps`"
(fact "it should return the right sd for the gaps"
(standard-deviation-gaps [12 60 40 120]) => 39.65M)))
(deftest output-tests
(facts "about 'gen-stat-summary'"
(fact "should contain the average save time"
(:average-save-time (gen-stat-summary session)) => 58.0M)
(fact "should return a suitable message for no snapshots"
(gen-stat-summary {:snapshots []}) => "no data")
(fact "should contain the sequence of save gaps"
(:gaps (gen-stat-summary session)) => [12 60 40 120])
(fact "should contain the standard deviation of the gaps"
(:standard-deviation (gen-stat-summary session)) => 39.65M)
(fact "should return the gaps within one SD of the mean"
(:one-sd-gaps (gen-stat-summary session)) => [40 60])))
|
86610
|
;; Copyright 2016 <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 tdd-trainer.stats.snapshot-stats-test
(:require [clojure.test :refer :all]
[midje.sweet :refer :all]
[clj-time.core :as t]
[tdd-trainer.stats.snapshot-stats :refer :all]))
(def session-start (t/date-time 2016 6 6 22 11 00))
(def snapshots [{:snapshot-timestamp (t/date-time 2016 6 6 22 11 12)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 12 12)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 12 52)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 14 52)}])
(def session {:session-id 111 :start-time session-start :snapshots snapshots})
(deftest save-time-tests
(facts "about `snapshot-gaps`"
(fact "it should return the difference between each snapshot in seconds"
(snapshot-gaps session-start snapshots) => [12 60 40 120]))
(facts "about `average-snapshot-gap`"
(fact "it should return the average snapshot gap"
(average-snapshot-gap [12 60 40 120]) => 58.0M))
(facts "about `standard-deviation-gaps`"
(fact "it should return the right sd for the gaps"
(standard-deviation-gaps [12 60 40 120]) => 39.65M)))
(deftest output-tests
(facts "about 'gen-stat-summary'"
(fact "should contain the average save time"
(:average-save-time (gen-stat-summary session)) => 58.0M)
(fact "should return a suitable message for no snapshots"
(gen-stat-summary {:snapshots []}) => "no data")
(fact "should contain the sequence of save gaps"
(:gaps (gen-stat-summary session)) => [12 60 40 120])
(fact "should contain the standard deviation of the gaps"
(:standard-deviation (gen-stat-summary session)) => 39.65M)
(fact "should return the gaps within one SD of the mean"
(:one-sd-gaps (gen-stat-summary session)) => [40 60])))
| true |
;; Copyright 2016 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 tdd-trainer.stats.snapshot-stats-test
(:require [clojure.test :refer :all]
[midje.sweet :refer :all]
[clj-time.core :as t]
[tdd-trainer.stats.snapshot-stats :refer :all]))
(def session-start (t/date-time 2016 6 6 22 11 00))
(def snapshots [{:snapshot-timestamp (t/date-time 2016 6 6 22 11 12)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 12 12)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 12 52)}
{:snapshot-timestamp (t/date-time 2016 6 6 22 14 52)}])
(def session {:session-id 111 :start-time session-start :snapshots snapshots})
(deftest save-time-tests
(facts "about `snapshot-gaps`"
(fact "it should return the difference between each snapshot in seconds"
(snapshot-gaps session-start snapshots) => [12 60 40 120]))
(facts "about `average-snapshot-gap`"
(fact "it should return the average snapshot gap"
(average-snapshot-gap [12 60 40 120]) => 58.0M))
(facts "about `standard-deviation-gaps`"
(fact "it should return the right sd for the gaps"
(standard-deviation-gaps [12 60 40 120]) => 39.65M)))
(deftest output-tests
(facts "about 'gen-stat-summary'"
(fact "should contain the average save time"
(:average-save-time (gen-stat-summary session)) => 58.0M)
(fact "should return a suitable message for no snapshots"
(gen-stat-summary {:snapshots []}) => "no data")
(fact "should contain the sequence of save gaps"
(:gaps (gen-stat-summary session)) => [12 60 40 120])
(fact "should contain the standard deviation of the gaps"
(:standard-deviation (gen-stat-summary session)) => 39.65M)
(fact "should return the gaps within one SD of the mean"
(:one-sd-gaps (gen-stat-summary session)) => [40 60])))
|
[
{
"context": " [:th \"Age\"]]\n\n [:tbody\n [:tr \n [:td \"Matthew\"]\n [:td \"26\"]]\n\n [:tr \n [:td \"Anna\"]\n ",
"end": 257,
"score": 0.9994515776634216,
"start": 250,
"tag": "NAME",
"value": "Matthew"
},
{
"context": "\"Matthew\"]\n [:td \"26\"]]\n\n [:tr \n [:td \"Anna\"]\n [:td \"24\"]]\n \n [:tr \n [:td \"Mich",
"end": 303,
"score": 0.9997427463531494,
"start": 299,
"tag": "NAME",
"value": "Anna"
},
{
"context": "Anna\"]\n [:td \"24\"]]\n \n [:tr \n [:td \"Michelle\"]\n [:td \"42\"]]\n \n [:tr \n [:td \"Fran",
"end": 357,
"score": 0.9997474551200867,
"start": 349,
"tag": "NAME",
"value": "Michelle"
},
{
"context": "elle\"]\n [:td \"42\"]]\n \n [:tr \n [:td \"Frank\"]\n [:td \"46\"]]\n ]])\n\n(defn home-did-mount ",
"end": 408,
"score": 0.9996347427368164,
"start": 403,
"tag": "NAME",
"value": "Frank"
}
] |
recipes/data-tables/src/cljs/data_tables/core.cljs
|
yatesj9/reagent-cookbook
| 1 |
(ns data-tables.core
(:require [reagent.core :as reagent]))
(defn home-render []
[:table.table.table-striped.table-bordered
{:cell-spacing "0" :width "100%"}
[:thead>tr
[:th "Name"]
[:th "Age"]]
[:tbody
[:tr
[:td "Matthew"]
[:td "26"]]
[:tr
[:td "Anna"]
[:td "24"]]
[:tr
[:td "Michelle"]
[:td "42"]]
[:tr
[:td "Frank"]
[:td "46"]]
]])
(defn home-did-mount [this]
(.DataTable (js/$ (reagent/dom-node this))))
(defn home []
(reagent/create-class {:reagent-render home-render
:component-did-mount home-did-mount}))
(defn ^:export main []
(reagent/render [home]
(.getElementById js/document "app")))
|
5037
|
(ns data-tables.core
(:require [reagent.core :as reagent]))
(defn home-render []
[:table.table.table-striped.table-bordered
{:cell-spacing "0" :width "100%"}
[:thead>tr
[:th "Name"]
[:th "Age"]]
[:tbody
[:tr
[:td "<NAME>"]
[:td "26"]]
[:tr
[:td "<NAME>"]
[:td "24"]]
[:tr
[:td "<NAME>"]
[:td "42"]]
[:tr
[:td "<NAME>"]
[:td "46"]]
]])
(defn home-did-mount [this]
(.DataTable (js/$ (reagent/dom-node this))))
(defn home []
(reagent/create-class {:reagent-render home-render
:component-did-mount home-did-mount}))
(defn ^:export main []
(reagent/render [home]
(.getElementById js/document "app")))
| true |
(ns data-tables.core
(:require [reagent.core :as reagent]))
(defn home-render []
[:table.table.table-striped.table-bordered
{:cell-spacing "0" :width "100%"}
[:thead>tr
[:th "Name"]
[:th "Age"]]
[:tbody
[:tr
[:td "PI:NAME:<NAME>END_PI"]
[:td "26"]]
[:tr
[:td "PI:NAME:<NAME>END_PI"]
[:td "24"]]
[:tr
[:td "PI:NAME:<NAME>END_PI"]
[:td "42"]]
[:tr
[:td "PI:NAME:<NAME>END_PI"]
[:td "46"]]
]])
(defn home-did-mount [this]
(.DataTable (js/$ (reagent/dom-node this))))
(defn home []
(reagent/create-class {:reagent-render home-render
:component-did-mount home-did-mount}))
(defn ^:export main []
(reagent/render [home]
(.getElementById js/document "app")))
|
[
{
"context": " [weasel \"0.4.0-SNAPSHOT\"]\n [jonase/kibit \"0.0.8\"]]\n\n :plugins [[lein-cljsbuild \"1.0",
"end": 928,
"score": 0.7914296388626099,
"start": 922,
"tag": "USERNAME",
"value": "jonase"
},
{
"context": " :nrepl-port 5001\n :ip \"127.0.0.1\"\n :log-level :info}}\n\n ",
"end": 2265,
"score": 0.9997751712799072,
"start": 2256,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "age :production\n :ip \"185.12.6.20\"\n :log-level :warn\n ",
"end": 2457,
"score": 0.9997667670249939,
"start": 2446,
"tag": "IP_ADDRESS",
"value": "185.12.6.20"
}
] |
project.clj
|
RyanMcG/sally
| 1 |
(defproject sally "0.1.0-SNAPSHOT"
:description "Static analysis library and service"
:url "http://sally.clojurecup.com/"
:license {:name "MIT"}
:source-paths ["src/clj" "src/cljs"]
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2342"]
[ring "1.3.1"]
[ring/ring-defaults "0.1.2"]
[ring-middleware-format "0.4.0"]
[compojure "1.1.9"]
[http-kit "2.1.18"]
[hiccup "1.0.5"]
[com.stuartsierra/component "0.2.2"]
[om "0.7.1"]
[figwheel "0.1.4-SNAPSHOT"]
[environ "1.0.0"]
[com.cemerick/piggieback "0.1.3"]
[com.taoensso/timbre "3.1.6"]
[sablono "0.2.22"]
[jayq "2.5.2"]
[weasel "0.4.0-SNAPSHOT"]
[jonase/kibit "0.0.8"]]
:plugins [[lein-cljsbuild "1.0.3"]
[lein-environ "1.0.0"]]
:min-lein-version "2.0.0"
:uberjar-name "sally.jar"
:cljsbuild {:builds {:app {:source-paths ["src/cljs"]
:compiler {:output-to "resources/public/app.js"
:output-dir "resources/public/out"
:source-map "resources/public/out.js.map"
:preamble ["react/react.min.js"]
:externs ["react/externs/react.js"
"resources/public/boots/js/jquery-1.10.2.min.js"]
:optimizations :none
:pretty-print true}}}}
:profiles {:dev {:dependencies []
:repl-options {:init-ns sally.repl
:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}
:plugins [[lein-figwheel "0.1.4-SNAPSHOT"]]
:figwheel {:http-server-root "public"
:port 3449}
:env {:stage :dev
:port 5000
:nrepl-port 5001
:ip "127.0.0.1"
:log-level :info}}
:uberjar {:hooks [leiningen.cljsbuild]
:env {:stage :production
:ip "185.12.6.20"
:log-level :warn
:port 80}
:omit-source true
:aot []
:cljsbuild {:builds {:app
{:compiler
{:optimizations :advanced
:pretty-print false}}}}}}
:main sally.main)
|
47361
|
(defproject sally "0.1.0-SNAPSHOT"
:description "Static analysis library and service"
:url "http://sally.clojurecup.com/"
:license {:name "MIT"}
:source-paths ["src/clj" "src/cljs"]
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2342"]
[ring "1.3.1"]
[ring/ring-defaults "0.1.2"]
[ring-middleware-format "0.4.0"]
[compojure "1.1.9"]
[http-kit "2.1.18"]
[hiccup "1.0.5"]
[com.stuartsierra/component "0.2.2"]
[om "0.7.1"]
[figwheel "0.1.4-SNAPSHOT"]
[environ "1.0.0"]
[com.cemerick/piggieback "0.1.3"]
[com.taoensso/timbre "3.1.6"]
[sablono "0.2.22"]
[jayq "2.5.2"]
[weasel "0.4.0-SNAPSHOT"]
[jonase/kibit "0.0.8"]]
:plugins [[lein-cljsbuild "1.0.3"]
[lein-environ "1.0.0"]]
:min-lein-version "2.0.0"
:uberjar-name "sally.jar"
:cljsbuild {:builds {:app {:source-paths ["src/cljs"]
:compiler {:output-to "resources/public/app.js"
:output-dir "resources/public/out"
:source-map "resources/public/out.js.map"
:preamble ["react/react.min.js"]
:externs ["react/externs/react.js"
"resources/public/boots/js/jquery-1.10.2.min.js"]
:optimizations :none
:pretty-print true}}}}
:profiles {:dev {:dependencies []
:repl-options {:init-ns sally.repl
:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}
:plugins [[lein-figwheel "0.1.4-SNAPSHOT"]]
:figwheel {:http-server-root "public"
:port 3449}
:env {:stage :dev
:port 5000
:nrepl-port 5001
:ip "127.0.0.1"
:log-level :info}}
:uberjar {:hooks [leiningen.cljsbuild]
:env {:stage :production
:ip "192.168.3.11"
:log-level :warn
:port 80}
:omit-source true
:aot []
:cljsbuild {:builds {:app
{:compiler
{:optimizations :advanced
:pretty-print false}}}}}}
:main sally.main)
| true |
(defproject sally "0.1.0-SNAPSHOT"
:description "Static analysis library and service"
:url "http://sally.clojurecup.com/"
:license {:name "MIT"}
:source-paths ["src/clj" "src/cljs"]
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2342"]
[ring "1.3.1"]
[ring/ring-defaults "0.1.2"]
[ring-middleware-format "0.4.0"]
[compojure "1.1.9"]
[http-kit "2.1.18"]
[hiccup "1.0.5"]
[com.stuartsierra/component "0.2.2"]
[om "0.7.1"]
[figwheel "0.1.4-SNAPSHOT"]
[environ "1.0.0"]
[com.cemerick/piggieback "0.1.3"]
[com.taoensso/timbre "3.1.6"]
[sablono "0.2.22"]
[jayq "2.5.2"]
[weasel "0.4.0-SNAPSHOT"]
[jonase/kibit "0.0.8"]]
:plugins [[lein-cljsbuild "1.0.3"]
[lein-environ "1.0.0"]]
:min-lein-version "2.0.0"
:uberjar-name "sally.jar"
:cljsbuild {:builds {:app {:source-paths ["src/cljs"]
:compiler {:output-to "resources/public/app.js"
:output-dir "resources/public/out"
:source-map "resources/public/out.js.map"
:preamble ["react/react.min.js"]
:externs ["react/externs/react.js"
"resources/public/boots/js/jquery-1.10.2.min.js"]
:optimizations :none
:pretty-print true}}}}
:profiles {:dev {:dependencies []
:repl-options {:init-ns sally.repl
:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]}
:plugins [[lein-figwheel "0.1.4-SNAPSHOT"]]
:figwheel {:http-server-root "public"
:port 3449}
:env {:stage :dev
:port 5000
:nrepl-port 5001
:ip "127.0.0.1"
:log-level :info}}
:uberjar {:hooks [leiningen.cljsbuild]
:env {:stage :production
:ip "PI:IP_ADDRESS:192.168.3.11END_PI"
:log-level :warn
:port 80}
:omit-source true
:aot []
:cljsbuild {:builds {:app
{:compiler
{:optimizations :advanced
:pretty-print false}}}}}}
:main sally.main)
|
[
{
"context": ";; Copyright (c) 2012-2014, Darren Mutz\n;; All rights reserved.\n;;\n;; Redistribution and ",
"end": 39,
"score": 0.9998644590377808,
"start": 28,
"tag": "NAME",
"value": "Darren Mutz"
},
{
"context": "F THE POSSIBILITY OF SUCH DAMAGE.\n\n(ns ^{:author \"Darren Mutz\"\n :see-also\n [[\"https://github.com/darr",
"end": 1614,
"score": 0.9998664259910583,
"start": 1603,
"tag": "NAME",
"value": "Darren Mutz"
},
{
"context": "z\"\n :see-also\n [[\"https://github.com/darrenmutz/sheaf\" \"Source code\"]]}\n sheaf.core\n (:impo",
"end": 1666,
"score": 0.5381403565406799,
"start": 1663,
"tag": "USERNAME",
"value": "ren"
}
] |
src/sheaf/core.clj
|
darrenmutz/sheaf
| 1 |
;; Copyright (c) 2012-2014, Darren Mutz
;; 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.
;; * Neither the name of Darren Mutz nor the names of its
;; contributors may be used to endorse or promote products derived
;; from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(ns ^{:author "Darren Mutz"
:see-also
[["https://github.com/darrenmutz/sheaf" "Source code"]]}
sheaf.core
(:import com.petebevin.markdown.MarkdownProcessor)
(:import org.joda.time.DateTime)
(:import org.joda.time.DateTimeZone)
(:import org.joda.time.format.DateTimeFormatterBuilder)
(:import org.joda.time.format.ISODateTimeFormat)
(:gen-class)
(:use clojure.java.io)
(:use clojure.tools.cli)
(:use [clojure.data.json :only (json-str write-json read-json)])
(:use [net.cgrand.enlive-html :only
(at deftemplate defsnippet content emit* set-attr do->
first-child html-resource select nth-of-type any-node
text-node html-content)])
(:use hiccup.core)
(:use hiccup.page)
(:use hiccup.util))
(load-file (str (System/getProperty (str "user.home")) "/.sheaf"))
(def ^:dynamic *template-url*
(str "file:///" (*config* :sheaf-root) "/" (*config* :template-file)))
(def ^:dynamic *archive-root*
(str (*config* :sheaf-root) "/" (*config* :archive-dir)))
(def ^:dynamic *smart-quote* true)
(defn create-metadata [archive article]
(sort #(compare (%2 :publish-time) (%1 :publish-time)) (cons article archive)))
(defn delete-metadata [archive slug]
(remove #(= (% :slug) slug) archive))
(defn get-archive-filename [month year]
(str *archive-root* "/" month "-" year ".json"))
(defn read-archive [filename]
(try
(seq (read-json (slurp filename)))
(catch java.io.FileNotFoundException e [])))
(defn article-exists? [archive slug]
(contains? (apply sorted-set (map :slug archive)) slug))
(defn get-article-metadata [archive slug]
(first (filter #(= (% :slug) slug) archive)))
(defn fetch-content [url]
(html-resource (java.net.URL. url)))
(defn long-form-date [datetime]
(-> (DateTimeFormatterBuilder.)
(.appendMonthOfYearText)
(.appendLiteral " ")
(.appendDayOfMonth 1)
(.appendLiteral ", ")
(.appendYear 4 4)
(.toFormatter)
(.print datetime)))
(def ^:dynamic *link-sel* [[:.archive-list (nth-of-type 1)] :> first-child])
(defn hexify [s]
(apply str (map #(format "%02x" %) (.getBytes s "UTF-8"))))
(defn unhexify [s]
(let [bytes (into-array Byte/TYPE
(map (fn [[x y]]
(unchecked-byte (Integer/parseInt (str x y) 16)))
(partition 2 s)))]
(String. bytes "UTF-8")))
(defsnippet link-model (fetch-content *template-url*) *link-sel*
[{:keys [month year]}]
[:a] (do->
(content (str month " " year))
(set-attr :href (str "/" month "-" year))))
(defn elipsis-glyphs
"Convert triple periods to precomposed elipsis glyphs."
[s]
(clojure.string/replace #"\.\.\." "…"))
(defn long-dashes
"Convert all double dashes to en dashes and triple dashes to em
dashes. Leave single dashes alone."
[s]
(-> s
(clojure.string/replace #"---" "—")
(clojure.string/replace #"--" "–")))
(defn curly-single-quote
"Naively convert all single quotes to right single quotation marks,
as though all single quotation marks appear in an English
contraction or possessive. Ignores matching and all other context."
[s]
(clojure.string/replace s #"'" "’"))
(defn smart-quote
"Naive smart quoter. Turns typewriter double quotes into curly
matched double quotes on a best effort basis. Assumes all double
quotes should be transformed and that they appear perfectly
balanced in the input. No attempt is made to reason about
interaction with existing curly quotes."
[s]
(let [tokens (clojure.string/split s #"\"")]
(apply str (map #(%1 %2) (cycle [identity #(str "“" % "”")])
tokens))))
(deftemplate article-template (fetch-content *template-url*)
[article title datetime permalink link]
(*config* :articles-selector) (apply content article)
(*config* :page-title-selector) (content title)
(*config* :title-selector) (content title)
(*config* :title-selector) (set-attr :href (if link link permalink))
(*config* :title-selector) (set-attr :id (if link "link" "permalink"))
(*config* :time-selector) (content (long-form-date datetime))
(*config* :time-selector) (set-attr "datetime" (.toString datetime))
(*config* :permalink-selector) (set-attr "href" permalink)
(*config* :archives-selector) nil)
(deftemplate index-template (fetch-content *template-url*)
[page-title articles archive-month-years]
(*config* :page-title-selector) (content page-title)
(*config* :index-articles-selector) (apply content articles)
(*config* :archive-list-selector) (content (map link-model
archive-month-years)))
(defn try-write [filename content]
(do
(.mkdirs (java.io.File. (.getParent (java.io.File. filename))))
(try
(do
(spit filename content)
(println "Wrote" filename))
(catch java.io.FileNotFoundException e
(do
(println "Couldn't write to" filename)
(. System (exit 1)))))))
(defn delete-by-filename [filename]
(if (.delete (java.io.File. filename))
(do
(println "Deleted" filename)
true)
(println "Failed to delete" filename)))
(defn get-year-month-day-millis [datetime]
(hash-map :year (.getYear datetime)
:month (.getAsShortText (.monthOfYear datetime))
:month-full (.getAsText (.monthOfYear datetime))
:month-num (.getMonthOfYear datetime)
:day (.getDayOfMonth datetime)
:millis (.getMillis datetime)))
(defn get-relative-path [month year slug]
(str month "-" year "/" slug ".html"))
(defn get-publish-time [archive slug]
(loop [remainder archive]
(if (empty? remainder)
nil
(if (= ((first remainder) :slug) slug)
((first remainder) :publish-time)
(recur (rest remainder))))))
(defn write-article [relative-path article-content title
publish-time link archive slug]
(try-write (str (*config* :doc-root) "/" relative-path)
(apply str (article-template
article-content
title
publish-time
(str "/" relative-path)
link))))
(defn unlink-article [relative-path]
(let [target-filename (str (*config* :doc-root) "/" relative-path)]
(if (.delete (java.io.File. target-filename))
(do
(println "Deleted" target-filename)
true)
(println "Failed to delete" target-filename))))
(defn publish-article [now slug title article-content link]
(let [ymdm (get-year-month-day-millis now)
year (ymdm :year)
month (ymdm :month)
millis (ymdm :millis)
archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)]
(if (article-exists? archive slug)
(println "Can't publish an article that already exists.")
(let [relative-path (get-relative-path month year slug)
encoded-title (hexify title)]
(try-write archive-filename
(json-str (create-metadata archive
{:slug slug
:publish-time millis
:relative-path relative-path
:title encoded-title})))
(write-article relative-path article-content title now link archive slug)
true))))
(defn revise-article [month year slug title article-content link now]
(let [archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)
revision-time (:millis (get-year-month-day-millis now))]
(if (article-exists? archive slug)
(let [orig-metadata (get-article-metadata archive slug)
relative-path (get-relative-path month year slug)
encoded-title (hexify title)
updated-archive (create-metadata (delete-metadata archive slug)
(assoc orig-metadata
:revision-time revision-time
:title encoded-title))]
(try-write archive-filename (json-str updated-archive))
(write-article relative-path article-content title
(get-publish-time archive slug) link
archive slug)
true)
(println "Can't revise an article that doesn't exist."))))
(defn delete-article [month year slug]
(let [archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)]
(if (article-exists? archive slug)
(if-let [metadata (get-article-metadata archive slug)]
(do
(if (unlink-article (metadata :relative-path))
(let [lighter-archive (delete-metadata archive slug)]
(if (empty? lighter-archive)
(delete-by-filename archive-filename)
(try-write archive-filename
(json-str (delete-metadata archive slug))))
true))))
(println "Can't delete an article that doesn't exist."))))
(defn datetime-from-month-year [month-year-string]
(if-let [[match month year] (re-find #"([A-Z][a-z]+)-([0-9]+)"
month-year-string)]
(let [builder (DateTimeFormatterBuilder.)
custom-builder (.builder
(.appendYear
(.appendLiteral
(.appendMonthOfYearShortText builder)) "-") 4 4)
formatter (.toFormatter custom-builder)]
(.parseDateTime formatter month-year-string)))
nil)
(defn dir-list [dir]
(apply vector (.list (java.io.File. dir))))
(defn datetime-from-month-year [month year]
(-> (DateTimeFormatterBuilder.)
(.appendMonthOfYearShortText)
(.appendLiteral "-")
(.appendYear 4 4)
(.toFormatter)
(.parseDateTime (str month "-" year))))
(defn annotated-archive-from-file [filename]
(let [archive-regex #"([A-Z][a-z]+)-([0-9]+).json"]
(if-let [[filename month year] (re-find archive-regex filename)]
(hash-map :filename (str *archive-root* "/" filename)
:datetime (datetime-from-month-year month year)
:month month
:year year))))
(defn archives-to-seq
([archives]
(archives-to-seq nil archives))
([articles archives]
(lazy-seq
(if (first articles)
(cons (first articles) (archives-to-seq (rest articles) archives))
(if (first archives)
(let [articles (read-archive (:filename (first archives)))]
(cons (first articles) (archives-to-seq (rest articles)
(rest archives))))
nil)))))
(defn get-desc-sorted-archives []
(sort #(compare (%2 :datetime) (%1 :datetime))
(map annotated-archive-from-file (dir-list *archive-root*))))
(defn generate-index [articles target-dir page-title archive-month-years]
(if (empty? articles)
(println "Not generating an empty index.")
(let [article-urls (map #(str "file:///" (*config* :doc-root) "/"
(% :relative-path)) articles)
article-contents (map fetch-content article-urls)
article-nodes (map #(select % (*config* :article-selector))
article-contents)]
(if (and (not (empty? article-nodes)) (not (empty? archive-month-years)))
(try-write (str target-dir "/index.html")
(apply str (index-template page-title article-nodes
archive-month-years)))
(println "Not generating empty index.")))))
(defn escaped-article-content-from-url [url]
(escape-html
(apply str
(emit* (-> (html-resource (java.net.URL. url))
(select (*config* :input-article-selector)))))))
(defn epoch-to-utc-timestamp [epoch-time]
(if epoch-time
(-> (ISODateTimeFormat/dateTime)
(.print (DateTime. epoch-time (DateTimeZone/UTC))))
nil))
(defn atom-entry [title link publish-time revision-time content]
(let [publish-ymdm (get-year-month-day-millis (DateTime. publish-time))
datestamp (apply str
(interpose \-
((juxt #(format "%04d" (:year %))
#(format "%02d" (:month-num %))
#(format "%02d" (:day %)))
publish-ymdm)))
[publish-utc-timestamp revision-utc-timestamp]
(map epoch-to-utc-timestamp [publish-time revision-time])]
[:entry
[:title title]
[:link {:rel "alternate" :type "text/html" :href link}]
[:id (str "tag:" (*config* :base-url) "," datestamp ":/" publish-time)]
[:published publish-utc-timestamp]
[:updated (if revision-utc-timestamp revision-utc-timestamp publish-utc-timestamp)]
[:author
[:name (*config* :author-name)]
[:uri (*config* :author-uri)]]
[:content {:type "html"} content]]))
(defn generate-atom [articles target-dir now]
(if (empty? articles)
(println "Not generating an empty index.")
(let [local-article-urls (map #(str "file:///" (*config* :doc-root)
(% :relative-path)) articles)
article-contents (map escaped-article-content-from-url local-article-urls)
absolute-article-urls (map #(str "http://" (*config* :base-url) "/"
(% :relative-path)) articles)
titles (map #(unhexify (:title %)) articles)
publish-times (map :publish-time articles)
revision-times (map :revision-time articles)
atom-entries (map atom-entry
titles
absolute-article-urls
publish-times
revision-times
article-contents)
latest-update (apply max
(remove #(nil? %)
(reduce conj
publish-times
revision-times)))]
(try-write
(str target-dir (*config* :atom-filename))
(apply
str
(html (xml-declaration "utf-8")
[:feed {:xmlns "http://www.w3.org/2005/Atom"}
[:title (*config* :blog-title)]
[:subtitle (*config* :blog-subtitle)]
[:link {:rel "alternate"
:type "text/html"
:href (str "http://" (*config* :base-url) "/")}]
[:link {:rel "self"
:type "application/atom+xml"
:href (str "http://" (*config* :base-url) "/"
(*config* :atom-filename))}]
[:id (*config* :feed-id)]
[:updated (epoch-to-utc-timestamp latest-update)]
[:rights
(format
"Copyright © %d, %s"
(:year (get-year-month-day-millis (DateTime. latest-update)))
(*config* :author-name))]
atom-entries]))))))
(defn generate-indices [for-datetime max-root-articles]
(let [ymdm (get-year-month-day-millis for-datetime)
year (str (ymdm :year))
month (ymdm :month)
month-full (ymdm :month-full)
sorted-archives (get-desc-sorted-archives)
target-month-archive (filter #(and (= year (:year %)) (= month (:month %)))
sorted-archives)
target-month-articles (archives-to-seq target-month-archive)
archive-month-years (map #(select-keys % [:month :year])
sorted-archives)
target-month-articles-asc (sort #(compare (%1 :publish-time)
(%2 :publish-time))
target-month-articles)
all-articles (archives-to-seq sorted-archives)]
(generate-index target-month-articles-asc
(str (*config* :doc-root) "/" month "-" year)
(str month-full " " year " - " (*config* :blog-title))
target-month-archive)
(generate-index (take max-root-articles all-articles)
(*config* :doc-root)
(*config* :blog-title)
archive-month-years)
(generate-atom (take max-root-articles all-articles) (*config* :doc-root)
for-datetime)))
(defn get-article-content [input-filename dumb-quotes]
(let [uri (str "file://" input-filename)]
;; If the input looks like it contains markdown, convert it to html
(if (re-seq #"^*.md$" uri)
(let [markdown (.markdown (MarkdownProcessor.)
(slurp (input-stream (java.net.URL. uri))))
double-quoter (if dumb-quotes identity smart-quote)]
(-> markdown
double-quoter
curly-single-quote
long-dashes
(.getBytes "UTF-8")
(java.io.ByteArrayInputStream.)
(java.io.InputStreamReader.)
html-resource))
(select (fetch-content uri) (*config* :input-article-selector)))))
(defn usage-and-exit [usage]
(do
(println usage)
(. System (exit 1))))
(defn -main [& args]
(let [[options args usage]
(cli args
["-p" "--publish" "Publish an article" :flag true]
["-r" "--revise" "Revise an article" :flag true]
["-d" "--delete" "Delete an article" :flag true]
["-m" "--month" "Month an article to revise was published in"]
["-y" "--year" "Year an article to revise was published in"]
["-s" "--slug" "Article slug, ex: my-article-title"]
["-t" "--title" "The article's title"]
["-l" "--link" "Title links externally link, ex: \"http://www.noaa.gov\""]
["-a" "--article" "File containing an article written in markdown or HTML"]
["-w" "--watch" "Optionally watch an input while revising" :flag true]
["-b" "--dumbquotes" "Disable smart quoting" :flag true]
["-h" "--help" "Display usage"])
now (DateTime.)
publish (options :publish)
revise (options :revise)
delete (options :delete)
month (options :month)
year (options :year)
slug (options :slug)
title (options :title)
link (options :link)
article (options :article)
watch (options :watch)
dumb-quotes (options :dumbquotes)
help (options :help)]
(if (not (or publish revise delete help))
(usage-and-exit usage))
(if delete
(if (and slug month year)
(if (delete-article month year slug)
(generate-indices (datetime-from-month-year month year)
(*config* :max-home-page-articles)))
(do
(println "Delete requires options slug, month and year.")
(usage-and-exit usage)))
(if revise
(if (and slug title article)
(loop [previous-modified 0]
(let [current-modified (.lastModified (java.io.File. article))]
(if (not (= previous-modified current-modified))
(do
(if (revise-article month year slug title
(get-article-content article dumb-quotes)
link now)
(generate-indices (datetime-from-month-year month year)
(*config* :max-home-page-articles)))
(if watch (recur current-modified)))
(do
(Thread/sleep 200)
(recur previous-modified)))))
(do
(println (str "Revise requires slug, title, article, month and year. If "
"you're revising a link post, include the link option, too."))
(usage-and-exit usage)))
(if publish
(if (and slug title article)
(if (publish-article now slug title
(get-article-content article dumb-quotes)
link)
(generate-indices now (*config* :max-home-page-articles)))
(do
(println "Publish requires slug, title and article.")
(usage-and-exit usage))))))))
|
2973
|
;; Copyright (c) 2012-2014, <NAME>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
;; * Neither the name of Darren Mutz nor the names of its
;; contributors may be used to endorse or promote products derived
;; from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(ns ^{:author "<NAME>"
:see-also
[["https://github.com/darrenmutz/sheaf" "Source code"]]}
sheaf.core
(:import com.petebevin.markdown.MarkdownProcessor)
(:import org.joda.time.DateTime)
(:import org.joda.time.DateTimeZone)
(:import org.joda.time.format.DateTimeFormatterBuilder)
(:import org.joda.time.format.ISODateTimeFormat)
(:gen-class)
(:use clojure.java.io)
(:use clojure.tools.cli)
(:use [clojure.data.json :only (json-str write-json read-json)])
(:use [net.cgrand.enlive-html :only
(at deftemplate defsnippet content emit* set-attr do->
first-child html-resource select nth-of-type any-node
text-node html-content)])
(:use hiccup.core)
(:use hiccup.page)
(:use hiccup.util))
(load-file (str (System/getProperty (str "user.home")) "/.sheaf"))
(def ^:dynamic *template-url*
(str "file:///" (*config* :sheaf-root) "/" (*config* :template-file)))
(def ^:dynamic *archive-root*
(str (*config* :sheaf-root) "/" (*config* :archive-dir)))
(def ^:dynamic *smart-quote* true)
(defn create-metadata [archive article]
(sort #(compare (%2 :publish-time) (%1 :publish-time)) (cons article archive)))
(defn delete-metadata [archive slug]
(remove #(= (% :slug) slug) archive))
(defn get-archive-filename [month year]
(str *archive-root* "/" month "-" year ".json"))
(defn read-archive [filename]
(try
(seq (read-json (slurp filename)))
(catch java.io.FileNotFoundException e [])))
(defn article-exists? [archive slug]
(contains? (apply sorted-set (map :slug archive)) slug))
(defn get-article-metadata [archive slug]
(first (filter #(= (% :slug) slug) archive)))
(defn fetch-content [url]
(html-resource (java.net.URL. url)))
(defn long-form-date [datetime]
(-> (DateTimeFormatterBuilder.)
(.appendMonthOfYearText)
(.appendLiteral " ")
(.appendDayOfMonth 1)
(.appendLiteral ", ")
(.appendYear 4 4)
(.toFormatter)
(.print datetime)))
(def ^:dynamic *link-sel* [[:.archive-list (nth-of-type 1)] :> first-child])
(defn hexify [s]
(apply str (map #(format "%02x" %) (.getBytes s "UTF-8"))))
(defn unhexify [s]
(let [bytes (into-array Byte/TYPE
(map (fn [[x y]]
(unchecked-byte (Integer/parseInt (str x y) 16)))
(partition 2 s)))]
(String. bytes "UTF-8")))
(defsnippet link-model (fetch-content *template-url*) *link-sel*
[{:keys [month year]}]
[:a] (do->
(content (str month " " year))
(set-attr :href (str "/" month "-" year))))
(defn elipsis-glyphs
"Convert triple periods to precomposed elipsis glyphs."
[s]
(clojure.string/replace #"\.\.\." "…"))
(defn long-dashes
"Convert all double dashes to en dashes and triple dashes to em
dashes. Leave single dashes alone."
[s]
(-> s
(clojure.string/replace #"---" "—")
(clojure.string/replace #"--" "–")))
(defn curly-single-quote
"Naively convert all single quotes to right single quotation marks,
as though all single quotation marks appear in an English
contraction or possessive. Ignores matching and all other context."
[s]
(clojure.string/replace s #"'" "’"))
(defn smart-quote
"Naive smart quoter. Turns typewriter double quotes into curly
matched double quotes on a best effort basis. Assumes all double
quotes should be transformed and that they appear perfectly
balanced in the input. No attempt is made to reason about
interaction with existing curly quotes."
[s]
(let [tokens (clojure.string/split s #"\"")]
(apply str (map #(%1 %2) (cycle [identity #(str "“" % "”")])
tokens))))
(deftemplate article-template (fetch-content *template-url*)
[article title datetime permalink link]
(*config* :articles-selector) (apply content article)
(*config* :page-title-selector) (content title)
(*config* :title-selector) (content title)
(*config* :title-selector) (set-attr :href (if link link permalink))
(*config* :title-selector) (set-attr :id (if link "link" "permalink"))
(*config* :time-selector) (content (long-form-date datetime))
(*config* :time-selector) (set-attr "datetime" (.toString datetime))
(*config* :permalink-selector) (set-attr "href" permalink)
(*config* :archives-selector) nil)
(deftemplate index-template (fetch-content *template-url*)
[page-title articles archive-month-years]
(*config* :page-title-selector) (content page-title)
(*config* :index-articles-selector) (apply content articles)
(*config* :archive-list-selector) (content (map link-model
archive-month-years)))
(defn try-write [filename content]
(do
(.mkdirs (java.io.File. (.getParent (java.io.File. filename))))
(try
(do
(spit filename content)
(println "Wrote" filename))
(catch java.io.FileNotFoundException e
(do
(println "Couldn't write to" filename)
(. System (exit 1)))))))
(defn delete-by-filename [filename]
(if (.delete (java.io.File. filename))
(do
(println "Deleted" filename)
true)
(println "Failed to delete" filename)))
(defn get-year-month-day-millis [datetime]
(hash-map :year (.getYear datetime)
:month (.getAsShortText (.monthOfYear datetime))
:month-full (.getAsText (.monthOfYear datetime))
:month-num (.getMonthOfYear datetime)
:day (.getDayOfMonth datetime)
:millis (.getMillis datetime)))
(defn get-relative-path [month year slug]
(str month "-" year "/" slug ".html"))
(defn get-publish-time [archive slug]
(loop [remainder archive]
(if (empty? remainder)
nil
(if (= ((first remainder) :slug) slug)
((first remainder) :publish-time)
(recur (rest remainder))))))
(defn write-article [relative-path article-content title
publish-time link archive slug]
(try-write (str (*config* :doc-root) "/" relative-path)
(apply str (article-template
article-content
title
publish-time
(str "/" relative-path)
link))))
(defn unlink-article [relative-path]
(let [target-filename (str (*config* :doc-root) "/" relative-path)]
(if (.delete (java.io.File. target-filename))
(do
(println "Deleted" target-filename)
true)
(println "Failed to delete" target-filename))))
(defn publish-article [now slug title article-content link]
(let [ymdm (get-year-month-day-millis now)
year (ymdm :year)
month (ymdm :month)
millis (ymdm :millis)
archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)]
(if (article-exists? archive slug)
(println "Can't publish an article that already exists.")
(let [relative-path (get-relative-path month year slug)
encoded-title (hexify title)]
(try-write archive-filename
(json-str (create-metadata archive
{:slug slug
:publish-time millis
:relative-path relative-path
:title encoded-title})))
(write-article relative-path article-content title now link archive slug)
true))))
(defn revise-article [month year slug title article-content link now]
(let [archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)
revision-time (:millis (get-year-month-day-millis now))]
(if (article-exists? archive slug)
(let [orig-metadata (get-article-metadata archive slug)
relative-path (get-relative-path month year slug)
encoded-title (hexify title)
updated-archive (create-metadata (delete-metadata archive slug)
(assoc orig-metadata
:revision-time revision-time
:title encoded-title))]
(try-write archive-filename (json-str updated-archive))
(write-article relative-path article-content title
(get-publish-time archive slug) link
archive slug)
true)
(println "Can't revise an article that doesn't exist."))))
(defn delete-article [month year slug]
(let [archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)]
(if (article-exists? archive slug)
(if-let [metadata (get-article-metadata archive slug)]
(do
(if (unlink-article (metadata :relative-path))
(let [lighter-archive (delete-metadata archive slug)]
(if (empty? lighter-archive)
(delete-by-filename archive-filename)
(try-write archive-filename
(json-str (delete-metadata archive slug))))
true))))
(println "Can't delete an article that doesn't exist."))))
(defn datetime-from-month-year [month-year-string]
(if-let [[match month year] (re-find #"([A-Z][a-z]+)-([0-9]+)"
month-year-string)]
(let [builder (DateTimeFormatterBuilder.)
custom-builder (.builder
(.appendYear
(.appendLiteral
(.appendMonthOfYearShortText builder)) "-") 4 4)
formatter (.toFormatter custom-builder)]
(.parseDateTime formatter month-year-string)))
nil)
(defn dir-list [dir]
(apply vector (.list (java.io.File. dir))))
(defn datetime-from-month-year [month year]
(-> (DateTimeFormatterBuilder.)
(.appendMonthOfYearShortText)
(.appendLiteral "-")
(.appendYear 4 4)
(.toFormatter)
(.parseDateTime (str month "-" year))))
(defn annotated-archive-from-file [filename]
(let [archive-regex #"([A-Z][a-z]+)-([0-9]+).json"]
(if-let [[filename month year] (re-find archive-regex filename)]
(hash-map :filename (str *archive-root* "/" filename)
:datetime (datetime-from-month-year month year)
:month month
:year year))))
(defn archives-to-seq
([archives]
(archives-to-seq nil archives))
([articles archives]
(lazy-seq
(if (first articles)
(cons (first articles) (archives-to-seq (rest articles) archives))
(if (first archives)
(let [articles (read-archive (:filename (first archives)))]
(cons (first articles) (archives-to-seq (rest articles)
(rest archives))))
nil)))))
(defn get-desc-sorted-archives []
(sort #(compare (%2 :datetime) (%1 :datetime))
(map annotated-archive-from-file (dir-list *archive-root*))))
(defn generate-index [articles target-dir page-title archive-month-years]
(if (empty? articles)
(println "Not generating an empty index.")
(let [article-urls (map #(str "file:///" (*config* :doc-root) "/"
(% :relative-path)) articles)
article-contents (map fetch-content article-urls)
article-nodes (map #(select % (*config* :article-selector))
article-contents)]
(if (and (not (empty? article-nodes)) (not (empty? archive-month-years)))
(try-write (str target-dir "/index.html")
(apply str (index-template page-title article-nodes
archive-month-years)))
(println "Not generating empty index.")))))
(defn escaped-article-content-from-url [url]
(escape-html
(apply str
(emit* (-> (html-resource (java.net.URL. url))
(select (*config* :input-article-selector)))))))
(defn epoch-to-utc-timestamp [epoch-time]
(if epoch-time
(-> (ISODateTimeFormat/dateTime)
(.print (DateTime. epoch-time (DateTimeZone/UTC))))
nil))
(defn atom-entry [title link publish-time revision-time content]
(let [publish-ymdm (get-year-month-day-millis (DateTime. publish-time))
datestamp (apply str
(interpose \-
((juxt #(format "%04d" (:year %))
#(format "%02d" (:month-num %))
#(format "%02d" (:day %)))
publish-ymdm)))
[publish-utc-timestamp revision-utc-timestamp]
(map epoch-to-utc-timestamp [publish-time revision-time])]
[:entry
[:title title]
[:link {:rel "alternate" :type "text/html" :href link}]
[:id (str "tag:" (*config* :base-url) "," datestamp ":/" publish-time)]
[:published publish-utc-timestamp]
[:updated (if revision-utc-timestamp revision-utc-timestamp publish-utc-timestamp)]
[:author
[:name (*config* :author-name)]
[:uri (*config* :author-uri)]]
[:content {:type "html"} content]]))
(defn generate-atom [articles target-dir now]
(if (empty? articles)
(println "Not generating an empty index.")
(let [local-article-urls (map #(str "file:///" (*config* :doc-root)
(% :relative-path)) articles)
article-contents (map escaped-article-content-from-url local-article-urls)
absolute-article-urls (map #(str "http://" (*config* :base-url) "/"
(% :relative-path)) articles)
titles (map #(unhexify (:title %)) articles)
publish-times (map :publish-time articles)
revision-times (map :revision-time articles)
atom-entries (map atom-entry
titles
absolute-article-urls
publish-times
revision-times
article-contents)
latest-update (apply max
(remove #(nil? %)
(reduce conj
publish-times
revision-times)))]
(try-write
(str target-dir (*config* :atom-filename))
(apply
str
(html (xml-declaration "utf-8")
[:feed {:xmlns "http://www.w3.org/2005/Atom"}
[:title (*config* :blog-title)]
[:subtitle (*config* :blog-subtitle)]
[:link {:rel "alternate"
:type "text/html"
:href (str "http://" (*config* :base-url) "/")}]
[:link {:rel "self"
:type "application/atom+xml"
:href (str "http://" (*config* :base-url) "/"
(*config* :atom-filename))}]
[:id (*config* :feed-id)]
[:updated (epoch-to-utc-timestamp latest-update)]
[:rights
(format
"Copyright © %d, %s"
(:year (get-year-month-day-millis (DateTime. latest-update)))
(*config* :author-name))]
atom-entries]))))))
(defn generate-indices [for-datetime max-root-articles]
(let [ymdm (get-year-month-day-millis for-datetime)
year (str (ymdm :year))
month (ymdm :month)
month-full (ymdm :month-full)
sorted-archives (get-desc-sorted-archives)
target-month-archive (filter #(and (= year (:year %)) (= month (:month %)))
sorted-archives)
target-month-articles (archives-to-seq target-month-archive)
archive-month-years (map #(select-keys % [:month :year])
sorted-archives)
target-month-articles-asc (sort #(compare (%1 :publish-time)
(%2 :publish-time))
target-month-articles)
all-articles (archives-to-seq sorted-archives)]
(generate-index target-month-articles-asc
(str (*config* :doc-root) "/" month "-" year)
(str month-full " " year " - " (*config* :blog-title))
target-month-archive)
(generate-index (take max-root-articles all-articles)
(*config* :doc-root)
(*config* :blog-title)
archive-month-years)
(generate-atom (take max-root-articles all-articles) (*config* :doc-root)
for-datetime)))
(defn get-article-content [input-filename dumb-quotes]
(let [uri (str "file://" input-filename)]
;; If the input looks like it contains markdown, convert it to html
(if (re-seq #"^*.md$" uri)
(let [markdown (.markdown (MarkdownProcessor.)
(slurp (input-stream (java.net.URL. uri))))
double-quoter (if dumb-quotes identity smart-quote)]
(-> markdown
double-quoter
curly-single-quote
long-dashes
(.getBytes "UTF-8")
(java.io.ByteArrayInputStream.)
(java.io.InputStreamReader.)
html-resource))
(select (fetch-content uri) (*config* :input-article-selector)))))
(defn usage-and-exit [usage]
(do
(println usage)
(. System (exit 1))))
(defn -main [& args]
(let [[options args usage]
(cli args
["-p" "--publish" "Publish an article" :flag true]
["-r" "--revise" "Revise an article" :flag true]
["-d" "--delete" "Delete an article" :flag true]
["-m" "--month" "Month an article to revise was published in"]
["-y" "--year" "Year an article to revise was published in"]
["-s" "--slug" "Article slug, ex: my-article-title"]
["-t" "--title" "The article's title"]
["-l" "--link" "Title links externally link, ex: \"http://www.noaa.gov\""]
["-a" "--article" "File containing an article written in markdown or HTML"]
["-w" "--watch" "Optionally watch an input while revising" :flag true]
["-b" "--dumbquotes" "Disable smart quoting" :flag true]
["-h" "--help" "Display usage"])
now (DateTime.)
publish (options :publish)
revise (options :revise)
delete (options :delete)
month (options :month)
year (options :year)
slug (options :slug)
title (options :title)
link (options :link)
article (options :article)
watch (options :watch)
dumb-quotes (options :dumbquotes)
help (options :help)]
(if (not (or publish revise delete help))
(usage-and-exit usage))
(if delete
(if (and slug month year)
(if (delete-article month year slug)
(generate-indices (datetime-from-month-year month year)
(*config* :max-home-page-articles)))
(do
(println "Delete requires options slug, month and year.")
(usage-and-exit usage)))
(if revise
(if (and slug title article)
(loop [previous-modified 0]
(let [current-modified (.lastModified (java.io.File. article))]
(if (not (= previous-modified current-modified))
(do
(if (revise-article month year slug title
(get-article-content article dumb-quotes)
link now)
(generate-indices (datetime-from-month-year month year)
(*config* :max-home-page-articles)))
(if watch (recur current-modified)))
(do
(Thread/sleep 200)
(recur previous-modified)))))
(do
(println (str "Revise requires slug, title, article, month and year. If "
"you're revising a link post, include the link option, too."))
(usage-and-exit usage)))
(if publish
(if (and slug title article)
(if (publish-article now slug title
(get-article-content article dumb-quotes)
link)
(generate-indices now (*config* :max-home-page-articles)))
(do
(println "Publish requires slug, title and article.")
(usage-and-exit usage))))))))
| true |
;; Copyright (c) 2012-2014, PI:NAME:<NAME>END_PI
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
;; * Neither the name of Darren Mutz nor the names of its
;; contributors may be used to endorse or promote products derived
;; from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(ns ^{:author "PI:NAME:<NAME>END_PI"
:see-also
[["https://github.com/darrenmutz/sheaf" "Source code"]]}
sheaf.core
(:import com.petebevin.markdown.MarkdownProcessor)
(:import org.joda.time.DateTime)
(:import org.joda.time.DateTimeZone)
(:import org.joda.time.format.DateTimeFormatterBuilder)
(:import org.joda.time.format.ISODateTimeFormat)
(:gen-class)
(:use clojure.java.io)
(:use clojure.tools.cli)
(:use [clojure.data.json :only (json-str write-json read-json)])
(:use [net.cgrand.enlive-html :only
(at deftemplate defsnippet content emit* set-attr do->
first-child html-resource select nth-of-type any-node
text-node html-content)])
(:use hiccup.core)
(:use hiccup.page)
(:use hiccup.util))
(load-file (str (System/getProperty (str "user.home")) "/.sheaf"))
(def ^:dynamic *template-url*
(str "file:///" (*config* :sheaf-root) "/" (*config* :template-file)))
(def ^:dynamic *archive-root*
(str (*config* :sheaf-root) "/" (*config* :archive-dir)))
(def ^:dynamic *smart-quote* true)
(defn create-metadata [archive article]
(sort #(compare (%2 :publish-time) (%1 :publish-time)) (cons article archive)))
(defn delete-metadata [archive slug]
(remove #(= (% :slug) slug) archive))
(defn get-archive-filename [month year]
(str *archive-root* "/" month "-" year ".json"))
(defn read-archive [filename]
(try
(seq (read-json (slurp filename)))
(catch java.io.FileNotFoundException e [])))
(defn article-exists? [archive slug]
(contains? (apply sorted-set (map :slug archive)) slug))
(defn get-article-metadata [archive slug]
(first (filter #(= (% :slug) slug) archive)))
(defn fetch-content [url]
(html-resource (java.net.URL. url)))
(defn long-form-date [datetime]
(-> (DateTimeFormatterBuilder.)
(.appendMonthOfYearText)
(.appendLiteral " ")
(.appendDayOfMonth 1)
(.appendLiteral ", ")
(.appendYear 4 4)
(.toFormatter)
(.print datetime)))
(def ^:dynamic *link-sel* [[:.archive-list (nth-of-type 1)] :> first-child])
(defn hexify [s]
(apply str (map #(format "%02x" %) (.getBytes s "UTF-8"))))
(defn unhexify [s]
(let [bytes (into-array Byte/TYPE
(map (fn [[x y]]
(unchecked-byte (Integer/parseInt (str x y) 16)))
(partition 2 s)))]
(String. bytes "UTF-8")))
(defsnippet link-model (fetch-content *template-url*) *link-sel*
[{:keys [month year]}]
[:a] (do->
(content (str month " " year))
(set-attr :href (str "/" month "-" year))))
(defn elipsis-glyphs
"Convert triple periods to precomposed elipsis glyphs."
[s]
(clojure.string/replace #"\.\.\." "…"))
(defn long-dashes
"Convert all double dashes to en dashes and triple dashes to em
dashes. Leave single dashes alone."
[s]
(-> s
(clojure.string/replace #"---" "—")
(clojure.string/replace #"--" "–")))
(defn curly-single-quote
"Naively convert all single quotes to right single quotation marks,
as though all single quotation marks appear in an English
contraction or possessive. Ignores matching and all other context."
[s]
(clojure.string/replace s #"'" "’"))
(defn smart-quote
"Naive smart quoter. Turns typewriter double quotes into curly
matched double quotes on a best effort basis. Assumes all double
quotes should be transformed and that they appear perfectly
balanced in the input. No attempt is made to reason about
interaction with existing curly quotes."
[s]
(let [tokens (clojure.string/split s #"\"")]
(apply str (map #(%1 %2) (cycle [identity #(str "“" % "”")])
tokens))))
(deftemplate article-template (fetch-content *template-url*)
[article title datetime permalink link]
(*config* :articles-selector) (apply content article)
(*config* :page-title-selector) (content title)
(*config* :title-selector) (content title)
(*config* :title-selector) (set-attr :href (if link link permalink))
(*config* :title-selector) (set-attr :id (if link "link" "permalink"))
(*config* :time-selector) (content (long-form-date datetime))
(*config* :time-selector) (set-attr "datetime" (.toString datetime))
(*config* :permalink-selector) (set-attr "href" permalink)
(*config* :archives-selector) nil)
(deftemplate index-template (fetch-content *template-url*)
[page-title articles archive-month-years]
(*config* :page-title-selector) (content page-title)
(*config* :index-articles-selector) (apply content articles)
(*config* :archive-list-selector) (content (map link-model
archive-month-years)))
(defn try-write [filename content]
(do
(.mkdirs (java.io.File. (.getParent (java.io.File. filename))))
(try
(do
(spit filename content)
(println "Wrote" filename))
(catch java.io.FileNotFoundException e
(do
(println "Couldn't write to" filename)
(. System (exit 1)))))))
(defn delete-by-filename [filename]
(if (.delete (java.io.File. filename))
(do
(println "Deleted" filename)
true)
(println "Failed to delete" filename)))
(defn get-year-month-day-millis [datetime]
(hash-map :year (.getYear datetime)
:month (.getAsShortText (.monthOfYear datetime))
:month-full (.getAsText (.monthOfYear datetime))
:month-num (.getMonthOfYear datetime)
:day (.getDayOfMonth datetime)
:millis (.getMillis datetime)))
(defn get-relative-path [month year slug]
(str month "-" year "/" slug ".html"))
(defn get-publish-time [archive slug]
(loop [remainder archive]
(if (empty? remainder)
nil
(if (= ((first remainder) :slug) slug)
((first remainder) :publish-time)
(recur (rest remainder))))))
(defn write-article [relative-path article-content title
publish-time link archive slug]
(try-write (str (*config* :doc-root) "/" relative-path)
(apply str (article-template
article-content
title
publish-time
(str "/" relative-path)
link))))
(defn unlink-article [relative-path]
(let [target-filename (str (*config* :doc-root) "/" relative-path)]
(if (.delete (java.io.File. target-filename))
(do
(println "Deleted" target-filename)
true)
(println "Failed to delete" target-filename))))
(defn publish-article [now slug title article-content link]
(let [ymdm (get-year-month-day-millis now)
year (ymdm :year)
month (ymdm :month)
millis (ymdm :millis)
archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)]
(if (article-exists? archive slug)
(println "Can't publish an article that already exists.")
(let [relative-path (get-relative-path month year slug)
encoded-title (hexify title)]
(try-write archive-filename
(json-str (create-metadata archive
{:slug slug
:publish-time millis
:relative-path relative-path
:title encoded-title})))
(write-article relative-path article-content title now link archive slug)
true))))
(defn revise-article [month year slug title article-content link now]
(let [archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)
revision-time (:millis (get-year-month-day-millis now))]
(if (article-exists? archive slug)
(let [orig-metadata (get-article-metadata archive slug)
relative-path (get-relative-path month year slug)
encoded-title (hexify title)
updated-archive (create-metadata (delete-metadata archive slug)
(assoc orig-metadata
:revision-time revision-time
:title encoded-title))]
(try-write archive-filename (json-str updated-archive))
(write-article relative-path article-content title
(get-publish-time archive slug) link
archive slug)
true)
(println "Can't revise an article that doesn't exist."))))
(defn delete-article [month year slug]
(let [archive-filename (get-archive-filename month year)
archive (read-archive archive-filename)]
(if (article-exists? archive slug)
(if-let [metadata (get-article-metadata archive slug)]
(do
(if (unlink-article (metadata :relative-path))
(let [lighter-archive (delete-metadata archive slug)]
(if (empty? lighter-archive)
(delete-by-filename archive-filename)
(try-write archive-filename
(json-str (delete-metadata archive slug))))
true))))
(println "Can't delete an article that doesn't exist."))))
(defn datetime-from-month-year [month-year-string]
(if-let [[match month year] (re-find #"([A-Z][a-z]+)-([0-9]+)"
month-year-string)]
(let [builder (DateTimeFormatterBuilder.)
custom-builder (.builder
(.appendYear
(.appendLiteral
(.appendMonthOfYearShortText builder)) "-") 4 4)
formatter (.toFormatter custom-builder)]
(.parseDateTime formatter month-year-string)))
nil)
(defn dir-list [dir]
(apply vector (.list (java.io.File. dir))))
(defn datetime-from-month-year [month year]
(-> (DateTimeFormatterBuilder.)
(.appendMonthOfYearShortText)
(.appendLiteral "-")
(.appendYear 4 4)
(.toFormatter)
(.parseDateTime (str month "-" year))))
(defn annotated-archive-from-file [filename]
(let [archive-regex #"([A-Z][a-z]+)-([0-9]+).json"]
(if-let [[filename month year] (re-find archive-regex filename)]
(hash-map :filename (str *archive-root* "/" filename)
:datetime (datetime-from-month-year month year)
:month month
:year year))))
(defn archives-to-seq
([archives]
(archives-to-seq nil archives))
([articles archives]
(lazy-seq
(if (first articles)
(cons (first articles) (archives-to-seq (rest articles) archives))
(if (first archives)
(let [articles (read-archive (:filename (first archives)))]
(cons (first articles) (archives-to-seq (rest articles)
(rest archives))))
nil)))))
(defn get-desc-sorted-archives []
(sort #(compare (%2 :datetime) (%1 :datetime))
(map annotated-archive-from-file (dir-list *archive-root*))))
(defn generate-index [articles target-dir page-title archive-month-years]
(if (empty? articles)
(println "Not generating an empty index.")
(let [article-urls (map #(str "file:///" (*config* :doc-root) "/"
(% :relative-path)) articles)
article-contents (map fetch-content article-urls)
article-nodes (map #(select % (*config* :article-selector))
article-contents)]
(if (and (not (empty? article-nodes)) (not (empty? archive-month-years)))
(try-write (str target-dir "/index.html")
(apply str (index-template page-title article-nodes
archive-month-years)))
(println "Not generating empty index.")))))
(defn escaped-article-content-from-url [url]
(escape-html
(apply str
(emit* (-> (html-resource (java.net.URL. url))
(select (*config* :input-article-selector)))))))
(defn epoch-to-utc-timestamp [epoch-time]
(if epoch-time
(-> (ISODateTimeFormat/dateTime)
(.print (DateTime. epoch-time (DateTimeZone/UTC))))
nil))
(defn atom-entry [title link publish-time revision-time content]
(let [publish-ymdm (get-year-month-day-millis (DateTime. publish-time))
datestamp (apply str
(interpose \-
((juxt #(format "%04d" (:year %))
#(format "%02d" (:month-num %))
#(format "%02d" (:day %)))
publish-ymdm)))
[publish-utc-timestamp revision-utc-timestamp]
(map epoch-to-utc-timestamp [publish-time revision-time])]
[:entry
[:title title]
[:link {:rel "alternate" :type "text/html" :href link}]
[:id (str "tag:" (*config* :base-url) "," datestamp ":/" publish-time)]
[:published publish-utc-timestamp]
[:updated (if revision-utc-timestamp revision-utc-timestamp publish-utc-timestamp)]
[:author
[:name (*config* :author-name)]
[:uri (*config* :author-uri)]]
[:content {:type "html"} content]]))
(defn generate-atom [articles target-dir now]
(if (empty? articles)
(println "Not generating an empty index.")
(let [local-article-urls (map #(str "file:///" (*config* :doc-root)
(% :relative-path)) articles)
article-contents (map escaped-article-content-from-url local-article-urls)
absolute-article-urls (map #(str "http://" (*config* :base-url) "/"
(% :relative-path)) articles)
titles (map #(unhexify (:title %)) articles)
publish-times (map :publish-time articles)
revision-times (map :revision-time articles)
atom-entries (map atom-entry
titles
absolute-article-urls
publish-times
revision-times
article-contents)
latest-update (apply max
(remove #(nil? %)
(reduce conj
publish-times
revision-times)))]
(try-write
(str target-dir (*config* :atom-filename))
(apply
str
(html (xml-declaration "utf-8")
[:feed {:xmlns "http://www.w3.org/2005/Atom"}
[:title (*config* :blog-title)]
[:subtitle (*config* :blog-subtitle)]
[:link {:rel "alternate"
:type "text/html"
:href (str "http://" (*config* :base-url) "/")}]
[:link {:rel "self"
:type "application/atom+xml"
:href (str "http://" (*config* :base-url) "/"
(*config* :atom-filename))}]
[:id (*config* :feed-id)]
[:updated (epoch-to-utc-timestamp latest-update)]
[:rights
(format
"Copyright © %d, %s"
(:year (get-year-month-day-millis (DateTime. latest-update)))
(*config* :author-name))]
atom-entries]))))))
(defn generate-indices [for-datetime max-root-articles]
(let [ymdm (get-year-month-day-millis for-datetime)
year (str (ymdm :year))
month (ymdm :month)
month-full (ymdm :month-full)
sorted-archives (get-desc-sorted-archives)
target-month-archive (filter #(and (= year (:year %)) (= month (:month %)))
sorted-archives)
target-month-articles (archives-to-seq target-month-archive)
archive-month-years (map #(select-keys % [:month :year])
sorted-archives)
target-month-articles-asc (sort #(compare (%1 :publish-time)
(%2 :publish-time))
target-month-articles)
all-articles (archives-to-seq sorted-archives)]
(generate-index target-month-articles-asc
(str (*config* :doc-root) "/" month "-" year)
(str month-full " " year " - " (*config* :blog-title))
target-month-archive)
(generate-index (take max-root-articles all-articles)
(*config* :doc-root)
(*config* :blog-title)
archive-month-years)
(generate-atom (take max-root-articles all-articles) (*config* :doc-root)
for-datetime)))
(defn get-article-content [input-filename dumb-quotes]
(let [uri (str "file://" input-filename)]
;; If the input looks like it contains markdown, convert it to html
(if (re-seq #"^*.md$" uri)
(let [markdown (.markdown (MarkdownProcessor.)
(slurp (input-stream (java.net.URL. uri))))
double-quoter (if dumb-quotes identity smart-quote)]
(-> markdown
double-quoter
curly-single-quote
long-dashes
(.getBytes "UTF-8")
(java.io.ByteArrayInputStream.)
(java.io.InputStreamReader.)
html-resource))
(select (fetch-content uri) (*config* :input-article-selector)))))
(defn usage-and-exit [usage]
(do
(println usage)
(. System (exit 1))))
(defn -main [& args]
(let [[options args usage]
(cli args
["-p" "--publish" "Publish an article" :flag true]
["-r" "--revise" "Revise an article" :flag true]
["-d" "--delete" "Delete an article" :flag true]
["-m" "--month" "Month an article to revise was published in"]
["-y" "--year" "Year an article to revise was published in"]
["-s" "--slug" "Article slug, ex: my-article-title"]
["-t" "--title" "The article's title"]
["-l" "--link" "Title links externally link, ex: \"http://www.noaa.gov\""]
["-a" "--article" "File containing an article written in markdown or HTML"]
["-w" "--watch" "Optionally watch an input while revising" :flag true]
["-b" "--dumbquotes" "Disable smart quoting" :flag true]
["-h" "--help" "Display usage"])
now (DateTime.)
publish (options :publish)
revise (options :revise)
delete (options :delete)
month (options :month)
year (options :year)
slug (options :slug)
title (options :title)
link (options :link)
article (options :article)
watch (options :watch)
dumb-quotes (options :dumbquotes)
help (options :help)]
(if (not (or publish revise delete help))
(usage-and-exit usage))
(if delete
(if (and slug month year)
(if (delete-article month year slug)
(generate-indices (datetime-from-month-year month year)
(*config* :max-home-page-articles)))
(do
(println "Delete requires options slug, month and year.")
(usage-and-exit usage)))
(if revise
(if (and slug title article)
(loop [previous-modified 0]
(let [current-modified (.lastModified (java.io.File. article))]
(if (not (= previous-modified current-modified))
(do
(if (revise-article month year slug title
(get-article-content article dumb-quotes)
link now)
(generate-indices (datetime-from-month-year month year)
(*config* :max-home-page-articles)))
(if watch (recur current-modified)))
(do
(Thread/sleep 200)
(recur previous-modified)))))
(do
(println (str "Revise requires slug, title, article, month and year. If "
"you're revising a link post, include the link option, too."))
(usage-and-exit usage)))
(if publish
(if (and slug title article)
(if (publish-article now slug title
(get-article-content article dumb-quotes)
link)
(generate-indices now (*config* :max-home-page-articles)))
(do
(println "Publish requires slug, title and article.")
(usage-and-exit usage))))))))
|
[
{
"context": "] [:person/id 2]]\n :person/id {1 {:person/name \"Bob\"}\n 2 {:person/name \"Judy\"}}})\n\n(let",
"end": 395,
"score": 0.9998363256454468,
"start": 392,
"tag": "NAME",
"value": "Bob"
},
{
"context": "erson/name \"Bob\"}\n 2 {:person/name \"Judy\"}}})\n\n(let [starting-node sample-db]\n (fdn/db->t",
"end": 434,
"score": 0.9998248219490051,
"start": 430,
"tag": "NAME",
"value": "Judy"
},
{
"context": "ple [(comp/get-initial-state Person {:id 1 :name \"Bob\"})\n (comp",
"end": 1459,
"score": 0.9998300075531006,
"start": 1456,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (comp/get-initial-state Person {:id 2 :name \"Judy\"})]})})\n\n(def app (app/fulcro-app))\n\n(app/mount! ",
"end": 1553,
"score": 0.9998431205749512,
"start": 1549,
"tag": "NAME",
"value": "Judy"
},
{
"context": "component! app Person {:person/id 3 :person/name \"Sally\" :person/address {:address/id 33 :address/street ",
"end": 1717,
"score": 0.9998050928115845,
"start": 1712,
"tag": "NAME",
"value": "Sally"
},
{
"context": "component! app Person {:person/id 3 :person/name \"Sally\"})\n(merge/merge-component! app Person {:person/id",
"end": 1914,
"score": 0.9998284578323364,
"start": 1909,
"tag": "NAME",
"value": "Sally"
},
{
"context": "component! app Person {:person/id 2 :person/name \"Jonathan\"})",
"end": 1989,
"score": 0.9998456239700317,
"start": 1981,
"tag": "NAME",
"value": "Jonathan"
}
] |
src/workspaces/com/example/workspaces/testing.clj
|
ozimos/fulcro-rad-demo
| 0 |
(ns com.example.workspaces.testing
(:require [com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.application :as app]))
(def sample-db
{:people [[:person/id 1] [:person/id 2]]
:person/id {1 {:person/name "Bob"}
2 {:person/name "Judy"}}})
(let [starting-node sample-db]
(fdn/db->tree [{:people [:person/stuff]}] starting-node sample-db))
(let [starting-node sample-db]
(fdn/db->tree [{:people [:person/name]}] starting-node sample-db))
(let [starting-entity {}]
(fdn/db->tree [[:person/id 1]] starting-entity sample-db))
(defsc SampleComp [this props]
{:ident (fn [] [:component/id ::SampleComp])})
(let [options (comp/component-options SampleComp)
ident-fn (get options :ident)]
(ident-fn SampleComp {}))
(defsc Address [this props]
{:query [:address/id :address/street]
:ident :address/id})
(defsc Person [this props]
{:query [:person/id :person/name {:person/address (comp/get-query Address)}]
:ident :person/id
:initial-state (fn [params] {:person/id (:id params)
:person/name (:name params)})})
(defsc Root [this props]
{:query [{:root/people (comp/get-query Person)}]
:initial-state (fn [_] {:root/people [(comp/get-initial-state Person {:id 1 :name "Bob"})
(comp/get-initial-state Person {:id 2 :name "Judy"})]})})
(def app (app/fulcro-app))
(app/mount! app Root :headless)
(app/current-state app)
(merge/merge-component! app Person {:person/id 3 :person/name "Sally" :person/address {:address/id 33 :address/street "111 Main St"}} :append [:root/people] :replace [:person/id 1 :person/spouse])
(merge/merge-component! app Person {:person/id 3 :person/name "Sally"})
(merge/merge-component! app Person {:person/id 2 :person/name "Jonathan"})
|
18308
|
(ns com.example.workspaces.testing
(:require [com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.application :as app]))
(def sample-db
{:people [[:person/id 1] [:person/id 2]]
:person/id {1 {:person/name "<NAME>"}
2 {:person/name "<NAME>"}}})
(let [starting-node sample-db]
(fdn/db->tree [{:people [:person/stuff]}] starting-node sample-db))
(let [starting-node sample-db]
(fdn/db->tree [{:people [:person/name]}] starting-node sample-db))
(let [starting-entity {}]
(fdn/db->tree [[:person/id 1]] starting-entity sample-db))
(defsc SampleComp [this props]
{:ident (fn [] [:component/id ::SampleComp])})
(let [options (comp/component-options SampleComp)
ident-fn (get options :ident)]
(ident-fn SampleComp {}))
(defsc Address [this props]
{:query [:address/id :address/street]
:ident :address/id})
(defsc Person [this props]
{:query [:person/id :person/name {:person/address (comp/get-query Address)}]
:ident :person/id
:initial-state (fn [params] {:person/id (:id params)
:person/name (:name params)})})
(defsc Root [this props]
{:query [{:root/people (comp/get-query Person)}]
:initial-state (fn [_] {:root/people [(comp/get-initial-state Person {:id 1 :name "<NAME>"})
(comp/get-initial-state Person {:id 2 :name "<NAME>"})]})})
(def app (app/fulcro-app))
(app/mount! app Root :headless)
(app/current-state app)
(merge/merge-component! app Person {:person/id 3 :person/name "<NAME>" :person/address {:address/id 33 :address/street "111 Main St"}} :append [:root/people] :replace [:person/id 1 :person/spouse])
(merge/merge-component! app Person {:person/id 3 :person/name "<NAME>"})
(merge/merge-component! app Person {:person/id 2 :person/name "<NAME>"})
| true |
(ns com.example.workspaces.testing
(:require [com.fulcrologic.fulcro.algorithms.denormalize :as fdn]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.application :as app]))
(def sample-db
{:people [[:person/id 1] [:person/id 2]]
:person/id {1 {:person/name "PI:NAME:<NAME>END_PI"}
2 {:person/name "PI:NAME:<NAME>END_PI"}}})
(let [starting-node sample-db]
(fdn/db->tree [{:people [:person/stuff]}] starting-node sample-db))
(let [starting-node sample-db]
(fdn/db->tree [{:people [:person/name]}] starting-node sample-db))
(let [starting-entity {}]
(fdn/db->tree [[:person/id 1]] starting-entity sample-db))
(defsc SampleComp [this props]
{:ident (fn [] [:component/id ::SampleComp])})
(let [options (comp/component-options SampleComp)
ident-fn (get options :ident)]
(ident-fn SampleComp {}))
(defsc Address [this props]
{:query [:address/id :address/street]
:ident :address/id})
(defsc Person [this props]
{:query [:person/id :person/name {:person/address (comp/get-query Address)}]
:ident :person/id
:initial-state (fn [params] {:person/id (:id params)
:person/name (:name params)})})
(defsc Root [this props]
{:query [{:root/people (comp/get-query Person)}]
:initial-state (fn [_] {:root/people [(comp/get-initial-state Person {:id 1 :name "PI:NAME:<NAME>END_PI"})
(comp/get-initial-state Person {:id 2 :name "PI:NAME:<NAME>END_PI"})]})})
(def app (app/fulcro-app))
(app/mount! app Root :headless)
(app/current-state app)
(merge/merge-component! app Person {:person/id 3 :person/name "PI:NAME:<NAME>END_PI" :person/address {:address/id 33 :address/street "111 Main St"}} :append [:root/people] :replace [:person/id 1 :person/spouse])
(merge/merge-component! app Person {:person/id 3 :person/name "PI:NAME:<NAME>END_PI"})
(merge/merge-component! app Person {:person/id 2 :person/name "PI:NAME:<NAME>END_PI"})
|
[
{
"context": "uce :refer [try-try-again]]))\n\n(def source-token \"36c35e23-8757-4a9d-aacf-345e9b7eb50d\")\n(def version",
"end": 621,
"score": 0.5372271537780762,
"start": 620,
"tag": "KEY",
"value": "3"
},
{
"context": "ce :refer [try-try-again]]))\n\n(def source-token \"36c35e23-8757-4a9d-aacf-345e9b7eb50d\")\n(def version \"0.1.6\")\n\n; Counters. \n(def heartb",
"end": 656,
"score": 0.8422544002532959,
"start": 621,
"tag": "PASSWORD",
"value": "6c35e23-8757-4a9d-aacf-345e9b7eb50d"
}
] |
src/event_data_wikipedia_agent/process.clj
|
CrossRef/event-data-wikipedia-agent
| 0 |
(ns event-data-wikipedia-agent.process
"Process edit events in Wikipedia."
(:require [org.crossref.event-data-agent-framework.web :as framework-web]
[org.crossref.event-data-agent-framework.core :as c]
[crossref.util.doi :as cr-doi])
(:require [clojure.data.json :as json]
[clojure.tools.logging :as l]
[clojure.set :refer [difference]])
(:require [org.httpkit.client :as http]
[clj-time.coerce :as clj-time-coerce])
(:import [java.net URLEncoder]
[java.util UUID])
(:require [robert.bruce :refer [try-try-again]]))
(def source-token "36c35e23-8757-4a9d-aacf-345e9b7eb50d")
(def version "0.1.6")
; Counters.
(def heartbeat-restbase (atom 0))
(def heartbeat-restbase-ok (atom 0))
(def heartbeat-restbase-error (atom 0))
(defn build-restbase-url
"Build a URL that can be retrieved from RESTBase"
[server-name title revision]
(let [encoded-title (URLEncoder/encode (.replaceAll title " " "_"))]
(str "https://" server-name "/api/rest_v1/page/html/" encoded-title "/" revision)))
(defn build-wikipedia-url
"Build a URL that can be used to fetch the page via the normal HTML website."
[server-name title]
(str "https://" server-name "/w/index.php?" (#'http/query-string {:title title})))
(defn process-bodies
"Process a diff between two HTML documents.
Return [added-dois removed-dois]."
[{old-revision :old-revision old-body :old-body
new-revision :new-revision new-body :new-body
title :title
server-name :server-name
input-event-id :input-event-id}]
(let [old-dois (framework-web/extract-dois-from-body old-body)
new-dois (framework-web/extract-dois-from-body new-body)
added-dois (difference new-dois old-dois)
removed-dois (difference old-dois new-dois)]
[added-dois removed-dois]))
(defn process
"Process a new input event by looking up old and new revisions.
Return an Evidence Record (which may or may not be empty of events)."
[data]
(let [server-name (get data "server_name")
server-url (get data "server_url")
title (get data "title")
old-revision (get-in data ["revision" "old"])
new-revision (get-in data ["revision" "new"])
old-restbase-url (build-restbase-url server-name title old-revision)
new-restbase-url (build-restbase-url server-name title new-revision)
{old-status :status old-body :body} (try-try-again {:tries 10 :delay 1000 :return? #(= 200 (:status %))} (fn [] @(http/get old-restbase-url {:timeout 10000})))
{new-status :status new-body :body} (try-try-again {:tries 10 :delay 1000 :return? #(= 200 (:status %))} (fn [] @(http/get new-restbase-url {:timeout 10000})))
timestamp (clj-time-coerce/from-long (* 1000 (get data "timestamp")))
[added-dois removed-dois] (when (and (= 200 old-status) (= 200 new-status))
(process-bodies {:old-revision old-revision :old-body old-body
:new-revision new-revision :new-body new-body
:title title
:server-name server-name
:timestamp timestamp}))
canonical-url (framework-web/fetch-canonical-url (build-wikipedia-url server-name title))
added-events (map (fn [doi] {:action "add" :doi doi :event-id (str (UUID/randomUUID))}) added-dois)
removed-events (map (fn [doi] {:action "delete" :doi doi :event-id (str (UUID/randomUUID))}) removed-dois)
all-events (concat added-events removed-events)
author-url (when-let [author-name (get-in data ["input" "user"])]
(str "https://" server-name "/wiki/User:" author-name))
deposits (map (fn [event]
{:uuid (:event-id event)
:source_token source-token
:subj_id canonical-url
:obj_id (cr-doi/normalise-doi (:doi event))
:relation_type_id "references"
:source_id "wikipedia"
:action (:action event)
:occurred_at (str timestamp)
:subj (merge
{:title title
:issued (str timestamp)
:pid canonical-url
:URL canonical-url
:type "entry-encyclopedia"}
(when author-url {:author {:literal author-url}}))}) all-events)]
(swap! heartbeat-restbase-ok (partial + 2))
(if (= 200 old-status)
(swap! heartbeat-restbase-ok inc)
(do
(swap! heartbeat-restbase-error inc)
(l/error "Failed to fetch" old-restbase-url)))
(if (= 200 new-status)
(swap! heartbeat-restbase-ok inc)
(do
(swap! heartbeat-restbase-error inc)
(l/error "Failed to fetch" new-restbase-url)))
(when (> (count added-events) 0)
(c/send-heartbeat "wikipedia-agent/input/found-doi-added" (count added-events)))
(when (> (count removed-events) 0)
(c/send-heartbeat "wikipedia-agent/input/found-doi-removed" (count removed-events)))
{:artifacts []
:agent {:name "wikipedia" :version version}
:input {:stream-input data
:old-revision-id old-revision
:new-revision-id new-revision
:old-body old-body
:new-body new-body}
:processing {:canonical canonical-url
:dois-added added-events
:dois-removed removed-events}
:deposits deposits}))
(defn process-change-event
"Return Evidence Records from the Event, but only if there are Events in it."
[change-event]
; Only interested in 'edit' type events (not 'comment', 'categorize' etc).
(when (= (get change-event "type") "edit")
(let [result (process change-event)]
(when (not-empty (:deposits result))
result))))
|
16685
|
(ns event-data-wikipedia-agent.process
"Process edit events in Wikipedia."
(:require [org.crossref.event-data-agent-framework.web :as framework-web]
[org.crossref.event-data-agent-framework.core :as c]
[crossref.util.doi :as cr-doi])
(:require [clojure.data.json :as json]
[clojure.tools.logging :as l]
[clojure.set :refer [difference]])
(:require [org.httpkit.client :as http]
[clj-time.coerce :as clj-time-coerce])
(:import [java.net URLEncoder]
[java.util UUID])
(:require [robert.bruce :refer [try-try-again]]))
(def source-token "<KEY> <PASSWORD>")
(def version "0.1.6")
; Counters.
(def heartbeat-restbase (atom 0))
(def heartbeat-restbase-ok (atom 0))
(def heartbeat-restbase-error (atom 0))
(defn build-restbase-url
"Build a URL that can be retrieved from RESTBase"
[server-name title revision]
(let [encoded-title (URLEncoder/encode (.replaceAll title " " "_"))]
(str "https://" server-name "/api/rest_v1/page/html/" encoded-title "/" revision)))
(defn build-wikipedia-url
"Build a URL that can be used to fetch the page via the normal HTML website."
[server-name title]
(str "https://" server-name "/w/index.php?" (#'http/query-string {:title title})))
(defn process-bodies
"Process a diff between two HTML documents.
Return [added-dois removed-dois]."
[{old-revision :old-revision old-body :old-body
new-revision :new-revision new-body :new-body
title :title
server-name :server-name
input-event-id :input-event-id}]
(let [old-dois (framework-web/extract-dois-from-body old-body)
new-dois (framework-web/extract-dois-from-body new-body)
added-dois (difference new-dois old-dois)
removed-dois (difference old-dois new-dois)]
[added-dois removed-dois]))
(defn process
"Process a new input event by looking up old and new revisions.
Return an Evidence Record (which may or may not be empty of events)."
[data]
(let [server-name (get data "server_name")
server-url (get data "server_url")
title (get data "title")
old-revision (get-in data ["revision" "old"])
new-revision (get-in data ["revision" "new"])
old-restbase-url (build-restbase-url server-name title old-revision)
new-restbase-url (build-restbase-url server-name title new-revision)
{old-status :status old-body :body} (try-try-again {:tries 10 :delay 1000 :return? #(= 200 (:status %))} (fn [] @(http/get old-restbase-url {:timeout 10000})))
{new-status :status new-body :body} (try-try-again {:tries 10 :delay 1000 :return? #(= 200 (:status %))} (fn [] @(http/get new-restbase-url {:timeout 10000})))
timestamp (clj-time-coerce/from-long (* 1000 (get data "timestamp")))
[added-dois removed-dois] (when (and (= 200 old-status) (= 200 new-status))
(process-bodies {:old-revision old-revision :old-body old-body
:new-revision new-revision :new-body new-body
:title title
:server-name server-name
:timestamp timestamp}))
canonical-url (framework-web/fetch-canonical-url (build-wikipedia-url server-name title))
added-events (map (fn [doi] {:action "add" :doi doi :event-id (str (UUID/randomUUID))}) added-dois)
removed-events (map (fn [doi] {:action "delete" :doi doi :event-id (str (UUID/randomUUID))}) removed-dois)
all-events (concat added-events removed-events)
author-url (when-let [author-name (get-in data ["input" "user"])]
(str "https://" server-name "/wiki/User:" author-name))
deposits (map (fn [event]
{:uuid (:event-id event)
:source_token source-token
:subj_id canonical-url
:obj_id (cr-doi/normalise-doi (:doi event))
:relation_type_id "references"
:source_id "wikipedia"
:action (:action event)
:occurred_at (str timestamp)
:subj (merge
{:title title
:issued (str timestamp)
:pid canonical-url
:URL canonical-url
:type "entry-encyclopedia"}
(when author-url {:author {:literal author-url}}))}) all-events)]
(swap! heartbeat-restbase-ok (partial + 2))
(if (= 200 old-status)
(swap! heartbeat-restbase-ok inc)
(do
(swap! heartbeat-restbase-error inc)
(l/error "Failed to fetch" old-restbase-url)))
(if (= 200 new-status)
(swap! heartbeat-restbase-ok inc)
(do
(swap! heartbeat-restbase-error inc)
(l/error "Failed to fetch" new-restbase-url)))
(when (> (count added-events) 0)
(c/send-heartbeat "wikipedia-agent/input/found-doi-added" (count added-events)))
(when (> (count removed-events) 0)
(c/send-heartbeat "wikipedia-agent/input/found-doi-removed" (count removed-events)))
{:artifacts []
:agent {:name "wikipedia" :version version}
:input {:stream-input data
:old-revision-id old-revision
:new-revision-id new-revision
:old-body old-body
:new-body new-body}
:processing {:canonical canonical-url
:dois-added added-events
:dois-removed removed-events}
:deposits deposits}))
(defn process-change-event
"Return Evidence Records from the Event, but only if there are Events in it."
[change-event]
; Only interested in 'edit' type events (not 'comment', 'categorize' etc).
(when (= (get change-event "type") "edit")
(let [result (process change-event)]
(when (not-empty (:deposits result))
result))))
| true |
(ns event-data-wikipedia-agent.process
"Process edit events in Wikipedia."
(:require [org.crossref.event-data-agent-framework.web :as framework-web]
[org.crossref.event-data-agent-framework.core :as c]
[crossref.util.doi :as cr-doi])
(:require [clojure.data.json :as json]
[clojure.tools.logging :as l]
[clojure.set :refer [difference]])
(:require [org.httpkit.client :as http]
[clj-time.coerce :as clj-time-coerce])
(:import [java.net URLEncoder]
[java.util UUID])
(:require [robert.bruce :refer [try-try-again]]))
(def source-token "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI")
(def version "0.1.6")
; Counters.
(def heartbeat-restbase (atom 0))
(def heartbeat-restbase-ok (atom 0))
(def heartbeat-restbase-error (atom 0))
(defn build-restbase-url
"Build a URL that can be retrieved from RESTBase"
[server-name title revision]
(let [encoded-title (URLEncoder/encode (.replaceAll title " " "_"))]
(str "https://" server-name "/api/rest_v1/page/html/" encoded-title "/" revision)))
(defn build-wikipedia-url
"Build a URL that can be used to fetch the page via the normal HTML website."
[server-name title]
(str "https://" server-name "/w/index.php?" (#'http/query-string {:title title})))
(defn process-bodies
"Process a diff between two HTML documents.
Return [added-dois removed-dois]."
[{old-revision :old-revision old-body :old-body
new-revision :new-revision new-body :new-body
title :title
server-name :server-name
input-event-id :input-event-id}]
(let [old-dois (framework-web/extract-dois-from-body old-body)
new-dois (framework-web/extract-dois-from-body new-body)
added-dois (difference new-dois old-dois)
removed-dois (difference old-dois new-dois)]
[added-dois removed-dois]))
(defn process
"Process a new input event by looking up old and new revisions.
Return an Evidence Record (which may or may not be empty of events)."
[data]
(let [server-name (get data "server_name")
server-url (get data "server_url")
title (get data "title")
old-revision (get-in data ["revision" "old"])
new-revision (get-in data ["revision" "new"])
old-restbase-url (build-restbase-url server-name title old-revision)
new-restbase-url (build-restbase-url server-name title new-revision)
{old-status :status old-body :body} (try-try-again {:tries 10 :delay 1000 :return? #(= 200 (:status %))} (fn [] @(http/get old-restbase-url {:timeout 10000})))
{new-status :status new-body :body} (try-try-again {:tries 10 :delay 1000 :return? #(= 200 (:status %))} (fn [] @(http/get new-restbase-url {:timeout 10000})))
timestamp (clj-time-coerce/from-long (* 1000 (get data "timestamp")))
[added-dois removed-dois] (when (and (= 200 old-status) (= 200 new-status))
(process-bodies {:old-revision old-revision :old-body old-body
:new-revision new-revision :new-body new-body
:title title
:server-name server-name
:timestamp timestamp}))
canonical-url (framework-web/fetch-canonical-url (build-wikipedia-url server-name title))
added-events (map (fn [doi] {:action "add" :doi doi :event-id (str (UUID/randomUUID))}) added-dois)
removed-events (map (fn [doi] {:action "delete" :doi doi :event-id (str (UUID/randomUUID))}) removed-dois)
all-events (concat added-events removed-events)
author-url (when-let [author-name (get-in data ["input" "user"])]
(str "https://" server-name "/wiki/User:" author-name))
deposits (map (fn [event]
{:uuid (:event-id event)
:source_token source-token
:subj_id canonical-url
:obj_id (cr-doi/normalise-doi (:doi event))
:relation_type_id "references"
:source_id "wikipedia"
:action (:action event)
:occurred_at (str timestamp)
:subj (merge
{:title title
:issued (str timestamp)
:pid canonical-url
:URL canonical-url
:type "entry-encyclopedia"}
(when author-url {:author {:literal author-url}}))}) all-events)]
(swap! heartbeat-restbase-ok (partial + 2))
(if (= 200 old-status)
(swap! heartbeat-restbase-ok inc)
(do
(swap! heartbeat-restbase-error inc)
(l/error "Failed to fetch" old-restbase-url)))
(if (= 200 new-status)
(swap! heartbeat-restbase-ok inc)
(do
(swap! heartbeat-restbase-error inc)
(l/error "Failed to fetch" new-restbase-url)))
(when (> (count added-events) 0)
(c/send-heartbeat "wikipedia-agent/input/found-doi-added" (count added-events)))
(when (> (count removed-events) 0)
(c/send-heartbeat "wikipedia-agent/input/found-doi-removed" (count removed-events)))
{:artifacts []
:agent {:name "wikipedia" :version version}
:input {:stream-input data
:old-revision-id old-revision
:new-revision-id new-revision
:old-body old-body
:new-body new-body}
:processing {:canonical canonical-url
:dois-added added-events
:dois-removed removed-events}
:deposits deposits}))
(defn process-change-event
"Return Evidence Records from the Event, but only if there are Events in it."
[change-event]
; Only interested in 'edit' type events (not 'comment', 'categorize' etc).
(when (= (get change-event "type") "edit")
(let [result (process change-event)]
(when (not-empty (:deposits result))
result))))
|
[
{
"context": " ^{:doc \"com.sb.auditor :: iam\"\n :author \"Istvan Szukacs\"}\nauditor.iam\n (:require\n [auditor.auth :as a",
"end": 672,
"score": 0.9998904466629028,
"start": 658,
"tag": "NAME",
"value": "Istvan Szukacs"
}
] |
src/auditor/iam.clj
|
StreamBright/auditor
| 1 |
;; Copyright 2016 StreamBright LLC and 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 ^{:doc "com.sb.auditor :: iam"
:author "Istvan Szukacs"}
auditor.iam
(:require
[auditor.auth :as auth]
[clojure.tools.logging :as log]
[clojure.walk :as walk])
(:import
[com.amazonaws.auth
BasicAWSCredentials]
[com.amazonaws.internal
SdkInternalList]
[com.amazonaws.services.identitymanagement
AmazonIdentityManagementAsyncClient]
[com.amazonaws.services.identitymanagement.model
User
Group
AttachedPolicy
ListUsersRequest ListUsersResult
ListGroupsRequest ListGroupsResult
ListUserPoliciesRequest ListUserPoliciesResult
ListAttachedUserPoliciesRequest ListAttachedUserPoliciesResult
ListGroupPoliciesRequest ListGroupPoliciesResult
ListAttachedGroupPoliciesRequest ListAttachedGroupPoliciesResult
]
)
(:gen-class))
; http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/identitymanagement/AmazonIdentityManagementClient.html
;AmazonIdentityManagement
;;AbstractAmazonIdentityManagement, AbstractAmazonIdentityManagementAsync,
;;AmazonIdentityManagementAsyncClient, AmazonIdentityManagementClient
(defn create-iam-async-client
^AmazonIdentityManagementAsyncClient [^BasicAWSCredentials creds]
(AmazonIdentityManagementAsyncClient. creds))
(defn get-account-summary
[^AmazonIdentityManagementAsyncClient iam-client]
(walk/keywordize-keys
(into {} (.getSummaryMap @(.getAccountSummaryAsync iam-client)))))
(defn get-user-details
[^User user]
{:arn (.getArn user)
:user-id (.getUserId user)
:user-name (.getUserName user)
:path (.getPath user)
:create-date (.getCreateDate user)
:password-last-updated (.getPasswordLastUsed user)})
(defn get-group-details
[^Group group]
{:arn (.getArn group)
:group-id (.getGroupId group)
:group-name (.getGroupName group)
:path (.getPath group)
:create-date (.getCreateDate group)})
(defn get-managed-policy-details
[^AttachedPolicy policy]
{:arn (.getPolicyArn policy)
:policy-name (.getPolicyName policy)})
;; List entities
;;
;; first try to page through requests
;;
(defn list-users
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client]
(let [^ListUsersResult result @(.listUsersAsync iam-client)]
(if-not (.isTruncated result)
;return
(.getUsers result)
;call the other signature
(list-users iam-client (.getUsers result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client acc marker]
(let [ ^ListUsersRequest request (doto (ListUsersRequest.) (.setMarker marker))
^ListUsersResult result @(.listUsersAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getUsers result))
;recur
(recur iam-client (.addAll acc (.getUsers result)) (.getMarker result))))))
(defn list-groups
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client]
(let [^ListGroupsResult result @(.listGroupsAsync iam-client) ]
(if-not (.isTruncated result)
;return
(.getGroups result)
;call the other signature
(list-groups iam-client (.getGroups result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client acc marker]
(let [ ^ListGroupsRequest request (.setMarker (ListGroupsRequest.) marker)
^ListGroupsResult result @(.listGroupsAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getGroups result))
;recur
(recur iam-client (.addAll acc (.getGroups result)) (.getMarker result))))))
(defn list-user-inline-policies
"Lists the names of the inline policies embedded in the specified user."
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name]
(let [ ^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.) (.setUserName user-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getPolicyNames result)
;call the other signature
(list-user-inline-policies iam-client user-name (.getPolicyNames result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name acc marker]
(let [ ^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.)
(.setMarker marker)
(.setUserName user-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getPolicyNames result))
;recur
(recur iam-client user-name (.addAll acc (.getPolicyNames result)) (.getMarker result))))))
(defn list-user-managed-policies
"Lists the names of the inline policies embedded in the specified user."
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name]
(let [ ^ListAttachedUserPoliciesRequest request (doto (ListAttachedUserPoliciesRequest.) (.setUserName user-name))
^ListAttachedUserPoliciesResult result @(.listAttachedUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getAttachedPolicies result)
;call the other signature
(list-user-managed-policies iam-client user-name (.getAttachedPolicies result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name acc marker]
(let [ ^ListAttachedUserPoliciesRequest request (doto (ListAttachedUserPoliciesRequest.)
(.setMarker marker)
(.setUserName user-name))
^ListAttachedUserPoliciesResult result @(.listAttachedUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getAttachedPolicies result))
;recur
(recur iam-client user-name (.addAll acc (.getAttachedPolicies result)) (.getMarker result))))))
(defn list-group-inline-policies
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name]
(let [^ListGroupPoliciesRequest request (ListGroupPoliciesRequest.)
_ (.setGroupName request group-name)
^ListGroupPoliciesResult result @(.listGroupPoliciesAsync iam-client request)]
(if-not (.isTruncated result)
;return
(.getPolicyNames result)
;call the other signature
(list-group-inline-policies iam-client group-name (.getPolicyNames result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name acc marker]
(let [^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.)
(.setMarker marker)
(.setUserName group-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getPolicyNames result))
;recur
(recur iam-client group-name (.addAll acc (.getPolicyNames result)) (.getMarker result))))))
(defn list-group-managed-policies
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name]
(let [^ListAttachedGroupPoliciesRequest request (doto (ListAttachedGroupPoliciesRequest.)
(.setGroupName group-name))
^ListAttachedGroupPoliciesResult result @(.listAttachedGroupPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getAttachedPolicies result)
;call the other signature
(list-group-managed-policies iam-client group-name (.getAttachedPolicies result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name acc marker]
(let [^ListAttachedGroupPoliciesRequest request (doto (ListAttachedGroupPoliciesRequest.)
(.setMarker marker)
(.setGroupName group-name))
^ListAttachedGroupPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getAttachedPolicies result))
;recur
(recur iam-client group-name (.addAll acc (.getAttachedPolicies result)) (.getMarker result))))))
;; Java -> Clojure
(defn users->clj
[^SdkInternalList users]
(vec (map get-user-details users)))
(defn groups->clj
[^SdkInternalList groups]
(vec (map get-group-details groups)))
(defn user-policies->clj
[^ListUserPoliciesResult policies]
(vec policies))
(defn group-managed-policies->clj
[^ListAttachedGroupPoliciesResult policies]
(vec (map get-managed-policy-details policies)))
;; Synthetic niceties
(defn get-user-managed-policies
[iam-client users]
(into {} (map #(hash-map
(keyword %)
(user-policies->clj (list-user-managed-policies iam-client %)))
(map :user-name users))))
(defn get-group-managed-policies
[iam-client groups]
(into {} (map #(hash-map
(keyword %)
(group-managed-policies->clj (list-group-managed-policies iam-client %)))
(map :group-name groups))))
|
58493
|
;; Copyright 2016 StreamBright LLC and 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 ^{:doc "com.sb.auditor :: iam"
:author "<NAME>"}
auditor.iam
(:require
[auditor.auth :as auth]
[clojure.tools.logging :as log]
[clojure.walk :as walk])
(:import
[com.amazonaws.auth
BasicAWSCredentials]
[com.amazonaws.internal
SdkInternalList]
[com.amazonaws.services.identitymanagement
AmazonIdentityManagementAsyncClient]
[com.amazonaws.services.identitymanagement.model
User
Group
AttachedPolicy
ListUsersRequest ListUsersResult
ListGroupsRequest ListGroupsResult
ListUserPoliciesRequest ListUserPoliciesResult
ListAttachedUserPoliciesRequest ListAttachedUserPoliciesResult
ListGroupPoliciesRequest ListGroupPoliciesResult
ListAttachedGroupPoliciesRequest ListAttachedGroupPoliciesResult
]
)
(:gen-class))
; http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/identitymanagement/AmazonIdentityManagementClient.html
;AmazonIdentityManagement
;;AbstractAmazonIdentityManagement, AbstractAmazonIdentityManagementAsync,
;;AmazonIdentityManagementAsyncClient, AmazonIdentityManagementClient
(defn create-iam-async-client
^AmazonIdentityManagementAsyncClient [^BasicAWSCredentials creds]
(AmazonIdentityManagementAsyncClient. creds))
(defn get-account-summary
[^AmazonIdentityManagementAsyncClient iam-client]
(walk/keywordize-keys
(into {} (.getSummaryMap @(.getAccountSummaryAsync iam-client)))))
(defn get-user-details
[^User user]
{:arn (.getArn user)
:user-id (.getUserId user)
:user-name (.getUserName user)
:path (.getPath user)
:create-date (.getCreateDate user)
:password-last-updated (.getPasswordLastUsed user)})
(defn get-group-details
[^Group group]
{:arn (.getArn group)
:group-id (.getGroupId group)
:group-name (.getGroupName group)
:path (.getPath group)
:create-date (.getCreateDate group)})
(defn get-managed-policy-details
[^AttachedPolicy policy]
{:arn (.getPolicyArn policy)
:policy-name (.getPolicyName policy)})
;; List entities
;;
;; first try to page through requests
;;
(defn list-users
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client]
(let [^ListUsersResult result @(.listUsersAsync iam-client)]
(if-not (.isTruncated result)
;return
(.getUsers result)
;call the other signature
(list-users iam-client (.getUsers result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client acc marker]
(let [ ^ListUsersRequest request (doto (ListUsersRequest.) (.setMarker marker))
^ListUsersResult result @(.listUsersAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getUsers result))
;recur
(recur iam-client (.addAll acc (.getUsers result)) (.getMarker result))))))
(defn list-groups
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client]
(let [^ListGroupsResult result @(.listGroupsAsync iam-client) ]
(if-not (.isTruncated result)
;return
(.getGroups result)
;call the other signature
(list-groups iam-client (.getGroups result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client acc marker]
(let [ ^ListGroupsRequest request (.setMarker (ListGroupsRequest.) marker)
^ListGroupsResult result @(.listGroupsAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getGroups result))
;recur
(recur iam-client (.addAll acc (.getGroups result)) (.getMarker result))))))
(defn list-user-inline-policies
"Lists the names of the inline policies embedded in the specified user."
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name]
(let [ ^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.) (.setUserName user-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getPolicyNames result)
;call the other signature
(list-user-inline-policies iam-client user-name (.getPolicyNames result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name acc marker]
(let [ ^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.)
(.setMarker marker)
(.setUserName user-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getPolicyNames result))
;recur
(recur iam-client user-name (.addAll acc (.getPolicyNames result)) (.getMarker result))))))
(defn list-user-managed-policies
"Lists the names of the inline policies embedded in the specified user."
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name]
(let [ ^ListAttachedUserPoliciesRequest request (doto (ListAttachedUserPoliciesRequest.) (.setUserName user-name))
^ListAttachedUserPoliciesResult result @(.listAttachedUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getAttachedPolicies result)
;call the other signature
(list-user-managed-policies iam-client user-name (.getAttachedPolicies result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name acc marker]
(let [ ^ListAttachedUserPoliciesRequest request (doto (ListAttachedUserPoliciesRequest.)
(.setMarker marker)
(.setUserName user-name))
^ListAttachedUserPoliciesResult result @(.listAttachedUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getAttachedPolicies result))
;recur
(recur iam-client user-name (.addAll acc (.getAttachedPolicies result)) (.getMarker result))))))
(defn list-group-inline-policies
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name]
(let [^ListGroupPoliciesRequest request (ListGroupPoliciesRequest.)
_ (.setGroupName request group-name)
^ListGroupPoliciesResult result @(.listGroupPoliciesAsync iam-client request)]
(if-not (.isTruncated result)
;return
(.getPolicyNames result)
;call the other signature
(list-group-inline-policies iam-client group-name (.getPolicyNames result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name acc marker]
(let [^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.)
(.setMarker marker)
(.setUserName group-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getPolicyNames result))
;recur
(recur iam-client group-name (.addAll acc (.getPolicyNames result)) (.getMarker result))))))
(defn list-group-managed-policies
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name]
(let [^ListAttachedGroupPoliciesRequest request (doto (ListAttachedGroupPoliciesRequest.)
(.setGroupName group-name))
^ListAttachedGroupPoliciesResult result @(.listAttachedGroupPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getAttachedPolicies result)
;call the other signature
(list-group-managed-policies iam-client group-name (.getAttachedPolicies result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name acc marker]
(let [^ListAttachedGroupPoliciesRequest request (doto (ListAttachedGroupPoliciesRequest.)
(.setMarker marker)
(.setGroupName group-name))
^ListAttachedGroupPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getAttachedPolicies result))
;recur
(recur iam-client group-name (.addAll acc (.getAttachedPolicies result)) (.getMarker result))))))
;; Java -> Clojure
(defn users->clj
[^SdkInternalList users]
(vec (map get-user-details users)))
(defn groups->clj
[^SdkInternalList groups]
(vec (map get-group-details groups)))
(defn user-policies->clj
[^ListUserPoliciesResult policies]
(vec policies))
(defn group-managed-policies->clj
[^ListAttachedGroupPoliciesResult policies]
(vec (map get-managed-policy-details policies)))
;; Synthetic niceties
(defn get-user-managed-policies
[iam-client users]
(into {} (map #(hash-map
(keyword %)
(user-policies->clj (list-user-managed-policies iam-client %)))
(map :user-name users))))
(defn get-group-managed-policies
[iam-client groups]
(into {} (map #(hash-map
(keyword %)
(group-managed-policies->clj (list-group-managed-policies iam-client %)))
(map :group-name groups))))
| true |
;; Copyright 2016 StreamBright LLC and 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 ^{:doc "com.sb.auditor :: iam"
:author "PI:NAME:<NAME>END_PI"}
auditor.iam
(:require
[auditor.auth :as auth]
[clojure.tools.logging :as log]
[clojure.walk :as walk])
(:import
[com.amazonaws.auth
BasicAWSCredentials]
[com.amazonaws.internal
SdkInternalList]
[com.amazonaws.services.identitymanagement
AmazonIdentityManagementAsyncClient]
[com.amazonaws.services.identitymanagement.model
User
Group
AttachedPolicy
ListUsersRequest ListUsersResult
ListGroupsRequest ListGroupsResult
ListUserPoliciesRequest ListUserPoliciesResult
ListAttachedUserPoliciesRequest ListAttachedUserPoliciesResult
ListGroupPoliciesRequest ListGroupPoliciesResult
ListAttachedGroupPoliciesRequest ListAttachedGroupPoliciesResult
]
)
(:gen-class))
; http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/identitymanagement/AmazonIdentityManagementClient.html
;AmazonIdentityManagement
;;AbstractAmazonIdentityManagement, AbstractAmazonIdentityManagementAsync,
;;AmazonIdentityManagementAsyncClient, AmazonIdentityManagementClient
(defn create-iam-async-client
^AmazonIdentityManagementAsyncClient [^BasicAWSCredentials creds]
(AmazonIdentityManagementAsyncClient. creds))
(defn get-account-summary
[^AmazonIdentityManagementAsyncClient iam-client]
(walk/keywordize-keys
(into {} (.getSummaryMap @(.getAccountSummaryAsync iam-client)))))
(defn get-user-details
[^User user]
{:arn (.getArn user)
:user-id (.getUserId user)
:user-name (.getUserName user)
:path (.getPath user)
:create-date (.getCreateDate user)
:password-last-updated (.getPasswordLastUsed user)})
(defn get-group-details
[^Group group]
{:arn (.getArn group)
:group-id (.getGroupId group)
:group-name (.getGroupName group)
:path (.getPath group)
:create-date (.getCreateDate group)})
(defn get-managed-policy-details
[^AttachedPolicy policy]
{:arn (.getPolicyArn policy)
:policy-name (.getPolicyName policy)})
;; List entities
;;
;; first try to page through requests
;;
(defn list-users
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client]
(let [^ListUsersResult result @(.listUsersAsync iam-client)]
(if-not (.isTruncated result)
;return
(.getUsers result)
;call the other signature
(list-users iam-client (.getUsers result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client acc marker]
(let [ ^ListUsersRequest request (doto (ListUsersRequest.) (.setMarker marker))
^ListUsersResult result @(.listUsersAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getUsers result))
;recur
(recur iam-client (.addAll acc (.getUsers result)) (.getMarker result))))))
(defn list-groups
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client]
(let [^ListGroupsResult result @(.listGroupsAsync iam-client) ]
(if-not (.isTruncated result)
;return
(.getGroups result)
;call the other signature
(list-groups iam-client (.getGroups result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client acc marker]
(let [ ^ListGroupsRequest request (.setMarker (ListGroupsRequest.) marker)
^ListGroupsResult result @(.listGroupsAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getGroups result))
;recur
(recur iam-client (.addAll acc (.getGroups result)) (.getMarker result))))))
(defn list-user-inline-policies
"Lists the names of the inline policies embedded in the specified user."
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name]
(let [ ^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.) (.setUserName user-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getPolicyNames result)
;call the other signature
(list-user-inline-policies iam-client user-name (.getPolicyNames result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name acc marker]
(let [ ^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.)
(.setMarker marker)
(.setUserName user-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getPolicyNames result))
;recur
(recur iam-client user-name (.addAll acc (.getPolicyNames result)) (.getMarker result))))))
(defn list-user-managed-policies
"Lists the names of the inline policies embedded in the specified user."
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name]
(let [ ^ListAttachedUserPoliciesRequest request (doto (ListAttachedUserPoliciesRequest.) (.setUserName user-name))
^ListAttachedUserPoliciesResult result @(.listAttachedUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getAttachedPolicies result)
;call the other signature
(list-user-managed-policies iam-client user-name (.getAttachedPolicies result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String user-name acc marker]
(let [ ^ListAttachedUserPoliciesRequest request (doto (ListAttachedUserPoliciesRequest.)
(.setMarker marker)
(.setUserName user-name))
^ListAttachedUserPoliciesResult result @(.listAttachedUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getAttachedPolicies result))
;recur
(recur iam-client user-name (.addAll acc (.getAttachedPolicies result)) (.getMarker result))))))
(defn list-group-inline-policies
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name]
(let [^ListGroupPoliciesRequest request (ListGroupPoliciesRequest.)
_ (.setGroupName request group-name)
^ListGroupPoliciesResult result @(.listGroupPoliciesAsync iam-client request)]
(if-not (.isTruncated result)
;return
(.getPolicyNames result)
;call the other signature
(list-group-inline-policies iam-client group-name (.getPolicyNames result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name acc marker]
(let [^ListUserPoliciesRequest request (doto (ListUserPoliciesRequest.)
(.setMarker marker)
(.setUserName group-name))
^ListUserPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getPolicyNames result))
;recur
(recur iam-client group-name (.addAll acc (.getPolicyNames result)) (.getMarker result))))))
(defn list-group-managed-policies
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name]
(let [^ListAttachedGroupPoliciesRequest request (doto (ListAttachedGroupPoliciesRequest.)
(.setGroupName group-name))
^ListAttachedGroupPoliciesResult result @(.listAttachedGroupPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.getAttachedPolicies result)
;call the other signature
(list-group-managed-policies iam-client group-name (.getAttachedPolicies result) (.getMarker result)))))
; paging
(^SdkInternalList [^AmazonIdentityManagementAsyncClient iam-client ^String group-name acc marker]
(let [^ListAttachedGroupPoliciesRequest request (doto (ListAttachedGroupPoliciesRequest.)
(.setMarker marker)
(.setGroupName group-name))
^ListAttachedGroupPoliciesResult result @(.listUserPoliciesAsync iam-client request) ]
(if-not (.isTruncated result)
;return
(.addAll acc (.getAttachedPolicies result))
;recur
(recur iam-client group-name (.addAll acc (.getAttachedPolicies result)) (.getMarker result))))))
;; Java -> Clojure
(defn users->clj
[^SdkInternalList users]
(vec (map get-user-details users)))
(defn groups->clj
[^SdkInternalList groups]
(vec (map get-group-details groups)))
(defn user-policies->clj
[^ListUserPoliciesResult policies]
(vec policies))
(defn group-managed-policies->clj
[^ListAttachedGroupPoliciesResult policies]
(vec (map get-managed-policy-details policies)))
;; Synthetic niceties
(defn get-user-managed-policies
[iam-client users]
(into {} (map #(hash-map
(keyword %)
(user-policies->clj (list-user-managed-policies iam-client %)))
(map :user-name users))))
(defn get-group-managed-policies
[iam-client groups]
(into {} (map #(hash-map
(keyword %)
(group-managed-policies->clj (list-group-managed-policies iam-client %)))
(map :group-name groups))))
|
[
{
"context": " examples\n(def dracula {:title \"Dracula\" :author \"Stoker\" :price 1.99 :genre :horror})\n\n; The cheaper-than",
"end": 2517,
"score": 0.9997518658638,
"start": 2511,
"tag": "NAME",
"value": "Stoker"
},
{
"context": "rue)\n 0)\n\n(publish-book {:title \"bingo\" :author \"Maddy\"})\n\n\n\n",
"end": 5231,
"score": 0.9984807968139648,
"start": 5226,
"tag": "NAME",
"value": "Maddy"
}
] |
cljlrn/src/learn/functions.clj
|
lenkite/learn
| 0 |
(ns learn.functions
(:require [clojure.io :as io])
(:import (java io.File net.URL)))
; TODO: Multi-Methods
; *multi-method*
; to-url uses the built-in class function, which will return the underlying
; type of the value as its dispatch function.
(defmulti to-url class)
(defmethod to-url io.File [f] (.toURL (.toURI f))) (defmethod to-url net.URL [url] url)
(defmethod to-url java.lang.String [s] (to-url (io/file s)))
; *apply*
; apply basically unwraps a sequence and applies the function to them as
; individual arguments. You use apply to convert a function that works on
; several arguments to one that works on a single sequence of arguments. You
; can also insert arguments before the sequence
; The clojure doc for apply sadly never talks about this vital unwrapping
; apply can be visualized thinking about "unrolling" or "spreading" arguments from a list to call a function.
(str (reverse "derp"))
;; => "(\"p\" \"r\" \"e\" \"d\")"
(apply str (reverse "derp"))
;; => "pred"
; when you call reverse on a string it returns a sequence of character string in the reverse order.
; Str is interesting because it can be called on one thing or more things. If
; called on just one thing then it stringifies the thing and if passed many
; arguments it will stringify them and then concatenate them. So, this is why
; the first incorrect version returns what it does. It sees the list of
; character strings as one thing- a list, and it then nonchalantly returns the
; stringified version of the whole list. The second example, on the other hand,
; is saying take the str function and apply it to all the arguments.
; classic example to transpose a matrix from clojuredoc
; http://clojuredocs.org/clojure.core/apply#example-542692cdc026201cdc326d4d
(apply map vector [[:a :b] [:c :d]])
;;=> ([:a :c] [:b :d])
; The one inserted argument here is vector. So the apply expands to
(map vector [:a :b] [:c :d])
;;=> ([:a :c] [:c :d]))
; *partial*
; called partial since it partially fills in the arguments for an existing
; function producing a new function of fewer arguments in the process
; aka currying.
; we know + takes varargs
; currying can ofcourse be done manually. Ex:
(defn my-inc [n] (+ 1 n))
; howweer we can also use partial like the below:
(def my-inc (partial + 1))
; note that first formused defn becuase we had a param vector and body, while
; the second form used plain def since we simply bound a value to my-inc
; Further examples
(def dracula {:title "Dracula" :author "Stoker" :price 1.99 :genre :horror})
; The cheaper-than function below takes advantage of Clojure’s truthy logic and
; return nil when the book fails the test, and the book map itself—which is
; truthy—when it passes.
(defn cheaper-than [max-price book]
(when (<= (:price book) max-price) book))
; variants of cheaper-than using partial
(def cheap? (partial cheaper-than 9.99))
(def crazy-cheap? (partial cheaper-than 1.00))
(defn horror? [book] (when (= (:genre book) :horror) book))
; *complement*
; compoment wraps the function that you supply with a call to not producing a
; new function that is the complement of the original
; Ex
(defn adventure? [book]
(when (= (:genre book) :adventure) book))
(adventure? dracula); => nil
; can be done manually like:
(defn not-adventure? [book] (not (adventure? book)))
(not-adventure? dracula); => true
; but can be done easily like:
(def not-adventure? (complement adventure?))
(not-adventure? dracula); => true
; *every-pred*
; Higher order function that combines predicate functions into a single function that ands them together.
(def cheap-horror? (every-pred cheap? horror?))
(cheap-horror? dracula) ; => true
; TODO: *lambdas, functional literals*
; *loop and recur*
; loop works with recur. When it hits a recur inside the body of a loop, Clojure
; will reset the values bound to the symbols to values passed into recur and
; then recursively reevaluate the loop body.
(def books
[{:title "Jaws" :copies-sold 2000000}
{:title "Emma" :copies-sold 3000000}
{:title "2001" :copies-sold 4000000}])
(defn sum-copies [books]
(loop [books books total 0]
(if (empty? books)
total
(recur (rest books) (+ total (:copies-sold (first books)))))));
(sum-copies books)
(apply + (map :copies-sold books))
; TODO: map
; Pre and Post Conditions
; To set up a :pre condition just add a map after the parameter vector and
; before the body expression - aa map with a :pre key. The value should be a
; vector of expressions. You will get a runtime exception if any of the
; expressions turn out to be falsy when the function is called
(defn publish-book [book] {:pre [(:title book)]}
(print book)
;(ship-book book)
)
; The below ensures that books have both title and author
(defn publish-book [book]
{:pre [(:title book) (:author book)]}
;(print-book book)
;(ship-book book)
)
; You can also specify a :post condition which lets you check on the value
; returned by the function. Value is available as placeholder %
(defn publish-book [book]
{
:pre [(:title book) (:author book)]
:post [(boolean? %)]
}
;(print-book book)
;(ship-book book)
;true)
0)
(publish-book {:title "bingo" :author "Maddy"})
|
87820
|
(ns learn.functions
(:require [clojure.io :as io])
(:import (java io.File net.URL)))
; TODO: Multi-Methods
; *multi-method*
; to-url uses the built-in class function, which will return the underlying
; type of the value as its dispatch function.
(defmulti to-url class)
(defmethod to-url io.File [f] (.toURL (.toURI f))) (defmethod to-url net.URL [url] url)
(defmethod to-url java.lang.String [s] (to-url (io/file s)))
; *apply*
; apply basically unwraps a sequence and applies the function to them as
; individual arguments. You use apply to convert a function that works on
; several arguments to one that works on a single sequence of arguments. You
; can also insert arguments before the sequence
; The clojure doc for apply sadly never talks about this vital unwrapping
; apply can be visualized thinking about "unrolling" or "spreading" arguments from a list to call a function.
(str (reverse "derp"))
;; => "(\"p\" \"r\" \"e\" \"d\")"
(apply str (reverse "derp"))
;; => "pred"
; when you call reverse on a string it returns a sequence of character string in the reverse order.
; Str is interesting because it can be called on one thing or more things. If
; called on just one thing then it stringifies the thing and if passed many
; arguments it will stringify them and then concatenate them. So, this is why
; the first incorrect version returns what it does. It sees the list of
; character strings as one thing- a list, and it then nonchalantly returns the
; stringified version of the whole list. The second example, on the other hand,
; is saying take the str function and apply it to all the arguments.
; classic example to transpose a matrix from clojuredoc
; http://clojuredocs.org/clojure.core/apply#example-542692cdc026201cdc326d4d
(apply map vector [[:a :b] [:c :d]])
;;=> ([:a :c] [:b :d])
; The one inserted argument here is vector. So the apply expands to
(map vector [:a :b] [:c :d])
;;=> ([:a :c] [:c :d]))
; *partial*
; called partial since it partially fills in the arguments for an existing
; function producing a new function of fewer arguments in the process
; aka currying.
; we know + takes varargs
; currying can ofcourse be done manually. Ex:
(defn my-inc [n] (+ 1 n))
; howweer we can also use partial like the below:
(def my-inc (partial + 1))
; note that first formused defn becuase we had a param vector and body, while
; the second form used plain def since we simply bound a value to my-inc
; Further examples
(def dracula {:title "Dracula" :author "<NAME>" :price 1.99 :genre :horror})
; The cheaper-than function below takes advantage of Clojure’s truthy logic and
; return nil when the book fails the test, and the book map itself—which is
; truthy—when it passes.
(defn cheaper-than [max-price book]
(when (<= (:price book) max-price) book))
; variants of cheaper-than using partial
(def cheap? (partial cheaper-than 9.99))
(def crazy-cheap? (partial cheaper-than 1.00))
(defn horror? [book] (when (= (:genre book) :horror) book))
; *complement*
; compoment wraps the function that you supply with a call to not producing a
; new function that is the complement of the original
; Ex
(defn adventure? [book]
(when (= (:genre book) :adventure) book))
(adventure? dracula); => nil
; can be done manually like:
(defn not-adventure? [book] (not (adventure? book)))
(not-adventure? dracula); => true
; but can be done easily like:
(def not-adventure? (complement adventure?))
(not-adventure? dracula); => true
; *every-pred*
; Higher order function that combines predicate functions into a single function that ands them together.
(def cheap-horror? (every-pred cheap? horror?))
(cheap-horror? dracula) ; => true
; TODO: *lambdas, functional literals*
; *loop and recur*
; loop works with recur. When it hits a recur inside the body of a loop, Clojure
; will reset the values bound to the symbols to values passed into recur and
; then recursively reevaluate the loop body.
(def books
[{:title "Jaws" :copies-sold 2000000}
{:title "Emma" :copies-sold 3000000}
{:title "2001" :copies-sold 4000000}])
(defn sum-copies [books]
(loop [books books total 0]
(if (empty? books)
total
(recur (rest books) (+ total (:copies-sold (first books)))))));
(sum-copies books)
(apply + (map :copies-sold books))
; TODO: map
; Pre and Post Conditions
; To set up a :pre condition just add a map after the parameter vector and
; before the body expression - aa map with a :pre key. The value should be a
; vector of expressions. You will get a runtime exception if any of the
; expressions turn out to be falsy when the function is called
(defn publish-book [book] {:pre [(:title book)]}
(print book)
;(ship-book book)
)
; The below ensures that books have both title and author
(defn publish-book [book]
{:pre [(:title book) (:author book)]}
;(print-book book)
;(ship-book book)
)
; You can also specify a :post condition which lets you check on the value
; returned by the function. Value is available as placeholder %
(defn publish-book [book]
{
:pre [(:title book) (:author book)]
:post [(boolean? %)]
}
;(print-book book)
;(ship-book book)
;true)
0)
(publish-book {:title "bingo" :author "<NAME>"})
| true |
(ns learn.functions
(:require [clojure.io :as io])
(:import (java io.File net.URL)))
; TODO: Multi-Methods
; *multi-method*
; to-url uses the built-in class function, which will return the underlying
; type of the value as its dispatch function.
(defmulti to-url class)
(defmethod to-url io.File [f] (.toURL (.toURI f))) (defmethod to-url net.URL [url] url)
(defmethod to-url java.lang.String [s] (to-url (io/file s)))
; *apply*
; apply basically unwraps a sequence and applies the function to them as
; individual arguments. You use apply to convert a function that works on
; several arguments to one that works on a single sequence of arguments. You
; can also insert arguments before the sequence
; The clojure doc for apply sadly never talks about this vital unwrapping
; apply can be visualized thinking about "unrolling" or "spreading" arguments from a list to call a function.
(str (reverse "derp"))
;; => "(\"p\" \"r\" \"e\" \"d\")"
(apply str (reverse "derp"))
;; => "pred"
; when you call reverse on a string it returns a sequence of character string in the reverse order.
; Str is interesting because it can be called on one thing or more things. If
; called on just one thing then it stringifies the thing and if passed many
; arguments it will stringify them and then concatenate them. So, this is why
; the first incorrect version returns what it does. It sees the list of
; character strings as one thing- a list, and it then nonchalantly returns the
; stringified version of the whole list. The second example, on the other hand,
; is saying take the str function and apply it to all the arguments.
; classic example to transpose a matrix from clojuredoc
; http://clojuredocs.org/clojure.core/apply#example-542692cdc026201cdc326d4d
(apply map vector [[:a :b] [:c :d]])
;;=> ([:a :c] [:b :d])
; The one inserted argument here is vector. So the apply expands to
(map vector [:a :b] [:c :d])
;;=> ([:a :c] [:c :d]))
; *partial*
; called partial since it partially fills in the arguments for an existing
; function producing a new function of fewer arguments in the process
; aka currying.
; we know + takes varargs
; currying can ofcourse be done manually. Ex:
(defn my-inc [n] (+ 1 n))
; howweer we can also use partial like the below:
(def my-inc (partial + 1))
; note that first formused defn becuase we had a param vector and body, while
; the second form used plain def since we simply bound a value to my-inc
; Further examples
(def dracula {:title "Dracula" :author "PI:NAME:<NAME>END_PI" :price 1.99 :genre :horror})
; The cheaper-than function below takes advantage of Clojure’s truthy logic and
; return nil when the book fails the test, and the book map itself—which is
; truthy—when it passes.
(defn cheaper-than [max-price book]
(when (<= (:price book) max-price) book))
; variants of cheaper-than using partial
(def cheap? (partial cheaper-than 9.99))
(def crazy-cheap? (partial cheaper-than 1.00))
(defn horror? [book] (when (= (:genre book) :horror) book))
; *complement*
; compoment wraps the function that you supply with a call to not producing a
; new function that is the complement of the original
; Ex
(defn adventure? [book]
(when (= (:genre book) :adventure) book))
(adventure? dracula); => nil
; can be done manually like:
(defn not-adventure? [book] (not (adventure? book)))
(not-adventure? dracula); => true
; but can be done easily like:
(def not-adventure? (complement adventure?))
(not-adventure? dracula); => true
; *every-pred*
; Higher order function that combines predicate functions into a single function that ands them together.
(def cheap-horror? (every-pred cheap? horror?))
(cheap-horror? dracula) ; => true
; TODO: *lambdas, functional literals*
; *loop and recur*
; loop works with recur. When it hits a recur inside the body of a loop, Clojure
; will reset the values bound to the symbols to values passed into recur and
; then recursively reevaluate the loop body.
(def books
[{:title "Jaws" :copies-sold 2000000}
{:title "Emma" :copies-sold 3000000}
{:title "2001" :copies-sold 4000000}])
(defn sum-copies [books]
(loop [books books total 0]
(if (empty? books)
total
(recur (rest books) (+ total (:copies-sold (first books)))))));
(sum-copies books)
(apply + (map :copies-sold books))
; TODO: map
; Pre and Post Conditions
; To set up a :pre condition just add a map after the parameter vector and
; before the body expression - aa map with a :pre key. The value should be a
; vector of expressions. You will get a runtime exception if any of the
; expressions turn out to be falsy when the function is called
(defn publish-book [book] {:pre [(:title book)]}
(print book)
;(ship-book book)
)
; The below ensures that books have both title and author
(defn publish-book [book]
{:pre [(:title book) (:author book)]}
;(print-book book)
;(ship-book book)
)
; You can also specify a :post condition which lets you check on the value
; returned by the function. Value is available as placeholder %
(defn publish-book [book]
{
:pre [(:title book) (:author book)]
:post [(boolean? %)]
}
;(print-book book)
;(ship-book book)
;true)
0)
(publish-book {:title "bingo" :author "PI:NAME:<NAME>END_PI"})
|
[
{
"context": ";; Copyright 2014 (c) Diego Souza <[email protected]>\n;;\n;; Licensed under the Apache",
"end": 33,
"score": 0.9998694658279419,
"start": 22,
"tag": "NAME",
"value": "Diego Souza"
},
{
"context": ";; Copyright 2014 (c) Diego Souza <[email protected]>\n;;\n;; Licensed under the Apache License, Version",
"end": 50,
"score": 0.9998936653137207,
"start": 35,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/blackbox/src/leela/blackbox/network/zmqserver.clj
|
locaweb/leela
| 22 |
;; Copyright 2014 (c) Diego Souza <[email protected]>
;;
;; 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 leela.blackbox.network.zmqserver
(:use [clojure.tools.logging :only [trace debug info error]])
(:require [msgpack.core :as msgp]
[leela.blackbox.f :as f]
[leela.blackbox.czmq.router :as router]
[leela.blackbox.storage.cassandra :as storage]
[leela.blackbox.storage.s3 :as s3]))
(defmacro third [list]
`(nth ~list 2))
(defmacro parse-opts [opts]
`(into {} (for [[k# v#] ~opts] [(keyword k#) v#])))
(def msg-pack-magic "000")
(defn msg-fail [status]
["fail" status])
(defn msg-done []
["done" nil])
(defn msg-name [u t k n g]
(if-not g
(msg-fail 404)
["name" [u t k n (str g)]]))
(defn msg-link [links]
["link" (map str links)])
(defn msg-label [labels]
["label" labels])
(defn msg-nattr [attrs]
["n-attr" attrs])
(defn msg-tattr [data]
["t-attr" data])
(defn msg-kattr [data]
(if-not data
(msg-fail 404)
["k-attr" data]))
(defn exec-getname [cluster [g]]
(let [g (f/bytes-to-uuid g)]
(storage/with-consistency :one
(storage/with-limit 1
(if-let [[u t k n] (storage/getname cluster g)]
(msg-name u t k n g)
(msg-fail 404))))))
(defn exec-getguid [cluster [u t k n]]
(let [u (f/bytes-to-str u)
t (f/bytes-to-str t)
k (f/bytes-to-str k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/with-limit 1
(msg-name u t k n (storage/getguid cluster u t k n))))))
(defn exec-putname [cluster [u t k n]]
(storage/with-consistency :quorum
(let [u (f/bytes-to-str u)
t (f/bytes-to-str t)
k (f/bytes-to-str k)
n (f/bytes-to-str n)
g (storage/putguid cluster u t k n)]
(msg-name u t k n g))))
(defn exec-getlink [cluster [a l page] limit]
(let [a (f/bytes-to-uuid a)
l (f/bytes-to-str l)
page (if (empty? page) f/uuid-zero (f/bytes-to-uuid page))]
(storage/with-consistency :one
(storage/with-limit limit
(msg-link (storage/getlink cluster a l page))))))
(defn exec-putlink [cluster links]
(storage/with-consistency :one
(storage/putlink
cluster
(map
(fn [[a l b]] {:a (f/bytes-to-uuid a) :l (f/bytes-to-str l) :b (f/bytes-to-uuid b)}) links)))
(msg-done))
(defn exec-dellink [cluster links]
(storage/with-consistency :one
(storage/dellink
cluster
(map
(fn [[a l b]]
(if (empty? b)
{:a (f/bytes-to-uuid a) :l (f/bytes-to-str l)}
{:a (f/bytes-to-uuid a) :l (f/bytes-to-str l) :b (f/bytes-to-uuid b)})) links)))
(msg-done))
(defn exec-get-tattr [cluster [k n t] limit]
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/with-limit limit
(msg-tattr (storage/get-tattr cluster k n t))))))
(defn exec-get-archived-tattr [s3-cred [b a]]
(let [b (f/bytes-to-str b)
a (f/bytes-to-str a)]
(f/stream-to-bytes (s3/get-archived-tattr s3-cred b a))))
(defn exec-put-archived-tattr [s3-cred [b a v]]
(let [b (f/bytes-to-str b)
a (f/bytes-to-str a)]
(let [v (s3/put-archived-tattr s3-cred b a v)]
(if-not (:errorcode v)
(msg-done)
(msg-fail (:statuscode v))))))
(defn exec-put-archived-bucket [s3-cred [b]]
(let [b (f/bytes-to-str b)]
(s3/create-bucket s3-cred b))
(msg-done))
(defn exec-put-tattr [cluster attrs]
(storage/with-consistency :one
(storage/put-tattr
cluster
(map
(fn [[k n t v o]]
[{:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:time t
:value (f/str-to-bytes v)}
(parse-opts o)]) attrs)))
(msg-done))
(defn exec-del-tattr [cluster attrs]
(storage/with-consistency :one
(storage/del-tattr
cluster
(map
(fn [[k n t]] {:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:time t}) attrs)))
(msg-done))
(defn exec-get-kattr [cluster [k s]]
(let [k (f/bytes-to-uuid k)
s (f/bytes-to-str s)]
(storage/with-consistency :one
(msg-kattr (storage/get-kattr cluster k s)))))
(defn exec-put-kattr [cluster attrs]
(storage/with-consistency :one
(storage/put-kattr
cluster
(map
(fn [[k n v o]] [{:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:value (f/str-to-bytes v)}
(parse-opts o)]) attrs)))
(msg-done))
(defn exec-del-kattr [cluster attrs]
(storage/with-consistency :one
(storage/del-kattr
cluster
(map
(fn [[k n]] {:key (f/bytes-to-uuid k) :name (f/bytes-to-str n)}) attrs)))
(msg-done))
(defn exec-getindex-exact [cluster table [k n]]
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/has-index cluster table k n))))
(defn exec-getindex-all [cluster table [k page] limit]
(let [k (f/bytes-to-uuid k)
page (f/bytes-to-str page)]
(storage/with-consistency :one
(storage/with-limit limit
(storage/get-index cluster table k page)))))
(defn exec-getindex-prefix [cluster table [k start finish] limit]
(let [k (f/bytes-to-uuid k)
start (f/bytes-to-str start)
finish (f/bytes-to-str finish)]
(storage/with-consistency :one
(storage/with-limit limit
(storage/get-index cluster table k start finish)))))
(defn exec-getlabel [cluster msg limit]
(case (first msg)
"all" (msg-label (exec-getindex-all cluster :g_index (drop 1 msg) limit))
"ext" (msg-label (exec-getindex-exact cluster :g_index (drop 1 msg)))
"pre" (msg-label (exec-getindex-prefix cluster :g_index (drop 1 msg) limit))
(msg-fail 400)))
(defn exec-enum [cluster [t l & attrs]]
(let [t (Long. (f/bytes-to-str t))
l (f/bytes-to-str l)]
(if-let [[k n b] attrs]
(do
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)
b (f/bytes-to-str b)]
(storage/enum-tattr cluster t l k n b)))
(storage/enum-tattr cluster t l))))
(defn exec-listattr [cluster table msg limit]
(let [table (get {"k-attr" :k_index "t-attr" :t_index} table)]
(case (first msg)
"all" (msg-nattr (exec-getindex-all cluster table (drop 1 msg) limit))
"ext" (msg-nattr (exec-getindex-exact cluster table (drop 1 msg)))
"pre" (msg-nattr (exec-getindex-prefix cluster table (drop 1 msg) limit))
(msg-fail 400))))
(defn exec-putlabel [cluster labels]
(storage/with-consistency :one
(storage/put-index
cluster
:g_index
(map (fn [[k n]] {:key (f/bytes-to-uuid k) :name (f/bytes-to-str n)}) labels)))
(msg-done))
(defn handle-get [attr-cluster graph-cluster msg]
(case (first msg)
"attr" (let [args (drop 1 msg)]
(exec-listattr attr-cluster (first args) (second args) (third args)))
"guid" (exec-getguid graph-cluster (second msg))
"link" (exec-getlink graph-cluster (second msg) (third msg))
"name" (exec-getname graph-cluster (second msg))
"label" (exec-getlabel graph-cluster (second msg) (third msg))
"k-attr" (exec-get-kattr attr-cluster (second msg))
"t-attr" (exec-get-tattr attr-cluster (second msg) (third msg))
(msg-fail 400)))
(defn handle-put [attr-cluster graph-cluster msg]
(case (first msg)
"link" (exec-putlink graph-cluster (second msg))
"name" (exec-putname graph-cluster (second msg))
"label" (exec-putlabel graph-cluster (second msg))
"k-attr" (exec-put-kattr attr-cluster (second msg))
"t-attr" (exec-put-tattr attr-cluster (second msg))
(msg-fail 400)))
(defn handle-del [attr-cluster graph-cluster msg]
(case (first msg)
"link" (exec-dellink graph-cluster (second msg))
"k-attr" (exec-del-kattr attr-cluster (second msg))
"t-attr" (exec-del-tattr attr-cluster (second msg))
(msg-fail 400)))
(defn fmtreply [req rep]
(case (first rep)
"fail" [[(take 2 req) rep] [msg-pack-magic (msgp/pack rep)]]
[[(take 2 req) (first rep)] [msg-pack-magic (msgp/pack rep)]]))
(defn handle-message [attr-cluster graph-cluster msg]
(if (< (count msg) 1)
(msg-fail 400)
(case (first msg)
"del" (handle-del attr-cluster graph-cluster (drop 1 msg))
"get" (handle-get attr-cluster graph-cluster (drop 1 msg))
"put" (handle-put attr-cluster graph-cluster (drop 1 msg))
(msg-fail 400))))
(defn handle-message-frame [attr-cluster graph-cluster msg]
(if (not= (count msg) 2)
(fmtreply [] (msg-fail 400))
(if (= msg-pack-magic (f/bytes-to-str (first msg)))
(let [req (msgp/unpack (second msg))]
(fmtreply req (handle-message attr-cluster graph-cluster req)))
(fmtreply [] (msg-fail 400)))))
(defn zmqworker [attr-cluster graph-cluster]
{:onjob #(handle-message-frame attr-cluster graph-cluster %) :onerr (msg-fail 500)})
(defn server-start [ctx attr-cluster graph-cluster options]
(router/router-start ctx (zmqworker attr-cluster graph-cluster) options))
|
39150
|
;; Copyright 2014 (c) <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 leela.blackbox.network.zmqserver
(:use [clojure.tools.logging :only [trace debug info error]])
(:require [msgpack.core :as msgp]
[leela.blackbox.f :as f]
[leela.blackbox.czmq.router :as router]
[leela.blackbox.storage.cassandra :as storage]
[leela.blackbox.storage.s3 :as s3]))
(defmacro third [list]
`(nth ~list 2))
(defmacro parse-opts [opts]
`(into {} (for [[k# v#] ~opts] [(keyword k#) v#])))
(def msg-pack-magic "000")
(defn msg-fail [status]
["fail" status])
(defn msg-done []
["done" nil])
(defn msg-name [u t k n g]
(if-not g
(msg-fail 404)
["name" [u t k n (str g)]]))
(defn msg-link [links]
["link" (map str links)])
(defn msg-label [labels]
["label" labels])
(defn msg-nattr [attrs]
["n-attr" attrs])
(defn msg-tattr [data]
["t-attr" data])
(defn msg-kattr [data]
(if-not data
(msg-fail 404)
["k-attr" data]))
(defn exec-getname [cluster [g]]
(let [g (f/bytes-to-uuid g)]
(storage/with-consistency :one
(storage/with-limit 1
(if-let [[u t k n] (storage/getname cluster g)]
(msg-name u t k n g)
(msg-fail 404))))))
(defn exec-getguid [cluster [u t k n]]
(let [u (f/bytes-to-str u)
t (f/bytes-to-str t)
k (f/bytes-to-str k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/with-limit 1
(msg-name u t k n (storage/getguid cluster u t k n))))))
(defn exec-putname [cluster [u t k n]]
(storage/with-consistency :quorum
(let [u (f/bytes-to-str u)
t (f/bytes-to-str t)
k (f/bytes-to-str k)
n (f/bytes-to-str n)
g (storage/putguid cluster u t k n)]
(msg-name u t k n g))))
(defn exec-getlink [cluster [a l page] limit]
(let [a (f/bytes-to-uuid a)
l (f/bytes-to-str l)
page (if (empty? page) f/uuid-zero (f/bytes-to-uuid page))]
(storage/with-consistency :one
(storage/with-limit limit
(msg-link (storage/getlink cluster a l page))))))
(defn exec-putlink [cluster links]
(storage/with-consistency :one
(storage/putlink
cluster
(map
(fn [[a l b]] {:a (f/bytes-to-uuid a) :l (f/bytes-to-str l) :b (f/bytes-to-uuid b)}) links)))
(msg-done))
(defn exec-dellink [cluster links]
(storage/with-consistency :one
(storage/dellink
cluster
(map
(fn [[a l b]]
(if (empty? b)
{:a (f/bytes-to-uuid a) :l (f/bytes-to-str l)}
{:a (f/bytes-to-uuid a) :l (f/bytes-to-str l) :b (f/bytes-to-uuid b)})) links)))
(msg-done))
(defn exec-get-tattr [cluster [k n t] limit]
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/with-limit limit
(msg-tattr (storage/get-tattr cluster k n t))))))
(defn exec-get-archived-tattr [s3-cred [b a]]
(let [b (f/bytes-to-str b)
a (f/bytes-to-str a)]
(f/stream-to-bytes (s3/get-archived-tattr s3-cred b a))))
(defn exec-put-archived-tattr [s3-cred [b a v]]
(let [b (f/bytes-to-str b)
a (f/bytes-to-str a)]
(let [v (s3/put-archived-tattr s3-cred b a v)]
(if-not (:errorcode v)
(msg-done)
(msg-fail (:statuscode v))))))
(defn exec-put-archived-bucket [s3-cred [b]]
(let [b (f/bytes-to-str b)]
(s3/create-bucket s3-cred b))
(msg-done))
(defn exec-put-tattr [cluster attrs]
(storage/with-consistency :one
(storage/put-tattr
cluster
(map
(fn [[k n t v o]]
[{:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:time t
:value (f/str-to-bytes v)}
(parse-opts o)]) attrs)))
(msg-done))
(defn exec-del-tattr [cluster attrs]
(storage/with-consistency :one
(storage/del-tattr
cluster
(map
(fn [[k n t]] {:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:time t}) attrs)))
(msg-done))
(defn exec-get-kattr [cluster [k s]]
(let [k (f/bytes-to-uuid k)
s (f/bytes-to-str s)]
(storage/with-consistency :one
(msg-kattr (storage/get-kattr cluster k s)))))
(defn exec-put-kattr [cluster attrs]
(storage/with-consistency :one
(storage/put-kattr
cluster
(map
(fn [[k n v o]] [{:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:value (f/str-to-bytes v)}
(parse-opts o)]) attrs)))
(msg-done))
(defn exec-del-kattr [cluster attrs]
(storage/with-consistency :one
(storage/del-kattr
cluster
(map
(fn [[k n]] {:key (f/bytes-to-uuid k) :name (f/bytes-to-str n)}) attrs)))
(msg-done))
(defn exec-getindex-exact [cluster table [k n]]
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/has-index cluster table k n))))
(defn exec-getindex-all [cluster table [k page] limit]
(let [k (f/bytes-to-uuid k)
page (f/bytes-to-str page)]
(storage/with-consistency :one
(storage/with-limit limit
(storage/get-index cluster table k page)))))
(defn exec-getindex-prefix [cluster table [k start finish] limit]
(let [k (f/bytes-to-uuid k)
start (f/bytes-to-str start)
finish (f/bytes-to-str finish)]
(storage/with-consistency :one
(storage/with-limit limit
(storage/get-index cluster table k start finish)))))
(defn exec-getlabel [cluster msg limit]
(case (first msg)
"all" (msg-label (exec-getindex-all cluster :g_index (drop 1 msg) limit))
"ext" (msg-label (exec-getindex-exact cluster :g_index (drop 1 msg)))
"pre" (msg-label (exec-getindex-prefix cluster :g_index (drop 1 msg) limit))
(msg-fail 400)))
(defn exec-enum [cluster [t l & attrs]]
(let [t (Long. (f/bytes-to-str t))
l (f/bytes-to-str l)]
(if-let [[k n b] attrs]
(do
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)
b (f/bytes-to-str b)]
(storage/enum-tattr cluster t l k n b)))
(storage/enum-tattr cluster t l))))
(defn exec-listattr [cluster table msg limit]
(let [table (get {"k-attr" :k_index "t-attr" :t_index} table)]
(case (first msg)
"all" (msg-nattr (exec-getindex-all cluster table (drop 1 msg) limit))
"ext" (msg-nattr (exec-getindex-exact cluster table (drop 1 msg)))
"pre" (msg-nattr (exec-getindex-prefix cluster table (drop 1 msg) limit))
(msg-fail 400))))
(defn exec-putlabel [cluster labels]
(storage/with-consistency :one
(storage/put-index
cluster
:g_index
(map (fn [[k n]] {:key (f/bytes-to-uuid k) :name (f/bytes-to-str n)}) labels)))
(msg-done))
(defn handle-get [attr-cluster graph-cluster msg]
(case (first msg)
"attr" (let [args (drop 1 msg)]
(exec-listattr attr-cluster (first args) (second args) (third args)))
"guid" (exec-getguid graph-cluster (second msg))
"link" (exec-getlink graph-cluster (second msg) (third msg))
"name" (exec-getname graph-cluster (second msg))
"label" (exec-getlabel graph-cluster (second msg) (third msg))
"k-attr" (exec-get-kattr attr-cluster (second msg))
"t-attr" (exec-get-tattr attr-cluster (second msg) (third msg))
(msg-fail 400)))
(defn handle-put [attr-cluster graph-cluster msg]
(case (first msg)
"link" (exec-putlink graph-cluster (second msg))
"name" (exec-putname graph-cluster (second msg))
"label" (exec-putlabel graph-cluster (second msg))
"k-attr" (exec-put-kattr attr-cluster (second msg))
"t-attr" (exec-put-tattr attr-cluster (second msg))
(msg-fail 400)))
(defn handle-del [attr-cluster graph-cluster msg]
(case (first msg)
"link" (exec-dellink graph-cluster (second msg))
"k-attr" (exec-del-kattr attr-cluster (second msg))
"t-attr" (exec-del-tattr attr-cluster (second msg))
(msg-fail 400)))
(defn fmtreply [req rep]
(case (first rep)
"fail" [[(take 2 req) rep] [msg-pack-magic (msgp/pack rep)]]
[[(take 2 req) (first rep)] [msg-pack-magic (msgp/pack rep)]]))
(defn handle-message [attr-cluster graph-cluster msg]
(if (< (count msg) 1)
(msg-fail 400)
(case (first msg)
"del" (handle-del attr-cluster graph-cluster (drop 1 msg))
"get" (handle-get attr-cluster graph-cluster (drop 1 msg))
"put" (handle-put attr-cluster graph-cluster (drop 1 msg))
(msg-fail 400))))
(defn handle-message-frame [attr-cluster graph-cluster msg]
(if (not= (count msg) 2)
(fmtreply [] (msg-fail 400))
(if (= msg-pack-magic (f/bytes-to-str (first msg)))
(let [req (msgp/unpack (second msg))]
(fmtreply req (handle-message attr-cluster graph-cluster req)))
(fmtreply [] (msg-fail 400)))))
(defn zmqworker [attr-cluster graph-cluster]
{:onjob #(handle-message-frame attr-cluster graph-cluster %) :onerr (msg-fail 500)})
(defn server-start [ctx attr-cluster graph-cluster options]
(router/router-start ctx (zmqworker attr-cluster graph-cluster) options))
| true |
;; Copyright 2014 (c) 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 leela.blackbox.network.zmqserver
(:use [clojure.tools.logging :only [trace debug info error]])
(:require [msgpack.core :as msgp]
[leela.blackbox.f :as f]
[leela.blackbox.czmq.router :as router]
[leela.blackbox.storage.cassandra :as storage]
[leela.blackbox.storage.s3 :as s3]))
(defmacro third [list]
`(nth ~list 2))
(defmacro parse-opts [opts]
`(into {} (for [[k# v#] ~opts] [(keyword k#) v#])))
(def msg-pack-magic "000")
(defn msg-fail [status]
["fail" status])
(defn msg-done []
["done" nil])
(defn msg-name [u t k n g]
(if-not g
(msg-fail 404)
["name" [u t k n (str g)]]))
(defn msg-link [links]
["link" (map str links)])
(defn msg-label [labels]
["label" labels])
(defn msg-nattr [attrs]
["n-attr" attrs])
(defn msg-tattr [data]
["t-attr" data])
(defn msg-kattr [data]
(if-not data
(msg-fail 404)
["k-attr" data]))
(defn exec-getname [cluster [g]]
(let [g (f/bytes-to-uuid g)]
(storage/with-consistency :one
(storage/with-limit 1
(if-let [[u t k n] (storage/getname cluster g)]
(msg-name u t k n g)
(msg-fail 404))))))
(defn exec-getguid [cluster [u t k n]]
(let [u (f/bytes-to-str u)
t (f/bytes-to-str t)
k (f/bytes-to-str k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/with-limit 1
(msg-name u t k n (storage/getguid cluster u t k n))))))
(defn exec-putname [cluster [u t k n]]
(storage/with-consistency :quorum
(let [u (f/bytes-to-str u)
t (f/bytes-to-str t)
k (f/bytes-to-str k)
n (f/bytes-to-str n)
g (storage/putguid cluster u t k n)]
(msg-name u t k n g))))
(defn exec-getlink [cluster [a l page] limit]
(let [a (f/bytes-to-uuid a)
l (f/bytes-to-str l)
page (if (empty? page) f/uuid-zero (f/bytes-to-uuid page))]
(storage/with-consistency :one
(storage/with-limit limit
(msg-link (storage/getlink cluster a l page))))))
(defn exec-putlink [cluster links]
(storage/with-consistency :one
(storage/putlink
cluster
(map
(fn [[a l b]] {:a (f/bytes-to-uuid a) :l (f/bytes-to-str l) :b (f/bytes-to-uuid b)}) links)))
(msg-done))
(defn exec-dellink [cluster links]
(storage/with-consistency :one
(storage/dellink
cluster
(map
(fn [[a l b]]
(if (empty? b)
{:a (f/bytes-to-uuid a) :l (f/bytes-to-str l)}
{:a (f/bytes-to-uuid a) :l (f/bytes-to-str l) :b (f/bytes-to-uuid b)})) links)))
(msg-done))
(defn exec-get-tattr [cluster [k n t] limit]
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/with-limit limit
(msg-tattr (storage/get-tattr cluster k n t))))))
(defn exec-get-archived-tattr [s3-cred [b a]]
(let [b (f/bytes-to-str b)
a (f/bytes-to-str a)]
(f/stream-to-bytes (s3/get-archived-tattr s3-cred b a))))
(defn exec-put-archived-tattr [s3-cred [b a v]]
(let [b (f/bytes-to-str b)
a (f/bytes-to-str a)]
(let [v (s3/put-archived-tattr s3-cred b a v)]
(if-not (:errorcode v)
(msg-done)
(msg-fail (:statuscode v))))))
(defn exec-put-archived-bucket [s3-cred [b]]
(let [b (f/bytes-to-str b)]
(s3/create-bucket s3-cred b))
(msg-done))
(defn exec-put-tattr [cluster attrs]
(storage/with-consistency :one
(storage/put-tattr
cluster
(map
(fn [[k n t v o]]
[{:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:time t
:value (f/str-to-bytes v)}
(parse-opts o)]) attrs)))
(msg-done))
(defn exec-del-tattr [cluster attrs]
(storage/with-consistency :one
(storage/del-tattr
cluster
(map
(fn [[k n t]] {:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:time t}) attrs)))
(msg-done))
(defn exec-get-kattr [cluster [k s]]
(let [k (f/bytes-to-uuid k)
s (f/bytes-to-str s)]
(storage/with-consistency :one
(msg-kattr (storage/get-kattr cluster k s)))))
(defn exec-put-kattr [cluster attrs]
(storage/with-consistency :one
(storage/put-kattr
cluster
(map
(fn [[k n v o]] [{:key (f/bytes-to-uuid k)
:name (f/bytes-to-str n)
:value (f/str-to-bytes v)}
(parse-opts o)]) attrs)))
(msg-done))
(defn exec-del-kattr [cluster attrs]
(storage/with-consistency :one
(storage/del-kattr
cluster
(map
(fn [[k n]] {:key (f/bytes-to-uuid k) :name (f/bytes-to-str n)}) attrs)))
(msg-done))
(defn exec-getindex-exact [cluster table [k n]]
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)]
(storage/with-consistency :one
(storage/has-index cluster table k n))))
(defn exec-getindex-all [cluster table [k page] limit]
(let [k (f/bytes-to-uuid k)
page (f/bytes-to-str page)]
(storage/with-consistency :one
(storage/with-limit limit
(storage/get-index cluster table k page)))))
(defn exec-getindex-prefix [cluster table [k start finish] limit]
(let [k (f/bytes-to-uuid k)
start (f/bytes-to-str start)
finish (f/bytes-to-str finish)]
(storage/with-consistency :one
(storage/with-limit limit
(storage/get-index cluster table k start finish)))))
(defn exec-getlabel [cluster msg limit]
(case (first msg)
"all" (msg-label (exec-getindex-all cluster :g_index (drop 1 msg) limit))
"ext" (msg-label (exec-getindex-exact cluster :g_index (drop 1 msg)))
"pre" (msg-label (exec-getindex-prefix cluster :g_index (drop 1 msg) limit))
(msg-fail 400)))
(defn exec-enum [cluster [t l & attrs]]
(let [t (Long. (f/bytes-to-str t))
l (f/bytes-to-str l)]
(if-let [[k n b] attrs]
(do
(let [k (f/bytes-to-uuid k)
n (f/bytes-to-str n)
b (f/bytes-to-str b)]
(storage/enum-tattr cluster t l k n b)))
(storage/enum-tattr cluster t l))))
(defn exec-listattr [cluster table msg limit]
(let [table (get {"k-attr" :k_index "t-attr" :t_index} table)]
(case (first msg)
"all" (msg-nattr (exec-getindex-all cluster table (drop 1 msg) limit))
"ext" (msg-nattr (exec-getindex-exact cluster table (drop 1 msg)))
"pre" (msg-nattr (exec-getindex-prefix cluster table (drop 1 msg) limit))
(msg-fail 400))))
(defn exec-putlabel [cluster labels]
(storage/with-consistency :one
(storage/put-index
cluster
:g_index
(map (fn [[k n]] {:key (f/bytes-to-uuid k) :name (f/bytes-to-str n)}) labels)))
(msg-done))
(defn handle-get [attr-cluster graph-cluster msg]
(case (first msg)
"attr" (let [args (drop 1 msg)]
(exec-listattr attr-cluster (first args) (second args) (third args)))
"guid" (exec-getguid graph-cluster (second msg))
"link" (exec-getlink graph-cluster (second msg) (third msg))
"name" (exec-getname graph-cluster (second msg))
"label" (exec-getlabel graph-cluster (second msg) (third msg))
"k-attr" (exec-get-kattr attr-cluster (second msg))
"t-attr" (exec-get-tattr attr-cluster (second msg) (third msg))
(msg-fail 400)))
(defn handle-put [attr-cluster graph-cluster msg]
(case (first msg)
"link" (exec-putlink graph-cluster (second msg))
"name" (exec-putname graph-cluster (second msg))
"label" (exec-putlabel graph-cluster (second msg))
"k-attr" (exec-put-kattr attr-cluster (second msg))
"t-attr" (exec-put-tattr attr-cluster (second msg))
(msg-fail 400)))
(defn handle-del [attr-cluster graph-cluster msg]
(case (first msg)
"link" (exec-dellink graph-cluster (second msg))
"k-attr" (exec-del-kattr attr-cluster (second msg))
"t-attr" (exec-del-tattr attr-cluster (second msg))
(msg-fail 400)))
(defn fmtreply [req rep]
(case (first rep)
"fail" [[(take 2 req) rep] [msg-pack-magic (msgp/pack rep)]]
[[(take 2 req) (first rep)] [msg-pack-magic (msgp/pack rep)]]))
(defn handle-message [attr-cluster graph-cluster msg]
(if (< (count msg) 1)
(msg-fail 400)
(case (first msg)
"del" (handle-del attr-cluster graph-cluster (drop 1 msg))
"get" (handle-get attr-cluster graph-cluster (drop 1 msg))
"put" (handle-put attr-cluster graph-cluster (drop 1 msg))
(msg-fail 400))))
(defn handle-message-frame [attr-cluster graph-cluster msg]
(if (not= (count msg) 2)
(fmtreply [] (msg-fail 400))
(if (= msg-pack-magic (f/bytes-to-str (first msg)))
(let [req (msgp/unpack (second msg))]
(fmtreply req (handle-message attr-cluster graph-cluster req)))
(fmtreply [] (msg-fail 400)))))
(defn zmqworker [attr-cluster graph-cluster]
{:onjob #(handle-message-frame attr-cluster graph-cluster %) :onerr (msg-fail 500)})
(defn server-start [ctx attr-cluster graph-cluster options]
(router/router-start ctx (zmqworker attr-cluster graph-cluster) options))
|
[
{
"context": "eated.\n\n ```javascript\n sprite.setData('name', 'Red Gem Stone');\n ```\n\n You can also pass in an obj",
"end": 43520,
"score": 0.6137969493865967,
"start": 43517,
"tag": "NAME",
"value": "Red"
},
{
"context": "\n ```javascript\n sprite.setData('name', 'Red Gem Stone');\n ```\n\n You can also pass in an object of key",
"end": 43530,
"score": 0.5378642082214355,
"start": 43525,
"tag": "NAME",
"value": "Stone"
},
{
"context": "ument:\n\n ```javascript\n sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 });\n ```\n\n ",
"end": 43672,
"score": 0.694881021976471,
"start": 43659,
"tag": "NAME",
"value": "Red Gem Stone"
},
{
"context": "r example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerL",
"end": 44240,
"score": 0.9305174946784973,
"start": 44229,
"tag": "KEY",
"value": "PlayerLives"
}
] |
src/phzr/physics/arcade/image.cljs
|
sjcasey21/phzr
| 1 |
(ns phzr.physics.arcade.image
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [update]))
(defn ->Image
" Parameters:
* scene (Phaser.Scene) - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
* x (number) - The horizontal position of this Game Object in the world.
* y (number) - The vertical position of this Game Object in the world.
* texture (string) - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager.
* frame (string | integer) {optional} - An optional frame from the Texture this Game Object is rendering with."
([scene x y texture]
(js/Phaser.Physics.Arcade.Image. (clj->phaser scene)
(clj->phaser x)
(clj->phaser y)
(clj->phaser texture)))
([scene x y texture frame]
(js/Phaser.Physics.Arcade.Image. (clj->phaser scene)
(clj->phaser x)
(clj->phaser y)
(clj->phaser texture)
(clj->phaser frame))))
(defn add-listener
"Add a listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.addListener image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.addListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn clear-alpha
"Clears all alpha values associated with this Game Object.
Immediately sets the alpha levels back to 1 (fully opaque).
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearAlpha image))))
(defn clear-mask
"Clears the mask that this Game Object was using.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* destroy-mask (boolean) {optional} - Destroy the mask before clearing it?
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearMask image)))
([image destroy-mask]
(phaser->clj
(.clearMask image
(clj->phaser destroy-mask)))))
(defn clear-tint
"Clears all tint values associated with this Game Object.
Immediately sets the color values back to 0xffffff and the tint type to 'additive',
which results in no visible change to the texture.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearTint image))))
(defn create-bitmap-mask
"Creates and returns a Bitmap Mask. This mask can be used by any Game Object,
including this one.
To create the mask you need to pass in a reference to a renderable Game Object.
A renderable Game Object is one that uses a texture to render with, such as an
Image, Sprite, Render Texture or BitmapText.
If you do not provide a renderable object, and this Game Object has a texture,
it will use itself as the object. This means you can call this method to create
a Bitmap Mask from any renderable Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* renderable (Phaser.GameObjects.GameObject) {optional} - A renderable Game Object that uses a texture, such as a Sprite.
Returns: Phaser.Display.Masks.BitmapMask - This Bitmap Mask that was created."
([image]
(phaser->clj
(.createBitmapMask image)))
([image renderable]
(phaser->clj
(.createBitmapMask image
(clj->phaser renderable)))))
(defn create-geometry-mask
"Creates and returns a Geometry Mask. This mask can be used by any Game Object,
including this one.
To create the mask you need to pass in a reference to a Graphics Game Object.
If you do not provide a graphics object, and this Game Object is an instance
of a Graphics object, then it will use itself to create the mask.
This means you can call this method to create a Geometry Mask from any Graphics Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* graphics (Phaser.GameObjects.Graphics) {optional} - A Graphics Game Object. The geometry within it will be used as the mask.
Returns: Phaser.Display.Masks.GeometryMask - This Geometry Mask that was created."
([image]
(phaser->clj
(.createGeometryMask image)))
([image graphics]
(phaser->clj
(.createGeometryMask image
(clj->phaser graphics)))))
(defn destroy
"Destroys this Game Object removing it from the Display List and Update List and
severing all ties to parent resources.
Also removes itself from the Input Manager and Physics Manager if previously enabled.
Use this to remove a Game Object from your game if you don't ever plan to use it again.
As long as no reference to it exists within your own code it should become free for
garbage collection by the browser.
If you just want to temporarily disable an object then look at using the
Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?"
([image]
(phaser->clj
(.destroy image)))
([image from-scene]
(phaser->clj
(.destroy image
(clj->phaser from-scene)))))
(defn disable-body
"Stops and disables this Game Object's Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* disable-game-object (boolean) {optional} - Also deactivate this Game Object.
* hide-game-object (boolean) {optional} - Also hide this Game Object.
Returns: this - This Game Object."
([image]
(phaser->clj
(.disableBody image)))
([image disable-game-object]
(phaser->clj
(.disableBody image
(clj->phaser disable-game-object))))
([image disable-game-object hide-game-object]
(phaser->clj
(.disableBody image
(clj->phaser disable-game-object)
(clj->phaser hide-game-object)))))
(defn disable-interactive
"If this Game Object has previously been enabled for input, this will disable it.
An object that is disabled for input stops processing or being considered for
input events, but can be turned back on again at any time by simply calling
`setInteractive()` with no arguments provided.
If want to completely remove interaction from this Game Object then use `removeInteractive` instead.
Returns: this - This GameObject."
([image]
(phaser->clj
(.disableInteractive image))))
(defn emit
"Calls each of the listeners registered for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* args (*) {optional} - Additional arguments that will be passed to the event handler.
Returns: boolean - `true` if the event had listeners, else `false`."
([image event]
(phaser->clj
(.emit image
(clj->phaser event))))
([image event args]
(phaser->clj
(.emit image
(clj->phaser event)
(clj->phaser args)))))
(defn enable-body
"Enables this Game Object's Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* reset (boolean) - Also reset the Body and place it at (x, y).
* x (number) - The horizontal position to place the Game Object and Body.
* y (number) - The horizontal position to place the Game Object and Body.
* enable-game-object (boolean) - Also activate this Game Object.
* show-game-object (boolean) - Also show this Game Object.
Returns: this - This Game Object."
([image reset x y enable-game-object show-game-object]
(phaser->clj
(.enableBody image
(clj->phaser reset)
(clj->phaser x)
(clj->phaser y)
(clj->phaser enable-game-object)
(clj->phaser show-game-object)))))
(defn event-names
"Return an array listing the events for which the emitter has registered listeners.
Returns: array - "
([image]
(phaser->clj
(.eventNames image))))
(defn get-bottom-center
"Gets the bottom-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomCenter image)))
([image output]
(phaser->clj
(.getBottomCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bottom-left
"Gets the bottom-left corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomLeft image)))
([image output]
(phaser->clj
(.getBottomLeft image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomLeft image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bottom-right
"Gets the bottom-right corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomRight image)))
([image output]
(phaser->clj
(.getBottomRight image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomRight image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bounds
"Gets the bounds of this Game Object, regardless of origin.
The values are stored and returned in a Rectangle, or Rectangle-like, object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Geom.Rectangle | object) {optional} - An object to store the values in. If not provided a new Rectangle will be created.
Returns: Phaser.Geom.Rectangle | object - The values stored in the output object."
([image]
(phaser->clj
(.getBounds image)))
([image output]
(phaser->clj
(.getBounds image
(clj->phaser output)))))
(defn get-center
"Gets the center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getCenter image)))
([image output]
(phaser->clj
(.getCenter image
(clj->phaser output)))))
(defn get-data
"Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist.
You can also access values via the `values` object. For example, if you had a key called `gold` you can do either:
```javascript
sprite.getData('gold');
```
Or access the value directly:
```javascript
sprite.data.values.gold;
```
You can also pass in an array of keys, in which case an array of values will be returned:
```javascript
sprite.getData([ 'gold', 'armor', 'health' ]);
```
This approach is useful for destructuring arrays in ES6.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string | Array.<string>) - The key of the value to retrieve, or an array of keys.
Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array."
([image key]
(phaser->clj
(.getData image
(clj->phaser key)))))
(defn get-index-list
"Returns an array containing the display list index of either this Game Object, or if it has one,
its parent Container. It then iterates up through all of the parent containers until it hits the
root of the display list (which is index 0 in the returned array).
Used internally by the InputPlugin but also useful if you wish to find out the display depth of
this Game Object and all of its ancestors.
Returns: Array.<integer> - An array of display list position indexes."
([image]
(phaser->clj
(.getIndexList image))))
(defn get-left-center
"Gets the left-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getLeftCenter image)))
([image output]
(phaser->clj
(.getLeftCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getLeftCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-local-transform-matrix
"Gets the local transform matrix for this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* temp-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - The matrix to populate with the values from this Game Object.
Returns: Phaser.GameObjects.Components.TransformMatrix - The populated Transform Matrix."
([image]
(phaser->clj
(.getLocalTransformMatrix image)))
([image temp-matrix]
(phaser->clj
(.getLocalTransformMatrix image
(clj->phaser temp-matrix)))))
(defn get-parent-rotation
"Gets the sum total rotation of all of this Game Objects parent Containers.
The returned value is in radians and will be zero if this Game Object has no parent container.
Returns: number - The sum total rotation, in radians, of all parent containers of this Game Object."
([image]
(phaser->clj
(.getParentRotation image))))
(defn get-pipeline-name
"Gets the name of the WebGL Pipeline this Game Object is currently using.
Returns: string - The string-based name of the pipeline being used by this Game Object."
([image]
(phaser->clj
(.getPipelineName image))))
(defn get-right-center
"Gets the right-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getRightCenter image)))
([image output]
(phaser->clj
(.getRightCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getRightCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-center
"Gets the top-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopCenter image)))
([image output]
(phaser->clj
(.getTopCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-left
"Gets the top-left corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopLeft image)))
([image output]
(phaser->clj
(.getTopLeft image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopLeft image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-right
"Gets the top-right corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopRight image)))
([image output]
(phaser->clj
(.getTopRight image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopRight image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-world-transform-matrix
"Gets the world transform matrix for this Game Object, factoring in any parent Containers.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* temp-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - The matrix to populate with the values from this Game Object.
* parent-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - A temporary matrix to hold parent values during the calculations.
Returns: Phaser.GameObjects.Components.TransformMatrix - The populated Transform Matrix."
([image]
(phaser->clj
(.getWorldTransformMatrix image)))
([image temp-matrix]
(phaser->clj
(.getWorldTransformMatrix image
(clj->phaser temp-matrix))))
([image temp-matrix parent-matrix]
(phaser->clj
(.getWorldTransformMatrix image
(clj->phaser temp-matrix)
(clj->phaser parent-matrix)))))
(defn init-pipeline
"Sets the initial WebGL Pipeline of this Game Object.
This should only be called during the instantiation of the Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* pipeline-name (string) {optional} - The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline.
Returns: boolean - `true` if the pipeline was set successfully, otherwise `false`."
([image]
(phaser->clj
(.initPipeline image)))
([image pipeline-name]
(phaser->clj
(.initPipeline image
(clj->phaser pipeline-name)))))
(defn listener-count
"Return the number of listeners listening to a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: number - The number of listeners."
([image event]
(phaser->clj
(.listenerCount image
(clj->phaser event)))))
(defn listeners
"Return the listeners registered for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: array - The registered listeners."
([image event]
(phaser->clj
(.listeners image
(clj->phaser event)))))
(defn off
"Remove the listeners of a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) {optional} - Only remove the listeners that match this function.
* context (*) {optional} - Only remove the listeners that have this context.
* once (boolean) {optional} - Only remove one-time listeners.
Returns: Phaser.Events.EventEmitter - `this`."
([image event]
(phaser->clj
(.off image
(clj->phaser event))))
([image event fn]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([image event fn context once]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn on
"Add a listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.on image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.on image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn once
"Add a one-time listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.once image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.once image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn refresh-body
"Syncs the Body's position and size with its parent Game Object.
You don't need to call this for Dynamic Bodies, as it happens automatically.
But for Static bodies it's a useful way of modifying the position of a Static Body
in the Physics World, based on its Game Object.
Returns: this - This Game Object."
([image]
(phaser->clj
(.refreshBody image))))
(defn remove-all-listeners
"Remove all listeners, or those of the specified event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) {optional} - The event name.
Returns: Phaser.Events.EventEmitter - `this`."
([image]
(phaser->clj
(.removeAllListeners image)))
([image event]
(phaser->clj
(.removeAllListeners image
(clj->phaser event)))))
(defn remove-interactive
"If this Game Object has previously been enabled for input, this will queue it
for removal, causing it to no longer be interactive. The removal happens on
the next game step, it is not immediate.
The Interactive Object that was assigned to this Game Object will be destroyed,
removed from the Input Manager and cleared from this Game Object.
If you wish to re-enable this Game Object at a later date you will need to
re-create its InteractiveObject by calling `setInteractive` again.
If you wish to only temporarily stop an object from receiving input then use
`disableInteractive` instead, as that toggles the interactive state, where-as
this erases it completely.
If you wish to resize a hit area, don't remove and then set it as being
interactive. Instead, access the hitarea object directly and resize the shape
being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the
shape is a Rectangle, which it is by default.)
Returns: this - This GameObject."
([image]
(phaser->clj
(.removeInteractive image))))
(defn remove-listener
"Remove the listeners of a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) {optional} - Only remove the listeners that match this function.
* context (*) {optional} - Only remove the listeners that have this context.
* once (boolean) {optional} - Only remove one-time listeners.
Returns: Phaser.Events.EventEmitter - `this`."
([image event]
(phaser->clj
(.removeListener image
(clj->phaser event))))
([image event fn]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([image event fn context once]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn reset-flip
"Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.resetFlip image))))
(defn reset-pipeline
"Resets the WebGL Pipeline of this Game Object back to the default it was created with.
Returns: boolean - `true` if the pipeline was set successfully, otherwise `false`."
([image]
(phaser->clj
(.resetPipeline image))))
(defn set-acceleration
"Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal acceleration
* y (number) {optional} - The vertical acceleration
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setAcceleration image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setAcceleration image
(clj->phaser x)
(clj->phaser y)))))
(defn set-acceleration-x
"Sets the body's horizontal acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The horizontal acceleration
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAccelerationX image
(clj->phaser value)))))
(defn set-acceleration-y
"Sets the body's vertical acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The vertical acceleration
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAccelerationY image
(clj->phaser value)))))
(defn set-active
"Sets the `active` property of this Game Object and returns this Game Object for further chaining.
A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - True if this Game Object should be set as active, false if not.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setActive image
(clj->phaser value)))))
(defn set-alpha
"Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders.
Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque.
If your game is running under WebGL you can optionally specify four different alpha values, each of which
correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (number) {optional} - The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object.
* top-right (number) {optional} - The alpha value used for the top-right of the Game Object. WebGL only.
* bottom-left (number) {optional} - The alpha value used for the bottom-left of the Game Object. WebGL only.
* bottom-right (number) {optional} - The alpha value used for the bottom-right of the Game Object. WebGL only.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setAlpha image)))
([image top-left]
(phaser->clj
(.setAlpha image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-angle
"Sets the angle of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* degrees (number) {optional} - The rotation of this Game Object, in degrees.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setAngle image)))
([image degrees]
(phaser->clj
(.setAngle image
(clj->phaser degrees)))))
(defn set-angular-acceleration
"Sets the angular acceleration of the body.
In Arcade Physics, bodies cannot rotate. They are always axis-aligned.
However, they can have angular motion, which is passed on to the Game Object bound to the body,
causing them to visually rotate, even though the body remains axis-aligned.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of angular acceleration.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularAcceleration image
(clj->phaser value)))))
(defn set-angular-drag
"Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of drag.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularDrag image
(clj->phaser value)))))
(defn set-angular-velocity
"Sets the angular velocity of the body.
In Arcade Physics, bodies cannot rotate. They are always axis-aligned.
However, they can have angular motion, which is passed on to the Game Object bound to the body,
causing them to visually rotate, even though the body remains axis-aligned.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of angular velocity.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularVelocity image
(clj->phaser value)))))
(defn set-blend-mode
"Sets the Blend Mode being used by this Game Object.
This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay)
Under WebGL only the following Blend Modes are available:
* ADD
* MULTIPLY
* SCREEN
* ERASE (only works when rendering to a framebuffer, like a Render Texture)
Canvas has more available depending on browser support.
You can also create your own custom Blend Modes in WebGL.
Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending
on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these
reasons try to be careful about the construction of your Scene and the frequency in which blend modes
are used.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (string | Phaser.BlendModes) - The BlendMode value. Either a string or a CONST.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setBlendMode image
(clj->phaser value)))))
(defn set-bounce
"Sets the bounce values of this body.
Bounce is the amount of restitution, or elasticity, the body has when it collides with another object.
A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1.
* y (number) {optional} - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setBounce image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setBounce image
(clj->phaser x)
(clj->phaser y)))))
(defn set-bounce-x
"Sets the horizontal bounce value for this body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setBounceX image
(clj->phaser value)))))
(defn set-bounce-y
"Sets the vertical bounce value for this body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setBounceY image
(clj->phaser value)))))
(defn set-circle
"Sets this physics body to use a circle for collision instead of a rectangle.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* radius (number) - The radius of the physics body, in pixels.
* offset-x (number) {optional} - The amount to offset the body from the parent Game Object along the x-axis.
* offset-y (number) {optional} - The amount to offset the body from the parent Game Object along the y-axis.
Returns: this - This Game Object."
([image radius]
(phaser->clj
(.setCircle image
(clj->phaser radius))))
([image radius offset-x]
(phaser->clj
(.setCircle image
(clj->phaser radius)
(clj->phaser offset-x))))
([image radius offset-x offset-y]
(phaser->clj
(.setCircle image
(clj->phaser radius)
(clj->phaser offset-x)
(clj->phaser offset-y)))))
(defn set-collide-world-bounds
"Sets whether this Body collides with the world boundary.
Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Vec2 first.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) {optional} - `true` if this body should collide with the world bounds, otherwise `false`.
* bounce-x (number) {optional} - If given this will be replace the `worldBounce.x` value.
* bounce-y (number) {optional} - If given this will be replace the `worldBounce.y` value.
Returns: this - This Game Object."
([image]
(phaser->clj
(.setCollideWorldBounds image)))
([image value]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value))))
([image value bounce-x]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value)
(clj->phaser bounce-x))))
([image value bounce-x bounce-y]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value)
(clj->phaser bounce-x)
(clj->phaser bounce-y)))))
(defn set-crop
"Applies a crop to a texture based Game Object, such as a Sprite or Image.
The crop is a rectangle that limits the area of the texture frame that is visible during rendering.
Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just
changes what is shown when rendered.
The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left.
Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left
half of it, you could call `setCrop(0, 0, 400, 600)`.
It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop
an area of 200x100 when applied to a Game Object that had a scale factor of 2.
You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument.
Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`.
You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow
the renderer to skip several internal calculations.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number | Phaser.Geom.Rectangle) {optional} - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored.
* y (number) {optional} - The y coordinate to start the crop from.
* width (number) {optional} - The width of the crop rectangle in pixels.
* height (number) {optional} - The height of the crop rectangle in pixels.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setCrop image)))
([image x]
(phaser->clj
(.setCrop image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y))))
([image x y width]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([image x y width height]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-damping
"If this Body is using `drag` for deceleration this function controls how the drag is applied.
If set to `true` drag will use a damping effect rather than a linear approach. If you are
creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in
the game Asteroids) then you will get a far smoother and more visually correct deceleration
by using damping, avoiding the axis-drift that is prone with linear deceleration.
If you enable this property then you should use far smaller `drag` values than with linear, as
they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow
deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - `true` to use damping for deceleration, or `false` to use linear deceleration.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDamping image
(clj->phaser value)))))
(defn set-data
"Allows you to store a key value pair within this Game Objects Data Manager.
If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled
before setting the value.
If the key doesn't already exist in the Data Manager then it is created.
```javascript
sprite.setData('name', 'Red Gem Stone');
```
You can also pass in an object of key value pairs as the first argument:
```javascript
sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 });
```
To get a value back again you can call `getData`:
```javascript
sprite.getData('gold');
```
Or you can access the value directly via the `values` property, where it works like any other variable:
```javascript
sprite.data.values.gold += 50;
```
When the value is first set, a `setdata` event is emitted from this Game Object.
If the key already exists, a `changedata` event is emitted instead, along an event named after the key.
For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`.
These events will be emitted regardless if you use this method to set the value, or the direct `values` setter.
Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string | object) - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored.
* data (*) {optional} - The value to set for the given key. If an object is provided as the key this argument is ignored.
Returns: this - This GameObject."
([image key]
(phaser->clj
(.setData image
(clj->phaser key))))
([image key data]
(phaser->clj
(.setData image
(clj->phaser key)
(clj->phaser data)))))
(defn set-data-enabled
"Adds a Data Manager component to this Game Object.
Returns: this - This GameObject."
([image]
(phaser->clj
(.setDataEnabled image))))
(defn set-debug
"Sets the debug values of this body.
Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole.
Note that there is a performance cost in drawing debug displays. It should never be used in production.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* show-body (boolean) - Set to `true` to have this body render its outline to the debug display.
* show-velocity (boolean) - Set to `true` to have this body render a velocity marker to the debug display.
* body-color (number) - The color of the body outline when rendered to the debug display.
Returns: this - This Game Object."
([image show-body show-velocity body-color]
(phaser->clj
(.setDebug image
(clj->phaser show-body)
(clj->phaser show-velocity)
(clj->phaser body-color)))))
(defn set-debug-body-color
"Sets the color of the body outline when it renders to the debug display.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The color of the body outline when rendered to the debug display.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDebugBodyColor image
(clj->phaser value)))))
(defn set-depth
"The depth of this Game Object within the Scene.
The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order
of Game Objects, without actually moving their position in the display list.
The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth
value will always render in front of one with a lower value.
Setting the depth will queue a depth sort event within the Scene.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (integer) - The depth of this Game Object.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setDepth image
(clj->phaser value)))))
(defn set-display-origin
"Sets the display origin of this Game Object.
The difference between this and setting the origin is that you can use pixel values for setting the display origin.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The horizontal display origin value.
* y (number) {optional} - The vertical display origin value. If not defined it will be set to the value of `x`.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setDisplayOrigin image)))
([image x]
(phaser->clj
(.setDisplayOrigin image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setDisplayOrigin image
(clj->phaser x)
(clj->phaser y)))))
(defn set-display-size
"Sets the display size of this Game Object.
Calling this will adjust the scale.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* width (number) - The width of this Game Object.
* height (number) - The height of this Game Object.
Returns: this - This Game Object instance."
([image width height]
(phaser->clj
(.setDisplaySize image
(clj->phaser width)
(clj->phaser height)))))
(defn set-drag
"Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal drag to apply.
* y (number) {optional} - The amount of vertical drag to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setDrag image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setDrag image
(clj->phaser x)
(clj->phaser y)))))
(defn set-drag-x
"Sets the body's horizontal drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of horizontal drag to apply.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDragX image
(clj->phaser value)))))
(defn set-drag-y
"Sets the body's vertical drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of vertical drag to apply.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDragY image
(clj->phaser value)))))
(defn set-flip
"Sets the horizontal and vertical flipped state of this Game Object.
A Game Object that is flipped will render inversed on the flipped axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (boolean) - The horizontal flipped state. `false` for no flip, or `true` to be flipped.
* y (boolean) - The horizontal flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image x y]
(phaser->clj
(.setFlip image
(clj->phaser x)
(clj->phaser y)))))
(defn set-flip-x
"Sets the horizontal flipped state of this Game Object.
A Game Object that is flipped horizontally will render inversed on the horizontal axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setFlipX image
(clj->phaser value)))))
(defn set-flip-y
"Sets the vertical flipped state of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setFlipY image
(clj->phaser value)))))
(defn set-frame
"Sets the frame this Game Object will use to render with.
The Frame has to belong to the current Texture being used.
It can be either a string or an index.
Calling `setFrame` will modify the `width` and `height` properties of your Game Object.
It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* frame (string | integer) - The name or index of the frame within the Texture.
* update-size (boolean) {optional} - Should this call adjust the size of the Game Object?
* update-origin (boolean) {optional} - Should this call adjust the origin of the Game Object?
Returns: this - This Game Object instance."
([image frame]
(phaser->clj
(.setFrame image
(clj->phaser frame))))
([image frame update-size]
(phaser->clj
(.setFrame image
(clj->phaser frame)
(clj->phaser update-size))))
([image frame update-size update-origin]
(phaser->clj
(.setFrame image
(clj->phaser frame)
(clj->phaser update-size)
(clj->phaser update-origin)))))
(defn set-friction
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal friction to apply.
* y (number) {optional} - The amount of vertical friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFriction image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setFriction image
(clj->phaser x)
(clj->phaser y)))))
(defn set-friction-x
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFrictionX image
(clj->phaser x)))))
(defn set-friction-y
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFrictionY image
(clj->phaser x)))))
(defn set-gravity
"Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect.
If only one value is provided, this value will be used for both the X and Y axis.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The gravitational force to be applied to the X-axis.
* y (number) {optional} - The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setGravity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setGravity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-gravity-x
"Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The gravitational force to be applied to the X-axis.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setGravityX image
(clj->phaser x)))))
(defn set-gravity-y
"Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* y (number) - The gravitational force to be applied to the Y-axis.
Returns: this - This Game Object."
([image y]
(phaser->clj
(.setGravityY image
(clj->phaser y)))))
(defn set-immovable
"Sets Whether this Body can be moved by collisions with another Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) {optional} - Sets if this body can be moved by collisions with another Body.
Returns: this - This Game Object."
([image]
(phaser->clj
(.setImmovable image)))
([image value]
(phaser->clj
(.setImmovable image
(clj->phaser value)))))
(defn set-interactive
"Pass this Game Object to the Input Manager to enable it for Input.
Input works by using hit areas, these are nearly always geometric shapes, such as rectangles or circles, that act as the hit area
for the Game Object. However, you can provide your own hit area shape and callback, should you wish to handle some more advanced
input detection.
If no arguments are provided it will try and create a rectangle hit area based on the texture frame the Game Object is using. If
this isn't a texture-bound object, such as a Graphics or BitmapText object, this will fail, and you'll need to provide a specific
shape for it to use.
You can also provide an Input Configuration Object as the only argument to this method.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* shape (Phaser.Types.Input.InputConfiguration | any) {optional} - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not specified a Rectangle will be used.
* callback (Phaser.Types.Input.HitAreaCallback) {optional} - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback.
* drop-zone (boolean) {optional} - Should this Game Object be treated as a drop zone target?
Returns: this - This GameObject."
([image]
(phaser->clj
(.setInteractive image)))
([image shape]
(phaser->clj
(.setInteractive image
(clj->phaser shape))))
([image shape callback]
(phaser->clj
(.setInteractive image
(clj->phaser shape)
(clj->phaser callback))))
([image shape callback drop-zone]
(phaser->clj
(.setInteractive image
(clj->phaser shape)
(clj->phaser callback)
(clj->phaser drop-zone)))))
(defn set-mask
"Sets the mask that this Game Object will use to render with.
The mask must have been previously created and can be either a GeometryMask or a BitmapMask.
Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas.
If a mask is already set on this Game Object it will be immediately replaced.
Masks are positioned in global space and are not relative to the Game Object to which they
are applied. The reason for this is that multiple Game Objects can all share the same mask.
Masks have no impact on physics or input detection. They are purely a rendering component
that allows you to limit what is visible during the render pass.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* mask (Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask) - The mask this Game Object will use when rendering.
Returns: this - This Game Object instance."
([image mask]
(phaser->clj
(.setMask image
(clj->phaser mask)))))
(defn set-mass
"Sets the mass of the physics body
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - New value for the mass of the body.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setMass image
(clj->phaser value)))))
(defn set-max-velocity
"Sets the maximum velocity of the body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The new maximum horizontal velocity.
* y (number) {optional} - The new maximum vertical velocity.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setMaxVelocity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setMaxVelocity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-name
"Sets the `name` property of this Game Object and returns this Game Object for further chaining.
The `name` property is not populated by Phaser and is presented for your own use.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (string) - The name to be given to this Game Object.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setName image
(clj->phaser value)))))
(defn set-offset
"Sets the body offset. This allows you to adjust the difference between the center of the body
and the x and y coordinates of the parent Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount to offset the body from the parent Game Object along the x-axis.
* y (number) {optional} - The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setOffset image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setOffset image
(clj->phaser x)
(clj->phaser y)))))
(defn set-origin
"Sets the origin of this Game Object.
The values are given in the range 0 to 1.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The horizontal origin value.
* y (number) {optional} - The vertical origin value. If not defined it will be set to the value of `x`.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setOrigin image)))
([image x]
(phaser->clj
(.setOrigin image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setOrigin image
(clj->phaser x)
(clj->phaser y)))))
(defn set-origin-from-frame
"Sets the origin of this Game Object based on the Pivot values in its Frame.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setOriginFromFrame image))))
(defn set-pipeline
"Sets the active WebGL Pipeline of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* pipeline-name (string) - The name of the pipeline to set on this Game Object.
Returns: this - This Game Object instance."
([image pipeline-name]
(phaser->clj
(.setPipeline image
(clj->phaser pipeline-name)))))
(defn set-position
"Sets the position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The x position of this Game Object.
* y (number) {optional} - The y position of this Game Object. If not set it will use the `x` value.
* z (number) {optional} - The z position of this Game Object.
* w (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setPosition image)))
([image x]
(phaser->clj
(.setPosition image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y))))
([image x y z]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser z))))
([image x y z w]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser z)
(clj->phaser w)))))
(defn set-random-position
"Sets the position of this Game Object to be a random position within the confines of
the given area.
If no area is specified a random position between 0 x 0 and the game width x height is used instead.
The position does not factor in the size of this Game Object, meaning that only the origin is
guaranteed to be within the area.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The x position of the top-left of the random area.
* y (number) {optional} - The y position of the top-left of the random area.
* width (number) {optional} - The width of the random area.
* height (number) {optional} - The height of the random area.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setRandomPosition image)))
([image x]
(phaser->clj
(.setRandomPosition image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y))))
([image x y width]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([image x y width height]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-rotation
"Sets the rotation of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* radians (number) {optional} - The rotation of this Game Object, in radians.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setRotation image)))
([image radians]
(phaser->clj
(.setRotation image
(clj->phaser radians)))))
(defn set-scale
"Sets the scale of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal scale of this Game Object.
* y (number) {optional} - The vertical scale of this Game Object. If not set it will use the `x` value.
Returns: this - This Game Object instance."
([image x]
(phaser->clj
(.setScale image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setScale image
(clj->phaser x)
(clj->phaser y)))))
(defn set-scroll-factor
"Sets the scroll factor of this Game Object.
The scroll factor controls the influence of the movement of a Camera upon this Game Object.
When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
It does not change the Game Objects actual position values.
A value of 1 means it will move exactly in sync with a camera.
A value of 0 means it will not move at all, even if the camera moves.
Other values control the degree to which the camera movement is mapped to this Game Object.
Please be aware that scroll factor values other than 1 are not taken in to consideration when
calculating physics collisions. Bodies always collide based on their world position, but changing
the scroll factor is a visual adjustment to where the textures are rendered, which can offset
them from physics bodies if not accounted for in your code.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal scroll factor of this Game Object.
* y (number) {optional} - The vertical scroll factor of this Game Object. If not set it will use the `x` value.
Returns: this - This Game Object instance."
([image x]
(phaser->clj
(.setScrollFactor image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setScrollFactor image
(clj->phaser x)
(clj->phaser y)))))
(defn set-size
"Sets the internal size of this Game Object, as used for frame or physics body creation.
This will not change the size that the Game Object is rendered in-game.
For that you need to either set the scale of the Game Object (`setScale`) or call the
`setDisplaySize` method, which is the same thing as changing the scale but allows you
to do so by giving pixel values.
If you have enabled this Game Object for input, changing the size will _not_ change the
size of the hit area. To do this you should adjust the `input.hitArea` object directly.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* width (number) - The width of this Game Object.
* height (number) - The height of this Game Object.
Returns: this - This Game Object instance."
([image width height]
(phaser->clj
(.setSize image
(clj->phaser width)
(clj->phaser height)))))
(defn set-size-to-frame
"Sets the size of this Game Object to be that of the given Frame.
This will not change the size that the Game Object is rendered in-game.
For that you need to either set the scale of the Game Object (`setScale`) or call the
`setDisplaySize` method, which is the same thing as changing the scale but allows you
to do so by giving pixel values.
If you have enabled this Game Object for input, changing the size will _not_ change the
size of the hit area. To do this you should adjust the `input.hitArea` object directly.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* frame (Phaser.Textures.Frame) - The frame to base the size of this Game Object on.
Returns: this - This Game Object instance."
([image frame]
(phaser->clj
(.setSizeToFrame image
(clj->phaser frame)))))
(defn set-state
"Sets the current state of this Game Object.
Phaser itself will never modify the State of a Game Object, although plugins may do so.
For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'.
The state value should typically be an integer (ideally mapped to a constant
in your game code), but could also be a string. It is recommended to keep it light and simple.
If you need to store complex data about your Game Object, look at using the Data Component instead.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (integer | string) - The state of the Game Object.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setState image
(clj->phaser value)))))
(defn set-texture
"Sets the texture and frame this Game Object will use to render with.
Textures are referenced by their string-based keys, as stored in the Texture Manager.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string) - The key of the texture to be used, as stored in the Texture Manager.
* frame (string | integer) {optional} - The name or index of the frame within the Texture.
Returns: this - This Game Object instance."
([image key]
(phaser->clj
(.setTexture image
(clj->phaser key))))
([image key frame]
(phaser->clj
(.setTexture image
(clj->phaser key)
(clj->phaser frame)))))
(defn set-tint
"Sets an additive tint on this Game Object.
The tint works by taking the pixel color values from the Game Objects texture, and then
multiplying it by the color value of the tint. You can provide either one color value,
in which case the whole Game Object will be tinted in that color. Or you can provide a color
per corner. The colors are blended together across the extent of the Game Object.
To modify the tint color once set, either call this method again with new values or use the
`tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight,
`tintBottomLeft` and `tintBottomRight` to set the corner color values independently.
To remove a tint call `clearTint`.
To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (integer) {optional} - The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object.
* top-right (integer) {optional} - The tint being applied to the top-right of the Game Object.
* bottom-left (integer) {optional} - The tint being applied to the bottom-left of the Game Object.
* bottom-right (integer) {optional} - The tint being applied to the bottom-right of the Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setTint image)))
([image top-left]
(phaser->clj
(.setTint image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-tint-fill
"Sets a fill-based tint on this Game Object.
Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture
with those in the tint. You can use this for effects such as making a player flash 'white'
if hit by something. You can provide either one color value, in which case the whole
Game Object will be rendered in that color. Or you can provide a color per corner. The colors
are blended together across the extent of the Game Object.
To modify the tint color once set, either call this method again with new values or use the
`tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight,
`tintBottomLeft` and `tintBottomRight` to set the corner color values independently.
To remove a tint call `clearTint`.
To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (integer) {optional} - The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object.
* top-right (integer) {optional} - The tint being applied to the top-right of the Game Object.
* bottom-left (integer) {optional} - The tint being applied to the bottom-left of the Game Object.
* bottom-right (integer) {optional} - The tint being applied to the bottom-right of the Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setTintFill image)))
([image top-left]
(phaser->clj
(.setTintFill image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-velocity
"Sets the velocity of the Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left.
* y (number) {optional} - The vertical velocity of the body. Positive values move the body down, while negative values move it up.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setVelocity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setVelocity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-velocity-x
"Sets the horizontal component of the body's velocity.
Positive values move the body to the right, while negative values move it to the left.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The new horizontal velocity.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setVelocityX image
(clj->phaser x)))))
(defn set-velocity-y
"Sets the vertical component of the body's velocity.
Positive values move the body down, while negative values move it up.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* y (number) - The new vertical velocity of the body.
Returns: this - This Game Object."
([image y]
(phaser->clj
(.setVelocityY image
(clj->phaser y)))))
(defn set-visible
"Sets the visibility of this Game Object.
An invisible Game Object will skip rendering, but will still process update logic.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The visible state of the Game Object.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setVisible image
(clj->phaser value)))))
(defn set-w
"Sets the w position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setW image)))
([image value]
(phaser->clj
(.setW image
(clj->phaser value)))))
(defn set-x
"Sets the x position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The x position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setX image)))
([image value]
(phaser->clj
(.setX image
(clj->phaser value)))))
(defn set-y
"Sets the y position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The y position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setY image)))
([image value]
(phaser->clj
(.setY image
(clj->phaser value)))))
(defn set-z
"Sets the z position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The z position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setZ image)))
([image value]
(phaser->clj
(.setZ image
(clj->phaser value)))))
(defn shutdown
"Removes all listeners."
([image]
(phaser->clj
(.shutdown image))))
(defn to-json
"Returns a JSON representation of the Game Object.
Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object."
([image]
(phaser->clj
(.toJSON image))))
(defn toggle-flip-x
"Toggles the horizontal flipped state of this Game Object.
A Game Object that is flipped horizontally will render inversed on the horizontal axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.toggleFlipX image))))
(defn toggle-flip-y
"Toggles the vertical flipped state of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.toggleFlipY image))))
(defn update
"To be overridden by custom GameObjects. Allows base objects to be used in a Pool.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* args (*) {optional} - args"
([image]
(phaser->clj
(.update image)))
([image args]
(phaser->clj
(.update image
(clj->phaser args)))))
(defn update-display-origin
"Updates the Display Origin cached values internally stored on this Game Object.
You don't usually call this directly, but it is exposed for edge-cases where you may.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.updateDisplayOrigin image))))
(defn will-render
"Compares the renderMask with the renderFlags to see if this Game Object will render or not.
Also checks the Game Object against the given Cameras exclusion list.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* camera (Phaser.Cameras.Scene2D.Camera) - The Camera to check against this Game Object.
Returns: boolean - True if the Game Object should be rendered, otherwise false."
([image camera]
(phaser->clj
(.willRender image
(clj->phaser camera)))))
|
90626
|
(ns phzr.physics.arcade.image
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [update]))
(defn ->Image
" Parameters:
* scene (Phaser.Scene) - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
* x (number) - The horizontal position of this Game Object in the world.
* y (number) - The vertical position of this Game Object in the world.
* texture (string) - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager.
* frame (string | integer) {optional} - An optional frame from the Texture this Game Object is rendering with."
([scene x y texture]
(js/Phaser.Physics.Arcade.Image. (clj->phaser scene)
(clj->phaser x)
(clj->phaser y)
(clj->phaser texture)))
([scene x y texture frame]
(js/Phaser.Physics.Arcade.Image. (clj->phaser scene)
(clj->phaser x)
(clj->phaser y)
(clj->phaser texture)
(clj->phaser frame))))
(defn add-listener
"Add a listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.addListener image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.addListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn clear-alpha
"Clears all alpha values associated with this Game Object.
Immediately sets the alpha levels back to 1 (fully opaque).
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearAlpha image))))
(defn clear-mask
"Clears the mask that this Game Object was using.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* destroy-mask (boolean) {optional} - Destroy the mask before clearing it?
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearMask image)))
([image destroy-mask]
(phaser->clj
(.clearMask image
(clj->phaser destroy-mask)))))
(defn clear-tint
"Clears all tint values associated with this Game Object.
Immediately sets the color values back to 0xffffff and the tint type to 'additive',
which results in no visible change to the texture.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearTint image))))
(defn create-bitmap-mask
"Creates and returns a Bitmap Mask. This mask can be used by any Game Object,
including this one.
To create the mask you need to pass in a reference to a renderable Game Object.
A renderable Game Object is one that uses a texture to render with, such as an
Image, Sprite, Render Texture or BitmapText.
If you do not provide a renderable object, and this Game Object has a texture,
it will use itself as the object. This means you can call this method to create
a Bitmap Mask from any renderable Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* renderable (Phaser.GameObjects.GameObject) {optional} - A renderable Game Object that uses a texture, such as a Sprite.
Returns: Phaser.Display.Masks.BitmapMask - This Bitmap Mask that was created."
([image]
(phaser->clj
(.createBitmapMask image)))
([image renderable]
(phaser->clj
(.createBitmapMask image
(clj->phaser renderable)))))
(defn create-geometry-mask
"Creates and returns a Geometry Mask. This mask can be used by any Game Object,
including this one.
To create the mask you need to pass in a reference to a Graphics Game Object.
If you do not provide a graphics object, and this Game Object is an instance
of a Graphics object, then it will use itself to create the mask.
This means you can call this method to create a Geometry Mask from any Graphics Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* graphics (Phaser.GameObjects.Graphics) {optional} - A Graphics Game Object. The geometry within it will be used as the mask.
Returns: Phaser.Display.Masks.GeometryMask - This Geometry Mask that was created."
([image]
(phaser->clj
(.createGeometryMask image)))
([image graphics]
(phaser->clj
(.createGeometryMask image
(clj->phaser graphics)))))
(defn destroy
"Destroys this Game Object removing it from the Display List and Update List and
severing all ties to parent resources.
Also removes itself from the Input Manager and Physics Manager if previously enabled.
Use this to remove a Game Object from your game if you don't ever plan to use it again.
As long as no reference to it exists within your own code it should become free for
garbage collection by the browser.
If you just want to temporarily disable an object then look at using the
Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?"
([image]
(phaser->clj
(.destroy image)))
([image from-scene]
(phaser->clj
(.destroy image
(clj->phaser from-scene)))))
(defn disable-body
"Stops and disables this Game Object's Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* disable-game-object (boolean) {optional} - Also deactivate this Game Object.
* hide-game-object (boolean) {optional} - Also hide this Game Object.
Returns: this - This Game Object."
([image]
(phaser->clj
(.disableBody image)))
([image disable-game-object]
(phaser->clj
(.disableBody image
(clj->phaser disable-game-object))))
([image disable-game-object hide-game-object]
(phaser->clj
(.disableBody image
(clj->phaser disable-game-object)
(clj->phaser hide-game-object)))))
(defn disable-interactive
"If this Game Object has previously been enabled for input, this will disable it.
An object that is disabled for input stops processing or being considered for
input events, but can be turned back on again at any time by simply calling
`setInteractive()` with no arguments provided.
If want to completely remove interaction from this Game Object then use `removeInteractive` instead.
Returns: this - This GameObject."
([image]
(phaser->clj
(.disableInteractive image))))
(defn emit
"Calls each of the listeners registered for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* args (*) {optional} - Additional arguments that will be passed to the event handler.
Returns: boolean - `true` if the event had listeners, else `false`."
([image event]
(phaser->clj
(.emit image
(clj->phaser event))))
([image event args]
(phaser->clj
(.emit image
(clj->phaser event)
(clj->phaser args)))))
(defn enable-body
"Enables this Game Object's Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* reset (boolean) - Also reset the Body and place it at (x, y).
* x (number) - The horizontal position to place the Game Object and Body.
* y (number) - The horizontal position to place the Game Object and Body.
* enable-game-object (boolean) - Also activate this Game Object.
* show-game-object (boolean) - Also show this Game Object.
Returns: this - This Game Object."
([image reset x y enable-game-object show-game-object]
(phaser->clj
(.enableBody image
(clj->phaser reset)
(clj->phaser x)
(clj->phaser y)
(clj->phaser enable-game-object)
(clj->phaser show-game-object)))))
(defn event-names
"Return an array listing the events for which the emitter has registered listeners.
Returns: array - "
([image]
(phaser->clj
(.eventNames image))))
(defn get-bottom-center
"Gets the bottom-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomCenter image)))
([image output]
(phaser->clj
(.getBottomCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bottom-left
"Gets the bottom-left corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomLeft image)))
([image output]
(phaser->clj
(.getBottomLeft image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomLeft image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bottom-right
"Gets the bottom-right corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomRight image)))
([image output]
(phaser->clj
(.getBottomRight image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomRight image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bounds
"Gets the bounds of this Game Object, regardless of origin.
The values are stored and returned in a Rectangle, or Rectangle-like, object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Geom.Rectangle | object) {optional} - An object to store the values in. If not provided a new Rectangle will be created.
Returns: Phaser.Geom.Rectangle | object - The values stored in the output object."
([image]
(phaser->clj
(.getBounds image)))
([image output]
(phaser->clj
(.getBounds image
(clj->phaser output)))))
(defn get-center
"Gets the center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getCenter image)))
([image output]
(phaser->clj
(.getCenter image
(clj->phaser output)))))
(defn get-data
"Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist.
You can also access values via the `values` object. For example, if you had a key called `gold` you can do either:
```javascript
sprite.getData('gold');
```
Or access the value directly:
```javascript
sprite.data.values.gold;
```
You can also pass in an array of keys, in which case an array of values will be returned:
```javascript
sprite.getData([ 'gold', 'armor', 'health' ]);
```
This approach is useful for destructuring arrays in ES6.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string | Array.<string>) - The key of the value to retrieve, or an array of keys.
Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array."
([image key]
(phaser->clj
(.getData image
(clj->phaser key)))))
(defn get-index-list
"Returns an array containing the display list index of either this Game Object, or if it has one,
its parent Container. It then iterates up through all of the parent containers until it hits the
root of the display list (which is index 0 in the returned array).
Used internally by the InputPlugin but also useful if you wish to find out the display depth of
this Game Object and all of its ancestors.
Returns: Array.<integer> - An array of display list position indexes."
([image]
(phaser->clj
(.getIndexList image))))
(defn get-left-center
"Gets the left-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getLeftCenter image)))
([image output]
(phaser->clj
(.getLeftCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getLeftCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-local-transform-matrix
"Gets the local transform matrix for this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* temp-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - The matrix to populate with the values from this Game Object.
Returns: Phaser.GameObjects.Components.TransformMatrix - The populated Transform Matrix."
([image]
(phaser->clj
(.getLocalTransformMatrix image)))
([image temp-matrix]
(phaser->clj
(.getLocalTransformMatrix image
(clj->phaser temp-matrix)))))
(defn get-parent-rotation
"Gets the sum total rotation of all of this Game Objects parent Containers.
The returned value is in radians and will be zero if this Game Object has no parent container.
Returns: number - The sum total rotation, in radians, of all parent containers of this Game Object."
([image]
(phaser->clj
(.getParentRotation image))))
(defn get-pipeline-name
"Gets the name of the WebGL Pipeline this Game Object is currently using.
Returns: string - The string-based name of the pipeline being used by this Game Object."
([image]
(phaser->clj
(.getPipelineName image))))
(defn get-right-center
"Gets the right-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getRightCenter image)))
([image output]
(phaser->clj
(.getRightCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getRightCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-center
"Gets the top-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopCenter image)))
([image output]
(phaser->clj
(.getTopCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-left
"Gets the top-left corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopLeft image)))
([image output]
(phaser->clj
(.getTopLeft image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopLeft image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-right
"Gets the top-right corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopRight image)))
([image output]
(phaser->clj
(.getTopRight image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopRight image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-world-transform-matrix
"Gets the world transform matrix for this Game Object, factoring in any parent Containers.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* temp-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - The matrix to populate with the values from this Game Object.
* parent-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - A temporary matrix to hold parent values during the calculations.
Returns: Phaser.GameObjects.Components.TransformMatrix - The populated Transform Matrix."
([image]
(phaser->clj
(.getWorldTransformMatrix image)))
([image temp-matrix]
(phaser->clj
(.getWorldTransformMatrix image
(clj->phaser temp-matrix))))
([image temp-matrix parent-matrix]
(phaser->clj
(.getWorldTransformMatrix image
(clj->phaser temp-matrix)
(clj->phaser parent-matrix)))))
(defn init-pipeline
"Sets the initial WebGL Pipeline of this Game Object.
This should only be called during the instantiation of the Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* pipeline-name (string) {optional} - The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline.
Returns: boolean - `true` if the pipeline was set successfully, otherwise `false`."
([image]
(phaser->clj
(.initPipeline image)))
([image pipeline-name]
(phaser->clj
(.initPipeline image
(clj->phaser pipeline-name)))))
(defn listener-count
"Return the number of listeners listening to a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: number - The number of listeners."
([image event]
(phaser->clj
(.listenerCount image
(clj->phaser event)))))
(defn listeners
"Return the listeners registered for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: array - The registered listeners."
([image event]
(phaser->clj
(.listeners image
(clj->phaser event)))))
(defn off
"Remove the listeners of a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) {optional} - Only remove the listeners that match this function.
* context (*) {optional} - Only remove the listeners that have this context.
* once (boolean) {optional} - Only remove one-time listeners.
Returns: Phaser.Events.EventEmitter - `this`."
([image event]
(phaser->clj
(.off image
(clj->phaser event))))
([image event fn]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([image event fn context once]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn on
"Add a listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.on image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.on image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn once
"Add a one-time listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.once image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.once image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn refresh-body
"Syncs the Body's position and size with its parent Game Object.
You don't need to call this for Dynamic Bodies, as it happens automatically.
But for Static bodies it's a useful way of modifying the position of a Static Body
in the Physics World, based on its Game Object.
Returns: this - This Game Object."
([image]
(phaser->clj
(.refreshBody image))))
(defn remove-all-listeners
"Remove all listeners, or those of the specified event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) {optional} - The event name.
Returns: Phaser.Events.EventEmitter - `this`."
([image]
(phaser->clj
(.removeAllListeners image)))
([image event]
(phaser->clj
(.removeAllListeners image
(clj->phaser event)))))
(defn remove-interactive
"If this Game Object has previously been enabled for input, this will queue it
for removal, causing it to no longer be interactive. The removal happens on
the next game step, it is not immediate.
The Interactive Object that was assigned to this Game Object will be destroyed,
removed from the Input Manager and cleared from this Game Object.
If you wish to re-enable this Game Object at a later date you will need to
re-create its InteractiveObject by calling `setInteractive` again.
If you wish to only temporarily stop an object from receiving input then use
`disableInteractive` instead, as that toggles the interactive state, where-as
this erases it completely.
If you wish to resize a hit area, don't remove and then set it as being
interactive. Instead, access the hitarea object directly and resize the shape
being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the
shape is a Rectangle, which it is by default.)
Returns: this - This GameObject."
([image]
(phaser->clj
(.removeInteractive image))))
(defn remove-listener
"Remove the listeners of a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) {optional} - Only remove the listeners that match this function.
* context (*) {optional} - Only remove the listeners that have this context.
* once (boolean) {optional} - Only remove one-time listeners.
Returns: Phaser.Events.EventEmitter - `this`."
([image event]
(phaser->clj
(.removeListener image
(clj->phaser event))))
([image event fn]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([image event fn context once]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn reset-flip
"Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.resetFlip image))))
(defn reset-pipeline
"Resets the WebGL Pipeline of this Game Object back to the default it was created with.
Returns: boolean - `true` if the pipeline was set successfully, otherwise `false`."
([image]
(phaser->clj
(.resetPipeline image))))
(defn set-acceleration
"Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal acceleration
* y (number) {optional} - The vertical acceleration
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setAcceleration image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setAcceleration image
(clj->phaser x)
(clj->phaser y)))))
(defn set-acceleration-x
"Sets the body's horizontal acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The horizontal acceleration
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAccelerationX image
(clj->phaser value)))))
(defn set-acceleration-y
"Sets the body's vertical acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The vertical acceleration
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAccelerationY image
(clj->phaser value)))))
(defn set-active
"Sets the `active` property of this Game Object and returns this Game Object for further chaining.
A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - True if this Game Object should be set as active, false if not.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setActive image
(clj->phaser value)))))
(defn set-alpha
"Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders.
Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque.
If your game is running under WebGL you can optionally specify four different alpha values, each of which
correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (number) {optional} - The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object.
* top-right (number) {optional} - The alpha value used for the top-right of the Game Object. WebGL only.
* bottom-left (number) {optional} - The alpha value used for the bottom-left of the Game Object. WebGL only.
* bottom-right (number) {optional} - The alpha value used for the bottom-right of the Game Object. WebGL only.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setAlpha image)))
([image top-left]
(phaser->clj
(.setAlpha image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-angle
"Sets the angle of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* degrees (number) {optional} - The rotation of this Game Object, in degrees.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setAngle image)))
([image degrees]
(phaser->clj
(.setAngle image
(clj->phaser degrees)))))
(defn set-angular-acceleration
"Sets the angular acceleration of the body.
In Arcade Physics, bodies cannot rotate. They are always axis-aligned.
However, they can have angular motion, which is passed on to the Game Object bound to the body,
causing them to visually rotate, even though the body remains axis-aligned.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of angular acceleration.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularAcceleration image
(clj->phaser value)))))
(defn set-angular-drag
"Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of drag.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularDrag image
(clj->phaser value)))))
(defn set-angular-velocity
"Sets the angular velocity of the body.
In Arcade Physics, bodies cannot rotate. They are always axis-aligned.
However, they can have angular motion, which is passed on to the Game Object bound to the body,
causing them to visually rotate, even though the body remains axis-aligned.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of angular velocity.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularVelocity image
(clj->phaser value)))))
(defn set-blend-mode
"Sets the Blend Mode being used by this Game Object.
This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay)
Under WebGL only the following Blend Modes are available:
* ADD
* MULTIPLY
* SCREEN
* ERASE (only works when rendering to a framebuffer, like a Render Texture)
Canvas has more available depending on browser support.
You can also create your own custom Blend Modes in WebGL.
Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending
on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these
reasons try to be careful about the construction of your Scene and the frequency in which blend modes
are used.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (string | Phaser.BlendModes) - The BlendMode value. Either a string or a CONST.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setBlendMode image
(clj->phaser value)))))
(defn set-bounce
"Sets the bounce values of this body.
Bounce is the amount of restitution, or elasticity, the body has when it collides with another object.
A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1.
* y (number) {optional} - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setBounce image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setBounce image
(clj->phaser x)
(clj->phaser y)))))
(defn set-bounce-x
"Sets the horizontal bounce value for this body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setBounceX image
(clj->phaser value)))))
(defn set-bounce-y
"Sets the vertical bounce value for this body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setBounceY image
(clj->phaser value)))))
(defn set-circle
"Sets this physics body to use a circle for collision instead of a rectangle.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* radius (number) - The radius of the physics body, in pixels.
* offset-x (number) {optional} - The amount to offset the body from the parent Game Object along the x-axis.
* offset-y (number) {optional} - The amount to offset the body from the parent Game Object along the y-axis.
Returns: this - This Game Object."
([image radius]
(phaser->clj
(.setCircle image
(clj->phaser radius))))
([image radius offset-x]
(phaser->clj
(.setCircle image
(clj->phaser radius)
(clj->phaser offset-x))))
([image radius offset-x offset-y]
(phaser->clj
(.setCircle image
(clj->phaser radius)
(clj->phaser offset-x)
(clj->phaser offset-y)))))
(defn set-collide-world-bounds
"Sets whether this Body collides with the world boundary.
Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Vec2 first.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) {optional} - `true` if this body should collide with the world bounds, otherwise `false`.
* bounce-x (number) {optional} - If given this will be replace the `worldBounce.x` value.
* bounce-y (number) {optional} - If given this will be replace the `worldBounce.y` value.
Returns: this - This Game Object."
([image]
(phaser->clj
(.setCollideWorldBounds image)))
([image value]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value))))
([image value bounce-x]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value)
(clj->phaser bounce-x))))
([image value bounce-x bounce-y]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value)
(clj->phaser bounce-x)
(clj->phaser bounce-y)))))
(defn set-crop
"Applies a crop to a texture based Game Object, such as a Sprite or Image.
The crop is a rectangle that limits the area of the texture frame that is visible during rendering.
Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just
changes what is shown when rendered.
The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left.
Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left
half of it, you could call `setCrop(0, 0, 400, 600)`.
It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop
an area of 200x100 when applied to a Game Object that had a scale factor of 2.
You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument.
Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`.
You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow
the renderer to skip several internal calculations.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number | Phaser.Geom.Rectangle) {optional} - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored.
* y (number) {optional} - The y coordinate to start the crop from.
* width (number) {optional} - The width of the crop rectangle in pixels.
* height (number) {optional} - The height of the crop rectangle in pixels.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setCrop image)))
([image x]
(phaser->clj
(.setCrop image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y))))
([image x y width]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([image x y width height]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-damping
"If this Body is using `drag` for deceleration this function controls how the drag is applied.
If set to `true` drag will use a damping effect rather than a linear approach. If you are
creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in
the game Asteroids) then you will get a far smoother and more visually correct deceleration
by using damping, avoiding the axis-drift that is prone with linear deceleration.
If you enable this property then you should use far smaller `drag` values than with linear, as
they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow
deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - `true` to use damping for deceleration, or `false` to use linear deceleration.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDamping image
(clj->phaser value)))))
(defn set-data
"Allows you to store a key value pair within this Game Objects Data Manager.
If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled
before setting the value.
If the key doesn't already exist in the Data Manager then it is created.
```javascript
sprite.setData('name', '<NAME> Gem <NAME>');
```
You can also pass in an object of key value pairs as the first argument:
```javascript
sprite.setData({ name: '<NAME>', level: 2, owner: 'Link', gold: 50 });
```
To get a value back again you can call `getData`:
```javascript
sprite.getData('gold');
```
Or you can access the value directly via the `values` property, where it works like any other variable:
```javascript
sprite.data.values.gold += 50;
```
When the value is first set, a `setdata` event is emitted from this Game Object.
If the key already exists, a `changedata` event is emitted instead, along an event named after the key.
For example, if you updated an existing key called `<KEY>` then it would emit the event `changedata-PlayerLives`.
These events will be emitted regardless if you use this method to set the value, or the direct `values` setter.
Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string | object) - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored.
* data (*) {optional} - The value to set for the given key. If an object is provided as the key this argument is ignored.
Returns: this - This GameObject."
([image key]
(phaser->clj
(.setData image
(clj->phaser key))))
([image key data]
(phaser->clj
(.setData image
(clj->phaser key)
(clj->phaser data)))))
(defn set-data-enabled
"Adds a Data Manager component to this Game Object.
Returns: this - This GameObject."
([image]
(phaser->clj
(.setDataEnabled image))))
(defn set-debug
"Sets the debug values of this body.
Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole.
Note that there is a performance cost in drawing debug displays. It should never be used in production.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* show-body (boolean) - Set to `true` to have this body render its outline to the debug display.
* show-velocity (boolean) - Set to `true` to have this body render a velocity marker to the debug display.
* body-color (number) - The color of the body outline when rendered to the debug display.
Returns: this - This Game Object."
([image show-body show-velocity body-color]
(phaser->clj
(.setDebug image
(clj->phaser show-body)
(clj->phaser show-velocity)
(clj->phaser body-color)))))
(defn set-debug-body-color
"Sets the color of the body outline when it renders to the debug display.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The color of the body outline when rendered to the debug display.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDebugBodyColor image
(clj->phaser value)))))
(defn set-depth
"The depth of this Game Object within the Scene.
The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order
of Game Objects, without actually moving their position in the display list.
The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth
value will always render in front of one with a lower value.
Setting the depth will queue a depth sort event within the Scene.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (integer) - The depth of this Game Object.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setDepth image
(clj->phaser value)))))
(defn set-display-origin
"Sets the display origin of this Game Object.
The difference between this and setting the origin is that you can use pixel values for setting the display origin.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The horizontal display origin value.
* y (number) {optional} - The vertical display origin value. If not defined it will be set to the value of `x`.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setDisplayOrigin image)))
([image x]
(phaser->clj
(.setDisplayOrigin image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setDisplayOrigin image
(clj->phaser x)
(clj->phaser y)))))
(defn set-display-size
"Sets the display size of this Game Object.
Calling this will adjust the scale.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* width (number) - The width of this Game Object.
* height (number) - The height of this Game Object.
Returns: this - This Game Object instance."
([image width height]
(phaser->clj
(.setDisplaySize image
(clj->phaser width)
(clj->phaser height)))))
(defn set-drag
"Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal drag to apply.
* y (number) {optional} - The amount of vertical drag to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setDrag image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setDrag image
(clj->phaser x)
(clj->phaser y)))))
(defn set-drag-x
"Sets the body's horizontal drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of horizontal drag to apply.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDragX image
(clj->phaser value)))))
(defn set-drag-y
"Sets the body's vertical drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of vertical drag to apply.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDragY image
(clj->phaser value)))))
(defn set-flip
"Sets the horizontal and vertical flipped state of this Game Object.
A Game Object that is flipped will render inversed on the flipped axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (boolean) - The horizontal flipped state. `false` for no flip, or `true` to be flipped.
* y (boolean) - The horizontal flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image x y]
(phaser->clj
(.setFlip image
(clj->phaser x)
(clj->phaser y)))))
(defn set-flip-x
"Sets the horizontal flipped state of this Game Object.
A Game Object that is flipped horizontally will render inversed on the horizontal axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setFlipX image
(clj->phaser value)))))
(defn set-flip-y
"Sets the vertical flipped state of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setFlipY image
(clj->phaser value)))))
(defn set-frame
"Sets the frame this Game Object will use to render with.
The Frame has to belong to the current Texture being used.
It can be either a string or an index.
Calling `setFrame` will modify the `width` and `height` properties of your Game Object.
It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* frame (string | integer) - The name or index of the frame within the Texture.
* update-size (boolean) {optional} - Should this call adjust the size of the Game Object?
* update-origin (boolean) {optional} - Should this call adjust the origin of the Game Object?
Returns: this - This Game Object instance."
([image frame]
(phaser->clj
(.setFrame image
(clj->phaser frame))))
([image frame update-size]
(phaser->clj
(.setFrame image
(clj->phaser frame)
(clj->phaser update-size))))
([image frame update-size update-origin]
(phaser->clj
(.setFrame image
(clj->phaser frame)
(clj->phaser update-size)
(clj->phaser update-origin)))))
(defn set-friction
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal friction to apply.
* y (number) {optional} - The amount of vertical friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFriction image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setFriction image
(clj->phaser x)
(clj->phaser y)))))
(defn set-friction-x
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFrictionX image
(clj->phaser x)))))
(defn set-friction-y
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFrictionY image
(clj->phaser x)))))
(defn set-gravity
"Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect.
If only one value is provided, this value will be used for both the X and Y axis.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The gravitational force to be applied to the X-axis.
* y (number) {optional} - The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setGravity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setGravity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-gravity-x
"Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The gravitational force to be applied to the X-axis.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setGravityX image
(clj->phaser x)))))
(defn set-gravity-y
"Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* y (number) - The gravitational force to be applied to the Y-axis.
Returns: this - This Game Object."
([image y]
(phaser->clj
(.setGravityY image
(clj->phaser y)))))
(defn set-immovable
"Sets Whether this Body can be moved by collisions with another Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) {optional} - Sets if this body can be moved by collisions with another Body.
Returns: this - This Game Object."
([image]
(phaser->clj
(.setImmovable image)))
([image value]
(phaser->clj
(.setImmovable image
(clj->phaser value)))))
(defn set-interactive
"Pass this Game Object to the Input Manager to enable it for Input.
Input works by using hit areas, these are nearly always geometric shapes, such as rectangles or circles, that act as the hit area
for the Game Object. However, you can provide your own hit area shape and callback, should you wish to handle some more advanced
input detection.
If no arguments are provided it will try and create a rectangle hit area based on the texture frame the Game Object is using. If
this isn't a texture-bound object, such as a Graphics or BitmapText object, this will fail, and you'll need to provide a specific
shape for it to use.
You can also provide an Input Configuration Object as the only argument to this method.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* shape (Phaser.Types.Input.InputConfiguration | any) {optional} - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not specified a Rectangle will be used.
* callback (Phaser.Types.Input.HitAreaCallback) {optional} - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback.
* drop-zone (boolean) {optional} - Should this Game Object be treated as a drop zone target?
Returns: this - This GameObject."
([image]
(phaser->clj
(.setInteractive image)))
([image shape]
(phaser->clj
(.setInteractive image
(clj->phaser shape))))
([image shape callback]
(phaser->clj
(.setInteractive image
(clj->phaser shape)
(clj->phaser callback))))
([image shape callback drop-zone]
(phaser->clj
(.setInteractive image
(clj->phaser shape)
(clj->phaser callback)
(clj->phaser drop-zone)))))
(defn set-mask
"Sets the mask that this Game Object will use to render with.
The mask must have been previously created and can be either a GeometryMask or a BitmapMask.
Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas.
If a mask is already set on this Game Object it will be immediately replaced.
Masks are positioned in global space and are not relative to the Game Object to which they
are applied. The reason for this is that multiple Game Objects can all share the same mask.
Masks have no impact on physics or input detection. They are purely a rendering component
that allows you to limit what is visible during the render pass.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* mask (Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask) - The mask this Game Object will use when rendering.
Returns: this - This Game Object instance."
([image mask]
(phaser->clj
(.setMask image
(clj->phaser mask)))))
(defn set-mass
"Sets the mass of the physics body
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - New value for the mass of the body.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setMass image
(clj->phaser value)))))
(defn set-max-velocity
"Sets the maximum velocity of the body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The new maximum horizontal velocity.
* y (number) {optional} - The new maximum vertical velocity.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setMaxVelocity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setMaxVelocity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-name
"Sets the `name` property of this Game Object and returns this Game Object for further chaining.
The `name` property is not populated by Phaser and is presented for your own use.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (string) - The name to be given to this Game Object.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setName image
(clj->phaser value)))))
(defn set-offset
"Sets the body offset. This allows you to adjust the difference between the center of the body
and the x and y coordinates of the parent Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount to offset the body from the parent Game Object along the x-axis.
* y (number) {optional} - The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setOffset image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setOffset image
(clj->phaser x)
(clj->phaser y)))))
(defn set-origin
"Sets the origin of this Game Object.
The values are given in the range 0 to 1.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The horizontal origin value.
* y (number) {optional} - The vertical origin value. If not defined it will be set to the value of `x`.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setOrigin image)))
([image x]
(phaser->clj
(.setOrigin image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setOrigin image
(clj->phaser x)
(clj->phaser y)))))
(defn set-origin-from-frame
"Sets the origin of this Game Object based on the Pivot values in its Frame.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setOriginFromFrame image))))
(defn set-pipeline
"Sets the active WebGL Pipeline of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* pipeline-name (string) - The name of the pipeline to set on this Game Object.
Returns: this - This Game Object instance."
([image pipeline-name]
(phaser->clj
(.setPipeline image
(clj->phaser pipeline-name)))))
(defn set-position
"Sets the position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The x position of this Game Object.
* y (number) {optional} - The y position of this Game Object. If not set it will use the `x` value.
* z (number) {optional} - The z position of this Game Object.
* w (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setPosition image)))
([image x]
(phaser->clj
(.setPosition image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y))))
([image x y z]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser z))))
([image x y z w]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser z)
(clj->phaser w)))))
(defn set-random-position
"Sets the position of this Game Object to be a random position within the confines of
the given area.
If no area is specified a random position between 0 x 0 and the game width x height is used instead.
The position does not factor in the size of this Game Object, meaning that only the origin is
guaranteed to be within the area.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The x position of the top-left of the random area.
* y (number) {optional} - The y position of the top-left of the random area.
* width (number) {optional} - The width of the random area.
* height (number) {optional} - The height of the random area.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setRandomPosition image)))
([image x]
(phaser->clj
(.setRandomPosition image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y))))
([image x y width]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([image x y width height]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-rotation
"Sets the rotation of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* radians (number) {optional} - The rotation of this Game Object, in radians.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setRotation image)))
([image radians]
(phaser->clj
(.setRotation image
(clj->phaser radians)))))
(defn set-scale
"Sets the scale of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal scale of this Game Object.
* y (number) {optional} - The vertical scale of this Game Object. If not set it will use the `x` value.
Returns: this - This Game Object instance."
([image x]
(phaser->clj
(.setScale image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setScale image
(clj->phaser x)
(clj->phaser y)))))
(defn set-scroll-factor
"Sets the scroll factor of this Game Object.
The scroll factor controls the influence of the movement of a Camera upon this Game Object.
When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
It does not change the Game Objects actual position values.
A value of 1 means it will move exactly in sync with a camera.
A value of 0 means it will not move at all, even if the camera moves.
Other values control the degree to which the camera movement is mapped to this Game Object.
Please be aware that scroll factor values other than 1 are not taken in to consideration when
calculating physics collisions. Bodies always collide based on their world position, but changing
the scroll factor is a visual adjustment to where the textures are rendered, which can offset
them from physics bodies if not accounted for in your code.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal scroll factor of this Game Object.
* y (number) {optional} - The vertical scroll factor of this Game Object. If not set it will use the `x` value.
Returns: this - This Game Object instance."
([image x]
(phaser->clj
(.setScrollFactor image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setScrollFactor image
(clj->phaser x)
(clj->phaser y)))))
(defn set-size
"Sets the internal size of this Game Object, as used for frame or physics body creation.
This will not change the size that the Game Object is rendered in-game.
For that you need to either set the scale of the Game Object (`setScale`) or call the
`setDisplaySize` method, which is the same thing as changing the scale but allows you
to do so by giving pixel values.
If you have enabled this Game Object for input, changing the size will _not_ change the
size of the hit area. To do this you should adjust the `input.hitArea` object directly.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* width (number) - The width of this Game Object.
* height (number) - The height of this Game Object.
Returns: this - This Game Object instance."
([image width height]
(phaser->clj
(.setSize image
(clj->phaser width)
(clj->phaser height)))))
(defn set-size-to-frame
"Sets the size of this Game Object to be that of the given Frame.
This will not change the size that the Game Object is rendered in-game.
For that you need to either set the scale of the Game Object (`setScale`) or call the
`setDisplaySize` method, which is the same thing as changing the scale but allows you
to do so by giving pixel values.
If you have enabled this Game Object for input, changing the size will _not_ change the
size of the hit area. To do this you should adjust the `input.hitArea` object directly.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* frame (Phaser.Textures.Frame) - The frame to base the size of this Game Object on.
Returns: this - This Game Object instance."
([image frame]
(phaser->clj
(.setSizeToFrame image
(clj->phaser frame)))))
(defn set-state
"Sets the current state of this Game Object.
Phaser itself will never modify the State of a Game Object, although plugins may do so.
For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'.
The state value should typically be an integer (ideally mapped to a constant
in your game code), but could also be a string. It is recommended to keep it light and simple.
If you need to store complex data about your Game Object, look at using the Data Component instead.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (integer | string) - The state of the Game Object.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setState image
(clj->phaser value)))))
(defn set-texture
"Sets the texture and frame this Game Object will use to render with.
Textures are referenced by their string-based keys, as stored in the Texture Manager.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string) - The key of the texture to be used, as stored in the Texture Manager.
* frame (string | integer) {optional} - The name or index of the frame within the Texture.
Returns: this - This Game Object instance."
([image key]
(phaser->clj
(.setTexture image
(clj->phaser key))))
([image key frame]
(phaser->clj
(.setTexture image
(clj->phaser key)
(clj->phaser frame)))))
(defn set-tint
"Sets an additive tint on this Game Object.
The tint works by taking the pixel color values from the Game Objects texture, and then
multiplying it by the color value of the tint. You can provide either one color value,
in which case the whole Game Object will be tinted in that color. Or you can provide a color
per corner. The colors are blended together across the extent of the Game Object.
To modify the tint color once set, either call this method again with new values or use the
`tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight,
`tintBottomLeft` and `tintBottomRight` to set the corner color values independently.
To remove a tint call `clearTint`.
To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (integer) {optional} - The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object.
* top-right (integer) {optional} - The tint being applied to the top-right of the Game Object.
* bottom-left (integer) {optional} - The tint being applied to the bottom-left of the Game Object.
* bottom-right (integer) {optional} - The tint being applied to the bottom-right of the Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setTint image)))
([image top-left]
(phaser->clj
(.setTint image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-tint-fill
"Sets a fill-based tint on this Game Object.
Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture
with those in the tint. You can use this for effects such as making a player flash 'white'
if hit by something. You can provide either one color value, in which case the whole
Game Object will be rendered in that color. Or you can provide a color per corner. The colors
are blended together across the extent of the Game Object.
To modify the tint color once set, either call this method again with new values or use the
`tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight,
`tintBottomLeft` and `tintBottomRight` to set the corner color values independently.
To remove a tint call `clearTint`.
To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (integer) {optional} - The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object.
* top-right (integer) {optional} - The tint being applied to the top-right of the Game Object.
* bottom-left (integer) {optional} - The tint being applied to the bottom-left of the Game Object.
* bottom-right (integer) {optional} - The tint being applied to the bottom-right of the Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setTintFill image)))
([image top-left]
(phaser->clj
(.setTintFill image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-velocity
"Sets the velocity of the Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left.
* y (number) {optional} - The vertical velocity of the body. Positive values move the body down, while negative values move it up.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setVelocity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setVelocity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-velocity-x
"Sets the horizontal component of the body's velocity.
Positive values move the body to the right, while negative values move it to the left.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The new horizontal velocity.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setVelocityX image
(clj->phaser x)))))
(defn set-velocity-y
"Sets the vertical component of the body's velocity.
Positive values move the body down, while negative values move it up.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* y (number) - The new vertical velocity of the body.
Returns: this - This Game Object."
([image y]
(phaser->clj
(.setVelocityY image
(clj->phaser y)))))
(defn set-visible
"Sets the visibility of this Game Object.
An invisible Game Object will skip rendering, but will still process update logic.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The visible state of the Game Object.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setVisible image
(clj->phaser value)))))
(defn set-w
"Sets the w position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setW image)))
([image value]
(phaser->clj
(.setW image
(clj->phaser value)))))
(defn set-x
"Sets the x position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The x position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setX image)))
([image value]
(phaser->clj
(.setX image
(clj->phaser value)))))
(defn set-y
"Sets the y position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The y position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setY image)))
([image value]
(phaser->clj
(.setY image
(clj->phaser value)))))
(defn set-z
"Sets the z position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The z position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setZ image)))
([image value]
(phaser->clj
(.setZ image
(clj->phaser value)))))
(defn shutdown
"Removes all listeners."
([image]
(phaser->clj
(.shutdown image))))
(defn to-json
"Returns a JSON representation of the Game Object.
Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object."
([image]
(phaser->clj
(.toJSON image))))
(defn toggle-flip-x
"Toggles the horizontal flipped state of this Game Object.
A Game Object that is flipped horizontally will render inversed on the horizontal axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.toggleFlipX image))))
(defn toggle-flip-y
"Toggles the vertical flipped state of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.toggleFlipY image))))
(defn update
"To be overridden by custom GameObjects. Allows base objects to be used in a Pool.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* args (*) {optional} - args"
([image]
(phaser->clj
(.update image)))
([image args]
(phaser->clj
(.update image
(clj->phaser args)))))
(defn update-display-origin
"Updates the Display Origin cached values internally stored on this Game Object.
You don't usually call this directly, but it is exposed for edge-cases where you may.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.updateDisplayOrigin image))))
(defn will-render
"Compares the renderMask with the renderFlags to see if this Game Object will render or not.
Also checks the Game Object against the given Cameras exclusion list.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* camera (Phaser.Cameras.Scene2D.Camera) - The Camera to check against this Game Object.
Returns: boolean - True if the Game Object should be rendered, otherwise false."
([image camera]
(phaser->clj
(.willRender image
(clj->phaser camera)))))
| true |
(ns phzr.physics.arcade.image
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [update]))
(defn ->Image
" Parameters:
* scene (Phaser.Scene) - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
* x (number) - The horizontal position of this Game Object in the world.
* y (number) - The vertical position of this Game Object in the world.
* texture (string) - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager.
* frame (string | integer) {optional} - An optional frame from the Texture this Game Object is rendering with."
([scene x y texture]
(js/Phaser.Physics.Arcade.Image. (clj->phaser scene)
(clj->phaser x)
(clj->phaser y)
(clj->phaser texture)))
([scene x y texture frame]
(js/Phaser.Physics.Arcade.Image. (clj->phaser scene)
(clj->phaser x)
(clj->phaser y)
(clj->phaser texture)
(clj->phaser frame))))
(defn add-listener
"Add a listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.addListener image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.addListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn clear-alpha
"Clears all alpha values associated with this Game Object.
Immediately sets the alpha levels back to 1 (fully opaque).
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearAlpha image))))
(defn clear-mask
"Clears the mask that this Game Object was using.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* destroy-mask (boolean) {optional} - Destroy the mask before clearing it?
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearMask image)))
([image destroy-mask]
(phaser->clj
(.clearMask image
(clj->phaser destroy-mask)))))
(defn clear-tint
"Clears all tint values associated with this Game Object.
Immediately sets the color values back to 0xffffff and the tint type to 'additive',
which results in no visible change to the texture.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.clearTint image))))
(defn create-bitmap-mask
"Creates and returns a Bitmap Mask. This mask can be used by any Game Object,
including this one.
To create the mask you need to pass in a reference to a renderable Game Object.
A renderable Game Object is one that uses a texture to render with, such as an
Image, Sprite, Render Texture or BitmapText.
If you do not provide a renderable object, and this Game Object has a texture,
it will use itself as the object. This means you can call this method to create
a Bitmap Mask from any renderable Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* renderable (Phaser.GameObjects.GameObject) {optional} - A renderable Game Object that uses a texture, such as a Sprite.
Returns: Phaser.Display.Masks.BitmapMask - This Bitmap Mask that was created."
([image]
(phaser->clj
(.createBitmapMask image)))
([image renderable]
(phaser->clj
(.createBitmapMask image
(clj->phaser renderable)))))
(defn create-geometry-mask
"Creates and returns a Geometry Mask. This mask can be used by any Game Object,
including this one.
To create the mask you need to pass in a reference to a Graphics Game Object.
If you do not provide a graphics object, and this Game Object is an instance
of a Graphics object, then it will use itself to create the mask.
This means you can call this method to create a Geometry Mask from any Graphics Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* graphics (Phaser.GameObjects.Graphics) {optional} - A Graphics Game Object. The geometry within it will be used as the mask.
Returns: Phaser.Display.Masks.GeometryMask - This Geometry Mask that was created."
([image]
(phaser->clj
(.createGeometryMask image)))
([image graphics]
(phaser->clj
(.createGeometryMask image
(clj->phaser graphics)))))
(defn destroy
"Destroys this Game Object removing it from the Display List and Update List and
severing all ties to parent resources.
Also removes itself from the Input Manager and Physics Manager if previously enabled.
Use this to remove a Game Object from your game if you don't ever plan to use it again.
As long as no reference to it exists within your own code it should become free for
garbage collection by the browser.
If you just want to temporarily disable an object then look at using the
Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?"
([image]
(phaser->clj
(.destroy image)))
([image from-scene]
(phaser->clj
(.destroy image
(clj->phaser from-scene)))))
(defn disable-body
"Stops and disables this Game Object's Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* disable-game-object (boolean) {optional} - Also deactivate this Game Object.
* hide-game-object (boolean) {optional} - Also hide this Game Object.
Returns: this - This Game Object."
([image]
(phaser->clj
(.disableBody image)))
([image disable-game-object]
(phaser->clj
(.disableBody image
(clj->phaser disable-game-object))))
([image disable-game-object hide-game-object]
(phaser->clj
(.disableBody image
(clj->phaser disable-game-object)
(clj->phaser hide-game-object)))))
(defn disable-interactive
"If this Game Object has previously been enabled for input, this will disable it.
An object that is disabled for input stops processing or being considered for
input events, but can be turned back on again at any time by simply calling
`setInteractive()` with no arguments provided.
If want to completely remove interaction from this Game Object then use `removeInteractive` instead.
Returns: this - This GameObject."
([image]
(phaser->clj
(.disableInteractive image))))
(defn emit
"Calls each of the listeners registered for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* args (*) {optional} - Additional arguments that will be passed to the event handler.
Returns: boolean - `true` if the event had listeners, else `false`."
([image event]
(phaser->clj
(.emit image
(clj->phaser event))))
([image event args]
(phaser->clj
(.emit image
(clj->phaser event)
(clj->phaser args)))))
(defn enable-body
"Enables this Game Object's Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* reset (boolean) - Also reset the Body and place it at (x, y).
* x (number) - The horizontal position to place the Game Object and Body.
* y (number) - The horizontal position to place the Game Object and Body.
* enable-game-object (boolean) - Also activate this Game Object.
* show-game-object (boolean) - Also show this Game Object.
Returns: this - This Game Object."
([image reset x y enable-game-object show-game-object]
(phaser->clj
(.enableBody image
(clj->phaser reset)
(clj->phaser x)
(clj->phaser y)
(clj->phaser enable-game-object)
(clj->phaser show-game-object)))))
(defn event-names
"Return an array listing the events for which the emitter has registered listeners.
Returns: array - "
([image]
(phaser->clj
(.eventNames image))))
(defn get-bottom-center
"Gets the bottom-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomCenter image)))
([image output]
(phaser->clj
(.getBottomCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bottom-left
"Gets the bottom-left corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomLeft image)))
([image output]
(phaser->clj
(.getBottomLeft image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomLeft image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bottom-right
"Gets the bottom-right corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getBottomRight image)))
([image output]
(phaser->clj
(.getBottomRight image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getBottomRight image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-bounds
"Gets the bounds of this Game Object, regardless of origin.
The values are stored and returned in a Rectangle, or Rectangle-like, object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Geom.Rectangle | object) {optional} - An object to store the values in. If not provided a new Rectangle will be created.
Returns: Phaser.Geom.Rectangle | object - The values stored in the output object."
([image]
(phaser->clj
(.getBounds image)))
([image output]
(phaser->clj
(.getBounds image
(clj->phaser output)))))
(defn get-center
"Gets the center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getCenter image)))
([image output]
(phaser->clj
(.getCenter image
(clj->phaser output)))))
(defn get-data
"Retrieves the value for the given key in this Game Objects Data Manager, or undefined if it doesn't exist.
You can also access values via the `values` object. For example, if you had a key called `gold` you can do either:
```javascript
sprite.getData('gold');
```
Or access the value directly:
```javascript
sprite.data.values.gold;
```
You can also pass in an array of keys, in which case an array of values will be returned:
```javascript
sprite.getData([ 'gold', 'armor', 'health' ]);
```
This approach is useful for destructuring arrays in ES6.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string | Array.<string>) - The key of the value to retrieve, or an array of keys.
Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array."
([image key]
(phaser->clj
(.getData image
(clj->phaser key)))))
(defn get-index-list
"Returns an array containing the display list index of either this Game Object, or if it has one,
its parent Container. It then iterates up through all of the parent containers until it hits the
root of the display list (which is index 0 in the returned array).
Used internally by the InputPlugin but also useful if you wish to find out the display depth of
this Game Object and all of its ancestors.
Returns: Array.<integer> - An array of display list position indexes."
([image]
(phaser->clj
(.getIndexList image))))
(defn get-left-center
"Gets the left-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getLeftCenter image)))
([image output]
(phaser->clj
(.getLeftCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getLeftCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-local-transform-matrix
"Gets the local transform matrix for this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* temp-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - The matrix to populate with the values from this Game Object.
Returns: Phaser.GameObjects.Components.TransformMatrix - The populated Transform Matrix."
([image]
(phaser->clj
(.getLocalTransformMatrix image)))
([image temp-matrix]
(phaser->clj
(.getLocalTransformMatrix image
(clj->phaser temp-matrix)))))
(defn get-parent-rotation
"Gets the sum total rotation of all of this Game Objects parent Containers.
The returned value is in radians and will be zero if this Game Object has no parent container.
Returns: number - The sum total rotation, in radians, of all parent containers of this Game Object."
([image]
(phaser->clj
(.getParentRotation image))))
(defn get-pipeline-name
"Gets the name of the WebGL Pipeline this Game Object is currently using.
Returns: string - The string-based name of the pipeline being used by this Game Object."
([image]
(phaser->clj
(.getPipelineName image))))
(defn get-right-center
"Gets the right-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getRightCenter image)))
([image output]
(phaser->clj
(.getRightCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getRightCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-center
"Gets the top-center coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopCenter image)))
([image output]
(phaser->clj
(.getTopCenter image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopCenter image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-left
"Gets the top-left corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopLeft image)))
([image output]
(phaser->clj
(.getTopLeft image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopLeft image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-top-right
"Gets the top-right corner coordinate of this Game Object, regardless of origin.
The returned point is calculated in local space and does not factor in any parent containers
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* output (Phaser.Math.Vector2 | object) {optional} - An object to store the values in. If not provided a new Vector2 will be created.
* include-parent (boolean) {optional} - If this Game Object has a parent Container, include it (and all other ancestors) in the resulting vector?
Returns: Phaser.Math.Vector2 | object - The values stored in the output object."
([image]
(phaser->clj
(.getTopRight image)))
([image output]
(phaser->clj
(.getTopRight image
(clj->phaser output))))
([image output include-parent]
(phaser->clj
(.getTopRight image
(clj->phaser output)
(clj->phaser include-parent)))))
(defn get-world-transform-matrix
"Gets the world transform matrix for this Game Object, factoring in any parent Containers.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* temp-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - The matrix to populate with the values from this Game Object.
* parent-matrix (Phaser.GameObjects.Components.TransformMatrix) {optional} - A temporary matrix to hold parent values during the calculations.
Returns: Phaser.GameObjects.Components.TransformMatrix - The populated Transform Matrix."
([image]
(phaser->clj
(.getWorldTransformMatrix image)))
([image temp-matrix]
(phaser->clj
(.getWorldTransformMatrix image
(clj->phaser temp-matrix))))
([image temp-matrix parent-matrix]
(phaser->clj
(.getWorldTransformMatrix image
(clj->phaser temp-matrix)
(clj->phaser parent-matrix)))))
(defn init-pipeline
"Sets the initial WebGL Pipeline of this Game Object.
This should only be called during the instantiation of the Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* pipeline-name (string) {optional} - The name of the pipeline to set on this Game Object. Defaults to the Texture Tint Pipeline.
Returns: boolean - `true` if the pipeline was set successfully, otherwise `false`."
([image]
(phaser->clj
(.initPipeline image)))
([image pipeline-name]
(phaser->clj
(.initPipeline image
(clj->phaser pipeline-name)))))
(defn listener-count
"Return the number of listeners listening to a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: number - The number of listeners."
([image event]
(phaser->clj
(.listenerCount image
(clj->phaser event)))))
(defn listeners
"Return the listeners registered for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: array - The registered listeners."
([image event]
(phaser->clj
(.listeners image
(clj->phaser event)))))
(defn off
"Remove the listeners of a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) {optional} - Only remove the listeners that match this function.
* context (*) {optional} - Only remove the listeners that have this context.
* once (boolean) {optional} - Only remove one-time listeners.
Returns: Phaser.Events.EventEmitter - `this`."
([image event]
(phaser->clj
(.off image
(clj->phaser event))))
([image event fn]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([image event fn context once]
(phaser->clj
(.off image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn on
"Add a listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.on image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.on image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn once
"Add a one-time listener for a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) - The listener function.
* context (*) {optional} - The context to invoke the listener with.
Returns: Phaser.Events.EventEmitter - `this`."
([image event fn]
(phaser->clj
(.once image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.once image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn refresh-body
"Syncs the Body's position and size with its parent Game Object.
You don't need to call this for Dynamic Bodies, as it happens automatically.
But for Static bodies it's a useful way of modifying the position of a Static Body
in the Physics World, based on its Game Object.
Returns: this - This Game Object."
([image]
(phaser->clj
(.refreshBody image))))
(defn remove-all-listeners
"Remove all listeners, or those of the specified event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) {optional} - The event name.
Returns: Phaser.Events.EventEmitter - `this`."
([image]
(phaser->clj
(.removeAllListeners image)))
([image event]
(phaser->clj
(.removeAllListeners image
(clj->phaser event)))))
(defn remove-interactive
"If this Game Object has previously been enabled for input, this will queue it
for removal, causing it to no longer be interactive. The removal happens on
the next game step, it is not immediate.
The Interactive Object that was assigned to this Game Object will be destroyed,
removed from the Input Manager and cleared from this Game Object.
If you wish to re-enable this Game Object at a later date you will need to
re-create its InteractiveObject by calling `setInteractive` again.
If you wish to only temporarily stop an object from receiving input then use
`disableInteractive` instead, as that toggles the interactive state, where-as
this erases it completely.
If you wish to resize a hit area, don't remove and then set it as being
interactive. Instead, access the hitarea object directly and resize the shape
being used. I.e.: `sprite.input.hitArea.setSize(width, height)` (assuming the
shape is a Rectangle, which it is by default.)
Returns: this - This GameObject."
([image]
(phaser->clj
(.removeInteractive image))))
(defn remove-listener
"Remove the listeners of a given event.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* event (string | symbol) - The event name.
* fn (function) {optional} - Only remove the listeners that match this function.
* context (*) {optional} - Only remove the listeners that have this context.
* once (boolean) {optional} - Only remove one-time listeners.
Returns: Phaser.Events.EventEmitter - `this`."
([image event]
(phaser->clj
(.removeListener image
(clj->phaser event))))
([image event fn]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn))))
([image event fn context]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([image event fn context once]
(phaser->clj
(.removeListener image
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn reset-flip
"Resets the horizontal and vertical flipped state of this Game Object back to their default un-flipped state.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.resetFlip image))))
(defn reset-pipeline
"Resets the WebGL Pipeline of this Game Object back to the default it was created with.
Returns: boolean - `true` if the pipeline was set successfully, otherwise `false`."
([image]
(phaser->clj
(.resetPipeline image))))
(defn set-acceleration
"Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal acceleration
* y (number) {optional} - The vertical acceleration
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setAcceleration image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setAcceleration image
(clj->phaser x)
(clj->phaser y)))))
(defn set-acceleration-x
"Sets the body's horizontal acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The horizontal acceleration
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAccelerationX image
(clj->phaser value)))))
(defn set-acceleration-y
"Sets the body's vertical acceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The vertical acceleration
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAccelerationY image
(clj->phaser value)))))
(defn set-active
"Sets the `active` property of this Game Object and returns this Game Object for further chaining.
A Game Object with its `active` property set to `true` will be updated by the Scenes UpdateList.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - True if this Game Object should be set as active, false if not.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setActive image
(clj->phaser value)))))
(defn set-alpha
"Set the Alpha level of this Game Object. The alpha controls the opacity of the Game Object as it renders.
Alpha values are provided as a float between 0, fully transparent, and 1, fully opaque.
If your game is running under WebGL you can optionally specify four different alpha values, each of which
correspond to the four corners of the Game Object. Under Canvas only the `topLeft` value given is used.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (number) {optional} - The alpha value used for the top-left of the Game Object. If this is the only value given it's applied across the whole Game Object.
* top-right (number) {optional} - The alpha value used for the top-right of the Game Object. WebGL only.
* bottom-left (number) {optional} - The alpha value used for the bottom-left of the Game Object. WebGL only.
* bottom-right (number) {optional} - The alpha value used for the bottom-right of the Game Object. WebGL only.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setAlpha image)))
([image top-left]
(phaser->clj
(.setAlpha image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setAlpha image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-angle
"Sets the angle of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* degrees (number) {optional} - The rotation of this Game Object, in degrees.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setAngle image)))
([image degrees]
(phaser->clj
(.setAngle image
(clj->phaser degrees)))))
(defn set-angular-acceleration
"Sets the angular acceleration of the body.
In Arcade Physics, bodies cannot rotate. They are always axis-aligned.
However, they can have angular motion, which is passed on to the Game Object bound to the body,
causing them to visually rotate, even though the body remains axis-aligned.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of angular acceleration.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularAcceleration image
(clj->phaser value)))))
(defn set-angular-drag
"Sets the angular drag of the body. Drag is applied to the current velocity, providing a form of deceleration.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of drag.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularDrag image
(clj->phaser value)))))
(defn set-angular-velocity
"Sets the angular velocity of the body.
In Arcade Physics, bodies cannot rotate. They are always axis-aligned.
However, they can have angular motion, which is passed on to the Game Object bound to the body,
causing them to visually rotate, even though the body remains axis-aligned.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of angular velocity.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setAngularVelocity image
(clj->phaser value)))))
(defn set-blend-mode
"Sets the Blend Mode being used by this Game Object.
This can be a const, such as `Phaser.BlendModes.SCREEN`, or an integer, such as 4 (for Overlay)
Under WebGL only the following Blend Modes are available:
* ADD
* MULTIPLY
* SCREEN
* ERASE (only works when rendering to a framebuffer, like a Render Texture)
Canvas has more available depending on browser support.
You can also create your own custom Blend Modes in WebGL.
Blend modes have different effects under Canvas and WebGL, and from browser to browser, depending
on support. Blend Modes also cause a WebGL batch flush should it encounter a new blend mode. For these
reasons try to be careful about the construction of your Scene and the frequency in which blend modes
are used.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (string | Phaser.BlendModes) - The BlendMode value. Either a string or a CONST.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setBlendMode image
(clj->phaser value)))))
(defn set-bounce
"Sets the bounce values of this body.
Bounce is the amount of restitution, or elasticity, the body has when it collides with another object.
A value of 1 means that it will retain its full velocity after the rebound. A value of 0 means it will not rebound at all.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1.
* y (number) {optional} - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setBounce image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setBounce image
(clj->phaser x)
(clj->phaser y)))))
(defn set-bounce-x
"Sets the horizontal bounce value for this body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of horizontal bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setBounceX image
(clj->phaser value)))))
(defn set-bounce-y
"Sets the vertical bounce value for this body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of vertical bounce to apply on collision. A float, typically between 0 and 1.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setBounceY image
(clj->phaser value)))))
(defn set-circle
"Sets this physics body to use a circle for collision instead of a rectangle.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* radius (number) - The radius of the physics body, in pixels.
* offset-x (number) {optional} - The amount to offset the body from the parent Game Object along the x-axis.
* offset-y (number) {optional} - The amount to offset the body from the parent Game Object along the y-axis.
Returns: this - This Game Object."
([image radius]
(phaser->clj
(.setCircle image
(clj->phaser radius))))
([image radius offset-x]
(phaser->clj
(.setCircle image
(clj->phaser radius)
(clj->phaser offset-x))))
([image radius offset-x offset-y]
(phaser->clj
(.setCircle image
(clj->phaser radius)
(clj->phaser offset-x)
(clj->phaser offset-y)))))
(defn set-collide-world-bounds
"Sets whether this Body collides with the world boundary.
Optionally also sets the World Bounce values. If the `Body.worldBounce` is null, it's set to a new Vec2 first.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) {optional} - `true` if this body should collide with the world bounds, otherwise `false`.
* bounce-x (number) {optional} - If given this will be replace the `worldBounce.x` value.
* bounce-y (number) {optional} - If given this will be replace the `worldBounce.y` value.
Returns: this - This Game Object."
([image]
(phaser->clj
(.setCollideWorldBounds image)))
([image value]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value))))
([image value bounce-x]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value)
(clj->phaser bounce-x))))
([image value bounce-x bounce-y]
(phaser->clj
(.setCollideWorldBounds image
(clj->phaser value)
(clj->phaser bounce-x)
(clj->phaser bounce-y)))))
(defn set-crop
"Applies a crop to a texture based Game Object, such as a Sprite or Image.
The crop is a rectangle that limits the area of the texture frame that is visible during rendering.
Cropping a Game Object does not change its size, dimensions, physics body or hit area, it just
changes what is shown when rendered.
The crop coordinates are relative to the texture frame, not the Game Object, meaning 0 x 0 is the top-left.
Therefore, if you had a Game Object that had an 800x600 sized texture, and you wanted to show only the left
half of it, you could call `setCrop(0, 0, 400, 600)`.
It is also scaled to match the Game Object scale automatically. Therefore a crop rect of 100x50 would crop
an area of 200x100 when applied to a Game Object that had a scale factor of 2.
You can either pass in numeric values directly, or you can provide a single Rectangle object as the first argument.
Call this method with no arguments at all to reset the crop, or toggle the property `isCropped` to `false`.
You should do this if the crop rectangle becomes the same size as the frame itself, as it will allow
the renderer to skip several internal calculations.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number | Phaser.Geom.Rectangle) {optional} - The x coordinate to start the crop from. Or a Phaser.Geom.Rectangle object, in which case the rest of the arguments are ignored.
* y (number) {optional} - The y coordinate to start the crop from.
* width (number) {optional} - The width of the crop rectangle in pixels.
* height (number) {optional} - The height of the crop rectangle in pixels.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setCrop image)))
([image x]
(phaser->clj
(.setCrop image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y))))
([image x y width]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([image x y width height]
(phaser->clj
(.setCrop image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-damping
"If this Body is using `drag` for deceleration this function controls how the drag is applied.
If set to `true` drag will use a damping effect rather than a linear approach. If you are
creating a game where the Body moves freely at any angle (i.e. like the way the ship moves in
the game Asteroids) then you will get a far smoother and more visually correct deceleration
by using damping, avoiding the axis-drift that is prone with linear deceleration.
If you enable this property then you should use far smaller `drag` values than with linear, as
they are used as a multiplier on the velocity. Values such as 0.95 will give a nice slow
deceleration, where-as smaller values, such as 0.5 will stop an object almost immediately.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - `true` to use damping for deceleration, or `false` to use linear deceleration.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDamping image
(clj->phaser value)))))
(defn set-data
"Allows you to store a key value pair within this Game Objects Data Manager.
If the Game Object has not been enabled for data (via `setDataEnabled`) then it will be enabled
before setting the value.
If the key doesn't already exist in the Data Manager then it is created.
```javascript
sprite.setData('name', 'PI:NAME:<NAME>END_PI Gem PI:NAME:<NAME>END_PI');
```
You can also pass in an object of key value pairs as the first argument:
```javascript
sprite.setData({ name: 'PI:NAME:<NAME>END_PI', level: 2, owner: 'Link', gold: 50 });
```
To get a value back again you can call `getData`:
```javascript
sprite.getData('gold');
```
Or you can access the value directly via the `values` property, where it works like any other variable:
```javascript
sprite.data.values.gold += 50;
```
When the value is first set, a `setdata` event is emitted from this Game Object.
If the key already exists, a `changedata` event is emitted instead, along an event named after the key.
For example, if you updated an existing key called `PI:KEY:<KEY>END_PI` then it would emit the event `changedata-PlayerLives`.
These events will be emitted regardless if you use this method to set the value, or the direct `values` setter.
Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string | object) - The key to set the value for. Or an object of key value pairs. If an object the `data` argument is ignored.
* data (*) {optional} - The value to set for the given key. If an object is provided as the key this argument is ignored.
Returns: this - This GameObject."
([image key]
(phaser->clj
(.setData image
(clj->phaser key))))
([image key data]
(phaser->clj
(.setData image
(clj->phaser key)
(clj->phaser data)))))
(defn set-data-enabled
"Adds a Data Manager component to this Game Object.
Returns: this - This GameObject."
([image]
(phaser->clj
(.setDataEnabled image))))
(defn set-debug
"Sets the debug values of this body.
Bodies will only draw their debug if debug has been enabled for Arcade Physics as a whole.
Note that there is a performance cost in drawing debug displays. It should never be used in production.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* show-body (boolean) - Set to `true` to have this body render its outline to the debug display.
* show-velocity (boolean) - Set to `true` to have this body render a velocity marker to the debug display.
* body-color (number) - The color of the body outline when rendered to the debug display.
Returns: this - This Game Object."
([image show-body show-velocity body-color]
(phaser->clj
(.setDebug image
(clj->phaser show-body)
(clj->phaser show-velocity)
(clj->phaser body-color)))))
(defn set-debug-body-color
"Sets the color of the body outline when it renders to the debug display.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The color of the body outline when rendered to the debug display.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDebugBodyColor image
(clj->phaser value)))))
(defn set-depth
"The depth of this Game Object within the Scene.
The depth is also known as the 'z-index' in some environments, and allows you to change the rendering order
of Game Objects, without actually moving their position in the display list.
The depth starts from zero (the default value) and increases from that point. A Game Object with a higher depth
value will always render in front of one with a lower value.
Setting the depth will queue a depth sort event within the Scene.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (integer) - The depth of this Game Object.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setDepth image
(clj->phaser value)))))
(defn set-display-origin
"Sets the display origin of this Game Object.
The difference between this and setting the origin is that you can use pixel values for setting the display origin.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The horizontal display origin value.
* y (number) {optional} - The vertical display origin value. If not defined it will be set to the value of `x`.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setDisplayOrigin image)))
([image x]
(phaser->clj
(.setDisplayOrigin image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setDisplayOrigin image
(clj->phaser x)
(clj->phaser y)))))
(defn set-display-size
"Sets the display size of this Game Object.
Calling this will adjust the scale.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* width (number) - The width of this Game Object.
* height (number) - The height of this Game Object.
Returns: this - This Game Object instance."
([image width height]
(phaser->clj
(.setDisplaySize image
(clj->phaser width)
(clj->phaser height)))))
(defn set-drag
"Sets the body's horizontal and vertical drag. If the vertical drag value is not provided, the vertical drag is set to the same value as the horizontal drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal drag to apply.
* y (number) {optional} - The amount of vertical drag to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setDrag image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setDrag image
(clj->phaser x)
(clj->phaser y)))))
(defn set-drag-x
"Sets the body's horizontal drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of horizontal drag to apply.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDragX image
(clj->phaser value)))))
(defn set-drag-y
"Sets the body's vertical drag.
Drag can be considered as a form of deceleration that will return the velocity of a body back to zero over time.
It is the absolute loss of velocity due to movement, in pixels per second squared.
The x and y components are applied separately.
When `useDamping` is true, this is 1 minus the damping factor.
A value of 1 means the Body loses no velocity.
A value of 0.95 means the Body loses 5% of its velocity per step.
A value of 0.5 means the Body loses 50% of its velocity per step.
Drag is applied only when `acceleration` is zero.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - The amount of vertical drag to apply.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setDragY image
(clj->phaser value)))))
(defn set-flip
"Sets the horizontal and vertical flipped state of this Game Object.
A Game Object that is flipped will render inversed on the flipped axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (boolean) - The horizontal flipped state. `false` for no flip, or `true` to be flipped.
* y (boolean) - The horizontal flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image x y]
(phaser->clj
(.setFlip image
(clj->phaser x)
(clj->phaser y)))))
(defn set-flip-x
"Sets the horizontal flipped state of this Game Object.
A Game Object that is flipped horizontally will render inversed on the horizontal axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setFlipX image
(clj->phaser value)))))
(defn set-flip-y
"Sets the vertical flipped state of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The flipped state. `false` for no flip, or `true` to be flipped.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setFlipY image
(clj->phaser value)))))
(defn set-frame
"Sets the frame this Game Object will use to render with.
The Frame has to belong to the current Texture being used.
It can be either a string or an index.
Calling `setFrame` will modify the `width` and `height` properties of your Game Object.
It will also change the `origin` if the Frame has a custom pivot point, as exported from packages like Texture Packer.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* frame (string | integer) - The name or index of the frame within the Texture.
* update-size (boolean) {optional} - Should this call adjust the size of the Game Object?
* update-origin (boolean) {optional} - Should this call adjust the origin of the Game Object?
Returns: this - This Game Object instance."
([image frame]
(phaser->clj
(.setFrame image
(clj->phaser frame))))
([image frame update-size]
(phaser->clj
(.setFrame image
(clj->phaser frame)
(clj->phaser update-size))))
([image frame update-size update-origin]
(phaser->clj
(.setFrame image
(clj->phaser frame)
(clj->phaser update-size)
(clj->phaser update-origin)))))
(defn set-friction
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of horizontal friction to apply.
* y (number) {optional} - The amount of vertical friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFriction image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setFriction image
(clj->phaser x)
(clj->phaser y)))))
(defn set-friction-x
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving horizontally in the X axis.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFrictionX image
(clj->phaser x)))))
(defn set-friction-y
"Sets the friction (e.g. the amount of velocity reduced over time) of the physics body when moving vertically in the Y axis.
The higher than friction, the faster the body will slow down once force stops being applied to it.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount of friction to apply.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setFrictionY image
(clj->phaser x)))))
(defn set-gravity
"Set the X and Y values of the gravitational pull to act upon this Arcade Physics Game Object. Values can be positive or negative. Larger values result in a stronger effect.
If only one value is provided, this value will be used for both the X and Y axis.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The gravitational force to be applied to the X-axis.
* y (number) {optional} - The gravitational force to be applied to the Y-axis. If this is not specified, the X value will be used.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setGravity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setGravity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-gravity-x
"Set the gravitational force to be applied to the X axis. Value can be positive or negative. Larger values result in a stronger effect.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The gravitational force to be applied to the X-axis.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setGravityX image
(clj->phaser x)))))
(defn set-gravity-y
"Set the gravitational force to be applied to the Y axis. Value can be positive or negative. Larger values result in a stronger effect.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* y (number) - The gravitational force to be applied to the Y-axis.
Returns: this - This Game Object."
([image y]
(phaser->clj
(.setGravityY image
(clj->phaser y)))))
(defn set-immovable
"Sets Whether this Body can be moved by collisions with another Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) {optional} - Sets if this body can be moved by collisions with another Body.
Returns: this - This Game Object."
([image]
(phaser->clj
(.setImmovable image)))
([image value]
(phaser->clj
(.setImmovable image
(clj->phaser value)))))
(defn set-interactive
"Pass this Game Object to the Input Manager to enable it for Input.
Input works by using hit areas, these are nearly always geometric shapes, such as rectangles or circles, that act as the hit area
for the Game Object. However, you can provide your own hit area shape and callback, should you wish to handle some more advanced
input detection.
If no arguments are provided it will try and create a rectangle hit area based on the texture frame the Game Object is using. If
this isn't a texture-bound object, such as a Graphics or BitmapText object, this will fail, and you'll need to provide a specific
shape for it to use.
You can also provide an Input Configuration Object as the only argument to this method.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* shape (Phaser.Types.Input.InputConfiguration | any) {optional} - Either an input configuration object, or a geometric shape that defines the hit area for the Game Object. If not specified a Rectangle will be used.
* callback (Phaser.Types.Input.HitAreaCallback) {optional} - A callback to be invoked when the Game Object is interacted with. If you provide a shape you must also provide a callback.
* drop-zone (boolean) {optional} - Should this Game Object be treated as a drop zone target?
Returns: this - This GameObject."
([image]
(phaser->clj
(.setInteractive image)))
([image shape]
(phaser->clj
(.setInteractive image
(clj->phaser shape))))
([image shape callback]
(phaser->clj
(.setInteractive image
(clj->phaser shape)
(clj->phaser callback))))
([image shape callback drop-zone]
(phaser->clj
(.setInteractive image
(clj->phaser shape)
(clj->phaser callback)
(clj->phaser drop-zone)))))
(defn set-mask
"Sets the mask that this Game Object will use to render with.
The mask must have been previously created and can be either a GeometryMask or a BitmapMask.
Note: Bitmap Masks only work on WebGL. Geometry Masks work on both WebGL and Canvas.
If a mask is already set on this Game Object it will be immediately replaced.
Masks are positioned in global space and are not relative to the Game Object to which they
are applied. The reason for this is that multiple Game Objects can all share the same mask.
Masks have no impact on physics or input detection. They are purely a rendering component
that allows you to limit what is visible during the render pass.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* mask (Phaser.Display.Masks.BitmapMask | Phaser.Display.Masks.GeometryMask) - The mask this Game Object will use when rendering.
Returns: this - This Game Object instance."
([image mask]
(phaser->clj
(.setMask image
(clj->phaser mask)))))
(defn set-mass
"Sets the mass of the physics body
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) - New value for the mass of the body.
Returns: this - This Game Object."
([image value]
(phaser->clj
(.setMass image
(clj->phaser value)))))
(defn set-max-velocity
"Sets the maximum velocity of the body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The new maximum horizontal velocity.
* y (number) {optional} - The new maximum vertical velocity.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setMaxVelocity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setMaxVelocity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-name
"Sets the `name` property of this Game Object and returns this Game Object for further chaining.
The `name` property is not populated by Phaser and is presented for your own use.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (string) - The name to be given to this Game Object.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setName image
(clj->phaser value)))))
(defn set-offset
"Sets the body offset. This allows you to adjust the difference between the center of the body
and the x and y coordinates of the parent Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The amount to offset the body from the parent Game Object along the x-axis.
* y (number) {optional} - The amount to offset the body from the parent Game Object along the y-axis. Defaults to the value given for the x-axis.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setOffset image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setOffset image
(clj->phaser x)
(clj->phaser y)))))
(defn set-origin
"Sets the origin of this Game Object.
The values are given in the range 0 to 1.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The horizontal origin value.
* y (number) {optional} - The vertical origin value. If not defined it will be set to the value of `x`.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setOrigin image)))
([image x]
(phaser->clj
(.setOrigin image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setOrigin image
(clj->phaser x)
(clj->phaser y)))))
(defn set-origin-from-frame
"Sets the origin of this Game Object based on the Pivot values in its Frame.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setOriginFromFrame image))))
(defn set-pipeline
"Sets the active WebGL Pipeline of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* pipeline-name (string) - The name of the pipeline to set on this Game Object.
Returns: this - This Game Object instance."
([image pipeline-name]
(phaser->clj
(.setPipeline image
(clj->phaser pipeline-name)))))
(defn set-position
"Sets the position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The x position of this Game Object.
* y (number) {optional} - The y position of this Game Object. If not set it will use the `x` value.
* z (number) {optional} - The z position of this Game Object.
* w (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setPosition image)))
([image x]
(phaser->clj
(.setPosition image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y))))
([image x y z]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser z))))
([image x y z w]
(phaser->clj
(.setPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser z)
(clj->phaser w)))))
(defn set-random-position
"Sets the position of this Game Object to be a random position within the confines of
the given area.
If no area is specified a random position between 0 x 0 and the game width x height is used instead.
The position does not factor in the size of this Game Object, meaning that only the origin is
guaranteed to be within the area.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) {optional} - The x position of the top-left of the random area.
* y (number) {optional} - The y position of the top-left of the random area.
* width (number) {optional} - The width of the random area.
* height (number) {optional} - The height of the random area.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setRandomPosition image)))
([image x]
(phaser->clj
(.setRandomPosition image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y))))
([image x y width]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([image x y width height]
(phaser->clj
(.setRandomPosition image
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-rotation
"Sets the rotation of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* radians (number) {optional} - The rotation of this Game Object, in radians.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setRotation image)))
([image radians]
(phaser->clj
(.setRotation image
(clj->phaser radians)))))
(defn set-scale
"Sets the scale of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal scale of this Game Object.
* y (number) {optional} - The vertical scale of this Game Object. If not set it will use the `x` value.
Returns: this - This Game Object instance."
([image x]
(phaser->clj
(.setScale image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setScale image
(clj->phaser x)
(clj->phaser y)))))
(defn set-scroll-factor
"Sets the scroll factor of this Game Object.
The scroll factor controls the influence of the movement of a Camera upon this Game Object.
When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
It does not change the Game Objects actual position values.
A value of 1 means it will move exactly in sync with a camera.
A value of 0 means it will not move at all, even if the camera moves.
Other values control the degree to which the camera movement is mapped to this Game Object.
Please be aware that scroll factor values other than 1 are not taken in to consideration when
calculating physics collisions. Bodies always collide based on their world position, but changing
the scroll factor is a visual adjustment to where the textures are rendered, which can offset
them from physics bodies if not accounted for in your code.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal scroll factor of this Game Object.
* y (number) {optional} - The vertical scroll factor of this Game Object. If not set it will use the `x` value.
Returns: this - This Game Object instance."
([image x]
(phaser->clj
(.setScrollFactor image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setScrollFactor image
(clj->phaser x)
(clj->phaser y)))))
(defn set-size
"Sets the internal size of this Game Object, as used for frame or physics body creation.
This will not change the size that the Game Object is rendered in-game.
For that you need to either set the scale of the Game Object (`setScale`) or call the
`setDisplaySize` method, which is the same thing as changing the scale but allows you
to do so by giving pixel values.
If you have enabled this Game Object for input, changing the size will _not_ change the
size of the hit area. To do this you should adjust the `input.hitArea` object directly.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* width (number) - The width of this Game Object.
* height (number) - The height of this Game Object.
Returns: this - This Game Object instance."
([image width height]
(phaser->clj
(.setSize image
(clj->phaser width)
(clj->phaser height)))))
(defn set-size-to-frame
"Sets the size of this Game Object to be that of the given Frame.
This will not change the size that the Game Object is rendered in-game.
For that you need to either set the scale of the Game Object (`setScale`) or call the
`setDisplaySize` method, which is the same thing as changing the scale but allows you
to do so by giving pixel values.
If you have enabled this Game Object for input, changing the size will _not_ change the
size of the hit area. To do this you should adjust the `input.hitArea` object directly.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* frame (Phaser.Textures.Frame) - The frame to base the size of this Game Object on.
Returns: this - This Game Object instance."
([image frame]
(phaser->clj
(.setSizeToFrame image
(clj->phaser frame)))))
(defn set-state
"Sets the current state of this Game Object.
Phaser itself will never modify the State of a Game Object, although plugins may do so.
For example, a Game Object could change from a state of 'moving', to 'attacking', to 'dead'.
The state value should typically be an integer (ideally mapped to a constant
in your game code), but could also be a string. It is recommended to keep it light and simple.
If you need to store complex data about your Game Object, look at using the Data Component instead.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (integer | string) - The state of the Game Object.
Returns: this - This GameObject."
([image value]
(phaser->clj
(.setState image
(clj->phaser value)))))
(defn set-texture
"Sets the texture and frame this Game Object will use to render with.
Textures are referenced by their string-based keys, as stored in the Texture Manager.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* key (string) - The key of the texture to be used, as stored in the Texture Manager.
* frame (string | integer) {optional} - The name or index of the frame within the Texture.
Returns: this - This Game Object instance."
([image key]
(phaser->clj
(.setTexture image
(clj->phaser key))))
([image key frame]
(phaser->clj
(.setTexture image
(clj->phaser key)
(clj->phaser frame)))))
(defn set-tint
"Sets an additive tint on this Game Object.
The tint works by taking the pixel color values from the Game Objects texture, and then
multiplying it by the color value of the tint. You can provide either one color value,
in which case the whole Game Object will be tinted in that color. Or you can provide a color
per corner. The colors are blended together across the extent of the Game Object.
To modify the tint color once set, either call this method again with new values or use the
`tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight,
`tintBottomLeft` and `tintBottomRight` to set the corner color values independently.
To remove a tint call `clearTint`.
To swap this from being an additive tint to a fill based tint set the property `tintFill` to `true`.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (integer) {optional} - The tint being applied to the top-left of the Game Object. If no other values are given this value is applied evenly, tinting the whole Game Object.
* top-right (integer) {optional} - The tint being applied to the top-right of the Game Object.
* bottom-left (integer) {optional} - The tint being applied to the bottom-left of the Game Object.
* bottom-right (integer) {optional} - The tint being applied to the bottom-right of the Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setTint image)))
([image top-left]
(phaser->clj
(.setTint image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setTint image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-tint-fill
"Sets a fill-based tint on this Game Object.
Unlike an additive tint, a fill-tint literally replaces the pixel colors from the texture
with those in the tint. You can use this for effects such as making a player flash 'white'
if hit by something. You can provide either one color value, in which case the whole
Game Object will be rendered in that color. Or you can provide a color per corner. The colors
are blended together across the extent of the Game Object.
To modify the tint color once set, either call this method again with new values or use the
`tint` property to set all colors at once. Or, use the properties `tintTopLeft`, `tintTopRight,
`tintBottomLeft` and `tintBottomRight` to set the corner color values independently.
To remove a tint call `clearTint`.
To swap this from being a fill-tint to an additive tint set the property `tintFill` to `false`.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* top-left (integer) {optional} - The tint being applied to the top-left of the Game Object. If not other values are given this value is applied evenly, tinting the whole Game Object.
* top-right (integer) {optional} - The tint being applied to the top-right of the Game Object.
* bottom-left (integer) {optional} - The tint being applied to the bottom-left of the Game Object.
* bottom-right (integer) {optional} - The tint being applied to the bottom-right of the Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setTintFill image)))
([image top-left]
(phaser->clj
(.setTintFill image
(clj->phaser top-left))))
([image top-left top-right]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right))))
([image top-left top-right bottom-left]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left))))
([image top-left top-right bottom-left bottom-right]
(phaser->clj
(.setTintFill image
(clj->phaser top-left)
(clj->phaser top-right)
(clj->phaser bottom-left)
(clj->phaser bottom-right)))))
(defn set-velocity
"Sets the velocity of the Body.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The horizontal velocity of the body. Positive values move the body to the right, while negative values move it to the left.
* y (number) {optional} - The vertical velocity of the body. Positive values move the body down, while negative values move it up.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setVelocity image
(clj->phaser x))))
([image x y]
(phaser->clj
(.setVelocity image
(clj->phaser x)
(clj->phaser y)))))
(defn set-velocity-x
"Sets the horizontal component of the body's velocity.
Positive values move the body to the right, while negative values move it to the left.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* x (number) - The new horizontal velocity.
Returns: this - This Game Object."
([image x]
(phaser->clj
(.setVelocityX image
(clj->phaser x)))))
(defn set-velocity-y
"Sets the vertical component of the body's velocity.
Positive values move the body down, while negative values move it up.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* y (number) - The new vertical velocity of the body.
Returns: this - This Game Object."
([image y]
(phaser->clj
(.setVelocityY image
(clj->phaser y)))))
(defn set-visible
"Sets the visibility of this Game Object.
An invisible Game Object will skip rendering, but will still process update logic.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (boolean) - The visible state of the Game Object.
Returns: this - This Game Object instance."
([image value]
(phaser->clj
(.setVisible image
(clj->phaser value)))))
(defn set-w
"Sets the w position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setW image)))
([image value]
(phaser->clj
(.setW image
(clj->phaser value)))))
(defn set-x
"Sets the x position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The x position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setX image)))
([image value]
(phaser->clj
(.setX image
(clj->phaser value)))))
(defn set-y
"Sets the y position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The y position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setY image)))
([image value]
(phaser->clj
(.setY image
(clj->phaser value)))))
(defn set-z
"Sets the z position of this Game Object.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* value (number) {optional} - The z position of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.setZ image)))
([image value]
(phaser->clj
(.setZ image
(clj->phaser value)))))
(defn shutdown
"Removes all listeners."
([image]
(phaser->clj
(.shutdown image))))
(defn to-json
"Returns a JSON representation of the Game Object.
Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object."
([image]
(phaser->clj
(.toJSON image))))
(defn toggle-flip-x
"Toggles the horizontal flipped state of this Game Object.
A Game Object that is flipped horizontally will render inversed on the horizontal axis.
Flipping always takes place from the middle of the texture and does not impact the scale value.
If this Game Object has a physics body, it will not change the body. This is a rendering toggle only.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.toggleFlipX image))))
(defn toggle-flip-y
"Toggles the vertical flipped state of this Game Object.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.toggleFlipY image))))
(defn update
"To be overridden by custom GameObjects. Allows base objects to be used in a Pool.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* args (*) {optional} - args"
([image]
(phaser->clj
(.update image)))
([image args]
(phaser->clj
(.update image
(clj->phaser args)))))
(defn update-display-origin
"Updates the Display Origin cached values internally stored on this Game Object.
You don't usually call this directly, but it is exposed for edge-cases where you may.
Returns: this - This Game Object instance."
([image]
(phaser->clj
(.updateDisplayOrigin image))))
(defn will-render
"Compares the renderMask with the renderFlags to see if this Game Object will render or not.
Also checks the Game Object against the given Cameras exclusion list.
Parameters:
* image (Phaser.Physics.Arcade.Image) - Targeted instance for method
* camera (Phaser.Cameras.Scene2D.Camera) - The Camera to check against this Game Object.
Returns: boolean - True if the Game Object should be rendered, otherwise false."
([image camera]
(phaser->clj
(.willRender image
(clj->phaser camera)))))
|
[
{
"context": "- Natural deduction -- tests\n\n; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 88,
"score": 0.9998666644096375,
"start": 74,
"tag": "NAME",
"value": "Burkhardt Renz"
}
] |
test/lwb/nd/roths_pred_test.clj
|
esb-lwb/lwb
| 22 |
; lwb Logic WorkBench -- Natural deduction -- tests
; Copyright (c) 2016 Burkhardt Renz, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.nd.roths-pred-test
(:require [clojure.test :refer :all]
[lwb.nd.rules :refer :all]
[lwb.nd.repl :refer :all]))
(defn setup []
(load-logic :pred))
(defn fixture [f]
(setup)
(f))
(use-fixtures :once fixture)
(deftest forall-test
(is (= (roth-structure-forward :forall-i) ; backward only
nil))
(is (= (roth-structure-backward :forall-i)
[:cm :g?] ))
(is (= (apply-roth :forall-i '(:? (forall [x] phi))) ; (step-b :forall-i k)
'[(infer (actual _0) (substitution phi x _0))]))
(is (= (roth-structure-forward :forall-e)
[:gm :gm :c?] ))
(is (= (apply-roth :forall-e '((forall [x] phi) (actual t) :?)) ; (step-f :forall-e m n)
'[(substitution phi x t)]))
(is (= (roth-structure-backward :forall-e) ; forward only
nil))
)
(deftest exists-test
(is (= (roth-structure-forward :exists-i) ; backward only
nil ))
(is (= (roth-structure-backward :exists-i)
[:cm :go :g?] ))
(is (= (apply-roth :exists-i '(:? :? (exists [x] phi))) ; (step-b :exists-i k)
'[(actual _0) (substitution phi x _0)] ))
(is (= (apply-roth :exists-i '((actual t) :? (exists [x] phi))) ; (step-b :exists-i k m)
'[(substitution phi x t)] ))
(is (= (roth-structure-forward :exists-e)
[:gm :g? :co] ))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? :?)) ; (step-f :exists-e m)
'[(infer [(actual _0) (substitution (P (x)) x _0)] _1) _1] ))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? X)) ; (step-f :exists-e m k)
'[(infer [(actual _0) (substitution (P (x)) x _0)] X)] ))
(is (= (roth-structure-backward :exists-e)
[:cm :go :g?] ))
(is (= (apply-roth :exists-e '(:? :? X)) ; (step-b :exists-e k)
'[(exists [_0] _1) (infer [(actual _2) (substitution _1 _0 _2)] X)]))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? X)) ; (step-b :exists-e k m)
'[(infer [(actual _0) (substitution (P (x)) x _0)] X)] ))
)
(deftest equal-test
(is (= (roth-structure-forward :equal-i)
[:c?] ))
(is (= (apply-roth :equal-i '(:?)) ; (step-f :equal-i) wie tnd
'[(= _0 _0)]))
(is (= (roth-structure-backward :equal-i) ; forward only
nil))
(is (= (roth-structure-forward :equal-e)
[:gm :gm :em :em :c?] ))
(is (= (apply-roth :equal-e '((= a b) (P a) (P z) z :?)) ; (step-f :equal-e m n e1 e2)
'[(substitution (P z) z b)] ))
(is (= (roth-structure-backward :equal-e) ; forward only
nil))
)
(run-tests)
|
60065
|
; lwb Logic WorkBench -- Natural deduction -- tests
; Copyright (c) 2016 <NAME>, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.nd.roths-pred-test
(:require [clojure.test :refer :all]
[lwb.nd.rules :refer :all]
[lwb.nd.repl :refer :all]))
(defn setup []
(load-logic :pred))
(defn fixture [f]
(setup)
(f))
(use-fixtures :once fixture)
(deftest forall-test
(is (= (roth-structure-forward :forall-i) ; backward only
nil))
(is (= (roth-structure-backward :forall-i)
[:cm :g?] ))
(is (= (apply-roth :forall-i '(:? (forall [x] phi))) ; (step-b :forall-i k)
'[(infer (actual _0) (substitution phi x _0))]))
(is (= (roth-structure-forward :forall-e)
[:gm :gm :c?] ))
(is (= (apply-roth :forall-e '((forall [x] phi) (actual t) :?)) ; (step-f :forall-e m n)
'[(substitution phi x t)]))
(is (= (roth-structure-backward :forall-e) ; forward only
nil))
)
(deftest exists-test
(is (= (roth-structure-forward :exists-i) ; backward only
nil ))
(is (= (roth-structure-backward :exists-i)
[:cm :go :g?] ))
(is (= (apply-roth :exists-i '(:? :? (exists [x] phi))) ; (step-b :exists-i k)
'[(actual _0) (substitution phi x _0)] ))
(is (= (apply-roth :exists-i '((actual t) :? (exists [x] phi))) ; (step-b :exists-i k m)
'[(substitution phi x t)] ))
(is (= (roth-structure-forward :exists-e)
[:gm :g? :co] ))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? :?)) ; (step-f :exists-e m)
'[(infer [(actual _0) (substitution (P (x)) x _0)] _1) _1] ))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? X)) ; (step-f :exists-e m k)
'[(infer [(actual _0) (substitution (P (x)) x _0)] X)] ))
(is (= (roth-structure-backward :exists-e)
[:cm :go :g?] ))
(is (= (apply-roth :exists-e '(:? :? X)) ; (step-b :exists-e k)
'[(exists [_0] _1) (infer [(actual _2) (substitution _1 _0 _2)] X)]))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? X)) ; (step-b :exists-e k m)
'[(infer [(actual _0) (substitution (P (x)) x _0)] X)] ))
)
(deftest equal-test
(is (= (roth-structure-forward :equal-i)
[:c?] ))
(is (= (apply-roth :equal-i '(:?)) ; (step-f :equal-i) wie tnd
'[(= _0 _0)]))
(is (= (roth-structure-backward :equal-i) ; forward only
nil))
(is (= (roth-structure-forward :equal-e)
[:gm :gm :em :em :c?] ))
(is (= (apply-roth :equal-e '((= a b) (P a) (P z) z :?)) ; (step-f :equal-e m n e1 e2)
'[(substitution (P z) z b)] ))
(is (= (roth-structure-backward :equal-e) ; forward only
nil))
)
(run-tests)
| true |
; lwb Logic WorkBench -- Natural deduction -- tests
; Copyright (c) 2016 PI:NAME:<NAME>END_PI, THM. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php).
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
(ns lwb.nd.roths-pred-test
(:require [clojure.test :refer :all]
[lwb.nd.rules :refer :all]
[lwb.nd.repl :refer :all]))
(defn setup []
(load-logic :pred))
(defn fixture [f]
(setup)
(f))
(use-fixtures :once fixture)
(deftest forall-test
(is (= (roth-structure-forward :forall-i) ; backward only
nil))
(is (= (roth-structure-backward :forall-i)
[:cm :g?] ))
(is (= (apply-roth :forall-i '(:? (forall [x] phi))) ; (step-b :forall-i k)
'[(infer (actual _0) (substitution phi x _0))]))
(is (= (roth-structure-forward :forall-e)
[:gm :gm :c?] ))
(is (= (apply-roth :forall-e '((forall [x] phi) (actual t) :?)) ; (step-f :forall-e m n)
'[(substitution phi x t)]))
(is (= (roth-structure-backward :forall-e) ; forward only
nil))
)
(deftest exists-test
(is (= (roth-structure-forward :exists-i) ; backward only
nil ))
(is (= (roth-structure-backward :exists-i)
[:cm :go :g?] ))
(is (= (apply-roth :exists-i '(:? :? (exists [x] phi))) ; (step-b :exists-i k)
'[(actual _0) (substitution phi x _0)] ))
(is (= (apply-roth :exists-i '((actual t) :? (exists [x] phi))) ; (step-b :exists-i k m)
'[(substitution phi x t)] ))
(is (= (roth-structure-forward :exists-e)
[:gm :g? :co] ))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? :?)) ; (step-f :exists-e m)
'[(infer [(actual _0) (substitution (P (x)) x _0)] _1) _1] ))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? X)) ; (step-f :exists-e m k)
'[(infer [(actual _0) (substitution (P (x)) x _0)] X)] ))
(is (= (roth-structure-backward :exists-e)
[:cm :go :g?] ))
(is (= (apply-roth :exists-e '(:? :? X)) ; (step-b :exists-e k)
'[(exists [_0] _1) (infer [(actual _2) (substitution _1 _0 _2)] X)]))
(is (= (apply-roth :exists-e '((exists [x] (P (x))) :? X)) ; (step-b :exists-e k m)
'[(infer [(actual _0) (substitution (P (x)) x _0)] X)] ))
)
(deftest equal-test
(is (= (roth-structure-forward :equal-i)
[:c?] ))
(is (= (apply-roth :equal-i '(:?)) ; (step-f :equal-i) wie tnd
'[(= _0 _0)]))
(is (= (roth-structure-backward :equal-i) ; forward only
nil))
(is (= (roth-structure-forward :equal-e)
[:gm :gm :em :em :c?] ))
(is (= (apply-roth :equal-e '((= a b) (P a) (P z) z :?)) ; (step-f :equal-e m n e1 e2)
'[(substitution (P z) z b)] ))
(is (= (roth-structure-backward :equal-e) ; forward only
nil))
)
(run-tests)
|
[
{
"context": " (h/p {:class \"footer\"}\n [(format \"© 2006-%d John Jacobsen.\" (dates/current-year))\n \" Made with \"\n ",
"end": 1329,
"score": 0.9997997283935547,
"start": 1316,
"tag": "NAME",
"value": "John Jacobsen"
},
{
"context": "de with \"\n (h/a {:href \"https://github.com/eigenhombre/organa\"} [\"Organa\"])\n \".\"]))\n\n;; Org mode ",
"end": 1427,
"score": 0.9618898034095764,
"start": 1416,
"tag": "USERNAME",
"value": "eigenhombre"
},
{
"context": " [\"John Jacobsen\"])])\n (h/br)\n ",
"end": 9217,
"score": 0.9997543692588806,
"start": 9204,
"tag": "NAME",
"value": "John Jacobsen"
}
] |
src/organa/core.clj
|
eigenhombre/organa
| 14 |
(ns organa.core
(:gen-class)
(:require [clj-time.format :as tformat]
[clojure.java.io :as io]
[clojure.java.shell]
[clojure.pprint :as pprint]
[clojure.string :as str]
[clojure.string :as string]
[clojure.walk]
[environ.core :refer [env]]
[garden.core :refer [css] :rename {css to-css}]
[net.cgrand.enlive-html :as html]
[organa.artworks :as artworks]
[organa.config :refer [config]]
[organa.dates :as dates]
[organa.egg :refer [easter-egg]]
[organa.fs :as fs]
[organa.gallery :as gal]
[organa.html :as h]
[organa.image :as img]
[organa.pages :as pages]
[organa.parse :as parse]
[organa.rss :as rss])
(:import [java.io File]))
(defn ^:private remove-newline-strings [coll]
(remove (partial = "\n") coll))
(defn ^:private content-remove-newline-strings
"
Remove newlines from `:content` portion of Enlive element `el`.
"
[el]
(update-in el [:content] remove-newline-strings))
(defn ^:private execute-organa [m]
(-> m
:content
first
read-string
eval))
(defn ^:private footer []
(h/p {:class "footer"}
[(format "© 2006-%d John Jacobsen." (dates/current-year))
" Made with "
(h/a {:href "https://github.com/eigenhombre/organa"} ["Organa"])
"."]))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file-via-old-span-tag [parsed-html]
(-> parsed-html
(html/select [:span.tag])
first
:content
(#(mapcat :content %))))
(defn ^:private tags-bracketed-by-colons
"
(tags-bracketed-by-colons \":foo:baz:\")
;;=> [\"foo\" \"baz\"]
(tags-bracketed-by-colons \"adfkljhsadf\")
;;=> nil
"
[s]
(some-> (re-find #"^\:(.+?)\:$" s)
second
(clojure.string/split
#":")))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file-using-h2 [parsed-html]
(->> (html/select parsed-html [:h2])
(mapcat (comp tags-bracketed-by-colons first :content))
(remove nil?)))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file [parsed-html]
(concat
(tags-for-org-file-via-old-span-tag parsed-html)
(tags-for-org-file-using-h2 parsed-html)))
(defn ^:private tag-markup [tags]
(interleave
(repeat " ")
(for [t tags]
(h/span {:class (str t "-tag tag")}
[(h/a {:href (str t "-blog.html")} t)]))))
(defn ^:private articles-nav-section [file-name
available-files
alltags
parsed-org-file-map]
(h/div
`(~(h/a {:name "allposts"} [])
~(h/h2 {:class "allposts"} ["Blog Posts "
(h/span {:class "postcount"}
(->> available-files
(remove :static?)
(remove :draft?)
count
(format "(%d)")))])
~(h/p (concat ["Select from below, "
(h/a {:href "blog.html"} "view all posts")
", or choose only posts for:"]
(for [tag (sort alltags)]
(h/span {:class (format "%s-tag tag" tag)}
[(h/a {:href (str tag "-blog.html")}
tag)
" "]))))
~@(when (not= file-name "index")
[(h/hr)
(h/p [(h/a {:href "index.html"} [(h/em ["Home"])])])])
~(h/hr)
~@(for [{:keys [file-name date tags]}
(->> available-files
(remove :static?)
(remove :draft?)
(remove (comp #{file-name} :file-name)))
:let [parsed-html
(->> file-name
parsed-org-file-map
:parsed-html)]]
(when parsed-html
(h/p
(concat
[(h/a {:href (str file-name ".html")}
[(parse/title-for-org-file parsed-html)])]
" "
(tag-markup tags)
[" "
(h/span {:class "article-date"}
[(when date (tformat/unparse dates/article-date-format
date))])]))))
~@(when (not= file-name "index")
[(h/p [(h/a {:href "index.html"} [(h/em ["Home"])])])])
~(rss/rss-links))))
(defn ^:private position-of-current-file [file-name available-files]
(->> available-files
(map-indexed vector)
(filter (comp (partial = file-name) :file-name second))
ffirst))
(defn ^:private prev-next-tags [file-name available-files]
(let [files (->> available-files
(remove :static?)
(remove :draft?)
vec)
current-pos (position-of-current-file file-name files)
next-post (get files (dec current-pos))
prev-post (get files (inc current-pos))]
[(when prev-post
(h/p {:class "prev-next-post"}
[(h/span {:class "post-nav-earlier-later"}
["Earlier post "])
(h/a {:href (str "./" (:file-name prev-post) ".html")}
[(:title prev-post)])
(h/span (tag-markup (:tags prev-post)))]))
(when next-post
[(h/p {:class "prev-next-post"}
[(h/span {:class "post-nav-earlier-later"} ["Later post "])
(h/a {:href (str "./" (:file-name next-post) ".html")}
[(:title next-post)])
(h/span (tag-markup (:tags next-post)))])])]))
(defn ^:private page-header [css]
(let [analytics-id (:google-analytics-tracking-id env)
site-id (:google-analytics-site-id env)]
[(html/html-snippet (easter-egg))
(h/script {:type "text/javascript"
:src (str "https://cdnjs.cloudflare.com"
"/ajax/libs/mathjax/2.7.2/"
"MathJax.js"
"?config=TeX-MML-AM_CHTML")}
[])
(h/link {:href "./favicon.gif"
:rel "icon"
:type "image/gif"}
[])
;; Analytics
(h/script {:type "text/javascript"
:async true
:src
(format "https://www.googletagmanager.com/gtag/js?id=UA-%s-%s"
analytics-id site-id)}
[])
(h/script {:type "text/javascript"}
["window.dataLayer = window.dataLayer || [];"
"function gtag(){dataLayer.push(arguments);}"
"gtag('js', new Date());"
(format "gtag('config', 'UA-%s-%s');" analytics-id site-id)])
(h/style css)]))
(defn ^:private transform-enlive [file-name
date
available-files
parsed-org-file-map
tags
alltags
css
static?
draft?
enl]
(let [prev-next-tags (when-not (or static? draft?)
(prev-next-tags file-name available-files))
nav-section (articles-nav-section file-name
available-files
alltags
parsed-org-file-map)]
(html/at enl
[:head :style] nil
[:head :script] nil
[:div#postamble] nil
;; Old org mode:
;; Remove dummy header lines containting tags, in first
;; sections:
[:h2#sec-1] (fn [thing]
(when-not (-> thing
:content
second
:attrs
:class
(= "tag"))
thing))
;; New org mode:
;; Remove dummy header lines containing tags:
[:h2] (fn [thing]
(when-not (-> thing
:content
first
tags-bracketed-by-colons)
thing))
[:body] content-remove-newline-strings
[:ul] content-remove-newline-strings
[:html] content-remove-newline-strings
[:head] content-remove-newline-strings
[:head] (html/append (page-header css))
[:pre.src-organa] execute-organa
[:div#content :h1.title]
(html/after
`[~@(concat
[(when-not static?
(tag-markup (remove #{"static" "draft"} tags)))
(h/p [(h/span {:class "author"} [(h/a {:href "index.html"}
["John Jacobsen"])])
(h/br)
(h/span {:class "article-header-date"}
[(tformat/unparse dates/article-date-format
date)])])
(h/p [(h/a {:href "index.html"} [(h/strong ["Home"])])
" "
(h/a {:href "blog.html"} ["Other Posts"])])]
prev-next-tags
[(h/div {:class "hspace"} [])])])
[:div#content] (html/append
(h/div {:class "hspace"} [])
prev-next-tags
nav-section
(footer)))))
(defn ^:private as-string [x]
(with-out-str
(pprint/pprint x)))
(defn ^:private process-html-file! [{:keys [target-dir]}
{:keys [file-name date static? draft?
parsed-html tags unparsed-html] :as r}
available-files
alltags
css
parsed-org-file-map]
(->> parsed-html
(transform-enlive file-name
date
available-files
parsed-org-file-map
tags
alltags
css
static?
draft?)
html/emit* ;; turn back into html
(apply str)
(spit (str target-dir "/" file-name ".html")))
(->> r
as-string
(spit (str target-dir "/" file-name ".edn"))))
(defn ^:private html-file-exists [org-file-name]
(-> org-file-name
(clojure.string/replace #"\.org$" ".html")
clojure.java.io/file
.exists))
(defn ^:private available-org-files [site-source-dir]
(->> (fs/files-in-directory site-source-dir :as :file)
(filter (comp #(.endsWith ^String % ".org") str))
(filter html-file-exists)
(remove (comp #(.contains ^String % ".#") str))
(map #(.getName ^File %))
(map #(.substring ^String % 0 (.lastIndexOf ^String % ".")))))
(defn ^:private sh [& cmds]
(apply clojure.java.shell/sh
(clojure.string/split (string/join cmds) #"\s+")))
(defn ^:private ensure-target-dir-exists! [target-dir]
;; FIXME: do it the Java way
(sh "mkdir -p " target-dir))
(defn ^:private stage-site-image-files! [site-source-dir target-dir]
;; FIXME: avoid bash hack?
(doseq [f (filter (partial re-find img/image-file-pattern)
(fs/files-in-directory site-source-dir :as :str))]
(sh "cp -p " f " " target-dir)))
(defn ^:private stage-site-static-files! [site-source-dir target-dir]
(println "Syncing files in static directory...")
(apply clojure.java.shell/sh
(clojure.string/split
(format "rsync -vurt %s/static %s/galleries %s/artworks %s"
site-source-dir
site-source-dir
site-source-dir
target-dir)
#" ")))
;; FIXME: Hack-y?
(def ^:private base-enlive-snippet
(html/html-snippet "<html><head></head><body></body></html>"))
(defn ^:private galleries-path [site-source-dir]
(str site-source-dir "/galleries"))
(defn ^:private generate-thumbnails-for-gallery! [galpath imagefiles]
(doseq [img (remove #(.contains ^String % "-thumb")
imagefiles)
:let [[base _] (fs/splitext img)
thumb-path (format "%s/%s-thumb.png" galpath base)
orig-path (format "%s/%s" galpath img)]]
(when-not (.exists (io/file thumb-path))
(printf "Creating thumbnail file %s from %s...\n"
thumb-path
orig-path)
(img/create-thumbnail! orig-path thumb-path))))
(defn ^:private generate-thumbnails-in-galleries! [site-source-dir]
(let [galleries-dir (galleries-path site-source-dir)]
(doseq [galpath (fs/files-in-directory galleries-dir :as :str)
:let [imagefiles (gal/gallery-images galpath)]]
(printf "Making thumbnails for gallery '%s'\n" (fs/basename galpath))
(generate-thumbnails-for-gallery! galpath imagefiles))))
(defn ^:private gallery-html [css galfiles]
(->> (html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body]
(html/append
[(h/div {:class "gallery"}
(for [f galfiles
:let [[base _] (fs/splitext f)
thumb-path (format "%s-thumb.png" base)]]
(h/a {:href (str "./" f)}
[(h/img {:src (str "./" thumb-path)
:height "250px"}
[])])))]))
(html/emit*)
(apply str)))
(defn ^:private generate-html-for-galleries! [site-source-dir css]
(let [galleries-dir (galleries-path site-source-dir)]
(doseq [galpath (fs/files-in-directory galleries-dir :as :str)
:let [galfiles (gal/gallery-images galpath)]]
(printf "Making gallery '%s'\n" (fs/basename galpath))
(spit (str galpath "/index.html")
(gallery-html css galfiles)))))
(defn ^:private wait-futures [futures]
(loop [cnt 0]
(let [new-cnt (count (filter realized? futures))]
(when-not (every? realized? futures)
(Thread/sleep 500)
(if (= cnt new-cnt)
(recur cnt)
(do
(println new-cnt "completed...")
(recur new-cnt))))))
(doseq [fu futures]
(try
(deref fu)
(catch Throwable t
(println t)))))
(defn ^:private emit-html-to-file [target-dir file-name enlive-tree]
(->> enlive-tree
(html/emit*)
(cons "<!doctype html>\n")
(apply str)
(spit (str target-dir "/" file-name))))
(defn ^:private make-old-home-page [{:keys [target-dir]}
org-files
parsed-org-file-map
tags
css]
(emit-html-to-file
target-dir
"index-old.html"
(html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body] (html/append
[(pages/home-body)
;;(div {:class "hspace"} [])
])
[:div#blogposts] (html/append
[(articles-nav-section "index"
org-files
tags
parsed-org-file-map)
(footer)]))))
(defn ^:private make-blog-page
([config org-files parsed-org-file-map tags css]
(make-blog-page config :all org-files parsed-org-file-map tags css))
([{:keys [target-dir]} tag org-files parsed-org-file-map tags css]
(println (format "Making blog page for tag '%s'" tag))
(let [tag-posts (if (= tag :all)
org-files
(filter (comp (partial some #{tag}) :tags) org-files))]
(emit-html-to-file
target-dir
(str (if (= tag :all) "" (str tag "-"))
"blog.html")
(html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body] (html/append
[(pages/blog-body)
;;(div {:class "hspace"} [])
])
[:div#blogposts] (html/append
[(articles-nav-section "blog"
tag-posts
tags
parsed-org-file-map)
(footer)]))))))
(defn ^:private remove-gnu-junk [snippet]
(html/at snippet
[:script] nil
[:style] nil))
(defn ^:private files->parsed [files-to-process]
(let [ssd (:site-source-dir config)]
(into {}
(for [f files-to-process]
(let [parsed-html (->> f
(h/parse-org-html ssd)
remove-gnu-junk)
tags (tags-for-org-file parsed-html)]
[f
;; FIXME: It's hacky to have f in both places
{:file-name f
;; FIXME: don't re-parse for dates!
:date (dates/date-for-org-file ssd f)
:title (parse/title-for-org-file parsed-html)
:tags tags
:parsed-html parsed-html
:unparsed-html (apply str (html/emit* parsed-html))
:static? (some #{"static"} tags)
:draft? (some #{"draft"} tags)}])))))
(defn ^:private proof-files-to-process [all-org-files]
(->> all-org-files
(sort-by (fn [fname]
(->> (str fname ".html")
(str (:site-source-dir config) "/")
(dates/date-for-file-by-os))))
reverse
(take 10)))
(defn ^:private generate-site [{:keys [target-dir proof?] :as config}]
(println "The party commences....")
(ensure-target-dir-exists! target-dir)
(let [ssd (:site-source-dir config)
css (->> (str ssd "/index.garden")
load-file
to-css)
all-org-files (available-org-files ssd)
files-to-process (if-not proof?
all-org-files
(proof-files-to-process all-org-files))
_ (println (format "Parsing %d HTML'ed Org files..."
(count files-to-process)))
parsed-org-file-map (files->parsed files-to-process)
org-files (->> parsed-org-file-map
vals
(sort-by :date)
reverse)
alltags (->> org-files
;; Don't show draft/in progress posts:
(remove (comp (partial some #{"draft"}) :tags))
(mapcat :tags)
(remove #{"static" "draft"})
(into #{}))
_ (generate-thumbnails-in-galleries! ssd)
image-future (future (stage-site-image-files! ssd
target-dir))
static-future (future (generate-html-for-galleries! ssd
css)
(stage-site-static-files! ssd
target-dir))]
(println "Making artworks pages...")
(artworks/spit-out-artworks-pages! css)
(make-old-home-page config org-files parsed-org-file-map alltags css)
(make-blog-page config org-files parsed-org-file-map alltags css)
(doseq [tag alltags]
(make-blog-page config tag org-files parsed-org-file-map alltags css))
(println "Making RSS feed...")
(rss/make-rss-feeds "feed.xml" org-files)
(rss/make-rss-feeds "clojure" "feed.clojure.xml" org-files)
(rss/make-rss-feeds "lisp" "feed.lisp.xml" org-files)
(let [page-futures (for [f org-files]
(future
(process-html-file! config
f
org-files
alltags
css
parsed-org-file-map)))]
(println "Waiting for static copies to finish...")
(wait-futures [static-future])
(println "Waiting for image future to finish...")
(wait-futures [image-future])
(println (format "Waiting for %d per-page threads to finish..."
(count page-futures)))
(wait-futures page-futures)
(println "OK"))))
(defn -main []
(generate-site config)
(shutdown-agents))
(comment
(require '[marginalia.core :as marg])
(marg/run-marginalia ["src/organa/core.clj"])
(clojure.java.shell/sh "open" "docs/uberdoc.html")
(generate-site config)
(generate-site (assoc config :proof? true))
(clojure.java.shell/sh "open" "/tmp/organa/index-old.html")
)
|
70751
|
(ns organa.core
(:gen-class)
(:require [clj-time.format :as tformat]
[clojure.java.io :as io]
[clojure.java.shell]
[clojure.pprint :as pprint]
[clojure.string :as str]
[clojure.string :as string]
[clojure.walk]
[environ.core :refer [env]]
[garden.core :refer [css] :rename {css to-css}]
[net.cgrand.enlive-html :as html]
[organa.artworks :as artworks]
[organa.config :refer [config]]
[organa.dates :as dates]
[organa.egg :refer [easter-egg]]
[organa.fs :as fs]
[organa.gallery :as gal]
[organa.html :as h]
[organa.image :as img]
[organa.pages :as pages]
[organa.parse :as parse]
[organa.rss :as rss])
(:import [java.io File]))
(defn ^:private remove-newline-strings [coll]
(remove (partial = "\n") coll))
(defn ^:private content-remove-newline-strings
"
Remove newlines from `:content` portion of Enlive element `el`.
"
[el]
(update-in el [:content] remove-newline-strings))
(defn ^:private execute-organa [m]
(-> m
:content
first
read-string
eval))
(defn ^:private footer []
(h/p {:class "footer"}
[(format "© 2006-%d <NAME>." (dates/current-year))
" Made with "
(h/a {:href "https://github.com/eigenhombre/organa"} ["Organa"])
"."]))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file-via-old-span-tag [parsed-html]
(-> parsed-html
(html/select [:span.tag])
first
:content
(#(mapcat :content %))))
(defn ^:private tags-bracketed-by-colons
"
(tags-bracketed-by-colons \":foo:baz:\")
;;=> [\"foo\" \"baz\"]
(tags-bracketed-by-colons \"adfkljhsadf\")
;;=> nil
"
[s]
(some-> (re-find #"^\:(.+?)\:$" s)
second
(clojure.string/split
#":")))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file-using-h2 [parsed-html]
(->> (html/select parsed-html [:h2])
(mapcat (comp tags-bracketed-by-colons first :content))
(remove nil?)))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file [parsed-html]
(concat
(tags-for-org-file-via-old-span-tag parsed-html)
(tags-for-org-file-using-h2 parsed-html)))
(defn ^:private tag-markup [tags]
(interleave
(repeat " ")
(for [t tags]
(h/span {:class (str t "-tag tag")}
[(h/a {:href (str t "-blog.html")} t)]))))
(defn ^:private articles-nav-section [file-name
available-files
alltags
parsed-org-file-map]
(h/div
`(~(h/a {:name "allposts"} [])
~(h/h2 {:class "allposts"} ["Blog Posts "
(h/span {:class "postcount"}
(->> available-files
(remove :static?)
(remove :draft?)
count
(format "(%d)")))])
~(h/p (concat ["Select from below, "
(h/a {:href "blog.html"} "view all posts")
", or choose only posts for:"]
(for [tag (sort alltags)]
(h/span {:class (format "%s-tag tag" tag)}
[(h/a {:href (str tag "-blog.html")}
tag)
" "]))))
~@(when (not= file-name "index")
[(h/hr)
(h/p [(h/a {:href "index.html"} [(h/em ["Home"])])])])
~(h/hr)
~@(for [{:keys [file-name date tags]}
(->> available-files
(remove :static?)
(remove :draft?)
(remove (comp #{file-name} :file-name)))
:let [parsed-html
(->> file-name
parsed-org-file-map
:parsed-html)]]
(when parsed-html
(h/p
(concat
[(h/a {:href (str file-name ".html")}
[(parse/title-for-org-file parsed-html)])]
" "
(tag-markup tags)
[" "
(h/span {:class "article-date"}
[(when date (tformat/unparse dates/article-date-format
date))])]))))
~@(when (not= file-name "index")
[(h/p [(h/a {:href "index.html"} [(h/em ["Home"])])])])
~(rss/rss-links))))
(defn ^:private position-of-current-file [file-name available-files]
(->> available-files
(map-indexed vector)
(filter (comp (partial = file-name) :file-name second))
ffirst))
(defn ^:private prev-next-tags [file-name available-files]
(let [files (->> available-files
(remove :static?)
(remove :draft?)
vec)
current-pos (position-of-current-file file-name files)
next-post (get files (dec current-pos))
prev-post (get files (inc current-pos))]
[(when prev-post
(h/p {:class "prev-next-post"}
[(h/span {:class "post-nav-earlier-later"}
["Earlier post "])
(h/a {:href (str "./" (:file-name prev-post) ".html")}
[(:title prev-post)])
(h/span (tag-markup (:tags prev-post)))]))
(when next-post
[(h/p {:class "prev-next-post"}
[(h/span {:class "post-nav-earlier-later"} ["Later post "])
(h/a {:href (str "./" (:file-name next-post) ".html")}
[(:title next-post)])
(h/span (tag-markup (:tags next-post)))])])]))
(defn ^:private page-header [css]
(let [analytics-id (:google-analytics-tracking-id env)
site-id (:google-analytics-site-id env)]
[(html/html-snippet (easter-egg))
(h/script {:type "text/javascript"
:src (str "https://cdnjs.cloudflare.com"
"/ajax/libs/mathjax/2.7.2/"
"MathJax.js"
"?config=TeX-MML-AM_CHTML")}
[])
(h/link {:href "./favicon.gif"
:rel "icon"
:type "image/gif"}
[])
;; Analytics
(h/script {:type "text/javascript"
:async true
:src
(format "https://www.googletagmanager.com/gtag/js?id=UA-%s-%s"
analytics-id site-id)}
[])
(h/script {:type "text/javascript"}
["window.dataLayer = window.dataLayer || [];"
"function gtag(){dataLayer.push(arguments);}"
"gtag('js', new Date());"
(format "gtag('config', 'UA-%s-%s');" analytics-id site-id)])
(h/style css)]))
(defn ^:private transform-enlive [file-name
date
available-files
parsed-org-file-map
tags
alltags
css
static?
draft?
enl]
(let [prev-next-tags (when-not (or static? draft?)
(prev-next-tags file-name available-files))
nav-section (articles-nav-section file-name
available-files
alltags
parsed-org-file-map)]
(html/at enl
[:head :style] nil
[:head :script] nil
[:div#postamble] nil
;; Old org mode:
;; Remove dummy header lines containting tags, in first
;; sections:
[:h2#sec-1] (fn [thing]
(when-not (-> thing
:content
second
:attrs
:class
(= "tag"))
thing))
;; New org mode:
;; Remove dummy header lines containing tags:
[:h2] (fn [thing]
(when-not (-> thing
:content
first
tags-bracketed-by-colons)
thing))
[:body] content-remove-newline-strings
[:ul] content-remove-newline-strings
[:html] content-remove-newline-strings
[:head] content-remove-newline-strings
[:head] (html/append (page-header css))
[:pre.src-organa] execute-organa
[:div#content :h1.title]
(html/after
`[~@(concat
[(when-not static?
(tag-markup (remove #{"static" "draft"} tags)))
(h/p [(h/span {:class "author"} [(h/a {:href "index.html"}
["<NAME>"])])
(h/br)
(h/span {:class "article-header-date"}
[(tformat/unparse dates/article-date-format
date)])])
(h/p [(h/a {:href "index.html"} [(h/strong ["Home"])])
" "
(h/a {:href "blog.html"} ["Other Posts"])])]
prev-next-tags
[(h/div {:class "hspace"} [])])])
[:div#content] (html/append
(h/div {:class "hspace"} [])
prev-next-tags
nav-section
(footer)))))
(defn ^:private as-string [x]
(with-out-str
(pprint/pprint x)))
(defn ^:private process-html-file! [{:keys [target-dir]}
{:keys [file-name date static? draft?
parsed-html tags unparsed-html] :as r}
available-files
alltags
css
parsed-org-file-map]
(->> parsed-html
(transform-enlive file-name
date
available-files
parsed-org-file-map
tags
alltags
css
static?
draft?)
html/emit* ;; turn back into html
(apply str)
(spit (str target-dir "/" file-name ".html")))
(->> r
as-string
(spit (str target-dir "/" file-name ".edn"))))
(defn ^:private html-file-exists [org-file-name]
(-> org-file-name
(clojure.string/replace #"\.org$" ".html")
clojure.java.io/file
.exists))
(defn ^:private available-org-files [site-source-dir]
(->> (fs/files-in-directory site-source-dir :as :file)
(filter (comp #(.endsWith ^String % ".org") str))
(filter html-file-exists)
(remove (comp #(.contains ^String % ".#") str))
(map #(.getName ^File %))
(map #(.substring ^String % 0 (.lastIndexOf ^String % ".")))))
(defn ^:private sh [& cmds]
(apply clojure.java.shell/sh
(clojure.string/split (string/join cmds) #"\s+")))
(defn ^:private ensure-target-dir-exists! [target-dir]
;; FIXME: do it the Java way
(sh "mkdir -p " target-dir))
(defn ^:private stage-site-image-files! [site-source-dir target-dir]
;; FIXME: avoid bash hack?
(doseq [f (filter (partial re-find img/image-file-pattern)
(fs/files-in-directory site-source-dir :as :str))]
(sh "cp -p " f " " target-dir)))
(defn ^:private stage-site-static-files! [site-source-dir target-dir]
(println "Syncing files in static directory...")
(apply clojure.java.shell/sh
(clojure.string/split
(format "rsync -vurt %s/static %s/galleries %s/artworks %s"
site-source-dir
site-source-dir
site-source-dir
target-dir)
#" ")))
;; FIXME: Hack-y?
(def ^:private base-enlive-snippet
(html/html-snippet "<html><head></head><body></body></html>"))
(defn ^:private galleries-path [site-source-dir]
(str site-source-dir "/galleries"))
(defn ^:private generate-thumbnails-for-gallery! [galpath imagefiles]
(doseq [img (remove #(.contains ^String % "-thumb")
imagefiles)
:let [[base _] (fs/splitext img)
thumb-path (format "%s/%s-thumb.png" galpath base)
orig-path (format "%s/%s" galpath img)]]
(when-not (.exists (io/file thumb-path))
(printf "Creating thumbnail file %s from %s...\n"
thumb-path
orig-path)
(img/create-thumbnail! orig-path thumb-path))))
(defn ^:private generate-thumbnails-in-galleries! [site-source-dir]
(let [galleries-dir (galleries-path site-source-dir)]
(doseq [galpath (fs/files-in-directory galleries-dir :as :str)
:let [imagefiles (gal/gallery-images galpath)]]
(printf "Making thumbnails for gallery '%s'\n" (fs/basename galpath))
(generate-thumbnails-for-gallery! galpath imagefiles))))
(defn ^:private gallery-html [css galfiles]
(->> (html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body]
(html/append
[(h/div {:class "gallery"}
(for [f galfiles
:let [[base _] (fs/splitext f)
thumb-path (format "%s-thumb.png" base)]]
(h/a {:href (str "./" f)}
[(h/img {:src (str "./" thumb-path)
:height "250px"}
[])])))]))
(html/emit*)
(apply str)))
(defn ^:private generate-html-for-galleries! [site-source-dir css]
(let [galleries-dir (galleries-path site-source-dir)]
(doseq [galpath (fs/files-in-directory galleries-dir :as :str)
:let [galfiles (gal/gallery-images galpath)]]
(printf "Making gallery '%s'\n" (fs/basename galpath))
(spit (str galpath "/index.html")
(gallery-html css galfiles)))))
(defn ^:private wait-futures [futures]
(loop [cnt 0]
(let [new-cnt (count (filter realized? futures))]
(when-not (every? realized? futures)
(Thread/sleep 500)
(if (= cnt new-cnt)
(recur cnt)
(do
(println new-cnt "completed...")
(recur new-cnt))))))
(doseq [fu futures]
(try
(deref fu)
(catch Throwable t
(println t)))))
(defn ^:private emit-html-to-file [target-dir file-name enlive-tree]
(->> enlive-tree
(html/emit*)
(cons "<!doctype html>\n")
(apply str)
(spit (str target-dir "/" file-name))))
(defn ^:private make-old-home-page [{:keys [target-dir]}
org-files
parsed-org-file-map
tags
css]
(emit-html-to-file
target-dir
"index-old.html"
(html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body] (html/append
[(pages/home-body)
;;(div {:class "hspace"} [])
])
[:div#blogposts] (html/append
[(articles-nav-section "index"
org-files
tags
parsed-org-file-map)
(footer)]))))
(defn ^:private make-blog-page
([config org-files parsed-org-file-map tags css]
(make-blog-page config :all org-files parsed-org-file-map tags css))
([{:keys [target-dir]} tag org-files parsed-org-file-map tags css]
(println (format "Making blog page for tag '%s'" tag))
(let [tag-posts (if (= tag :all)
org-files
(filter (comp (partial some #{tag}) :tags) org-files))]
(emit-html-to-file
target-dir
(str (if (= tag :all) "" (str tag "-"))
"blog.html")
(html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body] (html/append
[(pages/blog-body)
;;(div {:class "hspace"} [])
])
[:div#blogposts] (html/append
[(articles-nav-section "blog"
tag-posts
tags
parsed-org-file-map)
(footer)]))))))
(defn ^:private remove-gnu-junk [snippet]
(html/at snippet
[:script] nil
[:style] nil))
(defn ^:private files->parsed [files-to-process]
(let [ssd (:site-source-dir config)]
(into {}
(for [f files-to-process]
(let [parsed-html (->> f
(h/parse-org-html ssd)
remove-gnu-junk)
tags (tags-for-org-file parsed-html)]
[f
;; FIXME: It's hacky to have f in both places
{:file-name f
;; FIXME: don't re-parse for dates!
:date (dates/date-for-org-file ssd f)
:title (parse/title-for-org-file parsed-html)
:tags tags
:parsed-html parsed-html
:unparsed-html (apply str (html/emit* parsed-html))
:static? (some #{"static"} tags)
:draft? (some #{"draft"} tags)}])))))
(defn ^:private proof-files-to-process [all-org-files]
(->> all-org-files
(sort-by (fn [fname]
(->> (str fname ".html")
(str (:site-source-dir config) "/")
(dates/date-for-file-by-os))))
reverse
(take 10)))
(defn ^:private generate-site [{:keys [target-dir proof?] :as config}]
(println "The party commences....")
(ensure-target-dir-exists! target-dir)
(let [ssd (:site-source-dir config)
css (->> (str ssd "/index.garden")
load-file
to-css)
all-org-files (available-org-files ssd)
files-to-process (if-not proof?
all-org-files
(proof-files-to-process all-org-files))
_ (println (format "Parsing %d HTML'ed Org files..."
(count files-to-process)))
parsed-org-file-map (files->parsed files-to-process)
org-files (->> parsed-org-file-map
vals
(sort-by :date)
reverse)
alltags (->> org-files
;; Don't show draft/in progress posts:
(remove (comp (partial some #{"draft"}) :tags))
(mapcat :tags)
(remove #{"static" "draft"})
(into #{}))
_ (generate-thumbnails-in-galleries! ssd)
image-future (future (stage-site-image-files! ssd
target-dir))
static-future (future (generate-html-for-galleries! ssd
css)
(stage-site-static-files! ssd
target-dir))]
(println "Making artworks pages...")
(artworks/spit-out-artworks-pages! css)
(make-old-home-page config org-files parsed-org-file-map alltags css)
(make-blog-page config org-files parsed-org-file-map alltags css)
(doseq [tag alltags]
(make-blog-page config tag org-files parsed-org-file-map alltags css))
(println "Making RSS feed...")
(rss/make-rss-feeds "feed.xml" org-files)
(rss/make-rss-feeds "clojure" "feed.clojure.xml" org-files)
(rss/make-rss-feeds "lisp" "feed.lisp.xml" org-files)
(let [page-futures (for [f org-files]
(future
(process-html-file! config
f
org-files
alltags
css
parsed-org-file-map)))]
(println "Waiting for static copies to finish...")
(wait-futures [static-future])
(println "Waiting for image future to finish...")
(wait-futures [image-future])
(println (format "Waiting for %d per-page threads to finish..."
(count page-futures)))
(wait-futures page-futures)
(println "OK"))))
(defn -main []
(generate-site config)
(shutdown-agents))
(comment
(require '[marginalia.core :as marg])
(marg/run-marginalia ["src/organa/core.clj"])
(clojure.java.shell/sh "open" "docs/uberdoc.html")
(generate-site config)
(generate-site (assoc config :proof? true))
(clojure.java.shell/sh "open" "/tmp/organa/index-old.html")
)
| true |
(ns organa.core
(:gen-class)
(:require [clj-time.format :as tformat]
[clojure.java.io :as io]
[clojure.java.shell]
[clojure.pprint :as pprint]
[clojure.string :as str]
[clojure.string :as string]
[clojure.walk]
[environ.core :refer [env]]
[garden.core :refer [css] :rename {css to-css}]
[net.cgrand.enlive-html :as html]
[organa.artworks :as artworks]
[organa.config :refer [config]]
[organa.dates :as dates]
[organa.egg :refer [easter-egg]]
[organa.fs :as fs]
[organa.gallery :as gal]
[organa.html :as h]
[organa.image :as img]
[organa.pages :as pages]
[organa.parse :as parse]
[organa.rss :as rss])
(:import [java.io File]))
(defn ^:private remove-newline-strings [coll]
(remove (partial = "\n") coll))
(defn ^:private content-remove-newline-strings
"
Remove newlines from `:content` portion of Enlive element `el`.
"
[el]
(update-in el [:content] remove-newline-strings))
(defn ^:private execute-organa [m]
(-> m
:content
first
read-string
eval))
(defn ^:private footer []
(h/p {:class "footer"}
[(format "© 2006-%d PI:NAME:<NAME>END_PI." (dates/current-year))
" Made with "
(h/a {:href "https://github.com/eigenhombre/organa"} ["Organa"])
"."]))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file-via-old-span-tag [parsed-html]
(-> parsed-html
(html/select [:span.tag])
first
:content
(#(mapcat :content %))))
(defn ^:private tags-bracketed-by-colons
"
(tags-bracketed-by-colons \":foo:baz:\")
;;=> [\"foo\" \"baz\"]
(tags-bracketed-by-colons \"adfkljhsadf\")
;;=> nil
"
[s]
(some-> (re-find #"^\:(.+?)\:$" s)
second
(clojure.string/split
#":")))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file-using-h2 [parsed-html]
(->> (html/select parsed-html [:h2])
(mapcat (comp tags-bracketed-by-colons first :content))
(remove nil?)))
;; Org mode exports changed how tags in section headings are handled...
(defn ^:private tags-for-org-file [parsed-html]
(concat
(tags-for-org-file-via-old-span-tag parsed-html)
(tags-for-org-file-using-h2 parsed-html)))
(defn ^:private tag-markup [tags]
(interleave
(repeat " ")
(for [t tags]
(h/span {:class (str t "-tag tag")}
[(h/a {:href (str t "-blog.html")} t)]))))
(defn ^:private articles-nav-section [file-name
available-files
alltags
parsed-org-file-map]
(h/div
`(~(h/a {:name "allposts"} [])
~(h/h2 {:class "allposts"} ["Blog Posts "
(h/span {:class "postcount"}
(->> available-files
(remove :static?)
(remove :draft?)
count
(format "(%d)")))])
~(h/p (concat ["Select from below, "
(h/a {:href "blog.html"} "view all posts")
", or choose only posts for:"]
(for [tag (sort alltags)]
(h/span {:class (format "%s-tag tag" tag)}
[(h/a {:href (str tag "-blog.html")}
tag)
" "]))))
~@(when (not= file-name "index")
[(h/hr)
(h/p [(h/a {:href "index.html"} [(h/em ["Home"])])])])
~(h/hr)
~@(for [{:keys [file-name date tags]}
(->> available-files
(remove :static?)
(remove :draft?)
(remove (comp #{file-name} :file-name)))
:let [parsed-html
(->> file-name
parsed-org-file-map
:parsed-html)]]
(when parsed-html
(h/p
(concat
[(h/a {:href (str file-name ".html")}
[(parse/title-for-org-file parsed-html)])]
" "
(tag-markup tags)
[" "
(h/span {:class "article-date"}
[(when date (tformat/unparse dates/article-date-format
date))])]))))
~@(when (not= file-name "index")
[(h/p [(h/a {:href "index.html"} [(h/em ["Home"])])])])
~(rss/rss-links))))
(defn ^:private position-of-current-file [file-name available-files]
(->> available-files
(map-indexed vector)
(filter (comp (partial = file-name) :file-name second))
ffirst))
(defn ^:private prev-next-tags [file-name available-files]
(let [files (->> available-files
(remove :static?)
(remove :draft?)
vec)
current-pos (position-of-current-file file-name files)
next-post (get files (dec current-pos))
prev-post (get files (inc current-pos))]
[(when prev-post
(h/p {:class "prev-next-post"}
[(h/span {:class "post-nav-earlier-later"}
["Earlier post "])
(h/a {:href (str "./" (:file-name prev-post) ".html")}
[(:title prev-post)])
(h/span (tag-markup (:tags prev-post)))]))
(when next-post
[(h/p {:class "prev-next-post"}
[(h/span {:class "post-nav-earlier-later"} ["Later post "])
(h/a {:href (str "./" (:file-name next-post) ".html")}
[(:title next-post)])
(h/span (tag-markup (:tags next-post)))])])]))
(defn ^:private page-header [css]
(let [analytics-id (:google-analytics-tracking-id env)
site-id (:google-analytics-site-id env)]
[(html/html-snippet (easter-egg))
(h/script {:type "text/javascript"
:src (str "https://cdnjs.cloudflare.com"
"/ajax/libs/mathjax/2.7.2/"
"MathJax.js"
"?config=TeX-MML-AM_CHTML")}
[])
(h/link {:href "./favicon.gif"
:rel "icon"
:type "image/gif"}
[])
;; Analytics
(h/script {:type "text/javascript"
:async true
:src
(format "https://www.googletagmanager.com/gtag/js?id=UA-%s-%s"
analytics-id site-id)}
[])
(h/script {:type "text/javascript"}
["window.dataLayer = window.dataLayer || [];"
"function gtag(){dataLayer.push(arguments);}"
"gtag('js', new Date());"
(format "gtag('config', 'UA-%s-%s');" analytics-id site-id)])
(h/style css)]))
(defn ^:private transform-enlive [file-name
date
available-files
parsed-org-file-map
tags
alltags
css
static?
draft?
enl]
(let [prev-next-tags (when-not (or static? draft?)
(prev-next-tags file-name available-files))
nav-section (articles-nav-section file-name
available-files
alltags
parsed-org-file-map)]
(html/at enl
[:head :style] nil
[:head :script] nil
[:div#postamble] nil
;; Old org mode:
;; Remove dummy header lines containting tags, in first
;; sections:
[:h2#sec-1] (fn [thing]
(when-not (-> thing
:content
second
:attrs
:class
(= "tag"))
thing))
;; New org mode:
;; Remove dummy header lines containing tags:
[:h2] (fn [thing]
(when-not (-> thing
:content
first
tags-bracketed-by-colons)
thing))
[:body] content-remove-newline-strings
[:ul] content-remove-newline-strings
[:html] content-remove-newline-strings
[:head] content-remove-newline-strings
[:head] (html/append (page-header css))
[:pre.src-organa] execute-organa
[:div#content :h1.title]
(html/after
`[~@(concat
[(when-not static?
(tag-markup (remove #{"static" "draft"} tags)))
(h/p [(h/span {:class "author"} [(h/a {:href "index.html"}
["PI:NAME:<NAME>END_PI"])])
(h/br)
(h/span {:class "article-header-date"}
[(tformat/unparse dates/article-date-format
date)])])
(h/p [(h/a {:href "index.html"} [(h/strong ["Home"])])
" "
(h/a {:href "blog.html"} ["Other Posts"])])]
prev-next-tags
[(h/div {:class "hspace"} [])])])
[:div#content] (html/append
(h/div {:class "hspace"} [])
prev-next-tags
nav-section
(footer)))))
(defn ^:private as-string [x]
(with-out-str
(pprint/pprint x)))
(defn ^:private process-html-file! [{:keys [target-dir]}
{:keys [file-name date static? draft?
parsed-html tags unparsed-html] :as r}
available-files
alltags
css
parsed-org-file-map]
(->> parsed-html
(transform-enlive file-name
date
available-files
parsed-org-file-map
tags
alltags
css
static?
draft?)
html/emit* ;; turn back into html
(apply str)
(spit (str target-dir "/" file-name ".html")))
(->> r
as-string
(spit (str target-dir "/" file-name ".edn"))))
(defn ^:private html-file-exists [org-file-name]
(-> org-file-name
(clojure.string/replace #"\.org$" ".html")
clojure.java.io/file
.exists))
(defn ^:private available-org-files [site-source-dir]
(->> (fs/files-in-directory site-source-dir :as :file)
(filter (comp #(.endsWith ^String % ".org") str))
(filter html-file-exists)
(remove (comp #(.contains ^String % ".#") str))
(map #(.getName ^File %))
(map #(.substring ^String % 0 (.lastIndexOf ^String % ".")))))
(defn ^:private sh [& cmds]
(apply clojure.java.shell/sh
(clojure.string/split (string/join cmds) #"\s+")))
(defn ^:private ensure-target-dir-exists! [target-dir]
;; FIXME: do it the Java way
(sh "mkdir -p " target-dir))
(defn ^:private stage-site-image-files! [site-source-dir target-dir]
;; FIXME: avoid bash hack?
(doseq [f (filter (partial re-find img/image-file-pattern)
(fs/files-in-directory site-source-dir :as :str))]
(sh "cp -p " f " " target-dir)))
(defn ^:private stage-site-static-files! [site-source-dir target-dir]
(println "Syncing files in static directory...")
(apply clojure.java.shell/sh
(clojure.string/split
(format "rsync -vurt %s/static %s/galleries %s/artworks %s"
site-source-dir
site-source-dir
site-source-dir
target-dir)
#" ")))
;; FIXME: Hack-y?
(def ^:private base-enlive-snippet
(html/html-snippet "<html><head></head><body></body></html>"))
(defn ^:private galleries-path [site-source-dir]
(str site-source-dir "/galleries"))
(defn ^:private generate-thumbnails-for-gallery! [galpath imagefiles]
(doseq [img (remove #(.contains ^String % "-thumb")
imagefiles)
:let [[base _] (fs/splitext img)
thumb-path (format "%s/%s-thumb.png" galpath base)
orig-path (format "%s/%s" galpath img)]]
(when-not (.exists (io/file thumb-path))
(printf "Creating thumbnail file %s from %s...\n"
thumb-path
orig-path)
(img/create-thumbnail! orig-path thumb-path))))
(defn ^:private generate-thumbnails-in-galleries! [site-source-dir]
(let [galleries-dir (galleries-path site-source-dir)]
(doseq [galpath (fs/files-in-directory galleries-dir :as :str)
:let [imagefiles (gal/gallery-images galpath)]]
(printf "Making thumbnails for gallery '%s'\n" (fs/basename galpath))
(generate-thumbnails-for-gallery! galpath imagefiles))))
(defn ^:private gallery-html [css galfiles]
(->> (html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body]
(html/append
[(h/div {:class "gallery"}
(for [f galfiles
:let [[base _] (fs/splitext f)
thumb-path (format "%s-thumb.png" base)]]
(h/a {:href (str "./" f)}
[(h/img {:src (str "./" thumb-path)
:height "250px"}
[])])))]))
(html/emit*)
(apply str)))
(defn ^:private generate-html-for-galleries! [site-source-dir css]
(let [galleries-dir (galleries-path site-source-dir)]
(doseq [galpath (fs/files-in-directory galleries-dir :as :str)
:let [galfiles (gal/gallery-images galpath)]]
(printf "Making gallery '%s'\n" (fs/basename galpath))
(spit (str galpath "/index.html")
(gallery-html css galfiles)))))
(defn ^:private wait-futures [futures]
(loop [cnt 0]
(let [new-cnt (count (filter realized? futures))]
(when-not (every? realized? futures)
(Thread/sleep 500)
(if (= cnt new-cnt)
(recur cnt)
(do
(println new-cnt "completed...")
(recur new-cnt))))))
(doseq [fu futures]
(try
(deref fu)
(catch Throwable t
(println t)))))
(defn ^:private emit-html-to-file [target-dir file-name enlive-tree]
(->> enlive-tree
(html/emit*)
(cons "<!doctype html>\n")
(apply str)
(spit (str target-dir "/" file-name))))
(defn ^:private make-old-home-page [{:keys [target-dir]}
org-files
parsed-org-file-map
tags
css]
(emit-html-to-file
target-dir
"index-old.html"
(html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body] (html/append
[(pages/home-body)
;;(div {:class "hspace"} [])
])
[:div#blogposts] (html/append
[(articles-nav-section "index"
org-files
tags
parsed-org-file-map)
(footer)]))))
(defn ^:private make-blog-page
([config org-files parsed-org-file-map tags css]
(make-blog-page config :all org-files parsed-org-file-map tags css))
([{:keys [target-dir]} tag org-files parsed-org-file-map tags css]
(println (format "Making blog page for tag '%s'" tag))
(let [tag-posts (if (= tag :all)
org-files
(filter (comp (partial some #{tag}) :tags) org-files))]
(emit-html-to-file
target-dir
(str (if (= tag :all) "" (str tag "-"))
"blog.html")
(html/at base-enlive-snippet
[:head] (html/append (page-header css))
[:body] (html/append
[(pages/blog-body)
;;(div {:class "hspace"} [])
])
[:div#blogposts] (html/append
[(articles-nav-section "blog"
tag-posts
tags
parsed-org-file-map)
(footer)]))))))
(defn ^:private remove-gnu-junk [snippet]
(html/at snippet
[:script] nil
[:style] nil))
(defn ^:private files->parsed [files-to-process]
(let [ssd (:site-source-dir config)]
(into {}
(for [f files-to-process]
(let [parsed-html (->> f
(h/parse-org-html ssd)
remove-gnu-junk)
tags (tags-for-org-file parsed-html)]
[f
;; FIXME: It's hacky to have f in both places
{:file-name f
;; FIXME: don't re-parse for dates!
:date (dates/date-for-org-file ssd f)
:title (parse/title-for-org-file parsed-html)
:tags tags
:parsed-html parsed-html
:unparsed-html (apply str (html/emit* parsed-html))
:static? (some #{"static"} tags)
:draft? (some #{"draft"} tags)}])))))
(defn ^:private proof-files-to-process [all-org-files]
(->> all-org-files
(sort-by (fn [fname]
(->> (str fname ".html")
(str (:site-source-dir config) "/")
(dates/date-for-file-by-os))))
reverse
(take 10)))
(defn ^:private generate-site [{:keys [target-dir proof?] :as config}]
(println "The party commences....")
(ensure-target-dir-exists! target-dir)
(let [ssd (:site-source-dir config)
css (->> (str ssd "/index.garden")
load-file
to-css)
all-org-files (available-org-files ssd)
files-to-process (if-not proof?
all-org-files
(proof-files-to-process all-org-files))
_ (println (format "Parsing %d HTML'ed Org files..."
(count files-to-process)))
parsed-org-file-map (files->parsed files-to-process)
org-files (->> parsed-org-file-map
vals
(sort-by :date)
reverse)
alltags (->> org-files
;; Don't show draft/in progress posts:
(remove (comp (partial some #{"draft"}) :tags))
(mapcat :tags)
(remove #{"static" "draft"})
(into #{}))
_ (generate-thumbnails-in-galleries! ssd)
image-future (future (stage-site-image-files! ssd
target-dir))
static-future (future (generate-html-for-galleries! ssd
css)
(stage-site-static-files! ssd
target-dir))]
(println "Making artworks pages...")
(artworks/spit-out-artworks-pages! css)
(make-old-home-page config org-files parsed-org-file-map alltags css)
(make-blog-page config org-files parsed-org-file-map alltags css)
(doseq [tag alltags]
(make-blog-page config tag org-files parsed-org-file-map alltags css))
(println "Making RSS feed...")
(rss/make-rss-feeds "feed.xml" org-files)
(rss/make-rss-feeds "clojure" "feed.clojure.xml" org-files)
(rss/make-rss-feeds "lisp" "feed.lisp.xml" org-files)
(let [page-futures (for [f org-files]
(future
(process-html-file! config
f
org-files
alltags
css
parsed-org-file-map)))]
(println "Waiting for static copies to finish...")
(wait-futures [static-future])
(println "Waiting for image future to finish...")
(wait-futures [image-future])
(println (format "Waiting for %d per-page threads to finish..."
(count page-futures)))
(wait-futures page-futures)
(println "OK"))))
(defn -main []
(generate-site config)
(shutdown-agents))
(comment
(require '[marginalia.core :as marg])
(marg/run-marginalia ["src/organa/core.clj"])
(clojure.java.shell/sh "open" "docs/uberdoc.html")
(generate-site config)
(generate-site (assoc config :proof? true))
(clojure.java.shell/sh "open" "/tmp/organa/index-old.html")
)
|
[
{
"context": "/] dependency-checker\"\n :url \"https://github.com/rm-hull/lein-nvd\"\n :license {\n :name \"The MIT License",
"end": 158,
"score": 0.9996256828308105,
"start": 151,
"tag": "USERNAME",
"value": "rm-hull"
},
{
"context": "rsion\n ;; (see https://github.com/jeremylong/DependencyCheck/issues/3441):\n [c",
"end": 1004,
"score": 0.999687671661377,
"start": 994,
"tag": "USERNAME",
"value": "jeremylong"
},
{
"context": " \"3.8.1\" #_\"Satisfies :pedantic?\"]]\n :scm {:url \"[email protected]:rm-hull/lein-nvd.git\"}\n :source-paths [\"src\"]\n ",
"end": 2091,
"score": 0.9996857643127441,
"start": 2077,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "isfies :pedantic?\"]]\n :scm {:url \"[email protected]:rm-hull/lein-nvd.git\"}\n :source-paths [\"src\"]\n :jar-exc",
"end": 2099,
"score": 0.9986020922660828,
"start": 2092,
"tag": "USERNAME",
"value": "rm-hull"
},
{
"context": "path \"doc/api\"\n :source-uri \"http://github.com/rm-hull/lein-nvd/blob/master/{filepath}#L{line}\" }\n :mi",
"end": 2280,
"score": 0.9989433884620667,
"start": 2273,
"tag": "USERNAME",
"value": "rm-hull"
}
] |
project.clj
|
reducecombine/lein-nvd
| 0 |
(defproject nvd-clojure "1.5.0"
:description "National Vulnerability Database [https://nvd.nist.gov/] dependency-checker"
:url "https://github.com/rm-hull/lein-nvd"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.10.3"]
[clansi "1.0.0"]
[org.clojure/data.json "2.3.1"]
[org.slf4j/slf4j-simple "2.0.0-alpha1"]
[org.owasp/dependency-check-core "6.2.2"]
[rm-hull/table "0.7.1"]
[trptcolin/versioneer "0.2.0"]
[org.clojure/java.classpath "1.0.0"]
[org.clojure/tools.deps.alpha "0.11.931" :exclusions [org.slf4j/jcl-over-slf4j]]
;; Explicitly depend on a certain Jackson, consistently.
;; Otherwise, when using the Lein plugin, Leiningen's own dependencies can pull a different Jackson version
;; (see https://github.com/jeremylong/DependencyCheck/issues/3441):
[com.fasterxml.jackson.core/jackson-databind "2.12.3"]
[com.fasterxml.jackson.core/jackson-annotations "2.12.3"]
[com.fasterxml.jackson.core/jackson-core "2.12.3"]
[com.fasterxml.jackson.module/jackson-module-afterburner "2.12.3"]
[org.apache.maven.resolver/maven-resolver-transport-http "1.7.0" #_"Fixes a CVE"]
[org.apache.maven/maven-core "3.8.1" #_"Fixes a CVE"]
[org.eclipse.jetty/jetty-client "11.0.3" #_"Fixes a CVE"]
[org.apache.maven.resolver/maven-resolver-spi "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-api "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-util "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-impl "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven/maven-resolver-provider "3.8.1" #_"Satisfies :pedantic?"]]
:scm {:url "[email protected]:rm-hull/lein-nvd.git"}
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/lein-nvd/blob/master/{filepath}#L{line}" }
:min-lein-version "2.8.1"
:target-path "target/%s"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-cljfmt "0.7.0"]
[lein-codox "0.10.7"]
[lein-cloverage "1.2.2"]
[lein-ancient "0.7.0"]
[jonase/eastwood "0.4.3"]]
:dependencies [
[clj-kondo "2021.06.01"]
[commons-collections "20040616"]]}
:ci {:pedantic? :abort}
:clj-kondo {:dependencies [[clj-kondo "2021.06.01"]]}})
|
8619
|
(defproject nvd-clojure "1.5.0"
:description "National Vulnerability Database [https://nvd.nist.gov/] dependency-checker"
:url "https://github.com/rm-hull/lein-nvd"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.10.3"]
[clansi "1.0.0"]
[org.clojure/data.json "2.3.1"]
[org.slf4j/slf4j-simple "2.0.0-alpha1"]
[org.owasp/dependency-check-core "6.2.2"]
[rm-hull/table "0.7.1"]
[trptcolin/versioneer "0.2.0"]
[org.clojure/java.classpath "1.0.0"]
[org.clojure/tools.deps.alpha "0.11.931" :exclusions [org.slf4j/jcl-over-slf4j]]
;; Explicitly depend on a certain Jackson, consistently.
;; Otherwise, when using the Lein plugin, Leiningen's own dependencies can pull a different Jackson version
;; (see https://github.com/jeremylong/DependencyCheck/issues/3441):
[com.fasterxml.jackson.core/jackson-databind "2.12.3"]
[com.fasterxml.jackson.core/jackson-annotations "2.12.3"]
[com.fasterxml.jackson.core/jackson-core "2.12.3"]
[com.fasterxml.jackson.module/jackson-module-afterburner "2.12.3"]
[org.apache.maven.resolver/maven-resolver-transport-http "1.7.0" #_"Fixes a CVE"]
[org.apache.maven/maven-core "3.8.1" #_"Fixes a CVE"]
[org.eclipse.jetty/jetty-client "11.0.3" #_"Fixes a CVE"]
[org.apache.maven.resolver/maven-resolver-spi "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-api "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-util "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-impl "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven/maven-resolver-provider "3.8.1" #_"Satisfies :pedantic?"]]
:scm {:url "<EMAIL>:rm-hull/lein-nvd.git"}
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/lein-nvd/blob/master/{filepath}#L{line}" }
:min-lein-version "2.8.1"
:target-path "target/%s"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-cljfmt "0.7.0"]
[lein-codox "0.10.7"]
[lein-cloverage "1.2.2"]
[lein-ancient "0.7.0"]
[jonase/eastwood "0.4.3"]]
:dependencies [
[clj-kondo "2021.06.01"]
[commons-collections "20040616"]]}
:ci {:pedantic? :abort}
:clj-kondo {:dependencies [[clj-kondo "2021.06.01"]]}})
| true |
(defproject nvd-clojure "1.5.0"
:description "National Vulnerability Database [https://nvd.nist.gov/] dependency-checker"
:url "https://github.com/rm-hull/lein-nvd"
:license {
:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.10.3"]
[clansi "1.0.0"]
[org.clojure/data.json "2.3.1"]
[org.slf4j/slf4j-simple "2.0.0-alpha1"]
[org.owasp/dependency-check-core "6.2.2"]
[rm-hull/table "0.7.1"]
[trptcolin/versioneer "0.2.0"]
[org.clojure/java.classpath "1.0.0"]
[org.clojure/tools.deps.alpha "0.11.931" :exclusions [org.slf4j/jcl-over-slf4j]]
;; Explicitly depend on a certain Jackson, consistently.
;; Otherwise, when using the Lein plugin, Leiningen's own dependencies can pull a different Jackson version
;; (see https://github.com/jeremylong/DependencyCheck/issues/3441):
[com.fasterxml.jackson.core/jackson-databind "2.12.3"]
[com.fasterxml.jackson.core/jackson-annotations "2.12.3"]
[com.fasterxml.jackson.core/jackson-core "2.12.3"]
[com.fasterxml.jackson.module/jackson-module-afterburner "2.12.3"]
[org.apache.maven.resolver/maven-resolver-transport-http "1.7.0" #_"Fixes a CVE"]
[org.apache.maven/maven-core "3.8.1" #_"Fixes a CVE"]
[org.eclipse.jetty/jetty-client "11.0.3" #_"Fixes a CVE"]
[org.apache.maven.resolver/maven-resolver-spi "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-api "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-util "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven.resolver/maven-resolver-impl "1.7.0" #_"Satisfies :pedantic?"]
[org.apache.maven/maven-resolver-provider "3.8.1" #_"Satisfies :pedantic?"]]
:scm {:url "PI:EMAIL:<EMAIL>END_PI:rm-hull/lein-nvd.git"}
:source-paths ["src"]
:jar-exclusions [#"(?:^|/).git"]
:codox {
:source-paths ["src"]
:output-path "doc/api"
:source-uri "http://github.com/rm-hull/lein-nvd/blob/master/{filepath}#L{line}" }
:min-lein-version "2.8.1"
:target-path "target/%s"
:profiles {
:dev {
:global-vars {*warn-on-reflection* true}
:plugins [
[lein-cljfmt "0.7.0"]
[lein-codox "0.10.7"]
[lein-cloverage "1.2.2"]
[lein-ancient "0.7.0"]
[jonase/eastwood "0.4.3"]]
:dependencies [
[clj-kondo "2021.06.01"]
[commons-collections "20040616"]]}
:ci {:pedantic? :abort}
:clj-kondo {:dependencies [[clj-kondo "2021.06.01"]]}})
|
[
{
"context": "(=\r\n (= (format \"Hello, %s!\" \"Dave\") \"Hello, Dave!\")\r\n (= (format \"Hello, %s!\" \"Jen",
"end": 35,
"score": 0.9996933341026306,
"start": 31,
"tag": "NAME",
"value": "Dave"
},
{
"context": "(=\r\n (= (format \"Hello, %s!\" \"Dave\") \"Hello, Dave!\")\r\n (= (format \"Hello, %s!\" \"Jenn\") \"Hello, Jen",
"end": 50,
"score": 0.9992752075195312,
"start": 46,
"tag": "NAME",
"value": "Dave"
},
{
"context": "ave\") \"Hello, Dave!\")\r\n (= (format \"Hello, %s!\" \"Jenn\") \"Hello, Jenn!\")\r\n (= (format \"Hello, %s!\" \"Rhe",
"end": 86,
"score": 0.9997149705886841,
"start": 82,
"tag": "NAME",
"value": "Jenn"
},
{
"context": "Dave!\")\r\n (= (format \"Hello, %s!\" \"Jenn\") \"Hello, Jenn!\")\r\n (= (format \"Hello, %s!\" \"Rhea\") \"Hello, Rhe",
"end": 101,
"score": 0.9995949268341064,
"start": 97,
"tag": "NAME",
"value": "Jenn"
},
{
"context": "enn\") \"Hello, Jenn!\")\r\n (= (format \"Hello, %s!\" \"Rhea\") \"Hello, Rhea!\")\r\n true)",
"end": 137,
"score": 0.9996581077575684,
"start": 133,
"tag": "NAME",
"value": "Rhea"
},
{
"context": "Jenn!\")\r\n (= (format \"Hello, %s!\" \"Rhea\") \"Hello, Rhea!\")\r\n true)",
"end": 152,
"score": 0.9995758533477783,
"start": 148,
"tag": "NAME",
"value": "Rhea"
}
] |
src/4clojure/016.clj
|
pine613/4clojure
| 1 |
(=
(= (format "Hello, %s!" "Dave") "Hello, Dave!")
(= (format "Hello, %s!" "Jenn") "Hello, Jenn!")
(= (format "Hello, %s!" "Rhea") "Hello, Rhea!")
true)
|
52900
|
(=
(= (format "Hello, %s!" "<NAME>") "Hello, <NAME>!")
(= (format "Hello, %s!" "<NAME>") "Hello, <NAME>!")
(= (format "Hello, %s!" "<NAME>") "Hello, <NAME>!")
true)
| true |
(=
(= (format "Hello, %s!" "PI:NAME:<NAME>END_PI") "Hello, PI:NAME:<NAME>END_PI!")
(= (format "Hello, %s!" "PI:NAME:<NAME>END_PI") "Hello, PI:NAME:<NAME>END_PI!")
(= (format "Hello, %s!" "PI:NAME:<NAME>END_PI") "Hello, PI:NAME:<NAME>END_PI!")
true)
|
[
{
"context": "ingest-config/cmr-support-email)\n \"[email protected]\"\n '(\"https://cmr.link/g1\" \"https:/",
"end": 1407,
"score": 0.9999056458473206,
"start": 1390,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": ",\n \\\"SubscriberId\\\": \\\"someone1\\\",\n \\\"EmailAddress\\\": ",
"end": 1842,
"score": 0.9997195601463318,
"start": 1834,
"tag": "USERNAME",
"value": "someone1"
},
{
"context": ",\n \\\"EmailAddress\\\": \\\"[email protected]\\\"}\"\n :start-time \"2020-05-04T12:5",
"end": 1911,
"score": 0.9997528195381165,
"start": 1894,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :end-time \"2020-05-05T12:51:36Z\"})]\n (is (= \"[email protected]\" (:to actual)))\n (is (= \"Email Subscription No",
"end": 2050,
"score": 0.999887228012085,
"start": 2033,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
ingest-app/test/cmr/ingest/test/services/subscriptions_helper.clj
|
cgokey/Common-Metadata-Repository
| 0 |
(ns cmr.ingest.test.services.subscriptions-helper
"This tests some of the more complicated functions of cmr.ingest.services.jobs"
(:require
[clj-time.core :as t]
[clojure.test :refer :all]
[cmr.common.date-time-parser :as dtp]
[cmr.common.util :as u :refer [are3]]
[cmr.ingest.config :as ingest-config]
[cmr.ingest.services.subscriptions-helper :as jobs]))
(deftest create-query-params
(is (= {"polygon" "-78,-18,-77,-22,-73,-16,-74,-13,-78,-18"
"concept-id" "G123-PROV1"}
(jobs/create-query-params "polygon=-78,-18,-77,-22,-73,-16,-74,-13,-78,-18&concept-id=G123-PROV1"))))
(deftest email-granule-url-list-test
"This tests the utility function that unpacks a list of urls and turns it into markdown"
(let [actual (jobs/email-granule-url-list '("https://cmr.link/g1"
"https://cmr.link/g2"
"https://cmr.link/g3"))
expected (str "* [https://cmr.link/g1](https://cmr.link/g1)\n"
"* [https://cmr.link/g2](https://cmr.link/g2)\n"
"* [https://cmr.link/g3](https://cmr.link/g3)")]
(is (= expected actual))))
(deftest create-email-test
"This tests the HTML output of the email generation"
(let [actual (jobs/create-email-content
(ingest-config/cmr-support-email)
"[email protected]"
'("https://cmr.link/g1" "https://cmr.link/g2" "https://cmr.link/g3")
{:extra-fields {:collection-concept-id "C1200370131-EDF_DEV06"}
:metadata "{\"Name\": \"valid1\",
\"CollectionConceptId\": \"C1200370131-EDF_DEV06\",
\"Query\": \"updated_since[]=2020-05-04T12:51:36Z\",
\"SubscriberId\": \"someone1\",
\"EmailAddress\": \"[email protected]\"}"
:start-time "2020-05-04T12:51:36Z"
:end-time "2020-05-05T12:51:36Z"})]
(is (= "[email protected]" (:to actual)))
(is (= "Email Subscription Notification" (:subject actual)))
(is (= "text/html" (:type (first (:body actual)))))
(is (= (str "<p>You have subscribed to receive notifications when data is added to the following query:</p>"
"<p><code>C1200370131-EDF_DEV06</code></p>"
"<p><code>updated_since[]=2020-05-04T12:51:36Z</code></p>"
"<p>Running the query with a time window from 2020-05-04T12:51:36Z to 2020-05-05T12:51:36Z, the following granules have been "
"added or updated:</p>"
"<ul><li><a href='https://cmr.link/g1'>https://cmr.link/g1</a></li><li>"
"<a href='https://cmr.link/g2'>https://cmr.link/g2</a></li><li>"
"<a href='https://cmr.link/g3'>https://cmr.link/g3</a></li></ul>"
"<p>To unsubscribe from these notifications, or if you have any questions, "
"please contact us at <a href='mailto:"
(ingest-config/cmr-support-email)
"'>"
(ingest-config/cmr-support-email)
"</a>.</p>")
(:content (first (:body actual)))))))
(deftest subscription->time-constraint-test
"Test the subscription->time-constraint function as it is critical for internal
use. Test for when there is and is not a last-notified-at date and when there
is no date, test that the code will look back with a specified number of seconds"
(let [now (t/now)
one-hour-back (t/minus now (t/seconds 3600))
two-hours-back (t/minus now (t/seconds 7200))]
(testing
"Usecase one: no last-notified-at date, so start an hour ago and end now"
(let [data {:extra-fields {}}
expected (str one-hour-back "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Usecase one: no last-notified-at date, it's explicitly set to nil, so
start an hour ago and end now"
(let [data {:extra-fields {:last-notified-at nil}}
expected (str one-hour-back "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Usecase one: no last-notified-at date, it's explicitly set to nil, so start
two hours ago and end now ; test that look back is not hardcoded"
(let [data {:extra-fields {:last-notified-at nil}}
expected (str two-hours-back "," now)
actual (#'jobs/subscription->time-constraint data now 7200)]
(is (= expected actual))))
(testing
"Use case two: last-notified-at date is specified, start then and end now"
(let [start "2012-01-10T08:00:00.000Z"
data {:extra-fields {:last-notified-at start}}
expected (str start "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Use case two: last-notified-at date is specified, start then and end now,
look back seconds is ignored and can even be crazy"
(let [start "2012-01-10T08:00:00.000Z"
data {:extra-fields {:last-notified-at start}}
expected (str start "," now)
actual (#'jobs/subscription->time-constraint data now -1234)]
(is (= expected actual))))))
(deftest validate-revision-date-range-test
(testing "only start-date throws exception"
(let [revision-date-range "2000-01-01T10:00:00Z,"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "only end-date throws exception"
(let [revision-date-range ",2010-03-10T12:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date before end-date returns nil"
(let [revision-date-range "2000-01-01T10:00:00Z,2010-03-10T12:00:00Z"]
(is (nil? (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date equals end-date throws exception"
(let [revision-date-range "2000-01-01T10:00:00Z,2000-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date after end-date throws exception"
(let [revision-date-range "2010-01-01T10:00:00Z,2000-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "invalid format throws exception"
(let [revision-date-range "2000-01-01T10:00:Z,2010-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range))))))
|
3177
|
(ns cmr.ingest.test.services.subscriptions-helper
"This tests some of the more complicated functions of cmr.ingest.services.jobs"
(:require
[clj-time.core :as t]
[clojure.test :refer :all]
[cmr.common.date-time-parser :as dtp]
[cmr.common.util :as u :refer [are3]]
[cmr.ingest.config :as ingest-config]
[cmr.ingest.services.subscriptions-helper :as jobs]))
(deftest create-query-params
(is (= {"polygon" "-78,-18,-77,-22,-73,-16,-74,-13,-78,-18"
"concept-id" "G123-PROV1"}
(jobs/create-query-params "polygon=-78,-18,-77,-22,-73,-16,-74,-13,-78,-18&concept-id=G123-PROV1"))))
(deftest email-granule-url-list-test
"This tests the utility function that unpacks a list of urls and turns it into markdown"
(let [actual (jobs/email-granule-url-list '("https://cmr.link/g1"
"https://cmr.link/g2"
"https://cmr.link/g3"))
expected (str "* [https://cmr.link/g1](https://cmr.link/g1)\n"
"* [https://cmr.link/g2](https://cmr.link/g2)\n"
"* [https://cmr.link/g3](https://cmr.link/g3)")]
(is (= expected actual))))
(deftest create-email-test
"This tests the HTML output of the email generation"
(let [actual (jobs/create-email-content
(ingest-config/cmr-support-email)
"<EMAIL>"
'("https://cmr.link/g1" "https://cmr.link/g2" "https://cmr.link/g3")
{:extra-fields {:collection-concept-id "C1200370131-EDF_DEV06"}
:metadata "{\"Name\": \"valid1\",
\"CollectionConceptId\": \"C1200370131-EDF_DEV06\",
\"Query\": \"updated_since[]=2020-05-04T12:51:36Z\",
\"SubscriberId\": \"someone1\",
\"EmailAddress\": \"<EMAIL>\"}"
:start-time "2020-05-04T12:51:36Z"
:end-time "2020-05-05T12:51:36Z"})]
(is (= "<EMAIL>" (:to actual)))
(is (= "Email Subscription Notification" (:subject actual)))
(is (= "text/html" (:type (first (:body actual)))))
(is (= (str "<p>You have subscribed to receive notifications when data is added to the following query:</p>"
"<p><code>C1200370131-EDF_DEV06</code></p>"
"<p><code>updated_since[]=2020-05-04T12:51:36Z</code></p>"
"<p>Running the query with a time window from 2020-05-04T12:51:36Z to 2020-05-05T12:51:36Z, the following granules have been "
"added or updated:</p>"
"<ul><li><a href='https://cmr.link/g1'>https://cmr.link/g1</a></li><li>"
"<a href='https://cmr.link/g2'>https://cmr.link/g2</a></li><li>"
"<a href='https://cmr.link/g3'>https://cmr.link/g3</a></li></ul>"
"<p>To unsubscribe from these notifications, or if you have any questions, "
"please contact us at <a href='mailto:"
(ingest-config/cmr-support-email)
"'>"
(ingest-config/cmr-support-email)
"</a>.</p>")
(:content (first (:body actual)))))))
(deftest subscription->time-constraint-test
"Test the subscription->time-constraint function as it is critical for internal
use. Test for when there is and is not a last-notified-at date and when there
is no date, test that the code will look back with a specified number of seconds"
(let [now (t/now)
one-hour-back (t/minus now (t/seconds 3600))
two-hours-back (t/minus now (t/seconds 7200))]
(testing
"Usecase one: no last-notified-at date, so start an hour ago and end now"
(let [data {:extra-fields {}}
expected (str one-hour-back "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Usecase one: no last-notified-at date, it's explicitly set to nil, so
start an hour ago and end now"
(let [data {:extra-fields {:last-notified-at nil}}
expected (str one-hour-back "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Usecase one: no last-notified-at date, it's explicitly set to nil, so start
two hours ago and end now ; test that look back is not hardcoded"
(let [data {:extra-fields {:last-notified-at nil}}
expected (str two-hours-back "," now)
actual (#'jobs/subscription->time-constraint data now 7200)]
(is (= expected actual))))
(testing
"Use case two: last-notified-at date is specified, start then and end now"
(let [start "2012-01-10T08:00:00.000Z"
data {:extra-fields {:last-notified-at start}}
expected (str start "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Use case two: last-notified-at date is specified, start then and end now,
look back seconds is ignored and can even be crazy"
(let [start "2012-01-10T08:00:00.000Z"
data {:extra-fields {:last-notified-at start}}
expected (str start "," now)
actual (#'jobs/subscription->time-constraint data now -1234)]
(is (= expected actual))))))
(deftest validate-revision-date-range-test
(testing "only start-date throws exception"
(let [revision-date-range "2000-01-01T10:00:00Z,"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "only end-date throws exception"
(let [revision-date-range ",2010-03-10T12:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date before end-date returns nil"
(let [revision-date-range "2000-01-01T10:00:00Z,2010-03-10T12:00:00Z"]
(is (nil? (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date equals end-date throws exception"
(let [revision-date-range "2000-01-01T10:00:00Z,2000-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date after end-date throws exception"
(let [revision-date-range "2010-01-01T10:00:00Z,2000-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "invalid format throws exception"
(let [revision-date-range "2000-01-01T10:00:Z,2010-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range))))))
| true |
(ns cmr.ingest.test.services.subscriptions-helper
"This tests some of the more complicated functions of cmr.ingest.services.jobs"
(:require
[clj-time.core :as t]
[clojure.test :refer :all]
[cmr.common.date-time-parser :as dtp]
[cmr.common.util :as u :refer [are3]]
[cmr.ingest.config :as ingest-config]
[cmr.ingest.services.subscriptions-helper :as jobs]))
(deftest create-query-params
(is (= {"polygon" "-78,-18,-77,-22,-73,-16,-74,-13,-78,-18"
"concept-id" "G123-PROV1"}
(jobs/create-query-params "polygon=-78,-18,-77,-22,-73,-16,-74,-13,-78,-18&concept-id=G123-PROV1"))))
(deftest email-granule-url-list-test
"This tests the utility function that unpacks a list of urls and turns it into markdown"
(let [actual (jobs/email-granule-url-list '("https://cmr.link/g1"
"https://cmr.link/g2"
"https://cmr.link/g3"))
expected (str "* [https://cmr.link/g1](https://cmr.link/g1)\n"
"* [https://cmr.link/g2](https://cmr.link/g2)\n"
"* [https://cmr.link/g3](https://cmr.link/g3)")]
(is (= expected actual))))
(deftest create-email-test
"This tests the HTML output of the email generation"
(let [actual (jobs/create-email-content
(ingest-config/cmr-support-email)
"PI:EMAIL:<EMAIL>END_PI"
'("https://cmr.link/g1" "https://cmr.link/g2" "https://cmr.link/g3")
{:extra-fields {:collection-concept-id "C1200370131-EDF_DEV06"}
:metadata "{\"Name\": \"valid1\",
\"CollectionConceptId\": \"C1200370131-EDF_DEV06\",
\"Query\": \"updated_since[]=2020-05-04T12:51:36Z\",
\"SubscriberId\": \"someone1\",
\"EmailAddress\": \"PI:EMAIL:<EMAIL>END_PI\"}"
:start-time "2020-05-04T12:51:36Z"
:end-time "2020-05-05T12:51:36Z"})]
(is (= "PI:EMAIL:<EMAIL>END_PI" (:to actual)))
(is (= "Email Subscription Notification" (:subject actual)))
(is (= "text/html" (:type (first (:body actual)))))
(is (= (str "<p>You have subscribed to receive notifications when data is added to the following query:</p>"
"<p><code>C1200370131-EDF_DEV06</code></p>"
"<p><code>updated_since[]=2020-05-04T12:51:36Z</code></p>"
"<p>Running the query with a time window from 2020-05-04T12:51:36Z to 2020-05-05T12:51:36Z, the following granules have been "
"added or updated:</p>"
"<ul><li><a href='https://cmr.link/g1'>https://cmr.link/g1</a></li><li>"
"<a href='https://cmr.link/g2'>https://cmr.link/g2</a></li><li>"
"<a href='https://cmr.link/g3'>https://cmr.link/g3</a></li></ul>"
"<p>To unsubscribe from these notifications, or if you have any questions, "
"please contact us at <a href='mailto:"
(ingest-config/cmr-support-email)
"'>"
(ingest-config/cmr-support-email)
"</a>.</p>")
(:content (first (:body actual)))))))
(deftest subscription->time-constraint-test
"Test the subscription->time-constraint function as it is critical for internal
use. Test for when there is and is not a last-notified-at date and when there
is no date, test that the code will look back with a specified number of seconds"
(let [now (t/now)
one-hour-back (t/minus now (t/seconds 3600))
two-hours-back (t/minus now (t/seconds 7200))]
(testing
"Usecase one: no last-notified-at date, so start an hour ago and end now"
(let [data {:extra-fields {}}
expected (str one-hour-back "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Usecase one: no last-notified-at date, it's explicitly set to nil, so
start an hour ago and end now"
(let [data {:extra-fields {:last-notified-at nil}}
expected (str one-hour-back "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Usecase one: no last-notified-at date, it's explicitly set to nil, so start
two hours ago and end now ; test that look back is not hardcoded"
(let [data {:extra-fields {:last-notified-at nil}}
expected (str two-hours-back "," now)
actual (#'jobs/subscription->time-constraint data now 7200)]
(is (= expected actual))))
(testing
"Use case two: last-notified-at date is specified, start then and end now"
(let [start "2012-01-10T08:00:00.000Z"
data {:extra-fields {:last-notified-at start}}
expected (str start "," now)
actual (#'jobs/subscription->time-constraint data now 3600)]
(is (= expected actual))))
(testing
"Use case two: last-notified-at date is specified, start then and end now,
look back seconds is ignored and can even be crazy"
(let [start "2012-01-10T08:00:00.000Z"
data {:extra-fields {:last-notified-at start}}
expected (str start "," now)
actual (#'jobs/subscription->time-constraint data now -1234)]
(is (= expected actual))))))
(deftest validate-revision-date-range-test
(testing "only start-date throws exception"
(let [revision-date-range "2000-01-01T10:00:00Z,"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "only end-date throws exception"
(let [revision-date-range ",2010-03-10T12:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date before end-date returns nil"
(let [revision-date-range "2000-01-01T10:00:00Z,2010-03-10T12:00:00Z"]
(is (nil? (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date equals end-date throws exception"
(let [revision-date-range "2000-01-01T10:00:00Z,2000-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "start-date after end-date throws exception"
(let [revision-date-range "2010-01-01T10:00:00Z,2000-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range)))))
(testing "invalid format throws exception"
(let [revision-date-range "2000-01-01T10:00:Z,2010-01-01T10:00:00Z"]
(is (thrown? clojure.lang.ExceptionInfo (#'jobs/validate-revision-date-range revision-date-range))))))
|
[
{
"context": "--------------\n;; rel\n\n(defrel man p)\n\n(fact man 'Bob)\n(fact man 'John)\n(fact man 'Ricky)\n\n(defrel woma",
"end": 22425,
"score": 0.9997568726539612,
"start": 22422,
"tag": "NAME",
"value": "Bob"
},
{
"context": "; rel\n\n(defrel man p)\n\n(fact man 'Bob)\n(fact man 'John)\n(fact man 'Ricky)\n\n(defrel woman p)\n(fact woman ",
"end": 22442,
"score": 0.9997890591621399,
"start": 22438,
"tag": "NAME",
"value": "John"
},
{
"context": "n p)\n\n(fact man 'Bob)\n(fact man 'John)\n(fact man 'Ricky)\n\n(defrel woman p)\n(fact woman 'Mary)\n(fact woman",
"end": 22460,
"score": 0.9996697902679443,
"start": 22455,
"tag": "NAME",
"value": "Ricky"
},
{
"context": "\n(fact man 'Ricky)\n\n(defrel woman p)\n(fact woman 'Mary)\n(fact woman 'Martha)\n(fact woman 'Lucy)\n\n(defrel",
"end": 22497,
"score": 0.9994663000106812,
"start": 22493,
"tag": "NAME",
"value": "Mary"
},
{
"context": "\n(defrel woman p)\n(fact woman 'Mary)\n(fact woman 'Martha)\n(fact woman 'Lucy)\n\n(defrel likes p1 p2)\n(fact l",
"end": 22518,
"score": 0.9996411800384521,
"start": 22512,
"tag": "NAME",
"value": "Martha"
},
{
"context": "ct woman 'Mary)\n(fact woman 'Martha)\n(fact woman 'Lucy)\n\n(defrel likes p1 p2)\n(fact likes 'Bob 'Mary)\n(f",
"end": 22537,
"score": 0.9994995594024658,
"start": 22533,
"tag": "NAME",
"value": "Lucy"
},
{
"context": "t woman 'Lucy)\n\n(defrel likes p1 p2)\n(fact likes 'Bob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ri",
"end": 22577,
"score": 0.9997629523277283,
"start": 22574,
"tag": "NAME",
"value": "Bob"
},
{
"context": "an 'Lucy)\n\n(defrel likes p1 p2)\n(fact likes 'Bob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'L",
"end": 22583,
"score": 0.9995651245117188,
"start": 22579,
"tag": "NAME",
"value": "Mary"
},
{
"context": "likes p1 p2)\n(fact likes 'Bob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'Lucy)\n\n(defrel fun p",
"end": 22602,
"score": 0.9997515082359314,
"start": 22598,
"tag": "NAME",
"value": "John"
},
{
"context": "p1 p2)\n(fact likes 'Bob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'Lucy)\n\n(defrel fun p)\n(fact ",
"end": 22610,
"score": 0.9994434118270874,
"start": 22604,
"tag": "NAME",
"value": "Martha"
},
{
"context": "ob 'Mary)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'Lucy)\n\n(defrel fun p)\n(fact fun 'Lucy)\n\n(deftest",
"end": 22630,
"score": 0.9995209574699402,
"start": 22625,
"tag": "NAME",
"value": "Ricky"
},
{
"context": "y)\n(fact likes 'John 'Martha)\n(fact likes 'Ricky 'Lucy)\n\n(defrel fun p)\n(fact fun 'Lucy)\n\n(deftest test-",
"end": 22636,
"score": 0.9981077909469604,
"start": 22632,
"tag": "NAME",
"value": "Lucy"
},
{
"context": " (fun y)\n (== q [x y])))\n '([Ricky Lucy]))))\n\n(retraction likes 'Bob 'Mary)\n\n(deftest tes",
"end": 22831,
"score": 0.9722714424133301,
"start": 22821,
"tag": "NAME",
"value": "Ricky Lucy"
},
{
"context": ")\n '([Ricky Lucy]))))\n\n(retraction likes 'Bob 'Mary)\n\n(deftest test-rel-retract\n (is (= (run* ",
"end": 22860,
"score": 0.9997557997703552,
"start": 22857,
"tag": "NAME",
"value": "Bob"
},
{
"context": " '([Ricky Lucy]))))\n\n(retraction likes 'Bob 'Mary)\n\n(deftest test-rel-retract\n (is (= (run* [q]\n ",
"end": 22866,
"score": 0.9996219873428345,
"start": 22862,
"tag": "NAME",
"value": "Mary"
},
{
"context": "ikes x y)\n (== q [x y])))\n '([John Martha] [Ricky Lucy]))))\n\n(defrel rel1 ^:index a)\n(fact ",
"end": 23014,
"score": 0.9460158348083496,
"start": 23003,
"tag": "NAME",
"value": "John Martha"
},
{
"context": " (== q [x y])))\n '([John Martha] [Ricky Lucy]))))\n\n(defrel rel1 ^:index a)\n(fact rel1 [1 2])\n\n",
"end": 23027,
"score": 0.9943838119506836,
"start": 23017,
"tag": "NAME",
"value": "Ricky Lucy"
},
{
"context": "===============================================\n;; cKanren\n\n(deftest test-pair []\n (is (= (pair 1 2)\n ",
"end": 29548,
"score": 0.9802331924438477,
"start": 29541,
"tag": "NAME",
"value": "cKanren"
}
] |
src/test/clojure/clojure/core/logic/tests.clj
|
hugoduncan/core.logic
| 0 |
(ns clojure.core.logic.tests
(:refer-clojure :exclude [==])
(:use [clojure.core.logic :exclude [is] :as l]
clojure.test :reload)
(:require [clojure.pprint :as pp]))
;; =============================================================================
;; unify
;; -----------------------------------------------------------------------------
;; nil
(deftest unify-nil-object-1
(is (= (unify empty-s nil 1) nil)))
(deftest unify-nil-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x nil)]
(is (= (unify empty-s nil x) os))))
(deftest unify-nil-lseq-1
(let [x (lvar 'x)]
(is (= (unify empty-s nil (lcons 1 x)) nil))))
(deftest unify-nil-map-1
(let [x (lvar 'x)]
(is (= (unify empty-s nil {}) nil))))
;; -----------------------------------------------------------------------------
;; object
(deftest unify-object-nil-1
(is (= (unify empty-s 1 nil))))
(deftest unify-object-object-1
(is (= (unify empty-s 1 1) empty-s)))
(deftest unify-object-object-2
(is (= (unify empty-s :foo :foo) empty-s)))
(deftest unify-object-object-3
(is (= (unify empty-s 'foo 'foo) empty-s)))
(deftest unify-object-object-4
(is (= (unify empty-s "foo" "foo") empty-s)))
(deftest unify-object-object-5
(is (= (unify empty-s 1 2) nil)))
(deftest unify-object-object-6
(is (= (unify empty-s 2 1) nil)))
(deftest unify-object-object-7
(is (= (unify empty-s :foo :bar) nil)))
(deftest unify-object-object-8
(is (= (unify empty-s 'foo 'bar) nil)))
(deftest unify-object-object-9
(is (= (unify empty-s "foo" "bar") nil)))
(deftest unify-object-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s 1 x) os))))
(deftest unify-object-lcons-1
(let [x (lvar 'x)]
(is (= (unify empty-s 1 (lcons 1 'x)) nil))))
(deftest unify-object-seq-1
(is (= (unify empty-s 1 '()) nil)))
(deftest unify-object-seq-2
(is (= (unify empty-s 1 '[]) nil)))
(deftest unify-object-map-1
(is (= (unify empty-s 1 {}) nil)))
;; -----------------------------------------------------------------------------
;; lvar
(deftest unify-lvar-object-1
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s x 1) os))))
(deftest unify-lvar-lvar-1
(let [x (lvar 'x)
y (lvar 'y)
os (ext-no-check empty-s x y)]
(is (= (unify empty-s x y) os))))
(deftest unify-lvar-lcons-1
(let [x (lvar 'x)
y (lvar 'y)
l (lcons 1 y)
os (ext-no-check empty-s x l)]
(is (= (unify empty-s x l) os))))
(deftest unify-lvar-seq-1
(let [x (lvar 'x)
os (ext-no-check empty-s x [])]
(is (= (unify empty-s x []) os))))
(deftest unify-lvar-seq-2
(let [x (lvar 'x)
os (ext-no-check empty-s x [1 2 3])]
(is (= (unify empty-s x [1 2 3]) os))))
(deftest unify-lvar-seq-3
(let [x (lvar 'x)
os (ext-no-check empty-s x '())]
(is (= (unify empty-s x '()) os))))
(deftest unify-lvar-seq-4
(let [x (lvar 'x)
os (ext-no-check empty-s x '(1 2 3))]
(is (= (unify empty-s x '(1 2 3)) os))))
(deftest unify-lvar-map-1
(let [x (lvar 'x)
os (ext-no-check empty-s x {})]
(is (= (unify empty-s x {}) os))))
(deftest unify-lvar-map-2
(let [x (lvar 'x)
os (ext-no-check empty-s x {1 2 3 4})]
(is (= (unify empty-s x {1 2 3 4}) os))))
;; -----------------------------------------------------------------------------
;; lcons
(deftest unify-lcons-object-1
(let [x (lvar 'x)]
(is (= (unify empty-s (lcons 1 x) 1) nil))))
(deftest unify-lcons-lvar-1
(let [x (lvar 'x)
y (lvar 'y)
l (lcons 1 y)
os (ext-no-check empty-s x l)]
(is (= (unify empty-s l x) os))))
(deftest unify-lcons-lcons-1
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 x)
lc2 (lcons 1 y)
os (ext-no-check empty-s x y)]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-2
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons z y))
os (-> empty-s
(ext-no-check x y)
(ext-no-check z 2))]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-3
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 2 (lcons 3 y)))
os (ext-no-check empty-s x (lcons 3 y))]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-4
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 3 (lcons 4 y)))]
(is (= (unify empty-s lc1 lc2) nil))))
(deftest unify-lcons-lcons-5
(let [x (lvar 'x)
y (lvar 'y)
lc2 (lcons 1 (lcons 2 x))
lc1 (lcons 1 (lcons 3 (lcons 4 y)))]
(is (= (unify empty-s lc1 lc2) nil))))
(deftest unify-lcons-lcons-6
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 2 y))
os (ext-no-check empty-s x y)]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-seq-1
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 2 3 4)
os (ext-no-check empty-s x '(3 4))]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-2
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons y (lcons 3 x)))
l1 '(1 2 3 4)
os (-> empty-s
(ext-no-check x '(4))
(ext-no-check y 2))]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-3
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 (lcons 3 x)))
l1 '(1 2 3)
os (ext-no-check empty-s x '())]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-4
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 3 x))
l1 '(1 2 3 4)]
(is (= (unify empty-s lc1 l1) nil))))
(deftest unify-lcons-seq-5
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 3 4 5)]
(is (= (unify empty-s lc1 l1) nil))))
(deftest unify-lcons-map-1
(is (= (unify empty-s (lcons 1 (lvar 'x)) {}) nil)))
;; -----------------------------------------------------------------------------
;; seq
(deftest unify-seq-object-1
(is (= (unify empty-s '() 1) nil)))
(deftest unify-seq-object-2
(is (= (unify empty-s [] 1) nil)))
(deftest unify-seq-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x [])]
(is (= (unify empty-s [] x) os))))
(deftest unify-seq-lcons-1
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 2 3 4)
os (ext-no-check empty-s x '(3 4))]
(is (= (unify empty-s l1 lc1) os))))
(deftest unify-seq-seq-1
(is (= (unify empty-s [1 2 3] [1 2 3]) empty-s)))
(deftest unify-seq-seq-2
(is (= (unify empty-s '(1 2 3) [1 2 3]) empty-s)))
(deftest unify-seq-seq-3
(is (= (unify empty-s '(1 2 3) '(1 2 3)) empty-s)))
(deftest unify-seq-seq-4
(let [x (lvar 'x)
os (ext-no-check empty-s x 2)]
(is (= (unify empty-s `(1 ~x 3) `(1 2 3)) os))))
(deftest unify-seq-seq-5
(is (= (unify empty-s [1 2] [1 2 3]) nil)))
(deftest unify-seq-seq-6
(is (= (unify empty-s '(1 2) [1 2 3]) nil)))
(deftest unify-seq-seq-7
(is (= (unify empty-s [1 2 3] [3 2 1]) nil)))
(deftest unify-seq-seq-8
(is (= (unify empty-s '() '()) empty-s)))
(deftest unify-seq-seq-9
(is (= (unify empty-s '() '(1)) nil)))
(deftest unify-seq-seq-10
(is (= (unify empty-s '(1) '()) nil)))
(deftest unify-seq-seq-11
(is (= (unify empty-s [[1 2]] [[1 2]]) empty-s)))
(deftest unify-seq-seq-12
(is (= (unify empty-s [[1 2]] [[2 1]]) nil)))
(deftest unify-seq-seq-13
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s [[x 2]] [[1 2]]) os))))
(deftest unify-seq-seq-14
(let [x (lvar 'x)
os (ext-no-check empty-s x [1 2])]
(is (= (unify empty-s [x] [[1 2]]) os))))
(deftest unify-seq-seq-15
(let [x (lvar 'x) y (lvar 'y)
u (lvar 'u) v (lvar 'v)
os (-> empty-s
(ext-no-check x 'b)
(ext-no-check y 'a))]
(is (= (unify empty-s ['a x] [y 'b]) os))))
(deftest unify-seq-map-1
(is (= (unify empty-s [] {}) nil)))
(deftest unify-seq-map-2
(is (= (unify empty-s '() {}) nil)))
;; -----------------------------------------------------------------------------
;; map
(deftest unify-map-object-1
(is (= (unify empty-s {} 1) nil)))
(deftest unify-map-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x {})]
(is (= (unify empty-s {} x) os))))
(deftest unify-map-lcons-1
(let [x (lvar 'x)]
(is (= (unify empty-s {} (lcons 1 x)) nil))))
(deftest unify-map-seq-1
(is (= (unify empty-s {} '()) nil)))
(deftest unify-map-map-1
(is (= (unify empty-s {} {}) empty-s)))
(deftest unify-map-map-2
(is (= (unify empty-s {1 2 3 4} {1 2 3 4}) empty-s)))
(deftest unify-map-map-3
(is (= (unify empty-s {1 2} {1 2 3 4}) nil)))
(deftest unify-map-map-4
(let [x (lvar 'x)
m1 {1 2 3 4}
m2 {1 2 3 x}
os (ext-no-check empty-s x 4)]
(is (= (unify empty-s m1 m2) os))))
(deftest unify-map-map-5
(let [x (lvar 'x)
m1 {1 2 3 4}
m2 {1 4 3 x}]
(is (= (unify empty-s m1 m2) nil))))
(defstruct foo-struct :a :b)
(deftest unify-struct-map-1
(let [x (lvar 'x)
m1 (struct-map foo-struct :a 1 :b 2)
m2 (struct-map foo-struct :a 1 :b x)
os (ext-no-check empty-s x 2)]
(is (= (unify empty-s m1 m2) os))))
(deftest unify-struct-map-2
(let [x (lvar 'x)
m1 (struct-map foo-struct :a 1 :b 2)
m2 (struct-map foo-struct :a 1 :b 3)]
(is (= (unify empty-s m1 m2) nil))))
;; =============================================================================
;; walk
(deftest test-basic-walk
(is (= (let [x (lvar 'x)
y (lvar 'y)
ss (to-s [[x 5] [y x]])]
(walk ss y))
5)))
(deftest test-deep-walk
(is (= (let [[x y z c b a :as s] (map lvar '[x y z c b a])
ss (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])]
(walk ss a))
5)))
;; =============================================================================
;; reify
(deftest test-reify-lvar-name
(is (= (let [x (lvar 'x)
y (lvar 'y)]
(reify-lvar-name (to-s [[x 5] [y x]])))
'_.2)))
;; =============================================================================
;; walk*
(deftest test-walk*
(is (= (let [x (lvar 'x)
y (lvar 'y)]
(walk* (to-s [[x 5] [y x]]) `(~x ~y)))
'(5 5))))
;; =============================================================================
;; run and unify
(deftest test-basic-unify
(is (= (run* [q]
(== true q))
'(true))))
(deftest test-basic-unify-2
(is (= (run* [q]
(fresh [x y]
(== [x y] [1 5])
(== [x y] q)))
[[1 5]])))
(deftest test-basic-unify-3
(is (= (run* [q]
(fresh [x y]
(== [x y] q)))
'[[_.0 _.1]])))
;; =============================================================================
;; fail
(deftest test-basic-failure
(is (= (run* [q]
fail
(== true q))
[])))
;; =============================================================================
;; Basic
(deftest test-all
(is (= (run* [q]
(all
(== 1 1)
(== q true)))
'(true))))
;; =============================================================================
;; TRS
(defn pairo [p]
(fresh [a d]
(== (lcons a d) p)))
(defn twino [p]
(fresh [x]
(conso x x p)))
(defn listo [l]
(conde
[(emptyo l) s#]
[(pairo l)
(fresh [d]
(resto l d)
(listo d))]))
(defn flatteno [s out]
(conde
[(emptyo s) (== '() out)]
[(pairo s)
(fresh [a d res-a res-d]
(conso a d s)
(flatteno a res-a)
(flatteno d res-d)
(appendo res-a res-d out))]
[(conso s '() out)]))
;; =============================================================================
;; conde
(deftest test-basic-conde
(is (= (run* [x]
(conde
[(== x 'olive) succeed]
[succeed succeed]
[(== x 'oil) succeed]))
'[olive _.0 oil])))
(deftest test-basic-conde-2
(is (= (run* [r]
(fresh [x y]
(conde
[(== 'split x) (== 'pea y)]
[(== 'navy x) (== 'bean y)])
(== (cons x (cons y ())) r)))
'[(split pea) (navy bean)])))
(defn teacupo [x]
(conde
[(== 'tea x) s#]
[(== 'cup x) s#]))
(deftest test-basic-conde-e-3
(is (= (run* [r]
(fresh [x y]
(conde
[(teacupo x) (== true y) s#]
[(== false x) (== true y)])
(== (cons x (cons y ())) r)))
'((false true) (tea true) (cup true)))))
;; =============================================================================
;; conso
(deftest test-conso
(is (= (run* [q]
(fresh [a d]
(conso a d '())))
())))
(deftest test-conso-1
(let [a (lvar 'a)
d (lvar 'd)]
(is (= (run* [q]
(conso a d q))
[(lcons a d)]))))
(deftest test-conso-2
(is (= (run* [q]
(== [q] nil))
[])))
(deftest test-conso-3
(is (=
(run* [q]
(conso 'a nil q))
'[(a)])))
(deftest test-conso-4
(is (= (run* [q]
(conso 'a '(d) q))
'[(a d)])))
(deftest test-conso-empty-list
(is (= (run* [q]
(conso 'a q '(a)))
'[()])))
(deftest test-conso-5
(is (= (run* [q]
(conso q '(b c) '(a b c)))
'[a])))
;; =============================================================================
;; firsto
(deftest test-firsto
(is (= (run* [q]
(firsto q '(1 2)))
(list (lcons '(1 2) (lvar 'x))))))
;; =============================================================================
;; resto
(deftest test-resto
(is (= (run* [q]
(resto q '(1 2)))
'[(_.0 1 2)])))
(deftest test-resto-2
(is (= (run* [q]
(resto q [1 2]))
'[(_.0 1 2)])))
(deftest test-resto-3
(is (= (run* [q]
(resto [1 2] q))
'[(2)])))
(deftest test-resto-4
(is (= (run* [q]
(resto [1 2 3 4 5 6 7 8] q))
'[(2 3 4 5 6 7 8)])))
;; =============================================================================
;; flatteno
(deftest test-flatteno
(is (= (run* [x]
(flatteno '[[a b] c] x))
'(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ())
(a (b) (c)) (a (b) c) (a (b) c ()) (a b (c))
(a b () (c)) (a b c) (a b c ()) (a b () c)
(a b () c ())))))
;; =============================================================================
;; membero
(deftest membero-1
(is (= (run* [q]
(all
(== q [(lvar)])
(membero ['foo (lvar)] q)
(membero [(lvar) 'bar] q)))
'([[foo bar]]))))
(deftest membero-2
(is (= (run* [q]
(all
(== q [(lvar) (lvar)])
(membero ['foo (lvar)] q)
(membero [(lvar) 'bar] q)))
'([[foo bar] _.0] [[foo _.0] [_.1 bar]]
[[_.0 bar] [foo _.1]] [_.0 [foo bar]]))))
;; -----------------------------------------------------------------------------
;; rembero
(deftest rembero-1
(is (= (run 1 [q]
(rembero 'b '(a b c b d) q))
'((a c b d)))))
;; -----------------------------------------------------------------------------
;; conde clause count
(defn digit-1 [x]
(conde
[(== 0 x)]))
(defn digit-4 [x]
(conde
[(== 0 x)]
[(== 1 x)]
[(== 2 x)]
[(== 3 x)]))
(deftest test-conde-1-clause
(is (= (run* [q]
(fresh [x y]
(digit-1 x)
(digit-1 y)
(== q [x y])))
'([0 0]))))
(deftest test-conde-4-clauses
(is (= (run* [q]
(fresh [x y]
(digit-4 x)
(digit-4 y)
(== q [x y])))
'([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0]
[1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3]))))
;; -----------------------------------------------------------------------------
;; anyo
(defn anyo [q]
(conde
[q s#]
[(anyo q)]))
(deftest test-anyo-1
(is (= (run 1 [q]
(anyo s#)
(== true q))
(list true))))
(deftest test-anyo-2
(is (= (run 5 [q]
(anyo s#)
(== true q))
(list true true true true true))))
;; -----------------------------------------------------------------------------
;; divergence
(def f1 (fresh [] f1))
(deftest test-divergence-1
(is (= (run 1 [q]
(conde
[f1]
[(== false false)]))
'(_.0))))
(deftest test-divergence-2
(is (= (run 1 [q]
(conde
[f1 (== false false)]
[(== false false)]))
'(_.0))))
(def f2
(fresh []
(conde
[f2 (conde
[f2]
[(== false false)])]
[(== false false)])))
(deftest test-divergence-3
(is (= (run 5 [q] f2)
'(_.0 _.0 _.0 _.0 _.0))))
;; -----------------------------------------------------------------------------
;; conda (soft-cut)
(deftest test-conda-1
(is (= (run* [x]
(conda
[(== 'olive x) s#]
[(== 'oil x) s#]
[u#]))
'(olive))))
(deftest test-conda-2
(is (= (run* [x]
(conda
[(== 'virgin x) u#]
[(== 'olive x) s#]
[(== 'oil x) s#]
[u#]))
'())))
(deftest test-conda-3
(is (= (run* [x]
(fresh (x y)
(== 'split x)
(== 'pea y)
(conda
[(== 'split x) (== x y)]
[s#]))
(== true x))
'())))
(deftest test-conda-4
(is (= (run* [x]
(fresh (x y)
(== 'split x)
(== 'pea y)
(conda
[(== x y) (== 'split x)]
[s#]))
(== true x))
'(true))))
(defn not-pastao [x]
(conda
[(== 'pasta x) u#]
[s#]))
(deftest test-conda-5
(is (= (run* [x]
(conda
[(not-pastao x)]
[(== 'spaghetti x)]))
'(spaghetti))))
;; -----------------------------------------------------------------------------
;; condu (committed-choice)
(comment
(defn onceo [g]
(condu
(g s#)))
(deftest test-condu-1
(is (= (run* [x]
(onceo (teacupo x)))
'(tea))))
)
(deftest test-condu-2
(is (= (run* [r]
(conde
[(teacupo r) s#]
[(== false r) s#]))
'(false tea cup))))
(deftest test-condu-3
(is (= (run* [r]
(conda
[(teacupo r) s#]
[(== false r) s#]))
'(tea cup))))
;; -----------------------------------------------------------------------------
;; disequality
(deftest test-disequality-1
(is (= (run* [q]
(fresh [x]
(!= x 1)
(== q x)))
'((_.0 :- (!= _.0 1))))))
(deftest test-disequality-2
(is (= (run* [q]
(fresh [x]
(== q x)
(!= x 1)))
'((_.0 :- (!= _.0 1))))))
(deftest test-disequality-3
(is (= (run* [q]
(fresh [x]
(!= x 1)
(== x 1)
(== q x)))
())))
(deftest test-disequality-4
(is (= (run* [q]
(fresh [x]
(== x 1)
(!= x 1)
(== q x)))
())))
(deftest test-disequality-5
(is (= (run* [q]
(fresh [x y]
(!= x y)
(== x 1)
(== y 1)
(== q x)))
())))
(deftest test-disequality-6
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 1)
(!= x y)
(== q x)))
())))
(deftest test-disequality-7
(is (= (run* [q]
(fresh [x y]
(== x 1)
(!= x y)
(== y 2)
(== q x)))
'(1))))
(deftest test-disequality-8
(is (= (run* [q]
(fresh [x y]
(!= [x 2] [y 1])
(== x 1)
(== y 3)
(== q [x y])))
'([1 3]))))
(deftest test-disequality-9
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 3)
(!= [x 2] [y 1])
(== q [x y])))
'([1 3]))))
(deftest test-disequality-10
(is (= (run* [q]
(fresh [x y]
(!= [x 2] [1 y])
(== x 1)
(== y 2)
(== q [x y])))
())))
(deftest test-disequality-11
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 2)
(!= [x 2] [1 y])
(== q [x y])))
())))
(deftest test-disequality-12
(is (= (run* [q]
(fresh [x y z]
(!= x y)
(== y z)
(== x z)
(== q x)))
())))
(deftest test-disequality-13
(is (= (run* [q]
(fresh [x y z]
(== y z)
(== x z)
(!= x y)
(== q x)))
())))
(deftest test-disequality-14
(is (= (run* [q]
(fresh [x y z]
(== z y)
(== x z)
(!= x y)
(== q x)))
())))
(deftest test-disequality-15
(is (= (run* [q]
(fresh [x y]
(== q [x y])
(!= x 1)
(!= y 2)))
'(([_.0 _.1] :- (!= _.1 2) (!= _.0 1))))))
;; -----------------------------------------------------------------------------
;; tabled
(defne arco [x y]
([:a :b])
([:b :a])
([:b :d]))
(def patho
(tabled [x y]
(conde
[(arco x y)]
[(fresh [z]
(arco x z)
(patho z y))])))
(deftest test-tabled-1
(is (= (run* [q] (patho :a q))
'(:b :a :d))))
(defne arco-2 [x y]
([1 2])
([1 4])
([1 3])
([2 3])
([2 5])
([3 4])
([3 5])
([4 5]))
(def patho-2
(tabled [x y]
(conde
[(arco-2 x y)]
[(fresh [z]
(arco-2 x z)
(patho-2 z y))])))
(deftest test-tabled-2
(let [r (set (run* [q] (patho-2 1 q)))]
(is (and (= (count r) 4)
(= r #{2 3 4 5})))))
;; -----------------------------------------------------------------------------
;; rel
(defrel man p)
(fact man 'Bob)
(fact man 'John)
(fact man 'Ricky)
(defrel woman p)
(fact woman 'Mary)
(fact woman 'Martha)
(fact woman 'Lucy)
(defrel likes p1 p2)
(fact likes 'Bob 'Mary)
(fact likes 'John 'Martha)
(fact likes 'Ricky 'Lucy)
(defrel fun p)
(fact fun 'Lucy)
(deftest test-rel-1
(is (= (run* [q]
(fresh [x y]
(likes x y)
(fun y)
(== q [x y])))
'([Ricky Lucy]))))
(retraction likes 'Bob 'Mary)
(deftest test-rel-retract
(is (= (run* [q]
(fresh [x y]
(likes x y)
(== q [x y])))
'([John Martha] [Ricky Lucy]))))
(defrel rel1 ^:index a)
(fact rel1 [1 2])
(deftest test-rel-logic-29
(is (= (run* [q]
(fresh [a]
(rel1 [q a])
(== a 2)))
'(1))))
(defrel rel2 ^:index e ^:index a ^:index v)
(facts rel2 [[:e1 :a1 :v1]
[:e1 :a2 :v2]])
(retractions rel2 [[:e1 :a1 :v1]
[:e1 :a1 :v1]
[:e1 :a2 :v2]])
(deftest rel2-dup-retractions
(is (= (run* [out]
(fresh [e a v]
(rel2 e :a1 :v1)
(rel2 e a v)
(== [e a v] out))))
'()))
;; -----------------------------------------------------------------------------
;; nil in collection
(deftest test-nil-in-coll-1
(is (= (run* [q]
(== q [nil]))
'([nil]))))
(deftest test-nil-in-coll-2
(is (= (run* [q]
(== q [1 nil]))
'([1 nil]))))
(deftest test-nil-in-coll-3
(is (= (run* [q]
(== q [nil 1]))
'([nil 1]))))
(deftest test-nil-in-coll-4
(is (= (run* [q]
(== q '(nil)))
'((nil)))))
(deftest test-nil-in-coll-5
(is (= (run* [q]
(== q {:foo nil}))
'({:foo nil}))))
(deftest test-nil-in-coll-6
(is (= (run* [q]
(== q {nil :foo}))
'({nil :foo}))))
;; -----------------------------------------------------------------------------
;; Unifier
(deftest test-unifier-1
(is (= (unifier '(?x ?y) '(1 2))
'(1 2))))
(deftest test-unifier-2
(is (= (unifier '(?x ?y 3) '(1 2 ?z))
'(1 2 3))))
(deftest test-unifier-3
(is (= (unifier '[(?x . ?y) 3] [[1 2] 3])
'[(1 2) 3])))
(deftest test-unifier-4
(is (= (unifier '(?x . ?y) '(1 . ?z))
(lcons 1 '_.0))))
(deftest test-unifier-5
(is (= (unifier '(?x 2 . ?y) '(1 2 3 4 5))
'(1 2 3 4 5))))
(deftest test-unifier-6
(is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
(deftest test-unifier-7
(is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
(deftest test-unifier-8 ;;nested maps
(is (= (unifier '{:a {:b ?b}} {:a {:b 1}})
{:a {:b 1}})))
(deftest test-unifier-9 ;;nested vectors
(is (= (unifier '[?a [?b ?c] :d] [:a [:b :c] :d])
[:a [:b :c] :d])))
(deftest test-unifier-10 ;;nested seqs
(is (= (unifier '(?a (?b ?c) :d) '(:a (:b :c) :d))
'(:a (:b :c) :d))))
(deftest test-unifier-11 ;;all together now
(is (= (unifier '{:a [?b (?c [?d {:e ?e}])]} {:a [:b '(:c [:d {:e :e}])]})
{:a [:b '(:c [:d {:e :e}])]})))
(deftest test-binding-map-1
(is (= (binding-map '(?x ?y) '(1 2))
'{?x 1 ?y 2})))
(deftest test-binding-map-2
(is (= (binding-map '(?x ?y 3) '(1 2 ?z))
'{?x 1 ?y 2 ?z 3})))
(deftest test-binding-map-3
(is (= (binding-map '[(?x . ?y) 3] [[1 2] 3])
'{?x 1 ?y (2)})))
(deftest test-binding-map-4
(is (= (binding-map '(?x . ?y) '(1 . ?z))
'{?z _.0, ?x 1, ?y _.0})))
(deftest test-binding-map-5
(is (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5))
'{?x 1 ?y (3 4 5)})))
(deftest test-binding-map-6
(is (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
;; -----------------------------------------------------------------------------
;; Occurs Check
(deftest test-occurs-check-1
(is (= (run* [q]
(== q [q]))
())))
;; -----------------------------------------------------------------------------
;; Unifications that should fail
(deftest test-unify-fail-1
(is (= (run* [p] (fresh [a b] (== b ()) (== '(0 1) (lcons a b)) (== p [a b])))
())))
(deftest test-unify-fail-2
(is (= (run* [p] (fresh [a b] (== b '(1)) (== '(0) (lcons a b)) (== p [a b])))
())))
(deftest test-unify-fail-3
(is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d])))
())))
;; -----------------------------------------------------------------------------
;; Pattern matching functions preserve metadata
(defne ^:tabled dummy
"Docstring"
[x l]
([_ [x . tail]])
([_ [head . tail]]
(membero x tail)))
(deftest test-metadata-defne
(is (= (-> #'dummy meta :tabled)
true))
(is (= (-> #'dummy meta :doc)
"Docstring")))
(defn locals-membero [x l]
(matche [l]
([[x . tail]])
([[head . tail]]
(locals-membero x tail))))
(deftest test-matche-with-locals
(is (= [true] (run* [q]
(locals-membero 'foo [1 2 3 4 5 'foo])
(== q true))))
(is (= [] (run* [q]
(locals-membero 'foo [1 2 3 4 5])
(== true q)))))
;; -----------------------------------------------------------------------------
;; Pattern matching inline expression support
(defn s [n] (llist n []))
(def zero 0)
(def one (s zero))
(def two (s one))
(def three (s two))
(def four (s three))
(def five (s four))
(def six (s five))
(defn natural-number [x]
(matche [x]
([zero])
([(s y)] (natural-number y))))
(deftest test-matche-with-expr
(is (= (run* [q] (natural-number one))
'(_.0 _.0))))
;; -----------------------------------------------------------------------------
;; Pattern matching other data structures
(defne match-map [m o]
([{:foo {:bar o}} _]))
(defn test-defne-map []
(is (= (run* [q]
(match-map {:foo {:bar 1}} q))
'(1))))
;; -----------------------------------------------------------------------------
;; Tickets
(deftest test-31-unifier-associative
(is (= (binding [*reify-vars* false]
(unifier '{:a ?x} '{:a ?y} '{:a 5}))
{:a 5}))
(is (= (binding [*reify-vars* false]
(unifier '{:a ?x} '{:a 5} '{:a ?y}))
{:a 5})))
(deftest test-34-unify-with-metadata
(is (run* [q]
(== q (quote ^:haz-meta-daytuhs (form form form))))
'((^:haz-meta-daytuhs (form form form)))))
(deftest test-42-multiple-run-parameters
(is (= '[[3 _.0 [3 _.0]]]
(run* [x y z]
(== z [x y])
(== [x] [3])))))
(deftest test-49-partial-map-unification
(is (= '[#clojure.core.logic.PMap{:a 1}]
(run* [q]
(fresh [pm x]
(== pm (partial-map {:a x}))
(== pm {:a 1 :b 2})
(== pm q)))))
(is (= '[#clojure.core.logic.PMap{:a 1}]
(run* [q]
(fresh [pm x]
(== (partial-map {:a x}) pm)
(== {:a 1 :b 2} pm)
(== q pm))))))
;; =============================================================================
;; cKanren
(deftest test-pair []
(is (= (pair 1 2)
(pair 1 2))))
(deftest test-domfd-1 []
(let [x (lvar 'x)
s ((domfd x 1) empty-s)]
(is (= (:s s) {x 1}))))
#_(deftest test-domfd-2 []
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (:ws s) {x (interval 1 10)}))))
#_(deftest test-domfd-3 []
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 10))
(domfd x (interval 3 6))) empty-s)]
(is (= (:ws s) {x (interval 3 6)}))))
#_(deftest test-domfd-4 []
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 5))
(domfd x (interval 5 9))) empty-s)]
(is (= (:s s) {x 5}))
(is (= (:ws s) {}))))
(deftest test-keep-before-1 []
(is (= (keep-before (interval 1 10) 5)
(interval 1 4)))
(is (= (keep-before (interval 5 10) 5)
nil))
(is (= (keep-before (interval 5 10) 6)
5))
(is (= (keep-before (interval 5 10) 10)
(interval 5 9))))
(deftest test-drop-before-1 []
(is (= (drop-before (interval 5 10) 4)
(interval 5 10)))
(is (= (drop-before (interval 1 10) 5)
(interval 5 10)))
(is (= (drop-before (interval 5 10) 5)
(interval 5 10)))
(is (= (drop-before (interval 5 10) 6)
(interval 6 10)))
(is (= (drop-before (interval 5 10) 10)
10))
(is (= (drop-before (interval 5 10) 11)
nil)))
(deftest test-keep-before-2 []
(is (= (keep-before 1 3)
1))
(is (= (keep-before 1 2)
1))
(is (= (keep-before 1 1)
nil)))
(deftest test-drop-before-2 []
(is (= (drop-before 1 3)
nil))
(is (= (drop-before 1 2)
nil))
(is (= (drop-before 1 1)
1))
(is (= (drop-before 1 0)
1)))
(deftest test-drop-before-mi-1 []
(is (= (drop-before (multi-interval 2 4) (lb 3))
4)))
(deftest test-keep-before-mi-2 []
(is (= (keep-before (multi-interval 2 4) (lb 3))
2)))
(deftest test-singleton-interval
(is (= (interval 1 1) 1)))
(deftest test-interval-<
(is (interval-< (interval 1 10) (interval 11 20)))
(is (interval-< 1 (interval 11 20))))
(deftest test-interval->
(is (interval-> (interval 11 20) (interval 1 10)))
(is (interval-> (interval 11 20) 1)))
(deftest test-member?-ss-1
(is (true? (member? 1 1))))
(deftest test-member?-ss-2
(is (false? (member? 1 2))))
(deftest test-disjoint?-ss-1
(is (false? (disjoint? 1 1))))
(deftest test-disjoint?-ss-2
(is (true? (disjoint? 1 2))))
(deftest test-difference-ss-1
(is (= (difference 1 1)
nil)))
(deftest test-difference-ss-2
(is (= (difference 1 2)
1)))
(deftest test-intersection-ss-1
(is (= (intersection 1 1)
1)))
(deftest test-intersection-ss-2
(is (= (intersection 1 2)
nil)))
(deftest test-member?-is-1
(is (true? (member? (interval 1 10) 1))))
(deftest test-member?-si-1
(is (true? (member? 1 (interval 1 10)))))
(deftest test-disjoint?-is-1
(is (true? (disjoint? (interval 1 10) 11))))
(deftest test-disjoint?-si-1
(is (true? (disjoint? 11 (interval 1 10)))))
(deftest test-intersection-is-1
(is (= (intersection (interval 1 6) 1)
1)))
(deftest test-intersection-si-1
(is (= (intersection 1 (interval 1 6))
1)))
(deftest test-difference-is-1
(let [mi (difference (interval 1 10) 5)]
(is (= (first (intervals mi)) (interval 1 4)))
(is (= (second (intervals mi)) (interval 6 10)))))
(deftest test-difference-si-1
(let [mi (difference 5 (interval 1 10))]
(is (= (first (intervals mi)) (interval 1 4)))
(is (= (second (intervals mi)) (interval 6 10)))))
(deftest test-intersection-ii-1
(is (= (intersection (interval 1 6) (interval 5 10))
(interval 5 6))))
(deftest test-intersection-ii-2
(is (= (intersection (interval 5 10) (interval 1 6))
(interval 5 6))))
(deftest test-difference-ii-1
(is (= (difference (interval 1 6) (interval 5 10))
(interval 1 4))))
(deftest test-difference-ii-2
(is (= (difference (interval 1 4) (interval 5 10))
(interval 1 4))))
(deftest test-difference-ii-3
(is (= (difference (interval 5 10) (interval 1 4))
(interval 5 10))))
(deftest test-difference-ii-4
(is (= (difference (interval 1 10) (interval 1 10))
nil)))
(deftest test-difference-ii-5
(is (= (difference (interval 2 9) (interval 1 10))
nil)))
(deftest test-disjoint?-ii-1
(is (false? (disjoint? (interval 1 6) (interval 5 10))))
(is (false? (disjoint? (interval 5 10) (interval 1 6))))
(is (true? (disjoint? (interval 1 6) (interval 10 16))))
(is (true? (disjoint? (interval 10 16) (interval 1 6)))))
(deftest test-member?-mimi-1
(is (false? (member? 20 (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (false? (member? (multi-interval (interval 1 3) 5 (interval 7 10)) 20))))
(deftest test-disjoint?-mimi-1
(is (true? (disjoint? 20 (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (true? (disjoint? (multi-interval (interval 1 3) 5 (interval 7 10)) 20)))
(is (true? (disjoint? (interval 20 30) (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (true? (disjoint? (multi-interval (interval 1 3) 5 (interval 7 10)) (interval 20 30)))))
(deftest test-equals-mi
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 1 4) (interval 6 10))]
(is (= mi0 mi1))))
;; -----------------------------------------------------------------------------
;; MultiIntervalFD Intersection
(deftest test-intersection-mimi-1
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 9 13) (interval 17 20))]
(is (= (intersection mi0 mi1) (interval 9 10)))
(is (= (intersection mi1 mi0) (interval 9 10)))))
(deftest test-intersection-mimi-2
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))]
(is (= (intersection mi0 7) 7))
(is (= (intersection 7 mi0) 7))))
;; |-----|
;; |-----|
(deftest test-intersection-mimi-3
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (intersection mi0 (interval 3 8))
(multi-interval (interval 3 4) (interval 7 8))))))
;; |-----|
;; |---|
(deftest test-intersection-mimi-4
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))
mi1 (multi-interval (interval 2 3) (interval 6 9))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 2 3) (interval 7 9))))))
;; |-----|
;; |-----|
(deftest test-intersection-mimi-5
(let [mi0 (multi-interval (interval 4 8) (interval 12 16))
mi1 (multi-interval (interval 1 5) (interval 7 15))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 4 5) (interval 7 8) (interval 12 15))))))
;; |---|
;; |-----|
(deftest test-intersection-mimi-6
(let [mi0 (multi-interval (interval 1 3) (interval 5 6) (interval 8 10))
mi1 (multi-interval (interval 1 3) (interval 4 7) (interval 8 10))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 1 3) (interval 5 6) (interval 8 10))))))
;; |---| |---|
;; |-------|
(deftest test-intersection-mimi-7
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (intersection mi0 (interval 1 8))
(multi-interval (interval 1 4) (interval 7 8))))))
;; |--------| |--|
;; |---| |-------|
(deftest test-intersection-mimi-8
(let [mi0 (multi-interval (interval 1 7) (interval 9 10))
mi1 (multi-interval (interval 1 3) (interval 6 11))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 1 3) (interval 6 7) (interval 9 10))))))
;; -----------------------------------------------------------------------------
;; MultiIntervalFD Difference
;; |---| |---|
;; |---| |---|
(deftest test-difference-mimi-1
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 9 13) (interval 17 20))]
(is (= (difference mi0 mi1)
(multi-interval (interval 1 4) (interval 6 8))))))
;; |---| |---|
;; N
(deftest test-difference-mis-1
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (difference mi0 8)
(multi-interval (interval 1 4) 7 (interval 9 10))))))
;; N
;; |---| |---|
(deftest test-difference-smi-2
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))]
(is (= (difference 5 mi0) 5))))
;; |---| |---|
;; |-------|
;;
;; |-------|
;; |---| |---|
(deftest test-difference-mii-1
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (difference mi0 (interval 3 8))
(multi-interval (interval 1 2) (interval 9 10))))
(is (= (difference (interval 3 8) mi0)
(interval 5 6)))))
;; |---| |---|
;; |-------| |----|
(deftest test-difference-mimi-2
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))
mi1 (multi-interval (interval 1 8) (interval 10 13))]
(is (= (difference mi0 mi1) 9))))
;; |----| |-------|
;; |----| |---|
(deftest test-difference-mimi-3
(let [mi0 (multi-interval (interval 3 6) (interval 9 15))
mi1 (multi-interval (interval 1 4) (interval 10 12))]
(is (= (difference mi0 mi1)
(multi-interval (interval 5 6) 9 (interval 13 15))))))
;; |---| |---|
;; |-----| |-|
(deftest test-difference-mimi-4
(let [mi0 (multi-interval (interval 3 6) (interval 15 20))
mi1 (multi-interval (interval 1 6) (interval 10 13))]
(is (= (difference mi0 mi1)
(interval 15 20)))))
(deftest test-fd-1
(let [d (domain 1 2 3)]
(is (= (lb d) 1))
(is (= (ub d) 3))))
(deftest test-normalize-intervals-1
(let [d (domain 1 2 3)]
(is (= (normalize-intervals (intervals d))
[(interval 1 3)]))))
(deftest test-normalize-intervals-2
(let [d (multi-interval (interval 1 4) 5 (interval 6 10))]
(is (= (normalize-intervals (intervals d))
[(interval 1 10)]))))
(deftest test-domfd-interval-and-number-1
(is (= (run* [q]
(domfd q (interval 1 10))
(== q 1))
'(1)))
(is (= (run* [q]
(== q 1)
(domfd q (interval 1 10)))
'(1))))
(deftest test-domfd-interval-and-number-2
(is (= (run* [q]
(domfd q (interval 1 10))
(== q 11))
'()))
(is (= (run* [q]
(== q 11)
(domfd q (interval 1 10)))
'())))
(deftest test-domfd-many-intervals-1
(is (= (run* [q]
(domfd q (interval 1 100))
(domfd q (interval 30 60))
(domfd q (interval 50 55))
(== q 51))
'(51)))
(is (= (run* [q]
(domfd q (interval 1 100))
(domfd q (interval 30 60))
(domfd q (interval 50 55))
(== q 56))
'())))
(deftest test-process-dom-1
(let [x (lvar 'x)
s ((process-dom x 1) empty-s)]
(is (= (walk s x) 1))))
(deftest test-process-dom-2
(let [x (lvar 'x)
s ((process-dom x (interval 1 10)) empty-s)]
(is (= (get-dom s x) (interval 1 10)))))
(deftest test-domfd-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (get-dom s x) (interval 1 10)))))
(deftest test-infd-1
(let [x (lvar 'x)
y (lvar 'y)
f ((infd x y (interval 1 10)) empty-s)
s (f)]
(is (= (get-dom s x) (interval 1 10)))
(is (= (get-dom s y) (interval 1 10)))))
(deftest test-make-fdc-prim-1
(let [u (lvar 'u)
w (lvar 'w)
c (fdc (=fdc u w))]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`=fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-make-fdc-prim-2
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (+fdc u v w)]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`+fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-make-fdc-1
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`+fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-addc-1
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
cs (addc (make-cs) c)
sc (first (constraints-for cs u ::l/fd))]
(is (= c sc))
(is (= (id sc) 0))
(is (= (count (:km cs)) 2))
(is (= (count (:cm cs)) 1))))
(deftest test-addc-2
(let [u (lvar 'u)
v 1
w (lvar 'w)
c0 (fdc (+fdc u v w))
x (lvar 'x)
c1 (fdc (+fdc w v x))
cs (-> (make-cs )
(addc c0)
(addc c1))
sc0 (get (:cm cs) 0)
sc1 (get (:cm cs) 1)]
(is (= sc0 c0)) (is (= (id sc0) 0))
(is (= sc1 c1)) (is (= (id sc1) 1))
(is (= (id sc0) 0))
(is (= (count (:km cs)) 3))
(is (= (count (:cm cs)) 2))))
(deftest test-addcg
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
s ((addcg c) empty-s)]
(is (= (count (:km (:cs s))) 2))
(is (= (count (:cm (:cs s))) 1))))
#_(deftest test-purge-c
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
s ((addcg c) empty-s)
c (first (constraints-for (:cs s) u ::fd))
s (-> s
(ext-no-check u 1)
(ext-no-check w 2))
s ((checkcg c) s)]
(is (zero? (count (:km (:cs s)))))
(is (zero? (count (:cm (:cs s)))))))
(deftest test-=fd-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 6))
(domfd y (interval 5 10))) empty-s)
s ((=fd x y) s)
cs (:cs s)]
(is (= 2 (count (:km (:cs s))))) ;; works
(is (= 3 (count (:cm (:cs s)))))
(is (= (get-dom s x) (interval 5 6)))
(is (= (get-dom s y) (interval 5 6)))))
(deftest test-multi-interval-1
(let [mi (multi-interval (interval 1 3) (interval 7 10))]
(is (= 1 (lb mi)))
(is (= 10 (ub mi)))))
(deftest test-run-constraints*
(is (= (run-constraints* [] [] ::subst) s#)))
(deftest test-drop-one-1
(is (= (:s (drop-one (domain 1 2 3)))
#{2 3})))
(deftest test-drop-one-2
(is (= (drop-one (domain 1))
nil)))
(deftest test-drop-one-3
(is (= (drop-one 1)
nil)))
(deftest test-drop-one-4
(is (= (drop-one (interval 1 10))
(interval 2 10))))
(deftest test-drop-one-5
(is (= (drop-one (interval 1 1))
nil)))
(deftest test-drop-one-6
(is (= (drop-one (multi-interval (interval 1 10) (interval 15 20)))
(multi-interval (interval 2 10) (interval 15 20)))))
(deftest test-to-vals-1
(is (= (to-vals 1) '(1))))
(deftest test-to-vals-2
(is (= (to-vals (domain 1 2 3)) '(1 2 3))))
(deftest test-to-vals-3
(is (= (to-vals (interval 1 10))
'(1 2 3 4 5 6 7 8 9 10))))
(deftest test-to-vals-4
(is (= (to-vals (multi-interval (interval 1 5) (interval 7 10)))
'(1 2 3 4 5 7 8 9 10))))
(deftest test-to-vals-5
(is (= (to-vals (multi-interval (interval 1 5) 7 (interval 9 12)))
'(1 2 3 4 5 7 9 10 11 12))))
(deftest test-map-sum-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
((map-sum (fn [v] (updateg x v)))
(to-vals (interval 1 10)))))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
(force-ans x)))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-2
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
(force-ans [x])))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-3
(let [x (lvar 'x)
s ((domfd x (multi-interval (interval 1 4) (interval 6 10)))
empty-s)]
(is (= (take 10
(solutions s x
(force-ans x)))
'(1 2 3 4 6 7 8 9 10)))))
(deftest test-verify-all-bound-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 10))
(domfd y (interval 1 10))) empty-s)]
(is (nil? (verify-all-bound s [x y])))))
(deftest test-verify-all-bound-2
(let [x (lvar 'x)
y (lvar 'y)
s ((domfd x (interval 1 10)) empty-s)]
(is (thrown? Exception (verify-all-bound s [x y])))))
(deftest test-enforce-constraints-1
(let [x (lvar 'x)
s ((domfd x (interval 1 3)) empty-s)]
(is (= (solutions s x
(enforce-constraints x))
'(1 2 3)))))
(deftest test-reifyg-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 10))
(domfd y (interval 1 5))) empty-s)
s ((=fd x y) s)]
(is (= (take* ((reifyg x) s))
'(1 2 3 4 5)))))
(deftest test-process-interval-smaller-1
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 10))
(domfd x (interval 2 10))) empty-s)]
(is (= (get-dom s x)
(interval 2 10)))))
(deftest test-boundary-interval-1
(is (difference (interval 1 10) 1)
(interval 2 10)))
(deftest test-boundary-interval-1
(is (difference (interval 1 10) 10)
(interval 1 9)))
(deftest test-process-imi-1
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 2 10))
(domfd x (multi-interval (interval 1 4) (interval 6 10))))
empty-s)]
(is (= (get-dom s x)
(multi-interval (interval 2 4) (interval 6 10))))))
;; -----------------------------------------------------------------------------
;; cKanren
(deftest test-root-var-1
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y x))]
(is (= (root-var s y) x))))
(deftest test-ckanren-1
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(== q x)))
'(1 2 3))))
(deftest test-ckanren-2
(is (= (run* [q]
(fresh [x y z]
(infd x z (interval 1 5))
(infd y (interval 3 5))
(+fd x y z)
(== q [x y z])))
'([1 3 4] [2 3 5] [1 4 5]))))
(deftest test-ckanren-3
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(=fd x y)
(== q [x y])))
'([1 1] [2 2] [3 3]))))
(deftest test-ckanren-4
(is (true?
(every? (fn [[x y]] (not= x y))
(run* [q]
(fresh [x y]
(infd x y (interval 1 10))
(!=fd x y)
(== q [x y])))))))
(deftest test-ckanren-5
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(== x 2)
(!=fd x y)
(== q [x y])))
'([2 1] [2 3]))))
(deftest test-ckanren-6
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(+fd x 1 x)
(== q x)))
'())))
(deftest test-ckanren-7
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(+fd x x x)))
'())))
(deftest test-ckanren-8
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(<=fd x y)
(== q [x y])))
'([1 1] [1 2] [2 2] [1 3] [3 3] [2 3]))))
(deftest test-ckanren-9
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(<fd x y)
(== q [x y])))
'([1 2] [2 3] [1 3]))))
(defn subgoal [x]
(fresh [y]
(== y x)
(+fd 1 y 3)))
(deftest test-ckanren-10
(is (= (run* [q]
(fresh [a]
(infd a (interval 1 10))
(subgoal a)
(== q a)))
'(2))))
(deftest test-list-sorted
(is (true? (list-sorted? < [1 2 3])))
(is (true? (list-sorted? < [1 3 5])))
(is (false? (list-sorted? < [1 1 3])))
(is (false? (list-sorted? < [1 5 4 1]))))
(deftest test-with-id
(let [x (lvar 'x)
y (lvar 'y)
n* (sorted-set 1 3 5)
c (with-id (fdc (-distinctfdc x #{y} (conj n* 7))) 1)]
(is (= (id c) 1))
(is (= (id (:proc c)) 1))))
(deftest test-distinctfd
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 3))
(distinctfd [x y z])
(== q [x y z])))
'([1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]))))
(deftest test-=fd-1
(is (= (run* [q]
(fresh [a b]
(infd a b (interval 1 3))
(=fd a b)
(== q [a b])))
'([1 1] [2 2] [3 3]))))
(deftest test-!=fd-1
(is (= (run* [q]
(fresh [a b]
(infd a b (interval 1 3))
(!=fd a b)
(== q [a b])))
'([1 2] [1 3] [2 1] [2 3] [3 1] [3 2]))))
(deftest test-<fd-1
(is (= (run* [q]
(fresh [a b c]
(infd a b c (interval 1 3))
(<fd a b) (<fd b c)
(== q [a b c])))
'([1 2 3]))))
(deftest test-<fd-2
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 10))
(+fd x y z)
(<fd x y)
(== z 10)
(== q [x y z])))
'([1 9 10] [2 8 10] [3 7 10] [4 6 10]))))
(deftest test->fd-1
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 10))
(+fd x y z)
(>fd x y)
(== z 10)
(== q [x y z])))
'([6 4 10] [7 3 10] [8 2 10] [9 1 10]))))
(deftest test-<=fd-1
(is (= (run* [q]
(fresh [x y]
(== x 3)
(infd y (multi-interval 2 4))
(<=fd x y)
(== q y)))
'(4))))
(deftest test->=fd-1
(is (= (run* [q]
(fresh [x y]
(== x 3)
(infd y (multi-interval 2 4))
(>=fd x y)
(== q y)))
'(2))))
(deftest test-*fd-1
(is (= (run* [q]
(fresh [n m]
(infd n m (interval 1 10))
(*fd n 2 m)
(== q [n m])))
'([1 2] [2 4] [3 6] [4 8] [5 10]))))
(deftest test-*fd-2
(is (= (run* [q]
(fresh [n m]
(infd n m (interval 1 10))
(*fd n m 10)
(== q [n m])))
'([1 10] [2 5] [5 2] [10 1]))))
;; -----------------------------------------------------------------------------
;; CLP(Tree)
(deftest test-recover-vars []
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y 2))]
(is (= (recover-vars (:l s))
#{x y}))))
(deftest test-prefix-s []
(let [x (lvar 'x)
y (lvar 'y)
s empty-s
sp (-> s
(ext-no-check x 1)
(ext-no-check y 2))
p (prefix-s sp s)]
(is (= p
(list (pair y 2) (pair x 1))))
(is (= (-> p meta :s) sp))))
(deftest test-prefix-subsumes? []
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
s empty-s
sp (-> s
(ext-no-check x 1)
(ext-no-check y 2))
p (prefix-s sp s)]
(is (true? (prefix-subsumes? p (list (pair x 1)))))
(is (true? (prefix-subsumes? p (list (pair y 2)))))
(is (false? (prefix-subsumes? p (list (pair z 3)))))))
(deftest test-remc []
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
c (fdc (+fdc x y z))
cs (addc (make-cs) c)
cp (get (:cm cs) 0)
cs (remc cs cp)]
(is (= (:km cs) {}))
(is (= (:cm cs) {}))))
(deftest test-treec-id-1 []
(let [x (lvar 'x)
y (lvar 'y)
c (with-id (!=c x y) 0)]
(is (zero? (id c)))))
(deftest test-tree-constraint? []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1) (pair y 2)))
cs (addc (make-cs) c)]
(is (tree-constraint? ((:cm cs) 0)))
(is (= (into #{} (keys (:km cs)))
#{x y}))))
(deftest test-prefix-protocols []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1) (pair y 2)))
c (with-prefix c (list (pair x 1)))]
(is (= (prefix c)
(list (pair x 1))))))
(deftest test-!=-1 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)]
(is (= (prefix ((:cm (:cs s)) 0)) (list (pair x y))))))
(deftest test-!=-2 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)
s ((== x y) s)]
(is (= s nil))))
;; NOTE: we removed -relevant? protocol fn used for purging individual
;; vars from the constraint store. This may return but as a finer grained
;; protocol IRelevantLVar or some such
#_(deftest test-!=-3 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)
s ((== x 1) s)
s ((== y 2) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-4 []
(let [x (lvar 'x)
y (lvar 'y)
s ((== x 1) empty-s)
s ((== y 2) s)
s ((!= x y) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-5 []
(let [x (lvar 'x)
y (lvar 'y)
s ((== x 1) empty-s)
s ((!= x y) s)
s ((== y 2) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-6 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x 1) empty-s)]
(is (= (prefix ((:cm (:cs s)) 0)) (list (pair x 1))))))
#_(deftest test-normalize-store []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1)))
sc (!=c (list (pair x 1) (pair y 2)))
cs (addc (make-cs) c)]
))
(deftest test-multi-constraints-1 []
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 3))
(!= z 3)
(+fd x y z)
(== q [x y z])))
'([1 1 2]))))
(deftest test--fd-1 []
(is (= (run* [q]
(infd q (interval 1 10))
(-fd 4 q 1))
'(3)))
(is (= (run* [q]
(infd q (interval 1 10))
(-fd 4 2 q))
'(2))))
(deftest test-quotfd-1 []
(is (= (run* [q]
(infd q (interval 1 10))
(quotfd 4 2 q))
'(2))))
;; =============================================================================
;; eqfd
(deftest test-eqfd-1 []
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 0 9))
(eqfd
(= (+ x y) 9)
(= (+ (* x 2) (* y 4)) 24))
(== q [x y])))
'([6 3]))))
;; FIXME
(deftest test-eqfd-2 []
(is (= (run* [q]
(fresh [s e n d m o r y]
(== q [s e n d m o r y])
(infd s e n d m o r y (interval 0 9))
(distinctfd [s e n d m o r y])
(!=fd m 0) (!=fd s 0)
(eqfd
(= (+ (* 1000 s) (* 100 e) (* 10 n) d
(* 1000 m) (* 100 o) (* 10 r) e)
(+ (* 10000 m) (* 1000 o) (* 100 n) (* 10 e) y)))))
'([9 5 6 7 1 0 8 2]))))
(deftest test-eqfd-3 []
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 20))
(eqfd
(= (+ x y) 11)
(= (- (* 3 x) y) 5))
(== q [x y])))
'([4 7]))))
(deftest test-distinctfd-1 []
(is (= (run 1 [q]
(fresh [x y]
(distinctfd q)
(== q [x y])
(== x 1)
(== y 1)))
())))
(deftest test-logic-62-fd []
(is (= (run 1 [q]
(fresh [x y a b]
(distinctfd [x y])
(== [x y] [a b])
(== q [a b])
(== a 1)
(== b 1)))
()))
(is (= (run 1 [q]
(fresh [x y a b]
(== [x y] [a b])
(== q [a b])
(== a 1)
(== b 1)
(distinctfd [x y])))
())))
(deftest test-distincto-1 []
(is (= (run 1 [q]
(fresh [x y a b]
(distincto q)
(== [x y] [a b])
(== q [a b])
(== x 1)
(== y 2)))
'([1 2]))))
(deftest test-eq-vars-1 []
(let [x0 (lvar 'x)
x1 (with-meta x0 {:foo 'bar})
s (unify empty-s x0 x1)]
(is (= s empty-s))))
;; =============================================================================
;; predc
(deftest test-predc-1 []
(is (= (run* [q]
(predc q number? `number?))
'((_.0 :- clojure.core/number?))))
(is (= (run* [q]
(predc q number? `number?)
(== q 1))
'(1)))
(is (= (run* [q]
(== q 1)
(predc q number? `number?))
'(1)))
(is (= (run* [q]
(predc q number? `number?)
(== q "foo"))
()))
(is (= (run* [q]
(== q "foo")
(predc q number? `number?))
())))
;; =============================================================================
;; extensible unifier
(deftest test-extensible-unifier-1
(is (= (unifier '(^{::l/ann ::l/numeric} ?x) '(1))
'(1)))
(is (= (unifier '(^{::l/ann ::l/numeric} ?x) '("foo"))
nil)))
;; =============================================================================
;; Implementation Specific Tests - Subject To Change
(deftest test-attrs-1 []
(let [x (lvar 'x)
s (add-attr empty-s x :foo 'bar)]
(is (= (get-attr s x :foo) 'bar))))
(deftest test-attrs-2 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)
s (add-attr s x :foo 'bar)
s (add-attr s x :baz 'woz)]
(is (= (get-attr s x :foo) 'bar))
(is (= (get-attr s x :baz) 'woz))))
(deftest test-attrs-2 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)
s (add-attr s x :foo 'bar)
s (add-attr s x :baz 'woz)
s (rem-attr s x :foo)]
(is (= (get-attr s x :foo) nil))))
(deftest test-root-1 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)]
(= (root-var s x) x)
(= (root-val s x) 1)))
(deftest test-root-2 []
(let [x (lvar 'x)
s (add-attr empty-s x :foo 'bar)]
(is (subst-val? (root-val s x)))))
(deftest test-root-3 []
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y x))]
(is (= (root-var s y) x))))
(deftest test-update-1 []
(let [x (lvar 'x)
s (ext-no-check empty-s x (subst-val ::l/unbound))
s (add-attr s x ::fd (domain 1 2 3))
s (update s x 1)]
(is (= (:v (root-val s x)) 1))
(is (= (get-attr s x ::fd) (domain 1 2 3)))
(is (= (walk s x) 1))))
|
118368
|
(ns clojure.core.logic.tests
(:refer-clojure :exclude [==])
(:use [clojure.core.logic :exclude [is] :as l]
clojure.test :reload)
(:require [clojure.pprint :as pp]))
;; =============================================================================
;; unify
;; -----------------------------------------------------------------------------
;; nil
(deftest unify-nil-object-1
(is (= (unify empty-s nil 1) nil)))
(deftest unify-nil-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x nil)]
(is (= (unify empty-s nil x) os))))
(deftest unify-nil-lseq-1
(let [x (lvar 'x)]
(is (= (unify empty-s nil (lcons 1 x)) nil))))
(deftest unify-nil-map-1
(let [x (lvar 'x)]
(is (= (unify empty-s nil {}) nil))))
;; -----------------------------------------------------------------------------
;; object
(deftest unify-object-nil-1
(is (= (unify empty-s 1 nil))))
(deftest unify-object-object-1
(is (= (unify empty-s 1 1) empty-s)))
(deftest unify-object-object-2
(is (= (unify empty-s :foo :foo) empty-s)))
(deftest unify-object-object-3
(is (= (unify empty-s 'foo 'foo) empty-s)))
(deftest unify-object-object-4
(is (= (unify empty-s "foo" "foo") empty-s)))
(deftest unify-object-object-5
(is (= (unify empty-s 1 2) nil)))
(deftest unify-object-object-6
(is (= (unify empty-s 2 1) nil)))
(deftest unify-object-object-7
(is (= (unify empty-s :foo :bar) nil)))
(deftest unify-object-object-8
(is (= (unify empty-s 'foo 'bar) nil)))
(deftest unify-object-object-9
(is (= (unify empty-s "foo" "bar") nil)))
(deftest unify-object-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s 1 x) os))))
(deftest unify-object-lcons-1
(let [x (lvar 'x)]
(is (= (unify empty-s 1 (lcons 1 'x)) nil))))
(deftest unify-object-seq-1
(is (= (unify empty-s 1 '()) nil)))
(deftest unify-object-seq-2
(is (= (unify empty-s 1 '[]) nil)))
(deftest unify-object-map-1
(is (= (unify empty-s 1 {}) nil)))
;; -----------------------------------------------------------------------------
;; lvar
(deftest unify-lvar-object-1
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s x 1) os))))
(deftest unify-lvar-lvar-1
(let [x (lvar 'x)
y (lvar 'y)
os (ext-no-check empty-s x y)]
(is (= (unify empty-s x y) os))))
(deftest unify-lvar-lcons-1
(let [x (lvar 'x)
y (lvar 'y)
l (lcons 1 y)
os (ext-no-check empty-s x l)]
(is (= (unify empty-s x l) os))))
(deftest unify-lvar-seq-1
(let [x (lvar 'x)
os (ext-no-check empty-s x [])]
(is (= (unify empty-s x []) os))))
(deftest unify-lvar-seq-2
(let [x (lvar 'x)
os (ext-no-check empty-s x [1 2 3])]
(is (= (unify empty-s x [1 2 3]) os))))
(deftest unify-lvar-seq-3
(let [x (lvar 'x)
os (ext-no-check empty-s x '())]
(is (= (unify empty-s x '()) os))))
(deftest unify-lvar-seq-4
(let [x (lvar 'x)
os (ext-no-check empty-s x '(1 2 3))]
(is (= (unify empty-s x '(1 2 3)) os))))
(deftest unify-lvar-map-1
(let [x (lvar 'x)
os (ext-no-check empty-s x {})]
(is (= (unify empty-s x {}) os))))
(deftest unify-lvar-map-2
(let [x (lvar 'x)
os (ext-no-check empty-s x {1 2 3 4})]
(is (= (unify empty-s x {1 2 3 4}) os))))
;; -----------------------------------------------------------------------------
;; lcons
(deftest unify-lcons-object-1
(let [x (lvar 'x)]
(is (= (unify empty-s (lcons 1 x) 1) nil))))
(deftest unify-lcons-lvar-1
(let [x (lvar 'x)
y (lvar 'y)
l (lcons 1 y)
os (ext-no-check empty-s x l)]
(is (= (unify empty-s l x) os))))
(deftest unify-lcons-lcons-1
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 x)
lc2 (lcons 1 y)
os (ext-no-check empty-s x y)]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-2
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons z y))
os (-> empty-s
(ext-no-check x y)
(ext-no-check z 2))]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-3
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 2 (lcons 3 y)))
os (ext-no-check empty-s x (lcons 3 y))]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-4
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 3 (lcons 4 y)))]
(is (= (unify empty-s lc1 lc2) nil))))
(deftest unify-lcons-lcons-5
(let [x (lvar 'x)
y (lvar 'y)
lc2 (lcons 1 (lcons 2 x))
lc1 (lcons 1 (lcons 3 (lcons 4 y)))]
(is (= (unify empty-s lc1 lc2) nil))))
(deftest unify-lcons-lcons-6
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 2 y))
os (ext-no-check empty-s x y)]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-seq-1
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 2 3 4)
os (ext-no-check empty-s x '(3 4))]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-2
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons y (lcons 3 x)))
l1 '(1 2 3 4)
os (-> empty-s
(ext-no-check x '(4))
(ext-no-check y 2))]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-3
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 (lcons 3 x)))
l1 '(1 2 3)
os (ext-no-check empty-s x '())]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-4
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 3 x))
l1 '(1 2 3 4)]
(is (= (unify empty-s lc1 l1) nil))))
(deftest unify-lcons-seq-5
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 3 4 5)]
(is (= (unify empty-s lc1 l1) nil))))
(deftest unify-lcons-map-1
(is (= (unify empty-s (lcons 1 (lvar 'x)) {}) nil)))
;; -----------------------------------------------------------------------------
;; seq
(deftest unify-seq-object-1
(is (= (unify empty-s '() 1) nil)))
(deftest unify-seq-object-2
(is (= (unify empty-s [] 1) nil)))
(deftest unify-seq-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x [])]
(is (= (unify empty-s [] x) os))))
(deftest unify-seq-lcons-1
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 2 3 4)
os (ext-no-check empty-s x '(3 4))]
(is (= (unify empty-s l1 lc1) os))))
(deftest unify-seq-seq-1
(is (= (unify empty-s [1 2 3] [1 2 3]) empty-s)))
(deftest unify-seq-seq-2
(is (= (unify empty-s '(1 2 3) [1 2 3]) empty-s)))
(deftest unify-seq-seq-3
(is (= (unify empty-s '(1 2 3) '(1 2 3)) empty-s)))
(deftest unify-seq-seq-4
(let [x (lvar 'x)
os (ext-no-check empty-s x 2)]
(is (= (unify empty-s `(1 ~x 3) `(1 2 3)) os))))
(deftest unify-seq-seq-5
(is (= (unify empty-s [1 2] [1 2 3]) nil)))
(deftest unify-seq-seq-6
(is (= (unify empty-s '(1 2) [1 2 3]) nil)))
(deftest unify-seq-seq-7
(is (= (unify empty-s [1 2 3] [3 2 1]) nil)))
(deftest unify-seq-seq-8
(is (= (unify empty-s '() '()) empty-s)))
(deftest unify-seq-seq-9
(is (= (unify empty-s '() '(1)) nil)))
(deftest unify-seq-seq-10
(is (= (unify empty-s '(1) '()) nil)))
(deftest unify-seq-seq-11
(is (= (unify empty-s [[1 2]] [[1 2]]) empty-s)))
(deftest unify-seq-seq-12
(is (= (unify empty-s [[1 2]] [[2 1]]) nil)))
(deftest unify-seq-seq-13
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s [[x 2]] [[1 2]]) os))))
(deftest unify-seq-seq-14
(let [x (lvar 'x)
os (ext-no-check empty-s x [1 2])]
(is (= (unify empty-s [x] [[1 2]]) os))))
(deftest unify-seq-seq-15
(let [x (lvar 'x) y (lvar 'y)
u (lvar 'u) v (lvar 'v)
os (-> empty-s
(ext-no-check x 'b)
(ext-no-check y 'a))]
(is (= (unify empty-s ['a x] [y 'b]) os))))
(deftest unify-seq-map-1
(is (= (unify empty-s [] {}) nil)))
(deftest unify-seq-map-2
(is (= (unify empty-s '() {}) nil)))
;; -----------------------------------------------------------------------------
;; map
(deftest unify-map-object-1
(is (= (unify empty-s {} 1) nil)))
(deftest unify-map-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x {})]
(is (= (unify empty-s {} x) os))))
(deftest unify-map-lcons-1
(let [x (lvar 'x)]
(is (= (unify empty-s {} (lcons 1 x)) nil))))
(deftest unify-map-seq-1
(is (= (unify empty-s {} '()) nil)))
(deftest unify-map-map-1
(is (= (unify empty-s {} {}) empty-s)))
(deftest unify-map-map-2
(is (= (unify empty-s {1 2 3 4} {1 2 3 4}) empty-s)))
(deftest unify-map-map-3
(is (= (unify empty-s {1 2} {1 2 3 4}) nil)))
(deftest unify-map-map-4
(let [x (lvar 'x)
m1 {1 2 3 4}
m2 {1 2 3 x}
os (ext-no-check empty-s x 4)]
(is (= (unify empty-s m1 m2) os))))
(deftest unify-map-map-5
(let [x (lvar 'x)
m1 {1 2 3 4}
m2 {1 4 3 x}]
(is (= (unify empty-s m1 m2) nil))))
(defstruct foo-struct :a :b)
(deftest unify-struct-map-1
(let [x (lvar 'x)
m1 (struct-map foo-struct :a 1 :b 2)
m2 (struct-map foo-struct :a 1 :b x)
os (ext-no-check empty-s x 2)]
(is (= (unify empty-s m1 m2) os))))
(deftest unify-struct-map-2
(let [x (lvar 'x)
m1 (struct-map foo-struct :a 1 :b 2)
m2 (struct-map foo-struct :a 1 :b 3)]
(is (= (unify empty-s m1 m2) nil))))
;; =============================================================================
;; walk
(deftest test-basic-walk
(is (= (let [x (lvar 'x)
y (lvar 'y)
ss (to-s [[x 5] [y x]])]
(walk ss y))
5)))
(deftest test-deep-walk
(is (= (let [[x y z c b a :as s] (map lvar '[x y z c b a])
ss (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])]
(walk ss a))
5)))
;; =============================================================================
;; reify
(deftest test-reify-lvar-name
(is (= (let [x (lvar 'x)
y (lvar 'y)]
(reify-lvar-name (to-s [[x 5] [y x]])))
'_.2)))
;; =============================================================================
;; walk*
(deftest test-walk*
(is (= (let [x (lvar 'x)
y (lvar 'y)]
(walk* (to-s [[x 5] [y x]]) `(~x ~y)))
'(5 5))))
;; =============================================================================
;; run and unify
(deftest test-basic-unify
(is (= (run* [q]
(== true q))
'(true))))
(deftest test-basic-unify-2
(is (= (run* [q]
(fresh [x y]
(== [x y] [1 5])
(== [x y] q)))
[[1 5]])))
(deftest test-basic-unify-3
(is (= (run* [q]
(fresh [x y]
(== [x y] q)))
'[[_.0 _.1]])))
;; =============================================================================
;; fail
(deftest test-basic-failure
(is (= (run* [q]
fail
(== true q))
[])))
;; =============================================================================
;; Basic
(deftest test-all
(is (= (run* [q]
(all
(== 1 1)
(== q true)))
'(true))))
;; =============================================================================
;; TRS
(defn pairo [p]
(fresh [a d]
(== (lcons a d) p)))
(defn twino [p]
(fresh [x]
(conso x x p)))
(defn listo [l]
(conde
[(emptyo l) s#]
[(pairo l)
(fresh [d]
(resto l d)
(listo d))]))
(defn flatteno [s out]
(conde
[(emptyo s) (== '() out)]
[(pairo s)
(fresh [a d res-a res-d]
(conso a d s)
(flatteno a res-a)
(flatteno d res-d)
(appendo res-a res-d out))]
[(conso s '() out)]))
;; =============================================================================
;; conde
(deftest test-basic-conde
(is (= (run* [x]
(conde
[(== x 'olive) succeed]
[succeed succeed]
[(== x 'oil) succeed]))
'[olive _.0 oil])))
(deftest test-basic-conde-2
(is (= (run* [r]
(fresh [x y]
(conde
[(== 'split x) (== 'pea y)]
[(== 'navy x) (== 'bean y)])
(== (cons x (cons y ())) r)))
'[(split pea) (navy bean)])))
(defn teacupo [x]
(conde
[(== 'tea x) s#]
[(== 'cup x) s#]))
(deftest test-basic-conde-e-3
(is (= (run* [r]
(fresh [x y]
(conde
[(teacupo x) (== true y) s#]
[(== false x) (== true y)])
(== (cons x (cons y ())) r)))
'((false true) (tea true) (cup true)))))
;; =============================================================================
;; conso
(deftest test-conso
(is (= (run* [q]
(fresh [a d]
(conso a d '())))
())))
(deftest test-conso-1
(let [a (lvar 'a)
d (lvar 'd)]
(is (= (run* [q]
(conso a d q))
[(lcons a d)]))))
(deftest test-conso-2
(is (= (run* [q]
(== [q] nil))
[])))
(deftest test-conso-3
(is (=
(run* [q]
(conso 'a nil q))
'[(a)])))
(deftest test-conso-4
(is (= (run* [q]
(conso 'a '(d) q))
'[(a d)])))
(deftest test-conso-empty-list
(is (= (run* [q]
(conso 'a q '(a)))
'[()])))
(deftest test-conso-5
(is (= (run* [q]
(conso q '(b c) '(a b c)))
'[a])))
;; =============================================================================
;; firsto
(deftest test-firsto
(is (= (run* [q]
(firsto q '(1 2)))
(list (lcons '(1 2) (lvar 'x))))))
;; =============================================================================
;; resto
(deftest test-resto
(is (= (run* [q]
(resto q '(1 2)))
'[(_.0 1 2)])))
(deftest test-resto-2
(is (= (run* [q]
(resto q [1 2]))
'[(_.0 1 2)])))
(deftest test-resto-3
(is (= (run* [q]
(resto [1 2] q))
'[(2)])))
(deftest test-resto-4
(is (= (run* [q]
(resto [1 2 3 4 5 6 7 8] q))
'[(2 3 4 5 6 7 8)])))
;; =============================================================================
;; flatteno
(deftest test-flatteno
(is (= (run* [x]
(flatteno '[[a b] c] x))
'(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ())
(a (b) (c)) (a (b) c) (a (b) c ()) (a b (c))
(a b () (c)) (a b c) (a b c ()) (a b () c)
(a b () c ())))))
;; =============================================================================
;; membero
(deftest membero-1
(is (= (run* [q]
(all
(== q [(lvar)])
(membero ['foo (lvar)] q)
(membero [(lvar) 'bar] q)))
'([[foo bar]]))))
(deftest membero-2
(is (= (run* [q]
(all
(== q [(lvar) (lvar)])
(membero ['foo (lvar)] q)
(membero [(lvar) 'bar] q)))
'([[foo bar] _.0] [[foo _.0] [_.1 bar]]
[[_.0 bar] [foo _.1]] [_.0 [foo bar]]))))
;; -----------------------------------------------------------------------------
;; rembero
(deftest rembero-1
(is (= (run 1 [q]
(rembero 'b '(a b c b d) q))
'((a c b d)))))
;; -----------------------------------------------------------------------------
;; conde clause count
(defn digit-1 [x]
(conde
[(== 0 x)]))
(defn digit-4 [x]
(conde
[(== 0 x)]
[(== 1 x)]
[(== 2 x)]
[(== 3 x)]))
(deftest test-conde-1-clause
(is (= (run* [q]
(fresh [x y]
(digit-1 x)
(digit-1 y)
(== q [x y])))
'([0 0]))))
(deftest test-conde-4-clauses
(is (= (run* [q]
(fresh [x y]
(digit-4 x)
(digit-4 y)
(== q [x y])))
'([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0]
[1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3]))))
;; -----------------------------------------------------------------------------
;; anyo
(defn anyo [q]
(conde
[q s#]
[(anyo q)]))
(deftest test-anyo-1
(is (= (run 1 [q]
(anyo s#)
(== true q))
(list true))))
(deftest test-anyo-2
(is (= (run 5 [q]
(anyo s#)
(== true q))
(list true true true true true))))
;; -----------------------------------------------------------------------------
;; divergence
(def f1 (fresh [] f1))
(deftest test-divergence-1
(is (= (run 1 [q]
(conde
[f1]
[(== false false)]))
'(_.0))))
(deftest test-divergence-2
(is (= (run 1 [q]
(conde
[f1 (== false false)]
[(== false false)]))
'(_.0))))
(def f2
(fresh []
(conde
[f2 (conde
[f2]
[(== false false)])]
[(== false false)])))
(deftest test-divergence-3
(is (= (run 5 [q] f2)
'(_.0 _.0 _.0 _.0 _.0))))
;; -----------------------------------------------------------------------------
;; conda (soft-cut)
(deftest test-conda-1
(is (= (run* [x]
(conda
[(== 'olive x) s#]
[(== 'oil x) s#]
[u#]))
'(olive))))
(deftest test-conda-2
(is (= (run* [x]
(conda
[(== 'virgin x) u#]
[(== 'olive x) s#]
[(== 'oil x) s#]
[u#]))
'())))
(deftest test-conda-3
(is (= (run* [x]
(fresh (x y)
(== 'split x)
(== 'pea y)
(conda
[(== 'split x) (== x y)]
[s#]))
(== true x))
'())))
(deftest test-conda-4
(is (= (run* [x]
(fresh (x y)
(== 'split x)
(== 'pea y)
(conda
[(== x y) (== 'split x)]
[s#]))
(== true x))
'(true))))
(defn not-pastao [x]
(conda
[(== 'pasta x) u#]
[s#]))
(deftest test-conda-5
(is (= (run* [x]
(conda
[(not-pastao x)]
[(== 'spaghetti x)]))
'(spaghetti))))
;; -----------------------------------------------------------------------------
;; condu (committed-choice)
(comment
(defn onceo [g]
(condu
(g s#)))
(deftest test-condu-1
(is (= (run* [x]
(onceo (teacupo x)))
'(tea))))
)
(deftest test-condu-2
(is (= (run* [r]
(conde
[(teacupo r) s#]
[(== false r) s#]))
'(false tea cup))))
(deftest test-condu-3
(is (= (run* [r]
(conda
[(teacupo r) s#]
[(== false r) s#]))
'(tea cup))))
;; -----------------------------------------------------------------------------
;; disequality
(deftest test-disequality-1
(is (= (run* [q]
(fresh [x]
(!= x 1)
(== q x)))
'((_.0 :- (!= _.0 1))))))
(deftest test-disequality-2
(is (= (run* [q]
(fresh [x]
(== q x)
(!= x 1)))
'((_.0 :- (!= _.0 1))))))
(deftest test-disequality-3
(is (= (run* [q]
(fresh [x]
(!= x 1)
(== x 1)
(== q x)))
())))
(deftest test-disequality-4
(is (= (run* [q]
(fresh [x]
(== x 1)
(!= x 1)
(== q x)))
())))
(deftest test-disequality-5
(is (= (run* [q]
(fresh [x y]
(!= x y)
(== x 1)
(== y 1)
(== q x)))
())))
(deftest test-disequality-6
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 1)
(!= x y)
(== q x)))
())))
(deftest test-disequality-7
(is (= (run* [q]
(fresh [x y]
(== x 1)
(!= x y)
(== y 2)
(== q x)))
'(1))))
(deftest test-disequality-8
(is (= (run* [q]
(fresh [x y]
(!= [x 2] [y 1])
(== x 1)
(== y 3)
(== q [x y])))
'([1 3]))))
(deftest test-disequality-9
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 3)
(!= [x 2] [y 1])
(== q [x y])))
'([1 3]))))
(deftest test-disequality-10
(is (= (run* [q]
(fresh [x y]
(!= [x 2] [1 y])
(== x 1)
(== y 2)
(== q [x y])))
())))
(deftest test-disequality-11
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 2)
(!= [x 2] [1 y])
(== q [x y])))
())))
(deftest test-disequality-12
(is (= (run* [q]
(fresh [x y z]
(!= x y)
(== y z)
(== x z)
(== q x)))
())))
(deftest test-disequality-13
(is (= (run* [q]
(fresh [x y z]
(== y z)
(== x z)
(!= x y)
(== q x)))
())))
(deftest test-disequality-14
(is (= (run* [q]
(fresh [x y z]
(== z y)
(== x z)
(!= x y)
(== q x)))
())))
(deftest test-disequality-15
(is (= (run* [q]
(fresh [x y]
(== q [x y])
(!= x 1)
(!= y 2)))
'(([_.0 _.1] :- (!= _.1 2) (!= _.0 1))))))
;; -----------------------------------------------------------------------------
;; tabled
(defne arco [x y]
([:a :b])
([:b :a])
([:b :d]))
(def patho
(tabled [x y]
(conde
[(arco x y)]
[(fresh [z]
(arco x z)
(patho z y))])))
(deftest test-tabled-1
(is (= (run* [q] (patho :a q))
'(:b :a :d))))
(defne arco-2 [x y]
([1 2])
([1 4])
([1 3])
([2 3])
([2 5])
([3 4])
([3 5])
([4 5]))
(def patho-2
(tabled [x y]
(conde
[(arco-2 x y)]
[(fresh [z]
(arco-2 x z)
(patho-2 z y))])))
(deftest test-tabled-2
(let [r (set (run* [q] (patho-2 1 q)))]
(is (and (= (count r) 4)
(= r #{2 3 4 5})))))
;; -----------------------------------------------------------------------------
;; rel
(defrel man p)
(fact man '<NAME>)
(fact man '<NAME>)
(fact man '<NAME>)
(defrel woman p)
(fact woman '<NAME>)
(fact woman '<NAME>)
(fact woman '<NAME>)
(defrel likes p1 p2)
(fact likes '<NAME> '<NAME>)
(fact likes '<NAME> '<NAME>)
(fact likes '<NAME> '<NAME>)
(defrel fun p)
(fact fun 'Lucy)
(deftest test-rel-1
(is (= (run* [q]
(fresh [x y]
(likes x y)
(fun y)
(== q [x y])))
'([<NAME>]))))
(retraction likes '<NAME> '<NAME>)
(deftest test-rel-retract
(is (= (run* [q]
(fresh [x y]
(likes x y)
(== q [x y])))
'([<NAME>] [<NAME>]))))
(defrel rel1 ^:index a)
(fact rel1 [1 2])
(deftest test-rel-logic-29
(is (= (run* [q]
(fresh [a]
(rel1 [q a])
(== a 2)))
'(1))))
(defrel rel2 ^:index e ^:index a ^:index v)
(facts rel2 [[:e1 :a1 :v1]
[:e1 :a2 :v2]])
(retractions rel2 [[:e1 :a1 :v1]
[:e1 :a1 :v1]
[:e1 :a2 :v2]])
(deftest rel2-dup-retractions
(is (= (run* [out]
(fresh [e a v]
(rel2 e :a1 :v1)
(rel2 e a v)
(== [e a v] out))))
'()))
;; -----------------------------------------------------------------------------
;; nil in collection
(deftest test-nil-in-coll-1
(is (= (run* [q]
(== q [nil]))
'([nil]))))
(deftest test-nil-in-coll-2
(is (= (run* [q]
(== q [1 nil]))
'([1 nil]))))
(deftest test-nil-in-coll-3
(is (= (run* [q]
(== q [nil 1]))
'([nil 1]))))
(deftest test-nil-in-coll-4
(is (= (run* [q]
(== q '(nil)))
'((nil)))))
(deftest test-nil-in-coll-5
(is (= (run* [q]
(== q {:foo nil}))
'({:foo nil}))))
(deftest test-nil-in-coll-6
(is (= (run* [q]
(== q {nil :foo}))
'({nil :foo}))))
;; -----------------------------------------------------------------------------
;; Unifier
(deftest test-unifier-1
(is (= (unifier '(?x ?y) '(1 2))
'(1 2))))
(deftest test-unifier-2
(is (= (unifier '(?x ?y 3) '(1 2 ?z))
'(1 2 3))))
(deftest test-unifier-3
(is (= (unifier '[(?x . ?y) 3] [[1 2] 3])
'[(1 2) 3])))
(deftest test-unifier-4
(is (= (unifier '(?x . ?y) '(1 . ?z))
(lcons 1 '_.0))))
(deftest test-unifier-5
(is (= (unifier '(?x 2 . ?y) '(1 2 3 4 5))
'(1 2 3 4 5))))
(deftest test-unifier-6
(is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
(deftest test-unifier-7
(is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
(deftest test-unifier-8 ;;nested maps
(is (= (unifier '{:a {:b ?b}} {:a {:b 1}})
{:a {:b 1}})))
(deftest test-unifier-9 ;;nested vectors
(is (= (unifier '[?a [?b ?c] :d] [:a [:b :c] :d])
[:a [:b :c] :d])))
(deftest test-unifier-10 ;;nested seqs
(is (= (unifier '(?a (?b ?c) :d) '(:a (:b :c) :d))
'(:a (:b :c) :d))))
(deftest test-unifier-11 ;;all together now
(is (= (unifier '{:a [?b (?c [?d {:e ?e}])]} {:a [:b '(:c [:d {:e :e}])]})
{:a [:b '(:c [:d {:e :e}])]})))
(deftest test-binding-map-1
(is (= (binding-map '(?x ?y) '(1 2))
'{?x 1 ?y 2})))
(deftest test-binding-map-2
(is (= (binding-map '(?x ?y 3) '(1 2 ?z))
'{?x 1 ?y 2 ?z 3})))
(deftest test-binding-map-3
(is (= (binding-map '[(?x . ?y) 3] [[1 2] 3])
'{?x 1 ?y (2)})))
(deftest test-binding-map-4
(is (= (binding-map '(?x . ?y) '(1 . ?z))
'{?z _.0, ?x 1, ?y _.0})))
(deftest test-binding-map-5
(is (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5))
'{?x 1 ?y (3 4 5)})))
(deftest test-binding-map-6
(is (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
;; -----------------------------------------------------------------------------
;; Occurs Check
(deftest test-occurs-check-1
(is (= (run* [q]
(== q [q]))
())))
;; -----------------------------------------------------------------------------
;; Unifications that should fail
(deftest test-unify-fail-1
(is (= (run* [p] (fresh [a b] (== b ()) (== '(0 1) (lcons a b)) (== p [a b])))
())))
(deftest test-unify-fail-2
(is (= (run* [p] (fresh [a b] (== b '(1)) (== '(0) (lcons a b)) (== p [a b])))
())))
(deftest test-unify-fail-3
(is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d])))
())))
;; -----------------------------------------------------------------------------
;; Pattern matching functions preserve metadata
(defne ^:tabled dummy
"Docstring"
[x l]
([_ [x . tail]])
([_ [head . tail]]
(membero x tail)))
(deftest test-metadata-defne
(is (= (-> #'dummy meta :tabled)
true))
(is (= (-> #'dummy meta :doc)
"Docstring")))
(defn locals-membero [x l]
(matche [l]
([[x . tail]])
([[head . tail]]
(locals-membero x tail))))
(deftest test-matche-with-locals
(is (= [true] (run* [q]
(locals-membero 'foo [1 2 3 4 5 'foo])
(== q true))))
(is (= [] (run* [q]
(locals-membero 'foo [1 2 3 4 5])
(== true q)))))
;; -----------------------------------------------------------------------------
;; Pattern matching inline expression support
(defn s [n] (llist n []))
(def zero 0)
(def one (s zero))
(def two (s one))
(def three (s two))
(def four (s three))
(def five (s four))
(def six (s five))
(defn natural-number [x]
(matche [x]
([zero])
([(s y)] (natural-number y))))
(deftest test-matche-with-expr
(is (= (run* [q] (natural-number one))
'(_.0 _.0))))
;; -----------------------------------------------------------------------------
;; Pattern matching other data structures
(defne match-map [m o]
([{:foo {:bar o}} _]))
(defn test-defne-map []
(is (= (run* [q]
(match-map {:foo {:bar 1}} q))
'(1))))
;; -----------------------------------------------------------------------------
;; Tickets
(deftest test-31-unifier-associative
(is (= (binding [*reify-vars* false]
(unifier '{:a ?x} '{:a ?y} '{:a 5}))
{:a 5}))
(is (= (binding [*reify-vars* false]
(unifier '{:a ?x} '{:a 5} '{:a ?y}))
{:a 5})))
(deftest test-34-unify-with-metadata
(is (run* [q]
(== q (quote ^:haz-meta-daytuhs (form form form))))
'((^:haz-meta-daytuhs (form form form)))))
(deftest test-42-multiple-run-parameters
(is (= '[[3 _.0 [3 _.0]]]
(run* [x y z]
(== z [x y])
(== [x] [3])))))
(deftest test-49-partial-map-unification
(is (= '[#clojure.core.logic.PMap{:a 1}]
(run* [q]
(fresh [pm x]
(== pm (partial-map {:a x}))
(== pm {:a 1 :b 2})
(== pm q)))))
(is (= '[#clojure.core.logic.PMap{:a 1}]
(run* [q]
(fresh [pm x]
(== (partial-map {:a x}) pm)
(== {:a 1 :b 2} pm)
(== q pm))))))
;; =============================================================================
;; <NAME>
(deftest test-pair []
(is (= (pair 1 2)
(pair 1 2))))
(deftest test-domfd-1 []
(let [x (lvar 'x)
s ((domfd x 1) empty-s)]
(is (= (:s s) {x 1}))))
#_(deftest test-domfd-2 []
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (:ws s) {x (interval 1 10)}))))
#_(deftest test-domfd-3 []
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 10))
(domfd x (interval 3 6))) empty-s)]
(is (= (:ws s) {x (interval 3 6)}))))
#_(deftest test-domfd-4 []
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 5))
(domfd x (interval 5 9))) empty-s)]
(is (= (:s s) {x 5}))
(is (= (:ws s) {}))))
(deftest test-keep-before-1 []
(is (= (keep-before (interval 1 10) 5)
(interval 1 4)))
(is (= (keep-before (interval 5 10) 5)
nil))
(is (= (keep-before (interval 5 10) 6)
5))
(is (= (keep-before (interval 5 10) 10)
(interval 5 9))))
(deftest test-drop-before-1 []
(is (= (drop-before (interval 5 10) 4)
(interval 5 10)))
(is (= (drop-before (interval 1 10) 5)
(interval 5 10)))
(is (= (drop-before (interval 5 10) 5)
(interval 5 10)))
(is (= (drop-before (interval 5 10) 6)
(interval 6 10)))
(is (= (drop-before (interval 5 10) 10)
10))
(is (= (drop-before (interval 5 10) 11)
nil)))
(deftest test-keep-before-2 []
(is (= (keep-before 1 3)
1))
(is (= (keep-before 1 2)
1))
(is (= (keep-before 1 1)
nil)))
(deftest test-drop-before-2 []
(is (= (drop-before 1 3)
nil))
(is (= (drop-before 1 2)
nil))
(is (= (drop-before 1 1)
1))
(is (= (drop-before 1 0)
1)))
(deftest test-drop-before-mi-1 []
(is (= (drop-before (multi-interval 2 4) (lb 3))
4)))
(deftest test-keep-before-mi-2 []
(is (= (keep-before (multi-interval 2 4) (lb 3))
2)))
(deftest test-singleton-interval
(is (= (interval 1 1) 1)))
(deftest test-interval-<
(is (interval-< (interval 1 10) (interval 11 20)))
(is (interval-< 1 (interval 11 20))))
(deftest test-interval->
(is (interval-> (interval 11 20) (interval 1 10)))
(is (interval-> (interval 11 20) 1)))
(deftest test-member?-ss-1
(is (true? (member? 1 1))))
(deftest test-member?-ss-2
(is (false? (member? 1 2))))
(deftest test-disjoint?-ss-1
(is (false? (disjoint? 1 1))))
(deftest test-disjoint?-ss-2
(is (true? (disjoint? 1 2))))
(deftest test-difference-ss-1
(is (= (difference 1 1)
nil)))
(deftest test-difference-ss-2
(is (= (difference 1 2)
1)))
(deftest test-intersection-ss-1
(is (= (intersection 1 1)
1)))
(deftest test-intersection-ss-2
(is (= (intersection 1 2)
nil)))
(deftest test-member?-is-1
(is (true? (member? (interval 1 10) 1))))
(deftest test-member?-si-1
(is (true? (member? 1 (interval 1 10)))))
(deftest test-disjoint?-is-1
(is (true? (disjoint? (interval 1 10) 11))))
(deftest test-disjoint?-si-1
(is (true? (disjoint? 11 (interval 1 10)))))
(deftest test-intersection-is-1
(is (= (intersection (interval 1 6) 1)
1)))
(deftest test-intersection-si-1
(is (= (intersection 1 (interval 1 6))
1)))
(deftest test-difference-is-1
(let [mi (difference (interval 1 10) 5)]
(is (= (first (intervals mi)) (interval 1 4)))
(is (= (second (intervals mi)) (interval 6 10)))))
(deftest test-difference-si-1
(let [mi (difference 5 (interval 1 10))]
(is (= (first (intervals mi)) (interval 1 4)))
(is (= (second (intervals mi)) (interval 6 10)))))
(deftest test-intersection-ii-1
(is (= (intersection (interval 1 6) (interval 5 10))
(interval 5 6))))
(deftest test-intersection-ii-2
(is (= (intersection (interval 5 10) (interval 1 6))
(interval 5 6))))
(deftest test-difference-ii-1
(is (= (difference (interval 1 6) (interval 5 10))
(interval 1 4))))
(deftest test-difference-ii-2
(is (= (difference (interval 1 4) (interval 5 10))
(interval 1 4))))
(deftest test-difference-ii-3
(is (= (difference (interval 5 10) (interval 1 4))
(interval 5 10))))
(deftest test-difference-ii-4
(is (= (difference (interval 1 10) (interval 1 10))
nil)))
(deftest test-difference-ii-5
(is (= (difference (interval 2 9) (interval 1 10))
nil)))
(deftest test-disjoint?-ii-1
(is (false? (disjoint? (interval 1 6) (interval 5 10))))
(is (false? (disjoint? (interval 5 10) (interval 1 6))))
(is (true? (disjoint? (interval 1 6) (interval 10 16))))
(is (true? (disjoint? (interval 10 16) (interval 1 6)))))
(deftest test-member?-mimi-1
(is (false? (member? 20 (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (false? (member? (multi-interval (interval 1 3) 5 (interval 7 10)) 20))))
(deftest test-disjoint?-mimi-1
(is (true? (disjoint? 20 (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (true? (disjoint? (multi-interval (interval 1 3) 5 (interval 7 10)) 20)))
(is (true? (disjoint? (interval 20 30) (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (true? (disjoint? (multi-interval (interval 1 3) 5 (interval 7 10)) (interval 20 30)))))
(deftest test-equals-mi
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 1 4) (interval 6 10))]
(is (= mi0 mi1))))
;; -----------------------------------------------------------------------------
;; MultiIntervalFD Intersection
(deftest test-intersection-mimi-1
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 9 13) (interval 17 20))]
(is (= (intersection mi0 mi1) (interval 9 10)))
(is (= (intersection mi1 mi0) (interval 9 10)))))
(deftest test-intersection-mimi-2
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))]
(is (= (intersection mi0 7) 7))
(is (= (intersection 7 mi0) 7))))
;; |-----|
;; |-----|
(deftest test-intersection-mimi-3
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (intersection mi0 (interval 3 8))
(multi-interval (interval 3 4) (interval 7 8))))))
;; |-----|
;; |---|
(deftest test-intersection-mimi-4
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))
mi1 (multi-interval (interval 2 3) (interval 6 9))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 2 3) (interval 7 9))))))
;; |-----|
;; |-----|
(deftest test-intersection-mimi-5
(let [mi0 (multi-interval (interval 4 8) (interval 12 16))
mi1 (multi-interval (interval 1 5) (interval 7 15))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 4 5) (interval 7 8) (interval 12 15))))))
;; |---|
;; |-----|
(deftest test-intersection-mimi-6
(let [mi0 (multi-interval (interval 1 3) (interval 5 6) (interval 8 10))
mi1 (multi-interval (interval 1 3) (interval 4 7) (interval 8 10))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 1 3) (interval 5 6) (interval 8 10))))))
;; |---| |---|
;; |-------|
(deftest test-intersection-mimi-7
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (intersection mi0 (interval 1 8))
(multi-interval (interval 1 4) (interval 7 8))))))
;; |--------| |--|
;; |---| |-------|
(deftest test-intersection-mimi-8
(let [mi0 (multi-interval (interval 1 7) (interval 9 10))
mi1 (multi-interval (interval 1 3) (interval 6 11))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 1 3) (interval 6 7) (interval 9 10))))))
;; -----------------------------------------------------------------------------
;; MultiIntervalFD Difference
;; |---| |---|
;; |---| |---|
(deftest test-difference-mimi-1
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 9 13) (interval 17 20))]
(is (= (difference mi0 mi1)
(multi-interval (interval 1 4) (interval 6 8))))))
;; |---| |---|
;; N
(deftest test-difference-mis-1
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (difference mi0 8)
(multi-interval (interval 1 4) 7 (interval 9 10))))))
;; N
;; |---| |---|
(deftest test-difference-smi-2
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))]
(is (= (difference 5 mi0) 5))))
;; |---| |---|
;; |-------|
;;
;; |-------|
;; |---| |---|
(deftest test-difference-mii-1
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (difference mi0 (interval 3 8))
(multi-interval (interval 1 2) (interval 9 10))))
(is (= (difference (interval 3 8) mi0)
(interval 5 6)))))
;; |---| |---|
;; |-------| |----|
(deftest test-difference-mimi-2
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))
mi1 (multi-interval (interval 1 8) (interval 10 13))]
(is (= (difference mi0 mi1) 9))))
;; |----| |-------|
;; |----| |---|
(deftest test-difference-mimi-3
(let [mi0 (multi-interval (interval 3 6) (interval 9 15))
mi1 (multi-interval (interval 1 4) (interval 10 12))]
(is (= (difference mi0 mi1)
(multi-interval (interval 5 6) 9 (interval 13 15))))))
;; |---| |---|
;; |-----| |-|
(deftest test-difference-mimi-4
(let [mi0 (multi-interval (interval 3 6) (interval 15 20))
mi1 (multi-interval (interval 1 6) (interval 10 13))]
(is (= (difference mi0 mi1)
(interval 15 20)))))
(deftest test-fd-1
(let [d (domain 1 2 3)]
(is (= (lb d) 1))
(is (= (ub d) 3))))
(deftest test-normalize-intervals-1
(let [d (domain 1 2 3)]
(is (= (normalize-intervals (intervals d))
[(interval 1 3)]))))
(deftest test-normalize-intervals-2
(let [d (multi-interval (interval 1 4) 5 (interval 6 10))]
(is (= (normalize-intervals (intervals d))
[(interval 1 10)]))))
(deftest test-domfd-interval-and-number-1
(is (= (run* [q]
(domfd q (interval 1 10))
(== q 1))
'(1)))
(is (= (run* [q]
(== q 1)
(domfd q (interval 1 10)))
'(1))))
(deftest test-domfd-interval-and-number-2
(is (= (run* [q]
(domfd q (interval 1 10))
(== q 11))
'()))
(is (= (run* [q]
(== q 11)
(domfd q (interval 1 10)))
'())))
(deftest test-domfd-many-intervals-1
(is (= (run* [q]
(domfd q (interval 1 100))
(domfd q (interval 30 60))
(domfd q (interval 50 55))
(== q 51))
'(51)))
(is (= (run* [q]
(domfd q (interval 1 100))
(domfd q (interval 30 60))
(domfd q (interval 50 55))
(== q 56))
'())))
(deftest test-process-dom-1
(let [x (lvar 'x)
s ((process-dom x 1) empty-s)]
(is (= (walk s x) 1))))
(deftest test-process-dom-2
(let [x (lvar 'x)
s ((process-dom x (interval 1 10)) empty-s)]
(is (= (get-dom s x) (interval 1 10)))))
(deftest test-domfd-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (get-dom s x) (interval 1 10)))))
(deftest test-infd-1
(let [x (lvar 'x)
y (lvar 'y)
f ((infd x y (interval 1 10)) empty-s)
s (f)]
(is (= (get-dom s x) (interval 1 10)))
(is (= (get-dom s y) (interval 1 10)))))
(deftest test-make-fdc-prim-1
(let [u (lvar 'u)
w (lvar 'w)
c (fdc (=fdc u w))]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`=fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-make-fdc-prim-2
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (+fdc u v w)]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`+fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-make-fdc-1
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`+fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-addc-1
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
cs (addc (make-cs) c)
sc (first (constraints-for cs u ::l/fd))]
(is (= c sc))
(is (= (id sc) 0))
(is (= (count (:km cs)) 2))
(is (= (count (:cm cs)) 1))))
(deftest test-addc-2
(let [u (lvar 'u)
v 1
w (lvar 'w)
c0 (fdc (+fdc u v w))
x (lvar 'x)
c1 (fdc (+fdc w v x))
cs (-> (make-cs )
(addc c0)
(addc c1))
sc0 (get (:cm cs) 0)
sc1 (get (:cm cs) 1)]
(is (= sc0 c0)) (is (= (id sc0) 0))
(is (= sc1 c1)) (is (= (id sc1) 1))
(is (= (id sc0) 0))
(is (= (count (:km cs)) 3))
(is (= (count (:cm cs)) 2))))
(deftest test-addcg
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
s ((addcg c) empty-s)]
(is (= (count (:km (:cs s))) 2))
(is (= (count (:cm (:cs s))) 1))))
#_(deftest test-purge-c
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
s ((addcg c) empty-s)
c (first (constraints-for (:cs s) u ::fd))
s (-> s
(ext-no-check u 1)
(ext-no-check w 2))
s ((checkcg c) s)]
(is (zero? (count (:km (:cs s)))))
(is (zero? (count (:cm (:cs s)))))))
(deftest test-=fd-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 6))
(domfd y (interval 5 10))) empty-s)
s ((=fd x y) s)
cs (:cs s)]
(is (= 2 (count (:km (:cs s))))) ;; works
(is (= 3 (count (:cm (:cs s)))))
(is (= (get-dom s x) (interval 5 6)))
(is (= (get-dom s y) (interval 5 6)))))
(deftest test-multi-interval-1
(let [mi (multi-interval (interval 1 3) (interval 7 10))]
(is (= 1 (lb mi)))
(is (= 10 (ub mi)))))
(deftest test-run-constraints*
(is (= (run-constraints* [] [] ::subst) s#)))
(deftest test-drop-one-1
(is (= (:s (drop-one (domain 1 2 3)))
#{2 3})))
(deftest test-drop-one-2
(is (= (drop-one (domain 1))
nil)))
(deftest test-drop-one-3
(is (= (drop-one 1)
nil)))
(deftest test-drop-one-4
(is (= (drop-one (interval 1 10))
(interval 2 10))))
(deftest test-drop-one-5
(is (= (drop-one (interval 1 1))
nil)))
(deftest test-drop-one-6
(is (= (drop-one (multi-interval (interval 1 10) (interval 15 20)))
(multi-interval (interval 2 10) (interval 15 20)))))
(deftest test-to-vals-1
(is (= (to-vals 1) '(1))))
(deftest test-to-vals-2
(is (= (to-vals (domain 1 2 3)) '(1 2 3))))
(deftest test-to-vals-3
(is (= (to-vals (interval 1 10))
'(1 2 3 4 5 6 7 8 9 10))))
(deftest test-to-vals-4
(is (= (to-vals (multi-interval (interval 1 5) (interval 7 10)))
'(1 2 3 4 5 7 8 9 10))))
(deftest test-to-vals-5
(is (= (to-vals (multi-interval (interval 1 5) 7 (interval 9 12)))
'(1 2 3 4 5 7 9 10 11 12))))
(deftest test-map-sum-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
((map-sum (fn [v] (updateg x v)))
(to-vals (interval 1 10)))))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
(force-ans x)))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-2
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
(force-ans [x])))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-3
(let [x (lvar 'x)
s ((domfd x (multi-interval (interval 1 4) (interval 6 10)))
empty-s)]
(is (= (take 10
(solutions s x
(force-ans x)))
'(1 2 3 4 6 7 8 9 10)))))
(deftest test-verify-all-bound-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 10))
(domfd y (interval 1 10))) empty-s)]
(is (nil? (verify-all-bound s [x y])))))
(deftest test-verify-all-bound-2
(let [x (lvar 'x)
y (lvar 'y)
s ((domfd x (interval 1 10)) empty-s)]
(is (thrown? Exception (verify-all-bound s [x y])))))
(deftest test-enforce-constraints-1
(let [x (lvar 'x)
s ((domfd x (interval 1 3)) empty-s)]
(is (= (solutions s x
(enforce-constraints x))
'(1 2 3)))))
(deftest test-reifyg-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 10))
(domfd y (interval 1 5))) empty-s)
s ((=fd x y) s)]
(is (= (take* ((reifyg x) s))
'(1 2 3 4 5)))))
(deftest test-process-interval-smaller-1
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 10))
(domfd x (interval 2 10))) empty-s)]
(is (= (get-dom s x)
(interval 2 10)))))
(deftest test-boundary-interval-1
(is (difference (interval 1 10) 1)
(interval 2 10)))
(deftest test-boundary-interval-1
(is (difference (interval 1 10) 10)
(interval 1 9)))
(deftest test-process-imi-1
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 2 10))
(domfd x (multi-interval (interval 1 4) (interval 6 10))))
empty-s)]
(is (= (get-dom s x)
(multi-interval (interval 2 4) (interval 6 10))))))
;; -----------------------------------------------------------------------------
;; cKanren
(deftest test-root-var-1
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y x))]
(is (= (root-var s y) x))))
(deftest test-ckanren-1
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(== q x)))
'(1 2 3))))
(deftest test-ckanren-2
(is (= (run* [q]
(fresh [x y z]
(infd x z (interval 1 5))
(infd y (interval 3 5))
(+fd x y z)
(== q [x y z])))
'([1 3 4] [2 3 5] [1 4 5]))))
(deftest test-ckanren-3
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(=fd x y)
(== q [x y])))
'([1 1] [2 2] [3 3]))))
(deftest test-ckanren-4
(is (true?
(every? (fn [[x y]] (not= x y))
(run* [q]
(fresh [x y]
(infd x y (interval 1 10))
(!=fd x y)
(== q [x y])))))))
(deftest test-ckanren-5
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(== x 2)
(!=fd x y)
(== q [x y])))
'([2 1] [2 3]))))
(deftest test-ckanren-6
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(+fd x 1 x)
(== q x)))
'())))
(deftest test-ckanren-7
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(+fd x x x)))
'())))
(deftest test-ckanren-8
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(<=fd x y)
(== q [x y])))
'([1 1] [1 2] [2 2] [1 3] [3 3] [2 3]))))
(deftest test-ckanren-9
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(<fd x y)
(== q [x y])))
'([1 2] [2 3] [1 3]))))
(defn subgoal [x]
(fresh [y]
(== y x)
(+fd 1 y 3)))
(deftest test-ckanren-10
(is (= (run* [q]
(fresh [a]
(infd a (interval 1 10))
(subgoal a)
(== q a)))
'(2))))
(deftest test-list-sorted
(is (true? (list-sorted? < [1 2 3])))
(is (true? (list-sorted? < [1 3 5])))
(is (false? (list-sorted? < [1 1 3])))
(is (false? (list-sorted? < [1 5 4 1]))))
(deftest test-with-id
(let [x (lvar 'x)
y (lvar 'y)
n* (sorted-set 1 3 5)
c (with-id (fdc (-distinctfdc x #{y} (conj n* 7))) 1)]
(is (= (id c) 1))
(is (= (id (:proc c)) 1))))
(deftest test-distinctfd
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 3))
(distinctfd [x y z])
(== q [x y z])))
'([1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]))))
(deftest test-=fd-1
(is (= (run* [q]
(fresh [a b]
(infd a b (interval 1 3))
(=fd a b)
(== q [a b])))
'([1 1] [2 2] [3 3]))))
(deftest test-!=fd-1
(is (= (run* [q]
(fresh [a b]
(infd a b (interval 1 3))
(!=fd a b)
(== q [a b])))
'([1 2] [1 3] [2 1] [2 3] [3 1] [3 2]))))
(deftest test-<fd-1
(is (= (run* [q]
(fresh [a b c]
(infd a b c (interval 1 3))
(<fd a b) (<fd b c)
(== q [a b c])))
'([1 2 3]))))
(deftest test-<fd-2
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 10))
(+fd x y z)
(<fd x y)
(== z 10)
(== q [x y z])))
'([1 9 10] [2 8 10] [3 7 10] [4 6 10]))))
(deftest test->fd-1
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 10))
(+fd x y z)
(>fd x y)
(== z 10)
(== q [x y z])))
'([6 4 10] [7 3 10] [8 2 10] [9 1 10]))))
(deftest test-<=fd-1
(is (= (run* [q]
(fresh [x y]
(== x 3)
(infd y (multi-interval 2 4))
(<=fd x y)
(== q y)))
'(4))))
(deftest test->=fd-1
(is (= (run* [q]
(fresh [x y]
(== x 3)
(infd y (multi-interval 2 4))
(>=fd x y)
(== q y)))
'(2))))
(deftest test-*fd-1
(is (= (run* [q]
(fresh [n m]
(infd n m (interval 1 10))
(*fd n 2 m)
(== q [n m])))
'([1 2] [2 4] [3 6] [4 8] [5 10]))))
(deftest test-*fd-2
(is (= (run* [q]
(fresh [n m]
(infd n m (interval 1 10))
(*fd n m 10)
(== q [n m])))
'([1 10] [2 5] [5 2] [10 1]))))
;; -----------------------------------------------------------------------------
;; CLP(Tree)
(deftest test-recover-vars []
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y 2))]
(is (= (recover-vars (:l s))
#{x y}))))
(deftest test-prefix-s []
(let [x (lvar 'x)
y (lvar 'y)
s empty-s
sp (-> s
(ext-no-check x 1)
(ext-no-check y 2))
p (prefix-s sp s)]
(is (= p
(list (pair y 2) (pair x 1))))
(is (= (-> p meta :s) sp))))
(deftest test-prefix-subsumes? []
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
s empty-s
sp (-> s
(ext-no-check x 1)
(ext-no-check y 2))
p (prefix-s sp s)]
(is (true? (prefix-subsumes? p (list (pair x 1)))))
(is (true? (prefix-subsumes? p (list (pair y 2)))))
(is (false? (prefix-subsumes? p (list (pair z 3)))))))
(deftest test-remc []
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
c (fdc (+fdc x y z))
cs (addc (make-cs) c)
cp (get (:cm cs) 0)
cs (remc cs cp)]
(is (= (:km cs) {}))
(is (= (:cm cs) {}))))
(deftest test-treec-id-1 []
(let [x (lvar 'x)
y (lvar 'y)
c (with-id (!=c x y) 0)]
(is (zero? (id c)))))
(deftest test-tree-constraint? []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1) (pair y 2)))
cs (addc (make-cs) c)]
(is (tree-constraint? ((:cm cs) 0)))
(is (= (into #{} (keys (:km cs)))
#{x y}))))
(deftest test-prefix-protocols []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1) (pair y 2)))
c (with-prefix c (list (pair x 1)))]
(is (= (prefix c)
(list (pair x 1))))))
(deftest test-!=-1 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)]
(is (= (prefix ((:cm (:cs s)) 0)) (list (pair x y))))))
(deftest test-!=-2 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)
s ((== x y) s)]
(is (= s nil))))
;; NOTE: we removed -relevant? protocol fn used for purging individual
;; vars from the constraint store. This may return but as a finer grained
;; protocol IRelevantLVar or some such
#_(deftest test-!=-3 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)
s ((== x 1) s)
s ((== y 2) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-4 []
(let [x (lvar 'x)
y (lvar 'y)
s ((== x 1) empty-s)
s ((== y 2) s)
s ((!= x y) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-5 []
(let [x (lvar 'x)
y (lvar 'y)
s ((== x 1) empty-s)
s ((!= x y) s)
s ((== y 2) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-6 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x 1) empty-s)]
(is (= (prefix ((:cm (:cs s)) 0)) (list (pair x 1))))))
#_(deftest test-normalize-store []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1)))
sc (!=c (list (pair x 1) (pair y 2)))
cs (addc (make-cs) c)]
))
(deftest test-multi-constraints-1 []
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 3))
(!= z 3)
(+fd x y z)
(== q [x y z])))
'([1 1 2]))))
(deftest test--fd-1 []
(is (= (run* [q]
(infd q (interval 1 10))
(-fd 4 q 1))
'(3)))
(is (= (run* [q]
(infd q (interval 1 10))
(-fd 4 2 q))
'(2))))
(deftest test-quotfd-1 []
(is (= (run* [q]
(infd q (interval 1 10))
(quotfd 4 2 q))
'(2))))
;; =============================================================================
;; eqfd
(deftest test-eqfd-1 []
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 0 9))
(eqfd
(= (+ x y) 9)
(= (+ (* x 2) (* y 4)) 24))
(== q [x y])))
'([6 3]))))
;; FIXME
(deftest test-eqfd-2 []
(is (= (run* [q]
(fresh [s e n d m o r y]
(== q [s e n d m o r y])
(infd s e n d m o r y (interval 0 9))
(distinctfd [s e n d m o r y])
(!=fd m 0) (!=fd s 0)
(eqfd
(= (+ (* 1000 s) (* 100 e) (* 10 n) d
(* 1000 m) (* 100 o) (* 10 r) e)
(+ (* 10000 m) (* 1000 o) (* 100 n) (* 10 e) y)))))
'([9 5 6 7 1 0 8 2]))))
(deftest test-eqfd-3 []
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 20))
(eqfd
(= (+ x y) 11)
(= (- (* 3 x) y) 5))
(== q [x y])))
'([4 7]))))
(deftest test-distinctfd-1 []
(is (= (run 1 [q]
(fresh [x y]
(distinctfd q)
(== q [x y])
(== x 1)
(== y 1)))
())))
(deftest test-logic-62-fd []
(is (= (run 1 [q]
(fresh [x y a b]
(distinctfd [x y])
(== [x y] [a b])
(== q [a b])
(== a 1)
(== b 1)))
()))
(is (= (run 1 [q]
(fresh [x y a b]
(== [x y] [a b])
(== q [a b])
(== a 1)
(== b 1)
(distinctfd [x y])))
())))
(deftest test-distincto-1 []
(is (= (run 1 [q]
(fresh [x y a b]
(distincto q)
(== [x y] [a b])
(== q [a b])
(== x 1)
(== y 2)))
'([1 2]))))
(deftest test-eq-vars-1 []
(let [x0 (lvar 'x)
x1 (with-meta x0 {:foo 'bar})
s (unify empty-s x0 x1)]
(is (= s empty-s))))
;; =============================================================================
;; predc
(deftest test-predc-1 []
(is (= (run* [q]
(predc q number? `number?))
'((_.0 :- clojure.core/number?))))
(is (= (run* [q]
(predc q number? `number?)
(== q 1))
'(1)))
(is (= (run* [q]
(== q 1)
(predc q number? `number?))
'(1)))
(is (= (run* [q]
(predc q number? `number?)
(== q "foo"))
()))
(is (= (run* [q]
(== q "foo")
(predc q number? `number?))
())))
;; =============================================================================
;; extensible unifier
(deftest test-extensible-unifier-1
(is (= (unifier '(^{::l/ann ::l/numeric} ?x) '(1))
'(1)))
(is (= (unifier '(^{::l/ann ::l/numeric} ?x) '("foo"))
nil)))
;; =============================================================================
;; Implementation Specific Tests - Subject To Change
(deftest test-attrs-1 []
(let [x (lvar 'x)
s (add-attr empty-s x :foo 'bar)]
(is (= (get-attr s x :foo) 'bar))))
(deftest test-attrs-2 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)
s (add-attr s x :foo 'bar)
s (add-attr s x :baz 'woz)]
(is (= (get-attr s x :foo) 'bar))
(is (= (get-attr s x :baz) 'woz))))
(deftest test-attrs-2 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)
s (add-attr s x :foo 'bar)
s (add-attr s x :baz 'woz)
s (rem-attr s x :foo)]
(is (= (get-attr s x :foo) nil))))
(deftest test-root-1 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)]
(= (root-var s x) x)
(= (root-val s x) 1)))
(deftest test-root-2 []
(let [x (lvar 'x)
s (add-attr empty-s x :foo 'bar)]
(is (subst-val? (root-val s x)))))
(deftest test-root-3 []
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y x))]
(is (= (root-var s y) x))))
(deftest test-update-1 []
(let [x (lvar 'x)
s (ext-no-check empty-s x (subst-val ::l/unbound))
s (add-attr s x ::fd (domain 1 2 3))
s (update s x 1)]
(is (= (:v (root-val s x)) 1))
(is (= (get-attr s x ::fd) (domain 1 2 3)))
(is (= (walk s x) 1))))
| true |
(ns clojure.core.logic.tests
(:refer-clojure :exclude [==])
(:use [clojure.core.logic :exclude [is] :as l]
clojure.test :reload)
(:require [clojure.pprint :as pp]))
;; =============================================================================
;; unify
;; -----------------------------------------------------------------------------
;; nil
(deftest unify-nil-object-1
(is (= (unify empty-s nil 1) nil)))
(deftest unify-nil-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x nil)]
(is (= (unify empty-s nil x) os))))
(deftest unify-nil-lseq-1
(let [x (lvar 'x)]
(is (= (unify empty-s nil (lcons 1 x)) nil))))
(deftest unify-nil-map-1
(let [x (lvar 'x)]
(is (= (unify empty-s nil {}) nil))))
;; -----------------------------------------------------------------------------
;; object
(deftest unify-object-nil-1
(is (= (unify empty-s 1 nil))))
(deftest unify-object-object-1
(is (= (unify empty-s 1 1) empty-s)))
(deftest unify-object-object-2
(is (= (unify empty-s :foo :foo) empty-s)))
(deftest unify-object-object-3
(is (= (unify empty-s 'foo 'foo) empty-s)))
(deftest unify-object-object-4
(is (= (unify empty-s "foo" "foo") empty-s)))
(deftest unify-object-object-5
(is (= (unify empty-s 1 2) nil)))
(deftest unify-object-object-6
(is (= (unify empty-s 2 1) nil)))
(deftest unify-object-object-7
(is (= (unify empty-s :foo :bar) nil)))
(deftest unify-object-object-8
(is (= (unify empty-s 'foo 'bar) nil)))
(deftest unify-object-object-9
(is (= (unify empty-s "foo" "bar") nil)))
(deftest unify-object-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s 1 x) os))))
(deftest unify-object-lcons-1
(let [x (lvar 'x)]
(is (= (unify empty-s 1 (lcons 1 'x)) nil))))
(deftest unify-object-seq-1
(is (= (unify empty-s 1 '()) nil)))
(deftest unify-object-seq-2
(is (= (unify empty-s 1 '[]) nil)))
(deftest unify-object-map-1
(is (= (unify empty-s 1 {}) nil)))
;; -----------------------------------------------------------------------------
;; lvar
(deftest unify-lvar-object-1
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s x 1) os))))
(deftest unify-lvar-lvar-1
(let [x (lvar 'x)
y (lvar 'y)
os (ext-no-check empty-s x y)]
(is (= (unify empty-s x y) os))))
(deftest unify-lvar-lcons-1
(let [x (lvar 'x)
y (lvar 'y)
l (lcons 1 y)
os (ext-no-check empty-s x l)]
(is (= (unify empty-s x l) os))))
(deftest unify-lvar-seq-1
(let [x (lvar 'x)
os (ext-no-check empty-s x [])]
(is (= (unify empty-s x []) os))))
(deftest unify-lvar-seq-2
(let [x (lvar 'x)
os (ext-no-check empty-s x [1 2 3])]
(is (= (unify empty-s x [1 2 3]) os))))
(deftest unify-lvar-seq-3
(let [x (lvar 'x)
os (ext-no-check empty-s x '())]
(is (= (unify empty-s x '()) os))))
(deftest unify-lvar-seq-4
(let [x (lvar 'x)
os (ext-no-check empty-s x '(1 2 3))]
(is (= (unify empty-s x '(1 2 3)) os))))
(deftest unify-lvar-map-1
(let [x (lvar 'x)
os (ext-no-check empty-s x {})]
(is (= (unify empty-s x {}) os))))
(deftest unify-lvar-map-2
(let [x (lvar 'x)
os (ext-no-check empty-s x {1 2 3 4})]
(is (= (unify empty-s x {1 2 3 4}) os))))
;; -----------------------------------------------------------------------------
;; lcons
(deftest unify-lcons-object-1
(let [x (lvar 'x)]
(is (= (unify empty-s (lcons 1 x) 1) nil))))
(deftest unify-lcons-lvar-1
(let [x (lvar 'x)
y (lvar 'y)
l (lcons 1 y)
os (ext-no-check empty-s x l)]
(is (= (unify empty-s l x) os))))
(deftest unify-lcons-lcons-1
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 x)
lc2 (lcons 1 y)
os (ext-no-check empty-s x y)]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-2
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons z y))
os (-> empty-s
(ext-no-check x y)
(ext-no-check z 2))]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-3
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 2 (lcons 3 y)))
os (ext-no-check empty-s x (lcons 3 y))]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-lcons-4
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 3 (lcons 4 y)))]
(is (= (unify empty-s lc1 lc2) nil))))
(deftest unify-lcons-lcons-5
(let [x (lvar 'x)
y (lvar 'y)
lc2 (lcons 1 (lcons 2 x))
lc1 (lcons 1 (lcons 3 (lcons 4 y)))]
(is (= (unify empty-s lc1 lc2) nil))))
(deftest unify-lcons-lcons-6
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons 2 x))
lc2 (lcons 1 (lcons 2 y))
os (ext-no-check empty-s x y)]
(is (= (unify empty-s lc1 lc2) os))))
(deftest unify-lcons-seq-1
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 2 3 4)
os (ext-no-check empty-s x '(3 4))]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-2
(let [x (lvar 'x)
y (lvar 'y)
lc1 (lcons 1 (lcons y (lcons 3 x)))
l1 '(1 2 3 4)
os (-> empty-s
(ext-no-check x '(4))
(ext-no-check y 2))]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-3
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 (lcons 3 x)))
l1 '(1 2 3)
os (ext-no-check empty-s x '())]
(is (= (unify empty-s lc1 l1) os))))
(deftest unify-lcons-seq-4
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 3 x))
l1 '(1 2 3 4)]
(is (= (unify empty-s lc1 l1) nil))))
(deftest unify-lcons-seq-5
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 3 4 5)]
(is (= (unify empty-s lc1 l1) nil))))
(deftest unify-lcons-map-1
(is (= (unify empty-s (lcons 1 (lvar 'x)) {}) nil)))
;; -----------------------------------------------------------------------------
;; seq
(deftest unify-seq-object-1
(is (= (unify empty-s '() 1) nil)))
(deftest unify-seq-object-2
(is (= (unify empty-s [] 1) nil)))
(deftest unify-seq-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x [])]
(is (= (unify empty-s [] x) os))))
(deftest unify-seq-lcons-1
(let [x (lvar 'x)
lc1 (lcons 1 (lcons 2 x))
l1 '(1 2 3 4)
os (ext-no-check empty-s x '(3 4))]
(is (= (unify empty-s l1 lc1) os))))
(deftest unify-seq-seq-1
(is (= (unify empty-s [1 2 3] [1 2 3]) empty-s)))
(deftest unify-seq-seq-2
(is (= (unify empty-s '(1 2 3) [1 2 3]) empty-s)))
(deftest unify-seq-seq-3
(is (= (unify empty-s '(1 2 3) '(1 2 3)) empty-s)))
(deftest unify-seq-seq-4
(let [x (lvar 'x)
os (ext-no-check empty-s x 2)]
(is (= (unify empty-s `(1 ~x 3) `(1 2 3)) os))))
(deftest unify-seq-seq-5
(is (= (unify empty-s [1 2] [1 2 3]) nil)))
(deftest unify-seq-seq-6
(is (= (unify empty-s '(1 2) [1 2 3]) nil)))
(deftest unify-seq-seq-7
(is (= (unify empty-s [1 2 3] [3 2 1]) nil)))
(deftest unify-seq-seq-8
(is (= (unify empty-s '() '()) empty-s)))
(deftest unify-seq-seq-9
(is (= (unify empty-s '() '(1)) nil)))
(deftest unify-seq-seq-10
(is (= (unify empty-s '(1) '()) nil)))
(deftest unify-seq-seq-11
(is (= (unify empty-s [[1 2]] [[1 2]]) empty-s)))
(deftest unify-seq-seq-12
(is (= (unify empty-s [[1 2]] [[2 1]]) nil)))
(deftest unify-seq-seq-13
(let [x (lvar 'x)
os (ext-no-check empty-s x 1)]
(is (= (unify empty-s [[x 2]] [[1 2]]) os))))
(deftest unify-seq-seq-14
(let [x (lvar 'x)
os (ext-no-check empty-s x [1 2])]
(is (= (unify empty-s [x] [[1 2]]) os))))
(deftest unify-seq-seq-15
(let [x (lvar 'x) y (lvar 'y)
u (lvar 'u) v (lvar 'v)
os (-> empty-s
(ext-no-check x 'b)
(ext-no-check y 'a))]
(is (= (unify empty-s ['a x] [y 'b]) os))))
(deftest unify-seq-map-1
(is (= (unify empty-s [] {}) nil)))
(deftest unify-seq-map-2
(is (= (unify empty-s '() {}) nil)))
;; -----------------------------------------------------------------------------
;; map
(deftest unify-map-object-1
(is (= (unify empty-s {} 1) nil)))
(deftest unify-map-lvar-1
(let [x (lvar 'x)
os (ext-no-check empty-s x {})]
(is (= (unify empty-s {} x) os))))
(deftest unify-map-lcons-1
(let [x (lvar 'x)]
(is (= (unify empty-s {} (lcons 1 x)) nil))))
(deftest unify-map-seq-1
(is (= (unify empty-s {} '()) nil)))
(deftest unify-map-map-1
(is (= (unify empty-s {} {}) empty-s)))
(deftest unify-map-map-2
(is (= (unify empty-s {1 2 3 4} {1 2 3 4}) empty-s)))
(deftest unify-map-map-3
(is (= (unify empty-s {1 2} {1 2 3 4}) nil)))
(deftest unify-map-map-4
(let [x (lvar 'x)
m1 {1 2 3 4}
m2 {1 2 3 x}
os (ext-no-check empty-s x 4)]
(is (= (unify empty-s m1 m2) os))))
(deftest unify-map-map-5
(let [x (lvar 'x)
m1 {1 2 3 4}
m2 {1 4 3 x}]
(is (= (unify empty-s m1 m2) nil))))
(defstruct foo-struct :a :b)
(deftest unify-struct-map-1
(let [x (lvar 'x)
m1 (struct-map foo-struct :a 1 :b 2)
m2 (struct-map foo-struct :a 1 :b x)
os (ext-no-check empty-s x 2)]
(is (= (unify empty-s m1 m2) os))))
(deftest unify-struct-map-2
(let [x (lvar 'x)
m1 (struct-map foo-struct :a 1 :b 2)
m2 (struct-map foo-struct :a 1 :b 3)]
(is (= (unify empty-s m1 m2) nil))))
;; =============================================================================
;; walk
(deftest test-basic-walk
(is (= (let [x (lvar 'x)
y (lvar 'y)
ss (to-s [[x 5] [y x]])]
(walk ss y))
5)))
(deftest test-deep-walk
(is (= (let [[x y z c b a :as s] (map lvar '[x y z c b a])
ss (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])]
(walk ss a))
5)))
;; =============================================================================
;; reify
(deftest test-reify-lvar-name
(is (= (let [x (lvar 'x)
y (lvar 'y)]
(reify-lvar-name (to-s [[x 5] [y x]])))
'_.2)))
;; =============================================================================
;; walk*
(deftest test-walk*
(is (= (let [x (lvar 'x)
y (lvar 'y)]
(walk* (to-s [[x 5] [y x]]) `(~x ~y)))
'(5 5))))
;; =============================================================================
;; run and unify
(deftest test-basic-unify
(is (= (run* [q]
(== true q))
'(true))))
(deftest test-basic-unify-2
(is (= (run* [q]
(fresh [x y]
(== [x y] [1 5])
(== [x y] q)))
[[1 5]])))
(deftest test-basic-unify-3
(is (= (run* [q]
(fresh [x y]
(== [x y] q)))
'[[_.0 _.1]])))
;; =============================================================================
;; fail
(deftest test-basic-failure
(is (= (run* [q]
fail
(== true q))
[])))
;; =============================================================================
;; Basic
(deftest test-all
(is (= (run* [q]
(all
(== 1 1)
(== q true)))
'(true))))
;; =============================================================================
;; TRS
(defn pairo [p]
(fresh [a d]
(== (lcons a d) p)))
(defn twino [p]
(fresh [x]
(conso x x p)))
(defn listo [l]
(conde
[(emptyo l) s#]
[(pairo l)
(fresh [d]
(resto l d)
(listo d))]))
(defn flatteno [s out]
(conde
[(emptyo s) (== '() out)]
[(pairo s)
(fresh [a d res-a res-d]
(conso a d s)
(flatteno a res-a)
(flatteno d res-d)
(appendo res-a res-d out))]
[(conso s '() out)]))
;; =============================================================================
;; conde
(deftest test-basic-conde
(is (= (run* [x]
(conde
[(== x 'olive) succeed]
[succeed succeed]
[(== x 'oil) succeed]))
'[olive _.0 oil])))
(deftest test-basic-conde-2
(is (= (run* [r]
(fresh [x y]
(conde
[(== 'split x) (== 'pea y)]
[(== 'navy x) (== 'bean y)])
(== (cons x (cons y ())) r)))
'[(split pea) (navy bean)])))
(defn teacupo [x]
(conde
[(== 'tea x) s#]
[(== 'cup x) s#]))
(deftest test-basic-conde-e-3
(is (= (run* [r]
(fresh [x y]
(conde
[(teacupo x) (== true y) s#]
[(== false x) (== true y)])
(== (cons x (cons y ())) r)))
'((false true) (tea true) (cup true)))))
;; =============================================================================
;; conso
(deftest test-conso
(is (= (run* [q]
(fresh [a d]
(conso a d '())))
())))
(deftest test-conso-1
(let [a (lvar 'a)
d (lvar 'd)]
(is (= (run* [q]
(conso a d q))
[(lcons a d)]))))
(deftest test-conso-2
(is (= (run* [q]
(== [q] nil))
[])))
(deftest test-conso-3
(is (=
(run* [q]
(conso 'a nil q))
'[(a)])))
(deftest test-conso-4
(is (= (run* [q]
(conso 'a '(d) q))
'[(a d)])))
(deftest test-conso-empty-list
(is (= (run* [q]
(conso 'a q '(a)))
'[()])))
(deftest test-conso-5
(is (= (run* [q]
(conso q '(b c) '(a b c)))
'[a])))
;; =============================================================================
;; firsto
(deftest test-firsto
(is (= (run* [q]
(firsto q '(1 2)))
(list (lcons '(1 2) (lvar 'x))))))
;; =============================================================================
;; resto
(deftest test-resto
(is (= (run* [q]
(resto q '(1 2)))
'[(_.0 1 2)])))
(deftest test-resto-2
(is (= (run* [q]
(resto q [1 2]))
'[(_.0 1 2)])))
(deftest test-resto-3
(is (= (run* [q]
(resto [1 2] q))
'[(2)])))
(deftest test-resto-4
(is (= (run* [q]
(resto [1 2 3 4 5 6 7 8] q))
'[(2 3 4 5 6 7 8)])))
;; =============================================================================
;; flatteno
(deftest test-flatteno
(is (= (run* [x]
(flatteno '[[a b] c] x))
'(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ())
(a (b) (c)) (a (b) c) (a (b) c ()) (a b (c))
(a b () (c)) (a b c) (a b c ()) (a b () c)
(a b () c ())))))
;; =============================================================================
;; membero
(deftest membero-1
(is (= (run* [q]
(all
(== q [(lvar)])
(membero ['foo (lvar)] q)
(membero [(lvar) 'bar] q)))
'([[foo bar]]))))
(deftest membero-2
(is (= (run* [q]
(all
(== q [(lvar) (lvar)])
(membero ['foo (lvar)] q)
(membero [(lvar) 'bar] q)))
'([[foo bar] _.0] [[foo _.0] [_.1 bar]]
[[_.0 bar] [foo _.1]] [_.0 [foo bar]]))))
;; -----------------------------------------------------------------------------
;; rembero
(deftest rembero-1
(is (= (run 1 [q]
(rembero 'b '(a b c b d) q))
'((a c b d)))))
;; -----------------------------------------------------------------------------
;; conde clause count
(defn digit-1 [x]
(conde
[(== 0 x)]))
(defn digit-4 [x]
(conde
[(== 0 x)]
[(== 1 x)]
[(== 2 x)]
[(== 3 x)]))
(deftest test-conde-1-clause
(is (= (run* [q]
(fresh [x y]
(digit-1 x)
(digit-1 y)
(== q [x y])))
'([0 0]))))
(deftest test-conde-4-clauses
(is (= (run* [q]
(fresh [x y]
(digit-4 x)
(digit-4 y)
(== q [x y])))
'([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0]
[1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3]))))
;; -----------------------------------------------------------------------------
;; anyo
(defn anyo [q]
(conde
[q s#]
[(anyo q)]))
(deftest test-anyo-1
(is (= (run 1 [q]
(anyo s#)
(== true q))
(list true))))
(deftest test-anyo-2
(is (= (run 5 [q]
(anyo s#)
(== true q))
(list true true true true true))))
;; -----------------------------------------------------------------------------
;; divergence
(def f1 (fresh [] f1))
(deftest test-divergence-1
(is (= (run 1 [q]
(conde
[f1]
[(== false false)]))
'(_.0))))
(deftest test-divergence-2
(is (= (run 1 [q]
(conde
[f1 (== false false)]
[(== false false)]))
'(_.0))))
(def f2
(fresh []
(conde
[f2 (conde
[f2]
[(== false false)])]
[(== false false)])))
(deftest test-divergence-3
(is (= (run 5 [q] f2)
'(_.0 _.0 _.0 _.0 _.0))))
;; -----------------------------------------------------------------------------
;; conda (soft-cut)
(deftest test-conda-1
(is (= (run* [x]
(conda
[(== 'olive x) s#]
[(== 'oil x) s#]
[u#]))
'(olive))))
(deftest test-conda-2
(is (= (run* [x]
(conda
[(== 'virgin x) u#]
[(== 'olive x) s#]
[(== 'oil x) s#]
[u#]))
'())))
(deftest test-conda-3
(is (= (run* [x]
(fresh (x y)
(== 'split x)
(== 'pea y)
(conda
[(== 'split x) (== x y)]
[s#]))
(== true x))
'())))
(deftest test-conda-4
(is (= (run* [x]
(fresh (x y)
(== 'split x)
(== 'pea y)
(conda
[(== x y) (== 'split x)]
[s#]))
(== true x))
'(true))))
(defn not-pastao [x]
(conda
[(== 'pasta x) u#]
[s#]))
(deftest test-conda-5
(is (= (run* [x]
(conda
[(not-pastao x)]
[(== 'spaghetti x)]))
'(spaghetti))))
;; -----------------------------------------------------------------------------
;; condu (committed-choice)
(comment
(defn onceo [g]
(condu
(g s#)))
(deftest test-condu-1
(is (= (run* [x]
(onceo (teacupo x)))
'(tea))))
)
(deftest test-condu-2
(is (= (run* [r]
(conde
[(teacupo r) s#]
[(== false r) s#]))
'(false tea cup))))
(deftest test-condu-3
(is (= (run* [r]
(conda
[(teacupo r) s#]
[(== false r) s#]))
'(tea cup))))
;; -----------------------------------------------------------------------------
;; disequality
(deftest test-disequality-1
(is (= (run* [q]
(fresh [x]
(!= x 1)
(== q x)))
'((_.0 :- (!= _.0 1))))))
(deftest test-disequality-2
(is (= (run* [q]
(fresh [x]
(== q x)
(!= x 1)))
'((_.0 :- (!= _.0 1))))))
(deftest test-disequality-3
(is (= (run* [q]
(fresh [x]
(!= x 1)
(== x 1)
(== q x)))
())))
(deftest test-disequality-4
(is (= (run* [q]
(fresh [x]
(== x 1)
(!= x 1)
(== q x)))
())))
(deftest test-disequality-5
(is (= (run* [q]
(fresh [x y]
(!= x y)
(== x 1)
(== y 1)
(== q x)))
())))
(deftest test-disequality-6
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 1)
(!= x y)
(== q x)))
())))
(deftest test-disequality-7
(is (= (run* [q]
(fresh [x y]
(== x 1)
(!= x y)
(== y 2)
(== q x)))
'(1))))
(deftest test-disequality-8
(is (= (run* [q]
(fresh [x y]
(!= [x 2] [y 1])
(== x 1)
(== y 3)
(== q [x y])))
'([1 3]))))
(deftest test-disequality-9
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 3)
(!= [x 2] [y 1])
(== q [x y])))
'([1 3]))))
(deftest test-disequality-10
(is (= (run* [q]
(fresh [x y]
(!= [x 2] [1 y])
(== x 1)
(== y 2)
(== q [x y])))
())))
(deftest test-disequality-11
(is (= (run* [q]
(fresh [x y]
(== x 1)
(== y 2)
(!= [x 2] [1 y])
(== q [x y])))
())))
(deftest test-disequality-12
(is (= (run* [q]
(fresh [x y z]
(!= x y)
(== y z)
(== x z)
(== q x)))
())))
(deftest test-disequality-13
(is (= (run* [q]
(fresh [x y z]
(== y z)
(== x z)
(!= x y)
(== q x)))
())))
(deftest test-disequality-14
(is (= (run* [q]
(fresh [x y z]
(== z y)
(== x z)
(!= x y)
(== q x)))
())))
(deftest test-disequality-15
(is (= (run* [q]
(fresh [x y]
(== q [x y])
(!= x 1)
(!= y 2)))
'(([_.0 _.1] :- (!= _.1 2) (!= _.0 1))))))
;; -----------------------------------------------------------------------------
;; tabled
(defne arco [x y]
([:a :b])
([:b :a])
([:b :d]))
(def patho
(tabled [x y]
(conde
[(arco x y)]
[(fresh [z]
(arco x z)
(patho z y))])))
(deftest test-tabled-1
(is (= (run* [q] (patho :a q))
'(:b :a :d))))
(defne arco-2 [x y]
([1 2])
([1 4])
([1 3])
([2 3])
([2 5])
([3 4])
([3 5])
([4 5]))
(def patho-2
(tabled [x y]
(conde
[(arco-2 x y)]
[(fresh [z]
(arco-2 x z)
(patho-2 z y))])))
(deftest test-tabled-2
(let [r (set (run* [q] (patho-2 1 q)))]
(is (and (= (count r) 4)
(= r #{2 3 4 5})))))
;; -----------------------------------------------------------------------------
;; rel
(defrel man p)
(fact man 'PI:NAME:<NAME>END_PI)
(fact man 'PI:NAME:<NAME>END_PI)
(fact man 'PI:NAME:<NAME>END_PI)
(defrel woman p)
(fact woman 'PI:NAME:<NAME>END_PI)
(fact woman 'PI:NAME:<NAME>END_PI)
(fact woman 'PI:NAME:<NAME>END_PI)
(defrel likes p1 p2)
(fact likes 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI)
(fact likes 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI)
(fact likes 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI)
(defrel fun p)
(fact fun 'Lucy)
(deftest test-rel-1
(is (= (run* [q]
(fresh [x y]
(likes x y)
(fun y)
(== q [x y])))
'([PI:NAME:<NAME>END_PI]))))
(retraction likes 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI)
(deftest test-rel-retract
(is (= (run* [q]
(fresh [x y]
(likes x y)
(== q [x y])))
'([PI:NAME:<NAME>END_PI] [PI:NAME:<NAME>END_PI]))))
(defrel rel1 ^:index a)
(fact rel1 [1 2])
(deftest test-rel-logic-29
(is (= (run* [q]
(fresh [a]
(rel1 [q a])
(== a 2)))
'(1))))
(defrel rel2 ^:index e ^:index a ^:index v)
(facts rel2 [[:e1 :a1 :v1]
[:e1 :a2 :v2]])
(retractions rel2 [[:e1 :a1 :v1]
[:e1 :a1 :v1]
[:e1 :a2 :v2]])
(deftest rel2-dup-retractions
(is (= (run* [out]
(fresh [e a v]
(rel2 e :a1 :v1)
(rel2 e a v)
(== [e a v] out))))
'()))
;; -----------------------------------------------------------------------------
;; nil in collection
(deftest test-nil-in-coll-1
(is (= (run* [q]
(== q [nil]))
'([nil]))))
(deftest test-nil-in-coll-2
(is (= (run* [q]
(== q [1 nil]))
'([1 nil]))))
(deftest test-nil-in-coll-3
(is (= (run* [q]
(== q [nil 1]))
'([nil 1]))))
(deftest test-nil-in-coll-4
(is (= (run* [q]
(== q '(nil)))
'((nil)))))
(deftest test-nil-in-coll-5
(is (= (run* [q]
(== q {:foo nil}))
'({:foo nil}))))
(deftest test-nil-in-coll-6
(is (= (run* [q]
(== q {nil :foo}))
'({nil :foo}))))
;; -----------------------------------------------------------------------------
;; Unifier
(deftest test-unifier-1
(is (= (unifier '(?x ?y) '(1 2))
'(1 2))))
(deftest test-unifier-2
(is (= (unifier '(?x ?y 3) '(1 2 ?z))
'(1 2 3))))
(deftest test-unifier-3
(is (= (unifier '[(?x . ?y) 3] [[1 2] 3])
'[(1 2) 3])))
(deftest test-unifier-4
(is (= (unifier '(?x . ?y) '(1 . ?z))
(lcons 1 '_.0))))
(deftest test-unifier-5
(is (= (unifier '(?x 2 . ?y) '(1 2 3 4 5))
'(1 2 3 4 5))))
(deftest test-unifier-6
(is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
(deftest test-unifier-7
(is (= (unifier '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
(deftest test-unifier-8 ;;nested maps
(is (= (unifier '{:a {:b ?b}} {:a {:b 1}})
{:a {:b 1}})))
(deftest test-unifier-9 ;;nested vectors
(is (= (unifier '[?a [?b ?c] :d] [:a [:b :c] :d])
[:a [:b :c] :d])))
(deftest test-unifier-10 ;;nested seqs
(is (= (unifier '(?a (?b ?c) :d) '(:a (:b :c) :d))
'(:a (:b :c) :d))))
(deftest test-unifier-11 ;;all together now
(is (= (unifier '{:a [?b (?c [?d {:e ?e}])]} {:a [:b '(:c [:d {:e :e}])]})
{:a [:b '(:c [:d {:e :e}])]})))
(deftest test-binding-map-1
(is (= (binding-map '(?x ?y) '(1 2))
'{?x 1 ?y 2})))
(deftest test-binding-map-2
(is (= (binding-map '(?x ?y 3) '(1 2 ?z))
'{?x 1 ?y 2 ?z 3})))
(deftest test-binding-map-3
(is (= (binding-map '[(?x . ?y) 3] [[1 2] 3])
'{?x 1 ?y (2)})))
(deftest test-binding-map-4
(is (= (binding-map '(?x . ?y) '(1 . ?z))
'{?z _.0, ?x 1, ?y _.0})))
(deftest test-binding-map-5
(is (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5))
'{?x 1 ?y (3 4 5)})))
(deftest test-binding-map-6
(is (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5))
nil)))
;; -----------------------------------------------------------------------------
;; Occurs Check
(deftest test-occurs-check-1
(is (= (run* [q]
(== q [q]))
())))
;; -----------------------------------------------------------------------------
;; Unifications that should fail
(deftest test-unify-fail-1
(is (= (run* [p] (fresh [a b] (== b ()) (== '(0 1) (lcons a b)) (== p [a b])))
())))
(deftest test-unify-fail-2
(is (= (run* [p] (fresh [a b] (== b '(1)) (== '(0) (lcons a b)) (== p [a b])))
())))
(deftest test-unify-fail-3
(is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d])))
())))
;; -----------------------------------------------------------------------------
;; Pattern matching functions preserve metadata
(defne ^:tabled dummy
"Docstring"
[x l]
([_ [x . tail]])
([_ [head . tail]]
(membero x tail)))
(deftest test-metadata-defne
(is (= (-> #'dummy meta :tabled)
true))
(is (= (-> #'dummy meta :doc)
"Docstring")))
(defn locals-membero [x l]
(matche [l]
([[x . tail]])
([[head . tail]]
(locals-membero x tail))))
(deftest test-matche-with-locals
(is (= [true] (run* [q]
(locals-membero 'foo [1 2 3 4 5 'foo])
(== q true))))
(is (= [] (run* [q]
(locals-membero 'foo [1 2 3 4 5])
(== true q)))))
;; -----------------------------------------------------------------------------
;; Pattern matching inline expression support
(defn s [n] (llist n []))
(def zero 0)
(def one (s zero))
(def two (s one))
(def three (s two))
(def four (s three))
(def five (s four))
(def six (s five))
(defn natural-number [x]
(matche [x]
([zero])
([(s y)] (natural-number y))))
(deftest test-matche-with-expr
(is (= (run* [q] (natural-number one))
'(_.0 _.0))))
;; -----------------------------------------------------------------------------
;; Pattern matching other data structures
(defne match-map [m o]
([{:foo {:bar o}} _]))
(defn test-defne-map []
(is (= (run* [q]
(match-map {:foo {:bar 1}} q))
'(1))))
;; -----------------------------------------------------------------------------
;; Tickets
(deftest test-31-unifier-associative
(is (= (binding [*reify-vars* false]
(unifier '{:a ?x} '{:a ?y} '{:a 5}))
{:a 5}))
(is (= (binding [*reify-vars* false]
(unifier '{:a ?x} '{:a 5} '{:a ?y}))
{:a 5})))
(deftest test-34-unify-with-metadata
(is (run* [q]
(== q (quote ^:haz-meta-daytuhs (form form form))))
'((^:haz-meta-daytuhs (form form form)))))
(deftest test-42-multiple-run-parameters
(is (= '[[3 _.0 [3 _.0]]]
(run* [x y z]
(== z [x y])
(== [x] [3])))))
(deftest test-49-partial-map-unification
(is (= '[#clojure.core.logic.PMap{:a 1}]
(run* [q]
(fresh [pm x]
(== pm (partial-map {:a x}))
(== pm {:a 1 :b 2})
(== pm q)))))
(is (= '[#clojure.core.logic.PMap{:a 1}]
(run* [q]
(fresh [pm x]
(== (partial-map {:a x}) pm)
(== {:a 1 :b 2} pm)
(== q pm))))))
;; =============================================================================
;; PI:NAME:<NAME>END_PI
(deftest test-pair []
(is (= (pair 1 2)
(pair 1 2))))
(deftest test-domfd-1 []
(let [x (lvar 'x)
s ((domfd x 1) empty-s)]
(is (= (:s s) {x 1}))))
#_(deftest test-domfd-2 []
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (:ws s) {x (interval 1 10)}))))
#_(deftest test-domfd-3 []
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 10))
(domfd x (interval 3 6))) empty-s)]
(is (= (:ws s) {x (interval 3 6)}))))
#_(deftest test-domfd-4 []
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 5))
(domfd x (interval 5 9))) empty-s)]
(is (= (:s s) {x 5}))
(is (= (:ws s) {}))))
(deftest test-keep-before-1 []
(is (= (keep-before (interval 1 10) 5)
(interval 1 4)))
(is (= (keep-before (interval 5 10) 5)
nil))
(is (= (keep-before (interval 5 10) 6)
5))
(is (= (keep-before (interval 5 10) 10)
(interval 5 9))))
(deftest test-drop-before-1 []
(is (= (drop-before (interval 5 10) 4)
(interval 5 10)))
(is (= (drop-before (interval 1 10) 5)
(interval 5 10)))
(is (= (drop-before (interval 5 10) 5)
(interval 5 10)))
(is (= (drop-before (interval 5 10) 6)
(interval 6 10)))
(is (= (drop-before (interval 5 10) 10)
10))
(is (= (drop-before (interval 5 10) 11)
nil)))
(deftest test-keep-before-2 []
(is (= (keep-before 1 3)
1))
(is (= (keep-before 1 2)
1))
(is (= (keep-before 1 1)
nil)))
(deftest test-drop-before-2 []
(is (= (drop-before 1 3)
nil))
(is (= (drop-before 1 2)
nil))
(is (= (drop-before 1 1)
1))
(is (= (drop-before 1 0)
1)))
(deftest test-drop-before-mi-1 []
(is (= (drop-before (multi-interval 2 4) (lb 3))
4)))
(deftest test-keep-before-mi-2 []
(is (= (keep-before (multi-interval 2 4) (lb 3))
2)))
(deftest test-singleton-interval
(is (= (interval 1 1) 1)))
(deftest test-interval-<
(is (interval-< (interval 1 10) (interval 11 20)))
(is (interval-< 1 (interval 11 20))))
(deftest test-interval->
(is (interval-> (interval 11 20) (interval 1 10)))
(is (interval-> (interval 11 20) 1)))
(deftest test-member?-ss-1
(is (true? (member? 1 1))))
(deftest test-member?-ss-2
(is (false? (member? 1 2))))
(deftest test-disjoint?-ss-1
(is (false? (disjoint? 1 1))))
(deftest test-disjoint?-ss-2
(is (true? (disjoint? 1 2))))
(deftest test-difference-ss-1
(is (= (difference 1 1)
nil)))
(deftest test-difference-ss-2
(is (= (difference 1 2)
1)))
(deftest test-intersection-ss-1
(is (= (intersection 1 1)
1)))
(deftest test-intersection-ss-2
(is (= (intersection 1 2)
nil)))
(deftest test-member?-is-1
(is (true? (member? (interval 1 10) 1))))
(deftest test-member?-si-1
(is (true? (member? 1 (interval 1 10)))))
(deftest test-disjoint?-is-1
(is (true? (disjoint? (interval 1 10) 11))))
(deftest test-disjoint?-si-1
(is (true? (disjoint? 11 (interval 1 10)))))
(deftest test-intersection-is-1
(is (= (intersection (interval 1 6) 1)
1)))
(deftest test-intersection-si-1
(is (= (intersection 1 (interval 1 6))
1)))
(deftest test-difference-is-1
(let [mi (difference (interval 1 10) 5)]
(is (= (first (intervals mi)) (interval 1 4)))
(is (= (second (intervals mi)) (interval 6 10)))))
(deftest test-difference-si-1
(let [mi (difference 5 (interval 1 10))]
(is (= (first (intervals mi)) (interval 1 4)))
(is (= (second (intervals mi)) (interval 6 10)))))
(deftest test-intersection-ii-1
(is (= (intersection (interval 1 6) (interval 5 10))
(interval 5 6))))
(deftest test-intersection-ii-2
(is (= (intersection (interval 5 10) (interval 1 6))
(interval 5 6))))
(deftest test-difference-ii-1
(is (= (difference (interval 1 6) (interval 5 10))
(interval 1 4))))
(deftest test-difference-ii-2
(is (= (difference (interval 1 4) (interval 5 10))
(interval 1 4))))
(deftest test-difference-ii-3
(is (= (difference (interval 5 10) (interval 1 4))
(interval 5 10))))
(deftest test-difference-ii-4
(is (= (difference (interval 1 10) (interval 1 10))
nil)))
(deftest test-difference-ii-5
(is (= (difference (interval 2 9) (interval 1 10))
nil)))
(deftest test-disjoint?-ii-1
(is (false? (disjoint? (interval 1 6) (interval 5 10))))
(is (false? (disjoint? (interval 5 10) (interval 1 6))))
(is (true? (disjoint? (interval 1 6) (interval 10 16))))
(is (true? (disjoint? (interval 10 16) (interval 1 6)))))
(deftest test-member?-mimi-1
(is (false? (member? 20 (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (false? (member? (multi-interval (interval 1 3) 5 (interval 7 10)) 20))))
(deftest test-disjoint?-mimi-1
(is (true? (disjoint? 20 (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (true? (disjoint? (multi-interval (interval 1 3) 5 (interval 7 10)) 20)))
(is (true? (disjoint? (interval 20 30) (multi-interval (interval 1 3) 5 (interval 7 10)))))
(is (true? (disjoint? (multi-interval (interval 1 3) 5 (interval 7 10)) (interval 20 30)))))
(deftest test-equals-mi
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 1 4) (interval 6 10))]
(is (= mi0 mi1))))
;; -----------------------------------------------------------------------------
;; MultiIntervalFD Intersection
(deftest test-intersection-mimi-1
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 9 13) (interval 17 20))]
(is (= (intersection mi0 mi1) (interval 9 10)))
(is (= (intersection mi1 mi0) (interval 9 10)))))
(deftest test-intersection-mimi-2
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))]
(is (= (intersection mi0 7) 7))
(is (= (intersection 7 mi0) 7))))
;; |-----|
;; |-----|
(deftest test-intersection-mimi-3
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (intersection mi0 (interval 3 8))
(multi-interval (interval 3 4) (interval 7 8))))))
;; |-----|
;; |---|
(deftest test-intersection-mimi-4
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))
mi1 (multi-interval (interval 2 3) (interval 6 9))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 2 3) (interval 7 9))))))
;; |-----|
;; |-----|
(deftest test-intersection-mimi-5
(let [mi0 (multi-interval (interval 4 8) (interval 12 16))
mi1 (multi-interval (interval 1 5) (interval 7 15))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 4 5) (interval 7 8) (interval 12 15))))))
;; |---|
;; |-----|
(deftest test-intersection-mimi-6
(let [mi0 (multi-interval (interval 1 3) (interval 5 6) (interval 8 10))
mi1 (multi-interval (interval 1 3) (interval 4 7) (interval 8 10))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 1 3) (interval 5 6) (interval 8 10))))))
;; |---| |---|
;; |-------|
(deftest test-intersection-mimi-7
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (intersection mi0 (interval 1 8))
(multi-interval (interval 1 4) (interval 7 8))))))
;; |--------| |--|
;; |---| |-------|
(deftest test-intersection-mimi-8
(let [mi0 (multi-interval (interval 1 7) (interval 9 10))
mi1 (multi-interval (interval 1 3) (interval 6 11))]
(is (= (intersection mi0 mi1)
(multi-interval (interval 1 3) (interval 6 7) (interval 9 10))))))
;; -----------------------------------------------------------------------------
;; MultiIntervalFD Difference
;; |---| |---|
;; |---| |---|
(deftest test-difference-mimi-1
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))
mi1 (multi-interval (interval 9 13) (interval 17 20))]
(is (= (difference mi0 mi1)
(multi-interval (interval 1 4) (interval 6 8))))))
;; |---| |---|
;; N
(deftest test-difference-mis-1
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (difference mi0 8)
(multi-interval (interval 1 4) 7 (interval 9 10))))))
;; N
;; |---| |---|
(deftest test-difference-smi-2
(let [mi0 (multi-interval (interval 1 4) (interval 6 10))]
(is (= (difference 5 mi0) 5))))
;; |---| |---|
;; |-------|
;;
;; |-------|
;; |---| |---|
(deftest test-difference-mii-1
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))]
(is (= (difference mi0 (interval 3 8))
(multi-interval (interval 1 2) (interval 9 10))))
(is (= (difference (interval 3 8) mi0)
(interval 5 6)))))
;; |---| |---|
;; |-------| |----|
(deftest test-difference-mimi-2
(let [mi0 (multi-interval (interval 1 4) (interval 7 10))
mi1 (multi-interval (interval 1 8) (interval 10 13))]
(is (= (difference mi0 mi1) 9))))
;; |----| |-------|
;; |----| |---|
(deftest test-difference-mimi-3
(let [mi0 (multi-interval (interval 3 6) (interval 9 15))
mi1 (multi-interval (interval 1 4) (interval 10 12))]
(is (= (difference mi0 mi1)
(multi-interval (interval 5 6) 9 (interval 13 15))))))
;; |---| |---|
;; |-----| |-|
(deftest test-difference-mimi-4
(let [mi0 (multi-interval (interval 3 6) (interval 15 20))
mi1 (multi-interval (interval 1 6) (interval 10 13))]
(is (= (difference mi0 mi1)
(interval 15 20)))))
(deftest test-fd-1
(let [d (domain 1 2 3)]
(is (= (lb d) 1))
(is (= (ub d) 3))))
(deftest test-normalize-intervals-1
(let [d (domain 1 2 3)]
(is (= (normalize-intervals (intervals d))
[(interval 1 3)]))))
(deftest test-normalize-intervals-2
(let [d (multi-interval (interval 1 4) 5 (interval 6 10))]
(is (= (normalize-intervals (intervals d))
[(interval 1 10)]))))
(deftest test-domfd-interval-and-number-1
(is (= (run* [q]
(domfd q (interval 1 10))
(== q 1))
'(1)))
(is (= (run* [q]
(== q 1)
(domfd q (interval 1 10)))
'(1))))
(deftest test-domfd-interval-and-number-2
(is (= (run* [q]
(domfd q (interval 1 10))
(== q 11))
'()))
(is (= (run* [q]
(== q 11)
(domfd q (interval 1 10)))
'())))
(deftest test-domfd-many-intervals-1
(is (= (run* [q]
(domfd q (interval 1 100))
(domfd q (interval 30 60))
(domfd q (interval 50 55))
(== q 51))
'(51)))
(is (= (run* [q]
(domfd q (interval 1 100))
(domfd q (interval 30 60))
(domfd q (interval 50 55))
(== q 56))
'())))
(deftest test-process-dom-1
(let [x (lvar 'x)
s ((process-dom x 1) empty-s)]
(is (= (walk s x) 1))))
(deftest test-process-dom-2
(let [x (lvar 'x)
s ((process-dom x (interval 1 10)) empty-s)]
(is (= (get-dom s x) (interval 1 10)))))
(deftest test-domfd-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (get-dom s x) (interval 1 10)))))
(deftest test-infd-1
(let [x (lvar 'x)
y (lvar 'y)
f ((infd x y (interval 1 10)) empty-s)
s (f)]
(is (= (get-dom s x) (interval 1 10)))
(is (= (get-dom s y) (interval 1 10)))))
(deftest test-make-fdc-prim-1
(let [u (lvar 'u)
w (lvar 'w)
c (fdc (=fdc u w))]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`=fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-make-fdc-prim-2
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (+fdc u v w)]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`+fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-make-fdc-1
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))]
(is (= (var-rands c)
[u w]))
(is (= (rator c)
`+fd))
(is (false? (runnable? c empty-s)))
(is (true? (relevant? c empty-s)))))
(deftest test-addc-1
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
cs (addc (make-cs) c)
sc (first (constraints-for cs u ::l/fd))]
(is (= c sc))
(is (= (id sc) 0))
(is (= (count (:km cs)) 2))
(is (= (count (:cm cs)) 1))))
(deftest test-addc-2
(let [u (lvar 'u)
v 1
w (lvar 'w)
c0 (fdc (+fdc u v w))
x (lvar 'x)
c1 (fdc (+fdc w v x))
cs (-> (make-cs )
(addc c0)
(addc c1))
sc0 (get (:cm cs) 0)
sc1 (get (:cm cs) 1)]
(is (= sc0 c0)) (is (= (id sc0) 0))
(is (= sc1 c1)) (is (= (id sc1) 1))
(is (= (id sc0) 0))
(is (= (count (:km cs)) 3))
(is (= (count (:cm cs)) 2))))
(deftest test-addcg
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
s ((addcg c) empty-s)]
(is (= (count (:km (:cs s))) 2))
(is (= (count (:cm (:cs s))) 1))))
#_(deftest test-purge-c
(let [u (lvar 'u)
v 1
w (lvar 'w)
c (fdc (+fdc u v w))
s ((addcg c) empty-s)
c (first (constraints-for (:cs s) u ::fd))
s (-> s
(ext-no-check u 1)
(ext-no-check w 2))
s ((checkcg c) s)]
(is (zero? (count (:km (:cs s)))))
(is (zero? (count (:cm (:cs s)))))))
(deftest test-=fd-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 6))
(domfd y (interval 5 10))) empty-s)
s ((=fd x y) s)
cs (:cs s)]
(is (= 2 (count (:km (:cs s))))) ;; works
(is (= 3 (count (:cm (:cs s)))))
(is (= (get-dom s x) (interval 5 6)))
(is (= (get-dom s y) (interval 5 6)))))
(deftest test-multi-interval-1
(let [mi (multi-interval (interval 1 3) (interval 7 10))]
(is (= 1 (lb mi)))
(is (= 10 (ub mi)))))
(deftest test-run-constraints*
(is (= (run-constraints* [] [] ::subst) s#)))
(deftest test-drop-one-1
(is (= (:s (drop-one (domain 1 2 3)))
#{2 3})))
(deftest test-drop-one-2
(is (= (drop-one (domain 1))
nil)))
(deftest test-drop-one-3
(is (= (drop-one 1)
nil)))
(deftest test-drop-one-4
(is (= (drop-one (interval 1 10))
(interval 2 10))))
(deftest test-drop-one-5
(is (= (drop-one (interval 1 1))
nil)))
(deftest test-drop-one-6
(is (= (drop-one (multi-interval (interval 1 10) (interval 15 20)))
(multi-interval (interval 2 10) (interval 15 20)))))
(deftest test-to-vals-1
(is (= (to-vals 1) '(1))))
(deftest test-to-vals-2
(is (= (to-vals (domain 1 2 3)) '(1 2 3))))
(deftest test-to-vals-3
(is (= (to-vals (interval 1 10))
'(1 2 3 4 5 6 7 8 9 10))))
(deftest test-to-vals-4
(is (= (to-vals (multi-interval (interval 1 5) (interval 7 10)))
'(1 2 3 4 5 7 8 9 10))))
(deftest test-to-vals-5
(is (= (to-vals (multi-interval (interval 1 5) 7 (interval 9 12)))
'(1 2 3 4 5 7 9 10 11 12))))
(deftest test-map-sum-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
((map-sum (fn [v] (updateg x v)))
(to-vals (interval 1 10)))))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-1
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
(force-ans x)))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-2
(let [x (lvar 'x)
s ((domfd x (interval 1 10)) empty-s)]
(is (= (take 10
(solutions s x
(force-ans [x])))
'(1 2 3 4 5 6 7 8 9 10)))))
(deftest test-force-ans-3
(let [x (lvar 'x)
s ((domfd x (multi-interval (interval 1 4) (interval 6 10)))
empty-s)]
(is (= (take 10
(solutions s x
(force-ans x)))
'(1 2 3 4 6 7 8 9 10)))))
(deftest test-verify-all-bound-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 10))
(domfd y (interval 1 10))) empty-s)]
(is (nil? (verify-all-bound s [x y])))))
(deftest test-verify-all-bound-2
(let [x (lvar 'x)
y (lvar 'y)
s ((domfd x (interval 1 10)) empty-s)]
(is (thrown? Exception (verify-all-bound s [x y])))))
(deftest test-enforce-constraints-1
(let [x (lvar 'x)
s ((domfd x (interval 1 3)) empty-s)]
(is (= (solutions s x
(enforce-constraints x))
'(1 2 3)))))
(deftest test-reifyg-1
(let [x (lvar 'x)
y (lvar 'y)
s ((composeg
(domfd x (interval 1 10))
(domfd y (interval 1 5))) empty-s)
s ((=fd x y) s)]
(is (= (take* ((reifyg x) s))
'(1 2 3 4 5)))))
(deftest test-process-interval-smaller-1
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 1 10))
(domfd x (interval 2 10))) empty-s)]
(is (= (get-dom s x)
(interval 2 10)))))
(deftest test-boundary-interval-1
(is (difference (interval 1 10) 1)
(interval 2 10)))
(deftest test-boundary-interval-1
(is (difference (interval 1 10) 10)
(interval 1 9)))
(deftest test-process-imi-1
(let [x (lvar 'x)
s ((composeg
(domfd x (interval 2 10))
(domfd x (multi-interval (interval 1 4) (interval 6 10))))
empty-s)]
(is (= (get-dom s x)
(multi-interval (interval 2 4) (interval 6 10))))))
;; -----------------------------------------------------------------------------
;; cKanren
(deftest test-root-var-1
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y x))]
(is (= (root-var s y) x))))
(deftest test-ckanren-1
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(== q x)))
'(1 2 3))))
(deftest test-ckanren-2
(is (= (run* [q]
(fresh [x y z]
(infd x z (interval 1 5))
(infd y (interval 3 5))
(+fd x y z)
(== q [x y z])))
'([1 3 4] [2 3 5] [1 4 5]))))
(deftest test-ckanren-3
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(=fd x y)
(== q [x y])))
'([1 1] [2 2] [3 3]))))
(deftest test-ckanren-4
(is (true?
(every? (fn [[x y]] (not= x y))
(run* [q]
(fresh [x y]
(infd x y (interval 1 10))
(!=fd x y)
(== q [x y])))))))
(deftest test-ckanren-5
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(== x 2)
(!=fd x y)
(== q [x y])))
'([2 1] [2 3]))))
(deftest test-ckanren-6
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(+fd x 1 x)
(== q x)))
'())))
(deftest test-ckanren-7
(is (= (run* [q]
(fresh [x]
(infd x (interval 1 3))
(+fd x x x)))
'())))
(deftest test-ckanren-8
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(<=fd x y)
(== q [x y])))
'([1 1] [1 2] [2 2] [1 3] [3 3] [2 3]))))
(deftest test-ckanren-9
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 3))
(<fd x y)
(== q [x y])))
'([1 2] [2 3] [1 3]))))
(defn subgoal [x]
(fresh [y]
(== y x)
(+fd 1 y 3)))
(deftest test-ckanren-10
(is (= (run* [q]
(fresh [a]
(infd a (interval 1 10))
(subgoal a)
(== q a)))
'(2))))
(deftest test-list-sorted
(is (true? (list-sorted? < [1 2 3])))
(is (true? (list-sorted? < [1 3 5])))
(is (false? (list-sorted? < [1 1 3])))
(is (false? (list-sorted? < [1 5 4 1]))))
(deftest test-with-id
(let [x (lvar 'x)
y (lvar 'y)
n* (sorted-set 1 3 5)
c (with-id (fdc (-distinctfdc x #{y} (conj n* 7))) 1)]
(is (= (id c) 1))
(is (= (id (:proc c)) 1))))
(deftest test-distinctfd
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 3))
(distinctfd [x y z])
(== q [x y z])))
'([1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]))))
(deftest test-=fd-1
(is (= (run* [q]
(fresh [a b]
(infd a b (interval 1 3))
(=fd a b)
(== q [a b])))
'([1 1] [2 2] [3 3]))))
(deftest test-!=fd-1
(is (= (run* [q]
(fresh [a b]
(infd a b (interval 1 3))
(!=fd a b)
(== q [a b])))
'([1 2] [1 3] [2 1] [2 3] [3 1] [3 2]))))
(deftest test-<fd-1
(is (= (run* [q]
(fresh [a b c]
(infd a b c (interval 1 3))
(<fd a b) (<fd b c)
(== q [a b c])))
'([1 2 3]))))
(deftest test-<fd-2
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 10))
(+fd x y z)
(<fd x y)
(== z 10)
(== q [x y z])))
'([1 9 10] [2 8 10] [3 7 10] [4 6 10]))))
(deftest test->fd-1
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 10))
(+fd x y z)
(>fd x y)
(== z 10)
(== q [x y z])))
'([6 4 10] [7 3 10] [8 2 10] [9 1 10]))))
(deftest test-<=fd-1
(is (= (run* [q]
(fresh [x y]
(== x 3)
(infd y (multi-interval 2 4))
(<=fd x y)
(== q y)))
'(4))))
(deftest test->=fd-1
(is (= (run* [q]
(fresh [x y]
(== x 3)
(infd y (multi-interval 2 4))
(>=fd x y)
(== q y)))
'(2))))
(deftest test-*fd-1
(is (= (run* [q]
(fresh [n m]
(infd n m (interval 1 10))
(*fd n 2 m)
(== q [n m])))
'([1 2] [2 4] [3 6] [4 8] [5 10]))))
(deftest test-*fd-2
(is (= (run* [q]
(fresh [n m]
(infd n m (interval 1 10))
(*fd n m 10)
(== q [n m])))
'([1 10] [2 5] [5 2] [10 1]))))
;; -----------------------------------------------------------------------------
;; CLP(Tree)
(deftest test-recover-vars []
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y 2))]
(is (= (recover-vars (:l s))
#{x y}))))
(deftest test-prefix-s []
(let [x (lvar 'x)
y (lvar 'y)
s empty-s
sp (-> s
(ext-no-check x 1)
(ext-no-check y 2))
p (prefix-s sp s)]
(is (= p
(list (pair y 2) (pair x 1))))
(is (= (-> p meta :s) sp))))
(deftest test-prefix-subsumes? []
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
s empty-s
sp (-> s
(ext-no-check x 1)
(ext-no-check y 2))
p (prefix-s sp s)]
(is (true? (prefix-subsumes? p (list (pair x 1)))))
(is (true? (prefix-subsumes? p (list (pair y 2)))))
(is (false? (prefix-subsumes? p (list (pair z 3)))))))
(deftest test-remc []
(let [x (lvar 'x)
y (lvar 'y)
z (lvar 'z)
c (fdc (+fdc x y z))
cs (addc (make-cs) c)
cp (get (:cm cs) 0)
cs (remc cs cp)]
(is (= (:km cs) {}))
(is (= (:cm cs) {}))))
(deftest test-treec-id-1 []
(let [x (lvar 'x)
y (lvar 'y)
c (with-id (!=c x y) 0)]
(is (zero? (id c)))))
(deftest test-tree-constraint? []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1) (pair y 2)))
cs (addc (make-cs) c)]
(is (tree-constraint? ((:cm cs) 0)))
(is (= (into #{} (keys (:km cs)))
#{x y}))))
(deftest test-prefix-protocols []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1) (pair y 2)))
c (with-prefix c (list (pair x 1)))]
(is (= (prefix c)
(list (pair x 1))))))
(deftest test-!=-1 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)]
(is (= (prefix ((:cm (:cs s)) 0)) (list (pair x y))))))
(deftest test-!=-2 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)
s ((== x y) s)]
(is (= s nil))))
;; NOTE: we removed -relevant? protocol fn used for purging individual
;; vars from the constraint store. This may return but as a finer grained
;; protocol IRelevantLVar or some such
#_(deftest test-!=-3 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x y) empty-s)
s ((== x 1) s)
s ((== y 2) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-4 []
(let [x (lvar 'x)
y (lvar 'y)
s ((== x 1) empty-s)
s ((== y 2) s)
s ((!= x y) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-5 []
(let [x (lvar 'x)
y (lvar 'y)
s ((== x 1) empty-s)
s ((!= x y) s)
s ((== y 2) s)]
(is (empty? (:cm (:cs s))))
(is (empty? (:km (:cs s))))))
(deftest test-!=-6 []
(let [x (lvar 'x)
y (lvar 'y)
s ((!= x 1) empty-s)]
(is (= (prefix ((:cm (:cs s)) 0)) (list (pair x 1))))))
#_(deftest test-normalize-store []
(let [x (lvar 'x)
y (lvar 'y)
c (!=c (list (pair x 1)))
sc (!=c (list (pair x 1) (pair y 2)))
cs (addc (make-cs) c)]
))
(deftest test-multi-constraints-1 []
(is (= (run* [q]
(fresh [x y z]
(infd x y z (interval 1 3))
(!= z 3)
(+fd x y z)
(== q [x y z])))
'([1 1 2]))))
(deftest test--fd-1 []
(is (= (run* [q]
(infd q (interval 1 10))
(-fd 4 q 1))
'(3)))
(is (= (run* [q]
(infd q (interval 1 10))
(-fd 4 2 q))
'(2))))
(deftest test-quotfd-1 []
(is (= (run* [q]
(infd q (interval 1 10))
(quotfd 4 2 q))
'(2))))
;; =============================================================================
;; eqfd
(deftest test-eqfd-1 []
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 0 9))
(eqfd
(= (+ x y) 9)
(= (+ (* x 2) (* y 4)) 24))
(== q [x y])))
'([6 3]))))
;; FIXME
(deftest test-eqfd-2 []
(is (= (run* [q]
(fresh [s e n d m o r y]
(== q [s e n d m o r y])
(infd s e n d m o r y (interval 0 9))
(distinctfd [s e n d m o r y])
(!=fd m 0) (!=fd s 0)
(eqfd
(= (+ (* 1000 s) (* 100 e) (* 10 n) d
(* 1000 m) (* 100 o) (* 10 r) e)
(+ (* 10000 m) (* 1000 o) (* 100 n) (* 10 e) y)))))
'([9 5 6 7 1 0 8 2]))))
(deftest test-eqfd-3 []
(is (= (run* [q]
(fresh [x y]
(infd x y (interval 1 20))
(eqfd
(= (+ x y) 11)
(= (- (* 3 x) y) 5))
(== q [x y])))
'([4 7]))))
(deftest test-distinctfd-1 []
(is (= (run 1 [q]
(fresh [x y]
(distinctfd q)
(== q [x y])
(== x 1)
(== y 1)))
())))
(deftest test-logic-62-fd []
(is (= (run 1 [q]
(fresh [x y a b]
(distinctfd [x y])
(== [x y] [a b])
(== q [a b])
(== a 1)
(== b 1)))
()))
(is (= (run 1 [q]
(fresh [x y a b]
(== [x y] [a b])
(== q [a b])
(== a 1)
(== b 1)
(distinctfd [x y])))
())))
(deftest test-distincto-1 []
(is (= (run 1 [q]
(fresh [x y a b]
(distincto q)
(== [x y] [a b])
(== q [a b])
(== x 1)
(== y 2)))
'([1 2]))))
(deftest test-eq-vars-1 []
(let [x0 (lvar 'x)
x1 (with-meta x0 {:foo 'bar})
s (unify empty-s x0 x1)]
(is (= s empty-s))))
;; =============================================================================
;; predc
(deftest test-predc-1 []
(is (= (run* [q]
(predc q number? `number?))
'((_.0 :- clojure.core/number?))))
(is (= (run* [q]
(predc q number? `number?)
(== q 1))
'(1)))
(is (= (run* [q]
(== q 1)
(predc q number? `number?))
'(1)))
(is (= (run* [q]
(predc q number? `number?)
(== q "foo"))
()))
(is (= (run* [q]
(== q "foo")
(predc q number? `number?))
())))
;; =============================================================================
;; extensible unifier
(deftest test-extensible-unifier-1
(is (= (unifier '(^{::l/ann ::l/numeric} ?x) '(1))
'(1)))
(is (= (unifier '(^{::l/ann ::l/numeric} ?x) '("foo"))
nil)))
;; =============================================================================
;; Implementation Specific Tests - Subject To Change
(deftest test-attrs-1 []
(let [x (lvar 'x)
s (add-attr empty-s x :foo 'bar)]
(is (= (get-attr s x :foo) 'bar))))
(deftest test-attrs-2 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)
s (add-attr s x :foo 'bar)
s (add-attr s x :baz 'woz)]
(is (= (get-attr s x :foo) 'bar))
(is (= (get-attr s x :baz) 'woz))))
(deftest test-attrs-2 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)
s (add-attr s x :foo 'bar)
s (add-attr s x :baz 'woz)
s (rem-attr s x :foo)]
(is (= (get-attr s x :foo) nil))))
(deftest test-root-1 []
(let [x (lvar 'x)
s (ext-no-check empty-s x 1)]
(= (root-var s x) x)
(= (root-val s x) 1)))
(deftest test-root-2 []
(let [x (lvar 'x)
s (add-attr empty-s x :foo 'bar)]
(is (subst-val? (root-val s x)))))
(deftest test-root-3 []
(let [x (lvar 'x)
y (lvar 'y)
s (-> empty-s
(ext-no-check x 1)
(ext-no-check y x))]
(is (= (root-var s y) x))))
(deftest test-update-1 []
(let [x (lvar 'x)
s (ext-no-check empty-s x (subst-val ::l/unbound))
s (add-attr s x ::fd (domain 1 2 3))
s (update s x 1)]
(is (= (:v (root-val s x)) 1))
(is (= (get-attr s x ::fd) (domain 1 2 3)))
(is (= (walk s x) 1))))
|
[
{
"context": ";;\n;; Copyright (C) 2011,2012 Carlo Sciolla, Peter Monks\n;;\n;; Licensed under the Apache Lice",
"end": 43,
"score": 0.999836802482605,
"start": 30,
"tag": "NAME",
"value": "Carlo Sciolla"
},
{
"context": ";;\n;; Copyright (C) 2011,2012 Carlo Sciolla, Peter Monks\n;;\n;; Licensed under the Apache License, Version ",
"end": 56,
"score": 0.9997197985649109,
"start": 45,
"tag": "NAME",
"value": "Peter Monks"
}
] |
src/clojure/alfresco/nodes.clj
|
deas/lambdalf
| 1 |
;;
;; Copyright (C) 2011,2012 Carlo Sciolla, Peter Monks
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns alfresco.nodes
(:require [clojure.zip :as z]
[alfresco.core :as c]
[alfresco.model :as m]
[alfresco.search :as s]
[alfresco.auth :as a])
(:import [org.alfresco.model ContentModel]
[org.alfresco.repo.site SiteModel
DocLibNodeLocator]
[org.alfresco.service.cmr.repository ChildAssociationRef
NodeService
StoreRef
NodeRef]
[org.alfresco.repo.nodelocator NodeLocatorService
CompanyHomeNodeLocator
UserHomeNodeLocator
SitesHomeNodeLocator]))
(defn ^NodeService node-service
[]
(.getNodeService (c/alfresco-services)))
(defn ^NodeLocatorService node-locator-service
[]
(.getNodeLocatorService (c/alfresco-services)))
(defprotocol Node
"Clojure friendly interface for an Alfresco node"
(aspect? [this aspect] "True if aspect is applied to the the current ")
(properties [this] "Provides all the metadata fields currently held by this node")
(property [this prop] "Retrieves a property from a node")
(set-properties! [this & prop-defs] "Set properties on a node")
(aspects [this] "Provides all the aspect QNames of this node")
(dir? [this] "True if the node is of type or a subtype of cm:folder")
(site? [this] "True if the node is of type or a subtype of st:site")
(create-child-assoc [this propmap] "Creates a new node. Accepts a map containing the following parameters:
- assoc-type : OPTIONAL - the association type. Defaults to cm:contains
- assoc : OPTIONAL - the association name. Defaults to the new node cm:name
- props : QName -> Serializable map of initial node metadata.
It must at least contain an entry for cm:name
- type : new node type
It returns a map describing the new ChildAssociationRef")
(children [this] "Returns a seq of the node direct children")
(parent [this] "Gives the primary parent of node")
(delete! [this] "Deletes a node")
(add-aspect! [this aspect props] "Adds an aspect to a node.")
(del-aspect! [this aspect] "Removes an aspect from a node")
(type-qname [this] "Returns the qname of the provided node's type")
(set-type! [this type] "Sets the provided type onto the node. Yields nil")
(mime-type [this] "Gives the mime-type"))
(defn company-home
"Returns the 'Company Home' node."
[]
(.getNode (node-locator-service) CompanyHomeNodeLocator/NAME nil nil))
(defn user-home
"Return the node that contains the current user's home node."
[]
(.getNode (node-locator-service) UserHomeNodeLocator/NAME nil nil))
(defn sites-home
"Return the node that contains Share Sites."
[]
(.getNode (node-locator-service) SitesHomeNodeLocator/NAME nil nil))
(defn doc-lib
"Returns the Document Library for the given site, or Company Home if the given site does not have a document library.
Note: the provided node must be a valid site."
[site]
{:pre [(site? site)]}
(.getNode (node-locator-service) DocLibNodeLocator/NAME site nil))
(defn defs2map
"Creates a map out of a vararg parameter definition, e.g.:
(defn foo [x & varargs]
(let [as-map (defs2map varargs)]
(clojure.pprint/pprint as-map))))
Prints"
[& varargs]
(apply conj {} (for [[k v] (apply partition 2 varargs)]
[k v])))
(defn s2n
"Converts a String to a NodeRef."
[s]
(NodeRef. s))
(defn n2s
"Converts a NodeRef to a String."
[n]
(.toString n))
(extend-protocol Node
NodeRef
(aspect? [node aspect] (.hasAspect (node-service) node (m/qname aspect)))
(properties [node] (into {} (.getProperties (node-service) node)))
(aspects [node] (into #{} (doall (map m/qname-str (.getAspects (node-service) node)))))
(dir? [node] (= (m/qname ContentModel/TYPE_FOLDER) (.getType (node-service) node)))
(site? [node] (= (m/qname SiteModel/TYPE_SITE) (.getType (node-service) node)))
(create-child-assoc
[node {:keys [assoc-type assoc props type]}]
(let [props* (zipmap (map m/qname (keys props))
(vals props))
assoc-qname (if assoc-type
(m/qname assoc-type)
(m/qname ContentModel/ASSOC_CONTAINS))
assoc-name (if assoc
(m/qname assoc)
(m/qname (keyword "cm" (props* ContentModel/PROP_NAME))))
^ChildAssociationRef assoc-ref (.createNode (node-service)
node
assoc-qname
assoc-name
(m/qname type)
props*)]
{:type assoc-qname
:name assoc-name
:parent node
:child (.getChildRef assoc-ref)}))
(children
[node]
(into #{} (doall
(map (fn [^ChildAssociationRef x] (.getChildRef x))
(.getChildAssocs (node-service) node)))))
(parent
[node]
(.getParentRef
(.getPrimaryParent (node-service) node)))
(delete!
[node]
(.deleteNode (node-service) node))
(add-aspect!
[node aspect props]
(.addAspect (node-service)
node
(m/qname aspect)
(zipmap (map m/qname (keys props))
(vals props))))
(del-aspect!
[node aspect]
(.removeAspect (node-service) node (m/qname aspect)))
(property
[node prop]
(.getProperty (node-service) node (m/qname prop)))
(set-properties!
[node & prop-defs]
{:pre [(or (nil? prop-defs) (even? (count prop-defs)))]}
(let [prop-map (defs2map prop-defs)
qnamed-map (zipmap (map m/qname (keys prop-map))
(vals prop-map))]
(.setProperties (node-service) node qnamed-map)))
(type-qname
[node]
(m/qname (.getType (node-service) node)))
(set-type!
[type node]
(.setType (node-service) node (m/qname type)))
(mime-type
[node]
(if-let [content (property node ContentModel/PROP_CONTENT)]
(.getMimetype content)
nil)))
(defn to-seq
"Returns a lazy seq of the nodes representing the repository branch
having the given root. Uses the currently authenticated user to realize
the seq."
[root]
;; store the currently authenticated user, needed by the following closures
(let [user (a/whoami)
branch? (fn [x] (a/run-as user
(m/qname-isa? (type-qname x)
(m/qname :cm/folder))))
children (fn [x] (a/run-as user
(children x)))]
(tree-seq branch? children root)))
(defn branch?
"Verifies if the current location can have children.
While cm:content can have children, this is currently limited to cm:folder"
[node]
(m/qname-isa? "cm:folder" (type-qname node)))
(defn make-node
"Associates the given children with the given parent node"
[node children]
(apply create-child-assoc node children)
node)
(defn repo-zip
"Creates a zipper with the given node as root"
[root]
(let [children #(seq (children %))]
(z/zipper branch? children make-node root)))
|
31567
|
;;
;; Copyright (C) 2011,2012 <NAME>, <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 alfresco.nodes
(:require [clojure.zip :as z]
[alfresco.core :as c]
[alfresco.model :as m]
[alfresco.search :as s]
[alfresco.auth :as a])
(:import [org.alfresco.model ContentModel]
[org.alfresco.repo.site SiteModel
DocLibNodeLocator]
[org.alfresco.service.cmr.repository ChildAssociationRef
NodeService
StoreRef
NodeRef]
[org.alfresco.repo.nodelocator NodeLocatorService
CompanyHomeNodeLocator
UserHomeNodeLocator
SitesHomeNodeLocator]))
(defn ^NodeService node-service
[]
(.getNodeService (c/alfresco-services)))
(defn ^NodeLocatorService node-locator-service
[]
(.getNodeLocatorService (c/alfresco-services)))
(defprotocol Node
"Clojure friendly interface for an Alfresco node"
(aspect? [this aspect] "True if aspect is applied to the the current ")
(properties [this] "Provides all the metadata fields currently held by this node")
(property [this prop] "Retrieves a property from a node")
(set-properties! [this & prop-defs] "Set properties on a node")
(aspects [this] "Provides all the aspect QNames of this node")
(dir? [this] "True if the node is of type or a subtype of cm:folder")
(site? [this] "True if the node is of type or a subtype of st:site")
(create-child-assoc [this propmap] "Creates a new node. Accepts a map containing the following parameters:
- assoc-type : OPTIONAL - the association type. Defaults to cm:contains
- assoc : OPTIONAL - the association name. Defaults to the new node cm:name
- props : QName -> Serializable map of initial node metadata.
It must at least contain an entry for cm:name
- type : new node type
It returns a map describing the new ChildAssociationRef")
(children [this] "Returns a seq of the node direct children")
(parent [this] "Gives the primary parent of node")
(delete! [this] "Deletes a node")
(add-aspect! [this aspect props] "Adds an aspect to a node.")
(del-aspect! [this aspect] "Removes an aspect from a node")
(type-qname [this] "Returns the qname of the provided node's type")
(set-type! [this type] "Sets the provided type onto the node. Yields nil")
(mime-type [this] "Gives the mime-type"))
(defn company-home
"Returns the 'Company Home' node."
[]
(.getNode (node-locator-service) CompanyHomeNodeLocator/NAME nil nil))
(defn user-home
"Return the node that contains the current user's home node."
[]
(.getNode (node-locator-service) UserHomeNodeLocator/NAME nil nil))
(defn sites-home
"Return the node that contains Share Sites."
[]
(.getNode (node-locator-service) SitesHomeNodeLocator/NAME nil nil))
(defn doc-lib
"Returns the Document Library for the given site, or Company Home if the given site does not have a document library.
Note: the provided node must be a valid site."
[site]
{:pre [(site? site)]}
(.getNode (node-locator-service) DocLibNodeLocator/NAME site nil))
(defn defs2map
"Creates a map out of a vararg parameter definition, e.g.:
(defn foo [x & varargs]
(let [as-map (defs2map varargs)]
(clojure.pprint/pprint as-map))))
Prints"
[& varargs]
(apply conj {} (for [[k v] (apply partition 2 varargs)]
[k v])))
(defn s2n
"Converts a String to a NodeRef."
[s]
(NodeRef. s))
(defn n2s
"Converts a NodeRef to a String."
[n]
(.toString n))
(extend-protocol Node
NodeRef
(aspect? [node aspect] (.hasAspect (node-service) node (m/qname aspect)))
(properties [node] (into {} (.getProperties (node-service) node)))
(aspects [node] (into #{} (doall (map m/qname-str (.getAspects (node-service) node)))))
(dir? [node] (= (m/qname ContentModel/TYPE_FOLDER) (.getType (node-service) node)))
(site? [node] (= (m/qname SiteModel/TYPE_SITE) (.getType (node-service) node)))
(create-child-assoc
[node {:keys [assoc-type assoc props type]}]
(let [props* (zipmap (map m/qname (keys props))
(vals props))
assoc-qname (if assoc-type
(m/qname assoc-type)
(m/qname ContentModel/ASSOC_CONTAINS))
assoc-name (if assoc
(m/qname assoc)
(m/qname (keyword "cm" (props* ContentModel/PROP_NAME))))
^ChildAssociationRef assoc-ref (.createNode (node-service)
node
assoc-qname
assoc-name
(m/qname type)
props*)]
{:type assoc-qname
:name assoc-name
:parent node
:child (.getChildRef assoc-ref)}))
(children
[node]
(into #{} (doall
(map (fn [^ChildAssociationRef x] (.getChildRef x))
(.getChildAssocs (node-service) node)))))
(parent
[node]
(.getParentRef
(.getPrimaryParent (node-service) node)))
(delete!
[node]
(.deleteNode (node-service) node))
(add-aspect!
[node aspect props]
(.addAspect (node-service)
node
(m/qname aspect)
(zipmap (map m/qname (keys props))
(vals props))))
(del-aspect!
[node aspect]
(.removeAspect (node-service) node (m/qname aspect)))
(property
[node prop]
(.getProperty (node-service) node (m/qname prop)))
(set-properties!
[node & prop-defs]
{:pre [(or (nil? prop-defs) (even? (count prop-defs)))]}
(let [prop-map (defs2map prop-defs)
qnamed-map (zipmap (map m/qname (keys prop-map))
(vals prop-map))]
(.setProperties (node-service) node qnamed-map)))
(type-qname
[node]
(m/qname (.getType (node-service) node)))
(set-type!
[type node]
(.setType (node-service) node (m/qname type)))
(mime-type
[node]
(if-let [content (property node ContentModel/PROP_CONTENT)]
(.getMimetype content)
nil)))
(defn to-seq
"Returns a lazy seq of the nodes representing the repository branch
having the given root. Uses the currently authenticated user to realize
the seq."
[root]
;; store the currently authenticated user, needed by the following closures
(let [user (a/whoami)
branch? (fn [x] (a/run-as user
(m/qname-isa? (type-qname x)
(m/qname :cm/folder))))
children (fn [x] (a/run-as user
(children x)))]
(tree-seq branch? children root)))
(defn branch?
"Verifies if the current location can have children.
While cm:content can have children, this is currently limited to cm:folder"
[node]
(m/qname-isa? "cm:folder" (type-qname node)))
(defn make-node
"Associates the given children with the given parent node"
[node children]
(apply create-child-assoc node children)
node)
(defn repo-zip
"Creates a zipper with the given node as root"
[root]
(let [children #(seq (children %))]
(z/zipper branch? children make-node root)))
| true |
;;
;; Copyright (C) 2011,2012 PI:NAME:<NAME>END_PI, 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 alfresco.nodes
(:require [clojure.zip :as z]
[alfresco.core :as c]
[alfresco.model :as m]
[alfresco.search :as s]
[alfresco.auth :as a])
(:import [org.alfresco.model ContentModel]
[org.alfresco.repo.site SiteModel
DocLibNodeLocator]
[org.alfresco.service.cmr.repository ChildAssociationRef
NodeService
StoreRef
NodeRef]
[org.alfresco.repo.nodelocator NodeLocatorService
CompanyHomeNodeLocator
UserHomeNodeLocator
SitesHomeNodeLocator]))
(defn ^NodeService node-service
[]
(.getNodeService (c/alfresco-services)))
(defn ^NodeLocatorService node-locator-service
[]
(.getNodeLocatorService (c/alfresco-services)))
(defprotocol Node
"Clojure friendly interface for an Alfresco node"
(aspect? [this aspect] "True if aspect is applied to the the current ")
(properties [this] "Provides all the metadata fields currently held by this node")
(property [this prop] "Retrieves a property from a node")
(set-properties! [this & prop-defs] "Set properties on a node")
(aspects [this] "Provides all the aspect QNames of this node")
(dir? [this] "True if the node is of type or a subtype of cm:folder")
(site? [this] "True if the node is of type or a subtype of st:site")
(create-child-assoc [this propmap] "Creates a new node. Accepts a map containing the following parameters:
- assoc-type : OPTIONAL - the association type. Defaults to cm:contains
- assoc : OPTIONAL - the association name. Defaults to the new node cm:name
- props : QName -> Serializable map of initial node metadata.
It must at least contain an entry for cm:name
- type : new node type
It returns a map describing the new ChildAssociationRef")
(children [this] "Returns a seq of the node direct children")
(parent [this] "Gives the primary parent of node")
(delete! [this] "Deletes a node")
(add-aspect! [this aspect props] "Adds an aspect to a node.")
(del-aspect! [this aspect] "Removes an aspect from a node")
(type-qname [this] "Returns the qname of the provided node's type")
(set-type! [this type] "Sets the provided type onto the node. Yields nil")
(mime-type [this] "Gives the mime-type"))
(defn company-home
"Returns the 'Company Home' node."
[]
(.getNode (node-locator-service) CompanyHomeNodeLocator/NAME nil nil))
(defn user-home
"Return the node that contains the current user's home node."
[]
(.getNode (node-locator-service) UserHomeNodeLocator/NAME nil nil))
(defn sites-home
"Return the node that contains Share Sites."
[]
(.getNode (node-locator-service) SitesHomeNodeLocator/NAME nil nil))
(defn doc-lib
"Returns the Document Library for the given site, or Company Home if the given site does not have a document library.
Note: the provided node must be a valid site."
[site]
{:pre [(site? site)]}
(.getNode (node-locator-service) DocLibNodeLocator/NAME site nil))
(defn defs2map
"Creates a map out of a vararg parameter definition, e.g.:
(defn foo [x & varargs]
(let [as-map (defs2map varargs)]
(clojure.pprint/pprint as-map))))
Prints"
[& varargs]
(apply conj {} (for [[k v] (apply partition 2 varargs)]
[k v])))
(defn s2n
"Converts a String to a NodeRef."
[s]
(NodeRef. s))
(defn n2s
"Converts a NodeRef to a String."
[n]
(.toString n))
(extend-protocol Node
NodeRef
(aspect? [node aspect] (.hasAspect (node-service) node (m/qname aspect)))
(properties [node] (into {} (.getProperties (node-service) node)))
(aspects [node] (into #{} (doall (map m/qname-str (.getAspects (node-service) node)))))
(dir? [node] (= (m/qname ContentModel/TYPE_FOLDER) (.getType (node-service) node)))
(site? [node] (= (m/qname SiteModel/TYPE_SITE) (.getType (node-service) node)))
(create-child-assoc
[node {:keys [assoc-type assoc props type]}]
(let [props* (zipmap (map m/qname (keys props))
(vals props))
assoc-qname (if assoc-type
(m/qname assoc-type)
(m/qname ContentModel/ASSOC_CONTAINS))
assoc-name (if assoc
(m/qname assoc)
(m/qname (keyword "cm" (props* ContentModel/PROP_NAME))))
^ChildAssociationRef assoc-ref (.createNode (node-service)
node
assoc-qname
assoc-name
(m/qname type)
props*)]
{:type assoc-qname
:name assoc-name
:parent node
:child (.getChildRef assoc-ref)}))
(children
[node]
(into #{} (doall
(map (fn [^ChildAssociationRef x] (.getChildRef x))
(.getChildAssocs (node-service) node)))))
(parent
[node]
(.getParentRef
(.getPrimaryParent (node-service) node)))
(delete!
[node]
(.deleteNode (node-service) node))
(add-aspect!
[node aspect props]
(.addAspect (node-service)
node
(m/qname aspect)
(zipmap (map m/qname (keys props))
(vals props))))
(del-aspect!
[node aspect]
(.removeAspect (node-service) node (m/qname aspect)))
(property
[node prop]
(.getProperty (node-service) node (m/qname prop)))
(set-properties!
[node & prop-defs]
{:pre [(or (nil? prop-defs) (even? (count prop-defs)))]}
(let [prop-map (defs2map prop-defs)
qnamed-map (zipmap (map m/qname (keys prop-map))
(vals prop-map))]
(.setProperties (node-service) node qnamed-map)))
(type-qname
[node]
(m/qname (.getType (node-service) node)))
(set-type!
[type node]
(.setType (node-service) node (m/qname type)))
(mime-type
[node]
(if-let [content (property node ContentModel/PROP_CONTENT)]
(.getMimetype content)
nil)))
(defn to-seq
"Returns a lazy seq of the nodes representing the repository branch
having the given root. Uses the currently authenticated user to realize
the seq."
[root]
;; store the currently authenticated user, needed by the following closures
(let [user (a/whoami)
branch? (fn [x] (a/run-as user
(m/qname-isa? (type-qname x)
(m/qname :cm/folder))))
children (fn [x] (a/run-as user
(children x)))]
(tree-seq branch? children root)))
(defn branch?
"Verifies if the current location can have children.
While cm:content can have children, this is currently limited to cm:folder"
[node]
(m/qname-isa? "cm:folder" (type-qname node)))
(defn make-node
"Associates the given children with the given parent node"
[node children]
(apply create-child-assoc node children)
node)
(defn repo-zip
"Creates a zipper with the given node as root"
[root]
(let [children #(seq (children %))]
(z/zipper branch? children make-node root)))
|
[
{
"context": "50 (-> @dc/state :reporting :interval))))\n\n; TODO(Richo): The following test logs an error message, we sh",
"end": 2720,
"score": 0.9967036247253418,
"start": 2715,
"tag": "NAME",
"value": "Richo"
},
{
"context": "val 5, :ticks 22835, :interval-ms 100})))\n\n; TODO(Richo): The following test logs an error message, we sh",
"end": 5706,
"score": 0.9973610639572144,
"start": 5701,
"tag": "NAME",
"value": "Richo"
}
] |
middleware/server/test/middleware/controller_test.cljc
|
GIRA/UziScript
| 15 |
(ns middleware.controller-test
(:require #?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer-macros [deftest is testing use-fixtures]])
[clojure.core.async :as a :refer [<! go]]
[utils.tests :refer [setup-fixture test-async]]
[middleware.compilation.parser :as p]
[middleware.compilation.compiler :as cc]
[middleware.device.controller :as dc]
[middleware.device.ports.common :as ports]
[middleware.device.boards :refer [UNO]]
[middleware.device.utils.ring-buffer :as rb]
[middleware.utils.fs.common :as fs]))
(use-fixtures :once setup-fixture)
; HACK(Richo): Quick mock to fake an uzi port that does nothing...
(extend-type #?(:clj java.lang.String
:cljs string)
ports/UziPort
(close! [_])
(make-in-chan! [_] (a/to-chan! (iterate inc 0)))
(make-out-chan! [_] (a/chan (a/dropping-buffer 1))))
(defn compile-string [src]
(cc/compile-tree (p/parse src)))
(defn setup []
(ports/register-constructors! identity)
(reset! dc/state dc/initial-state)
; HACK(Richo): Fake connection
(swap! dc/state assoc
:connection (ports/connect! "FAKE_PORT")
:board UNO
:timing {:diffs (rb/make-ring-buffer 10)
:arduino nil
:middleware nil}
:reporting {:interval 5
:pins #{}
:globals #{}})
; HACK(Richo): Fake program
(let [program (compile-string
"task blink13() running 1/s { toggle(D13); }
var counter;
var n;
task loop() { add(n); }
proc add(v) { counter = inc(v); }
func inc(v) { return v + 1; }")]
(dc/run program)))
(deftest set-global-report
(setup)
(dc/set-global-report "counter" false)
(is (not (contains? (-> @dc/state :reporting :globals)
"counter")))
(dc/set-global-report "counter" true)
(is (contains? (-> @dc/state :reporting :globals)
"counter")))
(deftest set-pin-report
(setup)
(dc/set-pin-report "D13" false)
(is (not (contains? (-> @dc/state :reporting :pins)
"D13")))
(dc/set-pin-report "D13" true)
(is (contains? (-> @dc/state :reporting :pins)
"D13")))
(deftest run-program
(setup)
(let [program (compile-string "task blink13() running 1/s { toggle(D13); }")]
(dc/run program)
(is (empty? (-> @dc/state :reporting :globals)))
(is (= program (@dc/state :program)))))
(deftest set-report-interval
(setup)
(dc/set-report-interval 50)
(is (= 50 (-> @dc/state :reporting :interval))))
; TODO(Richo): The following test logs an error message, we should consider disabling logging
(deftest process-running-scripts
(setup)
(dc/process-running-scripts
{:scripts [{:running? true,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}
{:running? false,
:error-code 8,
:error-msg "OUT_OF_MEMORY",
:error? true}
{:running? false,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}
{:running? false,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}],
:timestamp 4880})
(is (= (-> @dc/state :scripts)
{"loop" {:running? false,
:index 1,
:name "loop",
:error-code 8,
:error-msg "OUT_OF_MEMORY",
:task? true,
:error? true},
"blink13" {:running? true,
:index 0,
:name "blink13",
:error-code 0,
:error-msg "NO_ERROR",
:task? true,
:error? false},
"inc" {:running? false,
:index 3,
:name "inc",
:error-code 0,
:error-msg "NO_ERROR",
:task? false,
:error? false},
"add" {:running? false,
:index 2,
:name "add",
:error-code 0,
:error-msg "NO_ERROR",
:task? false,
:error? false}})))
(deftest process-free-ram
(setup)
(dc/process-free-ram {:memory {:uzi 2182, :arduino 4163974488},
:timestamp 3429})
(is (= (-> @dc/state :memory)
{:uzi 2182, :arduino 4163974488})))
(deftest process-pin-value
(setup)
(dc/process-pin-value {:timestamp 14159, :data [{:number 13, :value 0}]})
(is (= (-> @dc/state :pins)
{:timestamp 14159, :data {"D13" {:number 13, :name "D13", :value 0}}})))
(deftest process-global-value
(setup)
(dc/process-global-value
{:timestamp 14167,
:data [{:number 3, :value 42, :raw-bytes [66 40 0 0]}
{:number 4, :value 42, :raw-bytes [66 40 0 0]}]})
(is (= (-> @dc/state :globals)
{:timestamp 14167,
:data {"n" {:number 4,
:name "n",
:value 42,
:raw-bytes [0x42 0x28 0x00 0x00]},
"counter" {:number 3,
:name "counter",
:value 42,
:raw-bytes [0x42 0x28 0x00 0x00]}}})))
(deftest process-profile
(setup)
(dc/process-profile
{:data {:report-interval 5, :ticks 22835, :interval-ms 100}})
(is (= (-> @dc/state :profiler)
{:report-interval 5, :ticks 22835, :interval-ms 100})))
; TODO(Richo): The following test logs an error message, we should consider disabling logging
(deftest process-error
(test-async
(go
(setup)
(is (dc/connected?))
(<! (dc/process-error {:error {:msg "DISCONNECT_ERROR", :code 32}}))
(is (not (dc/connected?))))))
(deftest process-debugger
(setup)
(dc/process-debugger {:data {:index 1
:pc 515
:stack [0 1 2 3 4 5 6 7]
:fp 4}})
(is (= (-> @dc/state :debugger :vm)
{:index 1, :pc 515, :stack [0 1 2 3 4 5 6 7], :fp 4})))
|
49556
|
(ns middleware.controller-test
(:require #?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer-macros [deftest is testing use-fixtures]])
[clojure.core.async :as a :refer [<! go]]
[utils.tests :refer [setup-fixture test-async]]
[middleware.compilation.parser :as p]
[middleware.compilation.compiler :as cc]
[middleware.device.controller :as dc]
[middleware.device.ports.common :as ports]
[middleware.device.boards :refer [UNO]]
[middleware.device.utils.ring-buffer :as rb]
[middleware.utils.fs.common :as fs]))
(use-fixtures :once setup-fixture)
; HACK(Richo): Quick mock to fake an uzi port that does nothing...
(extend-type #?(:clj java.lang.String
:cljs string)
ports/UziPort
(close! [_])
(make-in-chan! [_] (a/to-chan! (iterate inc 0)))
(make-out-chan! [_] (a/chan (a/dropping-buffer 1))))
(defn compile-string [src]
(cc/compile-tree (p/parse src)))
(defn setup []
(ports/register-constructors! identity)
(reset! dc/state dc/initial-state)
; HACK(Richo): Fake connection
(swap! dc/state assoc
:connection (ports/connect! "FAKE_PORT")
:board UNO
:timing {:diffs (rb/make-ring-buffer 10)
:arduino nil
:middleware nil}
:reporting {:interval 5
:pins #{}
:globals #{}})
; HACK(Richo): Fake program
(let [program (compile-string
"task blink13() running 1/s { toggle(D13); }
var counter;
var n;
task loop() { add(n); }
proc add(v) { counter = inc(v); }
func inc(v) { return v + 1; }")]
(dc/run program)))
(deftest set-global-report
(setup)
(dc/set-global-report "counter" false)
(is (not (contains? (-> @dc/state :reporting :globals)
"counter")))
(dc/set-global-report "counter" true)
(is (contains? (-> @dc/state :reporting :globals)
"counter")))
(deftest set-pin-report
(setup)
(dc/set-pin-report "D13" false)
(is (not (contains? (-> @dc/state :reporting :pins)
"D13")))
(dc/set-pin-report "D13" true)
(is (contains? (-> @dc/state :reporting :pins)
"D13")))
(deftest run-program
(setup)
(let [program (compile-string "task blink13() running 1/s { toggle(D13); }")]
(dc/run program)
(is (empty? (-> @dc/state :reporting :globals)))
(is (= program (@dc/state :program)))))
(deftest set-report-interval
(setup)
(dc/set-report-interval 50)
(is (= 50 (-> @dc/state :reporting :interval))))
; TODO(<NAME>): The following test logs an error message, we should consider disabling logging
(deftest process-running-scripts
(setup)
(dc/process-running-scripts
{:scripts [{:running? true,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}
{:running? false,
:error-code 8,
:error-msg "OUT_OF_MEMORY",
:error? true}
{:running? false,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}
{:running? false,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}],
:timestamp 4880})
(is (= (-> @dc/state :scripts)
{"loop" {:running? false,
:index 1,
:name "loop",
:error-code 8,
:error-msg "OUT_OF_MEMORY",
:task? true,
:error? true},
"blink13" {:running? true,
:index 0,
:name "blink13",
:error-code 0,
:error-msg "NO_ERROR",
:task? true,
:error? false},
"inc" {:running? false,
:index 3,
:name "inc",
:error-code 0,
:error-msg "NO_ERROR",
:task? false,
:error? false},
"add" {:running? false,
:index 2,
:name "add",
:error-code 0,
:error-msg "NO_ERROR",
:task? false,
:error? false}})))
(deftest process-free-ram
(setup)
(dc/process-free-ram {:memory {:uzi 2182, :arduino 4163974488},
:timestamp 3429})
(is (= (-> @dc/state :memory)
{:uzi 2182, :arduino 4163974488})))
(deftest process-pin-value
(setup)
(dc/process-pin-value {:timestamp 14159, :data [{:number 13, :value 0}]})
(is (= (-> @dc/state :pins)
{:timestamp 14159, :data {"D13" {:number 13, :name "D13", :value 0}}})))
(deftest process-global-value
(setup)
(dc/process-global-value
{:timestamp 14167,
:data [{:number 3, :value 42, :raw-bytes [66 40 0 0]}
{:number 4, :value 42, :raw-bytes [66 40 0 0]}]})
(is (= (-> @dc/state :globals)
{:timestamp 14167,
:data {"n" {:number 4,
:name "n",
:value 42,
:raw-bytes [0x42 0x28 0x00 0x00]},
"counter" {:number 3,
:name "counter",
:value 42,
:raw-bytes [0x42 0x28 0x00 0x00]}}})))
(deftest process-profile
(setup)
(dc/process-profile
{:data {:report-interval 5, :ticks 22835, :interval-ms 100}})
(is (= (-> @dc/state :profiler)
{:report-interval 5, :ticks 22835, :interval-ms 100})))
; TODO(<NAME>): The following test logs an error message, we should consider disabling logging
(deftest process-error
(test-async
(go
(setup)
(is (dc/connected?))
(<! (dc/process-error {:error {:msg "DISCONNECT_ERROR", :code 32}}))
(is (not (dc/connected?))))))
(deftest process-debugger
(setup)
(dc/process-debugger {:data {:index 1
:pc 515
:stack [0 1 2 3 4 5 6 7]
:fp 4}})
(is (= (-> @dc/state :debugger :vm)
{:index 1, :pc 515, :stack [0 1 2 3 4 5 6 7], :fp 4})))
| true |
(ns middleware.controller-test
(:require #?(:clj [clojure.test :refer :all]
:cljs [cljs.test :refer-macros [deftest is testing use-fixtures]])
[clojure.core.async :as a :refer [<! go]]
[utils.tests :refer [setup-fixture test-async]]
[middleware.compilation.parser :as p]
[middleware.compilation.compiler :as cc]
[middleware.device.controller :as dc]
[middleware.device.ports.common :as ports]
[middleware.device.boards :refer [UNO]]
[middleware.device.utils.ring-buffer :as rb]
[middleware.utils.fs.common :as fs]))
(use-fixtures :once setup-fixture)
; HACK(Richo): Quick mock to fake an uzi port that does nothing...
(extend-type #?(:clj java.lang.String
:cljs string)
ports/UziPort
(close! [_])
(make-in-chan! [_] (a/to-chan! (iterate inc 0)))
(make-out-chan! [_] (a/chan (a/dropping-buffer 1))))
(defn compile-string [src]
(cc/compile-tree (p/parse src)))
(defn setup []
(ports/register-constructors! identity)
(reset! dc/state dc/initial-state)
; HACK(Richo): Fake connection
(swap! dc/state assoc
:connection (ports/connect! "FAKE_PORT")
:board UNO
:timing {:diffs (rb/make-ring-buffer 10)
:arduino nil
:middleware nil}
:reporting {:interval 5
:pins #{}
:globals #{}})
; HACK(Richo): Fake program
(let [program (compile-string
"task blink13() running 1/s { toggle(D13); }
var counter;
var n;
task loop() { add(n); }
proc add(v) { counter = inc(v); }
func inc(v) { return v + 1; }")]
(dc/run program)))
(deftest set-global-report
(setup)
(dc/set-global-report "counter" false)
(is (not (contains? (-> @dc/state :reporting :globals)
"counter")))
(dc/set-global-report "counter" true)
(is (contains? (-> @dc/state :reporting :globals)
"counter")))
(deftest set-pin-report
(setup)
(dc/set-pin-report "D13" false)
(is (not (contains? (-> @dc/state :reporting :pins)
"D13")))
(dc/set-pin-report "D13" true)
(is (contains? (-> @dc/state :reporting :pins)
"D13")))
(deftest run-program
(setup)
(let [program (compile-string "task blink13() running 1/s { toggle(D13); }")]
(dc/run program)
(is (empty? (-> @dc/state :reporting :globals)))
(is (= program (@dc/state :program)))))
(deftest set-report-interval
(setup)
(dc/set-report-interval 50)
(is (= 50 (-> @dc/state :reporting :interval))))
; TODO(PI:NAME:<NAME>END_PI): The following test logs an error message, we should consider disabling logging
(deftest process-running-scripts
(setup)
(dc/process-running-scripts
{:scripts [{:running? true,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}
{:running? false,
:error-code 8,
:error-msg "OUT_OF_MEMORY",
:error? true}
{:running? false,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}
{:running? false,
:error-code 0,
:error-msg "NO_ERROR",
:error? false}],
:timestamp 4880})
(is (= (-> @dc/state :scripts)
{"loop" {:running? false,
:index 1,
:name "loop",
:error-code 8,
:error-msg "OUT_OF_MEMORY",
:task? true,
:error? true},
"blink13" {:running? true,
:index 0,
:name "blink13",
:error-code 0,
:error-msg "NO_ERROR",
:task? true,
:error? false},
"inc" {:running? false,
:index 3,
:name "inc",
:error-code 0,
:error-msg "NO_ERROR",
:task? false,
:error? false},
"add" {:running? false,
:index 2,
:name "add",
:error-code 0,
:error-msg "NO_ERROR",
:task? false,
:error? false}})))
(deftest process-free-ram
(setup)
(dc/process-free-ram {:memory {:uzi 2182, :arduino 4163974488},
:timestamp 3429})
(is (= (-> @dc/state :memory)
{:uzi 2182, :arduino 4163974488})))
(deftest process-pin-value
(setup)
(dc/process-pin-value {:timestamp 14159, :data [{:number 13, :value 0}]})
(is (= (-> @dc/state :pins)
{:timestamp 14159, :data {"D13" {:number 13, :name "D13", :value 0}}})))
(deftest process-global-value
(setup)
(dc/process-global-value
{:timestamp 14167,
:data [{:number 3, :value 42, :raw-bytes [66 40 0 0]}
{:number 4, :value 42, :raw-bytes [66 40 0 0]}]})
(is (= (-> @dc/state :globals)
{:timestamp 14167,
:data {"n" {:number 4,
:name "n",
:value 42,
:raw-bytes [0x42 0x28 0x00 0x00]},
"counter" {:number 3,
:name "counter",
:value 42,
:raw-bytes [0x42 0x28 0x00 0x00]}}})))
(deftest process-profile
(setup)
(dc/process-profile
{:data {:report-interval 5, :ticks 22835, :interval-ms 100}})
(is (= (-> @dc/state :profiler)
{:report-interval 5, :ticks 22835, :interval-ms 100})))
; TODO(PI:NAME:<NAME>END_PI): The following test logs an error message, we should consider disabling logging
(deftest process-error
(test-async
(go
(setup)
(is (dc/connected?))
(<! (dc/process-error {:error {:msg "DISCONNECT_ERROR", :code 32}}))
(is (not (dc/connected?))))))
(deftest process-debugger
(setup)
(dc/process-debugger {:data {:index 1
:pc 515
:stack [0 1 2 3 4 5 6 7]
:fp 4}})
(is (= (-> @dc/state :debugger :vm)
{:index 1, :pc 515, :stack [0 1 2 3 4 5 6 7], :fp 4})))
|
[
{
"context": "-------------------------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzz",
"end": 204,
"score": 0.9998515248298645,
"start": 188,
"tag": "NAME",
"value": "PLIQUE Guillaume"
},
{
"context": "------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzzy.phonetics\n (",
"end": 219,
"score": 0.998345673084259,
"start": 206,
"tag": "USERNAME",
"value": "Yomguithereal"
}
] |
src/clj_fuzzy/phonetics.cljc
|
sooheon/clj-fuzzy
| 222 |
;; -------------------------------------------------------------------
;; clj-fuzzy Phonetics API
;; -------------------------------------------------------------------
;;
;;
;; Author: PLIQUE Guillaume (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.phonetics
(:require clj-fuzzy.metaphone
clj-fuzzy.double-metaphone
clj-fuzzy.soundex
clj-fuzzy.nysiis
clj-fuzzy.caverphone
clj-fuzzy.match-rating
clj-fuzzy.cologne))
(def ^:export metaphone clj-fuzzy.metaphone/process)
(def ^:export double-metaphone clj-fuzzy.double-metaphone/process)
(def ^:export soundex clj-fuzzy.soundex/process)
(def ^:export nysiis clj-fuzzy.nysiis/process)
(def ^:export caverphone clj-fuzzy.caverphone/process)
(def ^:export mra-codex clj-fuzzy.match-rating/mra-codex)
(def ^:export cologne clj-fuzzy.cologne/process)
|
84383
|
;; -------------------------------------------------------------------
;; clj-fuzzy Phonetics API
;; -------------------------------------------------------------------
;;
;;
;; Author: <NAME> (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.phonetics
(:require clj-fuzzy.metaphone
clj-fuzzy.double-metaphone
clj-fuzzy.soundex
clj-fuzzy.nysiis
clj-fuzzy.caverphone
clj-fuzzy.match-rating
clj-fuzzy.cologne))
(def ^:export metaphone clj-fuzzy.metaphone/process)
(def ^:export double-metaphone clj-fuzzy.double-metaphone/process)
(def ^:export soundex clj-fuzzy.soundex/process)
(def ^:export nysiis clj-fuzzy.nysiis/process)
(def ^:export caverphone clj-fuzzy.caverphone/process)
(def ^:export mra-codex clj-fuzzy.match-rating/mra-codex)
(def ^:export cologne clj-fuzzy.cologne/process)
| true |
;; -------------------------------------------------------------------
;; clj-fuzzy Phonetics API
;; -------------------------------------------------------------------
;;
;;
;; Author: PI:NAME:<NAME>END_PI (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.phonetics
(:require clj-fuzzy.metaphone
clj-fuzzy.double-metaphone
clj-fuzzy.soundex
clj-fuzzy.nysiis
clj-fuzzy.caverphone
clj-fuzzy.match-rating
clj-fuzzy.cologne))
(def ^:export metaphone clj-fuzzy.metaphone/process)
(def ^:export double-metaphone clj-fuzzy.double-metaphone/process)
(def ^:export soundex clj-fuzzy.soundex/process)
(def ^:export nysiis clj-fuzzy.nysiis/process)
(def ^:export caverphone clj-fuzzy.caverphone/process)
(def ^:export mra-codex clj-fuzzy.match-rating/mra-codex)
(def ^:export cologne clj-fuzzy.cologne/process)
|
[
{
"context": " chords,\n intervals, etc.\"\n :author \"Jeff Rose, Sam Aaron & Marius Kempe\"}\n overtone.music.pitc",
"end": 254,
"score": 0.9998783469200134,
"start": 245,
"tag": "NAME",
"value": "Jeff Rose"
},
{
"context": " intervals, etc.\"\n :author \"Jeff Rose, Sam Aaron & Marius Kempe\"}\n overtone.music.pitch\n (:use [",
"end": 265,
"score": 0.9998748302459717,
"start": 256,
"tag": "NAME",
"value": "Sam Aaron"
},
{
"context": "ervals, etc.\"\n :author \"Jeff Rose, Sam Aaron & Marius Kempe\"}\n overtone.music.pitch\n (:use [clojure.string ",
"end": 280,
"score": 0.9998739361763,
"start": 268,
"tag": "NAME",
"value": "Marius Kempe"
}
] |
src/overtone/music/pitch.clj
|
samaaron/overtone
| 2 |
(ns
^{:doc "Functions to help generate and manipulate frequencies and sets of related frequencies.
This is the place for functions representing general musical knowledge, like scales, chords,
intervals, etc."
:author "Jeff Rose, Sam Aaron & Marius Kempe"}
overtone.music.pitch
(:use [clojure.string :only [capitalize]]
[overtone.util old-contrib]
[overtone.algo chance])
(:require [clojure.string :as string]))
;; Notes in a typical scale are related by small, prime number ratios. Of all
;; possible 7 note scales, the major scale has the highest number of consonant
;; intervals.
(defn play
[s notes]
(doall (map #(s %) notes)))
(defmacro defratio [rname ratio]
`(defn ~rname [freq#] (* freq# ~ratio)))
; Perfect consonance
(defratio unison 1/1)
(defratio octave 2/1)
(defratio fifth 3/2)
; Imperfect consonance
(defratio sixth 5/3)
(defratio third 5/4)
; Dissonance
(defratio fourth 4/3)
(defratio min-third 6/5)
(defratio min-sixth 8/5)
(defn cents
"Returns a frequency computed by adding n-cents to freq. A cent is a
logarithmic measurement of pitch, where 1-octave equals 1200 cents."
[freq n-cents]
(* freq (java.lang.Math/pow 2 (/ n-cents 1200))))
;; MIDI
(def MIDI-RANGE (range 128))
(def MIDDLE-C 60)
;; Manipulating pitch using midi note numbers
(defn shift
"Shift the 'notes' in 'phrase' by a given 'amount' of half-steps."
[phrase notes amount]
(if notes
(let [note (first notes)
shifted (+ (get phrase note) amount)]
(recur (assoc phrase note shifted) (next notes) amount))
phrase))
(defn flat
"Flatten the specified notes in the phrase."
[phrase notes]
(shift phrase notes -1))
(defn sharp
"Sharpen the specified notes in the phrase."
[phrase notes]
(shift phrase notes +1))
(defn invert
"Invert a sequence of notes using either the first note as the stationary
pivot point or the optional second argument."
[notes & [pivot]]
(let [pivot (or pivot (first notes))]
(for [n notes] (- pivot (- n pivot)))))
(defn octave-note
"Convert an octave and interval to a midi note."
[octave interval]
(+ (* octave 12) interval 12))
(def NOTES {:C 0 :c 0 :b# 0 :B# 0
:C# 1 :c# 1 :Db 1 :db 1 :DB 1 :dB 1
:D 2 :d 2
:D# 3 :d# 3 :Eb 3 :eb 3 :EB 3 :eB 3
:E 4 :e 4
:E# 5 :e# 5 :F 5 :f 5
:F# 6 :f# 6 :Gb 6 :gb 6 :GB 6 :gB 6
:G 7 :g 7
:G# 8 :g# 8 :Ab 8 :ab 8 :AB 8 :aB 8
:A 9 :a 9
:A# 10 :a# 10 :Bb 10 :bb 10 :BB 10 :bB 10
:B 11 :b 11 :Cb 11 :cb 11 :CB 11 :cB 11})
(def REVERSE-NOTES
{0 :C
1 :C#
2 :D
3 :Eb
4 :E
5 :F
6 :F#
7 :G
8 :Ab
9 :A
10 :Bb
11 :B})
(defn canonical-pitch-class-name
"Returns the canonical version of the specified pitch class pc."
[pc]
(let [pc (keyword (name pc))]
(REVERSE-NOTES (NOTES pc))))
(def MIDI-NOTE-RE-STR "([a-gA-G][#bB]?)([-0-9]+)" )
(def MIDI-NOTE-RE (re-pattern MIDI-NOTE-RE-STR))
(def ONLY-MIDI-NOTE-RE (re-pattern (str "\\A" MIDI-NOTE-RE-STR "\\Z")))
(defn- parse-note-match
"Takes a match array returned by a regexp match and returns a map of note info"
[match]
(let [[match pitch-class octave] match
pitch-class (canonical-pitch-class-name pitch-class)
octave (Integer. octave)
interval (NOTES (keyword pitch-class))]
{:match match
:pitch-class pitch-class
:octave (Integer. octave)
:interval interval
:midi-note (octave-note octave interval)}))
(defn note
"Resolves note to MIDI number format. Resolves upper and lower-case keywords
and strings in MIDI note format. If given an integer or nil, returns them
unmodified. All other inputs will raise an exception.
Usage examples:
(note \"C4\") ;=> 60
(note \"C#4\") ;=> 61
(note \"eb2\") ;=> 39
(note :F#7) ;=> 102
(note :db5) ;=> 73
(note 60) ;=> 60
(note nil) ;=> nil"
[n]
(cond
(nil? n) nil
(integer? n) (if (>= n 0)
n
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Value is out of range. Lowest value is 0"))))
(keyword? n) (note (name n))
(string? n) (let [match (re-find ONLY-MIDI-NOTE-RE n)
_ (when (nil? match)
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Does not appear to be in MIDI format i.e. C#4"))))
note-match (parse-note-match match)
_ (when (< (:octave note-match) -1)
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Octave is out of range. Lowest octave value is -1"))))]
(:midi-note note-match))
:else (throw (IllegalArgumentException. (str "Unable to resolve note: " n ". Wasn't a recognised format (either an integer, keyword, string or nil)")))))
(defn match-note
"Returns the first midi-note formatted substring in s. If passed optional prev
and pos strings will use them to generate positive look ahead and behind
matchers. "
([s] (match-note s "" ""))
([s prev-str post-str]
(let [look-behind (if prev-str (str "(?<=" prev-str ")") "")
look-ahead (if post-str (str "(?=" post-str ")") "")
match (re-find (re-pattern (str look-behind MIDI-NOTE-RE-STR look-ahead)) s)]
(when match
(parse-note-match match)))))
;; * Each note in a scale acts as either a generator or a collector of other notes,
;; depending on their relations in time within a sequence.
;; - How can this concept be developed into parameterized sequences with knobs for
;; adjusting things like tension, dissonance, swing, genre (latin, asian, arabic...)
;; - Can we develop a symbol language or visual representation so that someone could compose
;; a piece by using mood tokens rather than specifying scales and notes directly? Basically,
;; generator functions would have to choose the scales, chords, notes and rhythm based on
;; a mix of looking up aspects of the mood, and informed randomness.
;; Use a note (:C scale) or (:Eb scale)
;; You may be interested to know that each of the seven degrees of the diatonic scale has its own name:
;;
;; 1 (do) tonic
;; 2 (re) supertonic
;; 3 (mi) mediant
;; 4 (fa) subdominant
;; 5 (sol) dominant
;; 6 (la) submediant/superdominant
;; 7 (ti) subtonic"
;; Various scale intervals in terms of steps on a piano, or midi note numbers
;; All sequences should add up to 12 - the number of semitones in an octave
(def SCALE
(let [ionian-sequence [2 2 1 2 2 2 1]
ionian-len (count ionian-sequence)
rotate-ionian (fn [offset]
(drop offset (take (+ ionian-len offset)
(cycle ionian-sequence))))]
{:diatonic ionian-sequence
:ionian (rotate-ionian 0)
:major (rotate-ionian 0)
:dorian (rotate-ionian 1)
:phrygian (rotate-ionian 2)
:lydian (rotate-ionian 3)
:mixolydian (rotate-ionian 4)
:aeolian (rotate-ionian 5)
:minor (rotate-ionian 5)
:lochrian (rotate-ionian 6)
:pentatonic [2 3 2 2 3]
:major-pentatonic [2 2 3 2 3]
:minor-pentatonic [3 2 2 3 2]
:whole-tone [2 2 2 2 2 2]
:chromatic [1 1 1 1 1 1 1 1 1 1 1 1]
:harmonic-minor [2 1 2 2 1 3 1]
:melodic-minor-asc [2 1 2 2 2 2 1]
:hungarian-minor [2 1 3 1 1 3 1]
:octatonic [2 1 2 1 2 1 2 1]
:messiaen1 [2 2 2 2 2 2]
:messiaen2 [1 2 1 2 1 2 1 2]
:messiaen3 [2 1 1 2 1 1 2 1 1]
:messiaen4 [1 1 3 1 1 1 3 1]
:messiaen5 [1 4 1 1 4 1]
:messiaen6 [2 2 1 1 2 2 1 1]
:messiaen7 [1 1 1 2 1 1 1 1 2 1]}))
(defn resolve-scale
"Either looks the scale up in the map of SCALEs if it's a keyword or simply
returns it unnmodified. Allows users to specify a scale either as a seq
such as [2 2 1 2 2 2 1] or by keyword such as :aeolian"
[scale]
(if (keyword? scale)
(SCALE scale)
scale))
(defn scale-field [skey & [sname]]
"Create the note field for a given scale. Scales are specified with a keyword
representing the key and an optional scale name (defaulting to :major):
(scale-field :g)
(scale-field :g :minor)"
(let [base (NOTES skey)
sname (or sname :major)
intervals (SCALE sname)]
(reverse (next
(reduce (fn [mem interval]
(let [new-note (+ (first mem) interval)]
(conj mem new-note)))
(list base)
(take (* 8 12) (cycle intervals)))))))
(defn nth-interval
"Return the count of semitones for the nth degree from the start of the
diatonic scale in the specific mode (or ionian/major by default).
i.e. the ionian/major scale has an interval sequence of 2 2 1 2 2 2 1
therefore the 4th degree is (+ 2 2 1 2) semitones from the start of the
scale."
([n] (nth-interval :scale n))
([scale n]
(reduce + (take n (cycle (scale SCALE))))))
(def DEGREE {:i 1
:ii 2
:iii 3
:iv 4
:v 5
:vi 6
:vii 7
:_ nil})
(defn degree->int
[degree]
(if (some #{degree} (keys DEGREE))
(degree DEGREE)
(throw (IllegalArgumentException. (str "Unable to resolve degree: " degree ". Was expecting a roman numeral in the range :i -> :vii or the nil-note symbol :_")))))
(defn resolve-degree
"returns a map representing the degree, and the octave semitone
shift (i.e. sharp flat)"
([degree] (resolve-degree degree 0 0))
([degree octave-shift semitone-shift]
(cond
(.endsWith (name degree) "-")
(resolve-degree (keyword (chop (name degree))) (dec octave-shift) semitone-shift)
(.endsWith (name degree) "+")
(resolve-degree (keyword (chop (name degree))) (inc octave-shift) semitone-shift)
(.endsWith (name degree) "b")
(resolve-degree (keyword (chop (name degree))) octave-shift (dec semitone-shift))
(.endsWith (name degree) "#")
(resolve-degree (keyword (chop (name degree))) octave-shift (inc semitone-shift))
:default
(let [degree (degree->int degree)]
{:degree degree
:octave-shift octave-shift
:semitone-shift semitone-shift}))))
(defn degree->interval
"Converts the degree of a scale given as a roman numeral keyword and converts
it to the number of intervals (semitones) from the tonic of the specified
scale.
Trailing #, b, + - represent sharps, flats, octaves up and down respectively.
An arbitrary number may be added in any order."
([degree scale]
(cond
(nil? degree) nil
(= :_ degree) nil
(number? degree) (nth-interval scale (dec degree))
(keyword? degree) (let [degree (resolve-degree degree)
interval (nth-interval scale (dec (:degree degree)))
oct-shift (* 12 (:octave-shift degree))
semi-shift (:semitone-shift degree)]
(+ interval oct-shift semi-shift)))))
(defn degrees->pitches
"Convert intervals to pitches in MIDI number format. Supports nested collections."
[degrees scale root]
(let [root (note root)]
(when (nil? root)
(throw (IllegalArgumentException. (str "root resolved to a nil value. degrees->pitches requires a non-nil root."))))
(map (fn [degree]
(cond
(coll? degree) (degrees->pitches degree scale root)
(nil? degree) nil
:default (if-let [interval (degree->interval degree scale)]
(+ root interval))))
degrees)))
(defn resolve-degrees
"Either maps the degrees to integers if they're keywords using the map DEGREE
or leaves them unmodified"
[degrees]
(map #(if (keyword? %) (DEGREE %) %) degrees))
(defn scale
"Returns a list of notes for the specified scale. The root must be in
midi note format i.e. :C4 or :Bb4
(scale :c4 :major) ; c major -> (60 62 64 65 67 69 71 72)
(scale :Bb4 :minor) ; b flat minor -> (70 72 73 75 77 78 80 82)"
([root scale-name] (scale root scale-name (range 1 8)))
([root scale-name degrees]
(let [root (note root)
degrees (resolve-degrees degrees)]
(cons root (map #(+ root (nth-interval scale-name %)) degrees)))))
(def CHORD
(let [major #{0 4 7}
minor #{0 3 7}
major7 #{0 4 7 11}
dom7 #{0 4 7 10}
minor7 #{0 3 7 10}
aug #{0 4 8}
dim #{0 3 6}
dim7 #{0 3 6 9}]
{:1 #{0}
:5 #{0 7}
:+5 #{0 4 8}
:m+5 #{0 3 8}
:sus2 #{0 2 7}
:sus4 #{0 5 7}
:6 #{0 4 7 9}
:m6 #{0 3 7 9}
:7sus2 #{0 2 7 10}
:7sus4 #{0 5 7 10}
:7-5 #{0 4 6 10}
:m7-5 #{0 3 6 10}
:7+5 #{0 4 8 10}
:m7+5 #{0 3 8 10}
:9 #{0 4 7 10 14}
:m9 #{0 3 7 10 14}
:maj9 #{0 4 7 11 14}
:9sus4 #{0 5 7 10 14}
:6*9 #{0 4 7 9 14}
:m6*9 #{0 3 9 7 14}
:7-9 #{0 4 7 10 13}
:m7-9 #{0 3 7 10 13}
:7-10 #{0 4 7 10 15}
:9+5 #{0 10 13}
:m9+5 #{0 10 14}
:7+5-9 #{0 4 8 10 13}
:m7+5-9 #{0 3 8 10 13}
:11 #{0 4 7 10 14 17}
:m11 #{0 3 7 10 14 17}
:maj11 #{0 4 7 11 14 17}
:11+ #{0 4 7 10 14 18}
:m11+ #{0 3 7 10 14 18}
:13 #{0 4 7 10 14 17 21}
:m13 #{0 3 7 10 14 17 21}
:major major
:M major
:minor minor
:m minor
:major7 major7
:dom7 dom7
:7 dom7
:M7 major7
:minor7 minor7
:m7 minor7
:augmented aug
:a aug
:diminished dim
:dim dim
:i dim
:diminished7 dim7
:dim7 dim7
:i7 dim7}))
(defn resolve-chord
"Either looks the chord up in the map of CHORDs if it's a keyword or simply
returns it unnmodified. Allows users to specify a chord either with a set
such as #{0 4 7} or by keyword such as :major"
[chord]
(if (keyword? chord)
(CHORD chord)
chord))
(defn chord
"Returns a set of notes for the specified chord. The root must be in midi note
format i.e. :C3.
(chord :c3 :major) ; c major -> #{60 64 67}
(chord :a4 :minor) ; a minor -> #{57 60 64}
(chord :Bb4 :dim) ; b flat diminished -> #{70 73 76}
"
([root chord-name]
(let [root (note root)
chord (resolve-chord chord-name)]
(set (map #(+ % root) chord)))))
(defn rand-chord
"Generates a random list of MIDI notes with cardinality num-pitches bound
within the range of the specified root and pitch-range and only containing
pitches within the specified chord-name. Similar to Impromptu's pc:make-chord"
[root chord-name num-pitches pitch-range]
(let [chord (chord root chord-name)
root (note root)
max-pitch (+ pitch-range root)
roots (range 0 max-pitch 12)
notes (flatten (map (fn [root] (map #(+ root %) chord)) roots))
notes (take-while #(<= % max-pitch) notes)]
(sort (choose-n num-pitches notes))))
; midicps
(defn midi->hz
"Convert a midi note number to a frequency in hz."
[note]
(* 440.0 (java.lang.Math/pow 2.0 (/ (- note 69.0) 12.0))))
; cpsmidi
(defn hz->midi
"Convert from a frequency to the nearest midi note number."
[freq]
(java.lang.Math/round (+ 69
(* 12
(/ (java.lang.Math/log (* freq 0.0022727272727))
(java.lang.Math/log 2))))))
; ampdb
(defn amp->db
"Convert linear amplitude to decibels."
[amp]
(* 20 (java.lang.Math/log10 amp)))
; dbamp
(defn db->amp
"Convert decibels to linear amplitude."
[db]
(java.lang.Math/exp (* (/ db 20) (java.lang.Math/log 10))))
(defn nth-octave
"Returns the freq n octaves from the supplied reference freq
i.e. (nth-ocatve 440 1) will return 880 which is the freq of the next octave
from 440."
[freq n]
(* freq (java.lang.Math/pow 2 n)))
(defn nth-equal-tempered-freq
"Returns the frequency of a given scale interval using an equal-tempered
tuning i.e. dividing all 12 semi-tones equally across an octave. This is
currently the standard tuning."
[base-freq interval]
(* base-freq (java.lang.Math/pow 2 (/ interval 12))))
(defn interval-freq
"Returns the frequency of the given interval using the specified mode and
tuning (defaulting to ionian and equal-tempered respectively)."
([base-freq n] (interval-freq base-freq n :ionian :equal-tempered))
([base-freq n mode tuning]
(case tuning
:equal-tempered (nth-equal-tempered-freq base-freq (nth-interval n mode)))))
;; * shufflers (randomize a sequence, or notes within a scale, etc.)
;; *
;;* Sequence generators
;; - probabilistic arpeggiator
;; - take a rhythym seq, note seq, and groove seq
;; - latin sounds
;; - house sounds
;; - minimal techno sounds
;; - drum and bass sounds
;;
;;* create a library of sequence modifiers and harmonizers
;;; ideas:
;;; represent all notes with midi numbers
;;; represent sequences of notes (i.e. scales) with vectors/lists
;;; represent sequences of durations with vectors/lists
;;; [1 3 5 7]
;;; represent chords with sets
;;; #{1 3 5}
;;
;;[1 3 5 #{1 4 5} 7]
;;[1 1 2 6 3]
;; chromatic notes -> 0-11
;; degrees -> i -> vii
;; chord - concrete: (60 64 67)
;; chord - concrete - chromatic notes: (4 7 12)
;; chord - abstract - chromatic notes: (0 4 7)
;; chord - abstract - chromatic notes: (0 4 7)
;; chord - abstract - degrees: (i iii v)
|
75628
|
(ns
^{:doc "Functions to help generate and manipulate frequencies and sets of related frequencies.
This is the place for functions representing general musical knowledge, like scales, chords,
intervals, etc."
:author "<NAME>, <NAME> & <NAME>"}
overtone.music.pitch
(:use [clojure.string :only [capitalize]]
[overtone.util old-contrib]
[overtone.algo chance])
(:require [clojure.string :as string]))
;; Notes in a typical scale are related by small, prime number ratios. Of all
;; possible 7 note scales, the major scale has the highest number of consonant
;; intervals.
(defn play
[s notes]
(doall (map #(s %) notes)))
(defmacro defratio [rname ratio]
`(defn ~rname [freq#] (* freq# ~ratio)))
; Perfect consonance
(defratio unison 1/1)
(defratio octave 2/1)
(defratio fifth 3/2)
; Imperfect consonance
(defratio sixth 5/3)
(defratio third 5/4)
; Dissonance
(defratio fourth 4/3)
(defratio min-third 6/5)
(defratio min-sixth 8/5)
(defn cents
"Returns a frequency computed by adding n-cents to freq. A cent is a
logarithmic measurement of pitch, where 1-octave equals 1200 cents."
[freq n-cents]
(* freq (java.lang.Math/pow 2 (/ n-cents 1200))))
;; MIDI
(def MIDI-RANGE (range 128))
(def MIDDLE-C 60)
;; Manipulating pitch using midi note numbers
(defn shift
"Shift the 'notes' in 'phrase' by a given 'amount' of half-steps."
[phrase notes amount]
(if notes
(let [note (first notes)
shifted (+ (get phrase note) amount)]
(recur (assoc phrase note shifted) (next notes) amount))
phrase))
(defn flat
"Flatten the specified notes in the phrase."
[phrase notes]
(shift phrase notes -1))
(defn sharp
"Sharpen the specified notes in the phrase."
[phrase notes]
(shift phrase notes +1))
(defn invert
"Invert a sequence of notes using either the first note as the stationary
pivot point or the optional second argument."
[notes & [pivot]]
(let [pivot (or pivot (first notes))]
(for [n notes] (- pivot (- n pivot)))))
(defn octave-note
"Convert an octave and interval to a midi note."
[octave interval]
(+ (* octave 12) interval 12))
(def NOTES {:C 0 :c 0 :b# 0 :B# 0
:C# 1 :c# 1 :Db 1 :db 1 :DB 1 :dB 1
:D 2 :d 2
:D# 3 :d# 3 :Eb 3 :eb 3 :EB 3 :eB 3
:E 4 :e 4
:E# 5 :e# 5 :F 5 :f 5
:F# 6 :f# 6 :Gb 6 :gb 6 :GB 6 :gB 6
:G 7 :g 7
:G# 8 :g# 8 :Ab 8 :ab 8 :AB 8 :aB 8
:A 9 :a 9
:A# 10 :a# 10 :Bb 10 :bb 10 :BB 10 :bB 10
:B 11 :b 11 :Cb 11 :cb 11 :CB 11 :cB 11})
(def REVERSE-NOTES
{0 :C
1 :C#
2 :D
3 :Eb
4 :E
5 :F
6 :F#
7 :G
8 :Ab
9 :A
10 :Bb
11 :B})
(defn canonical-pitch-class-name
"Returns the canonical version of the specified pitch class pc."
[pc]
(let [pc (keyword (name pc))]
(REVERSE-NOTES (NOTES pc))))
(def MIDI-NOTE-RE-STR "([a-gA-G][#bB]?)([-0-9]+)" )
(def MIDI-NOTE-RE (re-pattern MIDI-NOTE-RE-STR))
(def ONLY-MIDI-NOTE-RE (re-pattern (str "\\A" MIDI-NOTE-RE-STR "\\Z")))
(defn- parse-note-match
"Takes a match array returned by a regexp match and returns a map of note info"
[match]
(let [[match pitch-class octave] match
pitch-class (canonical-pitch-class-name pitch-class)
octave (Integer. octave)
interval (NOTES (keyword pitch-class))]
{:match match
:pitch-class pitch-class
:octave (Integer. octave)
:interval interval
:midi-note (octave-note octave interval)}))
(defn note
"Resolves note to MIDI number format. Resolves upper and lower-case keywords
and strings in MIDI note format. If given an integer or nil, returns them
unmodified. All other inputs will raise an exception.
Usage examples:
(note \"C4\") ;=> 60
(note \"C#4\") ;=> 61
(note \"eb2\") ;=> 39
(note :F#7) ;=> 102
(note :db5) ;=> 73
(note 60) ;=> 60
(note nil) ;=> nil"
[n]
(cond
(nil? n) nil
(integer? n) (if (>= n 0)
n
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Value is out of range. Lowest value is 0"))))
(keyword? n) (note (name n))
(string? n) (let [match (re-find ONLY-MIDI-NOTE-RE n)
_ (when (nil? match)
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Does not appear to be in MIDI format i.e. C#4"))))
note-match (parse-note-match match)
_ (when (< (:octave note-match) -1)
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Octave is out of range. Lowest octave value is -1"))))]
(:midi-note note-match))
:else (throw (IllegalArgumentException. (str "Unable to resolve note: " n ". Wasn't a recognised format (either an integer, keyword, string or nil)")))))
(defn match-note
"Returns the first midi-note formatted substring in s. If passed optional prev
and pos strings will use them to generate positive look ahead and behind
matchers. "
([s] (match-note s "" ""))
([s prev-str post-str]
(let [look-behind (if prev-str (str "(?<=" prev-str ")") "")
look-ahead (if post-str (str "(?=" post-str ")") "")
match (re-find (re-pattern (str look-behind MIDI-NOTE-RE-STR look-ahead)) s)]
(when match
(parse-note-match match)))))
;; * Each note in a scale acts as either a generator or a collector of other notes,
;; depending on their relations in time within a sequence.
;; - How can this concept be developed into parameterized sequences with knobs for
;; adjusting things like tension, dissonance, swing, genre (latin, asian, arabic...)
;; - Can we develop a symbol language or visual representation so that someone could compose
;; a piece by using mood tokens rather than specifying scales and notes directly? Basically,
;; generator functions would have to choose the scales, chords, notes and rhythm based on
;; a mix of looking up aspects of the mood, and informed randomness.
;; Use a note (:C scale) or (:Eb scale)
;; You may be interested to know that each of the seven degrees of the diatonic scale has its own name:
;;
;; 1 (do) tonic
;; 2 (re) supertonic
;; 3 (mi) mediant
;; 4 (fa) subdominant
;; 5 (sol) dominant
;; 6 (la) submediant/superdominant
;; 7 (ti) subtonic"
;; Various scale intervals in terms of steps on a piano, or midi note numbers
;; All sequences should add up to 12 - the number of semitones in an octave
(def SCALE
(let [ionian-sequence [2 2 1 2 2 2 1]
ionian-len (count ionian-sequence)
rotate-ionian (fn [offset]
(drop offset (take (+ ionian-len offset)
(cycle ionian-sequence))))]
{:diatonic ionian-sequence
:ionian (rotate-ionian 0)
:major (rotate-ionian 0)
:dorian (rotate-ionian 1)
:phrygian (rotate-ionian 2)
:lydian (rotate-ionian 3)
:mixolydian (rotate-ionian 4)
:aeolian (rotate-ionian 5)
:minor (rotate-ionian 5)
:lochrian (rotate-ionian 6)
:pentatonic [2 3 2 2 3]
:major-pentatonic [2 2 3 2 3]
:minor-pentatonic [3 2 2 3 2]
:whole-tone [2 2 2 2 2 2]
:chromatic [1 1 1 1 1 1 1 1 1 1 1 1]
:harmonic-minor [2 1 2 2 1 3 1]
:melodic-minor-asc [2 1 2 2 2 2 1]
:hungarian-minor [2 1 3 1 1 3 1]
:octatonic [2 1 2 1 2 1 2 1]
:messiaen1 [2 2 2 2 2 2]
:messiaen2 [1 2 1 2 1 2 1 2]
:messiaen3 [2 1 1 2 1 1 2 1 1]
:messiaen4 [1 1 3 1 1 1 3 1]
:messiaen5 [1 4 1 1 4 1]
:messiaen6 [2 2 1 1 2 2 1 1]
:messiaen7 [1 1 1 2 1 1 1 1 2 1]}))
(defn resolve-scale
"Either looks the scale up in the map of SCALEs if it's a keyword or simply
returns it unnmodified. Allows users to specify a scale either as a seq
such as [2 2 1 2 2 2 1] or by keyword such as :aeolian"
[scale]
(if (keyword? scale)
(SCALE scale)
scale))
(defn scale-field [skey & [sname]]
"Create the note field for a given scale. Scales are specified with a keyword
representing the key and an optional scale name (defaulting to :major):
(scale-field :g)
(scale-field :g :minor)"
(let [base (NOTES skey)
sname (or sname :major)
intervals (SCALE sname)]
(reverse (next
(reduce (fn [mem interval]
(let [new-note (+ (first mem) interval)]
(conj mem new-note)))
(list base)
(take (* 8 12) (cycle intervals)))))))
(defn nth-interval
"Return the count of semitones for the nth degree from the start of the
diatonic scale in the specific mode (or ionian/major by default).
i.e. the ionian/major scale has an interval sequence of 2 2 1 2 2 2 1
therefore the 4th degree is (+ 2 2 1 2) semitones from the start of the
scale."
([n] (nth-interval :scale n))
([scale n]
(reduce + (take n (cycle (scale SCALE))))))
(def DEGREE {:i 1
:ii 2
:iii 3
:iv 4
:v 5
:vi 6
:vii 7
:_ nil})
(defn degree->int
[degree]
(if (some #{degree} (keys DEGREE))
(degree DEGREE)
(throw (IllegalArgumentException. (str "Unable to resolve degree: " degree ". Was expecting a roman numeral in the range :i -> :vii or the nil-note symbol :_")))))
(defn resolve-degree
"returns a map representing the degree, and the octave semitone
shift (i.e. sharp flat)"
([degree] (resolve-degree degree 0 0))
([degree octave-shift semitone-shift]
(cond
(.endsWith (name degree) "-")
(resolve-degree (keyword (chop (name degree))) (dec octave-shift) semitone-shift)
(.endsWith (name degree) "+")
(resolve-degree (keyword (chop (name degree))) (inc octave-shift) semitone-shift)
(.endsWith (name degree) "b")
(resolve-degree (keyword (chop (name degree))) octave-shift (dec semitone-shift))
(.endsWith (name degree) "#")
(resolve-degree (keyword (chop (name degree))) octave-shift (inc semitone-shift))
:default
(let [degree (degree->int degree)]
{:degree degree
:octave-shift octave-shift
:semitone-shift semitone-shift}))))
(defn degree->interval
"Converts the degree of a scale given as a roman numeral keyword and converts
it to the number of intervals (semitones) from the tonic of the specified
scale.
Trailing #, b, + - represent sharps, flats, octaves up and down respectively.
An arbitrary number may be added in any order."
([degree scale]
(cond
(nil? degree) nil
(= :_ degree) nil
(number? degree) (nth-interval scale (dec degree))
(keyword? degree) (let [degree (resolve-degree degree)
interval (nth-interval scale (dec (:degree degree)))
oct-shift (* 12 (:octave-shift degree))
semi-shift (:semitone-shift degree)]
(+ interval oct-shift semi-shift)))))
(defn degrees->pitches
"Convert intervals to pitches in MIDI number format. Supports nested collections."
[degrees scale root]
(let [root (note root)]
(when (nil? root)
(throw (IllegalArgumentException. (str "root resolved to a nil value. degrees->pitches requires a non-nil root."))))
(map (fn [degree]
(cond
(coll? degree) (degrees->pitches degree scale root)
(nil? degree) nil
:default (if-let [interval (degree->interval degree scale)]
(+ root interval))))
degrees)))
(defn resolve-degrees
"Either maps the degrees to integers if they're keywords using the map DEGREE
or leaves them unmodified"
[degrees]
(map #(if (keyword? %) (DEGREE %) %) degrees))
(defn scale
"Returns a list of notes for the specified scale. The root must be in
midi note format i.e. :C4 or :Bb4
(scale :c4 :major) ; c major -> (60 62 64 65 67 69 71 72)
(scale :Bb4 :minor) ; b flat minor -> (70 72 73 75 77 78 80 82)"
([root scale-name] (scale root scale-name (range 1 8)))
([root scale-name degrees]
(let [root (note root)
degrees (resolve-degrees degrees)]
(cons root (map #(+ root (nth-interval scale-name %)) degrees)))))
(def CHORD
(let [major #{0 4 7}
minor #{0 3 7}
major7 #{0 4 7 11}
dom7 #{0 4 7 10}
minor7 #{0 3 7 10}
aug #{0 4 8}
dim #{0 3 6}
dim7 #{0 3 6 9}]
{:1 #{0}
:5 #{0 7}
:+5 #{0 4 8}
:m+5 #{0 3 8}
:sus2 #{0 2 7}
:sus4 #{0 5 7}
:6 #{0 4 7 9}
:m6 #{0 3 7 9}
:7sus2 #{0 2 7 10}
:7sus4 #{0 5 7 10}
:7-5 #{0 4 6 10}
:m7-5 #{0 3 6 10}
:7+5 #{0 4 8 10}
:m7+5 #{0 3 8 10}
:9 #{0 4 7 10 14}
:m9 #{0 3 7 10 14}
:maj9 #{0 4 7 11 14}
:9sus4 #{0 5 7 10 14}
:6*9 #{0 4 7 9 14}
:m6*9 #{0 3 9 7 14}
:7-9 #{0 4 7 10 13}
:m7-9 #{0 3 7 10 13}
:7-10 #{0 4 7 10 15}
:9+5 #{0 10 13}
:m9+5 #{0 10 14}
:7+5-9 #{0 4 8 10 13}
:m7+5-9 #{0 3 8 10 13}
:11 #{0 4 7 10 14 17}
:m11 #{0 3 7 10 14 17}
:maj11 #{0 4 7 11 14 17}
:11+ #{0 4 7 10 14 18}
:m11+ #{0 3 7 10 14 18}
:13 #{0 4 7 10 14 17 21}
:m13 #{0 3 7 10 14 17 21}
:major major
:M major
:minor minor
:m minor
:major7 major7
:dom7 dom7
:7 dom7
:M7 major7
:minor7 minor7
:m7 minor7
:augmented aug
:a aug
:diminished dim
:dim dim
:i dim
:diminished7 dim7
:dim7 dim7
:i7 dim7}))
(defn resolve-chord
"Either looks the chord up in the map of CHORDs if it's a keyword or simply
returns it unnmodified. Allows users to specify a chord either with a set
such as #{0 4 7} or by keyword such as :major"
[chord]
(if (keyword? chord)
(CHORD chord)
chord))
(defn chord
"Returns a set of notes for the specified chord. The root must be in midi note
format i.e. :C3.
(chord :c3 :major) ; c major -> #{60 64 67}
(chord :a4 :minor) ; a minor -> #{57 60 64}
(chord :Bb4 :dim) ; b flat diminished -> #{70 73 76}
"
([root chord-name]
(let [root (note root)
chord (resolve-chord chord-name)]
(set (map #(+ % root) chord)))))
(defn rand-chord
"Generates a random list of MIDI notes with cardinality num-pitches bound
within the range of the specified root and pitch-range and only containing
pitches within the specified chord-name. Similar to Impromptu's pc:make-chord"
[root chord-name num-pitches pitch-range]
(let [chord (chord root chord-name)
root (note root)
max-pitch (+ pitch-range root)
roots (range 0 max-pitch 12)
notes (flatten (map (fn [root] (map #(+ root %) chord)) roots))
notes (take-while #(<= % max-pitch) notes)]
(sort (choose-n num-pitches notes))))
; midicps
(defn midi->hz
"Convert a midi note number to a frequency in hz."
[note]
(* 440.0 (java.lang.Math/pow 2.0 (/ (- note 69.0) 12.0))))
; cpsmidi
(defn hz->midi
"Convert from a frequency to the nearest midi note number."
[freq]
(java.lang.Math/round (+ 69
(* 12
(/ (java.lang.Math/log (* freq 0.0022727272727))
(java.lang.Math/log 2))))))
; ampdb
(defn amp->db
"Convert linear amplitude to decibels."
[amp]
(* 20 (java.lang.Math/log10 amp)))
; dbamp
(defn db->amp
"Convert decibels to linear amplitude."
[db]
(java.lang.Math/exp (* (/ db 20) (java.lang.Math/log 10))))
(defn nth-octave
"Returns the freq n octaves from the supplied reference freq
i.e. (nth-ocatve 440 1) will return 880 which is the freq of the next octave
from 440."
[freq n]
(* freq (java.lang.Math/pow 2 n)))
(defn nth-equal-tempered-freq
"Returns the frequency of a given scale interval using an equal-tempered
tuning i.e. dividing all 12 semi-tones equally across an octave. This is
currently the standard tuning."
[base-freq interval]
(* base-freq (java.lang.Math/pow 2 (/ interval 12))))
(defn interval-freq
"Returns the frequency of the given interval using the specified mode and
tuning (defaulting to ionian and equal-tempered respectively)."
([base-freq n] (interval-freq base-freq n :ionian :equal-tempered))
([base-freq n mode tuning]
(case tuning
:equal-tempered (nth-equal-tempered-freq base-freq (nth-interval n mode)))))
;; * shufflers (randomize a sequence, or notes within a scale, etc.)
;; *
;;* Sequence generators
;; - probabilistic arpeggiator
;; - take a rhythym seq, note seq, and groove seq
;; - latin sounds
;; - house sounds
;; - minimal techno sounds
;; - drum and bass sounds
;;
;;* create a library of sequence modifiers and harmonizers
;;; ideas:
;;; represent all notes with midi numbers
;;; represent sequences of notes (i.e. scales) with vectors/lists
;;; represent sequences of durations with vectors/lists
;;; [1 3 5 7]
;;; represent chords with sets
;;; #{1 3 5}
;;
;;[1 3 5 #{1 4 5} 7]
;;[1 1 2 6 3]
;; chromatic notes -> 0-11
;; degrees -> i -> vii
;; chord - concrete: (60 64 67)
;; chord - concrete - chromatic notes: (4 7 12)
;; chord - abstract - chromatic notes: (0 4 7)
;; chord - abstract - chromatic notes: (0 4 7)
;; chord - abstract - degrees: (i iii v)
| true |
(ns
^{:doc "Functions to help generate and manipulate frequencies and sets of related frequencies.
This is the place for functions representing general musical knowledge, like scales, chords,
intervals, etc."
:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI"}
overtone.music.pitch
(:use [clojure.string :only [capitalize]]
[overtone.util old-contrib]
[overtone.algo chance])
(:require [clojure.string :as string]))
;; Notes in a typical scale are related by small, prime number ratios. Of all
;; possible 7 note scales, the major scale has the highest number of consonant
;; intervals.
(defn play
[s notes]
(doall (map #(s %) notes)))
(defmacro defratio [rname ratio]
`(defn ~rname [freq#] (* freq# ~ratio)))
; Perfect consonance
(defratio unison 1/1)
(defratio octave 2/1)
(defratio fifth 3/2)
; Imperfect consonance
(defratio sixth 5/3)
(defratio third 5/4)
; Dissonance
(defratio fourth 4/3)
(defratio min-third 6/5)
(defratio min-sixth 8/5)
(defn cents
"Returns a frequency computed by adding n-cents to freq. A cent is a
logarithmic measurement of pitch, where 1-octave equals 1200 cents."
[freq n-cents]
(* freq (java.lang.Math/pow 2 (/ n-cents 1200))))
;; MIDI
(def MIDI-RANGE (range 128))
(def MIDDLE-C 60)
;; Manipulating pitch using midi note numbers
(defn shift
"Shift the 'notes' in 'phrase' by a given 'amount' of half-steps."
[phrase notes amount]
(if notes
(let [note (first notes)
shifted (+ (get phrase note) amount)]
(recur (assoc phrase note shifted) (next notes) amount))
phrase))
(defn flat
"Flatten the specified notes in the phrase."
[phrase notes]
(shift phrase notes -1))
(defn sharp
"Sharpen the specified notes in the phrase."
[phrase notes]
(shift phrase notes +1))
(defn invert
"Invert a sequence of notes using either the first note as the stationary
pivot point or the optional second argument."
[notes & [pivot]]
(let [pivot (or pivot (first notes))]
(for [n notes] (- pivot (- n pivot)))))
(defn octave-note
"Convert an octave and interval to a midi note."
[octave interval]
(+ (* octave 12) interval 12))
(def NOTES {:C 0 :c 0 :b# 0 :B# 0
:C# 1 :c# 1 :Db 1 :db 1 :DB 1 :dB 1
:D 2 :d 2
:D# 3 :d# 3 :Eb 3 :eb 3 :EB 3 :eB 3
:E 4 :e 4
:E# 5 :e# 5 :F 5 :f 5
:F# 6 :f# 6 :Gb 6 :gb 6 :GB 6 :gB 6
:G 7 :g 7
:G# 8 :g# 8 :Ab 8 :ab 8 :AB 8 :aB 8
:A 9 :a 9
:A# 10 :a# 10 :Bb 10 :bb 10 :BB 10 :bB 10
:B 11 :b 11 :Cb 11 :cb 11 :CB 11 :cB 11})
(def REVERSE-NOTES
{0 :C
1 :C#
2 :D
3 :Eb
4 :E
5 :F
6 :F#
7 :G
8 :Ab
9 :A
10 :Bb
11 :B})
(defn canonical-pitch-class-name
"Returns the canonical version of the specified pitch class pc."
[pc]
(let [pc (keyword (name pc))]
(REVERSE-NOTES (NOTES pc))))
(def MIDI-NOTE-RE-STR "([a-gA-G][#bB]?)([-0-9]+)" )
(def MIDI-NOTE-RE (re-pattern MIDI-NOTE-RE-STR))
(def ONLY-MIDI-NOTE-RE (re-pattern (str "\\A" MIDI-NOTE-RE-STR "\\Z")))
(defn- parse-note-match
"Takes a match array returned by a regexp match and returns a map of note info"
[match]
(let [[match pitch-class octave] match
pitch-class (canonical-pitch-class-name pitch-class)
octave (Integer. octave)
interval (NOTES (keyword pitch-class))]
{:match match
:pitch-class pitch-class
:octave (Integer. octave)
:interval interval
:midi-note (octave-note octave interval)}))
(defn note
"Resolves note to MIDI number format. Resolves upper and lower-case keywords
and strings in MIDI note format. If given an integer or nil, returns them
unmodified. All other inputs will raise an exception.
Usage examples:
(note \"C4\") ;=> 60
(note \"C#4\") ;=> 61
(note \"eb2\") ;=> 39
(note :F#7) ;=> 102
(note :db5) ;=> 73
(note 60) ;=> 60
(note nil) ;=> nil"
[n]
(cond
(nil? n) nil
(integer? n) (if (>= n 0)
n
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Value is out of range. Lowest value is 0"))))
(keyword? n) (note (name n))
(string? n) (let [match (re-find ONLY-MIDI-NOTE-RE n)
_ (when (nil? match)
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Does not appear to be in MIDI format i.e. C#4"))))
note-match (parse-note-match match)
_ (when (< (:octave note-match) -1)
(throw (IllegalArgumentException.
(str "Unable to resolve note: "
n
". Octave is out of range. Lowest octave value is -1"))))]
(:midi-note note-match))
:else (throw (IllegalArgumentException. (str "Unable to resolve note: " n ". Wasn't a recognised format (either an integer, keyword, string or nil)")))))
(defn match-note
"Returns the first midi-note formatted substring in s. If passed optional prev
and pos strings will use them to generate positive look ahead and behind
matchers. "
([s] (match-note s "" ""))
([s prev-str post-str]
(let [look-behind (if prev-str (str "(?<=" prev-str ")") "")
look-ahead (if post-str (str "(?=" post-str ")") "")
match (re-find (re-pattern (str look-behind MIDI-NOTE-RE-STR look-ahead)) s)]
(when match
(parse-note-match match)))))
;; * Each note in a scale acts as either a generator or a collector of other notes,
;; depending on their relations in time within a sequence.
;; - How can this concept be developed into parameterized sequences with knobs for
;; adjusting things like tension, dissonance, swing, genre (latin, asian, arabic...)
;; - Can we develop a symbol language or visual representation so that someone could compose
;; a piece by using mood tokens rather than specifying scales and notes directly? Basically,
;; generator functions would have to choose the scales, chords, notes and rhythm based on
;; a mix of looking up aspects of the mood, and informed randomness.
;; Use a note (:C scale) or (:Eb scale)
;; You may be interested to know that each of the seven degrees of the diatonic scale has its own name:
;;
;; 1 (do) tonic
;; 2 (re) supertonic
;; 3 (mi) mediant
;; 4 (fa) subdominant
;; 5 (sol) dominant
;; 6 (la) submediant/superdominant
;; 7 (ti) subtonic"
;; Various scale intervals in terms of steps on a piano, or midi note numbers
;; All sequences should add up to 12 - the number of semitones in an octave
(def SCALE
(let [ionian-sequence [2 2 1 2 2 2 1]
ionian-len (count ionian-sequence)
rotate-ionian (fn [offset]
(drop offset (take (+ ionian-len offset)
(cycle ionian-sequence))))]
{:diatonic ionian-sequence
:ionian (rotate-ionian 0)
:major (rotate-ionian 0)
:dorian (rotate-ionian 1)
:phrygian (rotate-ionian 2)
:lydian (rotate-ionian 3)
:mixolydian (rotate-ionian 4)
:aeolian (rotate-ionian 5)
:minor (rotate-ionian 5)
:lochrian (rotate-ionian 6)
:pentatonic [2 3 2 2 3]
:major-pentatonic [2 2 3 2 3]
:minor-pentatonic [3 2 2 3 2]
:whole-tone [2 2 2 2 2 2]
:chromatic [1 1 1 1 1 1 1 1 1 1 1 1]
:harmonic-minor [2 1 2 2 1 3 1]
:melodic-minor-asc [2 1 2 2 2 2 1]
:hungarian-minor [2 1 3 1 1 3 1]
:octatonic [2 1 2 1 2 1 2 1]
:messiaen1 [2 2 2 2 2 2]
:messiaen2 [1 2 1 2 1 2 1 2]
:messiaen3 [2 1 1 2 1 1 2 1 1]
:messiaen4 [1 1 3 1 1 1 3 1]
:messiaen5 [1 4 1 1 4 1]
:messiaen6 [2 2 1 1 2 2 1 1]
:messiaen7 [1 1 1 2 1 1 1 1 2 1]}))
(defn resolve-scale
"Either looks the scale up in the map of SCALEs if it's a keyword or simply
returns it unnmodified. Allows users to specify a scale either as a seq
such as [2 2 1 2 2 2 1] or by keyword such as :aeolian"
[scale]
(if (keyword? scale)
(SCALE scale)
scale))
(defn scale-field [skey & [sname]]
"Create the note field for a given scale. Scales are specified with a keyword
representing the key and an optional scale name (defaulting to :major):
(scale-field :g)
(scale-field :g :minor)"
(let [base (NOTES skey)
sname (or sname :major)
intervals (SCALE sname)]
(reverse (next
(reduce (fn [mem interval]
(let [new-note (+ (first mem) interval)]
(conj mem new-note)))
(list base)
(take (* 8 12) (cycle intervals)))))))
(defn nth-interval
"Return the count of semitones for the nth degree from the start of the
diatonic scale in the specific mode (or ionian/major by default).
i.e. the ionian/major scale has an interval sequence of 2 2 1 2 2 2 1
therefore the 4th degree is (+ 2 2 1 2) semitones from the start of the
scale."
([n] (nth-interval :scale n))
([scale n]
(reduce + (take n (cycle (scale SCALE))))))
(def DEGREE {:i 1
:ii 2
:iii 3
:iv 4
:v 5
:vi 6
:vii 7
:_ nil})
(defn degree->int
[degree]
(if (some #{degree} (keys DEGREE))
(degree DEGREE)
(throw (IllegalArgumentException. (str "Unable to resolve degree: " degree ". Was expecting a roman numeral in the range :i -> :vii or the nil-note symbol :_")))))
(defn resolve-degree
"returns a map representing the degree, and the octave semitone
shift (i.e. sharp flat)"
([degree] (resolve-degree degree 0 0))
([degree octave-shift semitone-shift]
(cond
(.endsWith (name degree) "-")
(resolve-degree (keyword (chop (name degree))) (dec octave-shift) semitone-shift)
(.endsWith (name degree) "+")
(resolve-degree (keyword (chop (name degree))) (inc octave-shift) semitone-shift)
(.endsWith (name degree) "b")
(resolve-degree (keyword (chop (name degree))) octave-shift (dec semitone-shift))
(.endsWith (name degree) "#")
(resolve-degree (keyword (chop (name degree))) octave-shift (inc semitone-shift))
:default
(let [degree (degree->int degree)]
{:degree degree
:octave-shift octave-shift
:semitone-shift semitone-shift}))))
(defn degree->interval
"Converts the degree of a scale given as a roman numeral keyword and converts
it to the number of intervals (semitones) from the tonic of the specified
scale.
Trailing #, b, + - represent sharps, flats, octaves up and down respectively.
An arbitrary number may be added in any order."
([degree scale]
(cond
(nil? degree) nil
(= :_ degree) nil
(number? degree) (nth-interval scale (dec degree))
(keyword? degree) (let [degree (resolve-degree degree)
interval (nth-interval scale (dec (:degree degree)))
oct-shift (* 12 (:octave-shift degree))
semi-shift (:semitone-shift degree)]
(+ interval oct-shift semi-shift)))))
(defn degrees->pitches
"Convert intervals to pitches in MIDI number format. Supports nested collections."
[degrees scale root]
(let [root (note root)]
(when (nil? root)
(throw (IllegalArgumentException. (str "root resolved to a nil value. degrees->pitches requires a non-nil root."))))
(map (fn [degree]
(cond
(coll? degree) (degrees->pitches degree scale root)
(nil? degree) nil
:default (if-let [interval (degree->interval degree scale)]
(+ root interval))))
degrees)))
(defn resolve-degrees
"Either maps the degrees to integers if they're keywords using the map DEGREE
or leaves them unmodified"
[degrees]
(map #(if (keyword? %) (DEGREE %) %) degrees))
(defn scale
"Returns a list of notes for the specified scale. The root must be in
midi note format i.e. :C4 or :Bb4
(scale :c4 :major) ; c major -> (60 62 64 65 67 69 71 72)
(scale :Bb4 :minor) ; b flat minor -> (70 72 73 75 77 78 80 82)"
([root scale-name] (scale root scale-name (range 1 8)))
([root scale-name degrees]
(let [root (note root)
degrees (resolve-degrees degrees)]
(cons root (map #(+ root (nth-interval scale-name %)) degrees)))))
(def CHORD
(let [major #{0 4 7}
minor #{0 3 7}
major7 #{0 4 7 11}
dom7 #{0 4 7 10}
minor7 #{0 3 7 10}
aug #{0 4 8}
dim #{0 3 6}
dim7 #{0 3 6 9}]
{:1 #{0}
:5 #{0 7}
:+5 #{0 4 8}
:m+5 #{0 3 8}
:sus2 #{0 2 7}
:sus4 #{0 5 7}
:6 #{0 4 7 9}
:m6 #{0 3 7 9}
:7sus2 #{0 2 7 10}
:7sus4 #{0 5 7 10}
:7-5 #{0 4 6 10}
:m7-5 #{0 3 6 10}
:7+5 #{0 4 8 10}
:m7+5 #{0 3 8 10}
:9 #{0 4 7 10 14}
:m9 #{0 3 7 10 14}
:maj9 #{0 4 7 11 14}
:9sus4 #{0 5 7 10 14}
:6*9 #{0 4 7 9 14}
:m6*9 #{0 3 9 7 14}
:7-9 #{0 4 7 10 13}
:m7-9 #{0 3 7 10 13}
:7-10 #{0 4 7 10 15}
:9+5 #{0 10 13}
:m9+5 #{0 10 14}
:7+5-9 #{0 4 8 10 13}
:m7+5-9 #{0 3 8 10 13}
:11 #{0 4 7 10 14 17}
:m11 #{0 3 7 10 14 17}
:maj11 #{0 4 7 11 14 17}
:11+ #{0 4 7 10 14 18}
:m11+ #{0 3 7 10 14 18}
:13 #{0 4 7 10 14 17 21}
:m13 #{0 3 7 10 14 17 21}
:major major
:M major
:minor minor
:m minor
:major7 major7
:dom7 dom7
:7 dom7
:M7 major7
:minor7 minor7
:m7 minor7
:augmented aug
:a aug
:diminished dim
:dim dim
:i dim
:diminished7 dim7
:dim7 dim7
:i7 dim7}))
(defn resolve-chord
"Either looks the chord up in the map of CHORDs if it's a keyword or simply
returns it unnmodified. Allows users to specify a chord either with a set
such as #{0 4 7} or by keyword such as :major"
[chord]
(if (keyword? chord)
(CHORD chord)
chord))
(defn chord
"Returns a set of notes for the specified chord. The root must be in midi note
format i.e. :C3.
(chord :c3 :major) ; c major -> #{60 64 67}
(chord :a4 :minor) ; a minor -> #{57 60 64}
(chord :Bb4 :dim) ; b flat diminished -> #{70 73 76}
"
([root chord-name]
(let [root (note root)
chord (resolve-chord chord-name)]
(set (map #(+ % root) chord)))))
(defn rand-chord
"Generates a random list of MIDI notes with cardinality num-pitches bound
within the range of the specified root and pitch-range and only containing
pitches within the specified chord-name. Similar to Impromptu's pc:make-chord"
[root chord-name num-pitches pitch-range]
(let [chord (chord root chord-name)
root (note root)
max-pitch (+ pitch-range root)
roots (range 0 max-pitch 12)
notes (flatten (map (fn [root] (map #(+ root %) chord)) roots))
notes (take-while #(<= % max-pitch) notes)]
(sort (choose-n num-pitches notes))))
; midicps
(defn midi->hz
"Convert a midi note number to a frequency in hz."
[note]
(* 440.0 (java.lang.Math/pow 2.0 (/ (- note 69.0) 12.0))))
; cpsmidi
(defn hz->midi
"Convert from a frequency to the nearest midi note number."
[freq]
(java.lang.Math/round (+ 69
(* 12
(/ (java.lang.Math/log (* freq 0.0022727272727))
(java.lang.Math/log 2))))))
; ampdb
(defn amp->db
"Convert linear amplitude to decibels."
[amp]
(* 20 (java.lang.Math/log10 amp)))
; dbamp
(defn db->amp
"Convert decibels to linear amplitude."
[db]
(java.lang.Math/exp (* (/ db 20) (java.lang.Math/log 10))))
(defn nth-octave
"Returns the freq n octaves from the supplied reference freq
i.e. (nth-ocatve 440 1) will return 880 which is the freq of the next octave
from 440."
[freq n]
(* freq (java.lang.Math/pow 2 n)))
(defn nth-equal-tempered-freq
"Returns the frequency of a given scale interval using an equal-tempered
tuning i.e. dividing all 12 semi-tones equally across an octave. This is
currently the standard tuning."
[base-freq interval]
(* base-freq (java.lang.Math/pow 2 (/ interval 12))))
(defn interval-freq
"Returns the frequency of the given interval using the specified mode and
tuning (defaulting to ionian and equal-tempered respectively)."
([base-freq n] (interval-freq base-freq n :ionian :equal-tempered))
([base-freq n mode tuning]
(case tuning
:equal-tempered (nth-equal-tempered-freq base-freq (nth-interval n mode)))))
;; * shufflers (randomize a sequence, or notes within a scale, etc.)
;; *
;;* Sequence generators
;; - probabilistic arpeggiator
;; - take a rhythym seq, note seq, and groove seq
;; - latin sounds
;; - house sounds
;; - minimal techno sounds
;; - drum and bass sounds
;;
;;* create a library of sequence modifiers and harmonizers
;;; ideas:
;;; represent all notes with midi numbers
;;; represent sequences of notes (i.e. scales) with vectors/lists
;;; represent sequences of durations with vectors/lists
;;; [1 3 5 7]
;;; represent chords with sets
;;; #{1 3 5}
;;
;;[1 3 5 #{1 4 5} 7]
;;[1 1 2 6 3]
;; chromatic notes -> 0-11
;; degrees -> i -> vii
;; chord - concrete: (60 64 67)
;; chord - concrete - chromatic notes: (4 7 12)
;; chord - abstract - chromatic notes: (0 4 7)
;; chord - abstract - chromatic notes: (0 4 7)
;; chord - abstract - degrees: (i iii v)
|
[
{
"context": "ied-science.js-interop :as j]))\n\n(def token #js {:msg_mac \"6GpVqi640U22dcEhfB5C58m0oqAWXuVZr+SQ4sBoTMQ=",
"end": 211,
"score": 0.33828219771385193,
"start": 208,
"tag": "KEY",
"value": "msg"
},
{
"context": "ce.js-interop :as j]))\n\n(def token #js {:msg_mac \"6GpVqi640U22dcEhfB5C58m0oqAWXuVZr+SQ4sBoTMQ=\"\n :time_created 1468951584000 })\n\n(",
"end": 262,
"score": 0.9931080937385559,
"start": 217,
"tag": "KEY",
"value": "6GpVqi640U22dcEhfB5C58m0oqAWXuVZr+SQ4sBoTMQ=\""
}
] |
resources/public/cljs-out/dev/klipse/lang/replit.cljs
|
23trastos/REPLiCA
| 0 |
(ns klipse.lang.replit
(:require-macros
[cljs.core.async.macros :refer [go go-loop]])
(:require
[cljs.core.async :refer [chan <! >! put!]]
[applied-science.js-interop :as j]))
(def token #js {:msg_mac "6GpVqi640U22dcEhfB5C58m0oqAWXuVZr+SQ4sBoTMQ="
:time_created 1468951584000 })
(defn init-repl* [language]
(js/ReplitClient. "api.repl.it" 80 language token))
(def init-repl (memoize init-repl*))
(defn evaluate [repl c exp]
(->
(j/call repl :evaluate exp
#js {:stdout (fn [output]
(put! c output))})
(.then (fn [result]
;(js/console.log result)
(if (empty? (j/get result :error))
(put! c (str "Result: " (j/get result :data) "\n"))
(put! c (str "Error: " (j/get result :error) "\n"))))
(fn [error]
(put! c error)))))
(defn connect-and-evaluate [language exp]
(let [c (chan)
repl (init-repl language)]
(->
(j/call repl :connect)
(.then (partial evaluate repl c exp)))
c))
|
97729
|
(ns klipse.lang.replit
(:require-macros
[cljs.core.async.macros :refer [go go-loop]])
(:require
[cljs.core.async :refer [chan <! >! put!]]
[applied-science.js-interop :as j]))
(def token #js {:<KEY>_mac "<KEY>
:time_created 1468951584000 })
(defn init-repl* [language]
(js/ReplitClient. "api.repl.it" 80 language token))
(def init-repl (memoize init-repl*))
(defn evaluate [repl c exp]
(->
(j/call repl :evaluate exp
#js {:stdout (fn [output]
(put! c output))})
(.then (fn [result]
;(js/console.log result)
(if (empty? (j/get result :error))
(put! c (str "Result: " (j/get result :data) "\n"))
(put! c (str "Error: " (j/get result :error) "\n"))))
(fn [error]
(put! c error)))))
(defn connect-and-evaluate [language exp]
(let [c (chan)
repl (init-repl language)]
(->
(j/call repl :connect)
(.then (partial evaluate repl c exp)))
c))
| true |
(ns klipse.lang.replit
(:require-macros
[cljs.core.async.macros :refer [go go-loop]])
(:require
[cljs.core.async :refer [chan <! >! put!]]
[applied-science.js-interop :as j]))
(def token #js {:PI:KEY:<KEY>END_PI_mac "PI:KEY:<KEY>END_PI
:time_created 1468951584000 })
(defn init-repl* [language]
(js/ReplitClient. "api.repl.it" 80 language token))
(def init-repl (memoize init-repl*))
(defn evaluate [repl c exp]
(->
(j/call repl :evaluate exp
#js {:stdout (fn [output]
(put! c output))})
(.then (fn [result]
;(js/console.log result)
(if (empty? (j/get result :error))
(put! c (str "Result: " (j/get result :data) "\n"))
(put! c (str "Error: " (j/get result :error) "\n"))))
(fn [error]
(put! c error)))))
(defn connect-and-evaluate [language exp]
(let [c (chan)
repl (init-repl language)]
(->
(j/call repl :connect)
(.then (partial evaluate repl c exp)))
c))
|
[
{
"context": "requestTimeEpoch\" 1515290348813,\n \"accountId\" \"460417021995\",\n \"resourceId\" \"rc0f2zjkyf\",\n \"path\" \"/dev",
"end": 211,
"score": 0.9996296763420105,
"start": 199,
"tag": "KEY",
"value": "460417021995"
},
{
"context": "dentityId\" nil,\n \"user\" nil,\n \"sourceIp\" \"174.127.216.60\",\n \"accessKey\" nil,\n \"cognitoIdentityPool",
"end": 666,
"score": 0.9996528625488281,
"start": 652,
"tag": "IP_ADDRESS",
"value": "174.127.216.60"
},
{
"context": "4351e052505105af7b9850a5\",\n \"X-Forwarded-For\" \"174.127.216.60, 52.46.16.5\",\n \"X-Forwarded-Proto\" \"https\",\n ",
"end": 1395,
"score": 0.9997437596321106,
"start": 1381,
"tag": "IP_ADDRESS",
"value": "174.127.216.60"
},
{
"context": "7b9850a5\",\n \"X-Forwarded-For\" \"174.127.216.60, 52.46.16.5\",\n \"X-Forwarded-Proto\" \"https\",\n \"CloudFron",
"end": 1407,
"score": 0.9997392892837524,
"start": 1397,
"tag": "IP_ADDRESS",
"value": "52.46.16.5"
}
] |
src/demoaws/mock.clj
|
Lokeh/clojure-lambda
| 1 |
(ns demoaws.mock)
(def http-get-event
{"resource" "/",
"body" nil,
"requestContext"
{"resourcePath" "/",
"protocol" "HTTP/1.1",
"requestTimeEpoch" 1515290348813,
"accountId" "460417021995",
"resourceId" "rc0f2zjkyf",
"path" "/dev/",
"httpMethod" "GET",
"requestTime" "07/Jan/2018:01:59:08 +0000",
"requestId" "593b0bfb-f34e-11e7-a39e-4fbda38ec64e",
"apiId" "k8efdele64",
"identity"
{"userAgent" "curl/7.54.0",
"accountId" nil,
"userArn" nil,
"cognitoAuthenticationProvider" nil,
"cognitoAuthenticationType" nil,
"cognitoIdentityId" nil,
"user" nil,
"sourceIp" "174.127.216.60",
"accessKey" nil,
"cognitoIdentityPoolId" nil,
"caller" nil},
"stage" "dev"},
"path" "/",
"httpMethod" "GET",
"pathParameters" nil,
"queryStringParameters" {"foo[]" "baz"},
"stageVariables" nil,
"isBase64Encoded" false,
"headers"
{"Via"
"1.1 e93b65cf89966087a2d9723b4713fb37.cloudfront.net (CloudFront)",
"CloudFront-Is-Tablet-Viewer" "false",
"User-Agent" "curl/7.54.0",
"X-Amz-Cf-Id"
"-CplXgmc1z_v_Ui2PY1c0vQEA2TymKz0Pao9ifRpgd-a8BhhZGGaLw==",
"X-Forwarded-Port" "443",
"CloudFront-Forwarded-Proto" "https",
"CloudFront-Is-Mobile-Viewer" "false",
"X-Amzn-Trace-Id" "Root=1-5a517eec-4351e052505105af7b9850a5",
"X-Forwarded-For" "174.127.216.60, 52.46.16.5",
"X-Forwarded-Proto" "https",
"CloudFront-Is-SmartTV-Viewer" "false",
"Accept" "*/*",
"CloudFront-Is-Desktop-Viewer" "true",
"Host" "k8efdele64.execute-api.us-east-1.amazonaws.com",
"CloudFront-Viewer-Country" "US"}})
|
9967
|
(ns demoaws.mock)
(def http-get-event
{"resource" "/",
"body" nil,
"requestContext"
{"resourcePath" "/",
"protocol" "HTTP/1.1",
"requestTimeEpoch" 1515290348813,
"accountId" "<KEY>",
"resourceId" "rc0f2zjkyf",
"path" "/dev/",
"httpMethod" "GET",
"requestTime" "07/Jan/2018:01:59:08 +0000",
"requestId" "593b0bfb-f34e-11e7-a39e-4fbda38ec64e",
"apiId" "k8efdele64",
"identity"
{"userAgent" "curl/7.54.0",
"accountId" nil,
"userArn" nil,
"cognitoAuthenticationProvider" nil,
"cognitoAuthenticationType" nil,
"cognitoIdentityId" nil,
"user" nil,
"sourceIp" "192.168.3.11",
"accessKey" nil,
"cognitoIdentityPoolId" nil,
"caller" nil},
"stage" "dev"},
"path" "/",
"httpMethod" "GET",
"pathParameters" nil,
"queryStringParameters" {"foo[]" "baz"},
"stageVariables" nil,
"isBase64Encoded" false,
"headers"
{"Via"
"1.1 e93b65cf89966087a2d9723b4713fb37.cloudfront.net (CloudFront)",
"CloudFront-Is-Tablet-Viewer" "false",
"User-Agent" "curl/7.54.0",
"X-Amz-Cf-Id"
"-CplXgmc1z_v_Ui2PY1c0vQEA2TymKz0Pao9ifRpgd-a8BhhZGGaLw==",
"X-Forwarded-Port" "443",
"CloudFront-Forwarded-Proto" "https",
"CloudFront-Is-Mobile-Viewer" "false",
"X-Amzn-Trace-Id" "Root=1-5a517eec-4351e052505105af7b9850a5",
"X-Forwarded-For" "192.168.3.11, 172.16.31.10",
"X-Forwarded-Proto" "https",
"CloudFront-Is-SmartTV-Viewer" "false",
"Accept" "*/*",
"CloudFront-Is-Desktop-Viewer" "true",
"Host" "k8efdele64.execute-api.us-east-1.amazonaws.com",
"CloudFront-Viewer-Country" "US"}})
| true |
(ns demoaws.mock)
(def http-get-event
{"resource" "/",
"body" nil,
"requestContext"
{"resourcePath" "/",
"protocol" "HTTP/1.1",
"requestTimeEpoch" 1515290348813,
"accountId" "PI:KEY:<KEY>END_PI",
"resourceId" "rc0f2zjkyf",
"path" "/dev/",
"httpMethod" "GET",
"requestTime" "07/Jan/2018:01:59:08 +0000",
"requestId" "593b0bfb-f34e-11e7-a39e-4fbda38ec64e",
"apiId" "k8efdele64",
"identity"
{"userAgent" "curl/7.54.0",
"accountId" nil,
"userArn" nil,
"cognitoAuthenticationProvider" nil,
"cognitoAuthenticationType" nil,
"cognitoIdentityId" nil,
"user" nil,
"sourceIp" "PI:IP_ADDRESS:192.168.3.11END_PI",
"accessKey" nil,
"cognitoIdentityPoolId" nil,
"caller" nil},
"stage" "dev"},
"path" "/",
"httpMethod" "GET",
"pathParameters" nil,
"queryStringParameters" {"foo[]" "baz"},
"stageVariables" nil,
"isBase64Encoded" false,
"headers"
{"Via"
"1.1 e93b65cf89966087a2d9723b4713fb37.cloudfront.net (CloudFront)",
"CloudFront-Is-Tablet-Viewer" "false",
"User-Agent" "curl/7.54.0",
"X-Amz-Cf-Id"
"-CplXgmc1z_v_Ui2PY1c0vQEA2TymKz0Pao9ifRpgd-a8BhhZGGaLw==",
"X-Forwarded-Port" "443",
"CloudFront-Forwarded-Proto" "https",
"CloudFront-Is-Mobile-Viewer" "false",
"X-Amzn-Trace-Id" "Root=1-5a517eec-4351e052505105af7b9850a5",
"X-Forwarded-For" "PI:IP_ADDRESS:192.168.3.11END_PI, PI:IP_ADDRESS:172.16.31.10END_PI",
"X-Forwarded-Proto" "https",
"CloudFront-Is-SmartTV-Viewer" "false",
"Accept" "*/*",
"CloudFront-Is-Desktop-Viewer" "true",
"Host" "k8efdele64.execute-api.us-east-1.amazonaws.com",
"CloudFront-Viewer-Country" "US"}})
|
[
{
"context": "flickr.people.getPublicPhotos&format=json&api_key=6f93d9bd5fef5831ec592f0b527fdeff&user_id=9395899@N08\")\n(def github \"https://api.gi",
"end": 4214,
"score": 0.9997005462646484,
"start": 4182,
"tag": "KEY",
"value": "6f93d9bd5fef5831ec592f0b527fdeff"
},
{
"context": "y=6f93d9bd5fef5831ec592f0b527fdeff&user_id=9395899@N08\")\n(def github \"https://api.github.com/\")\n(def op",
"end": 4233,
"score": 0.7624559998512268,
"start": 4230,
"tag": "KEY",
"value": "@N0"
}
] |
cljs/mxweb/src/mxweb/example/testing.cljs
|
kennytilton/SimpleJX
| 4 |
(ns mxweb.example.testing
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [clojure.string :as str]
[cljs.core.async :refer [<!]]
[tiltontec.util.core :refer [now]]
[tiltontec.cell.core :refer-macros [cF cFonce] :refer [cI]]
[tiltontec.cell.synapse
:refer-macros [with-synapse]
:refer []]
[tiltontec.model.core
:refer-macros [with-par]
:refer [fget matrix mx-par <mget mset!> mxi-find mxu-find-name] :as md]
[mxxhr.core
:refer [make-xhr send-xhr send-unparsed-xhr xhr-send xhr-await xhr-status
xhr-status-key xhr-resolved xhr-error xhr-error? xhrfo synaptic-xhr synaptic-xhr-unparsed
xhr-selection xhr-to-map xhr-name-to-map xhr-response]]
[mxweb.gen :refer [evt-tag target-value]
:refer-macros [h1 h2 h3 h4 h5 section label header footer br
textarea p span a img ul li input div button]]
[mxweb.style
:refer [make-css-inline]
:as css]
[goog.dom :as dom]
[goog.dom.classlist :as classlist]
[goog.editor.focus :as focus]
[goog.dom.selection :as selection]
[goog.events.Event :as event]
[goog.dom.forms :as form]
[cljs-http.client :as client]
[cognitect.transit :as t]
[clojure.walk :refer [keywordize-keys]]
[cljs.pprint :as pp]))
(defn test-page-3 []
[(div {:id "xx"
:onclick #(let [me (evt-tag %)]
(when true ;; (= (:id @me) "xx")
(println :xx-click!! % (:id @me) (:clicks @me))
(mset!> me :clicks (inc (:clicks @me)))))}
{:clicks (cI 0)}
(str "Conten ?! Content rule" (<mget (mx-par me) :clicks) "|Ooops")
(span {:style (cF (make-css-inline me
:color "blue"
:background-color "red"
:padding (cF (let [c (<mget (mx-par (:tag @me)) :clicks)]
(str (* c 6) "px")))))
:hidden (cF (odd? (<mget (mx-par me) :clicks)))}
{:content (cF (str "Himom style ?! " (<mget (mx-par me) :clicks)))})
(span {:style "color:red;background-color:#eee;padding:10px"}
{:content (cF (str "Himom style string! " (<mget (mx-par me) :clicks)))})
(span {:style (cF (let [c (<mget (mx-par me) :clicks)]
{:color "blue"
:background-color "yellow"
:padding (str (* c 6) "px")}))}
{:content (cF (str "Himom style ?! " (<mget (mx-par me) :clicks)))})
(div
(input {:id "subId"
:mxweb/type "checkbox"
:value "subvalue"
:checked (cF (<mget me :subbing?))
:onclick #(let [tgt (evt-tag %)]
(.stopPropagation %)
(mset!> (evt-tag %) :subbing?
(not (<mget me :subbing?))))}
{:subbing? (cI true)})
(label {:for "subId"}
"Sub label OK?"))
(div {:class "color-input" :style "margin-top:24px"}
"Time color: "
(input {:name :timecolor
:class (cF (let [xx (fget #(= "xx" (<mget % :id)) me)]
(assert xx)
(when (even? (<mget xx :clicks))
["back-cyan" "boulder"])))
:mxweb/type "text"
:value (cI "#0ff")}))
(textarea {:cols 40 :rows 5
:wrap "hard"
:placeholder "Tell me a story"
;;:value "Four score and seven"
:autofocus true}))])
(def ae-adderall "https://api.fda.gov/drug/event.json?search=patient.drug.openfda.brand_name:adderall&limit=1")
(def flickr "https://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&format=json&api_key=6f93d9bd5fef5831ec592f0b527fdeff&user_id=9395899@N08")
(def github "https://api.github.com/")
(def openstmap "http://www.openstreetmap.org/#map=4/38.01/-95.84")
(def mdn-css "https://developer.mozilla.org/en-US/docs/Web/CSS/line-height?raw§ion=Summary")
;;;;
;(defn parse-json$
; ([j$] (parse-json$ j$ true))
; ([j$ keywordize]
; (let [r (t/reader :json)]
; ((if keywordize keywordize-keys identity)
; (t/read r j$)))))
#_(go (let [r (<! (client/get ae-adderall {:with-credentials? false}))]
(if (:success r)
(do
(prn :body (keys (:body r)) #_(keys (parse-json$ (:body r))))
(prn :success (:status r) (keys r) (count (:body r))))
(prn :NO-success :stat (:status r) :ecode (:error-code r) :etext (:error-text r)))))
(def ae-brand
"https://api.fda.gov/drug/event.json?search=patient.drug.openfda.brand_name:~a&limit=~a")
(def rx-nav-unk
"https://rxnav.nlm.nih.gov/REST/interaction/interaction.json?rxcui=341248")
(defn evt-std [e]
(.stopPropagation e)
(.upgradeDom js/componentHandler))
(defn test-page-4 []
[(h1 {:class "mdl-typography--display-2"} "Clojure NYC Meet-Up")
(p {:class "mdl-typography--display-1"} "A Night to Remember")
(div {:id "xx"
:onclick #(let [me (evt-tag %)]
(when (= (:id @me) "xx")
(println :xx-click!! % (:id @me) (:clicks @me))
(mset!> me :clicks (inc (:clicks @me)))
(evt-std %)))}
{:clicks (cI 0)
:brand "adderall"}
(do (println :running! (:id @me))
(str "Content?! Content rule" (<mget me :clicks) "|Ooops"))
(br)
(div
(button {:class "mdl-button mdl-js-button mdl-js-ripple-effect"
:onclick #(evt-std %)}
{:mdl true}
"MDL Rizing")
(br)
(let [xx (mx-par me)]
(println :id?? (:id @me))
(assert (= "xx" (:id @xx)))
(when (odd? (<mget xx :clicks))
(button {:class "mdl-button mdl-js-button mdl-js-ripple-effect"
:onclick #(evt-std %)}
{:mdl true}
"MDL Rizing Dyno"))))
(br)
(div {}
{:ae (cF (with-synapse (:github [])
(send-xhr rx-nav-unk #_ ae-adderall)))}
(p (pp/cl-format "~a adverse event" (<mget me :brand)))
(when-let [r (xhr-response (<mget me :ae))]
(str "Booya!:" r)))
#_ (div (let [ax (with-synapse (:github [])
(send-xhr ae-adderall))]
(if-let [ae (first (:results (:body (xhr-response ax))))]
[(str "Booya!! " (keys ae))
(br)(:transmissiondate ae)
(br)(str (:senderorganization (:sender ae)))
(br)(str (keys (:patient ae)))
(br)(str (dissoc (:patient ae) :drug))
(br)(let [pt (:patient ae)]
(str "Age " (:patientonsetage pt) ", gender " (:patientsex pt)))
(br)(div (for [d (take 3 (:drug (:patient ae)))]
(str (keys d))))]
"No response yet"))))])
(defn matrix-build! []
(md/make ::startwatch
:mx-dom (cFonce (md/with-par me (test-page-4)))))
(comment
[ae-count 1
brand "adderall"
top (send-xhr :brand-adv-events (cl-format nil ae-brand brand ae-count)
{:brand brand
:kids (cF (when-let [aes (:results (xhr-selection me))]
(countit :aes aes)
(the-kids
(for [ae aes]
(make ::md/family
:name :adverse-event
:ae (select-keys ae [:transmissiondate
:sender
:serious])
:patient (dissoc (:patient ae) :drug)
:kids (patient-drugs ae))))))})])
#_
(div {:style {:background-color "yellow"
:display "flex"
:min-height "96px"
:flex-direction "row"
:flex-wrap "wrap"
;;:gap "24px"
:justify-content "space-between"
}}
(map #(span {:style {:background "cyan"
:flex-basis "content"}}{}
(str % ",")) (str/split "four score and seven years ago today our forefathers brought forth on this continent" " ")))
|
91959
|
(ns mxweb.example.testing
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [clojure.string :as str]
[cljs.core.async :refer [<!]]
[tiltontec.util.core :refer [now]]
[tiltontec.cell.core :refer-macros [cF cFonce] :refer [cI]]
[tiltontec.cell.synapse
:refer-macros [with-synapse]
:refer []]
[tiltontec.model.core
:refer-macros [with-par]
:refer [fget matrix mx-par <mget mset!> mxi-find mxu-find-name] :as md]
[mxxhr.core
:refer [make-xhr send-xhr send-unparsed-xhr xhr-send xhr-await xhr-status
xhr-status-key xhr-resolved xhr-error xhr-error? xhrfo synaptic-xhr synaptic-xhr-unparsed
xhr-selection xhr-to-map xhr-name-to-map xhr-response]]
[mxweb.gen :refer [evt-tag target-value]
:refer-macros [h1 h2 h3 h4 h5 section label header footer br
textarea p span a img ul li input div button]]
[mxweb.style
:refer [make-css-inline]
:as css]
[goog.dom :as dom]
[goog.dom.classlist :as classlist]
[goog.editor.focus :as focus]
[goog.dom.selection :as selection]
[goog.events.Event :as event]
[goog.dom.forms :as form]
[cljs-http.client :as client]
[cognitect.transit :as t]
[clojure.walk :refer [keywordize-keys]]
[cljs.pprint :as pp]))
(defn test-page-3 []
[(div {:id "xx"
:onclick #(let [me (evt-tag %)]
(when true ;; (= (:id @me) "xx")
(println :xx-click!! % (:id @me) (:clicks @me))
(mset!> me :clicks (inc (:clicks @me)))))}
{:clicks (cI 0)}
(str "Conten ?! Content rule" (<mget (mx-par me) :clicks) "|Ooops")
(span {:style (cF (make-css-inline me
:color "blue"
:background-color "red"
:padding (cF (let [c (<mget (mx-par (:tag @me)) :clicks)]
(str (* c 6) "px")))))
:hidden (cF (odd? (<mget (mx-par me) :clicks)))}
{:content (cF (str "Himom style ?! " (<mget (mx-par me) :clicks)))})
(span {:style "color:red;background-color:#eee;padding:10px"}
{:content (cF (str "Himom style string! " (<mget (mx-par me) :clicks)))})
(span {:style (cF (let [c (<mget (mx-par me) :clicks)]
{:color "blue"
:background-color "yellow"
:padding (str (* c 6) "px")}))}
{:content (cF (str "Himom style ?! " (<mget (mx-par me) :clicks)))})
(div
(input {:id "subId"
:mxweb/type "checkbox"
:value "subvalue"
:checked (cF (<mget me :subbing?))
:onclick #(let [tgt (evt-tag %)]
(.stopPropagation %)
(mset!> (evt-tag %) :subbing?
(not (<mget me :subbing?))))}
{:subbing? (cI true)})
(label {:for "subId"}
"Sub label OK?"))
(div {:class "color-input" :style "margin-top:24px"}
"Time color: "
(input {:name :timecolor
:class (cF (let [xx (fget #(= "xx" (<mget % :id)) me)]
(assert xx)
(when (even? (<mget xx :clicks))
["back-cyan" "boulder"])))
:mxweb/type "text"
:value (cI "#0ff")}))
(textarea {:cols 40 :rows 5
:wrap "hard"
:placeholder "Tell me a story"
;;:value "Four score and seven"
:autofocus true}))])
(def ae-adderall "https://api.fda.gov/drug/event.json?search=patient.drug.openfda.brand_name:adderall&limit=1")
(def flickr "https://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&format=json&api_key=<KEY>&user_id=9395899<KEY>8")
(def github "https://api.github.com/")
(def openstmap "http://www.openstreetmap.org/#map=4/38.01/-95.84")
(def mdn-css "https://developer.mozilla.org/en-US/docs/Web/CSS/line-height?raw§ion=Summary")
;;;;
;(defn parse-json$
; ([j$] (parse-json$ j$ true))
; ([j$ keywordize]
; (let [r (t/reader :json)]
; ((if keywordize keywordize-keys identity)
; (t/read r j$)))))
#_(go (let [r (<! (client/get ae-adderall {:with-credentials? false}))]
(if (:success r)
(do
(prn :body (keys (:body r)) #_(keys (parse-json$ (:body r))))
(prn :success (:status r) (keys r) (count (:body r))))
(prn :NO-success :stat (:status r) :ecode (:error-code r) :etext (:error-text r)))))
(def ae-brand
"https://api.fda.gov/drug/event.json?search=patient.drug.openfda.brand_name:~a&limit=~a")
(def rx-nav-unk
"https://rxnav.nlm.nih.gov/REST/interaction/interaction.json?rxcui=341248")
(defn evt-std [e]
(.stopPropagation e)
(.upgradeDom js/componentHandler))
(defn test-page-4 []
[(h1 {:class "mdl-typography--display-2"} "Clojure NYC Meet-Up")
(p {:class "mdl-typography--display-1"} "A Night to Remember")
(div {:id "xx"
:onclick #(let [me (evt-tag %)]
(when (= (:id @me) "xx")
(println :xx-click!! % (:id @me) (:clicks @me))
(mset!> me :clicks (inc (:clicks @me)))
(evt-std %)))}
{:clicks (cI 0)
:brand "adderall"}
(do (println :running! (:id @me))
(str "Content?! Content rule" (<mget me :clicks) "|Ooops"))
(br)
(div
(button {:class "mdl-button mdl-js-button mdl-js-ripple-effect"
:onclick #(evt-std %)}
{:mdl true}
"MDL Rizing")
(br)
(let [xx (mx-par me)]
(println :id?? (:id @me))
(assert (= "xx" (:id @xx)))
(when (odd? (<mget xx :clicks))
(button {:class "mdl-button mdl-js-button mdl-js-ripple-effect"
:onclick #(evt-std %)}
{:mdl true}
"MDL Rizing Dyno"))))
(br)
(div {}
{:ae (cF (with-synapse (:github [])
(send-xhr rx-nav-unk #_ ae-adderall)))}
(p (pp/cl-format "~a adverse event" (<mget me :brand)))
(when-let [r (xhr-response (<mget me :ae))]
(str "Booya!:" r)))
#_ (div (let [ax (with-synapse (:github [])
(send-xhr ae-adderall))]
(if-let [ae (first (:results (:body (xhr-response ax))))]
[(str "Booya!! " (keys ae))
(br)(:transmissiondate ae)
(br)(str (:senderorganization (:sender ae)))
(br)(str (keys (:patient ae)))
(br)(str (dissoc (:patient ae) :drug))
(br)(let [pt (:patient ae)]
(str "Age " (:patientonsetage pt) ", gender " (:patientsex pt)))
(br)(div (for [d (take 3 (:drug (:patient ae)))]
(str (keys d))))]
"No response yet"))))])
(defn matrix-build! []
(md/make ::startwatch
:mx-dom (cFonce (md/with-par me (test-page-4)))))
(comment
[ae-count 1
brand "adderall"
top (send-xhr :brand-adv-events (cl-format nil ae-brand brand ae-count)
{:brand brand
:kids (cF (when-let [aes (:results (xhr-selection me))]
(countit :aes aes)
(the-kids
(for [ae aes]
(make ::md/family
:name :adverse-event
:ae (select-keys ae [:transmissiondate
:sender
:serious])
:patient (dissoc (:patient ae) :drug)
:kids (patient-drugs ae))))))})])
#_
(div {:style {:background-color "yellow"
:display "flex"
:min-height "96px"
:flex-direction "row"
:flex-wrap "wrap"
;;:gap "24px"
:justify-content "space-between"
}}
(map #(span {:style {:background "cyan"
:flex-basis "content"}}{}
(str % ",")) (str/split "four score and seven years ago today our forefathers brought forth on this continent" " ")))
| true |
(ns mxweb.example.testing
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [clojure.string :as str]
[cljs.core.async :refer [<!]]
[tiltontec.util.core :refer [now]]
[tiltontec.cell.core :refer-macros [cF cFonce] :refer [cI]]
[tiltontec.cell.synapse
:refer-macros [with-synapse]
:refer []]
[tiltontec.model.core
:refer-macros [with-par]
:refer [fget matrix mx-par <mget mset!> mxi-find mxu-find-name] :as md]
[mxxhr.core
:refer [make-xhr send-xhr send-unparsed-xhr xhr-send xhr-await xhr-status
xhr-status-key xhr-resolved xhr-error xhr-error? xhrfo synaptic-xhr synaptic-xhr-unparsed
xhr-selection xhr-to-map xhr-name-to-map xhr-response]]
[mxweb.gen :refer [evt-tag target-value]
:refer-macros [h1 h2 h3 h4 h5 section label header footer br
textarea p span a img ul li input div button]]
[mxweb.style
:refer [make-css-inline]
:as css]
[goog.dom :as dom]
[goog.dom.classlist :as classlist]
[goog.editor.focus :as focus]
[goog.dom.selection :as selection]
[goog.events.Event :as event]
[goog.dom.forms :as form]
[cljs-http.client :as client]
[cognitect.transit :as t]
[clojure.walk :refer [keywordize-keys]]
[cljs.pprint :as pp]))
(defn test-page-3 []
[(div {:id "xx"
:onclick #(let [me (evt-tag %)]
(when true ;; (= (:id @me) "xx")
(println :xx-click!! % (:id @me) (:clicks @me))
(mset!> me :clicks (inc (:clicks @me)))))}
{:clicks (cI 0)}
(str "Conten ?! Content rule" (<mget (mx-par me) :clicks) "|Ooops")
(span {:style (cF (make-css-inline me
:color "blue"
:background-color "red"
:padding (cF (let [c (<mget (mx-par (:tag @me)) :clicks)]
(str (* c 6) "px")))))
:hidden (cF (odd? (<mget (mx-par me) :clicks)))}
{:content (cF (str "Himom style ?! " (<mget (mx-par me) :clicks)))})
(span {:style "color:red;background-color:#eee;padding:10px"}
{:content (cF (str "Himom style string! " (<mget (mx-par me) :clicks)))})
(span {:style (cF (let [c (<mget (mx-par me) :clicks)]
{:color "blue"
:background-color "yellow"
:padding (str (* c 6) "px")}))}
{:content (cF (str "Himom style ?! " (<mget (mx-par me) :clicks)))})
(div
(input {:id "subId"
:mxweb/type "checkbox"
:value "subvalue"
:checked (cF (<mget me :subbing?))
:onclick #(let [tgt (evt-tag %)]
(.stopPropagation %)
(mset!> (evt-tag %) :subbing?
(not (<mget me :subbing?))))}
{:subbing? (cI true)})
(label {:for "subId"}
"Sub label OK?"))
(div {:class "color-input" :style "margin-top:24px"}
"Time color: "
(input {:name :timecolor
:class (cF (let [xx (fget #(= "xx" (<mget % :id)) me)]
(assert xx)
(when (even? (<mget xx :clicks))
["back-cyan" "boulder"])))
:mxweb/type "text"
:value (cI "#0ff")}))
(textarea {:cols 40 :rows 5
:wrap "hard"
:placeholder "Tell me a story"
;;:value "Four score and seven"
:autofocus true}))])
(def ae-adderall "https://api.fda.gov/drug/event.json?search=patient.drug.openfda.brand_name:adderall&limit=1")
(def flickr "https://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&format=json&api_key=PI:KEY:<KEY>END_PI&user_id=9395899PI:KEY:<KEY>END_PI8")
(def github "https://api.github.com/")
(def openstmap "http://www.openstreetmap.org/#map=4/38.01/-95.84")
(def mdn-css "https://developer.mozilla.org/en-US/docs/Web/CSS/line-height?raw§ion=Summary")
;;;;
;(defn parse-json$
; ([j$] (parse-json$ j$ true))
; ([j$ keywordize]
; (let [r (t/reader :json)]
; ((if keywordize keywordize-keys identity)
; (t/read r j$)))))
#_(go (let [r (<! (client/get ae-adderall {:with-credentials? false}))]
(if (:success r)
(do
(prn :body (keys (:body r)) #_(keys (parse-json$ (:body r))))
(prn :success (:status r) (keys r) (count (:body r))))
(prn :NO-success :stat (:status r) :ecode (:error-code r) :etext (:error-text r)))))
(def ae-brand
"https://api.fda.gov/drug/event.json?search=patient.drug.openfda.brand_name:~a&limit=~a")
(def rx-nav-unk
"https://rxnav.nlm.nih.gov/REST/interaction/interaction.json?rxcui=341248")
(defn evt-std [e]
(.stopPropagation e)
(.upgradeDom js/componentHandler))
(defn test-page-4 []
[(h1 {:class "mdl-typography--display-2"} "Clojure NYC Meet-Up")
(p {:class "mdl-typography--display-1"} "A Night to Remember")
(div {:id "xx"
:onclick #(let [me (evt-tag %)]
(when (= (:id @me) "xx")
(println :xx-click!! % (:id @me) (:clicks @me))
(mset!> me :clicks (inc (:clicks @me)))
(evt-std %)))}
{:clicks (cI 0)
:brand "adderall"}
(do (println :running! (:id @me))
(str "Content?! Content rule" (<mget me :clicks) "|Ooops"))
(br)
(div
(button {:class "mdl-button mdl-js-button mdl-js-ripple-effect"
:onclick #(evt-std %)}
{:mdl true}
"MDL Rizing")
(br)
(let [xx (mx-par me)]
(println :id?? (:id @me))
(assert (= "xx" (:id @xx)))
(when (odd? (<mget xx :clicks))
(button {:class "mdl-button mdl-js-button mdl-js-ripple-effect"
:onclick #(evt-std %)}
{:mdl true}
"MDL Rizing Dyno"))))
(br)
(div {}
{:ae (cF (with-synapse (:github [])
(send-xhr rx-nav-unk #_ ae-adderall)))}
(p (pp/cl-format "~a adverse event" (<mget me :brand)))
(when-let [r (xhr-response (<mget me :ae))]
(str "Booya!:" r)))
#_ (div (let [ax (with-synapse (:github [])
(send-xhr ae-adderall))]
(if-let [ae (first (:results (:body (xhr-response ax))))]
[(str "Booya!! " (keys ae))
(br)(:transmissiondate ae)
(br)(str (:senderorganization (:sender ae)))
(br)(str (keys (:patient ae)))
(br)(str (dissoc (:patient ae) :drug))
(br)(let [pt (:patient ae)]
(str "Age " (:patientonsetage pt) ", gender " (:patientsex pt)))
(br)(div (for [d (take 3 (:drug (:patient ae)))]
(str (keys d))))]
"No response yet"))))])
(defn matrix-build! []
(md/make ::startwatch
:mx-dom (cFonce (md/with-par me (test-page-4)))))
(comment
[ae-count 1
brand "adderall"
top (send-xhr :brand-adv-events (cl-format nil ae-brand brand ae-count)
{:brand brand
:kids (cF (when-let [aes (:results (xhr-selection me))]
(countit :aes aes)
(the-kids
(for [ae aes]
(make ::md/family
:name :adverse-event
:ae (select-keys ae [:transmissiondate
:sender
:serious])
:patient (dissoc (:patient ae) :drug)
:kids (patient-drugs ae))))))})])
#_
(div {:style {:background-color "yellow"
:display "flex"
:min-height "96px"
:flex-direction "row"
:flex-wrap "wrap"
;;:gap "24px"
:justify-content "space-between"
}}
(map #(span {:style {:background "cyan"
:flex-basis "content"}}{}
(str % ",")) (str/split "four score and seven years ago today our forefathers brought forth on this continent" " ")))
|
[
{
"context": ")\n\n\n(deftest create-user-identifier\n (let [name \"some-username\"\n user {:id (str \"user/\" name)\n ",
"end": 608,
"score": 0.8980483412742615,
"start": 595,
"tag": "USERNAME",
"value": "some-username"
},
{
"context": " (str \"user/\" name)\n :username name\n :password \"12345\"\n ",
"end": 689,
"score": 0.900813102722168,
"start": 685,
"tag": "USERNAME",
"value": "name"
},
{
"context": " :username name\n :password \"12345\"\n :emailAddress \"[email protected]\"}\n aut",
"end": 724,
"score": 0.9993385076522827,
"start": 719,
"tag": "PASSWORD",
"value": "12345"
},
{
"context": "))))\n\n\n(deftest identities-for-user\n (let [name \"some-username\"\n external-login \"some-external-login\"\n ",
"end": 1595,
"score": 0.8098716735839844,
"start": 1582,
"tag": "USERNAME",
"value": "some-username"
},
{
"context": " (str \"user/\" name)\n :username name\n :password \"12345\"\n ",
"end": 1721,
"score": 0.9661992192268372,
"start": 1717,
"tag": "USERNAME",
"value": "name"
},
{
"context": " :username name\n :password \"12345\"\n :emailAddress \"[email protected]\"}\n _ (",
"end": 1756,
"score": 0.99940425157547,
"start": 1751,
"tag": "PASSWORD",
"value": "12345"
},
{
"context": "t identities-for-user-with-instance\n (let [name \"some-username\"\n instance \"some-instance\"\n externa",
"end": 2311,
"score": 0.923943817615509,
"start": 2298,
"tag": "USERNAME",
"value": "some-username"
},
{
"context": " (str \"user/\" name)\n :username name\n :password \"12345\"\n ",
"end": 2470,
"score": 0.8186100125312805,
"start": 2466,
"tag": "USERNAME",
"value": "name"
},
{
"context": " :username name\n :password \"12345\"\n :emailAddress \"[email protected]\"}\n _ (",
"end": 2505,
"score": 0.9993898272514343,
"start": 2500,
"tag": "PASSWORD",
"value": "12345"
},
{
"context": ")\n\n\n(deftest double-user-identifier\n (let [name \"some-username\"\n name2 \"other\"\n user {:id ",
"end": 3050,
"score": 0.9598798155784607,
"start": 3037,
"tag": "USERNAME",
"value": "some-username"
},
{
"context": " (str \"user/\" name)\n :username name\n :password \"12345\"\n ",
"end": 3153,
"score": 0.7998237609863281,
"start": 3149,
"tag": "USERNAME",
"value": "name"
},
{
"context": " :username name\n :password \"12345\"\n :emailAddress \"[email protected]\"}\n use",
"end": 3188,
"score": 0.9994330406188965,
"start": 3183,
"tag": "PASSWORD",
"value": "12345"
},
{
"context": "sword \"12345\"\n :emailAddress \"[email protected]\"}\n user2 (assoc user :username name2)\n ",
"end": 3222,
"score": 0.5034446716308594,
"start": 3222,
"tag": "EMAIL",
"value": ""
},
{
"context": "dress \"[email protected]\"}\n user2 (assoc user :username name2)\n authn-method :sample-method\n exte",
"end": 3268,
"score": 0.8686992526054382,
"start": 3263,
"tag": "USERNAME",
"value": "name2"
},
{
"context": " (str \"user/\" name)\n :username name\n :password \"12345\"\n ",
"end": 3943,
"score": 0.5529213547706604,
"start": 3939,
"tag": "USERNAME",
"value": "name"
},
{
"context": " :username name\n :password \"12345\"\n :emailAddress \"[email protected]\"}\n aut",
"end": 3978,
"score": 0.9992052316665649,
"start": 3973,
"tag": "PASSWORD",
"value": "12345"
},
{
"context": "assword \"12345\"\n :emailAddress \"[email protected]\"}\n authn-method :some-method\n un",
"end": 4010,
"score": 0.73729008436203,
"start": 4010,
"tag": "EMAIL",
"value": ""
},
{
"context": "sword \"12345\"\n :emailAddress \"[email protected]\"}\n authn-method :some-method\n unsa",
"end": 4012,
"score": 0.8085149526596069,
"start": 4012,
"tag": "EMAIL",
"value": ""
}
] |
cimi/test/com/sixsq/slipstream/ssclj/resources/user/user_identifier_utils_test.clj
|
slipstream/SlipStreamServer
| 6 |
(ns com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[com.sixsq.slipstream.auth.test-helper :as th]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu]))
(use-fixtures :each ltu/with-test-server-fixture)
(deftest create-user-identifier
(let [name "some-username"
user {:id (str "user/" name)
:username name
:password "12345"
:emailAddress "[email protected]"}
authn-method :sample-method
external-login "some-external-login"
instance "some-instance"
identifier (uiu/generate-identifier authn-method external-login instance)
user-response (th/add-user-for-test! user)
user-id (-> user-response :body :resource-id)
user-identifier-response (uiu/add-user-identifier! name authn-method external-login instance)
user-identifier-id (-> user-identifier-response :body :resource-id)]
(is (= 201 (:status user-identifier-response)))
(is (= (u/md5 identifier) (-> user-identifier-id (str/split #"/") second)))
(let [resource (crud/retrieve-by-id user-identifier-id)]
(is (= identifier (:identifier resource)))
(is (= {:href user-id} (:user resource))))))
(deftest identities-for-user
(let [name "some-username"
external-login "some-external-login"
user {:id (str "user/" name)
:username name
:password "12345"
:emailAddress "[email protected]"}
_ (th/add-user-for-test! user)
authn-methods #{:some-method :other-method :third-method}]
(doseq [authn-method authn-methods]
(uiu/add-user-identifier! name authn-method external-login nil))
(let [results (uiu/find-identities-by-user (:id user))]
(is (= (count authn-methods) (count results)))
(is (= (map :identifier results) (map #(uiu/generate-identifier % external-login nil) authn-methods))))))
(deftest identities-for-user-with-instance
(let [name "some-username"
instance "some-instance"
external-login "some-external-login"
user {:id (str "user/" name)
:username name
:password "12345"
:emailAddress "[email protected]"}
_ (th/add-user-for-test! user)
authn-methods #{:some-method :other-method :third-method}]
(doseq [authn-method authn-methods]
(uiu/add-user-identifier! name authn-method external-login instance))
(let [results (uiu/find-identities-by-user (:id user))]
(is (= 1 (count results)))
(is (= (set (map :identifier results)) (set (map #(uiu/generate-identifier % external-login instance) authn-methods)))))))
(deftest double-user-identifier
(let [name "some-username"
name2 "other"
user {:id (str "user/" name)
:username name
:password "12345"
:emailAddress "[email protected]"}
user2 (assoc user :username name2)
authn-method :sample-method
external-login "some-external-login"
instance "some-instance"
_ (th/add-user-for-test! user2)
user-identifier-response (uiu/add-user-identifier! name authn-method external-login instance)
user-identifier-response2 (uiu/add-user-identifier! name2 authn-method external-login instance)]
(is (= 201 (:status user-identifier-response)))
(is (= 409 (:status user-identifier-response2)))))
(deftest find-username-by-identifier
(let [name "some-username-before-slashes/after-slash/and-more-after-second-slash"
user {:id (str "user/" name)
:username name
:password "12345"
:emailAddress "[email protected]"}
authn-method :some-method
unsanitized-external-login "120720737412@eduid_chhttps#$$**eduid_ch_idp_shibboleth!https//fed-id.nuv.la]]samlbridge%module^php_*saml/sp\\metadata}php_sixsq}saml|bridge'iqqrh4oiyshzcw9o40cvo0;pgka_"
sanitized-external-login (uiu/sanitize-login-name unsanitized-external-login)
_ (th/add-user-for-test! user)
instances #{"instance1" "instance2" "instance3"}]
;; Username should be found both sanitized and unsanitized login
(doseq [instance instances]
;; Create User identifier with a sanitized identifier
(uiu/add-user-identifier! name authn-method sanitized-external-login instance)
(is (= name (uiu/find-username-by-identifier authn-method instance sanitized-external-login)))
(is (= name (uiu/find-username-by-identifier authn-method instance unsanitized-external-login))))
;; Need some time for complete removal of the sanitized identifier
(Thread/sleep 2000)
(let [identifiers (uiu/find-identities-by-user (:id user))]
(is (= (count instances) (count identifiers)))
;; Check that eventually the stored identifier is the unsanitized one
(is (= unsanitized-external-login (->> identifiers
(map :identifier)
(map #(str/split % #":"))
(map second)
first))))))
|
80166
|
(ns com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[com.sixsq.slipstream.auth.test-helper :as th]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu]))
(use-fixtures :each ltu/with-test-server-fixture)
(deftest create-user-identifier
(let [name "some-username"
user {:id (str "user/" name)
:username name
:password "<PASSWORD>"
:emailAddress "[email protected]"}
authn-method :sample-method
external-login "some-external-login"
instance "some-instance"
identifier (uiu/generate-identifier authn-method external-login instance)
user-response (th/add-user-for-test! user)
user-id (-> user-response :body :resource-id)
user-identifier-response (uiu/add-user-identifier! name authn-method external-login instance)
user-identifier-id (-> user-identifier-response :body :resource-id)]
(is (= 201 (:status user-identifier-response)))
(is (= (u/md5 identifier) (-> user-identifier-id (str/split #"/") second)))
(let [resource (crud/retrieve-by-id user-identifier-id)]
(is (= identifier (:identifier resource)))
(is (= {:href user-id} (:user resource))))))
(deftest identities-for-user
(let [name "some-username"
external-login "some-external-login"
user {:id (str "user/" name)
:username name
:password "<PASSWORD>"
:emailAddress "[email protected]"}
_ (th/add-user-for-test! user)
authn-methods #{:some-method :other-method :third-method}]
(doseq [authn-method authn-methods]
(uiu/add-user-identifier! name authn-method external-login nil))
(let [results (uiu/find-identities-by-user (:id user))]
(is (= (count authn-methods) (count results)))
(is (= (map :identifier results) (map #(uiu/generate-identifier % external-login nil) authn-methods))))))
(deftest identities-for-user-with-instance
(let [name "some-username"
instance "some-instance"
external-login "some-external-login"
user {:id (str "user/" name)
:username name
:password "<PASSWORD>"
:emailAddress "[email protected]"}
_ (th/add-user-for-test! user)
authn-methods #{:some-method :other-method :third-method}]
(doseq [authn-method authn-methods]
(uiu/add-user-identifier! name authn-method external-login instance))
(let [results (uiu/find-identities-by-user (:id user))]
(is (= 1 (count results)))
(is (= (set (map :identifier results)) (set (map #(uiu/generate-identifier % external-login instance) authn-methods)))))))
(deftest double-user-identifier
(let [name "some-username"
name2 "other"
user {:id (str "user/" name)
:username name
:password "<PASSWORD>"
:emailAddress "a@b<EMAIL>.c"}
user2 (assoc user :username name2)
authn-method :sample-method
external-login "some-external-login"
instance "some-instance"
_ (th/add-user-for-test! user2)
user-identifier-response (uiu/add-user-identifier! name authn-method external-login instance)
user-identifier-response2 (uiu/add-user-identifier! name2 authn-method external-login instance)]
(is (= 201 (:status user-identifier-response)))
(is (= 409 (:status user-identifier-response2)))))
(deftest find-username-by-identifier
(let [name "some-username-before-slashes/after-slash/and-more-after-second-slash"
user {:id (str "user/" name)
:username name
:password "<PASSWORD>"
:emailAddress "a<EMAIL>@b<EMAIL>.c"}
authn-method :some-method
unsanitized-external-login "120720737412@eduid_chhttps#$$**eduid_ch_idp_shibboleth!https//fed-id.nuv.la]]samlbridge%module^php_*saml/sp\\metadata}php_sixsq}saml|bridge'iqqrh4oiyshzcw9o40cvo0;pgka_"
sanitized-external-login (uiu/sanitize-login-name unsanitized-external-login)
_ (th/add-user-for-test! user)
instances #{"instance1" "instance2" "instance3"}]
;; Username should be found both sanitized and unsanitized login
(doseq [instance instances]
;; Create User identifier with a sanitized identifier
(uiu/add-user-identifier! name authn-method sanitized-external-login instance)
(is (= name (uiu/find-username-by-identifier authn-method instance sanitized-external-login)))
(is (= name (uiu/find-username-by-identifier authn-method instance unsanitized-external-login))))
;; Need some time for complete removal of the sanitized identifier
(Thread/sleep 2000)
(let [identifiers (uiu/find-identities-by-user (:id user))]
(is (= (count instances) (count identifiers)))
;; Check that eventually the stored identifier is the unsanitized one
(is (= unsanitized-external-login (->> identifiers
(map :identifier)
(map #(str/split % #":"))
(map second)
first))))))
| true |
(ns com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils-test
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[com.sixsq.slipstream.auth.test-helper :as th]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu]))
(use-fixtures :each ltu/with-test-server-fixture)
(deftest create-user-identifier
(let [name "some-username"
user {:id (str "user/" name)
:username name
:password "PI:PASSWORD:<PASSWORD>END_PI"
:emailAddress "[email protected]"}
authn-method :sample-method
external-login "some-external-login"
instance "some-instance"
identifier (uiu/generate-identifier authn-method external-login instance)
user-response (th/add-user-for-test! user)
user-id (-> user-response :body :resource-id)
user-identifier-response (uiu/add-user-identifier! name authn-method external-login instance)
user-identifier-id (-> user-identifier-response :body :resource-id)]
(is (= 201 (:status user-identifier-response)))
(is (= (u/md5 identifier) (-> user-identifier-id (str/split #"/") second)))
(let [resource (crud/retrieve-by-id user-identifier-id)]
(is (= identifier (:identifier resource)))
(is (= {:href user-id} (:user resource))))))
(deftest identities-for-user
(let [name "some-username"
external-login "some-external-login"
user {:id (str "user/" name)
:username name
:password "PI:PASSWORD:<PASSWORD>END_PI"
:emailAddress "[email protected]"}
_ (th/add-user-for-test! user)
authn-methods #{:some-method :other-method :third-method}]
(doseq [authn-method authn-methods]
(uiu/add-user-identifier! name authn-method external-login nil))
(let [results (uiu/find-identities-by-user (:id user))]
(is (= (count authn-methods) (count results)))
(is (= (map :identifier results) (map #(uiu/generate-identifier % external-login nil) authn-methods))))))
(deftest identities-for-user-with-instance
(let [name "some-username"
instance "some-instance"
external-login "some-external-login"
user {:id (str "user/" name)
:username name
:password "PI:PASSWORD:<PASSWORD>END_PI"
:emailAddress "[email protected]"}
_ (th/add-user-for-test! user)
authn-methods #{:some-method :other-method :third-method}]
(doseq [authn-method authn-methods]
(uiu/add-user-identifier! name authn-method external-login instance))
(let [results (uiu/find-identities-by-user (:id user))]
(is (= 1 (count results)))
(is (= (set (map :identifier results)) (set (map #(uiu/generate-identifier % external-login instance) authn-methods)))))))
(deftest double-user-identifier
(let [name "some-username"
name2 "other"
user {:id (str "user/" name)
:username name
:password "PI:PASSWORD:<PASSWORD>END_PI"
:emailAddress "a@bPI:EMAIL:<EMAIL>END_PI.c"}
user2 (assoc user :username name2)
authn-method :sample-method
external-login "some-external-login"
instance "some-instance"
_ (th/add-user-for-test! user2)
user-identifier-response (uiu/add-user-identifier! name authn-method external-login instance)
user-identifier-response2 (uiu/add-user-identifier! name2 authn-method external-login instance)]
(is (= 201 (:status user-identifier-response)))
(is (= 409 (:status user-identifier-response2)))))
(deftest find-username-by-identifier
(let [name "some-username-before-slashes/after-slash/and-more-after-second-slash"
user {:id (str "user/" name)
:username name
:password "PI:PASSWORD:<PASSWORD>END_PI"
:emailAddress "aPI:EMAIL:<EMAIL>END_PI@bPI:EMAIL:<EMAIL>END_PI.c"}
authn-method :some-method
unsanitized-external-login "120720737412@eduid_chhttps#$$**eduid_ch_idp_shibboleth!https//fed-id.nuv.la]]samlbridge%module^php_*saml/sp\\metadata}php_sixsq}saml|bridge'iqqrh4oiyshzcw9o40cvo0;pgka_"
sanitized-external-login (uiu/sanitize-login-name unsanitized-external-login)
_ (th/add-user-for-test! user)
instances #{"instance1" "instance2" "instance3"}]
;; Username should be found both sanitized and unsanitized login
(doseq [instance instances]
;; Create User identifier with a sanitized identifier
(uiu/add-user-identifier! name authn-method sanitized-external-login instance)
(is (= name (uiu/find-username-by-identifier authn-method instance sanitized-external-login)))
(is (= name (uiu/find-username-by-identifier authn-method instance unsanitized-external-login))))
;; Need some time for complete removal of the sanitized identifier
(Thread/sleep 2000)
(let [identifiers (uiu/find-identities-by-user (:id user))]
(is (= (count instances) (count identifiers)))
;; Check that eventually the stored identifier is the unsanitized one
(is (= unsanitized-external-login (->> identifiers
(map :identifier)
(map #(str/split % #":"))
(map second)
first))))))
|
[
{
"context": "e \"isla is a person\n mary is a person\n mary f",
"end": 1254,
"score": 0.9348012804985046,
"start": 1250,
"tag": "NAME",
"value": "mary"
},
{
"context": " mary is a person\n mary friend is isla\n isl",
"end": 1302,
"score": 0.5824533104896545,
"start": 1299,
"tag": "NAME",
"value": "ary"
},
{
"context": "interpret (parse \"isla is a person\\nisla name is 'isla'\\nisla age is 1\")\n (libr",
"end": 3462,
"score": 0.9664702415466309,
"start": 3458,
"tag": "NAME",
"value": "isla"
},
{
"context": "t (:ctx result) \"isla\")\n (new-person 1 \"isla\")))))\n\n(deftest test-non-existent-slot-assignment",
"end": 3615,
"score": 0.9251380562782288,
"start": 3611,
"tag": "NAME",
"value": "isla"
},
{
"context": "ult (interpret (parse \"mary is a person\\nfriend is mary\")\n (library/get-initial-",
"end": 4513,
"score": 0.7578679323196411,
"start": 4509,
"tag": "NAME",
"value": "mary"
}
] |
test/isla/test/interpreter.clj
|
maryrosecook/islaclj
| 38 |
(ns isla.test.interpreter
(:use [isla.interpreter])
(:use [isla.parser])
(:use [isla.user])
(:require [isla.library :as library])
(:use [clojure.test])
(:use [clojure.pprint])
(:require [mrc.utils :as utils]))
(defrecord Person [age name friend items])
(def extra-types
{"person" (fn [] (new isla.test.interpreter.Person 0 "" :undefined (isla-list)))})
(defn new-person
([] (new-person 0))
([age] (new-person age ""))
([age name] (new-person age name :undefined))
([age name friend] (new-person age name friend (isla-list)))
([age name friend items]
(map->Person {:age age :name name :friend friend :items items})))
;; non-slot assignment
(deftest integer-assignment
(let [result (interpret (parse "isla is 1"))]
(is (= (get (:ctx result) "isla")
1))))
(deftest test-lookup-resolves-to-referenced-data-with-updated-value
(let [env (interpret (parse "isla is a person\nfriend is isla\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "friend"} env)
(new-person 1)))))
(deftest test-lookup-resolves-object-slot-to-object-reference-with-updated-data
(let [env (interpret (parse "isla is a person
mary is a person
mary friend is isla
isla age is 1")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "mary"} env)
(let [isla (new-person 1)]
(new-person 0 "" isla))))))
;; invocation
(deftest test-single-invoke-returns-return-value
(let [result (interpret (parse "write 2"))]
(is (= (:ret result) 2))))
(deftest test-next-expression-overwrites-ret-of-previous
(let [result (interpret (parse "write 2\nwrite 3"))]
(is (= (:ret result) 3))))
(deftest test-second-not-returning-expression-removes-ret-value-of-prev
(let [result (interpret (parse "write 2"))]
(is (= (:ret result) 2)) ;; check first would have ret val
;; run test
(let [result (interpret (parse "write 2\nage is 1"))]
(is (nil? (:ret result))))))
(deftest test-write-assigned-value
(let [result (interpret (parse "name is 'mary'\nwrite name"))]
(is (= (:ret result) "mary"))))
(deftest test-invoking-with-variable-param
(let [result (interpret (parse "age is 1\nwrite age"))]
(is (= (:ret result) 1))))
(deftest test-invoking-with-object-param
(let [result (interpret (parse "mary is a person\nmary age is 2\nwrite mary age")
(library/get-initial-env extra-types))]
(is (= (:ret result) 2))))
;; type assignment
(deftest test-type-assignment
(let [result (interpret (parse "isla is a person")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person)))))
(deftest test-type-assignment-of-a-generic-type
(let [result (interpret (parse "isla is a giraffe")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
{}))))
;; slot assignment
(deftest test-slot-assignment
(let [result (interpret (parse "isla is a person\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 1)))))
(deftest test-slot-assignment-retention-of-other-slot-values
(let [result (interpret (parse "isla is a person\nisla name is 'isla'\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 1 "isla")))))
(deftest test-non-existent-slot-assignment
(let [result (interpret (parse "isla is a person\nisla material is 'metal'")
(library/get-initial-env extra-types))]
(is (= (get-in result [:ctx "isla" :material])
"metal"))))
(deftest test-slot-type-assignment
(let [result (interpret (parse "isla is a person\nisla friend is a person")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 0 "" (new-person))))))
(deftest test-generic-slot-assignment
(let [result (interpret (parse "isla is a monkey\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
{:age 1}))))
;; assignment
(deftest test-non-canonical-assigned-obj-is-ref
(let [result (interpret (parse "mary is a person\nfriend is mary")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "friend")
{:ref "mary"}))))
;; test extract fn
(deftest test-extract-block-tag
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :tag]) :block))))
(deftest test-extract-way-deep-assignee-scalar-name
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :c 0 :c 0
:c 0 :c 0 :c 0 :c 0]) "isla"))))
(deftest test-extract-way-deep-identifier-tag
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :c 0 :c 0
:c 0 :c 0 :c 0 :tag]) :identifier))))
;; lists
(deftest test-instantiate-list
(let [env (interpret (parse "items is a list")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-unknown-scalar-list-add-causes-exception
(try
(interpret (parse "add 'sword' to items")
(library/get-initial-env extra-types))
(is false) ;; should not get called
(catch Exception e
(is (= (.getMessage e) "I do not know of a list called items.")))))
(deftest test-unknown-object-attr-list-add-causes-exception
(try
(interpret (parse "add 1 to isla items")
(library/get-initial-env extra-types))
(is false) ;; should not get called
(catch Exception e
(is (= (.getMessage e) "I do not know of a list called isla items.")))))
;; list addition
(deftest test-add-list
(let [env (interpret (parse "items is a list\nadd 'sword' to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "sword")))))
(deftest test-add-obj-to-list-works-with-ref
(let [env (interpret (parse "items is a list\nmary is a person\nadd mary to items")
(library/get-initial-env extra-types))]
(is (= (get (:ctx env) "items") (isla-list {:ref "mary"})))))
(deftest test-add-duplicate-item-string
(let [env (interpret (parse "items is a list\nadd 'sword' to items\nadd 'sword' to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "sword" "sword")))))
(deftest test-add-duplicate-item-integer
(let [env (interpret (parse "items is a list\nadd 1 to items\nadd 1 to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list 1 1)))))
(deftest test-add-duplicate-item-does-nothing-obj
(let [env (interpret (parse "mary is a person\nitems is a list
add mary to items\nadd mary to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list ((get extra-types "person")))))))
(deftest test-add-to-obj-attribute-list
(let [env (interpret (parse "isla is a person\nadd 1 to isla items")
(library/get-initial-env extra-types))]
(is (= (-> (resolve- {:ref "isla"} env) :items)
(isla-list 1)))))
;; list removal
(deftest test-remove-list
(let [env (interpret (parse "items is a list\nadd 'sword' to items\nremove 'sword' from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-remove-obj-from-list-works-with-ref
(let [env (interpret (parse "items is a list\nmary is a person
add mary to items\nremove mary from items")
(library/get-initial-env extra-types))]
(is (= (get (:ctx env) "items") (isla-list)))))
(deftest test-remove-obj-list
(let [env (interpret (parse "mary is a person\nitems is a list
add mary to items\nremove mary from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-remove-non-existent-item-does-nothing-string
(let [env (interpret (parse "items is a list\nadd 'a' to items\nremove 'b' from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "a")))))
(deftest test-remove-non-existent-item-does-nothing-integer
(let [env (interpret (parse "items is a list\nadd 1 to items\nremove 2 from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list 1)))))
(deftest test-remove-non-existent-item-does-nothing-obj
(let [env (interpret (parse "mary is a person\nmary age is 1
isla is a person\nitems is a list
add isla to items\nadd mary to items\nremove mary to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env)
(isla-list ((get extra-types "person")))))))
|
123334
|
(ns isla.test.interpreter
(:use [isla.interpreter])
(:use [isla.parser])
(:use [isla.user])
(:require [isla.library :as library])
(:use [clojure.test])
(:use [clojure.pprint])
(:require [mrc.utils :as utils]))
(defrecord Person [age name friend items])
(def extra-types
{"person" (fn [] (new isla.test.interpreter.Person 0 "" :undefined (isla-list)))})
(defn new-person
([] (new-person 0))
([age] (new-person age ""))
([age name] (new-person age name :undefined))
([age name friend] (new-person age name friend (isla-list)))
([age name friend items]
(map->Person {:age age :name name :friend friend :items items})))
;; non-slot assignment
(deftest integer-assignment
(let [result (interpret (parse "isla is 1"))]
(is (= (get (:ctx result) "isla")
1))))
(deftest test-lookup-resolves-to-referenced-data-with-updated-value
(let [env (interpret (parse "isla is a person\nfriend is isla\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "friend"} env)
(new-person 1)))))
(deftest test-lookup-resolves-object-slot-to-object-reference-with-updated-data
(let [env (interpret (parse "isla is a person
<NAME> is a person
m<NAME> friend is isla
isla age is 1")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "mary"} env)
(let [isla (new-person 1)]
(new-person 0 "" isla))))))
;; invocation
(deftest test-single-invoke-returns-return-value
(let [result (interpret (parse "write 2"))]
(is (= (:ret result) 2))))
(deftest test-next-expression-overwrites-ret-of-previous
(let [result (interpret (parse "write 2\nwrite 3"))]
(is (= (:ret result) 3))))
(deftest test-second-not-returning-expression-removes-ret-value-of-prev
(let [result (interpret (parse "write 2"))]
(is (= (:ret result) 2)) ;; check first would have ret val
;; run test
(let [result (interpret (parse "write 2\nage is 1"))]
(is (nil? (:ret result))))))
(deftest test-write-assigned-value
(let [result (interpret (parse "name is 'mary'\nwrite name"))]
(is (= (:ret result) "mary"))))
(deftest test-invoking-with-variable-param
(let [result (interpret (parse "age is 1\nwrite age"))]
(is (= (:ret result) 1))))
(deftest test-invoking-with-object-param
(let [result (interpret (parse "mary is a person\nmary age is 2\nwrite mary age")
(library/get-initial-env extra-types))]
(is (= (:ret result) 2))))
;; type assignment
(deftest test-type-assignment
(let [result (interpret (parse "isla is a person")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person)))))
(deftest test-type-assignment-of-a-generic-type
(let [result (interpret (parse "isla is a giraffe")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
{}))))
;; slot assignment
(deftest test-slot-assignment
(let [result (interpret (parse "isla is a person\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 1)))))
(deftest test-slot-assignment-retention-of-other-slot-values
(let [result (interpret (parse "isla is a person\nisla name is '<NAME>'\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 1 "<NAME>")))))
(deftest test-non-existent-slot-assignment
(let [result (interpret (parse "isla is a person\nisla material is 'metal'")
(library/get-initial-env extra-types))]
(is (= (get-in result [:ctx "isla" :material])
"metal"))))
(deftest test-slot-type-assignment
(let [result (interpret (parse "isla is a person\nisla friend is a person")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 0 "" (new-person))))))
(deftest test-generic-slot-assignment
(let [result (interpret (parse "isla is a monkey\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
{:age 1}))))
;; assignment
(deftest test-non-canonical-assigned-obj-is-ref
(let [result (interpret (parse "mary is a person\nfriend is <NAME>")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "friend")
{:ref "mary"}))))
;; test extract fn
(deftest test-extract-block-tag
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :tag]) :block))))
(deftest test-extract-way-deep-assignee-scalar-name
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :c 0 :c 0
:c 0 :c 0 :c 0 :c 0]) "isla"))))
(deftest test-extract-way-deep-identifier-tag
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :c 0 :c 0
:c 0 :c 0 :c 0 :tag]) :identifier))))
;; lists
(deftest test-instantiate-list
(let [env (interpret (parse "items is a list")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-unknown-scalar-list-add-causes-exception
(try
(interpret (parse "add 'sword' to items")
(library/get-initial-env extra-types))
(is false) ;; should not get called
(catch Exception e
(is (= (.getMessage e) "I do not know of a list called items.")))))
(deftest test-unknown-object-attr-list-add-causes-exception
(try
(interpret (parse "add 1 to isla items")
(library/get-initial-env extra-types))
(is false) ;; should not get called
(catch Exception e
(is (= (.getMessage e) "I do not know of a list called isla items.")))))
;; list addition
(deftest test-add-list
(let [env (interpret (parse "items is a list\nadd 'sword' to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "sword")))))
(deftest test-add-obj-to-list-works-with-ref
(let [env (interpret (parse "items is a list\nmary is a person\nadd mary to items")
(library/get-initial-env extra-types))]
(is (= (get (:ctx env) "items") (isla-list {:ref "mary"})))))
(deftest test-add-duplicate-item-string
(let [env (interpret (parse "items is a list\nadd 'sword' to items\nadd 'sword' to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "sword" "sword")))))
(deftest test-add-duplicate-item-integer
(let [env (interpret (parse "items is a list\nadd 1 to items\nadd 1 to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list 1 1)))))
(deftest test-add-duplicate-item-does-nothing-obj
(let [env (interpret (parse "mary is a person\nitems is a list
add mary to items\nadd mary to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list ((get extra-types "person")))))))
(deftest test-add-to-obj-attribute-list
(let [env (interpret (parse "isla is a person\nadd 1 to isla items")
(library/get-initial-env extra-types))]
(is (= (-> (resolve- {:ref "isla"} env) :items)
(isla-list 1)))))
;; list removal
(deftest test-remove-list
(let [env (interpret (parse "items is a list\nadd 'sword' to items\nremove 'sword' from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-remove-obj-from-list-works-with-ref
(let [env (interpret (parse "items is a list\nmary is a person
add mary to items\nremove mary from items")
(library/get-initial-env extra-types))]
(is (= (get (:ctx env) "items") (isla-list)))))
(deftest test-remove-obj-list
(let [env (interpret (parse "mary is a person\nitems is a list
add mary to items\nremove mary from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-remove-non-existent-item-does-nothing-string
(let [env (interpret (parse "items is a list\nadd 'a' to items\nremove 'b' from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "a")))))
(deftest test-remove-non-existent-item-does-nothing-integer
(let [env (interpret (parse "items is a list\nadd 1 to items\nremove 2 from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list 1)))))
(deftest test-remove-non-existent-item-does-nothing-obj
(let [env (interpret (parse "mary is a person\nmary age is 1
isla is a person\nitems is a list
add isla to items\nadd mary to items\nremove mary to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env)
(isla-list ((get extra-types "person")))))))
| true |
(ns isla.test.interpreter
(:use [isla.interpreter])
(:use [isla.parser])
(:use [isla.user])
(:require [isla.library :as library])
(:use [clojure.test])
(:use [clojure.pprint])
(:require [mrc.utils :as utils]))
(defrecord Person [age name friend items])
(def extra-types
{"person" (fn [] (new isla.test.interpreter.Person 0 "" :undefined (isla-list)))})
(defn new-person
([] (new-person 0))
([age] (new-person age ""))
([age name] (new-person age name :undefined))
([age name friend] (new-person age name friend (isla-list)))
([age name friend items]
(map->Person {:age age :name name :friend friend :items items})))
;; non-slot assignment
(deftest integer-assignment
(let [result (interpret (parse "isla is 1"))]
(is (= (get (:ctx result) "isla")
1))))
(deftest test-lookup-resolves-to-referenced-data-with-updated-value
(let [env (interpret (parse "isla is a person\nfriend is isla\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "friend"} env)
(new-person 1)))))
(deftest test-lookup-resolves-object-slot-to-object-reference-with-updated-data
(let [env (interpret (parse "isla is a person
PI:NAME:<NAME>END_PI is a person
mPI:NAME:<NAME>END_PI friend is isla
isla age is 1")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "mary"} env)
(let [isla (new-person 1)]
(new-person 0 "" isla))))))
;; invocation
(deftest test-single-invoke-returns-return-value
(let [result (interpret (parse "write 2"))]
(is (= (:ret result) 2))))
(deftest test-next-expression-overwrites-ret-of-previous
(let [result (interpret (parse "write 2\nwrite 3"))]
(is (= (:ret result) 3))))
(deftest test-second-not-returning-expression-removes-ret-value-of-prev
(let [result (interpret (parse "write 2"))]
(is (= (:ret result) 2)) ;; check first would have ret val
;; run test
(let [result (interpret (parse "write 2\nage is 1"))]
(is (nil? (:ret result))))))
(deftest test-write-assigned-value
(let [result (interpret (parse "name is 'mary'\nwrite name"))]
(is (= (:ret result) "mary"))))
(deftest test-invoking-with-variable-param
(let [result (interpret (parse "age is 1\nwrite age"))]
(is (= (:ret result) 1))))
(deftest test-invoking-with-object-param
(let [result (interpret (parse "mary is a person\nmary age is 2\nwrite mary age")
(library/get-initial-env extra-types))]
(is (= (:ret result) 2))))
;; type assignment
(deftest test-type-assignment
(let [result (interpret (parse "isla is a person")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person)))))
(deftest test-type-assignment-of-a-generic-type
(let [result (interpret (parse "isla is a giraffe")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
{}))))
;; slot assignment
(deftest test-slot-assignment
(let [result (interpret (parse "isla is a person\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 1)))))
(deftest test-slot-assignment-retention-of-other-slot-values
(let [result (interpret (parse "isla is a person\nisla name is 'PI:NAME:<NAME>END_PI'\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 1 "PI:NAME:<NAME>END_PI")))))
(deftest test-non-existent-slot-assignment
(let [result (interpret (parse "isla is a person\nisla material is 'metal'")
(library/get-initial-env extra-types))]
(is (= (get-in result [:ctx "isla" :material])
"metal"))))
(deftest test-slot-type-assignment
(let [result (interpret (parse "isla is a person\nisla friend is a person")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
(new-person 0 "" (new-person))))))
(deftest test-generic-slot-assignment
(let [result (interpret (parse "isla is a monkey\nisla age is 1")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "isla")
{:age 1}))))
;; assignment
(deftest test-non-canonical-assigned-obj-is-ref
(let [result (interpret (parse "mary is a person\nfriend is PI:NAME:<NAME>END_PI")
(library/get-initial-env extra-types))]
(is (= (get (:ctx result) "friend")
{:ref "mary"}))))
;; test extract fn
(deftest test-extract-block-tag
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :tag]) :block))))
(deftest test-extract-way-deep-assignee-scalar-name
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :c 0 :c 0
:c 0 :c 0 :c 0 :c 0]) "isla"))))
(deftest test-extract-way-deep-identifier-tag
(let [ast (parse "isla is a person")]
(is (= (utils/extract ast [:c 0 :c 0 :c 0
:c 0 :c 0 :c 0 :tag]) :identifier))))
;; lists
(deftest test-instantiate-list
(let [env (interpret (parse "items is a list")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-unknown-scalar-list-add-causes-exception
(try
(interpret (parse "add 'sword' to items")
(library/get-initial-env extra-types))
(is false) ;; should not get called
(catch Exception e
(is (= (.getMessage e) "I do not know of a list called items.")))))
(deftest test-unknown-object-attr-list-add-causes-exception
(try
(interpret (parse "add 1 to isla items")
(library/get-initial-env extra-types))
(is false) ;; should not get called
(catch Exception e
(is (= (.getMessage e) "I do not know of a list called isla items.")))))
;; list addition
(deftest test-add-list
(let [env (interpret (parse "items is a list\nadd 'sword' to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "sword")))))
(deftest test-add-obj-to-list-works-with-ref
(let [env (interpret (parse "items is a list\nmary is a person\nadd mary to items")
(library/get-initial-env extra-types))]
(is (= (get (:ctx env) "items") (isla-list {:ref "mary"})))))
(deftest test-add-duplicate-item-string
(let [env (interpret (parse "items is a list\nadd 'sword' to items\nadd 'sword' to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "sword" "sword")))))
(deftest test-add-duplicate-item-integer
(let [env (interpret (parse "items is a list\nadd 1 to items\nadd 1 to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list 1 1)))))
(deftest test-add-duplicate-item-does-nothing-obj
(let [env (interpret (parse "mary is a person\nitems is a list
add mary to items\nadd mary to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list ((get extra-types "person")))))))
(deftest test-add-to-obj-attribute-list
(let [env (interpret (parse "isla is a person\nadd 1 to isla items")
(library/get-initial-env extra-types))]
(is (= (-> (resolve- {:ref "isla"} env) :items)
(isla-list 1)))))
;; list removal
(deftest test-remove-list
(let [env (interpret (parse "items is a list\nadd 'sword' to items\nremove 'sword' from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-remove-obj-from-list-works-with-ref
(let [env (interpret (parse "items is a list\nmary is a person
add mary to items\nremove mary from items")
(library/get-initial-env extra-types))]
(is (= (get (:ctx env) "items") (isla-list)))))
(deftest test-remove-obj-list
(let [env (interpret (parse "mary is a person\nitems is a list
add mary to items\nremove mary from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list)))))
(deftest test-remove-non-existent-item-does-nothing-string
(let [env (interpret (parse "items is a list\nadd 'a' to items\nremove 'b' from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list "a")))))
(deftest test-remove-non-existent-item-does-nothing-integer
(let [env (interpret (parse "items is a list\nadd 1 to items\nremove 2 from items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env) (isla-list 1)))))
(deftest test-remove-non-existent-item-does-nothing-obj
(let [env (interpret (parse "mary is a person\nmary age is 1
isla is a person\nitems is a list
add isla to items\nadd mary to items\nremove mary to items")
(library/get-initial-env extra-types))]
(is (= (resolve- {:ref "items"} env)
(isla-list ((get extra-types "person")))))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998083114624023,
"start": 96,
"tag": "NAME",
"value": "Ragnar Svensson"
},
{
"context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ",
"end": 129,
"score": 0.9998250007629395,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] |
editor/src/clj/editor/pipeline/font_gen.clj
|
cmarincia/defold
| 0 |
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.pipeline.font-gen
(:require [clojure.java.io :as io]
[editor.pipeline.fontc :as fontc]
[editor.texture.engine :refer [compress-rgba-buffer]])
(:import [com.google.protobuf ByteString]
[java.nio ByteBuffer]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn- make-input-stream-resolver [resource-resolver]
(fn [resource-path]
(io/input-stream (resource-resolver resource-path))))
(defn generate [font-desc font-resource resolver]
(when font-resource
(fontc/compile-font font-desc font-resource (make-input-stream-resolver resolver))))
(defn- data-size
^long [^ByteBuffer byte-buffer]
(if (nil? byte-buffer)
0
(- (.limit byte-buffer)
(.position byte-buffer))))
(defn- concat-byte-buffers
^ByteBuffer [byte-buffers]
(let [combined-size (transduce (map data-size) + byte-buffers)
backing-array (byte-array combined-size)
combined-buffer (ByteBuffer/wrap backing-array)]
(doseq [^ByteBuffer buffer byte-buffers
:when (some? buffer)
:let [position (.position buffer)]]
(.put combined-buffer buffer) ; Mutates source buffer position.
(.position buffer position))
(.flip combined-buffer)))
(defn compress [{:keys [^long glyph-channels ^ByteString glyph-data glyphs] :as font-map}]
;; NOTE: The compression is not parallelized over multiple threads here since
;; this is currently called only during the build process, which already runs
;; build functions on several threads.
(let [uncompressed-data-source
(-> (ByteBuffer/allocateDirect (.size glyph-data))
(.put (.asReadOnlyByteBuffer glyph-data))
(.flip))
glyph-byte-buffers
(map (fn [{:keys [^long glyph-data-offset ^long glyph-data-size] :as glyph}]
(when (pos? glyph-data-size)
(let [{:keys [^int width ^int height]} (:glyph-cell-wh glyph)
glyph-data-end (+ glyph-data-offset glyph-data-size)]
(.limit uncompressed-data-source glyph-data-end)
(.position uncompressed-data-source glyph-data-offset)
(compress-rgba-buffer uncompressed-data-source width height glyph-channels))))
glyphs)
glyph-data-sizes (map data-size glyph-byte-buffers)
glyph-data-offsets (reductions + (cons 0 glyph-data-sizes))
glyph-data-byte-buffer (concat-byte-buffers glyph-byte-buffers)]
(assoc font-map
:glyph-data (ByteString/copyFrom glyph-data-byte-buffer)
:glyphs (map (fn [glyph glyph-data-offset glyph-data-size]
(assoc glyph
:glyph-data-offset glyph-data-offset
:glyph-data-size glyph-data-size))
glyphs
glyph-data-offsets
glyph-data-sizes))))
|
23492
|
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.pipeline.font-gen
(:require [clojure.java.io :as io]
[editor.pipeline.fontc :as fontc]
[editor.texture.engine :refer [compress-rgba-buffer]])
(:import [com.google.protobuf ByteString]
[java.nio ByteBuffer]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn- make-input-stream-resolver [resource-resolver]
(fn [resource-path]
(io/input-stream (resource-resolver resource-path))))
(defn generate [font-desc font-resource resolver]
(when font-resource
(fontc/compile-font font-desc font-resource (make-input-stream-resolver resolver))))
(defn- data-size
^long [^ByteBuffer byte-buffer]
(if (nil? byte-buffer)
0
(- (.limit byte-buffer)
(.position byte-buffer))))
(defn- concat-byte-buffers
^ByteBuffer [byte-buffers]
(let [combined-size (transduce (map data-size) + byte-buffers)
backing-array (byte-array combined-size)
combined-buffer (ByteBuffer/wrap backing-array)]
(doseq [^ByteBuffer buffer byte-buffers
:when (some? buffer)
:let [position (.position buffer)]]
(.put combined-buffer buffer) ; Mutates source buffer position.
(.position buffer position))
(.flip combined-buffer)))
(defn compress [{:keys [^long glyph-channels ^ByteString glyph-data glyphs] :as font-map}]
;; NOTE: The compression is not parallelized over multiple threads here since
;; this is currently called only during the build process, which already runs
;; build functions on several threads.
(let [uncompressed-data-source
(-> (ByteBuffer/allocateDirect (.size glyph-data))
(.put (.asReadOnlyByteBuffer glyph-data))
(.flip))
glyph-byte-buffers
(map (fn [{:keys [^long glyph-data-offset ^long glyph-data-size] :as glyph}]
(when (pos? glyph-data-size)
(let [{:keys [^int width ^int height]} (:glyph-cell-wh glyph)
glyph-data-end (+ glyph-data-offset glyph-data-size)]
(.limit uncompressed-data-source glyph-data-end)
(.position uncompressed-data-source glyph-data-offset)
(compress-rgba-buffer uncompressed-data-source width height glyph-channels))))
glyphs)
glyph-data-sizes (map data-size glyph-byte-buffers)
glyph-data-offsets (reductions + (cons 0 glyph-data-sizes))
glyph-data-byte-buffer (concat-byte-buffers glyph-byte-buffers)]
(assoc font-map
:glyph-data (ByteString/copyFrom glyph-data-byte-buffer)
:glyphs (map (fn [glyph glyph-data-offset glyph-data-size]
(assoc glyph
:glyph-data-offset glyph-data-offset
:glyph-data-size glyph-data-size))
glyphs
glyph-data-offsets
glyph-data-sizes))))
| true |
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.pipeline.font-gen
(:require [clojure.java.io :as io]
[editor.pipeline.fontc :as fontc]
[editor.texture.engine :refer [compress-rgba-buffer]])
(:import [com.google.protobuf ByteString]
[java.nio ByteBuffer]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn- make-input-stream-resolver [resource-resolver]
(fn [resource-path]
(io/input-stream (resource-resolver resource-path))))
(defn generate [font-desc font-resource resolver]
(when font-resource
(fontc/compile-font font-desc font-resource (make-input-stream-resolver resolver))))
(defn- data-size
^long [^ByteBuffer byte-buffer]
(if (nil? byte-buffer)
0
(- (.limit byte-buffer)
(.position byte-buffer))))
(defn- concat-byte-buffers
^ByteBuffer [byte-buffers]
(let [combined-size (transduce (map data-size) + byte-buffers)
backing-array (byte-array combined-size)
combined-buffer (ByteBuffer/wrap backing-array)]
(doseq [^ByteBuffer buffer byte-buffers
:when (some? buffer)
:let [position (.position buffer)]]
(.put combined-buffer buffer) ; Mutates source buffer position.
(.position buffer position))
(.flip combined-buffer)))
(defn compress [{:keys [^long glyph-channels ^ByteString glyph-data glyphs] :as font-map}]
;; NOTE: The compression is not parallelized over multiple threads here since
;; this is currently called only during the build process, which already runs
;; build functions on several threads.
(let [uncompressed-data-source
(-> (ByteBuffer/allocateDirect (.size glyph-data))
(.put (.asReadOnlyByteBuffer glyph-data))
(.flip))
glyph-byte-buffers
(map (fn [{:keys [^long glyph-data-offset ^long glyph-data-size] :as glyph}]
(when (pos? glyph-data-size)
(let [{:keys [^int width ^int height]} (:glyph-cell-wh glyph)
glyph-data-end (+ glyph-data-offset glyph-data-size)]
(.limit uncompressed-data-source glyph-data-end)
(.position uncompressed-data-source glyph-data-offset)
(compress-rgba-buffer uncompressed-data-source width height glyph-channels))))
glyphs)
glyph-data-sizes (map data-size glyph-byte-buffers)
glyph-data-offsets (reductions + (cons 0 glyph-data-sizes))
glyph-data-byte-buffer (concat-byte-buffers glyph-byte-buffers)]
(assoc font-map
:glyph-data (ByteString/copyFrom glyph-data-byte-buffer)
:glyphs (map (fn [glyph glyph-data-offset glyph-data-size]
(assoc glyph
:glyph-data-offset glyph-data-offset
:glyph-data-size glyph-data-size))
glyphs
glyph-data-offsets
glyph-data-sizes))))
|
[
{
"context": "fn create-user\n [session-admin & {:keys [username password email activated?]}]\n (let [validation-link (atom",
"end": 1375,
"score": 0.938799262046814,
"start": 1367,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "href\n :password password\n :username use",
"end": 1628,
"score": 0.9983779191970825,
"start": 1620,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "word\n :username username\n :email ema",
"end": 1683,
"score": 0.999575674533844,
"start": 1675,
"tag": "USERNAME",
"value": "username"
},
{
"context": " (fn [_] {:host \"[email protected]\"\n :",
"end": 1857,
"score": 0.9998857378959656,
"start": 1841,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :pass \"password\"})\n\n ;; WARNING: This is a fragi",
"end": 2097,
"score": 0.9993679523468018,
"start": 2089,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "not create session\n (let [username \"anon\"\n plaintext-password \"anon\"\n\n ",
"end": 4343,
"score": 0.9983952641487122,
"start": 4339,
"tag": "USERNAME",
"value": "anon"
},
{
"context": " \"anon\"\n plaintext-password \"anon\"\n\n valid-create {:name nam",
"end": 4380,
"score": 0.9995630383491516,
"start": 4376,
"tag": "PASSWORD",
"value": "anon"
},
{
"context": " :password plaintext-password}}\n unauthorized-create (update-in valid-",
"end": 4749,
"score": 0.9920902252197266,
"start": 4731,
"tag": "PASSWORD",
"value": "plaintext-password"
},
{
"context": " can create session\n (let [username \"user/jane\"\n plaintext-password \"JaneJane-0\"\n\n ",
"end": 5423,
"score": 0.9996505379676819,
"start": 5414,
"tag": "USERNAME",
"value": "user/jane"
},
{
"context": " \"user/jane\"\n plaintext-password \"JaneJane-0\"\n\n valid-create {:name name",
"end": 5465,
"score": 0.999477207660675,
"start": 5455,
"tag": "PASSWORD",
"value": "JaneJane-0"
},
{
"context": " :password plaintext-password}}\n\n invalid-create (assoc-in valid-c",
"end": 5828,
"score": 0.8191855549812317,
"start": 5810,
"tag": "PASSWORD",
"value": "plaintext-password"
},
{
"context": " :username username\n :passwo",
"end": 6028,
"score": 0.6278116106987,
"start": 6020,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :password plaintext-password\n :activa",
"end": 6099,
"score": 0.978518545627594,
"start": 6081,
"tag": "PASSWORD",
"value": "plaintext-password"
},
{
"context": " :email \"[email protected]\")]\n\n ; anonymous create must succeed\n (",
"end": 6225,
"score": 0.9999029040336609,
"start": 6209,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "nnot create session\n (let [username \"alex\"\n plaintext-password \"AlexAlex-0\"\n\n ",
"end": 10520,
"score": 0.9984490275382996,
"start": 10516,
"tag": "USERNAME",
"value": "alex"
},
{
"context": "me \"alex\"\n plaintext-password \"AlexAlex-0\"\n\n valid-create {:name name",
"end": 10562,
"score": 0.998516857624054,
"start": 10552,
"tag": "PASSWORD",
"value": "AlexAlex-0"
},
{
"context": "te-user session-admin\n :username username\n :password plaintext-password\n ",
"end": 11000,
"score": 0.9843013882637024,
"start": 10992,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :activated? false\n :email \"[email protected]\")\n\n ; unauthorized create must return a 403 ",
"end": 11129,
"score": 0.9999227523803711,
"start": 11113,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ce-type \"/password\")\n\n username \"user/bob\"\n plaintext-password \"BobBob-0\"\n us",
"end": 11900,
"score": 0.9995438456535339,
"start": 11892,
"tag": "USERNAME",
"value": "user/bob"
},
{
"context": " \"user/bob\"\n plaintext-password \"BobBob-0\"\n user-id (create-user session-",
"end": 11938,
"score": 0.9991376399993896,
"start": 11930,
"tag": "PASSWORD",
"value": "BobBob-0"
},
{
"context": "\n :password plaintext-password\n :activate",
"end": 12121,
"score": 0.9552769660949707,
"start": 12103,
"tag": "PASSWORD",
"value": "plaintext-password"
},
{
"context": "e\n :email \"[email protected]\")]\n\n\n ;; anon with valid activated user can cr",
"end": 12242,
"score": 0.9999176859855652,
"start": 12227,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "e [:redundant-let]}\n (let [username \"user/bob\"\n plaintext-password \"BobBob-0\"\n\n ",
"end": 12386,
"score": 0.9995564818382263,
"start": 12378,
"tag": "USERNAME",
"value": "user/bob"
},
{
"context": " \"user/bob\"\n plaintext-password \"BobBob-0\"\n\n valid-create {:template {:href ",
"end": 12426,
"score": 0.999212384223938,
"start": 12418,
"tag": "PASSWORD",
"value": "BobBob-0"
},
{
"context": " :password plaintext-password}}]\n\n ; anonymous create must succeed\n (",
"end": 12614,
"score": 0.8090852499008179,
"start": 12606,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "e-type \"/password\")\n username \"user/jack\"\n plaintext-password \"JackJack-0\"\n\n ",
"end": 21370,
"score": 0.9931394457817078,
"start": 21361,
"tag": "USERNAME",
"value": "user/jack"
},
{
"context": " \"user/jack\"\n plaintext-password \"JackJack-0\"\n\n valid-create {:template {:href ",
"end": 21412,
"score": 0.9994056224822998,
"start": 21402,
"tag": "PASSWORD",
"value": "JackJack-0"
},
{
"context": " :username username\n :passwor",
"end": 21530,
"score": 0.9938048124313354,
"start": 21522,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :password plaintext-password}}]\n (create-user session-admin\n ",
"end": 21600,
"score": 0.9992950558662415,
"start": 21582,
"tag": "PASSWORD",
"value": "plaintext-password"
},
{
"context": "te-user session-admin\n :username username\n :password plaintext-password\n ",
"end": 21674,
"score": 0.9965364933013916,
"start": 21666,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :username username\n :password plaintext-password\n :activated? true\n ",
"end": 21722,
"score": 0.9992804527282715,
"start": 21704,
"tag": "PASSWORD",
"value": "plaintext-password"
},
{
"context": " :activated? true\n :email \"[email protected]\")\n\n ; anonymous create must succeed\n (l",
"end": 21802,
"score": 0.9999216198921204,
"start": 21786,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
code/test/sixsq/nuvla/server/resources/session_password_lifecycle_test.clj
|
0xbase12/api-server
| 6 |
(ns sixsq.nuvla.server.resources.session-password-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[sixsq.nuvla.auth.utils :as auth]
[sixsq.nuvla.auth.utils.sign :as sign]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info
:refer [authn-cookie authn-info-header wrap-authn-info]]
[sixsq.nuvla.server.resources.configuration-nuvla :as config-nuvla]
[sixsq.nuvla.server.resources.email.utils :as email-utils]
[sixsq.nuvla.server.resources.group :as group]
[sixsq.nuvla.server.resources.group-template :as group-tpl]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.nuvlabox :as nuvlabox]
[sixsq.nuvla.server.resources.session :as session]
[sixsq.nuvla.server.resources.session-template :as st]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-password :as email-password]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context session/resource-type))
(defn create-user
[session-admin & {:keys [username password email activated?]}]
(let [validation-link (atom nil)
href (str user-tpl/resource-type "/" email-password/registration-method)
href-create {:template {:href href
:password password
:username username
:email email}}]
(with-redefs [email-utils/extract-smtp-cfg
(fn [_] {:host "[email protected]"
:port 465
:ssl true
:user "admin"
:pass "password"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*")
second)]
(reset! validation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [user-id (-> session-admin
(request (str p/service-context user/resource-type)
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))]
(when activated?
(is (re-matches #"^email.*successfully validated$"
(-> session-admin
(request @validation-link)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
:message))))
user-id))))
(deftest lifecycle
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-user (header session-json authn-info-header "user group/nuvla-user")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
href (str st/resource-type "/password")
template-url (str p/service-context href)
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]]
;; password session template should exist
(-> session-anon
(request template-url)
(ltu/body->edn)
(ltu/is-status 200))
;; anon without valid user can not create session
(let [username "anon"
plaintext-password "anon"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password plaintext-password}}
unauthorized-create (update-in valid-create [:template :password] (constantly "BAD"))]
; anonymous query should succeed but have no entries
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; unauthorized create must return a 403 response
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str unauthorized-create))
(ltu/body->edn)
(ltu/is-status 403))
)
;; anon with valid activated user can create session
(let [username "user/jane"
plaintext-password "JaneJane-0"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password plaintext-password}}
invalid-create (assoc-in valid-create [:template :invalid] "BAD")
jane-user-id (create-user session-admin
:username username
:password plaintext-password
:activated? true
:email "[email protected]")]
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
token (get-in resp [:response :cookies authn-cookie :value])
authn-info (if token (sign/unsign-cookie-info token) {})
uri (ltu/location resp)
abs-uri (str p/service-context uri)]
; check claims in cookie
(is (= jane-user-id (:user-id authn-info)))
(is (= #{"group/nuvla-user"
"group/nuvla-anon"
uri
jane-user-id}
(some-> authn-info
:claims
(str/split #"\s")
set)))
(is (= uri (:session authn-info)))
(is (not (nil? (:exp authn-info))))
; user should not be able to see session without session role
(-> session-user
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 403))
; anonymous query should succeed but still have no entries
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; user query should succeed but have no entries because of missing session role
(-> session-user
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; admin query should succeed, but see no sessions without the correct session role
(-> session-admin
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 0))
; user should be able to see session with session role
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group))
; check contents of session
(let [{:keys [name description tags]} (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-uri)
(ltu/body->edn)
:response
:body)]
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr)))
; user query with session role should succeed but and have one entry
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
; user with session role can delete resource
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri
:request-method :delete)
(ltu/is-unset-cookie)
(ltu/body->edn)
(ltu/is-status 200))
; create with invalid template fails
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; admin create with invalid template fails
(-> session-admin
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; anon with valid non activated user cannot create session
(let [username "alex"
plaintext-password "AlexAlex-0"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password plaintext-password}}]
(create-user session-admin
:username username
:password plaintext-password
:activated? false
:email "[email protected]")
; unauthorized create must return a 403 response
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 403)))
))
(deftest claim-account-test
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
href (str st/resource-type "/password")
username "user/bob"
plaintext-password "BobBob-0"
user-id (create-user session-admin
:username username
:password plaintext-password
:activated? true
:email "[email protected]")]
;; anon with valid activated user can create session
#_{:clj-kondo/ignore [:redundant-let]}
(let [username "user/bob"
plaintext-password "BobBob-0"
valid-create {:template {:href href
:username username
:password plaintext-password}}]
; anonymous create must succeed
(let [session-1 (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
session-1-id (ltu/body-resource-id session-1)
session-1-uri (ltu/location session-1)
sesssion-1-abs-uri (str p/service-context session-1-uri)
handler (wrap-authn-info identity)
authn-session-1 (-> {:cookies (get-in session-1 [:response :cookies])}
handler
seq
flatten)
group-identifier "alpha"
group-alpha (str group/resource-type "/" group-identifier)
group-create {:template {:href (str group-tpl/resource-type "/generic")
:group-identifier group-identifier}}
group-url (-> session-admin
(request (str p/service-context group/resource-type)
:request-method :post
:body (json/write-str group-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location-url))]
; user without additional group should not have operation claim
(-> (apply request session-json (concat [sesssion-1-abs-uri] authn-session-1))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-1-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group))
;; add user to group/alpha
(-> session-admin
(request group-url
:request-method :put
:body (json/write-str {:users [user-id]}))
(ltu/body->edn)
(ltu/is-status 200))
;; check claim operation present
(let [session-2 (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
session-2-id (ltu/body-resource-id session-2)
session-2-uri (ltu/location session-2)
session-2-abs-uri (str p/service-context session-2-uri)
authn-session-2 (-> {:cookies (get-in session-2 [:response :cookies])}
handler
seq
flatten)
claim-op-url (-> (apply request session-json (concat [session-2-abs-uri] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/get-op-url :switch-group))]
(-> (apply request session-json (concat [session-2-abs-uri] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-2-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-present :switch-group)
(ltu/is-operation-present :get-peers))
;; claiming group-beta should fail
(-> (apply request session-json
(concat [claim-op-url :body (json/write-str {:claim "group/beta"})
:request-method :post] authn-session-2))
(ltu/body->edn)
(ltu/is-status 403)
(ltu/message-matches #"Switch group cannot be done to requested group:.*"))
;; claim with old session fail because wasn't in group/alpha
(-> (apply request session-json
(concat [claim-op-url :body (json/write-str {:claim group-alpha})
:request-method :post] authn-session-1))
(ltu/body->edn)
(ltu/is-status 403))
;; claim group-alpha
(let [cookie-claim (-> (apply request session-json
(concat [claim-op-url :body (json/write-str
{:claim group-alpha})
:request-method :post] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-set-cookie)
:response
:cookies)
authn-session-claim (-> {:cookies cookie-claim}
handler
seq
flatten)]
(is (= {:active-claim group-alpha
:claims #{"group/nuvla-anon"
"group/nuvla-user"
session-2-id
group-alpha}
:groups #{"group/alpha"}
:user-id user-id}
(-> {:cookies cookie-claim}
handler
auth/current-authentication)))
(-> (apply request session-json (concat [session-2-abs-uri] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-2-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-present :switch-group))
;; try create NuvlaBox and check who is the owner
(binding [config-nuvla/*stripe-api-key* nil]
(let [nuvlabox-url (-> (apply request session-json
(concat [(str p/service-context nuvlabox/resource-type)
:body (json/write-str {})
:request-method :post] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location-url))]
(-> session-admin
(request nuvlabox-url)
(ltu/body->edn)
(ltu/is-status 200))
(-> (apply request session-json (concat [nuvlabox-url] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :owner group-alpha))))
(let [cookie-claim-back (-> (apply request session-json
(concat [claim-op-url :body (json/write-str
{:claim user-id})
:request-method :post] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-set-cookie)
:response
:cookies)]
(is (= user-id
(-> {:cookies cookie-claim-back}
handler
auth/current-authentication
:user-id))))))
))))
(deftest get-peers-test
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-user (header session-json authn-info-header "user group/nuvla-user")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")]
(let [href (str st/resource-type "/password")
username "user/jack"
plaintext-password "JackJack-0"
valid-create {:template {:href href
:username username
:password plaintext-password}}]
(create-user session-admin
:username username
:password plaintext-password
:activated? true
:email "[email protected]")
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
uri (ltu/location resp)
abs-uri (str p/service-context uri)]
; user should be able to see session with session role
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group)
(ltu/is-operation-present :get-peers))
; check contents of session
(let [get-peers-url (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-uri)
(ltu/body->edn)
(ltu/get-op-url :get-peers))]
(-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request get-peers-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
(= {})
(is "Get peers body should be empty")))))))
|
100738
|
(ns sixsq.nuvla.server.resources.session-password-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[sixsq.nuvla.auth.utils :as auth]
[sixsq.nuvla.auth.utils.sign :as sign]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info
:refer [authn-cookie authn-info-header wrap-authn-info]]
[sixsq.nuvla.server.resources.configuration-nuvla :as config-nuvla]
[sixsq.nuvla.server.resources.email.utils :as email-utils]
[sixsq.nuvla.server.resources.group :as group]
[sixsq.nuvla.server.resources.group-template :as group-tpl]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.nuvlabox :as nuvlabox]
[sixsq.nuvla.server.resources.session :as session]
[sixsq.nuvla.server.resources.session-template :as st]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-password :as email-password]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context session/resource-type))
(defn create-user
[session-admin & {:keys [username <PASSWORD> email activated?]}]
(let [validation-link (atom nil)
href (str user-tpl/resource-type "/" email-password/registration-method)
href-create {:template {:href href
:password <PASSWORD>
:username username
:email email}}]
(with-redefs [email-utils/extract-smtp-cfg
(fn [_] {:host "<EMAIL>"
:port 465
:ssl true
:user "admin"
:pass "<PASSWORD>"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*")
second)]
(reset! validation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [user-id (-> session-admin
(request (str p/service-context user/resource-type)
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))]
(when activated?
(is (re-matches #"^email.*successfully validated$"
(-> session-admin
(request @validation-link)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
:message))))
user-id))))
(deftest lifecycle
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-user (header session-json authn-info-header "user group/nuvla-user")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
href (str st/resource-type "/password")
template-url (str p/service-context href)
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]]
;; password session template should exist
(-> session-anon
(request template-url)
(ltu/body->edn)
(ltu/is-status 200))
;; anon without valid user can not create session
(let [username "anon"
plaintext-password "<PASSWORD>"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password <PASSWORD>}}
unauthorized-create (update-in valid-create [:template :password] (constantly "BAD"))]
; anonymous query should succeed but have no entries
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; unauthorized create must return a 403 response
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str unauthorized-create))
(ltu/body->edn)
(ltu/is-status 403))
)
;; anon with valid activated user can create session
(let [username "user/jane"
plaintext-password "<PASSWORD>"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password <PASSWORD>}}
invalid-create (assoc-in valid-create [:template :invalid] "BAD")
jane-user-id (create-user session-admin
:username username
:password <PASSWORD>
:activated? true
:email "<EMAIL>")]
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
token (get-in resp [:response :cookies authn-cookie :value])
authn-info (if token (sign/unsign-cookie-info token) {})
uri (ltu/location resp)
abs-uri (str p/service-context uri)]
; check claims in cookie
(is (= jane-user-id (:user-id authn-info)))
(is (= #{"group/nuvla-user"
"group/nuvla-anon"
uri
jane-user-id}
(some-> authn-info
:claims
(str/split #"\s")
set)))
(is (= uri (:session authn-info)))
(is (not (nil? (:exp authn-info))))
; user should not be able to see session without session role
(-> session-user
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 403))
; anonymous query should succeed but still have no entries
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; user query should succeed but have no entries because of missing session role
(-> session-user
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; admin query should succeed, but see no sessions without the correct session role
(-> session-admin
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 0))
; user should be able to see session with session role
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group))
; check contents of session
(let [{:keys [name description tags]} (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-uri)
(ltu/body->edn)
:response
:body)]
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr)))
; user query with session role should succeed but and have one entry
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
; user with session role can delete resource
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri
:request-method :delete)
(ltu/is-unset-cookie)
(ltu/body->edn)
(ltu/is-status 200))
; create with invalid template fails
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; admin create with invalid template fails
(-> session-admin
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; anon with valid non activated user cannot create session
(let [username "alex"
plaintext-password "<PASSWORD>"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password plaintext-password}}]
(create-user session-admin
:username username
:password plaintext-password
:activated? false
:email "<EMAIL>")
; unauthorized create must return a 403 response
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 403)))
))
(deftest claim-account-test
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
href (str st/resource-type "/password")
username "user/bob"
plaintext-password "<PASSWORD>"
user-id (create-user session-admin
:username username
:password <PASSWORD>
:activated? true
:email "<EMAIL>")]
;; anon with valid activated user can create session
#_{:clj-kondo/ignore [:redundant-let]}
(let [username "user/bob"
plaintext-password "<PASSWORD>"
valid-create {:template {:href href
:username username
:password plaintext-<PASSWORD>}}]
; anonymous create must succeed
(let [session-1 (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
session-1-id (ltu/body-resource-id session-1)
session-1-uri (ltu/location session-1)
sesssion-1-abs-uri (str p/service-context session-1-uri)
handler (wrap-authn-info identity)
authn-session-1 (-> {:cookies (get-in session-1 [:response :cookies])}
handler
seq
flatten)
group-identifier "alpha"
group-alpha (str group/resource-type "/" group-identifier)
group-create {:template {:href (str group-tpl/resource-type "/generic")
:group-identifier group-identifier}}
group-url (-> session-admin
(request (str p/service-context group/resource-type)
:request-method :post
:body (json/write-str group-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location-url))]
; user without additional group should not have operation claim
(-> (apply request session-json (concat [sesssion-1-abs-uri] authn-session-1))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-1-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group))
;; add user to group/alpha
(-> session-admin
(request group-url
:request-method :put
:body (json/write-str {:users [user-id]}))
(ltu/body->edn)
(ltu/is-status 200))
;; check claim operation present
(let [session-2 (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
session-2-id (ltu/body-resource-id session-2)
session-2-uri (ltu/location session-2)
session-2-abs-uri (str p/service-context session-2-uri)
authn-session-2 (-> {:cookies (get-in session-2 [:response :cookies])}
handler
seq
flatten)
claim-op-url (-> (apply request session-json (concat [session-2-abs-uri] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/get-op-url :switch-group))]
(-> (apply request session-json (concat [session-2-abs-uri] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-2-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-present :switch-group)
(ltu/is-operation-present :get-peers))
;; claiming group-beta should fail
(-> (apply request session-json
(concat [claim-op-url :body (json/write-str {:claim "group/beta"})
:request-method :post] authn-session-2))
(ltu/body->edn)
(ltu/is-status 403)
(ltu/message-matches #"Switch group cannot be done to requested group:.*"))
;; claim with old session fail because wasn't in group/alpha
(-> (apply request session-json
(concat [claim-op-url :body (json/write-str {:claim group-alpha})
:request-method :post] authn-session-1))
(ltu/body->edn)
(ltu/is-status 403))
;; claim group-alpha
(let [cookie-claim (-> (apply request session-json
(concat [claim-op-url :body (json/write-str
{:claim group-alpha})
:request-method :post] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-set-cookie)
:response
:cookies)
authn-session-claim (-> {:cookies cookie-claim}
handler
seq
flatten)]
(is (= {:active-claim group-alpha
:claims #{"group/nuvla-anon"
"group/nuvla-user"
session-2-id
group-alpha}
:groups #{"group/alpha"}
:user-id user-id}
(-> {:cookies cookie-claim}
handler
auth/current-authentication)))
(-> (apply request session-json (concat [session-2-abs-uri] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-2-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-present :switch-group))
;; try create NuvlaBox and check who is the owner
(binding [config-nuvla/*stripe-api-key* nil]
(let [nuvlabox-url (-> (apply request session-json
(concat [(str p/service-context nuvlabox/resource-type)
:body (json/write-str {})
:request-method :post] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location-url))]
(-> session-admin
(request nuvlabox-url)
(ltu/body->edn)
(ltu/is-status 200))
(-> (apply request session-json (concat [nuvlabox-url] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :owner group-alpha))))
(let [cookie-claim-back (-> (apply request session-json
(concat [claim-op-url :body (json/write-str
{:claim user-id})
:request-method :post] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-set-cookie)
:response
:cookies)]
(is (= user-id
(-> {:cookies cookie-claim-back}
handler
auth/current-authentication
:user-id))))))
))))
(deftest get-peers-test
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-user (header session-json authn-info-header "user group/nuvla-user")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")]
(let [href (str st/resource-type "/password")
username "user/jack"
plaintext-password "<PASSWORD>"
valid-create {:template {:href href
:username username
:password <PASSWORD>}}]
(create-user session-admin
:username username
:password <PASSWORD>
:activated? true
:email "<EMAIL>")
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
uri (ltu/location resp)
abs-uri (str p/service-context uri)]
; user should be able to see session with session role
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group)
(ltu/is-operation-present :get-peers))
; check contents of session
(let [get-peers-url (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-uri)
(ltu/body->edn)
(ltu/get-op-url :get-peers))]
(-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request get-peers-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
(= {})
(is "Get peers body should be empty")))))))
| true |
(ns sixsq.nuvla.server.resources.session-password-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer [deftest is use-fixtures]]
[peridot.core :refer [content-type header request session]]
[postal.core :as postal]
[sixsq.nuvla.auth.utils :as auth]
[sixsq.nuvla.auth.utils.sign :as sign]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info
:refer [authn-cookie authn-info-header wrap-authn-info]]
[sixsq.nuvla.server.resources.configuration-nuvla :as config-nuvla]
[sixsq.nuvla.server.resources.email.utils :as email-utils]
[sixsq.nuvla.server.resources.group :as group]
[sixsq.nuvla.server.resources.group-template :as group-tpl]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.resources.nuvlabox :as nuvlabox]
[sixsq.nuvla.server.resources.session :as session]
[sixsq.nuvla.server.resources.session-template :as st]
[sixsq.nuvla.server.resources.user :as user]
[sixsq.nuvla.server.resources.user-template :as user-tpl]
[sixsq.nuvla.server.resources.user-template-email-password :as email-password]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context session/resource-type))
(defn create-user
[session-admin & {:keys [username PI:PASSWORD:<PASSWORD>END_PI email activated?]}]
(let [validation-link (atom nil)
href (str user-tpl/resource-type "/" email-password/registration-method)
href-create {:template {:href href
:password PI:PASSWORD:<PASSWORD>END_PI
:username username
:email email}}]
(with-redefs [email-utils/extract-smtp-cfg
(fn [_] {:host "PI:EMAIL:<EMAIL>END_PI"
:port 465
:ssl true
:user "admin"
:pass "PI:PASSWORD:<PASSWORD>END_PI"})
;; WARNING: This is a fragile! Regex matching to recover callback URL.
postal/send-message (fn [_ {:keys [body]}]
(let [url (->> body second :content
(re-matches #"(?s).*visit:\n\n\s+(.*?)\n.*")
second)]
(reset! validation-link url))
{:code 0, :error :SUCCESS, :message "OK"})]
(let [user-id (-> session-admin
(request (str p/service-context user/resource-type)
:request-method :post
:body (json/write-str href-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))]
(when activated?
(is (re-matches #"^email.*successfully validated$"
(-> session-admin
(request @validation-link)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
:message))))
user-id))))
(deftest lifecycle
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-user (header session-json authn-info-header "user group/nuvla-user")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
href (str st/resource-type "/password")
template-url (str p/service-context href)
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]]
;; password session template should exist
(-> session-anon
(request template-url)
(ltu/body->edn)
(ltu/is-status 200))
;; anon without valid user can not create session
(let [username "anon"
plaintext-password "PI:PASSWORD:<PASSWORD>END_PI"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password PI:PASSWORD:<PASSWORD>END_PI}}
unauthorized-create (update-in valid-create [:template :password] (constantly "BAD"))]
; anonymous query should succeed but have no entries
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; unauthorized create must return a 403 response
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str unauthorized-create))
(ltu/body->edn)
(ltu/is-status 403))
)
;; anon with valid activated user can create session
(let [username "user/jane"
plaintext-password "PI:PASSWORD:<PASSWORD>END_PI"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password PI:PASSWORD:<PASSWORD>END_PI}}
invalid-create (assoc-in valid-create [:template :invalid] "BAD")
jane-user-id (create-user session-admin
:username username
:password PI:PASSWORD:<PASSWORD>END_PI
:activated? true
:email "PI:EMAIL:<EMAIL>END_PI")]
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
token (get-in resp [:response :cookies authn-cookie :value])
authn-info (if token (sign/unsign-cookie-info token) {})
uri (ltu/location resp)
abs-uri (str p/service-context uri)]
; check claims in cookie
(is (= jane-user-id (:user-id authn-info)))
(is (= #{"group/nuvla-user"
"group/nuvla-anon"
uri
jane-user-id}
(some-> authn-info
:claims
(str/split #"\s")
set)))
(is (= uri (:session authn-info)))
(is (not (nil? (:exp authn-info))))
; user should not be able to see session without session role
(-> session-user
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 403))
; anonymous query should succeed but still have no entries
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; user query should succeed but have no entries because of missing session role
(-> session-user
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?))
; admin query should succeed, but see no sessions without the correct session role
(-> session-admin
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 0))
; user should be able to see session with session role
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group))
; check contents of session
(let [{:keys [name description tags]} (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-uri)
(ltu/body->edn)
:response
:body)]
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr)))
; user query with session role should succeed but and have one entry
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
; user with session role can delete resource
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri
:request-method :delete)
(ltu/is-unset-cookie)
(ltu/body->edn)
(ltu/is-status 200))
; create with invalid template fails
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; admin create with invalid template fails
(-> session-admin
(request base-uri
:request-method :post
:body (json/write-str invalid-create))
(ltu/body->edn)
(ltu/is-status 400)))
;; anon with valid non activated user cannot create session
(let [username "alex"
plaintext-password "PI:PASSWORD:<PASSWORD>END_PI"
valid-create {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:username username
:password plaintext-password}}]
(create-user session-admin
:username username
:password plaintext-password
:activated? false
:email "PI:EMAIL:<EMAIL>END_PI")
; unauthorized create must return a 403 response
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 403)))
))
(deftest claim-account-test
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
href (str st/resource-type "/password")
username "user/bob"
plaintext-password "PI:PASSWORD:<PASSWORD>END_PI"
user-id (create-user session-admin
:username username
:password PI:PASSWORD:<PASSWORD>END_PI
:activated? true
:email "PI:EMAIL:<EMAIL>END_PI")]
;; anon with valid activated user can create session
#_{:clj-kondo/ignore [:redundant-let]}
(let [username "user/bob"
plaintext-password "PI:PASSWORD:<PASSWORD>END_PI"
valid-create {:template {:href href
:username username
:password plaintext-PI:PASSWORD:<PASSWORD>END_PI}}]
; anonymous create must succeed
(let [session-1 (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
session-1-id (ltu/body-resource-id session-1)
session-1-uri (ltu/location session-1)
sesssion-1-abs-uri (str p/service-context session-1-uri)
handler (wrap-authn-info identity)
authn-session-1 (-> {:cookies (get-in session-1 [:response :cookies])}
handler
seq
flatten)
group-identifier "alpha"
group-alpha (str group/resource-type "/" group-identifier)
group-create {:template {:href (str group-tpl/resource-type "/generic")
:group-identifier group-identifier}}
group-url (-> session-admin
(request (str p/service-context group/resource-type)
:request-method :post
:body (json/write-str group-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location-url))]
; user without additional group should not have operation claim
(-> (apply request session-json (concat [sesssion-1-abs-uri] authn-session-1))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-1-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group))
;; add user to group/alpha
(-> session-admin
(request group-url
:request-method :put
:body (json/write-str {:users [user-id]}))
(ltu/body->edn)
(ltu/is-status 200))
;; check claim operation present
(let [session-2 (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
session-2-id (ltu/body-resource-id session-2)
session-2-uri (ltu/location session-2)
session-2-abs-uri (str p/service-context session-2-uri)
authn-session-2 (-> {:cookies (get-in session-2 [:response :cookies])}
handler
seq
flatten)
claim-op-url (-> (apply request session-json (concat [session-2-abs-uri] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/get-op-url :switch-group))]
(-> (apply request session-json (concat [session-2-abs-uri] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-2-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-present :switch-group)
(ltu/is-operation-present :get-peers))
;; claiming group-beta should fail
(-> (apply request session-json
(concat [claim-op-url :body (json/write-str {:claim "group/beta"})
:request-method :post] authn-session-2))
(ltu/body->edn)
(ltu/is-status 403)
(ltu/message-matches #"Switch group cannot be done to requested group:.*"))
;; claim with old session fail because wasn't in group/alpha
(-> (apply request session-json
(concat [claim-op-url :body (json/write-str {:claim group-alpha})
:request-method :post] authn-session-1))
(ltu/body->edn)
(ltu/is-status 403))
;; claim group-alpha
(let [cookie-claim (-> (apply request session-json
(concat [claim-op-url :body (json/write-str
{:claim group-alpha})
:request-method :post] authn-session-2))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-set-cookie)
:response
:cookies)
authn-session-claim (-> {:cookies cookie-claim}
handler
seq
flatten)]
(is (= {:active-claim group-alpha
:claims #{"group/nuvla-anon"
"group/nuvla-user"
session-2-id
group-alpha}
:groups #{"group/alpha"}
:user-id user-id}
(-> {:cookies cookie-claim}
handler
auth/current-authentication)))
(-> (apply request session-json (concat [session-2-abs-uri] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id session-2-id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-present :switch-group))
;; try create NuvlaBox and check who is the owner
(binding [config-nuvla/*stripe-api-key* nil]
(let [nuvlabox-url (-> (apply request session-json
(concat [(str p/service-context nuvlabox/resource-type)
:body (json/write-str {})
:request-method :post] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location-url))]
(-> session-admin
(request nuvlabox-url)
(ltu/body->edn)
(ltu/is-status 200))
(-> (apply request session-json (concat [nuvlabox-url] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :owner group-alpha))))
(let [cookie-claim-back (-> (apply request session-json
(concat [claim-op-url :body (json/write-str
{:claim user-id})
:request-method :post] authn-session-claim))
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-set-cookie)
:response
:cookies)]
(is (= user-id
(-> {:cookies cookie-claim-back}
handler
auth/current-authentication
:user-id))))))
))))
(deftest get-peers-test
(let [app (ltu/ring-app)
session-json (content-type (session app) "application/json")
session-user (header session-json authn-info-header "user group/nuvla-user")
session-anon (header session-json authn-info-header "user/unknown user/unknown group/nuvla-anon")
session-admin (header session-json authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")]
(let [href (str st/resource-type "/password")
username "user/jack"
plaintext-password "PI:PASSWORD:<PASSWORD>END_PI"
valid-create {:template {:href href
:username username
:password PI:PASSWORD:<PASSWORD>END_PI}}]
(create-user session-admin
:username username
:password PI:PASSWORD:<PASSWORD>END_PI
:activated? true
:email "PI:EMAIL:<EMAIL>END_PI")
; anonymous create must succeed
(let [resp (-> session-anon
(request base-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-set-cookie)
(ltu/is-status 201))
id (ltu/body-resource-id resp)
uri (ltu/location resp)
abs-uri (str p/service-context uri)]
; user should be able to see session with session role
(-> (session app)
(header authn-info-header (str "user/user group/nuvla-user " id))
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id id)
(ltu/is-operation-present :delete)
(ltu/is-operation-absent :edit)
(ltu/is-operation-absent :switch-group)
(ltu/is-operation-present :get-peers))
; check contents of session
(let [get-peers-url (-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request abs-uri)
(ltu/body->edn)
(ltu/get-op-url :get-peers))]
(-> session-user
(header authn-info-header (str "user/user group/nuvla-user group/nuvla-anon " id))
(request get-peers-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body)
(= {})
(is "Get peers body should be empty")))))))
|
[
{
"context": "efsc NewPasswordForm [this {:ui/keys [old-password new-password\n ",
"end": 1630,
"score": 0.6118881106376648,
"start": 1627,
"tag": "PASSWORD",
"value": "new"
},
{
"context": "password {:old-password old-password :new-password new-password})]))}\n\n (dd/typography\n {:component :",
"end": 2670,
"score": 0.8687679767608643,
"start": 2658,
"tag": "PASSWORD",
"value": "new-password"
}
] |
src/main/todoish/ui/settings.cljs
|
MrEbbinghaus/Todoish
| 10 |
(ns todoish.ui.settings
(:require [material-ui.layout :as layout]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[material-ui.surfaces :as surfaces]
[com.fulcrologic.fulcro.dom :as dom]
[com.fulcrologic.fulcro.dom.events :as evt]
[material-ui.utils :as mutils]
[material-ui.inputs :as inputs]
[taoensso.timbre :as log]
[material-ui.feedback :as feedback]
[todoish.ui.themes :as themes]
[material-ui.data-display :as dd]))
(defn wide-textfield
"Outlined textfield on full width with normal margins. Takes the same props as `material-ui.inputs/textfield`"
[props]
(inputs/textfield
(merge
{:variant :filled
:fullWidth true
:margin :normal}
props)))
(defmutation change-password [{:keys [old-password new-password]}]
(ok-action [{:keys [component] :as env}]
(let [{:keys [errors]}
(get-in env [:result :body 'todoish.api.user/change-password])]
(if (empty? errors)
(m/set-value!! component :ui/success-open? true)
(cond
(contains? errors :invalid-credentials)
(m/set-string!! component :ui/old-password-error :value "Password is wrong.")))))
(remote [env]
(m/with-server-side-mutation env 'todoish.api.user/change-password)))
(defsc NewPasswordForm [this {:ui/keys [old-password new-password
old-password-error new-password-error
success-open?]}]
{:query [:ui/old-password :ui/new-password :ui/old-password-error :ui/new-password-error :ui/success-open? fs/form-config-join]
:ident (fn [] [:component/id :settings/new-password-form])
:form-fields [:ui/old-password :ui/new-password]
:initial-state #:ui{:old-password ""
:new-password ""
:old-password-error nil
:new-password-error nil
:ui/success-open? false}}
(surfaces/paper {}
(layout/box
{:component "form"
:p 3
:onSubmit (fn submit-change-password [e]
(evt/prevent-default! e)
(comp/transact!! this
[(m/set-props {:ui/old-password ""
:ui/new-password ""})
(change-password {:old-password old-password :new-password new-password})]))}
(dd/typography
{:component :h1
:variant :h6}
"Change Password")
(wide-textfield {:label "Old Password"
:type :password
:error (boolean old-password-error)
:helperText old-password-error
:required true
:inputProps {:aria-label "Old Password"
:autoComplete :current-password}
:value old-password
:onChange (fn [e]
(m/set-value!! this :ui/old-password-error nil)
(m/set-string!! this :ui/old-password :event e))})
(wide-textfield {:label "New Password"
:type :password
:error (boolean new-password-error)
:helperText new-password-error
:required true
:value new-password
:inputProps {:minLength 10
:aria-label "New Password"
:autoComplete :new-password}
:onChange (fn [e]
(m/set-value!! this :ui/new-password-error nil)
(m/set-string!! this :ui/new-password :event e))})
(layout/box {:mt 2}
(inputs/button
{:color :primary
:variant :contained
:margin "normal"
:type :submit}
"Save")))
(feedback/snackbar
{:autoHideDuration 6000
:open success-open?
:onClose #(m/set-value!! this :ui/success-open? false)
:message "Password changed"})))
(def ui-new-password-form (comp/factory NewPasswordForm))
(defsc SettingsPage [_this {:ui/keys [new-password-form]}]
{:query [{:ui/new-password-form (comp/get-query NewPasswordForm)}]
:ident (fn [] [:page/id :settings])
:route-segment ["settings"]
:initial-state (fn [_] {:ui/new-password-form (comp/get-initial-state NewPasswordForm)})}
(layout/container
{:maxWidth "lg"}
(layout/grid
{:direction :column
:container true
:spacing 2
:justify "flex-start"}
(layout/grid {:item true
:xs 12}
(ui-new-password-form new-password-form)))))
|
33052
|
(ns todoish.ui.settings
(:require [material-ui.layout :as layout]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[material-ui.surfaces :as surfaces]
[com.fulcrologic.fulcro.dom :as dom]
[com.fulcrologic.fulcro.dom.events :as evt]
[material-ui.utils :as mutils]
[material-ui.inputs :as inputs]
[taoensso.timbre :as log]
[material-ui.feedback :as feedback]
[todoish.ui.themes :as themes]
[material-ui.data-display :as dd]))
(defn wide-textfield
"Outlined textfield on full width with normal margins. Takes the same props as `material-ui.inputs/textfield`"
[props]
(inputs/textfield
(merge
{:variant :filled
:fullWidth true
:margin :normal}
props)))
(defmutation change-password [{:keys [old-password new-password]}]
(ok-action [{:keys [component] :as env}]
(let [{:keys [errors]}
(get-in env [:result :body 'todoish.api.user/change-password])]
(if (empty? errors)
(m/set-value!! component :ui/success-open? true)
(cond
(contains? errors :invalid-credentials)
(m/set-string!! component :ui/old-password-error :value "Password is wrong.")))))
(remote [env]
(m/with-server-side-mutation env 'todoish.api.user/change-password)))
(defsc NewPasswordForm [this {:ui/keys [old-password <PASSWORD>-password
old-password-error new-password-error
success-open?]}]
{:query [:ui/old-password :ui/new-password :ui/old-password-error :ui/new-password-error :ui/success-open? fs/form-config-join]
:ident (fn [] [:component/id :settings/new-password-form])
:form-fields [:ui/old-password :ui/new-password]
:initial-state #:ui{:old-password ""
:new-password ""
:old-password-error nil
:new-password-error nil
:ui/success-open? false}}
(surfaces/paper {}
(layout/box
{:component "form"
:p 3
:onSubmit (fn submit-change-password [e]
(evt/prevent-default! e)
(comp/transact!! this
[(m/set-props {:ui/old-password ""
:ui/new-password ""})
(change-password {:old-password old-password :new-password <PASSWORD>})]))}
(dd/typography
{:component :h1
:variant :h6}
"Change Password")
(wide-textfield {:label "Old Password"
:type :password
:error (boolean old-password-error)
:helperText old-password-error
:required true
:inputProps {:aria-label "Old Password"
:autoComplete :current-password}
:value old-password
:onChange (fn [e]
(m/set-value!! this :ui/old-password-error nil)
(m/set-string!! this :ui/old-password :event e))})
(wide-textfield {:label "New Password"
:type :password
:error (boolean new-password-error)
:helperText new-password-error
:required true
:value new-password
:inputProps {:minLength 10
:aria-label "New Password"
:autoComplete :new-password}
:onChange (fn [e]
(m/set-value!! this :ui/new-password-error nil)
(m/set-string!! this :ui/new-password :event e))})
(layout/box {:mt 2}
(inputs/button
{:color :primary
:variant :contained
:margin "normal"
:type :submit}
"Save")))
(feedback/snackbar
{:autoHideDuration 6000
:open success-open?
:onClose #(m/set-value!! this :ui/success-open? false)
:message "Password changed"})))
(def ui-new-password-form (comp/factory NewPasswordForm))
(defsc SettingsPage [_this {:ui/keys [new-password-form]}]
{:query [{:ui/new-password-form (comp/get-query NewPasswordForm)}]
:ident (fn [] [:page/id :settings])
:route-segment ["settings"]
:initial-state (fn [_] {:ui/new-password-form (comp/get-initial-state NewPasswordForm)})}
(layout/container
{:maxWidth "lg"}
(layout/grid
{:direction :column
:container true
:spacing 2
:justify "flex-start"}
(layout/grid {:item true
:xs 12}
(ui-new-password-form new-password-form)))))
| true |
(ns todoish.ui.settings
(:require [material-ui.layout :as layout]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]
[material-ui.surfaces :as surfaces]
[com.fulcrologic.fulcro.dom :as dom]
[com.fulcrologic.fulcro.dom.events :as evt]
[material-ui.utils :as mutils]
[material-ui.inputs :as inputs]
[taoensso.timbre :as log]
[material-ui.feedback :as feedback]
[todoish.ui.themes :as themes]
[material-ui.data-display :as dd]))
(defn wide-textfield
"Outlined textfield on full width with normal margins. Takes the same props as `material-ui.inputs/textfield`"
[props]
(inputs/textfield
(merge
{:variant :filled
:fullWidth true
:margin :normal}
props)))
(defmutation change-password [{:keys [old-password new-password]}]
(ok-action [{:keys [component] :as env}]
(let [{:keys [errors]}
(get-in env [:result :body 'todoish.api.user/change-password])]
(if (empty? errors)
(m/set-value!! component :ui/success-open? true)
(cond
(contains? errors :invalid-credentials)
(m/set-string!! component :ui/old-password-error :value "Password is wrong.")))))
(remote [env]
(m/with-server-side-mutation env 'todoish.api.user/change-password)))
(defsc NewPasswordForm [this {:ui/keys [old-password PI:PASSWORD:<PASSWORD>END_PI-password
old-password-error new-password-error
success-open?]}]
{:query [:ui/old-password :ui/new-password :ui/old-password-error :ui/new-password-error :ui/success-open? fs/form-config-join]
:ident (fn [] [:component/id :settings/new-password-form])
:form-fields [:ui/old-password :ui/new-password]
:initial-state #:ui{:old-password ""
:new-password ""
:old-password-error nil
:new-password-error nil
:ui/success-open? false}}
(surfaces/paper {}
(layout/box
{:component "form"
:p 3
:onSubmit (fn submit-change-password [e]
(evt/prevent-default! e)
(comp/transact!! this
[(m/set-props {:ui/old-password ""
:ui/new-password ""})
(change-password {:old-password old-password :new-password PI:PASSWORD:<PASSWORD>END_PI})]))}
(dd/typography
{:component :h1
:variant :h6}
"Change Password")
(wide-textfield {:label "Old Password"
:type :password
:error (boolean old-password-error)
:helperText old-password-error
:required true
:inputProps {:aria-label "Old Password"
:autoComplete :current-password}
:value old-password
:onChange (fn [e]
(m/set-value!! this :ui/old-password-error nil)
(m/set-string!! this :ui/old-password :event e))})
(wide-textfield {:label "New Password"
:type :password
:error (boolean new-password-error)
:helperText new-password-error
:required true
:value new-password
:inputProps {:minLength 10
:aria-label "New Password"
:autoComplete :new-password}
:onChange (fn [e]
(m/set-value!! this :ui/new-password-error nil)
(m/set-string!! this :ui/new-password :event e))})
(layout/box {:mt 2}
(inputs/button
{:color :primary
:variant :contained
:margin "normal"
:type :submit}
"Save")))
(feedback/snackbar
{:autoHideDuration 6000
:open success-open?
:onClose #(m/set-value!! this :ui/success-open? false)
:message "Password changed"})))
(def ui-new-password-form (comp/factory NewPasswordForm))
(defsc SettingsPage [_this {:ui/keys [new-password-form]}]
{:query [{:ui/new-password-form (comp/get-query NewPasswordForm)}]
:ident (fn [] [:page/id :settings])
:route-segment ["settings"]
:initial-state (fn [_] {:ui/new-password-form (comp/get-initial-state NewPasswordForm)})}
(layout/container
{:maxWidth "lg"}
(layout/grid
{:direction :column
:container true
:spacing 2
:justify "flex-start"}
(layout/grid {:item true
:xs 12}
(ui-new-password-form new-password-form)))))
|
[
{
"context": " 1\n {:keylength 512\n :extensions [{:oid \"1.3.6",
"end": 5768,
"score": 0.9659882187843323,
"start": 5765,
"tag": "KEY",
"value": "512"
}
] |
test/integration/puppetlabs/puppetserver/auth_conf_test.clj
|
fpringvaldsen/puppet-server
| 0 |
(ns puppetlabs.puppetserver.auth-conf-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[puppetlabs.puppetserver.bootstrap-testutils :as bootstrap]
[puppetlabs.http.client.sync :as http-client]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.simple :as ssl-simple]
[puppetlabs.ssl-utils.core :as ssl-utils]
[schema.test :as schema-test]
[puppetlabs.services.jruby.jruby-testutils :as jruby-testutils]
[me.raynes.fs :as fs]
[ring.util.codec :as ring-codec])
(:import (java.io StringWriter)))
(def test-resources-dir
"./dev-resources/puppetlabs/puppetserver/auth_conf_test")
(use-fixtures
:once
schema-test/validate-schemas
(jruby-testutils/with-puppet-conf (fs/file test-resources-dir "puppet.conf")))
(defn http-get [path]
(http-client/get
(str "https://localhost:8140/" path)
bootstrap/request-options))
(deftest ^:integration legacy-auth-conf-used-when-legacy-auth-conf-true
(testing "Authorization is done per legacy auth.conf when :use-legacy-auth-conf true"
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf true}}
(logutils/with-test-logging
(testing "for puppet 4 routes"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response))))
(testing "for legacy puppet routes"
(let [response (http-get "production/node/public")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/node/private")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/public")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/private")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-ssl-cert-handled-via-tk-auth
(testing (str "Request with SSL certificate via trapperkeeper-authorization "
"handled")
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf false}
:authorization {:version 1
:allow-header-cert-info false
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}
{:match-request {:path "^/puppet/v3/node/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "node"}]}}
(logutils/with-test-logging
(testing "for puppet 4 routes"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response))))
(testing "for legacy puppet routes"
(let [response (http-get "production/node/public")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/node/private")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/public")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/private")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-x-client-headers-handled-via-tk-auth
(testing (str "Request with X-Client headers via trapperkeeper-authorization "
"handled")
(let [extension-value "UUUU-IIIII-DDD"
cert (:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength 512
:extensions [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value extension-value}]}))
url-encoded-cert (let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer))
http-get-no-ssl (fn [path]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "pson"
"X-Client-Cert" url-encoded-cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf false}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}]}
:webserver {:host "localhost"
:port 8080}}
(testing "as 403 for unauthorized user"
(logutils/with-test-logging
(let [response (http-get-no-ssl
"puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))
(testing "for certificate when provided"
(let [environment-dir (fs/file jruby-testutils/code-dir
"environments")
manifest-dir (fs/file environment-dir
"production"
"manifests")]
(try
(fs/mkdirs manifest-dir)
(spit (fs/file manifest-dir "site.pp")
(str/join "\n"
["notify {'trusty_info':"
" message => $trusted[extensions][pp_uuid]"
"}\n"]))
(let [response
(http-get-no-ssl
"puppet/v3/catalog/private?environment=production")
expected-content-in-catalog
(str
"\"parameters\":{\"message\":\""
extension-value
"\"}")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.contains (:body response) expected-content-in-catalog)
(str "Did not find '" expected-content-in-catalog
"' in full response body: " (:body response))))
(finally
(fs/delete-dir environment-dir))))))))))
|
16081
|
(ns puppetlabs.puppetserver.auth-conf-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[puppetlabs.puppetserver.bootstrap-testutils :as bootstrap]
[puppetlabs.http.client.sync :as http-client]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.simple :as ssl-simple]
[puppetlabs.ssl-utils.core :as ssl-utils]
[schema.test :as schema-test]
[puppetlabs.services.jruby.jruby-testutils :as jruby-testutils]
[me.raynes.fs :as fs]
[ring.util.codec :as ring-codec])
(:import (java.io StringWriter)))
(def test-resources-dir
"./dev-resources/puppetlabs/puppetserver/auth_conf_test")
(use-fixtures
:once
schema-test/validate-schemas
(jruby-testutils/with-puppet-conf (fs/file test-resources-dir "puppet.conf")))
(defn http-get [path]
(http-client/get
(str "https://localhost:8140/" path)
bootstrap/request-options))
(deftest ^:integration legacy-auth-conf-used-when-legacy-auth-conf-true
(testing "Authorization is done per legacy auth.conf when :use-legacy-auth-conf true"
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf true}}
(logutils/with-test-logging
(testing "for puppet 4 routes"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response))))
(testing "for legacy puppet routes"
(let [response (http-get "production/node/public")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/node/private")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/public")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/private")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-ssl-cert-handled-via-tk-auth
(testing (str "Request with SSL certificate via trapperkeeper-authorization "
"handled")
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf false}
:authorization {:version 1
:allow-header-cert-info false
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}
{:match-request {:path "^/puppet/v3/node/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "node"}]}}
(logutils/with-test-logging
(testing "for puppet 4 routes"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response))))
(testing "for legacy puppet routes"
(let [response (http-get "production/node/public")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/node/private")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/public")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/private")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-x-client-headers-handled-via-tk-auth
(testing (str "Request with X-Client headers via trapperkeeper-authorization "
"handled")
(let [extension-value "UUUU-IIIII-DDD"
cert (:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength <KEY>
:extensions [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value extension-value}]}))
url-encoded-cert (let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer))
http-get-no-ssl (fn [path]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "pson"
"X-Client-Cert" url-encoded-cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf false}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}]}
:webserver {:host "localhost"
:port 8080}}
(testing "as 403 for unauthorized user"
(logutils/with-test-logging
(let [response (http-get-no-ssl
"puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))
(testing "for certificate when provided"
(let [environment-dir (fs/file jruby-testutils/code-dir
"environments")
manifest-dir (fs/file environment-dir
"production"
"manifests")]
(try
(fs/mkdirs manifest-dir)
(spit (fs/file manifest-dir "site.pp")
(str/join "\n"
["notify {'trusty_info':"
" message => $trusted[extensions][pp_uuid]"
"}\n"]))
(let [response
(http-get-no-ssl
"puppet/v3/catalog/private?environment=production")
expected-content-in-catalog
(str
"\"parameters\":{\"message\":\""
extension-value
"\"}")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.contains (:body response) expected-content-in-catalog)
(str "Did not find '" expected-content-in-catalog
"' in full response body: " (:body response))))
(finally
(fs/delete-dir environment-dir))))))))))
| true |
(ns puppetlabs.puppetserver.auth-conf-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[puppetlabs.puppetserver.bootstrap-testutils :as bootstrap]
[puppetlabs.http.client.sync :as http-client]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.trapperkeeper.testutils.logging :as logutils]
[puppetlabs.ssl-utils.simple :as ssl-simple]
[puppetlabs.ssl-utils.core :as ssl-utils]
[schema.test :as schema-test]
[puppetlabs.services.jruby.jruby-testutils :as jruby-testutils]
[me.raynes.fs :as fs]
[ring.util.codec :as ring-codec])
(:import (java.io StringWriter)))
(def test-resources-dir
"./dev-resources/puppetlabs/puppetserver/auth_conf_test")
(use-fixtures
:once
schema-test/validate-schemas
(jruby-testutils/with-puppet-conf (fs/file test-resources-dir "puppet.conf")))
(defn http-get [path]
(http-client/get
(str "https://localhost:8140/" path)
bootstrap/request-options))
(deftest ^:integration legacy-auth-conf-used-when-legacy-auth-conf-true
(testing "Authorization is done per legacy auth.conf when :use-legacy-auth-conf true"
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf true}}
(logutils/with-test-logging
(testing "for puppet 4 routes"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response))))
(testing "for legacy puppet routes"
(let [response (http-get "production/node/public")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/node/private")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/public")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/private")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-ssl-cert-handled-via-tk-auth
(testing (str "Request with SSL certificate via trapperkeeper-authorization "
"handled")
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf false}
:authorization {:version 1
:allow-header-cert-info false
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}
{:match-request {:path "^/puppet/v3/node/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "node"}]}}
(logutils/with-test-logging
(testing "for puppet 4 routes"
(let [response (http-get "puppet/v3/node/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/node/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "puppet/v3/catalog/private?environment=production")]
(is (= 200 (:status response))
(ks/pprint-to-string response))))
(testing "for legacy puppet routes"
(let [response (http-get "production/node/public")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/node/private")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/public")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))
(let [response (http-get "production/catalog/private")]
(is (= 200 (:status response))
(ks/pprint-to-string response)))))))))
(deftest ^:integration request-with-x-client-headers-handled-via-tk-auth
(testing (str "Request with X-Client headers via trapperkeeper-authorization "
"handled")
(let [extension-value "UUUU-IIIII-DDD"
cert (:cert (ssl-simple/gen-self-signed-cert
"ssl-client"
1
{:keylength PI:KEY:<KEY>END_PI
:extensions [{:oid "1.3.6.1.4.1.34380.1.1.1"
:critical false
:value extension-value}]}))
url-encoded-cert (let [cert-writer (StringWriter.)
_ (ssl-utils/cert->pem! cert cert-writer)]
(ring-codec/url-encode cert-writer))
http-get-no-ssl (fn [path]
(http-client/get
(str "http://localhost:8080/" path)
{:headers {"Accept" "pson"
"X-Client-Cert" url-encoded-cert
"X-Client-DN" "CN=private"
"X-Client-Verify" "SUCCESS"}
:as :text}))]
(logutils/with-test-logging
(bootstrap/with-puppetserver-running
app
{:jruby-puppet {:use-legacy-auth-conf false}
:authorization {:version 1
:allow-header-cert-info true
:rules
[{:match-request {:path "^/puppet/v3/catalog/private$"
:type "regex"}
:allow ["private" "localhost"]
:sort-order 1
:name "catalog"}]}
:webserver {:host "localhost"
:port 8080}}
(testing "as 403 for unauthorized user"
(logutils/with-test-logging
(let [response (http-get-no-ssl
"puppet/v3/catalog/public?environment=production")]
(is (= 403 (:status response))
(ks/pprint-to-string response)))))
(testing "for certificate when provided"
(let [environment-dir (fs/file jruby-testutils/code-dir
"environments")
manifest-dir (fs/file environment-dir
"production"
"manifests")]
(try
(fs/mkdirs manifest-dir)
(spit (fs/file manifest-dir "site.pp")
(str/join "\n"
["notify {'trusty_info':"
" message => $trusted[extensions][pp_uuid]"
"}\n"]))
(let [response
(http-get-no-ssl
"puppet/v3/catalog/private?environment=production")
expected-content-in-catalog
(str
"\"parameters\":{\"message\":\""
extension-value
"\"}")]
(is (= 200 (:status response))
(ks/pprint-to-string response))
(is (.contains (:body response) expected-content-in-catalog)
(str "Did not find '" expected-content-in-catalog
"' in full response body: " (:body response))))
(finally
(fs/delete-dir environment-dir))))))))))
|
[
{
"context": ":doc \"Basic logging functionality.\"\n :author \"Jeff Rose\"}\n overtone.config.log\n (:import [java.util.log",
"end": 67,
"score": 0.9998781085014343,
"start": 58,
"tag": "NAME",
"value": "Jeff Rose"
}
] |
src/overtone/config/log.clj
|
ABaldwinHunter/overtone
| 3,870 |
(ns
^{:doc "Basic logging functionality."
:author "Jeff Rose"}
overtone.config.log
(:import [java.util.logging Logger Level ConsoleHandler FileHandler
StreamHandler Formatter LogRecord]
[java.util Date])
(:use [overtone.config store]
[clojure.pprint :only (pprint)]))
(def ^:private LOG-APPEND true)
(def ^:private LOG-LIMIT 5000000)
(def ^:private LOG-COUNT 2)
(def ^:private DEFAULT-LOG-LEVEL :warn)
(def ^:private LOG-LEVELS {:debug Level/FINE
:info Level/INFO
:warn Level/WARNING
:error Level/SEVERE})
(def ^:private REVERSE-LOG-LEVELS (apply hash-map (flatten (map reverse LOG-LEVELS))))
(defonce ^:private LOGGER (Logger/getLogger "overtone"))
(defonce ^:private LOG-CONSOLE (ConsoleHandler.))
(defonce ^:private LOG-FILE-HANDLER (FileHandler. OVERTONE-LOG-FILE LOG-LIMIT LOG-COUNT LOG-APPEND))
(defn- initial-log-level
[]
(or (config-get :log-level)
DEFAULT-LOG-LEVEL))
(defn- log-formatter []
(proxy [Formatter] []
(format [^LogRecord log-rec]
(let [lvl (REVERSE-LOG-LEVELS (.getLevel log-rec))
msg (.getMessage log-rec)
ts (.getMillis log-rec)]
(with-out-str (pprint {:level lvl
:timestamp ts
:date (Date. (long ts))
:msg msg}))))))
(defn- print-handler []
(let [formatter (log-formatter)]
(proxy [StreamHandler] []
(publish [msg] (println (.format formatter msg))))))
(defn console []
(.addHandler LOGGER (print-handler)))
(defn log-level
"Returns the current log level"
[]
(.getLevel LOGGER))
(defn set-level!
"Set the log level for this session. Use one of :debug, :info, :warn
or :error"
[level]
(assert (contains? LOG-LEVELS level))
(.setLevel LOGGER (get LOG-LEVELS level)))
(defn set-default-level!
"Set the log level for this and future sessions - stores level in
config. Use one of :debug, :info, :warn or :error"
[level]
(set-level! level)
(config-set! :log-level level)
level)
(defn debug
"Log msg with level debug"
[& msg]
(.log LOGGER Level/FINE (apply str msg)))
(defn info
"Log msg with level info"
[& msg]
(.log LOGGER Level/INFO (apply str msg)))
(defn warn
"Log msg with level warn"
[& msg]
(.log LOGGER Level/WARNING (apply str msg)))
(defn error
"Log msg with level error"
[& msg]
(.log LOGGER Level/SEVERE (apply str msg)))
(defmacro with-error-log
"Wrap body with a try/catch form, and log exceptions (using warning)."
[message & body]
`(try
~@body
(catch Exception ex#
(println "Exception: " ex#)
(warn (str ~message "\nException: " ex#
(with-out-str (clojure.stacktrace/print-stack-trace ex#)))))))
;;setup logger
(defonce ^:private __setup-logs__
(do
(set-level! (initial-log-level))
(.setFormatter LOG-FILE-HANDLER (log-formatter))
(.addHandler LOGGER LOG-FILE-HANDLER)))
(defonce ^:private __cleanup-logger-on-shutdown__
(.addShutdownHook (Runtime/getRuntime)
(Thread. (fn []
(info "Shutting down - cleaning up logger")
(.removeHandler LOGGER LOG-FILE-HANDLER)
(.close LOG-FILE-HANDLER)))))
|
78132
|
(ns
^{:doc "Basic logging functionality."
:author "<NAME>"}
overtone.config.log
(:import [java.util.logging Logger Level ConsoleHandler FileHandler
StreamHandler Formatter LogRecord]
[java.util Date])
(:use [overtone.config store]
[clojure.pprint :only (pprint)]))
(def ^:private LOG-APPEND true)
(def ^:private LOG-LIMIT 5000000)
(def ^:private LOG-COUNT 2)
(def ^:private DEFAULT-LOG-LEVEL :warn)
(def ^:private LOG-LEVELS {:debug Level/FINE
:info Level/INFO
:warn Level/WARNING
:error Level/SEVERE})
(def ^:private REVERSE-LOG-LEVELS (apply hash-map (flatten (map reverse LOG-LEVELS))))
(defonce ^:private LOGGER (Logger/getLogger "overtone"))
(defonce ^:private LOG-CONSOLE (ConsoleHandler.))
(defonce ^:private LOG-FILE-HANDLER (FileHandler. OVERTONE-LOG-FILE LOG-LIMIT LOG-COUNT LOG-APPEND))
(defn- initial-log-level
[]
(or (config-get :log-level)
DEFAULT-LOG-LEVEL))
(defn- log-formatter []
(proxy [Formatter] []
(format [^LogRecord log-rec]
(let [lvl (REVERSE-LOG-LEVELS (.getLevel log-rec))
msg (.getMessage log-rec)
ts (.getMillis log-rec)]
(with-out-str (pprint {:level lvl
:timestamp ts
:date (Date. (long ts))
:msg msg}))))))
(defn- print-handler []
(let [formatter (log-formatter)]
(proxy [StreamHandler] []
(publish [msg] (println (.format formatter msg))))))
(defn console []
(.addHandler LOGGER (print-handler)))
(defn log-level
"Returns the current log level"
[]
(.getLevel LOGGER))
(defn set-level!
"Set the log level for this session. Use one of :debug, :info, :warn
or :error"
[level]
(assert (contains? LOG-LEVELS level))
(.setLevel LOGGER (get LOG-LEVELS level)))
(defn set-default-level!
"Set the log level for this and future sessions - stores level in
config. Use one of :debug, :info, :warn or :error"
[level]
(set-level! level)
(config-set! :log-level level)
level)
(defn debug
"Log msg with level debug"
[& msg]
(.log LOGGER Level/FINE (apply str msg)))
(defn info
"Log msg with level info"
[& msg]
(.log LOGGER Level/INFO (apply str msg)))
(defn warn
"Log msg with level warn"
[& msg]
(.log LOGGER Level/WARNING (apply str msg)))
(defn error
"Log msg with level error"
[& msg]
(.log LOGGER Level/SEVERE (apply str msg)))
(defmacro with-error-log
"Wrap body with a try/catch form, and log exceptions (using warning)."
[message & body]
`(try
~@body
(catch Exception ex#
(println "Exception: " ex#)
(warn (str ~message "\nException: " ex#
(with-out-str (clojure.stacktrace/print-stack-trace ex#)))))))
;;setup logger
(defonce ^:private __setup-logs__
(do
(set-level! (initial-log-level))
(.setFormatter LOG-FILE-HANDLER (log-formatter))
(.addHandler LOGGER LOG-FILE-HANDLER)))
(defonce ^:private __cleanup-logger-on-shutdown__
(.addShutdownHook (Runtime/getRuntime)
(Thread. (fn []
(info "Shutting down - cleaning up logger")
(.removeHandler LOGGER LOG-FILE-HANDLER)
(.close LOG-FILE-HANDLER)))))
| true |
(ns
^{:doc "Basic logging functionality."
:author "PI:NAME:<NAME>END_PI"}
overtone.config.log
(:import [java.util.logging Logger Level ConsoleHandler FileHandler
StreamHandler Formatter LogRecord]
[java.util Date])
(:use [overtone.config store]
[clojure.pprint :only (pprint)]))
(def ^:private LOG-APPEND true)
(def ^:private LOG-LIMIT 5000000)
(def ^:private LOG-COUNT 2)
(def ^:private DEFAULT-LOG-LEVEL :warn)
(def ^:private LOG-LEVELS {:debug Level/FINE
:info Level/INFO
:warn Level/WARNING
:error Level/SEVERE})
(def ^:private REVERSE-LOG-LEVELS (apply hash-map (flatten (map reverse LOG-LEVELS))))
(defonce ^:private LOGGER (Logger/getLogger "overtone"))
(defonce ^:private LOG-CONSOLE (ConsoleHandler.))
(defonce ^:private LOG-FILE-HANDLER (FileHandler. OVERTONE-LOG-FILE LOG-LIMIT LOG-COUNT LOG-APPEND))
(defn- initial-log-level
[]
(or (config-get :log-level)
DEFAULT-LOG-LEVEL))
(defn- log-formatter []
(proxy [Formatter] []
(format [^LogRecord log-rec]
(let [lvl (REVERSE-LOG-LEVELS (.getLevel log-rec))
msg (.getMessage log-rec)
ts (.getMillis log-rec)]
(with-out-str (pprint {:level lvl
:timestamp ts
:date (Date. (long ts))
:msg msg}))))))
(defn- print-handler []
(let [formatter (log-formatter)]
(proxy [StreamHandler] []
(publish [msg] (println (.format formatter msg))))))
(defn console []
(.addHandler LOGGER (print-handler)))
(defn log-level
"Returns the current log level"
[]
(.getLevel LOGGER))
(defn set-level!
"Set the log level for this session. Use one of :debug, :info, :warn
or :error"
[level]
(assert (contains? LOG-LEVELS level))
(.setLevel LOGGER (get LOG-LEVELS level)))
(defn set-default-level!
"Set the log level for this and future sessions - stores level in
config. Use one of :debug, :info, :warn or :error"
[level]
(set-level! level)
(config-set! :log-level level)
level)
(defn debug
"Log msg with level debug"
[& msg]
(.log LOGGER Level/FINE (apply str msg)))
(defn info
"Log msg with level info"
[& msg]
(.log LOGGER Level/INFO (apply str msg)))
(defn warn
"Log msg with level warn"
[& msg]
(.log LOGGER Level/WARNING (apply str msg)))
(defn error
"Log msg with level error"
[& msg]
(.log LOGGER Level/SEVERE (apply str msg)))
(defmacro with-error-log
"Wrap body with a try/catch form, and log exceptions (using warning)."
[message & body]
`(try
~@body
(catch Exception ex#
(println "Exception: " ex#)
(warn (str ~message "\nException: " ex#
(with-out-str (clojure.stacktrace/print-stack-trace ex#)))))))
;;setup logger
(defonce ^:private __setup-logs__
(do
(set-level! (initial-log-level))
(.setFormatter LOG-FILE-HANDLER (log-formatter))
(.addHandler LOGGER LOG-FILE-HANDLER)))
(defonce ^:private __cleanup-logger-on-shutdown__
(.addShutdownHook (Runtime/getRuntime)
(Thread. (fn []
(info "Shutting down - cleaning up logger")
(.removeHandler LOGGER LOG-FILE-HANDLER)
(.close LOG-FILE-HANDLER)))))
|
[
{
"context": ";;Copyright (c) 2017 Rafik Naccache <[email protected]>\n;;Distributed under the MIT Lic",
"end": 35,
"score": 0.9998682141304016,
"start": 21,
"tag": "NAME",
"value": "Rafik Naccache"
},
{
"context": ";;Copyright (c) 2017 Rafik Naccache <[email protected]>\n;;Distributed under the MIT License\n(ns postagga",
"end": 52,
"score": 0.9999321699142456,
"start": 37,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
test/postagga/utils_test.cljc
|
jffrydsr/postagga
| 93 |
;;Copyright (c) 2017 Rafik Naccache <[email protected]>
;;Distributed under the MIT License
(ns postagga.utils-test
(:require [clojure.test :refer :all]
[postagga.tools :refer :all]))
(deftest get-column-test
(testing "Get Column")
(is (= {} (get-column nil 0)))
(is (= {} (get-column {} 0)))
(is (= {[0 0] 1} (get-column {[0 0] 1} 0)))
(is (= {[0 0] 1 [1 0] 2} (get-column {[0 0] 1 [1 0] 2} 0)))
(is (= {} (get-column {[0 0] 1 [1 0] 2} 1)))
(is (= {[0 1] 3 [1 1] 4} (get-column {[0 0] 1 [1 0] 2 [0 1] 3 [1 1] 4} 1)))
(is (= {[0 0] 1 [2 0] 2} (get-column {[0 0] 1 [2 0] 2} 0))))
(deftest get-row-test
(testing "Get Row")
(is (= {} (get-row nil 0)))
(is (= {} (get-row {} 0)))
(is (= {[0 0] 1} (get-row {[0 0] 1} 0)))
(is (= {[0 0] 1 [0 1] 2} (get-row {[0 0] 1 [0 1] 2} 0)))
(is (= {} (get-row {[0 0] 1 [0 1] 2} 1)))
(is (= {[1 0] 2 [1 1] 4} (get-row {[0 0] 1 [1 0] 2 [0 1] 3 [1 1] 4} 1)))
(is (= {[0 0] 1 [0 2] 2} (get-row {[0 0] 1 [0 2] 2} 0))))
(deftest arg-max-test
(testing "Arg Max")
(is (= nil (arg-max {})))
(is (= 0 (arg-max {0 0})))
(is (= 2 (arg-max {0 1 2 3}))))
(deftest bigrams-test
(testing "Bigrams")
(is (= #{} (bigrams nil)))
(is (= #{} (bigrams "")))
(is (= #{} (bigrams "a")))
(is (= #{"ab"} (bigrams "ab")))
(is (= #{"ab" "bc"} (bigrams "abc"))))
(deftest similarity-test
(testing "Similarity")
(is (= 0 (similarity nil nil))) ; TODO: should this really be the case
(is (= 0 (similarity "" ""))) ; TODO: should this really be the case
(is (= 0 (similarity "" nil)))
(is (= 0 (similarity "a" nil)))
(is (= 0 (similarity "a" "")))
(is (= 0 (similarity "a" "a"))) ; TODO: should this really be the case???
(is (= 1 (similarity "ab" "ab")))
(is (= 1/2 (similarity "ab" "abc")))
(is (= 1/3 (similarity "ab" "abcd")))
(is (= 0 (similarity "ab" "cd"))))
(deftest are-close-within-test
(testing "Are Close Within?")
(is (= false (are-close-within? 1/4 "ab" "cd")))
(is (= true (are-close-within? 0 "ab" "cd")))
(is (= false (are-close-within? 3/4 "abc" "bcd")))
(is (= true (are-close-within? 1/4 "abc" "bcd")))
(is (= true (are-close-within? 1 "abc" "abc"))))
(deftest find-first-test
(testing "Find first")
(is (= nil (find-first #(= % 2) nil )))
(is (= nil (find-first #(= % 2) [1] )))
(is (= 2 (find-first #(= % 2) [1 2 3 4] )))
(is (= 5 (find-first #(= 0 (mod % 5)) [5 10] ))))
|
112760
|
;;Copyright (c) 2017 <NAME> <<EMAIL>>
;;Distributed under the MIT License
(ns postagga.utils-test
(:require [clojure.test :refer :all]
[postagga.tools :refer :all]))
(deftest get-column-test
(testing "Get Column")
(is (= {} (get-column nil 0)))
(is (= {} (get-column {} 0)))
(is (= {[0 0] 1} (get-column {[0 0] 1} 0)))
(is (= {[0 0] 1 [1 0] 2} (get-column {[0 0] 1 [1 0] 2} 0)))
(is (= {} (get-column {[0 0] 1 [1 0] 2} 1)))
(is (= {[0 1] 3 [1 1] 4} (get-column {[0 0] 1 [1 0] 2 [0 1] 3 [1 1] 4} 1)))
(is (= {[0 0] 1 [2 0] 2} (get-column {[0 0] 1 [2 0] 2} 0))))
(deftest get-row-test
(testing "Get Row")
(is (= {} (get-row nil 0)))
(is (= {} (get-row {} 0)))
(is (= {[0 0] 1} (get-row {[0 0] 1} 0)))
(is (= {[0 0] 1 [0 1] 2} (get-row {[0 0] 1 [0 1] 2} 0)))
(is (= {} (get-row {[0 0] 1 [0 1] 2} 1)))
(is (= {[1 0] 2 [1 1] 4} (get-row {[0 0] 1 [1 0] 2 [0 1] 3 [1 1] 4} 1)))
(is (= {[0 0] 1 [0 2] 2} (get-row {[0 0] 1 [0 2] 2} 0))))
(deftest arg-max-test
(testing "Arg Max")
(is (= nil (arg-max {})))
(is (= 0 (arg-max {0 0})))
(is (= 2 (arg-max {0 1 2 3}))))
(deftest bigrams-test
(testing "Bigrams")
(is (= #{} (bigrams nil)))
(is (= #{} (bigrams "")))
(is (= #{} (bigrams "a")))
(is (= #{"ab"} (bigrams "ab")))
(is (= #{"ab" "bc"} (bigrams "abc"))))
(deftest similarity-test
(testing "Similarity")
(is (= 0 (similarity nil nil))) ; TODO: should this really be the case
(is (= 0 (similarity "" ""))) ; TODO: should this really be the case
(is (= 0 (similarity "" nil)))
(is (= 0 (similarity "a" nil)))
(is (= 0 (similarity "a" "")))
(is (= 0 (similarity "a" "a"))) ; TODO: should this really be the case???
(is (= 1 (similarity "ab" "ab")))
(is (= 1/2 (similarity "ab" "abc")))
(is (= 1/3 (similarity "ab" "abcd")))
(is (= 0 (similarity "ab" "cd"))))
(deftest are-close-within-test
(testing "Are Close Within?")
(is (= false (are-close-within? 1/4 "ab" "cd")))
(is (= true (are-close-within? 0 "ab" "cd")))
(is (= false (are-close-within? 3/4 "abc" "bcd")))
(is (= true (are-close-within? 1/4 "abc" "bcd")))
(is (= true (are-close-within? 1 "abc" "abc"))))
(deftest find-first-test
(testing "Find first")
(is (= nil (find-first #(= % 2) nil )))
(is (= nil (find-first #(= % 2) [1] )))
(is (= 2 (find-first #(= % 2) [1 2 3 4] )))
(is (= 5 (find-first #(= 0 (mod % 5)) [5 10] ))))
| true |
;;Copyright (c) 2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;Distributed under the MIT License
(ns postagga.utils-test
(:require [clojure.test :refer :all]
[postagga.tools :refer :all]))
(deftest get-column-test
(testing "Get Column")
(is (= {} (get-column nil 0)))
(is (= {} (get-column {} 0)))
(is (= {[0 0] 1} (get-column {[0 0] 1} 0)))
(is (= {[0 0] 1 [1 0] 2} (get-column {[0 0] 1 [1 0] 2} 0)))
(is (= {} (get-column {[0 0] 1 [1 0] 2} 1)))
(is (= {[0 1] 3 [1 1] 4} (get-column {[0 0] 1 [1 0] 2 [0 1] 3 [1 1] 4} 1)))
(is (= {[0 0] 1 [2 0] 2} (get-column {[0 0] 1 [2 0] 2} 0))))
(deftest get-row-test
(testing "Get Row")
(is (= {} (get-row nil 0)))
(is (= {} (get-row {} 0)))
(is (= {[0 0] 1} (get-row {[0 0] 1} 0)))
(is (= {[0 0] 1 [0 1] 2} (get-row {[0 0] 1 [0 1] 2} 0)))
(is (= {} (get-row {[0 0] 1 [0 1] 2} 1)))
(is (= {[1 0] 2 [1 1] 4} (get-row {[0 0] 1 [1 0] 2 [0 1] 3 [1 1] 4} 1)))
(is (= {[0 0] 1 [0 2] 2} (get-row {[0 0] 1 [0 2] 2} 0))))
(deftest arg-max-test
(testing "Arg Max")
(is (= nil (arg-max {})))
(is (= 0 (arg-max {0 0})))
(is (= 2 (arg-max {0 1 2 3}))))
(deftest bigrams-test
(testing "Bigrams")
(is (= #{} (bigrams nil)))
(is (= #{} (bigrams "")))
(is (= #{} (bigrams "a")))
(is (= #{"ab"} (bigrams "ab")))
(is (= #{"ab" "bc"} (bigrams "abc"))))
(deftest similarity-test
(testing "Similarity")
(is (= 0 (similarity nil nil))) ; TODO: should this really be the case
(is (= 0 (similarity "" ""))) ; TODO: should this really be the case
(is (= 0 (similarity "" nil)))
(is (= 0 (similarity "a" nil)))
(is (= 0 (similarity "a" "")))
(is (= 0 (similarity "a" "a"))) ; TODO: should this really be the case???
(is (= 1 (similarity "ab" "ab")))
(is (= 1/2 (similarity "ab" "abc")))
(is (= 1/3 (similarity "ab" "abcd")))
(is (= 0 (similarity "ab" "cd"))))
(deftest are-close-within-test
(testing "Are Close Within?")
(is (= false (are-close-within? 1/4 "ab" "cd")))
(is (= true (are-close-within? 0 "ab" "cd")))
(is (= false (are-close-within? 3/4 "abc" "bcd")))
(is (= true (are-close-within? 1/4 "abc" "bcd")))
(is (= true (are-close-within? 1 "abc" "abc"))))
(deftest find-first-test
(testing "Find first")
(is (= nil (find-first #(= % 2) nil )))
(is (= nil (find-first #(= % 2) [1] )))
(is (= 2 (find-first #(= % 2) [1 2 3 4] )))
(is (= 5 (find-first #(= 0 (mod % 5)) [5 10] ))))
|
[
{
"context": "id (ref/new 1755))\n (restaurant-name (ref/new \"Venezia\"))\n (customer-name (ref/new \"Jan Kowalski\"))\n ",
"end": 1384,
"score": 0.991719126701355,
"start": 1377,
"tag": "NAME",
"value": "Venezia"
},
{
"context": "(ref/new \"Venezia\"))\n (customer-name (ref/new \"Jan Kowalski\"))\n (customer-phone (ref/new \"123\"))\n (conf",
"end": 1429,
"score": 0.9997074007987976,
"start": 1417,
"tag": "NAME",
"value": "Jan Kowalski"
}
] |
example/foo.clj
|
zyla/random-lisp
| 0 |
(declare dynamic/pure : (forall [a] (-> [a] (Dynamic a))))
(declare dynamic/bind :
(forall [a b]
(-> [(Dynamic a) (-> [a] (Dynamic b))] (Dynamic b))))
(declare dynamic/subscribe :
(forall [a]
(-> [(Dynamic a) (-> [a] Unit)] Unit)))
(declare dynamic/read :
(forall [a]
(-> [(Dynamic a)] a)))
(declare ref/new :
(forall [a]
(-> [a] (Dynamic a))))
(declare ref/write :
(forall [a]
(-> [(Dynamic a) (Dynamic a)] Unit)))
(defn debug-subscribe [(name String) (dyn (Dynamic Int))]
(dynamic/subscribe dyn (fn [(x Int)] (print (concat (concat name ": ") (int->string x))))))
(declare el : (-> [String (Array Prop) (-> [] Unit)] Unit))
(declare text : (-> [(Dynamic String)] Unit))
(declare on-click : (-> [(-> [] Unit)] Prop))
(declare on-input : (-> [(-> [String] Unit)] Prop))
(declare attr : (-> [String (Dynamic String)] Prop))
(declare attr-if : (-> [(Dynamic Boolean) String (Dynamic String)] Prop))
(declare render-in-body : (-> [(-> [] Unit)] Unit))
; Hack, as we can't yet type an empty array
(declare no-props : (Array Prop))
(defn text-input [(props (Array Prop)) (ref (Dynamic String))]
(el "input"
(array/concat props
[(on-input (fn [(value String)] (ref/write ref value)))
(attr "value" ref)])
(fn [] (do))))
(def order-example
(let [
(order-id (ref/new 1755))
(restaurant-name (ref/new "Venezia"))
(customer-name (ref/new "Jan Kowalski"))
(customer-phone (ref/new "123"))
(confirmed (ref/new false))
(details-row
(fn [(label String) (body (-> [] Unit))]
(el "tr" no-props (fn []
(el "th" no-props (fn [] (text label)))
(el "td" no-props body)
))))
]
(render-in-body (fn []
(el "table" no-props (fn []
(details-row "Order id" (fn [] (text (int->string order-id))))
(details-row "Restaurant" (fn [] (text restaurant-name)))
(details-row "Customer" (fn [] (text (concat (concat customer-name ", ") customer-phone))))
(details-row "Status" (fn [] (text (if confirmed "Confirmed" "Waiting"))))
))
(el "div" no-props (fn []
(el "label" no-props (fn [] (text "Customer name: ")))
(text-input no-props customer-name)))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write customer-phone (concat customer-phone "7"))))]
(fn [] (text "Change phone")))))
(el "div" no-props (fn []
(el "label" no-props (fn [] (text "Restaurant: ")))
(text-input no-props restaurant-name)))
(el "div" no-props (fn []
(el "button"
[(on-click (fn [] (ref/write confirmed true)))
(attr-if confirmed "disabled" "disabled") ]
(fn [] (text "Confirm")))))
(el "div" no-props (fn []
(el "button"
[(on-click (fn [] (ref/write confirmed false)))
(attr-if (not confirmed) "disabled" "disabled") ]
(fn [] (text "Unconfirm")))))
)))
)
(def counter-example
(let [
(count (ref/new 0))
]
(render-in-body (fn []
(el "h2" no-props (fn [] (text "Counter")))
(el "div" no-props (fn [] (text (int->string count))))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write count (+ count 1))))]
(fn [] (text "Increment")))))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write count (- count 1))))]
(fn [] (text "Decrement")))))
))
))
|
37369
|
(declare dynamic/pure : (forall [a] (-> [a] (Dynamic a))))
(declare dynamic/bind :
(forall [a b]
(-> [(Dynamic a) (-> [a] (Dynamic b))] (Dynamic b))))
(declare dynamic/subscribe :
(forall [a]
(-> [(Dynamic a) (-> [a] Unit)] Unit)))
(declare dynamic/read :
(forall [a]
(-> [(Dynamic a)] a)))
(declare ref/new :
(forall [a]
(-> [a] (Dynamic a))))
(declare ref/write :
(forall [a]
(-> [(Dynamic a) (Dynamic a)] Unit)))
(defn debug-subscribe [(name String) (dyn (Dynamic Int))]
(dynamic/subscribe dyn (fn [(x Int)] (print (concat (concat name ": ") (int->string x))))))
(declare el : (-> [String (Array Prop) (-> [] Unit)] Unit))
(declare text : (-> [(Dynamic String)] Unit))
(declare on-click : (-> [(-> [] Unit)] Prop))
(declare on-input : (-> [(-> [String] Unit)] Prop))
(declare attr : (-> [String (Dynamic String)] Prop))
(declare attr-if : (-> [(Dynamic Boolean) String (Dynamic String)] Prop))
(declare render-in-body : (-> [(-> [] Unit)] Unit))
; Hack, as we can't yet type an empty array
(declare no-props : (Array Prop))
(defn text-input [(props (Array Prop)) (ref (Dynamic String))]
(el "input"
(array/concat props
[(on-input (fn [(value String)] (ref/write ref value)))
(attr "value" ref)])
(fn [] (do))))
(def order-example
(let [
(order-id (ref/new 1755))
(restaurant-name (ref/new "<NAME>"))
(customer-name (ref/new "<NAME>"))
(customer-phone (ref/new "123"))
(confirmed (ref/new false))
(details-row
(fn [(label String) (body (-> [] Unit))]
(el "tr" no-props (fn []
(el "th" no-props (fn [] (text label)))
(el "td" no-props body)
))))
]
(render-in-body (fn []
(el "table" no-props (fn []
(details-row "Order id" (fn [] (text (int->string order-id))))
(details-row "Restaurant" (fn [] (text restaurant-name)))
(details-row "Customer" (fn [] (text (concat (concat customer-name ", ") customer-phone))))
(details-row "Status" (fn [] (text (if confirmed "Confirmed" "Waiting"))))
))
(el "div" no-props (fn []
(el "label" no-props (fn [] (text "Customer name: ")))
(text-input no-props customer-name)))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write customer-phone (concat customer-phone "7"))))]
(fn [] (text "Change phone")))))
(el "div" no-props (fn []
(el "label" no-props (fn [] (text "Restaurant: ")))
(text-input no-props restaurant-name)))
(el "div" no-props (fn []
(el "button"
[(on-click (fn [] (ref/write confirmed true)))
(attr-if confirmed "disabled" "disabled") ]
(fn [] (text "Confirm")))))
(el "div" no-props (fn []
(el "button"
[(on-click (fn [] (ref/write confirmed false)))
(attr-if (not confirmed) "disabled" "disabled") ]
(fn [] (text "Unconfirm")))))
)))
)
(def counter-example
(let [
(count (ref/new 0))
]
(render-in-body (fn []
(el "h2" no-props (fn [] (text "Counter")))
(el "div" no-props (fn [] (text (int->string count))))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write count (+ count 1))))]
(fn [] (text "Increment")))))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write count (- count 1))))]
(fn [] (text "Decrement")))))
))
))
| true |
(declare dynamic/pure : (forall [a] (-> [a] (Dynamic a))))
(declare dynamic/bind :
(forall [a b]
(-> [(Dynamic a) (-> [a] (Dynamic b))] (Dynamic b))))
(declare dynamic/subscribe :
(forall [a]
(-> [(Dynamic a) (-> [a] Unit)] Unit)))
(declare dynamic/read :
(forall [a]
(-> [(Dynamic a)] a)))
(declare ref/new :
(forall [a]
(-> [a] (Dynamic a))))
(declare ref/write :
(forall [a]
(-> [(Dynamic a) (Dynamic a)] Unit)))
(defn debug-subscribe [(name String) (dyn (Dynamic Int))]
(dynamic/subscribe dyn (fn [(x Int)] (print (concat (concat name ": ") (int->string x))))))
(declare el : (-> [String (Array Prop) (-> [] Unit)] Unit))
(declare text : (-> [(Dynamic String)] Unit))
(declare on-click : (-> [(-> [] Unit)] Prop))
(declare on-input : (-> [(-> [String] Unit)] Prop))
(declare attr : (-> [String (Dynamic String)] Prop))
(declare attr-if : (-> [(Dynamic Boolean) String (Dynamic String)] Prop))
(declare render-in-body : (-> [(-> [] Unit)] Unit))
; Hack, as we can't yet type an empty array
(declare no-props : (Array Prop))
(defn text-input [(props (Array Prop)) (ref (Dynamic String))]
(el "input"
(array/concat props
[(on-input (fn [(value String)] (ref/write ref value)))
(attr "value" ref)])
(fn [] (do))))
(def order-example
(let [
(order-id (ref/new 1755))
(restaurant-name (ref/new "PI:NAME:<NAME>END_PI"))
(customer-name (ref/new "PI:NAME:<NAME>END_PI"))
(customer-phone (ref/new "123"))
(confirmed (ref/new false))
(details-row
(fn [(label String) (body (-> [] Unit))]
(el "tr" no-props (fn []
(el "th" no-props (fn [] (text label)))
(el "td" no-props body)
))))
]
(render-in-body (fn []
(el "table" no-props (fn []
(details-row "Order id" (fn [] (text (int->string order-id))))
(details-row "Restaurant" (fn [] (text restaurant-name)))
(details-row "Customer" (fn [] (text (concat (concat customer-name ", ") customer-phone))))
(details-row "Status" (fn [] (text (if confirmed "Confirmed" "Waiting"))))
))
(el "div" no-props (fn []
(el "label" no-props (fn [] (text "Customer name: ")))
(text-input no-props customer-name)))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write customer-phone (concat customer-phone "7"))))]
(fn [] (text "Change phone")))))
(el "div" no-props (fn []
(el "label" no-props (fn [] (text "Restaurant: ")))
(text-input no-props restaurant-name)))
(el "div" no-props (fn []
(el "button"
[(on-click (fn [] (ref/write confirmed true)))
(attr-if confirmed "disabled" "disabled") ]
(fn [] (text "Confirm")))))
(el "div" no-props (fn []
(el "button"
[(on-click (fn [] (ref/write confirmed false)))
(attr-if (not confirmed) "disabled" "disabled") ]
(fn [] (text "Unconfirm")))))
)))
)
(def counter-example
(let [
(count (ref/new 0))
]
(render-in-body (fn []
(el "h2" no-props (fn [] (text "Counter")))
(el "div" no-props (fn [] (text (int->string count))))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write count (+ count 1))))]
(fn [] (text "Increment")))))
(el "div" no-props (fn []
(el "button" [(on-click (fn [] (ref/write count (- count 1))))]
(fn [] (text "Decrement")))))
))
))
|
[
{
"context": "name)\n :user \"sa\"\n :password \"scott_tiger\"})\n\n (with-connection db\n\t(drop-table :cities)\n\t",
"end": 1654,
"score": 0.9991151690483093,
"start": 1643,
"tag": "PASSWORD",
"value": "scott_tiger"
}
] |
mssql/clojure/create/mssql_create.clj
|
ekzemplaro/data_base_language
| 3 |
; -----------------------------------------------------------------
;
; mssql_create.clj
;
; Jul/17/2014
;
; -----------------------------------------------------------------
(import '(java.util Date))
(import '(java.text SimpleDateFormat))
(use 'clojure.java.jdbc)
; -----------------------------------------------------------------
(defn insert_proc []
(insert-values :cities
[:id :name :population :date_mod] ["t1071" "前橋" 98732 "1970-4-22"])
(insert-values :cities
[:id :name :population :date_mod] ["t1072" "高崎" 31456 "1970-7-19"])
(insert-values :cities
[:id :name :population :date_mod] ["t1073" "桐生" 65182 "1970-5-15"])
(insert-values :cities
[:id :name :population :date_mod] ["t1074" "沼田" 42971 "1970-11-21"])
(insert-values :cities
[:id :name :population :date_mod] ["t1075" "伊勢崎" 86513 "1970-10-7"])
(insert-values :cities
[:id :name :population :date_mod] ["t1076" "水上" 41672 "1970-7-12"])
(insert-values :cities
[:id :name :population :date_mod] ["t1077" "太田" 82547 "1970-2-24"])
(insert-values :cities
[:id :name :population :date_mod] ["t1078" "安中" 74298 "1970-5-21"])
(insert-values :cities
[:id :name :population :date_mod] ["t1079" "みどり" 43596 "1970-9-17"])
)
; -----------------------------------------------------------------
(println "*** 開始 ***")
(let [db-host "host_mssql;"
db-name "databaseName=city"]
(def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver"
:subprotocol "sqlserver"
:subname (str "//" db-host db-name)
:user "sa"
:password "scott_tiger"})
(with-connection db
(drop-table :cities)
(create-table :cities
[:id "varchar(10)" "PRIMARY KEY"]
[:name "nvarchar(20)"]
[:population :int]
[:date_mod :datetime])
(insert_proc)
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
|
5432
|
; -----------------------------------------------------------------
;
; mssql_create.clj
;
; Jul/17/2014
;
; -----------------------------------------------------------------
(import '(java.util Date))
(import '(java.text SimpleDateFormat))
(use 'clojure.java.jdbc)
; -----------------------------------------------------------------
(defn insert_proc []
(insert-values :cities
[:id :name :population :date_mod] ["t1071" "前橋" 98732 "1970-4-22"])
(insert-values :cities
[:id :name :population :date_mod] ["t1072" "高崎" 31456 "1970-7-19"])
(insert-values :cities
[:id :name :population :date_mod] ["t1073" "桐生" 65182 "1970-5-15"])
(insert-values :cities
[:id :name :population :date_mod] ["t1074" "沼田" 42971 "1970-11-21"])
(insert-values :cities
[:id :name :population :date_mod] ["t1075" "伊勢崎" 86513 "1970-10-7"])
(insert-values :cities
[:id :name :population :date_mod] ["t1076" "水上" 41672 "1970-7-12"])
(insert-values :cities
[:id :name :population :date_mod] ["t1077" "太田" 82547 "1970-2-24"])
(insert-values :cities
[:id :name :population :date_mod] ["t1078" "安中" 74298 "1970-5-21"])
(insert-values :cities
[:id :name :population :date_mod] ["t1079" "みどり" 43596 "1970-9-17"])
)
; -----------------------------------------------------------------
(println "*** 開始 ***")
(let [db-host "host_mssql;"
db-name "databaseName=city"]
(def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver"
:subprotocol "sqlserver"
:subname (str "//" db-host db-name)
:user "sa"
:password "<PASSWORD>"})
(with-connection db
(drop-table :cities)
(create-table :cities
[:id "varchar(10)" "PRIMARY KEY"]
[:name "nvarchar(20)"]
[:population :int]
[:date_mod :datetime])
(insert_proc)
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
| true |
; -----------------------------------------------------------------
;
; mssql_create.clj
;
; Jul/17/2014
;
; -----------------------------------------------------------------
(import '(java.util Date))
(import '(java.text SimpleDateFormat))
(use 'clojure.java.jdbc)
; -----------------------------------------------------------------
(defn insert_proc []
(insert-values :cities
[:id :name :population :date_mod] ["t1071" "前橋" 98732 "1970-4-22"])
(insert-values :cities
[:id :name :population :date_mod] ["t1072" "高崎" 31456 "1970-7-19"])
(insert-values :cities
[:id :name :population :date_mod] ["t1073" "桐生" 65182 "1970-5-15"])
(insert-values :cities
[:id :name :population :date_mod] ["t1074" "沼田" 42971 "1970-11-21"])
(insert-values :cities
[:id :name :population :date_mod] ["t1075" "伊勢崎" 86513 "1970-10-7"])
(insert-values :cities
[:id :name :population :date_mod] ["t1076" "水上" 41672 "1970-7-12"])
(insert-values :cities
[:id :name :population :date_mod] ["t1077" "太田" 82547 "1970-2-24"])
(insert-values :cities
[:id :name :population :date_mod] ["t1078" "安中" 74298 "1970-5-21"])
(insert-values :cities
[:id :name :population :date_mod] ["t1079" "みどり" 43596 "1970-9-17"])
)
; -----------------------------------------------------------------
(println "*** 開始 ***")
(let [db-host "host_mssql;"
db-name "databaseName=city"]
(def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver"
:subprotocol "sqlserver"
:subname (str "//" db-host db-name)
:user "sa"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(with-connection db
(drop-table :cities)
(create-table :cities
[:id "varchar(10)" "PRIMARY KEY"]
[:name "nvarchar(20)"]
[:population :int]
[:date_mod :datetime])
(insert_proc)
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
|
[
{
"context": " :user (or (get-session-id) \"Anonimo\")}))\n\n;;start rodadas grid\n(def search-columns\n ",
"end": 537,
"score": 0.9193453788757324,
"start": 530,
"tag": "USERNAME",
"value": "Anonimo"
},
{
"context": " search (cond\n (= user \"Anonimo\") (grid-search-extra search \"anonimo = 'T' and ro",
"end": 1830,
"score": 0.7317480444908142,
"start": 1823,
"tag": "NAME",
"value": "Anonimo"
},
{
"context": " \"Mi nombre es <strong>\" user \"</strong> y mi correo electronico es <a href='ma",
"end": 3572,
"score": 0.9588636755943298,
"start": 3568,
"tag": "USERNAME",
"value": "user"
},
{
"context": "exicali. se aceptan sugerencias. <a href='mailto: [email protected]'>Clic aquí para mandar sugerencias</a></small>\")\n",
"end": 4139,
"score": 0.9999260306358337,
"start": 4116,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "a></small>\")\n body {:from \"[email protected]\"\n :to leader_email",
"end": 4249,
"score": 0.9999282360076904,
"start": 4226,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "leader_email\n :cc \"[email protected]\"\n :subject (str descrip",
"end": 4360,
"score": 0.9999266862869263,
"start": 4337,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "rams))\n user (or (get-session-id) \"Anonimo\")\n repetir (if (= user \"Anonimo\") \"F",
"end": 6287,
"score": 0.4386727809906006,
"start": 6285,
"tag": "NAME",
"value": "on"
},
{
"context": "ms))\n user (or (get-session-id) \"Anonimo\")\n repetir (if (= user \"Anonimo\") \"F\" (",
"end": 6290,
"score": 0.4839896857738495,
"start": 6287,
"tag": "USERNAME",
"value": "imo"
},
{
"context": "on-id) \"Anonimo\")\n repetir (if (= user \"Anonimo\") \"F\" (:repetir params))\n anonimo (if (",
"end": 6332,
"score": 0.5944311618804932,
"start": 6325,
"tag": "NAME",
"value": "Anonimo"
},
{
"context": ":repetir params))\n anonimo (if (= user \"Anonimo\") \"T\" \"F\")\n postvars {:id ",
"end": 6397,
"score": 0.719135046005249,
"start": 6390,
"tag": "NAME",
"value": "Anonimo"
},
{
"context": "exicali. se aceptan sugerencias. <a href='mailto: [email protected]'>Clic aquí para mandar sugerencias</a></small>\")\n",
"end": 8651,
"score": 0.9999302625656128,
"start": 8628,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " rodadas_id)\n body {:from \"[email protected]\"\n :to recipients\n ",
"end": 8817,
"score": 0.9999315738677979,
"start": 8794,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " recipients\n :cc \"[email protected]\"\n :subject (str descrip",
"end": 8926,
"score": 0.9999321699142456,
"start": 8903,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/cc/routes/entrenamiento/rodadas.clj
|
hectorqlucero/cc
| 3 |
(ns cc.routes.entrenamiento.rodadas
(:require [cc.models.crud :refer :all]
[cc.models.email :refer [host send-email]]
[cc.models.grid :refer :all]
[cc.models.util :refer :all]
[cheshire.core :refer :all]
[compojure.core :refer :all]
[selmer.parser :refer [render-file]]))
(defn rodadas
[]
(render-file "entrenamiento/rodadas/index.html" {:title "Entrenamiento - Rodadas"
:user (or (get-session-id) "Anonimo")}))
;;start rodadas grid
(def search-columns
["id"
"descripcion_corta"
"descripcion"
"punto_reunion"
"CASE WHEN nivel = 'P' THEN 'Principiantes' WHEN nivel = 'M' THEN 'Medio' WHEN nivel = 'A' THEN 'Avanzado' WHEN nivel = 'T' THEN 'TODOS' END"
"distancia"
"velocidad"
"CASE WHEN repetir = 'T' THEN 'Si' ELSE 'No' END"
"DATE_FORMAT(fecha,'%m/%d/%Y')"
"TIME_FORMAT(hora,'%h:%i %p')"
"leader"])
(def aliases-columns
["id"
"descripcion_corta"
"descripcion"
"CASE WHEN nivel = 'P' THEN 'Principiantes' WHEN nivel = 'M' THEN 'Medio' WHEN nivel = 'A' THEN 'Avanzado' WHEN nivel = 'T' THEN 'TODOS' END AS nivel"
"distancia"
"velocidad"
"punto_reunion"
"CASE WHEN repetir = 'T' THEN 'Si' ELSE 'No' END as repetir"
"DATE_FORMAT(fecha,'%m/%d/%Y') as fecha"
"TIME_FORMAT(hora,'%h:%i %p') as hora"
"leader"])
(defn grid-json
[{params :params}]
(try
(let [table "rodadas"
user (or (get-session-id) "Anonimo")
level (user-level)
email (user-email)
scolumns (convert-search-columns search-columns)
aliases aliases-columns
join ""
search (grid-search (:search params nil) scolumns)
search (cond
(= user "Anonimo") (grid-search-extra search "anonimo = 'T' and rodada = 'T'")
(= level "U") (grid-search-extra search (str "leader_email = '" email "'" " and rodada = 'T'"))
(= level "A") (grid-search-extra search (str "leader_email = '" email "'" " and rodada = 'T'"))
:else (grid-search-extra search "rodada = 'T'"))
order (grid-sort (:sort params nil) (:order params nil))
offset (grid-offset (parse-int (:rows params)) (parse-int (:page params)))
sql (grid-sql table aliases join search order offset)
rows (grid-rows table aliases join search order offset)]
(generate-string rows))
(catch Exception e (.getMessage e))))
;;end rodadas grid
;;start rodadas form
(def form-sql
"SELECT id as id,
descripcion,
descripcion_corta,
punto_reunion,
nivel,
distancia,
velocidad,
DATE_FORMAT(fecha,'%m/%d/%Y') as fecha,
TIME_FORMAT(hora,'%H:%i') as hora,
leader,
leader_email,
cuadrante,
repetir,
anonimo
FROM rodadas
WHERE id = ?")
(defn form-json
[id]
(try
(let [row (Query db [form-sql id])]
(generate-string (first row)))
(catch Exception e (.getMessage e))))
;;end rodadas form
;;Start form-assistir
(defn email-body [rodadas_id user email comentarios asistir_desc]
(let [row (first (Query db ["SELECT leader,leader_email,descripcion_corta FROM rodadas WHERE id = ?" rodadas_id]))
leader (:leader row)
leader_email (:leader_email row)
descripcion_corta (:descripcion_corta row)
content (str "<strong>Hola " leader ":</strong></br></br>"
"Mi nombre es <strong>" user "</strong> y mi correo electronico es <a href='mailto:" email "'>" email "</a> y estoy confirmando que <strong>" asistir_desc "</strong> al evento.</br>"
"<small><strong>Nota:</strong><i> Si desea contestarle a esta persona, por favor hacer clic en el email arriba!</i></br></br>"
"<strong>Comentarios:</strong> " comentarios "</br></br>"
"<small>Esta es un aplicación para todos los ciclistas de Mexicali. se aceptan sugerencias. <a href='mailto: [email protected]'>Clic aquí para mandar sugerencias</a></small>")
body {:from "[email protected]"
:to leader_email
:cc "[email protected]"
:subject (str descripcion_corta " - Confirmar asistencia")
:body [{:type "text/html;charset=utf-8"
:content content}]}]
body))
(defn form-asistir
[rodadas_id]
(let [row (first (Query db ["select descripcion_corta,DATE_FORMAT(fecha,'%m/%d/%Y') as fecha,TIME_FORMAT(hora,'%h:%i %p') as hora from rodadas where id = ?" rodadas_id]))
event_desc (:descripcion_corta row)
fecha (:fecha row)
hora (:hora row)
title (str fecha " - " hora " [" event_desc "] Confirmar asistencia")]
(render-file "entrenamiento/rodadas/asistir.html" {:title title
:rodadas_id rodadas_id})))
(defn form-asistir-save
[{params :params}]
(try
(let [rodadas_id (fix-id (:rodadas_id params))
email (:email params)
asistir_desc (if (= (:asistir params) "T")
"ASISTIRE"
"NO ASISTIRE")
postvars {:rodadas_id rodadas_id
:user (:user params)
:comentarios (:comentarios params)
:email email
:asistir (:asistir params)}
body (email-body rodadas_id (:user params) email (:comentarios params) asistir_desc)
result (Save db :rodadas_link postvars ["rodadas_id = ? and email = ?" rodadas_id email])]
(if (seq result)
(do
(send-email host body)
(generate-string {:success "Correctamente Processado!"}))
(generate-string {:error "No se pudo processar!"})))
(catch Exception e (.getMessage e))))
;;End form-assistir
(defn rodadas-save
[{params :params}]
(try
(let [id (fix-id (:id params))
user (or (get-session-id) "Anonimo")
repetir (if (= user "Anonimo") "F" (:repetir params))
anonimo (if (= user "Anonimo") "T" "F")
postvars {:id id
:descripcion (:descripcion params)
:descripcion_corta (:descripcion_corta params)
:punto_reunion (:punto_reunion params)
:nivel (:nivel params)
:distancia (:distancia params)
:velocidad (:velocidad params)
:fecha (format-date-internal (:fecha params))
:hora (fix-hour (:hora params))
:leader (:leader params)
:leader_email (:leader_email params)
:cuadrante (:cuadrante params)
:repetir repetir
:anonimo anonimo}
result (Save db :rodadas postvars ["id = ?" id])]
(if (seq result)
(generate-string {:success "Correctamente Processado!"})
(generate-string {:error "No se pudo processar!"})))
(catch Exception e (.getMessage e))))
;;Start rodadas-delete
(defn build-recipients [rodadas_id]
(into [] (map #(first (vals %)) (Query db ["SELECT email from rodadas_link where rodadas_id = ?" rodadas_id]))))
(defn email-delete-body [rodadas_id]
(let [row (first (Query db ["SELECT leader,leader_email,descripcion_corta FROM rodadas where id = ?" rodadas_id]))
leader (:leader row)
leader_email (:leader_email row)
descripcion_corta (:descripcion_corta row)
content (str "<strong>Hola:</strong></br></br>La rodada organizada por: " leader " <a href='mailto:" leader_email "'>" leader_email "</a> se cancelo. Disculpen la inconveniencia que esto pueda causar.</br>"
"<small><strong>Nota:</strong><i> Si desea contestarle a esta persona, por favor hacer clic en el email arriba!</i></br></br>"
"Muchas gracias por su participacion y esperamos que la proxima vez se pueda realizar la rodada.</br></br>"
"<small>Esta es un aplicación para todos los ciclistas de Mexicali. se aceptan sugerencias. <a href='mailto: [email protected]'>Clic aquí para mandar sugerencias</a></small>")
recipients (build-recipients rodadas_id)
body {:from "[email protected]"
:to recipients
:cc "[email protected]"
:subject (str descripcion_corta " - Cancelacion")
:body [{:type "text/html;charset=utf-8"
:content content}]}]
body))
(defn rodadas-delete
[{params :params}]
(try
(let [id (:id params nil)
result (if-not (nil? id)
(do
(send-email host (email-delete-body id))
(Delete db :rodadas ["id = ?" id]))
nil)]
(if (seq result)
(generate-string {:success "Removido appropiadamente!"})
(generate-string {:error "No se pudo remover!"})))
(catch Exception e (.getMessage e))))
;;End rodadas-delete
(defroutes rodadas-routes
(GET "/entrenamiento/rodadas" [] (rodadas))
(POST "/entrenamiento/rodadas/json/grid" request (grid-json request))
(GET "/entrenamiento/rodadas/json/form/:id" [id] (form-json id))
(GET "/entrenamiento/rodadas/asistir/:id" [id] (form-asistir id))
(POST "/entrenamiento/rodadas/asistir" request [] (form-asistir-save request))
(POST "/entrenamiento/rodadas/save" request [] (rodadas-save request))
(POST "/entrenamiento/rodadas/delete" request [] (rodadas-delete request)))
|
45980
|
(ns cc.routes.entrenamiento.rodadas
(:require [cc.models.crud :refer :all]
[cc.models.email :refer [host send-email]]
[cc.models.grid :refer :all]
[cc.models.util :refer :all]
[cheshire.core :refer :all]
[compojure.core :refer :all]
[selmer.parser :refer [render-file]]))
(defn rodadas
[]
(render-file "entrenamiento/rodadas/index.html" {:title "Entrenamiento - Rodadas"
:user (or (get-session-id) "Anonimo")}))
;;start rodadas grid
(def search-columns
["id"
"descripcion_corta"
"descripcion"
"punto_reunion"
"CASE WHEN nivel = 'P' THEN 'Principiantes' WHEN nivel = 'M' THEN 'Medio' WHEN nivel = 'A' THEN 'Avanzado' WHEN nivel = 'T' THEN 'TODOS' END"
"distancia"
"velocidad"
"CASE WHEN repetir = 'T' THEN 'Si' ELSE 'No' END"
"DATE_FORMAT(fecha,'%m/%d/%Y')"
"TIME_FORMAT(hora,'%h:%i %p')"
"leader"])
(def aliases-columns
["id"
"descripcion_corta"
"descripcion"
"CASE WHEN nivel = 'P' THEN 'Principiantes' WHEN nivel = 'M' THEN 'Medio' WHEN nivel = 'A' THEN 'Avanzado' WHEN nivel = 'T' THEN 'TODOS' END AS nivel"
"distancia"
"velocidad"
"punto_reunion"
"CASE WHEN repetir = 'T' THEN 'Si' ELSE 'No' END as repetir"
"DATE_FORMAT(fecha,'%m/%d/%Y') as fecha"
"TIME_FORMAT(hora,'%h:%i %p') as hora"
"leader"])
(defn grid-json
[{params :params}]
(try
(let [table "rodadas"
user (or (get-session-id) "Anonimo")
level (user-level)
email (user-email)
scolumns (convert-search-columns search-columns)
aliases aliases-columns
join ""
search (grid-search (:search params nil) scolumns)
search (cond
(= user "<NAME>") (grid-search-extra search "anonimo = 'T' and rodada = 'T'")
(= level "U") (grid-search-extra search (str "leader_email = '" email "'" " and rodada = 'T'"))
(= level "A") (grid-search-extra search (str "leader_email = '" email "'" " and rodada = 'T'"))
:else (grid-search-extra search "rodada = 'T'"))
order (grid-sort (:sort params nil) (:order params nil))
offset (grid-offset (parse-int (:rows params)) (parse-int (:page params)))
sql (grid-sql table aliases join search order offset)
rows (grid-rows table aliases join search order offset)]
(generate-string rows))
(catch Exception e (.getMessage e))))
;;end rodadas grid
;;start rodadas form
(def form-sql
"SELECT id as id,
descripcion,
descripcion_corta,
punto_reunion,
nivel,
distancia,
velocidad,
DATE_FORMAT(fecha,'%m/%d/%Y') as fecha,
TIME_FORMAT(hora,'%H:%i') as hora,
leader,
leader_email,
cuadrante,
repetir,
anonimo
FROM rodadas
WHERE id = ?")
(defn form-json
[id]
(try
(let [row (Query db [form-sql id])]
(generate-string (first row)))
(catch Exception e (.getMessage e))))
;;end rodadas form
;;Start form-assistir
(defn email-body [rodadas_id user email comentarios asistir_desc]
(let [row (first (Query db ["SELECT leader,leader_email,descripcion_corta FROM rodadas WHERE id = ?" rodadas_id]))
leader (:leader row)
leader_email (:leader_email row)
descripcion_corta (:descripcion_corta row)
content (str "<strong>Hola " leader ":</strong></br></br>"
"Mi nombre es <strong>" user "</strong> y mi correo electronico es <a href='mailto:" email "'>" email "</a> y estoy confirmando que <strong>" asistir_desc "</strong> al evento.</br>"
"<small><strong>Nota:</strong><i> Si desea contestarle a esta persona, por favor hacer clic en el email arriba!</i></br></br>"
"<strong>Comentarios:</strong> " comentarios "</br></br>"
"<small>Esta es un aplicación para todos los ciclistas de Mexicali. se aceptan sugerencias. <a href='mailto: <EMAIL>'>Clic aquí para mandar sugerencias</a></small>")
body {:from "<EMAIL>"
:to leader_email
:cc "<EMAIL>"
:subject (str descripcion_corta " - Confirmar asistencia")
:body [{:type "text/html;charset=utf-8"
:content content}]}]
body))
(defn form-asistir
[rodadas_id]
(let [row (first (Query db ["select descripcion_corta,DATE_FORMAT(fecha,'%m/%d/%Y') as fecha,TIME_FORMAT(hora,'%h:%i %p') as hora from rodadas where id = ?" rodadas_id]))
event_desc (:descripcion_corta row)
fecha (:fecha row)
hora (:hora row)
title (str fecha " - " hora " [" event_desc "] Confirmar asistencia")]
(render-file "entrenamiento/rodadas/asistir.html" {:title title
:rodadas_id rodadas_id})))
(defn form-asistir-save
[{params :params}]
(try
(let [rodadas_id (fix-id (:rodadas_id params))
email (:email params)
asistir_desc (if (= (:asistir params) "T")
"ASISTIRE"
"NO ASISTIRE")
postvars {:rodadas_id rodadas_id
:user (:user params)
:comentarios (:comentarios params)
:email email
:asistir (:asistir params)}
body (email-body rodadas_id (:user params) email (:comentarios params) asistir_desc)
result (Save db :rodadas_link postvars ["rodadas_id = ? and email = ?" rodadas_id email])]
(if (seq result)
(do
(send-email host body)
(generate-string {:success "Correctamente Processado!"}))
(generate-string {:error "No se pudo processar!"})))
(catch Exception e (.getMessage e))))
;;End form-assistir
(defn rodadas-save
[{params :params}]
(try
(let [id (fix-id (:id params))
user (or (get-session-id) "An<NAME>imo")
repetir (if (= user "<NAME>") "F" (:repetir params))
anonimo (if (= user "<NAME>") "T" "F")
postvars {:id id
:descripcion (:descripcion params)
:descripcion_corta (:descripcion_corta params)
:punto_reunion (:punto_reunion params)
:nivel (:nivel params)
:distancia (:distancia params)
:velocidad (:velocidad params)
:fecha (format-date-internal (:fecha params))
:hora (fix-hour (:hora params))
:leader (:leader params)
:leader_email (:leader_email params)
:cuadrante (:cuadrante params)
:repetir repetir
:anonimo anonimo}
result (Save db :rodadas postvars ["id = ?" id])]
(if (seq result)
(generate-string {:success "Correctamente Processado!"})
(generate-string {:error "No se pudo processar!"})))
(catch Exception e (.getMessage e))))
;;Start rodadas-delete
(defn build-recipients [rodadas_id]
(into [] (map #(first (vals %)) (Query db ["SELECT email from rodadas_link where rodadas_id = ?" rodadas_id]))))
(defn email-delete-body [rodadas_id]
(let [row (first (Query db ["SELECT leader,leader_email,descripcion_corta FROM rodadas where id = ?" rodadas_id]))
leader (:leader row)
leader_email (:leader_email row)
descripcion_corta (:descripcion_corta row)
content (str "<strong>Hola:</strong></br></br>La rodada organizada por: " leader " <a href='mailto:" leader_email "'>" leader_email "</a> se cancelo. Disculpen la inconveniencia que esto pueda causar.</br>"
"<small><strong>Nota:</strong><i> Si desea contestarle a esta persona, por favor hacer clic en el email arriba!</i></br></br>"
"Muchas gracias por su participacion y esperamos que la proxima vez se pueda realizar la rodada.</br></br>"
"<small>Esta es un aplicación para todos los ciclistas de Mexicali. se aceptan sugerencias. <a href='mailto: <EMAIL>'>Clic aquí para mandar sugerencias</a></small>")
recipients (build-recipients rodadas_id)
body {:from "<EMAIL>"
:to recipients
:cc "<EMAIL>"
:subject (str descripcion_corta " - Cancelacion")
:body [{:type "text/html;charset=utf-8"
:content content}]}]
body))
(defn rodadas-delete
[{params :params}]
(try
(let [id (:id params nil)
result (if-not (nil? id)
(do
(send-email host (email-delete-body id))
(Delete db :rodadas ["id = ?" id]))
nil)]
(if (seq result)
(generate-string {:success "Removido appropiadamente!"})
(generate-string {:error "No se pudo remover!"})))
(catch Exception e (.getMessage e))))
;;End rodadas-delete
(defroutes rodadas-routes
(GET "/entrenamiento/rodadas" [] (rodadas))
(POST "/entrenamiento/rodadas/json/grid" request (grid-json request))
(GET "/entrenamiento/rodadas/json/form/:id" [id] (form-json id))
(GET "/entrenamiento/rodadas/asistir/:id" [id] (form-asistir id))
(POST "/entrenamiento/rodadas/asistir" request [] (form-asistir-save request))
(POST "/entrenamiento/rodadas/save" request [] (rodadas-save request))
(POST "/entrenamiento/rodadas/delete" request [] (rodadas-delete request)))
| true |
(ns cc.routes.entrenamiento.rodadas
(:require [cc.models.crud :refer :all]
[cc.models.email :refer [host send-email]]
[cc.models.grid :refer :all]
[cc.models.util :refer :all]
[cheshire.core :refer :all]
[compojure.core :refer :all]
[selmer.parser :refer [render-file]]))
(defn rodadas
[]
(render-file "entrenamiento/rodadas/index.html" {:title "Entrenamiento - Rodadas"
:user (or (get-session-id) "Anonimo")}))
;;start rodadas grid
(def search-columns
["id"
"descripcion_corta"
"descripcion"
"punto_reunion"
"CASE WHEN nivel = 'P' THEN 'Principiantes' WHEN nivel = 'M' THEN 'Medio' WHEN nivel = 'A' THEN 'Avanzado' WHEN nivel = 'T' THEN 'TODOS' END"
"distancia"
"velocidad"
"CASE WHEN repetir = 'T' THEN 'Si' ELSE 'No' END"
"DATE_FORMAT(fecha,'%m/%d/%Y')"
"TIME_FORMAT(hora,'%h:%i %p')"
"leader"])
(def aliases-columns
["id"
"descripcion_corta"
"descripcion"
"CASE WHEN nivel = 'P' THEN 'Principiantes' WHEN nivel = 'M' THEN 'Medio' WHEN nivel = 'A' THEN 'Avanzado' WHEN nivel = 'T' THEN 'TODOS' END AS nivel"
"distancia"
"velocidad"
"punto_reunion"
"CASE WHEN repetir = 'T' THEN 'Si' ELSE 'No' END as repetir"
"DATE_FORMAT(fecha,'%m/%d/%Y') as fecha"
"TIME_FORMAT(hora,'%h:%i %p') as hora"
"leader"])
(defn grid-json
[{params :params}]
(try
(let [table "rodadas"
user (or (get-session-id) "Anonimo")
level (user-level)
email (user-email)
scolumns (convert-search-columns search-columns)
aliases aliases-columns
join ""
search (grid-search (:search params nil) scolumns)
search (cond
(= user "PI:NAME:<NAME>END_PI") (grid-search-extra search "anonimo = 'T' and rodada = 'T'")
(= level "U") (grid-search-extra search (str "leader_email = '" email "'" " and rodada = 'T'"))
(= level "A") (grid-search-extra search (str "leader_email = '" email "'" " and rodada = 'T'"))
:else (grid-search-extra search "rodada = 'T'"))
order (grid-sort (:sort params nil) (:order params nil))
offset (grid-offset (parse-int (:rows params)) (parse-int (:page params)))
sql (grid-sql table aliases join search order offset)
rows (grid-rows table aliases join search order offset)]
(generate-string rows))
(catch Exception e (.getMessage e))))
;;end rodadas grid
;;start rodadas form
(def form-sql
"SELECT id as id,
descripcion,
descripcion_corta,
punto_reunion,
nivel,
distancia,
velocidad,
DATE_FORMAT(fecha,'%m/%d/%Y') as fecha,
TIME_FORMAT(hora,'%H:%i') as hora,
leader,
leader_email,
cuadrante,
repetir,
anonimo
FROM rodadas
WHERE id = ?")
(defn form-json
[id]
(try
(let [row (Query db [form-sql id])]
(generate-string (first row)))
(catch Exception e (.getMessage e))))
;;end rodadas form
;;Start form-assistir
(defn email-body [rodadas_id user email comentarios asistir_desc]
(let [row (first (Query db ["SELECT leader,leader_email,descripcion_corta FROM rodadas WHERE id = ?" rodadas_id]))
leader (:leader row)
leader_email (:leader_email row)
descripcion_corta (:descripcion_corta row)
content (str "<strong>Hola " leader ":</strong></br></br>"
"Mi nombre es <strong>" user "</strong> y mi correo electronico es <a href='mailto:" email "'>" email "</a> y estoy confirmando que <strong>" asistir_desc "</strong> al evento.</br>"
"<small><strong>Nota:</strong><i> Si desea contestarle a esta persona, por favor hacer clic en el email arriba!</i></br></br>"
"<strong>Comentarios:</strong> " comentarios "</br></br>"
"<small>Esta es un aplicación para todos los ciclistas de Mexicali. se aceptan sugerencias. <a href='mailto: PI:EMAIL:<EMAIL>END_PI'>Clic aquí para mandar sugerencias</a></small>")
body {:from "PI:EMAIL:<EMAIL>END_PI"
:to leader_email
:cc "PI:EMAIL:<EMAIL>END_PI"
:subject (str descripcion_corta " - Confirmar asistencia")
:body [{:type "text/html;charset=utf-8"
:content content}]}]
body))
(defn form-asistir
[rodadas_id]
(let [row (first (Query db ["select descripcion_corta,DATE_FORMAT(fecha,'%m/%d/%Y') as fecha,TIME_FORMAT(hora,'%h:%i %p') as hora from rodadas where id = ?" rodadas_id]))
event_desc (:descripcion_corta row)
fecha (:fecha row)
hora (:hora row)
title (str fecha " - " hora " [" event_desc "] Confirmar asistencia")]
(render-file "entrenamiento/rodadas/asistir.html" {:title title
:rodadas_id rodadas_id})))
(defn form-asistir-save
[{params :params}]
(try
(let [rodadas_id (fix-id (:rodadas_id params))
email (:email params)
asistir_desc (if (= (:asistir params) "T")
"ASISTIRE"
"NO ASISTIRE")
postvars {:rodadas_id rodadas_id
:user (:user params)
:comentarios (:comentarios params)
:email email
:asistir (:asistir params)}
body (email-body rodadas_id (:user params) email (:comentarios params) asistir_desc)
result (Save db :rodadas_link postvars ["rodadas_id = ? and email = ?" rodadas_id email])]
(if (seq result)
(do
(send-email host body)
(generate-string {:success "Correctamente Processado!"}))
(generate-string {:error "No se pudo processar!"})))
(catch Exception e (.getMessage e))))
;;End form-assistir
(defn rodadas-save
[{params :params}]
(try
(let [id (fix-id (:id params))
user (or (get-session-id) "AnPI:NAME:<NAME>END_PIimo")
repetir (if (= user "PI:NAME:<NAME>END_PI") "F" (:repetir params))
anonimo (if (= user "PI:NAME:<NAME>END_PI") "T" "F")
postvars {:id id
:descripcion (:descripcion params)
:descripcion_corta (:descripcion_corta params)
:punto_reunion (:punto_reunion params)
:nivel (:nivel params)
:distancia (:distancia params)
:velocidad (:velocidad params)
:fecha (format-date-internal (:fecha params))
:hora (fix-hour (:hora params))
:leader (:leader params)
:leader_email (:leader_email params)
:cuadrante (:cuadrante params)
:repetir repetir
:anonimo anonimo}
result (Save db :rodadas postvars ["id = ?" id])]
(if (seq result)
(generate-string {:success "Correctamente Processado!"})
(generate-string {:error "No se pudo processar!"})))
(catch Exception e (.getMessage e))))
;;Start rodadas-delete
(defn build-recipients [rodadas_id]
(into [] (map #(first (vals %)) (Query db ["SELECT email from rodadas_link where rodadas_id = ?" rodadas_id]))))
(defn email-delete-body [rodadas_id]
(let [row (first (Query db ["SELECT leader,leader_email,descripcion_corta FROM rodadas where id = ?" rodadas_id]))
leader (:leader row)
leader_email (:leader_email row)
descripcion_corta (:descripcion_corta row)
content (str "<strong>Hola:</strong></br></br>La rodada organizada por: " leader " <a href='mailto:" leader_email "'>" leader_email "</a> se cancelo. Disculpen la inconveniencia que esto pueda causar.</br>"
"<small><strong>Nota:</strong><i> Si desea contestarle a esta persona, por favor hacer clic en el email arriba!</i></br></br>"
"Muchas gracias por su participacion y esperamos que la proxima vez se pueda realizar la rodada.</br></br>"
"<small>Esta es un aplicación para todos los ciclistas de Mexicali. se aceptan sugerencias. <a href='mailto: PI:EMAIL:<EMAIL>END_PI'>Clic aquí para mandar sugerencias</a></small>")
recipients (build-recipients rodadas_id)
body {:from "PI:EMAIL:<EMAIL>END_PI"
:to recipients
:cc "PI:EMAIL:<EMAIL>END_PI"
:subject (str descripcion_corta " - Cancelacion")
:body [{:type "text/html;charset=utf-8"
:content content}]}]
body))
(defn rodadas-delete
[{params :params}]
(try
(let [id (:id params nil)
result (if-not (nil? id)
(do
(send-email host (email-delete-body id))
(Delete db :rodadas ["id = ?" id]))
nil)]
(if (seq result)
(generate-string {:success "Removido appropiadamente!"})
(generate-string {:error "No se pudo remover!"})))
(catch Exception e (.getMessage e))))
;;End rodadas-delete
(defroutes rodadas-routes
(GET "/entrenamiento/rodadas" [] (rodadas))
(POST "/entrenamiento/rodadas/json/grid" request (grid-json request))
(GET "/entrenamiento/rodadas/json/form/:id" [id] (form-json id))
(GET "/entrenamiento/rodadas/asistir/:id" [id] (form-asistir id))
(POST "/entrenamiento/rodadas/asistir" request [] (form-asistir-save request))
(POST "/entrenamiento/rodadas/save" request [] (rodadas-save request))
(POST "/entrenamiento/rodadas/delete" request [] (rodadas-delete request)))
|
[
{
"context": " :blocks #\"\\\"text\\\":\\\"Hey John,\\\\nThe pipelinerun didn't succeed.\\\"\"\n ",
"end": 3005,
"score": 0.9975863099098206,
"start": 3001,
"tag": "NAME",
"value": "John"
},
{
"context": " :text \"Hey John,\\nThe pipelinerun didn't succeed.\\n\"}}))\n ",
"end": 3130,
"score": 0.9981557726860046,
"start": 3126,
"tag": "NAME",
"value": "John"
},
{
"context": " :receiver/name \"John\"\n ",
"end": 3554,
"score": 0.9978615641593933,
"start": 3550,
"tag": "NAME",
"value": "John"
},
{
"context": "ons {\"tekton-watcher.slack/preferred-user-email\" \"[email protected]\"}}}\n commit {:commit {:author {:emai",
"end": 4091,
"score": 0.9999244213104248,
"start": 4069,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "}\n commit {:commit {:author {:email \"[email protected]\"}}}\n config {:slack/oauth-token \"tok",
"end": 4162,
"score": 0.9999223351478577,
"start": 4144,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "oauth-token \"token\"}\n user {:name \"johndoe\"}]\n\n (testing \"attempts to lookup the user by ",
"end": 4253,
"score": 0.9996336698532104,
"start": 4246,
"tag": "USERNAME",
"value": "johndoe"
},
{
"context": " :slack.req/query {:email \"[email protected]\"}}))\n {:ok true :user user}]\n ",
"end": 4642,
"score": 0.9999232292175293,
"start": 4620,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "all (standalone/match? {:slack.req/query {:email \"[email protected]\"}}))\n {:ok true :error \"users_no",
"end": 5030,
"score": 0.9999083876609802,
"start": 5008,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "all (standalone/match? {:slack.req/query {:email \"[email protected]\"}}))\n {:ok true :user user}]\n ",
"end": 5184,
"score": 0.999904215335846,
"start": 5166,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "all (standalone/match? {:slack.req/query {:email \"[email protected]\"}}))\n {:ok true :user user}]\n ",
"end": 5558,
"score": 0.9999014735221863,
"start": 5540,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "all (standalone/match? {:slack.req/query {:email \"[email protected]\"}}))\n {:ok true :error \"users_no",
"end": 5911,
"score": 0.9999001026153564,
"start": 5889,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "all (standalone/match? {:slack.req/query {:email \"[email protected]\"}}))\n {:ok true :error \"users_no",
"end": 6065,
"score": 0.9999027848243713,
"start": 6047,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " commit {:commit {:author {:email \"[email protected]\"}}}\n slack-user {:name \"johndoe\"}]\n ",
"end": 7249,
"score": 0.9999150633811951,
"start": 7231,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[email protected]\"}}}\n slack-user {:name \"johndoe\"}]\n (providing [(http-client/send-and-await ",
"end": 7292,
"score": 0.9994713068008423,
"start": 7285,
"tag": "USERNAME",
"value": "johndoe"
},
{
"context": " :html-url \"https://github.com/nubank/heimdall\"}\n :pipeline-run",
"end": 8257,
"score": 0.9640281796455383,
"start": 8251,
"tag": "USERNAME",
"value": "nubank"
},
{
"context": "github.commit/data {:commit {:author {:email \"[email protected]\"}}}\n :github.repos",
"end": 12007,
"score": 0.999883770942688,
"start": 11989,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :github.repository/data {:owner \"nubank\"\n ",
"end": 12086,
"score": 0.7499985098838806,
"start": 12080,
"tag": "USERNAME",
"value": "nubank"
},
{
"context": " :html-url \"https://github.com/nubank/heimdall\"}\n :pipel",
"end": 12259,
"score": 0.9962567687034607,
"start": 12253,
"tag": "USERNAME",
"value": "nubank"
},
{
"context": " :name \"johndoe\"\n ",
"end": 12543,
"score": 0.999148964881897,
"start": 12536,
"tag": "USERNAME",
"value": "johndoe"
},
{
"context": " :profile {:first-name \"John\"}}}]\n\n (testing \"does nothing when the followi",
"end": 12629,
"score": 0.9996163845062256,
"start": 12625,
"tag": "NAME",
"value": "John"
},
{
"context": " :blocks #\"\\\"text\\\":\\\"Hey John,\\\\nThe pipelinerun succeeded!\\\"\"\n ",
"end": 14207,
"score": 0.596837043762207,
"start": 14203,
"tag": "NAME",
"value": "John"
},
{
"context": " :text \"Hey John,\\nThe pipelinerun succeeded!\\n\"}}))\n ",
"end": 14329,
"score": 0.7946588397026062,
"start": 14325,
"tag": "NAME",
"value": "John"
},
{
"context": " :blocks #\"\\\"text\\\":\\\"Hey John,\\\\nThe pipelinerun succeeded!\\\"\"\n ",
"end": 15804,
"score": 0.5270995497703552,
"start": 15802,
"tag": "NAME",
"value": "ey"
},
{
"context": " :blocks #\"\\\"text\\\":\\\"Hey John,\\\\nThe pipelinerun succeeded!\\\"\"\n ",
"end": 15809,
"score": 0.7954273223876953,
"start": 15805,
"tag": "NAME",
"value": "John"
},
{
"context": " :text \"Hey John,\\nThe pipelinerun succeeded!\\n\"}}))\n ",
"end": 15928,
"score": 0.5560497045516968,
"start": 15926,
"tag": "NAME",
"value": "ey"
},
{
"context": " :text \"Hey John,\\nThe pipelinerun succeeded!\\n\"}}))\n ",
"end": 15933,
"score": 0.8472158312797546,
"start": 15929,
"tag": "NAME",
"value": "John"
},
{
"context": " :blocks #\"\\\"text\\\":\\\"Hey John,\\\\nThe pipelinerun didn't succeed.\\\"\"\n ",
"end": 17244,
"score": 0.7194014191627502,
"start": 17240,
"tag": "NAME",
"value": "John"
},
{
"context": " :text \"Hey John,\\nThe pipelinerun didn't succeed.\\n\"}}))\n ",
"end": 17366,
"score": 0.6711733341217041,
"start": 17363,
"tag": "NAME",
"value": "Hey"
},
{
"context": " :text \"Hey John,\\nThe pipelinerun didn't succeed.\\n\"}}))\n ",
"end": 17371,
"score": 0.7427613735198975,
"start": 17367,
"tag": "NAME",
"value": "John"
}
] |
test/tekton_watcher/slack_notifications_test.clj
|
nubank/tekton-watcher
| 3 |
(ns tekton-watcher.slack-notifications-test
(:require [clojure.core.async :refer [<!!]]
[clojure.test :refer :all]
[matcher-combinators.matchers :as m]
[matcher-combinators.standalone :as standalone]
[matcher-combinators.test :refer [match?]]
[mockfn.macros :refer [providing]]
[slack-api.core :as slack]
[tekton-watcher.http-client :as http-client]
[tekton-watcher.slack-notifications :as slack-notifications]))
(deftest render-taskruns-test
(let [pipeline-run {:status
{:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Failed"
:status "False"
:type "Succeeded"}]}}}}}]
(testing "returns a vector containing Slack blocks describing the taskruns"
(is (= [{:type "section",
:text {:type "mrkdwn", :text ":fire: *cljfmt*"},
:accessory
{:type "button",
:text {:type "plain_text", :text "Details"},
:url
"http://localhost:9000/#/namespaces/dev/taskruns/heimdall-pr-run-7j86z-cljfmt-dpsd5"}}
{:type "section",
:text {:type "mrkdwn", :text ":thumbsup: *unit-tests*"},
:accessory
{:type "button",
:text {:type "plain_text", :text "Details"},
:url
"http://localhost:9000/#/namespaces/dev/taskruns/heimdall-pr-run-7j86z-unit-tests-jjhxf"}}] (slack-notifications/render-taskruns
{:config {:tekton.dashboard/task-run "http://localhost:9000/#/namespaces/dev/taskruns/{task-run}"}
:pipeline-run/data pipeline-run}))))))
(deftest post-message-test
(testing "reads the specified templates, replaces any declared placeholders
with values supplied through the context map and sends the message by using
the Slack API"
(providing [(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.client/opts {:oauth-token-fn fn?}
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey John,\\nThe pipelinerun didn't succeed.\""
:text "Hey John,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true}]
(is (= {:ok true}
(slack-notifications/post-message {:config {:slack/oauth-token "token"
:slack.templates/dir "test/resources/fixtures"}
:receiver/name "John"
:receiver/channel "U123"
:template.blocks/name "pipeline-run-did-not-succeed.json"
:template.text/name "pipeline-run-did-not-succeed.txt"}))))))
(deftest lookup-user-by-email-test
(let [pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.slack/preferred-user-email" "[email protected]"}}}
commit {:commit {:author {:email "[email protected]"}}}
config {:slack/oauth-token "token"}
user {:name "johndoe"}]
(testing "attempts to lookup the user by the preferred e-mail declared in
the pipelinerun"
(providing [(slack/call (standalone/match? {:slack/method :users/lookup-by-email
:slack.client/opts {:oauth-token-fn fn?}
:slack.req/query {:email "[email protected]"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email pipeline-run commit config)))))
(testing "attempts to lookup the user by the commit e-mail when it can't be
found by the preferred e-mail"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "[email protected]"}}))
{:ok true :error "users_not_found"}
(slack/call (standalone/match? {:slack.req/query {:email "[email protected]"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email pipeline-run commit config)))))
(testing "attempts to lookup the user by the commit e-mail when the preferred e-mail isn't supplied"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "[email protected]"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email {:metadata {:name "heimdall-run-1"}} commit config)))))
(testing "returns nil when the user can't be found"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "[email protected]"}}))
{:ok true :error "users_not_found"}
(slack/call (standalone/match? {:slack.req/query {:email "[email protected]"}}))
{:ok true :error "users_not_found"}]
(is (nil? (slack-notifications/lookup-user-by-email pipeline-run commit config)))))))
(deftest make-composition-context-test
(testing "builds a context map with all relevant information to compose and
send notifications"
(let [pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"}}}
config {:github.commits/url "https://api.github.com/repos/{repository-owner}/{repository-name}/commits/{commit-sha}"
:github/oauth-token "token"
:github.repositories/html-url "https://github.com/{repository-owner}/{repository-name}"
:tekton.dashboard/pipeline-run "http://localhost:9000/#/namespaces/dev/pipelineruns/{pipeline-run}"}
commit {:commit {:author {:email "[email protected]"}}}
slack-user {:name "johndoe"}]
(providing [(http-client/send-and-await #:http{:url "https://api.github.com/repos/{repository-owner}/{repository-name}/commits/{commit-sha}"
:path-params {:repository-owner "nubank"
:repository-name "heimdall"
:commit-sha "abc123"}
:oauth-token "token"}) commit
(slack-notifications/lookup-user-by-email pipeline-run commit config) slack-user]
(is (= {:config config
:github.commit/data commit
:github.repository/data {:owner "nubank"
:name "heimdall"
:html-url "https://github.com/nubank/heimdall"}
:pipeline-run/data pipeline-run
:pipeline-run/link "http://localhost:9000/#/namespaces/dev/pipelineruns/heimdall-run-1"
:slack/user slack-user}
(slack-notifications/make-composition-context pipeline-run config)))))))
(deftest send-notifications-test
(let [succeeded-pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"
"tekton-watcher.slack/channel" "#dev"}}
:status {:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}}}}
failed-pipeline-run {:metadata {:name "heimdall-run-2"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"
"tekton-watcher.slack/channel" "#dev"}}
:status {:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Failed"
:status "False"
:type "Succeeded"}]}}}}}
config {:slack.templates/dir "test/resources/fixtures"
:tekton.dashboard/task-run "http://localhost:9000/#/namespaces/dev/taskruns/{task-run}"}
context {:config config
:github.commit/data {:commit {:author {:email "[email protected]"}}}
:github.repository/data {:owner "nubank"
:name "heimdall"
:html-url "https://github.com/nubank/heimdall"}
:pipeline-run/link "http://localhost:9000/#/namespaces/dev/pipelineruns/heimdall-run-1"
:slack/user {:id "U123"
:name "johndoe"
:profile {:first-name "John"}}}]
(testing "does nothing when the following annotations aren't present"
(are [annotation] (nil? (slack-notifications/send-notifications (update-in succeeded-pipeline-run
[:metadata :annotations]
#(dissoc % annotation))
:pipeline-run/succeeded
config))
"tekton-watcher.github/repository-owner"
"tekton-watcher.github/repository-name"
"tekton-watcher.github/commit-sha"))
(testing "does nothing when the Slack user can't be found"
(providing [(slack-notifications/make-composition-context succeeded-pipeline-run config) {}]
(nil?
(slack-notifications/send-notifications succeeded-pipeline-run :pipeline-run/succeeded config))))
(testing "sends notifications about the succeeded pipeline to the user who
made the commit, as well to the configured channel"
(providing [(slack-notifications/make-composition-context succeeded-pipeline-run config) (assoc context :pipeline-run/data succeeded-pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey John,\\nThe pipelinerun succeeded!\""
:text "Hey John,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "U123"}
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "#dev"
:blocks #"\"text\":\"Hey peeps,\\nThe pipelinerun succeeded!\""
:text "Hey peeps,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "#dev"}]
(is (match? (m/in-any-order [{:ok true :channel "U123"}
{:ok true :channel "#dev"}])
(<!! (slack-notifications/send-notifications succeeded-pipeline-run :pipeline-run/succeeded config))))))
(testing "do not send a message to a Slack channel when there is no one
declared"
(let [pipeline-run (update-in succeeded-pipeline-run [:metadata :annotations] #(dissoc % "tekton-watcher.slack/channel"))]
(providing [(slack-notifications/make-composition-context pipeline-run config) (assoc context :pipeline-run/data pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey John,\\nThe pipelinerun succeeded!\""
:text "Hey John,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "U123"}]
(is (= [{:ok true :channel "U123"}]
(<!! (slack-notifications/send-notifications pipeline-run :pipeline-run/succeeded config)))))))
(testing "does nothing when the pipeline run succeeds and it's configured to
not send notifications"
(let [pipeline-run (assoc-in succeeded-pipeline-run [:metadata :annotations "tekton-watcher.slack.preferences/only-failed-runs"] "true")]
(providing [(slack-notifications/make-composition-context pipeline-run config) pipeline-run]
(nil?
(slack-notifications/send-notifications pipeline-run :pipeline-run/succeeded config)))))
(testing "sends notifications about the failed pipeline run to the user who
made the commit, as well to the configured channel"
(providing [(slack-notifications/make-composition-context failed-pipeline-run config) (assoc context :pipeline-run/data failed-pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey John,\\nThe pipelinerun didn't succeed.\""
:text "Hey John,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true :channel "U123"}
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "#dev"
:blocks #"\"text\":\"Hey peeps,\\nThe pipelinerun didn't succeed.\""
:text "Hey peeps,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true :channel "#dev"}]
(is (match? (m/in-any-order [{:ok true :channel "U123"}
{:ok true :channel "#dev"}])
(<!! (slack-notifications/send-notifications failed-pipeline-run :pipeline-run/failed config))))))))
|
84299
|
(ns tekton-watcher.slack-notifications-test
(:require [clojure.core.async :refer [<!!]]
[clojure.test :refer :all]
[matcher-combinators.matchers :as m]
[matcher-combinators.standalone :as standalone]
[matcher-combinators.test :refer [match?]]
[mockfn.macros :refer [providing]]
[slack-api.core :as slack]
[tekton-watcher.http-client :as http-client]
[tekton-watcher.slack-notifications :as slack-notifications]))
(deftest render-taskruns-test
(let [pipeline-run {:status
{:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Failed"
:status "False"
:type "Succeeded"}]}}}}}]
(testing "returns a vector containing Slack blocks describing the taskruns"
(is (= [{:type "section",
:text {:type "mrkdwn", :text ":fire: *cljfmt*"},
:accessory
{:type "button",
:text {:type "plain_text", :text "Details"},
:url
"http://localhost:9000/#/namespaces/dev/taskruns/heimdall-pr-run-7j86z-cljfmt-dpsd5"}}
{:type "section",
:text {:type "mrkdwn", :text ":thumbsup: *unit-tests*"},
:accessory
{:type "button",
:text {:type "plain_text", :text "Details"},
:url
"http://localhost:9000/#/namespaces/dev/taskruns/heimdall-pr-run-7j86z-unit-tests-jjhxf"}}] (slack-notifications/render-taskruns
{:config {:tekton.dashboard/task-run "http://localhost:9000/#/namespaces/dev/taskruns/{task-run}"}
:pipeline-run/data pipeline-run}))))))
(deftest post-message-test
(testing "reads the specified templates, replaces any declared placeholders
with values supplied through the context map and sends the message by using
the Slack API"
(providing [(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.client/opts {:oauth-token-fn fn?}
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey <NAME>,\\nThe pipelinerun didn't succeed.\""
:text "Hey <NAME>,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true}]
(is (= {:ok true}
(slack-notifications/post-message {:config {:slack/oauth-token "token"
:slack.templates/dir "test/resources/fixtures"}
:receiver/name "<NAME>"
:receiver/channel "U123"
:template.blocks/name "pipeline-run-did-not-succeed.json"
:template.text/name "pipeline-run-did-not-succeed.txt"}))))))
(deftest lookup-user-by-email-test
(let [pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.slack/preferred-user-email" "<EMAIL>"}}}
commit {:commit {:author {:email "<EMAIL>"}}}
config {:slack/oauth-token "token"}
user {:name "johndoe"}]
(testing "attempts to lookup the user by the preferred e-mail declared in
the pipelinerun"
(providing [(slack/call (standalone/match? {:slack/method :users/lookup-by-email
:slack.client/opts {:oauth-token-fn fn?}
:slack.req/query {:email "<EMAIL>"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email pipeline-run commit config)))))
(testing "attempts to lookup the user by the commit e-mail when it can't be
found by the preferred e-mail"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "<EMAIL>"}}))
{:ok true :error "users_not_found"}
(slack/call (standalone/match? {:slack.req/query {:email "<EMAIL>"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email pipeline-run commit config)))))
(testing "attempts to lookup the user by the commit e-mail when the preferred e-mail isn't supplied"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "<EMAIL>"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email {:metadata {:name "heimdall-run-1"}} commit config)))))
(testing "returns nil when the user can't be found"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "<EMAIL>"}}))
{:ok true :error "users_not_found"}
(slack/call (standalone/match? {:slack.req/query {:email "<EMAIL>"}}))
{:ok true :error "users_not_found"}]
(is (nil? (slack-notifications/lookup-user-by-email pipeline-run commit config)))))))
(deftest make-composition-context-test
(testing "builds a context map with all relevant information to compose and
send notifications"
(let [pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"}}}
config {:github.commits/url "https://api.github.com/repos/{repository-owner}/{repository-name}/commits/{commit-sha}"
:github/oauth-token "token"
:github.repositories/html-url "https://github.com/{repository-owner}/{repository-name}"
:tekton.dashboard/pipeline-run "http://localhost:9000/#/namespaces/dev/pipelineruns/{pipeline-run}"}
commit {:commit {:author {:email "<EMAIL>"}}}
slack-user {:name "johndoe"}]
(providing [(http-client/send-and-await #:http{:url "https://api.github.com/repos/{repository-owner}/{repository-name}/commits/{commit-sha}"
:path-params {:repository-owner "nubank"
:repository-name "heimdall"
:commit-sha "abc123"}
:oauth-token "token"}) commit
(slack-notifications/lookup-user-by-email pipeline-run commit config) slack-user]
(is (= {:config config
:github.commit/data commit
:github.repository/data {:owner "nubank"
:name "heimdall"
:html-url "https://github.com/nubank/heimdall"}
:pipeline-run/data pipeline-run
:pipeline-run/link "http://localhost:9000/#/namespaces/dev/pipelineruns/heimdall-run-1"
:slack/user slack-user}
(slack-notifications/make-composition-context pipeline-run config)))))))
(deftest send-notifications-test
(let [succeeded-pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"
"tekton-watcher.slack/channel" "#dev"}}
:status {:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}}}}
failed-pipeline-run {:metadata {:name "heimdall-run-2"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"
"tekton-watcher.slack/channel" "#dev"}}
:status {:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Failed"
:status "False"
:type "Succeeded"}]}}}}}
config {:slack.templates/dir "test/resources/fixtures"
:tekton.dashboard/task-run "http://localhost:9000/#/namespaces/dev/taskruns/{task-run}"}
context {:config config
:github.commit/data {:commit {:author {:email "<EMAIL>"}}}
:github.repository/data {:owner "nubank"
:name "heimdall"
:html-url "https://github.com/nubank/heimdall"}
:pipeline-run/link "http://localhost:9000/#/namespaces/dev/pipelineruns/heimdall-run-1"
:slack/user {:id "U123"
:name "johndoe"
:profile {:first-name "<NAME>"}}}]
(testing "does nothing when the following annotations aren't present"
(are [annotation] (nil? (slack-notifications/send-notifications (update-in succeeded-pipeline-run
[:metadata :annotations]
#(dissoc % annotation))
:pipeline-run/succeeded
config))
"tekton-watcher.github/repository-owner"
"tekton-watcher.github/repository-name"
"tekton-watcher.github/commit-sha"))
(testing "does nothing when the Slack user can't be found"
(providing [(slack-notifications/make-composition-context succeeded-pipeline-run config) {}]
(nil?
(slack-notifications/send-notifications succeeded-pipeline-run :pipeline-run/succeeded config))))
(testing "sends notifications about the succeeded pipeline to the user who
made the commit, as well to the configured channel"
(providing [(slack-notifications/make-composition-context succeeded-pipeline-run config) (assoc context :pipeline-run/data succeeded-pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey <NAME>,\\nThe pipelinerun succeeded!\""
:text "Hey <NAME>,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "U123"}
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "#dev"
:blocks #"\"text\":\"Hey peeps,\\nThe pipelinerun succeeded!\""
:text "Hey peeps,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "#dev"}]
(is (match? (m/in-any-order [{:ok true :channel "U123"}
{:ok true :channel "#dev"}])
(<!! (slack-notifications/send-notifications succeeded-pipeline-run :pipeline-run/succeeded config))))))
(testing "do not send a message to a Slack channel when there is no one
declared"
(let [pipeline-run (update-in succeeded-pipeline-run [:metadata :annotations] #(dissoc % "tekton-watcher.slack/channel"))]
(providing [(slack-notifications/make-composition-context pipeline-run config) (assoc context :pipeline-run/data pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"H<NAME> <NAME>,\\nThe pipelinerun succeeded!\""
:text "H<NAME> <NAME>,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "U123"}]
(is (= [{:ok true :channel "U123"}]
(<!! (slack-notifications/send-notifications pipeline-run :pipeline-run/succeeded config)))))))
(testing "does nothing when the pipeline run succeeds and it's configured to
not send notifications"
(let [pipeline-run (assoc-in succeeded-pipeline-run [:metadata :annotations "tekton-watcher.slack.preferences/only-failed-runs"] "true")]
(providing [(slack-notifications/make-composition-context pipeline-run config) pipeline-run]
(nil?
(slack-notifications/send-notifications pipeline-run :pipeline-run/succeeded config)))))
(testing "sends notifications about the failed pipeline run to the user who
made the commit, as well to the configured channel"
(providing [(slack-notifications/make-composition-context failed-pipeline-run config) (assoc context :pipeline-run/data failed-pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey <NAME>,\\nThe pipelinerun didn't succeed.\""
:text "<NAME> <NAME>,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true :channel "U123"}
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "#dev"
:blocks #"\"text\":\"Hey peeps,\\nThe pipelinerun didn't succeed.\""
:text "Hey peeps,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true :channel "#dev"}]
(is (match? (m/in-any-order [{:ok true :channel "U123"}
{:ok true :channel "#dev"}])
(<!! (slack-notifications/send-notifications failed-pipeline-run :pipeline-run/failed config))))))))
| true |
(ns tekton-watcher.slack-notifications-test
(:require [clojure.core.async :refer [<!!]]
[clojure.test :refer :all]
[matcher-combinators.matchers :as m]
[matcher-combinators.standalone :as standalone]
[matcher-combinators.test :refer [match?]]
[mockfn.macros :refer [providing]]
[slack-api.core :as slack]
[tekton-watcher.http-client :as http-client]
[tekton-watcher.slack-notifications :as slack-notifications]))
(deftest render-taskruns-test
(let [pipeline-run {:status
{:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Failed"
:status "False"
:type "Succeeded"}]}}}}}]
(testing "returns a vector containing Slack blocks describing the taskruns"
(is (= [{:type "section",
:text {:type "mrkdwn", :text ":fire: *cljfmt*"},
:accessory
{:type "button",
:text {:type "plain_text", :text "Details"},
:url
"http://localhost:9000/#/namespaces/dev/taskruns/heimdall-pr-run-7j86z-cljfmt-dpsd5"}}
{:type "section",
:text {:type "mrkdwn", :text ":thumbsup: *unit-tests*"},
:accessory
{:type "button",
:text {:type "plain_text", :text "Details"},
:url
"http://localhost:9000/#/namespaces/dev/taskruns/heimdall-pr-run-7j86z-unit-tests-jjhxf"}}] (slack-notifications/render-taskruns
{:config {:tekton.dashboard/task-run "http://localhost:9000/#/namespaces/dev/taskruns/{task-run}"}
:pipeline-run/data pipeline-run}))))))
(deftest post-message-test
(testing "reads the specified templates, replaces any declared placeholders
with values supplied through the context map and sends the message by using
the Slack API"
(providing [(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.client/opts {:oauth-token-fn fn?}
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey PI:NAME:<NAME>END_PI,\\nThe pipelinerun didn't succeed.\""
:text "Hey PI:NAME:<NAME>END_PI,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true}]
(is (= {:ok true}
(slack-notifications/post-message {:config {:slack/oauth-token "token"
:slack.templates/dir "test/resources/fixtures"}
:receiver/name "PI:NAME:<NAME>END_PI"
:receiver/channel "U123"
:template.blocks/name "pipeline-run-did-not-succeed.json"
:template.text/name "pipeline-run-did-not-succeed.txt"}))))))
(deftest lookup-user-by-email-test
(let [pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.slack/preferred-user-email" "PI:EMAIL:<EMAIL>END_PI"}}}
commit {:commit {:author {:email "PI:EMAIL:<EMAIL>END_PI"}}}
config {:slack/oauth-token "token"}
user {:name "johndoe"}]
(testing "attempts to lookup the user by the preferred e-mail declared in
the pipelinerun"
(providing [(slack/call (standalone/match? {:slack/method :users/lookup-by-email
:slack.client/opts {:oauth-token-fn fn?}
:slack.req/query {:email "PI:EMAIL:<EMAIL>END_PI"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email pipeline-run commit config)))))
(testing "attempts to lookup the user by the commit e-mail when it can't be
found by the preferred e-mail"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "PI:EMAIL:<EMAIL>END_PI"}}))
{:ok true :error "users_not_found"}
(slack/call (standalone/match? {:slack.req/query {:email "PI:EMAIL:<EMAIL>END_PI"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email pipeline-run commit config)))))
(testing "attempts to lookup the user by the commit e-mail when the preferred e-mail isn't supplied"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "PI:EMAIL:<EMAIL>END_PI"}}))
{:ok true :user user}]
(is (= user
(slack-notifications/lookup-user-by-email {:metadata {:name "heimdall-run-1"}} commit config)))))
(testing "returns nil when the user can't be found"
(providing [(slack/call (standalone/match? {:slack.req/query {:email "PI:EMAIL:<EMAIL>END_PI"}}))
{:ok true :error "users_not_found"}
(slack/call (standalone/match? {:slack.req/query {:email "PI:EMAIL:<EMAIL>END_PI"}}))
{:ok true :error "users_not_found"}]
(is (nil? (slack-notifications/lookup-user-by-email pipeline-run commit config)))))))
(deftest make-composition-context-test
(testing "builds a context map with all relevant information to compose and
send notifications"
(let [pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"}}}
config {:github.commits/url "https://api.github.com/repos/{repository-owner}/{repository-name}/commits/{commit-sha}"
:github/oauth-token "token"
:github.repositories/html-url "https://github.com/{repository-owner}/{repository-name}"
:tekton.dashboard/pipeline-run "http://localhost:9000/#/namespaces/dev/pipelineruns/{pipeline-run}"}
commit {:commit {:author {:email "PI:EMAIL:<EMAIL>END_PI"}}}
slack-user {:name "johndoe"}]
(providing [(http-client/send-and-await #:http{:url "https://api.github.com/repos/{repository-owner}/{repository-name}/commits/{commit-sha}"
:path-params {:repository-owner "nubank"
:repository-name "heimdall"
:commit-sha "abc123"}
:oauth-token "token"}) commit
(slack-notifications/lookup-user-by-email pipeline-run commit config) slack-user]
(is (= {:config config
:github.commit/data commit
:github.repository/data {:owner "nubank"
:name "heimdall"
:html-url "https://github.com/nubank/heimdall"}
:pipeline-run/data pipeline-run
:pipeline-run/link "http://localhost:9000/#/namespaces/dev/pipelineruns/heimdall-run-1"
:slack/user slack-user}
(slack-notifications/make-composition-context pipeline-run config)))))))
(deftest send-notifications-test
(let [succeeded-pipeline-run {:metadata {:name "heimdall-run-1"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"
"tekton-watcher.slack/channel" "#dev"}}
:status {:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}}}}
failed-pipeline-run {:metadata {:name "heimdall-run-2"
:annotations {"tekton-watcher.github/repository-owner" "nubank"
"tekton-watcher.github/repository-name" "heimdall"
"tekton-watcher.github/commit-sha" "abc123"
"tekton-watcher.slack/channel" "#dev"}}
:status {:taskRuns
{:heimdall-pr-run-7j86z-unit-tests-jjhxf
{:pipelineTaskName "unit-tests"
:status
{:conditions
[{:reason "Succeeded"
:status "True"
:type "Succeeded"}]}}
:heimdall-pr-run-7j86z-cljfmt-dpsd5
{:pipelineTaskName "cljfmt"
:status
{:conditions
[{:reason "Failed"
:status "False"
:type "Succeeded"}]}}}}}
config {:slack.templates/dir "test/resources/fixtures"
:tekton.dashboard/task-run "http://localhost:9000/#/namespaces/dev/taskruns/{task-run}"}
context {:config config
:github.commit/data {:commit {:author {:email "PI:EMAIL:<EMAIL>END_PI"}}}
:github.repository/data {:owner "nubank"
:name "heimdall"
:html-url "https://github.com/nubank/heimdall"}
:pipeline-run/link "http://localhost:9000/#/namespaces/dev/pipelineruns/heimdall-run-1"
:slack/user {:id "U123"
:name "johndoe"
:profile {:first-name "PI:NAME:<NAME>END_PI"}}}]
(testing "does nothing when the following annotations aren't present"
(are [annotation] (nil? (slack-notifications/send-notifications (update-in succeeded-pipeline-run
[:metadata :annotations]
#(dissoc % annotation))
:pipeline-run/succeeded
config))
"tekton-watcher.github/repository-owner"
"tekton-watcher.github/repository-name"
"tekton-watcher.github/commit-sha"))
(testing "does nothing when the Slack user can't be found"
(providing [(slack-notifications/make-composition-context succeeded-pipeline-run config) {}]
(nil?
(slack-notifications/send-notifications succeeded-pipeline-run :pipeline-run/succeeded config))))
(testing "sends notifications about the succeeded pipeline to the user who
made the commit, as well to the configured channel"
(providing [(slack-notifications/make-composition-context succeeded-pipeline-run config) (assoc context :pipeline-run/data succeeded-pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey PI:NAME:<NAME>END_PI,\\nThe pipelinerun succeeded!\""
:text "Hey PI:NAME:<NAME>END_PI,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "U123"}
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "#dev"
:blocks #"\"text\":\"Hey peeps,\\nThe pipelinerun succeeded!\""
:text "Hey peeps,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "#dev"}]
(is (match? (m/in-any-order [{:ok true :channel "U123"}
{:ok true :channel "#dev"}])
(<!! (slack-notifications/send-notifications succeeded-pipeline-run :pipeline-run/succeeded config))))))
(testing "do not send a message to a Slack channel when there is no one
declared"
(let [pipeline-run (update-in succeeded-pipeline-run [:metadata :annotations] #(dissoc % "tekton-watcher.slack/channel"))]
(providing [(slack-notifications/make-composition-context pipeline-run config) (assoc context :pipeline-run/data pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"HPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI,\\nThe pipelinerun succeeded!\""
:text "HPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI,\nThe pipelinerun succeeded!\n"}}))
{:ok true :channel "U123"}]
(is (= [{:ok true :channel "U123"}]
(<!! (slack-notifications/send-notifications pipeline-run :pipeline-run/succeeded config)))))))
(testing "does nothing when the pipeline run succeeds and it's configured to
not send notifications"
(let [pipeline-run (assoc-in succeeded-pipeline-run [:metadata :annotations "tekton-watcher.slack.preferences/only-failed-runs"] "true")]
(providing [(slack-notifications/make-composition-context pipeline-run config) pipeline-run]
(nil?
(slack-notifications/send-notifications pipeline-run :pipeline-run/succeeded config)))))
(testing "sends notifications about the failed pipeline run to the user who
made the commit, as well to the configured channel"
(providing [(slack-notifications/make-composition-context failed-pipeline-run config) (assoc context :pipeline-run/data failed-pipeline-run)
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "U123"
:blocks #"\"text\":\"Hey PI:NAME:<NAME>END_PI,\\nThe pipelinerun didn't succeed.\""
:text "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true :channel "U123"}
(slack/call (standalone/match? {:slack/method :chat/post-message
:slack.req/payload {:channel "#dev"
:blocks #"\"text\":\"Hey peeps,\\nThe pipelinerun didn't succeed.\""
:text "Hey peeps,\nThe pipelinerun didn't succeed.\n"}}))
{:ok true :channel "#dev"}]
(is (match? (m/in-any-order [{:ok true :channel "U123"}
{:ok true :channel "#dev"}])
(<!! (slack-notifications/send-notifications failed-pipeline-run :pipeline-run/failed config))))))))
|
[
{
"context": "en working with JDBC.\"\n :url \"https://github.com/evanspa/pe-jdbc-utils\"\n :license {:name \"MIT\"\n ",
"end": 157,
"score": 0.9970642924308777,
"start": 150,
"tag": "USERNAME",
"value": "evanspa"
},
{
"context": "[user]\n :src-dir-uri \"https://github.com/evanspa/pe-jdbc-utils/blob/0.0.22/\"\n :src-linenu",
"end": 808,
"score": 0.8493566513061523,
"start": 801,
"tag": "USERNAME",
"value": "evanspa"
},
{
"context": "-paths [\"test-resources\"]}}\n :signing {:gpg-key \"[email protected]\"}\n :repositories [[\"releases\" {:url \"https://clo",
"end": 1525,
"score": 0.9997371435165405,
"start": 1508,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
project.clj
|
evanspa/pe-jdbc-utils
| 0 |
(defproject pe-jdbc-utils "0.0.23-SNAPSHOT"
:description "A Clojure library of helper functions when working with JDBC."
:url "https://github.com/evanspa/pe-jdbc-utils"
:license {:name "MIT"
:url "http://opensource.org/licenses/MIT"}
:plugins [[lein-pprint "1.1.2"]
[codox "0.8.10"]]
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/data.codec "0.1.0"]
[ch.qos.logback/logback-classic "1.0.13"]
[org.slf4j/slf4j-api "1.7.5"]
[clj-time "0.8.0"]
[org.clojure/java.jdbc "0.5.8"]
[pe-core-utils "0.0.15"]]
:resource-paths ["resources"]
:codox {:exclude [user]
:src-dir-uri "https://github.com/evanspa/pe-jdbc-utils/blob/0.0.22/"
:src-linenum-anchor-prefix "L"}
:profiles {:dev {:source-paths ["dev"] ;ensures 'user.clj' gets auto-loaded
:plugins [[cider/cider-nrepl "0.12.0"]]
:dependencies [[org.clojure/tools.namespace "0.2.7"]
[org.clojure/java.classpath "0.2.2"]
[org.clojure/data.json "0.2.5"]
[org.clojure/tools.nrepl "0.2.12"]
[org.postgresql/postgresql "9.4.1208.jre7"]]
:resource-paths ["test-resources"]}
:test {:resource-paths ["test-resources"]}}
:signing {:gpg-key "[email protected]"}
:repositories [["releases" {:url "https://clojars.org/repo"
:creds :gpg}]])
|
78810
|
(defproject pe-jdbc-utils "0.0.23-SNAPSHOT"
:description "A Clojure library of helper functions when working with JDBC."
:url "https://github.com/evanspa/pe-jdbc-utils"
:license {:name "MIT"
:url "http://opensource.org/licenses/MIT"}
:plugins [[lein-pprint "1.1.2"]
[codox "0.8.10"]]
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/data.codec "0.1.0"]
[ch.qos.logback/logback-classic "1.0.13"]
[org.slf4j/slf4j-api "1.7.5"]
[clj-time "0.8.0"]
[org.clojure/java.jdbc "0.5.8"]
[pe-core-utils "0.0.15"]]
:resource-paths ["resources"]
:codox {:exclude [user]
:src-dir-uri "https://github.com/evanspa/pe-jdbc-utils/blob/0.0.22/"
:src-linenum-anchor-prefix "L"}
:profiles {:dev {:source-paths ["dev"] ;ensures 'user.clj' gets auto-loaded
:plugins [[cider/cider-nrepl "0.12.0"]]
:dependencies [[org.clojure/tools.namespace "0.2.7"]
[org.clojure/java.classpath "0.2.2"]
[org.clojure/data.json "0.2.5"]
[org.clojure/tools.nrepl "0.2.12"]
[org.postgresql/postgresql "9.4.1208.jre7"]]
:resource-paths ["test-resources"]}
:test {:resource-paths ["test-resources"]}}
:signing {:gpg-key "<EMAIL>"}
:repositories [["releases" {:url "https://clojars.org/repo"
:creds :gpg}]])
| true |
(defproject pe-jdbc-utils "0.0.23-SNAPSHOT"
:description "A Clojure library of helper functions when working with JDBC."
:url "https://github.com/evanspa/pe-jdbc-utils"
:license {:name "MIT"
:url "http://opensource.org/licenses/MIT"}
:plugins [[lein-pprint "1.1.2"]
[codox "0.8.10"]]
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/data.codec "0.1.0"]
[ch.qos.logback/logback-classic "1.0.13"]
[org.slf4j/slf4j-api "1.7.5"]
[clj-time "0.8.0"]
[org.clojure/java.jdbc "0.5.8"]
[pe-core-utils "0.0.15"]]
:resource-paths ["resources"]
:codox {:exclude [user]
:src-dir-uri "https://github.com/evanspa/pe-jdbc-utils/blob/0.0.22/"
:src-linenum-anchor-prefix "L"}
:profiles {:dev {:source-paths ["dev"] ;ensures 'user.clj' gets auto-loaded
:plugins [[cider/cider-nrepl "0.12.0"]]
:dependencies [[org.clojure/tools.namespace "0.2.7"]
[org.clojure/java.classpath "0.2.2"]
[org.clojure/data.json "0.2.5"]
[org.clojure/tools.nrepl "0.2.12"]
[org.postgresql/postgresql "9.4.1208.jre7"]]
:resource-paths ["test-resources"]}
:test {:resource-paths ["test-resources"]}}
:signing {:gpg-key "PI:EMAIL:<EMAIL>END_PI"}
:repositories [["releases" {:url "https://clojars.org/repo"
:creds :gpg}]])
|
[
{
"context": "id3.basics-util :as util]\n ))\n\n(def cursor-key :b04-make-elements-from-data)\n\n(def height 20)\n(def width 100)\n\n(defn example ",
"end": 201,
"score": 0.8099327683448792,
"start": 174,
"tag": "KEY",
"value": "b04-make-elements-from-data"
}
] |
src/basics/rid3/b04_make_elements_from_data.cljs
|
ryanechternacht/rid3
| 153 |
(ns rid3.b04-make-elements-from-data
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :b04-make-elements-from-data)
(def height 20)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(reset! viz-ratom
;; when using an `:elem-with-data` piece, it will default
;; to look at the dataset key of your ratom
{:dataset ["A" "B" "C"]})
(fn [app-state]
[:div
[:h4 "4) Make elements based on an array of data"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b04"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
:pieces
[{:kind :elem-with-data
:tag "text"
:class "text-from-data"
;; note: by default, this is what the prepare-dataset
;; function will be ... so if you wanted, you could drop
;; this. I am showing it here for completeness.
:prepare-dataset (fn [ratom]
(-> @ratom
(get :dataset)
clj->js))
:did-mount (fn [node ratom]
(let [dataset-n (-> @ratom
(get :dataset)
count)
x-scale (-> js/d3
.scaleLinear
(.rangeRound #js [0 width])
(.domain #js [0 dataset-n]))]
(rid3-> node
{:x (fn [d i]
(x-scale i))
:y 12
:fill "black"}
(.text (fn [d]
d)))))}
]}]])))
|
78767
|
(ns rid3.b04-make-elements-from-data
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :<KEY>)
(def height 20)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(reset! viz-ratom
;; when using an `:elem-with-data` piece, it will default
;; to look at the dataset key of your ratom
{:dataset ["A" "B" "C"]})
(fn [app-state]
[:div
[:h4 "4) Make elements based on an array of data"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b04"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
:pieces
[{:kind :elem-with-data
:tag "text"
:class "text-from-data"
;; note: by default, this is what the prepare-dataset
;; function will be ... so if you wanted, you could drop
;; this. I am showing it here for completeness.
:prepare-dataset (fn [ratom]
(-> @ratom
(get :dataset)
clj->js))
:did-mount (fn [node ratom]
(let [dataset-n (-> @ratom
(get :dataset)
count)
x-scale (-> js/d3
.scaleLinear
(.rangeRound #js [0 width])
(.domain #js [0 dataset-n]))]
(rid3-> node
{:x (fn [d i]
(x-scale i))
:y 12
:fill "black"}
(.text (fn [d]
d)))))}
]}]])))
| true |
(ns rid3.b04-make-elements-from-data
(:require
[reagent.core :as reagent]
[rid3.core :as rid3 :refer [rid3->]]
[rid3.basics-util :as util]
))
(def cursor-key :PI:KEY:<KEY>END_PI)
(def height 20)
(def width 100)
(defn example [app-state]
(let [viz-ratom (reagent/cursor app-state [cursor-key])]
(reset! viz-ratom
;; when using an `:elem-with-data` piece, it will default
;; to look at the dataset key of your ratom
{:dataset ["A" "B" "C"]})
(fn [app-state]
[:div
[:h4 "4) Make elements based on an array of data"]
[util/link-source (name cursor-key)]
[rid3/viz
{:id "b04"
:ratom viz-ratom
:svg {:did-mount (fn [node ratom]
(rid3-> node
{:height height
:width width}))}
:pieces
[{:kind :elem-with-data
:tag "text"
:class "text-from-data"
;; note: by default, this is what the prepare-dataset
;; function will be ... so if you wanted, you could drop
;; this. I am showing it here for completeness.
:prepare-dataset (fn [ratom]
(-> @ratom
(get :dataset)
clj->js))
:did-mount (fn [node ratom]
(let [dataset-n (-> @ratom
(get :dataset)
count)
x-scale (-> js/d3
.scaleLinear
(.rangeRound #js [0 width])
(.domain #js [0 dataset-n]))]
(rid3-> node
{:x (fn [d i]
(x-scale i))
:y 12
:fill "black"}
(.text (fn [d]
d)))))}
]}]])))
|
[
{
"context": "leeping-in [43 62 80])\n(def wisdom [26 29 39])\n\n;; Roy G. Biv\n(def red [255 0 0])\n(def orange [255 127 0])\n(def",
"end": 282,
"score": 0.9998897910118103,
"start": 272,
"tag": "NAME",
"value": "Roy G. Biv"
}
] |
src/sparkl/styling.clj
|
cbraith/sparkl
| 1 |
;; ====================================
;; Styling
;; ====================================
(ns sparkl.styling)
; color palette
; =====================================
(def white [255 255 255])
(def black [0 0 0])
(def sleeping-in [43 62 80])
(def wisdom [26 29 39])
;; Roy G. Biv
(def red [255 0 0])
(def orange [255 127 0])
(def yellow [255 255 0])
(def green [0 255 0])
(def blue [0 0 255])
(def indigo [75 0 130])
(def violet [148 0 211])
;; foreground/background pairs
(def stardust [63 137 155])
(def persimmon [188 62 49])
(def grape [193 155 179])
(def potato-chip [195 185 163])
(def wasabi [150 164 127])
(def nebula [75 70 67])
(def snow-day [204 204 204])
(def umami [60 60 60])
(def fall-foliage [198 205 194])
(def sriracha [189 14 26])
(def laughter [172 87 134])
(def candlelight [206 174 71])
|
18927
|
;; ====================================
;; Styling
;; ====================================
(ns sparkl.styling)
; color palette
; =====================================
(def white [255 255 255])
(def black [0 0 0])
(def sleeping-in [43 62 80])
(def wisdom [26 29 39])
;; <NAME>
(def red [255 0 0])
(def orange [255 127 0])
(def yellow [255 255 0])
(def green [0 255 0])
(def blue [0 0 255])
(def indigo [75 0 130])
(def violet [148 0 211])
;; foreground/background pairs
(def stardust [63 137 155])
(def persimmon [188 62 49])
(def grape [193 155 179])
(def potato-chip [195 185 163])
(def wasabi [150 164 127])
(def nebula [75 70 67])
(def snow-day [204 204 204])
(def umami [60 60 60])
(def fall-foliage [198 205 194])
(def sriracha [189 14 26])
(def laughter [172 87 134])
(def candlelight [206 174 71])
| true |
;; ====================================
;; Styling
;; ====================================
(ns sparkl.styling)
; color palette
; =====================================
(def white [255 255 255])
(def black [0 0 0])
(def sleeping-in [43 62 80])
(def wisdom [26 29 39])
;; PI:NAME:<NAME>END_PI
(def red [255 0 0])
(def orange [255 127 0])
(def yellow [255 255 0])
(def green [0 255 0])
(def blue [0 0 255])
(def indigo [75 0 130])
(def violet [148 0 211])
;; foreground/background pairs
(def stardust [63 137 155])
(def persimmon [188 62 49])
(def grape [193 155 179])
(def potato-chip [195 185 163])
(def wasabi [150 164 127])
(def nebula [75 70 67])
(def snow-day [204 204 204])
(def umami [60 60 60])
(def fall-foliage [198 205 194])
(def sriracha [189 14 26])
(def laughter [172 87 134])
(def candlelight [206 174 71])
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2016-11-16\"\n :date \"2017-11-",
"end": 114,
"score": 0.8055537939071655,
"start": 88,
"tag": "EMAIL",
"value": "wahpenayo at gmail dot com"
}
] |
src/main/clojure/taigabench/classify/result.clj
|
wahpenayo/taigabench
| 0 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpenayo at gmail dot com"
:since "2016-11-16"
:date "2017-11-20"
:doc "benchmark result datum" }
taigabench.classify.result
(:require [zana.api :as z]))
;;------------------------------------------------------------------------------
(z/define-datum Result [^String model
^int ntrain
^int ntest
^float datatime
^float traintime
^float predicttime
^float auc])
;;------------------------------------------------------------------------------
|
97753
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<EMAIL>"
:since "2016-11-16"
:date "2017-11-20"
:doc "benchmark result datum" }
taigabench.classify.result
(:require [zana.api :as z]))
;;------------------------------------------------------------------------------
(z/define-datum Result [^String model
^int ntrain
^int ntest
^float datatime
^float traintime
^float predicttime
^float auc])
;;------------------------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:EMAIL:<EMAIL>END_PI"
:since "2016-11-16"
:date "2017-11-20"
:doc "benchmark result datum" }
taigabench.classify.result
(:require [zana.api :as z]))
;;------------------------------------------------------------------------------
(z/define-datum Result [^String model
^int ntrain
^int ntest
^float datatime
^float traintime
^float predicttime
^float auc])
;;------------------------------------------------------------------------------
|
[
{
"context": ";; A Mandolin by Roger Allen.\n(ns explore-overtone.mandolin\n (:use [explore-o",
"end": 28,
"score": 0.9998547434806824,
"start": 17,
"tag": "NAME",
"value": "Roger Allen"
}
] |
data/train/clojure/2dc520bb966dd43945cd70c98e4169833ef6dcb9mandolin.clj
|
harshp8l/deep-learning-lang-detection
| 84 |
;; A Mandolin by Roger Allen.
(ns explore-overtone.mandolin
(:use [explore-overtone.stringed]
[overtone.music pitch]
[overtone.studio inst]
[overtone.sc envelope node server ugens]
[overtone.sc.cgens mix]))
;; a map of chords to frets.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone
(def mandolin-chord-frets
{:A [ 6 1 0 0 ]
:A7 [ 2 2 4 3 ]
:Am [ 5 1 0 0 ]
;;:Am7
:Bb [ 3 0 1 1 ]
:Bb7 [ 3 3 5 4 ]
:Bbm [ 3 3 4 6 ]
;;:Bbm7
;; FIXME ... finish rest
:B [ 4 3 2 2 ]
:B7 [ 2 3 2 2 ]
:Bm [ 4 2 2 2 ]
;;:Bm7
:C [ 0 0 0 3 ]
:C7 [ 0 0 0 1 ]
:Cm [ 0 3 3 3 ]
;;:Cm7
:Db [ 1 1 1 4 ]
:Db7 [ 1 1 1 2 ]
:Dbm [ 1 4 4 4 ]
;;:Dbm7
:D [ 2 2 2 0 ]
:D7 [ 2 2 2 3 ]
:Dm [ 2 2 1 0 ]
;;:Dm7
:Eb [ 3 3 3 6 ]
:Eb7 [ 3 3 3 4 ]
:Ebm [ 3 6 6 6 ]
;;:Ebm7
:E [ 4 4 4 7 ]
:E7 [ 1 2 0 2 ]
:Em [ 0 4 3 2 ]
;;:Em7
:F [ 2 0 1 0 ]
:F7 [ 2 3 1 0 ]
:Fm [ 1 0 1 3 ]
;;:Fm7
:Gb [ 3 1 2 1 ]
:Gb7 [ 3 4 2 4 ]
:Gbm [ 2 1 2 0 ]
;;:Gbm7
:G [ 0 2 3 2 ]
:G7 [ 0 2 1 2 ]
:Gm [ 0 2 3 1 ]
;;:Gm7
:Ab [ 5 3 4 3 ]
:Ab7 [ 1 3 2 3 ]
:Abm [ 4 3 4 2 ]
;;:Abm7
})
;; ======================================================================
;; an array of 4 mandolin strings: GDAE
(def mandolin-string-notes (map note [:g3 :d4 :a4 :e5]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the mandolin instrument.
(def pick (partial pick-string mandolin-string-notes))
(def strum (partial strum-strings mandolin-chord-frets mandolin-string-notes))
;; ======================================================================
;; Create the mandolin definst. Now via the power of macros
(gen-stringed-inst mandolin 4)
|
101809
|
;; A Mandolin by <NAME>.
(ns explore-overtone.mandolin
(:use [explore-overtone.stringed]
[overtone.music pitch]
[overtone.studio inst]
[overtone.sc envelope node server ugens]
[overtone.sc.cgens mix]))
;; a map of chords to frets.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone
(def mandolin-chord-frets
{:A [ 6 1 0 0 ]
:A7 [ 2 2 4 3 ]
:Am [ 5 1 0 0 ]
;;:Am7
:Bb [ 3 0 1 1 ]
:Bb7 [ 3 3 5 4 ]
:Bbm [ 3 3 4 6 ]
;;:Bbm7
;; FIXME ... finish rest
:B [ 4 3 2 2 ]
:B7 [ 2 3 2 2 ]
:Bm [ 4 2 2 2 ]
;;:Bm7
:C [ 0 0 0 3 ]
:C7 [ 0 0 0 1 ]
:Cm [ 0 3 3 3 ]
;;:Cm7
:Db [ 1 1 1 4 ]
:Db7 [ 1 1 1 2 ]
:Dbm [ 1 4 4 4 ]
;;:Dbm7
:D [ 2 2 2 0 ]
:D7 [ 2 2 2 3 ]
:Dm [ 2 2 1 0 ]
;;:Dm7
:Eb [ 3 3 3 6 ]
:Eb7 [ 3 3 3 4 ]
:Ebm [ 3 6 6 6 ]
;;:Ebm7
:E [ 4 4 4 7 ]
:E7 [ 1 2 0 2 ]
:Em [ 0 4 3 2 ]
;;:Em7
:F [ 2 0 1 0 ]
:F7 [ 2 3 1 0 ]
:Fm [ 1 0 1 3 ]
;;:Fm7
:Gb [ 3 1 2 1 ]
:Gb7 [ 3 4 2 4 ]
:Gbm [ 2 1 2 0 ]
;;:Gbm7
:G [ 0 2 3 2 ]
:G7 [ 0 2 1 2 ]
:Gm [ 0 2 3 1 ]
;;:Gm7
:Ab [ 5 3 4 3 ]
:Ab7 [ 1 3 2 3 ]
:Abm [ 4 3 4 2 ]
;;:Abm7
})
;; ======================================================================
;; an array of 4 mandolin strings: GDAE
(def mandolin-string-notes (map note [:g3 :d4 :a4 :e5]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the mandolin instrument.
(def pick (partial pick-string mandolin-string-notes))
(def strum (partial strum-strings mandolin-chord-frets mandolin-string-notes))
;; ======================================================================
;; Create the mandolin definst. Now via the power of macros
(gen-stringed-inst mandolin 4)
| true |
;; A Mandolin by PI:NAME:<NAME>END_PI.
(ns explore-overtone.mandolin
(:use [explore-overtone.stringed]
[overtone.music pitch]
[overtone.studio inst]
[overtone.sc envelope node server ugens]
[overtone.sc.cgens mix]))
;; a map of chords to frets.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone
(def mandolin-chord-frets
{:A [ 6 1 0 0 ]
:A7 [ 2 2 4 3 ]
:Am [ 5 1 0 0 ]
;;:Am7
:Bb [ 3 0 1 1 ]
:Bb7 [ 3 3 5 4 ]
:Bbm [ 3 3 4 6 ]
;;:Bbm7
;; FIXME ... finish rest
:B [ 4 3 2 2 ]
:B7 [ 2 3 2 2 ]
:Bm [ 4 2 2 2 ]
;;:Bm7
:C [ 0 0 0 3 ]
:C7 [ 0 0 0 1 ]
:Cm [ 0 3 3 3 ]
;;:Cm7
:Db [ 1 1 1 4 ]
:Db7 [ 1 1 1 2 ]
:Dbm [ 1 4 4 4 ]
;;:Dbm7
:D [ 2 2 2 0 ]
:D7 [ 2 2 2 3 ]
:Dm [ 2 2 1 0 ]
;;:Dm7
:Eb [ 3 3 3 6 ]
:Eb7 [ 3 3 3 4 ]
:Ebm [ 3 6 6 6 ]
;;:Ebm7
:E [ 4 4 4 7 ]
:E7 [ 1 2 0 2 ]
:Em [ 0 4 3 2 ]
;;:Em7
:F [ 2 0 1 0 ]
:F7 [ 2 3 1 0 ]
:Fm [ 1 0 1 3 ]
;;:Fm7
:Gb [ 3 1 2 1 ]
:Gb7 [ 3 4 2 4 ]
:Gbm [ 2 1 2 0 ]
;;:Gbm7
:G [ 0 2 3 2 ]
:G7 [ 0 2 1 2 ]
:Gm [ 0 2 3 1 ]
;;:Gm7
:Ab [ 5 3 4 3 ]
:Ab7 [ 1 3 2 3 ]
:Abm [ 4 3 4 2 ]
;;:Abm7
})
;; ======================================================================
;; an array of 4 mandolin strings: GDAE
(def mandolin-string-notes (map note [:g3 :d4 :a4 :e5]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the mandolin instrument.
(def pick (partial pick-string mandolin-string-notes))
(def strum (partial strum-strings mandolin-chord-frets mandolin-string-notes))
;; ======================================================================
;; Create the mandolin definst. Now via the power of macros
(gen-stringed-inst mandolin 4)
|
[
{
"context": "ng)\n\n(def default-firebase-config\n {:api-key \"AIzaSyAEEGdlXMkrxbF-OWbsDffCSKMogeiRvfA\"\n :project-id \"inferno-8d188\"})\n",
"end": 294,
"score": 0.9997024536132812,
"start": 255,
"tag": "KEY",
"value": "AIzaSyAEEGdlXMkrxbF-OWbsDffCSKMogeiRvfA"
}
] |
src/firemore/config.cljs
|
samedhi/firemore
| 18 |
(ns firemore.config
(:require
[clojure.string :as string]
[goog.object :as goog.object]))
(def TIMESTAMP :firemore/timestamp)
(def NO_DOCUMENT :firemore/no-document)
(def LOADING :firemore/loading)
(def default-firebase-config
{:api-key "AIzaSyAEEGdlXMkrxbF-OWbsDffCSKMogeiRvfA"
:project-id "inferno-8d188"})
|
60697
|
(ns firemore.config
(:require
[clojure.string :as string]
[goog.object :as goog.object]))
(def TIMESTAMP :firemore/timestamp)
(def NO_DOCUMENT :firemore/no-document)
(def LOADING :firemore/loading)
(def default-firebase-config
{:api-key "<KEY>"
:project-id "inferno-8d188"})
| true |
(ns firemore.config
(:require
[clojure.string :as string]
[goog.object :as goog.object]))
(def TIMESTAMP :firemore/timestamp)
(def NO_DOCUMENT :firemore/no-document)
(def LOADING :firemore/loading)
(def default-firebase-config
{:api-key "PI:KEY:<KEY>END_PI"
:project-id "inferno-8d188"})
|
[
{
"context": "d library + utilities\"\n :url \"https://github.com/nervous-systems/cljs-nodejs-externs\"\n :license {:name \"Apache 2.",
"end": 172,
"score": 0.9979227781295776,
"start": 157,
"tag": "USERNAME",
"value": "nervous-systems"
},
{
"context": ".0\"}\n :scm {:name \"git\" :url \"https://github.com/nervous-systems/cljs-nodejs-externs\"}\n :deploy-repositories [[\"c",
"end": 336,
"score": 0.9952586889266968,
"start": 321,
"tag": "USERNAME",
"value": "nervous-systems"
},
{
"context": "[[\"clojars\" {:creds :gpg}]]\n :signing {:gpg-key \"[email protected]\"}\n :plugins [[lein-npm \"0.5.0\"]]\n :profiles {:d",
"end": 446,
"score": 0.999633252620697,
"start": 432,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
project.clj
|
nervous-systems/cljs-node-externs
| 12 |
(defproject io.nervous/cljs-nodejs-externs "0.2.0"
:description "Packaged externs for the Node.js standard library + utilities"
:url "https://github.com/nervous-systems/cljs-nodejs-externs"
:license {:name "Apache 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"}
:scm {:name "git" :url "https://github.com/nervous-systems/cljs-nodejs-externs"}
:deploy-repositories [["clojars" {:creds :gpg}]]
:signing {:gpg-key "[email protected]"}
:plugins [[lein-npm "0.5.0"]]
:profiles {:dev
{:node-dependencies
[["closurecompiler-externs" "1.0.4"]]}})
|
37895
|
(defproject io.nervous/cljs-nodejs-externs "0.2.0"
:description "Packaged externs for the Node.js standard library + utilities"
:url "https://github.com/nervous-systems/cljs-nodejs-externs"
:license {:name "Apache 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"}
:scm {:name "git" :url "https://github.com/nervous-systems/cljs-nodejs-externs"}
:deploy-repositories [["clojars" {:creds :gpg}]]
:signing {:gpg-key "<EMAIL>"}
:plugins [[lein-npm "0.5.0"]]
:profiles {:dev
{:node-dependencies
[["closurecompiler-externs" "1.0.4"]]}})
| true |
(defproject io.nervous/cljs-nodejs-externs "0.2.0"
:description "Packaged externs for the Node.js standard library + utilities"
:url "https://github.com/nervous-systems/cljs-nodejs-externs"
:license {:name "Apache 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"}
:scm {:name "git" :url "https://github.com/nervous-systems/cljs-nodejs-externs"}
:deploy-repositories [["clojars" {:creds :gpg}]]
:signing {:gpg-key "PI:EMAIL:<EMAIL>END_PI"}
:plugins [[lein-npm "0.5.0"]]
:profiles {:dev
{:node-dependencies
[["closurecompiler-externs" "1.0.4"]]}})
|
[
{
"context": "rue)\n(set! *unchecked-math* false)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-11-23\"\n :doc \"scored vs all sub",
"end": 96,
"score": 0.9998756647109985,
"start": 78,
"tag": "NAME",
"value": "John Alan McDonald"
}
] |
src/scripts/clojure/taiga/scripts/profile/split/defs.clj
|
wahpenayo/taiga
| 4 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* false)
(ns ^{:author "John Alan McDonald" :date "2016-11-23"
:doc "scored vs all subsets." }
taiga.scripts.profile.split.defs
(:require [criterium.core :as criterium]
[zana.api :as z]
[taiga.forest :as forest]
[taiga.scripts.data.defs :as defs]
[taiga.scripts.data.record :as record]))
(set! *unchecked-math* :warn-on-boxed)
;;------------------------------------------------------------------------------
(defn primate-options []
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0) (* 64 1024))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))]
(assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/primate])))
;;------------------------------------------------------------------------------
(defn kolor-options []
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))]
(assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:kolor record/kolor])))
;;------------------------------------------------------------------------------
(defn bench [splitter options]
(println (z/name (first (:this-predictor options))))
(criterium/bench (splitter options)))
;;------------------------------------------------------------------------------
|
76024
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* false)
(ns ^{:author "<NAME>" :date "2016-11-23"
:doc "scored vs all subsets." }
taiga.scripts.profile.split.defs
(:require [criterium.core :as criterium]
[zana.api :as z]
[taiga.forest :as forest]
[taiga.scripts.data.defs :as defs]
[taiga.scripts.data.record :as record]))
(set! *unchecked-math* :warn-on-boxed)
;;------------------------------------------------------------------------------
(defn primate-options []
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0) (* 64 1024))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))]
(assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/primate])))
;;------------------------------------------------------------------------------
(defn kolor-options []
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))]
(assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:kolor record/kolor])))
;;------------------------------------------------------------------------------
(defn bench [splitter options]
(println (z/name (first (:this-predictor options))))
(criterium/bench (splitter options)))
;;------------------------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* false)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-11-23"
:doc "scored vs all subsets." }
taiga.scripts.profile.split.defs
(:require [criterium.core :as criterium]
[zana.api :as z]
[taiga.forest :as forest]
[taiga.scripts.data.defs :as defs]
[taiga.scripts.data.record :as record]))
(set! *unchecked-math* :warn-on-boxed)
;;------------------------------------------------------------------------------
(defn primate-options []
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0) (* 64 1024))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))]
(assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:primate record/primate])))
;;------------------------------------------------------------------------------
(defn kolor-options []
(z/reset-mersenne-twister-seeds)
(let [options (defs/options (record/make-pyramid-function 1.0))
options (forest/positive-fraction-probability-options options)
n (count (:data options))
;; cache arrays, mutated during numerical split optimization
x0 (double-array n)
y0 (double-array n)
w0 (when (:weight options) (double-array n))
y1 (double-array n)
w1 (when (:weight options) (double-array n))
perm (when (:weight options) (int-array n))]
(assoc options
:ground-truth record/true-class
:x0 x0 :y0 y0 :w0 w0 :perm perm :y1 y1 :w1 w1
:this-predictor [:kolor record/kolor])))
;;------------------------------------------------------------------------------
(defn bench [splitter options]
(println (z/name (first (:this-predictor options))))
(criterium/bench (splitter options)))
;;------------------------------------------------------------------------------
|
[
{
"context": "div.form-row\n [ :label { :for \"username\" } \"Username\" ]\n [ :input#user",
"end": 699,
"score": 0.9992617964744568,
"start": 691,
"tag": "USERNAME",
"value": "username"
},
{
"context": " [ :label { :for \"username\" } \"Username\" ]\n [ :input#username { :type ",
"end": 712,
"score": 0.9984931349754333,
"start": 704,
"tag": "USERNAME",
"value": "Username"
},
{
"context": "name\" } \"Username\" ]\n [ :input#username { :type \"text\" :name \"username\" } ]\n ",
"end": 753,
"score": 0.9929723739624023,
"start": 745,
"tag": "USERNAME",
"value": "username"
},
{
"context": " [ :input#username { :type \"text\" :name \"username\" } ]\n ]\n [ :div",
"end": 784,
"score": 0.9992532134056091,
"start": 776,
"tag": "USERNAME",
"value": "username"
},
{
"context": " [ :label { :for \"password\" } \"Password\" ]\n [ :input#password { :type ",
"end": 902,
"score": 0.9633886218070984,
"start": 894,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": " ]\n [ :input#password { :type \"password\" :name \"password\" } ]\n ]\n ",
"end": 961,
"score": 0.9813207387924194,
"start": 953,
"tag": "PASSWORD",
"value": "password"
}
] |
src/cesena/views/login.clj
|
dak0rn/taobaibai
| 0 |
;; login.clj - View for the login
(ns cesena.views.login
(:require [ cesena.views.partials.document :refer [ document ] ]
[ ring.util.anti-forgery :refer [ anti-forgery-field ] ]
[ hiccup.form :refer [ form-to ] ]))
(defn
^{
:doc "Renders the login form"
:added "0.1.0"
}
render-login
([ ] (render-login false))
([ has-error ]
(document "Cesena Login"
[ :div.login-window
[ :div.login-body
(when has-error [ :div.message.danger "Login failed" ])
(form-to [ :post "/login" ]
(anti-forgery-field)
[ :div.form-row
[ :label { :for "username" } "Username" ]
[ :input#username { :type "text" :name "username" } ]
]
[ :div.form-row
[ :label { :for "password" } "Password" ]
[ :input#password { :type "password" :name "password" } ]
]
[ :div.submit-row
[ :button "Login" ]
[ :div.clearfix ]
]
)
]])))
|
42161
|
;; login.clj - View for the login
(ns cesena.views.login
(:require [ cesena.views.partials.document :refer [ document ] ]
[ ring.util.anti-forgery :refer [ anti-forgery-field ] ]
[ hiccup.form :refer [ form-to ] ]))
(defn
^{
:doc "Renders the login form"
:added "0.1.0"
}
render-login
([ ] (render-login false))
([ has-error ]
(document "Cesena Login"
[ :div.login-window
[ :div.login-body
(when has-error [ :div.message.danger "Login failed" ])
(form-to [ :post "/login" ]
(anti-forgery-field)
[ :div.form-row
[ :label { :for "username" } "Username" ]
[ :input#username { :type "text" :name "username" } ]
]
[ :div.form-row
[ :label { :for "password" } "<PASSWORD>" ]
[ :input#password { :type "<PASSWORD>" :name "password" } ]
]
[ :div.submit-row
[ :button "Login" ]
[ :div.clearfix ]
]
)
]])))
| true |
;; login.clj - View for the login
(ns cesena.views.login
(:require [ cesena.views.partials.document :refer [ document ] ]
[ ring.util.anti-forgery :refer [ anti-forgery-field ] ]
[ hiccup.form :refer [ form-to ] ]))
(defn
^{
:doc "Renders the login form"
:added "0.1.0"
}
render-login
([ ] (render-login false))
([ has-error ]
(document "Cesena Login"
[ :div.login-window
[ :div.login-body
(when has-error [ :div.message.danger "Login failed" ])
(form-to [ :post "/login" ]
(anti-forgery-field)
[ :div.form-row
[ :label { :for "username" } "Username" ]
[ :input#username { :type "text" :name "username" } ]
]
[ :div.form-row
[ :label { :for "password" } "PI:PASSWORD:<PASSWORD>END_PI" ]
[ :input#password { :type "PI:PASSWORD:<PASSWORD>END_PI" :name "password" } ]
]
[ :div.submit-row
[ :button "Login" ]
[ :div.clearfix ]
]
)
]])))
|
[
{
"context": " :user \"root\"\n :password \"root\"\n })\n\n(defn get-clients []\n (sql/q",
"end": 219,
"score": 0.9992328882217407,
"start": 215,
"tag": "PASSWORD",
"value": "root"
}
] |
src/pawn_shop/db.clj
|
djordje-miladinovic/pawn-shop
| 0 |
(ns pawn-shop.db
(:require [clojure.java.jdbc :as sql])
)
(def mysql-db {
:subprotocol "mysql"
:subname "//localhost/pawn-shop"
:user "root"
:password "root"
})
(defn get-clients []
(sql/query mysql-db
["SELECT * FROM client"]
))
(defn get-client [id]
(sql/query mysql-db
["SELECT * FROM client WHERE id = ?" id]
))
(defn get-contracts []
(sql/query mysql-db
["SELECT * FROM contract"]
))
(defn get-contract [id]
(sql/query mysql-db
["SELECT * FROM contract WHERE id = ?" id]
))
(defn get-contract-items []
(sql/query mysql-db
["SELECT * FROM contract_item"]
))
(defn get-contract-item [id]
(sql/query mysql-db
["SELECT * FROM contract_item WHERE id = ?" id]
))
(defn get-contract-item-types []
(sql/query mysql-db
["SELECT * FROM contract_item_type"]
))
|
14384
|
(ns pawn-shop.db
(:require [clojure.java.jdbc :as sql])
)
(def mysql-db {
:subprotocol "mysql"
:subname "//localhost/pawn-shop"
:user "root"
:password "<PASSWORD>"
})
(defn get-clients []
(sql/query mysql-db
["SELECT * FROM client"]
))
(defn get-client [id]
(sql/query mysql-db
["SELECT * FROM client WHERE id = ?" id]
))
(defn get-contracts []
(sql/query mysql-db
["SELECT * FROM contract"]
))
(defn get-contract [id]
(sql/query mysql-db
["SELECT * FROM contract WHERE id = ?" id]
))
(defn get-contract-items []
(sql/query mysql-db
["SELECT * FROM contract_item"]
))
(defn get-contract-item [id]
(sql/query mysql-db
["SELECT * FROM contract_item WHERE id = ?" id]
))
(defn get-contract-item-types []
(sql/query mysql-db
["SELECT * FROM contract_item_type"]
))
| true |
(ns pawn-shop.db
(:require [clojure.java.jdbc :as sql])
)
(def mysql-db {
:subprotocol "mysql"
:subname "//localhost/pawn-shop"
:user "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
})
(defn get-clients []
(sql/query mysql-db
["SELECT * FROM client"]
))
(defn get-client [id]
(sql/query mysql-db
["SELECT * FROM client WHERE id = ?" id]
))
(defn get-contracts []
(sql/query mysql-db
["SELECT * FROM contract"]
))
(defn get-contract [id]
(sql/query mysql-db
["SELECT * FROM contract WHERE id = ?" id]
))
(defn get-contract-items []
(sql/query mysql-db
["SELECT * FROM contract_item"]
))
(defn get-contract-item [id]
(sql/query mysql-db
["SELECT * FROM contract_item WHERE id = ?" id]
))
(defn get-contract-item-types []
(sql/query mysql-db
["SELECT * FROM contract_item_type"]
))
|
[
{
"context": "oducers_pkey\",\n :index_keys [\"id\"],\n :type \"btree\",\n ",
"end": 15906,
"score": 0.7996883988380432,
"start": 15904,
"tag": "KEY",
"value": "id"
},
{
"context": "ers_name_key\",\n :index_keys [\"name\"],\n :type \"btree\",\n ",
"end": 16369,
"score": 0.9716429710388184,
"start": 16365,
"tag": "KEY",
"value": "name"
},
{
"context": "atalogs_prod\",\n :index_keys [\"producer_id\"],\n :type \"btree\",\n ",
"end": 16838,
"score": 0.9897444844245911,
"start": 16827,
"tag": "KEY",
"value": "producer_id"
},
{
"context": "reports_prod\",\n :index_keys [\"producer_id\"],\n :type \"btree\",\n ",
"end": 17306,
"score": 0.9872615337371826,
"start": 17295,
"tag": "KEY",
"value": "producer_id"
},
{
"context": "actsets_prod\",\n :index_keys [\"producer_id\"],\n :type \"btree\",\n ",
"end": 17776,
"score": 0.9898161888122559,
"start": 17765,
"tag": "KEY",
"value": "producer_id"
},
{
"context": "s_pkey\"\n :index_keys [\"id\"]\n :type \"btree\"\n ",
"end": 31259,
"score": 0.9220042824745178,
"start": 31257,
"tag": "KEY",
"value": "id"
},
{
"context": ":primary? true\n :user \"pdb_test\"}\n :right-only nil\n ",
"end": 31525,
"score": 0.9891610145568848,
"start": 31517,
"tag": "USERNAME",
"value": "pdb_test"
},
{
"context": "id_idx\"\n :index_keys [\"fact_value_id\"]\n :type \"btree\"\n ",
"end": 31851,
"score": 0.9886654615402222,
"start": 31838,
"tag": "KEY",
"value": "fact_value_id"
},
{
"context": "primary? false\n :user \"pdb_test\"}\n :right-only nil\n ",
"end": 32119,
"score": 0.9936366081237793,
"start": 32111,
"tag": "USERNAME",
"value": "pdb_test"
},
{
"context": "sh_key\"\n :index_keys [\"value_hash\"]\n :type \"btree\"\n ",
"end": 32451,
"score": 0.9855100512504578,
"start": 32441,
"tag": "KEY",
"value": "value_hash"
},
{
"context": "primary? false\n :user \"pdb_test\"}\n :right-only nil\n ",
"end": 32718,
"score": 0.9927789568901062,
"start": 32710,
"tag": "USERNAME",
"value": "pdb_test"
},
{
"context": "id_idx\"\n :index_keys [\"factset_id\"]\n :type \"btree\"\n ",
"end": 33122,
"score": 0.9378654360771179,
"start": 33112,
"tag": "KEY",
"value": "factset_id"
},
{
"context": "primary? false\n :user \"pdb_test\"}\n :same nil}\n ",
"end": 33390,
"score": 0.9935629963874817,
"start": 33382,
"tag": "USERNAME",
"value": "pdb_test"
},
{
"context": "primary? false\n :user \"pdb_test\"}\n :right-only nil\n ",
"end": 33967,
"score": 0.999575138092041,
"start": 33959,
"tag": "USERNAME",
"value": "pdb_test"
},
{
"context": "acts_value_string_trgm\"\n :index_keys [\"value_string\"]\n :type \"gin\"\n :uniq",
"end": 37932,
"score": 0.5943913459777832,
"start": 37926,
"tag": "KEY",
"value": "value_"
},
{
"context": "se\n :primary? false\n :user \"pdb_test\"}\n (get idxs [\"facts\" [\"value_string\"]]",
"end": 38108,
"score": 0.9974520802497864,
"start": 38100,
"tag": "USERNAME",
"value": "pdb_test"
}
] |
test/puppetlabs/puppetdb/scf/migrate_test.clj
|
er0ck/puppetdb
| 0 |
(ns puppetlabs.puppetdb.scf.migrate-test
(:require [clojure.set :as set]
[puppetlabs.puppetdb.scf.hash :as hash]
[puppetlabs.puppetdb.scf.migrate :as migrate]
[puppetlabs.puppetdb.scf.storage :as store]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.scf.storage-utils :as sutils
:refer [db-serialize]]
[cheshire.core :as json]
[clojure.java.jdbc :as sql]
[puppetlabs.puppetdb.scf.migrate :refer :all]
[clj-time.coerce :refer [to-timestamp]]
[clj-time.core :refer [now ago days]]
[clojure.test :refer :all]
[clojure.set :refer :all]
[puppetlabs.puppetdb.jdbc :as jdbc :refer [query-to-vec]]
[puppetlabs.puppetdb.testutils.db :as tdb
:refer [*db* clear-db-for-testing!
schema-info-map diff-schema-maps]]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.puppetdb.testutils.db :refer [*db* with-test-db]])
(:import [java.sql SQLIntegrityConstraintViolationException]
[org.postgresql.util PSQLException]))
(use-fixtures :each tdb/call-with-test-db)
(defn apply-migration-for-testing!
[i]
(let [migration (migrations i)]
(migration)
(record-migration! i)))
(defn fast-forward-to-migration!
[migration-number]
(doseq [[i migration] (sort migrations)
:while (<= i migration-number)]
(migration)
(record-migration! i)))
(deftest migration
(testing "pending migrations"
(testing "should return every migration if the *db* isn't migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(is (= (pending-migrations) migrations))))
(testing "should return nothing if the *db* is completely migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(migrate! *db*)
(is (empty? (pending-migrations)))))
(testing "should return missing migrations if the *db* is partially migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(let [applied '(28 29 31)]
(doseq [m applied]
(apply-migration-for-testing! m))
(is (= (set (keys (pending-migrations)))
(difference (set (keys migrations))
(set applied))))))))
(testing "applying the migrations"
(let [expected-migrations (apply sorted-set (keys migrations))]
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(is (= (applied-migrations) #{}))
(testing "should migrate the database"
(migrate! *db*)
(is (= (applied-migrations) expected-migrations)))
(testing "should not do anything the second time"
(migrate! *db*)
(is (= (applied-migrations) expected-migrations)))
(testing "should attempt a partial migration if there are migrations missing"
(clear-db-for-testing!)
;; We are using migration 19 here because it is isolated enough to be able
;; to execute on its own. This might need to be changed in the future.
(doseq [m (filter (fn [[i migration]] (not= i 36)) (pending-migrations))]
(apply-migration-for-testing! (first m)))
(is (= (keys (pending-migrations)) '(36)))
(migrate! *db*)
(is (= (applied-migrations) expected-migrations))))))
(testing "should throw error if *db* is at a higher schema rev than we support"
(jdbc/with-transacted-connection *db*
(migrate! *db*)
(jdbc/insert! :schema_migrations
{:version (inc migrate/desired-schema-version)
:time (to-timestamp (now))})
(is (thrown? IllegalStateException (migrate! *db*))))))
(deftest migration-29
(testing "should contain same reports before and after migration"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :report_statuses
{:status "testing1" :id 1})
(jdbc/insert! :environments
{:id 1 :name "testing1"})
(jdbc/insert-multi! :certnames
[{:name "testing1" :deactivated nil}
{:name "testing2" :deactivated nil}])
(jdbc/insert-multi!
:reports
[{:hash "01"
:configuration_version "thisisacoolconfigversion"
:transaction_uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"
:certname "testing1"
:puppet_version "0.0.0"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:environment_id 1
:status_id 1}
{:hash "0000"
:transaction_uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"
:configuration_version "blahblahblah"
:certname "testing2"
:puppet_version "911"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:environment_id 1
:status_id 1}])
(jdbc/insert-multi! :latest_reports
[{:report "01" :certname "testing1"}
{:report "0000" :certname "testing2"}])
(apply-migration-for-testing! 29)
(let [response
(query-to-vec
"SELECT encode(r.hash::bytea, 'hex') AS hash, r.certname,
e.name AS environment, rs.status, r.transaction_uuid::text AS uuid
FROM certnames c
INNER JOIN reports r on c.latest_report_id=r.id
AND c.certname=r.certname
INNER JOIN environments e on r.environment_id=e.id
INNER JOIN report_statuses rs on r.status_id=rs.id
order by c.certname")]
;; every node should with facts should be represented
(is (= response
[{:hash "01" :environment "testing1" :certname "testing1" :status "testing1" :uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"}
{:hash "0000" :environment "testing1" :certname "testing2" :status "testing1" :uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"}])))
(let [[id1 id2] (map :id
(query-to-vec "SELECT id from reports order by certname"))]
(let [latest-ids (map :latest_report_id
(query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= [id1 id2] latest-ids))))))))
(deftest migration-37
(testing "should contain same reports before and after migration"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 36)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :report_statuses
{:status "testing1" :id 1})
(jdbc/insert! :environments
{:id 1 :environment "testing1"})
(jdbc/insert-multi! :certnames
[{:certname "testing1" :deactivated nil}
{:certname "testing2" :deactivated nil}])
(jdbc/insert-multi!
:reports
[{:hash (sutils/munge-hash-for-storage "01")
:transaction_uuid (sutils/munge-uuid-for-storage
"bbbbbbbb-2222-bbbb-bbbb-222222222222")
:configuration_version "thisisacoolconfigversion"
:certname "testing1"
:puppet_version "0.0.0"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:producer_timestamp current-time
:environment_id 1
:status_id 1
:metrics (sutils/munge-json-for-storage [{:foo "bar"}])
:logs (sutils/munge-json-for-storage [{:bar "baz"}])}
{:hash (sutils/munge-hash-for-storage "0000")
:transaction_uuid (sutils/munge-uuid-for-storage
"aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa")
:configuration_version "blahblahblah"
:certname "testing2"
:puppet_version "911"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:producer_timestamp current-time
:environment_id 1
:status_id 1
:metrics (sutils/munge-json-for-storage [{:foo "bar"}])
:logs (sutils/munge-json-for-storage [{:bar "baz"}])}])
(jdbc/update! :certnames
{:latest_report_id 1}
["certname = ?" "testing1"])
(jdbc/update! :certnames
{:latest_report_id 2}
["certname = ?" "testing2"])
(apply-migration-for-testing! 37)
(let [response
(query-to-vec
"SELECT encode(r.hash, 'hex') AS hash, r.certname, e.environment, rs.status,
r.transaction_uuid::text AS uuid,
coalesce(metrics_json::jsonb, metrics) as metrics,
coalesce(logs_json::jsonb, logs) as logs
FROM certnames c
INNER JOIN reports r
ON c.latest_report_id=r.id AND c.certname=r.certname
INNER JOIN environments e ON r.environment_id=e.id
INNER JOIN report_statuses rs ON r.status_id=rs.id
ORDER BY c.certname")]
;; every node should with facts should be represented
(is (= [{:metrics [{:foo "bar"}] :logs [{:bar "baz"}]
:hash "01" :environment "testing1" :certname "testing1" :status "testing1" :uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"}
{:metrics [{:foo "bar"}] :logs [{:bar "baz"}]
:hash "0000" :environment "testing1" :certname "testing2" :status "testing1" :uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"}]
(map (comp #(update % :metrics sutils/parse-db-json)
#(update % :logs sutils/parse-db-json)) response))))
(let [[id1 id2] (map :id
(query-to-vec "SELECT id from reports order by certname"))]
(let [latest-ids (map :latest_report_id
(query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= [id1 id2] latest-ids))))))))
(deftest migration-29-producer-timestamp-not-null
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :environments
{:id 1 :name "test env"})
(jdbc/insert! :certnames
{:name "foo.local"})
(jdbc/insert! :catalogs
{:hash "18440af604d18536b1c77fd688dff8f0f9689d90"
:api_version 1
:catalog_version 1
:transaction_uuid "95d132b3-cb21-4e0a-976d-9a65567696ba"
:timestamp current-time
:certname "foo.local"
:environment_id 1
:producer_timestamp nil})
(jdbc/insert! :factsets
{:timestamp current-time
:certname "foo.local"
:environment_id 1
:producer_timestamp nil})
(apply-migration-for-testing! 29)
(let [catalogs-response (query-to-vec "SELECT producer_timestamp FROM catalogs")
factsets-response (query-to-vec "SELECT producer_timestamp FROM factsets")]
(is (= catalogs-response [{:producer_timestamp current-time}]))
(is (= factsets-response [{:producer_timestamp current-time}]))))))
(deftest migration-in-different-schema
(jdbc/with-db-connection *db*
(let [db-config {:database *db*}
test-db-name (tdb/subname->validated-db-name (:subname *db*))]
(clear-db-for-testing!)
(jdbc/with-db-connection (tdb/db-admin-config)
(let [db (tdb/subname->validated-db-name (:subname *db*))
user (get-in tdb/test-env [:user :name])]
(assert (tdb/valid-sql-id? db))
(jdbc/do-commands
(format "grant create on database %s to %s"
db (get-in tdb/test-env [:user :name])))))
(jdbc/do-commands
"CREATE SCHEMA pdbtestschema"
"SET SCHEMA 'pdbtestschema'")
(jdbc/with-db-connection (tdb/db-admin-config test-db-name)
(jdbc/do-commands
"DROP EXTENSION pg_trgm"
"CREATE EXTENSION pg_trgm WITH SCHEMA pdbtestschema"))
;; Currently sql-current-connection-table-names only looks in public.
(is (empty? (sutils/sql-current-connection-table-names)))
(migrate! *db*)
(indexes! db-config)
(indexes! db-config))))
(deftest test-hash-field-not-nullable
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 40)
(let [factset-template {:timestamp (to-timestamp (now))
:environment_id (store/ensure-environment "prod")
:producer_timestamp (to-timestamp (now))}
factset-data (map (fn [fs]
(merge factset-template fs))
[{:certname "foo.com"
:hash nil}
{:certname "bar.com"
:hash nil}
{:certname "baz.com"
:hash (sutils/munge-hash-for-storage "abc123")}])]
(jdbc/insert-multi! :certnames (map (fn [{:keys [certname]}]
{:certname certname :deactivated nil})
factset-data))
(jdbc/insert-multi! :factsets factset-data)
(is (= 2 (:c (first (query-to-vec "SELECT count(*) as c FROM factsets where hash is null")))))
(apply-migration-for-testing! 41)
(is (zero? (:c (first (query-to-vec "SELECT count(*) as c FROM factsets where hash is null"))))))))
(deftest test-only-hash-field-change
(clear-db-for-testing!)
(fast-forward-to-migration! 40)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 41)
(is (= {:index-diff nil,
:table-diff [{:left-only {:nullable? "YES"}
:right-only {:nullable? "NO"}
:same {:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "hash"
:table_name "factsets"}}]}
(diff-schema-maps before-migration (schema-info-map *db*))))))
(deftest test-add-producer-to-reports-catalogs-and-factsets-migration
(clear-db-for-testing!)
(fast-forward-to-migration! 46)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 47)
(let [schema-diff (diff-schema-maps before-migration (schema-info-map *db*))]
(is (= (set [{:left-only nil,
:right-only
{:schema "public",
:table "producers",
:index "producers_pkey",
:index_keys ["id"],
:type "btree",
:unique? true,
:functional? false,
:is_partial false,
:primary? true},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "producers",
:index "producers_name_key",
:index_keys ["name"],
:type "btree",
:unique? true,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "catalogs",
:index "idx_catalogs_prod",
:index_keys ["producer_id"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "reports",
:index "idx_reports_prod",
:index_keys ["producer_id"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "factsets",
:index "idx_factsets_prod",
:index_keys ["producer_id"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}])
(->> (:index-diff schema-diff)
(map #(kitchensink/mapvals (fn [idx] (dissoc idx :user)) %))
set)))
(is (= (set [{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "reports"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default "nextval('producers_id_seq'::regclass)",
:character_octet_length nil,
:datetime_precision nil,
:nullable? "NO",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "id",
:table_name "producers"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "catalogs"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale nil,
:column_default nil,
:character_octet_length 1073741824,
:datetime_precision nil,
:nullable? "NO",
:character_maximum_length nil,
:numeric_precision nil,
:numeric_precision_radix nil,
:data_type "text",
:column_name "name",
:table_name "producers"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "factsets"},
:same nil}])
(set (:table-diff schema-diff)))))))
(deftest test-migrate-from-unsupported-version
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(jdbc/do-commands "DELETE FROM schema_migrations")
(record-migration! 27)
(is (thrown-with-msg? IllegalStateException
#"Found an old and unuspported database migration.*"
(migrate! *db*))))
(deftest md5-agg-test
(with-test-db
(jdbc/with-db-connection *db*
(testing "dual_md5 function"
(is (= [{:encode "187ef4436122d1cc2f40dc2b92f0eba0"}]
(query-to-vec "select encode(dual_md5('a', 'b'), 'hex')"))))
(testing "md5_agg custom aggregator"
;; this hash is different from the above because it starts by executing
;; dual_md5(0::bytea, 'a'::bytea)
(is (= [{:encode "bdef73571a96923bdc6b78b5345377d3"}]
(query-to-vec
(str "select encode(md5_agg(val), 'hex') "
"from (values (1, 'a'::bytea), (1, 'b'::bytea)) x(gid, val) "
"group by gid"))))))))
(deftest migration-50-remove-historical-catalogs
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 49)
(jdbc/insert! :environments
{:id 1 :environment "testing"})
(jdbc/insert! :certnames
{:certname "foo.local"})
(jdbc/insert! :catalogs
{:hash (sutils/munge-hash-for-storage
"18440af604d18536b1c77fd688dff8f0f9689d90")
:id 1
:api_version 1
:catalog_version 1
:transaction_uuid (sutils/munge-uuid-for-storage
"95d132b3-cb21-4e0a-976d-9a65567696ba")
:timestamp (to-timestamp (now))
:certname "foo.local"
:environment_id 1
:producer_timestamp (to-timestamp (now))})
(jdbc/insert! :catalogs
{:hash (sutils/munge-hash-for-storage
"18445af604d18536b1c77fd688dff8f0f9689d90")
:id 2
:api_version 1
:catalog_version 1
:transaction_uuid (sutils/munge-uuid-for-storage
"95d136b3-cb21-4e0a-976d-9a65567696ba")
:timestamp (to-timestamp (now))
:certname "foo.local"
:environment_id 1
:producer_timestamp (to-timestamp (now))})
(jdbc/insert! :latest_catalogs
{:certname_id 1 :catalog_id 2})
(let [original-catalogs (jdbc/query-to-vec "select id from catalogs")
_ (apply-migration-for-testing! 50)
new-catalogs (jdbc/query-to-vec "select id from catalogs")]
(is (= #{1 2} (set (map :id original-catalogs))))
(is (= #{2} (set (map :id new-catalogs)))))))
(deftest test-migrate-from-unsupported-version
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(jdbc/do-commands "DELETE FROM schema_migrations")
(record-migration! 27)
(is (thrown-with-msg? IllegalStateException
#"Found an old and unuspported database migration.*"
(migrate! *db*))))
(deftest md5-agg-test
(with-test-db
(jdbc/with-db-connection *db*
(testing "dual_md5 function"
(is (= [{:encode "187ef4436122d1cc2f40dc2b92f0eba0"}]
(query-to-vec "select encode(dual_md5('a', 'b'), 'hex')"))))
(testing "md5_agg custom aggregator"
;; this hash is different from the above because it starts by executing
;; dual_md5(0::bytea, 'a'::bytea)
(is (= [{:encode "bdef73571a96923bdc6b78b5345377d3"}]
(query-to-vec
(str "select encode(md5_agg(val), 'hex') "
"from (values (1, 'a'::bytea), (1, 'b'::bytea)) x(gid, val) "
"group by gid"))))))))
(deftest test-fact-values-value->jsonb
(clear-db-for-testing!)
(fast-forward-to-migration! 49)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 51)
(is (= {:index-diff nil
:table-diff [{:left-only {:data_type "text",
:character_octet_length 1073741824},
:right-only {:data_type "jsonb",
:character_octet_length nil},
:same {:table_name "fact_values",
:column_name "value",
:numeric_precision_radix nil,
:numeric_precision nil,
:character_maximum_length nil,
:nullable? "YES",
:datetime_precision nil,
:column_default nil,
:numeric_scale nil}}]}
(diff-schema-maps before-migration (schema-info-map *db*))))))
(deftest test-resource-params-cache-parameters-to-jsonb
(clear-db-for-testing!)
(fast-forward-to-migration! 51)
(let [before-migration (schema-info-map *db*)]
(jdbc/insert! :resource_params_cache
{:resource (sutils/munge-hash-for-storage "a0a0a0")
:parameters (json/generate-string {:a "apple" :b {:1 "bear" :2 "button" :3 "butts"}})})
(jdbc/insert! :resource_params_cache
{:resource (sutils/munge-hash-for-storage "b1b1b1")
:parameters (json/generate-string {:c "camel" :d {:1 "dinosaur" :2 "donkey" :3 "daffodil"}})})
(apply-migration-for-testing! 52)
(testing "should migrate resource_params_cache data correctly"
(let [responses
(query-to-vec
(format "SELECT %s as resource, parameters FROM resource_params_cache"
(sutils/sql-hash-as-str "resource")))
parsed-responses (for [response responses] (assoc response :parameters (sutils/parse-db-json (response :parameters))))]
(is (= parsed-responses
[{:resource "a0a0a0" :parameters {:a "apple" :b {:1 "bear" :2 "button" :3 "butts"}}}
{:resource "b1b1b1" :parameters {:c "camel" :d {:1 "dinosaur" :2 "donkey" :3 "daffodil"}}}]))))
(testing "should change only value column type"
(let [schema-diff (diff-schema-maps before-migration (schema-info-map *db*))]
(is (= #{}
(->> (:index-diff schema-diff)
(map #(kitchensink/mapvals (fn [idx] (dissoc idx :user)) %))
set)))
(is (= #{{:left-only
{:data_type "text", :character_octet_length 1073741824},
:right-only
{:data_type "jsonb", :character_octet_length nil},
:same
{:table_name "resource_params_cache",
:column_name "parameters",
:numeric_precision_radix nil,
:numeric_precision nil,
:character_maximum_length nil,
:nullable? "YES",
:datetime_precision nil,
:column_default nil,
:numeric_scale nil}}}
(set (:table-diff schema-diff))))))))
(deftest fact-values-reduplication-schema-diff
;; This does not check the value_string trgm index since it is
;; created opportunistically later in trgm-indexes!
(clear-db-for-testing!)
(fast-forward-to-migration! 55)
(let [initial (schema-info-map *db*)]
(apply-migration-for-testing! 56)
(let [migrated (schema-info-map *db*)
rename-idx (fn [smap idx-id new-table new-name]
(let [idxs (:indexes smap)
idx-info (get idxs idx-id)
new-info (assoc idx-info
:table new-table
:index new-name)
new-id (assoc idx-id 0 new-table)]
(assert idx-info)
(update smap :indexes
#(-> %
(dissoc idx-id)
(assoc new-id new-info)))))
move-col (fn [smap idx-id new-table]
(let [idxs (:tables smap)
idx-info (get idxs idx-id)
new-info (assoc idx-info
:table_name new-table)
new-id (assoc idx-id 0 new-table)]
(assert idx-info)
(update smap :tables
#(-> %
(dissoc idx-id)
(assoc new-id new-info)))))
exp-smap (-> initial
(rename-idx ["fact_values" ["value_integer"]]
"facts" "facts_value_integer_idx")
(rename-idx ["fact_values" ["value_float"]]
"facts" "facts_value_float_idx")
(move-col ["fact_values" "value_type_id"] "facts")
(move-col ["fact_values" "value"] "facts")
(move-col ["fact_values" "value_boolean"] "facts")
(move-col ["fact_values" "value_integer"] "facts")
(move-col ["fact_values" "value_float"] "facts")
(move-col ["fact_values" "value_string"] "facts"))
diff (-> (diff-schema-maps exp-smap migrated)
(update :index-diff set)
(update :table-diff set))
exp-idx-diffs #{ ;; removed indexes
{:left-only
{:schema "public"
:table "fact_values"
:index "fact_values_pkey"
:index_keys ["id"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? true
:user "pdb_test"}
:right-only nil
:same nil}
{:left-only
{:schema "public"
:table "facts"
:index "facts_fact_value_id_idx"
:index_keys ["fact_value_id"]
:type "btree"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}
{:left-only
{:schema "public"
:table "fact_values"
:index "fact_values_value_hash_key"
:index_keys ["value_hash"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}
;; new indexes
{:left-only nil
:right-only
{:schema "public"
:table "facts"
:index "facts_factset_id_idx"
:index_keys ["factset_id"]
:type "btree"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:same nil}
{:left-only
{:schema "public"
:table "facts"
:index "facts_factset_id_fact_path_id_fact_key"
:index_keys ["factset_id" "fact_path_id"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}}
exp-table-diffs #{ ;; removed columns
{:left-only
{:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "value_hash"
:table_name "fact_values"}
:right-only nil
:same nil}
{:left-only
{:numeric_scale 0
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision 64
:numeric_precision_radix 2
:data_type "bigint"
:column_name "fact_value_id"
:table_name "facts"}
:right-only nil
:same nil}
{:left-only
{:numeric_scale 0
:column_default "nextval('fact_values_id_seq'::regclass)"
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision 64
:numeric_precision_radix 2
:data_type "bigint"
:column_name "id"
:table_name "fact_values"}
:right-only nil
:same nil}
;; new columns
{:left-only nil
:right-only
{:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "YES"
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "large_value_hash"
:table_name "facts"}
:same nil}}
expected {:index-diff exp-idx-diffs
:table-diff exp-table-diffs}]
;; Handy when trying to see what's wrong.
(when-not (= expected diff)
(let [unex (-> diff
(update :index-diff set/difference exp-idx-diffs)
(update :table-diff set/difference exp-table-diffs))]
(binding [*out* *err*]
(println "Unexpected differences:")
(clojure.pprint/pprint unex))))
(is (= expected diff)))))
(deftest trgm-indexes-as-expected
;; Assume the current *db* supports trgm
(clear-db-for-testing!)
(migrate! *db*)
(indexes! (:database *db*))
(let [idxs (:indexes (schema-info-map *db*))]
(is (= {:schema "public"
:table "facts"
:index "facts_value_string_trgm"
:index_keys ["value_string"]
:type "gin"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
(get idxs ["facts" ["value_string"]])))))
|
55500
|
(ns puppetlabs.puppetdb.scf.migrate-test
(:require [clojure.set :as set]
[puppetlabs.puppetdb.scf.hash :as hash]
[puppetlabs.puppetdb.scf.migrate :as migrate]
[puppetlabs.puppetdb.scf.storage :as store]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.scf.storage-utils :as sutils
:refer [db-serialize]]
[cheshire.core :as json]
[clojure.java.jdbc :as sql]
[puppetlabs.puppetdb.scf.migrate :refer :all]
[clj-time.coerce :refer [to-timestamp]]
[clj-time.core :refer [now ago days]]
[clojure.test :refer :all]
[clojure.set :refer :all]
[puppetlabs.puppetdb.jdbc :as jdbc :refer [query-to-vec]]
[puppetlabs.puppetdb.testutils.db :as tdb
:refer [*db* clear-db-for-testing!
schema-info-map diff-schema-maps]]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.puppetdb.testutils.db :refer [*db* with-test-db]])
(:import [java.sql SQLIntegrityConstraintViolationException]
[org.postgresql.util PSQLException]))
(use-fixtures :each tdb/call-with-test-db)
(defn apply-migration-for-testing!
[i]
(let [migration (migrations i)]
(migration)
(record-migration! i)))
(defn fast-forward-to-migration!
[migration-number]
(doseq [[i migration] (sort migrations)
:while (<= i migration-number)]
(migration)
(record-migration! i)))
(deftest migration
(testing "pending migrations"
(testing "should return every migration if the *db* isn't migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(is (= (pending-migrations) migrations))))
(testing "should return nothing if the *db* is completely migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(migrate! *db*)
(is (empty? (pending-migrations)))))
(testing "should return missing migrations if the *db* is partially migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(let [applied '(28 29 31)]
(doseq [m applied]
(apply-migration-for-testing! m))
(is (= (set (keys (pending-migrations)))
(difference (set (keys migrations))
(set applied))))))))
(testing "applying the migrations"
(let [expected-migrations (apply sorted-set (keys migrations))]
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(is (= (applied-migrations) #{}))
(testing "should migrate the database"
(migrate! *db*)
(is (= (applied-migrations) expected-migrations)))
(testing "should not do anything the second time"
(migrate! *db*)
(is (= (applied-migrations) expected-migrations)))
(testing "should attempt a partial migration if there are migrations missing"
(clear-db-for-testing!)
;; We are using migration 19 here because it is isolated enough to be able
;; to execute on its own. This might need to be changed in the future.
(doseq [m (filter (fn [[i migration]] (not= i 36)) (pending-migrations))]
(apply-migration-for-testing! (first m)))
(is (= (keys (pending-migrations)) '(36)))
(migrate! *db*)
(is (= (applied-migrations) expected-migrations))))))
(testing "should throw error if *db* is at a higher schema rev than we support"
(jdbc/with-transacted-connection *db*
(migrate! *db*)
(jdbc/insert! :schema_migrations
{:version (inc migrate/desired-schema-version)
:time (to-timestamp (now))})
(is (thrown? IllegalStateException (migrate! *db*))))))
(deftest migration-29
(testing "should contain same reports before and after migration"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :report_statuses
{:status "testing1" :id 1})
(jdbc/insert! :environments
{:id 1 :name "testing1"})
(jdbc/insert-multi! :certnames
[{:name "testing1" :deactivated nil}
{:name "testing2" :deactivated nil}])
(jdbc/insert-multi!
:reports
[{:hash "01"
:configuration_version "thisisacoolconfigversion"
:transaction_uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"
:certname "testing1"
:puppet_version "0.0.0"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:environment_id 1
:status_id 1}
{:hash "0000"
:transaction_uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"
:configuration_version "blahblahblah"
:certname "testing2"
:puppet_version "911"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:environment_id 1
:status_id 1}])
(jdbc/insert-multi! :latest_reports
[{:report "01" :certname "testing1"}
{:report "0000" :certname "testing2"}])
(apply-migration-for-testing! 29)
(let [response
(query-to-vec
"SELECT encode(r.hash::bytea, 'hex') AS hash, r.certname,
e.name AS environment, rs.status, r.transaction_uuid::text AS uuid
FROM certnames c
INNER JOIN reports r on c.latest_report_id=r.id
AND c.certname=r.certname
INNER JOIN environments e on r.environment_id=e.id
INNER JOIN report_statuses rs on r.status_id=rs.id
order by c.certname")]
;; every node should with facts should be represented
(is (= response
[{:hash "01" :environment "testing1" :certname "testing1" :status "testing1" :uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"}
{:hash "0000" :environment "testing1" :certname "testing2" :status "testing1" :uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"}])))
(let [[id1 id2] (map :id
(query-to-vec "SELECT id from reports order by certname"))]
(let [latest-ids (map :latest_report_id
(query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= [id1 id2] latest-ids))))))))
(deftest migration-37
(testing "should contain same reports before and after migration"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 36)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :report_statuses
{:status "testing1" :id 1})
(jdbc/insert! :environments
{:id 1 :environment "testing1"})
(jdbc/insert-multi! :certnames
[{:certname "testing1" :deactivated nil}
{:certname "testing2" :deactivated nil}])
(jdbc/insert-multi!
:reports
[{:hash (sutils/munge-hash-for-storage "01")
:transaction_uuid (sutils/munge-uuid-for-storage
"bbbbbbbb-2222-bbbb-bbbb-222222222222")
:configuration_version "thisisacoolconfigversion"
:certname "testing1"
:puppet_version "0.0.0"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:producer_timestamp current-time
:environment_id 1
:status_id 1
:metrics (sutils/munge-json-for-storage [{:foo "bar"}])
:logs (sutils/munge-json-for-storage [{:bar "baz"}])}
{:hash (sutils/munge-hash-for-storage "0000")
:transaction_uuid (sutils/munge-uuid-for-storage
"aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa")
:configuration_version "blahblahblah"
:certname "testing2"
:puppet_version "911"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:producer_timestamp current-time
:environment_id 1
:status_id 1
:metrics (sutils/munge-json-for-storage [{:foo "bar"}])
:logs (sutils/munge-json-for-storage [{:bar "baz"}])}])
(jdbc/update! :certnames
{:latest_report_id 1}
["certname = ?" "testing1"])
(jdbc/update! :certnames
{:latest_report_id 2}
["certname = ?" "testing2"])
(apply-migration-for-testing! 37)
(let [response
(query-to-vec
"SELECT encode(r.hash, 'hex') AS hash, r.certname, e.environment, rs.status,
r.transaction_uuid::text AS uuid,
coalesce(metrics_json::jsonb, metrics) as metrics,
coalesce(logs_json::jsonb, logs) as logs
FROM certnames c
INNER JOIN reports r
ON c.latest_report_id=r.id AND c.certname=r.certname
INNER JOIN environments e ON r.environment_id=e.id
INNER JOIN report_statuses rs ON r.status_id=rs.id
ORDER BY c.certname")]
;; every node should with facts should be represented
(is (= [{:metrics [{:foo "bar"}] :logs [{:bar "baz"}]
:hash "01" :environment "testing1" :certname "testing1" :status "testing1" :uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"}
{:metrics [{:foo "bar"}] :logs [{:bar "baz"}]
:hash "0000" :environment "testing1" :certname "testing2" :status "testing1" :uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"}]
(map (comp #(update % :metrics sutils/parse-db-json)
#(update % :logs sutils/parse-db-json)) response))))
(let [[id1 id2] (map :id
(query-to-vec "SELECT id from reports order by certname"))]
(let [latest-ids (map :latest_report_id
(query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= [id1 id2] latest-ids))))))))
(deftest migration-29-producer-timestamp-not-null
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :environments
{:id 1 :name "test env"})
(jdbc/insert! :certnames
{:name "foo.local"})
(jdbc/insert! :catalogs
{:hash "18440af604d18536b1c77fd688dff8f0f9689d90"
:api_version 1
:catalog_version 1
:transaction_uuid "95d132b3-cb21-4e0a-976d-9a65567696ba"
:timestamp current-time
:certname "foo.local"
:environment_id 1
:producer_timestamp nil})
(jdbc/insert! :factsets
{:timestamp current-time
:certname "foo.local"
:environment_id 1
:producer_timestamp nil})
(apply-migration-for-testing! 29)
(let [catalogs-response (query-to-vec "SELECT producer_timestamp FROM catalogs")
factsets-response (query-to-vec "SELECT producer_timestamp FROM factsets")]
(is (= catalogs-response [{:producer_timestamp current-time}]))
(is (= factsets-response [{:producer_timestamp current-time}]))))))
(deftest migration-in-different-schema
(jdbc/with-db-connection *db*
(let [db-config {:database *db*}
test-db-name (tdb/subname->validated-db-name (:subname *db*))]
(clear-db-for-testing!)
(jdbc/with-db-connection (tdb/db-admin-config)
(let [db (tdb/subname->validated-db-name (:subname *db*))
user (get-in tdb/test-env [:user :name])]
(assert (tdb/valid-sql-id? db))
(jdbc/do-commands
(format "grant create on database %s to %s"
db (get-in tdb/test-env [:user :name])))))
(jdbc/do-commands
"CREATE SCHEMA pdbtestschema"
"SET SCHEMA 'pdbtestschema'")
(jdbc/with-db-connection (tdb/db-admin-config test-db-name)
(jdbc/do-commands
"DROP EXTENSION pg_trgm"
"CREATE EXTENSION pg_trgm WITH SCHEMA pdbtestschema"))
;; Currently sql-current-connection-table-names only looks in public.
(is (empty? (sutils/sql-current-connection-table-names)))
(migrate! *db*)
(indexes! db-config)
(indexes! db-config))))
(deftest test-hash-field-not-nullable
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 40)
(let [factset-template {:timestamp (to-timestamp (now))
:environment_id (store/ensure-environment "prod")
:producer_timestamp (to-timestamp (now))}
factset-data (map (fn [fs]
(merge factset-template fs))
[{:certname "foo.com"
:hash nil}
{:certname "bar.com"
:hash nil}
{:certname "baz.com"
:hash (sutils/munge-hash-for-storage "abc123")}])]
(jdbc/insert-multi! :certnames (map (fn [{:keys [certname]}]
{:certname certname :deactivated nil})
factset-data))
(jdbc/insert-multi! :factsets factset-data)
(is (= 2 (:c (first (query-to-vec "SELECT count(*) as c FROM factsets where hash is null")))))
(apply-migration-for-testing! 41)
(is (zero? (:c (first (query-to-vec "SELECT count(*) as c FROM factsets where hash is null"))))))))
(deftest test-only-hash-field-change
(clear-db-for-testing!)
(fast-forward-to-migration! 40)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 41)
(is (= {:index-diff nil,
:table-diff [{:left-only {:nullable? "YES"}
:right-only {:nullable? "NO"}
:same {:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "hash"
:table_name "factsets"}}]}
(diff-schema-maps before-migration (schema-info-map *db*))))))
(deftest test-add-producer-to-reports-catalogs-and-factsets-migration
(clear-db-for-testing!)
(fast-forward-to-migration! 46)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 47)
(let [schema-diff (diff-schema-maps before-migration (schema-info-map *db*))]
(is (= (set [{:left-only nil,
:right-only
{:schema "public",
:table "producers",
:index "producers_pkey",
:index_keys ["<KEY>"],
:type "btree",
:unique? true,
:functional? false,
:is_partial false,
:primary? true},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "producers",
:index "producers_name_key",
:index_keys ["<KEY>"],
:type "btree",
:unique? true,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "catalogs",
:index "idx_catalogs_prod",
:index_keys ["<KEY>"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "reports",
:index "idx_reports_prod",
:index_keys ["<KEY>"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "factsets",
:index "idx_factsets_prod",
:index_keys ["<KEY>"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}])
(->> (:index-diff schema-diff)
(map #(kitchensink/mapvals (fn [idx] (dissoc idx :user)) %))
set)))
(is (= (set [{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "reports"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default "nextval('producers_id_seq'::regclass)",
:character_octet_length nil,
:datetime_precision nil,
:nullable? "NO",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "id",
:table_name "producers"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "catalogs"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale nil,
:column_default nil,
:character_octet_length 1073741824,
:datetime_precision nil,
:nullable? "NO",
:character_maximum_length nil,
:numeric_precision nil,
:numeric_precision_radix nil,
:data_type "text",
:column_name "name",
:table_name "producers"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "factsets"},
:same nil}])
(set (:table-diff schema-diff)))))))
(deftest test-migrate-from-unsupported-version
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(jdbc/do-commands "DELETE FROM schema_migrations")
(record-migration! 27)
(is (thrown-with-msg? IllegalStateException
#"Found an old and unuspported database migration.*"
(migrate! *db*))))
(deftest md5-agg-test
(with-test-db
(jdbc/with-db-connection *db*
(testing "dual_md5 function"
(is (= [{:encode "187ef4436122d1cc2f40dc2b92f0eba0"}]
(query-to-vec "select encode(dual_md5('a', 'b'), 'hex')"))))
(testing "md5_agg custom aggregator"
;; this hash is different from the above because it starts by executing
;; dual_md5(0::bytea, 'a'::bytea)
(is (= [{:encode "bdef73571a96923bdc6b78b5345377d3"}]
(query-to-vec
(str "select encode(md5_agg(val), 'hex') "
"from (values (1, 'a'::bytea), (1, 'b'::bytea)) x(gid, val) "
"group by gid"))))))))
(deftest migration-50-remove-historical-catalogs
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 49)
(jdbc/insert! :environments
{:id 1 :environment "testing"})
(jdbc/insert! :certnames
{:certname "foo.local"})
(jdbc/insert! :catalogs
{:hash (sutils/munge-hash-for-storage
"18440af604d18536b1c77fd688dff8f0f9689d90")
:id 1
:api_version 1
:catalog_version 1
:transaction_uuid (sutils/munge-uuid-for-storage
"95d132b3-cb21-4e0a-976d-9a65567696ba")
:timestamp (to-timestamp (now))
:certname "foo.local"
:environment_id 1
:producer_timestamp (to-timestamp (now))})
(jdbc/insert! :catalogs
{:hash (sutils/munge-hash-for-storage
"18445af604d18536b1c77fd688dff8f0f9689d90")
:id 2
:api_version 1
:catalog_version 1
:transaction_uuid (sutils/munge-uuid-for-storage
"95d136b3-cb21-4e0a-976d-9a65567696ba")
:timestamp (to-timestamp (now))
:certname "foo.local"
:environment_id 1
:producer_timestamp (to-timestamp (now))})
(jdbc/insert! :latest_catalogs
{:certname_id 1 :catalog_id 2})
(let [original-catalogs (jdbc/query-to-vec "select id from catalogs")
_ (apply-migration-for-testing! 50)
new-catalogs (jdbc/query-to-vec "select id from catalogs")]
(is (= #{1 2} (set (map :id original-catalogs))))
(is (= #{2} (set (map :id new-catalogs)))))))
(deftest test-migrate-from-unsupported-version
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(jdbc/do-commands "DELETE FROM schema_migrations")
(record-migration! 27)
(is (thrown-with-msg? IllegalStateException
#"Found an old and unuspported database migration.*"
(migrate! *db*))))
(deftest md5-agg-test
(with-test-db
(jdbc/with-db-connection *db*
(testing "dual_md5 function"
(is (= [{:encode "187ef4436122d1cc2f40dc2b92f0eba0"}]
(query-to-vec "select encode(dual_md5('a', 'b'), 'hex')"))))
(testing "md5_agg custom aggregator"
;; this hash is different from the above because it starts by executing
;; dual_md5(0::bytea, 'a'::bytea)
(is (= [{:encode "bdef73571a96923bdc6b78b5345377d3"}]
(query-to-vec
(str "select encode(md5_agg(val), 'hex') "
"from (values (1, 'a'::bytea), (1, 'b'::bytea)) x(gid, val) "
"group by gid"))))))))
(deftest test-fact-values-value->jsonb
(clear-db-for-testing!)
(fast-forward-to-migration! 49)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 51)
(is (= {:index-diff nil
:table-diff [{:left-only {:data_type "text",
:character_octet_length 1073741824},
:right-only {:data_type "jsonb",
:character_octet_length nil},
:same {:table_name "fact_values",
:column_name "value",
:numeric_precision_radix nil,
:numeric_precision nil,
:character_maximum_length nil,
:nullable? "YES",
:datetime_precision nil,
:column_default nil,
:numeric_scale nil}}]}
(diff-schema-maps before-migration (schema-info-map *db*))))))
(deftest test-resource-params-cache-parameters-to-jsonb
(clear-db-for-testing!)
(fast-forward-to-migration! 51)
(let [before-migration (schema-info-map *db*)]
(jdbc/insert! :resource_params_cache
{:resource (sutils/munge-hash-for-storage "a0a0a0")
:parameters (json/generate-string {:a "apple" :b {:1 "bear" :2 "button" :3 "butts"}})})
(jdbc/insert! :resource_params_cache
{:resource (sutils/munge-hash-for-storage "b1b1b1")
:parameters (json/generate-string {:c "camel" :d {:1 "dinosaur" :2 "donkey" :3 "daffodil"}})})
(apply-migration-for-testing! 52)
(testing "should migrate resource_params_cache data correctly"
(let [responses
(query-to-vec
(format "SELECT %s as resource, parameters FROM resource_params_cache"
(sutils/sql-hash-as-str "resource")))
parsed-responses (for [response responses] (assoc response :parameters (sutils/parse-db-json (response :parameters))))]
(is (= parsed-responses
[{:resource "a0a0a0" :parameters {:a "apple" :b {:1 "bear" :2 "button" :3 "butts"}}}
{:resource "b1b1b1" :parameters {:c "camel" :d {:1 "dinosaur" :2 "donkey" :3 "daffodil"}}}]))))
(testing "should change only value column type"
(let [schema-diff (diff-schema-maps before-migration (schema-info-map *db*))]
(is (= #{}
(->> (:index-diff schema-diff)
(map #(kitchensink/mapvals (fn [idx] (dissoc idx :user)) %))
set)))
(is (= #{{:left-only
{:data_type "text", :character_octet_length 1073741824},
:right-only
{:data_type "jsonb", :character_octet_length nil},
:same
{:table_name "resource_params_cache",
:column_name "parameters",
:numeric_precision_radix nil,
:numeric_precision nil,
:character_maximum_length nil,
:nullable? "YES",
:datetime_precision nil,
:column_default nil,
:numeric_scale nil}}}
(set (:table-diff schema-diff))))))))
(deftest fact-values-reduplication-schema-diff
;; This does not check the value_string trgm index since it is
;; created opportunistically later in trgm-indexes!
(clear-db-for-testing!)
(fast-forward-to-migration! 55)
(let [initial (schema-info-map *db*)]
(apply-migration-for-testing! 56)
(let [migrated (schema-info-map *db*)
rename-idx (fn [smap idx-id new-table new-name]
(let [idxs (:indexes smap)
idx-info (get idxs idx-id)
new-info (assoc idx-info
:table new-table
:index new-name)
new-id (assoc idx-id 0 new-table)]
(assert idx-info)
(update smap :indexes
#(-> %
(dissoc idx-id)
(assoc new-id new-info)))))
move-col (fn [smap idx-id new-table]
(let [idxs (:tables smap)
idx-info (get idxs idx-id)
new-info (assoc idx-info
:table_name new-table)
new-id (assoc idx-id 0 new-table)]
(assert idx-info)
(update smap :tables
#(-> %
(dissoc idx-id)
(assoc new-id new-info)))))
exp-smap (-> initial
(rename-idx ["fact_values" ["value_integer"]]
"facts" "facts_value_integer_idx")
(rename-idx ["fact_values" ["value_float"]]
"facts" "facts_value_float_idx")
(move-col ["fact_values" "value_type_id"] "facts")
(move-col ["fact_values" "value"] "facts")
(move-col ["fact_values" "value_boolean"] "facts")
(move-col ["fact_values" "value_integer"] "facts")
(move-col ["fact_values" "value_float"] "facts")
(move-col ["fact_values" "value_string"] "facts"))
diff (-> (diff-schema-maps exp-smap migrated)
(update :index-diff set)
(update :table-diff set))
exp-idx-diffs #{ ;; removed indexes
{:left-only
{:schema "public"
:table "fact_values"
:index "fact_values_pkey"
:index_keys ["<KEY>"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? true
:user "pdb_test"}
:right-only nil
:same nil}
{:left-only
{:schema "public"
:table "facts"
:index "facts_fact_value_id_idx"
:index_keys ["<KEY>"]
:type "btree"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}
{:left-only
{:schema "public"
:table "fact_values"
:index "fact_values_value_hash_key"
:index_keys ["<KEY>"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}
;; new indexes
{:left-only nil
:right-only
{:schema "public"
:table "facts"
:index "facts_factset_id_idx"
:index_keys ["<KEY>"]
:type "btree"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:same nil}
{:left-only
{:schema "public"
:table "facts"
:index "facts_factset_id_fact_path_id_fact_key"
:index_keys ["factset_id" "fact_path_id"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}}
exp-table-diffs #{ ;; removed columns
{:left-only
{:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "value_hash"
:table_name "fact_values"}
:right-only nil
:same nil}
{:left-only
{:numeric_scale 0
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision 64
:numeric_precision_radix 2
:data_type "bigint"
:column_name "fact_value_id"
:table_name "facts"}
:right-only nil
:same nil}
{:left-only
{:numeric_scale 0
:column_default "nextval('fact_values_id_seq'::regclass)"
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision 64
:numeric_precision_radix 2
:data_type "bigint"
:column_name "id"
:table_name "fact_values"}
:right-only nil
:same nil}
;; new columns
{:left-only nil
:right-only
{:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "YES"
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "large_value_hash"
:table_name "facts"}
:same nil}}
expected {:index-diff exp-idx-diffs
:table-diff exp-table-diffs}]
;; Handy when trying to see what's wrong.
(when-not (= expected diff)
(let [unex (-> diff
(update :index-diff set/difference exp-idx-diffs)
(update :table-diff set/difference exp-table-diffs))]
(binding [*out* *err*]
(println "Unexpected differences:")
(clojure.pprint/pprint unex))))
(is (= expected diff)))))
(deftest trgm-indexes-as-expected
;; Assume the current *db* supports trgm
(clear-db-for-testing!)
(migrate! *db*)
(indexes! (:database *db*))
(let [idxs (:indexes (schema-info-map *db*))]
(is (= {:schema "public"
:table "facts"
:index "facts_value_string_trgm"
:index_keys ["<KEY>string"]
:type "gin"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
(get idxs ["facts" ["value_string"]])))))
| true |
(ns puppetlabs.puppetdb.scf.migrate-test
(:require [clojure.set :as set]
[puppetlabs.puppetdb.scf.hash :as hash]
[puppetlabs.puppetdb.scf.migrate :as migrate]
[puppetlabs.puppetdb.scf.storage :as store]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.scf.storage-utils :as sutils
:refer [db-serialize]]
[cheshire.core :as json]
[clojure.java.jdbc :as sql]
[puppetlabs.puppetdb.scf.migrate :refer :all]
[clj-time.coerce :refer [to-timestamp]]
[clj-time.core :refer [now ago days]]
[clojure.test :refer :all]
[clojure.set :refer :all]
[puppetlabs.puppetdb.jdbc :as jdbc :refer [query-to-vec]]
[puppetlabs.puppetdb.testutils.db :as tdb
:refer [*db* clear-db-for-testing!
schema-info-map diff-schema-maps]]
[puppetlabs.kitchensink.core :as ks]
[puppetlabs.puppetdb.testutils.db :refer [*db* with-test-db]])
(:import [java.sql SQLIntegrityConstraintViolationException]
[org.postgresql.util PSQLException]))
(use-fixtures :each tdb/call-with-test-db)
(defn apply-migration-for-testing!
[i]
(let [migration (migrations i)]
(migration)
(record-migration! i)))
(defn fast-forward-to-migration!
[migration-number]
(doseq [[i migration] (sort migrations)
:while (<= i migration-number)]
(migration)
(record-migration! i)))
(deftest migration
(testing "pending migrations"
(testing "should return every migration if the *db* isn't migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(is (= (pending-migrations) migrations))))
(testing "should return nothing if the *db* is completely migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(migrate! *db*)
(is (empty? (pending-migrations)))))
(testing "should return missing migrations if the *db* is partially migrated"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(let [applied '(28 29 31)]
(doseq [m applied]
(apply-migration-for-testing! m))
(is (= (set (keys (pending-migrations)))
(difference (set (keys migrations))
(set applied))))))))
(testing "applying the migrations"
(let [expected-migrations (apply sorted-set (keys migrations))]
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(is (= (applied-migrations) #{}))
(testing "should migrate the database"
(migrate! *db*)
(is (= (applied-migrations) expected-migrations)))
(testing "should not do anything the second time"
(migrate! *db*)
(is (= (applied-migrations) expected-migrations)))
(testing "should attempt a partial migration if there are migrations missing"
(clear-db-for-testing!)
;; We are using migration 19 here because it is isolated enough to be able
;; to execute on its own. This might need to be changed in the future.
(doseq [m (filter (fn [[i migration]] (not= i 36)) (pending-migrations))]
(apply-migration-for-testing! (first m)))
(is (= (keys (pending-migrations)) '(36)))
(migrate! *db*)
(is (= (applied-migrations) expected-migrations))))))
(testing "should throw error if *db* is at a higher schema rev than we support"
(jdbc/with-transacted-connection *db*
(migrate! *db*)
(jdbc/insert! :schema_migrations
{:version (inc migrate/desired-schema-version)
:time (to-timestamp (now))})
(is (thrown? IllegalStateException (migrate! *db*))))))
(deftest migration-29
(testing "should contain same reports before and after migration"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :report_statuses
{:status "testing1" :id 1})
(jdbc/insert! :environments
{:id 1 :name "testing1"})
(jdbc/insert-multi! :certnames
[{:name "testing1" :deactivated nil}
{:name "testing2" :deactivated nil}])
(jdbc/insert-multi!
:reports
[{:hash "01"
:configuration_version "thisisacoolconfigversion"
:transaction_uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"
:certname "testing1"
:puppet_version "0.0.0"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:environment_id 1
:status_id 1}
{:hash "0000"
:transaction_uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"
:configuration_version "blahblahblah"
:certname "testing2"
:puppet_version "911"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:environment_id 1
:status_id 1}])
(jdbc/insert-multi! :latest_reports
[{:report "01" :certname "testing1"}
{:report "0000" :certname "testing2"}])
(apply-migration-for-testing! 29)
(let [response
(query-to-vec
"SELECT encode(r.hash::bytea, 'hex') AS hash, r.certname,
e.name AS environment, rs.status, r.transaction_uuid::text AS uuid
FROM certnames c
INNER JOIN reports r on c.latest_report_id=r.id
AND c.certname=r.certname
INNER JOIN environments e on r.environment_id=e.id
INNER JOIN report_statuses rs on r.status_id=rs.id
order by c.certname")]
;; every node should with facts should be represented
(is (= response
[{:hash "01" :environment "testing1" :certname "testing1" :status "testing1" :uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"}
{:hash "0000" :environment "testing1" :certname "testing2" :status "testing1" :uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"}])))
(let [[id1 id2] (map :id
(query-to-vec "SELECT id from reports order by certname"))]
(let [latest-ids (map :latest_report_id
(query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= [id1 id2] latest-ids))))))))
(deftest migration-37
(testing "should contain same reports before and after migration"
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 36)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :report_statuses
{:status "testing1" :id 1})
(jdbc/insert! :environments
{:id 1 :environment "testing1"})
(jdbc/insert-multi! :certnames
[{:certname "testing1" :deactivated nil}
{:certname "testing2" :deactivated nil}])
(jdbc/insert-multi!
:reports
[{:hash (sutils/munge-hash-for-storage "01")
:transaction_uuid (sutils/munge-uuid-for-storage
"bbbbbbbb-2222-bbbb-bbbb-222222222222")
:configuration_version "thisisacoolconfigversion"
:certname "testing1"
:puppet_version "0.0.0"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:producer_timestamp current-time
:environment_id 1
:status_id 1
:metrics (sutils/munge-json-for-storage [{:foo "bar"}])
:logs (sutils/munge-json-for-storage [{:bar "baz"}])}
{:hash (sutils/munge-hash-for-storage "0000")
:transaction_uuid (sutils/munge-uuid-for-storage
"aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa")
:configuration_version "blahblahblah"
:certname "testing2"
:puppet_version "911"
:report_format 1
:start_time current-time
:end_time current-time
:receive_time current-time
:producer_timestamp current-time
:environment_id 1
:status_id 1
:metrics (sutils/munge-json-for-storage [{:foo "bar"}])
:logs (sutils/munge-json-for-storage [{:bar "baz"}])}])
(jdbc/update! :certnames
{:latest_report_id 1}
["certname = ?" "testing1"])
(jdbc/update! :certnames
{:latest_report_id 2}
["certname = ?" "testing2"])
(apply-migration-for-testing! 37)
(let [response
(query-to-vec
"SELECT encode(r.hash, 'hex') AS hash, r.certname, e.environment, rs.status,
r.transaction_uuid::text AS uuid,
coalesce(metrics_json::jsonb, metrics) as metrics,
coalesce(logs_json::jsonb, logs) as logs
FROM certnames c
INNER JOIN reports r
ON c.latest_report_id=r.id AND c.certname=r.certname
INNER JOIN environments e ON r.environment_id=e.id
INNER JOIN report_statuses rs ON r.status_id=rs.id
ORDER BY c.certname")]
;; every node should with facts should be represented
(is (= [{:metrics [{:foo "bar"}] :logs [{:bar "baz"}]
:hash "01" :environment "testing1" :certname "testing1" :status "testing1" :uuid "bbbbbbbb-2222-bbbb-bbbb-222222222222"}
{:metrics [{:foo "bar"}] :logs [{:bar "baz"}]
:hash "0000" :environment "testing1" :certname "testing2" :status "testing1" :uuid "aaaaaaaa-1111-aaaa-1111-aaaaaaaaaaaa"}]
(map (comp #(update % :metrics sutils/parse-db-json)
#(update % :logs sutils/parse-db-json)) response))))
(let [[id1 id2] (map :id
(query-to-vec "SELECT id from reports order by certname"))]
(let [latest-ids (map :latest_report_id
(query-to-vec "select latest_report_id from certnames order by certname"))]
(is (= [id1 id2] latest-ids))))))))
(deftest migration-29-producer-timestamp-not-null
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(let [current-time (to-timestamp (now))]
(jdbc/insert! :environments
{:id 1 :name "test env"})
(jdbc/insert! :certnames
{:name "foo.local"})
(jdbc/insert! :catalogs
{:hash "18440af604d18536b1c77fd688dff8f0f9689d90"
:api_version 1
:catalog_version 1
:transaction_uuid "95d132b3-cb21-4e0a-976d-9a65567696ba"
:timestamp current-time
:certname "foo.local"
:environment_id 1
:producer_timestamp nil})
(jdbc/insert! :factsets
{:timestamp current-time
:certname "foo.local"
:environment_id 1
:producer_timestamp nil})
(apply-migration-for-testing! 29)
(let [catalogs-response (query-to-vec "SELECT producer_timestamp FROM catalogs")
factsets-response (query-to-vec "SELECT producer_timestamp FROM factsets")]
(is (= catalogs-response [{:producer_timestamp current-time}]))
(is (= factsets-response [{:producer_timestamp current-time}]))))))
(deftest migration-in-different-schema
(jdbc/with-db-connection *db*
(let [db-config {:database *db*}
test-db-name (tdb/subname->validated-db-name (:subname *db*))]
(clear-db-for-testing!)
(jdbc/with-db-connection (tdb/db-admin-config)
(let [db (tdb/subname->validated-db-name (:subname *db*))
user (get-in tdb/test-env [:user :name])]
(assert (tdb/valid-sql-id? db))
(jdbc/do-commands
(format "grant create on database %s to %s"
db (get-in tdb/test-env [:user :name])))))
(jdbc/do-commands
"CREATE SCHEMA pdbtestschema"
"SET SCHEMA 'pdbtestschema'")
(jdbc/with-db-connection (tdb/db-admin-config test-db-name)
(jdbc/do-commands
"DROP EXTENSION pg_trgm"
"CREATE EXTENSION pg_trgm WITH SCHEMA pdbtestschema"))
;; Currently sql-current-connection-table-names only looks in public.
(is (empty? (sutils/sql-current-connection-table-names)))
(migrate! *db*)
(indexes! db-config)
(indexes! db-config))))
(deftest test-hash-field-not-nullable
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 40)
(let [factset-template {:timestamp (to-timestamp (now))
:environment_id (store/ensure-environment "prod")
:producer_timestamp (to-timestamp (now))}
factset-data (map (fn [fs]
(merge factset-template fs))
[{:certname "foo.com"
:hash nil}
{:certname "bar.com"
:hash nil}
{:certname "baz.com"
:hash (sutils/munge-hash-for-storage "abc123")}])]
(jdbc/insert-multi! :certnames (map (fn [{:keys [certname]}]
{:certname certname :deactivated nil})
factset-data))
(jdbc/insert-multi! :factsets factset-data)
(is (= 2 (:c (first (query-to-vec "SELECT count(*) as c FROM factsets where hash is null")))))
(apply-migration-for-testing! 41)
(is (zero? (:c (first (query-to-vec "SELECT count(*) as c FROM factsets where hash is null"))))))))
(deftest test-only-hash-field-change
(clear-db-for-testing!)
(fast-forward-to-migration! 40)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 41)
(is (= {:index-diff nil,
:table-diff [{:left-only {:nullable? "YES"}
:right-only {:nullable? "NO"}
:same {:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "hash"
:table_name "factsets"}}]}
(diff-schema-maps before-migration (schema-info-map *db*))))))
(deftest test-add-producer-to-reports-catalogs-and-factsets-migration
(clear-db-for-testing!)
(fast-forward-to-migration! 46)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 47)
(let [schema-diff (diff-schema-maps before-migration (schema-info-map *db*))]
(is (= (set [{:left-only nil,
:right-only
{:schema "public",
:table "producers",
:index "producers_pkey",
:index_keys ["PI:KEY:<KEY>END_PI"],
:type "btree",
:unique? true,
:functional? false,
:is_partial false,
:primary? true},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "producers",
:index "producers_name_key",
:index_keys ["PI:KEY:<KEY>END_PI"],
:type "btree",
:unique? true,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "catalogs",
:index "idx_catalogs_prod",
:index_keys ["PI:KEY:<KEY>END_PI"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "reports",
:index "idx_reports_prod",
:index_keys ["PI:KEY:<KEY>END_PI"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}
{:left-only nil,
:right-only
{:schema "public",
:table "factsets",
:index "idx_factsets_prod",
:index_keys ["PI:KEY:<KEY>END_PI"],
:type "btree",
:unique? false,
:functional? false,
:is_partial false,
:primary? false},
:same nil}])
(->> (:index-diff schema-diff)
(map #(kitchensink/mapvals (fn [idx] (dissoc idx :user)) %))
set)))
(is (= (set [{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "reports"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default "nextval('producers_id_seq'::regclass)",
:character_octet_length nil,
:datetime_precision nil,
:nullable? "NO",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "id",
:table_name "producers"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "catalogs"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale nil,
:column_default nil,
:character_octet_length 1073741824,
:datetime_precision nil,
:nullable? "NO",
:character_maximum_length nil,
:numeric_precision nil,
:numeric_precision_radix nil,
:data_type "text",
:column_name "name",
:table_name "producers"},
:same nil}
{:left-only nil,
:right-only
{:numeric_scale 0,
:column_default nil,
:character_octet_length nil,
:datetime_precision nil,
:nullable? "YES",
:character_maximum_length nil,
:numeric_precision 64,
:numeric_precision_radix 2,
:data_type "bigint",
:column_name "producer_id",
:table_name "factsets"},
:same nil}])
(set (:table-diff schema-diff)))))))
(deftest test-migrate-from-unsupported-version
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(jdbc/do-commands "DELETE FROM schema_migrations")
(record-migration! 27)
(is (thrown-with-msg? IllegalStateException
#"Found an old and unuspported database migration.*"
(migrate! *db*))))
(deftest md5-agg-test
(with-test-db
(jdbc/with-db-connection *db*
(testing "dual_md5 function"
(is (= [{:encode "187ef4436122d1cc2f40dc2b92f0eba0"}]
(query-to-vec "select encode(dual_md5('a', 'b'), 'hex')"))))
(testing "md5_agg custom aggregator"
;; this hash is different from the above because it starts by executing
;; dual_md5(0::bytea, 'a'::bytea)
(is (= [{:encode "bdef73571a96923bdc6b78b5345377d3"}]
(query-to-vec
(str "select encode(md5_agg(val), 'hex') "
"from (values (1, 'a'::bytea), (1, 'b'::bytea)) x(gid, val) "
"group by gid"))))))))
(deftest migration-50-remove-historical-catalogs
(jdbc/with-db-connection *db*
(clear-db-for-testing!)
(fast-forward-to-migration! 49)
(jdbc/insert! :environments
{:id 1 :environment "testing"})
(jdbc/insert! :certnames
{:certname "foo.local"})
(jdbc/insert! :catalogs
{:hash (sutils/munge-hash-for-storage
"18440af604d18536b1c77fd688dff8f0f9689d90")
:id 1
:api_version 1
:catalog_version 1
:transaction_uuid (sutils/munge-uuid-for-storage
"95d132b3-cb21-4e0a-976d-9a65567696ba")
:timestamp (to-timestamp (now))
:certname "foo.local"
:environment_id 1
:producer_timestamp (to-timestamp (now))})
(jdbc/insert! :catalogs
{:hash (sutils/munge-hash-for-storage
"18445af604d18536b1c77fd688dff8f0f9689d90")
:id 2
:api_version 1
:catalog_version 1
:transaction_uuid (sutils/munge-uuid-for-storage
"95d136b3-cb21-4e0a-976d-9a65567696ba")
:timestamp (to-timestamp (now))
:certname "foo.local"
:environment_id 1
:producer_timestamp (to-timestamp (now))})
(jdbc/insert! :latest_catalogs
{:certname_id 1 :catalog_id 2})
(let [original-catalogs (jdbc/query-to-vec "select id from catalogs")
_ (apply-migration-for-testing! 50)
new-catalogs (jdbc/query-to-vec "select id from catalogs")]
(is (= #{1 2} (set (map :id original-catalogs))))
(is (= #{2} (set (map :id new-catalogs)))))))
(deftest test-migrate-from-unsupported-version
(clear-db-for-testing!)
(fast-forward-to-migration! 28)
(jdbc/do-commands "DELETE FROM schema_migrations")
(record-migration! 27)
(is (thrown-with-msg? IllegalStateException
#"Found an old and unuspported database migration.*"
(migrate! *db*))))
(deftest md5-agg-test
(with-test-db
(jdbc/with-db-connection *db*
(testing "dual_md5 function"
(is (= [{:encode "187ef4436122d1cc2f40dc2b92f0eba0"}]
(query-to-vec "select encode(dual_md5('a', 'b'), 'hex')"))))
(testing "md5_agg custom aggregator"
;; this hash is different from the above because it starts by executing
;; dual_md5(0::bytea, 'a'::bytea)
(is (= [{:encode "bdef73571a96923bdc6b78b5345377d3"}]
(query-to-vec
(str "select encode(md5_agg(val), 'hex') "
"from (values (1, 'a'::bytea), (1, 'b'::bytea)) x(gid, val) "
"group by gid"))))))))
(deftest test-fact-values-value->jsonb
(clear-db-for-testing!)
(fast-forward-to-migration! 49)
(let [before-migration (schema-info-map *db*)]
(apply-migration-for-testing! 51)
(is (= {:index-diff nil
:table-diff [{:left-only {:data_type "text",
:character_octet_length 1073741824},
:right-only {:data_type "jsonb",
:character_octet_length nil},
:same {:table_name "fact_values",
:column_name "value",
:numeric_precision_radix nil,
:numeric_precision nil,
:character_maximum_length nil,
:nullable? "YES",
:datetime_precision nil,
:column_default nil,
:numeric_scale nil}}]}
(diff-schema-maps before-migration (schema-info-map *db*))))))
(deftest test-resource-params-cache-parameters-to-jsonb
(clear-db-for-testing!)
(fast-forward-to-migration! 51)
(let [before-migration (schema-info-map *db*)]
(jdbc/insert! :resource_params_cache
{:resource (sutils/munge-hash-for-storage "a0a0a0")
:parameters (json/generate-string {:a "apple" :b {:1 "bear" :2 "button" :3 "butts"}})})
(jdbc/insert! :resource_params_cache
{:resource (sutils/munge-hash-for-storage "b1b1b1")
:parameters (json/generate-string {:c "camel" :d {:1 "dinosaur" :2 "donkey" :3 "daffodil"}})})
(apply-migration-for-testing! 52)
(testing "should migrate resource_params_cache data correctly"
(let [responses
(query-to-vec
(format "SELECT %s as resource, parameters FROM resource_params_cache"
(sutils/sql-hash-as-str "resource")))
parsed-responses (for [response responses] (assoc response :parameters (sutils/parse-db-json (response :parameters))))]
(is (= parsed-responses
[{:resource "a0a0a0" :parameters {:a "apple" :b {:1 "bear" :2 "button" :3 "butts"}}}
{:resource "b1b1b1" :parameters {:c "camel" :d {:1 "dinosaur" :2 "donkey" :3 "daffodil"}}}]))))
(testing "should change only value column type"
(let [schema-diff (diff-schema-maps before-migration (schema-info-map *db*))]
(is (= #{}
(->> (:index-diff schema-diff)
(map #(kitchensink/mapvals (fn [idx] (dissoc idx :user)) %))
set)))
(is (= #{{:left-only
{:data_type "text", :character_octet_length 1073741824},
:right-only
{:data_type "jsonb", :character_octet_length nil},
:same
{:table_name "resource_params_cache",
:column_name "parameters",
:numeric_precision_radix nil,
:numeric_precision nil,
:character_maximum_length nil,
:nullable? "YES",
:datetime_precision nil,
:column_default nil,
:numeric_scale nil}}}
(set (:table-diff schema-diff))))))))
(deftest fact-values-reduplication-schema-diff
;; This does not check the value_string trgm index since it is
;; created opportunistically later in trgm-indexes!
(clear-db-for-testing!)
(fast-forward-to-migration! 55)
(let [initial (schema-info-map *db*)]
(apply-migration-for-testing! 56)
(let [migrated (schema-info-map *db*)
rename-idx (fn [smap idx-id new-table new-name]
(let [idxs (:indexes smap)
idx-info (get idxs idx-id)
new-info (assoc idx-info
:table new-table
:index new-name)
new-id (assoc idx-id 0 new-table)]
(assert idx-info)
(update smap :indexes
#(-> %
(dissoc idx-id)
(assoc new-id new-info)))))
move-col (fn [smap idx-id new-table]
(let [idxs (:tables smap)
idx-info (get idxs idx-id)
new-info (assoc idx-info
:table_name new-table)
new-id (assoc idx-id 0 new-table)]
(assert idx-info)
(update smap :tables
#(-> %
(dissoc idx-id)
(assoc new-id new-info)))))
exp-smap (-> initial
(rename-idx ["fact_values" ["value_integer"]]
"facts" "facts_value_integer_idx")
(rename-idx ["fact_values" ["value_float"]]
"facts" "facts_value_float_idx")
(move-col ["fact_values" "value_type_id"] "facts")
(move-col ["fact_values" "value"] "facts")
(move-col ["fact_values" "value_boolean"] "facts")
(move-col ["fact_values" "value_integer"] "facts")
(move-col ["fact_values" "value_float"] "facts")
(move-col ["fact_values" "value_string"] "facts"))
diff (-> (diff-schema-maps exp-smap migrated)
(update :index-diff set)
(update :table-diff set))
exp-idx-diffs #{ ;; removed indexes
{:left-only
{:schema "public"
:table "fact_values"
:index "fact_values_pkey"
:index_keys ["PI:KEY:<KEY>END_PI"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? true
:user "pdb_test"}
:right-only nil
:same nil}
{:left-only
{:schema "public"
:table "facts"
:index "facts_fact_value_id_idx"
:index_keys ["PI:KEY:<KEY>END_PI"]
:type "btree"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}
{:left-only
{:schema "public"
:table "fact_values"
:index "fact_values_value_hash_key"
:index_keys ["PI:KEY:<KEY>END_PI"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}
;; new indexes
{:left-only nil
:right-only
{:schema "public"
:table "facts"
:index "facts_factset_id_idx"
:index_keys ["PI:KEY:<KEY>END_PI"]
:type "btree"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:same nil}
{:left-only
{:schema "public"
:table "facts"
:index "facts_factset_id_fact_path_id_fact_key"
:index_keys ["factset_id" "fact_path_id"]
:type "btree"
:unique? true
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
:right-only nil
:same nil}}
exp-table-diffs #{ ;; removed columns
{:left-only
{:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "value_hash"
:table_name "fact_values"}
:right-only nil
:same nil}
{:left-only
{:numeric_scale 0
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision 64
:numeric_precision_radix 2
:data_type "bigint"
:column_name "fact_value_id"
:table_name "facts"}
:right-only nil
:same nil}
{:left-only
{:numeric_scale 0
:column_default "nextval('fact_values_id_seq'::regclass)"
:character_octet_length nil
:datetime_precision nil
:nullable? "NO"
:character_maximum_length nil
:numeric_precision 64
:numeric_precision_radix 2
:data_type "bigint"
:column_name "id"
:table_name "fact_values"}
:right-only nil
:same nil}
;; new columns
{:left-only nil
:right-only
{:numeric_scale nil
:column_default nil
:character_octet_length nil
:datetime_precision nil
:nullable? "YES"
:character_maximum_length nil
:numeric_precision nil
:numeric_precision_radix nil
:data_type "bytea"
:column_name "large_value_hash"
:table_name "facts"}
:same nil}}
expected {:index-diff exp-idx-diffs
:table-diff exp-table-diffs}]
;; Handy when trying to see what's wrong.
(when-not (= expected diff)
(let [unex (-> diff
(update :index-diff set/difference exp-idx-diffs)
(update :table-diff set/difference exp-table-diffs))]
(binding [*out* *err*]
(println "Unexpected differences:")
(clojure.pprint/pprint unex))))
(is (= expected diff)))))
(deftest trgm-indexes-as-expected
;; Assume the current *db* supports trgm
(clear-db-for-testing!)
(migrate! *db*)
(indexes! (:database *db*))
(let [idxs (:indexes (schema-info-map *db*))]
(is (= {:schema "public"
:table "facts"
:index "facts_value_string_trgm"
:index_keys ["PI:KEY:<KEY>END_PIstring"]
:type "gin"
:unique? false
:functional? false
:is_partial false
:primary? false
:user "pdb_test"}
(get idxs ["facts" ["value_string"]])))))
|
[
{
"context": "let [signing-key (SecretKeySpec. (get-bytes key) \"HmacSHA1\")\n mac (doto (Mac/getInstance \"HmacSHA1\") ",
"end": 2287,
"score": 0.7124122381210327,
"start": 2279,
"tag": "KEY",
"value": "HmacSHA1"
}
] |
src/clojure/radigost/crypto.clj
|
danboykis/radigost
| 1 |
(ns radigost.crypto
(:require [clojure.string :as s])
(:import [java.util Base64]
[java.security KeyFactory Signature]
[java.security.spec X509EncodedKeySpec]
[java.nio.charset StandardCharsets]
[javax.crypto.spec SecretKeySpec]
[javax.crypto Mac]
[javax.xml.bind DatatypeConverter]))
(def ^:private BEGIN "-----BEGIN ")
(def ^:private END "-----END ")
(defn- decode-url-b64 [^String s]
(.decode (Base64/getUrlDecoder) s))
(defn- decode-b64 [^String s]
(.decode (Base64/getDecoder) s))
(defn- read-type [txt]
(as-> txt $
(subs $ (count BEGIN))
(subs $ 0 (s/index-of $ "-"))))
(defn- parse-type [txt]
(condp = (read-type txt)
"PUBLIC KEY" :pub-key
:prv-key))
(defn- strip-headers [lines]
(remove #(s/index-of % ":") lines))
(defn- parse-key [txt]
(let [type (parse-type txt)
key-lines (s/split (first (remove empty? (map s/trim (s/split txt #"-+.+-+"))))
#"\s+")]
{:type type
:key (-> key-lines
strip-headers
s/join
decode-b64
seq)}))
(defn- make-key [{:keys [type key]}]
(let [x509-key-spec (X509EncodedKeySpec. (byte-array key))
kf (KeyFactory/getInstance "RSA")]
(condp = type
:pub-key (.generatePublic kf x509-key-spec)
:prv-key (.generatePrivate kf x509-key-spec) ;;TODO make this work by parsing PKCS#1
(throw (IllegalArgumentException. "key is not valid")))))
(defn key-from-text [k]
(some-> k parse-key make-key))
(defn- verify-signature [sig pub-key data]
(let [signer (doto
(Signature/getInstance "SHA256withRSA")
(.initVerify pub-key)
(.update (.getBytes data StandardCharsets/ISO_8859_1)))]
(.verify signer (decode-url-b64 sig))))
(defn good-signature? [pub-key token]
(if-not (string? token)
false
(let [pk (key-from-text pub-key)
i (s/last-index-of token ".")
data (subs token 0 i)
sig (subs token (inc i))]
(verify-signature sig pk data))))
(defn- get-bytes [^String s]
(.getBytes s StandardCharsets/US_ASCII))
(defn hmac-sha1 [^String key ^String data]
(let [signing-key (SecretKeySpec. (get-bytes key) "HmacSHA1")
mac (doto (Mac/getInstance "HmacSHA1") (.init signing-key))]
(-> (Base64/getEncoder)
(.encodeToString (.doFinal mac (get-bytes data))))))
|
51926
|
(ns radigost.crypto
(:require [clojure.string :as s])
(:import [java.util Base64]
[java.security KeyFactory Signature]
[java.security.spec X509EncodedKeySpec]
[java.nio.charset StandardCharsets]
[javax.crypto.spec SecretKeySpec]
[javax.crypto Mac]
[javax.xml.bind DatatypeConverter]))
(def ^:private BEGIN "-----BEGIN ")
(def ^:private END "-----END ")
(defn- decode-url-b64 [^String s]
(.decode (Base64/getUrlDecoder) s))
(defn- decode-b64 [^String s]
(.decode (Base64/getDecoder) s))
(defn- read-type [txt]
(as-> txt $
(subs $ (count BEGIN))
(subs $ 0 (s/index-of $ "-"))))
(defn- parse-type [txt]
(condp = (read-type txt)
"PUBLIC KEY" :pub-key
:prv-key))
(defn- strip-headers [lines]
(remove #(s/index-of % ":") lines))
(defn- parse-key [txt]
(let [type (parse-type txt)
key-lines (s/split (first (remove empty? (map s/trim (s/split txt #"-+.+-+"))))
#"\s+")]
{:type type
:key (-> key-lines
strip-headers
s/join
decode-b64
seq)}))
(defn- make-key [{:keys [type key]}]
(let [x509-key-spec (X509EncodedKeySpec. (byte-array key))
kf (KeyFactory/getInstance "RSA")]
(condp = type
:pub-key (.generatePublic kf x509-key-spec)
:prv-key (.generatePrivate kf x509-key-spec) ;;TODO make this work by parsing PKCS#1
(throw (IllegalArgumentException. "key is not valid")))))
(defn key-from-text [k]
(some-> k parse-key make-key))
(defn- verify-signature [sig pub-key data]
(let [signer (doto
(Signature/getInstance "SHA256withRSA")
(.initVerify pub-key)
(.update (.getBytes data StandardCharsets/ISO_8859_1)))]
(.verify signer (decode-url-b64 sig))))
(defn good-signature? [pub-key token]
(if-not (string? token)
false
(let [pk (key-from-text pub-key)
i (s/last-index-of token ".")
data (subs token 0 i)
sig (subs token (inc i))]
(verify-signature sig pk data))))
(defn- get-bytes [^String s]
(.getBytes s StandardCharsets/US_ASCII))
(defn hmac-sha1 [^String key ^String data]
(let [signing-key (SecretKeySpec. (get-bytes key) "<KEY>")
mac (doto (Mac/getInstance "HmacSHA1") (.init signing-key))]
(-> (Base64/getEncoder)
(.encodeToString (.doFinal mac (get-bytes data))))))
| true |
(ns radigost.crypto
(:require [clojure.string :as s])
(:import [java.util Base64]
[java.security KeyFactory Signature]
[java.security.spec X509EncodedKeySpec]
[java.nio.charset StandardCharsets]
[javax.crypto.spec SecretKeySpec]
[javax.crypto Mac]
[javax.xml.bind DatatypeConverter]))
(def ^:private BEGIN "-----BEGIN ")
(def ^:private END "-----END ")
(defn- decode-url-b64 [^String s]
(.decode (Base64/getUrlDecoder) s))
(defn- decode-b64 [^String s]
(.decode (Base64/getDecoder) s))
(defn- read-type [txt]
(as-> txt $
(subs $ (count BEGIN))
(subs $ 0 (s/index-of $ "-"))))
(defn- parse-type [txt]
(condp = (read-type txt)
"PUBLIC KEY" :pub-key
:prv-key))
(defn- strip-headers [lines]
(remove #(s/index-of % ":") lines))
(defn- parse-key [txt]
(let [type (parse-type txt)
key-lines (s/split (first (remove empty? (map s/trim (s/split txt #"-+.+-+"))))
#"\s+")]
{:type type
:key (-> key-lines
strip-headers
s/join
decode-b64
seq)}))
(defn- make-key [{:keys [type key]}]
(let [x509-key-spec (X509EncodedKeySpec. (byte-array key))
kf (KeyFactory/getInstance "RSA")]
(condp = type
:pub-key (.generatePublic kf x509-key-spec)
:prv-key (.generatePrivate kf x509-key-spec) ;;TODO make this work by parsing PKCS#1
(throw (IllegalArgumentException. "key is not valid")))))
(defn key-from-text [k]
(some-> k parse-key make-key))
(defn- verify-signature [sig pub-key data]
(let [signer (doto
(Signature/getInstance "SHA256withRSA")
(.initVerify pub-key)
(.update (.getBytes data StandardCharsets/ISO_8859_1)))]
(.verify signer (decode-url-b64 sig))))
(defn good-signature? [pub-key token]
(if-not (string? token)
false
(let [pk (key-from-text pub-key)
i (s/last-index-of token ".")
data (subs token 0 i)
sig (subs token (inc i))]
(verify-signature sig pk data))))
(defn- get-bytes [^String s]
(.getBytes s StandardCharsets/US_ASCII))
(defn hmac-sha1 [^String key ^String data]
(let [signing-key (SecretKeySpec. (get-bytes key) "PI:KEY:<KEY>END_PI")
mac (doto (Mac/getInstance "HmacSHA1") (.init signing-key))]
(-> (Base64/getEncoder)
(.encodeToString (.doFinal mac (get-bytes data))))))
|
[
{
"context": "bc/insert!\n db\n :app_user\n {:first_name \"Andre\"\n :surname \"Agassi\"\n :height 180\n ",
"end": 185,
"score": 0.999791145324707,
"start": 180,
"tag": "NAME",
"value": "Andre"
},
{
"context": "p_user\n {:first_name \"Andre\"\n :surname \"Agassi\"\n :height 180\n :weight 80}))\n\n; o",
"end": 211,
"score": 0.999760091304779,
"start": 205,
"tag": "NAME",
"value": "Agassi"
},
{
"context": "\n [:first_name :surname :height :weight]\n [\"Andre\" \"Agassi\" 180 80]))\n\n(defn insert-activities\n [d",
"end": 387,
"score": 0.9998278617858887,
"start": 382,
"tag": "NAME",
"value": "Andre"
},
{
"context": "irst_name :surname :height :weight]\n [\"Andre\" \"Agassi\" 180 80]))\n\n(defn insert-activities\n [db]\n (jdb",
"end": 396,
"score": 0.9997718930244446,
"start": 390,
"tag": "NAME",
"value": "Agassi"
}
] |
chapter13/exercise13.4/src/packt_clj/exercises/data_insertion.clj
|
TrainingByPackt/Clojure
| 0 |
(ns packt-clj.exercises.data-insertion
(:require
[clojure.java.jdbc :as jdbc]))
; option 1
(defn insert-user-1
[db]
(jdbc/insert!
db
:app_user
{:first_name "Andre"
:surname "Agassi"
:height 180
:weight 80}))
; option 2
(defn insert-user-2
[db]
(jdbc/insert!
db
:app_user
[:first_name :surname :height :weight]
["Andre" "Agassi" 180 80]))
(defn insert-activities
[db]
(jdbc/insert-multi!
db
:activity
[{:activity_type "run" :distance 8.67 :duration 2520 :user_id 1}
{:activity_type "cycle" :distance 17.68 :duration 2703 :user_id 1}]))
|
19537
|
(ns packt-clj.exercises.data-insertion
(:require
[clojure.java.jdbc :as jdbc]))
; option 1
(defn insert-user-1
[db]
(jdbc/insert!
db
:app_user
{:first_name "<NAME>"
:surname "<NAME>"
:height 180
:weight 80}))
; option 2
(defn insert-user-2
[db]
(jdbc/insert!
db
:app_user
[:first_name :surname :height :weight]
["<NAME>" "<NAME>" 180 80]))
(defn insert-activities
[db]
(jdbc/insert-multi!
db
:activity
[{:activity_type "run" :distance 8.67 :duration 2520 :user_id 1}
{:activity_type "cycle" :distance 17.68 :duration 2703 :user_id 1}]))
| true |
(ns packt-clj.exercises.data-insertion
(:require
[clojure.java.jdbc :as jdbc]))
; option 1
(defn insert-user-1
[db]
(jdbc/insert!
db
:app_user
{:first_name "PI:NAME:<NAME>END_PI"
:surname "PI:NAME:<NAME>END_PI"
:height 180
:weight 80}))
; option 2
(defn insert-user-2
[db]
(jdbc/insert!
db
:app_user
[:first_name :surname :height :weight]
["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" 180 80]))
(defn insert-activities
[db]
(jdbc/insert-multi!
db
:activity
[{:activity_type "run" :distance 8.67 :duration 2520 :user_id 1}
{:activity_type "cycle" :distance 17.68 :duration 2703 :user_id 1}]))
|
[
{
"context": "sing with ImageJ/FIJI\"\n :url \"https://github.com/funimage/funimage\"\n :license {:name \"Apache v2.0\"\n ",
"end": 137,
"score": 0.999484658241272,
"start": 129,
"tag": "USERNAME",
"value": "funimage"
},
{
"context": "Apache v2.0\"\n :url \"https://github.com/funimage/funimage/LICENSE\"}\n :dependencies [[org.clojure/",
"end": 225,
"score": 0.9994915723800659,
"start": 217,
"tag": "USERNAME",
"value": "funimage"
},
{
"context": " :password :env/CI_DEPLOY_PASSWORD\n :sign-releas",
"end": 2462,
"score": 0.5838629007339478,
"start": 2454,
"tag": "PASSWORD",
"value": "PASSWORD"
},
{
"context": "\n :password :env/CI_DEPLOY_PASSWORD\n :sign-relea",
"end": 2766,
"score": 0.9141277074813843,
"start": 2744,
"tag": "PASSWORD",
"value": "env/CI_DEPLOY_PASSWORD"
},
{
"context": "mx32g\" \"-server\"\n ;\"-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-",
"end": 2974,
"score": 0.7054112553596497,
"start": 2970,
"tag": "USERNAME",
"value": "kyle"
}
] |
project.clj
|
skalarproduktraum/funimage
| 14 |
(defproject funimage "0.1.100-SNAPSHOT"
:description "Functional Image Processing with ImageJ/FIJI"
:url "https://github.com/funimage/funimage"
:license {:name "Apache v2.0"
:url "https://github.com/funimage/funimage/LICENSE"}
:dependencies [[org.clojure/clojure "1.8.0"]
[seesaw "1.4.4"]
;[me.raynes/fs "1.4.6"]
;[org.clojure/data.zip "0.1.1"]
[clj-random "0.1.8"]
;[cc.artifice/clj-ml "0.8.5"]
[random-forests-clj "0.2.0"]
; Java libs
[net.imglib2/imglib2-algorithm "0.8.0"]
[net.imglib2/imglib2-roi "0.4.6"]
[net.imglib2/imglib2-ij "2.0.0-beta-37"]
[net.imagej/imagej "2.0.0-rc-61" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm]]
[net.imagej/imagej-ops "0.38.1-SNAPSHOT"]
[net.imagej/imagej-mesh "0.1.1-SNAPSHOT"]
[ome/bioformats_package "5.3.3"]
[sc.fiji/Auto_Threshold "1.16.0"]
]
:java-source-paths ["java"]
:repositories [["imagej" "http://maven.imagej.net/content/groups/hosted/"]
["imagej-releases" "http://maven.imagej.net/content/repositories/releases/"]
["ome maven" "http://artifacts.openmicroscopy.org/artifactory/maven/"]
["imagej-snapshots" "http://maven.imagej.net/content/repositories/snapshots/"]
["clojars2" {:url "http://clojars.org/repo/"
:username :env/LEIN_USERNAME
:password :env/LEIN_PASSWORD}]]
:deploy-repositories [["releases" {:url "http://maven.imagej.net/content/repositories/releases"
;; Select a GPG private key to use for
;; signing. (See "How to specify a user
;; ID" in GPG's manual.) GPG will
;; otherwise pick the first private key
;; it finds in your keyring.
;; Currently only works in :deploy-repositories
;; or as a top-level (global) setting.
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_PASSWORD
:sign-releases false}]
["snapshots" {:url "http://maven.imagej.net/content/repositories/snapshots"
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_PASSWORD
:sign-releases false}]]
; Try to use lein parent when we can
; :plugins [[lein-parent "0.3.1"]]
:jvm-opts ["-Xmx32g" "-server"
;"-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-patcher-0.12.3.jar=init"
#_"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:8000"]
;:javac-options ["-target" "1.6" "-source" "1.6"]
)
|
65820
|
(defproject funimage "0.1.100-SNAPSHOT"
:description "Functional Image Processing with ImageJ/FIJI"
:url "https://github.com/funimage/funimage"
:license {:name "Apache v2.0"
:url "https://github.com/funimage/funimage/LICENSE"}
:dependencies [[org.clojure/clojure "1.8.0"]
[seesaw "1.4.4"]
;[me.raynes/fs "1.4.6"]
;[org.clojure/data.zip "0.1.1"]
[clj-random "0.1.8"]
;[cc.artifice/clj-ml "0.8.5"]
[random-forests-clj "0.2.0"]
; Java libs
[net.imglib2/imglib2-algorithm "0.8.0"]
[net.imglib2/imglib2-roi "0.4.6"]
[net.imglib2/imglib2-ij "2.0.0-beta-37"]
[net.imagej/imagej "2.0.0-rc-61" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm]]
[net.imagej/imagej-ops "0.38.1-SNAPSHOT"]
[net.imagej/imagej-mesh "0.1.1-SNAPSHOT"]
[ome/bioformats_package "5.3.3"]
[sc.fiji/Auto_Threshold "1.16.0"]
]
:java-source-paths ["java"]
:repositories [["imagej" "http://maven.imagej.net/content/groups/hosted/"]
["imagej-releases" "http://maven.imagej.net/content/repositories/releases/"]
["ome maven" "http://artifacts.openmicroscopy.org/artifactory/maven/"]
["imagej-snapshots" "http://maven.imagej.net/content/repositories/snapshots/"]
["clojars2" {:url "http://clojars.org/repo/"
:username :env/LEIN_USERNAME
:password :env/LEIN_PASSWORD}]]
:deploy-repositories [["releases" {:url "http://maven.imagej.net/content/repositories/releases"
;; Select a GPG private key to use for
;; signing. (See "How to specify a user
;; ID" in GPG's manual.) GPG will
;; otherwise pick the first private key
;; it finds in your keyring.
;; Currently only works in :deploy-repositories
;; or as a top-level (global) setting.
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_<PASSWORD>
:sign-releases false}]
["snapshots" {:url "http://maven.imagej.net/content/repositories/snapshots"
:username :env/CI_DEPLOY_USERNAME
:password :<PASSWORD>
:sign-releases false}]]
; Try to use lein parent when we can
; :plugins [[lein-parent "0.3.1"]]
:jvm-opts ["-Xmx32g" "-server"
;"-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-patcher-0.12.3.jar=init"
#_"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:8000"]
;:javac-options ["-target" "1.6" "-source" "1.6"]
)
| true |
(defproject funimage "0.1.100-SNAPSHOT"
:description "Functional Image Processing with ImageJ/FIJI"
:url "https://github.com/funimage/funimage"
:license {:name "Apache v2.0"
:url "https://github.com/funimage/funimage/LICENSE"}
:dependencies [[org.clojure/clojure "1.8.0"]
[seesaw "1.4.4"]
;[me.raynes/fs "1.4.6"]
;[org.clojure/data.zip "0.1.1"]
[clj-random "0.1.8"]
;[cc.artifice/clj-ml "0.8.5"]
[random-forests-clj "0.2.0"]
; Java libs
[net.imglib2/imglib2-algorithm "0.8.0"]
[net.imglib2/imglib2-roi "0.4.6"]
[net.imglib2/imglib2-ij "2.0.0-beta-37"]
[net.imagej/imagej "2.0.0-rc-61" :exclusions [com.github.jnr/jffi com.github.jnr/jnr-x86asm]]
[net.imagej/imagej-ops "0.38.1-SNAPSHOT"]
[net.imagej/imagej-mesh "0.1.1-SNAPSHOT"]
[ome/bioformats_package "5.3.3"]
[sc.fiji/Auto_Threshold "1.16.0"]
]
:java-source-paths ["java"]
:repositories [["imagej" "http://maven.imagej.net/content/groups/hosted/"]
["imagej-releases" "http://maven.imagej.net/content/repositories/releases/"]
["ome maven" "http://artifacts.openmicroscopy.org/artifactory/maven/"]
["imagej-snapshots" "http://maven.imagej.net/content/repositories/snapshots/"]
["clojars2" {:url "http://clojars.org/repo/"
:username :env/LEIN_USERNAME
:password :env/LEIN_PASSWORD}]]
:deploy-repositories [["releases" {:url "http://maven.imagej.net/content/repositories/releases"
;; Select a GPG private key to use for
;; signing. (See "How to specify a user
;; ID" in GPG's manual.) GPG will
;; otherwise pick the first private key
;; it finds in your keyring.
;; Currently only works in :deploy-repositories
;; or as a top-level (global) setting.
:username :env/CI_DEPLOY_USERNAME
:password :env/CI_DEPLOY_PI:PASSWORD:<PASSWORD>END_PI
:sign-releases false}]
["snapshots" {:url "http://maven.imagej.net/content/repositories/snapshots"
:username :env/CI_DEPLOY_USERNAME
:password :PI:PASSWORD:<PASSWORD>END_PI
:sign-releases false}]]
; Try to use lein parent when we can
; :plugins [[lein-parent "0.3.1"]]
:jvm-opts ["-Xmx32g" "-server"
;"-javaagent:/Users/kyle/.m2/repository/net/imagej/ij1-patcher/0.12.3/ij1-patcher-0.12.3.jar=init"
#_"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:8000"]
;:javac-options ["-target" "1.6" "-source" "1.6"]
)
|
[
{
"context": "(defproject reifyhealth/lein-git-down \"0.4.1-SNAPSHOT\"\n :descri",
"end": 14,
"score": 0.5052957534790039,
"start": 12,
"tag": "USERNAME",
"value": "re"
},
{
"context": " from a Git repository\"\n :url \"http://github.com/reifyhealth/lein-git-down\"\n :license {:name \"MIT\"}\n :depend",
"end": 193,
"score": 0.9830902218818665,
"start": 182,
"tag": "USERNAME",
"value": "reifyhealth"
},
{
"context": " :password :env/clojars_password\n :sign-release",
"end": 668,
"score": 0.5216768383979797,
"start": 660,
"tag": "PASSWORD",
"value": "password"
}
] |
project.clj
|
Folcon/lein-git-down
| 0 |
(defproject reifyhealth/lein-git-down "0.4.1-SNAPSHOT"
:description "A Leiningen plugin for resolving Clojure(Script) dependencies from a Git repository"
:url "http://github.com/reifyhealth/lein-git-down"
:license {:name "MIT"}
:dependencies [[org.clojure/tools.gitlibs "1.0.100"
:exclusions [org.apache.httpcomponents/httpclient
org.slf4j/slf4j-api]]
[leiningen "2.9.4" :scope "provided"]]
:deploy-repositories [["clojars" {:url "https://clojars.org/repo"
:username :env/clojars_username
:password :env/clojars_password
:sign-releases false}]])
|
8157
|
(defproject reifyhealth/lein-git-down "0.4.1-SNAPSHOT"
:description "A Leiningen plugin for resolving Clojure(Script) dependencies from a Git repository"
:url "http://github.com/reifyhealth/lein-git-down"
:license {:name "MIT"}
:dependencies [[org.clojure/tools.gitlibs "1.0.100"
:exclusions [org.apache.httpcomponents/httpclient
org.slf4j/slf4j-api]]
[leiningen "2.9.4" :scope "provided"]]
:deploy-repositories [["clojars" {:url "https://clojars.org/repo"
:username :env/clojars_username
:password :env/clojars_<PASSWORD>
:sign-releases false}]])
| true |
(defproject reifyhealth/lein-git-down "0.4.1-SNAPSHOT"
:description "A Leiningen plugin for resolving Clojure(Script) dependencies from a Git repository"
:url "http://github.com/reifyhealth/lein-git-down"
:license {:name "MIT"}
:dependencies [[org.clojure/tools.gitlibs "1.0.100"
:exclusions [org.apache.httpcomponents/httpclient
org.slf4j/slf4j-api]]
[leiningen "2.9.4" :scope "provided"]]
:deploy-repositories [["clojars" {:url "https://clojars.org/repo"
:username :env/clojars_username
:password :env/clojars_PI:PASSWORD:<PASSWORD>END_PI
:sign-releases false}]])
|
[
{
"context": "peer-test\n (testing \"Parse peer\"\n (let [line \"17.112.1.4 | 3356 7018 | 714 | 17.112.0.0/16 | APPLE-ENGINEE",
"end": 416,
"score": 0.9997273683547974,
"start": 406,
"tag": "IP_ADDRESS",
"value": "17.112.1.4"
},
{
"context": "r\"\n (let [line \"17.112.1.4 | 3356 7018 | 714 | 17.112.0.0/16 | APPLE-ENGINEERING | US | APPLE.COM | APPLE C",
"end": 447,
"score": 0.9997237920761108,
"start": 437,
"tag": "IP_ADDRESS",
"value": "17.112.0.0"
}
] |
test/ipbgp/test.clj
|
geirskjo/ipbgp
| 2 |
(ns ipbgp.test
(:use [ipbgp])
(:use [clojure.test]))
(deftest parse-origin-test
(testing "Parse origin"
(let [line "3356 | 4.0.0.0/9 | LEVEL3 | US | DSL-VERIZON.NET | GTE.NET LLC"
res (parse-ans-line :origin line)]
(is (= "US" (:cn res)))
(is (= "3356" (:asn res)))
(is (= "LEVEL3" (:asname res))))))
(deftest parse-peer-test
(testing "Parse peer"
(let [line "17.112.1.4 | 3356 7018 | 714 | 17.112.0.0/16 | APPLE-ENGINEERING | US | APPLE.COM | APPLE COMPUTER INC"
res (parse-ans-line :peer line)]
(is (= "US" (:cn res)))
(is (= "714" (:asn res)))
(is (= 2 (count (:peers res))))
(is (= "APPLE-ENGINEERING" (:asname res))))))
|
68993
|
(ns ipbgp.test
(:use [ipbgp])
(:use [clojure.test]))
(deftest parse-origin-test
(testing "Parse origin"
(let [line "3356 | 4.0.0.0/9 | LEVEL3 | US | DSL-VERIZON.NET | GTE.NET LLC"
res (parse-ans-line :origin line)]
(is (= "US" (:cn res)))
(is (= "3356" (:asn res)))
(is (= "LEVEL3" (:asname res))))))
(deftest parse-peer-test
(testing "Parse peer"
(let [line "192.168.127.12 | 3356 7018 | 714 | 172.16.58.3/16 | APPLE-ENGINEERING | US | APPLE.COM | APPLE COMPUTER INC"
res (parse-ans-line :peer line)]
(is (= "US" (:cn res)))
(is (= "714" (:asn res)))
(is (= 2 (count (:peers res))))
(is (= "APPLE-ENGINEERING" (:asname res))))))
| true |
(ns ipbgp.test
(:use [ipbgp])
(:use [clojure.test]))
(deftest parse-origin-test
(testing "Parse origin"
(let [line "3356 | 4.0.0.0/9 | LEVEL3 | US | DSL-VERIZON.NET | GTE.NET LLC"
res (parse-ans-line :origin line)]
(is (= "US" (:cn res)))
(is (= "3356" (:asn res)))
(is (= "LEVEL3" (:asname res))))))
(deftest parse-peer-test
(testing "Parse peer"
(let [line "PI:IP_ADDRESS:192.168.127.12END_PI | 3356 7018 | 714 | PI:IP_ADDRESS:172.16.58.3END_PI/16 | APPLE-ENGINEERING | US | APPLE.COM | APPLE COMPUTER INC"
res (parse-ans-line :peer line)]
(is (= "US" (:cn res)))
(is (= "714" (:asn res)))
(is (= 2 (count (:peers res))))
(is (= "APPLE-ENGINEERING" (:asname res))))))
|
[
{
"context": "enticate [pass]\n (let [body (json/encode {:name \"user-1\" :pass pass})\n options {:body body :conten",
"end": 382,
"score": 0.9865042567253113,
"start": 376,
"tag": "USERNAME",
"value": "user-1"
},
{
"context": "y\n (let [token-length (count (authenticate \"pass-1\"))]\n (is (> token-length 40))))\n\n(deftest logi",
"end": 609,
"score": 0.5054585337638855,
"start": 608,
"tag": "PASSWORD",
"value": "1"
}
] |
test/clj/fullstack/authenticate_test.clj
|
danielmarreirosdeoliveira/fullstack-clj
| 0 |
(ns fullstack.authenticate-test
(:require [fullstack.server-helper :refer [start-server! addr]]
[clojure.test :as t :refer [deftest is]]
[clj-http.client :as http]
[cheshire.core :as json]))
(defn start-server [f]
(start-server!)
(f))
(t/use-fixtures :once start-server)
(defn authenticate [pass]
(let [body (json/encode {:name "user-1" :pass pass})
options {:body body :content-type :json}
response (http/post (str addr "/api/login") options)]
(:body response)))
(deftest login-successfully
(let [token-length (count (authenticate "pass-1"))]
(is (> token-length 40))))
(deftest login-failed
(let [token-length (count (authenticate "pass-"))]
(is (= token-length 0))))
|
52516
|
(ns fullstack.authenticate-test
(:require [fullstack.server-helper :refer [start-server! addr]]
[clojure.test :as t :refer [deftest is]]
[clj-http.client :as http]
[cheshire.core :as json]))
(defn start-server [f]
(start-server!)
(f))
(t/use-fixtures :once start-server)
(defn authenticate [pass]
(let [body (json/encode {:name "user-1" :pass pass})
options {:body body :content-type :json}
response (http/post (str addr "/api/login") options)]
(:body response)))
(deftest login-successfully
(let [token-length (count (authenticate "pass-<PASSWORD>"))]
(is (> token-length 40))))
(deftest login-failed
(let [token-length (count (authenticate "pass-"))]
(is (= token-length 0))))
| true |
(ns fullstack.authenticate-test
(:require [fullstack.server-helper :refer [start-server! addr]]
[clojure.test :as t :refer [deftest is]]
[clj-http.client :as http]
[cheshire.core :as json]))
(defn start-server [f]
(start-server!)
(f))
(t/use-fixtures :once start-server)
(defn authenticate [pass]
(let [body (json/encode {:name "user-1" :pass pass})
options {:body body :content-type :json}
response (http/post (str addr "/api/login") options)]
(:body response)))
(deftest login-successfully
(let [token-length (count (authenticate "pass-PI:PASSWORD:<PASSWORD>END_PI"))]
(is (> token-length 40))))
(deftest login-failed
(let [token-length (count (authenticate "pass-"))]
(is (= token-length 0))))
|
[
{
"context": "lojure\n;; docs in clojure/contrib/jmx.clj!!\n\n;; by Stuart Halloway\n\n;; Copyright (c) Stuart Halloway, 2009. All righ",
"end": 90,
"score": 0.9998790621757507,
"start": 75,
"tag": "NAME",
"value": "Stuart Halloway"
},
{
"context": "jmx.clj!!\n\n;; by Stuart Halloway\n\n;; Copyright (c) Stuart Halloway, 2009. All rights reserved. The use\n;; and distr",
"end": 124,
"score": 0.9998782277107239,
"start": 109,
"tag": "NAME",
"value": "Stuart Halloway"
}
] |
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/jmx/server.clj
|
allertonm/Couverjure
| 3 |
;; JMX server APIs for Clojure
;; docs in clojure/contrib/jmx.clj!!
;; by Stuart Halloway
;; Copyright (c) Stuart Halloway, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(in-ns 'clojure.contrib.jmx)
(defn register-mbean [mbean mbean-name]
(.registerMBean *connection* mbean (as-object-name mbean-name)))
|
12708
|
;; JMX server APIs for Clojure
;; docs in clojure/contrib/jmx.clj!!
;; by <NAME>
;; Copyright (c) <NAME>, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(in-ns 'clojure.contrib.jmx)
(defn register-mbean [mbean mbean-name]
(.registerMBean *connection* mbean (as-object-name mbean-name)))
| true |
;; JMX server APIs for Clojure
;; docs in clojure/contrib/jmx.clj!!
;; by PI:NAME:<NAME>END_PI
;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(in-ns 'clojure.contrib.jmx)
(defn register-mbean [mbean mbean-name]
(.registerMBean *connection* mbean (as-object-name mbean-name)))
|
[
{
"context": "ce (-> db (.get \"person/alice\") (.put #js {:name \"alice\" :age \"22\"})))\n(def peter (-> db (.get \"person/al",
"end": 177,
"score": 0.9992925524711609,
"start": 172,
"tag": "NAME",
"value": "alice"
},
{
"context": "er (-> db (.get \"person/alice\") (.put #js {:name \"peter\" :age \"42\"})))\n;;(-> people (.set alice))\n(def co",
"end": 256,
"score": 0.9985930323600769,
"start": 251,
"tag": "NAME",
"value": "peter"
}
] |
src/gunmoo/experiment.cljs
|
petergarbers/gunz
| 0 |
(ns gunmoo.experiment
(:require [cljsjs.gun :as gun]))
(def db (js/Gun.))
(def people (.. db (get "people")))
(def alice (-> db (.get "person/alice") (.put #js {:name "alice" :age "22"})))
(def peter (-> db (.get "person/alice") (.put #js {:name "peter" :age "42"})))
;;(-> people (.set alice))
(def company (-> db (.get "startup/hype")
(.put #js {:name "hype"
:profitable false
:address #js {:street "123 moo"
:city "denver"
:state "CA"
:country "USA"}})))
(defn vv
[db]
(-> db (.map (fn [node]
(js/console.log "Alice: " node)))))
(def aa (-> (js/Gun.) (.get "atom")))
(-> aa (.put #js {:name "hype"
:profitable false
:address #js {:street "123 moo"
:city "denver"
:state "CA"
:country "USA"}}))
|
77120
|
(ns gunmoo.experiment
(:require [cljsjs.gun :as gun]))
(def db (js/Gun.))
(def people (.. db (get "people")))
(def alice (-> db (.get "person/alice") (.put #js {:name "<NAME>" :age "22"})))
(def peter (-> db (.get "person/alice") (.put #js {:name "<NAME>" :age "42"})))
;;(-> people (.set alice))
(def company (-> db (.get "startup/hype")
(.put #js {:name "hype"
:profitable false
:address #js {:street "123 moo"
:city "denver"
:state "CA"
:country "USA"}})))
(defn vv
[db]
(-> db (.map (fn [node]
(js/console.log "Alice: " node)))))
(def aa (-> (js/Gun.) (.get "atom")))
(-> aa (.put #js {:name "hype"
:profitable false
:address #js {:street "123 moo"
:city "denver"
:state "CA"
:country "USA"}}))
| true |
(ns gunmoo.experiment
(:require [cljsjs.gun :as gun]))
(def db (js/Gun.))
(def people (.. db (get "people")))
(def alice (-> db (.get "person/alice") (.put #js {:name "PI:NAME:<NAME>END_PI" :age "22"})))
(def peter (-> db (.get "person/alice") (.put #js {:name "PI:NAME:<NAME>END_PI" :age "42"})))
;;(-> people (.set alice))
(def company (-> db (.get "startup/hype")
(.put #js {:name "hype"
:profitable false
:address #js {:street "123 moo"
:city "denver"
:state "CA"
:country "USA"}})))
(defn vv
[db]
(-> db (.map (fn [node]
(js/console.log "Alice: " node)))))
(def aa (-> (js/Gun.) (.get "atom")))
(-> aa (.put #js {:name "hype"
:profitable false
:address #js {:street "123 moo"
:city "denver"
:state "CA"
:country "USA"}}))
|
[
{
"context": "ker/name queues)\n worker-started-key (str \"worker:\" worker-name \":started\")\n time (format \"%",
"end": 1309,
"score": 0.8058381676673889,
"start": 1303,
"tag": "KEY",
"value": "worker"
},
{
"context": " worker-started-key (str \"worker:\" worker-name \":started\")\n time (format \"%1$ta %1$tb %1$td %1$tk:%",
"end": 1333,
"score": 0.9007230401039124,
"start": 1326,
"tag": "KEY",
"value": "started"
}
] |
src/resque_clojure/resque.clj
|
dsabanin/resque-clojure
| 0 |
(ns resque-clojure.resque
(:import [java.util Date])
(:require [resque-clojure.redis :as redis]
[clojure.data.json :as json]
[resque-clojure.worker :as worker]))
;; private api
(declare -namespace-key
-full-queue-name
-format-error
-dequeue-randomized)
;;
;; public api
;;
(def config (atom {:namespace "resque"
:error-handler nil}))
(defn configure [c]
(swap! config merge c))
(defn enqueue [queue worker-name & args]
(redis/sadd (-namespace-key "queues") queue)
(redis/rpush (-full-queue-name queue)
(json/json-str {:class worker-name :args args})))
(defn dequeue [queues]
"Randomizes the list of queues. Then returns the first queue that contains a job.
Returns a hash of: {:queue \"queue-name\" :data {...}} or nil"
(let [msg (-dequeue-randomized queues)]
(if msg
(let [{:keys [class args]} (json/read-json (:data msg))]
(assoc msg :func class :args args)))))
(defn report-error [result]
(let [error (-format-error result)
handle (:error-handler @config)]
(redis/rpush (-namespace-key "failed") (json/json-str error))
(when handle
(handle error))))
(defn register [queues]
(let [worker-name (worker/name queues)
worker-started-key (str "worker:" worker-name ":started")
time (format "%1$ta %1$tb %1$td %1$tk:%1$tM:%1$tS %1$tz %1$tY" (Date.))]
(redis/sadd (-namespace-key "workers") worker-name)
(redis/set (-namespace-key worker-started-key) time)))
(defn unregister [queues]
(let [worker-name (worker/name queues)
keys (redis/keys (str "*" worker-name "*"))
workers-set (-namespace-key "workers")]
(redis/del worker-name)
(redis/srem workers-set worker-name)
(if (empty? (redis/smembers workers-set))
(redis/del workers-set))
(doseq [key keys]
(redis/del key))))
;;
;; private
;;
(defn -namespace-key [key]
(str (:namespace @config) ":" key))
(defn -full-queue-name [name]
(-namespace-key (str "queue:" name)))
(defn -format-error [result]
(let [exception (:exception result)
stacktrace (map #(.toString %) (.getStackTrace exception))
exception-class (-> exception (.getClass) (.getName))]
{:failed_at (format "%1$tY/%1$tm/%1$td %1$tk:%1$tM:%1$tS" (Date.))
:payload (select-keys result [:job :class :args])
:exception exception-class
:error (or (.getMessage exception) "(null)")
:backtrace stacktrace
:worker (apply str (interpose ":" (reverse (.split (.getName (java.lang.management.ManagementFactory/getRuntimeMXBean)) "@"))))
:queue (:queue result)}))
(defn -dequeue-randomized [queues]
"Randomizes the list of queues. Then returns the first queue that contains a job"
(loop [qs (shuffle queues)]
(let [q (first qs)
nsq (-full-queue-name q)
job (redis/lpop nsq)]
(cond
(empty? qs) nil
job {:queue q :data job}
:else (recur (rest qs))))))
|
13301
|
(ns resque-clojure.resque
(:import [java.util Date])
(:require [resque-clojure.redis :as redis]
[clojure.data.json :as json]
[resque-clojure.worker :as worker]))
;; private api
(declare -namespace-key
-full-queue-name
-format-error
-dequeue-randomized)
;;
;; public api
;;
(def config (atom {:namespace "resque"
:error-handler nil}))
(defn configure [c]
(swap! config merge c))
(defn enqueue [queue worker-name & args]
(redis/sadd (-namespace-key "queues") queue)
(redis/rpush (-full-queue-name queue)
(json/json-str {:class worker-name :args args})))
(defn dequeue [queues]
"Randomizes the list of queues. Then returns the first queue that contains a job.
Returns a hash of: {:queue \"queue-name\" :data {...}} or nil"
(let [msg (-dequeue-randomized queues)]
(if msg
(let [{:keys [class args]} (json/read-json (:data msg))]
(assoc msg :func class :args args)))))
(defn report-error [result]
(let [error (-format-error result)
handle (:error-handler @config)]
(redis/rpush (-namespace-key "failed") (json/json-str error))
(when handle
(handle error))))
(defn register [queues]
(let [worker-name (worker/name queues)
worker-started-key (str "<KEY>:" worker-name ":<KEY>")
time (format "%1$ta %1$tb %1$td %1$tk:%1$tM:%1$tS %1$tz %1$tY" (Date.))]
(redis/sadd (-namespace-key "workers") worker-name)
(redis/set (-namespace-key worker-started-key) time)))
(defn unregister [queues]
(let [worker-name (worker/name queues)
keys (redis/keys (str "*" worker-name "*"))
workers-set (-namespace-key "workers")]
(redis/del worker-name)
(redis/srem workers-set worker-name)
(if (empty? (redis/smembers workers-set))
(redis/del workers-set))
(doseq [key keys]
(redis/del key))))
;;
;; private
;;
(defn -namespace-key [key]
(str (:namespace @config) ":" key))
(defn -full-queue-name [name]
(-namespace-key (str "queue:" name)))
(defn -format-error [result]
(let [exception (:exception result)
stacktrace (map #(.toString %) (.getStackTrace exception))
exception-class (-> exception (.getClass) (.getName))]
{:failed_at (format "%1$tY/%1$tm/%1$td %1$tk:%1$tM:%1$tS" (Date.))
:payload (select-keys result [:job :class :args])
:exception exception-class
:error (or (.getMessage exception) "(null)")
:backtrace stacktrace
:worker (apply str (interpose ":" (reverse (.split (.getName (java.lang.management.ManagementFactory/getRuntimeMXBean)) "@"))))
:queue (:queue result)}))
(defn -dequeue-randomized [queues]
"Randomizes the list of queues. Then returns the first queue that contains a job"
(loop [qs (shuffle queues)]
(let [q (first qs)
nsq (-full-queue-name q)
job (redis/lpop nsq)]
(cond
(empty? qs) nil
job {:queue q :data job}
:else (recur (rest qs))))))
| true |
(ns resque-clojure.resque
(:import [java.util Date])
(:require [resque-clojure.redis :as redis]
[clojure.data.json :as json]
[resque-clojure.worker :as worker]))
;; private api
(declare -namespace-key
-full-queue-name
-format-error
-dequeue-randomized)
;;
;; public api
;;
(def config (atom {:namespace "resque"
:error-handler nil}))
(defn configure [c]
(swap! config merge c))
(defn enqueue [queue worker-name & args]
(redis/sadd (-namespace-key "queues") queue)
(redis/rpush (-full-queue-name queue)
(json/json-str {:class worker-name :args args})))
(defn dequeue [queues]
"Randomizes the list of queues. Then returns the first queue that contains a job.
Returns a hash of: {:queue \"queue-name\" :data {...}} or nil"
(let [msg (-dequeue-randomized queues)]
(if msg
(let [{:keys [class args]} (json/read-json (:data msg))]
(assoc msg :func class :args args)))))
(defn report-error [result]
(let [error (-format-error result)
handle (:error-handler @config)]
(redis/rpush (-namespace-key "failed") (json/json-str error))
(when handle
(handle error))))
(defn register [queues]
(let [worker-name (worker/name queues)
worker-started-key (str "PI:KEY:<KEY>END_PI:" worker-name ":PI:KEY:<KEY>END_PI")
time (format "%1$ta %1$tb %1$td %1$tk:%1$tM:%1$tS %1$tz %1$tY" (Date.))]
(redis/sadd (-namespace-key "workers") worker-name)
(redis/set (-namespace-key worker-started-key) time)))
(defn unregister [queues]
(let [worker-name (worker/name queues)
keys (redis/keys (str "*" worker-name "*"))
workers-set (-namespace-key "workers")]
(redis/del worker-name)
(redis/srem workers-set worker-name)
(if (empty? (redis/smembers workers-set))
(redis/del workers-set))
(doseq [key keys]
(redis/del key))))
;;
;; private
;;
(defn -namespace-key [key]
(str (:namespace @config) ":" key))
(defn -full-queue-name [name]
(-namespace-key (str "queue:" name)))
(defn -format-error [result]
(let [exception (:exception result)
stacktrace (map #(.toString %) (.getStackTrace exception))
exception-class (-> exception (.getClass) (.getName))]
{:failed_at (format "%1$tY/%1$tm/%1$td %1$tk:%1$tM:%1$tS" (Date.))
:payload (select-keys result [:job :class :args])
:exception exception-class
:error (or (.getMessage exception) "(null)")
:backtrace stacktrace
:worker (apply str (interpose ":" (reverse (.split (.getName (java.lang.management.ManagementFactory/getRuntimeMXBean)) "@"))))
:queue (:queue result)}))
(defn -dequeue-randomized [queues]
"Randomizes the list of queues. Then returns the first queue that contains a job"
(loop [qs (shuffle queues)]
(let [q (first qs)
nsq (-full-queue-name q)
job (redis/lpop nsq)]
(cond
(empty? qs) nil
job {:queue q :data job}
:else (recur (rest qs))))))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"palisades dot lakes at gmail dot com\"\n :date \"2021-10-25\"\n :doc \n \"Gene",
"end": 123,
"score": 0.9446613192558289,
"start": 87,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] |
src/main/clojure/nzqr/commons/core.clj
|
palisades-lakes/nzqr
| 0 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "palisades dot lakes at gmail dot com"
:date "2021-10-25"
:doc
"Generally useful stuff with no obvious better location" }
nzqr.commons.core
(:refer-clojure :exclude [contains? name time])
(:require [clojure.pprint :as pp]
[clojure.string :as s])
(:import [java.lang.reflect Method]
[java.util Collection HashMap Iterator List Map]
[java.time LocalDateTime]
[java.time.format DateTimeFormatter]
[com.google.common.collect Multimap]
;;[zana.java.functions Functions]
))
;;----------------------------------------------------------------
(defn jvm-args
"Return the command line arguments passed to java.
Useful for logging."
[]
(.getInputArguments
(java.lang.management.ManagementFactory/getRuntimeMXBean)))
;;----------------------------------------------------------------
;; try to find a reasonable name for any object
;;----------------------------------------------------------------
;(defn- fn-name [^clojure.lang.IFn f]
; (Functions/name f)
; #_(let [strf (str f)]
; (if (.startsWith ^String strf "clojure.core$constantly$fn")
; (str "(constantly " (print-str (f nil)) ")")
; (let [fname (s/replace strf #"^(.+)\$([^@]+)(|@.+)$" "$2")
; fname (s/replace fname \_ \-)
; fname (s/replace fname #"--\d+$" "")]
; fname))))
;;----------------------------------------------------------------
;; Search for a Var whose value is equal to v.
(defn- find-binding [v]
(ffirst (filter #(= v (var-get (second %)))
(mapcat ns-publics (all-ns)))))
(defn- binding-name [x]
(if-let [sym (find-binding x)] (str sym) ""))
;;----------------------------------------------------------------
(defmulti ^String name
"Try to find a reasonable name string for <code>x</code>.<br>
Try harder than <code>clojure.core/name</code>."
(fn dispatch-name [x] (class x)))
(defmethod name :default [x] (binding-name x))
(defmethod name nil [x] nil)
(defmethod name String [^String x] x)
(defmethod name Class [^Class x] (.getSimpleName x))
(defmethod name java.io.File [^java.io.File x] (.getName x))
(defmethod name clojure.lang.Namespace [x] (str x))
(defmethod name java.util.Collection [^java.util.Collection x]
(binding-name x))
(defmethod name clojure.lang.Fn [^clojure.lang.Fn x]
(let [mn (:name (meta x))
bn (binding-name x)
;;fn (fn-name x)
]
(cond (not (empty? mn)) mn
(not (empty? bn)) bn
;;(not (empty? fn)) fn
:else "")))
(defmethod name clojure.lang.IMeta [^clojure.lang.IMeta x]
(or (:name (meta x)) (binding-name x)))
(prefer-method name clojure.lang.IMeta java.util.Collection)
(prefer-method name clojure.lang.Fn clojure.lang.IMeta)
(defmethod name clojure.lang.Named [x] (clojure.core/name x))
(prefer-method name clojure.lang.Named java.util.Collection)
(prefer-method name clojure.lang.Named clojure.lang.Fn)
(prefer-method name clojure.lang.Named clojure.lang.IMeta)
;;----------------------------------------------------------------
;; see https://stackoverflow.com/questions/1696693/clojure-how-to-find-out-the-arity-of-function-at-runtime
(defn arity
"Returns the maximum arity of:
- anonymous functions like `#()` and `(fn [])`.
- defn'ed functions like `map` or `+`.
- macros, by passing a var like `#'->`.
Returns `:variadic` if the function/macro is variadic."
[f]
(let [func (if (var? f) @f f)
methods (->> func class .getDeclaredMethods
(map #(vector (.getName ^Method %)
(count (.getParameterTypes ^Method %)))))
var-args? (some #(-> % first #{"getRequiredArity"})
methods)]
(if var-args?
:variadic
(let [max-arity (->> methods
(filter (comp #{"invoke"} first))
(sort-by second)
last
second)]
(if (and (var? f) (-> f meta :macro))
(- (int max-arity) 2)
;; substract implicit &form and &env arguments
max-arity)))))
;;----------------------------------------------------------------
;; timing
;;----------------------------------------------------------------
;; like clojure.core.time, prefixes results with a message
(defmacro time
"Evaluates expr and prints the time it took.
Returns the value of expr."
([msg expr]
`(let [start# (System/nanoTime)
ret# ~expr
end# (System/nanoTime)
msec# (/ (Math/round (/ (double (- end# start#))
10000.0))
100.0)]
(println ~msg (float msec#) "ms")
ret#))
([expr] `(time (str (quote ~@expr)) ~expr)))
;; like clojure.core.time, but reports results rounded to seconds
;; and minutes
(defmacro seconds
"Evaluates expr and prints the time it took.
Returns the value of expr."
([msg & exprs]
(let [expr `(do ~@exprs)]
`(let [
^DateTimeFormatter fmt#
(DateTimeFormatter/ofPattern "yyyy-MM-dd HH:mm:ss")]
(println ~msg (.format fmt# (LocalDateTime/now)))
(let [start# (System/nanoTime)
ret# ~expr
end# (System/nanoTime)
msec# (/ (double (- end# start#)) 1000000.0)
sec# (/ msec# 1000.0)
min# (/ sec# 60.0)]
(println ~msg (.format fmt# (LocalDateTime/now))
(str "(" (int (Math/round msec#)) "ms)"
" ("(int (Math/round min#)) "m) "
(int (Math/round sec#)) "s"))
ret#))))
([exprs] `(seconds "" ~@exprs)))
;;----------------------------------------------------------------
(defn print-stack-trace
([] (.printStackTrace (Throwable.)))
([& args]
(let [^String msg (s/join " " args)]
(.printStackTrace (Throwable. msg)))))
;;----------------------------------------------------------------
(defn pprint-str
"Pretty print <code>x</code> without getting carried away..."
([x length depth]
(binding [*print-length* length
*print-level* depth
pp/*print-right-margin* 160
pp/*print-miser-width* 128
pp/*print-suppress-namespaces* true]
(with-out-str (pp/pprint x))))
([x length] (pprint-str x length 8))
([x] (pprint-str x 10 8)))
;;----------------------------------------------------------------
(defmacro echo
"Print the expressions followed by their values.
Useful for quick logging."
[& es]
`(do
~@(mapv (fn [e]
`(print
"\n"
(pprint-str (quote ~e) 60)
"->\n"
(pprint-str ~e 60)))
es)))
;;----------------------------------------------------------------
(defmacro echo-types
"Print the expressions followed by their values and types.
Useful for quick logging.
TODO: detect and format short expressions/values on one line;
newlines between expression, value, and type for
shorter ones. Desired line length as optional arg?
Line up expr, value, type in columns?"
[& es]
`(do
~@(mapv (fn [e]
`(let [v# ~e]
(println (quote ~e) "->" v# ":" (type v#))))
es)))
;;----------------------------------------------------------------
|
29586
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<EMAIL>"
:date "2021-10-25"
:doc
"Generally useful stuff with no obvious better location" }
nzqr.commons.core
(:refer-clojure :exclude [contains? name time])
(:require [clojure.pprint :as pp]
[clojure.string :as s])
(:import [java.lang.reflect Method]
[java.util Collection HashMap Iterator List Map]
[java.time LocalDateTime]
[java.time.format DateTimeFormatter]
[com.google.common.collect Multimap]
;;[zana.java.functions Functions]
))
;;----------------------------------------------------------------
(defn jvm-args
"Return the command line arguments passed to java.
Useful for logging."
[]
(.getInputArguments
(java.lang.management.ManagementFactory/getRuntimeMXBean)))
;;----------------------------------------------------------------
;; try to find a reasonable name for any object
;;----------------------------------------------------------------
;(defn- fn-name [^clojure.lang.IFn f]
; (Functions/name f)
; #_(let [strf (str f)]
; (if (.startsWith ^String strf "clojure.core$constantly$fn")
; (str "(constantly " (print-str (f nil)) ")")
; (let [fname (s/replace strf #"^(.+)\$([^@]+)(|@.+)$" "$2")
; fname (s/replace fname \_ \-)
; fname (s/replace fname #"--\d+$" "")]
; fname))))
;;----------------------------------------------------------------
;; Search for a Var whose value is equal to v.
(defn- find-binding [v]
(ffirst (filter #(= v (var-get (second %)))
(mapcat ns-publics (all-ns)))))
(defn- binding-name [x]
(if-let [sym (find-binding x)] (str sym) ""))
;;----------------------------------------------------------------
(defmulti ^String name
"Try to find a reasonable name string for <code>x</code>.<br>
Try harder than <code>clojure.core/name</code>."
(fn dispatch-name [x] (class x)))
(defmethod name :default [x] (binding-name x))
(defmethod name nil [x] nil)
(defmethod name String [^String x] x)
(defmethod name Class [^Class x] (.getSimpleName x))
(defmethod name java.io.File [^java.io.File x] (.getName x))
(defmethod name clojure.lang.Namespace [x] (str x))
(defmethod name java.util.Collection [^java.util.Collection x]
(binding-name x))
(defmethod name clojure.lang.Fn [^clojure.lang.Fn x]
(let [mn (:name (meta x))
bn (binding-name x)
;;fn (fn-name x)
]
(cond (not (empty? mn)) mn
(not (empty? bn)) bn
;;(not (empty? fn)) fn
:else "")))
(defmethod name clojure.lang.IMeta [^clojure.lang.IMeta x]
(or (:name (meta x)) (binding-name x)))
(prefer-method name clojure.lang.IMeta java.util.Collection)
(prefer-method name clojure.lang.Fn clojure.lang.IMeta)
(defmethod name clojure.lang.Named [x] (clojure.core/name x))
(prefer-method name clojure.lang.Named java.util.Collection)
(prefer-method name clojure.lang.Named clojure.lang.Fn)
(prefer-method name clojure.lang.Named clojure.lang.IMeta)
;;----------------------------------------------------------------
;; see https://stackoverflow.com/questions/1696693/clojure-how-to-find-out-the-arity-of-function-at-runtime
(defn arity
"Returns the maximum arity of:
- anonymous functions like `#()` and `(fn [])`.
- defn'ed functions like `map` or `+`.
- macros, by passing a var like `#'->`.
Returns `:variadic` if the function/macro is variadic."
[f]
(let [func (if (var? f) @f f)
methods (->> func class .getDeclaredMethods
(map #(vector (.getName ^Method %)
(count (.getParameterTypes ^Method %)))))
var-args? (some #(-> % first #{"getRequiredArity"})
methods)]
(if var-args?
:variadic
(let [max-arity (->> methods
(filter (comp #{"invoke"} first))
(sort-by second)
last
second)]
(if (and (var? f) (-> f meta :macro))
(- (int max-arity) 2)
;; substract implicit &form and &env arguments
max-arity)))))
;;----------------------------------------------------------------
;; timing
;;----------------------------------------------------------------
;; like clojure.core.time, prefixes results with a message
(defmacro time
"Evaluates expr and prints the time it took.
Returns the value of expr."
([msg expr]
`(let [start# (System/nanoTime)
ret# ~expr
end# (System/nanoTime)
msec# (/ (Math/round (/ (double (- end# start#))
10000.0))
100.0)]
(println ~msg (float msec#) "ms")
ret#))
([expr] `(time (str (quote ~@expr)) ~expr)))
;; like clojure.core.time, but reports results rounded to seconds
;; and minutes
(defmacro seconds
"Evaluates expr and prints the time it took.
Returns the value of expr."
([msg & exprs]
(let [expr `(do ~@exprs)]
`(let [
^DateTimeFormatter fmt#
(DateTimeFormatter/ofPattern "yyyy-MM-dd HH:mm:ss")]
(println ~msg (.format fmt# (LocalDateTime/now)))
(let [start# (System/nanoTime)
ret# ~expr
end# (System/nanoTime)
msec# (/ (double (- end# start#)) 1000000.0)
sec# (/ msec# 1000.0)
min# (/ sec# 60.0)]
(println ~msg (.format fmt# (LocalDateTime/now))
(str "(" (int (Math/round msec#)) "ms)"
" ("(int (Math/round min#)) "m) "
(int (Math/round sec#)) "s"))
ret#))))
([exprs] `(seconds "" ~@exprs)))
;;----------------------------------------------------------------
(defn print-stack-trace
([] (.printStackTrace (Throwable.)))
([& args]
(let [^String msg (s/join " " args)]
(.printStackTrace (Throwable. msg)))))
;;----------------------------------------------------------------
(defn pprint-str
"Pretty print <code>x</code> without getting carried away..."
([x length depth]
(binding [*print-length* length
*print-level* depth
pp/*print-right-margin* 160
pp/*print-miser-width* 128
pp/*print-suppress-namespaces* true]
(with-out-str (pp/pprint x))))
([x length] (pprint-str x length 8))
([x] (pprint-str x 10 8)))
;;----------------------------------------------------------------
(defmacro echo
"Print the expressions followed by their values.
Useful for quick logging."
[& es]
`(do
~@(mapv (fn [e]
`(print
"\n"
(pprint-str (quote ~e) 60)
"->\n"
(pprint-str ~e 60)))
es)))
;;----------------------------------------------------------------
(defmacro echo-types
"Print the expressions followed by their values and types.
Useful for quick logging.
TODO: detect and format short expressions/values on one line;
newlines between expression, value, and type for
shorter ones. Desired line length as optional arg?
Line up expr, value, type in columns?"
[& es]
`(do
~@(mapv (fn [e]
`(let [v# ~e]
(println (quote ~e) "->" v# ":" (type v#))))
es)))
;;----------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:EMAIL:<EMAIL>END_PI"
:date "2021-10-25"
:doc
"Generally useful stuff with no obvious better location" }
nzqr.commons.core
(:refer-clojure :exclude [contains? name time])
(:require [clojure.pprint :as pp]
[clojure.string :as s])
(:import [java.lang.reflect Method]
[java.util Collection HashMap Iterator List Map]
[java.time LocalDateTime]
[java.time.format DateTimeFormatter]
[com.google.common.collect Multimap]
;;[zana.java.functions Functions]
))
;;----------------------------------------------------------------
(defn jvm-args
"Return the command line arguments passed to java.
Useful for logging."
[]
(.getInputArguments
(java.lang.management.ManagementFactory/getRuntimeMXBean)))
;;----------------------------------------------------------------
;; try to find a reasonable name for any object
;;----------------------------------------------------------------
;(defn- fn-name [^clojure.lang.IFn f]
; (Functions/name f)
; #_(let [strf (str f)]
; (if (.startsWith ^String strf "clojure.core$constantly$fn")
; (str "(constantly " (print-str (f nil)) ")")
; (let [fname (s/replace strf #"^(.+)\$([^@]+)(|@.+)$" "$2")
; fname (s/replace fname \_ \-)
; fname (s/replace fname #"--\d+$" "")]
; fname))))
;;----------------------------------------------------------------
;; Search for a Var whose value is equal to v.
(defn- find-binding [v]
(ffirst (filter #(= v (var-get (second %)))
(mapcat ns-publics (all-ns)))))
(defn- binding-name [x]
(if-let [sym (find-binding x)] (str sym) ""))
;;----------------------------------------------------------------
(defmulti ^String name
"Try to find a reasonable name string for <code>x</code>.<br>
Try harder than <code>clojure.core/name</code>."
(fn dispatch-name [x] (class x)))
(defmethod name :default [x] (binding-name x))
(defmethod name nil [x] nil)
(defmethod name String [^String x] x)
(defmethod name Class [^Class x] (.getSimpleName x))
(defmethod name java.io.File [^java.io.File x] (.getName x))
(defmethod name clojure.lang.Namespace [x] (str x))
(defmethod name java.util.Collection [^java.util.Collection x]
(binding-name x))
(defmethod name clojure.lang.Fn [^clojure.lang.Fn x]
(let [mn (:name (meta x))
bn (binding-name x)
;;fn (fn-name x)
]
(cond (not (empty? mn)) mn
(not (empty? bn)) bn
;;(not (empty? fn)) fn
:else "")))
(defmethod name clojure.lang.IMeta [^clojure.lang.IMeta x]
(or (:name (meta x)) (binding-name x)))
(prefer-method name clojure.lang.IMeta java.util.Collection)
(prefer-method name clojure.lang.Fn clojure.lang.IMeta)
(defmethod name clojure.lang.Named [x] (clojure.core/name x))
(prefer-method name clojure.lang.Named java.util.Collection)
(prefer-method name clojure.lang.Named clojure.lang.Fn)
(prefer-method name clojure.lang.Named clojure.lang.IMeta)
;;----------------------------------------------------------------
;; see https://stackoverflow.com/questions/1696693/clojure-how-to-find-out-the-arity-of-function-at-runtime
(defn arity
"Returns the maximum arity of:
- anonymous functions like `#()` and `(fn [])`.
- defn'ed functions like `map` or `+`.
- macros, by passing a var like `#'->`.
Returns `:variadic` if the function/macro is variadic."
[f]
(let [func (if (var? f) @f f)
methods (->> func class .getDeclaredMethods
(map #(vector (.getName ^Method %)
(count (.getParameterTypes ^Method %)))))
var-args? (some #(-> % first #{"getRequiredArity"})
methods)]
(if var-args?
:variadic
(let [max-arity (->> methods
(filter (comp #{"invoke"} first))
(sort-by second)
last
second)]
(if (and (var? f) (-> f meta :macro))
(- (int max-arity) 2)
;; substract implicit &form and &env arguments
max-arity)))))
;;----------------------------------------------------------------
;; timing
;;----------------------------------------------------------------
;; like clojure.core.time, prefixes results with a message
(defmacro time
"Evaluates expr and prints the time it took.
Returns the value of expr."
([msg expr]
`(let [start# (System/nanoTime)
ret# ~expr
end# (System/nanoTime)
msec# (/ (Math/round (/ (double (- end# start#))
10000.0))
100.0)]
(println ~msg (float msec#) "ms")
ret#))
([expr] `(time (str (quote ~@expr)) ~expr)))
;; like clojure.core.time, but reports results rounded to seconds
;; and minutes
(defmacro seconds
"Evaluates expr and prints the time it took.
Returns the value of expr."
([msg & exprs]
(let [expr `(do ~@exprs)]
`(let [
^DateTimeFormatter fmt#
(DateTimeFormatter/ofPattern "yyyy-MM-dd HH:mm:ss")]
(println ~msg (.format fmt# (LocalDateTime/now)))
(let [start# (System/nanoTime)
ret# ~expr
end# (System/nanoTime)
msec# (/ (double (- end# start#)) 1000000.0)
sec# (/ msec# 1000.0)
min# (/ sec# 60.0)]
(println ~msg (.format fmt# (LocalDateTime/now))
(str "(" (int (Math/round msec#)) "ms)"
" ("(int (Math/round min#)) "m) "
(int (Math/round sec#)) "s"))
ret#))))
([exprs] `(seconds "" ~@exprs)))
;;----------------------------------------------------------------
(defn print-stack-trace
([] (.printStackTrace (Throwable.)))
([& args]
(let [^String msg (s/join " " args)]
(.printStackTrace (Throwable. msg)))))
;;----------------------------------------------------------------
(defn pprint-str
"Pretty print <code>x</code> without getting carried away..."
([x length depth]
(binding [*print-length* length
*print-level* depth
pp/*print-right-margin* 160
pp/*print-miser-width* 128
pp/*print-suppress-namespaces* true]
(with-out-str (pp/pprint x))))
([x length] (pprint-str x length 8))
([x] (pprint-str x 10 8)))
;;----------------------------------------------------------------
(defmacro echo
"Print the expressions followed by their values.
Useful for quick logging."
[& es]
`(do
~@(mapv (fn [e]
`(print
"\n"
(pprint-str (quote ~e) 60)
"->\n"
(pprint-str ~e 60)))
es)))
;;----------------------------------------------------------------
(defmacro echo-types
"Print the expressions followed by their values and types.
Useful for quick logging.
TODO: detect and format short expressions/values on one line;
newlines between expression, value, and type for
shorter ones. Desired line length as optional arg?
Line up expr, value, type in columns?"
[& es]
`(do
~@(mapv (fn [e]
`(let [v# ~e]
(println (quote ~e) "->" v# ":" (type v#))))
es)))
;;----------------------------------------------------------------
|
[
{
"context": " String\n :password String\n :first_name String\n :last_na",
"end": 161,
"score": 0.9909750819206238,
"start": 155,
"tag": "PASSWORD",
"value": "String"
}
] |
src/receptionist/identity/schema.clj
|
chargegrid/receptionist
| 0 |
(ns receptionist.identity.schema
(:require [schema.core :as s]))
(s/defschema User
{:email String
:password String
:first_name String
:last_name String
(s/optional-key :job_title) String})
(s/defschema Role
{:name String
(s/optional-key :description) String})
|
116196
|
(ns receptionist.identity.schema
(:require [schema.core :as s]))
(s/defschema User
{:email String
:password <PASSWORD>
:first_name String
:last_name String
(s/optional-key :job_title) String})
(s/defschema Role
{:name String
(s/optional-key :description) String})
| true |
(ns receptionist.identity.schema
(:require [schema.core :as s]))
(s/defschema User
{:email String
:password PI:PASSWORD:<PASSWORD>END_PI
:first_name String
:last_name String
(s/optional-key :job_title) String})
(s/defschema Role
{:name String
(s/optional-key :description) String})
|
[
{
"context": "\"#UserID\" username)\n (taxi/input-text \"#Password\" password)\n\n (taxi/click (taxi/element \"#loginImage\"))\n\n ",
"end": 509,
"score": 0.6623618602752686,
"start": 501,
"tag": "PASSWORD",
"value": "password"
}
] |
src/statement_hoarder/sites/american_express.clj
|
pgr0ss/statement_hoarder
| 4 |
(ns statement-hoarder.sites.american-express
(require [clj-webdriver.taxi :as taxi]
[clojure.string :as string]
[statement-hoarder.download :as download]
[statement-hoarder.finders :as finders]))
(def TABLE-SELECTOR "div#ctl00_SPWebPartManager1_g_d4ac20d8_bb7c_4b89_a496_19eed73e874f table")
(defn download [statement-path username password]
(taxi/get-url "https://www.americanexpress.com")
(taxi/input-text "#UserID" username)
(taxi/input-text "#Password" password)
(taxi/click (taxi/element "#loginImage"))
(taxi/click (finders/find-link-by-text "Statements & Activity"))
(taxi/click (taxi/element "#LinkBilling"))
(doseq [download-link (taxi/elements ".pdfImage")]
(let [date-string (-> download-link :webelement .getText)
[month day year] (string/split date-string #" ")
filename (str "Statement_" month " " year ".pdf")]
(download/download-link statement-path (str "American Express/" year) filename filename download-link))))
|
96535
|
(ns statement-hoarder.sites.american-express
(require [clj-webdriver.taxi :as taxi]
[clojure.string :as string]
[statement-hoarder.download :as download]
[statement-hoarder.finders :as finders]))
(def TABLE-SELECTOR "div#ctl00_SPWebPartManager1_g_d4ac20d8_bb7c_4b89_a496_19eed73e874f table")
(defn download [statement-path username password]
(taxi/get-url "https://www.americanexpress.com")
(taxi/input-text "#UserID" username)
(taxi/input-text "#Password" <PASSWORD>)
(taxi/click (taxi/element "#loginImage"))
(taxi/click (finders/find-link-by-text "Statements & Activity"))
(taxi/click (taxi/element "#LinkBilling"))
(doseq [download-link (taxi/elements ".pdfImage")]
(let [date-string (-> download-link :webelement .getText)
[month day year] (string/split date-string #" ")
filename (str "Statement_" month " " year ".pdf")]
(download/download-link statement-path (str "American Express/" year) filename filename download-link))))
| true |
(ns statement-hoarder.sites.american-express
(require [clj-webdriver.taxi :as taxi]
[clojure.string :as string]
[statement-hoarder.download :as download]
[statement-hoarder.finders :as finders]))
(def TABLE-SELECTOR "div#ctl00_SPWebPartManager1_g_d4ac20d8_bb7c_4b89_a496_19eed73e874f table")
(defn download [statement-path username password]
(taxi/get-url "https://www.americanexpress.com")
(taxi/input-text "#UserID" username)
(taxi/input-text "#Password" PI:PASSWORD:<PASSWORD>END_PI)
(taxi/click (taxi/element "#loginImage"))
(taxi/click (finders/find-link-by-text "Statements & Activity"))
(taxi/click (taxi/element "#LinkBilling"))
(doseq [download-link (taxi/elements ".pdfImage")]
(let [date-string (-> download-link :webelement .getText)
[month day year] (string/split date-string #" ")
filename (str "Statement_" month " " year ".pdf")]
(download/download-link statement-path (str "American Express/" year) filename filename download-link))))
|
[
{
"context": "\" db-user-name)\n (str \"jdbc.default.password=\" db-user-passwd)\n \"#\"\n \"# C3PO\"\n \"#\"\n ",
"end": 1964,
"score": 0.6275793313980103,
"start": 1962,
"tag": "PASSWORD",
"value": "db"
}
] |
main/src/dda/pallet/dda_liferay_crate/domain/liferay_config.clj
|
DomainDrivenArchitecture/dda-liferay-crate
| 0 |
; Licensed to the Apache Software Foundation (ASF) under one
; or more contributor license agreements. See the NOTICE file
; distributed with this work for additional information
; regarding copyright ownership. The ASF licenses this file
; to you under the Apache License, Version 2.0 (the
; "License"); you may not use this file except in compliance
; with the License. You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns dda.pallet.dda-liferay-crate.domain.liferay-config
(:require
[schema.core :as s]
[dda.pallet.dda-liferay-crate.domain.schema :as schema]))
; ---------- auxiliary functions for creating infra configuration ------
(s/defn portal-ext-properties
"creates the default portal-ext.properties for MySQL or mariaDB."
[domain-config :- schema/LiferayDomainConfigResolved
db-name :- s/Str
liferay-version]
(let [{:keys [db-user-name db-user-passwd]} domain-config
db-type (case liferay-version
:LR7 "mariadb"
:LR6 "mysql")
db-driver (case liferay-version
:LR7 "org.mariadb.jdbc.Driver"
:LR6 "com.mysql.jdbc.Driver")]
["#"
"# Techbase"
"#"
"liferay.home=/var/lib/liferay"
"setup.wizard.enabled=true"
"index.on.startup=false"
"#"
"# MySQL"
"#"
(str "jdbc.default.driverClassName=" db-driver)
(str "jdbc.default.url=jdbc:" db-type "://localhost:3306/" db-name
"?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false")
(str "jdbc.default.username=" db-user-name)
(str "jdbc.default.password=" db-user-passwd)
"#"
"# C3PO"
"#"
"#jdbc.default.acquireIncrement=2"
"#jdbc.default.idleConnectionTestPeriod=60"
"#jdbc.default.maxIdleTime=3600"
"#jdbc.default.maxPoolSize=100"
"#jdbc.default.minPoolSize=40"
""
"#"
"# Timeouts"
"#"
"com.liferay.util.Http.timeout=1000"
"session.timeout=120"
""]))
(s/defn default-release
"The default release configuration."
[portal-ext-lines liferay-version]
(merge {:name "LiferayCE"
:config portal-ext-lines}
(case liferay-version
:LR7 {:version [7 0 4]
:app ["ROOT" "https://netcologne.dl.sourceforge.net/project/lportal/Liferay%20Portal/7.0.4%20GA5/liferay-ce-portal-7.0-ga5-20171018150113838.war"]}
:LR6 {:version [6 2 1]
:app ["ROOT" "http://ufpr.dl.sourceforge.net/project/lportal/Liferay%20Portal/6.2.1%20GA2/liferay-portal-6.2-ce-ga2-20140319114139101.war"]})))
(s/defn default-release-config
"The default release configuration."
[domain-config :- schema/LiferayDomainConfigResolved
db-name :- s/Str
liferay-version]
(default-release (portal-ext-properties domain-config db-name liferay-version) liferay-version))
|
86815
|
; Licensed to the Apache Software Foundation (ASF) under one
; or more contributor license agreements. See the NOTICE file
; distributed with this work for additional information
; regarding copyright ownership. The ASF licenses this file
; to you under the Apache License, Version 2.0 (the
; "License"); you may not use this file except in compliance
; with the License. You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns dda.pallet.dda-liferay-crate.domain.liferay-config
(:require
[schema.core :as s]
[dda.pallet.dda-liferay-crate.domain.schema :as schema]))
; ---------- auxiliary functions for creating infra configuration ------
(s/defn portal-ext-properties
"creates the default portal-ext.properties for MySQL or mariaDB."
[domain-config :- schema/LiferayDomainConfigResolved
db-name :- s/Str
liferay-version]
(let [{:keys [db-user-name db-user-passwd]} domain-config
db-type (case liferay-version
:LR7 "mariadb"
:LR6 "mysql")
db-driver (case liferay-version
:LR7 "org.mariadb.jdbc.Driver"
:LR6 "com.mysql.jdbc.Driver")]
["#"
"# Techbase"
"#"
"liferay.home=/var/lib/liferay"
"setup.wizard.enabled=true"
"index.on.startup=false"
"#"
"# MySQL"
"#"
(str "jdbc.default.driverClassName=" db-driver)
(str "jdbc.default.url=jdbc:" db-type "://localhost:3306/" db-name
"?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false")
(str "jdbc.default.username=" db-user-name)
(str "jdbc.default.password=" <PASSWORD>-user-passwd)
"#"
"# C3PO"
"#"
"#jdbc.default.acquireIncrement=2"
"#jdbc.default.idleConnectionTestPeriod=60"
"#jdbc.default.maxIdleTime=3600"
"#jdbc.default.maxPoolSize=100"
"#jdbc.default.minPoolSize=40"
""
"#"
"# Timeouts"
"#"
"com.liferay.util.Http.timeout=1000"
"session.timeout=120"
""]))
(s/defn default-release
"The default release configuration."
[portal-ext-lines liferay-version]
(merge {:name "LiferayCE"
:config portal-ext-lines}
(case liferay-version
:LR7 {:version [7 0 4]
:app ["ROOT" "https://netcologne.dl.sourceforge.net/project/lportal/Liferay%20Portal/7.0.4%20GA5/liferay-ce-portal-7.0-ga5-20171018150113838.war"]}
:LR6 {:version [6 2 1]
:app ["ROOT" "http://ufpr.dl.sourceforge.net/project/lportal/Liferay%20Portal/6.2.1%20GA2/liferay-portal-6.2-ce-ga2-20140319114139101.war"]})))
(s/defn default-release-config
"The default release configuration."
[domain-config :- schema/LiferayDomainConfigResolved
db-name :- s/Str
liferay-version]
(default-release (portal-ext-properties domain-config db-name liferay-version) liferay-version))
| true |
; Licensed to the Apache Software Foundation (ASF) under one
; or more contributor license agreements. See the NOTICE file
; distributed with this work for additional information
; regarding copyright ownership. The ASF licenses this file
; to you under the Apache License, Version 2.0 (the
; "License"); you may not use this file except in compliance
; with the License. You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns dda.pallet.dda-liferay-crate.domain.liferay-config
(:require
[schema.core :as s]
[dda.pallet.dda-liferay-crate.domain.schema :as schema]))
; ---------- auxiliary functions for creating infra configuration ------
(s/defn portal-ext-properties
"creates the default portal-ext.properties for MySQL or mariaDB."
[domain-config :- schema/LiferayDomainConfigResolved
db-name :- s/Str
liferay-version]
(let [{:keys [db-user-name db-user-passwd]} domain-config
db-type (case liferay-version
:LR7 "mariadb"
:LR6 "mysql")
db-driver (case liferay-version
:LR7 "org.mariadb.jdbc.Driver"
:LR6 "com.mysql.jdbc.Driver")]
["#"
"# Techbase"
"#"
"liferay.home=/var/lib/liferay"
"setup.wizard.enabled=true"
"index.on.startup=false"
"#"
"# MySQL"
"#"
(str "jdbc.default.driverClassName=" db-driver)
(str "jdbc.default.url=jdbc:" db-type "://localhost:3306/" db-name
"?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false")
(str "jdbc.default.username=" db-user-name)
(str "jdbc.default.password=" PI:PASSWORD:<PASSWORD>END_PI-user-passwd)
"#"
"# C3PO"
"#"
"#jdbc.default.acquireIncrement=2"
"#jdbc.default.idleConnectionTestPeriod=60"
"#jdbc.default.maxIdleTime=3600"
"#jdbc.default.maxPoolSize=100"
"#jdbc.default.minPoolSize=40"
""
"#"
"# Timeouts"
"#"
"com.liferay.util.Http.timeout=1000"
"session.timeout=120"
""]))
(s/defn default-release
"The default release configuration."
[portal-ext-lines liferay-version]
(merge {:name "LiferayCE"
:config portal-ext-lines}
(case liferay-version
:LR7 {:version [7 0 4]
:app ["ROOT" "https://netcologne.dl.sourceforge.net/project/lportal/Liferay%20Portal/7.0.4%20GA5/liferay-ce-portal-7.0-ga5-20171018150113838.war"]}
:LR6 {:version [6 2 1]
:app ["ROOT" "http://ufpr.dl.sourceforge.net/project/lportal/Liferay%20Portal/6.2.1%20GA2/liferay-portal-6.2-ce-ga2-20140319114139101.war"]})))
(s/defn default-release-config
"The default release configuration."
[domain-config :- schema/LiferayDomainConfigResolved
db-name :- s/Str
liferay-version]
(default-release (portal-ext-properties domain-config db-name liferay-version) liferay-version))
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright 2015 Xebia B.V.\n;\n; Licensed under the Apache License, Version 2",
"end": 107,
"score": 0.9980223774909973,
"start": 98,
"tag": "NAME",
"value": "Xebia B.V"
}
] |
src/main/clojure/com/xebia/visualreview/starter.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.starter
(:import [org.eclipse.jetty.server Server])
(:require [ring.middleware
[params :as params]
[keyword-params :refer [wrap-keyword-params]]
[multipart-params :refer [wrap-multipart-params]]]
[ring.adapter.jetty :refer [run-jetty]]
[clojure.tools.logging :as log]
[com.xebia.visualreview.routes :as routes]
[com.xebia.visualreview.middleware :as middleware]))
(defn create-app-handler []
(-> routes/main-router
wrap-keyword-params
wrap-multipart-params
params/wrap-params
middleware/wrap-exception
(middleware/http-logger)))
(defonce server (atom nil))
(defn stop-server []
(if-let [ws @server]
(do
(.stop ^Server ws)
(reset! server nil)
(log/info "VisualReview server stopped"))
(log/info "VisualReview server not running")))
(defn start-server [port]
(try
(reset! server (run-jetty (create-app-handler) {
:join? false
:port port
;:configurator config
}))
(log/info (str "VisualReview server started on port " port))
(catch Exception e (log/error (str "Could not start server on port " port ": " (.getMessage e))))))
|
46038
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 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.starter
(:import [org.eclipse.jetty.server Server])
(:require [ring.middleware
[params :as params]
[keyword-params :refer [wrap-keyword-params]]
[multipart-params :refer [wrap-multipart-params]]]
[ring.adapter.jetty :refer [run-jetty]]
[clojure.tools.logging :as log]
[com.xebia.visualreview.routes :as routes]
[com.xebia.visualreview.middleware :as middleware]))
(defn create-app-handler []
(-> routes/main-router
wrap-keyword-params
wrap-multipart-params
params/wrap-params
middleware/wrap-exception
(middleware/http-logger)))
(defonce server (atom nil))
(defn stop-server []
(if-let [ws @server]
(do
(.stop ^Server ws)
(reset! server nil)
(log/info "VisualReview server stopped"))
(log/info "VisualReview server not running")))
(defn start-server [port]
(try
(reset! server (run-jetty (create-app-handler) {
:join? false
:port port
;:configurator config
}))
(log/info (str "VisualReview server started on port " port))
(catch Exception e (log/error (str "Could not start server on port " port ": " (.getMessage e))))))
| 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.starter
(:import [org.eclipse.jetty.server Server])
(:require [ring.middleware
[params :as params]
[keyword-params :refer [wrap-keyword-params]]
[multipart-params :refer [wrap-multipart-params]]]
[ring.adapter.jetty :refer [run-jetty]]
[clojure.tools.logging :as log]
[com.xebia.visualreview.routes :as routes]
[com.xebia.visualreview.middleware :as middleware]))
(defn create-app-handler []
(-> routes/main-router
wrap-keyword-params
wrap-multipart-params
params/wrap-params
middleware/wrap-exception
(middleware/http-logger)))
(defonce server (atom nil))
(defn stop-server []
(if-let [ws @server]
(do
(.stop ^Server ws)
(reset! server nil)
(log/info "VisualReview server stopped"))
(log/info "VisualReview server not running")))
(defn start-server [port]
(try
(reset! server (run-jetty (create-app-handler) {
:join? false
:port port
;:configurator config
}))
(log/info (str "VisualReview server started on port " port))
(catch Exception e (log/error (str "Could not start server on port " port ": " (.getMessage e))))))
|
[
{
"context": "s]]))\n\n(def expired-activation-data\n {:password \"newpassword\"\n :password_verify \"newpassword\"\n :code \"8cd3",
"end": 274,
"score": 0.9995175004005432,
"start": 263,
"tag": "PASSWORD",
"value": "newpassword"
},
{
"context": "a\n {:password \"newpassword\"\n :password_verify \"newpassword\"\n :code \"8cd3a052-5575-42a3-ad6b-f4b57ee9ebb4\"\n",
"end": 308,
"score": 0.9995119571685791,
"start": 297,
"tag": "PASSWORD",
"value": "newpassword"
},
{
"context": "_id 2})\n\n(def valid-activation-data\n {:password \"testtest\"\n :password_verify \"testtest\"\n :code \"94c3643",
"end": 424,
"score": 0.9995097517967224,
"start": 416,
"tag": "PASSWORD",
"value": "testtest"
},
{
"context": "data\n {:password \"testtest\"\n :password_verify \"testtest\"\n :code \"94c36436-d2ce-4337-a05a-64a6b849f144\"\n",
"end": 455,
"score": 0.9995105266571045,
"start": 447,
"tag": "PASSWORD",
"value": "testtest"
},
{
"context": "]} (test-api-request :post \"/user/reset\" {:email \"[email protected]\"})]\n status => 200\n (",
"end": 1317,
"score": 0.9977164268493652,
"start": 1295,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "api-request :post \"/user/reset\" {:email \"[email protected]\"})]\n status => 200\n (",
"end": 1576,
"score": 0.999920666217804,
"start": 1559,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "]} (test-api-request :post \"/user/reset\" {:email \"[email protected]\"})]\n status => 200\n (",
"end": 1823,
"score": 0.9999024271965027,
"start": 1802,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
test_old/clj/salava/user/reset_password_test.clj
|
Vilikkki/salava
| 17 |
(ns salava.user.reset-password-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]))
(def expired-activation-data
{:password "newpassword"
:password_verify "newpassword"
:code "8cd3a052-5575-42a3-ad6b-f4b57ee9ebb4"
:user_id 2})
(def valid-activation-data
{:password "testtest"
:password_verify "testtest"
:code "94c36436-d2ce-4337-a05a-64a6b849f144"
:user_id 3})
(facts "about requesting new password"
(fact "email address must be valid"
(:status (test-api-request :post "/user/reset" {})) => 400
(:status (test-api-request :post "/user/reset" {:email nil})) => 400
(:status (test-api-request :post "/user/reset" {:email ""})) => 400
(:status (test-api-request :post "/user/reset" {:email "not-valid-email-address"})) => 400
(:status (test-api-request :post "/user/reset" {:email "not-valid-email-address@either"})) => 400
(:status (test-api-request :post "/user/reset" {:email (str (apply str (repeat 252 "a")) "@a.a")})) => 400)
(fact "user must exist"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "[email protected]"})]
status => 200
(:status body) => "error"))
(fact "email address must be user's primary email address"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "[email protected]"})]
status => 200
(:status body) => "error"))
(fact "email is sent to user, if address is correct"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "[email protected]"})]
status => 200
(:status body) => "success")))
(facts "about resetting the password"
(fact "user can not reset password if code is expired"
(let [{:keys [status body]} (test-api-request :post "/user/activate" expired-activation-data)]
status => 200
(:status body) => "error"))
(fact "user can reset password"
(let [{:keys [status body]} (test-api-request :post "/user/activate" valid-activation-data)]
status => 200
(:status body) => "success")))
(migrator/reset-seeds (migrator/test-config))
|
33922
|
(ns salava.user.reset-password-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]))
(def expired-activation-data
{:password "<PASSWORD>"
:password_verify "<PASSWORD>"
:code "8cd3a052-5575-42a3-ad6b-f4b57ee9ebb4"
:user_id 2})
(def valid-activation-data
{:password "<PASSWORD>"
:password_verify "<PASSWORD>"
:code "94c36436-d2ce-4337-a05a-64a6b849f144"
:user_id 3})
(facts "about requesting new password"
(fact "email address must be valid"
(:status (test-api-request :post "/user/reset" {})) => 400
(:status (test-api-request :post "/user/reset" {:email nil})) => 400
(:status (test-api-request :post "/user/reset" {:email ""})) => 400
(:status (test-api-request :post "/user/reset" {:email "not-valid-email-address"})) => 400
(:status (test-api-request :post "/user/reset" {:email "not-valid-email-address@either"})) => 400
(:status (test-api-request :post "/user/reset" {:email (str (apply str (repeat 252 "a")) "@a.a")})) => 400)
(fact "user must exist"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "<EMAIL>"})]
status => 200
(:status body) => "error"))
(fact "email address must be user's primary email address"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "secondary.<EMAIL>"})]
status => 200
(:status body) => "error"))
(fact "email is sent to user, if address is correct"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "<EMAIL>"})]
status => 200
(:status body) => "success")))
(facts "about resetting the password"
(fact "user can not reset password if code is expired"
(let [{:keys [status body]} (test-api-request :post "/user/activate" expired-activation-data)]
status => 200
(:status body) => "error"))
(fact "user can reset password"
(let [{:keys [status body]} (test-api-request :post "/user/activate" valid-activation-data)]
status => 200
(:status body) => "success")))
(migrator/reset-seeds (migrator/test-config))
| true |
(ns salava.user.reset-password-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request login! logout! test-user-credentials]]))
(def expired-activation-data
{:password "PI:PASSWORD:<PASSWORD>END_PI"
:password_verify "PI:PASSWORD:<PASSWORD>END_PI"
:code "8cd3a052-5575-42a3-ad6b-f4b57ee9ebb4"
:user_id 2})
(def valid-activation-data
{:password "PI:PASSWORD:<PASSWORD>END_PI"
:password_verify "PI:PASSWORD:<PASSWORD>END_PI"
:code "94c36436-d2ce-4337-a05a-64a6b849f144"
:user_id 3})
(facts "about requesting new password"
(fact "email address must be valid"
(:status (test-api-request :post "/user/reset" {})) => 400
(:status (test-api-request :post "/user/reset" {:email nil})) => 400
(:status (test-api-request :post "/user/reset" {:email ""})) => 400
(:status (test-api-request :post "/user/reset" {:email "not-valid-email-address"})) => 400
(:status (test-api-request :post "/user/reset" {:email "not-valid-email-address@either"})) => 400
(:status (test-api-request :post "/user/reset" {:email (str (apply str (repeat 252 "a")) "@a.a")})) => 400)
(fact "user must exist"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "PI:EMAIL:<EMAIL>END_PI"})]
status => 200
(:status body) => "error"))
(fact "email address must be user's primary email address"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "secondary.PI:EMAIL:<EMAIL>END_PI"})]
status => 200
(:status body) => "error"))
(fact "email is sent to user, if address is correct"
(let [{:keys [status body]} (test-api-request :post "/user/reset" {:email "PI:EMAIL:<EMAIL>END_PI"})]
status => 200
(:status body) => "success")))
(facts "about resetting the password"
(fact "user can not reset password if code is expired"
(let [{:keys [status body]} (test-api-request :post "/user/activate" expired-activation-data)]
status => 200
(:status body) => "error"))
(fact "user can reset password"
(let [{:keys [status body]} (test-api-request :post "/user/activate" valid-activation-data)]
status => 200
(:status body) => "success")))
(migrator/reset-seeds (migrator/test-config))
|
[
{
"context": "oth ways:\n \n ```\n (def db (atom { :users { \\\"Ivan\\\" { :age 30 }}}))\n \n (def ivan (rum/cursor db",
"end": 17284,
"score": 0.9996386766433716,
"start": 17280,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "0 }}}))\n \n (def ivan (rum/cursor db [:users \\\"Ivan\\\"]))\n (deref ivan) ;; => { :age 30 }\n \n (sw",
"end": 17349,
"score": 0.9989017844200134,
"start": 17345,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "; => { :age 31 }\n (deref db) ;; => { :users { \\\"Ivan\\\" { :age 31 }}}\n \n (swap! db update-in [:user",
"end": 17480,
"score": 0.9995821118354797,
"start": 17476,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :age 31 }}}\n \n (swap! db update-in [:users \\\"Ivan\\\" :age] inc)\n ;; => { :users { \\\"Ivan\\\" { :age ",
"end": 17538,
"score": 0.999667763710022,
"start": 17534,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "[:users \\\"Ivan\\\" :age] inc)\n ;; => { :users { \\\"Ivan\\\" { :age 32 }}}\n \n (deref ivan) ;; => { :age ",
"end": 17578,
"score": 0.9995348453521729,
"start": 17574,
"tag": "NAME",
"value": "Ivan"
}
] |
out/rum/core.cljs
|
jecneps/happy-trails
| 0 |
(ns rum.core
(:refer-clojure :exclude [ref deref])
(:require-macros rum.core)
(:require
[cljsjs.react]
[cljsjs.react.dom]
[goog.object :as gobj]
[goog.functions :as fns]
[sablono.core]
[rum.cursor :as cursor]
[rum.util :as util :refer [collect collect* call-all]]
[rum.derived-atom :as derived-atom]))
(defn state
"Given React component, returns Rum state associated with it."
[comp]
(gobj/get (.-state comp) ":rum/state"))
(defn- extend! [obj props]
(doseq [[k v] props
:when (some? v)]
(gobj/set obj (name k) (clj->js v))))
(defn- build-class [render mixins display-name]
(let [init (collect :init mixins) ;; state props -> state
will-mount (collect* [:will-mount ;; state -> state
:before-render] mixins) ;; state -> state
render render ;; state -> [dom state]
wrap-render (collect :wrap-render mixins) ;; render-fn -> render-fn
wrapped-render (reduce #(%2 %1) render wrap-render)
did-mount (collect* [:did-mount ;; state -> state
:after-render] mixins) ;; state -> state
did-remount (collect :did-remount mixins) ;; old-state state -> state
should-update (collect :should-update mixins) ;; old-state state -> boolean
will-update (collect* [:will-update ;; state -> state
:before-render] mixins) ;; state -> state
did-update (collect* [:did-update ;; state -> state
:after-render] mixins) ;; state -> state
did-catch (collect :did-catch mixins) ;; state error info -> state
will-unmount (collect :will-unmount mixins) ;; state -> state
child-context (collect :child-context mixins) ;; state -> child-context
class-props (reduce merge (collect :class-properties mixins)) ;; custom prototype properties and methods
static-props (reduce merge (collect :static-properties mixins)) ;; custom static properties and methods
ctor (fn [props]
(this-as this
(gobj/set this "state"
#js {":rum/state"
(-> (gobj/get props ":rum/initial-state")
(assoc :rum/react-component this)
(call-all init props)
volatile!)})
(.call js/React.Component this props)))
_ (goog/inherits ctor js/React.Component)
prototype (gobj/get ctor "prototype")]
(when-not (empty? will-mount)
(gobj/set prototype "componentWillMount"
(fn []
(this-as this
(vswap! (state this) call-all will-mount)))))
(when-not (empty? did-mount)
(gobj/set prototype "componentDidMount"
(fn []
(this-as this
(vswap! (state this) call-all did-mount)))))
(gobj/set prototype "componentWillReceiveProps"
(fn [next-props]
(this-as this
(let [old-state @(state this)
state (merge old-state
(gobj/get next-props ":rum/initial-state"))
next-state (reduce #(%2 old-state %1) state did-remount)]
;; allocate new volatile so that we can access both old and new states in shouldComponentUpdate
(.setState this #js {":rum/state" (volatile! next-state)})))))
(when-not (empty? should-update)
(gobj/set prototype "shouldComponentUpdate"
(fn [next-props next-state]
(this-as this
(let [old-state @(state this)
new-state @(gobj/get next-state ":rum/state")]
(or (some #(% old-state new-state) should-update) false))))))
(when-not (empty? will-update)
(gobj/set prototype "componentWillUpdate"
(fn [_ next-state]
(this-as this
(let [new-state (gobj/get next-state ":rum/state")]
(vswap! new-state call-all will-update))))))
(gobj/set prototype "render"
(fn []
(this-as this
(let [state (state this)
[dom next-state] (wrapped-render @state)]
(vreset! state next-state)
dom))))
(when-not (empty? did-update)
(gobj/set prototype "componentDidUpdate"
(fn [_ _]
(this-as this
(vswap! (state this) call-all did-update)))))
(when-not (empty? did-catch)
(gobj/set prototype "componentDidCatch"
(fn [error info]
(this-as this
(vswap! (state this) call-all did-catch error {:rum/component-stack (gobj/get info "componentStack")})
(.forceUpdate this)))))
(gobj/set prototype "componentWillUnmount"
(fn []
(this-as this
(when-not (empty? will-unmount)
(vswap! (state this) call-all will-unmount))
(gobj/set this ":rum/unmounted?" true))))
(when-not (empty? child-context)
(gobj/set prototype "getChildContext"
(fn []
(this-as this
(let [state @(state this)]
(clj->js (transduce (map #(% state)) merge {} child-context)))))))
(extend! prototype class-props)
(gobj/set ctor "displayName" display-name)
(extend! ctor static-props)
ctor))
(defn- set-meta! [c]
(let [f #(let [ctr (c)]
(.apply ctr ctr (js-arguments)))]
(specify! f IMeta (-meta [_] (meta (c))))
f))
(defn lazy-build
"Wraps component construction in a way so that Google Closure Compiler
can properly recognize and elide unused components. The extra `set-meta`
fn is needed so that the compiler can properly detect that all functions
are side effect free."
[ctor render mixins display-name]
(let [bf #(ctor render mixins display-name) ;; Avoid IIFE
c (fns/cacheReturnValue bf)]
(set-meta! c)))
(defn- build-ctor [render mixins display-name]
(let [class (build-class render mixins display-name)
key-fn (first (collect :key-fn mixins))
ctor (if (some? key-fn)
(fn [& args]
(let [props #js {":rum/initial-state" {:rum/args args}
"key" (apply key-fn args)}]
(js/React.createElement class props)))
(fn [& args]
(let [props #js {":rum/initial-state" {:rum/args args}}]
(js/React.createElement class props))))]
(with-meta ctor {:rum/class class})))
(declare static)
(defn- memo-compare-props [prev-props next-props]
(= (aget prev-props ":rum/args")
(aget next-props ":rum/args")))
(defn react-memo [f]
(if-some [memo (.-memo js/React)]
(memo f memo-compare-props)
f))
(defn ^:no-doc build-defc [render-body mixins display-name]
(cond
(= mixins [static])
(let [class (fn [props]
(apply render-body (aget props ":rum/args")))
_ (aset class "displayName" display-name)
memo-class (react-memo class)
ctor (fn [& args]
(.createElement js/React memo-class #js {":rum/args" args}))]
(with-meta ctor {:rum/class memo-class}))
(empty? mixins)
(let [class (fn [props]
(apply render-body (aget props ":rum/args")))
_ (aset class "displayName" display-name)
ctor (fn [& args]
(.createElement js/React class #js {":rum/args" args}))]
(with-meta ctor {:rum/class class}))
:else
(let [render (fn [state] [(apply render-body (:rum/args state)) state])]
(build-ctor render mixins display-name))))
(defn ^:no-doc build-defcs [render-body mixins display-name]
(let [render (fn [state] [(apply render-body state (:rum/args state)) state])]
(build-ctor render mixins display-name)))
(defn ^:no-doc build-defcc [render-body mixins display-name]
(let [render (fn [state] [(apply render-body (:rum/react-component state) (:rum/args state)) state])]
(build-ctor render mixins display-name)))
;; render queue
(def ^:private schedule
(or (and (exists? js/window)
(or js/window.requestAnimationFrame
js/window.webkitRequestAnimationFrame
js/window.mozRequestAnimationFrame
js/window.msRequestAnimationFrame))
#(js/setTimeout % 16)))
(def ^:private batch
(or (when (exists? js/ReactNative) js/ReactNative.unstable_batchedUpdates)
(when (exists? js/ReactDOM) js/ReactDOM.unstable_batchedUpdates)
(fn [f a] (f a))))
(def ^:private empty-queue [])
(def ^:private render-queue (volatile! empty-queue))
(defn- render-all [queue]
(doseq [comp queue
:when (and (some? comp) (not (gobj/get comp ":rum/unmounted?")))]
(.forceUpdate comp)))
(defn- render []
(let [queue @render-queue]
(vreset! render-queue empty-queue)
(batch render-all queue)))
(defn request-render
"Schedules react component to be rendered on next animation frame."
[component]
(when (empty? @render-queue)
(schedule render))
(vswap! render-queue conj component))
(defn mount
"Add element to the DOM tree. Idempotent. Subsequent mounts will just update element."
[element node]
(js/ReactDOM.render element node)
nil)
(defn unmount
"Removes component from the DOM tree."
[node]
(js/ReactDOM.unmountComponentAtNode node))
(defn hydrate
"Same as [[mount]] but must be called on DOM tree already rendered by a server via [[render-html]]."
[element node]
(js/ReactDOM.hydrate element node))
(defn portal
"Render `element` in a DOM `node` that is ouside of current DOM hierarchy."
[element node]
(js/ReactDOM.createPortal element node))
(defn create-context [default-value]
(.createContext js/React default-value))
;; initialization
(defn with-key
"Adds React key to element.
```
(rum/defc label [text] [:div text])
(-> (label)
(rum/with-key \"abc\")
(rum/mount js/document.body))
```"
[element key]
(js/React.cloneElement element #js {"key" key} nil))
(defn with-ref
"Adds React ref (string or callback) to element.
```
(rum/defc label [text] [:div text])
(-> (label)
(rum/with-ref \"abc\")
(rum/mount js/document.body))
```"
[element ref]
(js/React.cloneElement element #js {"ref" ref} nil))
(defn dom-node
"Usage of this function is discouraged. Use :ref callback instead.
Given state, returns top-level DOM node of component. Call it during lifecycle callbacks. Can’t be called during render."
[state]
(js/ReactDOM.findDOMNode (:rum/react-component state)))
(defn ref
"DEPRECATED: Use :ref (fn [dom-or-nil]) callback instead. See rum issue #124
Given state and ref handle, returns React component."
[state key]
(-> state :rum/react-component (aget "refs") (aget (name key))))
(defn ref-node
"DEPRECATED: Use :ref (fn [dom-or-nil]) callback instead. See rum issue #124
Given state and ref handle, returns DOM node associated with ref."
[state key]
(js/ReactDOM.findDOMNode (ref state (name key))))
;; static mixin
(def static
"Mixin. Will avoid re-render if none of component’s arguments have changed. Does equality check (`=`) on all arguments.
```
(rum/defc label < rum/static
[text]
[:div text])
(rum/mount (label \"abc\") js/document.body)
;; def != abc, will re-render
(rum/mount (label \"def\") js/document.body)
;; def == def, won’t re-render
(rum/mount (label \"def\") js/document.body)
```"
{:should-update
(fn [old-state new-state]
(not= (:rum/args old-state) (:rum/args new-state)))})
;; local mixin
(defn local
"Mixin constructor. Adds an atom to component’s state that can be used to keep stuff during component’s lifecycle. Component will be re-rendered if atom’s value changes. Atom is stored under user-provided key or under `:rum/local` by default.
```
(rum/defcs counter < (rum/local 0 :cnt)
[state label]
(let [*cnt (:cnt state)]
[:div {:on-click (fn [_] (swap! *cnt inc))}
label @*cnt]))
(rum/mount (counter \"Click count: \"))
```"
([initial] (local initial :rum/local))
([initial key]
{:will-mount
(fn [state]
(let [local-state (atom initial)
component (:rum/react-component state)]
(add-watch local-state key
(fn [_ _ _ _]
(request-render component)))
(assoc state key local-state)))}))
;; reactive mixin
(def ^:private ^:dynamic *reactions*)
(def reactive
"Mixin. Works in conjunction with [[react]].
```
(rum/defc comp < rum/reactive
[*counter]
[:div (rum/react counter)])
(def *counter (atom 0))
(rum/mount (comp *counter) js/document.body)
(swap! *counter inc) ;; will force comp to re-render
```"
{:init
(fn [state props]
(assoc state :rum.reactive/key (random-uuid)))
:wrap-render
(fn [render-fn]
(fn [state]
(binding [*reactions* (volatile! #{})]
(let [comp (:rum/react-component state)
old-reactions (:rum.reactive/refs state #{})
[dom next-state] (render-fn state)
new-reactions @*reactions*
key (:rum.reactive/key state)]
(doseq [ref old-reactions]
(when-not (contains? new-reactions ref)
(remove-watch ref key)))
(doseq [ref new-reactions]
(when-not (contains? old-reactions ref)
(add-watch ref key
(fn [_ _ _ _]
(request-render comp)))))
[dom (assoc next-state :rum.reactive/refs new-reactions)]))))
:will-unmount
(fn [state]
(let [key (:rum.reactive/key state)]
(doseq [ref (:rum.reactive/refs state)]
(remove-watch ref key)))
(dissoc state :rum.reactive/refs :rum.reactive/key))})
(defn react
"Works in conjunction with [[reactive]] mixin. Use this function instead of `deref` inside render, and your component will subscribe to changes happening to the derefed atom."
[ref]
(assert *reactions* "rum.core/react is only supported in conjunction with rum.core/reactive")
(vswap! *reactions* conj ref)
@ref)
;; derived-atom
(def ^{:style/indent 2
:arglists '([refs key f] [refs key f opts])
:doc "Use this to create “chains” and acyclic graphs of dependent atoms.
[[derived-atom]] will:
- Take N “source” refs.
- Set up a watch on each of them.
- Create “sink” atom.
- When any of source refs changes:
- re-run function `f`, passing N dereferenced values of source refs.
- `reset!` result of `f` to the sink atom.
- Return sink atom.
Example:
```
(def *a (atom 0))
(def *b (atom 1))
(def *x (derived-atom [*a *b] ::key
(fn [a b]
(str a \":\" b))))
(type *x) ;; => clojure.lang.Atom
(deref *x) ;; => \"0:1\"
(swap! *a inc)
(deref *x) ;; => \"1:1\"
(reset! *b 7)
(deref *x) ;; => \"1:7\"
```
Arguments:
- `refs` - sequence of source refs,
- `key` - unique key to register watcher, same as in `clojure.core/add-watch`,
- `f` - function that must accept N arguments (same as number of source refs) and return a value to be written to the sink ref. Note: `f` will be called with already dereferenced values,
- `opts` - optional. Map of:
- `:ref` - use this as sink ref. By default creates new atom,
- `:check-equals?` - Defaults to `true`. If equality check should be run on each source update: `(= @sink (f new-vals))`. When result of recalculating `f` equals to the old value, `reset!` won’t be called. Set to `false` if checking for equality can be expensive."}
derived-atom derived-atom/derived-atom)
;; cursors
(defn cursor-in
"Given atom with deep nested value and path inside it, creates an atom-like structure
that can be used separately from main atom, but will sync changes both ways:
```
(def db (atom { :users { \"Ivan\" { :age 30 }}}))
(def ivan (rum/cursor db [:users \"Ivan\"]))
(deref ivan) ;; => { :age 30 }
(swap! ivan update :age inc) ;; => { :age 31 }
(deref db) ;; => { :users { \"Ivan\" { :age 31 }}}
(swap! db update-in [:users \"Ivan\" :age] inc)
;; => { :users { \"Ivan\" { :age 32 }}}
(deref ivan) ;; => { :age 32 }
```
Returned value supports `deref`, `swap!`, `reset!`, watches and metadata.
The only supported option is `:meta`"
[ref path & {:as options}]
(if (instance? cursor/Cursor ref)
(cursor/Cursor. (.-ref ref) (into (.-path ref) path) (:meta options))
(cursor/Cursor. ref path (:meta options))))
(defn cursor
"Same as [[cursor-in]] but accepts single key instead of path vector."
[ref key & options]
(apply cursor-in ref [key] options))
;; hooks
(defn ^array use-state
"Takes initial value or value returning fn and returns a tuple of [value set-value!],
where `value` is current state value and `set-value!` is a function that schedules re-render.
(let [[value set-state!] (rum/use-state 0)]
[:button {:on-click #(set-state! (inc value))}
value])"
[value-or-fn]
(.useState js/React value-or-fn))
(defn ^array use-reducer
"Takes reducing function and initial state value.
Returns a tuple of [value dispatch!], where `value` is current state value and `dispatch` is a function that schedules re-render.
(defmulti value-reducer (fn [event value] event))
(defmethod value-reducer :inc [_ value]
(inc value))
(let [[value dispatch!] (rum/use-reducer value-reducer 0)]
[:button {:on-click #(dispatch! :inc)}
value])
Read more at https://reactjs.org/docs/hooks-reference.html#usereducer"
([reducer-fn initial-value]
(.useReducer js/React #(reducer-fn %2 %1) initial-value identity)))
(defn use-effect!
"Takes setup-fn that executes either on the first render or after every update.
The function may return cleanup-fn to cleanup the effect, either before unmount or before every next update.
Calling behavior is controlled by deps argument.
(rum/use-effect!
(fn []
(.addEventListener js/window \"load\" handler)
#(.removeEventListener js/window \"load\" handler))
[]) ;; empty deps collection instructs React to run setup-fn only once on initial render
;; and cleanup-fn only once before unmounting
Read more at https://reactjs.org/docs/hooks-effect.html"
([setup-fn]
(.useEffect js/React #(or (setup-fn) js/undefined)))
([setup-fn deps]
(->> (if (array? deps) deps (into-array deps))
(.useEffect js/React #(or (setup-fn) js/undefined)))))
(defn use-callback
"Takes callback function and returns memoized variant, memoization is done based on provided deps collection.
(rum/defc button < rum/static
[{:keys [on-click]} text]
[:button {:on-click on-click}
text])
(rum/defc app [v]
(let [on-click (rum/use-callback #(do-stuff v) [v])]
;; because on-click callback is memoized here based on v argument
;; the callback won't be re-created on every render, unless v changes
;; which means that underlying `button` component won't re-render wastefully
[button {:on-click on-click}
\"press me\"]))
Read more at https://reactjs.org/docs/hooks-reference.html#usecallback"
([callback]
(.useCallback js/React callback))
([callback deps]
(->> (if (array? deps) deps (into-array deps))
(.useCallback js/React callback))))
(defn use-memo
"Takes a function, memoizes it based on provided deps collection and executes immediately returning a result.
Read more at https://reactjs.org/docs/hooks-reference.html#usememo"
([f]
(.useMemo js/React f))
([f deps]
(->> (if (array? deps) deps (into-array deps))
(.useMemo js/React f))))
(defn use-ref
"Takes a value and puts it into a mutable container which is persisted for the full lifetime of the component.
https://reactjs.org/docs/hooks-reference.html#useref"
([initial-value]
(.useRef js/React initial-value)))
;; Refs
(defn create-ref []
(.createRef js/React))
(defn deref
"Takes a ref returned from use-ref and returns its current value."
[^js ref]
(.-current ref))
(defn set-ref! [^js ref value]
(set! (.-current ref) value))
;;; Server-side rendering
;; Roman. For Node.js runtime we require "react-dom/server" for you
;; In the browser you have to add cljsjs/react-dom-server yourself
(defn render-html
"Main server-side rendering method. Given component, returns HTML string with static markup of that component.
Serve that string to the browser and [[hydrate]] same Rum component over it. React will be able to reuse already existing DOM and will initialize much faster.
No opts are supported at the moment."
([element]
(render-html element nil))
([element opts]
(if-not (identical? *target* "nodejs")
(.renderToString js/ReactDOMServer element)
(let [react-dom-server (js/require "react-dom/server")]
(.renderToString react-dom-server element)))))
(defn render-static-markup
"Same as [[render-html]] but returned string has nothing React-specific.
This allows Rum to be used as traditional server-side templating engine."
[src]
(if-not (identical? *target* "nodejs")
(.renderToStaticMarkup js/ReactDOMServer src)
(let [react-dom-server (js/require "react-dom/server")]
(.renderToStaticMarkup react-dom-server src))))
;; JS components adapter
(defn adapt-class-helper [type attrs children]
(let [args (.concat #js [type attrs] children)]
(.apply (.-createElement js/React) js/React args)))
|
50866
|
(ns rum.core
(:refer-clojure :exclude [ref deref])
(:require-macros rum.core)
(:require
[cljsjs.react]
[cljsjs.react.dom]
[goog.object :as gobj]
[goog.functions :as fns]
[sablono.core]
[rum.cursor :as cursor]
[rum.util :as util :refer [collect collect* call-all]]
[rum.derived-atom :as derived-atom]))
(defn state
"Given React component, returns Rum state associated with it."
[comp]
(gobj/get (.-state comp) ":rum/state"))
(defn- extend! [obj props]
(doseq [[k v] props
:when (some? v)]
(gobj/set obj (name k) (clj->js v))))
(defn- build-class [render mixins display-name]
(let [init (collect :init mixins) ;; state props -> state
will-mount (collect* [:will-mount ;; state -> state
:before-render] mixins) ;; state -> state
render render ;; state -> [dom state]
wrap-render (collect :wrap-render mixins) ;; render-fn -> render-fn
wrapped-render (reduce #(%2 %1) render wrap-render)
did-mount (collect* [:did-mount ;; state -> state
:after-render] mixins) ;; state -> state
did-remount (collect :did-remount mixins) ;; old-state state -> state
should-update (collect :should-update mixins) ;; old-state state -> boolean
will-update (collect* [:will-update ;; state -> state
:before-render] mixins) ;; state -> state
did-update (collect* [:did-update ;; state -> state
:after-render] mixins) ;; state -> state
did-catch (collect :did-catch mixins) ;; state error info -> state
will-unmount (collect :will-unmount mixins) ;; state -> state
child-context (collect :child-context mixins) ;; state -> child-context
class-props (reduce merge (collect :class-properties mixins)) ;; custom prototype properties and methods
static-props (reduce merge (collect :static-properties mixins)) ;; custom static properties and methods
ctor (fn [props]
(this-as this
(gobj/set this "state"
#js {":rum/state"
(-> (gobj/get props ":rum/initial-state")
(assoc :rum/react-component this)
(call-all init props)
volatile!)})
(.call js/React.Component this props)))
_ (goog/inherits ctor js/React.Component)
prototype (gobj/get ctor "prototype")]
(when-not (empty? will-mount)
(gobj/set prototype "componentWillMount"
(fn []
(this-as this
(vswap! (state this) call-all will-mount)))))
(when-not (empty? did-mount)
(gobj/set prototype "componentDidMount"
(fn []
(this-as this
(vswap! (state this) call-all did-mount)))))
(gobj/set prototype "componentWillReceiveProps"
(fn [next-props]
(this-as this
(let [old-state @(state this)
state (merge old-state
(gobj/get next-props ":rum/initial-state"))
next-state (reduce #(%2 old-state %1) state did-remount)]
;; allocate new volatile so that we can access both old and new states in shouldComponentUpdate
(.setState this #js {":rum/state" (volatile! next-state)})))))
(when-not (empty? should-update)
(gobj/set prototype "shouldComponentUpdate"
(fn [next-props next-state]
(this-as this
(let [old-state @(state this)
new-state @(gobj/get next-state ":rum/state")]
(or (some #(% old-state new-state) should-update) false))))))
(when-not (empty? will-update)
(gobj/set prototype "componentWillUpdate"
(fn [_ next-state]
(this-as this
(let [new-state (gobj/get next-state ":rum/state")]
(vswap! new-state call-all will-update))))))
(gobj/set prototype "render"
(fn []
(this-as this
(let [state (state this)
[dom next-state] (wrapped-render @state)]
(vreset! state next-state)
dom))))
(when-not (empty? did-update)
(gobj/set prototype "componentDidUpdate"
(fn [_ _]
(this-as this
(vswap! (state this) call-all did-update)))))
(when-not (empty? did-catch)
(gobj/set prototype "componentDidCatch"
(fn [error info]
(this-as this
(vswap! (state this) call-all did-catch error {:rum/component-stack (gobj/get info "componentStack")})
(.forceUpdate this)))))
(gobj/set prototype "componentWillUnmount"
(fn []
(this-as this
(when-not (empty? will-unmount)
(vswap! (state this) call-all will-unmount))
(gobj/set this ":rum/unmounted?" true))))
(when-not (empty? child-context)
(gobj/set prototype "getChildContext"
(fn []
(this-as this
(let [state @(state this)]
(clj->js (transduce (map #(% state)) merge {} child-context)))))))
(extend! prototype class-props)
(gobj/set ctor "displayName" display-name)
(extend! ctor static-props)
ctor))
(defn- set-meta! [c]
(let [f #(let [ctr (c)]
(.apply ctr ctr (js-arguments)))]
(specify! f IMeta (-meta [_] (meta (c))))
f))
(defn lazy-build
"Wraps component construction in a way so that Google Closure Compiler
can properly recognize and elide unused components. The extra `set-meta`
fn is needed so that the compiler can properly detect that all functions
are side effect free."
[ctor render mixins display-name]
(let [bf #(ctor render mixins display-name) ;; Avoid IIFE
c (fns/cacheReturnValue bf)]
(set-meta! c)))
(defn- build-ctor [render mixins display-name]
(let [class (build-class render mixins display-name)
key-fn (first (collect :key-fn mixins))
ctor (if (some? key-fn)
(fn [& args]
(let [props #js {":rum/initial-state" {:rum/args args}
"key" (apply key-fn args)}]
(js/React.createElement class props)))
(fn [& args]
(let [props #js {":rum/initial-state" {:rum/args args}}]
(js/React.createElement class props))))]
(with-meta ctor {:rum/class class})))
(declare static)
(defn- memo-compare-props [prev-props next-props]
(= (aget prev-props ":rum/args")
(aget next-props ":rum/args")))
(defn react-memo [f]
(if-some [memo (.-memo js/React)]
(memo f memo-compare-props)
f))
(defn ^:no-doc build-defc [render-body mixins display-name]
(cond
(= mixins [static])
(let [class (fn [props]
(apply render-body (aget props ":rum/args")))
_ (aset class "displayName" display-name)
memo-class (react-memo class)
ctor (fn [& args]
(.createElement js/React memo-class #js {":rum/args" args}))]
(with-meta ctor {:rum/class memo-class}))
(empty? mixins)
(let [class (fn [props]
(apply render-body (aget props ":rum/args")))
_ (aset class "displayName" display-name)
ctor (fn [& args]
(.createElement js/React class #js {":rum/args" args}))]
(with-meta ctor {:rum/class class}))
:else
(let [render (fn [state] [(apply render-body (:rum/args state)) state])]
(build-ctor render mixins display-name))))
(defn ^:no-doc build-defcs [render-body mixins display-name]
(let [render (fn [state] [(apply render-body state (:rum/args state)) state])]
(build-ctor render mixins display-name)))
(defn ^:no-doc build-defcc [render-body mixins display-name]
(let [render (fn [state] [(apply render-body (:rum/react-component state) (:rum/args state)) state])]
(build-ctor render mixins display-name)))
;; render queue
(def ^:private schedule
(or (and (exists? js/window)
(or js/window.requestAnimationFrame
js/window.webkitRequestAnimationFrame
js/window.mozRequestAnimationFrame
js/window.msRequestAnimationFrame))
#(js/setTimeout % 16)))
(def ^:private batch
(or (when (exists? js/ReactNative) js/ReactNative.unstable_batchedUpdates)
(when (exists? js/ReactDOM) js/ReactDOM.unstable_batchedUpdates)
(fn [f a] (f a))))
(def ^:private empty-queue [])
(def ^:private render-queue (volatile! empty-queue))
(defn- render-all [queue]
(doseq [comp queue
:when (and (some? comp) (not (gobj/get comp ":rum/unmounted?")))]
(.forceUpdate comp)))
(defn- render []
(let [queue @render-queue]
(vreset! render-queue empty-queue)
(batch render-all queue)))
(defn request-render
"Schedules react component to be rendered on next animation frame."
[component]
(when (empty? @render-queue)
(schedule render))
(vswap! render-queue conj component))
(defn mount
"Add element to the DOM tree. Idempotent. Subsequent mounts will just update element."
[element node]
(js/ReactDOM.render element node)
nil)
(defn unmount
"Removes component from the DOM tree."
[node]
(js/ReactDOM.unmountComponentAtNode node))
(defn hydrate
"Same as [[mount]] but must be called on DOM tree already rendered by a server via [[render-html]]."
[element node]
(js/ReactDOM.hydrate element node))
(defn portal
"Render `element` in a DOM `node` that is ouside of current DOM hierarchy."
[element node]
(js/ReactDOM.createPortal element node))
(defn create-context [default-value]
(.createContext js/React default-value))
;; initialization
(defn with-key
"Adds React key to element.
```
(rum/defc label [text] [:div text])
(-> (label)
(rum/with-key \"abc\")
(rum/mount js/document.body))
```"
[element key]
(js/React.cloneElement element #js {"key" key} nil))
(defn with-ref
"Adds React ref (string or callback) to element.
```
(rum/defc label [text] [:div text])
(-> (label)
(rum/with-ref \"abc\")
(rum/mount js/document.body))
```"
[element ref]
(js/React.cloneElement element #js {"ref" ref} nil))
(defn dom-node
"Usage of this function is discouraged. Use :ref callback instead.
Given state, returns top-level DOM node of component. Call it during lifecycle callbacks. Can’t be called during render."
[state]
(js/ReactDOM.findDOMNode (:rum/react-component state)))
(defn ref
"DEPRECATED: Use :ref (fn [dom-or-nil]) callback instead. See rum issue #124
Given state and ref handle, returns React component."
[state key]
(-> state :rum/react-component (aget "refs") (aget (name key))))
(defn ref-node
"DEPRECATED: Use :ref (fn [dom-or-nil]) callback instead. See rum issue #124
Given state and ref handle, returns DOM node associated with ref."
[state key]
(js/ReactDOM.findDOMNode (ref state (name key))))
;; static mixin
(def static
"Mixin. Will avoid re-render if none of component’s arguments have changed. Does equality check (`=`) on all arguments.
```
(rum/defc label < rum/static
[text]
[:div text])
(rum/mount (label \"abc\") js/document.body)
;; def != abc, will re-render
(rum/mount (label \"def\") js/document.body)
;; def == def, won’t re-render
(rum/mount (label \"def\") js/document.body)
```"
{:should-update
(fn [old-state new-state]
(not= (:rum/args old-state) (:rum/args new-state)))})
;; local mixin
(defn local
"Mixin constructor. Adds an atom to component’s state that can be used to keep stuff during component’s lifecycle. Component will be re-rendered if atom’s value changes. Atom is stored under user-provided key or under `:rum/local` by default.
```
(rum/defcs counter < (rum/local 0 :cnt)
[state label]
(let [*cnt (:cnt state)]
[:div {:on-click (fn [_] (swap! *cnt inc))}
label @*cnt]))
(rum/mount (counter \"Click count: \"))
```"
([initial] (local initial :rum/local))
([initial key]
{:will-mount
(fn [state]
(let [local-state (atom initial)
component (:rum/react-component state)]
(add-watch local-state key
(fn [_ _ _ _]
(request-render component)))
(assoc state key local-state)))}))
;; reactive mixin
(def ^:private ^:dynamic *reactions*)
(def reactive
"Mixin. Works in conjunction with [[react]].
```
(rum/defc comp < rum/reactive
[*counter]
[:div (rum/react counter)])
(def *counter (atom 0))
(rum/mount (comp *counter) js/document.body)
(swap! *counter inc) ;; will force comp to re-render
```"
{:init
(fn [state props]
(assoc state :rum.reactive/key (random-uuid)))
:wrap-render
(fn [render-fn]
(fn [state]
(binding [*reactions* (volatile! #{})]
(let [comp (:rum/react-component state)
old-reactions (:rum.reactive/refs state #{})
[dom next-state] (render-fn state)
new-reactions @*reactions*
key (:rum.reactive/key state)]
(doseq [ref old-reactions]
(when-not (contains? new-reactions ref)
(remove-watch ref key)))
(doseq [ref new-reactions]
(when-not (contains? old-reactions ref)
(add-watch ref key
(fn [_ _ _ _]
(request-render comp)))))
[dom (assoc next-state :rum.reactive/refs new-reactions)]))))
:will-unmount
(fn [state]
(let [key (:rum.reactive/key state)]
(doseq [ref (:rum.reactive/refs state)]
(remove-watch ref key)))
(dissoc state :rum.reactive/refs :rum.reactive/key))})
(defn react
"Works in conjunction with [[reactive]] mixin. Use this function instead of `deref` inside render, and your component will subscribe to changes happening to the derefed atom."
[ref]
(assert *reactions* "rum.core/react is only supported in conjunction with rum.core/reactive")
(vswap! *reactions* conj ref)
@ref)
;; derived-atom
(def ^{:style/indent 2
:arglists '([refs key f] [refs key f opts])
:doc "Use this to create “chains” and acyclic graphs of dependent atoms.
[[derived-atom]] will:
- Take N “source” refs.
- Set up a watch on each of them.
- Create “sink” atom.
- When any of source refs changes:
- re-run function `f`, passing N dereferenced values of source refs.
- `reset!` result of `f` to the sink atom.
- Return sink atom.
Example:
```
(def *a (atom 0))
(def *b (atom 1))
(def *x (derived-atom [*a *b] ::key
(fn [a b]
(str a \":\" b))))
(type *x) ;; => clojure.lang.Atom
(deref *x) ;; => \"0:1\"
(swap! *a inc)
(deref *x) ;; => \"1:1\"
(reset! *b 7)
(deref *x) ;; => \"1:7\"
```
Arguments:
- `refs` - sequence of source refs,
- `key` - unique key to register watcher, same as in `clojure.core/add-watch`,
- `f` - function that must accept N arguments (same as number of source refs) and return a value to be written to the sink ref. Note: `f` will be called with already dereferenced values,
- `opts` - optional. Map of:
- `:ref` - use this as sink ref. By default creates new atom,
- `:check-equals?` - Defaults to `true`. If equality check should be run on each source update: `(= @sink (f new-vals))`. When result of recalculating `f` equals to the old value, `reset!` won’t be called. Set to `false` if checking for equality can be expensive."}
derived-atom derived-atom/derived-atom)
;; cursors
(defn cursor-in
"Given atom with deep nested value and path inside it, creates an atom-like structure
that can be used separately from main atom, but will sync changes both ways:
```
(def db (atom { :users { \"<NAME>\" { :age 30 }}}))
(def ivan (rum/cursor db [:users \"<NAME>\"]))
(deref ivan) ;; => { :age 30 }
(swap! ivan update :age inc) ;; => { :age 31 }
(deref db) ;; => { :users { \"<NAME>\" { :age 31 }}}
(swap! db update-in [:users \"<NAME>\" :age] inc)
;; => { :users { \"<NAME>\" { :age 32 }}}
(deref ivan) ;; => { :age 32 }
```
Returned value supports `deref`, `swap!`, `reset!`, watches and metadata.
The only supported option is `:meta`"
[ref path & {:as options}]
(if (instance? cursor/Cursor ref)
(cursor/Cursor. (.-ref ref) (into (.-path ref) path) (:meta options))
(cursor/Cursor. ref path (:meta options))))
(defn cursor
"Same as [[cursor-in]] but accepts single key instead of path vector."
[ref key & options]
(apply cursor-in ref [key] options))
;; hooks
(defn ^array use-state
"Takes initial value or value returning fn and returns a tuple of [value set-value!],
where `value` is current state value and `set-value!` is a function that schedules re-render.
(let [[value set-state!] (rum/use-state 0)]
[:button {:on-click #(set-state! (inc value))}
value])"
[value-or-fn]
(.useState js/React value-or-fn))
(defn ^array use-reducer
"Takes reducing function and initial state value.
Returns a tuple of [value dispatch!], where `value` is current state value and `dispatch` is a function that schedules re-render.
(defmulti value-reducer (fn [event value] event))
(defmethod value-reducer :inc [_ value]
(inc value))
(let [[value dispatch!] (rum/use-reducer value-reducer 0)]
[:button {:on-click #(dispatch! :inc)}
value])
Read more at https://reactjs.org/docs/hooks-reference.html#usereducer"
([reducer-fn initial-value]
(.useReducer js/React #(reducer-fn %2 %1) initial-value identity)))
(defn use-effect!
"Takes setup-fn that executes either on the first render or after every update.
The function may return cleanup-fn to cleanup the effect, either before unmount or before every next update.
Calling behavior is controlled by deps argument.
(rum/use-effect!
(fn []
(.addEventListener js/window \"load\" handler)
#(.removeEventListener js/window \"load\" handler))
[]) ;; empty deps collection instructs React to run setup-fn only once on initial render
;; and cleanup-fn only once before unmounting
Read more at https://reactjs.org/docs/hooks-effect.html"
([setup-fn]
(.useEffect js/React #(or (setup-fn) js/undefined)))
([setup-fn deps]
(->> (if (array? deps) deps (into-array deps))
(.useEffect js/React #(or (setup-fn) js/undefined)))))
(defn use-callback
"Takes callback function and returns memoized variant, memoization is done based on provided deps collection.
(rum/defc button < rum/static
[{:keys [on-click]} text]
[:button {:on-click on-click}
text])
(rum/defc app [v]
(let [on-click (rum/use-callback #(do-stuff v) [v])]
;; because on-click callback is memoized here based on v argument
;; the callback won't be re-created on every render, unless v changes
;; which means that underlying `button` component won't re-render wastefully
[button {:on-click on-click}
\"press me\"]))
Read more at https://reactjs.org/docs/hooks-reference.html#usecallback"
([callback]
(.useCallback js/React callback))
([callback deps]
(->> (if (array? deps) deps (into-array deps))
(.useCallback js/React callback))))
(defn use-memo
"Takes a function, memoizes it based on provided deps collection and executes immediately returning a result.
Read more at https://reactjs.org/docs/hooks-reference.html#usememo"
([f]
(.useMemo js/React f))
([f deps]
(->> (if (array? deps) deps (into-array deps))
(.useMemo js/React f))))
(defn use-ref
"Takes a value and puts it into a mutable container which is persisted for the full lifetime of the component.
https://reactjs.org/docs/hooks-reference.html#useref"
([initial-value]
(.useRef js/React initial-value)))
;; Refs
(defn create-ref []
(.createRef js/React))
(defn deref
"Takes a ref returned from use-ref and returns its current value."
[^js ref]
(.-current ref))
(defn set-ref! [^js ref value]
(set! (.-current ref) value))
;;; Server-side rendering
;; Roman. For Node.js runtime we require "react-dom/server" for you
;; In the browser you have to add cljsjs/react-dom-server yourself
(defn render-html
"Main server-side rendering method. Given component, returns HTML string with static markup of that component.
Serve that string to the browser and [[hydrate]] same Rum component over it. React will be able to reuse already existing DOM and will initialize much faster.
No opts are supported at the moment."
([element]
(render-html element nil))
([element opts]
(if-not (identical? *target* "nodejs")
(.renderToString js/ReactDOMServer element)
(let [react-dom-server (js/require "react-dom/server")]
(.renderToString react-dom-server element)))))
(defn render-static-markup
"Same as [[render-html]] but returned string has nothing React-specific.
This allows Rum to be used as traditional server-side templating engine."
[src]
(if-not (identical? *target* "nodejs")
(.renderToStaticMarkup js/ReactDOMServer src)
(let [react-dom-server (js/require "react-dom/server")]
(.renderToStaticMarkup react-dom-server src))))
;; JS components adapter
(defn adapt-class-helper [type attrs children]
(let [args (.concat #js [type attrs] children)]
(.apply (.-createElement js/React) js/React args)))
| true |
(ns rum.core
(:refer-clojure :exclude [ref deref])
(:require-macros rum.core)
(:require
[cljsjs.react]
[cljsjs.react.dom]
[goog.object :as gobj]
[goog.functions :as fns]
[sablono.core]
[rum.cursor :as cursor]
[rum.util :as util :refer [collect collect* call-all]]
[rum.derived-atom :as derived-atom]))
(defn state
"Given React component, returns Rum state associated with it."
[comp]
(gobj/get (.-state comp) ":rum/state"))
(defn- extend! [obj props]
(doseq [[k v] props
:when (some? v)]
(gobj/set obj (name k) (clj->js v))))
(defn- build-class [render mixins display-name]
(let [init (collect :init mixins) ;; state props -> state
will-mount (collect* [:will-mount ;; state -> state
:before-render] mixins) ;; state -> state
render render ;; state -> [dom state]
wrap-render (collect :wrap-render mixins) ;; render-fn -> render-fn
wrapped-render (reduce #(%2 %1) render wrap-render)
did-mount (collect* [:did-mount ;; state -> state
:after-render] mixins) ;; state -> state
did-remount (collect :did-remount mixins) ;; old-state state -> state
should-update (collect :should-update mixins) ;; old-state state -> boolean
will-update (collect* [:will-update ;; state -> state
:before-render] mixins) ;; state -> state
did-update (collect* [:did-update ;; state -> state
:after-render] mixins) ;; state -> state
did-catch (collect :did-catch mixins) ;; state error info -> state
will-unmount (collect :will-unmount mixins) ;; state -> state
child-context (collect :child-context mixins) ;; state -> child-context
class-props (reduce merge (collect :class-properties mixins)) ;; custom prototype properties and methods
static-props (reduce merge (collect :static-properties mixins)) ;; custom static properties and methods
ctor (fn [props]
(this-as this
(gobj/set this "state"
#js {":rum/state"
(-> (gobj/get props ":rum/initial-state")
(assoc :rum/react-component this)
(call-all init props)
volatile!)})
(.call js/React.Component this props)))
_ (goog/inherits ctor js/React.Component)
prototype (gobj/get ctor "prototype")]
(when-not (empty? will-mount)
(gobj/set prototype "componentWillMount"
(fn []
(this-as this
(vswap! (state this) call-all will-mount)))))
(when-not (empty? did-mount)
(gobj/set prototype "componentDidMount"
(fn []
(this-as this
(vswap! (state this) call-all did-mount)))))
(gobj/set prototype "componentWillReceiveProps"
(fn [next-props]
(this-as this
(let [old-state @(state this)
state (merge old-state
(gobj/get next-props ":rum/initial-state"))
next-state (reduce #(%2 old-state %1) state did-remount)]
;; allocate new volatile so that we can access both old and new states in shouldComponentUpdate
(.setState this #js {":rum/state" (volatile! next-state)})))))
(when-not (empty? should-update)
(gobj/set prototype "shouldComponentUpdate"
(fn [next-props next-state]
(this-as this
(let [old-state @(state this)
new-state @(gobj/get next-state ":rum/state")]
(or (some #(% old-state new-state) should-update) false))))))
(when-not (empty? will-update)
(gobj/set prototype "componentWillUpdate"
(fn [_ next-state]
(this-as this
(let [new-state (gobj/get next-state ":rum/state")]
(vswap! new-state call-all will-update))))))
(gobj/set prototype "render"
(fn []
(this-as this
(let [state (state this)
[dom next-state] (wrapped-render @state)]
(vreset! state next-state)
dom))))
(when-not (empty? did-update)
(gobj/set prototype "componentDidUpdate"
(fn [_ _]
(this-as this
(vswap! (state this) call-all did-update)))))
(when-not (empty? did-catch)
(gobj/set prototype "componentDidCatch"
(fn [error info]
(this-as this
(vswap! (state this) call-all did-catch error {:rum/component-stack (gobj/get info "componentStack")})
(.forceUpdate this)))))
(gobj/set prototype "componentWillUnmount"
(fn []
(this-as this
(when-not (empty? will-unmount)
(vswap! (state this) call-all will-unmount))
(gobj/set this ":rum/unmounted?" true))))
(when-not (empty? child-context)
(gobj/set prototype "getChildContext"
(fn []
(this-as this
(let [state @(state this)]
(clj->js (transduce (map #(% state)) merge {} child-context)))))))
(extend! prototype class-props)
(gobj/set ctor "displayName" display-name)
(extend! ctor static-props)
ctor))
(defn- set-meta! [c]
(let [f #(let [ctr (c)]
(.apply ctr ctr (js-arguments)))]
(specify! f IMeta (-meta [_] (meta (c))))
f))
(defn lazy-build
"Wraps component construction in a way so that Google Closure Compiler
can properly recognize and elide unused components. The extra `set-meta`
fn is needed so that the compiler can properly detect that all functions
are side effect free."
[ctor render mixins display-name]
(let [bf #(ctor render mixins display-name) ;; Avoid IIFE
c (fns/cacheReturnValue bf)]
(set-meta! c)))
(defn- build-ctor [render mixins display-name]
(let [class (build-class render mixins display-name)
key-fn (first (collect :key-fn mixins))
ctor (if (some? key-fn)
(fn [& args]
(let [props #js {":rum/initial-state" {:rum/args args}
"key" (apply key-fn args)}]
(js/React.createElement class props)))
(fn [& args]
(let [props #js {":rum/initial-state" {:rum/args args}}]
(js/React.createElement class props))))]
(with-meta ctor {:rum/class class})))
(declare static)
(defn- memo-compare-props [prev-props next-props]
(= (aget prev-props ":rum/args")
(aget next-props ":rum/args")))
(defn react-memo [f]
(if-some [memo (.-memo js/React)]
(memo f memo-compare-props)
f))
(defn ^:no-doc build-defc [render-body mixins display-name]
(cond
(= mixins [static])
(let [class (fn [props]
(apply render-body (aget props ":rum/args")))
_ (aset class "displayName" display-name)
memo-class (react-memo class)
ctor (fn [& args]
(.createElement js/React memo-class #js {":rum/args" args}))]
(with-meta ctor {:rum/class memo-class}))
(empty? mixins)
(let [class (fn [props]
(apply render-body (aget props ":rum/args")))
_ (aset class "displayName" display-name)
ctor (fn [& args]
(.createElement js/React class #js {":rum/args" args}))]
(with-meta ctor {:rum/class class}))
:else
(let [render (fn [state] [(apply render-body (:rum/args state)) state])]
(build-ctor render mixins display-name))))
(defn ^:no-doc build-defcs [render-body mixins display-name]
(let [render (fn [state] [(apply render-body state (:rum/args state)) state])]
(build-ctor render mixins display-name)))
(defn ^:no-doc build-defcc [render-body mixins display-name]
(let [render (fn [state] [(apply render-body (:rum/react-component state) (:rum/args state)) state])]
(build-ctor render mixins display-name)))
;; render queue
(def ^:private schedule
(or (and (exists? js/window)
(or js/window.requestAnimationFrame
js/window.webkitRequestAnimationFrame
js/window.mozRequestAnimationFrame
js/window.msRequestAnimationFrame))
#(js/setTimeout % 16)))
(def ^:private batch
(or (when (exists? js/ReactNative) js/ReactNative.unstable_batchedUpdates)
(when (exists? js/ReactDOM) js/ReactDOM.unstable_batchedUpdates)
(fn [f a] (f a))))
(def ^:private empty-queue [])
(def ^:private render-queue (volatile! empty-queue))
(defn- render-all [queue]
(doseq [comp queue
:when (and (some? comp) (not (gobj/get comp ":rum/unmounted?")))]
(.forceUpdate comp)))
(defn- render []
(let [queue @render-queue]
(vreset! render-queue empty-queue)
(batch render-all queue)))
(defn request-render
"Schedules react component to be rendered on next animation frame."
[component]
(when (empty? @render-queue)
(schedule render))
(vswap! render-queue conj component))
(defn mount
"Add element to the DOM tree. Idempotent. Subsequent mounts will just update element."
[element node]
(js/ReactDOM.render element node)
nil)
(defn unmount
"Removes component from the DOM tree."
[node]
(js/ReactDOM.unmountComponentAtNode node))
(defn hydrate
"Same as [[mount]] but must be called on DOM tree already rendered by a server via [[render-html]]."
[element node]
(js/ReactDOM.hydrate element node))
(defn portal
"Render `element` in a DOM `node` that is ouside of current DOM hierarchy."
[element node]
(js/ReactDOM.createPortal element node))
(defn create-context [default-value]
(.createContext js/React default-value))
;; initialization
(defn with-key
"Adds React key to element.
```
(rum/defc label [text] [:div text])
(-> (label)
(rum/with-key \"abc\")
(rum/mount js/document.body))
```"
[element key]
(js/React.cloneElement element #js {"key" key} nil))
(defn with-ref
"Adds React ref (string or callback) to element.
```
(rum/defc label [text] [:div text])
(-> (label)
(rum/with-ref \"abc\")
(rum/mount js/document.body))
```"
[element ref]
(js/React.cloneElement element #js {"ref" ref} nil))
(defn dom-node
"Usage of this function is discouraged. Use :ref callback instead.
Given state, returns top-level DOM node of component. Call it during lifecycle callbacks. Can’t be called during render."
[state]
(js/ReactDOM.findDOMNode (:rum/react-component state)))
(defn ref
"DEPRECATED: Use :ref (fn [dom-or-nil]) callback instead. See rum issue #124
Given state and ref handle, returns React component."
[state key]
(-> state :rum/react-component (aget "refs") (aget (name key))))
(defn ref-node
"DEPRECATED: Use :ref (fn [dom-or-nil]) callback instead. See rum issue #124
Given state and ref handle, returns DOM node associated with ref."
[state key]
(js/ReactDOM.findDOMNode (ref state (name key))))
;; static mixin
(def static
"Mixin. Will avoid re-render if none of component’s arguments have changed. Does equality check (`=`) on all arguments.
```
(rum/defc label < rum/static
[text]
[:div text])
(rum/mount (label \"abc\") js/document.body)
;; def != abc, will re-render
(rum/mount (label \"def\") js/document.body)
;; def == def, won’t re-render
(rum/mount (label \"def\") js/document.body)
```"
{:should-update
(fn [old-state new-state]
(not= (:rum/args old-state) (:rum/args new-state)))})
;; local mixin
(defn local
"Mixin constructor. Adds an atom to component’s state that can be used to keep stuff during component’s lifecycle. Component will be re-rendered if atom’s value changes. Atom is stored under user-provided key or under `:rum/local` by default.
```
(rum/defcs counter < (rum/local 0 :cnt)
[state label]
(let [*cnt (:cnt state)]
[:div {:on-click (fn [_] (swap! *cnt inc))}
label @*cnt]))
(rum/mount (counter \"Click count: \"))
```"
([initial] (local initial :rum/local))
([initial key]
{:will-mount
(fn [state]
(let [local-state (atom initial)
component (:rum/react-component state)]
(add-watch local-state key
(fn [_ _ _ _]
(request-render component)))
(assoc state key local-state)))}))
;; reactive mixin
(def ^:private ^:dynamic *reactions*)
(def reactive
"Mixin. Works in conjunction with [[react]].
```
(rum/defc comp < rum/reactive
[*counter]
[:div (rum/react counter)])
(def *counter (atom 0))
(rum/mount (comp *counter) js/document.body)
(swap! *counter inc) ;; will force comp to re-render
```"
{:init
(fn [state props]
(assoc state :rum.reactive/key (random-uuid)))
:wrap-render
(fn [render-fn]
(fn [state]
(binding [*reactions* (volatile! #{})]
(let [comp (:rum/react-component state)
old-reactions (:rum.reactive/refs state #{})
[dom next-state] (render-fn state)
new-reactions @*reactions*
key (:rum.reactive/key state)]
(doseq [ref old-reactions]
(when-not (contains? new-reactions ref)
(remove-watch ref key)))
(doseq [ref new-reactions]
(when-not (contains? old-reactions ref)
(add-watch ref key
(fn [_ _ _ _]
(request-render comp)))))
[dom (assoc next-state :rum.reactive/refs new-reactions)]))))
:will-unmount
(fn [state]
(let [key (:rum.reactive/key state)]
(doseq [ref (:rum.reactive/refs state)]
(remove-watch ref key)))
(dissoc state :rum.reactive/refs :rum.reactive/key))})
(defn react
"Works in conjunction with [[reactive]] mixin. Use this function instead of `deref` inside render, and your component will subscribe to changes happening to the derefed atom."
[ref]
(assert *reactions* "rum.core/react is only supported in conjunction with rum.core/reactive")
(vswap! *reactions* conj ref)
@ref)
;; derived-atom
(def ^{:style/indent 2
:arglists '([refs key f] [refs key f opts])
:doc "Use this to create “chains” and acyclic graphs of dependent atoms.
[[derived-atom]] will:
- Take N “source” refs.
- Set up a watch on each of them.
- Create “sink” atom.
- When any of source refs changes:
- re-run function `f`, passing N dereferenced values of source refs.
- `reset!` result of `f` to the sink atom.
- Return sink atom.
Example:
```
(def *a (atom 0))
(def *b (atom 1))
(def *x (derived-atom [*a *b] ::key
(fn [a b]
(str a \":\" b))))
(type *x) ;; => clojure.lang.Atom
(deref *x) ;; => \"0:1\"
(swap! *a inc)
(deref *x) ;; => \"1:1\"
(reset! *b 7)
(deref *x) ;; => \"1:7\"
```
Arguments:
- `refs` - sequence of source refs,
- `key` - unique key to register watcher, same as in `clojure.core/add-watch`,
- `f` - function that must accept N arguments (same as number of source refs) and return a value to be written to the sink ref. Note: `f` will be called with already dereferenced values,
- `opts` - optional. Map of:
- `:ref` - use this as sink ref. By default creates new atom,
- `:check-equals?` - Defaults to `true`. If equality check should be run on each source update: `(= @sink (f new-vals))`. When result of recalculating `f` equals to the old value, `reset!` won’t be called. Set to `false` if checking for equality can be expensive."}
derived-atom derived-atom/derived-atom)
;; cursors
(defn cursor-in
"Given atom with deep nested value and path inside it, creates an atom-like structure
that can be used separately from main atom, but will sync changes both ways:
```
(def db (atom { :users { \"PI:NAME:<NAME>END_PI\" { :age 30 }}}))
(def ivan (rum/cursor db [:users \"PI:NAME:<NAME>END_PI\"]))
(deref ivan) ;; => { :age 30 }
(swap! ivan update :age inc) ;; => { :age 31 }
(deref db) ;; => { :users { \"PI:NAME:<NAME>END_PI\" { :age 31 }}}
(swap! db update-in [:users \"PI:NAME:<NAME>END_PI\" :age] inc)
;; => { :users { \"PI:NAME:<NAME>END_PI\" { :age 32 }}}
(deref ivan) ;; => { :age 32 }
```
Returned value supports `deref`, `swap!`, `reset!`, watches and metadata.
The only supported option is `:meta`"
[ref path & {:as options}]
(if (instance? cursor/Cursor ref)
(cursor/Cursor. (.-ref ref) (into (.-path ref) path) (:meta options))
(cursor/Cursor. ref path (:meta options))))
(defn cursor
"Same as [[cursor-in]] but accepts single key instead of path vector."
[ref key & options]
(apply cursor-in ref [key] options))
;; hooks
(defn ^array use-state
"Takes initial value or value returning fn and returns a tuple of [value set-value!],
where `value` is current state value and `set-value!` is a function that schedules re-render.
(let [[value set-state!] (rum/use-state 0)]
[:button {:on-click #(set-state! (inc value))}
value])"
[value-or-fn]
(.useState js/React value-or-fn))
(defn ^array use-reducer
"Takes reducing function and initial state value.
Returns a tuple of [value dispatch!], where `value` is current state value and `dispatch` is a function that schedules re-render.
(defmulti value-reducer (fn [event value] event))
(defmethod value-reducer :inc [_ value]
(inc value))
(let [[value dispatch!] (rum/use-reducer value-reducer 0)]
[:button {:on-click #(dispatch! :inc)}
value])
Read more at https://reactjs.org/docs/hooks-reference.html#usereducer"
([reducer-fn initial-value]
(.useReducer js/React #(reducer-fn %2 %1) initial-value identity)))
(defn use-effect!
"Takes setup-fn that executes either on the first render or after every update.
The function may return cleanup-fn to cleanup the effect, either before unmount or before every next update.
Calling behavior is controlled by deps argument.
(rum/use-effect!
(fn []
(.addEventListener js/window \"load\" handler)
#(.removeEventListener js/window \"load\" handler))
[]) ;; empty deps collection instructs React to run setup-fn only once on initial render
;; and cleanup-fn only once before unmounting
Read more at https://reactjs.org/docs/hooks-effect.html"
([setup-fn]
(.useEffect js/React #(or (setup-fn) js/undefined)))
([setup-fn deps]
(->> (if (array? deps) deps (into-array deps))
(.useEffect js/React #(or (setup-fn) js/undefined)))))
(defn use-callback
"Takes callback function and returns memoized variant, memoization is done based on provided deps collection.
(rum/defc button < rum/static
[{:keys [on-click]} text]
[:button {:on-click on-click}
text])
(rum/defc app [v]
(let [on-click (rum/use-callback #(do-stuff v) [v])]
;; because on-click callback is memoized here based on v argument
;; the callback won't be re-created on every render, unless v changes
;; which means that underlying `button` component won't re-render wastefully
[button {:on-click on-click}
\"press me\"]))
Read more at https://reactjs.org/docs/hooks-reference.html#usecallback"
([callback]
(.useCallback js/React callback))
([callback deps]
(->> (if (array? deps) deps (into-array deps))
(.useCallback js/React callback))))
(defn use-memo
"Takes a function, memoizes it based on provided deps collection and executes immediately returning a result.
Read more at https://reactjs.org/docs/hooks-reference.html#usememo"
([f]
(.useMemo js/React f))
([f deps]
(->> (if (array? deps) deps (into-array deps))
(.useMemo js/React f))))
(defn use-ref
"Takes a value and puts it into a mutable container which is persisted for the full lifetime of the component.
https://reactjs.org/docs/hooks-reference.html#useref"
([initial-value]
(.useRef js/React initial-value)))
;; Refs
(defn create-ref []
(.createRef js/React))
(defn deref
"Takes a ref returned from use-ref and returns its current value."
[^js ref]
(.-current ref))
(defn set-ref! [^js ref value]
(set! (.-current ref) value))
;;; Server-side rendering
;; Roman. For Node.js runtime we require "react-dom/server" for you
;; In the browser you have to add cljsjs/react-dom-server yourself
(defn render-html
"Main server-side rendering method. Given component, returns HTML string with static markup of that component.
Serve that string to the browser and [[hydrate]] same Rum component over it. React will be able to reuse already existing DOM and will initialize much faster.
No opts are supported at the moment."
([element]
(render-html element nil))
([element opts]
(if-not (identical? *target* "nodejs")
(.renderToString js/ReactDOMServer element)
(let [react-dom-server (js/require "react-dom/server")]
(.renderToString react-dom-server element)))))
(defn render-static-markup
"Same as [[render-html]] but returned string has nothing React-specific.
This allows Rum to be used as traditional server-side templating engine."
[src]
(if-not (identical? *target* "nodejs")
(.renderToStaticMarkup js/ReactDOMServer src)
(let [react-dom-server (js/require "react-dom/server")]
(.renderToStaticMarkup react-dom-server src))))
;; JS components adapter
(defn adapt-class-helper [type attrs children]
(let [args (.concat #js [type attrs] children)]
(.apply (.-createElement js/React) js/React args)))
|
[
{
"context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998876452445984,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
}
] |
test/territory_bro/user_test.clj
|
JessRoberts/territory_assistant
| 0 |
;; Copyright © 2015-2019 Esko Luontola
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.user-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[territory-bro.db :as db]
[territory-bro.fixtures :refer [db-fixture]]
[territory-bro.user :as user])
(:import (java.util UUID)))
(use-fixtures :once db-fixture)
(deftest users-test
(db/with-db [conn {}]
(jdbc/db-set-rollback-only! conn)
(let [user-id (user/save-user! conn "user1" {:name "User 1"})
unrelated-user-id (user/save-user! conn "user2" {:name "User 2"})
unrelated-user (user/get-by-id conn unrelated-user-id)]
(testing "create new user"
(is user-id)
(is (= {:user/id user-id
:user/subject "user1"
:user/attributes {:name "User 1"}}
(user/get-by-id conn user-id))))
(testing "update existing user"
(is (= user-id
(user/save-user! conn "user1" {:name "new name"}))
"should return same ID as before")
(is (= {:user/id user-id
:user/subject "user1"
:user/attributes {:name "new name"}}
(user/get-by-id conn user-id))
"should update attributes"))
(testing "list users"
(is (= ["user1" "user2"]
(->> (user/get-users conn)
(map :user/subject)
(sort)))))
(testing "find users by IDs"
(is (= ["user1"]
(->> (user/get-users conn {:ids [user-id]})
(map :user/subject)
(sort))))
(is (= ["user1" "user2"]
(->> (user/get-users conn {:ids [user-id unrelated-user-id]})
(map :user/subject)
(sort)))))
(testing "find user by ID"
(is (= user-id (:user/id (user/get-by-id conn user-id))))
(is (nil? (user/get-by-id conn (UUID/randomUUID)))
"not found"))
(testing "find user by subject"
(is (= user-id (:user/id (user/get-by-subject conn "user1"))))
(is (nil? (user/get-by-subject conn "no-such-user"))
"not found"))
(testing "did not accidentally change unrelated users"
(is (= unrelated-user (user/get-by-id conn unrelated-user-id)))))))
|
15197
|
;; Copyright © 2015-2019 <NAME>
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.user-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[territory-bro.db :as db]
[territory-bro.fixtures :refer [db-fixture]]
[territory-bro.user :as user])
(:import (java.util UUID)))
(use-fixtures :once db-fixture)
(deftest users-test
(db/with-db [conn {}]
(jdbc/db-set-rollback-only! conn)
(let [user-id (user/save-user! conn "user1" {:name "User 1"})
unrelated-user-id (user/save-user! conn "user2" {:name "User 2"})
unrelated-user (user/get-by-id conn unrelated-user-id)]
(testing "create new user"
(is user-id)
(is (= {:user/id user-id
:user/subject "user1"
:user/attributes {:name "User 1"}}
(user/get-by-id conn user-id))))
(testing "update existing user"
(is (= user-id
(user/save-user! conn "user1" {:name "new name"}))
"should return same ID as before")
(is (= {:user/id user-id
:user/subject "user1"
:user/attributes {:name "new name"}}
(user/get-by-id conn user-id))
"should update attributes"))
(testing "list users"
(is (= ["user1" "user2"]
(->> (user/get-users conn)
(map :user/subject)
(sort)))))
(testing "find users by IDs"
(is (= ["user1"]
(->> (user/get-users conn {:ids [user-id]})
(map :user/subject)
(sort))))
(is (= ["user1" "user2"]
(->> (user/get-users conn {:ids [user-id unrelated-user-id]})
(map :user/subject)
(sort)))))
(testing "find user by ID"
(is (= user-id (:user/id (user/get-by-id conn user-id))))
(is (nil? (user/get-by-id conn (UUID/randomUUID)))
"not found"))
(testing "find user by subject"
(is (= user-id (:user/id (user/get-by-subject conn "user1"))))
(is (nil? (user/get-by-subject conn "no-such-user"))
"not found"))
(testing "did not accidentally change unrelated users"
(is (= unrelated-user (user/get-by-id conn unrelated-user-id)))))))
| true |
;; Copyright © 2015-2019 PI:NAME:<NAME>END_PI
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.user-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[territory-bro.db :as db]
[territory-bro.fixtures :refer [db-fixture]]
[territory-bro.user :as user])
(:import (java.util UUID)))
(use-fixtures :once db-fixture)
(deftest users-test
(db/with-db [conn {}]
(jdbc/db-set-rollback-only! conn)
(let [user-id (user/save-user! conn "user1" {:name "User 1"})
unrelated-user-id (user/save-user! conn "user2" {:name "User 2"})
unrelated-user (user/get-by-id conn unrelated-user-id)]
(testing "create new user"
(is user-id)
(is (= {:user/id user-id
:user/subject "user1"
:user/attributes {:name "User 1"}}
(user/get-by-id conn user-id))))
(testing "update existing user"
(is (= user-id
(user/save-user! conn "user1" {:name "new name"}))
"should return same ID as before")
(is (= {:user/id user-id
:user/subject "user1"
:user/attributes {:name "new name"}}
(user/get-by-id conn user-id))
"should update attributes"))
(testing "list users"
(is (= ["user1" "user2"]
(->> (user/get-users conn)
(map :user/subject)
(sort)))))
(testing "find users by IDs"
(is (= ["user1"]
(->> (user/get-users conn {:ids [user-id]})
(map :user/subject)
(sort))))
(is (= ["user1" "user2"]
(->> (user/get-users conn {:ids [user-id unrelated-user-id]})
(map :user/subject)
(sort)))))
(testing "find user by ID"
(is (= user-id (:user/id (user/get-by-id conn user-id))))
(is (nil? (user/get-by-id conn (UUID/randomUUID)))
"not found"))
(testing "find user by subject"
(is (= user-id (:user/id (user/get-by-subject conn "user1"))))
(is (nil? (user/get-by-subject conn "no-such-user"))
"not found"))
(testing "did not accidentally change unrelated users"
(is (= unrelated-user (user/get-by-id conn unrelated-user-id)))))))
|
[
{
"context": "; Author: Arijit Dasgupta (@rivalslayer)\n; Brainfuck in Clojure\n\n(ns brainf",
"end": 25,
"score": 0.9998810887336731,
"start": 10,
"tag": "NAME",
"value": "Arijit Dasgupta"
},
{
"context": "; Author: Arijit Dasgupta (@rivalslayer)\n; Brainfuck in Clojure\n\n(ns brainfuck-in-clojure",
"end": 39,
"score": 0.9994295835494995,
"start": 26,
"tag": "USERNAME",
"value": "(@rivalslayer"
},
{
"context": "tln \"Brainfuck Interpreter v0.1\")\n (println \"by Arijit Dasgupta (@rivalslayer)\")\n (println \"RAM size: \")\n (",
"end": 4002,
"score": 0.9998820424079895,
"start": 3987,
"tag": "NAME",
"value": "Arijit Dasgupta"
},
{
"context": "nterpreter v0.1\")\n (println \"by Arijit Dasgupta (@rivalslayer)\")\n (println \"RAM size: \")\n (println ram-si",
"end": 4016,
"score": 0.9996630549430847,
"start": 4003,
"tag": "USERNAME",
"value": "(@rivalslayer"
}
] |
src/brainfuck_in_clojure/core.clj
|
rivalslayer/brainfuck-in-clojure
| 0 |
; Author: Arijit Dasgupta (@rivalslayer)
; Brainfuck in Clojure
(ns brainfuck-in-clojure.core
(:gen-class))
;
; State structure
; {
; :code array or string symbols literals e.g. [\. \+]
; :head Number/Integer
; :ram array of Number/Integer
; :pointer Number/Integer
; }
;
; + increment the value at pointer
; - decrement the value at pointer
; > increate the pointer value
; < decrate the pointer value
; . out the current data
; , in the next line
; [ if value at pointer is zero go to the next ]
;
;
(def ram-size 30)
(defn split-tape
[code]
(into [] (seq code)))
(defn initiate-state
[code]
{
:code (split-tape code)
:head 0
:ram (loop [array [] n 0]
(if (= n ram-size) array (recur (conj array 0) (inc n))))
:pointer 0
})
(def io
{
:output (fn [x] (println x))
:input (fn [] (read-string (read-line)))
})
(defn add-one
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state) current-value (get current-ram current-pointer)]
(assoc state :ram (assoc current-ram current-pointer (inc current-value)))))
(defn subtract-one
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state) current-value (get current-ram current-pointer)]
(assoc state :ram (assoc current-ram current-pointer (dec current-value)))))
(defn increment-pointer
[state io]
(let [current-pointer (:pointer state)]
(assoc state :pointer (inc current-pointer))))
(defn decrement-pointer
[state io]
(let [current-pointer (:pointer state)]
(assoc state :pointer (dec current-pointer))))
(defn goto-square
[state io]
(let [code (:code state) current-value (get (:ram state) (:pointer state))]
(if (<= current-value 0)
(loop [head (:head state) bdepth 0]
(cond
(= (get code head) \[) (recur (inc head) (inc bdepth))
(and (= (get code head) \]) (> bdepth 1)) (recur (inc head) (dec bdepth)) ;Crazy nested loop logic
(and (= (get code head) \]) (= bdepth 1)) (assoc state :head head)
:else (recur (inc head) bdepth)))
state)))
; (if (or (= (get code head) \]) (= head (count code)))
; (assoc state :head head)
; (recur (inc head))))
(defn goto-back-square
[state io]
(let [code (:code state)]
(loop [head (:head state) bdepth 0]
(cond
(= (get code head) \]) (recur (dec head) (inc bdepth))
(and (= (get code head) \[) (> bdepth 1)) (recur (dec head) (dec bdepth)) ;Crazy nested loop logic
(and (= (get code head) \[) (= bdepth 1)) (assoc state :head head)
:else (recur (dec head) bdepth)))))
; (if (= (get code head) \[)
; (assoc state :head head)
; (recur (dec head))))))
(defn output
[state io]
(let [current-value (get (:ram state) (:pointer state))]
(do
((:output io) current-value)
state)))
(defn input
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state)]
(assoc state :ram (assoc current-ram current-pointer ((:input io))))))
(defn print-state
[state io]
(do
((:output io) state)
state))
(defn check-instruction
[state]
(get (:code state) (:head state)))
(def funk-map {
\+ add-one
\- subtract-one
\> increment-pointer
\< decrement-pointer
\[ goto-square
\] goto-back-square
\. output
\, input
\M print-state})
(defn tape-machine
[initial-state io]
(loop [state initial-state]
(if (>= (:head state) (count (:code state)))
state
(let [funk (get funk-map (check-instruction state))
new-state (funk state io)
new-head (:head new-state)]
(if (>= new-head (:head state))
(recur (assoc new-state :head (inc new-head)))
(recur new-state))))))
(defn start-brainfuck
[code]
(let [new-state (initiate-state code)]
(tape-machine (initiate-state code) io)))
(defn -main
"Start the brainfuck interpreter"
[]
(do
(println "Brainfuck Interpreter v0.1")
(println "by Arijit Dasgupta (@rivalslayer)")
(println "RAM size: ")
(println ram-size)
(println "RAM is [0 0 0 0 ...].")
(println "Instruction pointer is 0.")
(println "Current pointer to RAM is 0.")
(println "Brainfuck: https://en.wikipedia.org/wiki/Brainfuck")
(println "Debug syntax M: Prints out whole state of the machine.")
(println "Operates only on integer numbers. For input, only accepts integers.")
(println "Caught errors are uncaught Java/Clojure errors. ")
(println "Please type out your brainfuck code [RETURN runs the code]")
(start-brainfuck (read-line))
(println "Good bye!")))
|
1755
|
; Author: <NAME> (@rivalslayer)
; Brainfuck in Clojure
(ns brainfuck-in-clojure.core
(:gen-class))
;
; State structure
; {
; :code array or string symbols literals e.g. [\. \+]
; :head Number/Integer
; :ram array of Number/Integer
; :pointer Number/Integer
; }
;
; + increment the value at pointer
; - decrement the value at pointer
; > increate the pointer value
; < decrate the pointer value
; . out the current data
; , in the next line
; [ if value at pointer is zero go to the next ]
;
;
(def ram-size 30)
(defn split-tape
[code]
(into [] (seq code)))
(defn initiate-state
[code]
{
:code (split-tape code)
:head 0
:ram (loop [array [] n 0]
(if (= n ram-size) array (recur (conj array 0) (inc n))))
:pointer 0
})
(def io
{
:output (fn [x] (println x))
:input (fn [] (read-string (read-line)))
})
(defn add-one
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state) current-value (get current-ram current-pointer)]
(assoc state :ram (assoc current-ram current-pointer (inc current-value)))))
(defn subtract-one
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state) current-value (get current-ram current-pointer)]
(assoc state :ram (assoc current-ram current-pointer (dec current-value)))))
(defn increment-pointer
[state io]
(let [current-pointer (:pointer state)]
(assoc state :pointer (inc current-pointer))))
(defn decrement-pointer
[state io]
(let [current-pointer (:pointer state)]
(assoc state :pointer (dec current-pointer))))
(defn goto-square
[state io]
(let [code (:code state) current-value (get (:ram state) (:pointer state))]
(if (<= current-value 0)
(loop [head (:head state) bdepth 0]
(cond
(= (get code head) \[) (recur (inc head) (inc bdepth))
(and (= (get code head) \]) (> bdepth 1)) (recur (inc head) (dec bdepth)) ;Crazy nested loop logic
(and (= (get code head) \]) (= bdepth 1)) (assoc state :head head)
:else (recur (inc head) bdepth)))
state)))
; (if (or (= (get code head) \]) (= head (count code)))
; (assoc state :head head)
; (recur (inc head))))
(defn goto-back-square
[state io]
(let [code (:code state)]
(loop [head (:head state) bdepth 0]
(cond
(= (get code head) \]) (recur (dec head) (inc bdepth))
(and (= (get code head) \[) (> bdepth 1)) (recur (dec head) (dec bdepth)) ;Crazy nested loop logic
(and (= (get code head) \[) (= bdepth 1)) (assoc state :head head)
:else (recur (dec head) bdepth)))))
; (if (= (get code head) \[)
; (assoc state :head head)
; (recur (dec head))))))
(defn output
[state io]
(let [current-value (get (:ram state) (:pointer state))]
(do
((:output io) current-value)
state)))
(defn input
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state)]
(assoc state :ram (assoc current-ram current-pointer ((:input io))))))
(defn print-state
[state io]
(do
((:output io) state)
state))
(defn check-instruction
[state]
(get (:code state) (:head state)))
(def funk-map {
\+ add-one
\- subtract-one
\> increment-pointer
\< decrement-pointer
\[ goto-square
\] goto-back-square
\. output
\, input
\M print-state})
(defn tape-machine
[initial-state io]
(loop [state initial-state]
(if (>= (:head state) (count (:code state)))
state
(let [funk (get funk-map (check-instruction state))
new-state (funk state io)
new-head (:head new-state)]
(if (>= new-head (:head state))
(recur (assoc new-state :head (inc new-head)))
(recur new-state))))))
(defn start-brainfuck
[code]
(let [new-state (initiate-state code)]
(tape-machine (initiate-state code) io)))
(defn -main
"Start the brainfuck interpreter"
[]
(do
(println "Brainfuck Interpreter v0.1")
(println "by <NAME> (@rivalslayer)")
(println "RAM size: ")
(println ram-size)
(println "RAM is [0 0 0 0 ...].")
(println "Instruction pointer is 0.")
(println "Current pointer to RAM is 0.")
(println "Brainfuck: https://en.wikipedia.org/wiki/Brainfuck")
(println "Debug syntax M: Prints out whole state of the machine.")
(println "Operates only on integer numbers. For input, only accepts integers.")
(println "Caught errors are uncaught Java/Clojure errors. ")
(println "Please type out your brainfuck code [RETURN runs the code]")
(start-brainfuck (read-line))
(println "Good bye!")))
| true |
; Author: PI:NAME:<NAME>END_PI (@rivalslayer)
; Brainfuck in Clojure
(ns brainfuck-in-clojure.core
(:gen-class))
;
; State structure
; {
; :code array or string symbols literals e.g. [\. \+]
; :head Number/Integer
; :ram array of Number/Integer
; :pointer Number/Integer
; }
;
; + increment the value at pointer
; - decrement the value at pointer
; > increate the pointer value
; < decrate the pointer value
; . out the current data
; , in the next line
; [ if value at pointer is zero go to the next ]
;
;
(def ram-size 30)
(defn split-tape
[code]
(into [] (seq code)))
(defn initiate-state
[code]
{
:code (split-tape code)
:head 0
:ram (loop [array [] n 0]
(if (= n ram-size) array (recur (conj array 0) (inc n))))
:pointer 0
})
(def io
{
:output (fn [x] (println x))
:input (fn [] (read-string (read-line)))
})
(defn add-one
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state) current-value (get current-ram current-pointer)]
(assoc state :ram (assoc current-ram current-pointer (inc current-value)))))
(defn subtract-one
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state) current-value (get current-ram current-pointer)]
(assoc state :ram (assoc current-ram current-pointer (dec current-value)))))
(defn increment-pointer
[state io]
(let [current-pointer (:pointer state)]
(assoc state :pointer (inc current-pointer))))
(defn decrement-pointer
[state io]
(let [current-pointer (:pointer state)]
(assoc state :pointer (dec current-pointer))))
(defn goto-square
[state io]
(let [code (:code state) current-value (get (:ram state) (:pointer state))]
(if (<= current-value 0)
(loop [head (:head state) bdepth 0]
(cond
(= (get code head) \[) (recur (inc head) (inc bdepth))
(and (= (get code head) \]) (> bdepth 1)) (recur (inc head) (dec bdepth)) ;Crazy nested loop logic
(and (= (get code head) \]) (= bdepth 1)) (assoc state :head head)
:else (recur (inc head) bdepth)))
state)))
; (if (or (= (get code head) \]) (= head (count code)))
; (assoc state :head head)
; (recur (inc head))))
(defn goto-back-square
[state io]
(let [code (:code state)]
(loop [head (:head state) bdepth 0]
(cond
(= (get code head) \]) (recur (dec head) (inc bdepth))
(and (= (get code head) \[) (> bdepth 1)) (recur (dec head) (dec bdepth)) ;Crazy nested loop logic
(and (= (get code head) \[) (= bdepth 1)) (assoc state :head head)
:else (recur (dec head) bdepth)))))
; (if (= (get code head) \[)
; (assoc state :head head)
; (recur (dec head))))))
(defn output
[state io]
(let [current-value (get (:ram state) (:pointer state))]
(do
((:output io) current-value)
state)))
(defn input
[state io]
(let [current-pointer (:pointer state) current-ram (:ram state)]
(assoc state :ram (assoc current-ram current-pointer ((:input io))))))
(defn print-state
[state io]
(do
((:output io) state)
state))
(defn check-instruction
[state]
(get (:code state) (:head state)))
(def funk-map {
\+ add-one
\- subtract-one
\> increment-pointer
\< decrement-pointer
\[ goto-square
\] goto-back-square
\. output
\, input
\M print-state})
(defn tape-machine
[initial-state io]
(loop [state initial-state]
(if (>= (:head state) (count (:code state)))
state
(let [funk (get funk-map (check-instruction state))
new-state (funk state io)
new-head (:head new-state)]
(if (>= new-head (:head state))
(recur (assoc new-state :head (inc new-head)))
(recur new-state))))))
(defn start-brainfuck
[code]
(let [new-state (initiate-state code)]
(tape-machine (initiate-state code) io)))
(defn -main
"Start the brainfuck interpreter"
[]
(do
(println "Brainfuck Interpreter v0.1")
(println "by PI:NAME:<NAME>END_PI (@rivalslayer)")
(println "RAM size: ")
(println ram-size)
(println "RAM is [0 0 0 0 ...].")
(println "Instruction pointer is 0.")
(println "Current pointer to RAM is 0.")
(println "Brainfuck: https://en.wikipedia.org/wiki/Brainfuck")
(println "Debug syntax M: Prints out whole state of the machine.")
(println "Operates only on integer numbers. For input, only accepts integers.")
(println "Caught errors are uncaught Java/Clojure errors. ")
(println "Please type out your brainfuck code [RETURN runs the code]")
(start-brainfuck (read-line))
(println "Good bye!")))
|
[
{
"context": "h [:set-dialogue\n {:character :adam\n :type :answer\n ",
"end": 1144,
"score": 0.6774210333824158,
"start": 1140,
"tag": "NAME",
"value": "adam"
}
] |
data/test/clojure/66bcc40f9fdc7cf589dd9807b388184394210225repl.cljs
|
harshp8l/deep-learning-lang-detection
| 84 |
(ns ggj17.repl
(:require [re-frame.core :as re-frame]))
(def db (re-frame/subscribe [:db]))
(:scene @db)
(:questions @db)
(def scene (re-frame/subscribe [:scene]))
(:characters @scene)
(:character @db)
(:foot @db)
(:objects @db)
(:dialogue @db)
(:realness @db)
(keys @db)
(re-frame/dispatch [:set-character "characters/rex.svg"])
(re-frame/dispatch [:set-objects [{:name "foot"
:file "objects/foot.svg"
:x "80%"
:y "70%"
:width "7%"
:action #(js/alert "Foot!")}]])
(re-frame/dispatch [:set-dialogue
{:character :rex
:file "characters/rex-face.svg"
:type :question
:id 5}])
(re-frame/dispatch [:set-dialogue
{:character :sam
:file "characters/sam-face.svg"
:type :answer
:id 0}])
(re-frame/dispatch [:set-dialogue nil])
(re-frame/dispatch [:set-dialogue
{:character :adam
:type :answer
:file "characters/adam-face.svg"
:id 0}])
(re-frame/dispatch [:set-dialogue
{:character :luce
:type :answer
:file "characters/scarlett-face.svg"
:id 0}])
|
38090
|
(ns ggj17.repl
(:require [re-frame.core :as re-frame]))
(def db (re-frame/subscribe [:db]))
(:scene @db)
(:questions @db)
(def scene (re-frame/subscribe [:scene]))
(:characters @scene)
(:character @db)
(:foot @db)
(:objects @db)
(:dialogue @db)
(:realness @db)
(keys @db)
(re-frame/dispatch [:set-character "characters/rex.svg"])
(re-frame/dispatch [:set-objects [{:name "foot"
:file "objects/foot.svg"
:x "80%"
:y "70%"
:width "7%"
:action #(js/alert "Foot!")}]])
(re-frame/dispatch [:set-dialogue
{:character :rex
:file "characters/rex-face.svg"
:type :question
:id 5}])
(re-frame/dispatch [:set-dialogue
{:character :sam
:file "characters/sam-face.svg"
:type :answer
:id 0}])
(re-frame/dispatch [:set-dialogue nil])
(re-frame/dispatch [:set-dialogue
{:character :<NAME>
:type :answer
:file "characters/adam-face.svg"
:id 0}])
(re-frame/dispatch [:set-dialogue
{:character :luce
:type :answer
:file "characters/scarlett-face.svg"
:id 0}])
| true |
(ns ggj17.repl
(:require [re-frame.core :as re-frame]))
(def db (re-frame/subscribe [:db]))
(:scene @db)
(:questions @db)
(def scene (re-frame/subscribe [:scene]))
(:characters @scene)
(:character @db)
(:foot @db)
(:objects @db)
(:dialogue @db)
(:realness @db)
(keys @db)
(re-frame/dispatch [:set-character "characters/rex.svg"])
(re-frame/dispatch [:set-objects [{:name "foot"
:file "objects/foot.svg"
:x "80%"
:y "70%"
:width "7%"
:action #(js/alert "Foot!")}]])
(re-frame/dispatch [:set-dialogue
{:character :rex
:file "characters/rex-face.svg"
:type :question
:id 5}])
(re-frame/dispatch [:set-dialogue
{:character :sam
:file "characters/sam-face.svg"
:type :answer
:id 0}])
(re-frame/dispatch [:set-dialogue nil])
(re-frame/dispatch [:set-dialogue
{:character :PI:NAME:<NAME>END_PI
:type :answer
:file "characters/adam-face.svg"
:id 0}])
(re-frame/dispatch [:set-dialogue
{:character :luce
:type :answer
:file "characters/scarlett-face.svg"
:id 0}])
|
[
{
"context": " 3 4 5 6]))\n\n(expect {:surname \"Doe\"} (in {:name \"John\" :surname \"Doe\"}))\n\n(expect 3 (in #{1 2 3 4}))",
"end": 347,
"score": 0.9979872703552246,
"start": 343,
"tag": "NAME",
"value": "John"
},
{
"context": "pect {:surname \"Doe\"} (in {:name \"John\" :surname \"Doe\"}))\n\n(expect 3 (in #{1 2 3 4}))",
"end": 362,
"score": 0.9712545871734619,
"start": 359,
"tag": "NAME",
"value": "Doe"
}
] |
Chapter11/testing-example/test/testing_example/expectations_tests.clj
|
srufle/Hands-On-Reactive-Programming-with-Clojure-Second-Edition
| 15 |
(ns testing-example.expectations-tests
(:require [expectations :refer :all]
[testing-example.core :refer :all]))
(expect true (non-blank? "Some text"))
(expect ClassCastException (non-blank? 1234))
(expect Boolean (non-blank? ""))
(expect #"Dev" "DevOps")
(expect 2 (in [1 2 3 4 5 6]))
(expect {:surname "Doe"} (in {:name "John" :surname "Doe"}))
(expect 3 (in #{1 2 3 4}))
|
53194
|
(ns testing-example.expectations-tests
(:require [expectations :refer :all]
[testing-example.core :refer :all]))
(expect true (non-blank? "Some text"))
(expect ClassCastException (non-blank? 1234))
(expect Boolean (non-blank? ""))
(expect #"Dev" "DevOps")
(expect 2 (in [1 2 3 4 5 6]))
(expect {:surname "Doe"} (in {:name "<NAME>" :surname "<NAME>"}))
(expect 3 (in #{1 2 3 4}))
| true |
(ns testing-example.expectations-tests
(:require [expectations :refer :all]
[testing-example.core :refer :all]))
(expect true (non-blank? "Some text"))
(expect ClassCastException (non-blank? 1234))
(expect Boolean (non-blank? ""))
(expect #"Dev" "DevOps")
(expect 2 (in [1 2 3 4 5 6]))
(expect {:surname "Doe"} (in {:name "PI:NAME:<NAME>END_PI" :surname "PI:NAME:<NAME>END_PI"}))
(expect 3 (in #{1 2 3 4}))
|
[
{
"context": "nnection for java.jdbc \"raw\"\n; https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/Conne",
"end": 235,
"score": 0.9414791464805603,
"start": 228,
"tag": "USERNAME",
"value": "clojure"
},
{
"context": "seServerPrepStmts&cacheRSMetadata=true\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"})\n\n; Database con",
"end": 856,
"score": 0.9950584769248962,
"start": 841,
"tag": "USERNAME",
"value": "benchmarkdbuser"
},
{
"context": "ta=true\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"})\n\n; Database connection\n(defdb db (mysql {:subn",
"end": 887,
"score": 0.9994190335273743,
"start": 872,
"tag": "PASSWORD",
"value": "benchmarkdbpass"
},
{
"context": "ts&cacheRSMetadata=true\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n ",
"end": 1414,
"score": 0.9960196614265442,
"start": 1399,
"tag": "USERNAME",
"value": "benchmarkdbuser"
},
{
"context": "er \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n ;;OPTIONAL KEYS\n ",
"end": 1460,
"score": 0.9994196891784668,
"start": 1445,
"tag": "PASSWORD",
"value": "benchmarkdbpass"
},
{
"context": "ser spec))\n (.setPassword (:password spec))\n ;; expire excess connections aft",
"end": 1913,
"score": 0.499019056558609,
"start": 1909,
"tag": "PASSWORD",
"value": "spec"
}
] |
frameworks/Clojure/luminus/hello/src/hello/models/schema.clj
|
lhotari/FrameworkBenchmarks
| 4 |
(ns hello.models.schema
(:require [korma.db :refer [defdb mysql]]
[clojure.java.jdbc :as sql])
(:import com.mchange.v2.c3p0.ComboPooledDataSource))
; Database connection for java.jdbc "raw"
; https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/ConnectionPooling.md
(def db-spec-mysql-raw
{:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//localhost:3306/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true"
:user "benchmarkdbuser"
:password "benchmarkdbpass"})
; Database connection
(defdb db (mysql {:subname "//localhost:3306/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true"
:user "benchmarkdbuser"
:password "benchmarkdbpass"
;;OPTIONAL KEYS
:delimiters "" ;; remove delimiters
:maximum-pool-size 256
}))
(defn pool
[spec]
(let [cpds (doto (ComboPooledDataSource.)
(.setDriverClass (:classname spec))
(.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec)))
(.setUser (:user spec))
(.setPassword (:password spec))
;; expire excess connections after 30 minutes of inactivity:
(.setMaxIdleTimeExcessConnections (* 30 60))
;; expire connections after 3 hours of inactivity:
(.setMaxIdleTime (* 3 60 60)))]
{:datasource cpds}))
(def pooled-db (delay (pool db-spec-mysql-raw)))
(defn db-raw [] @pooled-db)
|
109291
|
(ns hello.models.schema
(:require [korma.db :refer [defdb mysql]]
[clojure.java.jdbc :as sql])
(:import com.mchange.v2.c3p0.ComboPooledDataSource))
; Database connection for java.jdbc "raw"
; https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/ConnectionPooling.md
(def db-spec-mysql-raw
{:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//localhost:3306/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true"
:user "benchmarkdbuser"
:password "<PASSWORD>"})
; Database connection
(defdb db (mysql {:subname "//localhost:3306/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true"
:user "benchmarkdbuser"
:password "<PASSWORD>"
;;OPTIONAL KEYS
:delimiters "" ;; remove delimiters
:maximum-pool-size 256
}))
(defn pool
[spec]
(let [cpds (doto (ComboPooledDataSource.)
(.setDriverClass (:classname spec))
(.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec)))
(.setUser (:user spec))
(.setPassword (:password <PASSWORD>))
;; expire excess connections after 30 minutes of inactivity:
(.setMaxIdleTimeExcessConnections (* 30 60))
;; expire connections after 3 hours of inactivity:
(.setMaxIdleTime (* 3 60 60)))]
{:datasource cpds}))
(def pooled-db (delay (pool db-spec-mysql-raw)))
(defn db-raw [] @pooled-db)
| true |
(ns hello.models.schema
(:require [korma.db :refer [defdb mysql]]
[clojure.java.jdbc :as sql])
(:import com.mchange.v2.c3p0.ComboPooledDataSource))
; Database connection for java.jdbc "raw"
; https://github.com/clojure/java.jdbc/blob/master/doc/clojure/java/jdbc/ConnectionPooling.md
(def db-spec-mysql-raw
{:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//localhost:3306/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true"
:user "benchmarkdbuser"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
; Database connection
(defdb db (mysql {:subname "//localhost:3306/hello_world?jdbcCompliantTruncation=false&elideSetAutoCommits=true&useLocalSessionState=true&cachePrepStmts=true&cacheCallableStmts=true&alwaysSendSetIsolation=false&prepStmtCacheSize=4096&cacheServerConfiguration=true&prepStmtCacheSqlLimit=2048&zeroDateTimeBehavior=convertToNull&traceProtocol=false&useUnbufferedInput=false&useReadAheadInput=false&maintainTimeStats=false&useServerPrepStmts&cacheRSMetadata=true"
:user "benchmarkdbuser"
:password "PI:PASSWORD:<PASSWORD>END_PI"
;;OPTIONAL KEYS
:delimiters "" ;; remove delimiters
:maximum-pool-size 256
}))
(defn pool
[spec]
(let [cpds (doto (ComboPooledDataSource.)
(.setDriverClass (:classname spec))
(.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec)))
(.setUser (:user spec))
(.setPassword (:password PI:PASSWORD:<PASSWORD>END_PI))
;; expire excess connections after 30 minutes of inactivity:
(.setMaxIdleTimeExcessConnections (* 30 60))
;; expire connections after 3 hours of inactivity:
(.setMaxIdleTime (* 3 60 60)))]
{:datasource cpds}))
(def pooled-db (delay (pool db-spec-mysql-raw)))
(defn db-raw [] @pooled-db)
|
[
{
"context": " :asserted 1615939200\n :by \"dac\"}\n :iat 1618617600}]]}\n ",
"end": 2597,
"score": 0.9770728945732117,
"start": 2594,
"tag": "USERNAME",
"value": "dac"
},
{
"context": " :userid \"elixir-user\"\n :app",
"end": 2775,
"score": 0.9924281239509583,
"start": 2764,
"tag": "USERNAME",
"value": "elixir-user"
},
{
"context": " :approvedby \"dac-user\"\n :sta",
"end": 2842,
"score": 0.9952960014343262,
"start": 2834,
"tag": "USERNAME",
"value": "dac-user"
},
{
"context": "erate-api-key-with-account\n \"Logs into EGA with `username` and `password` to fetch an access token, then ge",
"end": 5657,
"score": 0.9923750758171082,
"start": 5649,
"tag": "USERNAME",
"value": "username"
},
{
"context": "generate the key for\n `:username` - EGA user to use\n `:password` - EGA user passw",
"end": 5861,
"score": 0.7202587127685547,
"start": 5854,
"tag": "USERNAME",
"value": "GA user"
},
{
"context": "EGA token...\")\n access-token (-> {:username username\n :password password\n ",
"end": 6371,
"score": 0.9931157827377319,
"start": 6363,
"tag": "USERNAME",
"value": "username"
},
{
"context": "rname username\n :password password\n :config config}\n ",
"end": 6416,
"score": 0.9989367127418518,
"start": 6408,
"tag": "PASSWORD",
"value": "password"
}
] |
src/clj/rems/api/services/ega.clj
|
tjb/rems
| 31 |
(ns rems.api.services.ega
"Service for interfacing with EGA Permission API."
(:require [clj-time.core :as time-core]
[clojure.string :as str]
[clojure.test :refer [deftest is]]
[clojure.tools.logging :as log]
[medley.core :refer [find-first]]
[rems.config :refer [env]]
[rems.db.user-secrets :as user-secrets]
[rems.db.user-settings :as user-settings]
[rems.ext.ega :as ega]
[rems.ga4gh :as ga4gh]
[rems.util :refer [getx]]))
(defn get-ega-config
"Returns the EGA push configuration.
NB: This is currently limited to one EGA of configuration at a time."
[]
(let [config (find-first (comp #{:ega} :type) (:entitlement-push env))]
(assert (seq config) "EGA entitlement push must be configured!")
config))
(defn- get-api-key-for [handler-userid]
(get-in (user-secrets/get-user-secrets handler-userid) [:ega :api-key])) ; TODO: implement
(defn- get-dac-for [_resid _handler-userid]
"EGAC00001000908")
(defn- entitlement->update
"Converts an entitlement to a GA4GH visa for EGA.
`entitlement` – entitlement to convert
NB: the GA4GH signing keys will be required from the environment"
[entitlement]
{:format "JWT"
:visas (-> [{:resid (:resid entitlement)
:start (:start entitlement)
:end (:end entitlement)
:userid (:userid entitlement)
:dac-id (get-dac-for (:resid entitlement) (:approvedby entitlement))}]
ga4gh/entitlements->passport
:ga4gh_passport_v1)})
(deftest test-entitlement->update
(with-redefs [env (rems.config/load-keys {:public-url "https://rems.example/"
:ga4gh-visa-private-key "test-data/example-private-key.jwk"
:ga4gh-visa-public-key "test-data/example-public-key.jwk"})
time-core/now (fn [] (time-core/date-time 2021 04 17))] ; iat
(is (= {:format "JWT"
:visas [[{:alg "RS256"
:kid "2011-04-29"
:jku "https://rems.example/api/jwk"
:typ "JWT"}
{:sub "elixir-user"
:iss "https://rems.example/"
:exp 1647475200
:ga4gh_visa_v1
{:value "EGAD00001006673"
:type "ControlledAccessGrants"
:source "EGAC00001000908"
:asserted 1615939200
:by "dac"}
:iat 1618617600}]]}
(update-in (entitlement->update {:resid "EGAD00001006673"
:userid "elixir-user"
:approvedby "dac-user"
:start (time-core/date-time 2021 03 17)
:end (time-core/date-time 2022 03 17)})
[:visas 0]
ga4gh/visa->claims)))))
(defn entitlement-push [action entitlement config]
(let [api-key (get-api-key-for (:approvedby entitlement))
common-fields {:api-key api-key
:account-id (:userid entitlement)
:config config}]
(when (str/blank? api-key)
(log/warnf "Missing EGA api-key for %s" (:approvedby entitlement)))
(log/infof "Pushing entitlements to %s %s: %s %s" (getx config :id) (getx config :permission-server-url) entitlement config)
(case action
:add
(ega/post-create-or-update-permissions (merge common-fields
(entitlement->update entitlement)))
:remove
(ega/delete-permissions (merge common-fields
{:dataset-ids [(:resid entitlement)]})))))
(defn generate-api-key-with-access-token
"Generates an API-Key with `access-token` and saves it to the user's secrets.
`:userid` - REMS user to generate the key for
`:access-token` - User's ELIXIR access token
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid access-token config]}]
(assert userid "User missing!")
(try
(let [_ (log/info "Generate API-Key...")
expiration-date (time-core/plus (time-core/now) (time-core/years 1))
api-key (-> {:access-token access-token
:id userid
:expiration-date expiration-date
:reason "rems_ega_push"
:config config}
ega/get-api-key-generate
:body
:token)
_ (assert api-key)
_ (log/info "Save user secret...")
secrets-result (user-secrets/update-user-secrets! userid {:ega {:api-key api-key}})
_ (assert (:success secrets-result))
_ (log/info "Save user settings...")
settings-result (user-settings/update-user-settings! userid {:ega {:api-key-expiration-date expiration-date}})
_ (assert (:success settings-result))]
(log/info "Success!")
{:success true
:api-key-expiration-date expiration-date})
(catch Throwable t
(log/error t "Failure!")
{:success false})))
(defn generate-api-key-with-account
"Logs into EGA with `username` and `password` to fetch an access token, then generates an API-Key and saves it to the user's secrets.
`:userid` - REMS user to generate the key for
`:username` - EGA user to use
`:password` - EGA user password
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid username password config]}]
(assert userid "User missing!")
(let [_ (log/info "Get EGA token...")
access-token (-> {:username username
:password password
:config config}
ega/post-token
:body
:access_token)
_ (assert access-token)]
(generate-api-key-with-access-token {:userid userid
:access-token access-token
:config config})))
(defn delete-api-key
"Deletes the API-Key and removes it from the user's secrets.
`:userid` - REMS user to delete the key of
`:access-token` - User's ELIXIR access token
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid access-token config]}]
(assert userid "User missing!")
(try
(let [_ (log/info "Deleting API-Key...")
_result (-> {:access-token access-token
:id userid
:config config}
ega/delete-api-key-invalidate)
_ (log/info "Remove user secret...")
secrets-result (user-secrets/update-user-secrets! userid {:ega {}})
_ (assert (:success secrets-result))
_ (log/info "Remove user setting...")
settings-result (user-settings/update-user-settings! userid {:ega {}})
_ (assert (:success settings-result))]
(log/info "Success!")
{:success true})
(catch Throwable t
(do
(log/error t "Failure!")
{:success false}))))
|
42091
|
(ns rems.api.services.ega
"Service for interfacing with EGA Permission API."
(:require [clj-time.core :as time-core]
[clojure.string :as str]
[clojure.test :refer [deftest is]]
[clojure.tools.logging :as log]
[medley.core :refer [find-first]]
[rems.config :refer [env]]
[rems.db.user-secrets :as user-secrets]
[rems.db.user-settings :as user-settings]
[rems.ext.ega :as ega]
[rems.ga4gh :as ga4gh]
[rems.util :refer [getx]]))
(defn get-ega-config
"Returns the EGA push configuration.
NB: This is currently limited to one EGA of configuration at a time."
[]
(let [config (find-first (comp #{:ega} :type) (:entitlement-push env))]
(assert (seq config) "EGA entitlement push must be configured!")
config))
(defn- get-api-key-for [handler-userid]
(get-in (user-secrets/get-user-secrets handler-userid) [:ega :api-key])) ; TODO: implement
(defn- get-dac-for [_resid _handler-userid]
"EGAC00001000908")
(defn- entitlement->update
"Converts an entitlement to a GA4GH visa for EGA.
`entitlement` – entitlement to convert
NB: the GA4GH signing keys will be required from the environment"
[entitlement]
{:format "JWT"
:visas (-> [{:resid (:resid entitlement)
:start (:start entitlement)
:end (:end entitlement)
:userid (:userid entitlement)
:dac-id (get-dac-for (:resid entitlement) (:approvedby entitlement))}]
ga4gh/entitlements->passport
:ga4gh_passport_v1)})
(deftest test-entitlement->update
(with-redefs [env (rems.config/load-keys {:public-url "https://rems.example/"
:ga4gh-visa-private-key "test-data/example-private-key.jwk"
:ga4gh-visa-public-key "test-data/example-public-key.jwk"})
time-core/now (fn [] (time-core/date-time 2021 04 17))] ; iat
(is (= {:format "JWT"
:visas [[{:alg "RS256"
:kid "2011-04-29"
:jku "https://rems.example/api/jwk"
:typ "JWT"}
{:sub "elixir-user"
:iss "https://rems.example/"
:exp 1647475200
:ga4gh_visa_v1
{:value "EGAD00001006673"
:type "ControlledAccessGrants"
:source "EGAC00001000908"
:asserted 1615939200
:by "dac"}
:iat 1618617600}]]}
(update-in (entitlement->update {:resid "EGAD00001006673"
:userid "elixir-user"
:approvedby "dac-user"
:start (time-core/date-time 2021 03 17)
:end (time-core/date-time 2022 03 17)})
[:visas 0]
ga4gh/visa->claims)))))
(defn entitlement-push [action entitlement config]
(let [api-key (get-api-key-for (:approvedby entitlement))
common-fields {:api-key api-key
:account-id (:userid entitlement)
:config config}]
(when (str/blank? api-key)
(log/warnf "Missing EGA api-key for %s" (:approvedby entitlement)))
(log/infof "Pushing entitlements to %s %s: %s %s" (getx config :id) (getx config :permission-server-url) entitlement config)
(case action
:add
(ega/post-create-or-update-permissions (merge common-fields
(entitlement->update entitlement)))
:remove
(ega/delete-permissions (merge common-fields
{:dataset-ids [(:resid entitlement)]})))))
(defn generate-api-key-with-access-token
"Generates an API-Key with `access-token` and saves it to the user's secrets.
`:userid` - REMS user to generate the key for
`:access-token` - User's ELIXIR access token
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid access-token config]}]
(assert userid "User missing!")
(try
(let [_ (log/info "Generate API-Key...")
expiration-date (time-core/plus (time-core/now) (time-core/years 1))
api-key (-> {:access-token access-token
:id userid
:expiration-date expiration-date
:reason "rems_ega_push"
:config config}
ega/get-api-key-generate
:body
:token)
_ (assert api-key)
_ (log/info "Save user secret...")
secrets-result (user-secrets/update-user-secrets! userid {:ega {:api-key api-key}})
_ (assert (:success secrets-result))
_ (log/info "Save user settings...")
settings-result (user-settings/update-user-settings! userid {:ega {:api-key-expiration-date expiration-date}})
_ (assert (:success settings-result))]
(log/info "Success!")
{:success true
:api-key-expiration-date expiration-date})
(catch Throwable t
(log/error t "Failure!")
{:success false})))
(defn generate-api-key-with-account
"Logs into EGA with `username` and `password` to fetch an access token, then generates an API-Key and saves it to the user's secrets.
`:userid` - REMS user to generate the key for
`:username` - EGA user to use
`:password` - EGA user password
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid username password config]}]
(assert userid "User missing!")
(let [_ (log/info "Get EGA token...")
access-token (-> {:username username
:password <PASSWORD>
:config config}
ega/post-token
:body
:access_token)
_ (assert access-token)]
(generate-api-key-with-access-token {:userid userid
:access-token access-token
:config config})))
(defn delete-api-key
"Deletes the API-Key and removes it from the user's secrets.
`:userid` - REMS user to delete the key of
`:access-token` - User's ELIXIR access token
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid access-token config]}]
(assert userid "User missing!")
(try
(let [_ (log/info "Deleting API-Key...")
_result (-> {:access-token access-token
:id userid
:config config}
ega/delete-api-key-invalidate)
_ (log/info "Remove user secret...")
secrets-result (user-secrets/update-user-secrets! userid {:ega {}})
_ (assert (:success secrets-result))
_ (log/info "Remove user setting...")
settings-result (user-settings/update-user-settings! userid {:ega {}})
_ (assert (:success settings-result))]
(log/info "Success!")
{:success true})
(catch Throwable t
(do
(log/error t "Failure!")
{:success false}))))
| true |
(ns rems.api.services.ega
"Service for interfacing with EGA Permission API."
(:require [clj-time.core :as time-core]
[clojure.string :as str]
[clojure.test :refer [deftest is]]
[clojure.tools.logging :as log]
[medley.core :refer [find-first]]
[rems.config :refer [env]]
[rems.db.user-secrets :as user-secrets]
[rems.db.user-settings :as user-settings]
[rems.ext.ega :as ega]
[rems.ga4gh :as ga4gh]
[rems.util :refer [getx]]))
(defn get-ega-config
"Returns the EGA push configuration.
NB: This is currently limited to one EGA of configuration at a time."
[]
(let [config (find-first (comp #{:ega} :type) (:entitlement-push env))]
(assert (seq config) "EGA entitlement push must be configured!")
config))
(defn- get-api-key-for [handler-userid]
(get-in (user-secrets/get-user-secrets handler-userid) [:ega :api-key])) ; TODO: implement
(defn- get-dac-for [_resid _handler-userid]
"EGAC00001000908")
(defn- entitlement->update
"Converts an entitlement to a GA4GH visa for EGA.
`entitlement` – entitlement to convert
NB: the GA4GH signing keys will be required from the environment"
[entitlement]
{:format "JWT"
:visas (-> [{:resid (:resid entitlement)
:start (:start entitlement)
:end (:end entitlement)
:userid (:userid entitlement)
:dac-id (get-dac-for (:resid entitlement) (:approvedby entitlement))}]
ga4gh/entitlements->passport
:ga4gh_passport_v1)})
(deftest test-entitlement->update
(with-redefs [env (rems.config/load-keys {:public-url "https://rems.example/"
:ga4gh-visa-private-key "test-data/example-private-key.jwk"
:ga4gh-visa-public-key "test-data/example-public-key.jwk"})
time-core/now (fn [] (time-core/date-time 2021 04 17))] ; iat
(is (= {:format "JWT"
:visas [[{:alg "RS256"
:kid "2011-04-29"
:jku "https://rems.example/api/jwk"
:typ "JWT"}
{:sub "elixir-user"
:iss "https://rems.example/"
:exp 1647475200
:ga4gh_visa_v1
{:value "EGAD00001006673"
:type "ControlledAccessGrants"
:source "EGAC00001000908"
:asserted 1615939200
:by "dac"}
:iat 1618617600}]]}
(update-in (entitlement->update {:resid "EGAD00001006673"
:userid "elixir-user"
:approvedby "dac-user"
:start (time-core/date-time 2021 03 17)
:end (time-core/date-time 2022 03 17)})
[:visas 0]
ga4gh/visa->claims)))))
(defn entitlement-push [action entitlement config]
(let [api-key (get-api-key-for (:approvedby entitlement))
common-fields {:api-key api-key
:account-id (:userid entitlement)
:config config}]
(when (str/blank? api-key)
(log/warnf "Missing EGA api-key for %s" (:approvedby entitlement)))
(log/infof "Pushing entitlements to %s %s: %s %s" (getx config :id) (getx config :permission-server-url) entitlement config)
(case action
:add
(ega/post-create-or-update-permissions (merge common-fields
(entitlement->update entitlement)))
:remove
(ega/delete-permissions (merge common-fields
{:dataset-ids [(:resid entitlement)]})))))
(defn generate-api-key-with-access-token
"Generates an API-Key with `access-token` and saves it to the user's secrets.
`:userid` - REMS user to generate the key for
`:access-token` - User's ELIXIR access token
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid access-token config]}]
(assert userid "User missing!")
(try
(let [_ (log/info "Generate API-Key...")
expiration-date (time-core/plus (time-core/now) (time-core/years 1))
api-key (-> {:access-token access-token
:id userid
:expiration-date expiration-date
:reason "rems_ega_push"
:config config}
ega/get-api-key-generate
:body
:token)
_ (assert api-key)
_ (log/info "Save user secret...")
secrets-result (user-secrets/update-user-secrets! userid {:ega {:api-key api-key}})
_ (assert (:success secrets-result))
_ (log/info "Save user settings...")
settings-result (user-settings/update-user-settings! userid {:ega {:api-key-expiration-date expiration-date}})
_ (assert (:success settings-result))]
(log/info "Success!")
{:success true
:api-key-expiration-date expiration-date})
(catch Throwable t
(log/error t "Failure!")
{:success false})))
(defn generate-api-key-with-account
"Logs into EGA with `username` and `password` to fetch an access token, then generates an API-Key and saves it to the user's secrets.
`:userid` - REMS user to generate the key for
`:username` - EGA user to use
`:password` - EGA user password
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid username password config]}]
(assert userid "User missing!")
(let [_ (log/info "Get EGA token...")
access-token (-> {:username username
:password PI:PASSWORD:<PASSWORD>END_PI
:config config}
ega/post-token
:body
:access_token)
_ (assert access-token)]
(generate-api-key-with-access-token {:userid userid
:access-token access-token
:config config})))
(defn delete-api-key
"Deletes the API-Key and removes it from the user's secrets.
`:userid` - REMS user to delete the key of
`:access-token` - User's ELIXIR access token
`:config` - configuration of the EGA integration with following keys:
`:connect-server-url` - EGA login server url
`:permission-server-url` - EGA permission server url
`:client-id` - client id for REMS
`:client-secret` - client secret for REMS"
[{:keys [userid access-token config]}]
(assert userid "User missing!")
(try
(let [_ (log/info "Deleting API-Key...")
_result (-> {:access-token access-token
:id userid
:config config}
ega/delete-api-key-invalidate)
_ (log/info "Remove user secret...")
secrets-result (user-secrets/update-user-secrets! userid {:ega {}})
_ (assert (:success secrets-result))
_ (log/info "Remove user setting...")
settings-result (user-settings/update-user-settings! userid {:ega {}})
_ (assert (:success settings-result))]
(log/info "Success!")
{:success true})
(catch Throwable t
(do
(log/error t "Failure!")
{:success false}))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\r\n; The use and distributi",
"end": 30,
"score": 0.9997779130935669,
"start": 19,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "ious tests in the Clojure\r\n;; test suite\r\n;;\r\n;; tomfaulhaber (gmail)\r\n;; Created 04 November 2010\r\n\r\n(ns cloj",
"end": 603,
"score": 0.9940571784973145,
"start": 591,
"tag": "USERNAME",
"value": "tomfaulhaber"
}
] |
Source/clojure/test_helper.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.
;
;; clojure.test-helper
;;
;; Utility functions shared by various tests in the Clojure
;; test suite
;;
;; tomfaulhaber (gmail)
;; Created 04 November 2010
(ns clojure.test-helper
(:use clojure.test)
(:import (System.Reflection BindingFlags))) ;;; added import
(let [nl Environment/NewLine] ;;; (System/getProperty "line.separator")]
(defn platform-newlines [s] (.Replace s "\n" nl))) ;;; .replace
(defn temp-ns
"Create and return a temporary ns, using clojure.core + uses"
[& uses]
(binding [*ns* *ns*]
(in-ns (gensym))
(apply clojure.core/use 'clojure.core uses)
*ns*))
(defmacro eval-in-temp-ns [& forms]
`(binding [*ns* *ns*]
(in-ns (gensym))
(clojure.core/use 'clojure.core)
(eval
'(do ~@forms))))
(defn causes
[^Exception throwable] ;;; Throwable
(loop [causes []
t throwable]
(if t (recur (conj causes t) (.InnerException t)) causes))) ;;; .getCause
;; this is how I wish clojure.test/thrown? worked...
;; Does body throw expected exception, anywhere in the .getCause chain?
(defmethod assert-expr 'fails-with-cause?
[msg [_ exception-class msg-re & body :as form]]
`(try
~@body
(report {:type :fail, :message ~msg, :expected '~form, :actual nil})
(catch Exception t# ;;; Throwable
(if (some (fn [cause#]
(and
(= ~exception-class (class cause#))
(re-find ~msg-re (.Message cause#)))) ;;; .getMessage
(causes t#))
(report {:type :pass, :message ~msg,
:expected '~form, :actual t#})
(report {:type :fail, :message ~msg,
:expected '~form, :actual t#})))))
(defn get-field
"Access to private or protected field. field-name is a symbol or
keyword."
([klass field-name]
(get-field klass field-name nil))
([klass field-name inst]
(-> klass (.GetField (name field-name) (enum-or BindingFlags/Public BindingFlags/NonPublic BindingFlags/DeclaredOnly BindingFlags/Instance BindingFlags/Static)) ;;; (.getDeclaredField (name field-name))
;;;(doto (.setAccessible true))
(.GetValue inst)))) ;;; .get
(defn set-var-roots
[maplike]
(doseq [[var val] maplike]
(alter-var-root var (fn [_] val))))
(defn with-var-roots*
"Temporarily set var roots, run block, then put original roots back."
[root-map f & args]
(let [originals (doall (map (fn [[var _]] [var @var]) root-map))]
(set-var-roots root-map)
(try
(apply f args)
(finally
(set-var-roots originals)))))
(defmacro with-var-roots
[root-map & body]
`(with-var-roots* ~root-map (fn [] ~@body)))
(defn exception
"Use this function to ensure that execution of a program doesn't
reach certain point."
[]
(throw (new Exception "Exception which should never occur")))
(defmacro with-err-print-writer
"Evaluate with err pointing to a temporary PrintWriter, and
return err contents as a string."
[& body]
`(let [s# (System.IO.StringWriter.) ;;; java.io.StringWriter.
p# s#] ;;; not needed: (java.io.PrintWriter. s#)]
(binding [*err* p#]
~@body
(str s#))))
(defmacro with-err-string-writer
"Evaluate with err pointing to a temporary StringWriter, and
return err contents as a string."
[& body]
`(let [s# (System.IO.StringWriter.)] ;;; java.io.StringWriter.
(binding [*err* s#]
~@body
(str s#))))
(defmacro should-print-err-message
"Turn on all warning flags, and test that error message prints
correctly for all semi-reasonable bindings of *err*."
[msg-re form]
`(binding [*warn-on-reflection* true]
(is (re-matches ~msg-re (with-err-string-writer (eval-in-temp-ns ~form))))
(is (re-matches ~msg-re (with-err-print-writer (eval-in-temp-ns ~form))))))
(defmacro should-not-reflect
"Turn on all warning flags, and test that reflection does not occur
(as identified by messages to *err*)."
[form]
`(binding [*warn-on-reflection* true]
(is (nil? (re-find #"^Reflection warning" (with-err-string-writer (eval-in-temp-ns ~form)))))
(is (nil? (re-find #"^Reflection warning" (with-err-print-writer (eval-in-temp-ns ~form)))))))
|
113426
|
; 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.
;
;; clojure.test-helper
;;
;; Utility functions shared by various tests in the Clojure
;; test suite
;;
;; tomfaulhaber (gmail)
;; Created 04 November 2010
(ns clojure.test-helper
(:use clojure.test)
(:import (System.Reflection BindingFlags))) ;;; added import
(let [nl Environment/NewLine] ;;; (System/getProperty "line.separator")]
(defn platform-newlines [s] (.Replace s "\n" nl))) ;;; .replace
(defn temp-ns
"Create and return a temporary ns, using clojure.core + uses"
[& uses]
(binding [*ns* *ns*]
(in-ns (gensym))
(apply clojure.core/use 'clojure.core uses)
*ns*))
(defmacro eval-in-temp-ns [& forms]
`(binding [*ns* *ns*]
(in-ns (gensym))
(clojure.core/use 'clojure.core)
(eval
'(do ~@forms))))
(defn causes
[^Exception throwable] ;;; Throwable
(loop [causes []
t throwable]
(if t (recur (conj causes t) (.InnerException t)) causes))) ;;; .getCause
;; this is how I wish clojure.test/thrown? worked...
;; Does body throw expected exception, anywhere in the .getCause chain?
(defmethod assert-expr 'fails-with-cause?
[msg [_ exception-class msg-re & body :as form]]
`(try
~@body
(report {:type :fail, :message ~msg, :expected '~form, :actual nil})
(catch Exception t# ;;; Throwable
(if (some (fn [cause#]
(and
(= ~exception-class (class cause#))
(re-find ~msg-re (.Message cause#)))) ;;; .getMessage
(causes t#))
(report {:type :pass, :message ~msg,
:expected '~form, :actual t#})
(report {:type :fail, :message ~msg,
:expected '~form, :actual t#})))))
(defn get-field
"Access to private or protected field. field-name is a symbol or
keyword."
([klass field-name]
(get-field klass field-name nil))
([klass field-name inst]
(-> klass (.GetField (name field-name) (enum-or BindingFlags/Public BindingFlags/NonPublic BindingFlags/DeclaredOnly BindingFlags/Instance BindingFlags/Static)) ;;; (.getDeclaredField (name field-name))
;;;(doto (.setAccessible true))
(.GetValue inst)))) ;;; .get
(defn set-var-roots
[maplike]
(doseq [[var val] maplike]
(alter-var-root var (fn [_] val))))
(defn with-var-roots*
"Temporarily set var roots, run block, then put original roots back."
[root-map f & args]
(let [originals (doall (map (fn [[var _]] [var @var]) root-map))]
(set-var-roots root-map)
(try
(apply f args)
(finally
(set-var-roots originals)))))
(defmacro with-var-roots
[root-map & body]
`(with-var-roots* ~root-map (fn [] ~@body)))
(defn exception
"Use this function to ensure that execution of a program doesn't
reach certain point."
[]
(throw (new Exception "Exception which should never occur")))
(defmacro with-err-print-writer
"Evaluate with err pointing to a temporary PrintWriter, and
return err contents as a string."
[& body]
`(let [s# (System.IO.StringWriter.) ;;; java.io.StringWriter.
p# s#] ;;; not needed: (java.io.PrintWriter. s#)]
(binding [*err* p#]
~@body
(str s#))))
(defmacro with-err-string-writer
"Evaluate with err pointing to a temporary StringWriter, and
return err contents as a string."
[& body]
`(let [s# (System.IO.StringWriter.)] ;;; java.io.StringWriter.
(binding [*err* s#]
~@body
(str s#))))
(defmacro should-print-err-message
"Turn on all warning flags, and test that error message prints
correctly for all semi-reasonable bindings of *err*."
[msg-re form]
`(binding [*warn-on-reflection* true]
(is (re-matches ~msg-re (with-err-string-writer (eval-in-temp-ns ~form))))
(is (re-matches ~msg-re (with-err-print-writer (eval-in-temp-ns ~form))))))
(defmacro should-not-reflect
"Turn on all warning flags, and test that reflection does not occur
(as identified by messages to *err*)."
[form]
`(binding [*warn-on-reflection* true]
(is (nil? (re-find #"^Reflection warning" (with-err-string-writer (eval-in-temp-ns ~form)))))
(is (nil? (re-find #"^Reflection warning" (with-err-print-writer (eval-in-temp-ns ~form)))))))
| 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.
;
;; clojure.test-helper
;;
;; Utility functions shared by various tests in the Clojure
;; test suite
;;
;; tomfaulhaber (gmail)
;; Created 04 November 2010
(ns clojure.test-helper
(:use clojure.test)
(:import (System.Reflection BindingFlags))) ;;; added import
(let [nl Environment/NewLine] ;;; (System/getProperty "line.separator")]
(defn platform-newlines [s] (.Replace s "\n" nl))) ;;; .replace
(defn temp-ns
"Create and return a temporary ns, using clojure.core + uses"
[& uses]
(binding [*ns* *ns*]
(in-ns (gensym))
(apply clojure.core/use 'clojure.core uses)
*ns*))
(defmacro eval-in-temp-ns [& forms]
`(binding [*ns* *ns*]
(in-ns (gensym))
(clojure.core/use 'clojure.core)
(eval
'(do ~@forms))))
(defn causes
[^Exception throwable] ;;; Throwable
(loop [causes []
t throwable]
(if t (recur (conj causes t) (.InnerException t)) causes))) ;;; .getCause
;; this is how I wish clojure.test/thrown? worked...
;; Does body throw expected exception, anywhere in the .getCause chain?
(defmethod assert-expr 'fails-with-cause?
[msg [_ exception-class msg-re & body :as form]]
`(try
~@body
(report {:type :fail, :message ~msg, :expected '~form, :actual nil})
(catch Exception t# ;;; Throwable
(if (some (fn [cause#]
(and
(= ~exception-class (class cause#))
(re-find ~msg-re (.Message cause#)))) ;;; .getMessage
(causes t#))
(report {:type :pass, :message ~msg,
:expected '~form, :actual t#})
(report {:type :fail, :message ~msg,
:expected '~form, :actual t#})))))
(defn get-field
"Access to private or protected field. field-name is a symbol or
keyword."
([klass field-name]
(get-field klass field-name nil))
([klass field-name inst]
(-> klass (.GetField (name field-name) (enum-or BindingFlags/Public BindingFlags/NonPublic BindingFlags/DeclaredOnly BindingFlags/Instance BindingFlags/Static)) ;;; (.getDeclaredField (name field-name))
;;;(doto (.setAccessible true))
(.GetValue inst)))) ;;; .get
(defn set-var-roots
[maplike]
(doseq [[var val] maplike]
(alter-var-root var (fn [_] val))))
(defn with-var-roots*
"Temporarily set var roots, run block, then put original roots back."
[root-map f & args]
(let [originals (doall (map (fn [[var _]] [var @var]) root-map))]
(set-var-roots root-map)
(try
(apply f args)
(finally
(set-var-roots originals)))))
(defmacro with-var-roots
[root-map & body]
`(with-var-roots* ~root-map (fn [] ~@body)))
(defn exception
"Use this function to ensure that execution of a program doesn't
reach certain point."
[]
(throw (new Exception "Exception which should never occur")))
(defmacro with-err-print-writer
"Evaluate with err pointing to a temporary PrintWriter, and
return err contents as a string."
[& body]
`(let [s# (System.IO.StringWriter.) ;;; java.io.StringWriter.
p# s#] ;;; not needed: (java.io.PrintWriter. s#)]
(binding [*err* p#]
~@body
(str s#))))
(defmacro with-err-string-writer
"Evaluate with err pointing to a temporary StringWriter, and
return err contents as a string."
[& body]
`(let [s# (System.IO.StringWriter.)] ;;; java.io.StringWriter.
(binding [*err* s#]
~@body
(str s#))))
(defmacro should-print-err-message
"Turn on all warning flags, and test that error message prints
correctly for all semi-reasonable bindings of *err*."
[msg-re form]
`(binding [*warn-on-reflection* true]
(is (re-matches ~msg-re (with-err-string-writer (eval-in-temp-ns ~form))))
(is (re-matches ~msg-re (with-err-print-writer (eval-in-temp-ns ~form))))))
(defmacro should-not-reflect
"Turn on all warning flags, and test that reflection does not occur
(as identified by messages to *err*)."
[form]
`(binding [*warn-on-reflection* true]
(is (nil? (re-find #"^Reflection warning" (with-err-string-writer (eval-in-temp-ns ~form)))))
(is (nil? (re-find #"^Reflection warning" (with-err-print-writer (eval-in-temp-ns ~form)))))))
|
[
{
"context": "-------------------------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzz",
"end": 212,
"score": 0.9998458027839661,
"start": 196,
"tag": "NAME",
"value": "PLIQUE Guillaume"
},
{
"context": "------------\n;;\n;;\n;; Author: PLIQUE Guillaume (Yomguithereal)\n;; Version: 0.1\n;;\n(ns clj-fuzzy.jaro-winkler)",
"end": 227,
"score": 0.9991621375083923,
"start": 214,
"tag": "USERNAME",
"value": "Yomguithereal"
}
] |
src/clj_fuzzy/jaro_winkler.cljc
|
sooheon/clj-fuzzy
| 222 |
;; -------------------------------------------------------------------
;; clj-fuzzy Jaro-Winkler Distance
;; -------------------------------------------------------------------
;;
;;
;; Author: PLIQUE Guillaume (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.jaro-winkler)
;; Utilities
;; OPTIMIZE: I cannot believe this is the most efficient way to do it
(defn- longest-sequence [seq1 seq2]
(if (>= (count seq1) (count seq2))
[seq1 seq2]
[seq2 seq1]))
(defn- match-window [min-len] (max (dec (int (/ min-len 2))) 0))
(defn- submatch [i ch shortest window-start window-end seq1-matches seq2-matches]
(loop [j window-start
nseq1-matches seq1-matches
nseq2-matches seq2-matches]
(if (and ((complement nil?) j)
(< j window-end))
(if (and (not (get seq2-matches j))
(= ch (get shortest j)))
(recur nil
(assoc nseq1-matches i ch)
(assoc nseq2-matches j (get shortest j)))
(recur (inc j) nseq1-matches nseq2-matches))
[nseq1-matches nseq2-matches])))
(defn- matches [seq1 seq2]
(let [[longest shortest] (longest-sequence seq1 seq2)
max-len (count longest)
min-len (count shortest)
mwindow (match-window max-len)]
(loop [i 0
seq1-matches (vec (repeat max-len nil))
seq2-matches (vec (repeat max-len nil))]
(if (< i max-len)
;; Recur
(let [window-start (max (- i mwindow) 0)
window-end (min (+ i mwindow 1) min-len)
[nseq1-matches nseq2-matches] (submatch i
(get longest i)
shortest
window-start
window-end
seq1-matches
seq2-matches)]
(recur (inc i) nseq1-matches nseq2-matches))
;; Return
[(remove nil? seq1-matches) (remove nil? seq2-matches)]))))
(defn- transpositions [longest-matches shortest-matches]
(let [pad (- (count longest-matches) (count shortest-matches))
comparison (partition 2 (interleave longest-matches
(concat shortest-matches (repeat pad nil))))]
(/ (count (filter #(not= (first %) (second %)) comparison)) 2)))
(defn- winkler-prefix [seq1 seq2]
(loop [i 0
prefix 0]
(if (< i 4)
(if (= (get seq1 i) (get seq2 i))
(recur (inc i) (inc prefix))
(recur 5 prefix))
prefix)))
;; Main Functions
(defn jaro
"Compute the Jaro distance between two sequences."
[seq1 seq2]
(let [[longest-matches shortest-matches] (matches seq1 seq2)
m (count longest-matches)
t (transpositions longest-matches shortest-matches)]
(if (zero? m)
0
(/ (+ (/ m (count seq1))
(/ m (count seq2))
(/ (- m t) m))
3.0))))
(defn jaro-winkler
"Compute the Jaro-Winkler distance between two sequences."
[seq1 seq2]
(let [j (jaro seq1 seq2)
l (winkler-prefix seq1 seq2)
p 0.1]
(+ j (* l p (- 1 j)))))
|
25082
|
;; -------------------------------------------------------------------
;; clj-fuzzy Jaro-Winkler Distance
;; -------------------------------------------------------------------
;;
;;
;; Author: <NAME> (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.jaro-winkler)
;; Utilities
;; OPTIMIZE: I cannot believe this is the most efficient way to do it
(defn- longest-sequence [seq1 seq2]
(if (>= (count seq1) (count seq2))
[seq1 seq2]
[seq2 seq1]))
(defn- match-window [min-len] (max (dec (int (/ min-len 2))) 0))
(defn- submatch [i ch shortest window-start window-end seq1-matches seq2-matches]
(loop [j window-start
nseq1-matches seq1-matches
nseq2-matches seq2-matches]
(if (and ((complement nil?) j)
(< j window-end))
(if (and (not (get seq2-matches j))
(= ch (get shortest j)))
(recur nil
(assoc nseq1-matches i ch)
(assoc nseq2-matches j (get shortest j)))
(recur (inc j) nseq1-matches nseq2-matches))
[nseq1-matches nseq2-matches])))
(defn- matches [seq1 seq2]
(let [[longest shortest] (longest-sequence seq1 seq2)
max-len (count longest)
min-len (count shortest)
mwindow (match-window max-len)]
(loop [i 0
seq1-matches (vec (repeat max-len nil))
seq2-matches (vec (repeat max-len nil))]
(if (< i max-len)
;; Recur
(let [window-start (max (- i mwindow) 0)
window-end (min (+ i mwindow 1) min-len)
[nseq1-matches nseq2-matches] (submatch i
(get longest i)
shortest
window-start
window-end
seq1-matches
seq2-matches)]
(recur (inc i) nseq1-matches nseq2-matches))
;; Return
[(remove nil? seq1-matches) (remove nil? seq2-matches)]))))
(defn- transpositions [longest-matches shortest-matches]
(let [pad (- (count longest-matches) (count shortest-matches))
comparison (partition 2 (interleave longest-matches
(concat shortest-matches (repeat pad nil))))]
(/ (count (filter #(not= (first %) (second %)) comparison)) 2)))
(defn- winkler-prefix [seq1 seq2]
(loop [i 0
prefix 0]
(if (< i 4)
(if (= (get seq1 i) (get seq2 i))
(recur (inc i) (inc prefix))
(recur 5 prefix))
prefix)))
;; Main Functions
(defn jaro
"Compute the Jaro distance between two sequences."
[seq1 seq2]
(let [[longest-matches shortest-matches] (matches seq1 seq2)
m (count longest-matches)
t (transpositions longest-matches shortest-matches)]
(if (zero? m)
0
(/ (+ (/ m (count seq1))
(/ m (count seq2))
(/ (- m t) m))
3.0))))
(defn jaro-winkler
"Compute the Jaro-Winkler distance between two sequences."
[seq1 seq2]
(let [j (jaro seq1 seq2)
l (winkler-prefix seq1 seq2)
p 0.1]
(+ j (* l p (- 1 j)))))
| true |
;; -------------------------------------------------------------------
;; clj-fuzzy Jaro-Winkler Distance
;; -------------------------------------------------------------------
;;
;;
;; Author: PI:NAME:<NAME>END_PI (Yomguithereal)
;; Version: 0.1
;;
(ns clj-fuzzy.jaro-winkler)
;; Utilities
;; OPTIMIZE: I cannot believe this is the most efficient way to do it
(defn- longest-sequence [seq1 seq2]
(if (>= (count seq1) (count seq2))
[seq1 seq2]
[seq2 seq1]))
(defn- match-window [min-len] (max (dec (int (/ min-len 2))) 0))
(defn- submatch [i ch shortest window-start window-end seq1-matches seq2-matches]
(loop [j window-start
nseq1-matches seq1-matches
nseq2-matches seq2-matches]
(if (and ((complement nil?) j)
(< j window-end))
(if (and (not (get seq2-matches j))
(= ch (get shortest j)))
(recur nil
(assoc nseq1-matches i ch)
(assoc nseq2-matches j (get shortest j)))
(recur (inc j) nseq1-matches nseq2-matches))
[nseq1-matches nseq2-matches])))
(defn- matches [seq1 seq2]
(let [[longest shortest] (longest-sequence seq1 seq2)
max-len (count longest)
min-len (count shortest)
mwindow (match-window max-len)]
(loop [i 0
seq1-matches (vec (repeat max-len nil))
seq2-matches (vec (repeat max-len nil))]
(if (< i max-len)
;; Recur
(let [window-start (max (- i mwindow) 0)
window-end (min (+ i mwindow 1) min-len)
[nseq1-matches nseq2-matches] (submatch i
(get longest i)
shortest
window-start
window-end
seq1-matches
seq2-matches)]
(recur (inc i) nseq1-matches nseq2-matches))
;; Return
[(remove nil? seq1-matches) (remove nil? seq2-matches)]))))
(defn- transpositions [longest-matches shortest-matches]
(let [pad (- (count longest-matches) (count shortest-matches))
comparison (partition 2 (interleave longest-matches
(concat shortest-matches (repeat pad nil))))]
(/ (count (filter #(not= (first %) (second %)) comparison)) 2)))
(defn- winkler-prefix [seq1 seq2]
(loop [i 0
prefix 0]
(if (< i 4)
(if (= (get seq1 i) (get seq2 i))
(recur (inc i) (inc prefix))
(recur 5 prefix))
prefix)))
;; Main Functions
(defn jaro
"Compute the Jaro distance between two sequences."
[seq1 seq2]
(let [[longest-matches shortest-matches] (matches seq1 seq2)
m (count longest-matches)
t (transpositions longest-matches shortest-matches)]
(if (zero? m)
0
(/ (+ (/ m (count seq1))
(/ m (count seq2))
(/ (- m t) m))
3.0))))
(defn jaro-winkler
"Compute the Jaro-Winkler distance between two sequences."
[seq1 seq2]
(let [j (jaro seq1 seq2)
l (winkler-prefix seq1 seq2)
p 0.1]
(+ j (* l p (- 1 j)))))
|
[
{
"context": " :fontSize \"250%\"}}\n \"HETAIRA\")}))\n (ui-grid-row\n {:colum",
"end": 1592,
"score": 0.5223305821418762,
"start": 1589,
"tag": "NAME",
"value": "ETA"
}
] |
src/cljs/etaira/ui/ico/whitepaper.cljs
|
okilimnik/etaira-web
| 0 |
(ns etaira.ui.ico.whitepaper
(:require
[com.fulcrologic.fulcro.dom :as dom :refer [div span br button h3 p a h2 img]]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[oops.core :refer [oget]]
[com.fulcrologic.semantic-ui.elements.button.ui-button :refer [ui-button]]
[com.fulcrologic.semantic-ui.elements.button.ui-button-content :refer [ui-button-content]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid :refer [ui-grid]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid-column :refer [ui-grid-column]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid-row :refer [ui-grid-row]]
[com.fulcrologic.semantic-ui.elements.image.ui-image :refer [ui-image]]))
(defn white-paper-b []
(div {:style {:backgroundColor "#00ffff"
:width "100%"
:display "block"
:padding "100px 0"}}
(ui-grid
{:stackable true}
(ui-grid-row
{:columns 1
:textAlign "center"}
(ui-grid-column
{:children
(ui-image {:src "/css/themes/default/assets/images/hetaira2.jpg"
:centered true
:style {:width "400px"
;;:minHeight "100%"
:opacity 0.4}})}))
(ui-grid-row
{:columns 1
:textAlign "center"}
(ui-grid-column
{:children (h2 {:style
{:color "#013220"
:fontSize "250%"}}
"HETAIRA")}))
(ui-grid-row
{:columns 2
:divided true
:centered true
:textAlign "center"}
(ui-grid-column
{:width 4
:textAlign "center"
:children (a {:href "https://docs.google.com/document/d/1oh658BCoAFP_toO3uHDXoesPRiBVJmTcgpjHY8lDM9k/edit?usp=sharing"}
(ui-button {:animated true
:circular true
:fluid true
:color "green"
:size "huge"}
(ui-button-content {:content (span {:style {:color "#013220"}} "Whitepaper")
:visible true})
(ui-button-content {:content (span {:style {:color "#013220"}} "Click please")
:hidden true})))})
(ui-grid-column
{:width 4
:textAlign "center"
:children (a {:href "https://docs.google.com/document/d/1RSea_dEQ9xBE4W6JyeQ6pltLnYb9XPSgid9GDpT8vPo/edit?usp=sharing"}
(ui-button {:animated true
:circular true
:fluid true
:color "green"
:size "huge"}
(ui-button-content {:content (span {:style {:color "#013220"}} "Documentation")
:visible true})
(ui-button-content {:content (span {:style {:color "#013220"}} "Read more")
:hidden true})))})))))
|
123645
|
(ns etaira.ui.ico.whitepaper
(:require
[com.fulcrologic.fulcro.dom :as dom :refer [div span br button h3 p a h2 img]]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[oops.core :refer [oget]]
[com.fulcrologic.semantic-ui.elements.button.ui-button :refer [ui-button]]
[com.fulcrologic.semantic-ui.elements.button.ui-button-content :refer [ui-button-content]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid :refer [ui-grid]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid-column :refer [ui-grid-column]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid-row :refer [ui-grid-row]]
[com.fulcrologic.semantic-ui.elements.image.ui-image :refer [ui-image]]))
(defn white-paper-b []
(div {:style {:backgroundColor "#00ffff"
:width "100%"
:display "block"
:padding "100px 0"}}
(ui-grid
{:stackable true}
(ui-grid-row
{:columns 1
:textAlign "center"}
(ui-grid-column
{:children
(ui-image {:src "/css/themes/default/assets/images/hetaira2.jpg"
:centered true
:style {:width "400px"
;;:minHeight "100%"
:opacity 0.4}})}))
(ui-grid-row
{:columns 1
:textAlign "center"}
(ui-grid-column
{:children (h2 {:style
{:color "#013220"
:fontSize "250%"}}
"H<NAME>IRA")}))
(ui-grid-row
{:columns 2
:divided true
:centered true
:textAlign "center"}
(ui-grid-column
{:width 4
:textAlign "center"
:children (a {:href "https://docs.google.com/document/d/1oh658BCoAFP_toO3uHDXoesPRiBVJmTcgpjHY8lDM9k/edit?usp=sharing"}
(ui-button {:animated true
:circular true
:fluid true
:color "green"
:size "huge"}
(ui-button-content {:content (span {:style {:color "#013220"}} "Whitepaper")
:visible true})
(ui-button-content {:content (span {:style {:color "#013220"}} "Click please")
:hidden true})))})
(ui-grid-column
{:width 4
:textAlign "center"
:children (a {:href "https://docs.google.com/document/d/1RSea_dEQ9xBE4W6JyeQ6pltLnYb9XPSgid9GDpT8vPo/edit?usp=sharing"}
(ui-button {:animated true
:circular true
:fluid true
:color "green"
:size "huge"}
(ui-button-content {:content (span {:style {:color "#013220"}} "Documentation")
:visible true})
(ui-button-content {:content (span {:style {:color "#013220"}} "Read more")
:hidden true})))})))))
| true |
(ns etaira.ui.ico.whitepaper
(:require
[com.fulcrologic.fulcro.dom :as dom :refer [div span br button h3 p a h2 img]]
[com.fulcrologic.fulcro.algorithms.react-interop :as interop]
[oops.core :refer [oget]]
[com.fulcrologic.semantic-ui.elements.button.ui-button :refer [ui-button]]
[com.fulcrologic.semantic-ui.elements.button.ui-button-content :refer [ui-button-content]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid :refer [ui-grid]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid-column :refer [ui-grid-column]]
[com.fulcrologic.semantic-ui.collections.grid.ui-grid-row :refer [ui-grid-row]]
[com.fulcrologic.semantic-ui.elements.image.ui-image :refer [ui-image]]))
(defn white-paper-b []
(div {:style {:backgroundColor "#00ffff"
:width "100%"
:display "block"
:padding "100px 0"}}
(ui-grid
{:stackable true}
(ui-grid-row
{:columns 1
:textAlign "center"}
(ui-grid-column
{:children
(ui-image {:src "/css/themes/default/assets/images/hetaira2.jpg"
:centered true
:style {:width "400px"
;;:minHeight "100%"
:opacity 0.4}})}))
(ui-grid-row
{:columns 1
:textAlign "center"}
(ui-grid-column
{:children (h2 {:style
{:color "#013220"
:fontSize "250%"}}
"HPI:NAME:<NAME>END_PIIRA")}))
(ui-grid-row
{:columns 2
:divided true
:centered true
:textAlign "center"}
(ui-grid-column
{:width 4
:textAlign "center"
:children (a {:href "https://docs.google.com/document/d/1oh658BCoAFP_toO3uHDXoesPRiBVJmTcgpjHY8lDM9k/edit?usp=sharing"}
(ui-button {:animated true
:circular true
:fluid true
:color "green"
:size "huge"}
(ui-button-content {:content (span {:style {:color "#013220"}} "Whitepaper")
:visible true})
(ui-button-content {:content (span {:style {:color "#013220"}} "Click please")
:hidden true})))})
(ui-grid-column
{:width 4
:textAlign "center"
:children (a {:href "https://docs.google.com/document/d/1RSea_dEQ9xBE4W6JyeQ6pltLnYb9XPSgid9GDpT8vPo/edit?usp=sharing"}
(ui-button {:animated true
:circular true
:fluid true
:color "green"
:size "huge"}
(ui-button-content {:content (span {:style {:color "#013220"}} "Documentation")
:visible true})
(ui-button-content {:content (span {:style {:color "#013220"}} "Read more")
:hidden true})))})))))
|
[
{
"context": ";; Copyright (c) James Reeves. All rights reserved.\n;; The use and distribution",
"end": 29,
"score": 0.999876856803894,
"start": 17,
"tag": "NAME",
"value": "James Reeves"
}
] |
data/clojure/0c05c0587968545c39572ab7993bd156_crypto.clj
|
maxim5/code-inspector
| 5 |
;; Copyright (c) James Reeves. 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 compojure.crypto
"Functions for cryptographically signing, verifying and encrypting data."
(:use compojure.encodings)
(:import java.security.SecureRandom)
(:import javax.crypto.Cipher)
(:import javax.crypto.KeyGenerator)
(:import javax.crypto.Mac)
(:import javax.crypto.spec.SecretKeySpec)
(:import javax.crypto.spec.IvParameterSpec)
(:import java.util.UUID))
(defn hmac
"Generate a hashed message authentication code with the supplied key and
algorithm on some string data."
[key algorithm data]
(let [spec (SecretKeySpec. key algorithm)
mac (doto (Mac/getInstance algorithm)
(.init spec))
bytes (.doFinal mac (.getBytes data))]
(base64-encode-bytes bytes)))
(defn gen-uuid
"Generate a random UUID."
[]
(str (UUID/randomUUID)))
(defn strict-seq=
"Like = for sequences, but always check every value in a sequence."
[x y]
(loop [f1 (first x) f2 (first y)
n1 (next x) n2 (next y)
a true]
(if (and n1 n2)
(recur (first n1) (first n2)
(next n1) (next n2)
(and (= f1 f2) a))
(and (= (count x) (count y)) a))))
(defn secure-random-bytes
"Returns a random byte array of the specified size and algorithm.
Defaults to SHA1PRNG."
([size] (secure-random-bytes size "SHA1PRNG"))
([size algorithm]
(let [seed (make-array (. Byte TYPE) size)]
(.nextBytes (SecureRandom/getInstance algorithm) seed)
seed)))
(defn gen-iv-param
"Generates a random IvParameterSpec for use with CBC encryption algorithms."
[size]
(IvParameterSpec. (secure-random-bytes size)))
(defn gen-key
"Generates a SecretKey of the specified algorithm and size."
[algorithm size]
(let [key-gen (doto (KeyGenerator/getInstance algorithm)
(.init size))]
(.generateKey key-gen)))
(defn- cipher
"Clojure wrapper for using javax.crypto.Cipher on a byte array."
[key algorithm params data mode]
(let [cipher (doto (Cipher/getInstance algorithm)
(.init mode key params))]
(.doFinal cipher data)))
(defn encrypt-bytes
"Encrypts a byte array with the given key and algorithm."
[key algorithm params data]
(cipher key algorithm params data Cipher/ENCRYPT_MODE))
(defn decrypt-bytes
"Decrypts a byte array with the given key and algorithm."
[key algorithm params data]
(cipher key algorithm params data Cipher/DECRYPT_MODE))
(defn encrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[key algorithm params s]
(base64-encode-bytes (encrypt-bytes key algorithm params (.getBytes s))))
(defn decrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[key algorithm params s]
(String. (decrypt-bytes key algorithm params (base64-decode-bytes s))))
|
101585
|
;; 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 compojure.crypto
"Functions for cryptographically signing, verifying and encrypting data."
(:use compojure.encodings)
(:import java.security.SecureRandom)
(:import javax.crypto.Cipher)
(:import javax.crypto.KeyGenerator)
(:import javax.crypto.Mac)
(:import javax.crypto.spec.SecretKeySpec)
(:import javax.crypto.spec.IvParameterSpec)
(:import java.util.UUID))
(defn hmac
"Generate a hashed message authentication code with the supplied key and
algorithm on some string data."
[key algorithm data]
(let [spec (SecretKeySpec. key algorithm)
mac (doto (Mac/getInstance algorithm)
(.init spec))
bytes (.doFinal mac (.getBytes data))]
(base64-encode-bytes bytes)))
(defn gen-uuid
"Generate a random UUID."
[]
(str (UUID/randomUUID)))
(defn strict-seq=
"Like = for sequences, but always check every value in a sequence."
[x y]
(loop [f1 (first x) f2 (first y)
n1 (next x) n2 (next y)
a true]
(if (and n1 n2)
(recur (first n1) (first n2)
(next n1) (next n2)
(and (= f1 f2) a))
(and (= (count x) (count y)) a))))
(defn secure-random-bytes
"Returns a random byte array of the specified size and algorithm.
Defaults to SHA1PRNG."
([size] (secure-random-bytes size "SHA1PRNG"))
([size algorithm]
(let [seed (make-array (. Byte TYPE) size)]
(.nextBytes (SecureRandom/getInstance algorithm) seed)
seed)))
(defn gen-iv-param
"Generates a random IvParameterSpec for use with CBC encryption algorithms."
[size]
(IvParameterSpec. (secure-random-bytes size)))
(defn gen-key
"Generates a SecretKey of the specified algorithm and size."
[algorithm size]
(let [key-gen (doto (KeyGenerator/getInstance algorithm)
(.init size))]
(.generateKey key-gen)))
(defn- cipher
"Clojure wrapper for using javax.crypto.Cipher on a byte array."
[key algorithm params data mode]
(let [cipher (doto (Cipher/getInstance algorithm)
(.init mode key params))]
(.doFinal cipher data)))
(defn encrypt-bytes
"Encrypts a byte array with the given key and algorithm."
[key algorithm params data]
(cipher key algorithm params data Cipher/ENCRYPT_MODE))
(defn decrypt-bytes
"Decrypts a byte array with the given key and algorithm."
[key algorithm params data]
(cipher key algorithm params data Cipher/DECRYPT_MODE))
(defn encrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[key algorithm params s]
(base64-encode-bytes (encrypt-bytes key algorithm params (.getBytes s))))
(defn decrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[key algorithm params s]
(String. (decrypt-bytes key algorithm params (base64-decode-bytes s))))
| 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 compojure.crypto
"Functions for cryptographically signing, verifying and encrypting data."
(:use compojure.encodings)
(:import java.security.SecureRandom)
(:import javax.crypto.Cipher)
(:import javax.crypto.KeyGenerator)
(:import javax.crypto.Mac)
(:import javax.crypto.spec.SecretKeySpec)
(:import javax.crypto.spec.IvParameterSpec)
(:import java.util.UUID))
(defn hmac
"Generate a hashed message authentication code with the supplied key and
algorithm on some string data."
[key algorithm data]
(let [spec (SecretKeySpec. key algorithm)
mac (doto (Mac/getInstance algorithm)
(.init spec))
bytes (.doFinal mac (.getBytes data))]
(base64-encode-bytes bytes)))
(defn gen-uuid
"Generate a random UUID."
[]
(str (UUID/randomUUID)))
(defn strict-seq=
"Like = for sequences, but always check every value in a sequence."
[x y]
(loop [f1 (first x) f2 (first y)
n1 (next x) n2 (next y)
a true]
(if (and n1 n2)
(recur (first n1) (first n2)
(next n1) (next n2)
(and (= f1 f2) a))
(and (= (count x) (count y)) a))))
(defn secure-random-bytes
"Returns a random byte array of the specified size and algorithm.
Defaults to SHA1PRNG."
([size] (secure-random-bytes size "SHA1PRNG"))
([size algorithm]
(let [seed (make-array (. Byte TYPE) size)]
(.nextBytes (SecureRandom/getInstance algorithm) seed)
seed)))
(defn gen-iv-param
"Generates a random IvParameterSpec for use with CBC encryption algorithms."
[size]
(IvParameterSpec. (secure-random-bytes size)))
(defn gen-key
"Generates a SecretKey of the specified algorithm and size."
[algorithm size]
(let [key-gen (doto (KeyGenerator/getInstance algorithm)
(.init size))]
(.generateKey key-gen)))
(defn- cipher
"Clojure wrapper for using javax.crypto.Cipher on a byte array."
[key algorithm params data mode]
(let [cipher (doto (Cipher/getInstance algorithm)
(.init mode key params))]
(.doFinal cipher data)))
(defn encrypt-bytes
"Encrypts a byte array with the given key and algorithm."
[key algorithm params data]
(cipher key algorithm params data Cipher/ENCRYPT_MODE))
(defn decrypt-bytes
"Decrypts a byte array with the given key and algorithm."
[key algorithm params data]
(cipher key algorithm params data Cipher/DECRYPT_MODE))
(defn encrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[key algorithm params s]
(base64-encode-bytes (encrypt-bytes key algorithm params (.getBytes s))))
(defn decrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[key algorithm params s]
(String. (decrypt-bytes key algorithm params (base64-decode-bytes s))))
|
[
{
"context": "deleted\"}\n :+\n {\"recipe-added\"\n {:name \"Burgers\"\n :grubs\n \"400 g ground beef\\nhambu",
"end": 5948,
"score": 0.5146909356117249,
"start": 5945,
"tag": "NAME",
"value": "Bur"
}
] |
src/test/grub/test/unit/diff.clj
|
sumeetminhas/changeurl
| 17 |
(ns grub.test.unit.diff
(:require [grub.diff :as diff]
[midje.sweet :refer :all]))
(def empty-diff {:tag 0
:shadow-tag 0
:grubs {:- #{} :+ nil}
:recipes {:- #{} :+ nil}})
(fact "Diff of empty states is empty diff"
(let [empty-state {:grubs {} :recipes {} :tag 0}]
(diff/diff-states empty-state empty-state) => empty-diff))
(fact "Diff of equal states is empty diff"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}})
=> empty-diff)
(fact "Diff of one added grub has one updated grub"
(diff/diff-states {:tag 0 :grubs {} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf" :completed false}} :recipes {}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:completed false, :text "asdf"}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one removed grub has one deleted grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{"id"}
:+ nil}
:recipes {:- #{} :+ nil}})
(fact "Diff of one changed grub has updated grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf2" :completed false}} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:text "asdf2"}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one completed grub has updated grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf" :completed true}} :recipes {}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:completed true}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one added recipe has updated recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {}}
{:tag 1 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ nil}
:recipes {:- #{} :+ {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}})
(fact "Diff of one changed recipe has one updated recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}
{:tag 1 :grubs {} :recipes {"id" {:name "Bleu Cheese Soup"
:grubs "Some grubs"}}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ nil}
:recipes {:- #{} :+ {"id" {:name "Bleu Cheese Soup" }}}})
(fact "Diff of one removed recipe has one deleted recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}
{:tag 1 :grubs {} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{} :+ nil}
:recipes {:- #{"id"} :+ nil}})
(def before-state
{:tag 0
:grubs
{"grub-same" {:completed false
:text "3 garlic cloves"}
"grub-completed" {:completed false
:text "2 tomatoes"}
"grub-updated" {:completed false
:text "BBQ sauce"}
"grub-deleted" {:completed true
:text "diapers"}}
:recipes
{"recipe-same" {:grubs "3 T. butter\n1 yellow onion\n1 1/2 dl red pepper\n1 dl apple\n3 garlic cloves\n1 t. curry\n3 dl water\n2-2 1/2 T. wheat flour\n1 kasvisliemikuutio\n200 g blue cheese\n2 dl apple juice\n2 dl milk\n1 t. basil\n1 package take-and-bake french bread"
:name "Blue Cheese Soup"}
"recipe-updated" {:grubs "450 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n350 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n3 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"
:name "Beef Stew"}
"recipe-deleted" {:grubs "8 slices rye bread\n400 g chicken breast\nBBQ sauce\nketchup\nmustard\nbutter\n1 package rocket\n4 tomatoes\n2 red onions\n1 bottle Coca Cola"
:name "Chickenburgers"}}})
(def after-state
{:tag 1
:grubs
{"grub-same" {:completed false,
:text "3 garlic cloves"}
"grub-completed" {:completed true,
:text "2 tomatoes"}
"grub-updated" {:completed false,
:text "Ketchup"}
"grub-added" {:completed false
:text "Toothpaste"}}
:recipes
{"recipe-same" {:grubs "3 T. butter\n1 yellow onion\n1 1/2 dl red pepper\n1 dl apple\n3 garlic cloves\n1 t. curry\n3 dl water\n2-2 1/2 T. wheat flour\n1 kasvisliemikuutio\n200 g blue cheese\n2 dl apple juice\n2 dl milk\n1 t. basil\n1 package take-and-bake french bread"
:name "Blue Cheese Soup"}
"recipe-updated" {:grubs "300 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n400 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n2 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"
:name "Beef Stew"}
"recipe-added" {:grubs "400 g ground beef\nhamburger buns\n2 red onions\n4 tomatoes\ncheddar cheese\nketchup\nmustard\npickles\nfresh basil\n1 bottle Coca Cola"
:name "Burgers"}}})
(def expected-diff
{:shadow-tag 0
:tag 1
:recipes
{:- #{"recipe-deleted"}
:+
{"recipe-added"
{:name "Burgers"
:grubs
"400 g ground beef\nhamburger buns\n2 red onions\n4 tomatoes\ncheddar cheese\nketchup\nmustard\npickles\nfresh basil\n1 bottle Coca Cola"}
"recipe-updated"
{:grubs
"300 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n400 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n2 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"}}}
:grubs
{:- #{"grub-deleted"}
:+
{"grub-completed" {:completed true}
"grub-updated" {:text "Ketchup"}
"grub-added"
{:completed false :text "Toothpaste"}}}})
(fact "Diff of many changes has all changes"
(diff/diff-states before-state after-state) => expected-diff)
(fact "Diff and patch of many changes returns original state"
(let [diff (diff/diff-states before-state after-state)]
(diff/patch-state before-state diff) => after-state))
|
105988
|
(ns grub.test.unit.diff
(:require [grub.diff :as diff]
[midje.sweet :refer :all]))
(def empty-diff {:tag 0
:shadow-tag 0
:grubs {:- #{} :+ nil}
:recipes {:- #{} :+ nil}})
(fact "Diff of empty states is empty diff"
(let [empty-state {:grubs {} :recipes {} :tag 0}]
(diff/diff-states empty-state empty-state) => empty-diff))
(fact "Diff of equal states is empty diff"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}})
=> empty-diff)
(fact "Diff of one added grub has one updated grub"
(diff/diff-states {:tag 0 :grubs {} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf" :completed false}} :recipes {}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:completed false, :text "asdf"}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one removed grub has one deleted grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{"id"}
:+ nil}
:recipes {:- #{} :+ nil}})
(fact "Diff of one changed grub has updated grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf2" :completed false}} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:text "asdf2"}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one completed grub has updated grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf" :completed true}} :recipes {}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:completed true}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one added recipe has updated recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {}}
{:tag 1 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ nil}
:recipes {:- #{} :+ {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}})
(fact "Diff of one changed recipe has one updated recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}
{:tag 1 :grubs {} :recipes {"id" {:name "Bleu Cheese Soup"
:grubs "Some grubs"}}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ nil}
:recipes {:- #{} :+ {"id" {:name "Bleu Cheese Soup" }}}})
(fact "Diff of one removed recipe has one deleted recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}
{:tag 1 :grubs {} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{} :+ nil}
:recipes {:- #{"id"} :+ nil}})
(def before-state
{:tag 0
:grubs
{"grub-same" {:completed false
:text "3 garlic cloves"}
"grub-completed" {:completed false
:text "2 tomatoes"}
"grub-updated" {:completed false
:text "BBQ sauce"}
"grub-deleted" {:completed true
:text "diapers"}}
:recipes
{"recipe-same" {:grubs "3 T. butter\n1 yellow onion\n1 1/2 dl red pepper\n1 dl apple\n3 garlic cloves\n1 t. curry\n3 dl water\n2-2 1/2 T. wheat flour\n1 kasvisliemikuutio\n200 g blue cheese\n2 dl apple juice\n2 dl milk\n1 t. basil\n1 package take-and-bake french bread"
:name "Blue Cheese Soup"}
"recipe-updated" {:grubs "450 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n350 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n3 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"
:name "Beef Stew"}
"recipe-deleted" {:grubs "8 slices rye bread\n400 g chicken breast\nBBQ sauce\nketchup\nmustard\nbutter\n1 package rocket\n4 tomatoes\n2 red onions\n1 bottle Coca Cola"
:name "Chickenburgers"}}})
(def after-state
{:tag 1
:grubs
{"grub-same" {:completed false,
:text "3 garlic cloves"}
"grub-completed" {:completed true,
:text "2 tomatoes"}
"grub-updated" {:completed false,
:text "Ketchup"}
"grub-added" {:completed false
:text "Toothpaste"}}
:recipes
{"recipe-same" {:grubs "3 T. butter\n1 yellow onion\n1 1/2 dl red pepper\n1 dl apple\n3 garlic cloves\n1 t. curry\n3 dl water\n2-2 1/2 T. wheat flour\n1 kasvisliemikuutio\n200 g blue cheese\n2 dl apple juice\n2 dl milk\n1 t. basil\n1 package take-and-bake french bread"
:name "Blue Cheese Soup"}
"recipe-updated" {:grubs "300 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n400 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n2 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"
:name "Beef Stew"}
"recipe-added" {:grubs "400 g ground beef\nhamburger buns\n2 red onions\n4 tomatoes\ncheddar cheese\nketchup\nmustard\npickles\nfresh basil\n1 bottle Coca Cola"
:name "Burgers"}}})
(def expected-diff
{:shadow-tag 0
:tag 1
:recipes
{:- #{"recipe-deleted"}
:+
{"recipe-added"
{:name "<NAME>gers"
:grubs
"400 g ground beef\nhamburger buns\n2 red onions\n4 tomatoes\ncheddar cheese\nketchup\nmustard\npickles\nfresh basil\n1 bottle Coca Cola"}
"recipe-updated"
{:grubs
"300 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n400 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n2 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"}}}
:grubs
{:- #{"grub-deleted"}
:+
{"grub-completed" {:completed true}
"grub-updated" {:text "Ketchup"}
"grub-added"
{:completed false :text "Toothpaste"}}}})
(fact "Diff of many changes has all changes"
(diff/diff-states before-state after-state) => expected-diff)
(fact "Diff and patch of many changes returns original state"
(let [diff (diff/diff-states before-state after-state)]
(diff/patch-state before-state diff) => after-state))
| true |
(ns grub.test.unit.diff
(:require [grub.diff :as diff]
[midje.sweet :refer :all]))
(def empty-diff {:tag 0
:shadow-tag 0
:grubs {:- #{} :+ nil}
:recipes {:- #{} :+ nil}})
(fact "Diff of empty states is empty diff"
(let [empty-state {:grubs {} :recipes {} :tag 0}]
(diff/diff-states empty-state empty-state) => empty-diff))
(fact "Diff of equal states is empty diff"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}})
=> empty-diff)
(fact "Diff of one added grub has one updated grub"
(diff/diff-states {:tag 0 :grubs {} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf" :completed false}} :recipes {}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:completed false, :text "asdf"}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one removed grub has one deleted grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{"id"}
:+ nil}
:recipes {:- #{} :+ nil}})
(fact "Diff of one changed grub has updated grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf2" :completed false}} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:text "asdf2"}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one completed grub has updated grub"
(diff/diff-states {:tag 0 :grubs {"id" {:text "asdf" :completed false}} :recipes {}}
{:tag 1 :grubs {"id" {:text "asdf" :completed true}} :recipes {}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ {"id" {:completed true}}}
:recipes {:- #{} :+ nil}})
(fact "Diff of one added recipe has updated recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {}}
{:tag 1 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ nil}
:recipes {:- #{} :+ {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}})
(fact "Diff of one changed recipe has one updated recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}
{:tag 1 :grubs {} :recipes {"id" {:name "Bleu Cheese Soup"
:grubs "Some grubs"}}})
=> {:shadow-tag 0
:tag 1
:grubs {:- #{}
:+ nil}
:recipes {:- #{} :+ {"id" {:name "Bleu Cheese Soup" }}}})
(fact "Diff of one removed recipe has one deleted recipe"
(diff/diff-states {:tag 0 :grubs {} :recipes {"id" {:name "Blue Cheese Soup"
:grubs "Some grubs"}}}
{:tag 1 :grubs {} :recipes {}})
=>
{:shadow-tag 0
:tag 1
:grubs {:- #{} :+ nil}
:recipes {:- #{"id"} :+ nil}})
(def before-state
{:tag 0
:grubs
{"grub-same" {:completed false
:text "3 garlic cloves"}
"grub-completed" {:completed false
:text "2 tomatoes"}
"grub-updated" {:completed false
:text "BBQ sauce"}
"grub-deleted" {:completed true
:text "diapers"}}
:recipes
{"recipe-same" {:grubs "3 T. butter\n1 yellow onion\n1 1/2 dl red pepper\n1 dl apple\n3 garlic cloves\n1 t. curry\n3 dl water\n2-2 1/2 T. wheat flour\n1 kasvisliemikuutio\n200 g blue cheese\n2 dl apple juice\n2 dl milk\n1 t. basil\n1 package take-and-bake french bread"
:name "Blue Cheese Soup"}
"recipe-updated" {:grubs "450 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n350 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n3 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"
:name "Beef Stew"}
"recipe-deleted" {:grubs "8 slices rye bread\n400 g chicken breast\nBBQ sauce\nketchup\nmustard\nbutter\n1 package rocket\n4 tomatoes\n2 red onions\n1 bottle Coca Cola"
:name "Chickenburgers"}}})
(def after-state
{:tag 1
:grubs
{"grub-same" {:completed false,
:text "3 garlic cloves"}
"grub-completed" {:completed true,
:text "2 tomatoes"}
"grub-updated" {:completed false,
:text "Ketchup"}
"grub-added" {:completed false
:text "Toothpaste"}}
:recipes
{"recipe-same" {:grubs "3 T. butter\n1 yellow onion\n1 1/2 dl red pepper\n1 dl apple\n3 garlic cloves\n1 t. curry\n3 dl water\n2-2 1/2 T. wheat flour\n1 kasvisliemikuutio\n200 g blue cheese\n2 dl apple juice\n2 dl milk\n1 t. basil\n1 package take-and-bake french bread"
:name "Blue Cheese Soup"}
"recipe-updated" {:grubs "300 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n400 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n2 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"
:name "Beef Stew"}
"recipe-added" {:grubs "400 g ground beef\nhamburger buns\n2 red onions\n4 tomatoes\ncheddar cheese\nketchup\nmustard\npickles\nfresh basil\n1 bottle Coca Cola"
:name "Burgers"}}})
(def expected-diff
{:shadow-tag 0
:tag 1
:recipes
{:- #{"recipe-deleted"}
:+
{"recipe-added"
{:name "PI:NAME:<NAME>END_PIgers"
:grubs
"400 g ground beef\nhamburger buns\n2 red onions\n4 tomatoes\ncheddar cheese\nketchup\nmustard\npickles\nfresh basil\n1 bottle Coca Cola"}
"recipe-updated"
{:grubs
"300 g lean stew beef (lapa/naudan etuselkä), cut into 1-inch cubes\n2 T. vegetable oil\n5 dl water\n2 lihaliemikuutios\n400 ml burgundy (or another red wine)\n1 garlic clove\n1 bay leaf (laakerinlehti)\n1/2 t. basil\n2 carrots\n1 yellow onion\n4 potatoes\n1 cup celery\n2 tablespoons of cornstarch (maissijauho/maizena)"}}}
:grubs
{:- #{"grub-deleted"}
:+
{"grub-completed" {:completed true}
"grub-updated" {:text "Ketchup"}
"grub-added"
{:completed false :text "Toothpaste"}}}})
(fact "Diff of many changes has all changes"
(diff/diff-states before-state after-state) => expected-diff)
(fact "Diff and patch of many changes returns original state"
(let [diff (diff/diff-states before-state after-state)]
(diff/patch-state before-state diff) => after-state))
|
[
{
"context": "\n :cancel [{:id 21 :symbol sym :account-id 4223421 :order-id 23341}\n {:id 22 :symbo",
"end": 1711,
"score": 0.6017871499061584,
"start": 1707,
"tag": "KEY",
"value": "2234"
},
{
"context": "\n {:id 25 :symbol sym :account-id 3423421 :order-id 9}]})",
"end": 1996,
"score": 0.5067519545555115,
"start": 1995,
"tag": "KEY",
"value": "4"
}
] |
counter/src/test/clojure/liu/mars/market/test_data.clj
|
gumplyz/market
| 92 |
(ns liu.mars.market.test-data)
(def sym "btcusdt")
(def note-paper
{:limit-ask [{:id 1 :symbol sym :price 34522M :quantity 1 :account-id 3223421}
{:id 2 :symbol sym :price 34512M :quantity 10001 :account-id 3223421}
{:id 3 :symbol sym :price 34525M :quantity 10020 :account-id 34223421}
{:id 4 :symbol sym :price 34562M :quantity 1000 :account-id 3422341}
{:id 5 :symbol sym :price 44522M :quantity 10000 :account-id 34223421}]
:limit-bid [{:id 6 :symbol sym :price 24522M :quantity 1 :account-id 34223421}
{:id 7 :symbol sym :price 3412M :quantity 10001 :account-id 34223421}
{:id 8 :symbol sym :price 32525M :quantity 10020 :account-id 34223421}
{:id 9 :symbol sym :price 31562M :quantity 1000 :account-id 34223421}
{:id 10 :symbol sym :price 1522M :quantity 9999 :account-id 34223421}]
:market-ask [{:id 11 :symbol sym :quantity 1 :account-id 34223421}
{:id 12 :symbol sym :quantity 10001 :account-id 3422342}
{:id 13 :symbol sym :quantity 10020 :account-id 34223421}
{:id 14 :symbol sym :quantity 1000 :account-id 3423421}
{:id 15 :symbol sym :quantity 10000 :account-id 34223421}]
:market-bid [{:id 16 :symbol sym :quantity 12433 :account-id 34223421}
{:id 17 :symbol sym :quantity 10001 :account-id 34223421}
{:id 18 :symbol sym :quantity 10020 :account-id 34223421}
{:id 19 :symbol sym :quantity 1000 :account-id 34223421}
{:id 20 :symbol sym :quantity 9999 :account-id 3422421}]
:cancel [{:id 21 :symbol sym :account-id 4223421 :order-id 23341}
{:id 22 :symbol sym :account-id 3423421 :order-id 23342}
{:id 23 :symbol sym :account-id 3422321 :order-id 2341}
{:id 24 :symbol sym :account-id 3423421 :order-id 23}
{:id 25 :symbol sym :account-id 3423421 :order-id 9}]})
|
75894
|
(ns liu.mars.market.test-data)
(def sym "btcusdt")
(def note-paper
{:limit-ask [{:id 1 :symbol sym :price 34522M :quantity 1 :account-id 3223421}
{:id 2 :symbol sym :price 34512M :quantity 10001 :account-id 3223421}
{:id 3 :symbol sym :price 34525M :quantity 10020 :account-id 34223421}
{:id 4 :symbol sym :price 34562M :quantity 1000 :account-id 3422341}
{:id 5 :symbol sym :price 44522M :quantity 10000 :account-id 34223421}]
:limit-bid [{:id 6 :symbol sym :price 24522M :quantity 1 :account-id 34223421}
{:id 7 :symbol sym :price 3412M :quantity 10001 :account-id 34223421}
{:id 8 :symbol sym :price 32525M :quantity 10020 :account-id 34223421}
{:id 9 :symbol sym :price 31562M :quantity 1000 :account-id 34223421}
{:id 10 :symbol sym :price 1522M :quantity 9999 :account-id 34223421}]
:market-ask [{:id 11 :symbol sym :quantity 1 :account-id 34223421}
{:id 12 :symbol sym :quantity 10001 :account-id 3422342}
{:id 13 :symbol sym :quantity 10020 :account-id 34223421}
{:id 14 :symbol sym :quantity 1000 :account-id 3423421}
{:id 15 :symbol sym :quantity 10000 :account-id 34223421}]
:market-bid [{:id 16 :symbol sym :quantity 12433 :account-id 34223421}
{:id 17 :symbol sym :quantity 10001 :account-id 34223421}
{:id 18 :symbol sym :quantity 10020 :account-id 34223421}
{:id 19 :symbol sym :quantity 1000 :account-id 34223421}
{:id 20 :symbol sym :quantity 9999 :account-id 3422421}]
:cancel [{:id 21 :symbol sym :account-id 4<KEY>21 :order-id 23341}
{:id 22 :symbol sym :account-id 3423421 :order-id 23342}
{:id 23 :symbol sym :account-id 3422321 :order-id 2341}
{:id 24 :symbol sym :account-id 3423421 :order-id 23}
{:id 25 :symbol sym :account-id 3<KEY>23421 :order-id 9}]})
| true |
(ns liu.mars.market.test-data)
(def sym "btcusdt")
(def note-paper
{:limit-ask [{:id 1 :symbol sym :price 34522M :quantity 1 :account-id 3223421}
{:id 2 :symbol sym :price 34512M :quantity 10001 :account-id 3223421}
{:id 3 :symbol sym :price 34525M :quantity 10020 :account-id 34223421}
{:id 4 :symbol sym :price 34562M :quantity 1000 :account-id 3422341}
{:id 5 :symbol sym :price 44522M :quantity 10000 :account-id 34223421}]
:limit-bid [{:id 6 :symbol sym :price 24522M :quantity 1 :account-id 34223421}
{:id 7 :symbol sym :price 3412M :quantity 10001 :account-id 34223421}
{:id 8 :symbol sym :price 32525M :quantity 10020 :account-id 34223421}
{:id 9 :symbol sym :price 31562M :quantity 1000 :account-id 34223421}
{:id 10 :symbol sym :price 1522M :quantity 9999 :account-id 34223421}]
:market-ask [{:id 11 :symbol sym :quantity 1 :account-id 34223421}
{:id 12 :symbol sym :quantity 10001 :account-id 3422342}
{:id 13 :symbol sym :quantity 10020 :account-id 34223421}
{:id 14 :symbol sym :quantity 1000 :account-id 3423421}
{:id 15 :symbol sym :quantity 10000 :account-id 34223421}]
:market-bid [{:id 16 :symbol sym :quantity 12433 :account-id 34223421}
{:id 17 :symbol sym :quantity 10001 :account-id 34223421}
{:id 18 :symbol sym :quantity 10020 :account-id 34223421}
{:id 19 :symbol sym :quantity 1000 :account-id 34223421}
{:id 20 :symbol sym :quantity 9999 :account-id 3422421}]
:cancel [{:id 21 :symbol sym :account-id 4PI:KEY:<KEY>END_PI21 :order-id 23341}
{:id 22 :symbol sym :account-id 3423421 :order-id 23342}
{:id 23 :symbol sym :account-id 3422321 :order-id 2341}
{:id 24 :symbol sym :account-id 3423421 :order-id 23}
{:id 25 :symbol sym :account-id 3PI:KEY:<KEY>END_PI23421 :order-id 9}]})
|
[
{
"context": " session)))))\n\n;; based on https://github.com/raquo/Airstream#frp-glitches\n(deftest frp-glitch\n (let",
"end": 20304,
"score": 0.9687407612800598,
"start": 20299,
"tag": "USERNAME",
"value": "raquo"
},
{
"context": " (is (= 3 (count people)))\n (is (= [alice charlie] (:friends bob)))\n (is (= [] (m",
"end": 23002,
"score": 0.9438231587409973,
"start": 22997,
"tag": "NAME",
"value": "alice"
},
{
"context": "(is (= 3 (count people)))\n (is (= [alice charlie] (:friends bob)))\n (is (= [] (mapv :",
"end": 23007,
"score": 0.7081730365753174,
"start": 23003,
"tag": "NAME",
"value": "char"
},
{
"context": "ple)))\n (is (= [alice charlie] (:friends bob)))\n (is (= [] (mapv :id (:friends alice",
"end": 23025,
"score": 0.9399915933609009,
"start": 23022,
"tag": "NAME",
"value": "bob"
},
{
"context": "ds bob)))\n (is (= [] (mapv :id (:friends alice))))\n (is (= [alice] (:friends charlie))",
"end": 23075,
"score": 0.9227132201194763,
"start": 23070,
"tag": "NAME",
"value": "alice"
},
{
"context": " (mapv :id (:friends alice))))\n (is (= [alice] (:friends charlie))))\n session))))\n\n;; n",
"end": 23104,
"score": 0.7532745599746704,
"start": 23099,
"tag": "NAME",
"value": "alice"
},
{
"context": "ends alice))))\n (is (= [alice] (:friends charlie))))\n session))))\n\n;; normally, the {:t",
"end": 23120,
"score": 0.9109406471252441,
"start": 23116,
"tag": "NAME",
"value": "char"
}
] |
test/odoyle/rules_test.cljc
|
davesann/odoyle-rules
| 0 |
(ns odoyle.rules-test
(:require [clojure.test :refer [deftest is]]
[odoyle.rules :as o]
[clojure.spec.test.alpha :as st]))
(st/instrument)
(deftest num-of-conditions-not=-num-of-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::num-conds-and-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
[x ::height h]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z ::zach))]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
(o/insert ::xavier ::height 72)
(o/insert ::thomas ::height 72)
(o/insert ::george ::height 72)
o/fire-rules
((fn [session]
(is (= 3 (count (o/query-all session ::num-conds-and-facts))))
session))))
(deftest adding-facts-out-of-order
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::out-of-order
[:what
[x ::right-of y]
[y ::left-of z]
[z ::color "red"]
[a ::color "maize"]
[b ::color "blue"]
[c ::color "green"]
[d ::color "white"]
[s ::on "table"]
[y ::right-of b]
[a ::left-of d]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z ::zach))]}))
(o/insert ::xavier ::right-of ::yair)
(o/insert ::yair ::left-of ::zach)
(o/insert ::zach ::color "red")
(o/insert ::alice ::color "maize")
(o/insert ::bob ::color "blue")
(o/insert ::charlie ::color "green")
(o/insert ::seth ::on "table")
(o/insert ::yair ::right-of ::bob)
(o/insert ::alice ::left-of ::david)
(o/insert ::david ::color "white")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::out-of-order))))
session))))
(deftest duplicate-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::duplicate-facts
[:what
[x ::self y]
[x ::color c]
[y ::color c]]}))
(o/insert ::bob ::self ::bob)
(o/insert ::bob ::color "red")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::duplicate-facts))))
(is (= "red" (:c (first (o/query-all session ::duplicate-facts)))))
session))
(o/insert ::bob ::color "green")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::duplicate-facts))))
(is (= "green" (:c (first (o/query-all session ::duplicate-facts)))))
session))))
(deftest removing-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::removing-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::removing-facts))))
session))
(o/retract ::yair ::right-of)
((fn [session]
(is (= 0 (count (o/query-all session ::removing-facts))))
session))
(o/retract ::bob ::color)
(o/insert ::bob ::color "blue")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::removing-facts))))
session))))
(deftest updating-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::updating-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts))))
(is (= ::zach (:z (first (o/query-all session ::updating-facts)))))
session))
(o/insert ::yair ::left-of ::xavier)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts))))
(is (= ::xavier (:z (first (o/query-all session ::updating-facts)))))
session))))
(deftest updating-facts-in-different-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::updating-facts-diff-nodes
[:what
[b ::color "blue"]
[y ::left-of ::zach]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts-diff-nodes))))
session))
(o/insert ::yair ::left-of ::xavier)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::updating-facts-diff-nodes))))
session))))
(deftest facts-can-be-stored-in-different-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[a ::left-of ::zach]]
::rule2
[:what
[a ::left-of z]]}))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(is (= ::alice (:a (first (o/query-all session ::rule1)))))
(is (= ::zach (:z (first (o/query-all session ::rule2)))))
session))))
(deftest complex-conditions
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::complex-cond
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
:when
(not= z ::zach)]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::complex-cond))))
session))
(o/insert ::yair ::left-of ::charlie)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::complex-cond))))
session))))
(deftest out-of-order-joins-between-id-and-value
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::right-of ::alice]
[y ::right-of b]
[b ::color "blue"]]}))
(o/insert ::bob ::right-of ::alice)
(o/insert ::bob ::color "blue")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
session))))
(deftest simple-conditions
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::simple-cond
[:what
[b ::color "blue"]
:when
false
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 0 @*count))
session)))))
(deftest queries
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "green")
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::height 64)
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::alice)
(o/insert ::charlie ::height 72)
o/fire-rules
((fn [session]
(is (= 3 (count (o/query-all session ::get-person))))
session))))
(deftest query-all-facts
(let [rules (o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]]})]
(-> (reduce o/add-rule (o/->session) rules)
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "green")
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::height 64)
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::alice)
(o/insert ::charlie ::height 72)
;; insert and retract a fact to make sure
;; it isn't returned by query-all
(o/insert ::zach ::color "blue")
(o/retract ::zach ::color)
((fn [session]
(let [facts (o/query-all session)
;; make a new session and insert the facts we retrieved
new-session (reduce o/add-rule (o/->session) rules)
new-session (reduce o/insert new-session facts)]
(is (= 9 (count facts)))
(is (= 3 (count (o/query-all new-session ::get-person))))
new-session))))))
(deftest creating-a-ruleset
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::bob
[:what
[b ::color "blue"]
[b ::right-of a]
:then
(is (= a ::alice))
(is (= b ::bob))]
::alice
[:what
[a ::color "red"]
[a ::left-of b]
:then
(is (= a ::alice))
(is (= b ::bob))]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::right-of ::alice)
(o/insert ::alice ::color "red")
(o/insert ::alice ::left-of ::bob)
o/fire-rules))
(deftest dont-trigger-rule-when-updating-certain-facts
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::dont-trigger
[:what
[b ::color "blue"]
[a ::color c {:then false}]
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
o/fire-rules
(o/insert ::alice ::color "red")
o/fire-rules
(o/insert ::alice ::color "maize")
o/fire-rules
((fn [session]
(is (= 1 @*count))
session)))))
(deftest inserting-inside-a-rule
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
[::alice ::color c {:then false}]
:then
(o/reset! (o/insert o/*session* ::alice ::color "maize"))]}))
(o/insert ::bob ::color "blue")
(o/insert ::alice ::color "red")
o/fire-rules
((fn [session]
(is (= "maize" (:c (first (o/query-all session ::rule1)))))
session))))
(deftest inserting-inside-a-rule-can-trigger-more-than-once
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
:then
(-> o/*session*
(o/insert ::alice ::color "maize")
(o/insert ::charlie ::color "gold")
o/reset!)]
::rule2
[:what
[::alice ::color c1]
[other-person ::color c2]
:when
(not= other-person ::alice)
:then
(swap! *count inc)]}))
(o/insert ::alice ::color "red")
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest inserting-inside-a-rule-cascades
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
:then
(o/reset! (o/insert o/*session* ::charlie ::right-of ::bob))]
::rule2
[:what
[c ::right-of b]
:then
(o/reset! (o/insert o/*session* b ::left-of c))]
::rule3
[:what
[b ::left-of c]]}))
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
(is (= 1 (count (o/query-all session ::rule2))))
(is (= 1 (count (o/query-all session ::rule3))))
session))))
(deftest conditions-can-use-external-values
(let [*allow-rule-to-fire (atom false)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[a ::left-of b]
:when
@*allow-rule-to-fire]}))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(reset! *allow-rule-to-fire true)
session))
(o/insert ::alice ::left-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
(reset! *allow-rule-to-fire false)
session))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::rule1))))
session)))))
(deftest id+attr-combos-can-be-stored-in-multiple-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-alice
[:what
[::alice ::color color]
[::alice ::height height]]
::get-person
[:what
[id ::color color]
[id ::height height]]}))
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
o/fire-rules
((fn [session]
(let [alice (first (o/query-all session ::get-alice))]
(is (= "blue" (:color alice)))
(is (= 60 (:height alice))))
session))
(o/retract ::alice ::color)
((fn [session]
(is (= 0 (count (o/query-all session ::get-alice))))
session))))
(deftest ids-can-be-arbitrary-integers
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
[z ::left-of b]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z 1))]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of 1)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
(o/insert 1 ::left-of ::bob)
o/fire-rules))
(deftest join-value-with-id
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::left-of id]
[id ::color color]
[id ::height height]]}))
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
(o/insert ::bob ::left-of ::alice)
(o/insert ::charlie ::color "green")
(o/insert ::charlie ::height 72)
(o/insert ::bob ::left-of ::charlie)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
session))))
(deftest multiple-joins
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[pid ::kind :player]
[pid ::color pcolor]
[pid ::height pheight]
[eid ::kind kind]
[eid ::color ecolor {:then false}]
[eid ::height eheight {:then false}]
:when
(not= kind :player)
:then
(-> o/*session*
(o/insert eid ::color "green")
(o/insert eid ::height 70)
o/reset!)]}))
(o/insert 1 {::kind :player
::color "red"
::height 72})
(o/insert 2 {::kind :enemy
::color "blue"
::height 60})
o/fire-rules
((fn [session]
(is (= "green" (:ecolor (first (o/query-all session ::rule1)))))
session))))
(deftest join-followed-by-non-join
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[id ::x x]
[id ::y y]
[id ::xv xv]
[id ::yv yv]
[::bob ::left-of z]]}))
(o/insert ::bob ::left-of ::zach)
(o/insert ::alice {::x 0 ::y 0 ::xv 1 ::yv 1})
(o/insert ::charlie {::x 1 ::y 1 ::xv 0 ::yv 0})
o/fire-rules
((fn [session]
(is (= 2 (count (o/query-all session ::rule1))))
session))))
(deftest only-last-condition-can-fire
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[id ::left-of ::bob {:then false}]
[id ::color color {:then false}]
[::alice ::height height]
:then
(swap! *count inc)]}))
(o/insert ::alice ::height 60) ;; out of order
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 1 @*count))
session))
(o/retract ::alice ::height)
(o/retract ::alice ::left-of)
(o/retract ::alice ::color)
(o/insert ::alice ::height 60)
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 2 @*count))
session))
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 2 @*count))
session))
(o/insert ::alice ::height 60)
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest avoid-unnecessary-rule-firings
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
o/fire-rules
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest then-finally
(let [*trigger-count (atom 0)
*all-people (atom [])]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
:then-finally
(->> (o/query-all o/*session* ::get-person)
(o/insert o/*session* ::people ::all)
o/reset!)]
::all-people
[:what
[::people ::all all-people]
:then
(reset! *all-people all-people)
(swap! *trigger-count inc)]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
o/fire-rules
((fn [session]
(is (= 2 (count @*all-people)))
(is (= 1 @*trigger-count))
session))
(o/retract ::alice ::color)
o/fire-rules
((fn [session]
(is (= 1 (count @*all-people)))
(is (= 2 @*trigger-count))
session)))))
;; based on https://github.com/raquo/Airstream#frp-glitches
(deftest frp-glitch
(let [*output (atom [])]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::is-positive
[:what
[::number ::any any-num]
:then
(o/insert! ::number ::positive? (pos? any-num))]
::doubled-numbers
[:what
[::number ::any any-num]
:then
(o/insert! ::number ::doubled (* 2 any-num))]
::combined
[:what
[::number ::positive? positive?]
[::number ::doubled doubled]
:then
(o/insert! ::number ::combined [doubled positive?])]
::print-combined
[:what
[::number ::combined combined]
:then
(swap! *output conj combined)]}))
(o/insert ::number ::any -1)
o/fire-rules
(o/insert ::number ::any 1)
o/fire-rules
((fn [session]
(is (= @*output [[-2 false] [2 true]]))
session)))))
(deftest recursion
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
[id ::friends friends {:then not=}]
:then-finally
(->> (o/query-all o/*session* ::get-person)
(reduce #(assoc %1 (:id %2) %2) {})
(o/insert! ::people ::by-id))]
::update-friends
[:what
[id ::friend-ids friend-ids]
[::people ::by-id id->person]
:then
(->> (mapv id->person friend-ids)
(o/insert! id ::friends))]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::bob ::friend-ids [::alice ::charlie])
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
(o/insert ::alice ::friend-ids [])
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::bob)
(o/insert ::charlie ::height 70)
(o/insert ::charlie ::friend-ids [::alice])
(o/insert ::people ::by-id {})
o/fire-rules
((fn [session]
(let [people (o/query-all session ::get-person)
bob (first (filter #(= ::bob (:id %)) people))
alice (first (filter #(= ::alice (:id %)) people))
charlie (first (filter #(= ::charlie (:id %)) people))]
(is (= 3 (count people)))
(is (= [alice charlie] (:friends bob)))
(is (= [] (mapv :id (:friends alice))))
(is (= [alice] (:friends charlie))))
session))))
;; normally, the {:then not=} would be enough to prevent an
;; infinite loop here. but because the other facts are joined
;; with the first one via `id`, they too will be updated when
;; the ::left-of fact is updated. therefore, they must have
;; {:then false} to prevent the infinite loop from happening.
(deftest avoid-infinite-loop-when-updating-fact-whose-value-is-joined
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::left-of id {:then not=}]
[id ::color color {:then false}]
[id ::height height {:then false}]
:then
(o/insert! b ::left-of ::charlie)]}))
(o/insert ::bob ::left-of ::alice)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
(o/insert ::charlie ::color "green")
(o/insert ::charlie ::height 72)
o/fire-rules
((fn [session]
(is (= ::charlie (-> (o/query-all session ::rule1)
first
:id)))
session))))
(deftest recursion-limit
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[::alice ::color c]
:then
(o/reset! (o/insert o/*session* ::alice ::height 15))]
::rule2
[:what
[::alice ::height height]
:then
(o/reset! (o/insert o/*session* ::alice ::age 10))]
::rule3
[:what
[::alice ::age age]
:then
(o/reset! (-> o/*session*
(o/insert ::alice ::color "maize")
(o/insert ::bob ::age 10)))]
::rule4
[:what
[::bob ::age age]
:then
(o/reset! (o/insert o/*session* ::bob ::height 15))]
::rule5
[:what
[::bob ::height height]
:then
(o/reset! (o/insert o/*session* ::bob ::age 10))]
::rule6
[:what
[::bob ::color c]
:then
(o/reset! (o/insert o/*session* ::bob ::color c))]}))
(o/insert ::alice ::color "red")
(o/insert ::bob ::color "blue")
((fn [session]
(is (thrown? #?(:clj Exception :cljs js/Error)
(o/fire-rules session)))))))
|
124842
|
(ns odoyle.rules-test
(:require [clojure.test :refer [deftest is]]
[odoyle.rules :as o]
[clojure.spec.test.alpha :as st]))
(st/instrument)
(deftest num-of-conditions-not=-num-of-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::num-conds-and-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
[x ::height h]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z ::zach))]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
(o/insert ::xavier ::height 72)
(o/insert ::thomas ::height 72)
(o/insert ::george ::height 72)
o/fire-rules
((fn [session]
(is (= 3 (count (o/query-all session ::num-conds-and-facts))))
session))))
(deftest adding-facts-out-of-order
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::out-of-order
[:what
[x ::right-of y]
[y ::left-of z]
[z ::color "red"]
[a ::color "maize"]
[b ::color "blue"]
[c ::color "green"]
[d ::color "white"]
[s ::on "table"]
[y ::right-of b]
[a ::left-of d]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z ::zach))]}))
(o/insert ::xavier ::right-of ::yair)
(o/insert ::yair ::left-of ::zach)
(o/insert ::zach ::color "red")
(o/insert ::alice ::color "maize")
(o/insert ::bob ::color "blue")
(o/insert ::charlie ::color "green")
(o/insert ::seth ::on "table")
(o/insert ::yair ::right-of ::bob)
(o/insert ::alice ::left-of ::david)
(o/insert ::david ::color "white")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::out-of-order))))
session))))
(deftest duplicate-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::duplicate-facts
[:what
[x ::self y]
[x ::color c]
[y ::color c]]}))
(o/insert ::bob ::self ::bob)
(o/insert ::bob ::color "red")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::duplicate-facts))))
(is (= "red" (:c (first (o/query-all session ::duplicate-facts)))))
session))
(o/insert ::bob ::color "green")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::duplicate-facts))))
(is (= "green" (:c (first (o/query-all session ::duplicate-facts)))))
session))))
(deftest removing-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::removing-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::removing-facts))))
session))
(o/retract ::yair ::right-of)
((fn [session]
(is (= 0 (count (o/query-all session ::removing-facts))))
session))
(o/retract ::bob ::color)
(o/insert ::bob ::color "blue")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::removing-facts))))
session))))
(deftest updating-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::updating-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts))))
(is (= ::zach (:z (first (o/query-all session ::updating-facts)))))
session))
(o/insert ::yair ::left-of ::xavier)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts))))
(is (= ::xavier (:z (first (o/query-all session ::updating-facts)))))
session))))
(deftest updating-facts-in-different-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::updating-facts-diff-nodes
[:what
[b ::color "blue"]
[y ::left-of ::zach]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts-diff-nodes))))
session))
(o/insert ::yair ::left-of ::xavier)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::updating-facts-diff-nodes))))
session))))
(deftest facts-can-be-stored-in-different-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[a ::left-of ::zach]]
::rule2
[:what
[a ::left-of z]]}))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(is (= ::alice (:a (first (o/query-all session ::rule1)))))
(is (= ::zach (:z (first (o/query-all session ::rule2)))))
session))))
(deftest complex-conditions
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::complex-cond
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
:when
(not= z ::zach)]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::complex-cond))))
session))
(o/insert ::yair ::left-of ::charlie)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::complex-cond))))
session))))
(deftest out-of-order-joins-between-id-and-value
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::right-of ::alice]
[y ::right-of b]
[b ::color "blue"]]}))
(o/insert ::bob ::right-of ::alice)
(o/insert ::bob ::color "blue")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
session))))
(deftest simple-conditions
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::simple-cond
[:what
[b ::color "blue"]
:when
false
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 0 @*count))
session)))))
(deftest queries
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "green")
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::height 64)
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::alice)
(o/insert ::charlie ::height 72)
o/fire-rules
((fn [session]
(is (= 3 (count (o/query-all session ::get-person))))
session))))
(deftest query-all-facts
(let [rules (o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]]})]
(-> (reduce o/add-rule (o/->session) rules)
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "green")
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::height 64)
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::alice)
(o/insert ::charlie ::height 72)
;; insert and retract a fact to make sure
;; it isn't returned by query-all
(o/insert ::zach ::color "blue")
(o/retract ::zach ::color)
((fn [session]
(let [facts (o/query-all session)
;; make a new session and insert the facts we retrieved
new-session (reduce o/add-rule (o/->session) rules)
new-session (reduce o/insert new-session facts)]
(is (= 9 (count facts)))
(is (= 3 (count (o/query-all new-session ::get-person))))
new-session))))))
(deftest creating-a-ruleset
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::bob
[:what
[b ::color "blue"]
[b ::right-of a]
:then
(is (= a ::alice))
(is (= b ::bob))]
::alice
[:what
[a ::color "red"]
[a ::left-of b]
:then
(is (= a ::alice))
(is (= b ::bob))]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::right-of ::alice)
(o/insert ::alice ::color "red")
(o/insert ::alice ::left-of ::bob)
o/fire-rules))
(deftest dont-trigger-rule-when-updating-certain-facts
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::dont-trigger
[:what
[b ::color "blue"]
[a ::color c {:then false}]
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
o/fire-rules
(o/insert ::alice ::color "red")
o/fire-rules
(o/insert ::alice ::color "maize")
o/fire-rules
((fn [session]
(is (= 1 @*count))
session)))))
(deftest inserting-inside-a-rule
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
[::alice ::color c {:then false}]
:then
(o/reset! (o/insert o/*session* ::alice ::color "maize"))]}))
(o/insert ::bob ::color "blue")
(o/insert ::alice ::color "red")
o/fire-rules
((fn [session]
(is (= "maize" (:c (first (o/query-all session ::rule1)))))
session))))
(deftest inserting-inside-a-rule-can-trigger-more-than-once
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
:then
(-> o/*session*
(o/insert ::alice ::color "maize")
(o/insert ::charlie ::color "gold")
o/reset!)]
::rule2
[:what
[::alice ::color c1]
[other-person ::color c2]
:when
(not= other-person ::alice)
:then
(swap! *count inc)]}))
(o/insert ::alice ::color "red")
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest inserting-inside-a-rule-cascades
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
:then
(o/reset! (o/insert o/*session* ::charlie ::right-of ::bob))]
::rule2
[:what
[c ::right-of b]
:then
(o/reset! (o/insert o/*session* b ::left-of c))]
::rule3
[:what
[b ::left-of c]]}))
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
(is (= 1 (count (o/query-all session ::rule2))))
(is (= 1 (count (o/query-all session ::rule3))))
session))))
(deftest conditions-can-use-external-values
(let [*allow-rule-to-fire (atom false)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[a ::left-of b]
:when
@*allow-rule-to-fire]}))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(reset! *allow-rule-to-fire true)
session))
(o/insert ::alice ::left-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
(reset! *allow-rule-to-fire false)
session))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::rule1))))
session)))))
(deftest id+attr-combos-can-be-stored-in-multiple-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-alice
[:what
[::alice ::color color]
[::alice ::height height]]
::get-person
[:what
[id ::color color]
[id ::height height]]}))
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
o/fire-rules
((fn [session]
(let [alice (first (o/query-all session ::get-alice))]
(is (= "blue" (:color alice)))
(is (= 60 (:height alice))))
session))
(o/retract ::alice ::color)
((fn [session]
(is (= 0 (count (o/query-all session ::get-alice))))
session))))
(deftest ids-can-be-arbitrary-integers
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
[z ::left-of b]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z 1))]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of 1)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
(o/insert 1 ::left-of ::bob)
o/fire-rules))
(deftest join-value-with-id
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::left-of id]
[id ::color color]
[id ::height height]]}))
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
(o/insert ::bob ::left-of ::alice)
(o/insert ::charlie ::color "green")
(o/insert ::charlie ::height 72)
(o/insert ::bob ::left-of ::charlie)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
session))))
(deftest multiple-joins
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[pid ::kind :player]
[pid ::color pcolor]
[pid ::height pheight]
[eid ::kind kind]
[eid ::color ecolor {:then false}]
[eid ::height eheight {:then false}]
:when
(not= kind :player)
:then
(-> o/*session*
(o/insert eid ::color "green")
(o/insert eid ::height 70)
o/reset!)]}))
(o/insert 1 {::kind :player
::color "red"
::height 72})
(o/insert 2 {::kind :enemy
::color "blue"
::height 60})
o/fire-rules
((fn [session]
(is (= "green" (:ecolor (first (o/query-all session ::rule1)))))
session))))
(deftest join-followed-by-non-join
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[id ::x x]
[id ::y y]
[id ::xv xv]
[id ::yv yv]
[::bob ::left-of z]]}))
(o/insert ::bob ::left-of ::zach)
(o/insert ::alice {::x 0 ::y 0 ::xv 1 ::yv 1})
(o/insert ::charlie {::x 1 ::y 1 ::xv 0 ::yv 0})
o/fire-rules
((fn [session]
(is (= 2 (count (o/query-all session ::rule1))))
session))))
(deftest only-last-condition-can-fire
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[id ::left-of ::bob {:then false}]
[id ::color color {:then false}]
[::alice ::height height]
:then
(swap! *count inc)]}))
(o/insert ::alice ::height 60) ;; out of order
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 1 @*count))
session))
(o/retract ::alice ::height)
(o/retract ::alice ::left-of)
(o/retract ::alice ::color)
(o/insert ::alice ::height 60)
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 2 @*count))
session))
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 2 @*count))
session))
(o/insert ::alice ::height 60)
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest avoid-unnecessary-rule-firings
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
o/fire-rules
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest then-finally
(let [*trigger-count (atom 0)
*all-people (atom [])]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
:then-finally
(->> (o/query-all o/*session* ::get-person)
(o/insert o/*session* ::people ::all)
o/reset!)]
::all-people
[:what
[::people ::all all-people]
:then
(reset! *all-people all-people)
(swap! *trigger-count inc)]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
o/fire-rules
((fn [session]
(is (= 2 (count @*all-people)))
(is (= 1 @*trigger-count))
session))
(o/retract ::alice ::color)
o/fire-rules
((fn [session]
(is (= 1 (count @*all-people)))
(is (= 2 @*trigger-count))
session)))))
;; based on https://github.com/raquo/Airstream#frp-glitches
(deftest frp-glitch
(let [*output (atom [])]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::is-positive
[:what
[::number ::any any-num]
:then
(o/insert! ::number ::positive? (pos? any-num))]
::doubled-numbers
[:what
[::number ::any any-num]
:then
(o/insert! ::number ::doubled (* 2 any-num))]
::combined
[:what
[::number ::positive? positive?]
[::number ::doubled doubled]
:then
(o/insert! ::number ::combined [doubled positive?])]
::print-combined
[:what
[::number ::combined combined]
:then
(swap! *output conj combined)]}))
(o/insert ::number ::any -1)
o/fire-rules
(o/insert ::number ::any 1)
o/fire-rules
((fn [session]
(is (= @*output [[-2 false] [2 true]]))
session)))))
(deftest recursion
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
[id ::friends friends {:then not=}]
:then-finally
(->> (o/query-all o/*session* ::get-person)
(reduce #(assoc %1 (:id %2) %2) {})
(o/insert! ::people ::by-id))]
::update-friends
[:what
[id ::friend-ids friend-ids]
[::people ::by-id id->person]
:then
(->> (mapv id->person friend-ids)
(o/insert! id ::friends))]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::bob ::friend-ids [::alice ::charlie])
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
(o/insert ::alice ::friend-ids [])
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::bob)
(o/insert ::charlie ::height 70)
(o/insert ::charlie ::friend-ids [::alice])
(o/insert ::people ::by-id {})
o/fire-rules
((fn [session]
(let [people (o/query-all session ::get-person)
bob (first (filter #(= ::bob (:id %)) people))
alice (first (filter #(= ::alice (:id %)) people))
charlie (first (filter #(= ::charlie (:id %)) people))]
(is (= 3 (count people)))
(is (= [<NAME> <NAME>lie] (:friends <NAME>)))
(is (= [] (mapv :id (:friends <NAME>))))
(is (= [<NAME>] (:friends <NAME>lie))))
session))))
;; normally, the {:then not=} would be enough to prevent an
;; infinite loop here. but because the other facts are joined
;; with the first one via `id`, they too will be updated when
;; the ::left-of fact is updated. therefore, they must have
;; {:then false} to prevent the infinite loop from happening.
(deftest avoid-infinite-loop-when-updating-fact-whose-value-is-joined
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::left-of id {:then not=}]
[id ::color color {:then false}]
[id ::height height {:then false}]
:then
(o/insert! b ::left-of ::charlie)]}))
(o/insert ::bob ::left-of ::alice)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
(o/insert ::charlie ::color "green")
(o/insert ::charlie ::height 72)
o/fire-rules
((fn [session]
(is (= ::charlie (-> (o/query-all session ::rule1)
first
:id)))
session))))
(deftest recursion-limit
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[::alice ::color c]
:then
(o/reset! (o/insert o/*session* ::alice ::height 15))]
::rule2
[:what
[::alice ::height height]
:then
(o/reset! (o/insert o/*session* ::alice ::age 10))]
::rule3
[:what
[::alice ::age age]
:then
(o/reset! (-> o/*session*
(o/insert ::alice ::color "maize")
(o/insert ::bob ::age 10)))]
::rule4
[:what
[::bob ::age age]
:then
(o/reset! (o/insert o/*session* ::bob ::height 15))]
::rule5
[:what
[::bob ::height height]
:then
(o/reset! (o/insert o/*session* ::bob ::age 10))]
::rule6
[:what
[::bob ::color c]
:then
(o/reset! (o/insert o/*session* ::bob ::color c))]}))
(o/insert ::alice ::color "red")
(o/insert ::bob ::color "blue")
((fn [session]
(is (thrown? #?(:clj Exception :cljs js/Error)
(o/fire-rules session)))))))
| true |
(ns odoyle.rules-test
(:require [clojure.test :refer [deftest is]]
[odoyle.rules :as o]
[clojure.spec.test.alpha :as st]))
(st/instrument)
(deftest num-of-conditions-not=-num-of-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::num-conds-and-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
[x ::height h]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z ::zach))]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
(o/insert ::xavier ::height 72)
(o/insert ::thomas ::height 72)
(o/insert ::george ::height 72)
o/fire-rules
((fn [session]
(is (= 3 (count (o/query-all session ::num-conds-and-facts))))
session))))
(deftest adding-facts-out-of-order
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::out-of-order
[:what
[x ::right-of y]
[y ::left-of z]
[z ::color "red"]
[a ::color "maize"]
[b ::color "blue"]
[c ::color "green"]
[d ::color "white"]
[s ::on "table"]
[y ::right-of b]
[a ::left-of d]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z ::zach))]}))
(o/insert ::xavier ::right-of ::yair)
(o/insert ::yair ::left-of ::zach)
(o/insert ::zach ::color "red")
(o/insert ::alice ::color "maize")
(o/insert ::bob ::color "blue")
(o/insert ::charlie ::color "green")
(o/insert ::seth ::on "table")
(o/insert ::yair ::right-of ::bob)
(o/insert ::alice ::left-of ::david)
(o/insert ::david ::color "white")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::out-of-order))))
session))))
(deftest duplicate-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::duplicate-facts
[:what
[x ::self y]
[x ::color c]
[y ::color c]]}))
(o/insert ::bob ::self ::bob)
(o/insert ::bob ::color "red")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::duplicate-facts))))
(is (= "red" (:c (first (o/query-all session ::duplicate-facts)))))
session))
(o/insert ::bob ::color "green")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::duplicate-facts))))
(is (= "green" (:c (first (o/query-all session ::duplicate-facts)))))
session))))
(deftest removing-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::removing-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::removing-facts))))
session))
(o/retract ::yair ::right-of)
((fn [session]
(is (= 0 (count (o/query-all session ::removing-facts))))
session))
(o/retract ::bob ::color)
(o/insert ::bob ::color "blue")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::removing-facts))))
session))))
(deftest updating-facts
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::updating-facts
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts))))
(is (= ::zach (:z (first (o/query-all session ::updating-facts)))))
session))
(o/insert ::yair ::left-of ::xavier)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts))))
(is (= ::xavier (:z (first (o/query-all session ::updating-facts)))))
session))))
(deftest updating-facts-in-different-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::updating-facts-diff-nodes
[:what
[b ::color "blue"]
[y ::left-of ::zach]
[a ::color "maize"]
[y ::right-of b]]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::updating-facts-diff-nodes))))
session))
(o/insert ::yair ::left-of ::xavier)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::updating-facts-diff-nodes))))
session))))
(deftest facts-can-be-stored-in-different-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[a ::left-of ::zach]]
::rule2
[:what
[a ::left-of z]]}))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(is (= ::alice (:a (first (o/query-all session ::rule1)))))
(is (= ::zach (:z (first (o/query-all session ::rule2)))))
session))))
(deftest complex-conditions
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::complex-cond
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
:when
(not= z ::zach)]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of ::zach)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::complex-cond))))
session))
(o/insert ::yair ::left-of ::charlie)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::complex-cond))))
session))))
(deftest out-of-order-joins-between-id-and-value
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::right-of ::alice]
[y ::right-of b]
[b ::color "blue"]]}))
(o/insert ::bob ::right-of ::alice)
(o/insert ::bob ::color "blue")
(o/insert ::yair ::right-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
session))))
(deftest simple-conditions
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::simple-cond
[:what
[b ::color "blue"]
:when
false
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 0 @*count))
session)))))
(deftest queries
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "green")
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::height 64)
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::alice)
(o/insert ::charlie ::height 72)
o/fire-rules
((fn [session]
(is (= 3 (count (o/query-all session ::get-person))))
session))))
(deftest query-all-facts
(let [rules (o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]]})]
(-> (reduce o/add-rule (o/->session) rules)
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "green")
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::height 64)
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::alice)
(o/insert ::charlie ::height 72)
;; insert and retract a fact to make sure
;; it isn't returned by query-all
(o/insert ::zach ::color "blue")
(o/retract ::zach ::color)
((fn [session]
(let [facts (o/query-all session)
;; make a new session and insert the facts we retrieved
new-session (reduce o/add-rule (o/->session) rules)
new-session (reduce o/insert new-session facts)]
(is (= 9 (count facts)))
(is (= 3 (count (o/query-all new-session ::get-person))))
new-session))))))
(deftest creating-a-ruleset
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::bob
[:what
[b ::color "blue"]
[b ::right-of a]
:then
(is (= a ::alice))
(is (= b ::bob))]
::alice
[:what
[a ::color "red"]
[a ::left-of b]
:then
(is (= a ::alice))
(is (= b ::bob))]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::right-of ::alice)
(o/insert ::alice ::color "red")
(o/insert ::alice ::left-of ::bob)
o/fire-rules))
(deftest dont-trigger-rule-when-updating-certain-facts
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::dont-trigger
[:what
[b ::color "blue"]
[a ::color c {:then false}]
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
o/fire-rules
(o/insert ::alice ::color "red")
o/fire-rules
(o/insert ::alice ::color "maize")
o/fire-rules
((fn [session]
(is (= 1 @*count))
session)))))
(deftest inserting-inside-a-rule
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
[::alice ::color c {:then false}]
:then
(o/reset! (o/insert o/*session* ::alice ::color "maize"))]}))
(o/insert ::bob ::color "blue")
(o/insert ::alice ::color "red")
o/fire-rules
((fn [session]
(is (= "maize" (:c (first (o/query-all session ::rule1)))))
session))))
(deftest inserting-inside-a-rule-can-trigger-more-than-once
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
:then
(-> o/*session*
(o/insert ::alice ::color "maize")
(o/insert ::charlie ::color "gold")
o/reset!)]
::rule2
[:what
[::alice ::color c1]
[other-person ::color c2]
:when
(not= other-person ::alice)
:then
(swap! *count inc)]}))
(o/insert ::alice ::color "red")
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest inserting-inside-a-rule-cascades
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
:then
(o/reset! (o/insert o/*session* ::charlie ::right-of ::bob))]
::rule2
[:what
[c ::right-of b]
:then
(o/reset! (o/insert o/*session* b ::left-of c))]
::rule3
[:what
[b ::left-of c]]}))
(o/insert ::bob ::color "blue")
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
(is (= 1 (count (o/query-all session ::rule2))))
(is (= 1 (count (o/query-all session ::rule3))))
session))))
(deftest conditions-can-use-external-values
(let [*allow-rule-to-fire (atom false)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[a ::left-of b]
:when
@*allow-rule-to-fire]}))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(reset! *allow-rule-to-fire true)
session))
(o/insert ::alice ::left-of ::bob)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
(reset! *allow-rule-to-fire false)
session))
(o/insert ::alice ::left-of ::zach)
o/fire-rules
((fn [session]
(is (= 0 (count (o/query-all session ::rule1))))
session)))))
(deftest id+attr-combos-can-be-stored-in-multiple-alpha-nodes
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-alice
[:what
[::alice ::color color]
[::alice ::height height]]
::get-person
[:what
[id ::color color]
[id ::height height]]}))
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
o/fire-rules
((fn [session]
(let [alice (first (o/query-all session ::get-alice))]
(is (= "blue" (:color alice)))
(is (= 60 (:height alice))))
session))
(o/retract ::alice ::color)
((fn [session]
(is (= 0 (count (o/query-all session ::get-alice))))
session))))
(deftest ids-can-be-arbitrary-integers
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::color "blue"]
[y ::left-of z]
[a ::color "maize"]
[y ::right-of b]
[z ::left-of b]
:then
(is (= a ::alice))
(is (= b ::bob))
(is (= y ::yair))
(is (= z 1))]}))
(o/insert ::bob ::color "blue")
(o/insert ::yair ::left-of 1)
(o/insert ::alice ::color "maize")
(o/insert ::yair ::right-of ::bob)
(o/insert 1 ::left-of ::bob)
o/fire-rules))
(deftest join-value-with-id
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::left-of id]
[id ::color color]
[id ::height height]]}))
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
(o/insert ::bob ::left-of ::alice)
(o/insert ::charlie ::color "green")
(o/insert ::charlie ::height 72)
(o/insert ::bob ::left-of ::charlie)
o/fire-rules
((fn [session]
(is (= 1 (count (o/query-all session ::rule1))))
session))))
(deftest multiple-joins
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[pid ::kind :player]
[pid ::color pcolor]
[pid ::height pheight]
[eid ::kind kind]
[eid ::color ecolor {:then false}]
[eid ::height eheight {:then false}]
:when
(not= kind :player)
:then
(-> o/*session*
(o/insert eid ::color "green")
(o/insert eid ::height 70)
o/reset!)]}))
(o/insert 1 {::kind :player
::color "red"
::height 72})
(o/insert 2 {::kind :enemy
::color "blue"
::height 60})
o/fire-rules
((fn [session]
(is (= "green" (:ecolor (first (o/query-all session ::rule1)))))
session))))
(deftest join-followed-by-non-join
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[id ::x x]
[id ::y y]
[id ::xv xv]
[id ::yv yv]
[::bob ::left-of z]]}))
(o/insert ::bob ::left-of ::zach)
(o/insert ::alice {::x 0 ::y 0 ::xv 1 ::yv 1})
(o/insert ::charlie {::x 1 ::y 1 ::xv 0 ::yv 0})
o/fire-rules
((fn [session]
(is (= 2 (count (o/query-all session ::rule1))))
session))))
(deftest only-last-condition-can-fire
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[id ::left-of ::bob {:then false}]
[id ::color color {:then false}]
[::alice ::height height]
:then
(swap! *count inc)]}))
(o/insert ::alice ::height 60) ;; out of order
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 1 @*count))
session))
(o/retract ::alice ::height)
(o/retract ::alice ::left-of)
(o/retract ::alice ::color)
(o/insert ::alice ::height 60)
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 2 @*count))
session))
(o/insert ::alice ::left-of ::bob)
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 2 @*count))
session))
(o/insert ::alice ::height 60)
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest avoid-unnecessary-rule-firings
(let [*count (atom 0)]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
:then
(swap! *count inc)]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
o/fire-rules
(o/insert ::alice ::color "blue")
o/fire-rules
((fn [session]
(is (= 3 @*count))
session)))))
(deftest then-finally
(let [*trigger-count (atom 0)
*all-people (atom [])]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
:then-finally
(->> (o/query-all o/*session* ::get-person)
(o/insert o/*session* ::people ::all)
o/reset!)]
::all-people
[:what
[::people ::all all-people]
:then
(reset! *all-people all-people)
(swap! *trigger-count inc)]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
o/fire-rules
((fn [session]
(is (= 2 (count @*all-people)))
(is (= 1 @*trigger-count))
session))
(o/retract ::alice ::color)
o/fire-rules
((fn [session]
(is (= 1 (count @*all-people)))
(is (= 2 @*trigger-count))
session)))))
;; based on https://github.com/raquo/Airstream#frp-glitches
(deftest frp-glitch
(let [*output (atom [])]
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::is-positive
[:what
[::number ::any any-num]
:then
(o/insert! ::number ::positive? (pos? any-num))]
::doubled-numbers
[:what
[::number ::any any-num]
:then
(o/insert! ::number ::doubled (* 2 any-num))]
::combined
[:what
[::number ::positive? positive?]
[::number ::doubled doubled]
:then
(o/insert! ::number ::combined [doubled positive?])]
::print-combined
[:what
[::number ::combined combined]
:then
(swap! *output conj combined)]}))
(o/insert ::number ::any -1)
o/fire-rules
(o/insert ::number ::any 1)
o/fire-rules
((fn [session]
(is (= @*output [[-2 false] [2 true]]))
session)))))
(deftest recursion
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::get-person
[:what
[id ::color color]
[id ::left-of left-of]
[id ::height height]
[id ::friends friends {:then not=}]
:then-finally
(->> (o/query-all o/*session* ::get-person)
(reduce #(assoc %1 (:id %2) %2) {})
(o/insert! ::people ::by-id))]
::update-friends
[:what
[id ::friend-ids friend-ids]
[::people ::by-id id->person]
:then
(->> (mapv id->person friend-ids)
(o/insert! id ::friends))]}))
(o/insert ::bob ::color "blue")
(o/insert ::bob ::left-of ::zach)
(o/insert ::bob ::height 72)
(o/insert ::bob ::friend-ids [::alice ::charlie])
(o/insert ::alice ::color "blue")
(o/insert ::alice ::left-of ::zach)
(o/insert ::alice ::height 72)
(o/insert ::alice ::friend-ids [])
(o/insert ::charlie ::color "red")
(o/insert ::charlie ::left-of ::bob)
(o/insert ::charlie ::height 70)
(o/insert ::charlie ::friend-ids [::alice])
(o/insert ::people ::by-id {})
o/fire-rules
((fn [session]
(let [people (o/query-all session ::get-person)
bob (first (filter #(= ::bob (:id %)) people))
alice (first (filter #(= ::alice (:id %)) people))
charlie (first (filter #(= ::charlie (:id %)) people))]
(is (= 3 (count people)))
(is (= [PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PIlie] (:friends PI:NAME:<NAME>END_PI)))
(is (= [] (mapv :id (:friends PI:NAME:<NAME>END_PI))))
(is (= [PI:NAME:<NAME>END_PI] (:friends PI:NAME:<NAME>END_PIlie))))
session))))
;; normally, the {:then not=} would be enough to prevent an
;; infinite loop here. but because the other facts are joined
;; with the first one via `id`, they too will be updated when
;; the ::left-of fact is updated. therefore, they must have
;; {:then false} to prevent the infinite loop from happening.
(deftest avoid-infinite-loop-when-updating-fact-whose-value-is-joined
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[b ::left-of id {:then not=}]
[id ::color color {:then false}]
[id ::height height {:then false}]
:then
(o/insert! b ::left-of ::charlie)]}))
(o/insert ::bob ::left-of ::alice)
(o/insert ::alice ::color "blue")
(o/insert ::alice ::height 60)
(o/insert ::charlie ::color "green")
(o/insert ::charlie ::height 72)
o/fire-rules
((fn [session]
(is (= ::charlie (-> (o/query-all session ::rule1)
first
:id)))
session))))
(deftest recursion-limit
(-> (reduce o/add-rule (o/->session)
(o/ruleset
{::rule1
[:what
[::alice ::color c]
:then
(o/reset! (o/insert o/*session* ::alice ::height 15))]
::rule2
[:what
[::alice ::height height]
:then
(o/reset! (o/insert o/*session* ::alice ::age 10))]
::rule3
[:what
[::alice ::age age]
:then
(o/reset! (-> o/*session*
(o/insert ::alice ::color "maize")
(o/insert ::bob ::age 10)))]
::rule4
[:what
[::bob ::age age]
:then
(o/reset! (o/insert o/*session* ::bob ::height 15))]
::rule5
[:what
[::bob ::height height]
:then
(o/reset! (o/insert o/*session* ::bob ::age 10))]
::rule6
[:what
[::bob ::color c]
:then
(o/reset! (o/insert o/*session* ::bob ::color c))]}))
(o/insert ::alice ::color "red")
(o/insert ::bob ::color "blue")
((fn [session]
(is (thrown? #?(:clj Exception :cljs js/Error)
(o/fire-rules session)))))))
|
[
{
"context": "/default-re->replacement))\n \"password=***** bar yada\" \"password=foo bar yada\"\n \"passwor",
"end": 259,
"score": 0.6973698735237122,
"start": 255,
"tag": "PASSWORD",
"value": "yada"
},
{
"context": "word=***** bar yada\" \"password=foo bar yada\"\n \"password:***** bar yada\" \"passw",
"end": 295,
"score": 0.6697066426277161,
"start": 291,
"tag": "PASSWORD",
"value": "yada"
},
{
"context": " \"password=foo bar yada\"\n \"password:***** bar yada\" \"password:foo bar yada\"\n \"passwor",
"end": 325,
"score": 0.6463121771812439,
"start": 321,
"tag": "PASSWORD",
"value": "yada"
},
{
"context": " \"password:***** bar yada\" \"password:foo bar yada\"\n \"password ***** bar yada\" \"passw",
"end": 361,
"score": 0.953294575214386,
"start": 349,
"tag": "PASSWORD",
"value": "foo bar yada"
},
{
"context": "password ***** bar yada\" \"password foo bar yada\"\n \"password: ***** bar yada\" \"passw",
"end": 427,
"score": 0.9595000147819519,
"start": 419,
"tag": "PASSWORD",
"value": "bar yada"
},
{
"context": " \"password foo bar yada\"\n \"password: ***** bar yada\" \"password: foo bar yada\"\n \"passwor",
"end": 458,
"score": 0.9503123164176941,
"start": 450,
"tag": "PASSWORD",
"value": "bar yada"
},
{
"context": " \"password: ***** bar yada\" \"password: foo bar yada\"\n \"password ***** bar yada\" \"passw",
"end": 494,
"score": 0.8860934972763062,
"start": 482,
"tag": "PASSWORD",
"value": "foo bar yada"
},
{
"context": " \"password ***** bar yada\" \"password foo bar yada\"\n \"password ***** bar yada\" \"passw",
"end": 562,
"score": 0.9755944013595581,
"start": 550,
"tag": "PASSWORD",
"value": "foo bar yada"
},
{
"context": " \"password foo bar yada\"\n \"password ***** bar yada\" \"password \\\"foo\\\" bar yada\"\n \"pas",
"end": 594,
"score": 0.9412553906440735,
"start": 586,
"tag": "PASSWORD",
"value": "bar yada"
},
{
"context": "assword ***** bar yada\" \"password \\\"foo\\\" bar yada\"\n \"password:***** bar yada\" \"passw",
"end": 634,
"score": 0.917214035987854,
"start": 620,
"tag": "PASSWORD",
"value": "foo\\\" bar yada"
},
{
"context": "ssword \\\"foo\\\" bar yada\"\n \"password:***** bar yada\" \"password:\\\"foo\\\" bar yada\"\n \"PaS",
"end": 664,
"score": 0.6768965721130371,
"start": 660,
"tag": "PASSWORD",
"value": "yada"
},
{
"context": "\"password:***** bar yada\" \"password:\\\"foo\\\" bar yada\"\n \"PaSSwoRD:***** bar yada\" \"PaSSw",
"end": 704,
"score": 0.9925400018692017,
"start": 690,
"tag": "PASSWORD",
"value": "foo\\\" bar yada"
},
{
"context": " \" pw=EUHIU#(*\\\") \"\n \" name=***** Piet\" \" name=Erwin Piet\"\n \" nam",
"end": 859,
"score": 0.6801015138626099,
"start": 855,
"tag": "NAME",
"value": "Piet"
},
{
"context": " \" name=***** Piet\" \" name=Erwin Piet\"\n \" name=*****, dit dan weer wel\" \" nam",
"end": 897,
"score": 0.9990217089653015,
"start": 887,
"tag": "NAME",
"value": "Erwin Piet"
},
{
"context": " \" name=*****, dit dan weer wel\" \" name=\\\"Erwin Piet\\\", dit dan weer wel\"\n \"2016093109\" ",
"end": 961,
"score": 0.9997603893280029,
"start": 951,
"tag": "NAME",
"value": "Erwin Piet"
},
{
"context": " \"{email: <email>, data}\" \"{email: [email protected], data}\"\n \"Tel.: <telefoon>\" ",
"end": 1100,
"score": 0.9998483657836914,
"start": 1089,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "d1\\n@\"\n \":value {:jdbc-url \\\"jdbc:postgresql://127.0.0.1:5432/config_db?user=config_reader&password=*****\\",
"end": 1754,
"score": 0.9996430277824402,
"start": 1745,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "*\\\"}}\"\n \":value {:jdbc-url \\\"jdbc:postgresql://127.0.0.1:5432/config_db?user=config_reader&password=xxx\\\"}",
"end": 1861,
"score": 0.9996467232704163,
"start": 1852,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] |
test/nl/mediquest/logback/util_test.clj
|
mediquest-nl/logback-masking-pattern-layouts
| 9 |
(ns nl.mediquest.logback.util-test
(:require
[clojure.test :refer [deftest are]]
[nl.mediquest.logback.util :as sut]))
(deftest scrub-test
(are [expected input] (= expected (sut/scrub input sut/default-re->replacement))
"password=***** bar yada" "password=foo bar yada"
"password:***** bar yada" "password:foo bar yada"
"password ***** bar yada" "password foo bar yada"
"password: ***** bar yada" "password: foo bar yada"
"password ***** bar yada" "password foo bar yada"
"password ***** bar yada" "password \"foo\" bar yada"
"password:***** bar yada" "password:\"foo\" bar yada"
"PaSSwoRD:***** bar yada" "PaSSwoRD:\"foo\" bar yada"
" pw=*****#(*\") " " pw=EUHIU#(*\") "
" name=***** Piet" " name=Erwin Piet"
" name=*****, dit dan weer wel" " name=\"Erwin Piet\", dit dan weer wel"
"2016093109" "2016093109"
"{email: <email>, data}" "{email: [email protected], data}"
"Tel.: <telefoon>" "Tel.: 0612345678"
"Bsn: *****" "Bsn: \"012345678\""
"IBAN: \"<iban>7101\"" "IBAN: \"NL88TRIO0298087101\""
"IBAN: \"<iban>7102\"" "IBAN: \"NL 88 TRIO 0298987102\""
"perinatologie 21017142210 [VSV]" "perinatologie 21017142210 [VSV]"
"creditcard: \"<creditcard> lalala\"" "creditcard: \"5500 0000 0000 0004 lalala\""
"postgresql://my_user:*****@" "postgresql://my_user:PassW0Rd1@"
"postgresql://my_user:*****@" "postgresql://my_user:\nPassW0Rd1\n@"
":value {:jdbc-url \"jdbc:postgresql://127.0.0.1:5432/config_db?user=config_reader&password=*****\"}}"
":value {:jdbc-url \"jdbc:postgresql://127.0.0.1:5432/config_db?user=config_reader&password=xxx\"}}"))
|
96548
|
(ns nl.mediquest.logback.util-test
(:require
[clojure.test :refer [deftest are]]
[nl.mediquest.logback.util :as sut]))
(deftest scrub-test
(are [expected input] (= expected (sut/scrub input sut/default-re->replacement))
"password=***** bar <PASSWORD>" "password=foo bar <PASSWORD>"
"password:***** bar <PASSWORD>" "password:<PASSWORD>"
"password ***** bar yada" "password foo <PASSWORD>"
"password: ***** <PASSWORD>" "password: <PASSWORD>"
"password ***** bar yada" "password <PASSWORD>"
"password ***** <PASSWORD>" "password \"<PASSWORD>"
"password:***** bar <PASSWORD>" "password:\"<PASSWORD>"
"PaSSwoRD:***** bar yada" "PaSSwoRD:\"foo\" bar yada"
" pw=*****#(*\") " " pw=EUHIU#(*\") "
" name=***** <NAME>" " name=<NAME>"
" name=*****, dit dan weer wel" " name=\"<NAME>\", dit dan weer wel"
"2016093109" "2016093109"
"{email: <email>, data}" "{email: <EMAIL>, data}"
"Tel.: <telefoon>" "Tel.: 0612345678"
"Bsn: *****" "Bsn: \"012345678\""
"IBAN: \"<iban>7101\"" "IBAN: \"NL88TRIO0298087101\""
"IBAN: \"<iban>7102\"" "IBAN: \"NL 88 TRIO 0298987102\""
"perinatologie 21017142210 [VSV]" "perinatologie 21017142210 [VSV]"
"creditcard: \"<creditcard> lalala\"" "creditcard: \"5500 0000 0000 0004 lalala\""
"postgresql://my_user:*****@" "postgresql://my_user:PassW0Rd1@"
"postgresql://my_user:*****@" "postgresql://my_user:\nPassW0Rd1\n@"
":value {:jdbc-url \"jdbc:postgresql://127.0.0.1:5432/config_db?user=config_reader&password=*****\"}}"
":value {:jdbc-url \"jdbc:postgresql://127.0.0.1:5432/config_db?user=config_reader&password=xxx\"}}"))
| true |
(ns nl.mediquest.logback.util-test
(:require
[clojure.test :refer [deftest are]]
[nl.mediquest.logback.util :as sut]))
(deftest scrub-test
(are [expected input] (= expected (sut/scrub input sut/default-re->replacement))
"password=***** bar PI:PASSWORD:<PASSWORD>END_PI" "password=foo bar PI:PASSWORD:<PASSWORD>END_PI"
"password:***** bar PI:PASSWORD:<PASSWORD>END_PI" "password:PI:PASSWORD:<PASSWORD>END_PI"
"password ***** bar yada" "password foo PI:PASSWORD:<PASSWORD>END_PI"
"password: ***** PI:PASSWORD:<PASSWORD>END_PI" "password: PI:PASSWORD:<PASSWORD>END_PI"
"password ***** bar yada" "password PI:PASSWORD:<PASSWORD>END_PI"
"password ***** PI:PASSWORD:<PASSWORD>END_PI" "password \"PI:PASSWORD:<PASSWORD>END_PI"
"password:***** bar PI:PASSWORD:<PASSWORD>END_PI" "password:\"PI:PASSWORD:<PASSWORD>END_PI"
"PaSSwoRD:***** bar yada" "PaSSwoRD:\"foo\" bar yada"
" pw=*****#(*\") " " pw=EUHIU#(*\") "
" name=***** PI:NAME:<NAME>END_PI" " name=PI:NAME:<NAME>END_PI"
" name=*****, dit dan weer wel" " name=\"PI:NAME:<NAME>END_PI\", dit dan weer wel"
"2016093109" "2016093109"
"{email: <email>, data}" "{email: PI:EMAIL:<EMAIL>END_PI, data}"
"Tel.: <telefoon>" "Tel.: 0612345678"
"Bsn: *****" "Bsn: \"012345678\""
"IBAN: \"<iban>7101\"" "IBAN: \"NL88TRIO0298087101\""
"IBAN: \"<iban>7102\"" "IBAN: \"NL 88 TRIO 0298987102\""
"perinatologie 21017142210 [VSV]" "perinatologie 21017142210 [VSV]"
"creditcard: \"<creditcard> lalala\"" "creditcard: \"5500 0000 0000 0004 lalala\""
"postgresql://my_user:*****@" "postgresql://my_user:PassW0Rd1@"
"postgresql://my_user:*****@" "postgresql://my_user:\nPassW0Rd1\n@"
":value {:jdbc-url \"jdbc:postgresql://127.0.0.1:5432/config_db?user=config_reader&password=*****\"}}"
":value {:jdbc-url \"jdbc:postgresql://127.0.0.1:5432/config_db?user=config_reader&password=xxx\"}}"))
|
[
{
"context": " {:reference-time (time/t -2 2013 2 12 4 30)}\n\n \"ahora\"\n \"ahorita\"\n \"cuanto antes\"\n (datetime 2013 2 ",
"end": 133,
"score": 0.9995124340057373,
"start": 128,
"tag": "NAME",
"value": "ahora"
},
{
"context": "ce-time (time/t -2 2013 2 12 4 30)}\n\n \"ahora\"\n \"ahorita\"\n \"cuanto antes\"\n (datetime 2013 2 12 4 30 00)\n",
"end": 145,
"score": 0.9996463656425476,
"start": 138,
"tag": "NAME",
"value": "ahorita"
},
{
"context": "e/t -2 2013 2 12 4 30)}\n\n \"ahora\"\n \"ahorita\"\n \"cuanto antes\"\n (datetime 2013 2 12 4 30 00)\n\n \"hoy\"\n (datet",
"end": 162,
"score": 0.8704743385314941,
"start": 150,
"tag": "NAME",
"value": "cuanto antes"
},
{
"context": "\"cuanto antes\"\n (datetime 2013 2 12 4 30 00)\n\n \"hoy\"\n (datetime 2013 2 12)\n\n \"ayer\"\n (datetime 201",
"end": 202,
"score": 0.9957548975944519,
"start": 199,
"tag": "NAME",
"value": "hoy"
},
{
"context": "2 12 4 30 00)\n\n \"hoy\"\n (datetime 2013 2 12)\n\n \"ayer\"\n (datetime 2013 2 11)\n\n \"anteayer\"\n \"antier\"\n",
"end": 235,
"score": 0.9924382567405701,
"start": 231,
"tag": "NAME",
"value": "ayer"
},
{
"context": "e 2013 2 12)\n\n \"ayer\"\n (datetime 2013 2 11)\n\n \"anteayer\"\n \"antier\"\n (datetime 2013 2 10)\n\n \"mañana\"\n ",
"end": 272,
"score": 0.9978576898574829,
"start": 264,
"tag": "NAME",
"value": "anteayer"
},
{
"context": "\n \"ayer\"\n (datetime 2013 2 11)\n\n \"anteayer\"\n \"antier\"\n (datetime 2013 2 10)\n\n \"mañana\"\n (datetime 2",
"end": 283,
"score": 0.9993529319763184,
"start": 277,
"tag": "NAME",
"value": "antier"
},
{
"context": " \"anteayer\"\n \"antier\"\n (datetime 2013 2 10)\n\n \"mañana\"\n (datetime 2013 2 13)\n\n \"pasado mañana\"\n (dat",
"end": 318,
"score": 0.9970049858093262,
"start": 312,
"tag": "NAME",
"value": "mañana"
},
{
"context": "3 2 10)\n\n \"mañana\"\n (datetime 2013 2 13)\n\n \"pasado mañana\"\n (datetime 2013 2 14)\n\n \"12 de diciembr",
"end": 353,
"score": 0.5677326321601868,
"start": 350,
"tag": "NAME",
"value": "ado"
}
] |
resources/languages/es/corpus/time.clj
|
irvingflores/duckling
| 0 |
(; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30)}
"ahora"
"ahorita"
"cuanto antes"
(datetime 2013 2 12 4 30 00)
"hoy"
(datetime 2013 2 12)
"ayer"
(datetime 2013 2 11)
"anteayer"
"antier"
(datetime 2013 2 10)
"mañana"
(datetime 2013 2 13)
"pasado mañana"
(datetime 2013 2 14)
"12 de diciembre del 2015"
"12 de diciembre del 15"
(datetime 2015 12 12 :day 12 :month 12)
"mayo 5 del 2013" ; in part of latin america
"5-5-2013"
"5 de mayo de 2013"
"5/5/2013"
"5/5/13"
(datetime 2013 5 5 :day 5 :month 5 :year 2013)
"1-3-2013"
"1/3/2013"
(datetime 2013 3 1 :day 1 :month 3 :year 2013)
"31/10/1974"
"31/10/74" ; smart two-digit year resolution
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"miercoles de la próxima semana"
(datetime 2013 2 20 :day-of-week 3)
"martes de esta semana"
(datetime 2013 2 12 :day-of-week 2)
; ;; Cycles
"esta semana"
(datetime 2013 2 11 :grain :week)
"la semana pasada"
(datetime 2013 2 4 :grain :week)
"la semana que viene"
"la proxima semana"
(datetime 2013 2 18 :grain :week)
"el pasado mes"
(datetime 2013 1)
"el mes que viene"
"el proximo mes"
(datetime 2013 3)
"el año pasado"
(datetime 2012)
"este ano"
(datetime 2013)
"el año que viene"
"el proximo ano"
(datetime 2014)
; "a las tres y cuarto mañana por la tarde" ;ALEX
; (datetime 2013 2 13 15 15 :hour 15 :minute 15)
;"viernes a las doce"
;(datetime 2013 2 15 12 :hour 12 :day-of-week 5)
;"viernes a las 12:00 horas"
;(datetime 2013 2 15 12 0 :hour 12 :day-of-week 5 :minute 0)
;; Involving periods ; look for grain-after-shift
"en un segundo"
(datetime 2013 2 12 4 30 1)
"en un minuto"
"en 1 min"
(datetime 2013 2 12 4 31 0)
"en 2 minutos"
"en dos minutos"
(datetime 2013 2 12 4 32 0)
"en 60 minutos"
(datetime 2013 2 12 5 30 0)
"en una hora"
(datetime 2013 2 12 5 30)
"hace dos horas"
(datetime 2013 2 12 2 30)
"en 24 horas"
"en veinticuatro horas"
(datetime 2013 2 13 4 30)
"en un dia"
(datetime 2013 2 13 4)
"en 7 dias"
(datetime 2013 2 19 4)
"en una semana"
(datetime 2013 2 19)
"hace tres semanas"
(datetime 2013 1 22)
"en dos meses"
(datetime 2013 4 12)
"hace tres meses"
(datetime 2012 11 12)
"en un ano"
"en 1 año"
(datetime 2014 2)
"hace dos años"
(datetime 2011 2)
; Intervals involving cycles
"pasados 2 segundos"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"proximos 3 segundos"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"pasados 2 minutos"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"proximos 3 minutos"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"proximas 3 horas"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"pasados 2 dias"
(datetime-interval [2013 2 10] [2013 2 12])
"proximos 3 dias"
(datetime-interval [2013 2 13] [2013 2 16])
"pasadas dos semanas"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"3 proximas semanas"
"3 semanas que vienen"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"pasados 2 meses"
"dos pasados meses"
(datetime-interval [2012 12] [2013 02])
"3 próximos meses"
"proximos tres meses"
"tres meses que vienen"
(datetime-interval [2013 3] [2013 6])
"pasados 2 anos"
"dos pasados años"
(datetime-interval [2011] [2013])
"3 próximos años"
"proximo tres años"
"3 años que vienen"
(datetime-interval [2014] [2017])
)
|
12017
|
(; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30)}
"<NAME>"
"<NAME>"
"<NAME>"
(datetime 2013 2 12 4 30 00)
"<NAME>"
(datetime 2013 2 12)
"<NAME>"
(datetime 2013 2 11)
"<NAME>"
"<NAME>"
(datetime 2013 2 10)
"<NAME>"
(datetime 2013 2 13)
"pas<NAME> mañana"
(datetime 2013 2 14)
"12 de diciembre del 2015"
"12 de diciembre del 15"
(datetime 2015 12 12 :day 12 :month 12)
"mayo 5 del 2013" ; in part of latin america
"5-5-2013"
"5 de mayo de 2013"
"5/5/2013"
"5/5/13"
(datetime 2013 5 5 :day 5 :month 5 :year 2013)
"1-3-2013"
"1/3/2013"
(datetime 2013 3 1 :day 1 :month 3 :year 2013)
"31/10/1974"
"31/10/74" ; smart two-digit year resolution
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"miercoles de la próxima semana"
(datetime 2013 2 20 :day-of-week 3)
"martes de esta semana"
(datetime 2013 2 12 :day-of-week 2)
; ;; Cycles
"esta semana"
(datetime 2013 2 11 :grain :week)
"la semana pasada"
(datetime 2013 2 4 :grain :week)
"la semana que viene"
"la proxima semana"
(datetime 2013 2 18 :grain :week)
"el pasado mes"
(datetime 2013 1)
"el mes que viene"
"el proximo mes"
(datetime 2013 3)
"el año pasado"
(datetime 2012)
"este ano"
(datetime 2013)
"el año que viene"
"el proximo ano"
(datetime 2014)
; "a las tres y cuarto mañana por la tarde" ;ALEX
; (datetime 2013 2 13 15 15 :hour 15 :minute 15)
;"viernes a las doce"
;(datetime 2013 2 15 12 :hour 12 :day-of-week 5)
;"viernes a las 12:00 horas"
;(datetime 2013 2 15 12 0 :hour 12 :day-of-week 5 :minute 0)
;; Involving periods ; look for grain-after-shift
"en un segundo"
(datetime 2013 2 12 4 30 1)
"en un minuto"
"en 1 min"
(datetime 2013 2 12 4 31 0)
"en 2 minutos"
"en dos minutos"
(datetime 2013 2 12 4 32 0)
"en 60 minutos"
(datetime 2013 2 12 5 30 0)
"en una hora"
(datetime 2013 2 12 5 30)
"hace dos horas"
(datetime 2013 2 12 2 30)
"en 24 horas"
"en veinticuatro horas"
(datetime 2013 2 13 4 30)
"en un dia"
(datetime 2013 2 13 4)
"en 7 dias"
(datetime 2013 2 19 4)
"en una semana"
(datetime 2013 2 19)
"hace tres semanas"
(datetime 2013 1 22)
"en dos meses"
(datetime 2013 4 12)
"hace tres meses"
(datetime 2012 11 12)
"en un ano"
"en 1 año"
(datetime 2014 2)
"hace dos años"
(datetime 2011 2)
; Intervals involving cycles
"pasados 2 segundos"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"proximos 3 segundos"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"pasados 2 minutos"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"proximos 3 minutos"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"proximas 3 horas"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"pasados 2 dias"
(datetime-interval [2013 2 10] [2013 2 12])
"proximos 3 dias"
(datetime-interval [2013 2 13] [2013 2 16])
"pasadas dos semanas"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"3 proximas semanas"
"3 semanas que vienen"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"pasados 2 meses"
"dos pasados meses"
(datetime-interval [2012 12] [2013 02])
"3 próximos meses"
"proximos tres meses"
"tres meses que vienen"
(datetime-interval [2013 3] [2013 6])
"pasados 2 anos"
"dos pasados años"
(datetime-interval [2011] [2013])
"3 próximos años"
"proximo tres años"
"3 años que vienen"
(datetime-interval [2014] [2017])
)
| true |
(; Context map
; Tuesday Feb 12, 2013 at 4:30am is the "now" for the tests
{:reference-time (time/t -2 2013 2 12 4 30)}
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 12 4 30 00)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 12)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 11)
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 10)
"PI:NAME:<NAME>END_PI"
(datetime 2013 2 13)
"pasPI:NAME:<NAME>END_PI mañana"
(datetime 2013 2 14)
"12 de diciembre del 2015"
"12 de diciembre del 15"
(datetime 2015 12 12 :day 12 :month 12)
"mayo 5 del 2013" ; in part of latin america
"5-5-2013"
"5 de mayo de 2013"
"5/5/2013"
"5/5/13"
(datetime 2013 5 5 :day 5 :month 5 :year 2013)
"1-3-2013"
"1/3/2013"
(datetime 2013 3 1 :day 1 :month 3 :year 2013)
"31/10/1974"
"31/10/74" ; smart two-digit year resolution
(datetime 1974 10 31 :day 31 :month 10 :year 1974)
"miercoles de la próxima semana"
(datetime 2013 2 20 :day-of-week 3)
"martes de esta semana"
(datetime 2013 2 12 :day-of-week 2)
; ;; Cycles
"esta semana"
(datetime 2013 2 11 :grain :week)
"la semana pasada"
(datetime 2013 2 4 :grain :week)
"la semana que viene"
"la proxima semana"
(datetime 2013 2 18 :grain :week)
"el pasado mes"
(datetime 2013 1)
"el mes que viene"
"el proximo mes"
(datetime 2013 3)
"el año pasado"
(datetime 2012)
"este ano"
(datetime 2013)
"el año que viene"
"el proximo ano"
(datetime 2014)
; "a las tres y cuarto mañana por la tarde" ;ALEX
; (datetime 2013 2 13 15 15 :hour 15 :minute 15)
;"viernes a las doce"
;(datetime 2013 2 15 12 :hour 12 :day-of-week 5)
;"viernes a las 12:00 horas"
;(datetime 2013 2 15 12 0 :hour 12 :day-of-week 5 :minute 0)
;; Involving periods ; look for grain-after-shift
"en un segundo"
(datetime 2013 2 12 4 30 1)
"en un minuto"
"en 1 min"
(datetime 2013 2 12 4 31 0)
"en 2 minutos"
"en dos minutos"
(datetime 2013 2 12 4 32 0)
"en 60 minutos"
(datetime 2013 2 12 5 30 0)
"en una hora"
(datetime 2013 2 12 5 30)
"hace dos horas"
(datetime 2013 2 12 2 30)
"en 24 horas"
"en veinticuatro horas"
(datetime 2013 2 13 4 30)
"en un dia"
(datetime 2013 2 13 4)
"en 7 dias"
(datetime 2013 2 19 4)
"en una semana"
(datetime 2013 2 19)
"hace tres semanas"
(datetime 2013 1 22)
"en dos meses"
(datetime 2013 4 12)
"hace tres meses"
(datetime 2012 11 12)
"en un ano"
"en 1 año"
(datetime 2014 2)
"hace dos años"
(datetime 2011 2)
; Intervals involving cycles
"pasados 2 segundos"
(datetime-interval [2013 2 12 4 29 58] [2013 2 12 4 30 00])
"proximos 3 segundos"
(datetime-interval [2013 2 12 4 30 01] [2013 2 12 4 30 04])
"pasados 2 minutos"
(datetime-interval [2013 2 12 4 28] [2013 2 12 4 30])
"proximos 3 minutos"
(datetime-interval [2013 2 12 4 31] [2013 2 12 4 34])
"proximas 3 horas"
(datetime-interval [2013 2 12 5] [2013 2 12 8])
"pasados 2 dias"
(datetime-interval [2013 2 10] [2013 2 12])
"proximos 3 dias"
(datetime-interval [2013 2 13] [2013 2 16])
"pasadas dos semanas"
(datetime-interval [2013 1 28 :grain :week] [2013 2 11 :grain :week])
"3 proximas semanas"
"3 semanas que vienen"
(datetime-interval [2013 2 18 :grain :week] [2013 3 11 :grain :week])
"pasados 2 meses"
"dos pasados meses"
(datetime-interval [2012 12] [2013 02])
"3 próximos meses"
"proximos tres meses"
"tres meses que vienen"
(datetime-interval [2013 3] [2013 6])
"pasados 2 anos"
"dos pasados años"
(datetime-interval [2011] [2013])
"3 próximos años"
"proximo tres años"
"3 años que vienen"
(datetime-interval [2014] [2017])
)
|
[
{
"context": " - The new username.\n |new-password| - The new password.\n\n This function returns a core.async channel o",
"end": 1219,
"score": 0.8193677067756653,
"start": 1211,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "--------------------\n;\n; docs: https://github.com/binaryage/chromex/#tapping-events\n\n(defmacro tap-on-saved-p",
"end": 12765,
"score": 0.9971179366111755,
"start": 12756,
"tag": "USERNAME",
"value": "binaryage"
},
{
"context": "s\", :type \"[array-of-integers]\"}\n {:name \"new-username\", :type \"string\"}\n {:name \"new-password\", :t",
"end": 17310,
"score": 0.7458727359771729,
"start": 17302,
"tag": "USERNAME",
"value": "username"
}
] |
src/apps_private/chromex/app/passwords_private.clj
|
elias94/chromex
| 396 |
(ns chromex.app.passwords-private
"Use the chrome.passwordsPrivate API to add or remove password
data from the settings UI.
* available since Chrome master"
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
; -- functions --------------------------------------------------------------------------------------------------------------
(defmacro record-passwords-page-access-in-settings
"Function that logs that the Passwords page was accessed from the Chrome Settings WebUI."
([] (gen-call :function ::record-passwords-page-access-in-settings &form)))
(defmacro change-saved-password
"Changes the saved password corresponding to |ids|. Since the password can be stored in Google Account and on device, in
this case we want to change the password for accountId and deviceId. Invokes |callback| or raises an error depending on
whether the operation succeeded.
|ids| - The ids for the password entry being updated.
|new-username| - The new username.
|new-password| - The new password.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([ids new-username new-password] (gen-call :function ::change-saved-password &form ids new-username new-password)))
(defmacro remove-saved-password
"Removes the saved password corresponding to |id|. If no saved password for this pair exists, this function is a no-op.
|id| - The id for the password entry being removed."
([id] (gen-call :function ::remove-saved-password &form id)))
(defmacro remove-saved-passwords
"Removes the saved password corresponding to |ids|. If no saved password exists for a certain id, that id is ignored.
Undoing this operation via undoRemoveSavedPasswordOrException will restore all the removed passwords in the batch.
|ids| - ?"
([ids] (gen-call :function ::remove-saved-passwords &form ids)))
(defmacro remove-password-exception
"Removes the saved password exception corresponding to |id|. If no exception with this id exists, this function is a no-op.
|id| - The id for the exception url entry being removed."
([id] (gen-call :function ::remove-password-exception &form id)))
(defmacro remove-password-exceptions
"Removes the saved password exceptions corresponding to |ids|. If no exception exists for a certain id, that id is ignored.
Undoing this operation via undoRemoveSavedPasswordOrException will restore all the removed exceptions in the batch.
|ids| - ?"
([ids] (gen-call :function ::remove-password-exceptions &form ids)))
(defmacro undo-remove-saved-password-or-exception
"Undoes the last removal of saved password(s) or exception(s)."
([] (gen-call :function ::undo-remove-saved-password-or-exception &form)))
(defmacro request-plaintext-password
"Returns the plaintext password corresponding to |id|. Note that on some operating systems, this call may result in an
OS-level reauthentication. Once the password has been fetched, it will be returned via |callback|.
|id| - The id for the password entry being being retrieved.
|reason| - The reason why the plaintext password is requested.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [password] where:
|password| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id reason] (gen-call :function ::request-plaintext-password &form id reason)))
(defmacro get-saved-password-list
"Returns the list of saved passwords.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [entries] where:
|entries| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-saved-password-list &form)))
(defmacro get-password-exception-list
"Returns the list of password exceptions.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [exceptions] where:
|exceptions| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-password-exception-list &form)))
(defmacro move-password-to-account
"Moves a password currently stored on the device to being stored in the signed-in, non-syncing Google Account. The result is
a no-op if any of these is true: |id| is invalid; |id| corresponds to a password already stored in the account; or the user
is not using the account-scoped password storage.
|id| - The id for the password entry being moved."
([id] (gen-call :function ::move-password-to-account &form id)))
(defmacro import-passwords
"Triggers the Password Manager password import functionality."
([] (gen-call :function ::import-passwords &form)))
(defmacro export-passwords
"Triggers the Password Manager password export functionality. Completion Will be signaled by the
onPasswordsFileExportProgress event. |callback| will be called when the request is started or rejected. If rejected
'runtime.lastError' will be set to 'in-progress' or 'reauth-failed'.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::export-passwords &form)))
(defmacro request-export-progress-status
"Requests the export progress status. This is the same as the last value seen on the onPasswordsFileExportProgress event.
This function is useful for checking if an export has already been initiated from an older tab, where we might have missed
the original event.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [status] where:
|status| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::request-export-progress-status &form)))
(defmacro cancel-export-passwords
"Stops exporting passwords and cleans up any passwords, which were already written to the filesystem."
([] (gen-call :function ::cancel-export-passwords &form)))
(defmacro is-opted-in-for-account-storage
"Requests the account-storage opt-in state of the current user.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [opted-in] where:
|opted-in| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::is-opted-in-for-account-storage &form)))
(defmacro opt-in-for-account-storage
"Triggers the opt-in or opt-out flow for the account storage.
|opt-in| - ?"
([opt-in] (gen-call :function ::opt-in-for-account-storage &form opt-in)))
(defmacro get-compromised-credentials
"Requests the latest compromised credentials.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [insecure-credentials] where:
|insecure-credentials| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-compromised-credentials &form)))
(defmacro get-weak-credentials
"Requests the latest weak credentials.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [insecure-credentials] where:
|insecure-credentials| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-weak-credentials &form)))
(defmacro get-plaintext-insecure-password
"Requests the plaintext password for |credential|. |callback| gets invoked with the same |credential|, whose |password
field will be set.
|credential| - The insecure credential whose password is being retrieved.
|reason| - The reason why the plaintext password is requested.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [credential] where:
|credential| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential reason] (gen-call :function ::get-plaintext-insecure-password &form credential reason)))
(defmacro change-insecure-credential
"Requests to change the password of |credential| to |new_password|. Invokes |callback| or raises an error depending on
whether the operation succeeded.
|credential| - The credential whose password should be changed.
|new-password| - The new password.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential new-password] (gen-call :function ::change-insecure-credential &form credential new-password)))
(defmacro remove-insecure-credential
"Requests to remove |credential| from the password store. Invokes |callback| on completion.
|credential| - ?
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential] (gen-call :function ::remove-insecure-credential &form credential)))
(defmacro start-password-check
"Starts a check for insecure passwords. Invokes |callback| on completion.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::start-password-check &form)))
(defmacro stop-password-check
"Stops checking for insecure passwords. Invokes |callback| on completion.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::stop-password-check &form)))
(defmacro get-password-check-status
"Returns the current status of the check via |callback|.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [status] where:
|status| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-password-check-status &form)))
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: https://github.com/binaryage/chromex/#tapping-events
(defmacro tap-on-saved-passwords-list-changed-events
"Fired when the saved passwords list has changed, meaning that an entry has been added or removed.
Events will be put on the |channel| with signature [::on-saved-passwords-list-changed [entries]] where:
|entries| - The updated list of password entries.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-saved-passwords-list-changed &form channel args)))
(defmacro tap-on-password-exceptions-list-changed-events
"Fired when the password exceptions list has changed, meaning that an entry has been added or removed.
Events will be put on the |channel| with signature [::on-password-exceptions-list-changed [exceptions]] where:
|exceptions| - The updated list of password exceptions.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-password-exceptions-list-changed &form channel args)))
(defmacro tap-on-passwords-file-export-progress-events
"Fired when the status of the export has changed.
Events will be put on the |channel| with signature [::on-passwords-file-export-progress [status]] where:
|status| - The progress status and an optional UI message.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-passwords-file-export-progress &form channel args)))
(defmacro tap-on-account-storage-opt-in-state-changed-events
"Fired when the opt-in state for the account-scoped storage has changed.
Events will be put on the |channel| with signature [::on-account-storage-opt-in-state-changed [opted-in]] where:
|opted-in| - The new opt-in state.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-account-storage-opt-in-state-changed &form channel args)))
(defmacro tap-on-compromised-credentials-changed-events
"Fired when the compromised credentials changed.
Events will be put on the |channel| with signature [::on-compromised-credentials-changed [compromised-credentials]] where:
|compromised-credentials| - The updated compromised credentials.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-compromised-credentials-changed &form channel args)))
(defmacro tap-on-weak-credentials-changed-events
"Fired when the weak credentials changed.
Events will be put on the |channel| with signature [::on-weak-credentials-changed [weak-credentials]] where:
|weak-credentials| - The updated weak credentials.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-weak-credentials-changed &form channel args)))
(defmacro tap-on-password-check-status-changed-events
"Fired when the status of the password check changes.
Events will be put on the |channel| with signature [::on-password-check-status-changed [status]] where:
|status| - The updated status of the password check.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-password-check-status-changed &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.passwords-private namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.passwordsPrivate",
:since "master",
:functions
[{:id ::record-passwords-page-access-in-settings, :name "recordPasswordsPageAccessInSettings"}
{:id ::change-saved-password,
:name "changeSavedPassword",
:callback? true,
:params
[{:name "ids", :type "[array-of-integers]"}
{:name "new-username", :type "string"}
{:name "new-password", :type "string"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::remove-saved-password, :name "removeSavedPassword", :params [{:name "id", :type "integer"}]}
{:id ::remove-saved-passwords, :name "removeSavedPasswords", :params [{:name "ids", :type "[array-of-integers]"}]}
{:id ::remove-password-exception, :name "removePasswordException", :params [{:name "id", :type "integer"}]}
{:id ::remove-password-exceptions,
:name "removePasswordExceptions",
:params [{:name "ids", :type "[array-of-integers]"}]}
{:id ::undo-remove-saved-password-or-exception, :name "undoRemoveSavedPasswordOrException"}
{:id ::request-plaintext-password,
:name "requestPlaintextPassword",
:callback? true,
:params
[{:name "id", :type "integer"}
{:name "reason", :type "passwordsPrivate.PlaintextReason"}
{:name "callback", :type :callback, :callback {:params [{:name "password", :type "string"}]}}]}
{:id ::get-saved-password-list,
:name "getSavedPasswordList",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "entries", :type "[array-of-passwordsPrivate.PasswordUiEntrys]"}]}}]}
{:id ::get-password-exception-list,
:name "getPasswordExceptionList",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "exceptions", :type "[array-of-passwordsPrivate.ExceptionEntrys]"}]}}]}
{:id ::move-password-to-account, :name "movePasswordToAccount", :params [{:name "id", :type "integer"}]}
{:id ::import-passwords, :name "importPasswords"}
{:id ::export-passwords, :name "exportPasswords", :callback? true, :params [{:name "callback", :type :callback}]}
{:id ::request-export-progress-status,
:name "requestExportProgressStatus",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "status", :type "passwordsPrivate.ExportProgressStatus"}]}}]}
{:id ::cancel-export-passwords, :name "cancelExportPasswords"}
{:id ::is-opted-in-for-account-storage,
:name "isOptedInForAccountStorage",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "opted-in", :type "boolean"}]}}]}
{:id ::opt-in-for-account-storage, :name "optInForAccountStorage", :params [{:name "opt-in", :type "boolean"}]}
{:id ::get-compromised-credentials,
:name "getCompromisedCredentials",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "insecure-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}}]}
{:id ::get-weak-credentials,
:name "getWeakCredentials",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "insecure-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}}]}
{:id ::get-plaintext-insecure-password,
:name "getPlaintextInsecurePassword",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "reason", :type "passwordsPrivate.PlaintextReason"}
{:name "callback",
:type :callback,
:callback {:params [{:name "credential", :type "passwordsPrivate.InsecureCredential"}]}}]}
{:id ::change-insecure-credential,
:name "changeInsecureCredential",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "new-password", :type "string"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::remove-insecure-credential,
:name "removeInsecureCredential",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::start-password-check,
:name "startPasswordCheck",
:callback? true,
:params [{:name "callback", :optional? true, :type :callback}]}
{:id ::stop-password-check,
:name "stopPasswordCheck",
:callback? true,
:params [{:name "callback", :optional? true, :type :callback}]}
{:id ::get-password-check-status,
:name "getPasswordCheckStatus",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "status", :type "passwordsPrivate.PasswordCheckStatus"}]}}]}],
:events
[{:id ::on-saved-passwords-list-changed,
:name "onSavedPasswordsListChanged",
:params [{:name "entries", :type "[array-of-passwordsPrivate.PasswordUiEntrys]"}]}
{:id ::on-password-exceptions-list-changed,
:name "onPasswordExceptionsListChanged",
:params [{:name "exceptions", :type "[array-of-passwordsPrivate.ExceptionEntrys]"}]}
{:id ::on-passwords-file-export-progress,
:name "onPasswordsFileExportProgress",
:params [{:name "status", :type "object"}]}
{:id ::on-account-storage-opt-in-state-changed,
:name "onAccountStorageOptInStateChanged",
:params [{:name "opted-in", :type "boolean"}]}
{:id ::on-compromised-credentials-changed,
:name "onCompromisedCredentialsChanged",
:params [{:name "compromised-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}
{:id ::on-weak-credentials-changed,
:name "onWeakCredentialsChanged",
:params [{:name "weak-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}
{:id ::on-password-check-status-changed,
:name "onPasswordCheckStatusChanged",
:params [{:name "status", :type "passwordsPrivate.PasswordCheckStatus"}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table))
|
40820
|
(ns chromex.app.passwords-private
"Use the chrome.passwordsPrivate API to add or remove password
data from the settings UI.
* available since Chrome master"
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
; -- functions --------------------------------------------------------------------------------------------------------------
(defmacro record-passwords-page-access-in-settings
"Function that logs that the Passwords page was accessed from the Chrome Settings WebUI."
([] (gen-call :function ::record-passwords-page-access-in-settings &form)))
(defmacro change-saved-password
"Changes the saved password corresponding to |ids|. Since the password can be stored in Google Account and on device, in
this case we want to change the password for accountId and deviceId. Invokes |callback| or raises an error depending on
whether the operation succeeded.
|ids| - The ids for the password entry being updated.
|new-username| - The new username.
|new-password| - The new <PASSWORD>.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([ids new-username new-password] (gen-call :function ::change-saved-password &form ids new-username new-password)))
(defmacro remove-saved-password
"Removes the saved password corresponding to |id|. If no saved password for this pair exists, this function is a no-op.
|id| - The id for the password entry being removed."
([id] (gen-call :function ::remove-saved-password &form id)))
(defmacro remove-saved-passwords
"Removes the saved password corresponding to |ids|. If no saved password exists for a certain id, that id is ignored.
Undoing this operation via undoRemoveSavedPasswordOrException will restore all the removed passwords in the batch.
|ids| - ?"
([ids] (gen-call :function ::remove-saved-passwords &form ids)))
(defmacro remove-password-exception
"Removes the saved password exception corresponding to |id|. If no exception with this id exists, this function is a no-op.
|id| - The id for the exception url entry being removed."
([id] (gen-call :function ::remove-password-exception &form id)))
(defmacro remove-password-exceptions
"Removes the saved password exceptions corresponding to |ids|. If no exception exists for a certain id, that id is ignored.
Undoing this operation via undoRemoveSavedPasswordOrException will restore all the removed exceptions in the batch.
|ids| - ?"
([ids] (gen-call :function ::remove-password-exceptions &form ids)))
(defmacro undo-remove-saved-password-or-exception
"Undoes the last removal of saved password(s) or exception(s)."
([] (gen-call :function ::undo-remove-saved-password-or-exception &form)))
(defmacro request-plaintext-password
"Returns the plaintext password corresponding to |id|. Note that on some operating systems, this call may result in an
OS-level reauthentication. Once the password has been fetched, it will be returned via |callback|.
|id| - The id for the password entry being being retrieved.
|reason| - The reason why the plaintext password is requested.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [password] where:
|password| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id reason] (gen-call :function ::request-plaintext-password &form id reason)))
(defmacro get-saved-password-list
"Returns the list of saved passwords.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [entries] where:
|entries| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-saved-password-list &form)))
(defmacro get-password-exception-list
"Returns the list of password exceptions.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [exceptions] where:
|exceptions| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-password-exception-list &form)))
(defmacro move-password-to-account
"Moves a password currently stored on the device to being stored in the signed-in, non-syncing Google Account. The result is
a no-op if any of these is true: |id| is invalid; |id| corresponds to a password already stored in the account; or the user
is not using the account-scoped password storage.
|id| - The id for the password entry being moved."
([id] (gen-call :function ::move-password-to-account &form id)))
(defmacro import-passwords
"Triggers the Password Manager password import functionality."
([] (gen-call :function ::import-passwords &form)))
(defmacro export-passwords
"Triggers the Password Manager password export functionality. Completion Will be signaled by the
onPasswordsFileExportProgress event. |callback| will be called when the request is started or rejected. If rejected
'runtime.lastError' will be set to 'in-progress' or 'reauth-failed'.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::export-passwords &form)))
(defmacro request-export-progress-status
"Requests the export progress status. This is the same as the last value seen on the onPasswordsFileExportProgress event.
This function is useful for checking if an export has already been initiated from an older tab, where we might have missed
the original event.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [status] where:
|status| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::request-export-progress-status &form)))
(defmacro cancel-export-passwords
"Stops exporting passwords and cleans up any passwords, which were already written to the filesystem."
([] (gen-call :function ::cancel-export-passwords &form)))
(defmacro is-opted-in-for-account-storage
"Requests the account-storage opt-in state of the current user.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [opted-in] where:
|opted-in| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::is-opted-in-for-account-storage &form)))
(defmacro opt-in-for-account-storage
"Triggers the opt-in or opt-out flow for the account storage.
|opt-in| - ?"
([opt-in] (gen-call :function ::opt-in-for-account-storage &form opt-in)))
(defmacro get-compromised-credentials
"Requests the latest compromised credentials.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [insecure-credentials] where:
|insecure-credentials| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-compromised-credentials &form)))
(defmacro get-weak-credentials
"Requests the latest weak credentials.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [insecure-credentials] where:
|insecure-credentials| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-weak-credentials &form)))
(defmacro get-plaintext-insecure-password
"Requests the plaintext password for |credential|. |callback| gets invoked with the same |credential|, whose |password
field will be set.
|credential| - The insecure credential whose password is being retrieved.
|reason| - The reason why the plaintext password is requested.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [credential] where:
|credential| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential reason] (gen-call :function ::get-plaintext-insecure-password &form credential reason)))
(defmacro change-insecure-credential
"Requests to change the password of |credential| to |new_password|. Invokes |callback| or raises an error depending on
whether the operation succeeded.
|credential| - The credential whose password should be changed.
|new-password| - The new password.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential new-password] (gen-call :function ::change-insecure-credential &form credential new-password)))
(defmacro remove-insecure-credential
"Requests to remove |credential| from the password store. Invokes |callback| on completion.
|credential| - ?
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential] (gen-call :function ::remove-insecure-credential &form credential)))
(defmacro start-password-check
"Starts a check for insecure passwords. Invokes |callback| on completion.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::start-password-check &form)))
(defmacro stop-password-check
"Stops checking for insecure passwords. Invokes |callback| on completion.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::stop-password-check &form)))
(defmacro get-password-check-status
"Returns the current status of the check via |callback|.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [status] where:
|status| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-password-check-status &form)))
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: https://github.com/binaryage/chromex/#tapping-events
(defmacro tap-on-saved-passwords-list-changed-events
"Fired when the saved passwords list has changed, meaning that an entry has been added or removed.
Events will be put on the |channel| with signature [::on-saved-passwords-list-changed [entries]] where:
|entries| - The updated list of password entries.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-saved-passwords-list-changed &form channel args)))
(defmacro tap-on-password-exceptions-list-changed-events
"Fired when the password exceptions list has changed, meaning that an entry has been added or removed.
Events will be put on the |channel| with signature [::on-password-exceptions-list-changed [exceptions]] where:
|exceptions| - The updated list of password exceptions.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-password-exceptions-list-changed &form channel args)))
(defmacro tap-on-passwords-file-export-progress-events
"Fired when the status of the export has changed.
Events will be put on the |channel| with signature [::on-passwords-file-export-progress [status]] where:
|status| - The progress status and an optional UI message.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-passwords-file-export-progress &form channel args)))
(defmacro tap-on-account-storage-opt-in-state-changed-events
"Fired when the opt-in state for the account-scoped storage has changed.
Events will be put on the |channel| with signature [::on-account-storage-opt-in-state-changed [opted-in]] where:
|opted-in| - The new opt-in state.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-account-storage-opt-in-state-changed &form channel args)))
(defmacro tap-on-compromised-credentials-changed-events
"Fired when the compromised credentials changed.
Events will be put on the |channel| with signature [::on-compromised-credentials-changed [compromised-credentials]] where:
|compromised-credentials| - The updated compromised credentials.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-compromised-credentials-changed &form channel args)))
(defmacro tap-on-weak-credentials-changed-events
"Fired when the weak credentials changed.
Events will be put on the |channel| with signature [::on-weak-credentials-changed [weak-credentials]] where:
|weak-credentials| - The updated weak credentials.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-weak-credentials-changed &form channel args)))
(defmacro tap-on-password-check-status-changed-events
"Fired when the status of the password check changes.
Events will be put on the |channel| with signature [::on-password-check-status-changed [status]] where:
|status| - The updated status of the password check.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-password-check-status-changed &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.passwords-private namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.passwordsPrivate",
:since "master",
:functions
[{:id ::record-passwords-page-access-in-settings, :name "recordPasswordsPageAccessInSettings"}
{:id ::change-saved-password,
:name "changeSavedPassword",
:callback? true,
:params
[{:name "ids", :type "[array-of-integers]"}
{:name "new-username", :type "string"}
{:name "new-password", :type "string"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::remove-saved-password, :name "removeSavedPassword", :params [{:name "id", :type "integer"}]}
{:id ::remove-saved-passwords, :name "removeSavedPasswords", :params [{:name "ids", :type "[array-of-integers]"}]}
{:id ::remove-password-exception, :name "removePasswordException", :params [{:name "id", :type "integer"}]}
{:id ::remove-password-exceptions,
:name "removePasswordExceptions",
:params [{:name "ids", :type "[array-of-integers]"}]}
{:id ::undo-remove-saved-password-or-exception, :name "undoRemoveSavedPasswordOrException"}
{:id ::request-plaintext-password,
:name "requestPlaintextPassword",
:callback? true,
:params
[{:name "id", :type "integer"}
{:name "reason", :type "passwordsPrivate.PlaintextReason"}
{:name "callback", :type :callback, :callback {:params [{:name "password", :type "string"}]}}]}
{:id ::get-saved-password-list,
:name "getSavedPasswordList",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "entries", :type "[array-of-passwordsPrivate.PasswordUiEntrys]"}]}}]}
{:id ::get-password-exception-list,
:name "getPasswordExceptionList",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "exceptions", :type "[array-of-passwordsPrivate.ExceptionEntrys]"}]}}]}
{:id ::move-password-to-account, :name "movePasswordToAccount", :params [{:name "id", :type "integer"}]}
{:id ::import-passwords, :name "importPasswords"}
{:id ::export-passwords, :name "exportPasswords", :callback? true, :params [{:name "callback", :type :callback}]}
{:id ::request-export-progress-status,
:name "requestExportProgressStatus",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "status", :type "passwordsPrivate.ExportProgressStatus"}]}}]}
{:id ::cancel-export-passwords, :name "cancelExportPasswords"}
{:id ::is-opted-in-for-account-storage,
:name "isOptedInForAccountStorage",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "opted-in", :type "boolean"}]}}]}
{:id ::opt-in-for-account-storage, :name "optInForAccountStorage", :params [{:name "opt-in", :type "boolean"}]}
{:id ::get-compromised-credentials,
:name "getCompromisedCredentials",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "insecure-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}}]}
{:id ::get-weak-credentials,
:name "getWeakCredentials",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "insecure-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}}]}
{:id ::get-plaintext-insecure-password,
:name "getPlaintextInsecurePassword",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "reason", :type "passwordsPrivate.PlaintextReason"}
{:name "callback",
:type :callback,
:callback {:params [{:name "credential", :type "passwordsPrivate.InsecureCredential"}]}}]}
{:id ::change-insecure-credential,
:name "changeInsecureCredential",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "new-password", :type "string"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::remove-insecure-credential,
:name "removeInsecureCredential",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::start-password-check,
:name "startPasswordCheck",
:callback? true,
:params [{:name "callback", :optional? true, :type :callback}]}
{:id ::stop-password-check,
:name "stopPasswordCheck",
:callback? true,
:params [{:name "callback", :optional? true, :type :callback}]}
{:id ::get-password-check-status,
:name "getPasswordCheckStatus",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "status", :type "passwordsPrivate.PasswordCheckStatus"}]}}]}],
:events
[{:id ::on-saved-passwords-list-changed,
:name "onSavedPasswordsListChanged",
:params [{:name "entries", :type "[array-of-passwordsPrivate.PasswordUiEntrys]"}]}
{:id ::on-password-exceptions-list-changed,
:name "onPasswordExceptionsListChanged",
:params [{:name "exceptions", :type "[array-of-passwordsPrivate.ExceptionEntrys]"}]}
{:id ::on-passwords-file-export-progress,
:name "onPasswordsFileExportProgress",
:params [{:name "status", :type "object"}]}
{:id ::on-account-storage-opt-in-state-changed,
:name "onAccountStorageOptInStateChanged",
:params [{:name "opted-in", :type "boolean"}]}
{:id ::on-compromised-credentials-changed,
:name "onCompromisedCredentialsChanged",
:params [{:name "compromised-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}
{:id ::on-weak-credentials-changed,
:name "onWeakCredentialsChanged",
:params [{:name "weak-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}
{:id ::on-password-check-status-changed,
:name "onPasswordCheckStatusChanged",
:params [{:name "status", :type "passwordsPrivate.PasswordCheckStatus"}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table))
| true |
(ns chromex.app.passwords-private
"Use the chrome.passwordsPrivate API to add or remove password
data from the settings UI.
* available since Chrome master"
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
; -- functions --------------------------------------------------------------------------------------------------------------
(defmacro record-passwords-page-access-in-settings
"Function that logs that the Passwords page was accessed from the Chrome Settings WebUI."
([] (gen-call :function ::record-passwords-page-access-in-settings &form)))
(defmacro change-saved-password
"Changes the saved password corresponding to |ids|. Since the password can be stored in Google Account and on device, in
this case we want to change the password for accountId and deviceId. Invokes |callback| or raises an error depending on
whether the operation succeeded.
|ids| - The ids for the password entry being updated.
|new-username| - The new username.
|new-password| - The new PI:PASSWORD:<PASSWORD>END_PI.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([ids new-username new-password] (gen-call :function ::change-saved-password &form ids new-username new-password)))
(defmacro remove-saved-password
"Removes the saved password corresponding to |id|. If no saved password for this pair exists, this function is a no-op.
|id| - The id for the password entry being removed."
([id] (gen-call :function ::remove-saved-password &form id)))
(defmacro remove-saved-passwords
"Removes the saved password corresponding to |ids|. If no saved password exists for a certain id, that id is ignored.
Undoing this operation via undoRemoveSavedPasswordOrException will restore all the removed passwords in the batch.
|ids| - ?"
([ids] (gen-call :function ::remove-saved-passwords &form ids)))
(defmacro remove-password-exception
"Removes the saved password exception corresponding to |id|. If no exception with this id exists, this function is a no-op.
|id| - The id for the exception url entry being removed."
([id] (gen-call :function ::remove-password-exception &form id)))
(defmacro remove-password-exceptions
"Removes the saved password exceptions corresponding to |ids|. If no exception exists for a certain id, that id is ignored.
Undoing this operation via undoRemoveSavedPasswordOrException will restore all the removed exceptions in the batch.
|ids| - ?"
([ids] (gen-call :function ::remove-password-exceptions &form ids)))
(defmacro undo-remove-saved-password-or-exception
"Undoes the last removal of saved password(s) or exception(s)."
([] (gen-call :function ::undo-remove-saved-password-or-exception &form)))
(defmacro request-plaintext-password
"Returns the plaintext password corresponding to |id|. Note that on some operating systems, this call may result in an
OS-level reauthentication. Once the password has been fetched, it will be returned via |callback|.
|id| - The id for the password entry being being retrieved.
|reason| - The reason why the plaintext password is requested.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [password] where:
|password| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([id reason] (gen-call :function ::request-plaintext-password &form id reason)))
(defmacro get-saved-password-list
"Returns the list of saved passwords.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [entries] where:
|entries| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-saved-password-list &form)))
(defmacro get-password-exception-list
"Returns the list of password exceptions.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [exceptions] where:
|exceptions| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-password-exception-list &form)))
(defmacro move-password-to-account
"Moves a password currently stored on the device to being stored in the signed-in, non-syncing Google Account. The result is
a no-op if any of these is true: |id| is invalid; |id| corresponds to a password already stored in the account; or the user
is not using the account-scoped password storage.
|id| - The id for the password entry being moved."
([id] (gen-call :function ::move-password-to-account &form id)))
(defmacro import-passwords
"Triggers the Password Manager password import functionality."
([] (gen-call :function ::import-passwords &form)))
(defmacro export-passwords
"Triggers the Password Manager password export functionality. Completion Will be signaled by the
onPasswordsFileExportProgress event. |callback| will be called when the request is started or rejected. If rejected
'runtime.lastError' will be set to 'in-progress' or 'reauth-failed'.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::export-passwords &form)))
(defmacro request-export-progress-status
"Requests the export progress status. This is the same as the last value seen on the onPasswordsFileExportProgress event.
This function is useful for checking if an export has already been initiated from an older tab, where we might have missed
the original event.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [status] where:
|status| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::request-export-progress-status &form)))
(defmacro cancel-export-passwords
"Stops exporting passwords and cleans up any passwords, which were already written to the filesystem."
([] (gen-call :function ::cancel-export-passwords &form)))
(defmacro is-opted-in-for-account-storage
"Requests the account-storage opt-in state of the current user.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [opted-in] where:
|opted-in| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::is-opted-in-for-account-storage &form)))
(defmacro opt-in-for-account-storage
"Triggers the opt-in or opt-out flow for the account storage.
|opt-in| - ?"
([opt-in] (gen-call :function ::opt-in-for-account-storage &form opt-in)))
(defmacro get-compromised-credentials
"Requests the latest compromised credentials.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [insecure-credentials] where:
|insecure-credentials| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-compromised-credentials &form)))
(defmacro get-weak-credentials
"Requests the latest weak credentials.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [insecure-credentials] where:
|insecure-credentials| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-weak-credentials &form)))
(defmacro get-plaintext-insecure-password
"Requests the plaintext password for |credential|. |callback| gets invoked with the same |credential|, whose |password
field will be set.
|credential| - The insecure credential whose password is being retrieved.
|reason| - The reason why the plaintext password is requested.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [credential] where:
|credential| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential reason] (gen-call :function ::get-plaintext-insecure-password &form credential reason)))
(defmacro change-insecure-credential
"Requests to change the password of |credential| to |new_password|. Invokes |callback| or raises an error depending on
whether the operation succeeded.
|credential| - The credential whose password should be changed.
|new-password| - The new password.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential new-password] (gen-call :function ::change-insecure-credential &form credential new-password)))
(defmacro remove-insecure-credential
"Requests to remove |credential| from the password store. Invokes |callback| on completion.
|credential| - ?
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([credential] (gen-call :function ::remove-insecure-credential &form credential)))
(defmacro start-password-check
"Starts a check for insecure passwords. Invokes |callback| on completion.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::start-password-check &form)))
(defmacro stop-password-check
"Stops checking for insecure passwords. Invokes |callback| on completion.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [].
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::stop-password-check &form)))
(defmacro get-password-check-status
"Returns the current status of the check via |callback|.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [status] where:
|status| - ?
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error."
([] (gen-call :function ::get-password-check-status &form)))
; -- events -----------------------------------------------------------------------------------------------------------------
;
; docs: https://github.com/binaryage/chromex/#tapping-events
(defmacro tap-on-saved-passwords-list-changed-events
"Fired when the saved passwords list has changed, meaning that an entry has been added or removed.
Events will be put on the |channel| with signature [::on-saved-passwords-list-changed [entries]] where:
|entries| - The updated list of password entries.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-saved-passwords-list-changed &form channel args)))
(defmacro tap-on-password-exceptions-list-changed-events
"Fired when the password exceptions list has changed, meaning that an entry has been added or removed.
Events will be put on the |channel| with signature [::on-password-exceptions-list-changed [exceptions]] where:
|exceptions| - The updated list of password exceptions.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-password-exceptions-list-changed &form channel args)))
(defmacro tap-on-passwords-file-export-progress-events
"Fired when the status of the export has changed.
Events will be put on the |channel| with signature [::on-passwords-file-export-progress [status]] where:
|status| - The progress status and an optional UI message.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-passwords-file-export-progress &form channel args)))
(defmacro tap-on-account-storage-opt-in-state-changed-events
"Fired when the opt-in state for the account-scoped storage has changed.
Events will be put on the |channel| with signature [::on-account-storage-opt-in-state-changed [opted-in]] where:
|opted-in| - The new opt-in state.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-account-storage-opt-in-state-changed &form channel args)))
(defmacro tap-on-compromised-credentials-changed-events
"Fired when the compromised credentials changed.
Events will be put on the |channel| with signature [::on-compromised-credentials-changed [compromised-credentials]] where:
|compromised-credentials| - The updated compromised credentials.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-compromised-credentials-changed &form channel args)))
(defmacro tap-on-weak-credentials-changed-events
"Fired when the weak credentials changed.
Events will be put on the |channel| with signature [::on-weak-credentials-changed [weak-credentials]] where:
|weak-credentials| - The updated weak credentials.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-weak-credentials-changed &form channel args)))
(defmacro tap-on-password-check-status-changed-events
"Fired when the status of the password check changes.
Events will be put on the |channel| with signature [::on-password-check-status-changed [status]] where:
|status| - The updated status of the password check.
Note: |args| will be passed as additional parameters into Chrome event's .addListener call."
([channel & args] (apply gen-call :event ::on-password-check-status-changed &form channel args)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.passwords-private namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.passwordsPrivate",
:since "master",
:functions
[{:id ::record-passwords-page-access-in-settings, :name "recordPasswordsPageAccessInSettings"}
{:id ::change-saved-password,
:name "changeSavedPassword",
:callback? true,
:params
[{:name "ids", :type "[array-of-integers]"}
{:name "new-username", :type "string"}
{:name "new-password", :type "string"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::remove-saved-password, :name "removeSavedPassword", :params [{:name "id", :type "integer"}]}
{:id ::remove-saved-passwords, :name "removeSavedPasswords", :params [{:name "ids", :type "[array-of-integers]"}]}
{:id ::remove-password-exception, :name "removePasswordException", :params [{:name "id", :type "integer"}]}
{:id ::remove-password-exceptions,
:name "removePasswordExceptions",
:params [{:name "ids", :type "[array-of-integers]"}]}
{:id ::undo-remove-saved-password-or-exception, :name "undoRemoveSavedPasswordOrException"}
{:id ::request-plaintext-password,
:name "requestPlaintextPassword",
:callback? true,
:params
[{:name "id", :type "integer"}
{:name "reason", :type "passwordsPrivate.PlaintextReason"}
{:name "callback", :type :callback, :callback {:params [{:name "password", :type "string"}]}}]}
{:id ::get-saved-password-list,
:name "getSavedPasswordList",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "entries", :type "[array-of-passwordsPrivate.PasswordUiEntrys]"}]}}]}
{:id ::get-password-exception-list,
:name "getPasswordExceptionList",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "exceptions", :type "[array-of-passwordsPrivate.ExceptionEntrys]"}]}}]}
{:id ::move-password-to-account, :name "movePasswordToAccount", :params [{:name "id", :type "integer"}]}
{:id ::import-passwords, :name "importPasswords"}
{:id ::export-passwords, :name "exportPasswords", :callback? true, :params [{:name "callback", :type :callback}]}
{:id ::request-export-progress-status,
:name "requestExportProgressStatus",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "status", :type "passwordsPrivate.ExportProgressStatus"}]}}]}
{:id ::cancel-export-passwords, :name "cancelExportPasswords"}
{:id ::is-opted-in-for-account-storage,
:name "isOptedInForAccountStorage",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "opted-in", :type "boolean"}]}}]}
{:id ::opt-in-for-account-storage, :name "optInForAccountStorage", :params [{:name "opt-in", :type "boolean"}]}
{:id ::get-compromised-credentials,
:name "getCompromisedCredentials",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "insecure-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}}]}
{:id ::get-weak-credentials,
:name "getWeakCredentials",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "insecure-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}}]}
{:id ::get-plaintext-insecure-password,
:name "getPlaintextInsecurePassword",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "reason", :type "passwordsPrivate.PlaintextReason"}
{:name "callback",
:type :callback,
:callback {:params [{:name "credential", :type "passwordsPrivate.InsecureCredential"}]}}]}
{:id ::change-insecure-credential,
:name "changeInsecureCredential",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "new-password", :type "string"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::remove-insecure-credential,
:name "removeInsecureCredential",
:callback? true,
:params
[{:name "credential", :type "passwordsPrivate.InsecureCredential"}
{:name "callback", :optional? true, :type :callback}]}
{:id ::start-password-check,
:name "startPasswordCheck",
:callback? true,
:params [{:name "callback", :optional? true, :type :callback}]}
{:id ::stop-password-check,
:name "stopPasswordCheck",
:callback? true,
:params [{:name "callback", :optional? true, :type :callback}]}
{:id ::get-password-check-status,
:name "getPasswordCheckStatus",
:callback? true,
:params
[{:name "callback",
:type :callback,
:callback {:params [{:name "status", :type "passwordsPrivate.PasswordCheckStatus"}]}}]}],
:events
[{:id ::on-saved-passwords-list-changed,
:name "onSavedPasswordsListChanged",
:params [{:name "entries", :type "[array-of-passwordsPrivate.PasswordUiEntrys]"}]}
{:id ::on-password-exceptions-list-changed,
:name "onPasswordExceptionsListChanged",
:params [{:name "exceptions", :type "[array-of-passwordsPrivate.ExceptionEntrys]"}]}
{:id ::on-passwords-file-export-progress,
:name "onPasswordsFileExportProgress",
:params [{:name "status", :type "object"}]}
{:id ::on-account-storage-opt-in-state-changed,
:name "onAccountStorageOptInStateChanged",
:params [{:name "opted-in", :type "boolean"}]}
{:id ::on-compromised-credentials-changed,
:name "onCompromisedCredentialsChanged",
:params [{:name "compromised-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}
{:id ::on-weak-credentials-changed,
:name "onWeakCredentialsChanged",
:params [{:name "weak-credentials", :type "[array-of-passwordsPrivate.InsecureCredentials]"}]}
{:id ::on-password-check-status-changed,
:name "onPasswordCheckStatusChanged",
:params [{:name "status", :type "passwordsPrivate.PasswordCheckStatus"}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table))
|
[
{
"context": ";; Copyright 2018 Chris Rink\n;;\n;; Licensed under the Apache License, Version ",
"end": 28,
"score": 0.999852180480957,
"start": 18,
"tag": "NAME",
"value": "Chris Rink"
}
] |
src/clojure/repopreview/web_server.clj
|
chrisrink10/repopreview
| 0 |
;; Copyright 2018 Chris Rink
;;
;; 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 repopreview.web-server
(:require
[clojure.spec.alpha :as s]
[mount.core :refer [defstate]]
[org.httpkit.server :as http]
[taoensso.timbre :as timbre]
[repopreview.config :as config]
[repopreview.routes :as routes]))
(s/def ::ip string?)
(s/def ::port (s/int-in 1 65536))
(s/def ::thread (s/int-in 1 9))
(s/def ::queue-size (s/int-in 10000 100000))
(s/def ::max-body (s/int-in 524288 16777216))
(s/def ::max-line (s/int-in 512 8192))
(s/def ::opts (s/keys :req-un [::port]
:opt-un [::ip ::thread ::queue-size ::max-body ::max-line]))
(s/def ::stop-fn ifn?)
(s/fdef start
:args (s/cat :opts (s/? ::opts)))
(defn start
"Start the HTTP Kit server."
([]
(-> [:web-server] (config/config) (start)))
([opts]
(try
(let [server (http/run-server #'routes/repopreview-app opts)]
(timbre/info {:message "Web server started" :opts opts})
server)
(catch Throwable t
(timbre/error {:message "Failed to start web server"
:opts opts
:exception t})
(throw t)))))
(s/fdef stop
:args (s/cat :server ::stop-fn))
(defn stop
"Stop the HTTP Kit server.
HTTP Kit's `(run-server)' function returns a function that can
be used to stop the server. This function accepts that function
and calls it."
[server]
(try
(do
(server)
(timbre/info {:message "Web server stopped"}))
(catch Throwable t
(timbre/error {:message "Failed to stop web server"
:exception t})
(throw t))))
(defstate web-server
:start (start)
:stop (stop web-server))
|
54513
|
;; Copyright 2018 <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 repopreview.web-server
(:require
[clojure.spec.alpha :as s]
[mount.core :refer [defstate]]
[org.httpkit.server :as http]
[taoensso.timbre :as timbre]
[repopreview.config :as config]
[repopreview.routes :as routes]))
(s/def ::ip string?)
(s/def ::port (s/int-in 1 65536))
(s/def ::thread (s/int-in 1 9))
(s/def ::queue-size (s/int-in 10000 100000))
(s/def ::max-body (s/int-in 524288 16777216))
(s/def ::max-line (s/int-in 512 8192))
(s/def ::opts (s/keys :req-un [::port]
:opt-un [::ip ::thread ::queue-size ::max-body ::max-line]))
(s/def ::stop-fn ifn?)
(s/fdef start
:args (s/cat :opts (s/? ::opts)))
(defn start
"Start the HTTP Kit server."
([]
(-> [:web-server] (config/config) (start)))
([opts]
(try
(let [server (http/run-server #'routes/repopreview-app opts)]
(timbre/info {:message "Web server started" :opts opts})
server)
(catch Throwable t
(timbre/error {:message "Failed to start web server"
:opts opts
:exception t})
(throw t)))))
(s/fdef stop
:args (s/cat :server ::stop-fn))
(defn stop
"Stop the HTTP Kit server.
HTTP Kit's `(run-server)' function returns a function that can
be used to stop the server. This function accepts that function
and calls it."
[server]
(try
(do
(server)
(timbre/info {:message "Web server stopped"}))
(catch Throwable t
(timbre/error {:message "Failed to stop web server"
:exception t})
(throw t))))
(defstate web-server
:start (start)
:stop (stop web-server))
| true |
;; Copyright 2018 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 repopreview.web-server
(:require
[clojure.spec.alpha :as s]
[mount.core :refer [defstate]]
[org.httpkit.server :as http]
[taoensso.timbre :as timbre]
[repopreview.config :as config]
[repopreview.routes :as routes]))
(s/def ::ip string?)
(s/def ::port (s/int-in 1 65536))
(s/def ::thread (s/int-in 1 9))
(s/def ::queue-size (s/int-in 10000 100000))
(s/def ::max-body (s/int-in 524288 16777216))
(s/def ::max-line (s/int-in 512 8192))
(s/def ::opts (s/keys :req-un [::port]
:opt-un [::ip ::thread ::queue-size ::max-body ::max-line]))
(s/def ::stop-fn ifn?)
(s/fdef start
:args (s/cat :opts (s/? ::opts)))
(defn start
"Start the HTTP Kit server."
([]
(-> [:web-server] (config/config) (start)))
([opts]
(try
(let [server (http/run-server #'routes/repopreview-app opts)]
(timbre/info {:message "Web server started" :opts opts})
server)
(catch Throwable t
(timbre/error {:message "Failed to start web server"
:opts opts
:exception t})
(throw t)))))
(s/fdef stop
:args (s/cat :server ::stop-fn))
(defn stop
"Stop the HTTP Kit server.
HTTP Kit's `(run-server)' function returns a function that can
be used to stop the server. This function accepts that function
and calls it."
[server]
(try
(do
(server)
(timbre/info {:message "Web server stopped"}))
(catch Throwable t
(timbre/error {:message "Failed to stop web server"
:exception t})
(throw t))))
(defstate web-server
:start (start)
:stop (stop web-server))
|
[
{
"context": "ard the-choice})))\n ;; Start id\n sunny \"Sunny Lebeau: Security Specialist\"\n ;; List of all G-Mod ",
"end": 603,
"score": 0.9892364740371704,
"start": 591,
"tag": "NAME",
"value": "Sunny Lebeau"
},
{
"context": " ;; List of all G-Mod identities\n geist \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n kate \"Kate \\\"M",
"end": 683,
"score": 0.9944118857383728,
"start": 677,
"tag": "NAME",
"value": "Armand"
},
{
"context": "ist of all G-Mod identities\n geist \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n kate \"Kate \\\"Mac\\\" McC",
"end": 691,
"score": 0.8944457173347473,
"start": 686,
"tag": "NAME",
"value": "Geist"
},
{
"context": "all G-Mod identities\n geist \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n kate \"Kate \\\"Mac\\\" McCaffrey: D",
"end": 700,
"score": 0.7156418561935425,
"start": 694,
"tag": "NAME",
"value": "Walker"
},
{
"context": " \"Armand \\\"Geist\\\" Walker: Tech Lord\"\n kate \"Kate \\\"Mac\\\" McCaffrey: Digital Tinker\"\n kit \"Rie",
"end": 729,
"score": 0.994908332824707,
"start": 725,
"tag": "NAME",
"value": "Kate"
},
{
"context": "d \\\"Geist\\\" Walker: Tech Lord\"\n kate \"Kate \\\"Mac\\\" McCaffrey: Digital Tinker\"\n kit \"Rielle \\\"",
"end": 735,
"score": 0.8915444016456604,
"start": 732,
"tag": "NAME",
"value": "Mac"
},
{
"context": "eist\\\" Walker: Tech Lord\"\n kate \"Kate \\\"Mac\\\" McCaffrey: Digital Tinker\"\n kit \"Rielle \\\"Kit\\\" Peddle",
"end": 747,
"score": 0.9131300449371338,
"start": 738,
"tag": "NAME",
"value": "McCaffrey"
},
{
"context": "ate \\\"Mac\\\" McCaffrey: Digital Tinker\"\n kit \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n professor \"The",
"end": 782,
"score": 0.984468936920166,
"start": 776,
"tag": "NAME",
"value": "Rielle"
},
{
"context": "\\\" McCaffrey: Digital Tinker\"\n kit \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n professor \"The Profe",
"end": 788,
"score": 0.39591649174690247,
"start": 785,
"tag": "NAME",
"value": "Kit"
},
{
"context": "Caffrey: Digital Tinker\"\n kit \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n professor \"The Professor: Keep",
"end": 798,
"score": 0.942376434803009,
"start": 791,
"tag": "NAME",
"value": "Peddler"
},
{
"context": "\"The Professor: Keeper of Knowledge\"\n jamie \"Jamie \\\"Bzzz\\\" Micken: Techno Savant\"\n chaos \"Chaos Theor",
"end": 890,
"score": 0.9276041388511658,
"start": 878,
"tag": "NAME",
"value": "Jamie \\\"Bzzz"
},
{
"context": ": Keeper of Knowledge\"\n jamie \"Jamie \\\"Bzzz\\\" Micken: Techno Savant\"\n chaos \"Chaos Theory: Wünder",
"end": 899,
"score": 0.9355872273445129,
"start": 893,
"tag": "NAME",
"value": "Micken"
},
{
"context": " whizzard \"Whizzard: Master Gamer\"\n reina \"Reina Roja: Freedom Fighter\"\n maxx \"MaxX: Maximum Punk ",
"end": 1018,
"score": 0.9688529968261719,
"start": 1008,
"tag": "NAME",
"value": "Reina Roja"
},
{
"context": "aximum Punk Rock\"]\n\n (deftest dj-fenris\n ;; DJ Fenris - host 1 g-mod id not in faction on DJ Fenris\n",
"end": 1110,
"score": 0.7275213003158569,
"start": 1107,
"tag": "NAME",
"value": "Fen"
},
{
"context": "-contestant)\n ;; Challenger id is Gabe, make sure Geist is not in list (would be firs",
"end": 1332,
"score": 0.5225717425346375,
"start": 1331,
"tag": "NAME",
"value": "G"
},
{
"context": "ld be first)\n (make-deck sunny [\"DJ Fenris\"]) {:start-as :challenger})\n (play-from-ha",
"end": 1431,
"score": 0.9979626536369324,
"start": 1422,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "nger})\n (play-from-hand state :challenger \"DJ Fenris\")\n (is (= (first (prompt-titles :challenge",
"end": 1512,
"score": 0.9986041188240051,
"start": 1503,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "rompt-titles :challenger))\n [professor whizzard jamie kate kit]))\n (choose-challe",
"end": 1794,
"score": 0.77655029296875,
"start": 1785,
"tag": "NAME",
"value": "professor"
},
{
"context": "les :challenger))\n [professor whizzard jamie kate kit]))\n (choose-challenger chao",
"end": 1803,
"score": 0.9995546340942383,
"start": 1795,
"tag": "NAME",
"value": "whizzard"
},
{
"context": "lenger))\n [professor whizzard jamie kate kit]))\n (choose-challenger chaos stat",
"end": 1809,
"score": 0.8484652042388916,
"start": 1804,
"tag": "NAME",
"value": "jamie"
},
{
"context": "))\n [professor whizzard jamie kate kit]))\n (choose-challenger chaos state prompt-",
"end": 1818,
"score": 0.9205815196037292,
"start": 1810,
"tag": "NAME",
"value": "kate kit"
},
{
"context": "te 0) [:hosted 0 :title])) \"Chaos Theory hosted on DJ Fenris\")\n (is (= sunny (:title (:identity (get-ch",
"end": 1978,
"score": 0.9705600738525391,
"start": 1969,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "te)) \"+1 MU from Chaos Theory\")\n ;; Discard DJ Fenris\n (discard-radicle state \"DJ Fenris\")\n ",
"end": 2235,
"score": 0.9946848154067993,
"start": 2226,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "Discard DJ Fenris\n (discard-radicle state \"DJ Fenris\")\n (is (= chaos (get-in (get-challenger) [",
"end": 2277,
"score": 0.9959080219268799,
"start": 2268,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "unt (:discard (get-challenger)))) \"1 card in heap: DJ Fenris\")\n (is (= 4 (core/available-mu state)) \"+1",
"end": 2453,
"score": 0.9849816560745239,
"start": 2444,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": " MU from Chaos Theory removed\")\n ;; Recover DJ Fenris\n (core/move state :challenger (get-in (get",
"end": 2563,
"score": 0.9805741310119629,
"start": 2554,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "in state :challenger :credit 3)\n ;; Re-play DJ Fenris\n (play-from-hand state :challenger \"DJ Fen",
"end": 2723,
"score": 0.9848202466964722,
"start": 2714,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "Fenris\n (play-from-hand state :challenger \"DJ Fenris\")\n (choose-challenger chaos state prompt-m",
"end": 2776,
"score": 0.9993121027946472,
"start": 2767,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "-contestant)\n ;; Challenger id is Gabe, make sure Geist is not in list (would be first)\n",
"end": 3381,
"score": 0.8806698322296143,
"start": 3377,
"tag": "NAME",
"value": "Gabe"
},
{
"context": "ld be first)\n (make-deck sunny [\"DJ Fenris\" (qty \"All-nighter\" 3) (qty \"Sure Gamble\" 3)]) {:",
"end": 3477,
"score": 0.9995993971824646,
"start": 3468,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "nger})\n (starting-hand state :challenger [\"DJ Fenris\" \"All-nighter\" \"All-nighter\"])\n (play-from",
"end": 3602,
"score": 0.9997562170028687,
"start": 3593,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "hter\")\n (play-from-hand state :challenger \"DJ Fenris\")\n (is (= (first (prompt-titles :challenge",
"end": 3800,
"score": 0.9997010231018066,
"start": 3791,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "les :challenger))\n [professor whizzard jamie kate kit]))\n (choose-challenger geis",
"end": 4091,
"score": 0.9977433085441589,
"start": 4083,
"tag": "NAME",
"value": "whizzard"
},
{
"context": "lenger))\n [professor whizzard jamie kate kit]))\n (choose-challenger geist stat",
"end": 4097,
"score": 0.9923338890075684,
"start": 4092,
"tag": "NAME",
"value": "jamie"
},
{
"context": "))\n [professor whizzard jamie kate kit]))\n (choose-challenger geist state pro",
"end": 4102,
"score": 0.8383461236953735,
"start": 4098,
"tag": "NAME",
"value": "kate"
},
{
"context": "cle state 2) [:hosted 0 :title])) \"Geist hosted on DJ Fenris\")\n (is (= sunny (:title (:identity (get-ch",
"end": 4259,
"score": 0.9918200373649597,
"start": 4250,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "scard ability\")\n (discard-radicle state \"DJ Fenris\")\n (is (= geist (get-in (get-challenger)",
"end": 4779,
"score": 0.9977051615715027,
"start": 4770,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": "t-challenger)))) \"2 cards in heap: All-nighter and DJ Fenris\")\n (card-ability state :challenger (get-",
"end": 4969,
"score": 0.9974251985549927,
"start": 4960,
"tag": "NAME",
"value": "DJ Fenris"
},
{
"context": " draw another card - Geist ability removed when DJ Fenris was discarded\"))))))\n",
"end": 5212,
"score": 0.8953044414520264,
"start": 5206,
"tag": "NAME",
"value": "Fenris"
}
] |
test/clj/game_test/cards/radicles.clj
|
rezwits/carncode
| 15 |
(ns game-test.cards.radicles
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards (partial reset-card-defs "radicles"))
(let [choose-challenger
(fn [name state prompt-map]
(let [the-choice (some #(when (= name (:title %)) %) (:choices (prompt-map :challenger)))]
(core/resolve-prompt state :challenger {:card the-choice})))
;; Start id
sunny "Sunny Lebeau: Security Specialist"
;; List of all G-Mod identities
geist "Armand \"Geist\" Walker: Tech Lord"
kate "Kate \"Mac\" McCaffrey: Digital Tinker"
kit "Rielle \"Kit\" Peddler: Transhuman"
professor "The Professor: Keeper of Knowledge"
jamie "Jamie \"Bzzz\" Micken: Techno Savant"
chaos "Chaos Theory: Wünderkind"
whizzard "Whizzard: Master Gamer"
reina "Reina Roja: Freedom Fighter"
maxx "MaxX: Maximum Punk Rock"]
(deftest dj-fenris
;; DJ Fenris - host 1 g-mod id not in faction on DJ Fenris
(testing "Hosting Chaos Theory"
;; Ensure +1 MU is handled correctly
(do-game
(new-game (default-contestant)
;; Challenger id is Gabe, make sure Geist is not in list (would be first)
(make-deck sunny ["DJ Fenris"]) {:start-as :challenger})
(play-from-hand state :challenger "DJ Fenris")
(is (= (first (prompt-titles :challenger)) geist) "List is sorted")
(is (every? #(some #{%} (prompt-titles :challenger))
[geist chaos reina maxx]))
(is (not-any? #(some #{%} (prompt-titles :challenger))
[professor whizzard jamie kate kit]))
(choose-challenger chaos state prompt-map)
(is (= chaos (get-in (get-radicle state 0) [:hosted 0 :title])) "Chaos Theory hosted on DJ Fenris")
(is (= sunny (:title (:identity (get-challenger)))) "Still Sunny, id not changed")
(is (= 2 (:link (get-challenger))) "2 link from Sunny")
(is (= 5 (core/available-mu state)) "+1 MU from Chaos Theory")
;; Discard DJ Fenris
(discard-radicle state "DJ Fenris")
(is (= chaos (get-in (get-challenger) [:rfg 0 :title])) "Chaos Theory moved to RFG")
(is (= 1 (count (:discard (get-challenger)))) "1 card in heap: DJ Fenris")
(is (= 4 (core/available-mu state)) "+1 MU from Chaos Theory removed")
;; Recover DJ Fenris
(core/move state :challenger (get-in (get-challenger) [:discard 0]) :hand)
(core/gain state :challenger :credit 3)
;; Re-play DJ Fenris
(play-from-hand state :challenger "DJ Fenris")
(choose-challenger chaos state prompt-map)
;; Try moving CT to hand
(game.core/move state :challenger (get-in (get-radicle state 0) [:hosted 0]) :hand)
(is (= chaos (get-in (get-challenger) [:rfg 0 :title])) "Chaos Theory moved to RFG")
(is (zero? (count (:hand (get-challenger)))) "Chaos Theory _not_ moved to hand")
(is (= 4 (core/available-mu state)) "+1 MU from Chaos Theory removed")))
(testing "Hosting Geist"
;; Ensure Geist effect triggers
(do-game
(new-game (default-contestant)
;; Challenger id is Gabe, make sure Geist is not in list (would be first)
(make-deck sunny ["DJ Fenris" (qty "All-nighter" 3) (qty "Sure Gamble" 3)]) {:start-as :challenger})
(starting-hand state :challenger ["DJ Fenris" "All-nighter" "All-nighter"])
(play-from-hand state :challenger "All-nighter")
(play-from-hand state :challenger "All-nighter")
(play-from-hand state :challenger "DJ Fenris")
(is (= (first (prompt-titles :challenger)) geist) "List is sorted")
(is (every? #(some #{%} (prompt-titles :challenger))
[geist chaos reina maxx]))
(is (not-any? #(some #{%} (prompt-titles :challenger))
[professor whizzard jamie kate kit]))
(choose-challenger geist state prompt-map)
(is (= geist (get-in (get-radicle state 2) [:hosted 0 :title])) "Geist hosted on DJ Fenris")
(is (= sunny (:title (:identity (get-challenger)))) "Still Sunny, id not changed")
(is (= 2 (:link (get-challenger))) "2 link from Sunny, no extra link from Geist")
(let [hand-count (count (:hand (get-challenger)))]
(card-ability state :challenger (get-radicle state 0) 0) ; Use All-nighter
(is (= (+ 1 hand-count) (count (:hand (get-challenger))))
"Drew one card with Geist when using All-nighter discard ability")
(discard-radicle state "DJ Fenris")
(is (= geist (get-in (get-challenger) [:rfg 0 :title])) "Geist moved to RFG")
(is (= 2 (count (:discard (get-challenger)))) "2 cards in heap: All-nighter and DJ Fenris")
(card-ability state :challenger (get-radicle state 0) 0) ; Use All-nighter (again)
(is (= (+ 1 hand-count) (count (:hand (get-challenger))))
"Did not draw another card - Geist ability removed when DJ Fenris was discarded"))))))
|
1652
|
(ns game-test.cards.radicles
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards (partial reset-card-defs "radicles"))
(let [choose-challenger
(fn [name state prompt-map]
(let [the-choice (some #(when (= name (:title %)) %) (:choices (prompt-map :challenger)))]
(core/resolve-prompt state :challenger {:card the-choice})))
;; Start id
sunny "<NAME>: Security Specialist"
;; List of all G-Mod identities
geist "<NAME> \"<NAME>\" <NAME>: Tech Lord"
kate "<NAME> \"<NAME>\" <NAME>: Digital Tinker"
kit "<NAME> \"<NAME>\" <NAME>: Transhuman"
professor "The Professor: Keeper of Knowledge"
jamie "<NAME>\" <NAME>: Techno Savant"
chaos "Chaos Theory: Wünderkind"
whizzard "Whizzard: Master Gamer"
reina "<NAME>: Freedom Fighter"
maxx "MaxX: Maximum Punk Rock"]
(deftest dj-fenris
;; DJ <NAME>ris - host 1 g-mod id not in faction on DJ Fenris
(testing "Hosting Chaos Theory"
;; Ensure +1 MU is handled correctly
(do-game
(new-game (default-contestant)
;; Challenger id is <NAME>abe, make sure Geist is not in list (would be first)
(make-deck sunny ["<NAME>"]) {:start-as :challenger})
(play-from-hand state :challenger "<NAME>")
(is (= (first (prompt-titles :challenger)) geist) "List is sorted")
(is (every? #(some #{%} (prompt-titles :challenger))
[geist chaos reina maxx]))
(is (not-any? #(some #{%} (prompt-titles :challenger))
[<NAME> <NAME> <NAME> <NAME>]))
(choose-challenger chaos state prompt-map)
(is (= chaos (get-in (get-radicle state 0) [:hosted 0 :title])) "Chaos Theory hosted on <NAME>")
(is (= sunny (:title (:identity (get-challenger)))) "Still Sunny, id not changed")
(is (= 2 (:link (get-challenger))) "2 link from Sunny")
(is (= 5 (core/available-mu state)) "+1 MU from Chaos Theory")
;; Discard <NAME>
(discard-radicle state "<NAME>")
(is (= chaos (get-in (get-challenger) [:rfg 0 :title])) "Chaos Theory moved to RFG")
(is (= 1 (count (:discard (get-challenger)))) "1 card in heap: <NAME>")
(is (= 4 (core/available-mu state)) "+1 MU from Chaos Theory removed")
;; Recover <NAME>
(core/move state :challenger (get-in (get-challenger) [:discard 0]) :hand)
(core/gain state :challenger :credit 3)
;; Re-play <NAME>
(play-from-hand state :challenger "<NAME>")
(choose-challenger chaos state prompt-map)
;; Try moving CT to hand
(game.core/move state :challenger (get-in (get-radicle state 0) [:hosted 0]) :hand)
(is (= chaos (get-in (get-challenger) [:rfg 0 :title])) "Chaos Theory moved to RFG")
(is (zero? (count (:hand (get-challenger)))) "Chaos Theory _not_ moved to hand")
(is (= 4 (core/available-mu state)) "+1 MU from Chaos Theory removed")))
(testing "Hosting Geist"
;; Ensure Geist effect triggers
(do-game
(new-game (default-contestant)
;; Challenger id is <NAME>, make sure Geist is not in list (would be first)
(make-deck sunny ["<NAME>" (qty "All-nighter" 3) (qty "Sure Gamble" 3)]) {:start-as :challenger})
(starting-hand state :challenger ["<NAME>" "All-nighter" "All-nighter"])
(play-from-hand state :challenger "All-nighter")
(play-from-hand state :challenger "All-nighter")
(play-from-hand state :challenger "<NAME>")
(is (= (first (prompt-titles :challenger)) geist) "List is sorted")
(is (every? #(some #{%} (prompt-titles :challenger))
[geist chaos reina maxx]))
(is (not-any? #(some #{%} (prompt-titles :challenger))
[professor <NAME> <NAME> <NAME> kit]))
(choose-challenger geist state prompt-map)
(is (= geist (get-in (get-radicle state 2) [:hosted 0 :title])) "Geist hosted on <NAME>")
(is (= sunny (:title (:identity (get-challenger)))) "Still Sunny, id not changed")
(is (= 2 (:link (get-challenger))) "2 link from Sunny, no extra link from Geist")
(let [hand-count (count (:hand (get-challenger)))]
(card-ability state :challenger (get-radicle state 0) 0) ; Use All-nighter
(is (= (+ 1 hand-count) (count (:hand (get-challenger))))
"Drew one card with Geist when using All-nighter discard ability")
(discard-radicle state "<NAME>")
(is (= geist (get-in (get-challenger) [:rfg 0 :title])) "Geist moved to RFG")
(is (= 2 (count (:discard (get-challenger)))) "2 cards in heap: All-nighter and <NAME>")
(card-ability state :challenger (get-radicle state 0) 0) ; Use All-nighter (again)
(is (= (+ 1 hand-count) (count (:hand (get-challenger))))
"Did not draw another card - Geist ability removed when DJ <NAME> was discarded"))))))
| true |
(ns game-test.cards.radicles
(:require [game.core :as core]
[game-test.core :refer :all]
[game-test.utils :refer :all]
[game-test.macros :refer :all]
[clojure.test :refer :all]))
(use-fixtures :once load-all-cards (partial reset-card-defs "radicles"))
(let [choose-challenger
(fn [name state prompt-map]
(let [the-choice (some #(when (= name (:title %)) %) (:choices (prompt-map :challenger)))]
(core/resolve-prompt state :challenger {:card the-choice})))
;; Start id
sunny "PI:NAME:<NAME>END_PI: Security Specialist"
;; List of all G-Mod identities
geist "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Tech Lord"
kate "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Digital Tinker"
kit "PI:NAME:<NAME>END_PI \"PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Transhuman"
professor "The Professor: Keeper of Knowledge"
jamie "PI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Techno Savant"
chaos "Chaos Theory: Wünderkind"
whizzard "Whizzard: Master Gamer"
reina "PI:NAME:<NAME>END_PI: Freedom Fighter"
maxx "MaxX: Maximum Punk Rock"]
(deftest dj-fenris
;; DJ PI:NAME:<NAME>END_PIris - host 1 g-mod id not in faction on DJ Fenris
(testing "Hosting Chaos Theory"
;; Ensure +1 MU is handled correctly
(do-game
(new-game (default-contestant)
;; Challenger id is PI:NAME:<NAME>END_PIabe, make sure Geist is not in list (would be first)
(make-deck sunny ["PI:NAME:<NAME>END_PI"]) {:start-as :challenger})
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(is (= (first (prompt-titles :challenger)) geist) "List is sorted")
(is (every? #(some #{%} (prompt-titles :challenger))
[geist chaos reina maxx]))
(is (not-any? #(some #{%} (prompt-titles :challenger))
[PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI]))
(choose-challenger chaos state prompt-map)
(is (= chaos (get-in (get-radicle state 0) [:hosted 0 :title])) "Chaos Theory hosted on PI:NAME:<NAME>END_PI")
(is (= sunny (:title (:identity (get-challenger)))) "Still Sunny, id not changed")
(is (= 2 (:link (get-challenger))) "2 link from Sunny")
(is (= 5 (core/available-mu state)) "+1 MU from Chaos Theory")
;; Discard PI:NAME:<NAME>END_PI
(discard-radicle state "PI:NAME:<NAME>END_PI")
(is (= chaos (get-in (get-challenger) [:rfg 0 :title])) "Chaos Theory moved to RFG")
(is (= 1 (count (:discard (get-challenger)))) "1 card in heap: PI:NAME:<NAME>END_PI")
(is (= 4 (core/available-mu state)) "+1 MU from Chaos Theory removed")
;; Recover PI:NAME:<NAME>END_PI
(core/move state :challenger (get-in (get-challenger) [:discard 0]) :hand)
(core/gain state :challenger :credit 3)
;; Re-play PI:NAME:<NAME>END_PI
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(choose-challenger chaos state prompt-map)
;; Try moving CT to hand
(game.core/move state :challenger (get-in (get-radicle state 0) [:hosted 0]) :hand)
(is (= chaos (get-in (get-challenger) [:rfg 0 :title])) "Chaos Theory moved to RFG")
(is (zero? (count (:hand (get-challenger)))) "Chaos Theory _not_ moved to hand")
(is (= 4 (core/available-mu state)) "+1 MU from Chaos Theory removed")))
(testing "Hosting Geist"
;; Ensure Geist effect triggers
(do-game
(new-game (default-contestant)
;; Challenger id is PI:NAME:<NAME>END_PI, make sure Geist is not in list (would be first)
(make-deck sunny ["PI:NAME:<NAME>END_PI" (qty "All-nighter" 3) (qty "Sure Gamble" 3)]) {:start-as :challenger})
(starting-hand state :challenger ["PI:NAME:<NAME>END_PI" "All-nighter" "All-nighter"])
(play-from-hand state :challenger "All-nighter")
(play-from-hand state :challenger "All-nighter")
(play-from-hand state :challenger "PI:NAME:<NAME>END_PI")
(is (= (first (prompt-titles :challenger)) geist) "List is sorted")
(is (every? #(some #{%} (prompt-titles :challenger))
[geist chaos reina maxx]))
(is (not-any? #(some #{%} (prompt-titles :challenger))
[professor PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI kit]))
(choose-challenger geist state prompt-map)
(is (= geist (get-in (get-radicle state 2) [:hosted 0 :title])) "Geist hosted on PI:NAME:<NAME>END_PI")
(is (= sunny (:title (:identity (get-challenger)))) "Still Sunny, id not changed")
(is (= 2 (:link (get-challenger))) "2 link from Sunny, no extra link from Geist")
(let [hand-count (count (:hand (get-challenger)))]
(card-ability state :challenger (get-radicle state 0) 0) ; Use All-nighter
(is (= (+ 1 hand-count) (count (:hand (get-challenger))))
"Drew one card with Geist when using All-nighter discard ability")
(discard-radicle state "PI:NAME:<NAME>END_PI")
(is (= geist (get-in (get-challenger) [:rfg 0 :title])) "Geist moved to RFG")
(is (= 2 (count (:discard (get-challenger)))) "2 cards in heap: All-nighter and PI:NAME:<NAME>END_PI")
(card-ability state :challenger (get-radicle state 0) 0) ; Use All-nighter (again)
(is (= (+ 1 hand-count) (count (:hand (get-challenger))))
"Did not draw another card - Geist ability removed when DJ PI:NAME:<NAME>END_PI was discarded"))))))
|
[
{
"context": ":scm {:name \"git\"\n :url \"[email protected]:thi-ng/tweeny.git\"}\n\n :min-lein-vesion \"2.4.0\"\n\n",
"end": 375,
"score": 0.9996618032455444,
"start": 361,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": ":name \"git\"\n :url \"[email protected]:thi-ng/tweeny.git\"}\n\n :min-lein-vesion \"2.4.0\"\n\n :depe",
"end": 382,
"score": 0.9968187808990479,
"start": 376,
"tag": "USERNAME",
"value": "thi-ng"
},
{
"context": "[:developer\n [:name \"Karsten Schmidt\"]\n [:url \"http://pos",
"end": 2407,
"score": 0.9997857809066772,
"start": 2392,
"tag": "NAME",
"value": "Karsten Schmidt"
}
] |
project.clj
|
thi-ng/tweeny
| 24 |
(defproject thi.ng/tweeny "0.1.0-SNAPSHOT"
:description "Keyframe animation & tweening functions for Clojure"
:url "http://thi.ng/tweeny"
:license {:name "Apache Software License 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"
:distribution :repo}
:scm {:name "git"
:url "[email protected]:thi-ng/tweeny.git"}
:min-lein-vesion "2.4.0"
:dependencies [[org.clojure/clojure "1.6.0"]]
:profiles {:dev {:dependencies [[org.clojure/clojurescript "0.0-2657"]
[criterium "0.4.3"]]
:plugins [[com.keminglabs/cljx "0.5.0"]
[lein-cljsbuild "1.0.4"]
[com.cemerick/clojurescript.test "0.3.3"]]
:global-vars {*warn-on-reflection* true}
:jvm-opts ^:replace []
:auto-clean false
:prep-tasks [["cljx" "once"]]
:aliases {"cleantest" ["do" "clean," "cljx" "once," "test," "cljsbuild" "test"]
"deploy" ["do" "clean," "cljx" "once," "deploy" "clojars"]}}}
:cljx {:builds [{:source-paths ["src/cljx"]
:output-path "target/classes"
:rules :clj}
{:source-paths ["src/cljx"]
:output-path "target/classes"
:rules :cljs}
{:source-paths ["test/cljx"]
:output-path "target/test-classes"
:rules :clj}
{:source-paths ["test/cljx"]
:output-path "target/test-classes"
:rules :cljs}]}
:cljsbuild {:builds [{:source-paths ["target/classes" "target/test-classes"]
:id "simple"
:compiler {:output-to "target/tweeny-0.1.0-SNAPSHOT.js"
:optimizations :whitespace
:pretty-print true}}]
:test-commands {"unit-tests" ["phantomjs" :runner "target/tweeny-0.1.0-SNAPSHOT.js"]}}
:jar-exclusions [#"\.cljx|\.DS_Store"]
:pom-addition [:developers [:developer
[:name "Karsten Schmidt"]
[:url "http://postspectacular.com"]
[:timezone "0"]]])
|
36055
|
(defproject thi.ng/tweeny "0.1.0-SNAPSHOT"
:description "Keyframe animation & tweening functions for Clojure"
:url "http://thi.ng/tweeny"
:license {:name "Apache Software License 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"
:distribution :repo}
:scm {:name "git"
:url "<EMAIL>:thi-ng/tweeny.git"}
:min-lein-vesion "2.4.0"
:dependencies [[org.clojure/clojure "1.6.0"]]
:profiles {:dev {:dependencies [[org.clojure/clojurescript "0.0-2657"]
[criterium "0.4.3"]]
:plugins [[com.keminglabs/cljx "0.5.0"]
[lein-cljsbuild "1.0.4"]
[com.cemerick/clojurescript.test "0.3.3"]]
:global-vars {*warn-on-reflection* true}
:jvm-opts ^:replace []
:auto-clean false
:prep-tasks [["cljx" "once"]]
:aliases {"cleantest" ["do" "clean," "cljx" "once," "test," "cljsbuild" "test"]
"deploy" ["do" "clean," "cljx" "once," "deploy" "clojars"]}}}
:cljx {:builds [{:source-paths ["src/cljx"]
:output-path "target/classes"
:rules :clj}
{:source-paths ["src/cljx"]
:output-path "target/classes"
:rules :cljs}
{:source-paths ["test/cljx"]
:output-path "target/test-classes"
:rules :clj}
{:source-paths ["test/cljx"]
:output-path "target/test-classes"
:rules :cljs}]}
:cljsbuild {:builds [{:source-paths ["target/classes" "target/test-classes"]
:id "simple"
:compiler {:output-to "target/tweeny-0.1.0-SNAPSHOT.js"
:optimizations :whitespace
:pretty-print true}}]
:test-commands {"unit-tests" ["phantomjs" :runner "target/tweeny-0.1.0-SNAPSHOT.js"]}}
:jar-exclusions [#"\.cljx|\.DS_Store"]
:pom-addition [:developers [:developer
[:name "<NAME>"]
[:url "http://postspectacular.com"]
[:timezone "0"]]])
| true |
(defproject thi.ng/tweeny "0.1.0-SNAPSHOT"
:description "Keyframe animation & tweening functions for Clojure"
:url "http://thi.ng/tweeny"
:license {:name "Apache Software License 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0"
:distribution :repo}
:scm {:name "git"
:url "PI:EMAIL:<EMAIL>END_PI:thi-ng/tweeny.git"}
:min-lein-vesion "2.4.0"
:dependencies [[org.clojure/clojure "1.6.0"]]
:profiles {:dev {:dependencies [[org.clojure/clojurescript "0.0-2657"]
[criterium "0.4.3"]]
:plugins [[com.keminglabs/cljx "0.5.0"]
[lein-cljsbuild "1.0.4"]
[com.cemerick/clojurescript.test "0.3.3"]]
:global-vars {*warn-on-reflection* true}
:jvm-opts ^:replace []
:auto-clean false
:prep-tasks [["cljx" "once"]]
:aliases {"cleantest" ["do" "clean," "cljx" "once," "test," "cljsbuild" "test"]
"deploy" ["do" "clean," "cljx" "once," "deploy" "clojars"]}}}
:cljx {:builds [{:source-paths ["src/cljx"]
:output-path "target/classes"
:rules :clj}
{:source-paths ["src/cljx"]
:output-path "target/classes"
:rules :cljs}
{:source-paths ["test/cljx"]
:output-path "target/test-classes"
:rules :clj}
{:source-paths ["test/cljx"]
:output-path "target/test-classes"
:rules :cljs}]}
:cljsbuild {:builds [{:source-paths ["target/classes" "target/test-classes"]
:id "simple"
:compiler {:output-to "target/tweeny-0.1.0-SNAPSHOT.js"
:optimizations :whitespace
:pretty-print true}}]
:test-commands {"unit-tests" ["phantomjs" :runner "target/tweeny-0.1.0-SNAPSHOT.js"]}}
:jar-exclusions [#"\.cljx|\.DS_Store"]
:pom-addition [:developers [:developer
[:name "PI:NAME:<NAME>END_PI"]
[:url "http://postspectacular.com"]
[:timezone "0"]]])
|
[
{
"context": "mon.testing FakeTicker]\n [com.github.benmanes.caffeine.cache Ticker]\n [java.util.co",
"end": 499,
"score": 0.8116111159324646,
"start": 496,
"tag": "USERNAME",
"value": "man"
},
{
"context": "t! reload-fails? true)\n (swap! db assoc :key 43)\n (.advance ticker 10 TimeUnit/SECONDS)\n ",
"end": 9186,
"score": 0.7333082556724548,
"start": 9184,
"tag": "KEY",
"value": "43"
},
{
"context": "needs to be refreshed\"\n (swap! db assoc :key 42)\n (.advance ticker 11 TimeUnit/SECONDS)\n ",
"end": 10861,
"score": 0.9668614268302917,
"start": 10859,
"tag": "KEY",
"value": "42"
},
{
"context": "t! reload-fails? true)\n (swap! db assoc :key 43)\n (.advance ticker 10 TimeUnit/SECONDS)\n ",
"end": 11191,
"score": 0.9264450669288635,
"start": 11189,
"tag": "KEY",
"value": "43"
}
] |
test/cloffeine/core_test.clj
|
asafch/cloffeine
| 0 |
(ns cloffeine.core-test
(:require [cloffeine.common :as common]
[cloffeine.cache :as cache]
[cloffeine.async-cache :as async-cache]
[cloffeine.loading-cache :as loading-cache]
[cloffeine.async-loading-cache :as async-loading-cache]
[clojure.test :refer [deftest is testing use-fixtures]]
[promesa.core :as p]
[clojure.string :as s])
(:import [com.google.common.testing FakeTicker]
[com.github.benmanes.caffeine.cache Ticker]
[java.util.concurrent TimeUnit]
[java.util.logging Logger Level]))
(defn configure-logger [test-fn]
(let [logger (Logger/getLogger "com.github.benmanes.caffeine")
initial-level (.getLevel logger)]
(.setLevel logger (Level/SEVERE))
(test-fn)
(.setLevel logger initial-level)))
(use-fixtures :each configure-logger)
(defn- reify-ticker [^FakeTicker ft]
(reify Ticker
(read [_this]
(.read ft))))
(deftest manual
(let [cache (cache/make-cache)]
(is (= 0 (cache/estimated-size cache)))
(cache/put! cache :key :v)
(is (= 1 (cache/estimated-size cache)))
(is (= :v (cache/get cache :key name)))
(cache/invalidate! cache :key)
(is (= "key" (cache/get cache :key name)))
(is (= {:key "key"}
(cache/get-all cache [:key] (fn [ks] (reduce
(fn [res k]
(assoc res k (name k)))
{}
ks)))))
(cache/invalidate-all! cache)
(is (= 0 (cache/estimated-size cache)))))
(deftest loading
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
lcache (loading-cache/make-cache cl {:recordStats true})]
(loading-cache/put! lcache :key :v)
(is (= :v (loading-cache/get lcache :key)))
(is (= 1 (:hitCount (common/stats lcache))))
(is (= 1 (:requestCount (common/stats lcache))))
(is (= 0 @loads))
(loading-cache/invalidate! lcache :key)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 2 (:requestCount (common/stats lcache))))
(is (= 1 (:loadCount (common/stats lcache))))
(is (= 0.5 (:hitRate (common/stats lcache))))
(is (= 0.5 (:missRate (common/stats lcache))))
(is (= 1 @loads))
(is (= "key" (loading-cache/get lcache :key name)))
(is (= 1 @loads))
(is (= "key" (cache/get lcache :key name)))
(is (= 1 @loads))
(cache/invalidate! lcache :key)
(is (= "key" (cache/get lcache :key name)))
(is (= 1 @loads))))
(deftest loading-exceptions
(let [loads (atom 0)
throw? (atom false)
load-nil? (atom false)
cl (common/reify-cache-loader (fn [k]
(cond
@throw? (throw (ex-info "fail" {}))
@load-nil? nil
:else (do
(swap! loads inc)
(name k)))))
ticker (FakeTicker.)
lcache (loading-cache/make-cache cl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(loading-cache/put! lcache :key :v)
(testing "successful get, existing key"
(is (= :v (loading-cache/get lcache :key)))
(is (= 0 @loads)))
(testing "loading a missing key"
(loading-cache/invalidate! lcache :key)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads)))
(testing "fail to load a missing key throws exception"
(reset! throw? true)
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"fail"
(loading-cache/get lcache :missing-key)))
(is (= 1 @loads)))
(testing "fail to load an expired key"
(is (true? @throw?))
(.advance ticker 11 TimeUnit/SECONDS)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads)))
(testing "loading a missing key but loader returns nil. nil returns, but mapping is not changed"
(reset! throw? false)
(reset! load-nil? true)
(is (nil? (loading-cache/get lcache :not-there)))
(is (= [:key] (keys (.asMap lcache)))))))
(deftest get-if-present
(let [cache (cache/make-cache)]
(cache/put! cache :key "v")
(cache/put! cache :key2 "v2")
(is (= "v" (cache/get-if-present cache :key)))
(is (= {:key "v"} (cache/get-all-present cache [:key "v2"])))
(is (nil? (cache/get-if-present cache :non-existent))))
(let [loading-cache (loading-cache/make-cache (common/reify-cache-loader str))]
(loading-cache/put! loading-cache :key "v")
(is (= (loading-cache/get-if-present loading-cache :key) "v"))
(loading-cache/invalidate! loading-cache :key)
(is (nil? (loading-cache/get-if-present loading-cache :key)))))
(deftest refresh-test
(let [loads (atom 0)
reloads (atom 0)
cl (common/reify-cache-loader
(fn [k]
(swap! loads inc)
(name k))
(fn [k _v]
(swap! reloads inc)
(name k)))
lcache (loading-cache/make-cache cl)]
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads))
(loading-cache/refresh lcache :key)
(Thread/sleep 10)
(is (= 1 @reloads))
(is (= 1 @loads))))
(deftest get-async
(let [acache (async-cache/make-cache)]
(async-cache/put! acache :key (p/resolved :v))
(is (= :v @(async-cache/get acache :key name)))
(async-cache/invalidate! acache :key)
(is (= "key" @(async-cache/get acache :key name))))
(let [alcache (async-loading-cache/make-cache (common/reify-cache-loader name))]
(async-cache/put! alcache :key (p/resolved :v))
(is (= :v @(async-loading-cache/get alcache :key name)))
(async-cache/invalidate! alcache :key)
(is (= "key" @(async-loading-cache/get alcache :key name)))))
(deftest get-if-present-async
(let [acache (async-cache/make-cache)]
(is (nil? (async-cache/get-if-present acache :key)))
(async-cache/put! acache :key (p/resolved :v))
(is (= :v @(async-cache/get-if-present acache :key))))
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
alcache (async-loading-cache/make-cache cl)]
(is (nil? (async-loading-cache/get-if-present alcache :key)))
(async-loading-cache/put! alcache :key (p/resolved :v))
(is (= :v @(async-loading-cache/get-if-present alcache :key)))
(is (= 0 @loads))))
(deftest get-async-loading
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
alcache (async-loading-cache/make-cache cl)]
(is (nil? (async-loading-cache/get-if-present alcache :key)))
(is (= 0 @loads))
(is (= "key" @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(async-loading-cache/invalidate! alcache :key)
(is (= "key" @(async-loading-cache/get alcache :key)))
(is (= 2 @loads))
(let [alcache2 (async-loading-cache/->LoadingCache alcache)]
(is (= "key" (loading-cache/get alcache2 :key)))
(is (= 2 @loads))
(is (= "key2" (loading-cache/get alcache2 :key2)))
(is (= 3 @loads)))))
(deftest auto-refresh
(let [loads (atom 0)
reloads (atom 0)
reload-fails? (atom false)
db (atom {:key 17})
cl (common/reify-cache-loader
(fn [k]
(swap! loads inc)
(get @db k))
(fn [k _old-v]
(swap! reloads inc)
(if @reload-fails?
(throw (Exception. (format "reload failed for key: %s" k)))
(get @db k))))
ticker (FakeTicker.)
lcache (loading-cache/make-cache cl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(testing "no key, load succeeds"
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key exists, just return from cache"
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key needs to be refreshed"
(swap! db assoc :key 42)
(.advance ticker 11 TimeUnit/SECONDS)
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(loading-cache/cleanup lcache)
(Thread/sleep 10)
(is (= 1 @reloads))
(is (= 42 (loading-cache/get lcache :key))))
(testing "time to refresh again, but reload fails"
(reset! reload-fails? true)
(swap! db assoc :key 43)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 (loading-cache/get lcache :key)))
(is (= 1 @reloads))
(is (= 42 (loading-cache/get lcache :key)))
(is (= 1 @reloads))
(reset! reload-fails? false)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 (loading-cache/get lcache :key)))
(loading-cache/cleanup lcache)
(Thread/sleep 10)
(is (= 2 @reloads))
(is (= 43 (loading-cache/get lcache :key)))
(is (= 2 @reloads)))))
(deftest async-auto-async-refresh
(let [loads (atom 0)
reloads (atom 0)
reload-fails? (atom false)
db (atom {:key 17})
acl (common/reify-async-cache-loader
(fn [k _executor]
(swap! loads inc)
(p/resolved (get @db k)))
(fn [k _old-v _executor]
(swap! reloads inc)
(if @reload-fails?
(p/resolved (ex-info "error" {}))
(p/resolved (get @db k)))))
ticker (FakeTicker.)
alcache (async-loading-cache/make-cache-async-loader acl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(testing "no key, load succeeds"
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key exists, just return from cache"
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key needs to be refreshed"
(swap! db assoc :key 42)
(.advance ticker 11 TimeUnit/SECONDS)
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 1 @reloads))
(is (= 42 @(async-loading-cache/get alcache :key))))
(testing "time to refresh again but relaod fails"
(reset! reload-fails? true)
(swap! db assoc :key 43)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 @(async-loading-cache/get alcache :key)))
(is (= 1 @reloads))
(reset! reload-fails? false)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 @(async-loading-cache/get alcache :key)))
(is (= 2 @reloads))
(is (= 43 @(async-loading-cache/get alcache :key))))))
(deftest compute
(let [c (cache/make-cache)
k "key"
remapper (fn [_k v]
(if (some? v)
(str v "bar")
"foo"))]
(cache/put! c k "foo")
(is (= "foobar" (cache/compute c k remapper)))
(doall
(pmap (fn [_]
(cache/compute c k remapper))
(range 100)))
(let [expected (s/join (concat ["foobar"] (repeat 100 "bar")))]
(is (= expected (cache/get-if-present c k))))))
|
62017
|
(ns cloffeine.core-test
(:require [cloffeine.common :as common]
[cloffeine.cache :as cache]
[cloffeine.async-cache :as async-cache]
[cloffeine.loading-cache :as loading-cache]
[cloffeine.async-loading-cache :as async-loading-cache]
[clojure.test :refer [deftest is testing use-fixtures]]
[promesa.core :as p]
[clojure.string :as s])
(:import [com.google.common.testing FakeTicker]
[com.github.benmanes.caffeine.cache Ticker]
[java.util.concurrent TimeUnit]
[java.util.logging Logger Level]))
(defn configure-logger [test-fn]
(let [logger (Logger/getLogger "com.github.benmanes.caffeine")
initial-level (.getLevel logger)]
(.setLevel logger (Level/SEVERE))
(test-fn)
(.setLevel logger initial-level)))
(use-fixtures :each configure-logger)
(defn- reify-ticker [^FakeTicker ft]
(reify Ticker
(read [_this]
(.read ft))))
(deftest manual
(let [cache (cache/make-cache)]
(is (= 0 (cache/estimated-size cache)))
(cache/put! cache :key :v)
(is (= 1 (cache/estimated-size cache)))
(is (= :v (cache/get cache :key name)))
(cache/invalidate! cache :key)
(is (= "key" (cache/get cache :key name)))
(is (= {:key "key"}
(cache/get-all cache [:key] (fn [ks] (reduce
(fn [res k]
(assoc res k (name k)))
{}
ks)))))
(cache/invalidate-all! cache)
(is (= 0 (cache/estimated-size cache)))))
(deftest loading
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
lcache (loading-cache/make-cache cl {:recordStats true})]
(loading-cache/put! lcache :key :v)
(is (= :v (loading-cache/get lcache :key)))
(is (= 1 (:hitCount (common/stats lcache))))
(is (= 1 (:requestCount (common/stats lcache))))
(is (= 0 @loads))
(loading-cache/invalidate! lcache :key)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 2 (:requestCount (common/stats lcache))))
(is (= 1 (:loadCount (common/stats lcache))))
(is (= 0.5 (:hitRate (common/stats lcache))))
(is (= 0.5 (:missRate (common/stats lcache))))
(is (= 1 @loads))
(is (= "key" (loading-cache/get lcache :key name)))
(is (= 1 @loads))
(is (= "key" (cache/get lcache :key name)))
(is (= 1 @loads))
(cache/invalidate! lcache :key)
(is (= "key" (cache/get lcache :key name)))
(is (= 1 @loads))))
(deftest loading-exceptions
(let [loads (atom 0)
throw? (atom false)
load-nil? (atom false)
cl (common/reify-cache-loader (fn [k]
(cond
@throw? (throw (ex-info "fail" {}))
@load-nil? nil
:else (do
(swap! loads inc)
(name k)))))
ticker (FakeTicker.)
lcache (loading-cache/make-cache cl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(loading-cache/put! lcache :key :v)
(testing "successful get, existing key"
(is (= :v (loading-cache/get lcache :key)))
(is (= 0 @loads)))
(testing "loading a missing key"
(loading-cache/invalidate! lcache :key)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads)))
(testing "fail to load a missing key throws exception"
(reset! throw? true)
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"fail"
(loading-cache/get lcache :missing-key)))
(is (= 1 @loads)))
(testing "fail to load an expired key"
(is (true? @throw?))
(.advance ticker 11 TimeUnit/SECONDS)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads)))
(testing "loading a missing key but loader returns nil. nil returns, but mapping is not changed"
(reset! throw? false)
(reset! load-nil? true)
(is (nil? (loading-cache/get lcache :not-there)))
(is (= [:key] (keys (.asMap lcache)))))))
(deftest get-if-present
(let [cache (cache/make-cache)]
(cache/put! cache :key "v")
(cache/put! cache :key2 "v2")
(is (= "v" (cache/get-if-present cache :key)))
(is (= {:key "v"} (cache/get-all-present cache [:key "v2"])))
(is (nil? (cache/get-if-present cache :non-existent))))
(let [loading-cache (loading-cache/make-cache (common/reify-cache-loader str))]
(loading-cache/put! loading-cache :key "v")
(is (= (loading-cache/get-if-present loading-cache :key) "v"))
(loading-cache/invalidate! loading-cache :key)
(is (nil? (loading-cache/get-if-present loading-cache :key)))))
(deftest refresh-test
(let [loads (atom 0)
reloads (atom 0)
cl (common/reify-cache-loader
(fn [k]
(swap! loads inc)
(name k))
(fn [k _v]
(swap! reloads inc)
(name k)))
lcache (loading-cache/make-cache cl)]
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads))
(loading-cache/refresh lcache :key)
(Thread/sleep 10)
(is (= 1 @reloads))
(is (= 1 @loads))))
(deftest get-async
(let [acache (async-cache/make-cache)]
(async-cache/put! acache :key (p/resolved :v))
(is (= :v @(async-cache/get acache :key name)))
(async-cache/invalidate! acache :key)
(is (= "key" @(async-cache/get acache :key name))))
(let [alcache (async-loading-cache/make-cache (common/reify-cache-loader name))]
(async-cache/put! alcache :key (p/resolved :v))
(is (= :v @(async-loading-cache/get alcache :key name)))
(async-cache/invalidate! alcache :key)
(is (= "key" @(async-loading-cache/get alcache :key name)))))
(deftest get-if-present-async
(let [acache (async-cache/make-cache)]
(is (nil? (async-cache/get-if-present acache :key)))
(async-cache/put! acache :key (p/resolved :v))
(is (= :v @(async-cache/get-if-present acache :key))))
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
alcache (async-loading-cache/make-cache cl)]
(is (nil? (async-loading-cache/get-if-present alcache :key)))
(async-loading-cache/put! alcache :key (p/resolved :v))
(is (= :v @(async-loading-cache/get-if-present alcache :key)))
(is (= 0 @loads))))
(deftest get-async-loading
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
alcache (async-loading-cache/make-cache cl)]
(is (nil? (async-loading-cache/get-if-present alcache :key)))
(is (= 0 @loads))
(is (= "key" @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(async-loading-cache/invalidate! alcache :key)
(is (= "key" @(async-loading-cache/get alcache :key)))
(is (= 2 @loads))
(let [alcache2 (async-loading-cache/->LoadingCache alcache)]
(is (= "key" (loading-cache/get alcache2 :key)))
(is (= 2 @loads))
(is (= "key2" (loading-cache/get alcache2 :key2)))
(is (= 3 @loads)))))
(deftest auto-refresh
(let [loads (atom 0)
reloads (atom 0)
reload-fails? (atom false)
db (atom {:key 17})
cl (common/reify-cache-loader
(fn [k]
(swap! loads inc)
(get @db k))
(fn [k _old-v]
(swap! reloads inc)
(if @reload-fails?
(throw (Exception. (format "reload failed for key: %s" k)))
(get @db k))))
ticker (FakeTicker.)
lcache (loading-cache/make-cache cl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(testing "no key, load succeeds"
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key exists, just return from cache"
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key needs to be refreshed"
(swap! db assoc :key 42)
(.advance ticker 11 TimeUnit/SECONDS)
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(loading-cache/cleanup lcache)
(Thread/sleep 10)
(is (= 1 @reloads))
(is (= 42 (loading-cache/get lcache :key))))
(testing "time to refresh again, but reload fails"
(reset! reload-fails? true)
(swap! db assoc :key <KEY>)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 (loading-cache/get lcache :key)))
(is (= 1 @reloads))
(is (= 42 (loading-cache/get lcache :key)))
(is (= 1 @reloads))
(reset! reload-fails? false)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 (loading-cache/get lcache :key)))
(loading-cache/cleanup lcache)
(Thread/sleep 10)
(is (= 2 @reloads))
(is (= 43 (loading-cache/get lcache :key)))
(is (= 2 @reloads)))))
(deftest async-auto-async-refresh
(let [loads (atom 0)
reloads (atom 0)
reload-fails? (atom false)
db (atom {:key 17})
acl (common/reify-async-cache-loader
(fn [k _executor]
(swap! loads inc)
(p/resolved (get @db k)))
(fn [k _old-v _executor]
(swap! reloads inc)
(if @reload-fails?
(p/resolved (ex-info "error" {}))
(p/resolved (get @db k)))))
ticker (FakeTicker.)
alcache (async-loading-cache/make-cache-async-loader acl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(testing "no key, load succeeds"
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key exists, just return from cache"
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key needs to be refreshed"
(swap! db assoc :key <KEY>)
(.advance ticker 11 TimeUnit/SECONDS)
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 1 @reloads))
(is (= 42 @(async-loading-cache/get alcache :key))))
(testing "time to refresh again but relaod fails"
(reset! reload-fails? true)
(swap! db assoc :key <KEY>)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 @(async-loading-cache/get alcache :key)))
(is (= 1 @reloads))
(reset! reload-fails? false)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 @(async-loading-cache/get alcache :key)))
(is (= 2 @reloads))
(is (= 43 @(async-loading-cache/get alcache :key))))))
(deftest compute
(let [c (cache/make-cache)
k "key"
remapper (fn [_k v]
(if (some? v)
(str v "bar")
"foo"))]
(cache/put! c k "foo")
(is (= "foobar" (cache/compute c k remapper)))
(doall
(pmap (fn [_]
(cache/compute c k remapper))
(range 100)))
(let [expected (s/join (concat ["foobar"] (repeat 100 "bar")))]
(is (= expected (cache/get-if-present c k))))))
| true |
(ns cloffeine.core-test
(:require [cloffeine.common :as common]
[cloffeine.cache :as cache]
[cloffeine.async-cache :as async-cache]
[cloffeine.loading-cache :as loading-cache]
[cloffeine.async-loading-cache :as async-loading-cache]
[clojure.test :refer [deftest is testing use-fixtures]]
[promesa.core :as p]
[clojure.string :as s])
(:import [com.google.common.testing FakeTicker]
[com.github.benmanes.caffeine.cache Ticker]
[java.util.concurrent TimeUnit]
[java.util.logging Logger Level]))
(defn configure-logger [test-fn]
(let [logger (Logger/getLogger "com.github.benmanes.caffeine")
initial-level (.getLevel logger)]
(.setLevel logger (Level/SEVERE))
(test-fn)
(.setLevel logger initial-level)))
(use-fixtures :each configure-logger)
(defn- reify-ticker [^FakeTicker ft]
(reify Ticker
(read [_this]
(.read ft))))
(deftest manual
(let [cache (cache/make-cache)]
(is (= 0 (cache/estimated-size cache)))
(cache/put! cache :key :v)
(is (= 1 (cache/estimated-size cache)))
(is (= :v (cache/get cache :key name)))
(cache/invalidate! cache :key)
(is (= "key" (cache/get cache :key name)))
(is (= {:key "key"}
(cache/get-all cache [:key] (fn [ks] (reduce
(fn [res k]
(assoc res k (name k)))
{}
ks)))))
(cache/invalidate-all! cache)
(is (= 0 (cache/estimated-size cache)))))
(deftest loading
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
lcache (loading-cache/make-cache cl {:recordStats true})]
(loading-cache/put! lcache :key :v)
(is (= :v (loading-cache/get lcache :key)))
(is (= 1 (:hitCount (common/stats lcache))))
(is (= 1 (:requestCount (common/stats lcache))))
(is (= 0 @loads))
(loading-cache/invalidate! lcache :key)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 2 (:requestCount (common/stats lcache))))
(is (= 1 (:loadCount (common/stats lcache))))
(is (= 0.5 (:hitRate (common/stats lcache))))
(is (= 0.5 (:missRate (common/stats lcache))))
(is (= 1 @loads))
(is (= "key" (loading-cache/get lcache :key name)))
(is (= 1 @loads))
(is (= "key" (cache/get lcache :key name)))
(is (= 1 @loads))
(cache/invalidate! lcache :key)
(is (= "key" (cache/get lcache :key name)))
(is (= 1 @loads))))
(deftest loading-exceptions
(let [loads (atom 0)
throw? (atom false)
load-nil? (atom false)
cl (common/reify-cache-loader (fn [k]
(cond
@throw? (throw (ex-info "fail" {}))
@load-nil? nil
:else (do
(swap! loads inc)
(name k)))))
ticker (FakeTicker.)
lcache (loading-cache/make-cache cl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(loading-cache/put! lcache :key :v)
(testing "successful get, existing key"
(is (= :v (loading-cache/get lcache :key)))
(is (= 0 @loads)))
(testing "loading a missing key"
(loading-cache/invalidate! lcache :key)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads)))
(testing "fail to load a missing key throws exception"
(reset! throw? true)
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"fail"
(loading-cache/get lcache :missing-key)))
(is (= 1 @loads)))
(testing "fail to load an expired key"
(is (true? @throw?))
(.advance ticker 11 TimeUnit/SECONDS)
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads)))
(testing "loading a missing key but loader returns nil. nil returns, but mapping is not changed"
(reset! throw? false)
(reset! load-nil? true)
(is (nil? (loading-cache/get lcache :not-there)))
(is (= [:key] (keys (.asMap lcache)))))))
(deftest get-if-present
(let [cache (cache/make-cache)]
(cache/put! cache :key "v")
(cache/put! cache :key2 "v2")
(is (= "v" (cache/get-if-present cache :key)))
(is (= {:key "v"} (cache/get-all-present cache [:key "v2"])))
(is (nil? (cache/get-if-present cache :non-existent))))
(let [loading-cache (loading-cache/make-cache (common/reify-cache-loader str))]
(loading-cache/put! loading-cache :key "v")
(is (= (loading-cache/get-if-present loading-cache :key) "v"))
(loading-cache/invalidate! loading-cache :key)
(is (nil? (loading-cache/get-if-present loading-cache :key)))))
(deftest refresh-test
(let [loads (atom 0)
reloads (atom 0)
cl (common/reify-cache-loader
(fn [k]
(swap! loads inc)
(name k))
(fn [k _v]
(swap! reloads inc)
(name k)))
lcache (loading-cache/make-cache cl)]
(is (= "key" (loading-cache/get lcache :key)))
(is (= 1 @loads))
(loading-cache/refresh lcache :key)
(Thread/sleep 10)
(is (= 1 @reloads))
(is (= 1 @loads))))
(deftest get-async
(let [acache (async-cache/make-cache)]
(async-cache/put! acache :key (p/resolved :v))
(is (= :v @(async-cache/get acache :key name)))
(async-cache/invalidate! acache :key)
(is (= "key" @(async-cache/get acache :key name))))
(let [alcache (async-loading-cache/make-cache (common/reify-cache-loader name))]
(async-cache/put! alcache :key (p/resolved :v))
(is (= :v @(async-loading-cache/get alcache :key name)))
(async-cache/invalidate! alcache :key)
(is (= "key" @(async-loading-cache/get alcache :key name)))))
(deftest get-if-present-async
(let [acache (async-cache/make-cache)]
(is (nil? (async-cache/get-if-present acache :key)))
(async-cache/put! acache :key (p/resolved :v))
(is (= :v @(async-cache/get-if-present acache :key))))
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
alcache (async-loading-cache/make-cache cl)]
(is (nil? (async-loading-cache/get-if-present alcache :key)))
(async-loading-cache/put! alcache :key (p/resolved :v))
(is (= :v @(async-loading-cache/get-if-present alcache :key)))
(is (= 0 @loads))))
(deftest get-async-loading
(let [loads (atom 0)
cl (common/reify-cache-loader (fn [k]
(swap! loads inc)
(name k)))
alcache (async-loading-cache/make-cache cl)]
(is (nil? (async-loading-cache/get-if-present alcache :key)))
(is (= 0 @loads))
(is (= "key" @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(async-loading-cache/invalidate! alcache :key)
(is (= "key" @(async-loading-cache/get alcache :key)))
(is (= 2 @loads))
(let [alcache2 (async-loading-cache/->LoadingCache alcache)]
(is (= "key" (loading-cache/get alcache2 :key)))
(is (= 2 @loads))
(is (= "key2" (loading-cache/get alcache2 :key2)))
(is (= 3 @loads)))))
(deftest auto-refresh
(let [loads (atom 0)
reloads (atom 0)
reload-fails? (atom false)
db (atom {:key 17})
cl (common/reify-cache-loader
(fn [k]
(swap! loads inc)
(get @db k))
(fn [k _old-v]
(swap! reloads inc)
(if @reload-fails?
(throw (Exception. (format "reload failed for key: %s" k)))
(get @db k))))
ticker (FakeTicker.)
lcache (loading-cache/make-cache cl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(testing "no key, load succeeds"
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key exists, just return from cache"
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key needs to be refreshed"
(swap! db assoc :key 42)
(.advance ticker 11 TimeUnit/SECONDS)
(is (= 17 (loading-cache/get lcache :key)))
(is (= 1 @loads))
(loading-cache/cleanup lcache)
(Thread/sleep 10)
(is (= 1 @reloads))
(is (= 42 (loading-cache/get lcache :key))))
(testing "time to refresh again, but reload fails"
(reset! reload-fails? true)
(swap! db assoc :key PI:KEY:<KEY>END_PI)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 (loading-cache/get lcache :key)))
(is (= 1 @reloads))
(is (= 42 (loading-cache/get lcache :key)))
(is (= 1 @reloads))
(reset! reload-fails? false)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 (loading-cache/get lcache :key)))
(loading-cache/cleanup lcache)
(Thread/sleep 10)
(is (= 2 @reloads))
(is (= 43 (loading-cache/get lcache :key)))
(is (= 2 @reloads)))))
(deftest async-auto-async-refresh
(let [loads (atom 0)
reloads (atom 0)
reload-fails? (atom false)
db (atom {:key 17})
acl (common/reify-async-cache-loader
(fn [k _executor]
(swap! loads inc)
(p/resolved (get @db k)))
(fn [k _old-v _executor]
(swap! reloads inc)
(if @reload-fails?
(p/resolved (ex-info "error" {}))
(p/resolved (get @db k)))))
ticker (FakeTicker.)
alcache (async-loading-cache/make-cache-async-loader acl {:refreshAfterWrite 10
:timeUnit :s
:ticker (reify-ticker ticker)})]
(testing "no key, load succeeds"
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key exists, just return from cache"
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 0 @reloads)))
(testing "key needs to be refreshed"
(swap! db assoc :key PI:KEY:<KEY>END_PI)
(.advance ticker 11 TimeUnit/SECONDS)
(is (= 17 @(async-loading-cache/get alcache :key)))
(is (= 1 @loads))
(is (= 1 @reloads))
(is (= 42 @(async-loading-cache/get alcache :key))))
(testing "time to refresh again but relaod fails"
(reset! reload-fails? true)
(swap! db assoc :key PI:KEY:<KEY>END_PI)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 @(async-loading-cache/get alcache :key)))
(is (= 1 @reloads))
(reset! reload-fails? false)
(.advance ticker 10 TimeUnit/SECONDS)
(is (= 42 @(async-loading-cache/get alcache :key)))
(is (= 2 @reloads))
(is (= 43 @(async-loading-cache/get alcache :key))))))
(deftest compute
(let [c (cache/make-cache)
k "key"
remapper (fn [_k v]
(if (some? v)
(str v "bar")
"foo"))]
(cache/put! c k "foo")
(is (= "foobar" (cache/compute c k remapper)))
(doall
(pmap (fn [_]
(cache/compute c k remapper))
(range 100)))
(let [expected (s/join (concat ["foobar"] (repeat 100 "bar")))]
(is (= expected (cache/get-if-present c k))))))
|
[
{
"context": "er\n [& guys]\n (map hello guys))\n\n(bot-codger \"John\" \"Nathan\" \"Tony\")\n",
"end": 159,
"score": 0.9997245669364929,
"start": 155,
"tag": "NAME",
"value": "John"
},
{
"context": " guys]\n (map hello guys))\n\n(bot-codger \"John\" \"Nathan\" \"Tony\")\n",
"end": 168,
"score": 0.9998513460159302,
"start": 162,
"tag": "NAME",
"value": "Nathan"
},
{
"context": " (map hello guys))\n\n(bot-codger \"John\" \"Nathan\" \"Tony\")\n",
"end": 175,
"score": 0.9998341798782349,
"start": 171,
"tag": "NAME",
"value": "Tony"
}
] |
day4/function-arity-variable.clj
|
joaopaulomoraes/7-days-of-clojure
| 8 |
(ns seven-days-of-clojure.arity-variable)
(defn hello
[guy]
(str "Hello, " guy "!"))
(defn bot-codger
[& guys]
(map hello guys))
(bot-codger "John" "Nathan" "Tony")
|
81147
|
(ns seven-days-of-clojure.arity-variable)
(defn hello
[guy]
(str "Hello, " guy "!"))
(defn bot-codger
[& guys]
(map hello guys))
(bot-codger "<NAME>" "<NAME>" "<NAME>")
| true |
(ns seven-days-of-clojure.arity-variable)
(defn hello
[guy]
(str "Hello, " guy "!"))
(defn bot-codger
[& guys]
(map hello guys))
(bot-codger "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")
|
[
{
"context": "name :- String] :- Player\n (match name\n \"Alice\" Player1\n \"Bob\" Player2))\n\n(def Player1 (",
"end": 555,
"score": 0.9997581243515015,
"start": 550,
"tag": "NAME",
"value": "Alice"
},
{
"context": "\n (match name\n \"Alice\" Player1\n \"Bob\" Player2))\n\n(def Player1 (->player \\O \"Alice\"))\n(",
"end": 578,
"score": 0.9997435212135315,
"start": 575,
"tag": "NAME",
"value": "Bob"
},
{
"context": " \"Bob\" Player2))\n\n(def Player1 (->player \\O \"Alice\"))\n(def Player2 (->player \\X \"Bob\"))\n\n(t/ann valu",
"end": 623,
"score": 0.9997242093086243,
"start": 618,
"tag": "NAME",
"value": "Alice"
},
{
"context": "(->player \\O \"Alice\"))\n(def Player2 (->player \\X \"Bob\"))\n\n(t/ann values (t/Coll Player))\n(def values [P",
"end": 657,
"score": 0.9997578263282776,
"start": 654,
"tag": "NAME",
"value": "Bob"
}
] |
src/clj/krestiky/Player.clj
|
slava92/krestiky
| 0 |
(ns krestiky.Player
(:require [krestiky.Types :refer :all]
[clojure.core.match :refer [match]]
[clojure.core.typed :as t :refer [check-ns]]))
(set! *warn-on-reflection* true)
(t/ann Player1 Player)
(declare Player1)
(t/ann Player2 Player)
(declare Player2)
(t/ann-record player [c :- char s :- String])
(defrecord ^:private player [c s]
Player
(alternate [this] (if (= this Player1) Player2 Player1))
(to-symbol [_] c)
Show
(to-string [_] s))
(t/defn value-of [name :- String] :- Player
(match name
"Alice" Player1
"Bob" Player2))
(def Player1 (->player \O "Alice"))
(def Player2 (->player \X "Bob"))
(t/ann values (t/Coll Player))
(def values [Player1 Player2])
|
28724
|
(ns krestiky.Player
(:require [krestiky.Types :refer :all]
[clojure.core.match :refer [match]]
[clojure.core.typed :as t :refer [check-ns]]))
(set! *warn-on-reflection* true)
(t/ann Player1 Player)
(declare Player1)
(t/ann Player2 Player)
(declare Player2)
(t/ann-record player [c :- char s :- String])
(defrecord ^:private player [c s]
Player
(alternate [this] (if (= this Player1) Player2 Player1))
(to-symbol [_] c)
Show
(to-string [_] s))
(t/defn value-of [name :- String] :- Player
(match name
"<NAME>" Player1
"<NAME>" Player2))
(def Player1 (->player \O "<NAME>"))
(def Player2 (->player \X "<NAME>"))
(t/ann values (t/Coll Player))
(def values [Player1 Player2])
| true |
(ns krestiky.Player
(:require [krestiky.Types :refer :all]
[clojure.core.match :refer [match]]
[clojure.core.typed :as t :refer [check-ns]]))
(set! *warn-on-reflection* true)
(t/ann Player1 Player)
(declare Player1)
(t/ann Player2 Player)
(declare Player2)
(t/ann-record player [c :- char s :- String])
(defrecord ^:private player [c s]
Player
(alternate [this] (if (= this Player1) Player2 Player1))
(to-symbol [_] c)
Show
(to-string [_] s))
(t/defn value-of [name :- String] :- Player
(match name
"PI:NAME:<NAME>END_PI" Player1
"PI:NAME:<NAME>END_PI" Player2))
(def Player1 (->player \O "PI:NAME:<NAME>END_PI"))
(def Player2 (->player \X "PI:NAME:<NAME>END_PI"))
(t/ann values (t/Coll Player))
(def values [Player1 Player2])
|
[
{
"context": ";; Authors: Sung Pae <[email protected]>\n\n(ns vim-clojure-static.test\n ",
"end": 20,
"score": 0.9998762607574463,
"start": 12,
"tag": "NAME",
"value": "Sung Pae"
},
{
"context": ";; Authors: Sung Pae <[email protected]>\n\n(ns vim-clojure-static.test\n (:require [clojur",
"end": 38,
"score": 0.9999282360076904,
"start": 22,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
clj/src/vim_clojure_static/test.clj
|
skanev/vim-clojure-static
| 1 |
;; Authors: Sung Pae <[email protected]>
(ns vim-clojure-static.test
(:require [clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.edn :as edn]
[clojure.string :as string]
[clojure.test :as test]))
(defn syn-id-names
"Map lines of clojure text to vim synID names at each column as keywords:
(syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …}
First parameter is the file that is used to communicate with Vim. The file
is not deleted to allow manual inspection."
[file & lines]
(io/make-parents file)
(spit file (string/join \newline lines))
(shell/sh "vim" "-u" "NONE" "-N" "-S" "vim/test-runtime.vim" file)
;; The last line of the file will contain valid EDN
(into {} (map (fn [l ids] [l (mapv keyword ids)])
lines
(edn/read-string (peek (string/split-lines (slurp file)))))))
(defn subfmt
"Extract a subsequence of seq s corresponding to the character positions of
%s in format spec fmt"
[fmt s]
(let [f (seq (format fmt \o001))
i (.indexOf f \o001)]
(->> s
(drop i)
(drop-last (- (count f) i 1)))))
(defmacro defsyntaxtest
"Create a new testing var with tests in the format:
(defsyntaxtest example
[format
[test-string test-predicate
…]]
[\"#\\\"%s\\\"\"
[\"123\" #(every? (partial = :clojureRegexp) %)
…]]
[…])
At runtime the syn-id-names of the strings (which are placed in the format
spec) are passed to their associated predicates. The format spec should
contain a single `%s`."
[name & body]
(assert (every? (fn [[fmt tests]] (and (string? fmt)
(coll? tests)
(even? (count tests))))
body))
(let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]]
(let [[ss λs] (apply map list (partition 2 tests))
ss (map #(format fmt %) ss)]
[(concat strings ss)
(conj contexts {:fmt fmt :ss ss :λs λs})]))
[[] []] body)
syntable (gensym "syntable")]
`(test/deftest ~name
;; Shellout to vim should happen at runtime
(let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)]
~@(map (fn [{:keys [fmt ss λs]}]
`(test/testing ~fmt
~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s)))))
ss λs)))
contexts)))))
(defn vim-nfa-dump
"Run a patched version of Vim compiled with -DDEBUG on a new file containing
buffer, then move the NFA log to log-path. The patch is located at
vim/custom-nfa-log.patch"
[vim-path buffer log-path]
(let [file "tmp/nfa-test-file.clj"]
(spit file buffer)
(time (shell/sh vim-path "-u" "NONE" "-N" "-S" "vim/test-runtime.vim" file))
(shell/sh "mv" "nfa_regexp.log" log-path)))
(defn compare-nfa-dumps
"Dump NFA logs with given buffer and syntax-files; log-files are written to
tmp/ and are distinguished by the hash of the buffer and syntax script.
The vim-path passed to vim-nfa-dump should either be in the VIMDEBUG
environment variable, or be the top vim in your PATH.
Returns the line count of each corresponding log file."
[buf [& syntax-files] & opts]
(let [{:keys [vim-path]
:or {vim-path (or (System/getenv "VIMDEBUG") "vim")}} opts
syn-path "../syntax/clojure.vim"
orig-syn (slurp syn-path)
buf-hash (hash buf)]
(try
(mapv (fn [path]
(let [syn-buf (slurp path)
syn-hash (hash syn-buf)
log-path (format "tmp/debug:%d:%d.log" buf-hash syn-hash)]
(spit syn-path syn-buf)
(vim-nfa-dump vim-path buf log-path)
(count (re-seq #"\n" (slurp log-path)))))
syntax-files)
(finally
(spit syn-path orig-syn)))))
(comment
(macroexpand-1
'(defsyntaxtest number-literals-test
["%s"
["123" #(every? (partial = :clojureNumber) %)
"456" #(every? (partial = :clojureNumber) %)]]
["#\"%s\""
["^" #(= % [:clojureRegexpBoundary])]]))
(test #'number-literals-test)
(defn dump! [buf]
(compare-nfa-dumps (format "#\"\\p{%s}\"\n" buf)
["../syntax/clojure.vim" "tmp/altsyntax.vim"]))
(dump! "Ll")
(dump! "javaLowercase")
(dump! "block=UNIFIED CANADIAN ABORIGINAL SYLLABICS")
)
|
61697
|
;; Authors: <NAME> <<EMAIL>>
(ns vim-clojure-static.test
(:require [clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.edn :as edn]
[clojure.string :as string]
[clojure.test :as test]))
(defn syn-id-names
"Map lines of clojure text to vim synID names at each column as keywords:
(syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …}
First parameter is the file that is used to communicate with Vim. The file
is not deleted to allow manual inspection."
[file & lines]
(io/make-parents file)
(spit file (string/join \newline lines))
(shell/sh "vim" "-u" "NONE" "-N" "-S" "vim/test-runtime.vim" file)
;; The last line of the file will contain valid EDN
(into {} (map (fn [l ids] [l (mapv keyword ids)])
lines
(edn/read-string (peek (string/split-lines (slurp file)))))))
(defn subfmt
"Extract a subsequence of seq s corresponding to the character positions of
%s in format spec fmt"
[fmt s]
(let [f (seq (format fmt \o001))
i (.indexOf f \o001)]
(->> s
(drop i)
(drop-last (- (count f) i 1)))))
(defmacro defsyntaxtest
"Create a new testing var with tests in the format:
(defsyntaxtest example
[format
[test-string test-predicate
…]]
[\"#\\\"%s\\\"\"
[\"123\" #(every? (partial = :clojureRegexp) %)
…]]
[…])
At runtime the syn-id-names of the strings (which are placed in the format
spec) are passed to their associated predicates. The format spec should
contain a single `%s`."
[name & body]
(assert (every? (fn [[fmt tests]] (and (string? fmt)
(coll? tests)
(even? (count tests))))
body))
(let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]]
(let [[ss λs] (apply map list (partition 2 tests))
ss (map #(format fmt %) ss)]
[(concat strings ss)
(conj contexts {:fmt fmt :ss ss :λs λs})]))
[[] []] body)
syntable (gensym "syntable")]
`(test/deftest ~name
;; Shellout to vim should happen at runtime
(let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)]
~@(map (fn [{:keys [fmt ss λs]}]
`(test/testing ~fmt
~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s)))))
ss λs)))
contexts)))))
(defn vim-nfa-dump
"Run a patched version of Vim compiled with -DDEBUG on a new file containing
buffer, then move the NFA log to log-path. The patch is located at
vim/custom-nfa-log.patch"
[vim-path buffer log-path]
(let [file "tmp/nfa-test-file.clj"]
(spit file buffer)
(time (shell/sh vim-path "-u" "NONE" "-N" "-S" "vim/test-runtime.vim" file))
(shell/sh "mv" "nfa_regexp.log" log-path)))
(defn compare-nfa-dumps
"Dump NFA logs with given buffer and syntax-files; log-files are written to
tmp/ and are distinguished by the hash of the buffer and syntax script.
The vim-path passed to vim-nfa-dump should either be in the VIMDEBUG
environment variable, or be the top vim in your PATH.
Returns the line count of each corresponding log file."
[buf [& syntax-files] & opts]
(let [{:keys [vim-path]
:or {vim-path (or (System/getenv "VIMDEBUG") "vim")}} opts
syn-path "../syntax/clojure.vim"
orig-syn (slurp syn-path)
buf-hash (hash buf)]
(try
(mapv (fn [path]
(let [syn-buf (slurp path)
syn-hash (hash syn-buf)
log-path (format "tmp/debug:%d:%d.log" buf-hash syn-hash)]
(spit syn-path syn-buf)
(vim-nfa-dump vim-path buf log-path)
(count (re-seq #"\n" (slurp log-path)))))
syntax-files)
(finally
(spit syn-path orig-syn)))))
(comment
(macroexpand-1
'(defsyntaxtest number-literals-test
["%s"
["123" #(every? (partial = :clojureNumber) %)
"456" #(every? (partial = :clojureNumber) %)]]
["#\"%s\""
["^" #(= % [:clojureRegexpBoundary])]]))
(test #'number-literals-test)
(defn dump! [buf]
(compare-nfa-dumps (format "#\"\\p{%s}\"\n" buf)
["../syntax/clojure.vim" "tmp/altsyntax.vim"]))
(dump! "Ll")
(dump! "javaLowercase")
(dump! "block=UNIFIED CANADIAN ABORIGINAL SYLLABICS")
)
| true |
;; Authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(ns vim-clojure-static.test
(:require [clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.edn :as edn]
[clojure.string :as string]
[clojure.test :as test]))
(defn syn-id-names
"Map lines of clojure text to vim synID names at each column as keywords:
(syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …}
First parameter is the file that is used to communicate with Vim. The file
is not deleted to allow manual inspection."
[file & lines]
(io/make-parents file)
(spit file (string/join \newline lines))
(shell/sh "vim" "-u" "NONE" "-N" "-S" "vim/test-runtime.vim" file)
;; The last line of the file will contain valid EDN
(into {} (map (fn [l ids] [l (mapv keyword ids)])
lines
(edn/read-string (peek (string/split-lines (slurp file)))))))
(defn subfmt
"Extract a subsequence of seq s corresponding to the character positions of
%s in format spec fmt"
[fmt s]
(let [f (seq (format fmt \o001))
i (.indexOf f \o001)]
(->> s
(drop i)
(drop-last (- (count f) i 1)))))
(defmacro defsyntaxtest
"Create a new testing var with tests in the format:
(defsyntaxtest example
[format
[test-string test-predicate
…]]
[\"#\\\"%s\\\"\"
[\"123\" #(every? (partial = :clojureRegexp) %)
…]]
[…])
At runtime the syn-id-names of the strings (which are placed in the format
spec) are passed to their associated predicates. The format spec should
contain a single `%s`."
[name & body]
(assert (every? (fn [[fmt tests]] (and (string? fmt)
(coll? tests)
(even? (count tests))))
body))
(let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]]
(let [[ss λs] (apply map list (partition 2 tests))
ss (map #(format fmt %) ss)]
[(concat strings ss)
(conj contexts {:fmt fmt :ss ss :λs λs})]))
[[] []] body)
syntable (gensym "syntable")]
`(test/deftest ~name
;; Shellout to vim should happen at runtime
(let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)]
~@(map (fn [{:keys [fmt ss λs]}]
`(test/testing ~fmt
~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s)))))
ss λs)))
contexts)))))
(defn vim-nfa-dump
"Run a patched version of Vim compiled with -DDEBUG on a new file containing
buffer, then move the NFA log to log-path. The patch is located at
vim/custom-nfa-log.patch"
[vim-path buffer log-path]
(let [file "tmp/nfa-test-file.clj"]
(spit file buffer)
(time (shell/sh vim-path "-u" "NONE" "-N" "-S" "vim/test-runtime.vim" file))
(shell/sh "mv" "nfa_regexp.log" log-path)))
(defn compare-nfa-dumps
"Dump NFA logs with given buffer and syntax-files; log-files are written to
tmp/ and are distinguished by the hash of the buffer and syntax script.
The vim-path passed to vim-nfa-dump should either be in the VIMDEBUG
environment variable, or be the top vim in your PATH.
Returns the line count of each corresponding log file."
[buf [& syntax-files] & opts]
(let [{:keys [vim-path]
:or {vim-path (or (System/getenv "VIMDEBUG") "vim")}} opts
syn-path "../syntax/clojure.vim"
orig-syn (slurp syn-path)
buf-hash (hash buf)]
(try
(mapv (fn [path]
(let [syn-buf (slurp path)
syn-hash (hash syn-buf)
log-path (format "tmp/debug:%d:%d.log" buf-hash syn-hash)]
(spit syn-path syn-buf)
(vim-nfa-dump vim-path buf log-path)
(count (re-seq #"\n" (slurp log-path)))))
syntax-files)
(finally
(spit syn-path orig-syn)))))
(comment
(macroexpand-1
'(defsyntaxtest number-literals-test
["%s"
["123" #(every? (partial = :clojureNumber) %)
"456" #(every? (partial = :clojureNumber) %)]]
["#\"%s\""
["^" #(= % [:clojureRegexpBoundary])]]))
(test #'number-literals-test)
(defn dump! [buf]
(compare-nfa-dumps (format "#\"\\p{%s}\"\n" buf)
["../syntax/clojure.vim" "tmp/altsyntax.vim"]))
(dump! "Ll")
(dump! "javaLowercase")
(dump! "block=UNIFIED CANADIAN ABORIGINAL SYLLABICS")
)
|
[
{
"context": "oss] :as arch-spec}]\n (let [arch-spec-key (str \":arch-spec:target:\" XBPS_TARGET_ARCH\n \":host:\" XBPS_",
"end": 505,
"score": 0.8545032143592834,
"start": 473,
"tag": "KEY",
"value": "\":arch-spec:target:\" XBPS_TARGET"
},
{
"context": "ch-spec-key (str \":arch-spec:target:\" XBPS_TARGET_ARCH\n \":host:\" XBPS_ARCH ",
"end": 510,
"score": 0.642462432384491,
"start": 506,
"tag": "KEY",
"value": "ARCH"
}
] |
src/dxpb_clj/db.clj
|
dxpb/dxpb-clj
| 0 |
(ns dxpb-clj.db
(:require [crux.api :as crux]
[clojure.java.io :as io]
[config.core :refer [env]]
[clojure.set :refer [union]]
))
(def crux-fn-delete-package
'(fn [ctx pkgname {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross]}]
[]))
(def crux-fn-ensure-pruned-subpkgs
'(fn [ctx]
[]))
(def crux-fn-delete-arch-spec
'(fn [ctx {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :as arch-spec}]
(let [arch-spec-key (str ":arch-spec:target:" XBPS_TARGET_ARCH
":host:" XBPS_ARCH ":cross:" cross)
pkgs-to-remove (crux.api/q (crux.api/db ctx)
'{:find [e]
:in [[host target cross]]
:where [[e :dxpb/type :package]
[e :dxpb/hostarch host]
[e :dxpb/targetarch target]
[e :dxpb/crossbuild cross]]}
[XBPS_ARCH XBPS_TARGET_ARCH cross])]
(apply conj [[:crux.tx/delete arch-spec-key]]
(map (partial vector :crux.tx/delete) pkgs-to-remove)))))
(def node (atom nil))
(defn- only [in]
(when (= 1 (count in))
(first in)))
(defn start-standalone-node ^crux.api.ICruxAPI [storage-dir]
(let [mkdatadir #(str (io/file storage-dir %))]
(crux/start-node {:crux/tx-log {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "tx-log")}}
:crux/document-store {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "docs")}}
:crux/index-store {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "indexes")}}
})))
(defn get-storage-dir! []
(or (:DXPB_SERVER_DIR env)
"./datadir"))
(defn ensure-db-functions [db]
(when (not= (crux/entity (crux/db db) :delete-package)
crux-fn-delete-package)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :delete-package
:crux.db/fn crux-fn-delete-package}]]))
(when (not= (crux/entity (crux/db db) :ensure-pruned-subpkgs)
crux-fn-ensure-pruned-subpkgs)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :ensure-pruned-subpkgs
:crux.db/fn crux-fn-ensure-pruned-subpkgs}]]))
(when (not= (crux/entity (crux/db db) :delete-arch-spec)
crux-fn-delete-arch-spec)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :delete-arch-spec
:crux.db/fn crux-fn-delete-arch-spec}]])))
(defn db-guard []
(when (nil? @node)
(reset! node (start-standalone-node (get-storage-dir!)))
(ensure-db-functions @node)))
(defn take-instruction [instructions]
(db-guard)
(crux/submit-tx @node instructions))
(defn arch-spec->db-key [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false}}]
(str ":arch-spec"
":target:" XBPS_TARGET_ARCH
":host:" XBPS_ARCH
":cross:" cross))
(defn arch-spec-present? [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(->> arch-spec
arch-spec->db-key
(crux/entity (crux/db @node))
some?))
(defn insert-arch-spec [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(let [spec-key (arch-spec->db-key arch-spec)
spec (-> arch-spec
(assoc :crux.db/id spec-key)
(assoc :dxpb/type :arch-spec))]
(or (= spec (crux/entity (crux/db @node) spec-key))
(->> spec
(vector :crux.tx/put)
vector
(crux/submit-tx @node)))))
(defn arch-specs []
(db-guard)
(->> (crux/q (crux/db @node)
{:find '[XBPS_ARCH XBPS_TARGET_ARCH cross]
:where '[[e :dxpb/type :arch-spec]
[e :XBPS_ARCH XBPS_ARCH]
[e :XBPS_TARGET_ARCH XBPS_TARGET_ARCH]
[e :cross cross]]})
(map (partial zipmap [:XBPS_ARCH :XBPS_TARGET_ARCH :cross]))))
(defn remove-arch-spec [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(crux/submit-tx @node [[:crux.tx/fn :delete-arch-spec arch-spec]]))
#_ (remove-arch-spec {:XBPS_ARCH "x86_64" :XBPS_TARGET_ARCH "x86_64-musl" :cross true})
(defn does-pkgname-exist [pkgname]
(db-guard)
(seq
(crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]]
:args [{'?name pkgname}]})))
(defn list-of-all-pkgnames []
(db-guard)
(apply concat (crux/q (crux/db @node)
{:find '[?name]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]]})))
(defn list-of-bootstrap-pkgnames []
(db-guard)
(apply concat (crux/q (crux/db @node)
{:find '[?name]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :bootstrap ?ignored]]})))
(defn get-pkg-key [pkgname {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false}}]
(db-guard)
(crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :dxpb/hostarch ?hostarch]
[?e :dxpb/targetarch ?targetarch]
[?e :dxpb/crossbuild ?cross]]
:args [{'?name pkgname
'?hostarch XBPS_ARCH
'?targetarch XBPS_TARGET_ARCH
'?cross cross}]}))
#_ (get-pkg-key "gcc" {:XBPS_ARCH "x86_64" :XBPS_TARGET_ARCH "x86_64" :cross false})
#_ (crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :dxpb/crossbuild ?cross]]
:args [{'?name "gcc"
'?cross false}]})
(defn get-pkg-data
([pkgkey]
(db-guard)
(crux/entity (crux/db @node) pkgkey))
([pkgname build-profile]
(-> (get-pkg-key pkgname build-profile)
only
only
get-pkg-data)))
(defn get-all-needs-for-arch [& {:keys [pkgnames arch]}]
(db-guard)
(if (empty? pkgnames)
#{}
(let [all-pkg-query-args (vec (map #(hash-map '?name % '?targetarch arch) pkgnames))
depends (crux/q (crux/db @node)
{:find '[?deps]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :depends ?deps]
[?e :dxpb/targetarch ?targetarch]]
:args all-pkg-query-args})
makedepends (crux/q (crux/db @node)
{:find '[?deps]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :makedepends ?deps]
[?e :dxpb/targetarch ?targetarch]]
:args all-pkg-query-args})]
(apply union (map set [(-> depends vec flatten) (-> makedepends vec flatten)])))))
(defn pkg-is-noarch [pkgname]
(db-guard)
(let [pkgname (if (keyword? pkgname) (name pkgname) pkgname)]
(-> (crux/q (crux/db @node)
{:find '[?archs]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :archs ?archs]]
:args [{'?name pkgname}]})
;; We have a set of vectors of lists
only
;; We have a vector of lists, each vector is from 1 pkg
only
;; We have a list of archs. It's not noarch if there are multiple values
only
;; We have a string or nil.
(= "noarch"))))
(defn pkg-version [pkgname]
(db-guard)
(let [pkgname (if (keyword? pkgname) (name pkgname) pkgname)]
(-> (crux/q (crux/db @node)
{:find '[?version]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :version ?version]]
:args [{'?name pkgname}]})
;; We have a set of vectors of strings. Better be the same across all pkgs!
only
;; We have a vector of strings, each vector is from 1 pkg, hope they all match!
only)))
|
6396
|
(ns dxpb-clj.db
(:require [crux.api :as crux]
[clojure.java.io :as io]
[config.core :refer [env]]
[clojure.set :refer [union]]
))
(def crux-fn-delete-package
'(fn [ctx pkgname {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross]}]
[]))
(def crux-fn-ensure-pruned-subpkgs
'(fn [ctx]
[]))
(def crux-fn-delete-arch-spec
'(fn [ctx {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :as arch-spec}]
(let [arch-spec-key (str <KEY>_<KEY>
":host:" XBPS_ARCH ":cross:" cross)
pkgs-to-remove (crux.api/q (crux.api/db ctx)
'{:find [e]
:in [[host target cross]]
:where [[e :dxpb/type :package]
[e :dxpb/hostarch host]
[e :dxpb/targetarch target]
[e :dxpb/crossbuild cross]]}
[XBPS_ARCH XBPS_TARGET_ARCH cross])]
(apply conj [[:crux.tx/delete arch-spec-key]]
(map (partial vector :crux.tx/delete) pkgs-to-remove)))))
(def node (atom nil))
(defn- only [in]
(when (= 1 (count in))
(first in)))
(defn start-standalone-node ^crux.api.ICruxAPI [storage-dir]
(let [mkdatadir #(str (io/file storage-dir %))]
(crux/start-node {:crux/tx-log {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "tx-log")}}
:crux/document-store {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "docs")}}
:crux/index-store {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "indexes")}}
})))
(defn get-storage-dir! []
(or (:DXPB_SERVER_DIR env)
"./datadir"))
(defn ensure-db-functions [db]
(when (not= (crux/entity (crux/db db) :delete-package)
crux-fn-delete-package)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :delete-package
:crux.db/fn crux-fn-delete-package}]]))
(when (not= (crux/entity (crux/db db) :ensure-pruned-subpkgs)
crux-fn-ensure-pruned-subpkgs)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :ensure-pruned-subpkgs
:crux.db/fn crux-fn-ensure-pruned-subpkgs}]]))
(when (not= (crux/entity (crux/db db) :delete-arch-spec)
crux-fn-delete-arch-spec)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :delete-arch-spec
:crux.db/fn crux-fn-delete-arch-spec}]])))
(defn db-guard []
(when (nil? @node)
(reset! node (start-standalone-node (get-storage-dir!)))
(ensure-db-functions @node)))
(defn take-instruction [instructions]
(db-guard)
(crux/submit-tx @node instructions))
(defn arch-spec->db-key [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false}}]
(str ":arch-spec"
":target:" XBPS_TARGET_ARCH
":host:" XBPS_ARCH
":cross:" cross))
(defn arch-spec-present? [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(->> arch-spec
arch-spec->db-key
(crux/entity (crux/db @node))
some?))
(defn insert-arch-spec [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(let [spec-key (arch-spec->db-key arch-spec)
spec (-> arch-spec
(assoc :crux.db/id spec-key)
(assoc :dxpb/type :arch-spec))]
(or (= spec (crux/entity (crux/db @node) spec-key))
(->> spec
(vector :crux.tx/put)
vector
(crux/submit-tx @node)))))
(defn arch-specs []
(db-guard)
(->> (crux/q (crux/db @node)
{:find '[XBPS_ARCH XBPS_TARGET_ARCH cross]
:where '[[e :dxpb/type :arch-spec]
[e :XBPS_ARCH XBPS_ARCH]
[e :XBPS_TARGET_ARCH XBPS_TARGET_ARCH]
[e :cross cross]]})
(map (partial zipmap [:XBPS_ARCH :XBPS_TARGET_ARCH :cross]))))
(defn remove-arch-spec [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(crux/submit-tx @node [[:crux.tx/fn :delete-arch-spec arch-spec]]))
#_ (remove-arch-spec {:XBPS_ARCH "x86_64" :XBPS_TARGET_ARCH "x86_64-musl" :cross true})
(defn does-pkgname-exist [pkgname]
(db-guard)
(seq
(crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]]
:args [{'?name pkgname}]})))
(defn list-of-all-pkgnames []
(db-guard)
(apply concat (crux/q (crux/db @node)
{:find '[?name]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]]})))
(defn list-of-bootstrap-pkgnames []
(db-guard)
(apply concat (crux/q (crux/db @node)
{:find '[?name]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :bootstrap ?ignored]]})))
(defn get-pkg-key [pkgname {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false}}]
(db-guard)
(crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :dxpb/hostarch ?hostarch]
[?e :dxpb/targetarch ?targetarch]
[?e :dxpb/crossbuild ?cross]]
:args [{'?name pkgname
'?hostarch XBPS_ARCH
'?targetarch XBPS_TARGET_ARCH
'?cross cross}]}))
#_ (get-pkg-key "gcc" {:XBPS_ARCH "x86_64" :XBPS_TARGET_ARCH "x86_64" :cross false})
#_ (crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :dxpb/crossbuild ?cross]]
:args [{'?name "gcc"
'?cross false}]})
(defn get-pkg-data
([pkgkey]
(db-guard)
(crux/entity (crux/db @node) pkgkey))
([pkgname build-profile]
(-> (get-pkg-key pkgname build-profile)
only
only
get-pkg-data)))
(defn get-all-needs-for-arch [& {:keys [pkgnames arch]}]
(db-guard)
(if (empty? pkgnames)
#{}
(let [all-pkg-query-args (vec (map #(hash-map '?name % '?targetarch arch) pkgnames))
depends (crux/q (crux/db @node)
{:find '[?deps]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :depends ?deps]
[?e :dxpb/targetarch ?targetarch]]
:args all-pkg-query-args})
makedepends (crux/q (crux/db @node)
{:find '[?deps]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :makedepends ?deps]
[?e :dxpb/targetarch ?targetarch]]
:args all-pkg-query-args})]
(apply union (map set [(-> depends vec flatten) (-> makedepends vec flatten)])))))
(defn pkg-is-noarch [pkgname]
(db-guard)
(let [pkgname (if (keyword? pkgname) (name pkgname) pkgname)]
(-> (crux/q (crux/db @node)
{:find '[?archs]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :archs ?archs]]
:args [{'?name pkgname}]})
;; We have a set of vectors of lists
only
;; We have a vector of lists, each vector is from 1 pkg
only
;; We have a list of archs. It's not noarch if there are multiple values
only
;; We have a string or nil.
(= "noarch"))))
(defn pkg-version [pkgname]
(db-guard)
(let [pkgname (if (keyword? pkgname) (name pkgname) pkgname)]
(-> (crux/q (crux/db @node)
{:find '[?version]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :version ?version]]
:args [{'?name pkgname}]})
;; We have a set of vectors of strings. Better be the same across all pkgs!
only
;; We have a vector of strings, each vector is from 1 pkg, hope they all match!
only)))
| true |
(ns dxpb-clj.db
(:require [crux.api :as crux]
[clojure.java.io :as io]
[config.core :refer [env]]
[clojure.set :refer [union]]
))
(def crux-fn-delete-package
'(fn [ctx pkgname {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross]}]
[]))
(def crux-fn-ensure-pruned-subpkgs
'(fn [ctx]
[]))
(def crux-fn-delete-arch-spec
'(fn [ctx {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :as arch-spec}]
(let [arch-spec-key (str PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI
":host:" XBPS_ARCH ":cross:" cross)
pkgs-to-remove (crux.api/q (crux.api/db ctx)
'{:find [e]
:in [[host target cross]]
:where [[e :dxpb/type :package]
[e :dxpb/hostarch host]
[e :dxpb/targetarch target]
[e :dxpb/crossbuild cross]]}
[XBPS_ARCH XBPS_TARGET_ARCH cross])]
(apply conj [[:crux.tx/delete arch-spec-key]]
(map (partial vector :crux.tx/delete) pkgs-to-remove)))))
(def node (atom nil))
(defn- only [in]
(when (= 1 (count in))
(first in)))
(defn start-standalone-node ^crux.api.ICruxAPI [storage-dir]
(let [mkdatadir #(str (io/file storage-dir %))]
(crux/start-node {:crux/tx-log {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "tx-log")}}
:crux/document-store {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "docs")}}
:crux/index-store {:kv-store {:crux/module 'crux.rocksdb/->kv-store
:db-dir (mkdatadir "indexes")}}
})))
(defn get-storage-dir! []
(or (:DXPB_SERVER_DIR env)
"./datadir"))
(defn ensure-db-functions [db]
(when (not= (crux/entity (crux/db db) :delete-package)
crux-fn-delete-package)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :delete-package
:crux.db/fn crux-fn-delete-package}]]))
(when (not= (crux/entity (crux/db db) :ensure-pruned-subpkgs)
crux-fn-ensure-pruned-subpkgs)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :ensure-pruned-subpkgs
:crux.db/fn crux-fn-ensure-pruned-subpkgs}]]))
(when (not= (crux/entity (crux/db db) :delete-arch-spec)
crux-fn-delete-arch-spec)
(crux/submit-tx db [[:crux.tx/put {:crux.db/id :delete-arch-spec
:crux.db/fn crux-fn-delete-arch-spec}]])))
(defn db-guard []
(when (nil? @node)
(reset! node (start-standalone-node (get-storage-dir!)))
(ensure-db-functions @node)))
(defn take-instruction [instructions]
(db-guard)
(crux/submit-tx @node instructions))
(defn arch-spec->db-key [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false}}]
(str ":arch-spec"
":target:" XBPS_TARGET_ARCH
":host:" XBPS_ARCH
":cross:" cross))
(defn arch-spec-present? [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(->> arch-spec
arch-spec->db-key
(crux/entity (crux/db @node))
some?))
(defn insert-arch-spec [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(let [spec-key (arch-spec->db-key arch-spec)
spec (-> arch-spec
(assoc :crux.db/id spec-key)
(assoc :dxpb/type :arch-spec))]
(or (= spec (crux/entity (crux/db @node) spec-key))
(->> spec
(vector :crux.tx/put)
vector
(crux/submit-tx @node)))))
(defn arch-specs []
(db-guard)
(->> (crux/q (crux/db @node)
{:find '[XBPS_ARCH XBPS_TARGET_ARCH cross]
:where '[[e :dxpb/type :arch-spec]
[e :XBPS_ARCH XBPS_ARCH]
[e :XBPS_TARGET_ARCH XBPS_TARGET_ARCH]
[e :cross cross]]})
(map (partial zipmap [:XBPS_ARCH :XBPS_TARGET_ARCH :cross]))))
(defn remove-arch-spec [{:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false} :as arch-spec}]
(db-guard)
(crux/submit-tx @node [[:crux.tx/fn :delete-arch-spec arch-spec]]))
#_ (remove-arch-spec {:XBPS_ARCH "x86_64" :XBPS_TARGET_ARCH "x86_64-musl" :cross true})
(defn does-pkgname-exist [pkgname]
(db-guard)
(seq
(crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]]
:args [{'?name pkgname}]})))
(defn list-of-all-pkgnames []
(db-guard)
(apply concat (crux/q (crux/db @node)
{:find '[?name]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]]})))
(defn list-of-bootstrap-pkgnames []
(db-guard)
(apply concat (crux/q (crux/db @node)
{:find '[?name]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :bootstrap ?ignored]]})))
(defn get-pkg-key [pkgname {:keys [XBPS_ARCH XBPS_TARGET_ARCH cross] :or {cross false}}]
(db-guard)
(crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :dxpb/hostarch ?hostarch]
[?e :dxpb/targetarch ?targetarch]
[?e :dxpb/crossbuild ?cross]]
:args [{'?name pkgname
'?hostarch XBPS_ARCH
'?targetarch XBPS_TARGET_ARCH
'?cross cross}]}))
#_ (get-pkg-key "gcc" {:XBPS_ARCH "x86_64" :XBPS_TARGET_ARCH "x86_64" :cross false})
#_ (crux/q (crux/db @node)
{:find '[?e]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :dxpb/crossbuild ?cross]]
:args [{'?name "gcc"
'?cross false}]})
(defn get-pkg-data
([pkgkey]
(db-guard)
(crux/entity (crux/db @node) pkgkey))
([pkgname build-profile]
(-> (get-pkg-key pkgname build-profile)
only
only
get-pkg-data)))
(defn get-all-needs-for-arch [& {:keys [pkgnames arch]}]
(db-guard)
(if (empty? pkgnames)
#{}
(let [all-pkg-query-args (vec (map #(hash-map '?name % '?targetarch arch) pkgnames))
depends (crux/q (crux/db @node)
{:find '[?deps]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :depends ?deps]
[?e :dxpb/targetarch ?targetarch]]
:args all-pkg-query-args})
makedepends (crux/q (crux/db @node)
{:find '[?deps]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :makedepends ?deps]
[?e :dxpb/targetarch ?targetarch]]
:args all-pkg-query-args})]
(apply union (map set [(-> depends vec flatten) (-> makedepends vec flatten)])))))
(defn pkg-is-noarch [pkgname]
(db-guard)
(let [pkgname (if (keyword? pkgname) (name pkgname) pkgname)]
(-> (crux/q (crux/db @node)
{:find '[?archs]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :archs ?archs]]
:args [{'?name pkgname}]})
;; We have a set of vectors of lists
only
;; We have a vector of lists, each vector is from 1 pkg
only
;; We have a list of archs. It's not noarch if there are multiple values
only
;; We have a string or nil.
(= "noarch"))))
(defn pkg-version [pkgname]
(db-guard)
(let [pkgname (if (keyword? pkgname) (name pkgname) pkgname)]
(-> (crux/q (crux/db @node)
{:find '[?version]
:where '[[?e :pkgname ?name]
[?e :dxpb/type :package]
[?e :version ?version]]
:args [{'?name pkgname}]})
;; We have a set of vectors of strings. Better be the same across all pkgs!
only
;; We have a vector of strings, each vector is from 1 pkg, hope they all match!
only)))
|
[
{
"context": "\"//james:3306/nova\"\n :user \"root\"\n :password \"56592b2f97c7de918edd\"})\n\n(defn skip-line? [line]\n (let [line (str/tri",
"end": 322,
"score": 0.9993483424186707,
"start": 302,
"tag": "PASSWORD",
"value": "56592b2f97c7de918edd"
}
] |
src/gremlin/core.clj
|
amadev/migration_tests
| 0 |
(ns migration-tests.core
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log])
(:gen-class))
(def db-spec
{:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//james:3306/nova"
:user "root"
:password "56592b2f97c7de918edd"})
(defn skip-line? [line]
(let [line (str/trim line)]
(or (empty? line) (str/starts-with? line "--"))))
(defn split-sql-statements [text]
"Naive way of splitting sql statements.
Strings with semicolons and multi-line comments are not supported"
(remove skip-line? (str/split text #";" )))
(defn exec-sql-file [file-name]
(jdbc/db-do-commands db-spec (split-sql-statements (slurp file-name))))
(defn case-name [case name]
(str "cases/" case "/" name ".sql"))
(defn -main
[& args]
(let [cs "add_index"]
(log/debug "Starting ...")
(exec-sql-file (case-name cs "init"))
(println "Done!")))
|
118373
|
(ns migration-tests.core
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log])
(:gen-class))
(def db-spec
{:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//james:3306/nova"
:user "root"
:password "<PASSWORD>"})
(defn skip-line? [line]
(let [line (str/trim line)]
(or (empty? line) (str/starts-with? line "--"))))
(defn split-sql-statements [text]
"Naive way of splitting sql statements.
Strings with semicolons and multi-line comments are not supported"
(remove skip-line? (str/split text #";" )))
(defn exec-sql-file [file-name]
(jdbc/db-do-commands db-spec (split-sql-statements (slurp file-name))))
(defn case-name [case name]
(str "cases/" case "/" name ".sql"))
(defn -main
[& args]
(let [cs "add_index"]
(log/debug "Starting ...")
(exec-sql-file (case-name cs "init"))
(println "Done!")))
| true |
(ns migration-tests.core
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log])
(:gen-class))
(def db-spec
{:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//james:3306/nova"
:user "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(defn skip-line? [line]
(let [line (str/trim line)]
(or (empty? line) (str/starts-with? line "--"))))
(defn split-sql-statements [text]
"Naive way of splitting sql statements.
Strings with semicolons and multi-line comments are not supported"
(remove skip-line? (str/split text #";" )))
(defn exec-sql-file [file-name]
(jdbc/db-do-commands db-spec (split-sql-statements (slurp file-name))))
(defn case-name [case name]
(str "cases/" case "/" name ".sql"))
(defn -main
[& args]
(let [cs "add_index"]
(log/debug "Starting ...")
(exec-sql-file (case-name cs "init"))
(println "Done!")))
|
[
{
"context": "UID)\n :hamster/name \"Farley Moat\"\n :hamster/age 12}]\n",
"end": 440,
"score": 0.9998558759689331,
"start": 429,
"tag": "NAME",
"value": "Farley Moat"
},
{
"context": "UID)\n :hamster/name \"Barley Goat\"\n :hamster/age 3}]\n ",
"end": 607,
"score": 0.9998564720153809,
"start": 596,
"tag": "NAME",
"value": "Barley Goat"
},
{
"context": "UID)\n :hamster/name \"Gnarly Rote\"\n :hamster/age 99}]]",
"end": 773,
"score": 0.9998435378074646,
"start": 762,
"tag": "NAME",
"value": "Gnarly Rote"
}
] |
test/seeds/xtdb.clj
|
pariyatti/crux-migrate
| 1 |
(ns seeds.xtdb
(:require [xtdb.api :as xt]
[joplin.xtdb.database :as d]))
(defn run [target & args]
;; NOTE: in a real migration, use `with-open`. The joplin.xtdb test suite
;; seems to fail when using `with-open` because we use a shared node.
(when-let [node (d/get-node (-> target :db :conf))]
(let [txs [[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "Farley Moat"
:hamster/age 12}]
[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "Barley Goat"
:hamster/age 3}]
[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "Gnarly Rote"
:hamster/age 99}]]]
(d/transact! node txs (format "Seed '%s' failed to apply." (ns-name *ns*)))))
(d/close!))
|
20627
|
(ns seeds.xtdb
(:require [xtdb.api :as xt]
[joplin.xtdb.database :as d]))
(defn run [target & args]
;; NOTE: in a real migration, use `with-open`. The joplin.xtdb test suite
;; seems to fail when using `with-open` because we use a shared node.
(when-let [node (d/get-node (-> target :db :conf))]
(let [txs [[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "<NAME>"
:hamster/age 12}]
[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "<NAME>"
:hamster/age 3}]
[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "<NAME>"
:hamster/age 99}]]]
(d/transact! node txs (format "Seed '%s' failed to apply." (ns-name *ns*)))))
(d/close!))
| true |
(ns seeds.xtdb
(:require [xtdb.api :as xt]
[joplin.xtdb.database :as d]))
(defn run [target & args]
;; NOTE: in a real migration, use `with-open`. The joplin.xtdb test suite
;; seems to fail when using `with-open` because we use a shared node.
(when-let [node (d/get-node (-> target :db :conf))]
(let [txs [[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "PI:NAME:<NAME>END_PI"
:hamster/age 12}]
[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "PI:NAME:<NAME>END_PI"
:hamster/age 3}]
[::xt/put {:xt/id (java.util.UUID/randomUUID)
:hamster/name "PI:NAME:<NAME>END_PI"
:hamster/age 99}]]]
(d/transact! node txs (format "Seed '%s' failed to apply." (ns-name *ns*)))))
(d/close!))
|
[
{
"context": "mock-users {\n :1 {:first-name \"Betty\"\n :last-name \"Velez\"\n ",
"end": 10309,
"score": 0.9998197555541992,
"start": 10304,
"tag": "NAME",
"value": "Betty"
},
{
"context": "name \"Betty\"\n :last-name \"Velez\"\n :email \"bettyrvelez",
"end": 10353,
"score": 0.9996978044509888,
"start": 10348,
"tag": "NAME",
"value": "Velez"
},
{
"context": "ame \"Velez\"\n :email \"[email protected]\"\n :phone \"475-23-7849",
"end": 10415,
"score": 0.9999271035194397,
"start": 10392,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "user-1.jpg\"}\n :2 {:first-name \"Carlos\"\n :last-name \"Doyle\"\n ",
"end": 10620,
"score": 0.9998156428337097,
"start": 10614,
"tag": "NAME",
"value": "Carlos"
},
{
"context": "ame \"Carlos\"\n :last-name \"Doyle\"\n :email \"carlosdoyle",
"end": 10664,
"score": 0.9997700452804565,
"start": 10659,
"tag": "NAME",
"value": "Doyle"
},
{
"context": "ame \"Doyle\"\n :email \"[email protected]\"\n :phone \"928-999-678",
"end": 10726,
"score": 0.9999299049377441,
"start": 10703,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "user-2.jpg\"}\n :3 {:first-name \"Carrie\"\n :last-name \"Ball\"\n ",
"end": 10932,
"score": 0.999815821647644,
"start": 10926,
"tag": "NAME",
"value": "Carrie"
},
{
"context": "ame \"Carrie\"\n :last-name \"Ball\"\n :email \"carrieball@",
"end": 10975,
"score": 0.9995416402816772,
"start": 10971,
"tag": "NAME",
"value": "Ball"
},
{
"context": "name \"Ball\"\n :email \"[email protected]\"\n :phone \"321-260-719",
"end": 11039,
"score": 0.9999305009841919,
"start": 11014,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "user-3.jpg\"}\n :4 {:first-name \"Brian\"\n :last-name \"Nelson\"\n ",
"end": 11245,
"score": 0.9998066425323486,
"start": 11240,
"tag": "NAME",
"value": "Brian"
},
{
"context": "name \"Brian\"\n :last-name \"Nelson\"\n :email \"briannelson",
"end": 11290,
"score": 0.9997875094413757,
"start": 11284,
"tag": "NAME",
"value": "Nelson"
},
{
"context": "me \"Nelson\"\n :email \"[email protected]\"\n :phone \"617-295-930",
"end": 11355,
"score": 0.999934732913971,
"start": 11329,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "user-4.jpg\"}\n :5 {:first-name \"Norman\"\n :last-name \"Mendoza\"\n ",
"end": 11558,
"score": 0.999822735786438,
"start": 11552,
"tag": "NAME",
"value": "Norman"
},
{
"context": "ame \"Norman\"\n :last-name \"Mendoza\"\n :email \"normanmendo",
"end": 11604,
"score": 0.9994857907295227,
"start": 11597,
"tag": "NAME",
"value": "Mendoza"
},
{
"context": "e \"Mendoza\"\n :email \"[email protected]\"\n :phone \"732-8320-32",
"end": 11668,
"score": 0.9999356865882874,
"start": 11643,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "user-5.jpg\"}\n :6 {:first-name \"Thomas\"\n :last-name \"Colburn\"\n ",
"end": 11876,
"score": 0.9997316002845764,
"start": 11870,
"tag": "NAME",
"value": "Thomas"
},
{
"context": "ame \"Thomas\"\n :last-name \"Colburn\"\n :email \"thomascolbu",
"end": 11922,
"score": 0.9997365474700928,
"start": 11915,
"tag": "NAME",
"value": "Colburn"
},
{
"context": "e \"Colburn\"\n :email \"[email protected]\"\n :phone \"920-472-417",
"end": 11986,
"score": 0.9999324679374695,
"start": 11961,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/css-guide/styles/util.cljc
|
AlloyCSS/untangled-components
| 0 |
(ns styles.util
#?(:clj
(:require [devcards.core :as dc :include-macros true]
cljs.repl
[clojure.string :as str])
:cljs
(:require [devcards.core :as dc :include-macros true]
[clojure.set :as set]
[clojure.string :as str]
[hickory.core :as hc]
[untangled.client.mutations :as m]
[untangled.client.core :as uc]
[untangled.ui.elements :as e]
[om.next :as om :refer [defui]]
[om.dom :as dom]
[devcards.util.markdown :as md]
[devcards.util.edn-renderer :as edn])))
#?(:clj
(defmacro source->react [obj body]
(let [code (cljs.repl/source-fn &env obj)
; HACK: Use the first form in the sexp to find the end of the doc, so we can trim out the macro source
marker (str "(" (first body))
beginning (- (.indexOf code marker) 2)
; HACK: drop the last closing paren
end (- (.length code) 1)
code (.substring code beginning end)]
`(devcards.core/markdown->react
(dc/mkdn-code
~(or code (str "Source not found")))))))
#?(:clj
(defmacro defarticle
"Define an example that just renders some doc."
[sym doc]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"}) (devcards.core/markdown->react ~doc))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defexample
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div nil (devcards.core/markdown->react ~doc)))
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__figure u-column--12"})
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(~symfn this#)))
(om.dom/div (cljs.core/clj->js {:className "ui-example__source u-column--12"})
(styles.util/source->react ~symfn ~body))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defview
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div nil (devcards.core/markdown->react ~doc)))
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__figure u-column--12"})
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(~symfn this#)))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defviewport
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-viewport-container"})
(om.dom/div (cljs.core/clj->js {:className "ui-viewport ui-viewport--mobile ui-viewport--android"})
(e/ui-iframe {:height "570" :width "100%"}
(om.dom/div nil
(om.dom/link (cljs.core/clj->js {:rel "stylesheet" :href "css/untangled-ui.css"}))
(~symfn this#))))
(om.dom/div (cljs.core/clj->js {:className "c-message c-message--neutral u-leader--quarter"})
(om.dom/div nil (devcards.core/markdown->react ~doc))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defsnippet
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__source u-column--12"})
(styles.util/source->react ~symfn ~body))))))
(def ~sym {:name ~(name sym)
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
(def attr-renames {
:class :className
:for :htmlFor
:tabindex :tabIndex
:viewbox :viewBox
:spellcheck :spellcheck
:autocorrect :autoCorrect
:autocomplete :autoComplete})
#?(:cljs
(defn elem-to-cljs [elem]
(cond
(string? elem) elem
(vector? elem) (let [tag (name (first elem))
attrs (set/rename-keys (second elem) attr-renames)
children (map elem-to-cljs (rest (rest elem)))]
(concat (list (symbol "dom" tag) (symbol "#js") attrs) children))
:otherwise "UNKNOWN")))
#?(:cljs
(defn to-cljs
"Convert an HTML fragment (containing just one tag) into a corresponding Om Dom cljs"
[html-fragment]
(let [hiccup-list (map hc/as-hiccup (hc/parse-fragment html-fragment))]
(first (map elem-to-cljs hiccup-list)))))
#?(:cljs
(defmethod m/mutate 'convert [{:keys [state]} k p]
{:action (fn []
(let [html (get-in @state [:top :conv :html])
cljs (to-cljs html)]
(swap! state assoc-in [:top :conv :cljs] cljs)))}))
#?(:cljs
(defui HTMLConverter
static uc/InitialAppState
(initial-state [clz params] {:html "<div> </div>" :cljs (list)})
static om/IQuery
(query [this] [:cljs :html])
static om/Ident
(ident [this p] [:top :conv])
Object
(render [this]
(let [{:keys [html cljs]} (om/props this)]
(dom/div #js {:className ""}
(dom/textarea #js {:cols 80 :rows 10
:onChange (fn [evt] (m/set-string! this :html :event evt))
:value html})
(dom/div #js {} (edn/html-edn cljs))
(dom/button #js {:className "c-button" :onClick (fn [evt]
(om/transact! this '[(convert)]))} "Convert"))))))
#?(:cljs
(def ui-html-convert (om/factory HTMLConverter)))
#?(:cljs
(defui HTMLConverterApp
static uc/InitialAppState
(initial-state [clz params] {:converter (uc/initial-state HTMLConverter {})})
static om/IQuery
(query [this] [{:converter (om/get-query HTMLConverter)} :react-key])
static om/Ident
(ident [this p] [:top :conv])
Object
(render [this]
(let [{:keys [converter ui/react-key]} (om/props this)]
(dom/div
#js {:key react-key} (ui-html-convert converter))))))
#?(:cljs
(defn section
"Render a section with examples."
[id sections]
(let [{:keys [title documentation examples]} (first (filter #(= id (:id %)) sections))]
(dom/span nil
(dom/a #js {:id id}
(dom/h1 nil title))
(when documentation
(dom/div #js {:className "ui-example__description"} (dc/markdown->react documentation)))
(map-indexed (fn [idx render]
(dom/span #js {:key (str "section-" idx)}
(render))) examples)))))
#?(:cljs
(defn section-index
"Render a clickable index of a given set of sections."
[sections]
(dom/ul nil
(map #(dom/li nil (dom/a #js {:href (str "#" (:id %))} (:title %))) sections))))
#?(:cljs
(def mock-users {
:1 {:first-name "Betty"
:last-name "Velez"
:email "[email protected]"
:phone "475-23-7849"
:birthday "October 30, 1936"
:photo "/img/user-1.jpg"}
:2 {:first-name "Carlos"
:last-name "Doyle"
:email "[email protected]"
:phone "928-999-6782"
:birthday "October 11, 1942"
:photo "/img/user-2.jpg"}
:3 {:first-name "Carrie"
:last-name "Ball"
:email "[email protected]"
:phone "321-260-7190"
:birthday "February 15, 1945"
:photo "/img/user-3.jpg"}
:4 {:first-name "Brian"
:last-name "Nelson"
:email "[email protected]"
:phone "617-295-9302"
:birthday "March 5, 1980"
:photo "/img/user-4.jpg"}
:5 {:first-name "Norman"
:last-name "Mendoza"
:email "[email protected]"
:phone "732-8320-3240"
:birthday "November 14, 1981"
:photo "/img/user-5.jpg"}
:6 {:first-name "Thomas"
:last-name "Colburn"
:email "[email protected]"
:phone "920-472-4173"
:birthday "November 9, 1987"
:photo "/img/user-6.jpg"}
}))
#?(:cljs
(defn full-name [num]
(str (:first-name (mock-users num)) " " (:last-name (mock-users num)))))
|
89193
|
(ns styles.util
#?(:clj
(:require [devcards.core :as dc :include-macros true]
cljs.repl
[clojure.string :as str])
:cljs
(:require [devcards.core :as dc :include-macros true]
[clojure.set :as set]
[clojure.string :as str]
[hickory.core :as hc]
[untangled.client.mutations :as m]
[untangled.client.core :as uc]
[untangled.ui.elements :as e]
[om.next :as om :refer [defui]]
[om.dom :as dom]
[devcards.util.markdown :as md]
[devcards.util.edn-renderer :as edn])))
#?(:clj
(defmacro source->react [obj body]
(let [code (cljs.repl/source-fn &env obj)
; HACK: Use the first form in the sexp to find the end of the doc, so we can trim out the macro source
marker (str "(" (first body))
beginning (- (.indexOf code marker) 2)
; HACK: drop the last closing paren
end (- (.length code) 1)
code (.substring code beginning end)]
`(devcards.core/markdown->react
(dc/mkdn-code
~(or code (str "Source not found")))))))
#?(:clj
(defmacro defarticle
"Define an example that just renders some doc."
[sym doc]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"}) (devcards.core/markdown->react ~doc))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defexample
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div nil (devcards.core/markdown->react ~doc)))
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__figure u-column--12"})
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(~symfn this#)))
(om.dom/div (cljs.core/clj->js {:className "ui-example__source u-column--12"})
(styles.util/source->react ~symfn ~body))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defview
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div nil (devcards.core/markdown->react ~doc)))
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__figure u-column--12"})
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(~symfn this#)))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defviewport
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-viewport-container"})
(om.dom/div (cljs.core/clj->js {:className "ui-viewport ui-viewport--mobile ui-viewport--android"})
(e/ui-iframe {:height "570" :width "100%"}
(om.dom/div nil
(om.dom/link (cljs.core/clj->js {:rel "stylesheet" :href "css/untangled-ui.css"}))
(~symfn this#))))
(om.dom/div (cljs.core/clj->js {:className "c-message c-message--neutral u-leader--quarter"})
(om.dom/div nil (devcards.core/markdown->react ~doc))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defsnippet
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__source u-column--12"})
(styles.util/source->react ~symfn ~body))))))
(def ~sym {:name ~(name sym)
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
(def attr-renames {
:class :className
:for :htmlFor
:tabindex :tabIndex
:viewbox :viewBox
:spellcheck :spellcheck
:autocorrect :autoCorrect
:autocomplete :autoComplete})
#?(:cljs
(defn elem-to-cljs [elem]
(cond
(string? elem) elem
(vector? elem) (let [tag (name (first elem))
attrs (set/rename-keys (second elem) attr-renames)
children (map elem-to-cljs (rest (rest elem)))]
(concat (list (symbol "dom" tag) (symbol "#js") attrs) children))
:otherwise "UNKNOWN")))
#?(:cljs
(defn to-cljs
"Convert an HTML fragment (containing just one tag) into a corresponding Om Dom cljs"
[html-fragment]
(let [hiccup-list (map hc/as-hiccup (hc/parse-fragment html-fragment))]
(first (map elem-to-cljs hiccup-list)))))
#?(:cljs
(defmethod m/mutate 'convert [{:keys [state]} k p]
{:action (fn []
(let [html (get-in @state [:top :conv :html])
cljs (to-cljs html)]
(swap! state assoc-in [:top :conv :cljs] cljs)))}))
#?(:cljs
(defui HTMLConverter
static uc/InitialAppState
(initial-state [clz params] {:html "<div> </div>" :cljs (list)})
static om/IQuery
(query [this] [:cljs :html])
static om/Ident
(ident [this p] [:top :conv])
Object
(render [this]
(let [{:keys [html cljs]} (om/props this)]
(dom/div #js {:className ""}
(dom/textarea #js {:cols 80 :rows 10
:onChange (fn [evt] (m/set-string! this :html :event evt))
:value html})
(dom/div #js {} (edn/html-edn cljs))
(dom/button #js {:className "c-button" :onClick (fn [evt]
(om/transact! this '[(convert)]))} "Convert"))))))
#?(:cljs
(def ui-html-convert (om/factory HTMLConverter)))
#?(:cljs
(defui HTMLConverterApp
static uc/InitialAppState
(initial-state [clz params] {:converter (uc/initial-state HTMLConverter {})})
static om/IQuery
(query [this] [{:converter (om/get-query HTMLConverter)} :react-key])
static om/Ident
(ident [this p] [:top :conv])
Object
(render [this]
(let [{:keys [converter ui/react-key]} (om/props this)]
(dom/div
#js {:key react-key} (ui-html-convert converter))))))
#?(:cljs
(defn section
"Render a section with examples."
[id sections]
(let [{:keys [title documentation examples]} (first (filter #(= id (:id %)) sections))]
(dom/span nil
(dom/a #js {:id id}
(dom/h1 nil title))
(when documentation
(dom/div #js {:className "ui-example__description"} (dc/markdown->react documentation)))
(map-indexed (fn [idx render]
(dom/span #js {:key (str "section-" idx)}
(render))) examples)))))
#?(:cljs
(defn section-index
"Render a clickable index of a given set of sections."
[sections]
(dom/ul nil
(map #(dom/li nil (dom/a #js {:href (str "#" (:id %))} (:title %))) sections))))
#?(:cljs
(def mock-users {
:1 {:first-name "<NAME>"
:last-name "<NAME>"
:email "<EMAIL>"
:phone "475-23-7849"
:birthday "October 30, 1936"
:photo "/img/user-1.jpg"}
:2 {:first-name "<NAME>"
:last-name "<NAME>"
:email "<EMAIL>"
:phone "928-999-6782"
:birthday "October 11, 1942"
:photo "/img/user-2.jpg"}
:3 {:first-name "<NAME>"
:last-name "<NAME>"
:email "<EMAIL>"
:phone "321-260-7190"
:birthday "February 15, 1945"
:photo "/img/user-3.jpg"}
:4 {:first-name "<NAME>"
:last-name "<NAME>"
:email "<EMAIL>"
:phone "617-295-9302"
:birthday "March 5, 1980"
:photo "/img/user-4.jpg"}
:5 {:first-name "<NAME>"
:last-name "<NAME>"
:email "<EMAIL>"
:phone "732-8320-3240"
:birthday "November 14, 1981"
:photo "/img/user-5.jpg"}
:6 {:first-name "<NAME>"
:last-name "<NAME>"
:email "<EMAIL>"
:phone "920-472-4173"
:birthday "November 9, 1987"
:photo "/img/user-6.jpg"}
}))
#?(:cljs
(defn full-name [num]
(str (:first-name (mock-users num)) " " (:last-name (mock-users num)))))
| true |
(ns styles.util
#?(:clj
(:require [devcards.core :as dc :include-macros true]
cljs.repl
[clojure.string :as str])
:cljs
(:require [devcards.core :as dc :include-macros true]
[clojure.set :as set]
[clojure.string :as str]
[hickory.core :as hc]
[untangled.client.mutations :as m]
[untangled.client.core :as uc]
[untangled.ui.elements :as e]
[om.next :as om :refer [defui]]
[om.dom :as dom]
[devcards.util.markdown :as md]
[devcards.util.edn-renderer :as edn])))
#?(:clj
(defmacro source->react [obj body]
(let [code (cljs.repl/source-fn &env obj)
; HACK: Use the first form in the sexp to find the end of the doc, so we can trim out the macro source
marker (str "(" (first body))
beginning (- (.indexOf code marker) 2)
; HACK: drop the last closing paren
end (- (.length code) 1)
code (.substring code beginning end)]
`(devcards.core/markdown->react
(dc/mkdn-code
~(or code (str "Source not found")))))))
#?(:clj
(defmacro defarticle
"Define an example that just renders some doc."
[sym doc]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"}) (devcards.core/markdown->react ~doc))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defexample
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div nil (devcards.core/markdown->react ~doc)))
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__figure u-column--12"})
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(~symfn this#)))
(om.dom/div (cljs.core/clj->js {:className "ui-example__source u-column--12"})
(styles.util/source->react ~symfn ~body))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defview
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__description"})
(om.dom/div nil (devcards.core/markdown->react ~doc)))
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__figure u-column--12"})
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(~symfn this#)))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defviewport
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym doc body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-viewport-container"})
(om.dom/div (cljs.core/clj->js {:className "ui-viewport ui-viewport--mobile ui-viewport--android"})
(e/ui-iframe {:height "570" :width "100%"}
(om.dom/div nil
(om.dom/link (cljs.core/clj->js {:rel "stylesheet" :href "css/untangled-ui.css"}))
(~symfn this#))))
(om.dom/div (cljs.core/clj->js {:className "c-message c-message--neutral u-leader--quarter"})
(om.dom/div nil (devcards.core/markdown->react ~doc))))))
(def ~sym {:name ~(name sym)
:documentation ~doc
:search-terms ~(str/join " " (map str/lower-case [doc (name sym)]))
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
#?(:clj
(defmacro defsnippet
"Define a DOM example. The body may reference `this` as if in the body of
an Om component `(render [this] ...)`"
[sym body]
(let [basename (str sym "-")
root (gensym basename)
symfn (symbol (str (name sym) "-code"))]
`(do
(defn ~symfn [~'this] ~body)
(om.next/defui ~root
~'Object
(~'render [this#]
(om.dom/div (cljs.core/clj->js {:className "ui-example"})
(om.dom/div (cljs.core/clj->js {:className "u-row"})
(om.dom/div (cljs.core/clj->js {:className "ui-example__source u-column--12"})
(styles.util/source->react ~symfn ~body))))))
(def ~sym {:name ~(name sym)
:renderer (om.next/factory ~root {:keyfn (fn [] ~(name root))})})))))
(def attr-renames {
:class :className
:for :htmlFor
:tabindex :tabIndex
:viewbox :viewBox
:spellcheck :spellcheck
:autocorrect :autoCorrect
:autocomplete :autoComplete})
#?(:cljs
(defn elem-to-cljs [elem]
(cond
(string? elem) elem
(vector? elem) (let [tag (name (first elem))
attrs (set/rename-keys (second elem) attr-renames)
children (map elem-to-cljs (rest (rest elem)))]
(concat (list (symbol "dom" tag) (symbol "#js") attrs) children))
:otherwise "UNKNOWN")))
#?(:cljs
(defn to-cljs
"Convert an HTML fragment (containing just one tag) into a corresponding Om Dom cljs"
[html-fragment]
(let [hiccup-list (map hc/as-hiccup (hc/parse-fragment html-fragment))]
(first (map elem-to-cljs hiccup-list)))))
#?(:cljs
(defmethod m/mutate 'convert [{:keys [state]} k p]
{:action (fn []
(let [html (get-in @state [:top :conv :html])
cljs (to-cljs html)]
(swap! state assoc-in [:top :conv :cljs] cljs)))}))
#?(:cljs
(defui HTMLConverter
static uc/InitialAppState
(initial-state [clz params] {:html "<div> </div>" :cljs (list)})
static om/IQuery
(query [this] [:cljs :html])
static om/Ident
(ident [this p] [:top :conv])
Object
(render [this]
(let [{:keys [html cljs]} (om/props this)]
(dom/div #js {:className ""}
(dom/textarea #js {:cols 80 :rows 10
:onChange (fn [evt] (m/set-string! this :html :event evt))
:value html})
(dom/div #js {} (edn/html-edn cljs))
(dom/button #js {:className "c-button" :onClick (fn [evt]
(om/transact! this '[(convert)]))} "Convert"))))))
#?(:cljs
(def ui-html-convert (om/factory HTMLConverter)))
#?(:cljs
(defui HTMLConverterApp
static uc/InitialAppState
(initial-state [clz params] {:converter (uc/initial-state HTMLConverter {})})
static om/IQuery
(query [this] [{:converter (om/get-query HTMLConverter)} :react-key])
static om/Ident
(ident [this p] [:top :conv])
Object
(render [this]
(let [{:keys [converter ui/react-key]} (om/props this)]
(dom/div
#js {:key react-key} (ui-html-convert converter))))))
#?(:cljs
(defn section
"Render a section with examples."
[id sections]
(let [{:keys [title documentation examples]} (first (filter #(= id (:id %)) sections))]
(dom/span nil
(dom/a #js {:id id}
(dom/h1 nil title))
(when documentation
(dom/div #js {:className "ui-example__description"} (dc/markdown->react documentation)))
(map-indexed (fn [idx render]
(dom/span #js {:key (str "section-" idx)}
(render))) examples)))))
#?(:cljs
(defn section-index
"Render a clickable index of a given set of sections."
[sections]
(dom/ul nil
(map #(dom/li nil (dom/a #js {:href (str "#" (:id %))} (:title %))) sections))))
#?(:cljs
(def mock-users {
:1 {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "475-23-7849"
:birthday "October 30, 1936"
:photo "/img/user-1.jpg"}
:2 {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "928-999-6782"
:birthday "October 11, 1942"
:photo "/img/user-2.jpg"}
:3 {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "321-260-7190"
:birthday "February 15, 1945"
:photo "/img/user-3.jpg"}
:4 {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "617-295-9302"
:birthday "March 5, 1980"
:photo "/img/user-4.jpg"}
:5 {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "732-8320-3240"
:birthday "November 14, 1981"
:photo "/img/user-5.jpg"}
:6 {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:phone "920-472-4173"
:birthday "November 9, 1987"
:photo "/img/user-6.jpg"}
}))
#?(:cljs
(defn full-name [num]
(str (:first-name (mock-users num)) " " (:last-name (mock-users num)))))
|
[
{
"context": "atic-table-resolver :song/id\n {1 {:song/name \"Marchinha Psicotica de Dr. Soup\"}\n 2 {:song/name \"There's Enough",
"end": 1500,
"score": 0.8580642938613892,
"start": 1481,
"tag": "NAME",
"value": "Marchinha Psicotica"
},
{
"context": "/id\n {1 {:song/name \"Marchinha Psicotica de Dr. Soup\"}\n 2 {:song/name \"There's Enough\"}})\n\n ; y",
"end": 1512,
"score": 0.7788504958152771,
"start": 1508,
"tag": "NAME",
"value": "Soup"
},
{
"context": "/name :song/duration]))\n; => #:song{:id 1, :name \"Marchinha Psicotica de Dr. Soup\", :duration 280}\n\n;; 05: Static Attribute Map\n\n; ",
"end": 1970,
"score": 0.8886480927467346,
"start": 1939,
"tag": "NAME",
"value": "Marchinha Psicotica de Dr. Soup"
},
{
"context": "tribute-map-resolver :song/id :song/name\n {1 \"Marchinha Psicotica de Dr. Soup\"\n 2 \"There's Enough\"})\n\n (pbir/static-tabl",
"end": 2193,
"score": 0.9141724705696106,
"start": 2162,
"tag": "NAME",
"value": "Marchinha Psicotica de Dr. Soup"
},
{
"context": "/name :song/duration]))\n; => #:song{:id 1, :name \"Marchinha Psicotica de Dr. Soup\", :duration 280}\n\n;; 06: EDN File Resolver\n\n; app",
"end": 2560,
"score": 0.914606511592865,
"start": 2529,
"tag": "NAME",
"value": "Marchinha Psicotica de Dr. Soup"
},
{
"context": "; => {:my.system/port 1234, :my.system.user/name \"Anne\"}\n\n;; 08: Global Data\n\n; Global data is the same ",
"end": 3256,
"score": 0.9988473653793335,
"start": 3252,
"tag": "NAME",
"value": "Anne"
}
] |
clj/ex/study_pathom/pathom01/src/main/builtin_resolver01.clj
|
mertnuhoglu/study
| 1 |
(ns main.builtin-resolver01
(:require
[com.wsscode.pathom3.connect.operation :as pco]
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.interface.smart-map :as psm]
[com.wsscode.pathom3.connect.built-in.resolvers :as pbir]))
;; 01: Constants
; constant literal
(pbir/constantly-resolver :math/PI 3.1415)
; constant function value
(pbir/constantly-fn-resolver ::throw-error (fn [_] (throw (ex-info "Error" {}))))
;; 02: Aliasing
(pbir/alias-resolver :specific.impl.product/id :generic.ui.product/id)
; is equivalent to:
(pco/defresolver spec->generic-prod-id [{:specific.impl.product/keys [id]}]
{:generic.ui.product/id id})
;; 02: Equivalence
(pbir/equivalence-resolver :acme.product/upc :affiliate.product/upc)
; iki yönlü alias gibi düşün bunu
;; 03: Simple one-to-one transformation
; in this example we create one different transformation for each direction
(def registry
[(pbir/single-attr-resolver :acme.track/duration-ms :affiliate.track/duration-seconds #(/ % 1000))
(pbir/single-attr-resolver :affiliate.track/duration-seconds :acme.track/duration-ms #(* % 1000))])
(def indexes (pci/register registry))
(-> (psm/smart-map indexes {:acme.track/duration-ms 324000})
:affiliate.track/duration-seconds)
; => 324
(-> (psm/smart-map indexes {:affiliate.track/duration-seconds 324})
:acme.track/duration-ms)
; => 324000
;; 04: Static Tables
(def registry
[(pbir/static-table-resolver :song/id
{1 {:song/name "Marchinha Psicotica de Dr. Soup"}
2 {:song/name "There's Enough"}})
; you can provide a name for the resolver, prefer fully qualified symbols
(pbir/static-table-resolver `song-analysis :song/id
{1 {:song/duration 280 :song/tempo 98}
2 {:song/duration 150 :song/tempo 130}})])
(let [sm (psm/smart-map (pci/register registry)
{:song/id 1})]
(select-keys sm [:song/id :song/name :song/duration]))
; => #:song{:id 1, :name "Marchinha Psicotica de Dr. Soup", :duration 280}
;; 05: Static Attribute Map
; Tek atributtan oluşan tablolar
(def registry
[; simple attribute table
(pbir/static-attribute-map-resolver :song/id :song/name
{1 "Marchinha Psicotica de Dr. Soup"
2 "There's Enough"})
(pbir/static-table-resolver `song-analysis :song/id
{1 {:song/duration 280 :song/tempo 98}
2 {:song/duration 150 :song/tempo 130}})])
(let [sm (psm/smart-map (pci/register registry)
{:song/id 1})]
(select-keys sm [:song/id :song/name :song/duration]))
; => #:song{:id 1, :name "Marchinha Psicotica de Dr. Soup", :duration 280}
;; 06: EDN File Resolver
; app
(pco/defresolver full-url [{:keys [my.system.server/port my.system.resource/path]}]
{::server-url (str "http://localhost:" port "/" path)})
(def registry
[(pbir/edn-file-resolver "resources/file-resolver.edn")
full-url])
(-> (psm/smart-map (pci/register registry))
::server-url)
; => "http://localhost:1234/resources/public
;; 07: Static tables on EDN Files
; app
(def registry (pbir/edn-file-resolver "resources/file-resolver-with-table.edn"))
(let [sm (psm/smart-map (pci/register registry) {:my.system/user-id 4})]
(select-keys sm [:my.system/port :my.system.user/name]))
; => {:my.system/port 1234, :my.system.user/name "Anne"}
;; 08: Global Data
; Global data is the same operation that EDN Files do, but using the data directly:
; app
(pco/defresolver full-url [{:keys [my.system.server/port my.system.resource/path]}]
{::server-url (str "http://localhost:" port "/" path)})
(def registry
[(pbir/global-data-resolver {:my.system.server/port
1234
:my.system.resource/path
"resources/public"})
full-url])
(-> (psm/smart-map (pci/register registry))
::server-url)
; => "http://localhost:1234/resources/public
|
95014
|
(ns main.builtin-resolver01
(:require
[com.wsscode.pathom3.connect.operation :as pco]
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.interface.smart-map :as psm]
[com.wsscode.pathom3.connect.built-in.resolvers :as pbir]))
;; 01: Constants
; constant literal
(pbir/constantly-resolver :math/PI 3.1415)
; constant function value
(pbir/constantly-fn-resolver ::throw-error (fn [_] (throw (ex-info "Error" {}))))
;; 02: Aliasing
(pbir/alias-resolver :specific.impl.product/id :generic.ui.product/id)
; is equivalent to:
(pco/defresolver spec->generic-prod-id [{:specific.impl.product/keys [id]}]
{:generic.ui.product/id id})
;; 02: Equivalence
(pbir/equivalence-resolver :acme.product/upc :affiliate.product/upc)
; iki yönlü alias gibi düşün bunu
;; 03: Simple one-to-one transformation
; in this example we create one different transformation for each direction
(def registry
[(pbir/single-attr-resolver :acme.track/duration-ms :affiliate.track/duration-seconds #(/ % 1000))
(pbir/single-attr-resolver :affiliate.track/duration-seconds :acme.track/duration-ms #(* % 1000))])
(def indexes (pci/register registry))
(-> (psm/smart-map indexes {:acme.track/duration-ms 324000})
:affiliate.track/duration-seconds)
; => 324
(-> (psm/smart-map indexes {:affiliate.track/duration-seconds 324})
:acme.track/duration-ms)
; => 324000
;; 04: Static Tables
(def registry
[(pbir/static-table-resolver :song/id
{1 {:song/name "<NAME> de Dr. <NAME>"}
2 {:song/name "There's Enough"}})
; you can provide a name for the resolver, prefer fully qualified symbols
(pbir/static-table-resolver `song-analysis :song/id
{1 {:song/duration 280 :song/tempo 98}
2 {:song/duration 150 :song/tempo 130}})])
(let [sm (psm/smart-map (pci/register registry)
{:song/id 1})]
(select-keys sm [:song/id :song/name :song/duration]))
; => #:song{:id 1, :name "<NAME>", :duration 280}
;; 05: Static Attribute Map
; Tek atributtan oluşan tablolar
(def registry
[; simple attribute table
(pbir/static-attribute-map-resolver :song/id :song/name
{1 "<NAME>"
2 "There's Enough"})
(pbir/static-table-resolver `song-analysis :song/id
{1 {:song/duration 280 :song/tempo 98}
2 {:song/duration 150 :song/tempo 130}})])
(let [sm (psm/smart-map (pci/register registry)
{:song/id 1})]
(select-keys sm [:song/id :song/name :song/duration]))
; => #:song{:id 1, :name "<NAME>", :duration 280}
;; 06: EDN File Resolver
; app
(pco/defresolver full-url [{:keys [my.system.server/port my.system.resource/path]}]
{::server-url (str "http://localhost:" port "/" path)})
(def registry
[(pbir/edn-file-resolver "resources/file-resolver.edn")
full-url])
(-> (psm/smart-map (pci/register registry))
::server-url)
; => "http://localhost:1234/resources/public
;; 07: Static tables on EDN Files
; app
(def registry (pbir/edn-file-resolver "resources/file-resolver-with-table.edn"))
(let [sm (psm/smart-map (pci/register registry) {:my.system/user-id 4})]
(select-keys sm [:my.system/port :my.system.user/name]))
; => {:my.system/port 1234, :my.system.user/name "<NAME>"}
;; 08: Global Data
; Global data is the same operation that EDN Files do, but using the data directly:
; app
(pco/defresolver full-url [{:keys [my.system.server/port my.system.resource/path]}]
{::server-url (str "http://localhost:" port "/" path)})
(def registry
[(pbir/global-data-resolver {:my.system.server/port
1234
:my.system.resource/path
"resources/public"})
full-url])
(-> (psm/smart-map (pci/register registry))
::server-url)
; => "http://localhost:1234/resources/public
| true |
(ns main.builtin-resolver01
(:require
[com.wsscode.pathom3.connect.operation :as pco]
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.interface.smart-map :as psm]
[com.wsscode.pathom3.connect.built-in.resolvers :as pbir]))
;; 01: Constants
; constant literal
(pbir/constantly-resolver :math/PI 3.1415)
; constant function value
(pbir/constantly-fn-resolver ::throw-error (fn [_] (throw (ex-info "Error" {}))))
;; 02: Aliasing
(pbir/alias-resolver :specific.impl.product/id :generic.ui.product/id)
; is equivalent to:
(pco/defresolver spec->generic-prod-id [{:specific.impl.product/keys [id]}]
{:generic.ui.product/id id})
;; 02: Equivalence
(pbir/equivalence-resolver :acme.product/upc :affiliate.product/upc)
; iki yönlü alias gibi düşün bunu
;; 03: Simple one-to-one transformation
; in this example we create one different transformation for each direction
(def registry
[(pbir/single-attr-resolver :acme.track/duration-ms :affiliate.track/duration-seconds #(/ % 1000))
(pbir/single-attr-resolver :affiliate.track/duration-seconds :acme.track/duration-ms #(* % 1000))])
(def indexes (pci/register registry))
(-> (psm/smart-map indexes {:acme.track/duration-ms 324000})
:affiliate.track/duration-seconds)
; => 324
(-> (psm/smart-map indexes {:affiliate.track/duration-seconds 324})
:acme.track/duration-ms)
; => 324000
;; 04: Static Tables
(def registry
[(pbir/static-table-resolver :song/id
{1 {:song/name "PI:NAME:<NAME>END_PI de Dr. PI:NAME:<NAME>END_PI"}
2 {:song/name "There's Enough"}})
; you can provide a name for the resolver, prefer fully qualified symbols
(pbir/static-table-resolver `song-analysis :song/id
{1 {:song/duration 280 :song/tempo 98}
2 {:song/duration 150 :song/tempo 130}})])
(let [sm (psm/smart-map (pci/register registry)
{:song/id 1})]
(select-keys sm [:song/id :song/name :song/duration]))
; => #:song{:id 1, :name "PI:NAME:<NAME>END_PI", :duration 280}
;; 05: Static Attribute Map
; Tek atributtan oluşan tablolar
(def registry
[; simple attribute table
(pbir/static-attribute-map-resolver :song/id :song/name
{1 "PI:NAME:<NAME>END_PI"
2 "There's Enough"})
(pbir/static-table-resolver `song-analysis :song/id
{1 {:song/duration 280 :song/tempo 98}
2 {:song/duration 150 :song/tempo 130}})])
(let [sm (psm/smart-map (pci/register registry)
{:song/id 1})]
(select-keys sm [:song/id :song/name :song/duration]))
; => #:song{:id 1, :name "PI:NAME:<NAME>END_PI", :duration 280}
;; 06: EDN File Resolver
; app
(pco/defresolver full-url [{:keys [my.system.server/port my.system.resource/path]}]
{::server-url (str "http://localhost:" port "/" path)})
(def registry
[(pbir/edn-file-resolver "resources/file-resolver.edn")
full-url])
(-> (psm/smart-map (pci/register registry))
::server-url)
; => "http://localhost:1234/resources/public
;; 07: Static tables on EDN Files
; app
(def registry (pbir/edn-file-resolver "resources/file-resolver-with-table.edn"))
(let [sm (psm/smart-map (pci/register registry) {:my.system/user-id 4})]
(select-keys sm [:my.system/port :my.system.user/name]))
; => {:my.system/port 1234, :my.system.user/name "PI:NAME:<NAME>END_PI"}
;; 08: Global Data
; Global data is the same operation that EDN Files do, but using the data directly:
; app
(pco/defresolver full-url [{:keys [my.system.server/port my.system.resource/path]}]
{::server-url (str "http://localhost:" port "/" path)})
(def registry
[(pbir/global-data-resolver {:my.system.server/port
1234
:my.system.resource/path
"resources/public"})
full-url])
(-> (psm/smart-map (pci/register registry))
::server-url)
; => "http://localhost:1234/resources/public
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.test.nettio.disc",
"end": 597,
"score": 0.9998575448989868,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
}
] |
src/test/clojure/czlab/test/nettio/discard.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.test.nettio.discard
"Sample netty app - accepts and discards the request."
(:gen-class)
(:require [czlab.basal.proc :as p]
[czlab.basal.core :as c]
[czlab.basal.util :as u]
[czlab.niou.core :as cc]
[czlab.nettio.server :as sv]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
(c/defonce- svr (atom nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- mkcb
[cb]
(fn [msg]
(-> (cc/http-result msg) cc/reply-result) (cb)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn discard-httpd<>
"Drops the req and returns OK"
[cb & args]
(sv/web-server-module<>
(merge {:user-cb (mkcb cb)} (c/kvs->map args))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn finz-server
[] (when @svr (c/stop @svr) (reset! svr nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn -main
[& args]
(cond
(< (count args) 2)
(println "usage: discard host port")
:else
(let [{:keys [host port] :as w}
(-> (discard-httpd<>
#(println "hello, poked by discarder!"))
(c/start {:host (nth args 0)
:port (c/s->int (nth args 1) 8080)}))]
(p/exit-hook #(c/stop w))
(reset! svr w)
(u/block!))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
65071
|
;; 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.test.nettio.discard
"Sample netty app - accepts and discards the request."
(:gen-class)
(:require [czlab.basal.proc :as p]
[czlab.basal.core :as c]
[czlab.basal.util :as u]
[czlab.niou.core :as cc]
[czlab.nettio.server :as sv]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
(c/defonce- svr (atom nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- mkcb
[cb]
(fn [msg]
(-> (cc/http-result msg) cc/reply-result) (cb)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn discard-httpd<>
"Drops the req and returns OK"
[cb & args]
(sv/web-server-module<>
(merge {:user-cb (mkcb cb)} (c/kvs->map args))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn finz-server
[] (when @svr (c/stop @svr) (reset! svr nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn -main
[& args]
(cond
(< (count args) 2)
(println "usage: discard host port")
:else
(let [{:keys [host port] :as w}
(-> (discard-httpd<>
#(println "hello, poked by discarder!"))
(c/start {:host (nth args 0)
:port (c/s->int (nth args 1) 8080)}))]
(p/exit-hook #(c/stop w))
(reset! svr w)
(u/block!))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;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.test.nettio.discard
"Sample netty app - accepts and discards the request."
(:gen-class)
(:require [czlab.basal.proc :as p]
[czlab.basal.core :as c]
[czlab.basal.util :as u]
[czlab.niou.core :as cc]
[czlab.nettio.server :as sv]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
(c/defonce- svr (atom nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- mkcb
[cb]
(fn [msg]
(-> (cc/http-result msg) cc/reply-result) (cb)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn discard-httpd<>
"Drops the req and returns OK"
[cb & args]
(sv/web-server-module<>
(merge {:user-cb (mkcb cb)} (c/kvs->map args))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn finz-server
[] (when @svr (c/stop @svr) (reset! svr nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn -main
[& args]
(cond
(< (count args) 2)
(println "usage: discard host port")
:else
(let [{:keys [host port] :as w}
(-> (discard-httpd<>
#(println "hello, poked by discarder!"))
(c/start {:host (nth args 0)
:port (c/s->int (nth args 1) 8080)}))]
(p/exit-hook #(c/stop w))
(reset! svr w)
(u/block!))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": "st-case for reactor-core.publisher.\"\n :author \"Vladimir Tsanev\"}\n reactor-core.publisher-test\n #?(:cljs (:requ",
"end": 686,
"score": 0.9998198747634888,
"start": 671,
"tag": "NAME",
"value": "Vladimir Tsanev"
}
] |
test/reactor_core/publisher_test.cljc
|
jaju/reactor-core-clojure
| 2 |
;
; Copyright 2018 the original author or authors.
;
; 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
^{:doc "A test-case for reactor-core.publisher."
:author "Vladimir Tsanev"}
reactor-core.publisher-test
#?(:cljs (:require-macros [cljs.test :refer [async]])
:clj
(:use [reactor-core.test :only [async]]))
(:require
#?(:cljs [cljs.test :as t]
:clj [clojure.test :as t])
[reactor-core.publisher :as p]))
#?(:cljs (set! *warn-on-infer* true)
:clj (set! *warn-on-reflection* true))
(t/deftest range-test
(t/testing "consume range."
(async done
(let [values (atom [])]
(->> (p/range 1 10)
(p/subscribe
(fn [value]
(swap! values conj value))
(fn [_])
(fn []
(t/is (= @values [1 2 3 4 5 6 7 8 9 10]))
(done))))))))
(t/deftest error-test
(t/testing "consume error"
(async done
(->> (p/error (ex-info "test" {}))
(p/subscribe
(fn [_] (t/is false))
(fn [e]
(t/is (thrown-with-msg? #?(:clj Exception :cljs js/Error) #"test" (throw e)))
(done))
(fn [] (t/is false)))))))
(t/deftest empty-test
(t/testing "consume empty"
(async done
(->> (p/empty)
(p/subscribe
(fn [_] (t/is false))
(fn [_] (t/is false))
(fn [] (t/is true)
(done)))))))
(t/deftest array-test
(t/testing "consume array."
(async done
(let [values (atom [])]
(->> (p/from (into-array [1 2 3]))
(p/subscribe
(fn [value]
(swap! values conj value))
(fn [_]
(t/is false))
(fn []
(t/is (= @values [1 2 3]))
(done))))))))
(t/deftest even-numbers-test
(t/testing "finishes"
(async done
(let [even-numbers (p/filter even? (p/range 1 6))
noop (fn [_])]
(p/subscribe noop noop done even-numbers))))
(t/testing "has 3 numbers"
(async done
(let [cnt (atom 0)
even-numbers (p/filter even? (p/range 1 6))
on-number (fn [_] (reset! cnt (inc @cnt)))]
(p/subscribe on-number
(constantly nil)
(fn []
(t/is (= 3 @cnt) "got 3 numbers")
(done))
even-numbers))))
(t/testing "has no errors"
(async done
(let [even-numbers (->> (p/range 1 6)
(p/filter even?)
(p/map (fn [_]
(throw (ex-info "oh no" {})))))]
(p/subscribe (fn [_])
(fn [e]
(t/is (thrown-with-msg? #?(:clj Exception :cljs js/Error) #"oh no" (throw e)))
(done))
(fn []
(t/is false "on-complete")
(done))
even-numbers)))))
|
39515
|
;
; Copyright 2018 the original author or authors.
;
; 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
^{:doc "A test-case for reactor-core.publisher."
:author "<NAME>"}
reactor-core.publisher-test
#?(:cljs (:require-macros [cljs.test :refer [async]])
:clj
(:use [reactor-core.test :only [async]]))
(:require
#?(:cljs [cljs.test :as t]
:clj [clojure.test :as t])
[reactor-core.publisher :as p]))
#?(:cljs (set! *warn-on-infer* true)
:clj (set! *warn-on-reflection* true))
(t/deftest range-test
(t/testing "consume range."
(async done
(let [values (atom [])]
(->> (p/range 1 10)
(p/subscribe
(fn [value]
(swap! values conj value))
(fn [_])
(fn []
(t/is (= @values [1 2 3 4 5 6 7 8 9 10]))
(done))))))))
(t/deftest error-test
(t/testing "consume error"
(async done
(->> (p/error (ex-info "test" {}))
(p/subscribe
(fn [_] (t/is false))
(fn [e]
(t/is (thrown-with-msg? #?(:clj Exception :cljs js/Error) #"test" (throw e)))
(done))
(fn [] (t/is false)))))))
(t/deftest empty-test
(t/testing "consume empty"
(async done
(->> (p/empty)
(p/subscribe
(fn [_] (t/is false))
(fn [_] (t/is false))
(fn [] (t/is true)
(done)))))))
(t/deftest array-test
(t/testing "consume array."
(async done
(let [values (atom [])]
(->> (p/from (into-array [1 2 3]))
(p/subscribe
(fn [value]
(swap! values conj value))
(fn [_]
(t/is false))
(fn []
(t/is (= @values [1 2 3]))
(done))))))))
(t/deftest even-numbers-test
(t/testing "finishes"
(async done
(let [even-numbers (p/filter even? (p/range 1 6))
noop (fn [_])]
(p/subscribe noop noop done even-numbers))))
(t/testing "has 3 numbers"
(async done
(let [cnt (atom 0)
even-numbers (p/filter even? (p/range 1 6))
on-number (fn [_] (reset! cnt (inc @cnt)))]
(p/subscribe on-number
(constantly nil)
(fn []
(t/is (= 3 @cnt) "got 3 numbers")
(done))
even-numbers))))
(t/testing "has no errors"
(async done
(let [even-numbers (->> (p/range 1 6)
(p/filter even?)
(p/map (fn [_]
(throw (ex-info "oh no" {})))))]
(p/subscribe (fn [_])
(fn [e]
(t/is (thrown-with-msg? #?(:clj Exception :cljs js/Error) #"oh no" (throw e)))
(done))
(fn []
(t/is false "on-complete")
(done))
even-numbers)))))
| true |
;
; Copyright 2018 the original author or authors.
;
; 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
^{:doc "A test-case for reactor-core.publisher."
:author "PI:NAME:<NAME>END_PI"}
reactor-core.publisher-test
#?(:cljs (:require-macros [cljs.test :refer [async]])
:clj
(:use [reactor-core.test :only [async]]))
(:require
#?(:cljs [cljs.test :as t]
:clj [clojure.test :as t])
[reactor-core.publisher :as p]))
#?(:cljs (set! *warn-on-infer* true)
:clj (set! *warn-on-reflection* true))
(t/deftest range-test
(t/testing "consume range."
(async done
(let [values (atom [])]
(->> (p/range 1 10)
(p/subscribe
(fn [value]
(swap! values conj value))
(fn [_])
(fn []
(t/is (= @values [1 2 3 4 5 6 7 8 9 10]))
(done))))))))
(t/deftest error-test
(t/testing "consume error"
(async done
(->> (p/error (ex-info "test" {}))
(p/subscribe
(fn [_] (t/is false))
(fn [e]
(t/is (thrown-with-msg? #?(:clj Exception :cljs js/Error) #"test" (throw e)))
(done))
(fn [] (t/is false)))))))
(t/deftest empty-test
(t/testing "consume empty"
(async done
(->> (p/empty)
(p/subscribe
(fn [_] (t/is false))
(fn [_] (t/is false))
(fn [] (t/is true)
(done)))))))
(t/deftest array-test
(t/testing "consume array."
(async done
(let [values (atom [])]
(->> (p/from (into-array [1 2 3]))
(p/subscribe
(fn [value]
(swap! values conj value))
(fn [_]
(t/is false))
(fn []
(t/is (= @values [1 2 3]))
(done))))))))
(t/deftest even-numbers-test
(t/testing "finishes"
(async done
(let [even-numbers (p/filter even? (p/range 1 6))
noop (fn [_])]
(p/subscribe noop noop done even-numbers))))
(t/testing "has 3 numbers"
(async done
(let [cnt (atom 0)
even-numbers (p/filter even? (p/range 1 6))
on-number (fn [_] (reset! cnt (inc @cnt)))]
(p/subscribe on-number
(constantly nil)
(fn []
(t/is (= 3 @cnt) "got 3 numbers")
(done))
even-numbers))))
(t/testing "has no errors"
(async done
(let [even-numbers (->> (p/range 1 6)
(p/filter even?)
(p/map (fn [_]
(throw (ex-info "oh no" {})))))]
(p/subscribe (fn [_])
(fn [e]
(t/is (thrown-with-msg? #?(:clj Exception :cljs js/Error) #"oh no" (throw e)))
(done))
(fn []
(t/is false "on-complete")
(done))
even-numbers)))))
|
[
{
"context": " \"properties\" [{\"key\" \"sum\"\n ",
"end": 3401,
"score": 0.9021121263504028,
"start": 3398,
"tag": "KEY",
"value": "sum"
}
] |
dev/src/dev.clj
|
xray-tech/xorc-xray
| 7 |
(ns dev
(:refer-clojure :exclude [test])
(:require [clojure.repl :refer :all]
[fipp.edn :refer [pprint]]
[clojure.tools.namespace.repl :refer [refresh]]
[clojure.java.io :as io]
[duct.core :as duct]
[duct.core.repl :as duct-repl]
[eftest.runner :as eftest]
[integrant.core :as ig]
[integrant.repl :refer [clear halt go init prep]]
[integrant.repl.state :as state :refer [config system]]
[qbits.alia :as alia]
[re.kafka-producer :as kafka]
[qbits.alia.uuid :as uuid]
[re.utils :as utils]))
(duct/load-hierarchy)
(defn read-config []
(duct/read-config (io/resource "re/config.dev.edn")))
;; TODO utility function to remove all daemon keys
(defn read-prod-config []
(-> (duct/read-config (io/resource "re/config.prod.edn"))
(dissoc :re/kafka-consumer)))
(defn test []
(eftest/run-tests (eftest/find-tests "test") {:multithread? false}))
(clojure.tools.namespace.repl/set-refresh-dirs "dev/src" "src" "test")
(when (io/resource "local.clj")
(load "local"))
(defn with-prod []
(integrant.repl/set-prep! (comp duct/prep read-prod-config)))
(def keys-to-start [:duct/daemon :re/init :re/db])
(integrant.repl/set-prep!
(fn []
(-> (read-config)
(duct/prep keys-to-start))))
;; resume / reset are copypasted here from integrant.repl.state. the only reason
;; for this is not to start all keys from config, but
;; only [:duct/daemon :re/init] descendants
(defn resume []
(if-let [prep state/preparer]
(let [cfg (prep)]
(alter-var-root #'state/config (constantly cfg))
(alter-var-root #'state/system (fn [sys]
(if sys
(ig/resume cfg sys keys-to-start)
(ig/init cfg keys-to-start))))
:resumed)
(throw (Error. "No system preparer function found."))))
(defn reset []
(integrant.repl/suspend)
(refresh :after 'dev/resume))
(comment
(add-program "dev" "re/oam/timer.oam")
(add-program "dev" "re/oam/subscription.oam"))
(defn add-program [universe path]
(let [program (uuid/random)]
(alia/execute (:session (:re/db system))
{:insert :programs
:values [[:universe universe]
[:id program]
[:is_active true]
[:oam (utils/file-to-byte-buffer (io/file (io/resource path)))]]})
program))
(comment
(send-event "dev" "events.SDKEvent" {"header" {"type" "events.SDKEvent"
"recipientId" "dev-entity"
"createdAt" 0
"source" "repl"}
"event" {"name" "dev-event"}
"environment" {"appId" "dev"}})
(send-event "dev" "events.SDKEvent" {"header" {"type" "events.SDKEvent"
"recipientId" "dev-entity"
"createdAt" 0
"source" "repl"}
"event" {"name" "checkout"
"properties" [{"key" "sum"
"numberValue" 1000}]}
"environment" {"appId" "dev"}}))
(defn send-event [topic type event]
(let [encoder (:re/encoder system)
kafka (:re/kafka-producer system)]
(kafka/send kafka {:topic topic
:key type
:value (encoder event)})))
|
100952
|
(ns dev
(:refer-clojure :exclude [test])
(:require [clojure.repl :refer :all]
[fipp.edn :refer [pprint]]
[clojure.tools.namespace.repl :refer [refresh]]
[clojure.java.io :as io]
[duct.core :as duct]
[duct.core.repl :as duct-repl]
[eftest.runner :as eftest]
[integrant.core :as ig]
[integrant.repl :refer [clear halt go init prep]]
[integrant.repl.state :as state :refer [config system]]
[qbits.alia :as alia]
[re.kafka-producer :as kafka]
[qbits.alia.uuid :as uuid]
[re.utils :as utils]))
(duct/load-hierarchy)
(defn read-config []
(duct/read-config (io/resource "re/config.dev.edn")))
;; TODO utility function to remove all daemon keys
(defn read-prod-config []
(-> (duct/read-config (io/resource "re/config.prod.edn"))
(dissoc :re/kafka-consumer)))
(defn test []
(eftest/run-tests (eftest/find-tests "test") {:multithread? false}))
(clojure.tools.namespace.repl/set-refresh-dirs "dev/src" "src" "test")
(when (io/resource "local.clj")
(load "local"))
(defn with-prod []
(integrant.repl/set-prep! (comp duct/prep read-prod-config)))
(def keys-to-start [:duct/daemon :re/init :re/db])
(integrant.repl/set-prep!
(fn []
(-> (read-config)
(duct/prep keys-to-start))))
;; resume / reset are copypasted here from integrant.repl.state. the only reason
;; for this is not to start all keys from config, but
;; only [:duct/daemon :re/init] descendants
(defn resume []
(if-let [prep state/preparer]
(let [cfg (prep)]
(alter-var-root #'state/config (constantly cfg))
(alter-var-root #'state/system (fn [sys]
(if sys
(ig/resume cfg sys keys-to-start)
(ig/init cfg keys-to-start))))
:resumed)
(throw (Error. "No system preparer function found."))))
(defn reset []
(integrant.repl/suspend)
(refresh :after 'dev/resume))
(comment
(add-program "dev" "re/oam/timer.oam")
(add-program "dev" "re/oam/subscription.oam"))
(defn add-program [universe path]
(let [program (uuid/random)]
(alia/execute (:session (:re/db system))
{:insert :programs
:values [[:universe universe]
[:id program]
[:is_active true]
[:oam (utils/file-to-byte-buffer (io/file (io/resource path)))]]})
program))
(comment
(send-event "dev" "events.SDKEvent" {"header" {"type" "events.SDKEvent"
"recipientId" "dev-entity"
"createdAt" 0
"source" "repl"}
"event" {"name" "dev-event"}
"environment" {"appId" "dev"}})
(send-event "dev" "events.SDKEvent" {"header" {"type" "events.SDKEvent"
"recipientId" "dev-entity"
"createdAt" 0
"source" "repl"}
"event" {"name" "checkout"
"properties" [{"key" "<KEY>"
"numberValue" 1000}]}
"environment" {"appId" "dev"}}))
(defn send-event [topic type event]
(let [encoder (:re/encoder system)
kafka (:re/kafka-producer system)]
(kafka/send kafka {:topic topic
:key type
:value (encoder event)})))
| true |
(ns dev
(:refer-clojure :exclude [test])
(:require [clojure.repl :refer :all]
[fipp.edn :refer [pprint]]
[clojure.tools.namespace.repl :refer [refresh]]
[clojure.java.io :as io]
[duct.core :as duct]
[duct.core.repl :as duct-repl]
[eftest.runner :as eftest]
[integrant.core :as ig]
[integrant.repl :refer [clear halt go init prep]]
[integrant.repl.state :as state :refer [config system]]
[qbits.alia :as alia]
[re.kafka-producer :as kafka]
[qbits.alia.uuid :as uuid]
[re.utils :as utils]))
(duct/load-hierarchy)
(defn read-config []
(duct/read-config (io/resource "re/config.dev.edn")))
;; TODO utility function to remove all daemon keys
(defn read-prod-config []
(-> (duct/read-config (io/resource "re/config.prod.edn"))
(dissoc :re/kafka-consumer)))
(defn test []
(eftest/run-tests (eftest/find-tests "test") {:multithread? false}))
(clojure.tools.namespace.repl/set-refresh-dirs "dev/src" "src" "test")
(when (io/resource "local.clj")
(load "local"))
(defn with-prod []
(integrant.repl/set-prep! (comp duct/prep read-prod-config)))
(def keys-to-start [:duct/daemon :re/init :re/db])
(integrant.repl/set-prep!
(fn []
(-> (read-config)
(duct/prep keys-to-start))))
;; resume / reset are copypasted here from integrant.repl.state. the only reason
;; for this is not to start all keys from config, but
;; only [:duct/daemon :re/init] descendants
(defn resume []
(if-let [prep state/preparer]
(let [cfg (prep)]
(alter-var-root #'state/config (constantly cfg))
(alter-var-root #'state/system (fn [sys]
(if sys
(ig/resume cfg sys keys-to-start)
(ig/init cfg keys-to-start))))
:resumed)
(throw (Error. "No system preparer function found."))))
(defn reset []
(integrant.repl/suspend)
(refresh :after 'dev/resume))
(comment
(add-program "dev" "re/oam/timer.oam")
(add-program "dev" "re/oam/subscription.oam"))
(defn add-program [universe path]
(let [program (uuid/random)]
(alia/execute (:session (:re/db system))
{:insert :programs
:values [[:universe universe]
[:id program]
[:is_active true]
[:oam (utils/file-to-byte-buffer (io/file (io/resource path)))]]})
program))
(comment
(send-event "dev" "events.SDKEvent" {"header" {"type" "events.SDKEvent"
"recipientId" "dev-entity"
"createdAt" 0
"source" "repl"}
"event" {"name" "dev-event"}
"environment" {"appId" "dev"}})
(send-event "dev" "events.SDKEvent" {"header" {"type" "events.SDKEvent"
"recipientId" "dev-entity"
"createdAt" 0
"source" "repl"}
"event" {"name" "checkout"
"properties" [{"key" "PI:KEY:<KEY>END_PI"
"numberValue" 1000}]}
"environment" {"appId" "dev"}}))
(defn send-event [topic type event]
(let [encoder (:re/encoder system)
kafka (:re/kafka-producer system)]
(kafka/send kafka {:topic topic
:key type
:value (encoder event)})))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.