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": "esql\"\n :username (or (System/getenv \"PG_USER\") \"test\")\n :password (or (System/getenv \"PG_PASSWORD\") ",
"end": 220,
"score": 0.5830251574516296,
"start": 216,
"tag": "USERNAME",
"value": "test"
},
{
"context": ")\n :password (or (System/getenv \"PG_PASSWORD\") \"password\")\n :server-name (or (System/getenv \"PG_HOST\") ",
"end": 279,
"score": 0.998721718788147,
"start": 271,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ")\n :server-name (or (System/getenv \"PG_HOST\") \"127.0.0.1\")\n :port-number (Integer/parseInt (or (System/g",
"end": 339,
"score": 0.99972003698349,
"start": 330,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | test/utility_belt/sql/connection.clj | nomnom-insights/nomnom.utility-belt.sql | 2 | (ns utility-belt.sql.connection
(:require
[utility-belt.sql.component.connection-pool :as cp]))
(def connection-spec
{:pool-name "test"
:adapter "postgresql"
:username (or (System/getenv "PG_USER") "test")
:password (or (System/getenv "PG_PASSWORD") "password")
:server-name (or (System/getenv "PG_HOST") "127.0.0.1")
:port-number (Integer/parseInt (or (System/getenv "PG_PORT") "5434"))
:maximum-pool-size 10
:database-name (or (System/getenv "PG_NAME") "test")})
(defn start! [conn-atom]
(reset! conn-atom (.start (cp/create connection-spec))))
(defn stop! [conn-atom]
(.stop @conn-atom))
| 37047 | (ns utility-belt.sql.connection
(:require
[utility-belt.sql.component.connection-pool :as cp]))
(def connection-spec
{:pool-name "test"
:adapter "postgresql"
:username (or (System/getenv "PG_USER") "test")
:password (or (System/getenv "PG_PASSWORD") "<PASSWORD>")
:server-name (or (System/getenv "PG_HOST") "127.0.0.1")
:port-number (Integer/parseInt (or (System/getenv "PG_PORT") "5434"))
:maximum-pool-size 10
:database-name (or (System/getenv "PG_NAME") "test")})
(defn start! [conn-atom]
(reset! conn-atom (.start (cp/create connection-spec))))
(defn stop! [conn-atom]
(.stop @conn-atom))
| true | (ns utility-belt.sql.connection
(:require
[utility-belt.sql.component.connection-pool :as cp]))
(def connection-spec
{:pool-name "test"
:adapter "postgresql"
:username (or (System/getenv "PG_USER") "test")
:password (or (System/getenv "PG_PASSWORD") "PI:PASSWORD:<PASSWORD>END_PI")
:server-name (or (System/getenv "PG_HOST") "127.0.0.1")
:port-number (Integer/parseInt (or (System/getenv "PG_PORT") "5434"))
:maximum-pool-size 10
:database-name (or (System/getenv "PG_NAME") "test")})
(defn start! [conn-atom]
(reset! conn-atom (.start (cp/create connection-spec))))
(defn stop! [conn-atom]
(.stop @conn-atom))
|
[
{
"context": " screenname\n :pass pass\n :pass-confirm pass-confirm",
"end": 2498,
"score": 0.9969311952590942,
"start": 2494,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "belongs-to\n :pass pass\n :pass-confirm pass-conf",
"end": 3230,
"score": 0.9956108927726746,
"start": 3226,
"tag": "PASSWORD",
"value": "pass"
}
] | src/clj/memory_hole/routes/services.clj | paulrd/memory-hole | 0 | (ns memory-hole.routes.services
(:require [ring.util.http-response :refer :all]
[compojure.api.sweet :refer :all]
[compojure.api.upload :refer [TempFileUpload wrap-multipart-params]]
[schema.core :as s]
[compojure.api.meta :refer [restructure-param]]
[memory-hole.routes.services.attachments :as attachments]
[memory-hole.routes.services.auth :as auth]
[memory-hole.routes.services.groups :as groups]
[memory-hole.routes.services.issues :as issues]
[memory-hole.config :refer [env]]
[buddy.auth.accessrules :refer [restrict]]
[buddy.auth :refer [authenticated?]]))
(defn admin?
[request]
(:admin (:identity request)))
(defn access-error [_ _]
(unauthorized {:error "unauthorized"}))
(defn wrap-restricted [handler rule]
(restrict handler {:handler rule
:on-error access-error}))
(defmethod restructure-param :auth-rules
[_ rule acc]
(update-in acc [:middleware] conj [wrap-restricted rule]))
(defmethod restructure-param :current-user
[_ binding acc]
(update-in acc [:letks] into [binding `(:identity ~'+compojure-api-request+)]))
(defapi service-routes
{:swagger {:ui "/swagger-ui"
:spec "/swagger.json"
:data {:info {:version "1.0.0"
:title "Sample API"
:description "Sample Services"}}}}
(POST "/api/login" req
:return auth/LoginResponse
:body-params [userid :- s/Str
pass :- s/Str]
:summary "user login handler"
(auth/login userid pass req))
(context "/admin" []
:auth-rules admin?
:tags ["admin"]
;;users
(GET "/users/:screenname" []
:path-params [screenname :- s/Str]
:return auth/SearchResponse
:summary "returns users with matching screennames"
(auth/find-users screenname))
(GET "/users/group/:group-name" []
:path-params [group-name :- s/Str]
:return auth/SearchResponse
:summary "returns users that are part of a group"
(auth/find-users-by-group group-name))
(POST "/user" []
:body-params [screenname :- s/Str
pass :- s/Str
pass-confirm :- s/Str
admin :- s/Bool
belongs-to :- [s/Str]
is-active :- s/Bool]
(auth/register! {:screenname screenname
:pass pass
:pass-confirm pass-confirm
:admin admin
:belongs-to belongs-to
:is-active is-active}))
(PUT "/user" []
:body-params [user-id :- s/Int
screenname :- s/Str
pass :- (s/maybe s/Str)
pass-confirm :- (s/maybe s/Str)
admin :- s/Bool
belongs-to :- [s/Str]
is-active :- s/Bool]
:return auth/LoginResponse
(auth/update-user! {:user-id user-id
:screenname screenname
:belongs-to belongs-to
:pass pass
:pass-confirm pass-confirm
:admin admin
:is-active is-active}))
;;groups
(POST "/group" []
:body [group groups/Group]
:return groups/GroupResult
:summary "add a new group"
(if (contains? env :ldap)
(groups/add-group! (select-keys group [:group-id :group-name]))
(groups/add-group! (select-keys group [:group-name])))))
(context "/api" []
:auth-rules authenticated?
:tags ["private"]
(POST "/logout" []
:return auth/LogoutResponse
:summary "remove the user from the session"
(auth/logout))
;;groups
(GET "/groups" []
:return groups/GroupsResult
:summary "list all groups current user belongs to (or all groups if admin)"
:current-user user
(groups/groups-by-user {:user-id (:user-id user)}))
;;tags
(GET "/tags" []
:return issues/TagsResult
:summary "list available tags"
:current-user user
(issues/tags {:user-id (:user-id user)}))
;;issues
(GET "/issues" []
:return issues/IssueSummaryResults
:summary "list all issues"
:current-user user
(issues/all-issues {:user-id (:user-id user)}))
(GET "/recent-issues" []
:return issues/IssueSummaryResults
:summary "list 10 most recent issues"
:current-user user
(issues/recent-issues {:user-id (:user-id user)
:limit 10}))
(GET "/issues-by-views/:offset/:limit" []
:path-params [offset :- s/Int limit :- s/Int]
:return issues/IssueSummaryResults
:summary "list issues by views using the given offset and limit"
:current-user user
(issues/issues-by-views {:user-id (:user-id user) :offset offset :limit limit}))
(GET "/issues-by-tag/:tag" []
:path-params [tag :- s/Str]
:return issues/IssueSummaryResults
:summary "list issues by the given tag"
:current-user user
(issues/issues-by-tag {:tag tag
:user-id (:user-id user)}))
(GET "/issues-by-group/:group" []
:path-params [group :- s/Str]
:return issues/IssueSummaryResults
:current-user user
:summary "list issues by the given group name"
(issues/issues-by-group {:group-name group
:user-id (:user-id user)}))
(DELETE "/issue/:id" []
:path-params [id :- s/Int]
:return s/Int
:current-user user
:summary "delete the issue with the given id"
(issues/delete-issue! {:support-issue-id id
:user-id (:user-id user)}))
(POST "/search-issues" []
:body-params [query :- s/Str
limit :- s/Int
offset :- s/Int]
:return issues/IssueSummaryResults
:summary "search for issues matching the query"
:current-user user
(issues/search-issues {:query query
:limit limit
:offset offset
:user-id (:user-id user)}))
(GET "/issue/:id" []
:path-params [id :- s/Int]
:return issues/IssueResult
:summary "returns the issue with the given id"
:current-user user
(issues/issue {:support-issue-id id
:user-id (:user-id user)}))
(POST "/issue" []
:current-user user
:body-params [title :- s/Str
summary :- s/Str
detail :- s/Str
group-id :- s/Str
tags :- [s/Str]]
:return s/Int
:summary "adds a new issue"
(issues/add-issue!
{:title title
:summary summary
:detail detail
:tags tags
:group-id group-id
:user-id (:user-id user)}))
(PUT "/issue" []
:current-user user
:body-params [support-issue-id :- s/Int
title :- s/Str
summary :- s/Str
detail :- s/Str
group-id :- s/Str
tags :- [s/Str]]
:return s/Int
:summary "update an existing issue"
(issues/update-issue!
{:support-issue-id support-issue-id
:title title
:summary summary
:detail detail
:tags tags
:group-id group-id
:user-id (:user-id user)}))
;;attachments
(POST "/attach-file" []
:multipart-params [support-issue-id :- s/Int
file :- TempFileUpload]
:middleware [wrap-multipart-params]
:current-user user
:summary "handles file upload"
:return attachments/AttachmentResult
(attachments/attach-file-to-issue! {:support-issue-id support-issue-id
:user-id (:user-id user)} file))
(GET "/file/:support-issue-id/:name" []
:summary "load a file from the database matching the support issue id and the filename"
:path-params [support-issue-id :- s/Int
name :- s/Str]
:current-user user
(attachments/load-file-data {:user-id (:user-id user)
:support-issue-id support-issue-id
:name name}))
(DELETE "/file/:support-issue-id/:name" []
:summary "delete a file from the database"
:path-params [support-issue-id :- s/Int
name :- s/Str]
:current-user user
:return attachments/AttachmentResult
(attachments/remove-file-from-issue! {:user-id (:user-id user)
:support-issue-id support-issue-id
:name name}))))
| 57847 | (ns memory-hole.routes.services
(:require [ring.util.http-response :refer :all]
[compojure.api.sweet :refer :all]
[compojure.api.upload :refer [TempFileUpload wrap-multipart-params]]
[schema.core :as s]
[compojure.api.meta :refer [restructure-param]]
[memory-hole.routes.services.attachments :as attachments]
[memory-hole.routes.services.auth :as auth]
[memory-hole.routes.services.groups :as groups]
[memory-hole.routes.services.issues :as issues]
[memory-hole.config :refer [env]]
[buddy.auth.accessrules :refer [restrict]]
[buddy.auth :refer [authenticated?]]))
(defn admin?
[request]
(:admin (:identity request)))
(defn access-error [_ _]
(unauthorized {:error "unauthorized"}))
(defn wrap-restricted [handler rule]
(restrict handler {:handler rule
:on-error access-error}))
(defmethod restructure-param :auth-rules
[_ rule acc]
(update-in acc [:middleware] conj [wrap-restricted rule]))
(defmethod restructure-param :current-user
[_ binding acc]
(update-in acc [:letks] into [binding `(:identity ~'+compojure-api-request+)]))
(defapi service-routes
{:swagger {:ui "/swagger-ui"
:spec "/swagger.json"
:data {:info {:version "1.0.0"
:title "Sample API"
:description "Sample Services"}}}}
(POST "/api/login" req
:return auth/LoginResponse
:body-params [userid :- s/Str
pass :- s/Str]
:summary "user login handler"
(auth/login userid pass req))
(context "/admin" []
:auth-rules admin?
:tags ["admin"]
;;users
(GET "/users/:screenname" []
:path-params [screenname :- s/Str]
:return auth/SearchResponse
:summary "returns users with matching screennames"
(auth/find-users screenname))
(GET "/users/group/:group-name" []
:path-params [group-name :- s/Str]
:return auth/SearchResponse
:summary "returns users that are part of a group"
(auth/find-users-by-group group-name))
(POST "/user" []
:body-params [screenname :- s/Str
pass :- s/Str
pass-confirm :- s/Str
admin :- s/Bool
belongs-to :- [s/Str]
is-active :- s/Bool]
(auth/register! {:screenname screenname
:pass <PASSWORD>
:pass-confirm pass-confirm
:admin admin
:belongs-to belongs-to
:is-active is-active}))
(PUT "/user" []
:body-params [user-id :- s/Int
screenname :- s/Str
pass :- (s/maybe s/Str)
pass-confirm :- (s/maybe s/Str)
admin :- s/Bool
belongs-to :- [s/Str]
is-active :- s/Bool]
:return auth/LoginResponse
(auth/update-user! {:user-id user-id
:screenname screenname
:belongs-to belongs-to
:pass <PASSWORD>
:pass-confirm pass-confirm
:admin admin
:is-active is-active}))
;;groups
(POST "/group" []
:body [group groups/Group]
:return groups/GroupResult
:summary "add a new group"
(if (contains? env :ldap)
(groups/add-group! (select-keys group [:group-id :group-name]))
(groups/add-group! (select-keys group [:group-name])))))
(context "/api" []
:auth-rules authenticated?
:tags ["private"]
(POST "/logout" []
:return auth/LogoutResponse
:summary "remove the user from the session"
(auth/logout))
;;groups
(GET "/groups" []
:return groups/GroupsResult
:summary "list all groups current user belongs to (or all groups if admin)"
:current-user user
(groups/groups-by-user {:user-id (:user-id user)}))
;;tags
(GET "/tags" []
:return issues/TagsResult
:summary "list available tags"
:current-user user
(issues/tags {:user-id (:user-id user)}))
;;issues
(GET "/issues" []
:return issues/IssueSummaryResults
:summary "list all issues"
:current-user user
(issues/all-issues {:user-id (:user-id user)}))
(GET "/recent-issues" []
:return issues/IssueSummaryResults
:summary "list 10 most recent issues"
:current-user user
(issues/recent-issues {:user-id (:user-id user)
:limit 10}))
(GET "/issues-by-views/:offset/:limit" []
:path-params [offset :- s/Int limit :- s/Int]
:return issues/IssueSummaryResults
:summary "list issues by views using the given offset and limit"
:current-user user
(issues/issues-by-views {:user-id (:user-id user) :offset offset :limit limit}))
(GET "/issues-by-tag/:tag" []
:path-params [tag :- s/Str]
:return issues/IssueSummaryResults
:summary "list issues by the given tag"
:current-user user
(issues/issues-by-tag {:tag tag
:user-id (:user-id user)}))
(GET "/issues-by-group/:group" []
:path-params [group :- s/Str]
:return issues/IssueSummaryResults
:current-user user
:summary "list issues by the given group name"
(issues/issues-by-group {:group-name group
:user-id (:user-id user)}))
(DELETE "/issue/:id" []
:path-params [id :- s/Int]
:return s/Int
:current-user user
:summary "delete the issue with the given id"
(issues/delete-issue! {:support-issue-id id
:user-id (:user-id user)}))
(POST "/search-issues" []
:body-params [query :- s/Str
limit :- s/Int
offset :- s/Int]
:return issues/IssueSummaryResults
:summary "search for issues matching the query"
:current-user user
(issues/search-issues {:query query
:limit limit
:offset offset
:user-id (:user-id user)}))
(GET "/issue/:id" []
:path-params [id :- s/Int]
:return issues/IssueResult
:summary "returns the issue with the given id"
:current-user user
(issues/issue {:support-issue-id id
:user-id (:user-id user)}))
(POST "/issue" []
:current-user user
:body-params [title :- s/Str
summary :- s/Str
detail :- s/Str
group-id :- s/Str
tags :- [s/Str]]
:return s/Int
:summary "adds a new issue"
(issues/add-issue!
{:title title
:summary summary
:detail detail
:tags tags
:group-id group-id
:user-id (:user-id user)}))
(PUT "/issue" []
:current-user user
:body-params [support-issue-id :- s/Int
title :- s/Str
summary :- s/Str
detail :- s/Str
group-id :- s/Str
tags :- [s/Str]]
:return s/Int
:summary "update an existing issue"
(issues/update-issue!
{:support-issue-id support-issue-id
:title title
:summary summary
:detail detail
:tags tags
:group-id group-id
:user-id (:user-id user)}))
;;attachments
(POST "/attach-file" []
:multipart-params [support-issue-id :- s/Int
file :- TempFileUpload]
:middleware [wrap-multipart-params]
:current-user user
:summary "handles file upload"
:return attachments/AttachmentResult
(attachments/attach-file-to-issue! {:support-issue-id support-issue-id
:user-id (:user-id user)} file))
(GET "/file/:support-issue-id/:name" []
:summary "load a file from the database matching the support issue id and the filename"
:path-params [support-issue-id :- s/Int
name :- s/Str]
:current-user user
(attachments/load-file-data {:user-id (:user-id user)
:support-issue-id support-issue-id
:name name}))
(DELETE "/file/:support-issue-id/:name" []
:summary "delete a file from the database"
:path-params [support-issue-id :- s/Int
name :- s/Str]
:current-user user
:return attachments/AttachmentResult
(attachments/remove-file-from-issue! {:user-id (:user-id user)
:support-issue-id support-issue-id
:name name}))))
| true | (ns memory-hole.routes.services
(:require [ring.util.http-response :refer :all]
[compojure.api.sweet :refer :all]
[compojure.api.upload :refer [TempFileUpload wrap-multipart-params]]
[schema.core :as s]
[compojure.api.meta :refer [restructure-param]]
[memory-hole.routes.services.attachments :as attachments]
[memory-hole.routes.services.auth :as auth]
[memory-hole.routes.services.groups :as groups]
[memory-hole.routes.services.issues :as issues]
[memory-hole.config :refer [env]]
[buddy.auth.accessrules :refer [restrict]]
[buddy.auth :refer [authenticated?]]))
(defn admin?
[request]
(:admin (:identity request)))
(defn access-error [_ _]
(unauthorized {:error "unauthorized"}))
(defn wrap-restricted [handler rule]
(restrict handler {:handler rule
:on-error access-error}))
(defmethod restructure-param :auth-rules
[_ rule acc]
(update-in acc [:middleware] conj [wrap-restricted rule]))
(defmethod restructure-param :current-user
[_ binding acc]
(update-in acc [:letks] into [binding `(:identity ~'+compojure-api-request+)]))
(defapi service-routes
{:swagger {:ui "/swagger-ui"
:spec "/swagger.json"
:data {:info {:version "1.0.0"
:title "Sample API"
:description "Sample Services"}}}}
(POST "/api/login" req
:return auth/LoginResponse
:body-params [userid :- s/Str
pass :- s/Str]
:summary "user login handler"
(auth/login userid pass req))
(context "/admin" []
:auth-rules admin?
:tags ["admin"]
;;users
(GET "/users/:screenname" []
:path-params [screenname :- s/Str]
:return auth/SearchResponse
:summary "returns users with matching screennames"
(auth/find-users screenname))
(GET "/users/group/:group-name" []
:path-params [group-name :- s/Str]
:return auth/SearchResponse
:summary "returns users that are part of a group"
(auth/find-users-by-group group-name))
(POST "/user" []
:body-params [screenname :- s/Str
pass :- s/Str
pass-confirm :- s/Str
admin :- s/Bool
belongs-to :- [s/Str]
is-active :- s/Bool]
(auth/register! {:screenname screenname
:pass PI:PASSWORD:<PASSWORD>END_PI
:pass-confirm pass-confirm
:admin admin
:belongs-to belongs-to
:is-active is-active}))
(PUT "/user" []
:body-params [user-id :- s/Int
screenname :- s/Str
pass :- (s/maybe s/Str)
pass-confirm :- (s/maybe s/Str)
admin :- s/Bool
belongs-to :- [s/Str]
is-active :- s/Bool]
:return auth/LoginResponse
(auth/update-user! {:user-id user-id
:screenname screenname
:belongs-to belongs-to
:pass PI:PASSWORD:<PASSWORD>END_PI
:pass-confirm pass-confirm
:admin admin
:is-active is-active}))
;;groups
(POST "/group" []
:body [group groups/Group]
:return groups/GroupResult
:summary "add a new group"
(if (contains? env :ldap)
(groups/add-group! (select-keys group [:group-id :group-name]))
(groups/add-group! (select-keys group [:group-name])))))
(context "/api" []
:auth-rules authenticated?
:tags ["private"]
(POST "/logout" []
:return auth/LogoutResponse
:summary "remove the user from the session"
(auth/logout))
;;groups
(GET "/groups" []
:return groups/GroupsResult
:summary "list all groups current user belongs to (or all groups if admin)"
:current-user user
(groups/groups-by-user {:user-id (:user-id user)}))
;;tags
(GET "/tags" []
:return issues/TagsResult
:summary "list available tags"
:current-user user
(issues/tags {:user-id (:user-id user)}))
;;issues
(GET "/issues" []
:return issues/IssueSummaryResults
:summary "list all issues"
:current-user user
(issues/all-issues {:user-id (:user-id user)}))
(GET "/recent-issues" []
:return issues/IssueSummaryResults
:summary "list 10 most recent issues"
:current-user user
(issues/recent-issues {:user-id (:user-id user)
:limit 10}))
(GET "/issues-by-views/:offset/:limit" []
:path-params [offset :- s/Int limit :- s/Int]
:return issues/IssueSummaryResults
:summary "list issues by views using the given offset and limit"
:current-user user
(issues/issues-by-views {:user-id (:user-id user) :offset offset :limit limit}))
(GET "/issues-by-tag/:tag" []
:path-params [tag :- s/Str]
:return issues/IssueSummaryResults
:summary "list issues by the given tag"
:current-user user
(issues/issues-by-tag {:tag tag
:user-id (:user-id user)}))
(GET "/issues-by-group/:group" []
:path-params [group :- s/Str]
:return issues/IssueSummaryResults
:current-user user
:summary "list issues by the given group name"
(issues/issues-by-group {:group-name group
:user-id (:user-id user)}))
(DELETE "/issue/:id" []
:path-params [id :- s/Int]
:return s/Int
:current-user user
:summary "delete the issue with the given id"
(issues/delete-issue! {:support-issue-id id
:user-id (:user-id user)}))
(POST "/search-issues" []
:body-params [query :- s/Str
limit :- s/Int
offset :- s/Int]
:return issues/IssueSummaryResults
:summary "search for issues matching the query"
:current-user user
(issues/search-issues {:query query
:limit limit
:offset offset
:user-id (:user-id user)}))
(GET "/issue/:id" []
:path-params [id :- s/Int]
:return issues/IssueResult
:summary "returns the issue with the given id"
:current-user user
(issues/issue {:support-issue-id id
:user-id (:user-id user)}))
(POST "/issue" []
:current-user user
:body-params [title :- s/Str
summary :- s/Str
detail :- s/Str
group-id :- s/Str
tags :- [s/Str]]
:return s/Int
:summary "adds a new issue"
(issues/add-issue!
{:title title
:summary summary
:detail detail
:tags tags
:group-id group-id
:user-id (:user-id user)}))
(PUT "/issue" []
:current-user user
:body-params [support-issue-id :- s/Int
title :- s/Str
summary :- s/Str
detail :- s/Str
group-id :- s/Str
tags :- [s/Str]]
:return s/Int
:summary "update an existing issue"
(issues/update-issue!
{:support-issue-id support-issue-id
:title title
:summary summary
:detail detail
:tags tags
:group-id group-id
:user-id (:user-id user)}))
;;attachments
(POST "/attach-file" []
:multipart-params [support-issue-id :- s/Int
file :- TempFileUpload]
:middleware [wrap-multipart-params]
:current-user user
:summary "handles file upload"
:return attachments/AttachmentResult
(attachments/attach-file-to-issue! {:support-issue-id support-issue-id
:user-id (:user-id user)} file))
(GET "/file/:support-issue-id/:name" []
:summary "load a file from the database matching the support issue id and the filename"
:path-params [support-issue-id :- s/Int
name :- s/Str]
:current-user user
(attachments/load-file-data {:user-id (:user-id user)
:support-issue-id support-issue-id
:name name}))
(DELETE "/file/:support-issue-id/:name" []
:summary "delete a file from the database"
:path-params [support-issue-id :- s/Int
name :- s/Str]
:current-user user
:return attachments/AttachmentResult
(attachments/remove-file-from-issue! {:user-id (:user-id user)
:support-issue-id support-issue-id
:name name}))))
|
[
{
"context": "://localhost/todo?user=db_user_name_here&password=db_user_password_here\"}\n :plugins\n [[lein-ring \"0.8.10\"]\n [lein-env",
"end": 341,
"score": 0.9969477653503418,
"start": 320,
"tag": "PASSWORD",
"value": "db_user_password_here"
}
] | project.clj | vyorkin-play/clojure-todo3 | 0 | (defproject
todo
"0.1.0-SNAPSHOT"
:description
"FIXME: write description"
:ring
{:handler todo.handler/app,
:init todo.handler/init,
:destroy todo.handler/destroy}
:ragtime
{:migrations ragtime.sql.files/migrations,
:database
"jdbc:postgresql://localhost/todo?user=db_user_name_here&password=db_user_password_here"}
:plugins
[[lein-ring "0.8.10"]
[lein-environ "0.5.0"]
[ragtime/ragtime.lein "0.3.6"]]
:url
"http://example.com/FIXME"
:profiles
{:uberjar {:aot :all},
:production
{:ring
{:open-browser? false, :stacktraces? false, :auto-reload? false}},
:dev
{:dependencies
[[ring-mock "0.1.5"]
[ring/ring-devel "1.3.0"]
[pjstadig/humane-test-output "0.6.0"]],
:injections
[(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)],
:env {:dev true}}}
:dependencies
[[log4j
"1.2.17"
:exclusions
[javax.mail/mail
javax.jms/jms
com.sun.jdmk/jmxtools
com.sun.jmx/jmxri]]
[selmer "0.6.8"]
[com.taoensso/timbre "3.2.1"]
[noir-exception "0.2.2"]
[markdown-clj "0.9.44"]
[environ "0.5.0"]
[korma "0.3.2"]
[org.clojure/clojure "1.6.0"]
[ring-server "0.3.1"]
[postgresql/postgresql "9.1-901-1.jdbc4"]
[com.taoensso/tower "2.0.2"]
[ragtime "0.3.6"]
[lib-noir "0.8.4"]]
:repl-options
{:init-ns todo.repl}
:min-lein-version "2.0.0")
| 105659 | (defproject
todo
"0.1.0-SNAPSHOT"
:description
"FIXME: write description"
:ring
{:handler todo.handler/app,
:init todo.handler/init,
:destroy todo.handler/destroy}
:ragtime
{:migrations ragtime.sql.files/migrations,
:database
"jdbc:postgresql://localhost/todo?user=db_user_name_here&password=<PASSWORD>"}
:plugins
[[lein-ring "0.8.10"]
[lein-environ "0.5.0"]
[ragtime/ragtime.lein "0.3.6"]]
:url
"http://example.com/FIXME"
:profiles
{:uberjar {:aot :all},
:production
{:ring
{:open-browser? false, :stacktraces? false, :auto-reload? false}},
:dev
{:dependencies
[[ring-mock "0.1.5"]
[ring/ring-devel "1.3.0"]
[pjstadig/humane-test-output "0.6.0"]],
:injections
[(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)],
:env {:dev true}}}
:dependencies
[[log4j
"1.2.17"
:exclusions
[javax.mail/mail
javax.jms/jms
com.sun.jdmk/jmxtools
com.sun.jmx/jmxri]]
[selmer "0.6.8"]
[com.taoensso/timbre "3.2.1"]
[noir-exception "0.2.2"]
[markdown-clj "0.9.44"]
[environ "0.5.0"]
[korma "0.3.2"]
[org.clojure/clojure "1.6.0"]
[ring-server "0.3.1"]
[postgresql/postgresql "9.1-901-1.jdbc4"]
[com.taoensso/tower "2.0.2"]
[ragtime "0.3.6"]
[lib-noir "0.8.4"]]
:repl-options
{:init-ns todo.repl}
:min-lein-version "2.0.0")
| true | (defproject
todo
"0.1.0-SNAPSHOT"
:description
"FIXME: write description"
:ring
{:handler todo.handler/app,
:init todo.handler/init,
:destroy todo.handler/destroy}
:ragtime
{:migrations ragtime.sql.files/migrations,
:database
"jdbc:postgresql://localhost/todo?user=db_user_name_here&password=PI:PASSWORD:<PASSWORD>END_PI"}
:plugins
[[lein-ring "0.8.10"]
[lein-environ "0.5.0"]
[ragtime/ragtime.lein "0.3.6"]]
:url
"http://example.com/FIXME"
:profiles
{:uberjar {:aot :all},
:production
{:ring
{:open-browser? false, :stacktraces? false, :auto-reload? false}},
:dev
{:dependencies
[[ring-mock "0.1.5"]
[ring/ring-devel "1.3.0"]
[pjstadig/humane-test-output "0.6.0"]],
:injections
[(require 'pjstadig.humane-test-output)
(pjstadig.humane-test-output/activate!)],
:env {:dev true}}}
:dependencies
[[log4j
"1.2.17"
:exclusions
[javax.mail/mail
javax.jms/jms
com.sun.jdmk/jmxtools
com.sun.jmx/jmxri]]
[selmer "0.6.8"]
[com.taoensso/timbre "3.2.1"]
[noir-exception "0.2.2"]
[markdown-clj "0.9.44"]
[environ "0.5.0"]
[korma "0.3.2"]
[org.clojure/clojure "1.6.0"]
[ring-server "0.3.1"]
[postgresql/postgresql "9.1-901-1.jdbc4"]
[com.taoensso/tower "2.0.2"]
[ragtime "0.3.6"]
[lib-noir "0.8.4"]]
:repl-options
{:init-ns todo.repl}
:min-lein-version "2.0.0")
|
[
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brow",
"end": 25,
"score": 0.9998528361320496,
"start": 15,
"tag": "NAME",
"value": "Adam Jacob"
},
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>",
"end": 44,
"score": 0.9999330639839172,
"start": 28,
"tag": "EMAIL",
"value": "adam@opscode.com"
},
{
"context": "thor:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2",
"end": 76,
"score": 0.9997920989990234,
"start": 59,
"tag": "NAME",
"value": "Christopher Brown"
},
{
"context": "dam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2010 Opscode, Inc.",
"end": 93,
"score": 0.999934196472168,
"start": 79,
"tag": "EMAIL",
"value": "cb@opscode.com"
},
{
"context": "der the License.\n;;\n\n(project \"chef-server-full\" \"0.10.8\" \"2\"\n :build-order [\n ",
"end": 784,
"score": 0.9995966553688049,
"start": 778,
"tag": "IP_ADDRESS",
"value": "0.10.8"
}
] | config/projects/chef-server-full.clj | racker/omnibus | 2 | ;;
;; Author:: Adam Jacob (<adam@opscode.com>)
;; Author:: Christopher Brown (<cb@opscode.com>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(project "chef-server-full" "0.10.8" "2"
:build-order [
"prep" "autoconf" "zlib" "libiconv" "db" "gdbm"
"ncurses" "openssl" "libxml2" "libxslt" "ruby" "rsync"
"gecode" "erlang" "icu" "spidermonkey" "curl" "couchdb"
"rabbitmq" "runit" "jre" "pcre" "nginx" "chef" "chef-server" "chef-server-cookbooks"])
| 74555 | ;;
;; Author:: <NAME> (<<EMAIL>>)
;; Author:: <NAME> (<<EMAIL>>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(project "chef-server-full" "0.10.8" "2"
:build-order [
"prep" "autoconf" "zlib" "libiconv" "db" "gdbm"
"ncurses" "openssl" "libxml2" "libxslt" "ruby" "rsync"
"gecode" "erlang" "icu" "spidermonkey" "curl" "couchdb"
"rabbitmq" "runit" "jre" "pcre" "nginx" "chef" "chef-server" "chef-server-cookbooks"])
| true | ;;
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(project "chef-server-full" "0.10.8" "2"
:build-order [
"prep" "autoconf" "zlib" "libiconv" "db" "gdbm"
"ncurses" "openssl" "libxml2" "libxslt" "ruby" "rsync"
"gecode" "erlang" "icu" "spidermonkey" "curl" "couchdb"
"rabbitmq" "runit" "jre" "pcre" "nginx" "chef" "chef-server" "chef-server-cookbooks"])
|
[
{
"context": "\"Columbia\"\n :lm-name \"Eagle\"\n :orbits 30\n ",
"end": 1335,
"score": 0.7960905432701111,
"start": 1330,
"tag": "NAME",
"value": "Eagle"
}
] | clojure/clojure-applied/cljapplied/src/ch1/apollo.clj | mdssjc/mds-lisp | 0 | (ns ch1.apollo)
(defn make-mission
[name system launched manned? opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} opts]
,,, ))
(def apollo-4
(make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
{:orbits 3}))
(def mission-defaults {:orbits 0, :evas 0})
(defn make-mission
[name system launched manned? opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} (merge mission-defaults opts)]
,,, ))
(defn make-mission
[name system launched manned? & opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} opts]
,,, ))
(def apollo-4 (make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
:orbits 3))
(def apollo-11 (make-mission "Apollo 11"
"Saturn V"
#inst "1969-07-16T13:32:00-00:00" true
:cm-name "Columbia"
:lm-name "Eagle"
:orbits 30
:evas 1))
(defn make-mission
[name system launched manned? & opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]
:or {orbits 0, evas 0}} opts] ;; default to 0
,,, ))
(def apollo-4 (make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
:orbits 3))
(defn euclidean-norm [ecc-vector] ,,,)
(defrecord Planet
[name moons volume mass aphelion perihelion orbital-eccentricity])
(defn make-planet
"Make a planet from field values and an eccentricity vector"
[name moons volume mass aphelion perhelion ecc-vector]
(->Planet
name moons volume mass aphelion perhelion
(euclidean-norm ecc-vector)))
| 53266 | (ns ch1.apollo)
(defn make-mission
[name system launched manned? opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} opts]
,,, ))
(def apollo-4
(make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
{:orbits 3}))
(def mission-defaults {:orbits 0, :evas 0})
(defn make-mission
[name system launched manned? opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} (merge mission-defaults opts)]
,,, ))
(defn make-mission
[name system launched manned? & opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} opts]
,,, ))
(def apollo-4 (make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
:orbits 3))
(def apollo-11 (make-mission "Apollo 11"
"Saturn V"
#inst "1969-07-16T13:32:00-00:00" true
:cm-name "Columbia"
:lm-name "<NAME>"
:orbits 30
:evas 1))
(defn make-mission
[name system launched manned? & opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]
:or {orbits 0, evas 0}} opts] ;; default to 0
,,, ))
(def apollo-4 (make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
:orbits 3))
(defn euclidean-norm [ecc-vector] ,,,)
(defrecord Planet
[name moons volume mass aphelion perihelion orbital-eccentricity])
(defn make-planet
"Make a planet from field values and an eccentricity vector"
[name moons volume mass aphelion perhelion ecc-vector]
(->Planet
name moons volume mass aphelion perhelion
(euclidean-norm ecc-vector)))
| true | (ns ch1.apollo)
(defn make-mission
[name system launched manned? opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} opts]
,,, ))
(def apollo-4
(make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
{:orbits 3}))
(def mission-defaults {:orbits 0, :evas 0})
(defn make-mission
[name system launched manned? opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} (merge mission-defaults opts)]
,,, ))
(defn make-mission
[name system launched manned? & opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]} opts]
,,, ))
(def apollo-4 (make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
:orbits 3))
(def apollo-11 (make-mission "Apollo 11"
"Saturn V"
#inst "1969-07-16T13:32:00-00:00" true
:cm-name "Columbia"
:lm-name "PI:NAME:<NAME>END_PI"
:orbits 30
:evas 1))
(defn make-mission
[name system launched manned? & opts]
(let [{:keys [cm-name ;; command module
lm-name ;; lunar module
orbits
evas]
:or {orbits 0, evas 0}} opts] ;; default to 0
,,, ))
(def apollo-4 (make-mission "Apollo 4"
"Saturn V"
#inst "1967-11-09T12:00:01-00:00"
false
:orbits 3))
(defn euclidean-norm [ecc-vector] ,,,)
(defrecord Planet
[name moons volume mass aphelion perihelion orbital-eccentricity])
(defn make-planet
"Make a planet from field values and an eccentricity vector"
[name moons volume mass aphelion perhelion ecc-vector]
(->Planet
name moons volume mass aphelion perhelion
(euclidean-norm ecc-vector)))
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.nettio.resp\n\n (",
"end": 597,
"score": 0.9998552203178406,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
}
] | src/main/clojure/czlab/nettio/resp.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.nettio.resp
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.niou.mime :as mm]
[czlab.niou.core :as cc]
[czlab.niou.webss :as ss]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.basal.core :as c]
[czlab.basal.dates :as d]
[czlab.nettio.core :as n]
[czlab.nettio.http :as h1]
[czlab.nettio.ranges :as nr])
(:import [io.netty.channel ChannelFuture Channel ChannelHandlerContext]
[io.netty.buffer Unpooled ByteBuf ByteBufAllocator]
[java.io IOException File InputStream]
[io.netty.util ReferenceCountUtil]
[clojure.lang APersistentVector]
[java.nio.charset Charset]
[java.net HttpCookie URL]
[java.util Date]
[czlab.basal XData]
[czlab.niou Headers DateUtil]
[czlab.niou.core WsockMsg Http1xMsg HttpResultMsg]
[czlab.nettio.ranges HttpRangesObj]
[io.netty.handler.codec.http.cookie
Cookie
ServerCookieEncoder]
[io.netty.handler.codec.http
HttpResponseStatus
DefaultHttpHeaders
FullHttpResponse
HttpChunkedInput
HttpVersion
HttpUtil
HttpMessage
HttpHeaderValues
HttpHeaderNames
HttpResponse
HttpHeaders]
[io.netty.handler.stream
ChunkedNioFile
ChunkedInput
ChunkedFile
ChunkedStream]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- conds-hds
[[:if-unmod-since (str (n/h1hdr* IF_UNMODIFIED_SINCE))]
[:if-mod-since (str (n/h1hdr* IF_MODIFIED_SINCE))]
[:if-none-match (str (n/h1hdr* IF_NONE_MATCH))]
[:if-match (str (n/h1hdr* IF_MATCH))]
[:if-range (str (n/h1hdr* IF_RANGE))]
[:range (str (n/h1hdr* RANGE))]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- resp-hds
[[:last-mod (str (n/h1hdr* LAST_MODIFIED))]
[:etag (str (n/h1hdr* ETAG))]
[:ctype (str (n/h1hdr* CONTENT_TYPE))]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare replyer<> result<>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- result<>
[theReq status]
{:pre [(or (nil? status)
(number? status))]}
(c/object<> HttpResultMsg
:headers (Headers.)
:request theReq
:cookies {}
:protocol (.text HttpVersion/HTTP_1_1)
:status (or status (n/scode* OK))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgCreator
Http1xMsg
(http-result
([theReq] (cc/http-result theReq 200))
([theReq status] (result<> theReq status))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgReplyer
HttpResultMsg
(reply-result
([theRes] (cc/reply-result theRes nil))
([theRes arg] (replyer<> theRes arg))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgReplyer
WsockMsg
(reply-result
([theRes] (cc/reply-result theRes nil))
([theRes _] (let [ch (:socket theRes)]
(some-> ch (n/write-msg theRes))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgModifier
HttpResultMsg
(res-cookie-add [res cookie]
(update-in res
[:cookies]
assoc (.getName ^HttpCookie cookie) cookie))
(res-status-set [res s]
(assoc res :status s))
(res-body-set [res body]
(assoc res :body body))
(res-header-add [res name value]
(c/do-with [res]
(.add (n/ghdrs res) ^String name value)))
(res-header-set [res name value]
(c/do-with [res]
(.set (n/ghdrs res) ^String name value)))
(res-header-del [res name]
(c/do-with [res]
(.remove (n/ghdrs res) ^String name))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn etag-file
"ETag based on a file object."
^String [in]
(if-some [f (io/file in)]
(format "\"%s-%s\"" (.lastModified f) (.hashCode f))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defmacro- code-ok?
[c] `(let [c# ~c] (and (>= c# 200)(< c# 300))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defmacro- cond-err-code
[m] `(let [m# ~m]
(if (or (= m# :get) (= m# :head))
(n/scode* ~'NOT_MODIFIED)
(n/scode* ~'PRECONDITION_FAILED))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-none-match?
"Condition fails if the reply eTag
matches, or if filter is a wildcard."
[method eTag code body conds]
(let [{:keys [value has?]} (:if-none-match conds)
value (c/strim value)
ec (cond-err-code method)]
[(cond (or (not has?) (c/nichts? value)) code
(c/eq-any? value ["*" "\"*\""]) (if (c/hgl? eTag) ec code)
(c/eq-any? eTag (map #(c/strim %)
(c/split value ","))) ec :else code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-match?
"Condition fails if reply eTag doesn't
match, or if filter is wildcard and no eTag."
[method eTag code body conds]
(let [{:keys [value has?]} (:if-match conds)
value (c/strim value)
ec (cond-err-code method)]
[(cond (or (not has?) (c/nichts? value)) code
(c/eq-any? value ["*" "\"*\""]) (if (c/hgl? eTag) code ec)
(not (c/eq-any? eTag
(map #(c/strim %)
(c/split value ",")))) ec :else code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-unmod-since?
"Condition fails if the last-modified
timestamp is greater than the given date."
[method lastMod code body conds]
(let [{:keys [value has?]} (:if-unmod-since conds)
value (c/strim value)
rc (cond-err-code method)
t (DateUtil/parseHttpDate value -1)]
[(if (and (c/spos? t)
(c/spos? lastMod))
(if (< lastMod t) code rc) code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-mod-since?
"Condition fails if the last-modified
time-stamp is less than the given date."
[method lastMod code body conds]
(let [{:keys [value has?]} (:if-mod-since conds)
value (c/strim value)
rc (cond-err-code method)
t (DateUtil/parseHttpDate value -1)]
[(if (and (c/spos? t)
(c/spos? lastMod))
(if (> lastMod t) code rc) code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-range?
"Sort out the range if any, then apply
the if-range condition."
[eTag lastMod code cType body conds]
(let [ec (n/scode* REQUESTED_RANGE_NOT_SATISFIABLE)
pc (n/scode* PARTIAL_CONTENT)
^String hd (get-in conds [:if-range :value])
{:keys [value has?]} (:range conds)
value (c/strim value)
g (nr/http-ranges<> (if has? value nil) cType body)]
(cond (or (not has?)
(c/nichts? value)) [code body]
(nil? g) [ec nil]
(c/nichts? hd) [pc g]
(and (cs/ends-with? hd "GMT")
(cs/index-of hd \,)
(cs/index-of hd \:))
(let [t (DateUtil/parseHttpDate hd -1)]
(if (and (c/spos? lastMod)
(c/spos? t)
(> lastMod t)) [code body] [pc g]))
(not= hd eTag) [code body] :else [pc g])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- encode-cookies
[cookies]
(c/preduce<vec>
#(let [^Cookie c
(condp instance? %2
Cookie %2
HttpCookie (n/netty-cookie<> %2)
(u/throw-BadArg "Bad cookie"))]
(conj! %1 (.encode ServerCookieEncoder/STRICT c))) cookies))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- replyer<>
[res sessionObj]
(c/debug "replyer called with res = %s.\nsessionObj = %s." res sessionObj)
(letfn
[(zmap-headers [msg headers]
(zipmap (map #(let [[k v] %1] k) headers)
(map #(let [[k v] %1]
{:has? (cc/msg-header? msg v)
:value (cc/msg-header msg v)}) headers)))
(converge [body cs]
(cond (bytes? body)
body
(string? body)
(i/x->bytes body cs)
(c/is? XData body)
(converge (.content ^XData body) cs) :else body))]
(let [{:keys [body status request charset] :as res}
(ss/downstream res sessionObj)
{:keys [headers last-mod etag cookies] :as cfg} res
{:keys [keep-alive?
^Channel socket request-method]} request
;^Channel ch (:socket req)
;method (:method req)
cs (u/charset?? charset)
;code (:status res)
body0 (converge body cs)
_ (c/debug "resp: body0===> %s." body0)
conds (zmap-headers request conds-hds)
rhds (zmap-headers res resp-hds)
cType (get-in rhds [:ctype :value])
[status body]
(if (code-ok? status)
(if-range? etag last-mod status cType body0 conds)
[status body0])
[status body]
(if (code-ok? status)
(if-match? request-method etag status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-none-match? request-method etag status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-mod-since? request-method last-mod status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-unmod-since? request-method last-mod status body conds)
[status body])
[status body]
(if (and (= :head request-method)
(code-ok? status))
[status nil] [status body])
rangeRef
(if-some
[ro (c/cast? HttpRangesObj body)] (c/finz ro))
[body clen]
(cond (c/is? InputStream body)
[(HttpChunkedInput.
(ChunkedStream. ^InputStream body)) -1]
rangeRef
[(HttpChunkedInput. ^ChunkedInput body) -1] ;(.length ^ChunkedInput body)]
(bytes? body)
[body (count body)]
(c/is? File body)
[(HttpChunkedInput. (ChunkedNioFile. ^File body)) -1];(.length ^File body)]
(nil? body)
[nil 0]
:else
(u/throw-IOE "Unsupported result content"))
_ (c/debug "body = %s." body)
[rsp body]
(cond (bytes? body)
[(n/http-reply<+> status body (.alloc socket)) nil]
(nil? body)
[(n/http-reply<+> status) nil]
(and (zero? clen)
(nil? body))
[(n/http-reply<+> status) nil]
:else
[(n/http-reply<> status) body])
hds (.set (.headers ^HttpMessage rsp)
(h1/std->headers headers))]
(cond (== status 416)
(nr/fmt-error hds body0)
rangeRef
(nr/fmt-success hds rangeRef))
(c/debug "response = %s." rsp)
(c/debug "body-len = %s." clen)
(if-not (zero? clen)
(->> (and body
(not (c/is? FullHttpResponse rsp)))
boolean
(HttpUtil/setTransferEncodingChunked rsp )))
(if-not (c/sneg? clen)
(HttpUtil/setContentLength rsp clen))
(if (c/sneg? clen)
(HttpUtil/setKeepAlive rsp false)
(HttpUtil/setKeepAlive rsp keep-alive?))
(if (or (nil? body)
(and (zero? clen)(nil? body)))
(.remove hds (n/h1hdr* CONTENT_TYPE)))
(doseq [s (encode-cookies (vals cookies))]
(c/debug "resp: setting cookie: %s." s)
(.add hds (n/h1hdr* SET_COOKIE) s))
(if (and (c/spos? last-mod)
(not (get-in rhds [:last-mod :has?])))
(.set hds
(n/h1hdr* LAST_MODIFIED)
(DateUtil/formatHttpDate ^long last-mod)))
(if (and (c/hgl? etag)
(not (get-in rhds [:etag :has?])))
(.set hds (n/h1hdr* ETAG) etag))
(let [c? (HttpUtil/isKeepAlive rsp)
cf (if (nil? body)
(do (c/debug "reply has no chunked body, write and flush %s." rsp)
(.writeAndFlush socket rsp))
(do (c/debug "reply has chunked body, write and flush %s." rsp)
(.write socket rsp)
(c/debug "reply body, write and flush body: %s." body)
(.writeAndFlush socket body)))]
(c/debug "resp replied, keep-alive? = %s." c?)
(n/cf-close cf c?)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 98562 | ;; 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.nettio.resp
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.niou.mime :as mm]
[czlab.niou.core :as cc]
[czlab.niou.webss :as ss]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.basal.core :as c]
[czlab.basal.dates :as d]
[czlab.nettio.core :as n]
[czlab.nettio.http :as h1]
[czlab.nettio.ranges :as nr])
(:import [io.netty.channel ChannelFuture Channel ChannelHandlerContext]
[io.netty.buffer Unpooled ByteBuf ByteBufAllocator]
[java.io IOException File InputStream]
[io.netty.util ReferenceCountUtil]
[clojure.lang APersistentVector]
[java.nio.charset Charset]
[java.net HttpCookie URL]
[java.util Date]
[czlab.basal XData]
[czlab.niou Headers DateUtil]
[czlab.niou.core WsockMsg Http1xMsg HttpResultMsg]
[czlab.nettio.ranges HttpRangesObj]
[io.netty.handler.codec.http.cookie
Cookie
ServerCookieEncoder]
[io.netty.handler.codec.http
HttpResponseStatus
DefaultHttpHeaders
FullHttpResponse
HttpChunkedInput
HttpVersion
HttpUtil
HttpMessage
HttpHeaderValues
HttpHeaderNames
HttpResponse
HttpHeaders]
[io.netty.handler.stream
ChunkedNioFile
ChunkedInput
ChunkedFile
ChunkedStream]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- conds-hds
[[:if-unmod-since (str (n/h1hdr* IF_UNMODIFIED_SINCE))]
[:if-mod-since (str (n/h1hdr* IF_MODIFIED_SINCE))]
[:if-none-match (str (n/h1hdr* IF_NONE_MATCH))]
[:if-match (str (n/h1hdr* IF_MATCH))]
[:if-range (str (n/h1hdr* IF_RANGE))]
[:range (str (n/h1hdr* RANGE))]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- resp-hds
[[:last-mod (str (n/h1hdr* LAST_MODIFIED))]
[:etag (str (n/h1hdr* ETAG))]
[:ctype (str (n/h1hdr* CONTENT_TYPE))]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare replyer<> result<>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- result<>
[theReq status]
{:pre [(or (nil? status)
(number? status))]}
(c/object<> HttpResultMsg
:headers (Headers.)
:request theReq
:cookies {}
:protocol (.text HttpVersion/HTTP_1_1)
:status (or status (n/scode* OK))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgCreator
Http1xMsg
(http-result
([theReq] (cc/http-result theReq 200))
([theReq status] (result<> theReq status))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgReplyer
HttpResultMsg
(reply-result
([theRes] (cc/reply-result theRes nil))
([theRes arg] (replyer<> theRes arg))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgReplyer
WsockMsg
(reply-result
([theRes] (cc/reply-result theRes nil))
([theRes _] (let [ch (:socket theRes)]
(some-> ch (n/write-msg theRes))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgModifier
HttpResultMsg
(res-cookie-add [res cookie]
(update-in res
[:cookies]
assoc (.getName ^HttpCookie cookie) cookie))
(res-status-set [res s]
(assoc res :status s))
(res-body-set [res body]
(assoc res :body body))
(res-header-add [res name value]
(c/do-with [res]
(.add (n/ghdrs res) ^String name value)))
(res-header-set [res name value]
(c/do-with [res]
(.set (n/ghdrs res) ^String name value)))
(res-header-del [res name]
(c/do-with [res]
(.remove (n/ghdrs res) ^String name))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn etag-file
"ETag based on a file object."
^String [in]
(if-some [f (io/file in)]
(format "\"%s-%s\"" (.lastModified f) (.hashCode f))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defmacro- code-ok?
[c] `(let [c# ~c] (and (>= c# 200)(< c# 300))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defmacro- cond-err-code
[m] `(let [m# ~m]
(if (or (= m# :get) (= m# :head))
(n/scode* ~'NOT_MODIFIED)
(n/scode* ~'PRECONDITION_FAILED))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-none-match?
"Condition fails if the reply eTag
matches, or if filter is a wildcard."
[method eTag code body conds]
(let [{:keys [value has?]} (:if-none-match conds)
value (c/strim value)
ec (cond-err-code method)]
[(cond (or (not has?) (c/nichts? value)) code
(c/eq-any? value ["*" "\"*\""]) (if (c/hgl? eTag) ec code)
(c/eq-any? eTag (map #(c/strim %)
(c/split value ","))) ec :else code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-match?
"Condition fails if reply eTag doesn't
match, or if filter is wildcard and no eTag."
[method eTag code body conds]
(let [{:keys [value has?]} (:if-match conds)
value (c/strim value)
ec (cond-err-code method)]
[(cond (or (not has?) (c/nichts? value)) code
(c/eq-any? value ["*" "\"*\""]) (if (c/hgl? eTag) code ec)
(not (c/eq-any? eTag
(map #(c/strim %)
(c/split value ",")))) ec :else code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-unmod-since?
"Condition fails if the last-modified
timestamp is greater than the given date."
[method lastMod code body conds]
(let [{:keys [value has?]} (:if-unmod-since conds)
value (c/strim value)
rc (cond-err-code method)
t (DateUtil/parseHttpDate value -1)]
[(if (and (c/spos? t)
(c/spos? lastMod))
(if (< lastMod t) code rc) code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-mod-since?
"Condition fails if the last-modified
time-stamp is less than the given date."
[method lastMod code body conds]
(let [{:keys [value has?]} (:if-mod-since conds)
value (c/strim value)
rc (cond-err-code method)
t (DateUtil/parseHttpDate value -1)]
[(if (and (c/spos? t)
(c/spos? lastMod))
(if (> lastMod t) code rc) code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-range?
"Sort out the range if any, then apply
the if-range condition."
[eTag lastMod code cType body conds]
(let [ec (n/scode* REQUESTED_RANGE_NOT_SATISFIABLE)
pc (n/scode* PARTIAL_CONTENT)
^String hd (get-in conds [:if-range :value])
{:keys [value has?]} (:range conds)
value (c/strim value)
g (nr/http-ranges<> (if has? value nil) cType body)]
(cond (or (not has?)
(c/nichts? value)) [code body]
(nil? g) [ec nil]
(c/nichts? hd) [pc g]
(and (cs/ends-with? hd "GMT")
(cs/index-of hd \,)
(cs/index-of hd \:))
(let [t (DateUtil/parseHttpDate hd -1)]
(if (and (c/spos? lastMod)
(c/spos? t)
(> lastMod t)) [code body] [pc g]))
(not= hd eTag) [code body] :else [pc g])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- encode-cookies
[cookies]
(c/preduce<vec>
#(let [^Cookie c
(condp instance? %2
Cookie %2
HttpCookie (n/netty-cookie<> %2)
(u/throw-BadArg "Bad cookie"))]
(conj! %1 (.encode ServerCookieEncoder/STRICT c))) cookies))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- replyer<>
[res sessionObj]
(c/debug "replyer called with res = %s.\nsessionObj = %s." res sessionObj)
(letfn
[(zmap-headers [msg headers]
(zipmap (map #(let [[k v] %1] k) headers)
(map #(let [[k v] %1]
{:has? (cc/msg-header? msg v)
:value (cc/msg-header msg v)}) headers)))
(converge [body cs]
(cond (bytes? body)
body
(string? body)
(i/x->bytes body cs)
(c/is? XData body)
(converge (.content ^XData body) cs) :else body))]
(let [{:keys [body status request charset] :as res}
(ss/downstream res sessionObj)
{:keys [headers last-mod etag cookies] :as cfg} res
{:keys [keep-alive?
^Channel socket request-method]} request
;^Channel ch (:socket req)
;method (:method req)
cs (u/charset?? charset)
;code (:status res)
body0 (converge body cs)
_ (c/debug "resp: body0===> %s." body0)
conds (zmap-headers request conds-hds)
rhds (zmap-headers res resp-hds)
cType (get-in rhds [:ctype :value])
[status body]
(if (code-ok? status)
(if-range? etag last-mod status cType body0 conds)
[status body0])
[status body]
(if (code-ok? status)
(if-match? request-method etag status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-none-match? request-method etag status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-mod-since? request-method last-mod status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-unmod-since? request-method last-mod status body conds)
[status body])
[status body]
(if (and (= :head request-method)
(code-ok? status))
[status nil] [status body])
rangeRef
(if-some
[ro (c/cast? HttpRangesObj body)] (c/finz ro))
[body clen]
(cond (c/is? InputStream body)
[(HttpChunkedInput.
(ChunkedStream. ^InputStream body)) -1]
rangeRef
[(HttpChunkedInput. ^ChunkedInput body) -1] ;(.length ^ChunkedInput body)]
(bytes? body)
[body (count body)]
(c/is? File body)
[(HttpChunkedInput. (ChunkedNioFile. ^File body)) -1];(.length ^File body)]
(nil? body)
[nil 0]
:else
(u/throw-IOE "Unsupported result content"))
_ (c/debug "body = %s." body)
[rsp body]
(cond (bytes? body)
[(n/http-reply<+> status body (.alloc socket)) nil]
(nil? body)
[(n/http-reply<+> status) nil]
(and (zero? clen)
(nil? body))
[(n/http-reply<+> status) nil]
:else
[(n/http-reply<> status) body])
hds (.set (.headers ^HttpMessage rsp)
(h1/std->headers headers))]
(cond (== status 416)
(nr/fmt-error hds body0)
rangeRef
(nr/fmt-success hds rangeRef))
(c/debug "response = %s." rsp)
(c/debug "body-len = %s." clen)
(if-not (zero? clen)
(->> (and body
(not (c/is? FullHttpResponse rsp)))
boolean
(HttpUtil/setTransferEncodingChunked rsp )))
(if-not (c/sneg? clen)
(HttpUtil/setContentLength rsp clen))
(if (c/sneg? clen)
(HttpUtil/setKeepAlive rsp false)
(HttpUtil/setKeepAlive rsp keep-alive?))
(if (or (nil? body)
(and (zero? clen)(nil? body)))
(.remove hds (n/h1hdr* CONTENT_TYPE)))
(doseq [s (encode-cookies (vals cookies))]
(c/debug "resp: setting cookie: %s." s)
(.add hds (n/h1hdr* SET_COOKIE) s))
(if (and (c/spos? last-mod)
(not (get-in rhds [:last-mod :has?])))
(.set hds
(n/h1hdr* LAST_MODIFIED)
(DateUtil/formatHttpDate ^long last-mod)))
(if (and (c/hgl? etag)
(not (get-in rhds [:etag :has?])))
(.set hds (n/h1hdr* ETAG) etag))
(let [c? (HttpUtil/isKeepAlive rsp)
cf (if (nil? body)
(do (c/debug "reply has no chunked body, write and flush %s." rsp)
(.writeAndFlush socket rsp))
(do (c/debug "reply has chunked body, write and flush %s." rsp)
(.write socket rsp)
(c/debug "reply body, write and flush body: %s." body)
(.writeAndFlush socket body)))]
(c/debug "resp replied, keep-alive? = %s." c?)
(n/cf-close cf c?)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;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.nettio.resp
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.niou.mime :as mm]
[czlab.niou.core :as cc]
[czlab.niou.webss :as ss]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.basal.core :as c]
[czlab.basal.dates :as d]
[czlab.nettio.core :as n]
[czlab.nettio.http :as h1]
[czlab.nettio.ranges :as nr])
(:import [io.netty.channel ChannelFuture Channel ChannelHandlerContext]
[io.netty.buffer Unpooled ByteBuf ByteBufAllocator]
[java.io IOException File InputStream]
[io.netty.util ReferenceCountUtil]
[clojure.lang APersistentVector]
[java.nio.charset Charset]
[java.net HttpCookie URL]
[java.util Date]
[czlab.basal XData]
[czlab.niou Headers DateUtil]
[czlab.niou.core WsockMsg Http1xMsg HttpResultMsg]
[czlab.nettio.ranges HttpRangesObj]
[io.netty.handler.codec.http.cookie
Cookie
ServerCookieEncoder]
[io.netty.handler.codec.http
HttpResponseStatus
DefaultHttpHeaders
FullHttpResponse
HttpChunkedInput
HttpVersion
HttpUtil
HttpMessage
HttpHeaderValues
HttpHeaderNames
HttpResponse
HttpHeaders]
[io.netty.handler.stream
ChunkedNioFile
ChunkedInput
ChunkedFile
ChunkedStream]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* false)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- conds-hds
[[:if-unmod-since (str (n/h1hdr* IF_UNMODIFIED_SINCE))]
[:if-mod-since (str (n/h1hdr* IF_MODIFIED_SINCE))]
[:if-none-match (str (n/h1hdr* IF_NONE_MATCH))]
[:if-match (str (n/h1hdr* IF_MATCH))]
[:if-range (str (n/h1hdr* IF_RANGE))]
[:range (str (n/h1hdr* RANGE))]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- resp-hds
[[:last-mod (str (n/h1hdr* LAST_MODIFIED))]
[:etag (str (n/h1hdr* ETAG))]
[:ctype (str (n/h1hdr* CONTENT_TYPE))]])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare replyer<> result<>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- result<>
[theReq status]
{:pre [(or (nil? status)
(number? status))]}
(c/object<> HttpResultMsg
:headers (Headers.)
:request theReq
:cookies {}
:protocol (.text HttpVersion/HTTP_1_1)
:status (or status (n/scode* OK))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgCreator
Http1xMsg
(http-result
([theReq] (cc/http-result theReq 200))
([theReq status] (result<> theReq status))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgReplyer
HttpResultMsg
(reply-result
([theRes] (cc/reply-result theRes nil))
([theRes arg] (replyer<> theRes arg))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgReplyer
WsockMsg
(reply-result
([theRes] (cc/reply-result theRes nil))
([theRes _] (let [ch (:socket theRes)]
(some-> ch (n/write-msg theRes))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol cc/HttpResultMsgModifier
HttpResultMsg
(res-cookie-add [res cookie]
(update-in res
[:cookies]
assoc (.getName ^HttpCookie cookie) cookie))
(res-status-set [res s]
(assoc res :status s))
(res-body-set [res body]
(assoc res :body body))
(res-header-add [res name value]
(c/do-with [res]
(.add (n/ghdrs res) ^String name value)))
(res-header-set [res name value]
(c/do-with [res]
(.set (n/ghdrs res) ^String name value)))
(res-header-del [res name]
(c/do-with [res]
(.remove (n/ghdrs res) ^String name))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn etag-file
"ETag based on a file object."
^String [in]
(if-some [f (io/file in)]
(format "\"%s-%s\"" (.lastModified f) (.hashCode f))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defmacro- code-ok?
[c] `(let [c# ~c] (and (>= c# 200)(< c# 300))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defmacro- cond-err-code
[m] `(let [m# ~m]
(if (or (= m# :get) (= m# :head))
(n/scode* ~'NOT_MODIFIED)
(n/scode* ~'PRECONDITION_FAILED))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-none-match?
"Condition fails if the reply eTag
matches, or if filter is a wildcard."
[method eTag code body conds]
(let [{:keys [value has?]} (:if-none-match conds)
value (c/strim value)
ec (cond-err-code method)]
[(cond (or (not has?) (c/nichts? value)) code
(c/eq-any? value ["*" "\"*\""]) (if (c/hgl? eTag) ec code)
(c/eq-any? eTag (map #(c/strim %)
(c/split value ","))) ec :else code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-match?
"Condition fails if reply eTag doesn't
match, or if filter is wildcard and no eTag."
[method eTag code body conds]
(let [{:keys [value has?]} (:if-match conds)
value (c/strim value)
ec (cond-err-code method)]
[(cond (or (not has?) (c/nichts? value)) code
(c/eq-any? value ["*" "\"*\""]) (if (c/hgl? eTag) code ec)
(not (c/eq-any? eTag
(map #(c/strim %)
(c/split value ",")))) ec :else code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-unmod-since?
"Condition fails if the last-modified
timestamp is greater than the given date."
[method lastMod code body conds]
(let [{:keys [value has?]} (:if-unmod-since conds)
value (c/strim value)
rc (cond-err-code method)
t (DateUtil/parseHttpDate value -1)]
[(if (and (c/spos? t)
(c/spos? lastMod))
(if (< lastMod t) code rc) code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-mod-since?
"Condition fails if the last-modified
time-stamp is less than the given date."
[method lastMod code body conds]
(let [{:keys [value has?]} (:if-mod-since conds)
value (c/strim value)
rc (cond-err-code method)
t (DateUtil/parseHttpDate value -1)]
[(if (and (c/spos? t)
(c/spos? lastMod))
(if (> lastMod t) code rc) code) body]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- if-range?
"Sort out the range if any, then apply
the if-range condition."
[eTag lastMod code cType body conds]
(let [ec (n/scode* REQUESTED_RANGE_NOT_SATISFIABLE)
pc (n/scode* PARTIAL_CONTENT)
^String hd (get-in conds [:if-range :value])
{:keys [value has?]} (:range conds)
value (c/strim value)
g (nr/http-ranges<> (if has? value nil) cType body)]
(cond (or (not has?)
(c/nichts? value)) [code body]
(nil? g) [ec nil]
(c/nichts? hd) [pc g]
(and (cs/ends-with? hd "GMT")
(cs/index-of hd \,)
(cs/index-of hd \:))
(let [t (DateUtil/parseHttpDate hd -1)]
(if (and (c/spos? lastMod)
(c/spos? t)
(> lastMod t)) [code body] [pc g]))
(not= hd eTag) [code body] :else [pc g])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- encode-cookies
[cookies]
(c/preduce<vec>
#(let [^Cookie c
(condp instance? %2
Cookie %2
HttpCookie (n/netty-cookie<> %2)
(u/throw-BadArg "Bad cookie"))]
(conj! %1 (.encode ServerCookieEncoder/STRICT c))) cookies))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- replyer<>
[res sessionObj]
(c/debug "replyer called with res = %s.\nsessionObj = %s." res sessionObj)
(letfn
[(zmap-headers [msg headers]
(zipmap (map #(let [[k v] %1] k) headers)
(map #(let [[k v] %1]
{:has? (cc/msg-header? msg v)
:value (cc/msg-header msg v)}) headers)))
(converge [body cs]
(cond (bytes? body)
body
(string? body)
(i/x->bytes body cs)
(c/is? XData body)
(converge (.content ^XData body) cs) :else body))]
(let [{:keys [body status request charset] :as res}
(ss/downstream res sessionObj)
{:keys [headers last-mod etag cookies] :as cfg} res
{:keys [keep-alive?
^Channel socket request-method]} request
;^Channel ch (:socket req)
;method (:method req)
cs (u/charset?? charset)
;code (:status res)
body0 (converge body cs)
_ (c/debug "resp: body0===> %s." body0)
conds (zmap-headers request conds-hds)
rhds (zmap-headers res resp-hds)
cType (get-in rhds [:ctype :value])
[status body]
(if (code-ok? status)
(if-range? etag last-mod status cType body0 conds)
[status body0])
[status body]
(if (code-ok? status)
(if-match? request-method etag status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-none-match? request-method etag status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-mod-since? request-method last-mod status body conds)
[status body])
[status body]
(if (code-ok? status)
(if-unmod-since? request-method last-mod status body conds)
[status body])
[status body]
(if (and (= :head request-method)
(code-ok? status))
[status nil] [status body])
rangeRef
(if-some
[ro (c/cast? HttpRangesObj body)] (c/finz ro))
[body clen]
(cond (c/is? InputStream body)
[(HttpChunkedInput.
(ChunkedStream. ^InputStream body)) -1]
rangeRef
[(HttpChunkedInput. ^ChunkedInput body) -1] ;(.length ^ChunkedInput body)]
(bytes? body)
[body (count body)]
(c/is? File body)
[(HttpChunkedInput. (ChunkedNioFile. ^File body)) -1];(.length ^File body)]
(nil? body)
[nil 0]
:else
(u/throw-IOE "Unsupported result content"))
_ (c/debug "body = %s." body)
[rsp body]
(cond (bytes? body)
[(n/http-reply<+> status body (.alloc socket)) nil]
(nil? body)
[(n/http-reply<+> status) nil]
(and (zero? clen)
(nil? body))
[(n/http-reply<+> status) nil]
:else
[(n/http-reply<> status) body])
hds (.set (.headers ^HttpMessage rsp)
(h1/std->headers headers))]
(cond (== status 416)
(nr/fmt-error hds body0)
rangeRef
(nr/fmt-success hds rangeRef))
(c/debug "response = %s." rsp)
(c/debug "body-len = %s." clen)
(if-not (zero? clen)
(->> (and body
(not (c/is? FullHttpResponse rsp)))
boolean
(HttpUtil/setTransferEncodingChunked rsp )))
(if-not (c/sneg? clen)
(HttpUtil/setContentLength rsp clen))
(if (c/sneg? clen)
(HttpUtil/setKeepAlive rsp false)
(HttpUtil/setKeepAlive rsp keep-alive?))
(if (or (nil? body)
(and (zero? clen)(nil? body)))
(.remove hds (n/h1hdr* CONTENT_TYPE)))
(doseq [s (encode-cookies (vals cookies))]
(c/debug "resp: setting cookie: %s." s)
(.add hds (n/h1hdr* SET_COOKIE) s))
(if (and (c/spos? last-mod)
(not (get-in rhds [:last-mod :has?])))
(.set hds
(n/h1hdr* LAST_MODIFIED)
(DateUtil/formatHttpDate ^long last-mod)))
(if (and (c/hgl? etag)
(not (get-in rhds [:etag :has?])))
(.set hds (n/h1hdr* ETAG) etag))
(let [c? (HttpUtil/isKeepAlive rsp)
cf (if (nil? body)
(do (c/debug "reply has no chunked body, write and flush %s." rsp)
(.writeAndFlush socket rsp))
(do (c/debug "reply has chunked body, write and flush %s." rsp)
(.write socket rsp)
(c/debug "reply body, write and flush body: %s." body)
(.writeAndFlush socket body)))]
(c/debug "resp replied, keep-alive? = %s." c?)
(n/cf-close cf c?)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": "\"group\"}\n [:input {:type \"submit\", :value \"Szukaj\", :class \"search-button\"}]\n [:a {:class \"adv",
"end": 4310,
"score": 0.6469111442565918,
"start": 4306,
"tag": "NAME",
"value": "ukaj"
},
{
"context": "div\n [:input {:key (str \"filter-cb-\" n)\n :type \"chec",
"end": 6476,
"score": 0.654154896736145,
"start": 6465,
"tag": "KEY",
"value": "filter-cb-\""
}
] | src/cljs/smyrna/document_table.cljs | nathell/smyrna | 4 | (ns smyrna.document-table
(:require [clojure.walk :refer [postwalk]]
[clojure.string :as string]
[reagent.core :as reagent :refer [atom]]
[re-frame.core :as re-frame :refer [reg-event-db reg-event-fx reg-sub dispatch dispatch-sync subscribe]]
[smyrna.api :as api]
[smyrna.utils :refer [reg-accessors reg-getters dispatch-value]]
[smyrna.table :refer [table]]
[smyrna.tabbar :refer [tabbar]]))
(defn filter-params [{:keys [page rows-per-page filters phrase within]}]
{:offset (* page rows-per-page),
:limit rows-per-page,
:filters filters,
:phrase phrase,
:within within})
(defn toggle [set el]
((if (set el) disj conj) set el))
(defn toggle-nilable [s el n]
(toggle (or s (set (range n))) el))
(reg-accessors :new-area :browsed-document :browsed-document-num :document-tab :advanced)
(reg-getters :document-filter :current-filter :metadata :contexts :document-table)
(reg-sub :vignette #(-> %1 :custom :vignette))
(reg-sub :phrase #(-> %1 :document-filter :phrase))
(reg-event-db
:set-documents
(fn [db [_ documents]]
(assoc-in db [:document-table :data] documents)))
(reg-event-db
:set-phrase
(fn [db [_ value]]
(assoc-in db [:document-filter :phrase] value)))
(reg-event-db
:set-filter
(fn [db [_ column value]]
(if (empty? value)
(update-in db [:document-filter :filters] dissoc column)
(assoc-in db [:document-filter :filters column] value))))
(reg-event-db
:checkboxes-set-all
(fn [db [_ column]]
(update-in db [:document-filter :filters] dissoc column)))
(reg-event-db
:checkboxes-clear-all
(fn [db [_ column]]
(assoc-in db [:document-filter :filters column] #{})))
(reg-event-db
:checkboxes-toggle
(fn [db [_ column value cnt]]
(update-in db [:document-filter :filters column] toggle-nilable value cnt)))
(reg-event-db
:browse-basic
(fn [db [_ n documents]]
(if (seq documents)
(assoc db
:browsed-document-num n
:browsed-document (first documents)
:document-tab 1)
db)))
(reg-event-db
:browse
(fn [db [_ row document]]
(let [df (:document-filter db)]
(assoc db
:browsed-document-num (+ row (* (:page df) (:rows-per-page df)))
:browsed-document document
:document-tab 1))))
(reg-event-db
:set-search-context
(fn [db [_ value]]
(assoc-in db [:document-filter :within] value)))
(reg-event-fx
:refresh-table
(fn [{db :db} _]
{:api ["get-documents"
(assoc (filter-params (:document-filter db))
:corpus (:current-corpus db))
:set-documents]
:db (assoc db :current-filter (:document-filter db))}))
(reg-event-fx
:reset-filters
(fn [{db :db} _]
{:db (assoc db :document-filter {:page 0, :rows-per-page 10, :filters {}})
:dispatch [:refresh-table]}))
(reg-event-fx
:move-page
(fn [{db :db} [_ delta]]
{:db (update-in db [:document-filter :page] + delta)
:dispatch [:refresh-table]}))
(reg-event-fx
:browse-num
(fn [{db :db} [_ n]]
{:api ["get-documents"
(assoc (filter-params (:document-filter db))
:corpus (:current-corpus db)
:offset n :limit 1)
:browse-basic n]}))
(reg-event-fx
:create-area
(fn [{db :db} [_ n]]
(let [params (filter-params (:document-filter db))
name (:new-area db)]
{:api ["create-context" {:name name, :description params, :corpus (:current-corpus db)}]
:db (update-in db [:contexts] conj [name params])})))
(defn area-creator []
[:div
[:input {:type "text", :placeholder "Wpisz nazwę obszaru", :on-change (dispatch-value :set-new-area)}]
[:button {:on-click #(do (dispatch [:create-area])
(dispatch [:set-modal nil]))}
"Utwórz obszar"]])
(defn search []
(let [contexts (subscribe [:contexts])
phrase (subscribe [:phrase])
advanced (subscribe [:advanced])]
[:form {:class "search" :on-submit #(do (.preventDefault %1) (dispatch [:refresh-table]) false)}
[:div {:class "group"}
[:input {:class "phrase", :type "text", :autoFocus true, :placeholder "Wpisz szukaną frazę", :on-change (dispatch-value :set-phrase), :value @phrase}]]
[:div {:class "group"}
[:input {:type "submit", :value "Szukaj", :class "search-button"}]
[:a {:class "advanced" :href "#" :on-click #(dispatch [:set-advanced (not @advanced)])} (if @advanced "« Ukryj zaawansowane opcje" "Pokaż zaawansowane opcje »")]]
(if @advanced
[:div {:class "group"}
"Obszar: "
(into [:select {:on-change (dispatch-value :set-search-context)}
[:option "Cały korpus"]]
(for [[opt _] @contexts]
[:option {:value opt, #_:selected #_(= (:within @search-params) opt)} opt]))])
(if @advanced
[:div {:class "group"}
[:button {:on-click #(dispatch [:set-modal area-creator])} "Utwórz obszar"]
[:button {:on-click #(dispatch [:reset-filters])} "Resetuj filtry"]])]))
(defn document-summary
[]
(let [{:keys [phrase within filters page]} @(subscribe [:current-filter])]
[:p.summary
(if (seq phrase)
[:span "Dokumenty zawierające frazę „" [:b phrase] "”"]
"Wszystkie dokumenty")
" w "
(if (or (nil? within) (= within "Cały korpus"))
"całym korpusie"
[:span "obszarze " [:b [:i within]]])
[:br]
"Strona " (inc page)
[:br]
(if (seq filters)
[:span
"Aktywne filtry: " [:i (string/join ", " (keys filters))]
" ("
[:a {:href "#" :on-click #(dispatch [:reset-filters])} "resetuj"]
")"]
"Brak aktywnych filtrów")
]))
(defn pagination []
(let [document-filter (subscribe [:document-filter])]
[:div {:class "pagination", :style {:width @(subscribe [:table-width])}}
[:button (if (> (:page @document-filter) 0)
{:on-click #(dispatch [:move-page -1])}
{:disabled true}) "<<"]
[document-summary]
[:button {:on-click #(dispatch [:move-page 1])} ">>"]]))
(defn top-overlay []
[:div
[search]])
(defn filter-checkboxes-content [labels key]
(let [document-filter (subscribe [:document-filter])
cnt (count labels)
flt (get-in @document-filter [:filters key])]
(into [:div {:class "checkboxes"}]
(map-indexed (fn [n label]
[:div
[:input {:key (str "filter-cb-" n)
:type "checkbox"
:checked (if flt (boolean (flt n)) true)
:on-change #(dispatch [:checkboxes-toggle key n cnt])}]
[:label {:key (str "filter-lbl-" n)} label]])
labels))))
(defn filter-header [key]
[:h1 (str "Filtruj: " (name key))])
(defn filter-checkboxes [labels key]
[:div {:class "filter filter-cb"}
[filter-header key]
[filter-checkboxes-content labels key]
[:div {:class "buttons"}
[:button {:on-click #(dispatch [:checkboxes-set-all key])} "Zaznacz wszystkie"]
[:button {:on-click #(dispatch [:checkboxes-clear-all key])} "Wyczyść wszystkie"]
[:button {:on-click #(do (dispatch [:set-modal nil])
(dispatch [:refresh-table]))} "OK"]]])
(defn filter-text [key]
(let [filter (subscribe [:document-filter])]
[:div {:class "filter filter-text"}
[filter-header key]
[:input {:type "text"
:value (get-in @filter [:filters key])
:on-change (dispatch-value :set-filter key)}]
[:button {:on-click #(do (dispatch [:set-modal nil])
(dispatch [:refresh-table]))} "OK"]]))
(defn filter-widget [col valset]
(if valset
(filter-checkboxes valset col)
(filter-text col)))
(defn main-table-header [col title]
(let [document-table (subscribe [:document-table])
[col-id valset] (nth (:metadata @document-table) col)]
[:a {:href "#"
:on-click #(dispatch [:set-modal (partial filter-widget col-id valset)])} title]))
(defn main-table-proper []
(table :document-table
:cell-renderer (fn [{:keys [data]} row col]
(let [val (nth (nth data row) (inc col))]
[:a {:href "#"
:on-click #(dispatch [:browse row (nth data row)])
:title val} val]))
:header-renderer (fn [col title]
[main-table-header col title])))
(defn main-table []
[:div {:class "fullsize"}
[pagination]
[main-table-proper]])
(defn iframe-matches []
(let [iframe (js/document.getElementById "browsed")
doc (-> iframe .-contentWindow .-document)
matches (.getElementsByClassName doc "match")]
(vec (js/Array.prototype.slice.call matches))))
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
(defn advance-match [delta]
(let [matches (iframe-matches)
current (first (indices #(.contains (.-classList %) "selected") matches))
nxt (-> (if current (+ current delta) 0) (max 0) (min (dec (count matches))))]
(when (seq matches)
(when current
(.remove (.-classList (matches current)) "selected"))
(.add (.-classList (matches nxt)) "selected")
(.scrollIntoView (matches nxt)))))
(defn advance-document-button [label title delta]
(let [browsed-document-num (subscribe [:browsed-document-num])]
[:button {:title title
:on-click #(dispatch [:browse-num (+ @browsed-document-num delta)])}
label]))
(reg-sub :meta-keys
#(subscribe [:document-table])
#(map (comp keyword first) (:metadata %1)))
(defn meta-item [key]
(let [meta-keys (subscribe [:meta-keys])
browsed-document (subscribe [:browsed-document])]
(when-let [doc @browsed-document]
(let [meta-map (zipmap @meta-keys (rest doc))]
[:span (meta-map key)]))))
(defn vignette
[]
(let [v @(subscribe [:vignette])]
(if v
(postwalk #(if (and (keyword? %) (= (namespace %) "meta"))
[meta-item (keyword (name %))]
%)
v)
[:div.vignette
[:table
(for [k @(subscribe [:meta-keys])]
[:tr [:th k] [:td [meta-item k]]])]])))
(defn document-browser []
(let [browsed-document (subscribe [:browsed-document])
document-filter (subscribe [:document-filter])
corpus (subscribe [:current-corpus])]
(if-let [doc @browsed-document]
[:table {:class "fixed-top document"}
[:tbody
[:tr {:class "navigation"}
[:td
[advance-document-button "<<" "Poprzedni dokument" -1]
(when (:phrase @document-filter)
[:button {:on-click #(advance-match -1) :title "Poprzednie wystąpienie"} "<"])]
[:td [vignette]]
[:td
(when (:phrase @document-filter)
[:button {:on-click #(advance-match 1) :title "Następne wystąpienie"} ">"])
[advance-document-button ">>" "Następny dokument" 1]]]
[:tr [:td {:col-span 3}
[:div
[:iframe {:id "browsed"
:on-load #(let [slf (js/document.getElementById "browsed")
doc (-> slf .-contentWindow .-document)]
nil #_
(js/alert (str "Found matches: " (.-length (.getElementsByClassName doc "match")))))
:src
(if-let [phrase (:phrase @document-filter)]
(str "/highlight/" @corpus "/" phrase "/" (first doc))
(str "/corpus/" @corpus "/" (first doc)))}]]]]]]
[:h2 "Brak dokumentu do wyświetlenia."])))
(defn document-table []
[:table {:class "fixed-top documents"}
[:tbody
[:tr [:td [top-overlay]]]
[:tr [:td [tabbar :document-tab
["Lista dokumentów" [main-table]
"Pojedynczy dokument" [document-browser]]]]]]])
| 47651 | (ns smyrna.document-table
(:require [clojure.walk :refer [postwalk]]
[clojure.string :as string]
[reagent.core :as reagent :refer [atom]]
[re-frame.core :as re-frame :refer [reg-event-db reg-event-fx reg-sub dispatch dispatch-sync subscribe]]
[smyrna.api :as api]
[smyrna.utils :refer [reg-accessors reg-getters dispatch-value]]
[smyrna.table :refer [table]]
[smyrna.tabbar :refer [tabbar]]))
(defn filter-params [{:keys [page rows-per-page filters phrase within]}]
{:offset (* page rows-per-page),
:limit rows-per-page,
:filters filters,
:phrase phrase,
:within within})
(defn toggle [set el]
((if (set el) disj conj) set el))
(defn toggle-nilable [s el n]
(toggle (or s (set (range n))) el))
(reg-accessors :new-area :browsed-document :browsed-document-num :document-tab :advanced)
(reg-getters :document-filter :current-filter :metadata :contexts :document-table)
(reg-sub :vignette #(-> %1 :custom :vignette))
(reg-sub :phrase #(-> %1 :document-filter :phrase))
(reg-event-db
:set-documents
(fn [db [_ documents]]
(assoc-in db [:document-table :data] documents)))
(reg-event-db
:set-phrase
(fn [db [_ value]]
(assoc-in db [:document-filter :phrase] value)))
(reg-event-db
:set-filter
(fn [db [_ column value]]
(if (empty? value)
(update-in db [:document-filter :filters] dissoc column)
(assoc-in db [:document-filter :filters column] value))))
(reg-event-db
:checkboxes-set-all
(fn [db [_ column]]
(update-in db [:document-filter :filters] dissoc column)))
(reg-event-db
:checkboxes-clear-all
(fn [db [_ column]]
(assoc-in db [:document-filter :filters column] #{})))
(reg-event-db
:checkboxes-toggle
(fn [db [_ column value cnt]]
(update-in db [:document-filter :filters column] toggle-nilable value cnt)))
(reg-event-db
:browse-basic
(fn [db [_ n documents]]
(if (seq documents)
(assoc db
:browsed-document-num n
:browsed-document (first documents)
:document-tab 1)
db)))
(reg-event-db
:browse
(fn [db [_ row document]]
(let [df (:document-filter db)]
(assoc db
:browsed-document-num (+ row (* (:page df) (:rows-per-page df)))
:browsed-document document
:document-tab 1))))
(reg-event-db
:set-search-context
(fn [db [_ value]]
(assoc-in db [:document-filter :within] value)))
(reg-event-fx
:refresh-table
(fn [{db :db} _]
{:api ["get-documents"
(assoc (filter-params (:document-filter db))
:corpus (:current-corpus db))
:set-documents]
:db (assoc db :current-filter (:document-filter db))}))
(reg-event-fx
:reset-filters
(fn [{db :db} _]
{:db (assoc db :document-filter {:page 0, :rows-per-page 10, :filters {}})
:dispatch [:refresh-table]}))
(reg-event-fx
:move-page
(fn [{db :db} [_ delta]]
{:db (update-in db [:document-filter :page] + delta)
:dispatch [:refresh-table]}))
(reg-event-fx
:browse-num
(fn [{db :db} [_ n]]
{:api ["get-documents"
(assoc (filter-params (:document-filter db))
:corpus (:current-corpus db)
:offset n :limit 1)
:browse-basic n]}))
(reg-event-fx
:create-area
(fn [{db :db} [_ n]]
(let [params (filter-params (:document-filter db))
name (:new-area db)]
{:api ["create-context" {:name name, :description params, :corpus (:current-corpus db)}]
:db (update-in db [:contexts] conj [name params])})))
(defn area-creator []
[:div
[:input {:type "text", :placeholder "Wpisz nazwę obszaru", :on-change (dispatch-value :set-new-area)}]
[:button {:on-click #(do (dispatch [:create-area])
(dispatch [:set-modal nil]))}
"Utwórz obszar"]])
(defn search []
(let [contexts (subscribe [:contexts])
phrase (subscribe [:phrase])
advanced (subscribe [:advanced])]
[:form {:class "search" :on-submit #(do (.preventDefault %1) (dispatch [:refresh-table]) false)}
[:div {:class "group"}
[:input {:class "phrase", :type "text", :autoFocus true, :placeholder "Wpisz szukaną frazę", :on-change (dispatch-value :set-phrase), :value @phrase}]]
[:div {:class "group"}
[:input {:type "submit", :value "Sz<NAME>", :class "search-button"}]
[:a {:class "advanced" :href "#" :on-click #(dispatch [:set-advanced (not @advanced)])} (if @advanced "« Ukryj zaawansowane opcje" "Pokaż zaawansowane opcje »")]]
(if @advanced
[:div {:class "group"}
"Obszar: "
(into [:select {:on-change (dispatch-value :set-search-context)}
[:option "Cały korpus"]]
(for [[opt _] @contexts]
[:option {:value opt, #_:selected #_(= (:within @search-params) opt)} opt]))])
(if @advanced
[:div {:class "group"}
[:button {:on-click #(dispatch [:set-modal area-creator])} "Utwórz obszar"]
[:button {:on-click #(dispatch [:reset-filters])} "Resetuj filtry"]])]))
(defn document-summary
[]
(let [{:keys [phrase within filters page]} @(subscribe [:current-filter])]
[:p.summary
(if (seq phrase)
[:span "Dokumenty zawierające frazę „" [:b phrase] "”"]
"Wszystkie dokumenty")
" w "
(if (or (nil? within) (= within "Cały korpus"))
"całym korpusie"
[:span "obszarze " [:b [:i within]]])
[:br]
"Strona " (inc page)
[:br]
(if (seq filters)
[:span
"Aktywne filtry: " [:i (string/join ", " (keys filters))]
" ("
[:a {:href "#" :on-click #(dispatch [:reset-filters])} "resetuj"]
")"]
"Brak aktywnych filtrów")
]))
(defn pagination []
(let [document-filter (subscribe [:document-filter])]
[:div {:class "pagination", :style {:width @(subscribe [:table-width])}}
[:button (if (> (:page @document-filter) 0)
{:on-click #(dispatch [:move-page -1])}
{:disabled true}) "<<"]
[document-summary]
[:button {:on-click #(dispatch [:move-page 1])} ">>"]]))
(defn top-overlay []
[:div
[search]])
(defn filter-checkboxes-content [labels key]
(let [document-filter (subscribe [:document-filter])
cnt (count labels)
flt (get-in @document-filter [:filters key])]
(into [:div {:class "checkboxes"}]
(map-indexed (fn [n label]
[:div
[:input {:key (str "<KEY> n)
:type "checkbox"
:checked (if flt (boolean (flt n)) true)
:on-change #(dispatch [:checkboxes-toggle key n cnt])}]
[:label {:key (str "filter-lbl-" n)} label]])
labels))))
(defn filter-header [key]
[:h1 (str "Filtruj: " (name key))])
(defn filter-checkboxes [labels key]
[:div {:class "filter filter-cb"}
[filter-header key]
[filter-checkboxes-content labels key]
[:div {:class "buttons"}
[:button {:on-click #(dispatch [:checkboxes-set-all key])} "Zaznacz wszystkie"]
[:button {:on-click #(dispatch [:checkboxes-clear-all key])} "Wyczyść wszystkie"]
[:button {:on-click #(do (dispatch [:set-modal nil])
(dispatch [:refresh-table]))} "OK"]]])
(defn filter-text [key]
(let [filter (subscribe [:document-filter])]
[:div {:class "filter filter-text"}
[filter-header key]
[:input {:type "text"
:value (get-in @filter [:filters key])
:on-change (dispatch-value :set-filter key)}]
[:button {:on-click #(do (dispatch [:set-modal nil])
(dispatch [:refresh-table]))} "OK"]]))
(defn filter-widget [col valset]
(if valset
(filter-checkboxes valset col)
(filter-text col)))
(defn main-table-header [col title]
(let [document-table (subscribe [:document-table])
[col-id valset] (nth (:metadata @document-table) col)]
[:a {:href "#"
:on-click #(dispatch [:set-modal (partial filter-widget col-id valset)])} title]))
(defn main-table-proper []
(table :document-table
:cell-renderer (fn [{:keys [data]} row col]
(let [val (nth (nth data row) (inc col))]
[:a {:href "#"
:on-click #(dispatch [:browse row (nth data row)])
:title val} val]))
:header-renderer (fn [col title]
[main-table-header col title])))
(defn main-table []
[:div {:class "fullsize"}
[pagination]
[main-table-proper]])
(defn iframe-matches []
(let [iframe (js/document.getElementById "browsed")
doc (-> iframe .-contentWindow .-document)
matches (.getElementsByClassName doc "match")]
(vec (js/Array.prototype.slice.call matches))))
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
(defn advance-match [delta]
(let [matches (iframe-matches)
current (first (indices #(.contains (.-classList %) "selected") matches))
nxt (-> (if current (+ current delta) 0) (max 0) (min (dec (count matches))))]
(when (seq matches)
(when current
(.remove (.-classList (matches current)) "selected"))
(.add (.-classList (matches nxt)) "selected")
(.scrollIntoView (matches nxt)))))
(defn advance-document-button [label title delta]
(let [browsed-document-num (subscribe [:browsed-document-num])]
[:button {:title title
:on-click #(dispatch [:browse-num (+ @browsed-document-num delta)])}
label]))
(reg-sub :meta-keys
#(subscribe [:document-table])
#(map (comp keyword first) (:metadata %1)))
(defn meta-item [key]
(let [meta-keys (subscribe [:meta-keys])
browsed-document (subscribe [:browsed-document])]
(when-let [doc @browsed-document]
(let [meta-map (zipmap @meta-keys (rest doc))]
[:span (meta-map key)]))))
(defn vignette
[]
(let [v @(subscribe [:vignette])]
(if v
(postwalk #(if (and (keyword? %) (= (namespace %) "meta"))
[meta-item (keyword (name %))]
%)
v)
[:div.vignette
[:table
(for [k @(subscribe [:meta-keys])]
[:tr [:th k] [:td [meta-item k]]])]])))
(defn document-browser []
(let [browsed-document (subscribe [:browsed-document])
document-filter (subscribe [:document-filter])
corpus (subscribe [:current-corpus])]
(if-let [doc @browsed-document]
[:table {:class "fixed-top document"}
[:tbody
[:tr {:class "navigation"}
[:td
[advance-document-button "<<" "Poprzedni dokument" -1]
(when (:phrase @document-filter)
[:button {:on-click #(advance-match -1) :title "Poprzednie wystąpienie"} "<"])]
[:td [vignette]]
[:td
(when (:phrase @document-filter)
[:button {:on-click #(advance-match 1) :title "Następne wystąpienie"} ">"])
[advance-document-button ">>" "Następny dokument" 1]]]
[:tr [:td {:col-span 3}
[:div
[:iframe {:id "browsed"
:on-load #(let [slf (js/document.getElementById "browsed")
doc (-> slf .-contentWindow .-document)]
nil #_
(js/alert (str "Found matches: " (.-length (.getElementsByClassName doc "match")))))
:src
(if-let [phrase (:phrase @document-filter)]
(str "/highlight/" @corpus "/" phrase "/" (first doc))
(str "/corpus/" @corpus "/" (first doc)))}]]]]]]
[:h2 "Brak dokumentu do wyświetlenia."])))
(defn document-table []
[:table {:class "fixed-top documents"}
[:tbody
[:tr [:td [top-overlay]]]
[:tr [:td [tabbar :document-tab
["Lista dokumentów" [main-table]
"Pojedynczy dokument" [document-browser]]]]]]])
| true | (ns smyrna.document-table
(:require [clojure.walk :refer [postwalk]]
[clojure.string :as string]
[reagent.core :as reagent :refer [atom]]
[re-frame.core :as re-frame :refer [reg-event-db reg-event-fx reg-sub dispatch dispatch-sync subscribe]]
[smyrna.api :as api]
[smyrna.utils :refer [reg-accessors reg-getters dispatch-value]]
[smyrna.table :refer [table]]
[smyrna.tabbar :refer [tabbar]]))
(defn filter-params [{:keys [page rows-per-page filters phrase within]}]
{:offset (* page rows-per-page),
:limit rows-per-page,
:filters filters,
:phrase phrase,
:within within})
(defn toggle [set el]
((if (set el) disj conj) set el))
(defn toggle-nilable [s el n]
(toggle (or s (set (range n))) el))
(reg-accessors :new-area :browsed-document :browsed-document-num :document-tab :advanced)
(reg-getters :document-filter :current-filter :metadata :contexts :document-table)
(reg-sub :vignette #(-> %1 :custom :vignette))
(reg-sub :phrase #(-> %1 :document-filter :phrase))
(reg-event-db
:set-documents
(fn [db [_ documents]]
(assoc-in db [:document-table :data] documents)))
(reg-event-db
:set-phrase
(fn [db [_ value]]
(assoc-in db [:document-filter :phrase] value)))
(reg-event-db
:set-filter
(fn [db [_ column value]]
(if (empty? value)
(update-in db [:document-filter :filters] dissoc column)
(assoc-in db [:document-filter :filters column] value))))
(reg-event-db
:checkboxes-set-all
(fn [db [_ column]]
(update-in db [:document-filter :filters] dissoc column)))
(reg-event-db
:checkboxes-clear-all
(fn [db [_ column]]
(assoc-in db [:document-filter :filters column] #{})))
(reg-event-db
:checkboxes-toggle
(fn [db [_ column value cnt]]
(update-in db [:document-filter :filters column] toggle-nilable value cnt)))
(reg-event-db
:browse-basic
(fn [db [_ n documents]]
(if (seq documents)
(assoc db
:browsed-document-num n
:browsed-document (first documents)
:document-tab 1)
db)))
(reg-event-db
:browse
(fn [db [_ row document]]
(let [df (:document-filter db)]
(assoc db
:browsed-document-num (+ row (* (:page df) (:rows-per-page df)))
:browsed-document document
:document-tab 1))))
(reg-event-db
:set-search-context
(fn [db [_ value]]
(assoc-in db [:document-filter :within] value)))
(reg-event-fx
:refresh-table
(fn [{db :db} _]
{:api ["get-documents"
(assoc (filter-params (:document-filter db))
:corpus (:current-corpus db))
:set-documents]
:db (assoc db :current-filter (:document-filter db))}))
(reg-event-fx
:reset-filters
(fn [{db :db} _]
{:db (assoc db :document-filter {:page 0, :rows-per-page 10, :filters {}})
:dispatch [:refresh-table]}))
(reg-event-fx
:move-page
(fn [{db :db} [_ delta]]
{:db (update-in db [:document-filter :page] + delta)
:dispatch [:refresh-table]}))
(reg-event-fx
:browse-num
(fn [{db :db} [_ n]]
{:api ["get-documents"
(assoc (filter-params (:document-filter db))
:corpus (:current-corpus db)
:offset n :limit 1)
:browse-basic n]}))
(reg-event-fx
:create-area
(fn [{db :db} [_ n]]
(let [params (filter-params (:document-filter db))
name (:new-area db)]
{:api ["create-context" {:name name, :description params, :corpus (:current-corpus db)}]
:db (update-in db [:contexts] conj [name params])})))
(defn area-creator []
[:div
[:input {:type "text", :placeholder "Wpisz nazwę obszaru", :on-change (dispatch-value :set-new-area)}]
[:button {:on-click #(do (dispatch [:create-area])
(dispatch [:set-modal nil]))}
"Utwórz obszar"]])
(defn search []
(let [contexts (subscribe [:contexts])
phrase (subscribe [:phrase])
advanced (subscribe [:advanced])]
[:form {:class "search" :on-submit #(do (.preventDefault %1) (dispatch [:refresh-table]) false)}
[:div {:class "group"}
[:input {:class "phrase", :type "text", :autoFocus true, :placeholder "Wpisz szukaną frazę", :on-change (dispatch-value :set-phrase), :value @phrase}]]
[:div {:class "group"}
[:input {:type "submit", :value "SzPI:NAME:<NAME>END_PI", :class "search-button"}]
[:a {:class "advanced" :href "#" :on-click #(dispatch [:set-advanced (not @advanced)])} (if @advanced "« Ukryj zaawansowane opcje" "Pokaż zaawansowane opcje »")]]
(if @advanced
[:div {:class "group"}
"Obszar: "
(into [:select {:on-change (dispatch-value :set-search-context)}
[:option "Cały korpus"]]
(for [[opt _] @contexts]
[:option {:value opt, #_:selected #_(= (:within @search-params) opt)} opt]))])
(if @advanced
[:div {:class "group"}
[:button {:on-click #(dispatch [:set-modal area-creator])} "Utwórz obszar"]
[:button {:on-click #(dispatch [:reset-filters])} "Resetuj filtry"]])]))
(defn document-summary
[]
(let [{:keys [phrase within filters page]} @(subscribe [:current-filter])]
[:p.summary
(if (seq phrase)
[:span "Dokumenty zawierające frazę „" [:b phrase] "”"]
"Wszystkie dokumenty")
" w "
(if (or (nil? within) (= within "Cały korpus"))
"całym korpusie"
[:span "obszarze " [:b [:i within]]])
[:br]
"Strona " (inc page)
[:br]
(if (seq filters)
[:span
"Aktywne filtry: " [:i (string/join ", " (keys filters))]
" ("
[:a {:href "#" :on-click #(dispatch [:reset-filters])} "resetuj"]
")"]
"Brak aktywnych filtrów")
]))
(defn pagination []
(let [document-filter (subscribe [:document-filter])]
[:div {:class "pagination", :style {:width @(subscribe [:table-width])}}
[:button (if (> (:page @document-filter) 0)
{:on-click #(dispatch [:move-page -1])}
{:disabled true}) "<<"]
[document-summary]
[:button {:on-click #(dispatch [:move-page 1])} ">>"]]))
(defn top-overlay []
[:div
[search]])
(defn filter-checkboxes-content [labels key]
(let [document-filter (subscribe [:document-filter])
cnt (count labels)
flt (get-in @document-filter [:filters key])]
(into [:div {:class "checkboxes"}]
(map-indexed (fn [n label]
[:div
[:input {:key (str "PI:KEY:<KEY>END_PI n)
:type "checkbox"
:checked (if flt (boolean (flt n)) true)
:on-change #(dispatch [:checkboxes-toggle key n cnt])}]
[:label {:key (str "filter-lbl-" n)} label]])
labels))))
(defn filter-header [key]
[:h1 (str "Filtruj: " (name key))])
(defn filter-checkboxes [labels key]
[:div {:class "filter filter-cb"}
[filter-header key]
[filter-checkboxes-content labels key]
[:div {:class "buttons"}
[:button {:on-click #(dispatch [:checkboxes-set-all key])} "Zaznacz wszystkie"]
[:button {:on-click #(dispatch [:checkboxes-clear-all key])} "Wyczyść wszystkie"]
[:button {:on-click #(do (dispatch [:set-modal nil])
(dispatch [:refresh-table]))} "OK"]]])
(defn filter-text [key]
(let [filter (subscribe [:document-filter])]
[:div {:class "filter filter-text"}
[filter-header key]
[:input {:type "text"
:value (get-in @filter [:filters key])
:on-change (dispatch-value :set-filter key)}]
[:button {:on-click #(do (dispatch [:set-modal nil])
(dispatch [:refresh-table]))} "OK"]]))
(defn filter-widget [col valset]
(if valset
(filter-checkboxes valset col)
(filter-text col)))
(defn main-table-header [col title]
(let [document-table (subscribe [:document-table])
[col-id valset] (nth (:metadata @document-table) col)]
[:a {:href "#"
:on-click #(dispatch [:set-modal (partial filter-widget col-id valset)])} title]))
(defn main-table-proper []
(table :document-table
:cell-renderer (fn [{:keys [data]} row col]
(let [val (nth (nth data row) (inc col))]
[:a {:href "#"
:on-click #(dispatch [:browse row (nth data row)])
:title val} val]))
:header-renderer (fn [col title]
[main-table-header col title])))
(defn main-table []
[:div {:class "fullsize"}
[pagination]
[main-table-proper]])
(defn iframe-matches []
(let [iframe (js/document.getElementById "browsed")
doc (-> iframe .-contentWindow .-document)
matches (.getElementsByClassName doc "match")]
(vec (js/Array.prototype.slice.call matches))))
(defn indices [pred coll]
(keep-indexed #(when (pred %2) %1) coll))
(defn advance-match [delta]
(let [matches (iframe-matches)
current (first (indices #(.contains (.-classList %) "selected") matches))
nxt (-> (if current (+ current delta) 0) (max 0) (min (dec (count matches))))]
(when (seq matches)
(when current
(.remove (.-classList (matches current)) "selected"))
(.add (.-classList (matches nxt)) "selected")
(.scrollIntoView (matches nxt)))))
(defn advance-document-button [label title delta]
(let [browsed-document-num (subscribe [:browsed-document-num])]
[:button {:title title
:on-click #(dispatch [:browse-num (+ @browsed-document-num delta)])}
label]))
(reg-sub :meta-keys
#(subscribe [:document-table])
#(map (comp keyword first) (:metadata %1)))
(defn meta-item [key]
(let [meta-keys (subscribe [:meta-keys])
browsed-document (subscribe [:browsed-document])]
(when-let [doc @browsed-document]
(let [meta-map (zipmap @meta-keys (rest doc))]
[:span (meta-map key)]))))
(defn vignette
[]
(let [v @(subscribe [:vignette])]
(if v
(postwalk #(if (and (keyword? %) (= (namespace %) "meta"))
[meta-item (keyword (name %))]
%)
v)
[:div.vignette
[:table
(for [k @(subscribe [:meta-keys])]
[:tr [:th k] [:td [meta-item k]]])]])))
(defn document-browser []
(let [browsed-document (subscribe [:browsed-document])
document-filter (subscribe [:document-filter])
corpus (subscribe [:current-corpus])]
(if-let [doc @browsed-document]
[:table {:class "fixed-top document"}
[:tbody
[:tr {:class "navigation"}
[:td
[advance-document-button "<<" "Poprzedni dokument" -1]
(when (:phrase @document-filter)
[:button {:on-click #(advance-match -1) :title "Poprzednie wystąpienie"} "<"])]
[:td [vignette]]
[:td
(when (:phrase @document-filter)
[:button {:on-click #(advance-match 1) :title "Następne wystąpienie"} ">"])
[advance-document-button ">>" "Następny dokument" 1]]]
[:tr [:td {:col-span 3}
[:div
[:iframe {:id "browsed"
:on-load #(let [slf (js/document.getElementById "browsed")
doc (-> slf .-contentWindow .-document)]
nil #_
(js/alert (str "Found matches: " (.-length (.getElementsByClassName doc "match")))))
:src
(if-let [phrase (:phrase @document-filter)]
(str "/highlight/" @corpus "/" phrase "/" (first doc))
(str "/corpus/" @corpus "/" (first doc)))}]]]]]]
[:h2 "Brak dokumentu do wyświetlenia."])))
(defn document-table []
[:table {:class "fixed-top documents"}
[:tbody
[:tr [:td [top-overlay]]]
[:tr [:td [tabbar :document-tab
["Lista dokumentów" [main-table]
"Pojedynczy dokument" [document-browser]]]]]]])
|
[
{
"context": ";; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.be>\n;; All rights reserved.\n;;\n;; Redi",
"end": 40,
"score": 0.9998818635940552,
"start": 27,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.be>\n;; All rights reserved.\n;;\n;; Redistribution and",
"end": 54,
"score": 0.9999322891235352,
"start": 42,
"tag": "EMAIL",
"value": "niwi@niwi.be"
}
] | src/suricatta/proto.clj | smaant-test2-rename10/suricatta | 0 | ;; Copyright (c) 2014-2015 Andrey Antukh <niwi@niwi.be>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns suricatta.proto)
(defprotocol IContextHolder
(-get-context [_] "Get jooq context with attached configuration")
(-get-config [_] "Get attached configuration."))
(defprotocol IConnectionFactory
(-connection [_] "Create a jdbc connection."))
(defprotocol IExecute
(-execute [q ctx] "Execute a query and return a number of rows affected."))
(defprotocol IFetch
(-fetch [q ctx opts] "Fetch eagerly results executing query."))
(defprotocol IFetchLazy
(-fetch-lazy [q ctx opts] "Fetch lazy results executing query."))
(defprotocol IRenderer
(-get-sql [_ type dialect] "Render a query sql into a string.")
(-get-bind-values [_] "Get query bind values."))
(defprotocol IQuery
(-query [_ ctx] "Build a query."))
;; Custom data types binding protocols
(defprotocol IParamContext
"A lightweight abstraction for access
to the basic properties on the render/bind
context instances."
(-get-statement [_] "Get the prepared statement if it is awailable.")
(-get-next-bindindex [_] "Get the next bind index (WARN: side effectful)")
(-render-inline? [_] "Return true in case the context is setup for inline."))
(defprotocol IParamType
"A basic abstraction for adapt user defined
types to work within suricatta."
(-render [_ ctx] "Render the value as sql.")
(-bind [_ ctx] "Bind param value to the prepared statement."))
(defprotocol ISQLType
"An abstraction for handle the backward type
conversion: from SQL->User."
(-convert [_] "Convert sql type to user type."))
| 45721 | ;; Copyright (c) 2014-2015 <NAME> <<EMAIL>>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns suricatta.proto)
(defprotocol IContextHolder
(-get-context [_] "Get jooq context with attached configuration")
(-get-config [_] "Get attached configuration."))
(defprotocol IConnectionFactory
(-connection [_] "Create a jdbc connection."))
(defprotocol IExecute
(-execute [q ctx] "Execute a query and return a number of rows affected."))
(defprotocol IFetch
(-fetch [q ctx opts] "Fetch eagerly results executing query."))
(defprotocol IFetchLazy
(-fetch-lazy [q ctx opts] "Fetch lazy results executing query."))
(defprotocol IRenderer
(-get-sql [_ type dialect] "Render a query sql into a string.")
(-get-bind-values [_] "Get query bind values."))
(defprotocol IQuery
(-query [_ ctx] "Build a query."))
;; Custom data types binding protocols
(defprotocol IParamContext
"A lightweight abstraction for access
to the basic properties on the render/bind
context instances."
(-get-statement [_] "Get the prepared statement if it is awailable.")
(-get-next-bindindex [_] "Get the next bind index (WARN: side effectful)")
(-render-inline? [_] "Return true in case the context is setup for inline."))
(defprotocol IParamType
"A basic abstraction for adapt user defined
types to work within suricatta."
(-render [_ ctx] "Render the value as sql.")
(-bind [_ ctx] "Bind param value to the prepared statement."))
(defprotocol ISQLType
"An abstraction for handle the backward type
conversion: from SQL->User."
(-convert [_] "Convert sql type to user type."))
| true | ;; Copyright (c) 2014-2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns suricatta.proto)
(defprotocol IContextHolder
(-get-context [_] "Get jooq context with attached configuration")
(-get-config [_] "Get attached configuration."))
(defprotocol IConnectionFactory
(-connection [_] "Create a jdbc connection."))
(defprotocol IExecute
(-execute [q ctx] "Execute a query and return a number of rows affected."))
(defprotocol IFetch
(-fetch [q ctx opts] "Fetch eagerly results executing query."))
(defprotocol IFetchLazy
(-fetch-lazy [q ctx opts] "Fetch lazy results executing query."))
(defprotocol IRenderer
(-get-sql [_ type dialect] "Render a query sql into a string.")
(-get-bind-values [_] "Get query bind values."))
(defprotocol IQuery
(-query [_ ctx] "Build a query."))
;; Custom data types binding protocols
(defprotocol IParamContext
"A lightweight abstraction for access
to the basic properties on the render/bind
context instances."
(-get-statement [_] "Get the prepared statement if it is awailable.")
(-get-next-bindindex [_] "Get the next bind index (WARN: side effectful)")
(-render-inline? [_] "Return true in case the context is setup for inline."))
(defprotocol IParamType
"A basic abstraction for adapt user defined
types to work within suricatta."
(-render [_ ctx] "Render the value as sql.")
(-bind [_ ctx] "Bind param value to the prepared statement."))
(defprotocol ISQLType
"An abstraction for handle the backward type
conversion: from SQL->User."
(-convert [_] "Convert sql type to user type."))
|
[
{
"context": " \"VIEW\"}]})\n\n(def valid-up-cred\n {:username \"myusername\"\n :password \"mypassword\"})\n\n(def valid-sshkey-c",
"end": 1141,
"score": 0.999408483505249,
"start": 1131,
"tag": "USERNAME",
"value": "myusername"
},
{
"context": "d-up-cred\n {:username \"myusername\"\n :password \"mypassword\"})\n\n(def valid-sshkey-cred\n {:publicKey \"DUMMY K",
"end": 1167,
"score": 0.9992051720619202,
"start": 1157,
"tag": "PASSWORD",
"value": "mypassword"
}
] | jar/src/test/clojure/eu/stratuslab/cimi/resources/credential_template_schema_test.clj | StratusLab/cimi | 0 | ;
; Copyright 2014 Centre National de la Recherche Scientifique (CNRS)
;
; 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 eu.stratuslab.cimi.resources.credential-template-schema-test
(:require
[eu.stratuslab.cimi.resources.credential-template :refer :all]
[schema.core :as s]
[expectations :refer :all]
[eu.stratuslab.cimi.resources.utils.utils :as u]))
(def valid-acl {:owner {:principal "::ADMIN"
:type "ROLE"}
:rules [{:principal "::ANON"
:type "ROLE"
:right "VIEW"}]})
(def valid-up-cred
{:username "myusername"
:password "mypassword"})
(def valid-sshkey-cred
{:publicKey "DUMMY KEY SHOULD BE BASE64"})
(expect nil? (s/check UsernamePasswordCredential valid-up-cred))
(expect (s/check UsernamePasswordCredential (dissoc valid-up-cred :username)))
(expect (s/check UsernamePasswordCredential (dissoc valid-up-cred :password)))
(expect (s/check UsernamePasswordCredential (assoc valid-up-cred :invalid "BAD")))
(expect nil? (s/check SSHPublicKeyCredential valid-sshkey-cred))
(expect (s/check SSHPublicKeyCredential (dissoc valid-sshkey-cred :publicKey)))
(expect (s/check SSHPublicKeyCredential (assoc valid-sshkey-cred :invalid "BAD")))
(let [uri (str resource-name "/" (u/random-uuid))
tpl (assoc valid-up-cred
:id uri
:acl valid-acl
:resourceURI resource-uri
:created "1964-08-25T10:00:00.0Z"
:updated "1964-08-25T10:00:00.0Z")]
(println (s/check CredentialTemplate tpl))
(expect nil? (s/check CredentialTemplate tpl))
(expect (s/check CredentialTemplate (assoc tpl :invalid "BAD"))))
(let [uri (str resource-name "/" (u/random-uuid))
tpl (assoc valid-sshkey-cred
:id uri
:acl valid-acl
:resourceURI resource-uri
:created "1964-08-25T10:00:00.0Z"
:updated "1964-08-25T10:00:00.0Z")]
(println (s/check CredentialTemplate tpl))
(expect nil? (s/check CredentialTemplate tpl))
(expect (s/check CredentialTemplate (assoc tpl :invalid "BAD"))))
(run-tests [*ns*])
| 71270 | ;
; Copyright 2014 Centre National de la Recherche Scientifique (CNRS)
;
; 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 eu.stratuslab.cimi.resources.credential-template-schema-test
(:require
[eu.stratuslab.cimi.resources.credential-template :refer :all]
[schema.core :as s]
[expectations :refer :all]
[eu.stratuslab.cimi.resources.utils.utils :as u]))
(def valid-acl {:owner {:principal "::ADMIN"
:type "ROLE"}
:rules [{:principal "::ANON"
:type "ROLE"
:right "VIEW"}]})
(def valid-up-cred
{:username "myusername"
:password "<PASSWORD>"})
(def valid-sshkey-cred
{:publicKey "DUMMY KEY SHOULD BE BASE64"})
(expect nil? (s/check UsernamePasswordCredential valid-up-cred))
(expect (s/check UsernamePasswordCredential (dissoc valid-up-cred :username)))
(expect (s/check UsernamePasswordCredential (dissoc valid-up-cred :password)))
(expect (s/check UsernamePasswordCredential (assoc valid-up-cred :invalid "BAD")))
(expect nil? (s/check SSHPublicKeyCredential valid-sshkey-cred))
(expect (s/check SSHPublicKeyCredential (dissoc valid-sshkey-cred :publicKey)))
(expect (s/check SSHPublicKeyCredential (assoc valid-sshkey-cred :invalid "BAD")))
(let [uri (str resource-name "/" (u/random-uuid))
tpl (assoc valid-up-cred
:id uri
:acl valid-acl
:resourceURI resource-uri
:created "1964-08-25T10:00:00.0Z"
:updated "1964-08-25T10:00:00.0Z")]
(println (s/check CredentialTemplate tpl))
(expect nil? (s/check CredentialTemplate tpl))
(expect (s/check CredentialTemplate (assoc tpl :invalid "BAD"))))
(let [uri (str resource-name "/" (u/random-uuid))
tpl (assoc valid-sshkey-cred
:id uri
:acl valid-acl
:resourceURI resource-uri
:created "1964-08-25T10:00:00.0Z"
:updated "1964-08-25T10:00:00.0Z")]
(println (s/check CredentialTemplate tpl))
(expect nil? (s/check CredentialTemplate tpl))
(expect (s/check CredentialTemplate (assoc tpl :invalid "BAD"))))
(run-tests [*ns*])
| true | ;
; Copyright 2014 Centre National de la Recherche Scientifique (CNRS)
;
; 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 eu.stratuslab.cimi.resources.credential-template-schema-test
(:require
[eu.stratuslab.cimi.resources.credential-template :refer :all]
[schema.core :as s]
[expectations :refer :all]
[eu.stratuslab.cimi.resources.utils.utils :as u]))
(def valid-acl {:owner {:principal "::ADMIN"
:type "ROLE"}
:rules [{:principal "::ANON"
:type "ROLE"
:right "VIEW"}]})
(def valid-up-cred
{:username "myusername"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(def valid-sshkey-cred
{:publicKey "DUMMY KEY SHOULD BE BASE64"})
(expect nil? (s/check UsernamePasswordCredential valid-up-cred))
(expect (s/check UsernamePasswordCredential (dissoc valid-up-cred :username)))
(expect (s/check UsernamePasswordCredential (dissoc valid-up-cred :password)))
(expect (s/check UsernamePasswordCredential (assoc valid-up-cred :invalid "BAD")))
(expect nil? (s/check SSHPublicKeyCredential valid-sshkey-cred))
(expect (s/check SSHPublicKeyCredential (dissoc valid-sshkey-cred :publicKey)))
(expect (s/check SSHPublicKeyCredential (assoc valid-sshkey-cred :invalid "BAD")))
(let [uri (str resource-name "/" (u/random-uuid))
tpl (assoc valid-up-cred
:id uri
:acl valid-acl
:resourceURI resource-uri
:created "1964-08-25T10:00:00.0Z"
:updated "1964-08-25T10:00:00.0Z")]
(println (s/check CredentialTemplate tpl))
(expect nil? (s/check CredentialTemplate tpl))
(expect (s/check CredentialTemplate (assoc tpl :invalid "BAD"))))
(let [uri (str resource-name "/" (u/random-uuid))
tpl (assoc valid-sshkey-cred
:id uri
:acl valid-acl
:resourceURI resource-uri
:created "1964-08-25T10:00:00.0Z"
:updated "1964-08-25T10:00:00.0Z")]
(println (s/check CredentialTemplate tpl))
(expect nil? (s/check CredentialTemplate tpl))
(expect (s/check CredentialTemplate (assoc tpl :invalid "BAD"))))
(run-tests [*ns*])
|
[
{
"context": ";; \"roles\": [\"local-heroes\"],\n;; \"names\": [\"rebecca\", \"pete\"]\n;; },\n;; \"readers\": {\n;; \"roles\": ",
"end": 1227,
"score": 0.9995031952857971,
"start": 1220,
"tag": "NAME",
"value": "rebecca"
},
{
"context": "s\": [\"local-heroes\"],\n;; \"names\": [\"rebecca\", \"pete\"]\n;; },\n;; \"readers\": {\n;; \"roles\": [\"lolcat",
"end": 1235,
"score": 0.999514102935791,
"start": 1231,
"tag": "NAME",
"value": "pete"
},
{
"context": "; \"roles\": [\"lolcat-heroes\"],\n;; \"names\": [\"simon\", \"ben\", \"james\"]\n;; }\n;;}\n(defn security\n \"Get",
"end": 1318,
"score": 0.9997321367263794,
"start": 1313,
"tag": "NAME",
"value": "simon"
},
{
"context": "es\": [\"lolcat-heroes\"],\n;; \"names\": [\"simon\", \"ben\", \"james\"]\n;; }\n;;}\n(defn security\n \"Get or set",
"end": 1325,
"score": 0.999656081199646,
"start": 1322,
"tag": "NAME",
"value": "ben"
},
{
"context": "lolcat-heroes\"],\n;; \"names\": [\"simon\", \"ben\", \"james\"]\n;; }\n;;}\n(defn security\n \"Get or set security",
"end": 1334,
"score": 0.9993586540222168,
"start": 1329,
"tag": "NAME",
"value": "james"
}
] | src/joiner/admin.clj | jalpedersen/couch-joiner | 0 | (ns joiner.admin
(:require [com.ashafa.clutch.utils :as utils]
[com.ashafa.clutch :as clutch]
[com.ashafa.clutch.http-client :as http])
(:use [joiner.core]))
(defn create-admin [username password]
(http/couchdb-request :put
(database-url (str "_config/admins/" username))
:data-type "text/plain"
:data (str "\"" password "\"")))
(defn delete-admin [username]
(http/couchdb-request :delete
(database-url (str "_config/admins/" username))))
(defn get-admins []
(http/couchdb-request :get
(database-url "_config/admins/")))
(defn get-configuration []
(http/couchdb-request :get
(database-url "_config")))
(defn- get-security []
"Get security settings for current database"
(clutch/get-document "_security"))
(defn- set-security [security-settings]
"Set security settings for current database"
(http/couchdb-request :put
(utils/url (clutch/get-database) "_security")
:data security-settings))
;;Example settings:
;;{
;; "admins": {
;; "roles": ["local-heroes"],
;; "names": ["rebecca", "pete"]
;; },
;; "readers": {
;; "roles": ["lolcat-heroes"],
;; "names": ["simon", "ben", "james"]
;; }
;;}
(defn security
"Get or set security settings for current database"
([]
(get-security))
([settings]
(set-security settings)))
(defn compact [& [db]]
(let [database (if (nil? db) (clutch/get-database) db)]
(http/couchdb-request :post
(utils/url db "_compact"))))
| 65714 | (ns joiner.admin
(:require [com.ashafa.clutch.utils :as utils]
[com.ashafa.clutch :as clutch]
[com.ashafa.clutch.http-client :as http])
(:use [joiner.core]))
(defn create-admin [username password]
(http/couchdb-request :put
(database-url (str "_config/admins/" username))
:data-type "text/plain"
:data (str "\"" password "\"")))
(defn delete-admin [username]
(http/couchdb-request :delete
(database-url (str "_config/admins/" username))))
(defn get-admins []
(http/couchdb-request :get
(database-url "_config/admins/")))
(defn get-configuration []
(http/couchdb-request :get
(database-url "_config")))
(defn- get-security []
"Get security settings for current database"
(clutch/get-document "_security"))
(defn- set-security [security-settings]
"Set security settings for current database"
(http/couchdb-request :put
(utils/url (clutch/get-database) "_security")
:data security-settings))
;;Example settings:
;;{
;; "admins": {
;; "roles": ["local-heroes"],
;; "names": ["<NAME>", "<NAME>"]
;; },
;; "readers": {
;; "roles": ["lolcat-heroes"],
;; "names": ["<NAME>", "<NAME>", "<NAME>"]
;; }
;;}
(defn security
"Get or set security settings for current database"
([]
(get-security))
([settings]
(set-security settings)))
(defn compact [& [db]]
(let [database (if (nil? db) (clutch/get-database) db)]
(http/couchdb-request :post
(utils/url db "_compact"))))
| true | (ns joiner.admin
(:require [com.ashafa.clutch.utils :as utils]
[com.ashafa.clutch :as clutch]
[com.ashafa.clutch.http-client :as http])
(:use [joiner.core]))
(defn create-admin [username password]
(http/couchdb-request :put
(database-url (str "_config/admins/" username))
:data-type "text/plain"
:data (str "\"" password "\"")))
(defn delete-admin [username]
(http/couchdb-request :delete
(database-url (str "_config/admins/" username))))
(defn get-admins []
(http/couchdb-request :get
(database-url "_config/admins/")))
(defn get-configuration []
(http/couchdb-request :get
(database-url "_config")))
(defn- get-security []
"Get security settings for current database"
(clutch/get-document "_security"))
(defn- set-security [security-settings]
"Set security settings for current database"
(http/couchdb-request :put
(utils/url (clutch/get-database) "_security")
:data security-settings))
;;Example settings:
;;{
;; "admins": {
;; "roles": ["local-heroes"],
;; "names": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
;; },
;; "readers": {
;; "roles": ["lolcat-heroes"],
;; "names": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
;; }
;;}
(defn security
"Get or set security settings for current database"
([]
(get-security))
([settings]
(set-security settings)))
(defn compact [& [db]]
(let [database (if (nil? db) (clutch/get-database) db)]
(http/couchdb-request :post
(utils/url db "_compact"))))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-11-23\"}\n \n taiga.scripts.profi",
"end": 105,
"score": 0.9998783469200134,
"start": 87,
"tag": "NAME",
"value": "John Alan McDonald"
}
] | src/scripts/clojure/taiga/scripts/profile/split/scored.clj | wahpenayo/taiga | 4 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "John Alan McDonald" :date "2016-11-23"}
taiga.scripts.profile.split.scored
(:require [taiga.split.numerical.categorical.scored :as scored]
[taiga.scripts.profile.split.defs :as defs]))
;; clj src\scripts\clojure\taiga\scripts\profile\split\scored.clj
;;------------------------------------------------------------------------------
(println "scored")
(defs/bench scored/split (defs/primate-options))
(defs/bench scored/split (defs/kolor-options))
;;------------------------------------------------------------------------------
| 58532 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<NAME>" :date "2016-11-23"}
taiga.scripts.profile.split.scored
(:require [taiga.split.numerical.categorical.scored :as scored]
[taiga.scripts.profile.split.defs :as defs]))
;; clj src\scripts\clojure\taiga\scripts\profile\split\scored.clj
;;------------------------------------------------------------------------------
(println "scored")
(defs/bench scored/split (defs/primate-options))
(defs/bench scored/split (defs/kolor-options))
;;------------------------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-11-23"}
taiga.scripts.profile.split.scored
(:require [taiga.split.numerical.categorical.scored :as scored]
[taiga.scripts.profile.split.defs :as defs]))
;; clj src\scripts\clojure\taiga\scripts\profile\split\scored.clj
;;------------------------------------------------------------------------------
(println "scored")
(defs/bench scored/split (defs/primate-options))
(defs/bench scored/split (defs/kolor-options))
;;------------------------------------------------------------------------------
|
[
{
"context": "t/unit \"METERS\")\n\n (s/valid? :my-app/pet {:name \"bla\" :dob #inst \"2000-10-10\" :race \"cat\"})\n\n (s/vali",
"end": 14856,
"score": 0.9211703538894653,
"start": 14853,
"tag": "NAME",
"value": "bla"
},
{
"context": "\"cat\"})\n\n (s/valid? :my-app/person {:first-name \"Tiago\"\n :last-name \"Luchini\"",
"end": 14943,
"score": 0.9997588396072388,
"start": 14938,
"tag": "NAME",
"value": "Tiago"
},
{
"context": "e \"Tiago\"\n :last-name \"Luchini\"\n :gender \"MALE\"\n ",
"end": 14992,
"score": 0.9996076226234436,
"start": 14985,
"tag": "NAME",
"value": "Luchini"
},
{
"context": "1.78})\n\n (s/explain :my-app/person {:first-name \"Tiago\"\n :last-name \"Luchini",
"end": 15128,
"score": 0.9997717142105103,
"start": 15123,
"tag": "NAME",
"value": "Tiago"
},
{
"context": " \"Tiago\"\n :last-name \"Luchini\"\n :gender \"MALE\"\n ",
"end": 15178,
"score": 0.999630868434906,
"start": 15171,
"tag": "NAME",
"value": "Luchini"
},
{
"context": "d? :my-app.query-root/search\n [{:name \"Lexie\"\n :dob #inst \"2016-10-10\"\n ",
"end": 15333,
"score": 0.9997169971466064,
"start": 15328,
"tag": "NAME",
"value": "Lexie"
},
{
"context": " :race \"Dog\"}\n {:first-name \"Tiago\"\n :last-name \"Luchini\"\n ",
"end": 15432,
"score": 0.9997876882553101,
"start": 15427,
"tag": "NAME",
"value": "Tiago"
},
{
"context": " {:first-name \"Tiago\"\n :last-name \"Luchini\"\n :gender \"MALE\"\n :heig",
"end": 15467,
"score": 0.9997089505195618,
"start": 15460,
"tag": "NAME",
"value": "Luchini"
},
{
"context": "exactly-three-to-five-people\n [{:name \"Name\" :gender \"MALE\"}\n {:name \"Name\" :gend",
"end": 15905,
"score": 0.9794484972953796,
"start": 15901,
"tag": "NAME",
"value": "Name"
},
{
"context": "alid? :my-app.extend-override-entity/email-field \"qwe@asd.com\")\n\n (gen/generate (s/gen :my-app/animal))\n\n (ge",
"end": 16449,
"score": 0.9865443706512451,
"start": 16438,
"tag": "EMAIL",
"value": "qwe@asd.com"
}
] | src/hodur_spec_schema/core.clj | molequedeideias/hodur-spec-schema | 0 | (ns hodur-spec-schema.core
(:require [clojure.spec.alpha :as s]
[datascript.core :as d]
[datascript.query-v3 :as q]
[camel-snake-kebab.core :refer [->kebab-case-string]]))
(defn ^:private get-ids-by-node-type [conn node-type]
(case node-type
:type (d/q '[:find [?e ...]
:in $ ?node-type
:where
[?e :node/type ?node-type]
[?e :spec/tag true]
[?e :type/nature :user]]
@conn node-type)
(d/q '[:find [?e ...]
:in $ ?node-type
:where
[?e :node/type ?node-type]
[?e :spec/tag true]]
@conn node-type)))
(defn ^:private prepend-core-ns [sym]
(when (not (nil? sym))
(if (namespace sym)
sym
(symbol "clojure.core" (str sym)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare get-spec-form)
(defmulti ^:private get-spec-name
(fn [obj opts]
(cond
(and (seqable? obj)
(every? #(= :param (:node/type %)) obj))
:param-group
:default
(:node/type obj))))
(defn ^:private get-spec-entity-name
[type-name
{:keys [prefix]}]
(keyword (name prefix)
(->kebab-case-string type-name)))
(defn ^:private get-spec-field-name
[type-name field-name
{:keys [prefix]}]
(keyword (str (name prefix) "." (->kebab-case-string type-name))
(->kebab-case-string field-name)))
(defn ^:private get-spec-param-name
[type-name field-name param-name
{:keys [prefix]}]
(keyword (str (name prefix) "." (->kebab-case-string type-name) "."
(->kebab-case-string field-name))
(->kebab-case-string param-name)))
(defn ^:private get-spec-param-group-name
[type-name field-name
{:keys [prefix params-postfix group-type] :or {params-postfix "%"} :as opts}]
(keyword (str (name prefix) "." (->kebab-case-string type-name))
(str (->kebab-case-string field-name)
(case group-type
:map ""
:tuple "-ordered")
params-postfix)))
(defmethod get-spec-name :type
[{:keys [type/kebab-case-name]} opts]
(get-spec-entity-name (name kebab-case-name) opts))
(defmethod get-spec-name :field
[{:keys [field/kebab-case-name
field/parent] :as field} opts]
(get-spec-field-name (name (:type/kebab-case-name parent))
(name kebab-case-name)
opts))
(defmethod get-spec-name :param
[param opts]
(let [type-name (-> param :param/parent :field/parent :type/kebab-case-name)
field-name (-> param :param/parent :field/kebab-case-name)
param-name (-> param :param/kebab-case-name)]
(get-spec-param-name type-name
field-name
param-name
opts)))
(defmethod get-spec-name :param-group
[params opts]
(let [type-name (-> params first :param/parent :field/parent :type/kebab-case-name)
field-name (-> params first :param/parent :field/kebab-case-name)]
(get-spec-param-group-name type-name
field-name
opts)))
(defmethod get-spec-name :default
[obj opts]
(if (nil? obj)
nil
(throw (ex-info "Unable to name a spec for object"
{:obj obj}))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn ^:private get-cardinality [dep-obj]
(or (:field/cardinality dep-obj)
(:param/cardinality dep-obj)))
(defn ^:private card-type [dep-obj]
(let [cardinality (get-cardinality dep-obj)]
(when cardinality
(if (and (= 1 (first cardinality))
(= 1 (second cardinality)))
:one
:many))))
(defn ^:private many-cardinality? [dep-obj]
(= :many (card-type dep-obj)))
(defn ^:private one-cardinality? [dep-obj]
(= :one (card-type dep-obj)))
(defmulti ^:private get-spec-form*
(fn [obj opts]
(cond
(:field/optional obj)
:optional-field
(:param/optional obj)
:optional-param
(many-cardinality? obj)
:many-ref
(:type/enum obj)
:enum
(:type/union obj)
:union
(and (:field/name obj)
(-> obj :field/parent :type/enum))
:enum-entry
(:field/union-type obj)
:union-field
(:type/name obj)
:entity
(and (seqable? obj)
(every? #(= :param (:node/type %)) obj))
:param-group
(:field/name obj) ;; simple field, dispatch type name
(-> obj :field/type :type/name)
(:param/name obj) ;; simple param, dispatch type name
(-> obj :param/type :type/name))))
(defn ^:private get-spec-form [obj opts]
(if (map? obj)
(let [{:keys [spec/override spec/extend spec/gen]} obj
override' (prepend-core-ns override)
extend' (prepend-core-ns extend)
gen' (prepend-core-ns gen)
target-form (if override'
override'
(if extend'
(list* `s/and [extend' (get-spec-form* obj opts)])
(get-spec-form* obj opts)))]
(if gen'
(list* `s/with-gen [target-form gen'])
target-form))
(get-spec-form* obj opts)))
(defn ^:private get-counts [obj]
(let [many? (many-cardinality? obj)
card (get-cardinality obj)
from (first card)
to (second card)]
(when many?
(cond-> {}
(= from to)
(assoc :count from)
(and (not= from to)
(not= 'n from))
(assoc :min-count from)
(and (not= from to)
(not= 'n to))
(assoc :max-count to)))))
(defn ^:private get-many-meta-specs [{:keys [spec/distinct spec/kind] :as obj}]
(let [kind' (prepend-core-ns kind)]
(cond-> {}
distinct (assoc :distinct distinct)
kind (assoc :kind kind'))))
(defmethod get-spec-form* :many-ref
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :field/cardinality :param/cardinality) opts)
other-nodes (merge (get-counts obj)
(get-many-meta-specs obj))]
(list* `s/coll-of
(reduce-kv (fn [c k v]
(conj c k v))
[entity-spec] other-nodes))))
(defmethod get-spec-form* :enum
[{:keys [field/_parent]} opts]
(list* `s/or
(reduce (fn [c {:keys [field/kebab-case-name] :as field}]
(conj c kebab-case-name (get-spec-name field opts)))
[] _parent)))
(defmethod get-spec-form* :union
[{:keys [field/_parent]} opts]
(list* `s/or
(reduce (fn [c {:keys [field/kebab-case-name] :as field}]
(conj c kebab-case-name (get-spec-name field opts)))
[] _parent)))
(defmethod get-spec-form* :enum-entry
[{:keys [field/name]} _]
`#(= ~name (when (or (string? %)
(keyword? %))
(name %))))
(defmethod get-spec-form* :union-field
[{:keys [field/union-type]} opts]
(get-spec-name union-type opts))
(defmethod get-spec-form* :optional-param
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :param/optional) opts)]
(list* `s/nilable [entity-spec])))
(defmethod get-spec-form* :optional-field
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :field/optional) opts)]
(list* `s/nilable [entity-spec])))
(defmethod get-spec-form* :entity
[{:keys [field/_parent type/implements]} opts]
(let [filter-fn (fn [pred c]
(->> c
(filter :spec/tag)
(filter pred)
(map #(get-spec-name % opts))
vec))
req (filter-fn #(not (:field/optional %)) _parent)
opt (filter-fn #(:field/optional %) _parent)
form `(s/keys :req-un ~req :opt-un ~opt)]
(if implements
(list* `s/and
(reduce (fn [c interface]
(conj c (get-spec-name interface opts)))
[form] implements))
form)))
(defmethod get-spec-form* :param-group
[params {:keys [group-type] :as opts}]
(let [filter-fn (fn [pred c]
(->> c
(filter pred)
(map #(get-spec-name % opts))
vec))
req (filter-fn #(not (:param/optional %)) params)
opt (filter-fn #(:param/optional %) params)]
(case group-type
:map `(s/keys :req-un ~req :opt-un ~opt)
:tuple (list* `s/tuple (map #(get-spec-name % opts) params)))))
(defmethod get-spec-form* "String" [_ _] `string?)
(defmethod get-spec-form* "ID" [_ _] `string?)
(defmethod get-spec-form* "Integer" [_ _] `integer?)
(defmethod get-spec-form* "Boolean" [_ _] `boolean?)
(defmethod get-spec-form* "Float" [_ _] `float?)
(defmethod get-spec-form* "DateTime" [_ _] `inst?)
(defmethod get-spec-form* :default [obj opts]
(let [ref-type (or (-> obj :field/type)
(-> obj :param/type))]
(if ref-type
(get-spec-name ref-type opts)
(throw (ex-info "Unable to create a spec form for object"
{:obj obj})))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti ^:private pull-node
(fn [conn node]
(:node/type node)))
(def ^:private param-selector
'[*
{:param/parent [*
{:field/parent [*]}]}
{:param/type [*]}])
(def ^:private field-selector
`[~'*
{:param/_parent ~param-selector}
{:field/parent ~'[*]}
{:field/type ~'[*]}
{:field/union-type ~'[*]}])
(def ^:private type-selector
`[~'* {:type/implements ~'[*]
:field/_parent ~field-selector}])
(defmethod pull-node :type
[conn {:keys [db/id]}]
(d/pull @conn type-selector id))
(defmethod pull-node :field
[conn {:keys [db/id]}]
(d/pull @conn field-selector id))
(defmethod pull-node :param
[conn {:keys [db/id]}]
(d/pull @conn param-selector id))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn ^:private build-aliases-spec [conn opts]
(let [eids (-> (q/q '[:find ?e
:where
[?e :spec/tag true]
(or [?e :spec/alias]
[?e :spec/aliases])]
@conn)
vec flatten)
objs (d/pull-many @conn '[*] eids)]
(reduce (fn [c {:keys [spec/alias spec/aliases] :as obj}]
(let [aliases' (or aliases alias)
aliases'' (if (seqable? aliases') aliases' [aliases'])
node (pull-node conn obj)]
(into c (map #(hash-map % (get-spec-name node opts))
aliases''))))
[] objs)))
(defn ^:private build-param-group-specs [conn group-type opts]
(let [eids (-> (q/q '[:find ?f
:where
[_ :param/parent ?f]
[?f :spec/tag true]]
@conn)
vec flatten)
objs (d/pull-many @conn '[{:param/_parent [:db/id :node/type]}] eids)]
(reduce (fn [c {:keys [param/_parent] :as field}]
(let [nodes (map #(pull-node conn %) _parent)
opts' (assoc opts :group-type group-type)]
(conj c (hash-map (get-spec-name nodes opts')
(get-spec-form nodes opts')))))
[] objs)))
(defn ^:private build-dummy-types-specs [conn opts]
(let [eids (get-ids-by-node-type conn :type)
objs (d/pull-many @conn '[*] eids)]
(reduce (fn [c obj]
(conj c (hash-map (get-spec-name obj opts)
'any?)))
[] objs)))
(defn ^:private build-node-spec [conn node opts]
(-> conn
(pull-node node)
(#(hash-map (get-spec-name % opts)
(get-spec-form % opts)))))
(defn ^:private build-by-type-specs [conn node-type opts]
(let [eids (get-ids-by-node-type conn node-type)
nodes (d/pull-many @conn [:db/id :node/type] eids)]
(map #(build-node-spec conn % opts) nodes)))
(defn ^:private compile-all
[conn opts]
(let [dummy-types-specs (build-dummy-types-specs conn opts)
params-specs (build-by-type-specs conn :param opts)
field-specs (build-by-type-specs conn :field opts)
type-specs (build-by-type-specs conn :type opts)
aliases-specs (build-aliases-spec conn opts)
param-groups-specs (build-param-group-specs conn :map opts)
param-groups-ordered-specs (build-param-group-specs conn :tuple opts)]
(->> (concat dummy-types-specs
params-specs
field-specs
type-specs
aliases-specs
param-groups-specs
param-groups-ordered-specs)
(mapv (fn [entry]
(let [k (first (keys entry))
v (first (vals entry))]
#_(do (println " - " k)
(println " =>" v)
(println " "))
`(s/def ~k ~v)))))))
(defn ^:private eval-default-prefix []
(eval '(str (ns-name *ns*))))
(defn ^:private default-prefix []
(str (ns-name *ns*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn schema
([conn]
(schema conn nil))
([conn {:keys [prefix] :as opts}]
(let [opts' (if-not prefix (assoc opts :prefix (default-prefix)) opts)]
(compile-all conn opts'))))
(defmacro defspecs
([conn]
`(defspecs ~conn nil))
([conn {:keys [prefix] :as opts}]
(let [opts# (if-not prefix (assoc opts :prefix (eval-default-prefix)) (eval opts))
conn# (eval conn)]
(mapv (fn [form] form)
(schema conn# opts#)))))
(comment
(require '[clojure.spec.gen.alpha :as gen])
(require '[hodur-engine.core :as engine])
(require 'test-fns)
(use 'core-test))
(comment
(def meta-db (engine/init-schema basic-schema
#_cardinality-schema
#_aliases-schema
#_extend-override-schema))
(let [s (schema meta-db {:prefix :my-app})]
#_(clojure.pprint/pprint s)))
(comment
(defspecs meta-db {:prefix :my-app})
(count (schema meta-db {:prefix :my-app}))
(count (filter #(or (clojure.string/starts-with? (namespace %) "my-app")
(clojure.string/starts-with? (namespace %) "beings")
(clojure.string/starts-with? (namespace %) "my-entity")
(clojure.string/starts-with? (namespace %) "my-field")
(clojure.string/starts-with? (namespace %) "my-param"))
(keys (s/registry))))
(s/valid? :my-app.person.height/unit "METERS")
(s/valid? :my-app/pet {:name "bla" :dob #inst "2000-10-10" :race "cat"})
(s/valid? :my-app/person {:first-name "Tiago"
:last-name "Luchini"
:gender "MALE"
:height 1.78})
(s/explain :my-app/person {:first-name "Tiago"
:last-name "Luchini"
:gender "MALE"
:height 1.78})
(s/valid? :my-app.query-root/search
[{:name "Lexie"
:dob #inst "2016-10-10"
:race "Dog"}
{:first-name "Tiago"
:last-name "Luchini"
:gender "MALE"
:height 1.78}])
(s/valid? :my-app.cardinality-entity/many-strings [])
(s/valid? :my-app.cardinality-entity/many-strings ["foo" "bar"])
(s/valid? :my-app.cardinality-entity/many-genders ["MALE" "UNKOWN"])
(s/valid? :my-app.cardinality-entity/exactly-four-strings ["foo" "bar" "foo2" "bar2"])
(s/valid? :my-app.cardinality-entity/exactly-three-to-five-people
[{:name "Name" :gender "MALE"}
{:name "Name" :gender "MALE"}
{:name "Name" :gender "MALE"}])
(s/valid? :my-app.cardinality-entity/distinct-integers [1 2 3])
(s/valid? :my-app.cardinality-entity/distinct-integers-in-a-list '(1 2 3))
(s/valid? :my-param/alias "qwe")
(s/valid? :my-field/alias1 "qwe")
(s/valid? :my-field/alias2 "qwe")
(s/valid? :my-entity/alias {:an-aliased-field "qwe"})
(s/valid? :my-app.extend-override-entity/keyword-field :qwe)
(s/valid? :my-app.extend-override-entity/email-field "qwe@asd.com")
(gen/generate (s/gen :my-app/animal))
(gen/generate (s/gen :my-app.extend-override-entity/keyword-field))
(gen/generate (s/gen :my-app.extend-override-entity/email-field))
(gen/generate (s/gen :my-app/extend-override-entity)))
| 22692 | (ns hodur-spec-schema.core
(:require [clojure.spec.alpha :as s]
[datascript.core :as d]
[datascript.query-v3 :as q]
[camel-snake-kebab.core :refer [->kebab-case-string]]))
(defn ^:private get-ids-by-node-type [conn node-type]
(case node-type
:type (d/q '[:find [?e ...]
:in $ ?node-type
:where
[?e :node/type ?node-type]
[?e :spec/tag true]
[?e :type/nature :user]]
@conn node-type)
(d/q '[:find [?e ...]
:in $ ?node-type
:where
[?e :node/type ?node-type]
[?e :spec/tag true]]
@conn node-type)))
(defn ^:private prepend-core-ns [sym]
(when (not (nil? sym))
(if (namespace sym)
sym
(symbol "clojure.core" (str sym)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare get-spec-form)
(defmulti ^:private get-spec-name
(fn [obj opts]
(cond
(and (seqable? obj)
(every? #(= :param (:node/type %)) obj))
:param-group
:default
(:node/type obj))))
(defn ^:private get-spec-entity-name
[type-name
{:keys [prefix]}]
(keyword (name prefix)
(->kebab-case-string type-name)))
(defn ^:private get-spec-field-name
[type-name field-name
{:keys [prefix]}]
(keyword (str (name prefix) "." (->kebab-case-string type-name))
(->kebab-case-string field-name)))
(defn ^:private get-spec-param-name
[type-name field-name param-name
{:keys [prefix]}]
(keyword (str (name prefix) "." (->kebab-case-string type-name) "."
(->kebab-case-string field-name))
(->kebab-case-string param-name)))
(defn ^:private get-spec-param-group-name
[type-name field-name
{:keys [prefix params-postfix group-type] :or {params-postfix "%"} :as opts}]
(keyword (str (name prefix) "." (->kebab-case-string type-name))
(str (->kebab-case-string field-name)
(case group-type
:map ""
:tuple "-ordered")
params-postfix)))
(defmethod get-spec-name :type
[{:keys [type/kebab-case-name]} opts]
(get-spec-entity-name (name kebab-case-name) opts))
(defmethod get-spec-name :field
[{:keys [field/kebab-case-name
field/parent] :as field} opts]
(get-spec-field-name (name (:type/kebab-case-name parent))
(name kebab-case-name)
opts))
(defmethod get-spec-name :param
[param opts]
(let [type-name (-> param :param/parent :field/parent :type/kebab-case-name)
field-name (-> param :param/parent :field/kebab-case-name)
param-name (-> param :param/kebab-case-name)]
(get-spec-param-name type-name
field-name
param-name
opts)))
(defmethod get-spec-name :param-group
[params opts]
(let [type-name (-> params first :param/parent :field/parent :type/kebab-case-name)
field-name (-> params first :param/parent :field/kebab-case-name)]
(get-spec-param-group-name type-name
field-name
opts)))
(defmethod get-spec-name :default
[obj opts]
(if (nil? obj)
nil
(throw (ex-info "Unable to name a spec for object"
{:obj obj}))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn ^:private get-cardinality [dep-obj]
(or (:field/cardinality dep-obj)
(:param/cardinality dep-obj)))
(defn ^:private card-type [dep-obj]
(let [cardinality (get-cardinality dep-obj)]
(when cardinality
(if (and (= 1 (first cardinality))
(= 1 (second cardinality)))
:one
:many))))
(defn ^:private many-cardinality? [dep-obj]
(= :many (card-type dep-obj)))
(defn ^:private one-cardinality? [dep-obj]
(= :one (card-type dep-obj)))
(defmulti ^:private get-spec-form*
(fn [obj opts]
(cond
(:field/optional obj)
:optional-field
(:param/optional obj)
:optional-param
(many-cardinality? obj)
:many-ref
(:type/enum obj)
:enum
(:type/union obj)
:union
(and (:field/name obj)
(-> obj :field/parent :type/enum))
:enum-entry
(:field/union-type obj)
:union-field
(:type/name obj)
:entity
(and (seqable? obj)
(every? #(= :param (:node/type %)) obj))
:param-group
(:field/name obj) ;; simple field, dispatch type name
(-> obj :field/type :type/name)
(:param/name obj) ;; simple param, dispatch type name
(-> obj :param/type :type/name))))
(defn ^:private get-spec-form [obj opts]
(if (map? obj)
(let [{:keys [spec/override spec/extend spec/gen]} obj
override' (prepend-core-ns override)
extend' (prepend-core-ns extend)
gen' (prepend-core-ns gen)
target-form (if override'
override'
(if extend'
(list* `s/and [extend' (get-spec-form* obj opts)])
(get-spec-form* obj opts)))]
(if gen'
(list* `s/with-gen [target-form gen'])
target-form))
(get-spec-form* obj opts)))
(defn ^:private get-counts [obj]
(let [many? (many-cardinality? obj)
card (get-cardinality obj)
from (first card)
to (second card)]
(when many?
(cond-> {}
(= from to)
(assoc :count from)
(and (not= from to)
(not= 'n from))
(assoc :min-count from)
(and (not= from to)
(not= 'n to))
(assoc :max-count to)))))
(defn ^:private get-many-meta-specs [{:keys [spec/distinct spec/kind] :as obj}]
(let [kind' (prepend-core-ns kind)]
(cond-> {}
distinct (assoc :distinct distinct)
kind (assoc :kind kind'))))
(defmethod get-spec-form* :many-ref
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :field/cardinality :param/cardinality) opts)
other-nodes (merge (get-counts obj)
(get-many-meta-specs obj))]
(list* `s/coll-of
(reduce-kv (fn [c k v]
(conj c k v))
[entity-spec] other-nodes))))
(defmethod get-spec-form* :enum
[{:keys [field/_parent]} opts]
(list* `s/or
(reduce (fn [c {:keys [field/kebab-case-name] :as field}]
(conj c kebab-case-name (get-spec-name field opts)))
[] _parent)))
(defmethod get-spec-form* :union
[{:keys [field/_parent]} opts]
(list* `s/or
(reduce (fn [c {:keys [field/kebab-case-name] :as field}]
(conj c kebab-case-name (get-spec-name field opts)))
[] _parent)))
(defmethod get-spec-form* :enum-entry
[{:keys [field/name]} _]
`#(= ~name (when (or (string? %)
(keyword? %))
(name %))))
(defmethod get-spec-form* :union-field
[{:keys [field/union-type]} opts]
(get-spec-name union-type opts))
(defmethod get-spec-form* :optional-param
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :param/optional) opts)]
(list* `s/nilable [entity-spec])))
(defmethod get-spec-form* :optional-field
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :field/optional) opts)]
(list* `s/nilable [entity-spec])))
(defmethod get-spec-form* :entity
[{:keys [field/_parent type/implements]} opts]
(let [filter-fn (fn [pred c]
(->> c
(filter :spec/tag)
(filter pred)
(map #(get-spec-name % opts))
vec))
req (filter-fn #(not (:field/optional %)) _parent)
opt (filter-fn #(:field/optional %) _parent)
form `(s/keys :req-un ~req :opt-un ~opt)]
(if implements
(list* `s/and
(reduce (fn [c interface]
(conj c (get-spec-name interface opts)))
[form] implements))
form)))
(defmethod get-spec-form* :param-group
[params {:keys [group-type] :as opts}]
(let [filter-fn (fn [pred c]
(->> c
(filter pred)
(map #(get-spec-name % opts))
vec))
req (filter-fn #(not (:param/optional %)) params)
opt (filter-fn #(:param/optional %) params)]
(case group-type
:map `(s/keys :req-un ~req :opt-un ~opt)
:tuple (list* `s/tuple (map #(get-spec-name % opts) params)))))
(defmethod get-spec-form* "String" [_ _] `string?)
(defmethod get-spec-form* "ID" [_ _] `string?)
(defmethod get-spec-form* "Integer" [_ _] `integer?)
(defmethod get-spec-form* "Boolean" [_ _] `boolean?)
(defmethod get-spec-form* "Float" [_ _] `float?)
(defmethod get-spec-form* "DateTime" [_ _] `inst?)
(defmethod get-spec-form* :default [obj opts]
(let [ref-type (or (-> obj :field/type)
(-> obj :param/type))]
(if ref-type
(get-spec-name ref-type opts)
(throw (ex-info "Unable to create a spec form for object"
{:obj obj})))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti ^:private pull-node
(fn [conn node]
(:node/type node)))
(def ^:private param-selector
'[*
{:param/parent [*
{:field/parent [*]}]}
{:param/type [*]}])
(def ^:private field-selector
`[~'*
{:param/_parent ~param-selector}
{:field/parent ~'[*]}
{:field/type ~'[*]}
{:field/union-type ~'[*]}])
(def ^:private type-selector
`[~'* {:type/implements ~'[*]
:field/_parent ~field-selector}])
(defmethod pull-node :type
[conn {:keys [db/id]}]
(d/pull @conn type-selector id))
(defmethod pull-node :field
[conn {:keys [db/id]}]
(d/pull @conn field-selector id))
(defmethod pull-node :param
[conn {:keys [db/id]}]
(d/pull @conn param-selector id))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn ^:private build-aliases-spec [conn opts]
(let [eids (-> (q/q '[:find ?e
:where
[?e :spec/tag true]
(or [?e :spec/alias]
[?e :spec/aliases])]
@conn)
vec flatten)
objs (d/pull-many @conn '[*] eids)]
(reduce (fn [c {:keys [spec/alias spec/aliases] :as obj}]
(let [aliases' (or aliases alias)
aliases'' (if (seqable? aliases') aliases' [aliases'])
node (pull-node conn obj)]
(into c (map #(hash-map % (get-spec-name node opts))
aliases''))))
[] objs)))
(defn ^:private build-param-group-specs [conn group-type opts]
(let [eids (-> (q/q '[:find ?f
:where
[_ :param/parent ?f]
[?f :spec/tag true]]
@conn)
vec flatten)
objs (d/pull-many @conn '[{:param/_parent [:db/id :node/type]}] eids)]
(reduce (fn [c {:keys [param/_parent] :as field}]
(let [nodes (map #(pull-node conn %) _parent)
opts' (assoc opts :group-type group-type)]
(conj c (hash-map (get-spec-name nodes opts')
(get-spec-form nodes opts')))))
[] objs)))
(defn ^:private build-dummy-types-specs [conn opts]
(let [eids (get-ids-by-node-type conn :type)
objs (d/pull-many @conn '[*] eids)]
(reduce (fn [c obj]
(conj c (hash-map (get-spec-name obj opts)
'any?)))
[] objs)))
(defn ^:private build-node-spec [conn node opts]
(-> conn
(pull-node node)
(#(hash-map (get-spec-name % opts)
(get-spec-form % opts)))))
(defn ^:private build-by-type-specs [conn node-type opts]
(let [eids (get-ids-by-node-type conn node-type)
nodes (d/pull-many @conn [:db/id :node/type] eids)]
(map #(build-node-spec conn % opts) nodes)))
(defn ^:private compile-all
[conn opts]
(let [dummy-types-specs (build-dummy-types-specs conn opts)
params-specs (build-by-type-specs conn :param opts)
field-specs (build-by-type-specs conn :field opts)
type-specs (build-by-type-specs conn :type opts)
aliases-specs (build-aliases-spec conn opts)
param-groups-specs (build-param-group-specs conn :map opts)
param-groups-ordered-specs (build-param-group-specs conn :tuple opts)]
(->> (concat dummy-types-specs
params-specs
field-specs
type-specs
aliases-specs
param-groups-specs
param-groups-ordered-specs)
(mapv (fn [entry]
(let [k (first (keys entry))
v (first (vals entry))]
#_(do (println " - " k)
(println " =>" v)
(println " "))
`(s/def ~k ~v)))))))
(defn ^:private eval-default-prefix []
(eval '(str (ns-name *ns*))))
(defn ^:private default-prefix []
(str (ns-name *ns*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn schema
([conn]
(schema conn nil))
([conn {:keys [prefix] :as opts}]
(let [opts' (if-not prefix (assoc opts :prefix (default-prefix)) opts)]
(compile-all conn opts'))))
(defmacro defspecs
([conn]
`(defspecs ~conn nil))
([conn {:keys [prefix] :as opts}]
(let [opts# (if-not prefix (assoc opts :prefix (eval-default-prefix)) (eval opts))
conn# (eval conn)]
(mapv (fn [form] form)
(schema conn# opts#)))))
(comment
(require '[clojure.spec.gen.alpha :as gen])
(require '[hodur-engine.core :as engine])
(require 'test-fns)
(use 'core-test))
(comment
(def meta-db (engine/init-schema basic-schema
#_cardinality-schema
#_aliases-schema
#_extend-override-schema))
(let [s (schema meta-db {:prefix :my-app})]
#_(clojure.pprint/pprint s)))
(comment
(defspecs meta-db {:prefix :my-app})
(count (schema meta-db {:prefix :my-app}))
(count (filter #(or (clojure.string/starts-with? (namespace %) "my-app")
(clojure.string/starts-with? (namespace %) "beings")
(clojure.string/starts-with? (namespace %) "my-entity")
(clojure.string/starts-with? (namespace %) "my-field")
(clojure.string/starts-with? (namespace %) "my-param"))
(keys (s/registry))))
(s/valid? :my-app.person.height/unit "METERS")
(s/valid? :my-app/pet {:name "<NAME>" :dob #inst "2000-10-10" :race "cat"})
(s/valid? :my-app/person {:first-name "<NAME>"
:last-name "<NAME>"
:gender "MALE"
:height 1.78})
(s/explain :my-app/person {:first-name "<NAME>"
:last-name "<NAME>"
:gender "MALE"
:height 1.78})
(s/valid? :my-app.query-root/search
[{:name "<NAME>"
:dob #inst "2016-10-10"
:race "Dog"}
{:first-name "<NAME>"
:last-name "<NAME>"
:gender "MALE"
:height 1.78}])
(s/valid? :my-app.cardinality-entity/many-strings [])
(s/valid? :my-app.cardinality-entity/many-strings ["foo" "bar"])
(s/valid? :my-app.cardinality-entity/many-genders ["MALE" "UNKOWN"])
(s/valid? :my-app.cardinality-entity/exactly-four-strings ["foo" "bar" "foo2" "bar2"])
(s/valid? :my-app.cardinality-entity/exactly-three-to-five-people
[{:name "<NAME>" :gender "MALE"}
{:name "Name" :gender "MALE"}
{:name "Name" :gender "MALE"}])
(s/valid? :my-app.cardinality-entity/distinct-integers [1 2 3])
(s/valid? :my-app.cardinality-entity/distinct-integers-in-a-list '(1 2 3))
(s/valid? :my-param/alias "qwe")
(s/valid? :my-field/alias1 "qwe")
(s/valid? :my-field/alias2 "qwe")
(s/valid? :my-entity/alias {:an-aliased-field "qwe"})
(s/valid? :my-app.extend-override-entity/keyword-field :qwe)
(s/valid? :my-app.extend-override-entity/email-field "<EMAIL>")
(gen/generate (s/gen :my-app/animal))
(gen/generate (s/gen :my-app.extend-override-entity/keyword-field))
(gen/generate (s/gen :my-app.extend-override-entity/email-field))
(gen/generate (s/gen :my-app/extend-override-entity)))
| true | (ns hodur-spec-schema.core
(:require [clojure.spec.alpha :as s]
[datascript.core :as d]
[datascript.query-v3 :as q]
[camel-snake-kebab.core :refer [->kebab-case-string]]))
(defn ^:private get-ids-by-node-type [conn node-type]
(case node-type
:type (d/q '[:find [?e ...]
:in $ ?node-type
:where
[?e :node/type ?node-type]
[?e :spec/tag true]
[?e :type/nature :user]]
@conn node-type)
(d/q '[:find [?e ...]
:in $ ?node-type
:where
[?e :node/type ?node-type]
[?e :spec/tag true]]
@conn node-type)))
(defn ^:private prepend-core-ns [sym]
(when (not (nil? sym))
(if (namespace sym)
sym
(symbol "clojure.core" (str sym)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare get-spec-form)
(defmulti ^:private get-spec-name
(fn [obj opts]
(cond
(and (seqable? obj)
(every? #(= :param (:node/type %)) obj))
:param-group
:default
(:node/type obj))))
(defn ^:private get-spec-entity-name
[type-name
{:keys [prefix]}]
(keyword (name prefix)
(->kebab-case-string type-name)))
(defn ^:private get-spec-field-name
[type-name field-name
{:keys [prefix]}]
(keyword (str (name prefix) "." (->kebab-case-string type-name))
(->kebab-case-string field-name)))
(defn ^:private get-spec-param-name
[type-name field-name param-name
{:keys [prefix]}]
(keyword (str (name prefix) "." (->kebab-case-string type-name) "."
(->kebab-case-string field-name))
(->kebab-case-string param-name)))
(defn ^:private get-spec-param-group-name
[type-name field-name
{:keys [prefix params-postfix group-type] :or {params-postfix "%"} :as opts}]
(keyword (str (name prefix) "." (->kebab-case-string type-name))
(str (->kebab-case-string field-name)
(case group-type
:map ""
:tuple "-ordered")
params-postfix)))
(defmethod get-spec-name :type
[{:keys [type/kebab-case-name]} opts]
(get-spec-entity-name (name kebab-case-name) opts))
(defmethod get-spec-name :field
[{:keys [field/kebab-case-name
field/parent] :as field} opts]
(get-spec-field-name (name (:type/kebab-case-name parent))
(name kebab-case-name)
opts))
(defmethod get-spec-name :param
[param opts]
(let [type-name (-> param :param/parent :field/parent :type/kebab-case-name)
field-name (-> param :param/parent :field/kebab-case-name)
param-name (-> param :param/kebab-case-name)]
(get-spec-param-name type-name
field-name
param-name
opts)))
(defmethod get-spec-name :param-group
[params opts]
(let [type-name (-> params first :param/parent :field/parent :type/kebab-case-name)
field-name (-> params first :param/parent :field/kebab-case-name)]
(get-spec-param-group-name type-name
field-name
opts)))
(defmethod get-spec-name :default
[obj opts]
(if (nil? obj)
nil
(throw (ex-info "Unable to name a spec for object"
{:obj obj}))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn ^:private get-cardinality [dep-obj]
(or (:field/cardinality dep-obj)
(:param/cardinality dep-obj)))
(defn ^:private card-type [dep-obj]
(let [cardinality (get-cardinality dep-obj)]
(when cardinality
(if (and (= 1 (first cardinality))
(= 1 (second cardinality)))
:one
:many))))
(defn ^:private many-cardinality? [dep-obj]
(= :many (card-type dep-obj)))
(defn ^:private one-cardinality? [dep-obj]
(= :one (card-type dep-obj)))
(defmulti ^:private get-spec-form*
(fn [obj opts]
(cond
(:field/optional obj)
:optional-field
(:param/optional obj)
:optional-param
(many-cardinality? obj)
:many-ref
(:type/enum obj)
:enum
(:type/union obj)
:union
(and (:field/name obj)
(-> obj :field/parent :type/enum))
:enum-entry
(:field/union-type obj)
:union-field
(:type/name obj)
:entity
(and (seqable? obj)
(every? #(= :param (:node/type %)) obj))
:param-group
(:field/name obj) ;; simple field, dispatch type name
(-> obj :field/type :type/name)
(:param/name obj) ;; simple param, dispatch type name
(-> obj :param/type :type/name))))
(defn ^:private get-spec-form [obj opts]
(if (map? obj)
(let [{:keys [spec/override spec/extend spec/gen]} obj
override' (prepend-core-ns override)
extend' (prepend-core-ns extend)
gen' (prepend-core-ns gen)
target-form (if override'
override'
(if extend'
(list* `s/and [extend' (get-spec-form* obj opts)])
(get-spec-form* obj opts)))]
(if gen'
(list* `s/with-gen [target-form gen'])
target-form))
(get-spec-form* obj opts)))
(defn ^:private get-counts [obj]
(let [many? (many-cardinality? obj)
card (get-cardinality obj)
from (first card)
to (second card)]
(when many?
(cond-> {}
(= from to)
(assoc :count from)
(and (not= from to)
(not= 'n from))
(assoc :min-count from)
(and (not= from to)
(not= 'n to))
(assoc :max-count to)))))
(defn ^:private get-many-meta-specs [{:keys [spec/distinct spec/kind] :as obj}]
(let [kind' (prepend-core-ns kind)]
(cond-> {}
distinct (assoc :distinct distinct)
kind (assoc :kind kind'))))
(defmethod get-spec-form* :many-ref
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :field/cardinality :param/cardinality) opts)
other-nodes (merge (get-counts obj)
(get-many-meta-specs obj))]
(list* `s/coll-of
(reduce-kv (fn [c k v]
(conj c k v))
[entity-spec] other-nodes))))
(defmethod get-spec-form* :enum
[{:keys [field/_parent]} opts]
(list* `s/or
(reduce (fn [c {:keys [field/kebab-case-name] :as field}]
(conj c kebab-case-name (get-spec-name field opts)))
[] _parent)))
(defmethod get-spec-form* :union
[{:keys [field/_parent]} opts]
(list* `s/or
(reduce (fn [c {:keys [field/kebab-case-name] :as field}]
(conj c kebab-case-name (get-spec-name field opts)))
[] _parent)))
(defmethod get-spec-form* :enum-entry
[{:keys [field/name]} _]
`#(= ~name (when (or (string? %)
(keyword? %))
(name %))))
(defmethod get-spec-form* :union-field
[{:keys [field/union-type]} opts]
(get-spec-name union-type opts))
(defmethod get-spec-form* :optional-param
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :param/optional) opts)]
(list* `s/nilable [entity-spec])))
(defmethod get-spec-form* :optional-field
[obj opts]
(let [entity-spec (get-spec-form (dissoc obj :field/optional) opts)]
(list* `s/nilable [entity-spec])))
(defmethod get-spec-form* :entity
[{:keys [field/_parent type/implements]} opts]
(let [filter-fn (fn [pred c]
(->> c
(filter :spec/tag)
(filter pred)
(map #(get-spec-name % opts))
vec))
req (filter-fn #(not (:field/optional %)) _parent)
opt (filter-fn #(:field/optional %) _parent)
form `(s/keys :req-un ~req :opt-un ~opt)]
(if implements
(list* `s/and
(reduce (fn [c interface]
(conj c (get-spec-name interface opts)))
[form] implements))
form)))
(defmethod get-spec-form* :param-group
[params {:keys [group-type] :as opts}]
(let [filter-fn (fn [pred c]
(->> c
(filter pred)
(map #(get-spec-name % opts))
vec))
req (filter-fn #(not (:param/optional %)) params)
opt (filter-fn #(:param/optional %) params)]
(case group-type
:map `(s/keys :req-un ~req :opt-un ~opt)
:tuple (list* `s/tuple (map #(get-spec-name % opts) params)))))
(defmethod get-spec-form* "String" [_ _] `string?)
(defmethod get-spec-form* "ID" [_ _] `string?)
(defmethod get-spec-form* "Integer" [_ _] `integer?)
(defmethod get-spec-form* "Boolean" [_ _] `boolean?)
(defmethod get-spec-form* "Float" [_ _] `float?)
(defmethod get-spec-form* "DateTime" [_ _] `inst?)
(defmethod get-spec-form* :default [obj opts]
(let [ref-type (or (-> obj :field/type)
(-> obj :param/type))]
(if ref-type
(get-spec-name ref-type opts)
(throw (ex-info "Unable to create a spec form for object"
{:obj obj})))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti ^:private pull-node
(fn [conn node]
(:node/type node)))
(def ^:private param-selector
'[*
{:param/parent [*
{:field/parent [*]}]}
{:param/type [*]}])
(def ^:private field-selector
`[~'*
{:param/_parent ~param-selector}
{:field/parent ~'[*]}
{:field/type ~'[*]}
{:field/union-type ~'[*]}])
(def ^:private type-selector
`[~'* {:type/implements ~'[*]
:field/_parent ~field-selector}])
(defmethod pull-node :type
[conn {:keys [db/id]}]
(d/pull @conn type-selector id))
(defmethod pull-node :field
[conn {:keys [db/id]}]
(d/pull @conn field-selector id))
(defmethod pull-node :param
[conn {:keys [db/id]}]
(d/pull @conn param-selector id))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn ^:private build-aliases-spec [conn opts]
(let [eids (-> (q/q '[:find ?e
:where
[?e :spec/tag true]
(or [?e :spec/alias]
[?e :spec/aliases])]
@conn)
vec flatten)
objs (d/pull-many @conn '[*] eids)]
(reduce (fn [c {:keys [spec/alias spec/aliases] :as obj}]
(let [aliases' (or aliases alias)
aliases'' (if (seqable? aliases') aliases' [aliases'])
node (pull-node conn obj)]
(into c (map #(hash-map % (get-spec-name node opts))
aliases''))))
[] objs)))
(defn ^:private build-param-group-specs [conn group-type opts]
(let [eids (-> (q/q '[:find ?f
:where
[_ :param/parent ?f]
[?f :spec/tag true]]
@conn)
vec flatten)
objs (d/pull-many @conn '[{:param/_parent [:db/id :node/type]}] eids)]
(reduce (fn [c {:keys [param/_parent] :as field}]
(let [nodes (map #(pull-node conn %) _parent)
opts' (assoc opts :group-type group-type)]
(conj c (hash-map (get-spec-name nodes opts')
(get-spec-form nodes opts')))))
[] objs)))
(defn ^:private build-dummy-types-specs [conn opts]
(let [eids (get-ids-by-node-type conn :type)
objs (d/pull-many @conn '[*] eids)]
(reduce (fn [c obj]
(conj c (hash-map (get-spec-name obj opts)
'any?)))
[] objs)))
(defn ^:private build-node-spec [conn node opts]
(-> conn
(pull-node node)
(#(hash-map (get-spec-name % opts)
(get-spec-form % opts)))))
(defn ^:private build-by-type-specs [conn node-type opts]
(let [eids (get-ids-by-node-type conn node-type)
nodes (d/pull-many @conn [:db/id :node/type] eids)]
(map #(build-node-spec conn % opts) nodes)))
(defn ^:private compile-all
[conn opts]
(let [dummy-types-specs (build-dummy-types-specs conn opts)
params-specs (build-by-type-specs conn :param opts)
field-specs (build-by-type-specs conn :field opts)
type-specs (build-by-type-specs conn :type opts)
aliases-specs (build-aliases-spec conn opts)
param-groups-specs (build-param-group-specs conn :map opts)
param-groups-ordered-specs (build-param-group-specs conn :tuple opts)]
(->> (concat dummy-types-specs
params-specs
field-specs
type-specs
aliases-specs
param-groups-specs
param-groups-ordered-specs)
(mapv (fn [entry]
(let [k (first (keys entry))
v (first (vals entry))]
#_(do (println " - " k)
(println " =>" v)
(println " "))
`(s/def ~k ~v)))))))
(defn ^:private eval-default-prefix []
(eval '(str (ns-name *ns*))))
(defn ^:private default-prefix []
(str (ns-name *ns*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn schema
([conn]
(schema conn nil))
([conn {:keys [prefix] :as opts}]
(let [opts' (if-not prefix (assoc opts :prefix (default-prefix)) opts)]
(compile-all conn opts'))))
(defmacro defspecs
([conn]
`(defspecs ~conn nil))
([conn {:keys [prefix] :as opts}]
(let [opts# (if-not prefix (assoc opts :prefix (eval-default-prefix)) (eval opts))
conn# (eval conn)]
(mapv (fn [form] form)
(schema conn# opts#)))))
(comment
(require '[clojure.spec.gen.alpha :as gen])
(require '[hodur-engine.core :as engine])
(require 'test-fns)
(use 'core-test))
(comment
(def meta-db (engine/init-schema basic-schema
#_cardinality-schema
#_aliases-schema
#_extend-override-schema))
(let [s (schema meta-db {:prefix :my-app})]
#_(clojure.pprint/pprint s)))
(comment
(defspecs meta-db {:prefix :my-app})
(count (schema meta-db {:prefix :my-app}))
(count (filter #(or (clojure.string/starts-with? (namespace %) "my-app")
(clojure.string/starts-with? (namespace %) "beings")
(clojure.string/starts-with? (namespace %) "my-entity")
(clojure.string/starts-with? (namespace %) "my-field")
(clojure.string/starts-with? (namespace %) "my-param"))
(keys (s/registry))))
(s/valid? :my-app.person.height/unit "METERS")
(s/valid? :my-app/pet {:name "PI:NAME:<NAME>END_PI" :dob #inst "2000-10-10" :race "cat"})
(s/valid? :my-app/person {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:gender "MALE"
:height 1.78})
(s/explain :my-app/person {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:gender "MALE"
:height 1.78})
(s/valid? :my-app.query-root/search
[{:name "PI:NAME:<NAME>END_PI"
:dob #inst "2016-10-10"
:race "Dog"}
{:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:gender "MALE"
:height 1.78}])
(s/valid? :my-app.cardinality-entity/many-strings [])
(s/valid? :my-app.cardinality-entity/many-strings ["foo" "bar"])
(s/valid? :my-app.cardinality-entity/many-genders ["MALE" "UNKOWN"])
(s/valid? :my-app.cardinality-entity/exactly-four-strings ["foo" "bar" "foo2" "bar2"])
(s/valid? :my-app.cardinality-entity/exactly-three-to-five-people
[{:name "PI:NAME:<NAME>END_PI" :gender "MALE"}
{:name "Name" :gender "MALE"}
{:name "Name" :gender "MALE"}])
(s/valid? :my-app.cardinality-entity/distinct-integers [1 2 3])
(s/valid? :my-app.cardinality-entity/distinct-integers-in-a-list '(1 2 3))
(s/valid? :my-param/alias "qwe")
(s/valid? :my-field/alias1 "qwe")
(s/valid? :my-field/alias2 "qwe")
(s/valid? :my-entity/alias {:an-aliased-field "qwe"})
(s/valid? :my-app.extend-override-entity/keyword-field :qwe)
(s/valid? :my-app.extend-override-entity/email-field "PI:EMAIL:<EMAIL>END_PI")
(gen/generate (s/gen :my-app/animal))
(gen/generate (s/gen :my-app.extend-override-entity/keyword-field))
(gen/generate (s/gen :my-app.extend-override-entity/email-field))
(gen/generate (s/gen :my-app/extend-override-entity)))
|
[
{
"context": " (put! \n [\"101\" {:info {:age 17 :name \"Alice\"}\n :score {:math 99 :physics 78}}]",
"end": 758,
"score": 0.999869167804718,
"start": 753,
"tag": "NAME",
"value": "Alice"
},
{
"context": "sics 78}}]\n\n [\"102\" {:info {:age 19 :name \"Bob\"}\n :score {:math 63 :physics 52}}]",
"end": 851,
"score": 0.999855101108551,
"start": 848,
"tag": "NAME",
"value": "Bob"
},
{
"context": "[[\"102\"\n {:info {:age 19 :name \"Bob\"}\n :score {:math 63 :physics 5",
"end": 1074,
"score": 0.9998636245727539,
"start": 1071,
"tag": "NAME",
"value": "Bob"
},
{
"context": "just \n [[\"101\" {:info {:age 17 :name \"Alice\"}\n :score {:math 99 :physics",
"end": 1972,
"score": 0.9998078346252441,
"start": 1967,
"tag": "NAME",
"value": "Alice"
},
{
"context": "8}}]\n\n [\"102\" {:info {:age 19 :name \"Bob\"}\n :score {:math 63 :physics",
"end": 2077,
"score": 0.9998096227645874,
"start": 2074,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (put! \n [\"103\" {:info {:age 21 :name \"Cathy\"}\n :score {:math 100 :physics 84 :",
"end": 2806,
"score": 0.9925121068954468,
"start": 2801,
"tag": "NAME",
"value": "Cathy"
},
{
"context": "stry 70}}]\n\n [\"104\" {:info {:age 20 :name \"Dante\"}\n :score {:math 73 :physics 92}}]",
"end": 2916,
"score": 0.993166446685791,
"start": 2911,
"tag": "NAME",
"value": "Dante"
}
] | data/train/clojure/f4903fae9f883d7a6f6cc789af702630b94d937bcore_test.clj | harshp8l/deep-learning-lang-detection | 84 | (ns hbase-clj.core-test
(:require
[midje.sweet :refer :all]
(hbase-clj
[core :refer :all]
[driver :refer :all]
[manage :refer :all])))
(defhbase test-hbase
"hbase.zookeeper.quorum" "localhost")
(def table-name "hbase_clj_teststu")
;;Delete the test table first to avoid accidents
(try
(delete-table! test-hbase table-name)
(catch Exception e nil))
(create-table!
test-hbase table-name
"info" "score")
(def-hbtable test-table
{:id-type :string
:table-name table-name
:hbase test-hbase}
:info {:--ktype :keyword :--vtype :int :name :string}
:score {:--ktype :keyword :--vtype :long})
(try
(facts "About CRUDs"
(with-table test-table
(put!
["101" {:info {:age 17 :name "Alice"}
:score {:math 99 :physics 78}}]
["102" {:info {:age 19 :name "Bob"}
:score {:math 63 :physics 52}}])
(fact "Get single data by key without constraints returns the full data"
(get "102")
=> (just [["102"
{:info {:age 19 :name "Bob"}
:score {:math 63 :physics 52}}]]))
(fact "with-versions works in get"
(get :with-versions "102")
=> (just
[(just
["102"
(contains
{:info
(contains
{:age (contains [(contains {:val 19})])})})])]))
(fact "family constraints works in get"
(get ["101" {:info :*}])
=> (just [(just ["101" (just {:info (contains {})})])]))
(fact "attr constraints works in get"
(get ["101" {:score :math}])
=> (just [(just ["101" (just {:score (just {:math number?})})])])
(= (get ["101" {:score :math}]) (get ["101" {:score [:math]}]))
=> truthy)
(fact "scanning without any constraints returns every thing"
(scan)
=> (just
[["101" {:info {:age 17 :name "Alice"}
:score {:math 99 :physics 78}}]
["102" {:info {:age 19 :name "Bob"}
:score {:math 63 :physics 52}}]]))
(fact "`with-versions` works in scan"
(scan :with-versions)
=> (contains
[(just
["102"
(contains
{:info
(contains
{:age (contains [(contains {:val 19})])})})])]))
(fact "family constraints works in scan"
(scan :attrs {:info :*})
=> (contains [(just ["101" (just {:info (contains {})})])]))
(fact "attr constraints works in scan"
(scan :attrs {:score [:math]})
=> (contains [(just ["101" (just {:score (just {:math number?})})])]))
(put!
["103" {:info {:age 21 :name "Cathy"}
:score {:math 100 :physics 84 :chemistry 70}}]
["104" {:info {:age 20 :name "Dante"}
:score {:math 73 :physics 92}}])
(fact "start-id and stop-id works in scan"
(scan :start-id "102") => (just [(contains ["102"])
(contains ["103"])
(contains ["104"])])
(scan :stop-id "104") => (just [(contains ["101"])
(contains ["102"])
(contains ["103"])])
(scan :start-id "102"
:stop-id "104") => (just [(contains ["102"])
(contains ["103"])]))
(fact "scan is lazy"
(realized? (scan)) => falsey
(type (scan)) => clojure.lang.LazySeq)
(fact "scan is not lazy when `eager?` is set to be false"
(vector? (scan :eager? true)) => truthy)
(fact "calling `incr!` to update"
(incr! ["101" {:info {:age 5}}])
(get ["101" {:info [:age]}])
=> (just [(just ["101" {:info {:age 22}}])]))
(fact "calling `incr!` on nil cols inits the col"
(incr! ["101" {:info {:height 180}}])
(get ["101" {:info [:height]}])
=> (just [(just ["101" {:info {:height 180}}])]))
(fact "calling `incr!` on non-existing rows inits the row"
(incr! ["201" {:info {:height 180}}])
(get ["201" {:info [:height]}])
=> (just [(just ["201" {:info {:height 180}}])]))
(fact "batch support works"
(with-batch
(put! ["202" {:info {:height 180}}])
(incr! ["202" {:info {:height 2}}])
(incr! ["202" {:info {:height 2}}])
(dotimes [x 200]
(incr! ["202" {:info {:x 2}}])))
(get ["202" {:info [:height :x]}])
=> (just [(just ["202" {:info {:height 184 :x 400}}])]))
#_(fact "calling `delete!` on a row"
(delete! "101")
(scan) => (just [(contains ["102"])
(contains ["103"])
(contains ["104"])]))
#_(fact "calling `delete!` on a family "
(delete! ["102" [:score]])
(scan) => (contains [(contains ["102" (just {:info map?})])]))
#_(fact "calling `delete!` on an attr "
(delete! ["103" [:score [:chemistry :math]]])
(scan) => (contains [(contains ["103" (contains {:score (just {:physics 84})})])]))))
(catch Exception e
(clojure.stacktrace/print-cause-trace e)))
(delete-table! test-hbase table-name)
| 12168 | (ns hbase-clj.core-test
(:require
[midje.sweet :refer :all]
(hbase-clj
[core :refer :all]
[driver :refer :all]
[manage :refer :all])))
(defhbase test-hbase
"hbase.zookeeper.quorum" "localhost")
(def table-name "hbase_clj_teststu")
;;Delete the test table first to avoid accidents
(try
(delete-table! test-hbase table-name)
(catch Exception e nil))
(create-table!
test-hbase table-name
"info" "score")
(def-hbtable test-table
{:id-type :string
:table-name table-name
:hbase test-hbase}
:info {:--ktype :keyword :--vtype :int :name :string}
:score {:--ktype :keyword :--vtype :long})
(try
(facts "About CRUDs"
(with-table test-table
(put!
["101" {:info {:age 17 :name "<NAME>"}
:score {:math 99 :physics 78}}]
["102" {:info {:age 19 :name "<NAME>"}
:score {:math 63 :physics 52}}])
(fact "Get single data by key without constraints returns the full data"
(get "102")
=> (just [["102"
{:info {:age 19 :name "<NAME>"}
:score {:math 63 :physics 52}}]]))
(fact "with-versions works in get"
(get :with-versions "102")
=> (just
[(just
["102"
(contains
{:info
(contains
{:age (contains [(contains {:val 19})])})})])]))
(fact "family constraints works in get"
(get ["101" {:info :*}])
=> (just [(just ["101" (just {:info (contains {})})])]))
(fact "attr constraints works in get"
(get ["101" {:score :math}])
=> (just [(just ["101" (just {:score (just {:math number?})})])])
(= (get ["101" {:score :math}]) (get ["101" {:score [:math]}]))
=> truthy)
(fact "scanning without any constraints returns every thing"
(scan)
=> (just
[["101" {:info {:age 17 :name "<NAME>"}
:score {:math 99 :physics 78}}]
["102" {:info {:age 19 :name "<NAME>"}
:score {:math 63 :physics 52}}]]))
(fact "`with-versions` works in scan"
(scan :with-versions)
=> (contains
[(just
["102"
(contains
{:info
(contains
{:age (contains [(contains {:val 19})])})})])]))
(fact "family constraints works in scan"
(scan :attrs {:info :*})
=> (contains [(just ["101" (just {:info (contains {})})])]))
(fact "attr constraints works in scan"
(scan :attrs {:score [:math]})
=> (contains [(just ["101" (just {:score (just {:math number?})})])]))
(put!
["103" {:info {:age 21 :name "<NAME>"}
:score {:math 100 :physics 84 :chemistry 70}}]
["104" {:info {:age 20 :name "<NAME>"}
:score {:math 73 :physics 92}}])
(fact "start-id and stop-id works in scan"
(scan :start-id "102") => (just [(contains ["102"])
(contains ["103"])
(contains ["104"])])
(scan :stop-id "104") => (just [(contains ["101"])
(contains ["102"])
(contains ["103"])])
(scan :start-id "102"
:stop-id "104") => (just [(contains ["102"])
(contains ["103"])]))
(fact "scan is lazy"
(realized? (scan)) => falsey
(type (scan)) => clojure.lang.LazySeq)
(fact "scan is not lazy when `eager?` is set to be false"
(vector? (scan :eager? true)) => truthy)
(fact "calling `incr!` to update"
(incr! ["101" {:info {:age 5}}])
(get ["101" {:info [:age]}])
=> (just [(just ["101" {:info {:age 22}}])]))
(fact "calling `incr!` on nil cols inits the col"
(incr! ["101" {:info {:height 180}}])
(get ["101" {:info [:height]}])
=> (just [(just ["101" {:info {:height 180}}])]))
(fact "calling `incr!` on non-existing rows inits the row"
(incr! ["201" {:info {:height 180}}])
(get ["201" {:info [:height]}])
=> (just [(just ["201" {:info {:height 180}}])]))
(fact "batch support works"
(with-batch
(put! ["202" {:info {:height 180}}])
(incr! ["202" {:info {:height 2}}])
(incr! ["202" {:info {:height 2}}])
(dotimes [x 200]
(incr! ["202" {:info {:x 2}}])))
(get ["202" {:info [:height :x]}])
=> (just [(just ["202" {:info {:height 184 :x 400}}])]))
#_(fact "calling `delete!` on a row"
(delete! "101")
(scan) => (just [(contains ["102"])
(contains ["103"])
(contains ["104"])]))
#_(fact "calling `delete!` on a family "
(delete! ["102" [:score]])
(scan) => (contains [(contains ["102" (just {:info map?})])]))
#_(fact "calling `delete!` on an attr "
(delete! ["103" [:score [:chemistry :math]]])
(scan) => (contains [(contains ["103" (contains {:score (just {:physics 84})})])]))))
(catch Exception e
(clojure.stacktrace/print-cause-trace e)))
(delete-table! test-hbase table-name)
| true | (ns hbase-clj.core-test
(:require
[midje.sweet :refer :all]
(hbase-clj
[core :refer :all]
[driver :refer :all]
[manage :refer :all])))
(defhbase test-hbase
"hbase.zookeeper.quorum" "localhost")
(def table-name "hbase_clj_teststu")
;;Delete the test table first to avoid accidents
(try
(delete-table! test-hbase table-name)
(catch Exception e nil))
(create-table!
test-hbase table-name
"info" "score")
(def-hbtable test-table
{:id-type :string
:table-name table-name
:hbase test-hbase}
:info {:--ktype :keyword :--vtype :int :name :string}
:score {:--ktype :keyword :--vtype :long})
(try
(facts "About CRUDs"
(with-table test-table
(put!
["101" {:info {:age 17 :name "PI:NAME:<NAME>END_PI"}
:score {:math 99 :physics 78}}]
["102" {:info {:age 19 :name "PI:NAME:<NAME>END_PI"}
:score {:math 63 :physics 52}}])
(fact "Get single data by key without constraints returns the full data"
(get "102")
=> (just [["102"
{:info {:age 19 :name "PI:NAME:<NAME>END_PI"}
:score {:math 63 :physics 52}}]]))
(fact "with-versions works in get"
(get :with-versions "102")
=> (just
[(just
["102"
(contains
{:info
(contains
{:age (contains [(contains {:val 19})])})})])]))
(fact "family constraints works in get"
(get ["101" {:info :*}])
=> (just [(just ["101" (just {:info (contains {})})])]))
(fact "attr constraints works in get"
(get ["101" {:score :math}])
=> (just [(just ["101" (just {:score (just {:math number?})})])])
(= (get ["101" {:score :math}]) (get ["101" {:score [:math]}]))
=> truthy)
(fact "scanning without any constraints returns every thing"
(scan)
=> (just
[["101" {:info {:age 17 :name "PI:NAME:<NAME>END_PI"}
:score {:math 99 :physics 78}}]
["102" {:info {:age 19 :name "PI:NAME:<NAME>END_PI"}
:score {:math 63 :physics 52}}]]))
(fact "`with-versions` works in scan"
(scan :with-versions)
=> (contains
[(just
["102"
(contains
{:info
(contains
{:age (contains [(contains {:val 19})])})})])]))
(fact "family constraints works in scan"
(scan :attrs {:info :*})
=> (contains [(just ["101" (just {:info (contains {})})])]))
(fact "attr constraints works in scan"
(scan :attrs {:score [:math]})
=> (contains [(just ["101" (just {:score (just {:math number?})})])]))
(put!
["103" {:info {:age 21 :name "PI:NAME:<NAME>END_PI"}
:score {:math 100 :physics 84 :chemistry 70}}]
["104" {:info {:age 20 :name "PI:NAME:<NAME>END_PI"}
:score {:math 73 :physics 92}}])
(fact "start-id and stop-id works in scan"
(scan :start-id "102") => (just [(contains ["102"])
(contains ["103"])
(contains ["104"])])
(scan :stop-id "104") => (just [(contains ["101"])
(contains ["102"])
(contains ["103"])])
(scan :start-id "102"
:stop-id "104") => (just [(contains ["102"])
(contains ["103"])]))
(fact "scan is lazy"
(realized? (scan)) => falsey
(type (scan)) => clojure.lang.LazySeq)
(fact "scan is not lazy when `eager?` is set to be false"
(vector? (scan :eager? true)) => truthy)
(fact "calling `incr!` to update"
(incr! ["101" {:info {:age 5}}])
(get ["101" {:info [:age]}])
=> (just [(just ["101" {:info {:age 22}}])]))
(fact "calling `incr!` on nil cols inits the col"
(incr! ["101" {:info {:height 180}}])
(get ["101" {:info [:height]}])
=> (just [(just ["101" {:info {:height 180}}])]))
(fact "calling `incr!` on non-existing rows inits the row"
(incr! ["201" {:info {:height 180}}])
(get ["201" {:info [:height]}])
=> (just [(just ["201" {:info {:height 180}}])]))
(fact "batch support works"
(with-batch
(put! ["202" {:info {:height 180}}])
(incr! ["202" {:info {:height 2}}])
(incr! ["202" {:info {:height 2}}])
(dotimes [x 200]
(incr! ["202" {:info {:x 2}}])))
(get ["202" {:info [:height :x]}])
=> (just [(just ["202" {:info {:height 184 :x 400}}])]))
#_(fact "calling `delete!` on a row"
(delete! "101")
(scan) => (just [(contains ["102"])
(contains ["103"])
(contains ["104"])]))
#_(fact "calling `delete!` on a family "
(delete! ["102" [:score]])
(scan) => (contains [(contains ["102" (just {:info map?})])]))
#_(fact "calling `delete!` on an attr "
(delete! ["103" [:score [:chemistry :math]]])
(scan) => (contains [(contains ["103" (contains {:score (just {:physics 84})})])]))))
(catch Exception e
(clojure.stacktrace/print-cause-trace e)))
(delete-table! test-hbase table-name)
|
[
{
"context": "ltered-tweet {:text \"tweet\", :user {:screen_name \"tweety\"}}) => {:screen_name \"tweety\", :tweet \"tweet\"}\n ",
"end": 557,
"score": 0.9994609355926514,
"start": 551,
"tag": "USERNAME",
"value": "tweety"
},
{
"context": ":user {:screen_name \"tweety\"}}) => {:screen_name \"tweety\", :tweet \"tweet\"}\n (filtered-tweet single-tweet-",
"end": 586,
"score": 0.999467134475708,
"start": 580,
"tag": "USERNAME",
"value": "tweety"
},
{
"context": "red-tweet single-tweet-fixture) => {:screen_name \"izaloko\", :tweet \"qu por qu kieres saver como poner pabli",
"end": 670,
"score": 0.999538242816925,
"start": 663,
"tag": "USERNAME",
"value": "izaloko"
},
{
"context": " {:status 200 :body (json/generate-string {:name \"freddy\"})})\n (provided\n (session-get :twitter-oauth)",
"end": 1869,
"score": 0.9391593933105469,
"start": 1863,
"tag": "NAME",
"value": "freddy"
},
{
"context": " (session-get :twitter-oauth) => {:screen_name \"freddy\"})\n\n \"wrap-oauth returns a 401 error containi",
"end": 1941,
"score": 0.7535035014152527,
"start": 1938,
"tag": "NAME",
"value": "fre"
},
{
"context": "(session-get :twitter-oauth) => {:screen_name \"freddy\"})\n\n \"wrap-oauth returns a 401 error containing ",
"end": 1944,
"score": 0.5145596265792847,
"start": 1941,
"tag": "USERNAME",
"value": "ddy"
}
] | test/twitter_example/core_test.clj | kornysietsma/twitter-example | 1 | (ns twitter-example.core-test
(:use
midje.sweet
twitter-example.core
compojure.core
sandbar.stateful-session
[compojure.response :only [resource]])
(:require
[clj-json.core :as json]
[clojure.java.io :as io]))
(def fixture-path "test/twitter_example/fixtures/")
(def single-tweet-fixture
(first (json/parsed-seq (io/reader (str fixture-path "single_tweet.json")) true)))
(facts "about filtering tweets"
(filtered-tweet {}) => {:screen_name nil, :tweet nil}
(filtered-tweet {:text "tweet", :user {:screen_name "tweety"}}) => {:screen_name "tweety", :tweet "tweet"}
(filtered-tweet single-tweet-fixture) => {:screen_name "izaloko", :tweet "qu por qu kieres saver como poner pablito"})
(facts "about the main routes"
"Bare request returns index file"
(main-routes {:uri "/" :request-method :get})
=> (contains {:status 200
:body "stuff"})
(provided
(resource "public/index.html") => "stuff")
"On redirect from twitter oauth, tokens are stored in session and user is redirected to '/'"
(main-routes {:uri "/twitter_oauth_response"
:request-method :get
:params {:oauth_verifier "verifier" :oauth_token "token"}})
=> (contains {:status 302 :headers {"Location" "/"}})
(provided
(session-get :request-token) => ...request_token...
(access-token-response ...request_token... "verifier") => ...oauth_response...
(session-put! :twitter-oauth ...oauth_response...) => anything))
; These are really integration tests - wrap-oauth is wired in to the app at startup, so can't easily be mocked out
(facts "about wrap-oauth middleware"
"wrap-oauth provides twitter information to later handlers if it is available in the session"
(app {:uri "/auth/status.json" :request-method :get})
=> (contains {:status 200 :body (json/generate-string {:name "freddy"})})
(provided
(session-get :twitter-oauth) => {:screen_name "freddy"})
"wrap-oauth returns a 401 error containing a twitter redirect url if no twitter information is in the session"
(app {:uri "/auth/status.json" :request-method :get})
=> (contains {:status 401 :body (json/generate-string {:authUrl "the_url"})})
(provided
(session-get :twitter-oauth) => nil
(twitter-request-token) => ...request_token...
(callback-uri ...request_token...) => "the_url"))
| 19370 | (ns twitter-example.core-test
(:use
midje.sweet
twitter-example.core
compojure.core
sandbar.stateful-session
[compojure.response :only [resource]])
(:require
[clj-json.core :as json]
[clojure.java.io :as io]))
(def fixture-path "test/twitter_example/fixtures/")
(def single-tweet-fixture
(first (json/parsed-seq (io/reader (str fixture-path "single_tweet.json")) true)))
(facts "about filtering tweets"
(filtered-tweet {}) => {:screen_name nil, :tweet nil}
(filtered-tweet {:text "tweet", :user {:screen_name "tweety"}}) => {:screen_name "tweety", :tweet "tweet"}
(filtered-tweet single-tweet-fixture) => {:screen_name "izaloko", :tweet "qu por qu kieres saver como poner pablito"})
(facts "about the main routes"
"Bare request returns index file"
(main-routes {:uri "/" :request-method :get})
=> (contains {:status 200
:body "stuff"})
(provided
(resource "public/index.html") => "stuff")
"On redirect from twitter oauth, tokens are stored in session and user is redirected to '/'"
(main-routes {:uri "/twitter_oauth_response"
:request-method :get
:params {:oauth_verifier "verifier" :oauth_token "token"}})
=> (contains {:status 302 :headers {"Location" "/"}})
(provided
(session-get :request-token) => ...request_token...
(access-token-response ...request_token... "verifier") => ...oauth_response...
(session-put! :twitter-oauth ...oauth_response...) => anything))
; These are really integration tests - wrap-oauth is wired in to the app at startup, so can't easily be mocked out
(facts "about wrap-oauth middleware"
"wrap-oauth provides twitter information to later handlers if it is available in the session"
(app {:uri "/auth/status.json" :request-method :get})
=> (contains {:status 200 :body (json/generate-string {:name "<NAME>"})})
(provided
(session-get :twitter-oauth) => {:screen_name "<NAME>ddy"})
"wrap-oauth returns a 401 error containing a twitter redirect url if no twitter information is in the session"
(app {:uri "/auth/status.json" :request-method :get})
=> (contains {:status 401 :body (json/generate-string {:authUrl "the_url"})})
(provided
(session-get :twitter-oauth) => nil
(twitter-request-token) => ...request_token...
(callback-uri ...request_token...) => "the_url"))
| true | (ns twitter-example.core-test
(:use
midje.sweet
twitter-example.core
compojure.core
sandbar.stateful-session
[compojure.response :only [resource]])
(:require
[clj-json.core :as json]
[clojure.java.io :as io]))
(def fixture-path "test/twitter_example/fixtures/")
(def single-tweet-fixture
(first (json/parsed-seq (io/reader (str fixture-path "single_tweet.json")) true)))
(facts "about filtering tweets"
(filtered-tweet {}) => {:screen_name nil, :tweet nil}
(filtered-tweet {:text "tweet", :user {:screen_name "tweety"}}) => {:screen_name "tweety", :tweet "tweet"}
(filtered-tweet single-tweet-fixture) => {:screen_name "izaloko", :tweet "qu por qu kieres saver como poner pablito"})
(facts "about the main routes"
"Bare request returns index file"
(main-routes {:uri "/" :request-method :get})
=> (contains {:status 200
:body "stuff"})
(provided
(resource "public/index.html") => "stuff")
"On redirect from twitter oauth, tokens are stored in session and user is redirected to '/'"
(main-routes {:uri "/twitter_oauth_response"
:request-method :get
:params {:oauth_verifier "verifier" :oauth_token "token"}})
=> (contains {:status 302 :headers {"Location" "/"}})
(provided
(session-get :request-token) => ...request_token...
(access-token-response ...request_token... "verifier") => ...oauth_response...
(session-put! :twitter-oauth ...oauth_response...) => anything))
; These are really integration tests - wrap-oauth is wired in to the app at startup, so can't easily be mocked out
(facts "about wrap-oauth middleware"
"wrap-oauth provides twitter information to later handlers if it is available in the session"
(app {:uri "/auth/status.json" :request-method :get})
=> (contains {:status 200 :body (json/generate-string {:name "PI:NAME:<NAME>END_PI"})})
(provided
(session-get :twitter-oauth) => {:screen_name "PI:NAME:<NAME>END_PIddy"})
"wrap-oauth returns a 401 error containing a twitter redirect url if no twitter information is in the session"
(app {:uri "/auth/status.json" :request-method :get})
=> (contains {:status 401 :body (json/generate-string {:authUrl "the_url"})})
(provided
(session-get :twitter-oauth) => nil
(twitter-request-token) => ...request_token...
(callback-uri ...request_token...) => "the_url"))
|
[
{
"context": "n/generate-string\n {:email @phoenix-user\n :password @phoenix-pass",
"end": 2529,
"score": 0.6732776165008545,
"start": 2516,
"tag": "USERNAME",
"value": "@phoenix-user"
},
{
"context": " @phoenix-user\n :password @phoenix-password\n :org \"tenant\"})\n ",
"end": 2583,
"score": 0.992097020149231,
"start": 2566,
"tag": "PASSWORD",
"value": "@phoenix-password"
}
] | messaging/src/messaging/phoenix.clj | FoxComm/highlander | 10 | (ns messaging.phoenix
(:require [aleph.http :as http]
[compojure.core :refer :all]
[compojure.route :as route]
[messaging.settings :as settings]
[ring.util.response :refer [response]]
[ring.middleware.json :refer [wrap-json-body wrap-json-response]]
[cheshire.core :as json]
[byte-streams :as bs]
[taoensso.timbre :as log]
[environ.core :refer [env]]))
(def description "Provides messaging integration with Mailchimp/Mandrill")
(defn parse-int [s]
(if (integer? s)
s
(Integer/parseInt s)))
(def api-port (delay (parse-int
(or
(:port env)
15054))))
(def api-host (delay (:api-host env)))
(def phoenix-url (delay (:phoenix-url env)))
(def phoenix-user (delay (:phoenix-user env)))
(def phoenix-password (delay (:phoenix-password env)))
(def http-pool (delay (http/connection-pool
{:connection-options {:insecure? true}})))
(defroutes app
(GET "/_settings/schema" [] (response settings/schema))
(GET "/_ping" [] (response {:ok "pong"}))
(POST "/_set-log-level" {body :body}
(let [level (some-> body
(get "level")
keyword)]
(if (log/valid-level? level)
(do
(log/info "Set log level to" level)
(log/set-level! level)
(response {:result "ok"}))
(do
(log/error "Can't set log level to invalid level" level)
{:status 400
:headers {}
:body {:result (str "invalid log level: " level)}}))))
(POST "/_settings/upload" {body :body}
(log/info "Updating Settings: " body)
(settings/update-settings body)
(response {:ok "updated"}))
(route/not-found (response {:error {:code 404 :text "Not found"}})))
;; start-stop
(def phoenix-server (atom nil))
(defn start-phoenix
[]
(log/info (str "Start HTTP API at :" @api-port))
(let [server (http/start-server (-> app
wrap-json-body
wrap-json-response)
{:port @api-port})]
(reset! phoenix-server server)))
(defn stop-phoenix
[]
(when @phoenix-server
(.close @phoenix-server)))
(defn authenticate
[]
(-> (http/post (str @phoenix-url "/v1/public/login")
{:pool @http-pool
:body (json/generate-string
{:email @phoenix-user
:password @phoenix-password
:org "tenant"})
:content-type :json})
deref
:headers
(get "jwt")))
(defn get-order-info
[order-ref]
(let [jwt (authenticate)
request (http/get (str @phoenix-url "/v1/orders/" order-ref)
{:pool @http-pool
:headers {"JWT" jwt}
:content-type :json})
resp (-> request
deref
:body
bs/to-string
json/parse-string)]
resp))
(defn register-plugin
[schema]
(when (empty? @phoenix-url)
(log/error "Phoenix address not set, can't register myself into phoenix :(")
(throw (ex-info "$PHOENIX_URL is empty" {})))
(try
(log/info "Register plugin at phoenix" @phoenix-url)
(let [plugin-info {:name "messaging"
:description description
:apiHost @api-host
:version "1.0"
:apiPort @api-port
:schemaSettings schema}
resp (-> (http/post
(str @phoenix-url "/v1/plugins/register")
{:pool @http-pool
:body (json/generate-string plugin-info)
:content-type :json
:headers {"JWT" (authenticate)}})
deref
:body
bs/to-string
json/parse-string)]
(log/info "Plugin registered at phoenix, resp" resp)
(settings/update-settings (get resp "settings")))
(catch Exception e
(try
(let [error-body (-> (ex-data e) :body bs/to-string)]
(log/error "Can't register plugin at phoenix" error-body))
(catch Exception einner
(log/error "Can't register plugin at phoenix" e)))
(throw e))))
| 65599 | (ns messaging.phoenix
(:require [aleph.http :as http]
[compojure.core :refer :all]
[compojure.route :as route]
[messaging.settings :as settings]
[ring.util.response :refer [response]]
[ring.middleware.json :refer [wrap-json-body wrap-json-response]]
[cheshire.core :as json]
[byte-streams :as bs]
[taoensso.timbre :as log]
[environ.core :refer [env]]))
(def description "Provides messaging integration with Mailchimp/Mandrill")
(defn parse-int [s]
(if (integer? s)
s
(Integer/parseInt s)))
(def api-port (delay (parse-int
(or
(:port env)
15054))))
(def api-host (delay (:api-host env)))
(def phoenix-url (delay (:phoenix-url env)))
(def phoenix-user (delay (:phoenix-user env)))
(def phoenix-password (delay (:phoenix-password env)))
(def http-pool (delay (http/connection-pool
{:connection-options {:insecure? true}})))
(defroutes app
(GET "/_settings/schema" [] (response settings/schema))
(GET "/_ping" [] (response {:ok "pong"}))
(POST "/_set-log-level" {body :body}
(let [level (some-> body
(get "level")
keyword)]
(if (log/valid-level? level)
(do
(log/info "Set log level to" level)
(log/set-level! level)
(response {:result "ok"}))
(do
(log/error "Can't set log level to invalid level" level)
{:status 400
:headers {}
:body {:result (str "invalid log level: " level)}}))))
(POST "/_settings/upload" {body :body}
(log/info "Updating Settings: " body)
(settings/update-settings body)
(response {:ok "updated"}))
(route/not-found (response {:error {:code 404 :text "Not found"}})))
;; start-stop
(def phoenix-server (atom nil))
(defn start-phoenix
[]
(log/info (str "Start HTTP API at :" @api-port))
(let [server (http/start-server (-> app
wrap-json-body
wrap-json-response)
{:port @api-port})]
(reset! phoenix-server server)))
(defn stop-phoenix
[]
(when @phoenix-server
(.close @phoenix-server)))
(defn authenticate
[]
(-> (http/post (str @phoenix-url "/v1/public/login")
{:pool @http-pool
:body (json/generate-string
{:email @phoenix-user
:password <PASSWORD>
:org "tenant"})
:content-type :json})
deref
:headers
(get "jwt")))
(defn get-order-info
[order-ref]
(let [jwt (authenticate)
request (http/get (str @phoenix-url "/v1/orders/" order-ref)
{:pool @http-pool
:headers {"JWT" jwt}
:content-type :json})
resp (-> request
deref
:body
bs/to-string
json/parse-string)]
resp))
(defn register-plugin
[schema]
(when (empty? @phoenix-url)
(log/error "Phoenix address not set, can't register myself into phoenix :(")
(throw (ex-info "$PHOENIX_URL is empty" {})))
(try
(log/info "Register plugin at phoenix" @phoenix-url)
(let [plugin-info {:name "messaging"
:description description
:apiHost @api-host
:version "1.0"
:apiPort @api-port
:schemaSettings schema}
resp (-> (http/post
(str @phoenix-url "/v1/plugins/register")
{:pool @http-pool
:body (json/generate-string plugin-info)
:content-type :json
:headers {"JWT" (authenticate)}})
deref
:body
bs/to-string
json/parse-string)]
(log/info "Plugin registered at phoenix, resp" resp)
(settings/update-settings (get resp "settings")))
(catch Exception e
(try
(let [error-body (-> (ex-data e) :body bs/to-string)]
(log/error "Can't register plugin at phoenix" error-body))
(catch Exception einner
(log/error "Can't register plugin at phoenix" e)))
(throw e))))
| true | (ns messaging.phoenix
(:require [aleph.http :as http]
[compojure.core :refer :all]
[compojure.route :as route]
[messaging.settings :as settings]
[ring.util.response :refer [response]]
[ring.middleware.json :refer [wrap-json-body wrap-json-response]]
[cheshire.core :as json]
[byte-streams :as bs]
[taoensso.timbre :as log]
[environ.core :refer [env]]))
(def description "Provides messaging integration with Mailchimp/Mandrill")
(defn parse-int [s]
(if (integer? s)
s
(Integer/parseInt s)))
(def api-port (delay (parse-int
(or
(:port env)
15054))))
(def api-host (delay (:api-host env)))
(def phoenix-url (delay (:phoenix-url env)))
(def phoenix-user (delay (:phoenix-user env)))
(def phoenix-password (delay (:phoenix-password env)))
(def http-pool (delay (http/connection-pool
{:connection-options {:insecure? true}})))
(defroutes app
(GET "/_settings/schema" [] (response settings/schema))
(GET "/_ping" [] (response {:ok "pong"}))
(POST "/_set-log-level" {body :body}
(let [level (some-> body
(get "level")
keyword)]
(if (log/valid-level? level)
(do
(log/info "Set log level to" level)
(log/set-level! level)
(response {:result "ok"}))
(do
(log/error "Can't set log level to invalid level" level)
{:status 400
:headers {}
:body {:result (str "invalid log level: " level)}}))))
(POST "/_settings/upload" {body :body}
(log/info "Updating Settings: " body)
(settings/update-settings body)
(response {:ok "updated"}))
(route/not-found (response {:error {:code 404 :text "Not found"}})))
;; start-stop
(def phoenix-server (atom nil))
(defn start-phoenix
[]
(log/info (str "Start HTTP API at :" @api-port))
(let [server (http/start-server (-> app
wrap-json-body
wrap-json-response)
{:port @api-port})]
(reset! phoenix-server server)))
(defn stop-phoenix
[]
(when @phoenix-server
(.close @phoenix-server)))
(defn authenticate
[]
(-> (http/post (str @phoenix-url "/v1/public/login")
{:pool @http-pool
:body (json/generate-string
{:email @phoenix-user
:password PI:PASSWORD:<PASSWORD>END_PI
:org "tenant"})
:content-type :json})
deref
:headers
(get "jwt")))
(defn get-order-info
[order-ref]
(let [jwt (authenticate)
request (http/get (str @phoenix-url "/v1/orders/" order-ref)
{:pool @http-pool
:headers {"JWT" jwt}
:content-type :json})
resp (-> request
deref
:body
bs/to-string
json/parse-string)]
resp))
(defn register-plugin
[schema]
(when (empty? @phoenix-url)
(log/error "Phoenix address not set, can't register myself into phoenix :(")
(throw (ex-info "$PHOENIX_URL is empty" {})))
(try
(log/info "Register plugin at phoenix" @phoenix-url)
(let [plugin-info {:name "messaging"
:description description
:apiHost @api-host
:version "1.0"
:apiPort @api-port
:schemaSettings schema}
resp (-> (http/post
(str @phoenix-url "/v1/plugins/register")
{:pool @http-pool
:body (json/generate-string plugin-info)
:content-type :json
:headers {"JWT" (authenticate)}})
deref
:body
bs/to-string
json/parse-string)]
(log/info "Plugin registered at phoenix, resp" resp)
(settings/update-settings (get resp "settings")))
(catch Exception e
(try
(let [error-body (-> (ex-data e) :body bs/to-string)]
(log/error "Can't register plugin at phoenix" error-body))
(catch Exception einner
(log/error "Can't register plugin at phoenix" e)))
(throw e))))
|
[
{
"context": "; Copyright (c) 2021 Mikołaj Kuranowski\n; SPDX-License-Identifier: WTFPL\n(ns day10a\n (:r",
"end": 39,
"score": 0.9997009038925171,
"start": 21,
"tag": "NAME",
"value": "Mikołaj Kuranowski"
}
] | src/day10a.clj | MKuranowski/AdventOfCode2020 | 0 | ; Copyright (c) 2021 Mikołaj Kuranowski
; SPDX-License-Identifier: WTFPL
(ns day10a
(:require [core]))
(defn read-adapters [filename]
(->> filename
core/lines-from-file
(map core/parse-int)
sort))
(defn adapters-with-socket-and-device [filename]
(let [adapters-with-socket (into [0] (read-adapters filename))]
(conj adapters-with-socket (+ 3 (peek adapters-with-socket)))))
(defn differences [adapters]
(->> (map list adapters (rest adapters)) ; Pair element with its next
(map (fn [[a b]] (- b a))))
)
(defn solve [differences]
(* (core/count-if #(= 1 %) differences) (core/count-if #(= 3 %) differences)))
(defn -main [filename]
(->> filename
adapters-with-socket-and-device
differences
solve
prn))
| 117259 | ; Copyright (c) 2021 <NAME>
; SPDX-License-Identifier: WTFPL
(ns day10a
(:require [core]))
(defn read-adapters [filename]
(->> filename
core/lines-from-file
(map core/parse-int)
sort))
(defn adapters-with-socket-and-device [filename]
(let [adapters-with-socket (into [0] (read-adapters filename))]
(conj adapters-with-socket (+ 3 (peek adapters-with-socket)))))
(defn differences [adapters]
(->> (map list adapters (rest adapters)) ; Pair element with its next
(map (fn [[a b]] (- b a))))
)
(defn solve [differences]
(* (core/count-if #(= 1 %) differences) (core/count-if #(= 3 %) differences)))
(defn -main [filename]
(->> filename
adapters-with-socket-and-device
differences
solve
prn))
| true | ; Copyright (c) 2021 PI:NAME:<NAME>END_PI
; SPDX-License-Identifier: WTFPL
(ns day10a
(:require [core]))
(defn read-adapters [filename]
(->> filename
core/lines-from-file
(map core/parse-int)
sort))
(defn adapters-with-socket-and-device [filename]
(let [adapters-with-socket (into [0] (read-adapters filename))]
(conj adapters-with-socket (+ 3 (peek adapters-with-socket)))))
(defn differences [adapters]
(->> (map list adapters (rest adapters)) ; Pair element with its next
(map (fn [[a b]] (- b a))))
)
(defn solve [differences]
(* (core/count-if #(= 1 %) differences) (core/count-if #(= 3 %) differences)))
(defn -main [filename]
(->> filename
adapters-with-socket-and-device
differences
solve
prn))
|
[
{
"context": " :attendees [{:email \"zachary.kim@gmail.com\"}]\n :summary \"Fre",
"end": 8030,
"score": 0.9999229907989502,
"start": 8009,
"tag": "EMAIL",
"value": "zachary.kim@gmail.com"
}
] | src/cljs-browser/rx/browser/gcal.cljs | zk/rx-lib | 0 | (ns rx.browser.gcal
(:require [rx.kitchen-sink :as ks]
[rx.anom :as anom
:refer-macros [<defn <? gol]]
[rx.browser :as browser]
[clojure.core.async :as async
:refer [go <! chan close! put!]]))
(defn <init-gcal-api [{:keys [api-key
client-id
discovery-docs
scopes]}]
(let [ch (chan)]
(gol
(<! (browser/<ensure-script "https://apis.google.com/js/api.js"))
(.load js/gapi "client:auth2"
(fn []
(gol
(let [res (<! (ks/<promise
(.init (.-client js/gapi)
(clj->js
{:apiKey api-key
:clientId client-id
:discoveryDocs discovery-docs
:scope scopes}))))]
(if (anom/? res)
(put! ch res))
(close! ch))))))
ch))
(defn test-stuff []
(browser/<show-component!
[:div "HI"]))
(defn auth-inst []
(.getAuthInstance (.-auth2 js/gapi)))
(defn current-user-profile []
(let [user (.get (.-currentUser (auth-inst)))]
(when user
(let [p (.getBasicProfile user)]
{:id (.getId p)
:name (.getName p)
:given-name (.getGivenName p)
:family-name (.getFamilyName p)
:image-url (.getImageUrl p)
:email (.getEmail p)}))))
(defn is-signed-in-listen [f]
(.listen (.-isSignedIn (auth-inst)) f))
(defn is-signed-in []
(.get (.-isSignedIn (auth-inst))))
(defn <do-sign-in []
(ks/<promise (.signIn (auth-inst))))
(defn <list-events [opts]
(gol
(let [resp (<? (ks/<promise
(.list
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(merge
(js->clj res)
{::call-opts opts
::call-type ::events-list})
(anom/anom
{:desc "Error listing events"
::resp resp})))))
(<defn <delete-event [opts]
(let [resp (<? (ks/<promise
(.delete
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling delete event"
::resp resp}))))
(<defn <update-event [opts]
(let [resp (<? (ks/<promise
(.update
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling delete event"
::resp resp}))))
(<defn <patch-event [opts]
(let [resp (<? (ks/<promise
(.patch
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling patch event"
::resp resp}))))
(<defn <insert-event [opts]
(let [resp (<? (ks/<promise
(.insert
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling insert event"
::resp resp}))))
(<defn <get-calendar [opts]
(let [resp (<? (ks/<promise
(.get
(.. js/gapi -client -calendar -calendars)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling insert event"
::resp resp}))))
(<defn <next [resp]
(if-let [page-token (get resp "page-token")]
(let [{:keys [::call-opts ::call-type]} resp
f (condp = call-type
::events-list
<list-events)]
(<? (f (merge call-opts
{:nextPageToken (get resp "nextPageToken")}))))
(anom/anom
{:desc "Page token not present"})))
(defn tz-offset-now [tz-str]
(let [date (js/Date.)
utc-date (js/Date. (.toLocaleString date "en-US" (clj->js {:timeZone "UTC"})))
tz-date (js/Date. (.toLocaleString date "en-US" (clj->js {:timeZone tz-str})))]
(- (/
(- (.getTime utc-date) (.getTime tz-date))
(* 1000 60 60)))))
(defn tz-offset-str-now [tz-str]
(let [offset (tz-offset-now tz-str)
pad? (< (ks/abs offset) 10)
pos? (>= offset 0)
offset-str (str
(if pos?
"+"
"-")
(if pad? "0")
(* (ks/abs offset) 100))
offset-str (str (apply str (take 3 offset-str))
":"
(apply str (drop 3 offset-str)))]
offset-str))
(defn date-to-iso8601 [date-str tz-str]
(str date-str "T00:00:00" (tz-offset-str-now tz-str)))
(defn <events-for-calendar-day [{:keys [calendarId
tz-str
date-str]}]
(go
(let [res (<! (<list-events
(ks/spy
{:calendarId calendarId
:showDeleted false
:singleEvents true
:timeMin (str date-str "T00:00:00" (tz-offset-str-now tz-str))
:timeMax (str date-str "T23:59:59" (tz-offset-str-now tz-str))})))]
(if (anom/? res)
res
(get res "items")))))
(defn <events-for-calendar-days [{:keys [calendarId
tz-str
days-count
date-str]}]
(go
(let [max-date-str (let [d (js/Date. date-str)]
(.setDate d (+ (.getDate d) days-count))
(ks/date-format
(.getTime d)
"yyyy-MM-dd"))
res (<! (<list-events
(ks/spy
{:calendarId calendarId
:showDeleted false
:singleEvents true
:maxResults 2000
:timeMin (str date-str "T00:00:00" (tz-offset-str-now tz-str))
:timeMax (str max-date-str "T23:59:59" (tz-offset-str-now tz-str))})))]
(if (anom/? res)
res
(get res "items")))))
(comment
(ks/<pp (<get-calendar
{:calendarId "primary"}))
(ks/<pp
(<events-for-calendar-day
{:calendarId "primary"
:tz-str "Pacific/Honolulu"
:date-str "2021-04-08"}))
)
(defn test-create-dummy-event [id]
)
(comment
(<do-sign-in)
(go
(ks/pp (<! (<next (<! (<list-events
{:calendarId "primary"
:timeMin (.toISOString (js/Date.))
:maxResults 1}))))))
(go
(ks/pp (get
(<! (<list-events
{:calendarId "primary"
:timeMin (.toISOString (js/Date.))
}))
"items")))
(go
(ks/pp (count (<! (<events-for-calendar-days
{:calendarId "primary"
:days-count 7
:date-str "2021-04-08"
:tz-str "Pacific/Honolulu"})))))
(->> (get events "items")
(map (fn [item]
(keys item))))
(go
(def event (<! (<insert-event
{:calendarId "primary"
:sendUpdates "none"
:resource {:start {:dateTime (js/Date. (+ (ks/now) (* 1000 60 60 10)))}
:end {:dateTime (js/Date. (+ (ks/now) (* 1000 60 60 10)))}
:attendees [{:email "zachary.kim@gmail.com"}]
:summary "Freeday Test Event"}}))))
(ks/<pp (<patch-event
{:calendarId "primary"
:eventId (get event "id")
:resource
{:description "Testing html desc:<br/>\n\nThis event cancelled by Freeday. <a href=\"https://freeday.zk.dev\">Get your free day too, for free</a>."}}))
(ks/<pp (<delete-event
{:calendarId "primary"
:eventId (get event "id")
:sendUpdates "all"}))
(prn "e" event)
(prn events)
(ks/<pp (<delete-event
{:calendarId "primary"
:eventId "mb8sldcblvik3r9k0j4loedk1o"}))
(<do-sign-in)
)
#_(is-signed-in-listen
(fn [& args]
(prn args)
(.log js/console (first args))))
(comment
(test-stuff)
(go
(time
(ks/pp
)))
(ks/<pp (<init-gcal-api
{:api-key ""
:client-id ""
:discovery-docs ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]
:scopes "https://www.googleapis.com/auth/calendar.events"}))
)
| 5333 | (ns rx.browser.gcal
(:require [rx.kitchen-sink :as ks]
[rx.anom :as anom
:refer-macros [<defn <? gol]]
[rx.browser :as browser]
[clojure.core.async :as async
:refer [go <! chan close! put!]]))
(defn <init-gcal-api [{:keys [api-key
client-id
discovery-docs
scopes]}]
(let [ch (chan)]
(gol
(<! (browser/<ensure-script "https://apis.google.com/js/api.js"))
(.load js/gapi "client:auth2"
(fn []
(gol
(let [res (<! (ks/<promise
(.init (.-client js/gapi)
(clj->js
{:apiKey api-key
:clientId client-id
:discoveryDocs discovery-docs
:scope scopes}))))]
(if (anom/? res)
(put! ch res))
(close! ch))))))
ch))
(defn test-stuff []
(browser/<show-component!
[:div "HI"]))
(defn auth-inst []
(.getAuthInstance (.-auth2 js/gapi)))
(defn current-user-profile []
(let [user (.get (.-currentUser (auth-inst)))]
(when user
(let [p (.getBasicProfile user)]
{:id (.getId p)
:name (.getName p)
:given-name (.getGivenName p)
:family-name (.getFamilyName p)
:image-url (.getImageUrl p)
:email (.getEmail p)}))))
(defn is-signed-in-listen [f]
(.listen (.-isSignedIn (auth-inst)) f))
(defn is-signed-in []
(.get (.-isSignedIn (auth-inst))))
(defn <do-sign-in []
(ks/<promise (.signIn (auth-inst))))
(defn <list-events [opts]
(gol
(let [resp (<? (ks/<promise
(.list
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(merge
(js->clj res)
{::call-opts opts
::call-type ::events-list})
(anom/anom
{:desc "Error listing events"
::resp resp})))))
(<defn <delete-event [opts]
(let [resp (<? (ks/<promise
(.delete
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling delete event"
::resp resp}))))
(<defn <update-event [opts]
(let [resp (<? (ks/<promise
(.update
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling delete event"
::resp resp}))))
(<defn <patch-event [opts]
(let [resp (<? (ks/<promise
(.patch
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling patch event"
::resp resp}))))
(<defn <insert-event [opts]
(let [resp (<? (ks/<promise
(.insert
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling insert event"
::resp resp}))))
(<defn <get-calendar [opts]
(let [resp (<? (ks/<promise
(.get
(.. js/gapi -client -calendar -calendars)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling insert event"
::resp resp}))))
(<defn <next [resp]
(if-let [page-token (get resp "page-token")]
(let [{:keys [::call-opts ::call-type]} resp
f (condp = call-type
::events-list
<list-events)]
(<? (f (merge call-opts
{:nextPageToken (get resp "nextPageToken")}))))
(anom/anom
{:desc "Page token not present"})))
(defn tz-offset-now [tz-str]
(let [date (js/Date.)
utc-date (js/Date. (.toLocaleString date "en-US" (clj->js {:timeZone "UTC"})))
tz-date (js/Date. (.toLocaleString date "en-US" (clj->js {:timeZone tz-str})))]
(- (/
(- (.getTime utc-date) (.getTime tz-date))
(* 1000 60 60)))))
(defn tz-offset-str-now [tz-str]
(let [offset (tz-offset-now tz-str)
pad? (< (ks/abs offset) 10)
pos? (>= offset 0)
offset-str (str
(if pos?
"+"
"-")
(if pad? "0")
(* (ks/abs offset) 100))
offset-str (str (apply str (take 3 offset-str))
":"
(apply str (drop 3 offset-str)))]
offset-str))
(defn date-to-iso8601 [date-str tz-str]
(str date-str "T00:00:00" (tz-offset-str-now tz-str)))
(defn <events-for-calendar-day [{:keys [calendarId
tz-str
date-str]}]
(go
(let [res (<! (<list-events
(ks/spy
{:calendarId calendarId
:showDeleted false
:singleEvents true
:timeMin (str date-str "T00:00:00" (tz-offset-str-now tz-str))
:timeMax (str date-str "T23:59:59" (tz-offset-str-now tz-str))})))]
(if (anom/? res)
res
(get res "items")))))
(defn <events-for-calendar-days [{:keys [calendarId
tz-str
days-count
date-str]}]
(go
(let [max-date-str (let [d (js/Date. date-str)]
(.setDate d (+ (.getDate d) days-count))
(ks/date-format
(.getTime d)
"yyyy-MM-dd"))
res (<! (<list-events
(ks/spy
{:calendarId calendarId
:showDeleted false
:singleEvents true
:maxResults 2000
:timeMin (str date-str "T00:00:00" (tz-offset-str-now tz-str))
:timeMax (str max-date-str "T23:59:59" (tz-offset-str-now tz-str))})))]
(if (anom/? res)
res
(get res "items")))))
(comment
(ks/<pp (<get-calendar
{:calendarId "primary"}))
(ks/<pp
(<events-for-calendar-day
{:calendarId "primary"
:tz-str "Pacific/Honolulu"
:date-str "2021-04-08"}))
)
(defn test-create-dummy-event [id]
)
(comment
(<do-sign-in)
(go
(ks/pp (<! (<next (<! (<list-events
{:calendarId "primary"
:timeMin (.toISOString (js/Date.))
:maxResults 1}))))))
(go
(ks/pp (get
(<! (<list-events
{:calendarId "primary"
:timeMin (.toISOString (js/Date.))
}))
"items")))
(go
(ks/pp (count (<! (<events-for-calendar-days
{:calendarId "primary"
:days-count 7
:date-str "2021-04-08"
:tz-str "Pacific/Honolulu"})))))
(->> (get events "items")
(map (fn [item]
(keys item))))
(go
(def event (<! (<insert-event
{:calendarId "primary"
:sendUpdates "none"
:resource {:start {:dateTime (js/Date. (+ (ks/now) (* 1000 60 60 10)))}
:end {:dateTime (js/Date. (+ (ks/now) (* 1000 60 60 10)))}
:attendees [{:email "<EMAIL>"}]
:summary "Freeday Test Event"}}))))
(ks/<pp (<patch-event
{:calendarId "primary"
:eventId (get event "id")
:resource
{:description "Testing html desc:<br/>\n\nThis event cancelled by Freeday. <a href=\"https://freeday.zk.dev\">Get your free day too, for free</a>."}}))
(ks/<pp (<delete-event
{:calendarId "primary"
:eventId (get event "id")
:sendUpdates "all"}))
(prn "e" event)
(prn events)
(ks/<pp (<delete-event
{:calendarId "primary"
:eventId "mb8sldcblvik3r9k0j4loedk1o"}))
(<do-sign-in)
)
#_(is-signed-in-listen
(fn [& args]
(prn args)
(.log js/console (first args))))
(comment
(test-stuff)
(go
(time
(ks/pp
)))
(ks/<pp (<init-gcal-api
{:api-key ""
:client-id ""
:discovery-docs ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]
:scopes "https://www.googleapis.com/auth/calendar.events"}))
)
| true | (ns rx.browser.gcal
(:require [rx.kitchen-sink :as ks]
[rx.anom :as anom
:refer-macros [<defn <? gol]]
[rx.browser :as browser]
[clojure.core.async :as async
:refer [go <! chan close! put!]]))
(defn <init-gcal-api [{:keys [api-key
client-id
discovery-docs
scopes]}]
(let [ch (chan)]
(gol
(<! (browser/<ensure-script "https://apis.google.com/js/api.js"))
(.load js/gapi "client:auth2"
(fn []
(gol
(let [res (<! (ks/<promise
(.init (.-client js/gapi)
(clj->js
{:apiKey api-key
:clientId client-id
:discoveryDocs discovery-docs
:scope scopes}))))]
(if (anom/? res)
(put! ch res))
(close! ch))))))
ch))
(defn test-stuff []
(browser/<show-component!
[:div "HI"]))
(defn auth-inst []
(.getAuthInstance (.-auth2 js/gapi)))
(defn current-user-profile []
(let [user (.get (.-currentUser (auth-inst)))]
(when user
(let [p (.getBasicProfile user)]
{:id (.getId p)
:name (.getName p)
:given-name (.getGivenName p)
:family-name (.getFamilyName p)
:image-url (.getImageUrl p)
:email (.getEmail p)}))))
(defn is-signed-in-listen [f]
(.listen (.-isSignedIn (auth-inst)) f))
(defn is-signed-in []
(.get (.-isSignedIn (auth-inst))))
(defn <do-sign-in []
(ks/<promise (.signIn (auth-inst))))
(defn <list-events [opts]
(gol
(let [resp (<? (ks/<promise
(.list
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(merge
(js->clj res)
{::call-opts opts
::call-type ::events-list})
(anom/anom
{:desc "Error listing events"
::resp resp})))))
(<defn <delete-event [opts]
(let [resp (<? (ks/<promise
(.delete
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling delete event"
::resp resp}))))
(<defn <update-event [opts]
(let [resp (<? (ks/<promise
(.update
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling delete event"
::resp resp}))))
(<defn <patch-event [opts]
(let [resp (<? (ks/<promise
(.patch
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling patch event"
::resp resp}))))
(<defn <insert-event [opts]
(let [resp (<? (ks/<promise
(.insert
(.. js/gapi -client -calendar -events)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling insert event"
::resp resp}))))
(<defn <get-calendar [opts]
(let [resp (<? (ks/<promise
(.get
(.. js/gapi -client -calendar -calendars)
(clj->js opts))))]
(if-let [res (.-result resp)]
(js->clj res)
(anom/anom
{:desc "Error calling insert event"
::resp resp}))))
(<defn <next [resp]
(if-let [page-token (get resp "page-token")]
(let [{:keys [::call-opts ::call-type]} resp
f (condp = call-type
::events-list
<list-events)]
(<? (f (merge call-opts
{:nextPageToken (get resp "nextPageToken")}))))
(anom/anom
{:desc "Page token not present"})))
(defn tz-offset-now [tz-str]
(let [date (js/Date.)
utc-date (js/Date. (.toLocaleString date "en-US" (clj->js {:timeZone "UTC"})))
tz-date (js/Date. (.toLocaleString date "en-US" (clj->js {:timeZone tz-str})))]
(- (/
(- (.getTime utc-date) (.getTime tz-date))
(* 1000 60 60)))))
(defn tz-offset-str-now [tz-str]
(let [offset (tz-offset-now tz-str)
pad? (< (ks/abs offset) 10)
pos? (>= offset 0)
offset-str (str
(if pos?
"+"
"-")
(if pad? "0")
(* (ks/abs offset) 100))
offset-str (str (apply str (take 3 offset-str))
":"
(apply str (drop 3 offset-str)))]
offset-str))
(defn date-to-iso8601 [date-str tz-str]
(str date-str "T00:00:00" (tz-offset-str-now tz-str)))
(defn <events-for-calendar-day [{:keys [calendarId
tz-str
date-str]}]
(go
(let [res (<! (<list-events
(ks/spy
{:calendarId calendarId
:showDeleted false
:singleEvents true
:timeMin (str date-str "T00:00:00" (tz-offset-str-now tz-str))
:timeMax (str date-str "T23:59:59" (tz-offset-str-now tz-str))})))]
(if (anom/? res)
res
(get res "items")))))
(defn <events-for-calendar-days [{:keys [calendarId
tz-str
days-count
date-str]}]
(go
(let [max-date-str (let [d (js/Date. date-str)]
(.setDate d (+ (.getDate d) days-count))
(ks/date-format
(.getTime d)
"yyyy-MM-dd"))
res (<! (<list-events
(ks/spy
{:calendarId calendarId
:showDeleted false
:singleEvents true
:maxResults 2000
:timeMin (str date-str "T00:00:00" (tz-offset-str-now tz-str))
:timeMax (str max-date-str "T23:59:59" (tz-offset-str-now tz-str))})))]
(if (anom/? res)
res
(get res "items")))))
(comment
(ks/<pp (<get-calendar
{:calendarId "primary"}))
(ks/<pp
(<events-for-calendar-day
{:calendarId "primary"
:tz-str "Pacific/Honolulu"
:date-str "2021-04-08"}))
)
(defn test-create-dummy-event [id]
)
(comment
(<do-sign-in)
(go
(ks/pp (<! (<next (<! (<list-events
{:calendarId "primary"
:timeMin (.toISOString (js/Date.))
:maxResults 1}))))))
(go
(ks/pp (get
(<! (<list-events
{:calendarId "primary"
:timeMin (.toISOString (js/Date.))
}))
"items")))
(go
(ks/pp (count (<! (<events-for-calendar-days
{:calendarId "primary"
:days-count 7
:date-str "2021-04-08"
:tz-str "Pacific/Honolulu"})))))
(->> (get events "items")
(map (fn [item]
(keys item))))
(go
(def event (<! (<insert-event
{:calendarId "primary"
:sendUpdates "none"
:resource {:start {:dateTime (js/Date. (+ (ks/now) (* 1000 60 60 10)))}
:end {:dateTime (js/Date. (+ (ks/now) (* 1000 60 60 10)))}
:attendees [{:email "PI:EMAIL:<EMAIL>END_PI"}]
:summary "Freeday Test Event"}}))))
(ks/<pp (<patch-event
{:calendarId "primary"
:eventId (get event "id")
:resource
{:description "Testing html desc:<br/>\n\nThis event cancelled by Freeday. <a href=\"https://freeday.zk.dev\">Get your free day too, for free</a>."}}))
(ks/<pp (<delete-event
{:calendarId "primary"
:eventId (get event "id")
:sendUpdates "all"}))
(prn "e" event)
(prn events)
(ks/<pp (<delete-event
{:calendarId "primary"
:eventId "mb8sldcblvik3r9k0j4loedk1o"}))
(<do-sign-in)
)
#_(is-signed-in-listen
(fn [& args]
(prn args)
(.log js/console (first args))))
(comment
(test-stuff)
(go
(time
(ks/pp
)))
(ks/<pp (<init-gcal-api
{:api-key ""
:client-id ""
:discovery-docs ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]
:scopes "https://www.googleapis.com/auth/calendar.events"}))
)
|
[
{
"context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis",
"end": 33,
"score": 0.9998489022254944,
"start": 19,
"tag": "NAME",
"value": "Nicola Mometto"
},
{
"context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter",
"end": 46,
"score": 0.9998348951339722,
"start": 35,
"tag": "NAME",
"value": "Rich Hickey"
}
] | tools.analyzer/resources/tools.analyzer.js-tools.analyzer.js-0.1.0-beta5/src/main/clojure/clojure/tools/analyzer/passes/js/analyze_host_expr.clj | abhi18av/ClojureToolsOCaml | 0 | ;; Copyright (c) Nicola Mometto, Rich Hickey & contributors.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns clojure.tools.analyzer.passes.js.analyze-host-expr
(:require [clojure.tools.analyzer.env :as env]
[clojure.tools.analyzer.utils :refer [resolve-ns resolve-var]]))
(defmulti analyze-host-expr
"Transform :host-interop nodes into :host-call, transform
:maybe-class or :maybe-host-form nodes resolvable to js vars
into :js-var nodes"
{:pass-info {:walk :any :depends #{}}}
:op)
(defmethod analyze-host-expr :default [ast] ast)
(defmethod analyze-host-expr :host-interop
[{:keys [m-or-f target] :as ast}]
(merge (dissoc ast :m-or-f)
{:op :host-call
:method m-or-f
:args []
:children [:target :args]}))
(defmethod analyze-host-expr :maybe-class
[{:keys [class env] :as ast}]
(if-let [v (resolve-var class env)]
(merge (dissoc ast :class)
{:op :js-var
:var v
:assignable? true})
ast))
(defmethod analyze-host-expr :maybe-host-form
[{:keys [class field env form] :as ast}]
(cond
(= 'js class)
(merge (dissoc ast :field :class)
{:op :js-var
:var {:op :js-var
:name field
:ns nil}
:assignable? true})
(get-in (env/deref-env) [:namespaces (resolve-ns class env) :js-namespace])
(let [field (or (:name (resolve-var form env)) field)]
(merge (dissoc ast :field :class)
{:op :js-var
:var {:op :js-var
:name field
:ns (resolve-ns class env)}
:assignable? true}))
:else
ast))
| 88981 | ;; Copyright (c) <NAME>, <NAME> & contributors.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns clojure.tools.analyzer.passes.js.analyze-host-expr
(:require [clojure.tools.analyzer.env :as env]
[clojure.tools.analyzer.utils :refer [resolve-ns resolve-var]]))
(defmulti analyze-host-expr
"Transform :host-interop nodes into :host-call, transform
:maybe-class or :maybe-host-form nodes resolvable to js vars
into :js-var nodes"
{:pass-info {:walk :any :depends #{}}}
:op)
(defmethod analyze-host-expr :default [ast] ast)
(defmethod analyze-host-expr :host-interop
[{:keys [m-or-f target] :as ast}]
(merge (dissoc ast :m-or-f)
{:op :host-call
:method m-or-f
:args []
:children [:target :args]}))
(defmethod analyze-host-expr :maybe-class
[{:keys [class env] :as ast}]
(if-let [v (resolve-var class env)]
(merge (dissoc ast :class)
{:op :js-var
:var v
:assignable? true})
ast))
(defmethod analyze-host-expr :maybe-host-form
[{:keys [class field env form] :as ast}]
(cond
(= 'js class)
(merge (dissoc ast :field :class)
{:op :js-var
:var {:op :js-var
:name field
:ns nil}
:assignable? true})
(get-in (env/deref-env) [:namespaces (resolve-ns class env) :js-namespace])
(let [field (or (:name (resolve-var form env)) field)]
(merge (dissoc ast :field :class)
{:op :js-var
:var {:op :js-var
:name field
:ns (resolve-ns class env)}
:assignable? true}))
:else
ast))
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns clojure.tools.analyzer.passes.js.analyze-host-expr
(:require [clojure.tools.analyzer.env :as env]
[clojure.tools.analyzer.utils :refer [resolve-ns resolve-var]]))
(defmulti analyze-host-expr
"Transform :host-interop nodes into :host-call, transform
:maybe-class or :maybe-host-form nodes resolvable to js vars
into :js-var nodes"
{:pass-info {:walk :any :depends #{}}}
:op)
(defmethod analyze-host-expr :default [ast] ast)
(defmethod analyze-host-expr :host-interop
[{:keys [m-or-f target] :as ast}]
(merge (dissoc ast :m-or-f)
{:op :host-call
:method m-or-f
:args []
:children [:target :args]}))
(defmethod analyze-host-expr :maybe-class
[{:keys [class env] :as ast}]
(if-let [v (resolve-var class env)]
(merge (dissoc ast :class)
{:op :js-var
:var v
:assignable? true})
ast))
(defmethod analyze-host-expr :maybe-host-form
[{:keys [class field env form] :as ast}]
(cond
(= 'js class)
(merge (dissoc ast :field :class)
{:op :js-var
:var {:op :js-var
:name field
:ns nil}
:assignable? true})
(get-in (env/deref-env) [:namespaces (resolve-ns class env) :js-namespace])
(let [field (or (:name (resolve-var form env)) field)]
(merge (dissoc ast :field :class)
{:op :js-var
:var {:op :js-var
:name field
:ns (resolve-ns class env)}
:assignable? true}))
:else
ast))
|
[
{
"context": "ropositions\"]\n [:a (merge text {:href \"mailto:arturdumchev@gmail.com\"})\n \"arturdumchev@gmail.com\"]\n [:br]\n ",
"end": 809,
"score": 0.9999261498451233,
"start": 787,
"tag": "EMAIL",
"value": "arturdumchev@gmail.com"
},
{
"context": "t {:href \"mailto:arturdumchev@gmail.com\"})\n \"arturdumchev@gmail.com\"]\n [:br]\n [:a {:href \"https://github.com/",
"end": 842,
"score": 0.9999281764030457,
"start": 820,
"tag": "EMAIL",
"value": "arturdumchev@gmail.com"
},
{
"context": "\"]\n [:br]\n [:a {:href \"https://github.com/liverm0r/Plus-Minus-Fullstack/\"}\n \"github\"]\n [:p ",
"end": 900,
"score": 0.9983376264572144,
"start": 892,
"tag": "USERNAME",
"value": "liverm0r"
}
] | src/cljs/plus_minus/game/about.cljs | Liverm0r/plusminus.me | 3 | (ns plus-minus.game.about
(:require [plus-minus.app-db :as db]
[plus-minus.components.theme :refer [color]]))
(defn component []
(let [text {:style {:color (color :text)}}
title {:style {:color (color :blue)}}]
[:div.content
[:h5 title "Rules"]
[:p text
"In this turn based game you need to get more points than your oppenent." [:br]
"Select a number from the colored line and this number will be added to your points." [:br]
"Perky oppenent will have to choose from the perpendicular line where you've just moved."]
[:h5 title "Project state"]
[:p text
"This project is under active development." [:br]
"Feel free to contact me if you have any issues or propositions"]
[:a (merge text {:href "mailto:arturdumchev@gmail.com"})
"arturdumchev@gmail.com"]
[:br]
[:a {:href "https://github.com/liverm0r/Plus-Minus-Fullstack/"}
"github"]
[:p text "published with "
[:a {:href "https://m.do.co/c/edb551a6bfca"} "digitalocean.com"]]]))
| 47402 | (ns plus-minus.game.about
(:require [plus-minus.app-db :as db]
[plus-minus.components.theme :refer [color]]))
(defn component []
(let [text {:style {:color (color :text)}}
title {:style {:color (color :blue)}}]
[:div.content
[:h5 title "Rules"]
[:p text
"In this turn based game you need to get more points than your oppenent." [:br]
"Select a number from the colored line and this number will be added to your points." [:br]
"Perky oppenent will have to choose from the perpendicular line where you've just moved."]
[:h5 title "Project state"]
[:p text
"This project is under active development." [:br]
"Feel free to contact me if you have any issues or propositions"]
[:a (merge text {:href "mailto:<EMAIL>"})
"<EMAIL>"]
[:br]
[:a {:href "https://github.com/liverm0r/Plus-Minus-Fullstack/"}
"github"]
[:p text "published with "
[:a {:href "https://m.do.co/c/edb551a6bfca"} "digitalocean.com"]]]))
| true | (ns plus-minus.game.about
(:require [plus-minus.app-db :as db]
[plus-minus.components.theme :refer [color]]))
(defn component []
(let [text {:style {:color (color :text)}}
title {:style {:color (color :blue)}}]
[:div.content
[:h5 title "Rules"]
[:p text
"In this turn based game you need to get more points than your oppenent." [:br]
"Select a number from the colored line and this number will be added to your points." [:br]
"Perky oppenent will have to choose from the perpendicular line where you've just moved."]
[:h5 title "Project state"]
[:p text
"This project is under active development." [:br]
"Feel free to contact me if you have any issues or propositions"]
[:a (merge text {:href "mailto:PI:EMAIL:<EMAIL>END_PI"})
"PI:EMAIL:<EMAIL>END_PI"]
[:br]
[:a {:href "https://github.com/liverm0r/Plus-Minus-Fullstack/"}
"github"]
[:p text "published with "
[:a {:href "https://m.do.co/c/edb551a6bfca"} "digitalocean.com"]]]))
|
[
{
"context": " \"sink-test\"\n :bootstrap.servers \"127.0.0.1:9092\"\n :linger.ms 0}})\n ; wit",
"end": 2887,
"score": 0.9997045993804932,
"start": 2878,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " \"sink-test\"\n :bootstrap.servers \"127.0.0.1:9092\"}})\n ; with headers\n (store!\n [{:key ",
"end": 3083,
"score": 0.9997075200080872,
"start": 3074,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "92\"}})\n ; with headers\n (store!\n [{:key \"test\"\n :value {:test \"test\"}\n :headers {:t",
"end": 3140,
"score": 0.5241341590881348,
"start": 3136,
"tag": "KEY",
"value": "test"
},
{
"context": " \"sink-test\"\n :bootstrap.servers \"127.0.0.1:9092\"}}))\n",
"end": 3302,
"score": 0.9997178316116333,
"start": 3293,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | src/sink/kafka.clj | vinted/kafka-elasticsearch-tool | 4 | (ns sink.kafka
(:require [clojure.tools.logging :as log]
[core.json :as json]
[core.properties :as properties])
(:import (java.time Duration)
(java.util UUID)
(org.apache.kafka.clients.producer KafkaProducer ProducerRecord ProducerConfig Callback)
(org.apache.kafka.common.serialization StringSerializer)
(org.apache.kafka.common.header.internals RecordHeader)))
(def not-producer-keys [:topic :encode-value? :implementation])
(defn kafka-producer
"Supported options are http://kafka.apache.org/documentation.html#producerconfigs
Keys in the opts can be either keywords or strings."
[opts]
(let [opts (apply dissoc opts not-producer-keys)]
(KafkaProducer.
(doto (properties/opts->properties opts)
; Set the required defaults properties for the kafka producer
(.put ProducerConfig/CLIENT_ID_CONFIG
(or (get opts :client.id) (get opts "client.id")
(str "ESToolsKafkaProducer-" (UUID/randomUUID))))
(.put ProducerConfig/KEY_SERIALIZER_CLASS_CONFIG (.getName StringSerializer))
(.put ProducerConfig/VALUE_SERIALIZER_CLASS_CONFIG (.getName StringSerializer))))))
(defn map->headers [r]
(map (fn [[k v]] (RecordHeader. (name k) (.getBytes (str v))))
(remove (fn [[_ v]] (empty? v)) r)))
(defn store!
"Records is a list of maps {:keys String :record Map :headers Map}.
It should be possible to JSON encode the :record
opts must contain :sink which is a map with the Kafka Consumer opts either
with string of keyword keys. Also, some additional keys:
:topic - name of the topic to which to store the records
:encode-value? - whether to JSON encode value, default true"
[records opts]
(properties/opts-valid? :topic (:sink opts))
(let [sink-opts (:sink opts)
^KafkaProducer producer (kafka-producer sink-opts)
topic (:topic sink-opts)]
(doseq [r records]
(try
(.send producer
(ProducerRecord. topic nil nil
(:key r)
(if (false? (:encode-value? sink-opts))
(:value r)
(json/encode (:value r)))
(map->headers (:headers r)))
(reify Callback
(onCompletion [this metadata exception]
(when exception
(println metadata exception)))))
(catch Exception e
(log/errorf "Failed to store record '%s' in kafka because '%s'" r e))))
(log/infof "Flushing records")
(.flush producer)
(log/infof "Flushed")
(.close producer (Duration/ofSeconds 2))))
(comment
; without the key
(store!
[{:value {:test "test-1"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"
:linger.ms 0}})
; with the key
(store!
[{:key "test" :value {:test "test"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"}})
; with headers
(store!
[{:key "test"
:value {:test "test"}
:headers {:test-header "test-header"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"}}))
| 64986 | (ns sink.kafka
(:require [clojure.tools.logging :as log]
[core.json :as json]
[core.properties :as properties])
(:import (java.time Duration)
(java.util UUID)
(org.apache.kafka.clients.producer KafkaProducer ProducerRecord ProducerConfig Callback)
(org.apache.kafka.common.serialization StringSerializer)
(org.apache.kafka.common.header.internals RecordHeader)))
(def not-producer-keys [:topic :encode-value? :implementation])
(defn kafka-producer
"Supported options are http://kafka.apache.org/documentation.html#producerconfigs
Keys in the opts can be either keywords or strings."
[opts]
(let [opts (apply dissoc opts not-producer-keys)]
(KafkaProducer.
(doto (properties/opts->properties opts)
; Set the required defaults properties for the kafka producer
(.put ProducerConfig/CLIENT_ID_CONFIG
(or (get opts :client.id) (get opts "client.id")
(str "ESToolsKafkaProducer-" (UUID/randomUUID))))
(.put ProducerConfig/KEY_SERIALIZER_CLASS_CONFIG (.getName StringSerializer))
(.put ProducerConfig/VALUE_SERIALIZER_CLASS_CONFIG (.getName StringSerializer))))))
(defn map->headers [r]
(map (fn [[k v]] (RecordHeader. (name k) (.getBytes (str v))))
(remove (fn [[_ v]] (empty? v)) r)))
(defn store!
"Records is a list of maps {:keys String :record Map :headers Map}.
It should be possible to JSON encode the :record
opts must contain :sink which is a map with the Kafka Consumer opts either
with string of keyword keys. Also, some additional keys:
:topic - name of the topic to which to store the records
:encode-value? - whether to JSON encode value, default true"
[records opts]
(properties/opts-valid? :topic (:sink opts))
(let [sink-opts (:sink opts)
^KafkaProducer producer (kafka-producer sink-opts)
topic (:topic sink-opts)]
(doseq [r records]
(try
(.send producer
(ProducerRecord. topic nil nil
(:key r)
(if (false? (:encode-value? sink-opts))
(:value r)
(json/encode (:value r)))
(map->headers (:headers r)))
(reify Callback
(onCompletion [this metadata exception]
(when exception
(println metadata exception)))))
(catch Exception e
(log/errorf "Failed to store record '%s' in kafka because '%s'" r e))))
(log/infof "Flushing records")
(.flush producer)
(log/infof "Flushed")
(.close producer (Duration/ofSeconds 2))))
(comment
; without the key
(store!
[{:value {:test "test-1"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"
:linger.ms 0}})
; with the key
(store!
[{:key "test" :value {:test "test"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"}})
; with headers
(store!
[{:key "<KEY>"
:value {:test "test"}
:headers {:test-header "test-header"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"}}))
| true | (ns sink.kafka
(:require [clojure.tools.logging :as log]
[core.json :as json]
[core.properties :as properties])
(:import (java.time Duration)
(java.util UUID)
(org.apache.kafka.clients.producer KafkaProducer ProducerRecord ProducerConfig Callback)
(org.apache.kafka.common.serialization StringSerializer)
(org.apache.kafka.common.header.internals RecordHeader)))
(def not-producer-keys [:topic :encode-value? :implementation])
(defn kafka-producer
"Supported options are http://kafka.apache.org/documentation.html#producerconfigs
Keys in the opts can be either keywords or strings."
[opts]
(let [opts (apply dissoc opts not-producer-keys)]
(KafkaProducer.
(doto (properties/opts->properties opts)
; Set the required defaults properties for the kafka producer
(.put ProducerConfig/CLIENT_ID_CONFIG
(or (get opts :client.id) (get opts "client.id")
(str "ESToolsKafkaProducer-" (UUID/randomUUID))))
(.put ProducerConfig/KEY_SERIALIZER_CLASS_CONFIG (.getName StringSerializer))
(.put ProducerConfig/VALUE_SERIALIZER_CLASS_CONFIG (.getName StringSerializer))))))
(defn map->headers [r]
(map (fn [[k v]] (RecordHeader. (name k) (.getBytes (str v))))
(remove (fn [[_ v]] (empty? v)) r)))
(defn store!
"Records is a list of maps {:keys String :record Map :headers Map}.
It should be possible to JSON encode the :record
opts must contain :sink which is a map with the Kafka Consumer opts either
with string of keyword keys. Also, some additional keys:
:topic - name of the topic to which to store the records
:encode-value? - whether to JSON encode value, default true"
[records opts]
(properties/opts-valid? :topic (:sink opts))
(let [sink-opts (:sink opts)
^KafkaProducer producer (kafka-producer sink-opts)
topic (:topic sink-opts)]
(doseq [r records]
(try
(.send producer
(ProducerRecord. topic nil nil
(:key r)
(if (false? (:encode-value? sink-opts))
(:value r)
(json/encode (:value r)))
(map->headers (:headers r)))
(reify Callback
(onCompletion [this metadata exception]
(when exception
(println metadata exception)))))
(catch Exception e
(log/errorf "Failed to store record '%s' in kafka because '%s'" r e))))
(log/infof "Flushing records")
(.flush producer)
(log/infof "Flushed")
(.close producer (Duration/ofSeconds 2))))
(comment
; without the key
(store!
[{:value {:test "test-1"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"
:linger.ms 0}})
; with the key
(store!
[{:key "test" :value {:test "test"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"}})
; with headers
(store!
[{:key "PI:KEY:<KEY>END_PI"
:value {:test "test"}
:headers {:test-header "test-header"}}]
{:sink {:topic "sink-test"
:bootstrap.servers "127.0.0.1:9092"}}))
|
[
{
"context": "sed\n in generated templates.\"\n :author \"Simon Brooke\"}\n adl-support.tags\n (:require [clojure.string ",
"end": 137,
"score": 0.9998873472213745,
"start": 125,
"tag": "NAME",
"value": "Simon Brooke"
},
{
"context": "nse for more details.\n;;;;\n;;;; Copyright (C) 2018 Simon Brooke\n;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 854,
"score": 0.9998797178268433,
"start": 842,
"tag": "NAME",
"value": "Simon Brooke"
}
] | src/adl_support/tags.clj | simon-brooke/adl-support | 0 | (ns ^{:doc "Application Description Language support - custom Selmer tags used
in generated templates."
:author "Simon Brooke"}
adl-support.tags
(:require [clojure.string :refer [split]]
[selmer.parser :as p]
[selmer.tags :as t]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; adl-support.tags: selmer tags required by ADL selmer views.
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the MIT-style licence provided; see LICENSE.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; License for more details.
;;;;
;;;; Copyright (C) 2018 Simon Brooke
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn if-member-of-permitted
"If at least one of these `args` matches some group name in the `:user-roles`
of this `context`, return this `success`, else this `failure`."
[args context success failure]
(if
(and
(seq? args)
(set? (:user-roles context))
(some (:user-roles context) args))
success
failure))
(defn parse-arg
[arg context]
(cond
(number? arg)
arg
(number? (read-string arg))
(read-string arg)
(= \" (first arg))
(.substring arg 1 (dec (.length arg)))
(and (= \: (first arg)) (> (count arg) 1))
(keyword (subs arg 1))
:else
(get-in context (map keyword (split arg #"\.")))))
(defn add-tags []
"Add custom tags required by ADL-generated code to the parser's tags."
(p/add-tag! :ifmemberof
(fn [args context content]
(if-member-of-permitted
args context
(get-in content [:ifmemberof :content])
(get-in content [:else :content])))
:else
(fn [args context content]
"")
:endifmemberof)
(p/add-tag! :ifcontains
(fn [[c v] context content]
(let [value (parse-arg v context)
collection (parse-arg c context)]
(if
(some
#(= % value)
collection)
(get-in content [:ifcontains :content])
(get-in content [:else :content]))))
:else
(fn [args context content]
"")
:endifcontains))
(add-tags)
| 57690 | (ns ^{:doc "Application Description Language support - custom Selmer tags used
in generated templates."
:author "<NAME>"}
adl-support.tags
(:require [clojure.string :refer [split]]
[selmer.parser :as p]
[selmer.tags :as t]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; adl-support.tags: selmer tags required by ADL selmer views.
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the MIT-style licence provided; see LICENSE.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; License for more details.
;;;;
;;;; Copyright (C) 2018 <NAME>
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn if-member-of-permitted
"If at least one of these `args` matches some group name in the `:user-roles`
of this `context`, return this `success`, else this `failure`."
[args context success failure]
(if
(and
(seq? args)
(set? (:user-roles context))
(some (:user-roles context) args))
success
failure))
(defn parse-arg
[arg context]
(cond
(number? arg)
arg
(number? (read-string arg))
(read-string arg)
(= \" (first arg))
(.substring arg 1 (dec (.length arg)))
(and (= \: (first arg)) (> (count arg) 1))
(keyword (subs arg 1))
:else
(get-in context (map keyword (split arg #"\.")))))
(defn add-tags []
"Add custom tags required by ADL-generated code to the parser's tags."
(p/add-tag! :ifmemberof
(fn [args context content]
(if-member-of-permitted
args context
(get-in content [:ifmemberof :content])
(get-in content [:else :content])))
:else
(fn [args context content]
"")
:endifmemberof)
(p/add-tag! :ifcontains
(fn [[c v] context content]
(let [value (parse-arg v context)
collection (parse-arg c context)]
(if
(some
#(= % value)
collection)
(get-in content [:ifcontains :content])
(get-in content [:else :content]))))
:else
(fn [args context content]
"")
:endifcontains))
(add-tags)
| true | (ns ^{:doc "Application Description Language support - custom Selmer tags used
in generated templates."
:author "PI:NAME:<NAME>END_PI"}
adl-support.tags
(:require [clojure.string :refer [split]]
[selmer.parser :as p]
[selmer.tags :as t]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; adl-support.tags: selmer tags required by ADL selmer views.
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the MIT-style licence provided; see LICENSE.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; License for more details.
;;;;
;;;; Copyright (C) 2018 PI:NAME:<NAME>END_PI
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn if-member-of-permitted
"If at least one of these `args` matches some group name in the `:user-roles`
of this `context`, return this `success`, else this `failure`."
[args context success failure]
(if
(and
(seq? args)
(set? (:user-roles context))
(some (:user-roles context) args))
success
failure))
(defn parse-arg
[arg context]
(cond
(number? arg)
arg
(number? (read-string arg))
(read-string arg)
(= \" (first arg))
(.substring arg 1 (dec (.length arg)))
(and (= \: (first arg)) (> (count arg) 1))
(keyword (subs arg 1))
:else
(get-in context (map keyword (split arg #"\.")))))
(defn add-tags []
"Add custom tags required by ADL-generated code to the parser's tags."
(p/add-tag! :ifmemberof
(fn [args context content]
(if-member-of-permitted
args context
(get-in content [:ifmemberof :content])
(get-in content [:else :content])))
:else
(fn [args context content]
"")
:endifmemberof)
(p/add-tag! :ifcontains
(fn [[c v] context content]
(let [value (parse-arg v context)
collection (parse-arg c context)]
(if
(some
#(= % value)
collection)
(get-in content [:ifcontains :content])
(get-in content [:else :content]))))
:else
(fn [args context content]
"")
:endifcontains))
(add-tags)
|
[
{
"context": ";; Copyright (c) Stuart Sierra, 2012. All rights reserved. The use and\n;; distri",
"end": 30,
"score": 0.9998875260353088,
"start": 17,
"tag": "NAME",
"value": "Stuart Sierra"
},
{
"context": "or any other, from this software.\n\n(ns ^{:author \"Stuart Sierra\"\n :doc \"Dependency tracker which can compute",
"end": 493,
"score": 0.9998931288719177,
"start": 480,
"tag": "NAME",
"value": "Stuart Sierra"
}
] | server/target/clojure/tools/namespace/track.clj | OctavioBR/healthcheck | 0 | ;; Copyright (c) Stuart Sierra, 2012. 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 ^{:author "Stuart Sierra"
:doc "Dependency tracker which can compute which namespaces need to be
reloaded after files have changed. This is the low-level
implementation that requires you to find the namespace dependencies
yourself: most uses will interact with the wrappers in
clojure.tools.namespace.file and clojure.tools.namespace.dir or the
public API in clojure.tools.namespace.repl."}
clojure.tools.namespace.track
(:refer-clojure :exclude (remove))
(:require [clojure.set :as set]
[clojure.tools.namespace.dependency :as dep]))
(defn- remove-deps [deps names]
(reduce dep/remove-node deps names))
(defn- add-deps [deps depmap]
(reduce (fn [ds [name dependencies]]
(reduce (fn [g dep] (dep/depend g name dep))
ds dependencies))
deps depmap))
(defn- update-deps [deps depmap]
(-> deps
(remove-deps (keys depmap))
(add-deps depmap)))
(defn- affected-namespaces [deps names]
(set/union (set names)
(dep/transitive-dependents-set deps names)))
(defn add
"Returns an updated dependency tracker with new/updated namespaces.
Depmap is a map describing the new or modified namespaces. Keys in
the map are namespace names (symbols). Values in the map are sets of
symbols naming the direct dependencies of each namespace. For
example, assuming these ns declarations:
(ns alpha (:require beta))
(ns beta (:require gamma delta))
the depmap would look like this:
{alpha #{beta}
beta #{gamma delta}}
After adding new/updated namespaces, the dependency tracker will
have two lists associated with the following keys:
:clojure.tools.namespace.track/unload
is the list of namespaces that need to be removed
:clojure.tools.namespace.track/load
is the list of namespaces that need to be reloaded
To reload namespaces in the correct order, first remove/unload all
namespaces in the 'unload' list, then (re)load all namespaces in the
'load' list. The clojure.tools.namespace.reload namespace has
functions to do this."
[tracker depmap]
(let [{load ::load
unload ::unload
deps ::deps
:or {load (), unload (), deps (dep/graph)}} tracker
new-deps (update-deps deps depmap)
changed (affected-namespaces new-deps (keys depmap))
;; With a new tracker, old dependencies are empty, so
;; unload order will be undefined unless we use new
;; dependencies (TNS-20).
old-deps (if (empty? (dep/nodes deps)) new-deps deps)]
(assoc tracker
::deps new-deps
::unload (distinct
(concat (reverse (sort (dep/topo-comparator old-deps) changed))
unload))
::load (distinct
(concat (sort (dep/topo-comparator new-deps) changed)
load)))))
(defn remove
"Returns an updated dependency tracker from which the namespaces
(symbols) have been removed. The ::unload and ::load lists are
populated as with 'add'."
[tracker names]
(let [{load ::load
unload ::unload
deps ::deps
:or {load (), unload (), deps (dep/graph)}} tracker
known (set (dep/nodes deps))
removed-names (filter known names)
new-deps (remove-deps deps removed-names)
changed (affected-namespaces deps removed-names)]
(assoc tracker
::deps new-deps
::unload (distinct
(concat (reverse (sort (dep/topo-comparator deps) changed))
unload))
::load (distinct
(filter (complement (set removed-names))
(concat (sort (dep/topo-comparator new-deps) changed)
load))))))
(defn tracker
"Returns a new, empty dependency tracker"
[]
{})
(comment
;; Structure of the namespace tracker map
{;; Dependency graph of namespace names (symbols) as defined in
;; clojure.tools.namespace.dependency/graph
:clojure.tools.namespace.track/deps {}
;; Ordered list of namespace names (symbols) that need to be
;; removed to bring the running system into agreement with the
;; source files.
:clojure.tools.namespace.track/unload ()
;; Ordered list of namespace names (symbols) that need to be
;; (re)loaded to bring the running system into agreement with the
;; source files.
:clojure.tools.namespace.track/load ()
;; Added by clojure.tools.namespace.file: Map from source files
;; (java.io.File) to the names (symbols) of namespaces they
;; represent.
:clojure.tools.namespace.file/filemap {}
;; Added by clojure.tools.namespace.dir: Set of source files
;; (java.io.File) which have been seen by this dependency tracker;
;; used to determine when files have been deleted.
:clojure.tools.namespace.dir/files #{}
;; Added by clojure.tools.namespace.dir: Instant when the
;; directories were last scanned, as returned by
;; System/currentTimeMillis.
:clojure.tools.namespace.dir/time 1405201862262})
| 32937 | ;; Copyright (c) <NAME>, 2012. 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 ^{:author "<NAME>"
:doc "Dependency tracker which can compute which namespaces need to be
reloaded after files have changed. This is the low-level
implementation that requires you to find the namespace dependencies
yourself: most uses will interact with the wrappers in
clojure.tools.namespace.file and clojure.tools.namespace.dir or the
public API in clojure.tools.namespace.repl."}
clojure.tools.namespace.track
(:refer-clojure :exclude (remove))
(:require [clojure.set :as set]
[clojure.tools.namespace.dependency :as dep]))
(defn- remove-deps [deps names]
(reduce dep/remove-node deps names))
(defn- add-deps [deps depmap]
(reduce (fn [ds [name dependencies]]
(reduce (fn [g dep] (dep/depend g name dep))
ds dependencies))
deps depmap))
(defn- update-deps [deps depmap]
(-> deps
(remove-deps (keys depmap))
(add-deps depmap)))
(defn- affected-namespaces [deps names]
(set/union (set names)
(dep/transitive-dependents-set deps names)))
(defn add
"Returns an updated dependency tracker with new/updated namespaces.
Depmap is a map describing the new or modified namespaces. Keys in
the map are namespace names (symbols). Values in the map are sets of
symbols naming the direct dependencies of each namespace. For
example, assuming these ns declarations:
(ns alpha (:require beta))
(ns beta (:require gamma delta))
the depmap would look like this:
{alpha #{beta}
beta #{gamma delta}}
After adding new/updated namespaces, the dependency tracker will
have two lists associated with the following keys:
:clojure.tools.namespace.track/unload
is the list of namespaces that need to be removed
:clojure.tools.namespace.track/load
is the list of namespaces that need to be reloaded
To reload namespaces in the correct order, first remove/unload all
namespaces in the 'unload' list, then (re)load all namespaces in the
'load' list. The clojure.tools.namespace.reload namespace has
functions to do this."
[tracker depmap]
(let [{load ::load
unload ::unload
deps ::deps
:or {load (), unload (), deps (dep/graph)}} tracker
new-deps (update-deps deps depmap)
changed (affected-namespaces new-deps (keys depmap))
;; With a new tracker, old dependencies are empty, so
;; unload order will be undefined unless we use new
;; dependencies (TNS-20).
old-deps (if (empty? (dep/nodes deps)) new-deps deps)]
(assoc tracker
::deps new-deps
::unload (distinct
(concat (reverse (sort (dep/topo-comparator old-deps) changed))
unload))
::load (distinct
(concat (sort (dep/topo-comparator new-deps) changed)
load)))))
(defn remove
"Returns an updated dependency tracker from which the namespaces
(symbols) have been removed. The ::unload and ::load lists are
populated as with 'add'."
[tracker names]
(let [{load ::load
unload ::unload
deps ::deps
:or {load (), unload (), deps (dep/graph)}} tracker
known (set (dep/nodes deps))
removed-names (filter known names)
new-deps (remove-deps deps removed-names)
changed (affected-namespaces deps removed-names)]
(assoc tracker
::deps new-deps
::unload (distinct
(concat (reverse (sort (dep/topo-comparator deps) changed))
unload))
::load (distinct
(filter (complement (set removed-names))
(concat (sort (dep/topo-comparator new-deps) changed)
load))))))
(defn tracker
"Returns a new, empty dependency tracker"
[]
{})
(comment
;; Structure of the namespace tracker map
{;; Dependency graph of namespace names (symbols) as defined in
;; clojure.tools.namespace.dependency/graph
:clojure.tools.namespace.track/deps {}
;; Ordered list of namespace names (symbols) that need to be
;; removed to bring the running system into agreement with the
;; source files.
:clojure.tools.namespace.track/unload ()
;; Ordered list of namespace names (symbols) that need to be
;; (re)loaded to bring the running system into agreement with the
;; source files.
:clojure.tools.namespace.track/load ()
;; Added by clojure.tools.namespace.file: Map from source files
;; (java.io.File) to the names (symbols) of namespaces they
;; represent.
:clojure.tools.namespace.file/filemap {}
;; Added by clojure.tools.namespace.dir: Set of source files
;; (java.io.File) which have been seen by this dependency tracker;
;; used to determine when files have been deleted.
:clojure.tools.namespace.dir/files #{}
;; Added by clojure.tools.namespace.dir: Instant when the
;; directories were last scanned, as returned by
;; System/currentTimeMillis.
:clojure.tools.namespace.dir/time 1405201862262})
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI, 2012. 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 ^{:author "PI:NAME:<NAME>END_PI"
:doc "Dependency tracker which can compute which namespaces need to be
reloaded after files have changed. This is the low-level
implementation that requires you to find the namespace dependencies
yourself: most uses will interact with the wrappers in
clojure.tools.namespace.file and clojure.tools.namespace.dir or the
public API in clojure.tools.namespace.repl."}
clojure.tools.namespace.track
(:refer-clojure :exclude (remove))
(:require [clojure.set :as set]
[clojure.tools.namespace.dependency :as dep]))
(defn- remove-deps [deps names]
(reduce dep/remove-node deps names))
(defn- add-deps [deps depmap]
(reduce (fn [ds [name dependencies]]
(reduce (fn [g dep] (dep/depend g name dep))
ds dependencies))
deps depmap))
(defn- update-deps [deps depmap]
(-> deps
(remove-deps (keys depmap))
(add-deps depmap)))
(defn- affected-namespaces [deps names]
(set/union (set names)
(dep/transitive-dependents-set deps names)))
(defn add
"Returns an updated dependency tracker with new/updated namespaces.
Depmap is a map describing the new or modified namespaces. Keys in
the map are namespace names (symbols). Values in the map are sets of
symbols naming the direct dependencies of each namespace. For
example, assuming these ns declarations:
(ns alpha (:require beta))
(ns beta (:require gamma delta))
the depmap would look like this:
{alpha #{beta}
beta #{gamma delta}}
After adding new/updated namespaces, the dependency tracker will
have two lists associated with the following keys:
:clojure.tools.namespace.track/unload
is the list of namespaces that need to be removed
:clojure.tools.namespace.track/load
is the list of namespaces that need to be reloaded
To reload namespaces in the correct order, first remove/unload all
namespaces in the 'unload' list, then (re)load all namespaces in the
'load' list. The clojure.tools.namespace.reload namespace has
functions to do this."
[tracker depmap]
(let [{load ::load
unload ::unload
deps ::deps
:or {load (), unload (), deps (dep/graph)}} tracker
new-deps (update-deps deps depmap)
changed (affected-namespaces new-deps (keys depmap))
;; With a new tracker, old dependencies are empty, so
;; unload order will be undefined unless we use new
;; dependencies (TNS-20).
old-deps (if (empty? (dep/nodes deps)) new-deps deps)]
(assoc tracker
::deps new-deps
::unload (distinct
(concat (reverse (sort (dep/topo-comparator old-deps) changed))
unload))
::load (distinct
(concat (sort (dep/topo-comparator new-deps) changed)
load)))))
(defn remove
"Returns an updated dependency tracker from which the namespaces
(symbols) have been removed. The ::unload and ::load lists are
populated as with 'add'."
[tracker names]
(let [{load ::load
unload ::unload
deps ::deps
:or {load (), unload (), deps (dep/graph)}} tracker
known (set (dep/nodes deps))
removed-names (filter known names)
new-deps (remove-deps deps removed-names)
changed (affected-namespaces deps removed-names)]
(assoc tracker
::deps new-deps
::unload (distinct
(concat (reverse (sort (dep/topo-comparator deps) changed))
unload))
::load (distinct
(filter (complement (set removed-names))
(concat (sort (dep/topo-comparator new-deps) changed)
load))))))
(defn tracker
"Returns a new, empty dependency tracker"
[]
{})
(comment
;; Structure of the namespace tracker map
{;; Dependency graph of namespace names (symbols) as defined in
;; clojure.tools.namespace.dependency/graph
:clojure.tools.namespace.track/deps {}
;; Ordered list of namespace names (symbols) that need to be
;; removed to bring the running system into agreement with the
;; source files.
:clojure.tools.namespace.track/unload ()
;; Ordered list of namespace names (symbols) that need to be
;; (re)loaded to bring the running system into agreement with the
;; source files.
:clojure.tools.namespace.track/load ()
;; Added by clojure.tools.namespace.file: Map from source files
;; (java.io.File) to the names (symbols) of namespaces they
;; represent.
:clojure.tools.namespace.file/filemap {}
;; Added by clojure.tools.namespace.dir: Set of source files
;; (java.io.File) which have been seen by this dependency tracker;
;; used to determine when files have been deleted.
:clojure.tools.namespace.dir/files #{}
;; Added by clojure.tools.namespace.dir: Instant when the
;; directories were last scanned, as returned by
;; System/currentTimeMillis.
:clojure.tools.namespace.dir/time 1405201862262})
|
[
{
"context": "; Copyright (c) 2017-present Walmart, Inc.\n;\n; Licensed under the Apache License, ",
"end": 32,
"score": 0.7319592237472534,
"start": 29,
"tag": "NAME",
"value": "Wal"
}
] | src/com/walmartlabs/lacinia/util.clj | hagenek/lacinia | 1,762 | ; Copyright (c) 2017-present Walmart, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.util
"Useful utility functions."
(:require
[com.walmartlabs.lacinia.internal-utils
:as internal
:refer [to-message map-vals cond-let update? apply-description
name->path assoc-in!]]))
(defn ^:private attach-callbacks
[field-container callbacks-map callback-kw error-name]
(map-vals (fn [field]
(cond-let
:let [reference (get field callback-kw)]
(nil? reference)
field
(fn? reference)
field
(var? reference)
field
:let [factory? (sequential? reference)
callback-source (get callbacks-map
(if factory?
(first reference)
reference))]
(nil? callback-source)
(throw (ex-info (format "%s specified in schema not provided."
error-name)
{:reference reference
:callbacks (keys callbacks-map)}))
factory?
(assoc field callback-kw (apply callback-source (rest reference)))
:else
(assoc field callback-kw callback-source)))
field-container))
(defn attach-resolvers
"Given a GraphQL schema and a map of keywords to resolver fns, replace
each placeholder keyword in the schema with the actual resolver fn.
resolver-m is a map from of resolver functions and resolver function factories.
The keys are usually keywords, but may be any value including string or symbol.
When the value in the :resolve key is a simjple value, it is simply replaced
with the corresponding resolver function from resolver-m.
Alternately, the :resolve value may be a seq, indicating a resolver factory.
The first value in the seq is used to select the resolver factory function, which
is then invoked, via `apply`, with the remaining values in the seq."
[schema resolver-m]
(let [f (fn [field-container]
(attach-callbacks field-container resolver-m :resolve "Resolver"))
f-object #(update % :fields f)]
(-> schema
(update? :objects #(map-vals f-object %))
(update? :queries f)
(update? :mutations f)
(update? :subscriptions f))))
(defn attach-streamers
"Attaches stream handler functions to subscriptions.
Replaces the :stream key inside subscription operations using the same logic as
[[attach-resolvers]]."
{:added "0.19.0"}
[schema streamer-map]
(update schema :subscriptions #(attach-callbacks % streamer-map :stream "Streamer")))
(defn attach-scalar-transformers
"Given a GraphQL schema, attaches functions in the transform-m map to the schema.
Inside each scalar definition, the :parse and :serialize keys are replaced with
values from the transform-m map.
In the initial schema, use a keyword for the :parse and :serialize keys, then
provide a corresponding value in transform-m."
[schema transform-m]
(let [transform #(get transform-m % %)]
(update schema :scalars
#(map-vals (fn [scalar-def]
(-> scalar-def
(update :parse transform)
(update :serialize transform)))
%))))
(defn ^{:added "0.36.0"} inject-enum-transformers
"Given a GraphQL schema, injects transformers for enums into the schema.
transform-m maps from the scalar name (a keyword) to a map with keys :parse
and/or :serialize; these are applied to the Enum.
Each enum must exist, or an exception is thrown."
[schema transform-m]
(let [f (fn [enums enum m]
(when-not (contains? enums enum)
(throw (ex-info "Undefined enum when injecting enum transformer."
{:enum enum
:enums (-> enums keys sort vec)})))
(let [{:keys [parse serialize]} m]
(update enums enum #(cond-> %
parse (assoc :parse parse)
serialize (assoc :serialize serialize)))))]
(update schema :enums #(reduce-kv f % transform-m))))
(defn inject-scalar-transformers
"Given a GraphQL schema, injects transformers for scalars into the schema.
transform-m maps from the scalar name (a keyword) to a map with keys :parse
and :serialize; these are applied to the Enum.
Each scalar must exist, or an exception is thrown."
{:added "0.37.0"}
[schema transform-m]
(let [f (fn [scalars scalar m]
(when-not (contains? scalars scalar)
(throw (ex-info "Undefined scalar when injecting scalar transformer"
{:scalar scalar
:scalars (-> scalars keys sort vec)})))
(let [{:keys [parse serialize]} m]
(update scalars scalar assoc :parse parse :serialize serialize)))]
(update schema :scalars #(reduce-kv f % transform-m))))
(defn as-error-map
"Converts an exception into an error map, including a :message key, plus
any additional keys and values via `ex-data`.
In the second arity, a further map of values to be merged into the error
map can be provided."
{:added "0.16.0"}
([^Throwable t]
(as-error-map t nil))
([^Throwable t more-data]
(let [extension-data (merge (ex-data t) more-data)
locations (:locations extension-data)
remaining-data (dissoc extension-data :locations)]
(cond-> {:message (to-message t)}
locations (assoc :locations locations)
(seq remaining-data) (assoc :extensions remaining-data)))))
(defn inject-descriptions
"Injects documentation into a schema, as `:description` keys on various elements
within the schema.
The documentation map keys are keywords with a particular structure,
and the values are formatted Markdown strings.
The keys are one of the following forms:
- `:Type`
- `:Type/name`
- `:Type/name.argument`
A simple `Type` will document an object, input object, interface, union, or enum.
The second form is used to document a field of an object, input object, or interface, or
to document a specific value of an enum (e.g., `:Episode/NEW_HOPE`).
The final form is used to document an argument to a field (it does not make sense for enums).
Additionally, the `Type` can be `queries`, `mutations`, or `subscriptions`, in which case
the `name` will be the name of the operation (e.g., `:queries/episode`).
An exception is thrown if an element identified by a key does not exist.
See [[parse-docs]]."
{:added "0.27.0"}
[schema documentation]
(reduce-kv (fn [schema' location description]
(apply-description schema' location description))
schema
documentation))
(defn inject-resolvers
"Adds resolvers to the schema. The resolvers map is a map of keywords to
field resolvers (as functions, or [[FieldResolver]] instances).
The key identifies where the resolver should be added, in the form `:Type/field`.
Alternately, the key may be of the format `:queries/name` (or `:mutations/name` or
`:subscriptions/name`).
Throws an exception if the target of the resolver can't be found.
In many cases, this is a full replacement for [[attach-resolvers]], but the two functions
can also be used in conjunction with each other."
{:added "0.27.0"}
[schema resolvers]
(reduce-kv (fn [schema' k resolver]
(assoc-in! schema' (name->path schema' k :resolve) resolver))
schema
resolvers))
(defn inject-streamers
"As [[inject-resolvers]] but the updated key is :stream, thereby supplying a subscription
streamer function."
{:added "0.37.0"}
[schema streamers]
(reduce-kv (fn [schema' k streamer]
(assoc-in! schema' (name->path schema' k :stream) streamer))
schema
streamers))
| 21187 | ; Copyright (c) 2017-present <NAME>mart, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.util
"Useful utility functions."
(:require
[com.walmartlabs.lacinia.internal-utils
:as internal
:refer [to-message map-vals cond-let update? apply-description
name->path assoc-in!]]))
(defn ^:private attach-callbacks
[field-container callbacks-map callback-kw error-name]
(map-vals (fn [field]
(cond-let
:let [reference (get field callback-kw)]
(nil? reference)
field
(fn? reference)
field
(var? reference)
field
:let [factory? (sequential? reference)
callback-source (get callbacks-map
(if factory?
(first reference)
reference))]
(nil? callback-source)
(throw (ex-info (format "%s specified in schema not provided."
error-name)
{:reference reference
:callbacks (keys callbacks-map)}))
factory?
(assoc field callback-kw (apply callback-source (rest reference)))
:else
(assoc field callback-kw callback-source)))
field-container))
(defn attach-resolvers
"Given a GraphQL schema and a map of keywords to resolver fns, replace
each placeholder keyword in the schema with the actual resolver fn.
resolver-m is a map from of resolver functions and resolver function factories.
The keys are usually keywords, but may be any value including string or symbol.
When the value in the :resolve key is a simjple value, it is simply replaced
with the corresponding resolver function from resolver-m.
Alternately, the :resolve value may be a seq, indicating a resolver factory.
The first value in the seq is used to select the resolver factory function, which
is then invoked, via `apply`, with the remaining values in the seq."
[schema resolver-m]
(let [f (fn [field-container]
(attach-callbacks field-container resolver-m :resolve "Resolver"))
f-object #(update % :fields f)]
(-> schema
(update? :objects #(map-vals f-object %))
(update? :queries f)
(update? :mutations f)
(update? :subscriptions f))))
(defn attach-streamers
"Attaches stream handler functions to subscriptions.
Replaces the :stream key inside subscription operations using the same logic as
[[attach-resolvers]]."
{:added "0.19.0"}
[schema streamer-map]
(update schema :subscriptions #(attach-callbacks % streamer-map :stream "Streamer")))
(defn attach-scalar-transformers
"Given a GraphQL schema, attaches functions in the transform-m map to the schema.
Inside each scalar definition, the :parse and :serialize keys are replaced with
values from the transform-m map.
In the initial schema, use a keyword for the :parse and :serialize keys, then
provide a corresponding value in transform-m."
[schema transform-m]
(let [transform #(get transform-m % %)]
(update schema :scalars
#(map-vals (fn [scalar-def]
(-> scalar-def
(update :parse transform)
(update :serialize transform)))
%))))
(defn ^{:added "0.36.0"} inject-enum-transformers
"Given a GraphQL schema, injects transformers for enums into the schema.
transform-m maps from the scalar name (a keyword) to a map with keys :parse
and/or :serialize; these are applied to the Enum.
Each enum must exist, or an exception is thrown."
[schema transform-m]
(let [f (fn [enums enum m]
(when-not (contains? enums enum)
(throw (ex-info "Undefined enum when injecting enum transformer."
{:enum enum
:enums (-> enums keys sort vec)})))
(let [{:keys [parse serialize]} m]
(update enums enum #(cond-> %
parse (assoc :parse parse)
serialize (assoc :serialize serialize)))))]
(update schema :enums #(reduce-kv f % transform-m))))
(defn inject-scalar-transformers
"Given a GraphQL schema, injects transformers for scalars into the schema.
transform-m maps from the scalar name (a keyword) to a map with keys :parse
and :serialize; these are applied to the Enum.
Each scalar must exist, or an exception is thrown."
{:added "0.37.0"}
[schema transform-m]
(let [f (fn [scalars scalar m]
(when-not (contains? scalars scalar)
(throw (ex-info "Undefined scalar when injecting scalar transformer"
{:scalar scalar
:scalars (-> scalars keys sort vec)})))
(let [{:keys [parse serialize]} m]
(update scalars scalar assoc :parse parse :serialize serialize)))]
(update schema :scalars #(reduce-kv f % transform-m))))
(defn as-error-map
"Converts an exception into an error map, including a :message key, plus
any additional keys and values via `ex-data`.
In the second arity, a further map of values to be merged into the error
map can be provided."
{:added "0.16.0"}
([^Throwable t]
(as-error-map t nil))
([^Throwable t more-data]
(let [extension-data (merge (ex-data t) more-data)
locations (:locations extension-data)
remaining-data (dissoc extension-data :locations)]
(cond-> {:message (to-message t)}
locations (assoc :locations locations)
(seq remaining-data) (assoc :extensions remaining-data)))))
(defn inject-descriptions
"Injects documentation into a schema, as `:description` keys on various elements
within the schema.
The documentation map keys are keywords with a particular structure,
and the values are formatted Markdown strings.
The keys are one of the following forms:
- `:Type`
- `:Type/name`
- `:Type/name.argument`
A simple `Type` will document an object, input object, interface, union, or enum.
The second form is used to document a field of an object, input object, or interface, or
to document a specific value of an enum (e.g., `:Episode/NEW_HOPE`).
The final form is used to document an argument to a field (it does not make sense for enums).
Additionally, the `Type` can be `queries`, `mutations`, or `subscriptions`, in which case
the `name` will be the name of the operation (e.g., `:queries/episode`).
An exception is thrown if an element identified by a key does not exist.
See [[parse-docs]]."
{:added "0.27.0"}
[schema documentation]
(reduce-kv (fn [schema' location description]
(apply-description schema' location description))
schema
documentation))
(defn inject-resolvers
"Adds resolvers to the schema. The resolvers map is a map of keywords to
field resolvers (as functions, or [[FieldResolver]] instances).
The key identifies where the resolver should be added, in the form `:Type/field`.
Alternately, the key may be of the format `:queries/name` (or `:mutations/name` or
`:subscriptions/name`).
Throws an exception if the target of the resolver can't be found.
In many cases, this is a full replacement for [[attach-resolvers]], but the two functions
can also be used in conjunction with each other."
{:added "0.27.0"}
[schema resolvers]
(reduce-kv (fn [schema' k resolver]
(assoc-in! schema' (name->path schema' k :resolve) resolver))
schema
resolvers))
(defn inject-streamers
"As [[inject-resolvers]] but the updated key is :stream, thereby supplying a subscription
streamer function."
{:added "0.37.0"}
[schema streamers]
(reduce-kv (fn [schema' k streamer]
(assoc-in! schema' (name->path schema' k :stream) streamer))
schema
streamers))
| true | ; Copyright (c) 2017-present PI:NAME:<NAME>END_PImart, Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns com.walmartlabs.lacinia.util
"Useful utility functions."
(:require
[com.walmartlabs.lacinia.internal-utils
:as internal
:refer [to-message map-vals cond-let update? apply-description
name->path assoc-in!]]))
(defn ^:private attach-callbacks
[field-container callbacks-map callback-kw error-name]
(map-vals (fn [field]
(cond-let
:let [reference (get field callback-kw)]
(nil? reference)
field
(fn? reference)
field
(var? reference)
field
:let [factory? (sequential? reference)
callback-source (get callbacks-map
(if factory?
(first reference)
reference))]
(nil? callback-source)
(throw (ex-info (format "%s specified in schema not provided."
error-name)
{:reference reference
:callbacks (keys callbacks-map)}))
factory?
(assoc field callback-kw (apply callback-source (rest reference)))
:else
(assoc field callback-kw callback-source)))
field-container))
(defn attach-resolvers
"Given a GraphQL schema and a map of keywords to resolver fns, replace
each placeholder keyword in the schema with the actual resolver fn.
resolver-m is a map from of resolver functions and resolver function factories.
The keys are usually keywords, but may be any value including string or symbol.
When the value in the :resolve key is a simjple value, it is simply replaced
with the corresponding resolver function from resolver-m.
Alternately, the :resolve value may be a seq, indicating a resolver factory.
The first value in the seq is used to select the resolver factory function, which
is then invoked, via `apply`, with the remaining values in the seq."
[schema resolver-m]
(let [f (fn [field-container]
(attach-callbacks field-container resolver-m :resolve "Resolver"))
f-object #(update % :fields f)]
(-> schema
(update? :objects #(map-vals f-object %))
(update? :queries f)
(update? :mutations f)
(update? :subscriptions f))))
(defn attach-streamers
"Attaches stream handler functions to subscriptions.
Replaces the :stream key inside subscription operations using the same logic as
[[attach-resolvers]]."
{:added "0.19.0"}
[schema streamer-map]
(update schema :subscriptions #(attach-callbacks % streamer-map :stream "Streamer")))
(defn attach-scalar-transformers
"Given a GraphQL schema, attaches functions in the transform-m map to the schema.
Inside each scalar definition, the :parse and :serialize keys are replaced with
values from the transform-m map.
In the initial schema, use a keyword for the :parse and :serialize keys, then
provide a corresponding value in transform-m."
[schema transform-m]
(let [transform #(get transform-m % %)]
(update schema :scalars
#(map-vals (fn [scalar-def]
(-> scalar-def
(update :parse transform)
(update :serialize transform)))
%))))
(defn ^{:added "0.36.0"} inject-enum-transformers
"Given a GraphQL schema, injects transformers for enums into the schema.
transform-m maps from the scalar name (a keyword) to a map with keys :parse
and/or :serialize; these are applied to the Enum.
Each enum must exist, or an exception is thrown."
[schema transform-m]
(let [f (fn [enums enum m]
(when-not (contains? enums enum)
(throw (ex-info "Undefined enum when injecting enum transformer."
{:enum enum
:enums (-> enums keys sort vec)})))
(let [{:keys [parse serialize]} m]
(update enums enum #(cond-> %
parse (assoc :parse parse)
serialize (assoc :serialize serialize)))))]
(update schema :enums #(reduce-kv f % transform-m))))
(defn inject-scalar-transformers
"Given a GraphQL schema, injects transformers for scalars into the schema.
transform-m maps from the scalar name (a keyword) to a map with keys :parse
and :serialize; these are applied to the Enum.
Each scalar must exist, or an exception is thrown."
{:added "0.37.0"}
[schema transform-m]
(let [f (fn [scalars scalar m]
(when-not (contains? scalars scalar)
(throw (ex-info "Undefined scalar when injecting scalar transformer"
{:scalar scalar
:scalars (-> scalars keys sort vec)})))
(let [{:keys [parse serialize]} m]
(update scalars scalar assoc :parse parse :serialize serialize)))]
(update schema :scalars #(reduce-kv f % transform-m))))
(defn as-error-map
"Converts an exception into an error map, including a :message key, plus
any additional keys and values via `ex-data`.
In the second arity, a further map of values to be merged into the error
map can be provided."
{:added "0.16.0"}
([^Throwable t]
(as-error-map t nil))
([^Throwable t more-data]
(let [extension-data (merge (ex-data t) more-data)
locations (:locations extension-data)
remaining-data (dissoc extension-data :locations)]
(cond-> {:message (to-message t)}
locations (assoc :locations locations)
(seq remaining-data) (assoc :extensions remaining-data)))))
(defn inject-descriptions
"Injects documentation into a schema, as `:description` keys on various elements
within the schema.
The documentation map keys are keywords with a particular structure,
and the values are formatted Markdown strings.
The keys are one of the following forms:
- `:Type`
- `:Type/name`
- `:Type/name.argument`
A simple `Type` will document an object, input object, interface, union, or enum.
The second form is used to document a field of an object, input object, or interface, or
to document a specific value of an enum (e.g., `:Episode/NEW_HOPE`).
The final form is used to document an argument to a field (it does not make sense for enums).
Additionally, the `Type` can be `queries`, `mutations`, or `subscriptions`, in which case
the `name` will be the name of the operation (e.g., `:queries/episode`).
An exception is thrown if an element identified by a key does not exist.
See [[parse-docs]]."
{:added "0.27.0"}
[schema documentation]
(reduce-kv (fn [schema' location description]
(apply-description schema' location description))
schema
documentation))
(defn inject-resolvers
"Adds resolvers to the schema. The resolvers map is a map of keywords to
field resolvers (as functions, or [[FieldResolver]] instances).
The key identifies where the resolver should be added, in the form `:Type/field`.
Alternately, the key may be of the format `:queries/name` (or `:mutations/name` or
`:subscriptions/name`).
Throws an exception if the target of the resolver can't be found.
In many cases, this is a full replacement for [[attach-resolvers]], but the two functions
can also be used in conjunction with each other."
{:added "0.27.0"}
[schema resolvers]
(reduce-kv (fn [schema' k resolver]
(assoc-in! schema' (name->path schema' k :resolve) resolver))
schema
resolvers))
(defn inject-streamers
"As [[inject-resolvers]] but the updated key is :stream, thereby supplying a subscription
streamer function."
{:added "0.37.0"}
[schema streamers]
(reduce-kv (fn [schema' k streamer]
(assoc-in! schema' (name->path schema' k :stream) streamer))
schema
streamers))
|
[
{
"context": "/\n ;; See also: https://github.com/pedestal/pedestal/issues/499\n ;;::http/secure",
"end": 6060,
"score": 0.9996466040611267,
"start": 6052,
"tag": "USERNAME",
"value": "pedestal"
},
{
"context": " ;:key-password \"password\"\n ;:ssl-po",
"end": 7174,
"score": 0.9981481432914734,
"start": 7166,
"tag": "PASSWORD",
"value": "password"
}
] | src/comment_api_server/service.clj | iwot/comment-api-server | 0 | (ns comment-api-server.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[io.pedestal.http.body-params :as body-params]
[ring.util.response :as ring-resp]
[io.pedestal.interceptor :as interceptor]
[cheshire.core :as json]
[io.pedestal.log :as log]
[data.comments :as comments]
[data.db :as db]
[clojure.walk :as walk]
[postal.core :refer [send-message]]))
(def config (atom nil))
(defn load-config
[path]
(prn "load-config" path)
(swap! config (fn [c] (clojure.edn/read-string (slurp path)))))
(defn get-config
[]
@config)
(defn allowed-origins
[]
(:allowed-origins (get-config)))
(defn sned-new-comment-info
[from to]
(if (and from to) (send-message
{:from from
:to [to]
:subject "新しいコメントが投稿されました"
:body "新しいコメントが投稿されました"})))
(defn get-info-from-email
[]
(:from-email (:info (get-config))))
(defn get-info-to-email
[]
(:to-email (:info (get-config))))
(def content-length-json-body
(interceptor/interceptor
{:name ::content-length-json-body
:leave (fn [context]
(let [response (:response context)
body (:body response)
json-response-body (if body (json/generate-string body) "")
;; Content-Length is the size of the response in bytes
;; Let's count the bytes instead of the string, in case there are unicode characters
content-length (count (.getBytes ^String json-response-body))
headers (:headers response {})]
(assoc context
:response {:status (:status response)
:body json-response-body
:headers (merge headers
{"Content-Type" "application/json;charset=UTF-8"
"Content-Length" (str content-length)})})))}))
(defn exists-db
[path]
(.exists (clojure.java.io/as-file path)))
(defn create-db-if-not-exists
[]
(if (not (exists-db (:subname (db/db-spec (get-config)))))
(comments/create-comments-table (db/db-spec (get-config)))))
(defn validate-email-pattern
[mail]
(let [pattern #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"]
(and (string? mail) (re-matches pattern mail))))
(defn validate-email
[mail]
(if (validate-email-pattern mail)
nil
"mail pattern mismatch"))
(defn validate-name
[name]
(if (and (string? name) (> (count name) 0))
nil
"empty name"))
(defn validate-comment
[comment]
(if (and (string? comment) (> (count comment) 0))
nil
"empty comment"))
(defn new-comment-validator
[input]
(let [name-error (validate-name (:name input))
email-error (validate-email (:mail input))
comment-error (validate-comment (:comment input))]
(if (or name-error email-error comment-error)
[name-error email-error comment-error]
nil)))
(defn db-comments
[page-id]
(create-db-if-not-exists)
(let [cs (seq (comments/comments-by-page (db/db-spec (get-config)) {:page_id page-id}))]
(if cs cs '())))
(defn get-comments
[request]
(let [page-id (:page-id (:path-params request))
comments (db-comments page-id)]
(ring-resp/response comments)))
(defn db-new-comment
[page-id ip params]
(create-db-if-not-exists)
(let [p (assoc (walk/keywordize-keys params) :page_id page-id :ip ip)
validation-errors (new-comment-validator p)]
(if validation-errors
{:success 0, :messages (filter #(not (nil? %)) validation-errors)}
(if (comments/insert-comment (db/db-spec (get-config)) p)
(do (sned-new-comment-info (get-info-from-email) (get-info-to-email)) {:success 1})
{:success 0, :messages ["insert failure"]}))))
(defn ip-from-request
[request]
(let [headers (walk/keywordize-keys (:headers request))]
(if (:x-real-ip headers)
(:x-real-ip headers)
(if (:x-forwarded-for headers)
(:x-forwarded-for headers)
(:remote-addr request)))))
(defn add-comment
[request]
(let [page-id (:page-id (:path-params request))
result (db-new-comment page-id (ip-from-request request) (:params request))]
(ring-resp/response {:success result})))
(def common-interceptors [(body-params/body-params) http/json-body])
(def custom-interceptors [(body-params/body-params) content-length-json-body])
(def routes #{["/comment/:page-id" :get (conj common-interceptors `get-comments) :constraints {:page-id #"^[a-zA-Z0-9\-_/\%]+"}]
["/comment/:page-id" :post (conj common-interceptors `add-comment) :constraints {:page-id #"^[a-zA-Z0-9\-_/\%]+"}]})
;; Consumed by comment-api-server.server/create-server
;; See http/default-interceptors for additional options you can configure
(def service {:env :prod
;; You can bring your own non-default interceptors. Make
;; sure you include routing and set it up right for
;; dev-mode. If you do, many other keys for configuring
;; default interceptors will be ignored.
;; ::http/interceptors []
::http/routes routes
;; Uncomment next line to enable CORS support, add
;; string(s) specifying scheme, host and port for
;; allowed source(s):
;;
;; "http://localhost:8080"
;;
; ::http/allowed-origins {:creds true :allowed-origins ["https://www.sysbe.net"]}
;; Tune the Secure Headers
;; and specifically the Content Security Policy appropriate to your service/application
;; For more information, see: https://content-security-policy.com/
;; See also: https://github.com/pedestal/pedestal/issues/499
;;::http/secure-headers {:content-security-policy-settings {:object-src "'none'"
;; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:"
;; :frame-ancestors "'none'"}}
;; Root for resource interceptor that is available by default.
::http/resource-path "/public"
;; Either :jetty, :immutant or :tomcat (see comments in project.clj)
;; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider
::http/type :jetty
;;::http/host "localhost"
::http/port 8080
;; Options to pass to the container (Jetty)
::http/container-options {:h2c? true
:h2? false
;:keystore "test/hp/keystore.jks"
;:key-password "password"
;:ssl-port 8443
:ssl? false
;; Alternatively, You can specify you're own Jetty HTTPConfiguration
;; via the `:io.pedestal.http.jetty/http-configuration` container option.
;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.)
}})
| 18704 | (ns comment-api-server.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[io.pedestal.http.body-params :as body-params]
[ring.util.response :as ring-resp]
[io.pedestal.interceptor :as interceptor]
[cheshire.core :as json]
[io.pedestal.log :as log]
[data.comments :as comments]
[data.db :as db]
[clojure.walk :as walk]
[postal.core :refer [send-message]]))
(def config (atom nil))
(defn load-config
[path]
(prn "load-config" path)
(swap! config (fn [c] (clojure.edn/read-string (slurp path)))))
(defn get-config
[]
@config)
(defn allowed-origins
[]
(:allowed-origins (get-config)))
(defn sned-new-comment-info
[from to]
(if (and from to) (send-message
{:from from
:to [to]
:subject "新しいコメントが投稿されました"
:body "新しいコメントが投稿されました"})))
(defn get-info-from-email
[]
(:from-email (:info (get-config))))
(defn get-info-to-email
[]
(:to-email (:info (get-config))))
(def content-length-json-body
(interceptor/interceptor
{:name ::content-length-json-body
:leave (fn [context]
(let [response (:response context)
body (:body response)
json-response-body (if body (json/generate-string body) "")
;; Content-Length is the size of the response in bytes
;; Let's count the bytes instead of the string, in case there are unicode characters
content-length (count (.getBytes ^String json-response-body))
headers (:headers response {})]
(assoc context
:response {:status (:status response)
:body json-response-body
:headers (merge headers
{"Content-Type" "application/json;charset=UTF-8"
"Content-Length" (str content-length)})})))}))
(defn exists-db
[path]
(.exists (clojure.java.io/as-file path)))
(defn create-db-if-not-exists
[]
(if (not (exists-db (:subname (db/db-spec (get-config)))))
(comments/create-comments-table (db/db-spec (get-config)))))
(defn validate-email-pattern
[mail]
(let [pattern #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"]
(and (string? mail) (re-matches pattern mail))))
(defn validate-email
[mail]
(if (validate-email-pattern mail)
nil
"mail pattern mismatch"))
(defn validate-name
[name]
(if (and (string? name) (> (count name) 0))
nil
"empty name"))
(defn validate-comment
[comment]
(if (and (string? comment) (> (count comment) 0))
nil
"empty comment"))
(defn new-comment-validator
[input]
(let [name-error (validate-name (:name input))
email-error (validate-email (:mail input))
comment-error (validate-comment (:comment input))]
(if (or name-error email-error comment-error)
[name-error email-error comment-error]
nil)))
(defn db-comments
[page-id]
(create-db-if-not-exists)
(let [cs (seq (comments/comments-by-page (db/db-spec (get-config)) {:page_id page-id}))]
(if cs cs '())))
(defn get-comments
[request]
(let [page-id (:page-id (:path-params request))
comments (db-comments page-id)]
(ring-resp/response comments)))
(defn db-new-comment
[page-id ip params]
(create-db-if-not-exists)
(let [p (assoc (walk/keywordize-keys params) :page_id page-id :ip ip)
validation-errors (new-comment-validator p)]
(if validation-errors
{:success 0, :messages (filter #(not (nil? %)) validation-errors)}
(if (comments/insert-comment (db/db-spec (get-config)) p)
(do (sned-new-comment-info (get-info-from-email) (get-info-to-email)) {:success 1})
{:success 0, :messages ["insert failure"]}))))
(defn ip-from-request
[request]
(let [headers (walk/keywordize-keys (:headers request))]
(if (:x-real-ip headers)
(:x-real-ip headers)
(if (:x-forwarded-for headers)
(:x-forwarded-for headers)
(:remote-addr request)))))
(defn add-comment
[request]
(let [page-id (:page-id (:path-params request))
result (db-new-comment page-id (ip-from-request request) (:params request))]
(ring-resp/response {:success result})))
(def common-interceptors [(body-params/body-params) http/json-body])
(def custom-interceptors [(body-params/body-params) content-length-json-body])
(def routes #{["/comment/:page-id" :get (conj common-interceptors `get-comments) :constraints {:page-id #"^[a-zA-Z0-9\-_/\%]+"}]
["/comment/:page-id" :post (conj common-interceptors `add-comment) :constraints {:page-id #"^[a-zA-Z0-9\-_/\%]+"}]})
;; Consumed by comment-api-server.server/create-server
;; See http/default-interceptors for additional options you can configure
(def service {:env :prod
;; You can bring your own non-default interceptors. Make
;; sure you include routing and set it up right for
;; dev-mode. If you do, many other keys for configuring
;; default interceptors will be ignored.
;; ::http/interceptors []
::http/routes routes
;; Uncomment next line to enable CORS support, add
;; string(s) specifying scheme, host and port for
;; allowed source(s):
;;
;; "http://localhost:8080"
;;
; ::http/allowed-origins {:creds true :allowed-origins ["https://www.sysbe.net"]}
;; Tune the Secure Headers
;; and specifically the Content Security Policy appropriate to your service/application
;; For more information, see: https://content-security-policy.com/
;; See also: https://github.com/pedestal/pedestal/issues/499
;;::http/secure-headers {:content-security-policy-settings {:object-src "'none'"
;; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:"
;; :frame-ancestors "'none'"}}
;; Root for resource interceptor that is available by default.
::http/resource-path "/public"
;; Either :jetty, :immutant or :tomcat (see comments in project.clj)
;; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider
::http/type :jetty
;;::http/host "localhost"
::http/port 8080
;; Options to pass to the container (Jetty)
::http/container-options {:h2c? true
:h2? false
;:keystore "test/hp/keystore.jks"
;:key-password "<PASSWORD>"
;:ssl-port 8443
:ssl? false
;; Alternatively, You can specify you're own Jetty HTTPConfiguration
;; via the `:io.pedestal.http.jetty/http-configuration` container option.
;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.)
}})
| true | (ns comment-api-server.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[io.pedestal.http.body-params :as body-params]
[ring.util.response :as ring-resp]
[io.pedestal.interceptor :as interceptor]
[cheshire.core :as json]
[io.pedestal.log :as log]
[data.comments :as comments]
[data.db :as db]
[clojure.walk :as walk]
[postal.core :refer [send-message]]))
(def config (atom nil))
(defn load-config
[path]
(prn "load-config" path)
(swap! config (fn [c] (clojure.edn/read-string (slurp path)))))
(defn get-config
[]
@config)
(defn allowed-origins
[]
(:allowed-origins (get-config)))
(defn sned-new-comment-info
[from to]
(if (and from to) (send-message
{:from from
:to [to]
:subject "新しいコメントが投稿されました"
:body "新しいコメントが投稿されました"})))
(defn get-info-from-email
[]
(:from-email (:info (get-config))))
(defn get-info-to-email
[]
(:to-email (:info (get-config))))
(def content-length-json-body
(interceptor/interceptor
{:name ::content-length-json-body
:leave (fn [context]
(let [response (:response context)
body (:body response)
json-response-body (if body (json/generate-string body) "")
;; Content-Length is the size of the response in bytes
;; Let's count the bytes instead of the string, in case there are unicode characters
content-length (count (.getBytes ^String json-response-body))
headers (:headers response {})]
(assoc context
:response {:status (:status response)
:body json-response-body
:headers (merge headers
{"Content-Type" "application/json;charset=UTF-8"
"Content-Length" (str content-length)})})))}))
(defn exists-db
[path]
(.exists (clojure.java.io/as-file path)))
(defn create-db-if-not-exists
[]
(if (not (exists-db (:subname (db/db-spec (get-config)))))
(comments/create-comments-table (db/db-spec (get-config)))))
(defn validate-email-pattern
[mail]
(let [pattern #"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"]
(and (string? mail) (re-matches pattern mail))))
(defn validate-email
[mail]
(if (validate-email-pattern mail)
nil
"mail pattern mismatch"))
(defn validate-name
[name]
(if (and (string? name) (> (count name) 0))
nil
"empty name"))
(defn validate-comment
[comment]
(if (and (string? comment) (> (count comment) 0))
nil
"empty comment"))
(defn new-comment-validator
[input]
(let [name-error (validate-name (:name input))
email-error (validate-email (:mail input))
comment-error (validate-comment (:comment input))]
(if (or name-error email-error comment-error)
[name-error email-error comment-error]
nil)))
(defn db-comments
[page-id]
(create-db-if-not-exists)
(let [cs (seq (comments/comments-by-page (db/db-spec (get-config)) {:page_id page-id}))]
(if cs cs '())))
(defn get-comments
[request]
(let [page-id (:page-id (:path-params request))
comments (db-comments page-id)]
(ring-resp/response comments)))
(defn db-new-comment
[page-id ip params]
(create-db-if-not-exists)
(let [p (assoc (walk/keywordize-keys params) :page_id page-id :ip ip)
validation-errors (new-comment-validator p)]
(if validation-errors
{:success 0, :messages (filter #(not (nil? %)) validation-errors)}
(if (comments/insert-comment (db/db-spec (get-config)) p)
(do (sned-new-comment-info (get-info-from-email) (get-info-to-email)) {:success 1})
{:success 0, :messages ["insert failure"]}))))
(defn ip-from-request
[request]
(let [headers (walk/keywordize-keys (:headers request))]
(if (:x-real-ip headers)
(:x-real-ip headers)
(if (:x-forwarded-for headers)
(:x-forwarded-for headers)
(:remote-addr request)))))
(defn add-comment
[request]
(let [page-id (:page-id (:path-params request))
result (db-new-comment page-id (ip-from-request request) (:params request))]
(ring-resp/response {:success result})))
(def common-interceptors [(body-params/body-params) http/json-body])
(def custom-interceptors [(body-params/body-params) content-length-json-body])
(def routes #{["/comment/:page-id" :get (conj common-interceptors `get-comments) :constraints {:page-id #"^[a-zA-Z0-9\-_/\%]+"}]
["/comment/:page-id" :post (conj common-interceptors `add-comment) :constraints {:page-id #"^[a-zA-Z0-9\-_/\%]+"}]})
;; Consumed by comment-api-server.server/create-server
;; See http/default-interceptors for additional options you can configure
(def service {:env :prod
;; You can bring your own non-default interceptors. Make
;; sure you include routing and set it up right for
;; dev-mode. If you do, many other keys for configuring
;; default interceptors will be ignored.
;; ::http/interceptors []
::http/routes routes
;; Uncomment next line to enable CORS support, add
;; string(s) specifying scheme, host and port for
;; allowed source(s):
;;
;; "http://localhost:8080"
;;
; ::http/allowed-origins {:creds true :allowed-origins ["https://www.sysbe.net"]}
;; Tune the Secure Headers
;; and specifically the Content Security Policy appropriate to your service/application
;; For more information, see: https://content-security-policy.com/
;; See also: https://github.com/pedestal/pedestal/issues/499
;;::http/secure-headers {:content-security-policy-settings {:object-src "'none'"
;; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:"
;; :frame-ancestors "'none'"}}
;; Root for resource interceptor that is available by default.
::http/resource-path "/public"
;; Either :jetty, :immutant or :tomcat (see comments in project.clj)
;; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider
::http/type :jetty
;;::http/host "localhost"
::http/port 8080
;; Options to pass to the container (Jetty)
::http/container-options {:h2c? true
:h2? false
;:keystore "test/hp/keystore.jks"
;:key-password "PI:PASSWORD:<PASSWORD>END_PI"
;:ssl-port 8443
:ssl? false
;; Alternatively, You can specify you're own Jetty HTTPConfiguration
;; via the `:io.pedestal.http.jetty/http-configuration` container option.
;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.)
}})
|
[
{
"context": "(ns #^{:author \"Mikael Reponen\"}\n trigger.trigger\n (:use [overtone.core]\n ",
"end": 30,
"score": 0.9998837113380432,
"start": 16,
"tag": "NAME",
"value": "Mikael Reponen"
},
{
"context": "(buffer-id buf)))\n size-key (keyword (str size))\n pool @bufferPool\n pool ",
"end": 5539,
"score": 0.6667588353157043,
"start": 5531,
"tag": "KEY",
"value": "str size"
},
{
"context": "ttern-name))\n synth-group (:group (@synthConfig pattern-name))\n mixer-group ",
"end": 22788,
"score": 0.5225136280059814,
"start": 22785,
"tag": "USERNAME",
"value": "syn"
},
{
"context": "rn-name))\n out-mixer (:out-mixer (@synthConfig pattern-name))\n ;;trigger-vol-id ",
"end": 23142,
"score": 0.5225304961204529,
"start": 23139,
"tag": "USERNAME",
"value": "syn"
},
{
"context": "put\n valid-keys (concat [:pn :sn] (vec (synth-args synth-name)))\n ",
"end": 36862,
"score": 0.8426687121391296,
"start": 36853,
"tag": "KEY",
"value": "[:pn :sn]"
},
{
"context": " valid-keys (concat [:pn :spn :sn] (vec (synth-args synth-name)))\n ",
"end": 39680,
"score": 0.832892119884491,
"start": 39678,
"tag": "KEY",
"value": "pn"
},
{
"context": " valid-keys (concat [:pn :spn :sn] (vec (synth-args synth-name)))\n ",
"end": 39685,
"score": 0.8820329904556274,
"start": 39682,
"tag": "KEY",
"value": "spn"
},
{
"context": " valid-keys (concat [:pn :spn :sn] (vec (synth-args synth-name)))\n ",
"end": 39689,
"score": 0.733248770236969,
"start": 39687,
"tag": "KEY",
"value": "sn"
},
{
"context": " ;OSC\n;(var addr=NetAddr.new(\"127.0.0.1\", 3333); OSCdef ('/tidalplay2', { arg msg; addr.",
"end": 50172,
"score": 0.9930300116539001,
"start": 50163,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | src/trigger/trigger.clj | Viritystila/trigger | 2 | (ns #^{:author "Mikael Reponen"}
trigger.trigger
(:use [overtone.core]
[clojure.data])
(:require
[trigger.synths :refer :all]
[trigger.misc :refer :all]
[trigger.algo :refer :all]
[trigger.speech :refer :all]
[trigger.samples :refer :all]
[trigger.trg_fx :refer :all]
[clojure.core.async :as async]
[clojure.tools.namespace.repl :refer [refresh]]
[clj-native.structs :refer [byref]]
[overtone.sc.machinery.server.comms :refer [with-server-sync server-sync]]
[clojure.walk :only prewalk]
[overtone.sc.machinery.server.connection :refer [boot]]
[overtone.sc.machinery.server native])
(:import
(java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder)))
;Boot Supercollider
(def port 57111)
(defn boot-ext [] (if (server-connected?) nil (boot-external-server port {:max-buffers 2621440 :max-control-bus 80960}) ))
;(boot-ext)
(defn boot-int [] (if (server-connected?) nil (boot :internal port {:max-buffers 2621440 :max-control-bus 80960}) ))
(boot-int)
;; (defn cb
;; "Get a an array of floats for the synthesis sound buffer with the given ID."
;; [sc buf-id]
;; (let [buf (byref overtone.sc.machinery.server.native/sound-buffer)
;; changed? (byref overtone.sc.machinery.server.native/bool-val)
;; ;; changed? (java.nio.ByteBuffer/allocate 1)
;; cc (ByteBuffer/allocate 1)
;; ]
;; ;(.samples buf)
;; (println buf)
;; (println (:value changed?))
;; ;(.getFloatArray (.data buf) 0 (.samples buf))
;; ( overtone.sc.machinery.server.native/world-copy-sound-buffer (:world sc) buf-id buf 0 cc)
;; ;(.getFloatArray (.data buf) 0 (.samples buf))
;; ))
;State atoms
(defonce synthConfig (atom {}))
(defonce algConfig (atom {}))
(defonce bufferPool (atom {}))
(defonce buffersInUse (atom {}))
(defonce timeatom (atom 0))
(defn init_groups_dur_and_del []
;Groups
(do
(defonce main-g (group "main group")))
;Base duration
(do
(def base-dur (buffer 1))
(buffer-write! base-dur [1]))
; Base trigger delay
(do
(def base-del (buffer 1))
(buffer-write! base-del [0])))
;Synthdefs
(defsynth base-trigger-synth [out-bus 0 trigger-id 0 base-dur-in 0 base-del-in 0]
(let [trg1 (t-duty:kr (dbufrd base-dur-in (dseries 0 1 INF)) 0 1)
trg (t-delay:kr trg1 (buf-rd:kr 1 base-del-in))]
(send-trig trg trigger-id trg)
(out:kr out-bus trg)))
(defsynth base-trigger-counter [base-trigger-bus-in 0 base-trigger-count-bus-out 0]
(out:kr base-trigger-count-bus-out (pulse-count:kr (in:kr base-trigger-bus-in))))
(def dbg (control-bus 1))
(def dbg2 (control-bus 1))
(defsynth vol-send [in-bus 0 base-dur 0.017 trigger-id 0]
(let [trg (t-duty:kr (dseq [base-dur] INF) )
inar (in:ar in-bus)
inkr (a2k inar)]
(send-trig trg trigger-id inkr)
(out 0 0)))
(defsynth trigger-generator [base-trigger-bus-in 0
base-counter-bus-in 0
base-pattern-buffer-in 0
base-pattern-value-buffer-in 0
trigger-bus-out 0
trigger-value-bus-out 0
trigger-id 0
trigger-val-id 0
base-dur-in 0]
(let [base-trigger (in:kr base-trigger-bus-in)
base-counter (in:kr base-counter-bus-in)
pattern-buffer-id (dbufrd base-pattern-buffer-in base-counter)
pattern-value-buffer-id (dbufrd base-pattern-value-buffer-in base-counter)
pattern-first-value (demand:kr base-trigger base-trigger (dbufrd pattern-buffer-id (dseries 0 1 1) 0) )
pattern-value-start-idx (select:kr
(= 0.0 pattern-first-value) [0 1])
;; Depending on if a spacer trigger exists or not in the first index of a buffer,
;;this value needs to be either 1 or 0 in order to play the buffer as intended.
trg (t-duty:kr
(* (dbufrd base-dur-in (dseries 0 1 INF) )
(dbufrd pattern-buffer-id (dseries 0 1 INF) 0))
base-trigger
(dbufrd pattern-buffer-id (dseries 0 1 INF) 0))
pattern-item-value (demand:kr trg base-trigger
(dbufrd pattern-value-buffer-id
(dseries pattern-value-start-idx 1 INF)))
pattern-trg-value (demand:kr trg base-trigger
(dbufrd pattern-buffer-id
(dseries pattern-value-start-idx 1 INF)))
cntr (pulse-count:kr trg base-trigger)
trg (select:kr (= 0 cntr) [trg 0]) ]
(send-trig trg trigger-id pattern-trg-value)
(send-trig trg trigger-val-id pattern-item-value)
(out:kr trigger-value-bus-out pattern-item-value)
(out:kr trigger-bus-out trg)))
;Buffer pool functions
(defn store-buffer [buf]
(let [size (buffer-size buf)
buf-id-key (keyword (str (buffer-id buf)))
size-key (keyword (str size))
pool @bufferPool
pool (update pool size-key (fnil concat []) [buf])]
(reset! bufferPool pool)
(reset! buffersInUse (dissoc @buffersInUse buf-id-key))))
(defn retrieve-buffer [size]
;(println size)
(let [size-key (keyword (str size))
pool @bufferPool
buffers-left (and (contains? pool size-key) (< 0 (count (size-key pool))))
first-buf (first (size-key pool))
rest-buf (rest (size-key pool))
pool (assoc pool size-key rest-buf )]
(if (and buffers-left true )
(do (let [first-buf-id-key (keyword (str (buffer-id first-buf)))]
(if (not (contains? @buffersInUse first-buf-id-key))
(do
;(println "use existing buffer")
(reset! bufferPool pool)
(reset! buffersInUse (assoc @buffersInUse first-buf-id-key first-buf))
first-buf)
(do
;(println "create new buffer")
(let [new-buf (with-server-sync #(buffer size) "Whilst retrieve-buffer")]
(reset! buffersInUse (assoc @buffersInUse
(keyword
(str (buffer-id new-buf))) new-buf))
new-buf))
))
first-buf)
(do (let [new-buf (with-server-sync #(buffer size) "Whilst retrieve-buffer")]
(reset! buffersInUse (assoc @buffersInUse
(keyword
(str (buffer-id new-buf))) new-buf))
new-buf)) )))
(defn generate-buffer-pool [sizes amount]
(let [size-vectors (vec (range 1 sizes))
size-keys (pmap (fn [x] (keyword (str x))) size-vectors)
buffers (doall (pmap (fn [y] (doall (map (fn [x] (with-server-sync #(buffer x) "Whilst generate-buffer-pool")) (repeat amount y)))) size-vectors))
b_p (zipmap size-keys buffers)]
(reset! bufferPool b_p)) nil)
;Start
(defn start-trigger []
(init_groups_dur_and_del)
(def base-trigger-id (trig-id))
(def base-trigger-bus (control-bus 1))
(def external-trigger-bus (control-bus 1))
(def base-trigger-dur-bus (control-bus 1))
(control-bus-set! base-trigger-dur-bus 1)
(buffer-write! base-dur [(/ 1 0.5625)])
(def base-trigger (base-trigger-synth [:tail main-g] base-trigger-bus base-trigger-id base-dur base-del))
(def base-trigger-count-bus (control-bus 1))
(def base-trigger-count (base-trigger-counter [:tail main-g] base-trigger-bus base-trigger-count-bus))
(println "Begin generating buffer pool, please wait.")
(generate-buffer-pool 128 256)
(println "trigger initialized")
(println (trigger-logo))
)
;Default value bus generation
(defn is-in-arg [arg-key arg-val]
(if (some? (re-find #"in-" (str arg-key))) {(keyword arg-key) arg-val} nil ))
(defn get-in-defaults [synth-name]
(let [arg-names (map :name (:params synth-name))
arg-keys (map :default (:params synth-name))
arg-val-keys (map (fn [x] (keyword (str (name x) "-val"))) arg-keys)
args-names-vals (map (fn [x y] (is-in-arg x y)) arg-names arg-keys)
args-names-vals (remove nil? args-names-vals)
args-names-vals (apply conj args-names-vals)]
args-names-vals) )
(defn generate-default-buses [synth-name]
(let [anv (get-in-defaults synth-name)
buses-def (vec (map (fn [x] (control-bus 1)) (vals anv)))
set-buses (vec (map (fn [x y] (control-bus-set! x y)) buses-def (vals anv )))
buses (vec (map (fn [x y] {x y}) (keys anv) buses-def))
buses (apply conj buses)]
buses))
(defn trigger-dur [dur]
(if (= dur 0) 0 1) )
;Pattern generation functions
(defn traverse-vector ([input-array]
(let [input-vec input-array
xvv (vec input-vec)
result []]
(if true
(loop [xv input-vec
result []]
(if xv
(let [ length (count input-vec)
x (first xv)]
(if (vector? x) (recur (next xv) (conj result (traverse-vector x length)))
(recur (next xv) (conj result (/ 1 length 1))))) result)))))
([input-array bl] (let [input-vec input-array
xvv (vec input-vec)]
(if (vector? input-vec)
(loop [xv input-vec
result []]
(if xv
(let [length (count input-vec)
x (first xv)]
(if (vector? x) (recur (next xv) (conj result (traverse-vector x (* bl length))))
(recur (next xv) (conj result (/ 1 length bl))))) result))))))
(defn sum-zero-durs [idxs input-vector full-durs]
(let [idxsv (vec idxs)]
(loop [xv idxsv
sum 0]
(if xv
(let [x (first xv)
zero-x (nth input-vector x )
dur-x (nth full-durs x)]
(if (= zero-x 0) (do (recur (next xv) (+ dur-x sum))) sum)) sum))))
(defn adjust-duration [input-vector input-original]
(let [length (count input-vector)
full-durs input-vector
input-vector (into [] (map * input-vector input-original))
idxs (vec (range length))]
(loop [xv idxs
result []]
(if xv
(let [xidx (first xv)
nidx (if (< (+ 1 xidx) length) (+ 1 xidx) (- length 1))
opnext (nth input-vector nidx)
op (nth input-vector xidx)
vec-ring (vec (subvec idxs nidx))
op (if (and (not= 0 op) ( = 0 opnext)) (+ op (sum-zero-durs vec-ring input-vector full-durs)) op)]
(recur (next xv) (conj result op))) result))))
(defn generate-durations [input input-val]
(let [mod-input (vec (map trigger-dur (vec (flatten input))))
durs (traverse-vector input)
durs (into [] (flatten durs))
mod-beat durs
durs (adjust-duration durs (vec (flatten mod-input)))]
{:dur durs :val (flatten input-val) :mod-input mod-beat }))
(defn split-to-sizes [input sizes]
(let [s input]
(apply concat (reduce
(fn [[s xs] len]
[(subvec s len)
(conj xs (subvec s 0 len))])
[s []]
sizes))))
(defn conditional-remove-zero [cond inputvec]
(let [size (count inputvec)
idxs (vec (range size))]
(loop [xv idxs
result []]
(if xv
(let [idx (first xv)
cond-i (nth cond idx )
value-i (nth inputvec idx)]
(if (= cond-i false) (do (recur (next xv) (conj result value-i))) (do (recur (next xv) result )))) result))))
(defn dur-and-val-zero [durs vals]
(map (fn [x y] (= x y 0)) durs vals))
(defn string-zero-to-one [str-in]
(clojure.string/replace str-in #"0" "1") )
(defn string-hyphen-to-zero [str-in]
(clojure.string/replace str-in #"~" "0") )
(defn fix-pattern-borders [input-vector]
(let [xvr (vec (range (count input-vector)))]
(loop [xv xvr
result input-vector]
(if xv
(let [x (first xv)
pattern-x (vec (nth result x ))
pattern-x-prev (vec (nth result (mod (- x 1) (count result))))
pattern-mod (assoc pattern-x 0 (last pattern-x-prev))]
(if true (do (recur (next xv) (assoc result x (seq pattern-mod)))) nil)) result))))
(defn generate-pattern-vector [new-buf-data]
(let [new-trig-data (vec (map (fn [x] (string-zero-to-one x)) new-buf-data))
new-trig-data (map clojure.edn/read-string (vec (map (fn [x] (string-hyphen-to-zero x)) new-trig-data)))
new-val-data (map clojure.edn/read-string (vec (map (fn [x] (string-hyphen-to-zero x)) new-buf-data)))
new-durs-and-vals (map generate-durations new-trig-data new-val-data)
durs (map :dur new-durs-and-vals)
vals (map :val new-durs-and-vals)
mod-beat (map :mod-input new-durs-and-vals)
base-sizes (map count new-trig-data)
base-durations (map (fn [x] (/ 1 x) ) base-sizes)
leading-zeros (map (fn [x] (count (filter #{0} (first (partition-by identity x))))) durs)
silent-trigger-durs (mapv (fn [x y] (into [] (subvec x 0 y))) mod-beat leading-zeros )
silent-trigger-durs (mapv (fn [x] (reduce + x)) silent-trigger-durs)
durs-and-vals-zero (mapv (fn [x y] (vec (dur-and-val-zero x y))) durs vals)
durs (mapv (fn [x y] (conditional-remove-zero x y)) durs-and-vals-zero durs)
vals (map (fn [x y] (conditional-remove-zero x y)) durs-and-vals-zero vals)
durs (mapv (fn [x y] (concat [x] y)) silent-trigger-durs durs)
vals (mapv (fn [x]
(let [cur-idx x
cur-vec (nth vals cur-idx)]
(concat [0] cur-vec))) (range (count vals)))
vals_range (range (count vals))
vals (fix-pattern-borders vals)
vals (fix-pattern-borders vals)]
{:dur durs :val vals}))
;pattern timing adjustments
(defn set-pattern-duration [dur]
(buffer-write! base-dur [dur])nil)
(defn set-pattern-delay [delay]
(buffer-write! base-del [delay]) nil)
;Synth trigger generation
(defprotocol synth-control
(kill-synth [this])
(kill-trg [this])
(ctl-synth [this var value])
(free-default-buses [this])
(free-out-bus [this])
(free-secondary-out-bus [this])
(apply-default-buses [this])
(apply-default-bus [this db])
(apply-control-out-bus [this])
(apply-out-bus [this])
(apply-secondary-out-bus [this])
(free-control-out-bus [this])
(set-out-channel [this channel]))
(defrecord synthContainer [pattern-name
group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
is-sub-synth
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
]
synth-control
(kill-synth [this] (kill (. this play-synth)))
(kill-trg [this] (group-free (. this group)))
(ctl-synth [this var value] (ctl (. this play-synth) var value))
(free-default-buses [this] ( doseq [x (vals default-buses)] (free-bus x)))
(free-out-bus [this] (free-bus (. this out-bus)))
(free-secondary-out-bus [this] (free-bus (. this out-bus-secondary)))
(apply-default-buses [this] (doseq [x default-buses] (ctl (. this play-synth) (key x) (val x))))
(apply-default-bus [this db] (ctl (. this play-synth) db (db default-buses)))
(apply-control-out-bus [this] (ctl (. this play-synth) :ctrl-out (. this control-out-bus)))
(apply-out-bus [this] (ctl (. this play-synth) :out-bus 0 ))
(apply-secondary-out-bus [this] (ctl (. this play-synth) :out-bus (. this out-bus-secondary)))
(free-control-out-bus [this] (free-bus (. this control-out-bus)))
(set-out-channel [this channel] (ctl (. this out-mixer ) :out-bus channel)))
(defprotocol trigger-control
(kill-trg-group [this])
(store-buffers [this])
(get-or-create-pattern-buf [this new-size])
(get-or-create-pattern-value-buf [this new-size])
(get-trigger-value-bus [this])
(get-pattern-vector [this])
(get-pattern-value-vector [this])
(pause-trigger [this])
(play-trigger [this]))
(defrecord triggerContainer [trigger-id
trigger-val-id
control-key
control-val-key
group
play-synth
trigger-bus
trigger-value-bus
trigger-synth
pattern-vector
pattern-value-vector
pattern-buf
pattern-value-buf
original-pattern-vector
original-pattern-value-vector]
trigger-control
(kill-trg-group [this] (do (group-free (. this group))
(free-bus trigger-bus)
(free-bus trigger-value-bus)
(doseq [x pattern-vector] (store-buffer x))
(doseq [x pattern-value-vector] (store-buffer x))
(store-buffer pattern-buf)
(store-buffer pattern-value-buf)))
(store-buffers [this] (doseq [x pattern-vector] (store-buffer x))
(doseq [x pattern-value-vector] (store-buffer x))
(store-buffer pattern-buf)
(store-buffer pattern-value-buf))
(get-or-create-pattern-buf [this new-size] (let [old-size (count (. this pattern-vector))]
(if (= old-size new-size)
(. this pattern-buf)
(do (store-buffer (. this pattern-buf))
(retrieve-buffer new-size)) )))
(get-or-create-pattern-value-buf [this new-size] (let [old-size (count (. this pattern-value-vector))]
(if (= old-size new-size)
(. this pattern-value-buf)
(do (store-buffer (. this pattern-value-buf )) (retrieve-buffer new-size)))))
(get-trigger-value-bus [this] (. this trigger-value-bus))
(get-pattern-vector [this] (. this pattern-vector))
(get-pattern-value-vector [this] (. this pattern-value-vector))
(pause-trigger [this] (node-pause (to-id (. this trigger-synth))))
(play-trigger [this] (node-start (to-id (. this trigger-synth)))))
(defn create-synth-config [pattern-name synth-name & {:keys [issub]
:or {issub false}}]
(let [out-bus (audio-bus 1)
out-bus-secondary (audio-bus 1)
synth-group (with-server-sync #(group pattern-name :tail main-g) "synth group")
sub-synth-group (with-server-sync #(group "sub-synth-group" :tail synth-group) "sub-synth group")
mixer-group (with-server-sync #(group "mixer-group" :tail synth-group) "mixer group")
play-synth (with-server-sync #(synth-name [:head synth-group] :out-bus out-bus) "synth creation")
;;trigger-vol-id (trig-id)
;;vol-sender (vol-send [:tail mixer-group] out-bus 0.017 trigger-vol-id)
out-mixer (mono-inst-mixer [:tail mixer-group] out-bus 0 1 0.0)
_ (println play-synth)
default-buses (generate-default-buses synth-name)
control-out-bus (control-bus 1)
triggers {}
sub-synths {}
synth-container (synthContainer.
pattern-name
synth-group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
issub
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
)]
(apply-default-buses synth-container)
(apply-control-out-bus synth-container)
synth-container))
(defn create-synth-config! [pattern-name sub-pattern-name synth-name & {:keys [issub]
:or {issub true}}]
(let [out-bus (:out-bus (@synthConfig pattern-name))
out-bus-secondary (:out-bus-secondary (@synthConfig pattern-name))
sub-synth-group (:sub-synth-group (@synthConfig pattern-name))
synth-group (:group (@synthConfig pattern-name))
mixer-group (:mixer-group (@synthConfig pattern-name))
play-synth (with-server-sync
#(synth-name [:tail sub-synth-group] :bus-in out-bus :out-bus out-bus)
(str "create synth config" sub-pattern-name))
out-mixer (:out-mixer (@synthConfig pattern-name))
;;trigger-vol-id (:trigger-vol-id (@synthConfig pattern-name))
;;vol-sender (:vol-sender (@synthConfig pattern-name))
_ (println play-synth)
default-buses (generate-default-buses synth-name)
control-out-bus (control-bus 1)
triggers {}
sub-synths {pattern-name (keyword sub-pattern-name)}
synth-container (synthContainer.
sub-pattern-name
sub-synth-group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
issub
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
)]
(apply-default-buses synth-container)
(apply-control-out-bus synth-container)
synth-container))
(defn buffer-writer [buf data]
;(println (buffer-id buf))
(with-server-sync #(buffer-write-relay! buf data) "Whlist buffer-writer")
;; (try
;; ;(buffer-write-relay! buf data)
;; (do
;; (println "Buffer write failed")
;; ;(store-buffer buf)
;; ))
)
(defn create-trigger [control-key
control-val-key
synth-name
pattern-group
pattern-vector
pattern-value-vector]
(let [trigger-id (with-server-sync #(trig-id) "create-trigger, trigger-id")
trigger-val-id (with-server-sync #(trig-id) "create-trigger, trigger-val-id")
trig-group (with-server-sync #(group (str control-key) :tail pattern-group) (str "trigger-group" control-key))
trig-bus (with-server-sync #(control-bus 1) "create-trigger, trig-bus")
trig-val-bus (with-server-sync #(control-bus 1) "create-trigger, trig-val-bus")
buf-size (count pattern-vector)
dur-buffers (vec (mapv (fn [x] (retrieve-buffer (count x))) pattern-vector))
val-buffers (vec (mapv (fn [x] (retrieve-buffer (count x))) pattern-value-vector))
_ (vec (mapv (fn [x y] (buffer-writer x y)) dur-buffers pattern-vector ))
_ (vec (mapv (fn [x y] (buffer-writer x y)) val-buffers pattern-value-vector))
pattern-id-buf (retrieve-buffer buf-size)
pattern-value-id-buf (retrieve-buffer buf-size)
dur-id-vec (vec (map (fn [x] (buffer-id x)) dur-buffers))
val-id-vec (vec (map (fn [x] (buffer-id x)) val-buffers))
_ (buffer-writer pattern-id-buf dur-id-vec)
_ (buffer-writer pattern-value-id-buf val-id-vec)
trig-synth (with-server-sync
#(trigger-generator [:tail trig-group]
base-trigger-bus
base-trigger-count-bus
pattern-id-buf
pattern-value-id-buf
trig-bus
trig-val-bus
trigger-id
trigger-val-id
base-dur)
(str "trigger" control-key))]
(try
(do (ctl synth-name control-key trig-bus control-val-key trig-val-bus))
(catch Exception ex
(println "CTL failed during create-trigger")))
(triggerContainer. trigger-id trigger-val-id control-key control-val-key trig-group synth-name trig-bus trig-val-bus trig-synth dur-buffers val-buffers pattern-id-buf pattern-value-id-buf pattern-vector pattern-value-vector)))
(defn reuse-or-create-buffer [new-buf-vec]
(let [new-size (count new-buf-vec)]
(retrieve-buffer new-size)))
;Buffer-write relays cause timeout expections occasionally
(defn update-trigger [trigger
pattern-vector
pattern-value-vector]
(let [trigger_old trigger
control-key (:control-key trigger)
buf-size (count pattern-vector)
old-dur-buffers (vec (:pattern-vector trigger))
old-val-buffers (vec (:pattern-value-vector trigger))
old-id-buffers (:pattern-buf trigger)
old-value-id-buffers (:pattern-value-buf trigger)
dur-buffers (vec (map (fn [x] (reuse-or-create-buffer x)) pattern-vector))
val-buffers (vec (map (fn [x] (reuse-or-create-buffer x)) pattern-value-vector))
_ (vec (mapv (fn [x y] (buffer-writer x y)) dur-buffers pattern-vector ))
_ (vec (mapv (fn [x y] (buffer-writer x y)) val-buffers pattern-value-vector))
pattern-id-buf (retrieve-buffer buf-size)
pattern-value-id-buf (retrieve-buffer buf-size)
_ (buffer-writer pattern-id-buf (vec (map (fn [x] (buffer-id x)) dur-buffers)))
_ (buffer-writer pattern-value-id-buf (vec (map (fn [x] (buffer-id x)) val-buffers)))
trigger (assoc trigger :pattern-vector dur-buffers)
trigger (assoc trigger :pattern-value-vector val-buffers)
trigger (assoc trigger :pattern-buf pattern-id-buf)
trigger (assoc trigger :pattern-value-buf pattern-value-id-buf)
trigger (assoc trigger :original-pattern-vector pattern-vector)
trigger (assoc trigger :original-pattern-value-vector pattern-value-vector)
trig-synth (:trigger-synth trigger)]
;(println old-dur-buffers)
;(println old-id-buffers)
;(println old-value-id-buffers)
(try
(do (ctl trig-synth
:base-pattern-buffer-in pattern-id-buf
:base-pattern-value-buffer-in pattern-value-id-buf)
(vec (map (fn [x] (store-buffer x)) old-dur-buffers))
(vec (map (fn [x] (store-buffer x)) old-val-buffers))
(vec (map (fn [x] (store-buffer x)) [old-id-buffers]))
(vec (map (fn [x] (store-buffer x)) [old-value-id-buffers]))
trigger)
(catch Exception ex
(do
(println "CTL failed during update-trigger" control-key)
(println (str (.getMessage ex)))
(.store-buffers trigger)
trigger_old)))))
(defn changed? [trigger new-trigger-pattern new-control-pattern]
(let [old-trigger-pattern (:original-pattern-vector trigger)
old-control-pattern (:original-pattern-value-vector trigger)]
;(println old-trigger-pattern)
(or (not= new-trigger-pattern old-trigger-pattern) (not= new-control-pattern old-control-pattern))))
(defn t [synth-container control-pair]
(let [control-key (first control-pair)
control-val-key (keyword (str (name control-key) "-val"))
control-pattern (last control-pair)
pattern-vectors (generate-pattern-vector control-pattern)
trig-pattern (:dur pattern-vectors)
val-pattern (:val pattern-vectors)
pattern-group (:group synth-container)
triggers (:triggers synth-container)
play-synth (:play-synth synth-container)
trigger-status (control-key triggers)
has-changed (if (some? trigger-status)
(changed? trigger-status trig-pattern val-pattern))
;_ (println control-key)
trigger (if (some? trigger-status)
(if (= true has-changed)
(update-trigger trigger-status trig-pattern val-pattern) trigger-status)
(create-trigger control-key
control-val-key
play-synth
pattern-group
trig-pattern
val-pattern))]
trigger))
(defonce r "~")
(defn parse-input-vector [input]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv) ]
(if (vector? fst) (recur (next xv) (conj result (vec (parse-input-vector fst))))
(if (seq? fst) (recur (next xv) (apply conj result (vec (parse-input-vector fst))))
(recur (next xv) (conj result fst))))) result ))))
(defn parse-input-vector-string [input idx]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv) ]
(if (vector? fst) (recur (next xv) (conj result (vec (parse-input-vector-string fst idx))))
(if (seq? fst) (recur (next xv) (apply conj result (vec (parse-input-vector-string fst idx))))
(recur (next xv) (conj result (clojure.string/trim (nth (clojure.string/split fst #",") idx))))))) result ))))
(defn string-not-r? [x]
(let [is-string (string? x)
is-r (if is-string (= r x) false)]
(if (and is-string (not is-r )) true false )))
(defn split-special-string [x d]
(clojure.string/trim (last (clojure.string/split x d 2))))
(defn match-special-case [x]
(let [is-input-string (string-not-r? x)
n-string "n"
freq-string "f"
buffer-string "b"
value-string "v"
]
(if is-input-string
(cond
;(re-matches #"n.*" x) (note (keyword (split-special-string x #"n")))
(re-matches #"n.*" x) (midi->hz (note (keyword (split-special-string x #"n"))))
(re-matches #"f.*" x) (midi->hz (note (keyword (split-special-string x #"f"))))
(re-matches #"b.*" x) (get-sample-id (keyword (split-special-string x #"b")))
(re-matches #"v.*" x) (Float/parseFloat (split-special-string x #"v")))
(cond
(= x nil) r
:else x))))
(defn special-case [input key]
(let [y input]
(match-special-case y)))
(defn apply-special-cases [input special-cond]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv)]
(if (vector? fst)
(recur (next xv) (conj result (vec (apply-special-cases fst special-cond))))
(recur (next xv) (conj result (special-case fst special-cond))))) result ))))
(defn copy-key-val [input key]
(let [value (key input)
value-size (count value)
is-string (if (= 1 value-size) (string? (first value)) false)
is-keyformat (if is-string (= 2 (count (clojure.string/split (first value) #":"))) false)
source-key (if is-keyformat (keyword (last (clojure.string/split (first value) #":"))) nil)
has-source (contains? input source-key)]
(if has-source (source-key input) (key input))))
(defn split-input [input]
(let [ip (into
(sorted-map)
(map (fn [x] {(first (first x)) (vec (parse-input-vector (last x)))})
(partition 2 (partition-by keyword? input))))
specip (into {} (map (fn [x] {x (copy-key-val ip x)}) (keys ip)))
ip specip
ip (into {} (map (fn [x] {x (apply-special-cases (x ip) x)}) (keys ip))) ]
(apply conj
(map (fn [x] {(key x) (vec (map (fn [x] (clojure.string/replace x #"\"~\"" "~") ) (map str (val x))))})
ip))))
(defn synth-name-check [new-sn synth-container]
(let [sc synth-container
old-sn (:synth-name synth-container)]
(if (nil? sc) new-sn
(if (not= old-sn new-sn) old-sn new-sn))))
;Alternative input system
(defn inp [keys & input]
(if true
(let [no_keys (count keys)
output (map (fn [x] (seq [(keyword (nth keys x)) (seq (parse-input-vector-string input x))])) (range no_keys) )]
(seq (parse-input-vector output)))
input))
(declare trg)
(defn make-helper-function [pattern-name synth-name & input]
(let [fname (symbol pattern-name)]
(if (nil? (resolve (symbol pattern-name)))
(do (intern (ns-name *ns*) fname (fn [& input] (trg (keyword pattern-name) synth-name input ))))
(do (println "Definition exists")))))
;New trigger input function, allows more terse and powerful way to create patterns. Now clojure functions such as repeat can be used directly in the input.
(defn trg ([pn sn & input]
(let [input (seq (parse-input-vector input))
pattern-name (if (keyword? pn) (name pn) pn )
pattern-name-key (keyword pattern-name)
synth-container (pattern-name-key @synthConfig)
synth-name (synth-name-check sn synth-container)
input (split-input input)
original-input input
valid-keys (concat [:pn :sn] (vec (synth-args synth-name)))
input (select-keys input (vec valid-keys)) ; Make input valid, meaning remove control keys that are not present in the synth args
input-controls-only input
initial-controls-only input-controls-only
input-check (some? (not-empty input-controls-only))]
(if
(= nil synth-container)
(do (println "Synth created")
(swap! synthConfig assoc pattern-name-key (create-synth-config pattern-name synth-name)))
(do (println "Synth exists")))
(do
(let [synth-container (pattern-name-key @synthConfig)
triggers (:triggers synth-container)
running-trigger-keys(keys triggers)
input-trigger-keys (keys initial-controls-only)
synth-container (assoc synth-container :triggers triggers)]
(swap! synthConfig assoc pattern-name-key synth-container)))
(let [synth-container (pattern-name-key @synthConfig)
triggers (:triggers synth-container)
;_ (println input-controls-only)
;_ (println (filter #(not (.contains (flatten %) nil)) input-controls-only) )
updated-triggers (zipmap
(keys input-controls-only)
(map
(partial t (pattern-name-key @synthConfig)) input-controls-only))
merged-triggers (merge triggers updated-triggers)
]
(swap! synthConfig assoc pattern-name-key
(assoc (pattern-name-key @synthConfig)
:triggers
merged-triggers)))
(make-helper-function pattern-name synth-name input)
pattern-name)))
(defn trg! ([pn spn sn & input]
(let [pattern-name (if (keyword? pn) (name pn) pn )
pattern-name-key (keyword pattern-name)
sub-pattern-name (if (keyword? spn) (name spn) spn )
sub-pattern-name-key (keyword sub-pattern-name)
parent-synth-container (pattern-name-key @synthConfig)
parent-sub-synths (:sub-synths parent-synth-container)
synth-container (sub-pattern-name-key @synthConfig)
synth-name (synth-name-check sn synth-container)
input (split-input input)
original-input input
valid-keys (concat [:pn :spn :sn] (vec (synth-args synth-name)))
input (select-keys input (vec valid-keys)) ; Make input valid, meaning remove control keys that are not present in the synth args
input-controls-only input
initial-controls-only input-controls-only
input-check (some? (not-empty input-controls-only))]
(if (not= nil parent-synth-container)
(do (if (= nil synth-container)
(do (println "Synth created")
(swap! synthConfig assoc pattern-name-key (assoc parent-synth-container :sub-synths (assoc parent-sub-synths sub-pattern-name-key pattern-name-key)))
(swap! synthConfig assoc sub-pattern-name-key (create-synth-config! pattern-name-key sub-pattern-name synth-name)) )
(do (println "Synth exists")))
(do
(let [synth-container (sub-pattern-name-key @synthConfig)
triggers (:triggers synth-container)
running-trigger-keys(keys triggers)
input-trigger-keys (keys initial-controls-only)
triggers-not-renewd (first (diff running-trigger-keys input-trigger-keys))
synth-container (assoc synth-container :triggers triggers)]
(swap! synthConfig assoc sub-pattern-name-key synth-container)))
(let [synth-container (sub-pattern-name-key @synthConfig)
triggers (:triggers synth-container)
updated-triggers (zipmap
(keys input-controls-only)
(map
(partial t (sub-pattern-name-key @synthConfig)) input-controls-only))
merged-triggers (merge triggers updated-triggers)
] (swap! synthConfig assoc sub-pattern-name-key
(assoc (sub-pattern-name-key @synthConfig)
:triggers
merged-triggers
)))) (println "Parent synth" pattern-name-key "does not exist.") )
(make-helper-function sub-pattern-name synth-name input)
sub-pattern-name)))
;;Functions to set patterns to multiple synths at once, for example to
;;play chords.
(defn | [& input]
(let [input (piv input)
lenip (count input)
ranip (mapv keyword (mapv str(vec (range lenip))))
ip (zipmap ranip input)]
;(println ip)
(fn [] ip)))
(defn condition-pattern [pattern key replace-with-r open-map]
(let [mod-pat1 (clojure.walk/prewalk
#(condp apply [%]
number? (if replace-with-r r %)
%)
pattern)
mod-pat2 (clojure.walk/prewalk
#(condp apply [%]
map? (if open-map (key %) %)
keyword? %
fn? (if (and (map? (%)) open-map)
(if (nil? (key (%))) r (key (%)) ) (%))
string? %
%)
mod-pat1)]
;(println "mod-pat2" mod-pat2)
mod-pat2))
;(trg :kick_1 (:synth-name (:kick_1 @synthConfig)) :in-f3 [100])
(defn gtc [synths & input]
(let [synths synths
last-synths (subvec synths 1)
lensynths (count synths)
ransynths (mapv keyword (mapv str (vec (range lensynths))))
synmap (zipmap synths (vec (range (count synths))))
patterns (condition-pattern input :0 false true)]
;(println synmap)
;(trg (first synths) (:synth-name ((first synths) @synthConfig)) (condition-pattern input (keyword (str ((first synths) synmap))) false true ))
(doseq [x synths] (trg x (:synth-name (:x @synthConfig)) (condition-pattern input (keyword (str (x synmap))) false true )) )
;(println patterns)
))
; Misc pattern related functions
(defn stop-pattern [pattern-name]
(let [pattern-name-key pattern-name ;(keyword pattern-name)
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
;_ (println pattern-name-key)
;_ (println issub)
;_ (println sub-synths)
;_ (println (into [] (filter #(do (= (first %) pattern-name-key) sub-synths))))
sub-synth-keys (keys sub-synths)
;_ (println sub-synth-keys)
sub-synth-vals (vals sub-synths)
triggers (vals (:triggers pattern-status))]
(if (some? pattern-status)
(do (if (not issub) (free-default-buses pattern-status))
(if (not issub) (free-control-out-bus pattern-status))
(if (not issub) (free-out-bus pattern-status))
(if (not issub) (free-secondary-out-bus pattern-status))
(doseq [x triggers] (kill-trg-group x))
(if (not issub)
(kill-trg pattern-status)
(kill-synth pattern-status) )
(if (not issub)
(reset! synthConfig (apply dissoc @synthConfig sub-synth-keys))
(do
(reset! synthConfig (apply dissoc @synthConfig sub-synth-vals))
(doseq [x sub-synth-keys] (reset! synthConfig (assoc @synthConfig x (assoc (x @synthConfig) :sub-synths (apply dissoc (:sub-synths (x @synthConfig)) sub-synth-vals))))))
)
(swap! synthConfig dissoc pattern-name-key) (println "pattern" (:pattern-name pattern-status) "stopped")) (println "No such pattern") )))
(defn stp [& pattern-names]
(doseq [x pattern-names]
(let [pattern-name-key x
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
sub-synth-keys (keys sub-synths)]
;(println sub-synth-keys)
;(println issub)
(doseq [y sub-synth-keys] (do (if (:is-sub-synth (y @synthConfig)) (stop-pattern y))))
(stop-pattern x)) ))
(defn sta []
(doseq [x (keys @synthConfig)]
(let [pattern-name-key x
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
sub-synth-keys (keys sub-synths)]
;(println sub-synth-keys)
;(println issub)
(doseq [y sub-synth-keys] (do (if (:is-sub-synth (y @synthConfig)) (stop-pattern y))))
(stop-pattern x)) (stop-pattern x)))
(defn set-out-bus [pattern-name]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (apply-out-bus pattern-status) )))
(defn set-secondary-out-bus [pattern-name]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (apply-secondary-out-bus pattern-status) )))
(defn set-mixer-out-channel [pattern-name channel]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (set-out-channel pattern-status channel) )) nil)
(defn get-out-bus [pattern-name]
(:out-bus (pattern-name @synthConfig)))
(defn get-secondary-out-bus [pattern-name]
(:out-bus-secondary (pattern-name @synthConfig)))
(defn get-ctrl-bus [pattern-name]
(:control-out-bus (pattern-name @synthConfig)))
(defn get-trigger-vol-id [pattern-name]
(:trigger-vol-id (pattern-name @synthConfig)))
(defn get-trigger-bus [pattern-name trig-name]
(:trigger-bus (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-val-bus [pattern-name trig-name]
(:trigger-val-bus (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-id [pattern-name trig-name]
(:trigger-id (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-val-id [pattern-name trig-name]
(:trigger-val-id (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-vector [pattern-name trig-name]
(get-pattern-vector (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-value-vector [pattern-name trig-name]
(get-pattern-value-vector (trig-name (:triggers (pattern-name @synthConfig)))))
(defn pat [pattern-name trig-name]
(pause-trigger (trig-name (:triggers (pattern-name @synthConfig)))))
(defn stt [pattern-name trig-name]
(play-trigger (trig-name (:triggers (pattern-name @synthConfig)))))
(defn list-sub-synths [pattern-name] (let [pattern (pattern-name @synthConfig)
issub (:is-sub-synth pattern)]
(if issub (println "Is a sub-synth, parent:" (keys (:sub-synths pattern)))
(println "Sub synths:" (keys (:sub-synths pattern)))))
nil)
;pattern-vector
;pattern-value-vector
;pattern-buf
;pattern-value-buf
;original-pattern-vector
;original-pattern-value-vector
(defn get-buffer-ids [pattern-name bt]
(let [pattern-status (pattern-name @synthConfig)
triggers (:triggers pattern-status)]
;(println (count triggers))
(vec (:pattern-vector (bt triggers)))
;(mapv (fn [x] (bt ((first x) triggers))) triggers)
)
)
(defn sctl [pattern-name var value]
(let [pattern-status (pattern-name @synthConfig)]
(if (some? pattern-status) (ctl-synth pattern-status var value))))
(defn connect-synths [src-synth dst-synth input-name]
(let [output-bus (get-secondary-out-bus src-synth)]
(sctl dst-synth input-name output-bus)
(set-secondary-out-bus src-synth)) )
(defn lss [] (println (keys @synthConfig)) (keys @synthConfig) )
;OSC
;(var addr=NetAddr.new("127.0.0.1", 3333); OSCdef ('/tidalplay2', { arg msg; addr.sendMsg("/play2", *msg);}, '/play2', n);)
;; (defn init-osc [port]
;; (def oscserver (osc-server port "osc-clj"))
;; (def client (osc-client "localhost" port))
;; (zero-conf-on)
;; (java.net.InetAddress/getLocalHost))
;; (defn osc-extract-tidal [msg key]
;; (let [submsg (into [] (subvec (vec (key msg)) 1))
;; part (mapv (fn [x] [(keyword (first x)) (last x)]) (partition 2 submsg))]
;; (into {} part)))
;Algorithm
(defn rm-alg [pattern trigger buf-id]
(let [trg_str (str (name trigger) "-" (str buf-id))
alg-key (keyword (name pattern) trg_str)
key-exist (some? (alg-key @algConfig))]
(if key-exist (do
(swap! algConfig dissoc alg-key)
(remove-event-handler alg-key) ))))
(defn alg [pattern trigger buf-id function & args]
(let [pat-vec (get-vector pattern trigger)
pat-val-vec (get-value-vector pattern trigger)
trigger-id (get-trigger-val-id pattern trigger)
vec-size (count pat-vec)
trg_str (str (name trigger) "-" (str buf-id))
alg-key (keyword (name pattern) trg_str)
key-exist (some? (alg-key @algConfig))]
(println alg-key)
(println (nth pat-vec 0))
(if key-exist
(do (println "Alg key exists for pattern" pattern ", trigger" trigger ", buffer" buf-id))
(do (function trigger-id alg-key pat-vec pat-val-vec buf-id algConfig args)
(swap! algConfig assoc alg-key alg-key )))))
;Mixer and Instrument effects functions
(defn volume! [pattern-name vol] (let [pat (pattern-name @synthConfig)]
(ctl (:out-mixer pat) :volume vol) )
nil)
(defn fade-out! [pattern-name & args]
(let [pat (pattern-name @synthConfig)
synth (:out-mixer pat)
s-id (to-id synth)
ivol (node-get-control s-id :volume)
isargs (not (empty? args))
;args (if isargs (first args) args)
args (into {} (mapv vec (vec (partition 2 args))))
time (if (and isargs (contains? args :t)) (:t args) 5000)
time (if (nil? time) 1000 time)
steps 100
step (/ ivol (+ 1 steps))
rang (range ivol 0 (* -1 step))
st (/ time (+ 1 (count rang)))]
;(println step)
;(println (count rang))
;(println st)
(async/go
(doseq [x rang]
(volume! pattern-name x)
;(println x)
(async/<! (async/timeout (* 1 st))))
(volume! pattern-name 0)
;(Thread/sleep (* st 1))
)))
(defn fade-in! [pattern-name & args]
(let [pat (pattern-name @synthConfig)
synth (:out-mixer pat)
s-id (to-id synth)
ivol (node-get-control s-id :volume)
isargs (not (empty? args))
;args (if isargs (first args) args)
args (into {} (mapv vec (vec (partition 2 args))))
time (if (and isargs (contains? args :t)) (:t args) 5000)
time (if (nil? time) 1000 time)
dvol (if (and isargs (contains? args :dvol)) (:dvol args) 1)
steps 100
step (/ (- dvol ivol) (+ 1 steps))
rang (range ivol dvol step)
st (/ time (+ 1 (count rang)))]
;(println time)
;(println st)
(async/go
(doseq [x rang]
(volume! pattern-name x)
(async/<! (async/timeout st))
;(Thread/sleep (* 1000 st))
)
(volume! pattern-name dvol))))
(defn pan! [pattern-name pan] (let [pat (pattern-name @synthConfig)]
(ctl (:out-mixer pat) :pan pan) ) nil )
(defn clrfx! [pattern-name] (let [pat (pattern-name @synthConfig)
inst (:synth-name pat) ]
(clear-fx inst))
nil)
(defn pause! [pattern-name] (let [pat (pattern-name @synthConfig)
synth (:play-synth pat)
;;vo (:vol-sender pat)
s-id (to-id synth)
;;vo-id (to-id vo)
]
(node-pause s-id)
;;(node-pause vo-id)
) nil)
(defn play! [pattern-name] (let [pat (pattern-name @synthConfig)
synth (:play-synth pat)
;;vo (:vol-sender pat)
s-id (to-id synth)
;;vo-id (to-id vo)
]
(node-start s-id)
;;(node-start vo-id)
) nil)
;Start trigger
(start-trigger)
| 97619 | (ns #^{:author "<NAME>"}
trigger.trigger
(:use [overtone.core]
[clojure.data])
(:require
[trigger.synths :refer :all]
[trigger.misc :refer :all]
[trigger.algo :refer :all]
[trigger.speech :refer :all]
[trigger.samples :refer :all]
[trigger.trg_fx :refer :all]
[clojure.core.async :as async]
[clojure.tools.namespace.repl :refer [refresh]]
[clj-native.structs :refer [byref]]
[overtone.sc.machinery.server.comms :refer [with-server-sync server-sync]]
[clojure.walk :only prewalk]
[overtone.sc.machinery.server.connection :refer [boot]]
[overtone.sc.machinery.server native])
(:import
(java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder)))
;Boot Supercollider
(def port 57111)
(defn boot-ext [] (if (server-connected?) nil (boot-external-server port {:max-buffers 2621440 :max-control-bus 80960}) ))
;(boot-ext)
(defn boot-int [] (if (server-connected?) nil (boot :internal port {:max-buffers 2621440 :max-control-bus 80960}) ))
(boot-int)
;; (defn cb
;; "Get a an array of floats for the synthesis sound buffer with the given ID."
;; [sc buf-id]
;; (let [buf (byref overtone.sc.machinery.server.native/sound-buffer)
;; changed? (byref overtone.sc.machinery.server.native/bool-val)
;; ;; changed? (java.nio.ByteBuffer/allocate 1)
;; cc (ByteBuffer/allocate 1)
;; ]
;; ;(.samples buf)
;; (println buf)
;; (println (:value changed?))
;; ;(.getFloatArray (.data buf) 0 (.samples buf))
;; ( overtone.sc.machinery.server.native/world-copy-sound-buffer (:world sc) buf-id buf 0 cc)
;; ;(.getFloatArray (.data buf) 0 (.samples buf))
;; ))
;State atoms
(defonce synthConfig (atom {}))
(defonce algConfig (atom {}))
(defonce bufferPool (atom {}))
(defonce buffersInUse (atom {}))
(defonce timeatom (atom 0))
(defn init_groups_dur_and_del []
;Groups
(do
(defonce main-g (group "main group")))
;Base duration
(do
(def base-dur (buffer 1))
(buffer-write! base-dur [1]))
; Base trigger delay
(do
(def base-del (buffer 1))
(buffer-write! base-del [0])))
;Synthdefs
(defsynth base-trigger-synth [out-bus 0 trigger-id 0 base-dur-in 0 base-del-in 0]
(let [trg1 (t-duty:kr (dbufrd base-dur-in (dseries 0 1 INF)) 0 1)
trg (t-delay:kr trg1 (buf-rd:kr 1 base-del-in))]
(send-trig trg trigger-id trg)
(out:kr out-bus trg)))
(defsynth base-trigger-counter [base-trigger-bus-in 0 base-trigger-count-bus-out 0]
(out:kr base-trigger-count-bus-out (pulse-count:kr (in:kr base-trigger-bus-in))))
(def dbg (control-bus 1))
(def dbg2 (control-bus 1))
(defsynth vol-send [in-bus 0 base-dur 0.017 trigger-id 0]
(let [trg (t-duty:kr (dseq [base-dur] INF) )
inar (in:ar in-bus)
inkr (a2k inar)]
(send-trig trg trigger-id inkr)
(out 0 0)))
(defsynth trigger-generator [base-trigger-bus-in 0
base-counter-bus-in 0
base-pattern-buffer-in 0
base-pattern-value-buffer-in 0
trigger-bus-out 0
trigger-value-bus-out 0
trigger-id 0
trigger-val-id 0
base-dur-in 0]
(let [base-trigger (in:kr base-trigger-bus-in)
base-counter (in:kr base-counter-bus-in)
pattern-buffer-id (dbufrd base-pattern-buffer-in base-counter)
pattern-value-buffer-id (dbufrd base-pattern-value-buffer-in base-counter)
pattern-first-value (demand:kr base-trigger base-trigger (dbufrd pattern-buffer-id (dseries 0 1 1) 0) )
pattern-value-start-idx (select:kr
(= 0.0 pattern-first-value) [0 1])
;; Depending on if a spacer trigger exists or not in the first index of a buffer,
;;this value needs to be either 1 or 0 in order to play the buffer as intended.
trg (t-duty:kr
(* (dbufrd base-dur-in (dseries 0 1 INF) )
(dbufrd pattern-buffer-id (dseries 0 1 INF) 0))
base-trigger
(dbufrd pattern-buffer-id (dseries 0 1 INF) 0))
pattern-item-value (demand:kr trg base-trigger
(dbufrd pattern-value-buffer-id
(dseries pattern-value-start-idx 1 INF)))
pattern-trg-value (demand:kr trg base-trigger
(dbufrd pattern-buffer-id
(dseries pattern-value-start-idx 1 INF)))
cntr (pulse-count:kr trg base-trigger)
trg (select:kr (= 0 cntr) [trg 0]) ]
(send-trig trg trigger-id pattern-trg-value)
(send-trig trg trigger-val-id pattern-item-value)
(out:kr trigger-value-bus-out pattern-item-value)
(out:kr trigger-bus-out trg)))
;Buffer pool functions
(defn store-buffer [buf]
(let [size (buffer-size buf)
buf-id-key (keyword (str (buffer-id buf)))
size-key (keyword (<KEY>))
pool @bufferPool
pool (update pool size-key (fnil concat []) [buf])]
(reset! bufferPool pool)
(reset! buffersInUse (dissoc @buffersInUse buf-id-key))))
(defn retrieve-buffer [size]
;(println size)
(let [size-key (keyword (str size))
pool @bufferPool
buffers-left (and (contains? pool size-key) (< 0 (count (size-key pool))))
first-buf (first (size-key pool))
rest-buf (rest (size-key pool))
pool (assoc pool size-key rest-buf )]
(if (and buffers-left true )
(do (let [first-buf-id-key (keyword (str (buffer-id first-buf)))]
(if (not (contains? @buffersInUse first-buf-id-key))
(do
;(println "use existing buffer")
(reset! bufferPool pool)
(reset! buffersInUse (assoc @buffersInUse first-buf-id-key first-buf))
first-buf)
(do
;(println "create new buffer")
(let [new-buf (with-server-sync #(buffer size) "Whilst retrieve-buffer")]
(reset! buffersInUse (assoc @buffersInUse
(keyword
(str (buffer-id new-buf))) new-buf))
new-buf))
))
first-buf)
(do (let [new-buf (with-server-sync #(buffer size) "Whilst retrieve-buffer")]
(reset! buffersInUse (assoc @buffersInUse
(keyword
(str (buffer-id new-buf))) new-buf))
new-buf)) )))
(defn generate-buffer-pool [sizes amount]
(let [size-vectors (vec (range 1 sizes))
size-keys (pmap (fn [x] (keyword (str x))) size-vectors)
buffers (doall (pmap (fn [y] (doall (map (fn [x] (with-server-sync #(buffer x) "Whilst generate-buffer-pool")) (repeat amount y)))) size-vectors))
b_p (zipmap size-keys buffers)]
(reset! bufferPool b_p)) nil)
;Start
(defn start-trigger []
(init_groups_dur_and_del)
(def base-trigger-id (trig-id))
(def base-trigger-bus (control-bus 1))
(def external-trigger-bus (control-bus 1))
(def base-trigger-dur-bus (control-bus 1))
(control-bus-set! base-trigger-dur-bus 1)
(buffer-write! base-dur [(/ 1 0.5625)])
(def base-trigger (base-trigger-synth [:tail main-g] base-trigger-bus base-trigger-id base-dur base-del))
(def base-trigger-count-bus (control-bus 1))
(def base-trigger-count (base-trigger-counter [:tail main-g] base-trigger-bus base-trigger-count-bus))
(println "Begin generating buffer pool, please wait.")
(generate-buffer-pool 128 256)
(println "trigger initialized")
(println (trigger-logo))
)
;Default value bus generation
(defn is-in-arg [arg-key arg-val]
(if (some? (re-find #"in-" (str arg-key))) {(keyword arg-key) arg-val} nil ))
(defn get-in-defaults [synth-name]
(let [arg-names (map :name (:params synth-name))
arg-keys (map :default (:params synth-name))
arg-val-keys (map (fn [x] (keyword (str (name x) "-val"))) arg-keys)
args-names-vals (map (fn [x y] (is-in-arg x y)) arg-names arg-keys)
args-names-vals (remove nil? args-names-vals)
args-names-vals (apply conj args-names-vals)]
args-names-vals) )
(defn generate-default-buses [synth-name]
(let [anv (get-in-defaults synth-name)
buses-def (vec (map (fn [x] (control-bus 1)) (vals anv)))
set-buses (vec (map (fn [x y] (control-bus-set! x y)) buses-def (vals anv )))
buses (vec (map (fn [x y] {x y}) (keys anv) buses-def))
buses (apply conj buses)]
buses))
(defn trigger-dur [dur]
(if (= dur 0) 0 1) )
;Pattern generation functions
(defn traverse-vector ([input-array]
(let [input-vec input-array
xvv (vec input-vec)
result []]
(if true
(loop [xv input-vec
result []]
(if xv
(let [ length (count input-vec)
x (first xv)]
(if (vector? x) (recur (next xv) (conj result (traverse-vector x length)))
(recur (next xv) (conj result (/ 1 length 1))))) result)))))
([input-array bl] (let [input-vec input-array
xvv (vec input-vec)]
(if (vector? input-vec)
(loop [xv input-vec
result []]
(if xv
(let [length (count input-vec)
x (first xv)]
(if (vector? x) (recur (next xv) (conj result (traverse-vector x (* bl length))))
(recur (next xv) (conj result (/ 1 length bl))))) result))))))
(defn sum-zero-durs [idxs input-vector full-durs]
(let [idxsv (vec idxs)]
(loop [xv idxsv
sum 0]
(if xv
(let [x (first xv)
zero-x (nth input-vector x )
dur-x (nth full-durs x)]
(if (= zero-x 0) (do (recur (next xv) (+ dur-x sum))) sum)) sum))))
(defn adjust-duration [input-vector input-original]
(let [length (count input-vector)
full-durs input-vector
input-vector (into [] (map * input-vector input-original))
idxs (vec (range length))]
(loop [xv idxs
result []]
(if xv
(let [xidx (first xv)
nidx (if (< (+ 1 xidx) length) (+ 1 xidx) (- length 1))
opnext (nth input-vector nidx)
op (nth input-vector xidx)
vec-ring (vec (subvec idxs nidx))
op (if (and (not= 0 op) ( = 0 opnext)) (+ op (sum-zero-durs vec-ring input-vector full-durs)) op)]
(recur (next xv) (conj result op))) result))))
(defn generate-durations [input input-val]
(let [mod-input (vec (map trigger-dur (vec (flatten input))))
durs (traverse-vector input)
durs (into [] (flatten durs))
mod-beat durs
durs (adjust-duration durs (vec (flatten mod-input)))]
{:dur durs :val (flatten input-val) :mod-input mod-beat }))
(defn split-to-sizes [input sizes]
(let [s input]
(apply concat (reduce
(fn [[s xs] len]
[(subvec s len)
(conj xs (subvec s 0 len))])
[s []]
sizes))))
(defn conditional-remove-zero [cond inputvec]
(let [size (count inputvec)
idxs (vec (range size))]
(loop [xv idxs
result []]
(if xv
(let [idx (first xv)
cond-i (nth cond idx )
value-i (nth inputvec idx)]
(if (= cond-i false) (do (recur (next xv) (conj result value-i))) (do (recur (next xv) result )))) result))))
(defn dur-and-val-zero [durs vals]
(map (fn [x y] (= x y 0)) durs vals))
(defn string-zero-to-one [str-in]
(clojure.string/replace str-in #"0" "1") )
(defn string-hyphen-to-zero [str-in]
(clojure.string/replace str-in #"~" "0") )
(defn fix-pattern-borders [input-vector]
(let [xvr (vec (range (count input-vector)))]
(loop [xv xvr
result input-vector]
(if xv
(let [x (first xv)
pattern-x (vec (nth result x ))
pattern-x-prev (vec (nth result (mod (- x 1) (count result))))
pattern-mod (assoc pattern-x 0 (last pattern-x-prev))]
(if true (do (recur (next xv) (assoc result x (seq pattern-mod)))) nil)) result))))
(defn generate-pattern-vector [new-buf-data]
(let [new-trig-data (vec (map (fn [x] (string-zero-to-one x)) new-buf-data))
new-trig-data (map clojure.edn/read-string (vec (map (fn [x] (string-hyphen-to-zero x)) new-trig-data)))
new-val-data (map clojure.edn/read-string (vec (map (fn [x] (string-hyphen-to-zero x)) new-buf-data)))
new-durs-and-vals (map generate-durations new-trig-data new-val-data)
durs (map :dur new-durs-and-vals)
vals (map :val new-durs-and-vals)
mod-beat (map :mod-input new-durs-and-vals)
base-sizes (map count new-trig-data)
base-durations (map (fn [x] (/ 1 x) ) base-sizes)
leading-zeros (map (fn [x] (count (filter #{0} (first (partition-by identity x))))) durs)
silent-trigger-durs (mapv (fn [x y] (into [] (subvec x 0 y))) mod-beat leading-zeros )
silent-trigger-durs (mapv (fn [x] (reduce + x)) silent-trigger-durs)
durs-and-vals-zero (mapv (fn [x y] (vec (dur-and-val-zero x y))) durs vals)
durs (mapv (fn [x y] (conditional-remove-zero x y)) durs-and-vals-zero durs)
vals (map (fn [x y] (conditional-remove-zero x y)) durs-and-vals-zero vals)
durs (mapv (fn [x y] (concat [x] y)) silent-trigger-durs durs)
vals (mapv (fn [x]
(let [cur-idx x
cur-vec (nth vals cur-idx)]
(concat [0] cur-vec))) (range (count vals)))
vals_range (range (count vals))
vals (fix-pattern-borders vals)
vals (fix-pattern-borders vals)]
{:dur durs :val vals}))
;pattern timing adjustments
(defn set-pattern-duration [dur]
(buffer-write! base-dur [dur])nil)
(defn set-pattern-delay [delay]
(buffer-write! base-del [delay]) nil)
;Synth trigger generation
(defprotocol synth-control
(kill-synth [this])
(kill-trg [this])
(ctl-synth [this var value])
(free-default-buses [this])
(free-out-bus [this])
(free-secondary-out-bus [this])
(apply-default-buses [this])
(apply-default-bus [this db])
(apply-control-out-bus [this])
(apply-out-bus [this])
(apply-secondary-out-bus [this])
(free-control-out-bus [this])
(set-out-channel [this channel]))
(defrecord synthContainer [pattern-name
group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
is-sub-synth
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
]
synth-control
(kill-synth [this] (kill (. this play-synth)))
(kill-trg [this] (group-free (. this group)))
(ctl-synth [this var value] (ctl (. this play-synth) var value))
(free-default-buses [this] ( doseq [x (vals default-buses)] (free-bus x)))
(free-out-bus [this] (free-bus (. this out-bus)))
(free-secondary-out-bus [this] (free-bus (. this out-bus-secondary)))
(apply-default-buses [this] (doseq [x default-buses] (ctl (. this play-synth) (key x) (val x))))
(apply-default-bus [this db] (ctl (. this play-synth) db (db default-buses)))
(apply-control-out-bus [this] (ctl (. this play-synth) :ctrl-out (. this control-out-bus)))
(apply-out-bus [this] (ctl (. this play-synth) :out-bus 0 ))
(apply-secondary-out-bus [this] (ctl (. this play-synth) :out-bus (. this out-bus-secondary)))
(free-control-out-bus [this] (free-bus (. this control-out-bus)))
(set-out-channel [this channel] (ctl (. this out-mixer ) :out-bus channel)))
(defprotocol trigger-control
(kill-trg-group [this])
(store-buffers [this])
(get-or-create-pattern-buf [this new-size])
(get-or-create-pattern-value-buf [this new-size])
(get-trigger-value-bus [this])
(get-pattern-vector [this])
(get-pattern-value-vector [this])
(pause-trigger [this])
(play-trigger [this]))
(defrecord triggerContainer [trigger-id
trigger-val-id
control-key
control-val-key
group
play-synth
trigger-bus
trigger-value-bus
trigger-synth
pattern-vector
pattern-value-vector
pattern-buf
pattern-value-buf
original-pattern-vector
original-pattern-value-vector]
trigger-control
(kill-trg-group [this] (do (group-free (. this group))
(free-bus trigger-bus)
(free-bus trigger-value-bus)
(doseq [x pattern-vector] (store-buffer x))
(doseq [x pattern-value-vector] (store-buffer x))
(store-buffer pattern-buf)
(store-buffer pattern-value-buf)))
(store-buffers [this] (doseq [x pattern-vector] (store-buffer x))
(doseq [x pattern-value-vector] (store-buffer x))
(store-buffer pattern-buf)
(store-buffer pattern-value-buf))
(get-or-create-pattern-buf [this new-size] (let [old-size (count (. this pattern-vector))]
(if (= old-size new-size)
(. this pattern-buf)
(do (store-buffer (. this pattern-buf))
(retrieve-buffer new-size)) )))
(get-or-create-pattern-value-buf [this new-size] (let [old-size (count (. this pattern-value-vector))]
(if (= old-size new-size)
(. this pattern-value-buf)
(do (store-buffer (. this pattern-value-buf )) (retrieve-buffer new-size)))))
(get-trigger-value-bus [this] (. this trigger-value-bus))
(get-pattern-vector [this] (. this pattern-vector))
(get-pattern-value-vector [this] (. this pattern-value-vector))
(pause-trigger [this] (node-pause (to-id (. this trigger-synth))))
(play-trigger [this] (node-start (to-id (. this trigger-synth)))))
(defn create-synth-config [pattern-name synth-name & {:keys [issub]
:or {issub false}}]
(let [out-bus (audio-bus 1)
out-bus-secondary (audio-bus 1)
synth-group (with-server-sync #(group pattern-name :tail main-g) "synth group")
sub-synth-group (with-server-sync #(group "sub-synth-group" :tail synth-group) "sub-synth group")
mixer-group (with-server-sync #(group "mixer-group" :tail synth-group) "mixer group")
play-synth (with-server-sync #(synth-name [:head synth-group] :out-bus out-bus) "synth creation")
;;trigger-vol-id (trig-id)
;;vol-sender (vol-send [:tail mixer-group] out-bus 0.017 trigger-vol-id)
out-mixer (mono-inst-mixer [:tail mixer-group] out-bus 0 1 0.0)
_ (println play-synth)
default-buses (generate-default-buses synth-name)
control-out-bus (control-bus 1)
triggers {}
sub-synths {}
synth-container (synthContainer.
pattern-name
synth-group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
issub
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
)]
(apply-default-buses synth-container)
(apply-control-out-bus synth-container)
synth-container))
(defn create-synth-config! [pattern-name sub-pattern-name synth-name & {:keys [issub]
:or {issub true}}]
(let [out-bus (:out-bus (@synthConfig pattern-name))
out-bus-secondary (:out-bus-secondary (@synthConfig pattern-name))
sub-synth-group (:sub-synth-group (@synthConfig pattern-name))
synth-group (:group (@synthConfig pattern-name))
mixer-group (:mixer-group (@synthConfig pattern-name))
play-synth (with-server-sync
#(synth-name [:tail sub-synth-group] :bus-in out-bus :out-bus out-bus)
(str "create synth config" sub-pattern-name))
out-mixer (:out-mixer (@synthConfig pattern-name))
;;trigger-vol-id (:trigger-vol-id (@synthConfig pattern-name))
;;vol-sender (:vol-sender (@synthConfig pattern-name))
_ (println play-synth)
default-buses (generate-default-buses synth-name)
control-out-bus (control-bus 1)
triggers {}
sub-synths {pattern-name (keyword sub-pattern-name)}
synth-container (synthContainer.
sub-pattern-name
sub-synth-group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
issub
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
)]
(apply-default-buses synth-container)
(apply-control-out-bus synth-container)
synth-container))
(defn buffer-writer [buf data]
;(println (buffer-id buf))
(with-server-sync #(buffer-write-relay! buf data) "Whlist buffer-writer")
;; (try
;; ;(buffer-write-relay! buf data)
;; (do
;; (println "Buffer write failed")
;; ;(store-buffer buf)
;; ))
)
(defn create-trigger [control-key
control-val-key
synth-name
pattern-group
pattern-vector
pattern-value-vector]
(let [trigger-id (with-server-sync #(trig-id) "create-trigger, trigger-id")
trigger-val-id (with-server-sync #(trig-id) "create-trigger, trigger-val-id")
trig-group (with-server-sync #(group (str control-key) :tail pattern-group) (str "trigger-group" control-key))
trig-bus (with-server-sync #(control-bus 1) "create-trigger, trig-bus")
trig-val-bus (with-server-sync #(control-bus 1) "create-trigger, trig-val-bus")
buf-size (count pattern-vector)
dur-buffers (vec (mapv (fn [x] (retrieve-buffer (count x))) pattern-vector))
val-buffers (vec (mapv (fn [x] (retrieve-buffer (count x))) pattern-value-vector))
_ (vec (mapv (fn [x y] (buffer-writer x y)) dur-buffers pattern-vector ))
_ (vec (mapv (fn [x y] (buffer-writer x y)) val-buffers pattern-value-vector))
pattern-id-buf (retrieve-buffer buf-size)
pattern-value-id-buf (retrieve-buffer buf-size)
dur-id-vec (vec (map (fn [x] (buffer-id x)) dur-buffers))
val-id-vec (vec (map (fn [x] (buffer-id x)) val-buffers))
_ (buffer-writer pattern-id-buf dur-id-vec)
_ (buffer-writer pattern-value-id-buf val-id-vec)
trig-synth (with-server-sync
#(trigger-generator [:tail trig-group]
base-trigger-bus
base-trigger-count-bus
pattern-id-buf
pattern-value-id-buf
trig-bus
trig-val-bus
trigger-id
trigger-val-id
base-dur)
(str "trigger" control-key))]
(try
(do (ctl synth-name control-key trig-bus control-val-key trig-val-bus))
(catch Exception ex
(println "CTL failed during create-trigger")))
(triggerContainer. trigger-id trigger-val-id control-key control-val-key trig-group synth-name trig-bus trig-val-bus trig-synth dur-buffers val-buffers pattern-id-buf pattern-value-id-buf pattern-vector pattern-value-vector)))
(defn reuse-or-create-buffer [new-buf-vec]
(let [new-size (count new-buf-vec)]
(retrieve-buffer new-size)))
;Buffer-write relays cause timeout expections occasionally
(defn update-trigger [trigger
pattern-vector
pattern-value-vector]
(let [trigger_old trigger
control-key (:control-key trigger)
buf-size (count pattern-vector)
old-dur-buffers (vec (:pattern-vector trigger))
old-val-buffers (vec (:pattern-value-vector trigger))
old-id-buffers (:pattern-buf trigger)
old-value-id-buffers (:pattern-value-buf trigger)
dur-buffers (vec (map (fn [x] (reuse-or-create-buffer x)) pattern-vector))
val-buffers (vec (map (fn [x] (reuse-or-create-buffer x)) pattern-value-vector))
_ (vec (mapv (fn [x y] (buffer-writer x y)) dur-buffers pattern-vector ))
_ (vec (mapv (fn [x y] (buffer-writer x y)) val-buffers pattern-value-vector))
pattern-id-buf (retrieve-buffer buf-size)
pattern-value-id-buf (retrieve-buffer buf-size)
_ (buffer-writer pattern-id-buf (vec (map (fn [x] (buffer-id x)) dur-buffers)))
_ (buffer-writer pattern-value-id-buf (vec (map (fn [x] (buffer-id x)) val-buffers)))
trigger (assoc trigger :pattern-vector dur-buffers)
trigger (assoc trigger :pattern-value-vector val-buffers)
trigger (assoc trigger :pattern-buf pattern-id-buf)
trigger (assoc trigger :pattern-value-buf pattern-value-id-buf)
trigger (assoc trigger :original-pattern-vector pattern-vector)
trigger (assoc trigger :original-pattern-value-vector pattern-value-vector)
trig-synth (:trigger-synth trigger)]
;(println old-dur-buffers)
;(println old-id-buffers)
;(println old-value-id-buffers)
(try
(do (ctl trig-synth
:base-pattern-buffer-in pattern-id-buf
:base-pattern-value-buffer-in pattern-value-id-buf)
(vec (map (fn [x] (store-buffer x)) old-dur-buffers))
(vec (map (fn [x] (store-buffer x)) old-val-buffers))
(vec (map (fn [x] (store-buffer x)) [old-id-buffers]))
(vec (map (fn [x] (store-buffer x)) [old-value-id-buffers]))
trigger)
(catch Exception ex
(do
(println "CTL failed during update-trigger" control-key)
(println (str (.getMessage ex)))
(.store-buffers trigger)
trigger_old)))))
(defn changed? [trigger new-trigger-pattern new-control-pattern]
(let [old-trigger-pattern (:original-pattern-vector trigger)
old-control-pattern (:original-pattern-value-vector trigger)]
;(println old-trigger-pattern)
(or (not= new-trigger-pattern old-trigger-pattern) (not= new-control-pattern old-control-pattern))))
(defn t [synth-container control-pair]
(let [control-key (first control-pair)
control-val-key (keyword (str (name control-key) "-val"))
control-pattern (last control-pair)
pattern-vectors (generate-pattern-vector control-pattern)
trig-pattern (:dur pattern-vectors)
val-pattern (:val pattern-vectors)
pattern-group (:group synth-container)
triggers (:triggers synth-container)
play-synth (:play-synth synth-container)
trigger-status (control-key triggers)
has-changed (if (some? trigger-status)
(changed? trigger-status trig-pattern val-pattern))
;_ (println control-key)
trigger (if (some? trigger-status)
(if (= true has-changed)
(update-trigger trigger-status trig-pattern val-pattern) trigger-status)
(create-trigger control-key
control-val-key
play-synth
pattern-group
trig-pattern
val-pattern))]
trigger))
(defonce r "~")
(defn parse-input-vector [input]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv) ]
(if (vector? fst) (recur (next xv) (conj result (vec (parse-input-vector fst))))
(if (seq? fst) (recur (next xv) (apply conj result (vec (parse-input-vector fst))))
(recur (next xv) (conj result fst))))) result ))))
(defn parse-input-vector-string [input idx]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv) ]
(if (vector? fst) (recur (next xv) (conj result (vec (parse-input-vector-string fst idx))))
(if (seq? fst) (recur (next xv) (apply conj result (vec (parse-input-vector-string fst idx))))
(recur (next xv) (conj result (clojure.string/trim (nth (clojure.string/split fst #",") idx))))))) result ))))
(defn string-not-r? [x]
(let [is-string (string? x)
is-r (if is-string (= r x) false)]
(if (and is-string (not is-r )) true false )))
(defn split-special-string [x d]
(clojure.string/trim (last (clojure.string/split x d 2))))
(defn match-special-case [x]
(let [is-input-string (string-not-r? x)
n-string "n"
freq-string "f"
buffer-string "b"
value-string "v"
]
(if is-input-string
(cond
;(re-matches #"n.*" x) (note (keyword (split-special-string x #"n")))
(re-matches #"n.*" x) (midi->hz (note (keyword (split-special-string x #"n"))))
(re-matches #"f.*" x) (midi->hz (note (keyword (split-special-string x #"f"))))
(re-matches #"b.*" x) (get-sample-id (keyword (split-special-string x #"b")))
(re-matches #"v.*" x) (Float/parseFloat (split-special-string x #"v")))
(cond
(= x nil) r
:else x))))
(defn special-case [input key]
(let [y input]
(match-special-case y)))
(defn apply-special-cases [input special-cond]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv)]
(if (vector? fst)
(recur (next xv) (conj result (vec (apply-special-cases fst special-cond))))
(recur (next xv) (conj result (special-case fst special-cond))))) result ))))
(defn copy-key-val [input key]
(let [value (key input)
value-size (count value)
is-string (if (= 1 value-size) (string? (first value)) false)
is-keyformat (if is-string (= 2 (count (clojure.string/split (first value) #":"))) false)
source-key (if is-keyformat (keyword (last (clojure.string/split (first value) #":"))) nil)
has-source (contains? input source-key)]
(if has-source (source-key input) (key input))))
(defn split-input [input]
(let [ip (into
(sorted-map)
(map (fn [x] {(first (first x)) (vec (parse-input-vector (last x)))})
(partition 2 (partition-by keyword? input))))
specip (into {} (map (fn [x] {x (copy-key-val ip x)}) (keys ip)))
ip specip
ip (into {} (map (fn [x] {x (apply-special-cases (x ip) x)}) (keys ip))) ]
(apply conj
(map (fn [x] {(key x) (vec (map (fn [x] (clojure.string/replace x #"\"~\"" "~") ) (map str (val x))))})
ip))))
(defn synth-name-check [new-sn synth-container]
(let [sc synth-container
old-sn (:synth-name synth-container)]
(if (nil? sc) new-sn
(if (not= old-sn new-sn) old-sn new-sn))))
;Alternative input system
(defn inp [keys & input]
(if true
(let [no_keys (count keys)
output (map (fn [x] (seq [(keyword (nth keys x)) (seq (parse-input-vector-string input x))])) (range no_keys) )]
(seq (parse-input-vector output)))
input))
(declare trg)
(defn make-helper-function [pattern-name synth-name & input]
(let [fname (symbol pattern-name)]
(if (nil? (resolve (symbol pattern-name)))
(do (intern (ns-name *ns*) fname (fn [& input] (trg (keyword pattern-name) synth-name input ))))
(do (println "Definition exists")))))
;New trigger input function, allows more terse and powerful way to create patterns. Now clojure functions such as repeat can be used directly in the input.
(defn trg ([pn sn & input]
(let [input (seq (parse-input-vector input))
pattern-name (if (keyword? pn) (name pn) pn )
pattern-name-key (keyword pattern-name)
synth-container (pattern-name-key @synthConfig)
synth-name (synth-name-check sn synth-container)
input (split-input input)
original-input input
valid-keys (concat <KEY> (vec (synth-args synth-name)))
input (select-keys input (vec valid-keys)) ; Make input valid, meaning remove control keys that are not present in the synth args
input-controls-only input
initial-controls-only input-controls-only
input-check (some? (not-empty input-controls-only))]
(if
(= nil synth-container)
(do (println "Synth created")
(swap! synthConfig assoc pattern-name-key (create-synth-config pattern-name synth-name)))
(do (println "Synth exists")))
(do
(let [synth-container (pattern-name-key @synthConfig)
triggers (:triggers synth-container)
running-trigger-keys(keys triggers)
input-trigger-keys (keys initial-controls-only)
synth-container (assoc synth-container :triggers triggers)]
(swap! synthConfig assoc pattern-name-key synth-container)))
(let [synth-container (pattern-name-key @synthConfig)
triggers (:triggers synth-container)
;_ (println input-controls-only)
;_ (println (filter #(not (.contains (flatten %) nil)) input-controls-only) )
updated-triggers (zipmap
(keys input-controls-only)
(map
(partial t (pattern-name-key @synthConfig)) input-controls-only))
merged-triggers (merge triggers updated-triggers)
]
(swap! synthConfig assoc pattern-name-key
(assoc (pattern-name-key @synthConfig)
:triggers
merged-triggers)))
(make-helper-function pattern-name synth-name input)
pattern-name)))
(defn trg! ([pn spn sn & input]
(let [pattern-name (if (keyword? pn) (name pn) pn )
pattern-name-key (keyword pattern-name)
sub-pattern-name (if (keyword? spn) (name spn) spn )
sub-pattern-name-key (keyword sub-pattern-name)
parent-synth-container (pattern-name-key @synthConfig)
parent-sub-synths (:sub-synths parent-synth-container)
synth-container (sub-pattern-name-key @synthConfig)
synth-name (synth-name-check sn synth-container)
input (split-input input)
original-input input
valid-keys (concat [:<KEY> :<KEY> :<KEY>] (vec (synth-args synth-name)))
input (select-keys input (vec valid-keys)) ; Make input valid, meaning remove control keys that are not present in the synth args
input-controls-only input
initial-controls-only input-controls-only
input-check (some? (not-empty input-controls-only))]
(if (not= nil parent-synth-container)
(do (if (= nil synth-container)
(do (println "Synth created")
(swap! synthConfig assoc pattern-name-key (assoc parent-synth-container :sub-synths (assoc parent-sub-synths sub-pattern-name-key pattern-name-key)))
(swap! synthConfig assoc sub-pattern-name-key (create-synth-config! pattern-name-key sub-pattern-name synth-name)) )
(do (println "Synth exists")))
(do
(let [synth-container (sub-pattern-name-key @synthConfig)
triggers (:triggers synth-container)
running-trigger-keys(keys triggers)
input-trigger-keys (keys initial-controls-only)
triggers-not-renewd (first (diff running-trigger-keys input-trigger-keys))
synth-container (assoc synth-container :triggers triggers)]
(swap! synthConfig assoc sub-pattern-name-key synth-container)))
(let [synth-container (sub-pattern-name-key @synthConfig)
triggers (:triggers synth-container)
updated-triggers (zipmap
(keys input-controls-only)
(map
(partial t (sub-pattern-name-key @synthConfig)) input-controls-only))
merged-triggers (merge triggers updated-triggers)
] (swap! synthConfig assoc sub-pattern-name-key
(assoc (sub-pattern-name-key @synthConfig)
:triggers
merged-triggers
)))) (println "Parent synth" pattern-name-key "does not exist.") )
(make-helper-function sub-pattern-name synth-name input)
sub-pattern-name)))
;;Functions to set patterns to multiple synths at once, for example to
;;play chords.
(defn | [& input]
(let [input (piv input)
lenip (count input)
ranip (mapv keyword (mapv str(vec (range lenip))))
ip (zipmap ranip input)]
;(println ip)
(fn [] ip)))
(defn condition-pattern [pattern key replace-with-r open-map]
(let [mod-pat1 (clojure.walk/prewalk
#(condp apply [%]
number? (if replace-with-r r %)
%)
pattern)
mod-pat2 (clojure.walk/prewalk
#(condp apply [%]
map? (if open-map (key %) %)
keyword? %
fn? (if (and (map? (%)) open-map)
(if (nil? (key (%))) r (key (%)) ) (%))
string? %
%)
mod-pat1)]
;(println "mod-pat2" mod-pat2)
mod-pat2))
;(trg :kick_1 (:synth-name (:kick_1 @synthConfig)) :in-f3 [100])
(defn gtc [synths & input]
(let [synths synths
last-synths (subvec synths 1)
lensynths (count synths)
ransynths (mapv keyword (mapv str (vec (range lensynths))))
synmap (zipmap synths (vec (range (count synths))))
patterns (condition-pattern input :0 false true)]
;(println synmap)
;(trg (first synths) (:synth-name ((first synths) @synthConfig)) (condition-pattern input (keyword (str ((first synths) synmap))) false true ))
(doseq [x synths] (trg x (:synth-name (:x @synthConfig)) (condition-pattern input (keyword (str (x synmap))) false true )) )
;(println patterns)
))
; Misc pattern related functions
(defn stop-pattern [pattern-name]
(let [pattern-name-key pattern-name ;(keyword pattern-name)
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
;_ (println pattern-name-key)
;_ (println issub)
;_ (println sub-synths)
;_ (println (into [] (filter #(do (= (first %) pattern-name-key) sub-synths))))
sub-synth-keys (keys sub-synths)
;_ (println sub-synth-keys)
sub-synth-vals (vals sub-synths)
triggers (vals (:triggers pattern-status))]
(if (some? pattern-status)
(do (if (not issub) (free-default-buses pattern-status))
(if (not issub) (free-control-out-bus pattern-status))
(if (not issub) (free-out-bus pattern-status))
(if (not issub) (free-secondary-out-bus pattern-status))
(doseq [x triggers] (kill-trg-group x))
(if (not issub)
(kill-trg pattern-status)
(kill-synth pattern-status) )
(if (not issub)
(reset! synthConfig (apply dissoc @synthConfig sub-synth-keys))
(do
(reset! synthConfig (apply dissoc @synthConfig sub-synth-vals))
(doseq [x sub-synth-keys] (reset! synthConfig (assoc @synthConfig x (assoc (x @synthConfig) :sub-synths (apply dissoc (:sub-synths (x @synthConfig)) sub-synth-vals))))))
)
(swap! synthConfig dissoc pattern-name-key) (println "pattern" (:pattern-name pattern-status) "stopped")) (println "No such pattern") )))
(defn stp [& pattern-names]
(doseq [x pattern-names]
(let [pattern-name-key x
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
sub-synth-keys (keys sub-synths)]
;(println sub-synth-keys)
;(println issub)
(doseq [y sub-synth-keys] (do (if (:is-sub-synth (y @synthConfig)) (stop-pattern y))))
(stop-pattern x)) ))
(defn sta []
(doseq [x (keys @synthConfig)]
(let [pattern-name-key x
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
sub-synth-keys (keys sub-synths)]
;(println sub-synth-keys)
;(println issub)
(doseq [y sub-synth-keys] (do (if (:is-sub-synth (y @synthConfig)) (stop-pattern y))))
(stop-pattern x)) (stop-pattern x)))
(defn set-out-bus [pattern-name]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (apply-out-bus pattern-status) )))
(defn set-secondary-out-bus [pattern-name]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (apply-secondary-out-bus pattern-status) )))
(defn set-mixer-out-channel [pattern-name channel]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (set-out-channel pattern-status channel) )) nil)
(defn get-out-bus [pattern-name]
(:out-bus (pattern-name @synthConfig)))
(defn get-secondary-out-bus [pattern-name]
(:out-bus-secondary (pattern-name @synthConfig)))
(defn get-ctrl-bus [pattern-name]
(:control-out-bus (pattern-name @synthConfig)))
(defn get-trigger-vol-id [pattern-name]
(:trigger-vol-id (pattern-name @synthConfig)))
(defn get-trigger-bus [pattern-name trig-name]
(:trigger-bus (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-val-bus [pattern-name trig-name]
(:trigger-val-bus (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-id [pattern-name trig-name]
(:trigger-id (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-val-id [pattern-name trig-name]
(:trigger-val-id (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-vector [pattern-name trig-name]
(get-pattern-vector (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-value-vector [pattern-name trig-name]
(get-pattern-value-vector (trig-name (:triggers (pattern-name @synthConfig)))))
(defn pat [pattern-name trig-name]
(pause-trigger (trig-name (:triggers (pattern-name @synthConfig)))))
(defn stt [pattern-name trig-name]
(play-trigger (trig-name (:triggers (pattern-name @synthConfig)))))
(defn list-sub-synths [pattern-name] (let [pattern (pattern-name @synthConfig)
issub (:is-sub-synth pattern)]
(if issub (println "Is a sub-synth, parent:" (keys (:sub-synths pattern)))
(println "Sub synths:" (keys (:sub-synths pattern)))))
nil)
;pattern-vector
;pattern-value-vector
;pattern-buf
;pattern-value-buf
;original-pattern-vector
;original-pattern-value-vector
(defn get-buffer-ids [pattern-name bt]
(let [pattern-status (pattern-name @synthConfig)
triggers (:triggers pattern-status)]
;(println (count triggers))
(vec (:pattern-vector (bt triggers)))
;(mapv (fn [x] (bt ((first x) triggers))) triggers)
)
)
(defn sctl [pattern-name var value]
(let [pattern-status (pattern-name @synthConfig)]
(if (some? pattern-status) (ctl-synth pattern-status var value))))
(defn connect-synths [src-synth dst-synth input-name]
(let [output-bus (get-secondary-out-bus src-synth)]
(sctl dst-synth input-name output-bus)
(set-secondary-out-bus src-synth)) )
(defn lss [] (println (keys @synthConfig)) (keys @synthConfig) )
;OSC
;(var addr=NetAddr.new("127.0.0.1", 3333); OSCdef ('/tidalplay2', { arg msg; addr.sendMsg("/play2", *msg);}, '/play2', n);)
;; (defn init-osc [port]
;; (def oscserver (osc-server port "osc-clj"))
;; (def client (osc-client "localhost" port))
;; (zero-conf-on)
;; (java.net.InetAddress/getLocalHost))
;; (defn osc-extract-tidal [msg key]
;; (let [submsg (into [] (subvec (vec (key msg)) 1))
;; part (mapv (fn [x] [(keyword (first x)) (last x)]) (partition 2 submsg))]
;; (into {} part)))
;Algorithm
(defn rm-alg [pattern trigger buf-id]
(let [trg_str (str (name trigger) "-" (str buf-id))
alg-key (keyword (name pattern) trg_str)
key-exist (some? (alg-key @algConfig))]
(if key-exist (do
(swap! algConfig dissoc alg-key)
(remove-event-handler alg-key) ))))
(defn alg [pattern trigger buf-id function & args]
(let [pat-vec (get-vector pattern trigger)
pat-val-vec (get-value-vector pattern trigger)
trigger-id (get-trigger-val-id pattern trigger)
vec-size (count pat-vec)
trg_str (str (name trigger) "-" (str buf-id))
alg-key (keyword (name pattern) trg_str)
key-exist (some? (alg-key @algConfig))]
(println alg-key)
(println (nth pat-vec 0))
(if key-exist
(do (println "Alg key exists for pattern" pattern ", trigger" trigger ", buffer" buf-id))
(do (function trigger-id alg-key pat-vec pat-val-vec buf-id algConfig args)
(swap! algConfig assoc alg-key alg-key )))))
;Mixer and Instrument effects functions
(defn volume! [pattern-name vol] (let [pat (pattern-name @synthConfig)]
(ctl (:out-mixer pat) :volume vol) )
nil)
(defn fade-out! [pattern-name & args]
(let [pat (pattern-name @synthConfig)
synth (:out-mixer pat)
s-id (to-id synth)
ivol (node-get-control s-id :volume)
isargs (not (empty? args))
;args (if isargs (first args) args)
args (into {} (mapv vec (vec (partition 2 args))))
time (if (and isargs (contains? args :t)) (:t args) 5000)
time (if (nil? time) 1000 time)
steps 100
step (/ ivol (+ 1 steps))
rang (range ivol 0 (* -1 step))
st (/ time (+ 1 (count rang)))]
;(println step)
;(println (count rang))
;(println st)
(async/go
(doseq [x rang]
(volume! pattern-name x)
;(println x)
(async/<! (async/timeout (* 1 st))))
(volume! pattern-name 0)
;(Thread/sleep (* st 1))
)))
(defn fade-in! [pattern-name & args]
(let [pat (pattern-name @synthConfig)
synth (:out-mixer pat)
s-id (to-id synth)
ivol (node-get-control s-id :volume)
isargs (not (empty? args))
;args (if isargs (first args) args)
args (into {} (mapv vec (vec (partition 2 args))))
time (if (and isargs (contains? args :t)) (:t args) 5000)
time (if (nil? time) 1000 time)
dvol (if (and isargs (contains? args :dvol)) (:dvol args) 1)
steps 100
step (/ (- dvol ivol) (+ 1 steps))
rang (range ivol dvol step)
st (/ time (+ 1 (count rang)))]
;(println time)
;(println st)
(async/go
(doseq [x rang]
(volume! pattern-name x)
(async/<! (async/timeout st))
;(Thread/sleep (* 1000 st))
)
(volume! pattern-name dvol))))
(defn pan! [pattern-name pan] (let [pat (pattern-name @synthConfig)]
(ctl (:out-mixer pat) :pan pan) ) nil )
(defn clrfx! [pattern-name] (let [pat (pattern-name @synthConfig)
inst (:synth-name pat) ]
(clear-fx inst))
nil)
(defn pause! [pattern-name] (let [pat (pattern-name @synthConfig)
synth (:play-synth pat)
;;vo (:vol-sender pat)
s-id (to-id synth)
;;vo-id (to-id vo)
]
(node-pause s-id)
;;(node-pause vo-id)
) nil)
(defn play! [pattern-name] (let [pat (pattern-name @synthConfig)
synth (:play-synth pat)
;;vo (:vol-sender pat)
s-id (to-id synth)
;;vo-id (to-id vo)
]
(node-start s-id)
;;(node-start vo-id)
) nil)
;Start trigger
(start-trigger)
| true | (ns #^{:author "PI:NAME:<NAME>END_PI"}
trigger.trigger
(:use [overtone.core]
[clojure.data])
(:require
[trigger.synths :refer :all]
[trigger.misc :refer :all]
[trigger.algo :refer :all]
[trigger.speech :refer :all]
[trigger.samples :refer :all]
[trigger.trg_fx :refer :all]
[clojure.core.async :as async]
[clojure.tools.namespace.repl :refer [refresh]]
[clj-native.structs :refer [byref]]
[overtone.sc.machinery.server.comms :refer [with-server-sync server-sync]]
[clojure.walk :only prewalk]
[overtone.sc.machinery.server.connection :refer [boot]]
[overtone.sc.machinery.server native])
(:import
(java.nio IntBuffer ByteBuffer FloatBuffer ByteOrder)))
;Boot Supercollider
(def port 57111)
(defn boot-ext [] (if (server-connected?) nil (boot-external-server port {:max-buffers 2621440 :max-control-bus 80960}) ))
;(boot-ext)
(defn boot-int [] (if (server-connected?) nil (boot :internal port {:max-buffers 2621440 :max-control-bus 80960}) ))
(boot-int)
;; (defn cb
;; "Get a an array of floats for the synthesis sound buffer with the given ID."
;; [sc buf-id]
;; (let [buf (byref overtone.sc.machinery.server.native/sound-buffer)
;; changed? (byref overtone.sc.machinery.server.native/bool-val)
;; ;; changed? (java.nio.ByteBuffer/allocate 1)
;; cc (ByteBuffer/allocate 1)
;; ]
;; ;(.samples buf)
;; (println buf)
;; (println (:value changed?))
;; ;(.getFloatArray (.data buf) 0 (.samples buf))
;; ( overtone.sc.machinery.server.native/world-copy-sound-buffer (:world sc) buf-id buf 0 cc)
;; ;(.getFloatArray (.data buf) 0 (.samples buf))
;; ))
;State atoms
(defonce synthConfig (atom {}))
(defonce algConfig (atom {}))
(defonce bufferPool (atom {}))
(defonce buffersInUse (atom {}))
(defonce timeatom (atom 0))
(defn init_groups_dur_and_del []
;Groups
(do
(defonce main-g (group "main group")))
;Base duration
(do
(def base-dur (buffer 1))
(buffer-write! base-dur [1]))
; Base trigger delay
(do
(def base-del (buffer 1))
(buffer-write! base-del [0])))
;Synthdefs
(defsynth base-trigger-synth [out-bus 0 trigger-id 0 base-dur-in 0 base-del-in 0]
(let [trg1 (t-duty:kr (dbufrd base-dur-in (dseries 0 1 INF)) 0 1)
trg (t-delay:kr trg1 (buf-rd:kr 1 base-del-in))]
(send-trig trg trigger-id trg)
(out:kr out-bus trg)))
(defsynth base-trigger-counter [base-trigger-bus-in 0 base-trigger-count-bus-out 0]
(out:kr base-trigger-count-bus-out (pulse-count:kr (in:kr base-trigger-bus-in))))
(def dbg (control-bus 1))
(def dbg2 (control-bus 1))
(defsynth vol-send [in-bus 0 base-dur 0.017 trigger-id 0]
(let [trg (t-duty:kr (dseq [base-dur] INF) )
inar (in:ar in-bus)
inkr (a2k inar)]
(send-trig trg trigger-id inkr)
(out 0 0)))
(defsynth trigger-generator [base-trigger-bus-in 0
base-counter-bus-in 0
base-pattern-buffer-in 0
base-pattern-value-buffer-in 0
trigger-bus-out 0
trigger-value-bus-out 0
trigger-id 0
trigger-val-id 0
base-dur-in 0]
(let [base-trigger (in:kr base-trigger-bus-in)
base-counter (in:kr base-counter-bus-in)
pattern-buffer-id (dbufrd base-pattern-buffer-in base-counter)
pattern-value-buffer-id (dbufrd base-pattern-value-buffer-in base-counter)
pattern-first-value (demand:kr base-trigger base-trigger (dbufrd pattern-buffer-id (dseries 0 1 1) 0) )
pattern-value-start-idx (select:kr
(= 0.0 pattern-first-value) [0 1])
;; Depending on if a spacer trigger exists or not in the first index of a buffer,
;;this value needs to be either 1 or 0 in order to play the buffer as intended.
trg (t-duty:kr
(* (dbufrd base-dur-in (dseries 0 1 INF) )
(dbufrd pattern-buffer-id (dseries 0 1 INF) 0))
base-trigger
(dbufrd pattern-buffer-id (dseries 0 1 INF) 0))
pattern-item-value (demand:kr trg base-trigger
(dbufrd pattern-value-buffer-id
(dseries pattern-value-start-idx 1 INF)))
pattern-trg-value (demand:kr trg base-trigger
(dbufrd pattern-buffer-id
(dseries pattern-value-start-idx 1 INF)))
cntr (pulse-count:kr trg base-trigger)
trg (select:kr (= 0 cntr) [trg 0]) ]
(send-trig trg trigger-id pattern-trg-value)
(send-trig trg trigger-val-id pattern-item-value)
(out:kr trigger-value-bus-out pattern-item-value)
(out:kr trigger-bus-out trg)))
;Buffer pool functions
(defn store-buffer [buf]
(let [size (buffer-size buf)
buf-id-key (keyword (str (buffer-id buf)))
size-key (keyword (PI:KEY:<KEY>END_PI))
pool @bufferPool
pool (update pool size-key (fnil concat []) [buf])]
(reset! bufferPool pool)
(reset! buffersInUse (dissoc @buffersInUse buf-id-key))))
(defn retrieve-buffer [size]
;(println size)
(let [size-key (keyword (str size))
pool @bufferPool
buffers-left (and (contains? pool size-key) (< 0 (count (size-key pool))))
first-buf (first (size-key pool))
rest-buf (rest (size-key pool))
pool (assoc pool size-key rest-buf )]
(if (and buffers-left true )
(do (let [first-buf-id-key (keyword (str (buffer-id first-buf)))]
(if (not (contains? @buffersInUse first-buf-id-key))
(do
;(println "use existing buffer")
(reset! bufferPool pool)
(reset! buffersInUse (assoc @buffersInUse first-buf-id-key first-buf))
first-buf)
(do
;(println "create new buffer")
(let [new-buf (with-server-sync #(buffer size) "Whilst retrieve-buffer")]
(reset! buffersInUse (assoc @buffersInUse
(keyword
(str (buffer-id new-buf))) new-buf))
new-buf))
))
first-buf)
(do (let [new-buf (with-server-sync #(buffer size) "Whilst retrieve-buffer")]
(reset! buffersInUse (assoc @buffersInUse
(keyword
(str (buffer-id new-buf))) new-buf))
new-buf)) )))
(defn generate-buffer-pool [sizes amount]
(let [size-vectors (vec (range 1 sizes))
size-keys (pmap (fn [x] (keyword (str x))) size-vectors)
buffers (doall (pmap (fn [y] (doall (map (fn [x] (with-server-sync #(buffer x) "Whilst generate-buffer-pool")) (repeat amount y)))) size-vectors))
b_p (zipmap size-keys buffers)]
(reset! bufferPool b_p)) nil)
;Start
(defn start-trigger []
(init_groups_dur_and_del)
(def base-trigger-id (trig-id))
(def base-trigger-bus (control-bus 1))
(def external-trigger-bus (control-bus 1))
(def base-trigger-dur-bus (control-bus 1))
(control-bus-set! base-trigger-dur-bus 1)
(buffer-write! base-dur [(/ 1 0.5625)])
(def base-trigger (base-trigger-synth [:tail main-g] base-trigger-bus base-trigger-id base-dur base-del))
(def base-trigger-count-bus (control-bus 1))
(def base-trigger-count (base-trigger-counter [:tail main-g] base-trigger-bus base-trigger-count-bus))
(println "Begin generating buffer pool, please wait.")
(generate-buffer-pool 128 256)
(println "trigger initialized")
(println (trigger-logo))
)
;Default value bus generation
(defn is-in-arg [arg-key arg-val]
(if (some? (re-find #"in-" (str arg-key))) {(keyword arg-key) arg-val} nil ))
(defn get-in-defaults [synth-name]
(let [arg-names (map :name (:params synth-name))
arg-keys (map :default (:params synth-name))
arg-val-keys (map (fn [x] (keyword (str (name x) "-val"))) arg-keys)
args-names-vals (map (fn [x y] (is-in-arg x y)) arg-names arg-keys)
args-names-vals (remove nil? args-names-vals)
args-names-vals (apply conj args-names-vals)]
args-names-vals) )
(defn generate-default-buses [synth-name]
(let [anv (get-in-defaults synth-name)
buses-def (vec (map (fn [x] (control-bus 1)) (vals anv)))
set-buses (vec (map (fn [x y] (control-bus-set! x y)) buses-def (vals anv )))
buses (vec (map (fn [x y] {x y}) (keys anv) buses-def))
buses (apply conj buses)]
buses))
(defn trigger-dur [dur]
(if (= dur 0) 0 1) )
;Pattern generation functions
(defn traverse-vector ([input-array]
(let [input-vec input-array
xvv (vec input-vec)
result []]
(if true
(loop [xv input-vec
result []]
(if xv
(let [ length (count input-vec)
x (first xv)]
(if (vector? x) (recur (next xv) (conj result (traverse-vector x length)))
(recur (next xv) (conj result (/ 1 length 1))))) result)))))
([input-array bl] (let [input-vec input-array
xvv (vec input-vec)]
(if (vector? input-vec)
(loop [xv input-vec
result []]
(if xv
(let [length (count input-vec)
x (first xv)]
(if (vector? x) (recur (next xv) (conj result (traverse-vector x (* bl length))))
(recur (next xv) (conj result (/ 1 length bl))))) result))))))
(defn sum-zero-durs [idxs input-vector full-durs]
(let [idxsv (vec idxs)]
(loop [xv idxsv
sum 0]
(if xv
(let [x (first xv)
zero-x (nth input-vector x )
dur-x (nth full-durs x)]
(if (= zero-x 0) (do (recur (next xv) (+ dur-x sum))) sum)) sum))))
(defn adjust-duration [input-vector input-original]
(let [length (count input-vector)
full-durs input-vector
input-vector (into [] (map * input-vector input-original))
idxs (vec (range length))]
(loop [xv idxs
result []]
(if xv
(let [xidx (first xv)
nidx (if (< (+ 1 xidx) length) (+ 1 xidx) (- length 1))
opnext (nth input-vector nidx)
op (nth input-vector xidx)
vec-ring (vec (subvec idxs nidx))
op (if (and (not= 0 op) ( = 0 opnext)) (+ op (sum-zero-durs vec-ring input-vector full-durs)) op)]
(recur (next xv) (conj result op))) result))))
(defn generate-durations [input input-val]
(let [mod-input (vec (map trigger-dur (vec (flatten input))))
durs (traverse-vector input)
durs (into [] (flatten durs))
mod-beat durs
durs (adjust-duration durs (vec (flatten mod-input)))]
{:dur durs :val (flatten input-val) :mod-input mod-beat }))
(defn split-to-sizes [input sizes]
(let [s input]
(apply concat (reduce
(fn [[s xs] len]
[(subvec s len)
(conj xs (subvec s 0 len))])
[s []]
sizes))))
(defn conditional-remove-zero [cond inputvec]
(let [size (count inputvec)
idxs (vec (range size))]
(loop [xv idxs
result []]
(if xv
(let [idx (first xv)
cond-i (nth cond idx )
value-i (nth inputvec idx)]
(if (= cond-i false) (do (recur (next xv) (conj result value-i))) (do (recur (next xv) result )))) result))))
(defn dur-and-val-zero [durs vals]
(map (fn [x y] (= x y 0)) durs vals))
(defn string-zero-to-one [str-in]
(clojure.string/replace str-in #"0" "1") )
(defn string-hyphen-to-zero [str-in]
(clojure.string/replace str-in #"~" "0") )
(defn fix-pattern-borders [input-vector]
(let [xvr (vec (range (count input-vector)))]
(loop [xv xvr
result input-vector]
(if xv
(let [x (first xv)
pattern-x (vec (nth result x ))
pattern-x-prev (vec (nth result (mod (- x 1) (count result))))
pattern-mod (assoc pattern-x 0 (last pattern-x-prev))]
(if true (do (recur (next xv) (assoc result x (seq pattern-mod)))) nil)) result))))
(defn generate-pattern-vector [new-buf-data]
(let [new-trig-data (vec (map (fn [x] (string-zero-to-one x)) new-buf-data))
new-trig-data (map clojure.edn/read-string (vec (map (fn [x] (string-hyphen-to-zero x)) new-trig-data)))
new-val-data (map clojure.edn/read-string (vec (map (fn [x] (string-hyphen-to-zero x)) new-buf-data)))
new-durs-and-vals (map generate-durations new-trig-data new-val-data)
durs (map :dur new-durs-and-vals)
vals (map :val new-durs-and-vals)
mod-beat (map :mod-input new-durs-and-vals)
base-sizes (map count new-trig-data)
base-durations (map (fn [x] (/ 1 x) ) base-sizes)
leading-zeros (map (fn [x] (count (filter #{0} (first (partition-by identity x))))) durs)
silent-trigger-durs (mapv (fn [x y] (into [] (subvec x 0 y))) mod-beat leading-zeros )
silent-trigger-durs (mapv (fn [x] (reduce + x)) silent-trigger-durs)
durs-and-vals-zero (mapv (fn [x y] (vec (dur-and-val-zero x y))) durs vals)
durs (mapv (fn [x y] (conditional-remove-zero x y)) durs-and-vals-zero durs)
vals (map (fn [x y] (conditional-remove-zero x y)) durs-and-vals-zero vals)
durs (mapv (fn [x y] (concat [x] y)) silent-trigger-durs durs)
vals (mapv (fn [x]
(let [cur-idx x
cur-vec (nth vals cur-idx)]
(concat [0] cur-vec))) (range (count vals)))
vals_range (range (count vals))
vals (fix-pattern-borders vals)
vals (fix-pattern-borders vals)]
{:dur durs :val vals}))
;pattern timing adjustments
(defn set-pattern-duration [dur]
(buffer-write! base-dur [dur])nil)
(defn set-pattern-delay [delay]
(buffer-write! base-del [delay]) nil)
;Synth trigger generation
(defprotocol synth-control
(kill-synth [this])
(kill-trg [this])
(ctl-synth [this var value])
(free-default-buses [this])
(free-out-bus [this])
(free-secondary-out-bus [this])
(apply-default-buses [this])
(apply-default-bus [this db])
(apply-control-out-bus [this])
(apply-out-bus [this])
(apply-secondary-out-bus [this])
(free-control-out-bus [this])
(set-out-channel [this channel]))
(defrecord synthContainer [pattern-name
group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
is-sub-synth
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
]
synth-control
(kill-synth [this] (kill (. this play-synth)))
(kill-trg [this] (group-free (. this group)))
(ctl-synth [this var value] (ctl (. this play-synth) var value))
(free-default-buses [this] ( doseq [x (vals default-buses)] (free-bus x)))
(free-out-bus [this] (free-bus (. this out-bus)))
(free-secondary-out-bus [this] (free-bus (. this out-bus-secondary)))
(apply-default-buses [this] (doseq [x default-buses] (ctl (. this play-synth) (key x) (val x))))
(apply-default-bus [this db] (ctl (. this play-synth) db (db default-buses)))
(apply-control-out-bus [this] (ctl (. this play-synth) :ctrl-out (. this control-out-bus)))
(apply-out-bus [this] (ctl (. this play-synth) :out-bus 0 ))
(apply-secondary-out-bus [this] (ctl (. this play-synth) :out-bus (. this out-bus-secondary)))
(free-control-out-bus [this] (free-bus (. this control-out-bus)))
(set-out-channel [this channel] (ctl (. this out-mixer ) :out-bus channel)))
(defprotocol trigger-control
(kill-trg-group [this])
(store-buffers [this])
(get-or-create-pattern-buf [this new-size])
(get-or-create-pattern-value-buf [this new-size])
(get-trigger-value-bus [this])
(get-pattern-vector [this])
(get-pattern-value-vector [this])
(pause-trigger [this])
(play-trigger [this]))
(defrecord triggerContainer [trigger-id
trigger-val-id
control-key
control-val-key
group
play-synth
trigger-bus
trigger-value-bus
trigger-synth
pattern-vector
pattern-value-vector
pattern-buf
pattern-value-buf
original-pattern-vector
original-pattern-value-vector]
trigger-control
(kill-trg-group [this] (do (group-free (. this group))
(free-bus trigger-bus)
(free-bus trigger-value-bus)
(doseq [x pattern-vector] (store-buffer x))
(doseq [x pattern-value-vector] (store-buffer x))
(store-buffer pattern-buf)
(store-buffer pattern-value-buf)))
(store-buffers [this] (doseq [x pattern-vector] (store-buffer x))
(doseq [x pattern-value-vector] (store-buffer x))
(store-buffer pattern-buf)
(store-buffer pattern-value-buf))
(get-or-create-pattern-buf [this new-size] (let [old-size (count (. this pattern-vector))]
(if (= old-size new-size)
(. this pattern-buf)
(do (store-buffer (. this pattern-buf))
(retrieve-buffer new-size)) )))
(get-or-create-pattern-value-buf [this new-size] (let [old-size (count (. this pattern-value-vector))]
(if (= old-size new-size)
(. this pattern-value-buf)
(do (store-buffer (. this pattern-value-buf )) (retrieve-buffer new-size)))))
(get-trigger-value-bus [this] (. this trigger-value-bus))
(get-pattern-vector [this] (. this pattern-vector))
(get-pattern-value-vector [this] (. this pattern-value-vector))
(pause-trigger [this] (node-pause (to-id (. this trigger-synth))))
(play-trigger [this] (node-start (to-id (. this trigger-synth)))))
(defn create-synth-config [pattern-name synth-name & {:keys [issub]
:or {issub false}}]
(let [out-bus (audio-bus 1)
out-bus-secondary (audio-bus 1)
synth-group (with-server-sync #(group pattern-name :tail main-g) "synth group")
sub-synth-group (with-server-sync #(group "sub-synth-group" :tail synth-group) "sub-synth group")
mixer-group (with-server-sync #(group "mixer-group" :tail synth-group) "mixer group")
play-synth (with-server-sync #(synth-name [:head synth-group] :out-bus out-bus) "synth creation")
;;trigger-vol-id (trig-id)
;;vol-sender (vol-send [:tail mixer-group] out-bus 0.017 trigger-vol-id)
out-mixer (mono-inst-mixer [:tail mixer-group] out-bus 0 1 0.0)
_ (println play-synth)
default-buses (generate-default-buses synth-name)
control-out-bus (control-bus 1)
triggers {}
sub-synths {}
synth-container (synthContainer.
pattern-name
synth-group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
issub
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
)]
(apply-default-buses synth-container)
(apply-control-out-bus synth-container)
synth-container))
(defn create-synth-config! [pattern-name sub-pattern-name synth-name & {:keys [issub]
:or {issub true}}]
(let [out-bus (:out-bus (@synthConfig pattern-name))
out-bus-secondary (:out-bus-secondary (@synthConfig pattern-name))
sub-synth-group (:sub-synth-group (@synthConfig pattern-name))
synth-group (:group (@synthConfig pattern-name))
mixer-group (:mixer-group (@synthConfig pattern-name))
play-synth (with-server-sync
#(synth-name [:tail sub-synth-group] :bus-in out-bus :out-bus out-bus)
(str "create synth config" sub-pattern-name))
out-mixer (:out-mixer (@synthConfig pattern-name))
;;trigger-vol-id (:trigger-vol-id (@synthConfig pattern-name))
;;vol-sender (:vol-sender (@synthConfig pattern-name))
_ (println play-synth)
default-buses (generate-default-buses synth-name)
control-out-bus (control-bus 1)
triggers {}
sub-synths {pattern-name (keyword sub-pattern-name)}
synth-container (synthContainer.
sub-pattern-name
sub-synth-group
out-bus
out-bus-secondary
play-synth
triggers
synth-name
default-buses
control-out-bus
out-mixer
mixer-group
issub
sub-synths
sub-synth-group
;;trigger-vol-id
;;vol-sender
)]
(apply-default-buses synth-container)
(apply-control-out-bus synth-container)
synth-container))
(defn buffer-writer [buf data]
;(println (buffer-id buf))
(with-server-sync #(buffer-write-relay! buf data) "Whlist buffer-writer")
;; (try
;; ;(buffer-write-relay! buf data)
;; (do
;; (println "Buffer write failed")
;; ;(store-buffer buf)
;; ))
)
(defn create-trigger [control-key
control-val-key
synth-name
pattern-group
pattern-vector
pattern-value-vector]
(let [trigger-id (with-server-sync #(trig-id) "create-trigger, trigger-id")
trigger-val-id (with-server-sync #(trig-id) "create-trigger, trigger-val-id")
trig-group (with-server-sync #(group (str control-key) :tail pattern-group) (str "trigger-group" control-key))
trig-bus (with-server-sync #(control-bus 1) "create-trigger, trig-bus")
trig-val-bus (with-server-sync #(control-bus 1) "create-trigger, trig-val-bus")
buf-size (count pattern-vector)
dur-buffers (vec (mapv (fn [x] (retrieve-buffer (count x))) pattern-vector))
val-buffers (vec (mapv (fn [x] (retrieve-buffer (count x))) pattern-value-vector))
_ (vec (mapv (fn [x y] (buffer-writer x y)) dur-buffers pattern-vector ))
_ (vec (mapv (fn [x y] (buffer-writer x y)) val-buffers pattern-value-vector))
pattern-id-buf (retrieve-buffer buf-size)
pattern-value-id-buf (retrieve-buffer buf-size)
dur-id-vec (vec (map (fn [x] (buffer-id x)) dur-buffers))
val-id-vec (vec (map (fn [x] (buffer-id x)) val-buffers))
_ (buffer-writer pattern-id-buf dur-id-vec)
_ (buffer-writer pattern-value-id-buf val-id-vec)
trig-synth (with-server-sync
#(trigger-generator [:tail trig-group]
base-trigger-bus
base-trigger-count-bus
pattern-id-buf
pattern-value-id-buf
trig-bus
trig-val-bus
trigger-id
trigger-val-id
base-dur)
(str "trigger" control-key))]
(try
(do (ctl synth-name control-key trig-bus control-val-key trig-val-bus))
(catch Exception ex
(println "CTL failed during create-trigger")))
(triggerContainer. trigger-id trigger-val-id control-key control-val-key trig-group synth-name trig-bus trig-val-bus trig-synth dur-buffers val-buffers pattern-id-buf pattern-value-id-buf pattern-vector pattern-value-vector)))
(defn reuse-or-create-buffer [new-buf-vec]
(let [new-size (count new-buf-vec)]
(retrieve-buffer new-size)))
;Buffer-write relays cause timeout expections occasionally
(defn update-trigger [trigger
pattern-vector
pattern-value-vector]
(let [trigger_old trigger
control-key (:control-key trigger)
buf-size (count pattern-vector)
old-dur-buffers (vec (:pattern-vector trigger))
old-val-buffers (vec (:pattern-value-vector trigger))
old-id-buffers (:pattern-buf trigger)
old-value-id-buffers (:pattern-value-buf trigger)
dur-buffers (vec (map (fn [x] (reuse-or-create-buffer x)) pattern-vector))
val-buffers (vec (map (fn [x] (reuse-or-create-buffer x)) pattern-value-vector))
_ (vec (mapv (fn [x y] (buffer-writer x y)) dur-buffers pattern-vector ))
_ (vec (mapv (fn [x y] (buffer-writer x y)) val-buffers pattern-value-vector))
pattern-id-buf (retrieve-buffer buf-size)
pattern-value-id-buf (retrieve-buffer buf-size)
_ (buffer-writer pattern-id-buf (vec (map (fn [x] (buffer-id x)) dur-buffers)))
_ (buffer-writer pattern-value-id-buf (vec (map (fn [x] (buffer-id x)) val-buffers)))
trigger (assoc trigger :pattern-vector dur-buffers)
trigger (assoc trigger :pattern-value-vector val-buffers)
trigger (assoc trigger :pattern-buf pattern-id-buf)
trigger (assoc trigger :pattern-value-buf pattern-value-id-buf)
trigger (assoc trigger :original-pattern-vector pattern-vector)
trigger (assoc trigger :original-pattern-value-vector pattern-value-vector)
trig-synth (:trigger-synth trigger)]
;(println old-dur-buffers)
;(println old-id-buffers)
;(println old-value-id-buffers)
(try
(do (ctl trig-synth
:base-pattern-buffer-in pattern-id-buf
:base-pattern-value-buffer-in pattern-value-id-buf)
(vec (map (fn [x] (store-buffer x)) old-dur-buffers))
(vec (map (fn [x] (store-buffer x)) old-val-buffers))
(vec (map (fn [x] (store-buffer x)) [old-id-buffers]))
(vec (map (fn [x] (store-buffer x)) [old-value-id-buffers]))
trigger)
(catch Exception ex
(do
(println "CTL failed during update-trigger" control-key)
(println (str (.getMessage ex)))
(.store-buffers trigger)
trigger_old)))))
(defn changed? [trigger new-trigger-pattern new-control-pattern]
(let [old-trigger-pattern (:original-pattern-vector trigger)
old-control-pattern (:original-pattern-value-vector trigger)]
;(println old-trigger-pattern)
(or (not= new-trigger-pattern old-trigger-pattern) (not= new-control-pattern old-control-pattern))))
(defn t [synth-container control-pair]
(let [control-key (first control-pair)
control-val-key (keyword (str (name control-key) "-val"))
control-pattern (last control-pair)
pattern-vectors (generate-pattern-vector control-pattern)
trig-pattern (:dur pattern-vectors)
val-pattern (:val pattern-vectors)
pattern-group (:group synth-container)
triggers (:triggers synth-container)
play-synth (:play-synth synth-container)
trigger-status (control-key triggers)
has-changed (if (some? trigger-status)
(changed? trigger-status trig-pattern val-pattern))
;_ (println control-key)
trigger (if (some? trigger-status)
(if (= true has-changed)
(update-trigger trigger-status trig-pattern val-pattern) trigger-status)
(create-trigger control-key
control-val-key
play-synth
pattern-group
trig-pattern
val-pattern))]
trigger))
(defonce r "~")
(defn parse-input-vector [input]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv) ]
(if (vector? fst) (recur (next xv) (conj result (vec (parse-input-vector fst))))
(if (seq? fst) (recur (next xv) (apply conj result (vec (parse-input-vector fst))))
(recur (next xv) (conj result fst))))) result ))))
(defn parse-input-vector-string [input idx]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv) ]
(if (vector? fst) (recur (next xv) (conj result (vec (parse-input-vector-string fst idx))))
(if (seq? fst) (recur (next xv) (apply conj result (vec (parse-input-vector-string fst idx))))
(recur (next xv) (conj result (clojure.string/trim (nth (clojure.string/split fst #",") idx))))))) result ))))
(defn string-not-r? [x]
(let [is-string (string? x)
is-r (if is-string (= r x) false)]
(if (and is-string (not is-r )) true false )))
(defn split-special-string [x d]
(clojure.string/trim (last (clojure.string/split x d 2))))
(defn match-special-case [x]
(let [is-input-string (string-not-r? x)
n-string "n"
freq-string "f"
buffer-string "b"
value-string "v"
]
(if is-input-string
(cond
;(re-matches #"n.*" x) (note (keyword (split-special-string x #"n")))
(re-matches #"n.*" x) (midi->hz (note (keyword (split-special-string x #"n"))))
(re-matches #"f.*" x) (midi->hz (note (keyword (split-special-string x #"f"))))
(re-matches #"b.*" x) (get-sample-id (keyword (split-special-string x #"b")))
(re-matches #"v.*" x) (Float/parseFloat (split-special-string x #"v")))
(cond
(= x nil) r
:else x))))
(defn special-case [input key]
(let [y input]
(match-special-case y)))
(defn apply-special-cases [input special-cond]
(let []
(loop [xv input
result []]
(if xv
(let [fst (first xv)]
(if (vector? fst)
(recur (next xv) (conj result (vec (apply-special-cases fst special-cond))))
(recur (next xv) (conj result (special-case fst special-cond))))) result ))))
(defn copy-key-val [input key]
(let [value (key input)
value-size (count value)
is-string (if (= 1 value-size) (string? (first value)) false)
is-keyformat (if is-string (= 2 (count (clojure.string/split (first value) #":"))) false)
source-key (if is-keyformat (keyword (last (clojure.string/split (first value) #":"))) nil)
has-source (contains? input source-key)]
(if has-source (source-key input) (key input))))
(defn split-input [input]
(let [ip (into
(sorted-map)
(map (fn [x] {(first (first x)) (vec (parse-input-vector (last x)))})
(partition 2 (partition-by keyword? input))))
specip (into {} (map (fn [x] {x (copy-key-val ip x)}) (keys ip)))
ip specip
ip (into {} (map (fn [x] {x (apply-special-cases (x ip) x)}) (keys ip))) ]
(apply conj
(map (fn [x] {(key x) (vec (map (fn [x] (clojure.string/replace x #"\"~\"" "~") ) (map str (val x))))})
ip))))
(defn synth-name-check [new-sn synth-container]
(let [sc synth-container
old-sn (:synth-name synth-container)]
(if (nil? sc) new-sn
(if (not= old-sn new-sn) old-sn new-sn))))
;Alternative input system
(defn inp [keys & input]
(if true
(let [no_keys (count keys)
output (map (fn [x] (seq [(keyword (nth keys x)) (seq (parse-input-vector-string input x))])) (range no_keys) )]
(seq (parse-input-vector output)))
input))
(declare trg)
(defn make-helper-function [pattern-name synth-name & input]
(let [fname (symbol pattern-name)]
(if (nil? (resolve (symbol pattern-name)))
(do (intern (ns-name *ns*) fname (fn [& input] (trg (keyword pattern-name) synth-name input ))))
(do (println "Definition exists")))))
;New trigger input function, allows more terse and powerful way to create patterns. Now clojure functions such as repeat can be used directly in the input.
(defn trg ([pn sn & input]
(let [input (seq (parse-input-vector input))
pattern-name (if (keyword? pn) (name pn) pn )
pattern-name-key (keyword pattern-name)
synth-container (pattern-name-key @synthConfig)
synth-name (synth-name-check sn synth-container)
input (split-input input)
original-input input
valid-keys (concat PI:KEY:<KEY>END_PI (vec (synth-args synth-name)))
input (select-keys input (vec valid-keys)) ; Make input valid, meaning remove control keys that are not present in the synth args
input-controls-only input
initial-controls-only input-controls-only
input-check (some? (not-empty input-controls-only))]
(if
(= nil synth-container)
(do (println "Synth created")
(swap! synthConfig assoc pattern-name-key (create-synth-config pattern-name synth-name)))
(do (println "Synth exists")))
(do
(let [synth-container (pattern-name-key @synthConfig)
triggers (:triggers synth-container)
running-trigger-keys(keys triggers)
input-trigger-keys (keys initial-controls-only)
synth-container (assoc synth-container :triggers triggers)]
(swap! synthConfig assoc pattern-name-key synth-container)))
(let [synth-container (pattern-name-key @synthConfig)
triggers (:triggers synth-container)
;_ (println input-controls-only)
;_ (println (filter #(not (.contains (flatten %) nil)) input-controls-only) )
updated-triggers (zipmap
(keys input-controls-only)
(map
(partial t (pattern-name-key @synthConfig)) input-controls-only))
merged-triggers (merge triggers updated-triggers)
]
(swap! synthConfig assoc pattern-name-key
(assoc (pattern-name-key @synthConfig)
:triggers
merged-triggers)))
(make-helper-function pattern-name synth-name input)
pattern-name)))
(defn trg! ([pn spn sn & input]
(let [pattern-name (if (keyword? pn) (name pn) pn )
pattern-name-key (keyword pattern-name)
sub-pattern-name (if (keyword? spn) (name spn) spn )
sub-pattern-name-key (keyword sub-pattern-name)
parent-synth-container (pattern-name-key @synthConfig)
parent-sub-synths (:sub-synths parent-synth-container)
synth-container (sub-pattern-name-key @synthConfig)
synth-name (synth-name-check sn synth-container)
input (split-input input)
original-input input
valid-keys (concat [:PI:KEY:<KEY>END_PI :PI:KEY:<KEY>END_PI :PI:KEY:<KEY>END_PI] (vec (synth-args synth-name)))
input (select-keys input (vec valid-keys)) ; Make input valid, meaning remove control keys that are not present in the synth args
input-controls-only input
initial-controls-only input-controls-only
input-check (some? (not-empty input-controls-only))]
(if (not= nil parent-synth-container)
(do (if (= nil synth-container)
(do (println "Synth created")
(swap! synthConfig assoc pattern-name-key (assoc parent-synth-container :sub-synths (assoc parent-sub-synths sub-pattern-name-key pattern-name-key)))
(swap! synthConfig assoc sub-pattern-name-key (create-synth-config! pattern-name-key sub-pattern-name synth-name)) )
(do (println "Synth exists")))
(do
(let [synth-container (sub-pattern-name-key @synthConfig)
triggers (:triggers synth-container)
running-trigger-keys(keys triggers)
input-trigger-keys (keys initial-controls-only)
triggers-not-renewd (first (diff running-trigger-keys input-trigger-keys))
synth-container (assoc synth-container :triggers triggers)]
(swap! synthConfig assoc sub-pattern-name-key synth-container)))
(let [synth-container (sub-pattern-name-key @synthConfig)
triggers (:triggers synth-container)
updated-triggers (zipmap
(keys input-controls-only)
(map
(partial t (sub-pattern-name-key @synthConfig)) input-controls-only))
merged-triggers (merge triggers updated-triggers)
] (swap! synthConfig assoc sub-pattern-name-key
(assoc (sub-pattern-name-key @synthConfig)
:triggers
merged-triggers
)))) (println "Parent synth" pattern-name-key "does not exist.") )
(make-helper-function sub-pattern-name synth-name input)
sub-pattern-name)))
;;Functions to set patterns to multiple synths at once, for example to
;;play chords.
(defn | [& input]
(let [input (piv input)
lenip (count input)
ranip (mapv keyword (mapv str(vec (range lenip))))
ip (zipmap ranip input)]
;(println ip)
(fn [] ip)))
(defn condition-pattern [pattern key replace-with-r open-map]
(let [mod-pat1 (clojure.walk/prewalk
#(condp apply [%]
number? (if replace-with-r r %)
%)
pattern)
mod-pat2 (clojure.walk/prewalk
#(condp apply [%]
map? (if open-map (key %) %)
keyword? %
fn? (if (and (map? (%)) open-map)
(if (nil? (key (%))) r (key (%)) ) (%))
string? %
%)
mod-pat1)]
;(println "mod-pat2" mod-pat2)
mod-pat2))
;(trg :kick_1 (:synth-name (:kick_1 @synthConfig)) :in-f3 [100])
(defn gtc [synths & input]
(let [synths synths
last-synths (subvec synths 1)
lensynths (count synths)
ransynths (mapv keyword (mapv str (vec (range lensynths))))
synmap (zipmap synths (vec (range (count synths))))
patterns (condition-pattern input :0 false true)]
;(println synmap)
;(trg (first synths) (:synth-name ((first synths) @synthConfig)) (condition-pattern input (keyword (str ((first synths) synmap))) false true ))
(doseq [x synths] (trg x (:synth-name (:x @synthConfig)) (condition-pattern input (keyword (str (x synmap))) false true )) )
;(println patterns)
))
; Misc pattern related functions
(defn stop-pattern [pattern-name]
(let [pattern-name-key pattern-name ;(keyword pattern-name)
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
;_ (println pattern-name-key)
;_ (println issub)
;_ (println sub-synths)
;_ (println (into [] (filter #(do (= (first %) pattern-name-key) sub-synths))))
sub-synth-keys (keys sub-synths)
;_ (println sub-synth-keys)
sub-synth-vals (vals sub-synths)
triggers (vals (:triggers pattern-status))]
(if (some? pattern-status)
(do (if (not issub) (free-default-buses pattern-status))
(if (not issub) (free-control-out-bus pattern-status))
(if (not issub) (free-out-bus pattern-status))
(if (not issub) (free-secondary-out-bus pattern-status))
(doseq [x triggers] (kill-trg-group x))
(if (not issub)
(kill-trg pattern-status)
(kill-synth pattern-status) )
(if (not issub)
(reset! synthConfig (apply dissoc @synthConfig sub-synth-keys))
(do
(reset! synthConfig (apply dissoc @synthConfig sub-synth-vals))
(doseq [x sub-synth-keys] (reset! synthConfig (assoc @synthConfig x (assoc (x @synthConfig) :sub-synths (apply dissoc (:sub-synths (x @synthConfig)) sub-synth-vals))))))
)
(swap! synthConfig dissoc pattern-name-key) (println "pattern" (:pattern-name pattern-status) "stopped")) (println "No such pattern") )))
(defn stp [& pattern-names]
(doseq [x pattern-names]
(let [pattern-name-key x
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
sub-synth-keys (keys sub-synths)]
;(println sub-synth-keys)
;(println issub)
(doseq [y sub-synth-keys] (do (if (:is-sub-synth (y @synthConfig)) (stop-pattern y))))
(stop-pattern x)) ))
(defn sta []
(doseq [x (keys @synthConfig)]
(let [pattern-name-key x
pattern-status (pattern-name-key @synthConfig)
issub (:is-sub-synth pattern-status)
sub-synths (:sub-synths pattern-status)
sub-synth-keys (keys sub-synths)]
;(println sub-synth-keys)
;(println issub)
(doseq [y sub-synth-keys] (do (if (:is-sub-synth (y @synthConfig)) (stop-pattern y))))
(stop-pattern x)) (stop-pattern x)))
(defn set-out-bus [pattern-name]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (apply-out-bus pattern-status) )))
(defn set-secondary-out-bus [pattern-name]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (apply-secondary-out-bus pattern-status) )))
(defn set-mixer-out-channel [pattern-name channel]
(let [pattern-name-key pattern-name
pattern-status (pattern-name-key @synthConfig)]
(if (some? pattern-status) (set-out-channel pattern-status channel) )) nil)
(defn get-out-bus [pattern-name]
(:out-bus (pattern-name @synthConfig)))
(defn get-secondary-out-bus [pattern-name]
(:out-bus-secondary (pattern-name @synthConfig)))
(defn get-ctrl-bus [pattern-name]
(:control-out-bus (pattern-name @synthConfig)))
(defn get-trigger-vol-id [pattern-name]
(:trigger-vol-id (pattern-name @synthConfig)))
(defn get-trigger-bus [pattern-name trig-name]
(:trigger-bus (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-val-bus [pattern-name trig-name]
(:trigger-val-bus (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-id [pattern-name trig-name]
(:trigger-id (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-trigger-val-id [pattern-name trig-name]
(:trigger-val-id (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-vector [pattern-name trig-name]
(get-pattern-vector (trig-name (:triggers (pattern-name @synthConfig)))))
(defn get-value-vector [pattern-name trig-name]
(get-pattern-value-vector (trig-name (:triggers (pattern-name @synthConfig)))))
(defn pat [pattern-name trig-name]
(pause-trigger (trig-name (:triggers (pattern-name @synthConfig)))))
(defn stt [pattern-name trig-name]
(play-trigger (trig-name (:triggers (pattern-name @synthConfig)))))
(defn list-sub-synths [pattern-name] (let [pattern (pattern-name @synthConfig)
issub (:is-sub-synth pattern)]
(if issub (println "Is a sub-synth, parent:" (keys (:sub-synths pattern)))
(println "Sub synths:" (keys (:sub-synths pattern)))))
nil)
;pattern-vector
;pattern-value-vector
;pattern-buf
;pattern-value-buf
;original-pattern-vector
;original-pattern-value-vector
(defn get-buffer-ids [pattern-name bt]
(let [pattern-status (pattern-name @synthConfig)
triggers (:triggers pattern-status)]
;(println (count triggers))
(vec (:pattern-vector (bt triggers)))
;(mapv (fn [x] (bt ((first x) triggers))) triggers)
)
)
(defn sctl [pattern-name var value]
(let [pattern-status (pattern-name @synthConfig)]
(if (some? pattern-status) (ctl-synth pattern-status var value))))
(defn connect-synths [src-synth dst-synth input-name]
(let [output-bus (get-secondary-out-bus src-synth)]
(sctl dst-synth input-name output-bus)
(set-secondary-out-bus src-synth)) )
(defn lss [] (println (keys @synthConfig)) (keys @synthConfig) )
;OSC
;(var addr=NetAddr.new("127.0.0.1", 3333); OSCdef ('/tidalplay2', { arg msg; addr.sendMsg("/play2", *msg);}, '/play2', n);)
;; (defn init-osc [port]
;; (def oscserver (osc-server port "osc-clj"))
;; (def client (osc-client "localhost" port))
;; (zero-conf-on)
;; (java.net.InetAddress/getLocalHost))
;; (defn osc-extract-tidal [msg key]
;; (let [submsg (into [] (subvec (vec (key msg)) 1))
;; part (mapv (fn [x] [(keyword (first x)) (last x)]) (partition 2 submsg))]
;; (into {} part)))
;Algorithm
(defn rm-alg [pattern trigger buf-id]
(let [trg_str (str (name trigger) "-" (str buf-id))
alg-key (keyword (name pattern) trg_str)
key-exist (some? (alg-key @algConfig))]
(if key-exist (do
(swap! algConfig dissoc alg-key)
(remove-event-handler alg-key) ))))
(defn alg [pattern trigger buf-id function & args]
(let [pat-vec (get-vector pattern trigger)
pat-val-vec (get-value-vector pattern trigger)
trigger-id (get-trigger-val-id pattern trigger)
vec-size (count pat-vec)
trg_str (str (name trigger) "-" (str buf-id))
alg-key (keyword (name pattern) trg_str)
key-exist (some? (alg-key @algConfig))]
(println alg-key)
(println (nth pat-vec 0))
(if key-exist
(do (println "Alg key exists for pattern" pattern ", trigger" trigger ", buffer" buf-id))
(do (function trigger-id alg-key pat-vec pat-val-vec buf-id algConfig args)
(swap! algConfig assoc alg-key alg-key )))))
;Mixer and Instrument effects functions
(defn volume! [pattern-name vol] (let [pat (pattern-name @synthConfig)]
(ctl (:out-mixer pat) :volume vol) )
nil)
(defn fade-out! [pattern-name & args]
(let [pat (pattern-name @synthConfig)
synth (:out-mixer pat)
s-id (to-id synth)
ivol (node-get-control s-id :volume)
isargs (not (empty? args))
;args (if isargs (first args) args)
args (into {} (mapv vec (vec (partition 2 args))))
time (if (and isargs (contains? args :t)) (:t args) 5000)
time (if (nil? time) 1000 time)
steps 100
step (/ ivol (+ 1 steps))
rang (range ivol 0 (* -1 step))
st (/ time (+ 1 (count rang)))]
;(println step)
;(println (count rang))
;(println st)
(async/go
(doseq [x rang]
(volume! pattern-name x)
;(println x)
(async/<! (async/timeout (* 1 st))))
(volume! pattern-name 0)
;(Thread/sleep (* st 1))
)))
(defn fade-in! [pattern-name & args]
(let [pat (pattern-name @synthConfig)
synth (:out-mixer pat)
s-id (to-id synth)
ivol (node-get-control s-id :volume)
isargs (not (empty? args))
;args (if isargs (first args) args)
args (into {} (mapv vec (vec (partition 2 args))))
time (if (and isargs (contains? args :t)) (:t args) 5000)
time (if (nil? time) 1000 time)
dvol (if (and isargs (contains? args :dvol)) (:dvol args) 1)
steps 100
step (/ (- dvol ivol) (+ 1 steps))
rang (range ivol dvol step)
st (/ time (+ 1 (count rang)))]
;(println time)
;(println st)
(async/go
(doseq [x rang]
(volume! pattern-name x)
(async/<! (async/timeout st))
;(Thread/sleep (* 1000 st))
)
(volume! pattern-name dvol))))
(defn pan! [pattern-name pan] (let [pat (pattern-name @synthConfig)]
(ctl (:out-mixer pat) :pan pan) ) nil )
(defn clrfx! [pattern-name] (let [pat (pattern-name @synthConfig)
inst (:synth-name pat) ]
(clear-fx inst))
nil)
(defn pause! [pattern-name] (let [pat (pattern-name @synthConfig)
synth (:play-synth pat)
;;vo (:vol-sender pat)
s-id (to-id synth)
;;vo-id (to-id vo)
]
(node-pause s-id)
;;(node-pause vo-id)
) nil)
(defn play! [pattern-name] (let [pat (pattern-name @synthConfig)
synth (:play-synth pat)
;;vo (:vol-sender pat)
s-id (to-id synth)
;;vo-id (to-id vo)
]
(node-start s-id)
;;(node-start vo-id)
) nil)
;Start trigger
(start-trigger)
|
[
{
"context": "ption tags\n vpn-common-name vpn-certificate\n vpn-intermediate",
"end": 8488,
"score": 0.653626561164856,
"start": 8485,
"tag": "KEY",
"value": "pn-"
}
] | code/test/sixsq/nuvla/server/resources/credential/vpn_utils_test.clj | nuvla/server | 6 | (ns sixsq.nuvla.server.resources.credential.vpn-utils-test
(:require
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer [is]]
[peridot.core :refer [content-type header request session]]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.configuration :as configuration]
[sixsq.nuvla.server.resources.configuration-template :as configuration-tpl]
[sixsq.nuvla.server.resources.configuration-template-vpn-api :as configuration-tpl-vpn]
[sixsq.nuvla.server.resources.credential :as credential]
[sixsq.nuvla.server.resources.credential-template :as ct]
[sixsq.nuvla.server.resources.credential.vpn-utils :as vpn-utils]
[sixsq.nuvla.server.resources.infrastructure-service :as infra-service]
[sixsq.nuvla.server.resources.infrastructure-service-template :as infra-service-tpl]
[sixsq.nuvla.server.resources.infrastructure-service-template-vpn
:as infra-srvc-tpl-vpn]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]))
(def base-uri (str p/service-context credential/resource-type))
(defn credential-vpn-lifecycle-test
[method vpn-scope user-id claims method-not-corresponding-to-scope]
(let [session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-test (header session authn-info-header claims)
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]
common-name-value user-id
certificate-value "my-public-certificate"
inter-ca-values ["certif-1"]
private-key-value "private key visible only once at creation time"
infra-service-create {:template {:href (str infra-service-tpl/resource-type "/"
infra-srvc-tpl-vpn/method)
:vpn-scope vpn-scope
:acl {:owners ["nuvla/admin"]
:view-acl ["nuvla/user"
"nuvla/nuvlabox"]}}}
infra-service-id (-> session-admin
(request (str p/service-context infra-service/resource-type)
:request-method :post
:body (json/write-str infra-service-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
configuration-create {:template
{:href (str configuration-tpl/resource-type "/"
configuration-tpl-vpn/service)
:instance "vpn"
:endpoint "http://vpn.test"
:infrastructure-services [infra-service-id]}}
href (str ct/resource-type "/" method)
bad-href (str ct/resource-type "/" method-not-corresponding-to-scope)
template-url (str p/service-context ct/resource-type "/" method)
template (-> session-test
(request template-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))
create-import-no-href {:template (ltu/strip-unwanted-attrs template)}
create-import-href {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:parent infra-service-id}}]
;; admin/user query should succeed but be empty (no credentials created yet)
(doseq [session [session-admin session-test]]
(-> session
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit)))
;; anonymous credential collection query should not succeed
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; creating a new credential without reference will fail for all types of users
(doseq [session [session-admin session-test session-anon]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str create-import-no-href))
(ltu/body->edn)
(ltu/is-status 400)))
;; creating a new credential as anon will fail; expect 400 because href cannot be accessed
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 400))
(with-redefs [vpn-utils/generate-credential (fn [_ _ _ _]
{:certificate certificate-value
:common-name common-name-value
:intermediate-ca inter-ca-values
:private-key private-key-value})]
(-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 400)
(ltu/is-key-value
#(str/starts-with? % "No vpn api endpoint found for ") :message true))
(-> session-admin
(request (str p/service-context configuration/resource-type)
:request-method :post
:body (json/write-str configuration-create))
(ltu/body->edn)
(ltu/is-status 201))
;; even with admin the create will fail when using bad template and scope
(-> session-admin
(request
base-uri
:request-method :post
:body (json/write-str (assoc-in create-import-href [:template :href] bad-href)))
(ltu/body->edn)
(ltu/is-key-value :message
"Bad infrastructure service scope for selected credential template!")
(ltu/is-status 400))
;; create a credential as a normal user
(let [resp (-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/is-key-value :private-key private-key-value)
(ltu/is-key-value :common-name common-name-value)
(ltu/is-key-value :intermediate-ca inter-ca-values))
id (ltu/body-resource-id resp)
uri (-> resp
(ltu/location))
abs-uri (str p/service-context uri)]
;; resource id and the uri (location) should be the same
(is (= id uri))
;; admin should be able to see and delete credential
(-> session-admin
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-operation-present :delete)
(ltu/is-operation-present :edit))
;; user should be able to see and delete credential
(-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-operation-present :delete))
;; ensure credential contains correct information
(let [{:keys [name description tags
vpn-common-name vpn-certificate
vpn-intermediate-ca parent]} (-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))]
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr))
(is (= vpn-common-name common-name-value))
(is (= vpn-certificate certificate-value))
(is (= parent infra-service-id))
(is (= vpn-intermediate-ca inter-ca-values)))
(-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-key-value :message (str "Credential VPN already exist for your account on "
"selected VPN infrastructure service!"))
(ltu/is-status 400))
;; credential should not be deleted if vpn api respond with error
(with-redefs [vpn-utils/delete-credential
(fn [_ _]
(throw (Exception.)))]
(-> session-test
(request abs-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 500)))
;; credential wasn't deleted
(-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200))
;; delete credential should succeed
(with-redefs [vpn-utils/delete-credential (fn [_ _])]
(-> session-test
(request abs-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200)))
))
))
| 13173 | (ns sixsq.nuvla.server.resources.credential.vpn-utils-test
(:require
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer [is]]
[peridot.core :refer [content-type header request session]]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.configuration :as configuration]
[sixsq.nuvla.server.resources.configuration-template :as configuration-tpl]
[sixsq.nuvla.server.resources.configuration-template-vpn-api :as configuration-tpl-vpn]
[sixsq.nuvla.server.resources.credential :as credential]
[sixsq.nuvla.server.resources.credential-template :as ct]
[sixsq.nuvla.server.resources.credential.vpn-utils :as vpn-utils]
[sixsq.nuvla.server.resources.infrastructure-service :as infra-service]
[sixsq.nuvla.server.resources.infrastructure-service-template :as infra-service-tpl]
[sixsq.nuvla.server.resources.infrastructure-service-template-vpn
:as infra-srvc-tpl-vpn]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]))
(def base-uri (str p/service-context credential/resource-type))
(defn credential-vpn-lifecycle-test
[method vpn-scope user-id claims method-not-corresponding-to-scope]
(let [session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-test (header session authn-info-header claims)
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]
common-name-value user-id
certificate-value "my-public-certificate"
inter-ca-values ["certif-1"]
private-key-value "private key visible only once at creation time"
infra-service-create {:template {:href (str infra-service-tpl/resource-type "/"
infra-srvc-tpl-vpn/method)
:vpn-scope vpn-scope
:acl {:owners ["nuvla/admin"]
:view-acl ["nuvla/user"
"nuvla/nuvlabox"]}}}
infra-service-id (-> session-admin
(request (str p/service-context infra-service/resource-type)
:request-method :post
:body (json/write-str infra-service-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
configuration-create {:template
{:href (str configuration-tpl/resource-type "/"
configuration-tpl-vpn/service)
:instance "vpn"
:endpoint "http://vpn.test"
:infrastructure-services [infra-service-id]}}
href (str ct/resource-type "/" method)
bad-href (str ct/resource-type "/" method-not-corresponding-to-scope)
template-url (str p/service-context ct/resource-type "/" method)
template (-> session-test
(request template-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))
create-import-no-href {:template (ltu/strip-unwanted-attrs template)}
create-import-href {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:parent infra-service-id}}]
;; admin/user query should succeed but be empty (no credentials created yet)
(doseq [session [session-admin session-test]]
(-> session
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit)))
;; anonymous credential collection query should not succeed
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; creating a new credential without reference will fail for all types of users
(doseq [session [session-admin session-test session-anon]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str create-import-no-href))
(ltu/body->edn)
(ltu/is-status 400)))
;; creating a new credential as anon will fail; expect 400 because href cannot be accessed
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 400))
(with-redefs [vpn-utils/generate-credential (fn [_ _ _ _]
{:certificate certificate-value
:common-name common-name-value
:intermediate-ca inter-ca-values
:private-key private-key-value})]
(-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 400)
(ltu/is-key-value
#(str/starts-with? % "No vpn api endpoint found for ") :message true))
(-> session-admin
(request (str p/service-context configuration/resource-type)
:request-method :post
:body (json/write-str configuration-create))
(ltu/body->edn)
(ltu/is-status 201))
;; even with admin the create will fail when using bad template and scope
(-> session-admin
(request
base-uri
:request-method :post
:body (json/write-str (assoc-in create-import-href [:template :href] bad-href)))
(ltu/body->edn)
(ltu/is-key-value :message
"Bad infrastructure service scope for selected credential template!")
(ltu/is-status 400))
;; create a credential as a normal user
(let [resp (-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/is-key-value :private-key private-key-value)
(ltu/is-key-value :common-name common-name-value)
(ltu/is-key-value :intermediate-ca inter-ca-values))
id (ltu/body-resource-id resp)
uri (-> resp
(ltu/location))
abs-uri (str p/service-context uri)]
;; resource id and the uri (location) should be the same
(is (= id uri))
;; admin should be able to see and delete credential
(-> session-admin
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-operation-present :delete)
(ltu/is-operation-present :edit))
;; user should be able to see and delete credential
(-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-operation-present :delete))
;; ensure credential contains correct information
(let [{:keys [name description tags
vpn-common-name v<KEY>certificate
vpn-intermediate-ca parent]} (-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))]
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr))
(is (= vpn-common-name common-name-value))
(is (= vpn-certificate certificate-value))
(is (= parent infra-service-id))
(is (= vpn-intermediate-ca inter-ca-values)))
(-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-key-value :message (str "Credential VPN already exist for your account on "
"selected VPN infrastructure service!"))
(ltu/is-status 400))
;; credential should not be deleted if vpn api respond with error
(with-redefs [vpn-utils/delete-credential
(fn [_ _]
(throw (Exception.)))]
(-> session-test
(request abs-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 500)))
;; credential wasn't deleted
(-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200))
;; delete credential should succeed
(with-redefs [vpn-utils/delete-credential (fn [_ _])]
(-> session-test
(request abs-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200)))
))
))
| true | (ns sixsq.nuvla.server.resources.credential.vpn-utils-test
(:require
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer [is]]
[peridot.core :refer [content-type header request session]]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.configuration :as configuration]
[sixsq.nuvla.server.resources.configuration-template :as configuration-tpl]
[sixsq.nuvla.server.resources.configuration-template-vpn-api :as configuration-tpl-vpn]
[sixsq.nuvla.server.resources.credential :as credential]
[sixsq.nuvla.server.resources.credential-template :as ct]
[sixsq.nuvla.server.resources.credential.vpn-utils :as vpn-utils]
[sixsq.nuvla.server.resources.infrastructure-service :as infra-service]
[sixsq.nuvla.server.resources.infrastructure-service-template :as infra-service-tpl]
[sixsq.nuvla.server.resources.infrastructure-service-template-vpn
:as infra-srvc-tpl-vpn]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]))
(def base-uri (str p/service-context credential/resource-type))
(defn credential-vpn-lifecycle-test
[method vpn-scope user-id claims method-not-corresponding-to-scope]
(let [session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-test (header session authn-info-header claims)
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")
name-attr "name"
description-attr "description"
tags-attr ["one", "two"]
common-name-value user-id
certificate-value "my-public-certificate"
inter-ca-values ["certif-1"]
private-key-value "private key visible only once at creation time"
infra-service-create {:template {:href (str infra-service-tpl/resource-type "/"
infra-srvc-tpl-vpn/method)
:vpn-scope vpn-scope
:acl {:owners ["nuvla/admin"]
:view-acl ["nuvla/user"
"nuvla/nuvlabox"]}}}
infra-service-id (-> session-admin
(request (str p/service-context infra-service/resource-type)
:request-method :post
:body (json/write-str infra-service-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
configuration-create {:template
{:href (str configuration-tpl/resource-type "/"
configuration-tpl-vpn/service)
:instance "vpn"
:endpoint "http://vpn.test"
:infrastructure-services [infra-service-id]}}
href (str ct/resource-type "/" method)
bad-href (str ct/resource-type "/" method-not-corresponding-to-scope)
template-url (str p/service-context ct/resource-type "/" method)
template (-> session-test
(request template-url)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))
create-import-no-href {:template (ltu/strip-unwanted-attrs template)}
create-import-href {:name name-attr
:description description-attr
:tags tags-attr
:template {:href href
:parent infra-service-id}}]
;; admin/user query should succeed but be empty (no credentials created yet)
(doseq [session [session-admin session-test]]
(-> session
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present :add)
(ltu/is-operation-absent :delete)
(ltu/is-operation-absent :edit)))
;; anonymous credential collection query should not succeed
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; creating a new credential without reference will fail for all types of users
(doseq [session [session-admin session-test session-anon]]
(-> session
(request base-uri
:request-method :post
:body (json/write-str create-import-no-href))
(ltu/body->edn)
(ltu/is-status 400)))
;; creating a new credential as anon will fail; expect 400 because href cannot be accessed
(-> session-anon
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 400))
(with-redefs [vpn-utils/generate-credential (fn [_ _ _ _]
{:certificate certificate-value
:common-name common-name-value
:intermediate-ca inter-ca-values
:private-key private-key-value})]
(-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 400)
(ltu/is-key-value
#(str/starts-with? % "No vpn api endpoint found for ") :message true))
(-> session-admin
(request (str p/service-context configuration/resource-type)
:request-method :post
:body (json/write-str configuration-create))
(ltu/body->edn)
(ltu/is-status 201))
;; even with admin the create will fail when using bad template and scope
(-> session-admin
(request
base-uri
:request-method :post
:body (json/write-str (assoc-in create-import-href [:template :href] bad-href)))
(ltu/body->edn)
(ltu/is-key-value :message
"Bad infrastructure service scope for selected credential template!")
(ltu/is-status 400))
;; create a credential as a normal user
(let [resp (-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/is-key-value :private-key private-key-value)
(ltu/is-key-value :common-name common-name-value)
(ltu/is-key-value :intermediate-ca inter-ca-values))
id (ltu/body-resource-id resp)
uri (-> resp
(ltu/location))
abs-uri (str p/service-context uri)]
;; resource id and the uri (location) should be the same
(is (= id uri))
;; admin should be able to see and delete credential
(-> session-admin
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-operation-present :delete)
(ltu/is-operation-present :edit))
;; user should be able to see and delete credential
(-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-operation-present :delete))
;; ensure credential contains correct information
(let [{:keys [name description tags
vpn-common-name vPI:KEY:<KEY>END_PIcertificate
vpn-intermediate-ca parent]} (-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/body))]
(is (= name name-attr))
(is (= description description-attr))
(is (= tags tags-attr))
(is (= vpn-common-name common-name-value))
(is (= vpn-certificate certificate-value))
(is (= parent infra-service-id))
(is (= vpn-intermediate-ca inter-ca-values)))
(-> session-test
(request base-uri
:request-method :post
:body (json/write-str create-import-href))
(ltu/body->edn)
(ltu/is-key-value :message (str "Credential VPN already exist for your account on "
"selected VPN infrastructure service!"))
(ltu/is-status 400))
;; credential should not be deleted if vpn api respond with error
(with-redefs [vpn-utils/delete-credential
(fn [_ _]
(throw (Exception.)))]
(-> session-test
(request abs-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 500)))
;; credential wasn't deleted
(-> session-test
(request abs-uri)
(ltu/body->edn)
(ltu/is-status 200))
;; delete credential should succeed
(with-redefs [vpn-utils/delete-credential (fn [_ _])]
(-> session-test
(request abs-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200)))
))
))
|
[
{
"context": "(ns franiwalksdogs.captcha\n (:require \n [reagent.core :as r",
"end": 13,
"score": 0.6969212889671326,
"start": 4,
"tag": "USERNAME",
"value": "franiwalk"
},
{
"context": "quire \n [reagent.core :as r]))\n\n(def site-key \"6Lfm_n0UAAAAAAs3jz7FKPGK2KkZbe8QV7BgJrBf\")\n\n(defn- on-mount [captcha-id fields errors]\n (",
"end": 123,
"score": 0.9997491836547852,
"start": 83,
"tag": "KEY",
"value": "6Lfm_n0UAAAAAAs3jz7FKPGK2KkZbe8QV7BgJrBf"
}
] | src/cljs/franiwalksdogs/captcha.cljs | daplay/franiwalksdogs | 0 | (ns franiwalksdogs.captcha
(:require
[reagent.core :as r]))
(def site-key "6Lfm_n0UAAAAAAs3jz7FKPGK2KkZbe8QV7BgJrBf")
(defn- on-mount [captcha-id fields errors]
(fn [div]
(reset! captcha-id
(js/window.grecaptcha.render
(-> div r/dom-node .-firstChild)
(clj->js {:sitekey site-key
:expired-callback #(swap! fields dissoc :captcha)
:callback #(do (swap! errors dissoc :captcha)
(swap! fields assoc :captcha %))})))))
(defn on-update [captcha-id errors]
(fn [this old-argv]
(when (and @captcha-id (:captcha @errors))
(.reset js/grecaptcha @captcha-id))))
(defn- html [errors]
(fn []
[:div.form-group
[:div]
]))
(defn- html-min-captcha [errors]
(fn []
[:div
[:div]
]))
(defn captcha [fields errors]
(let [captcha-id (atom nil)]
(r/create-class {:render (html errors)
:component-did-update (on-update captcha-id errors)
:component-did-mount (on-mount captcha-id fields errors)})))
(defn min-captcha [fields errors]
(let [captcha-id (atom nil)]
(r/create-class {:render (html-min-captcha errors)
:component-did-update (on-update captcha-id errors)
:component-did-mount (on-mount captcha-id fields errors)})))
| 71728 | (ns franiwalksdogs.captcha
(:require
[reagent.core :as r]))
(def site-key "<KEY>")
(defn- on-mount [captcha-id fields errors]
(fn [div]
(reset! captcha-id
(js/window.grecaptcha.render
(-> div r/dom-node .-firstChild)
(clj->js {:sitekey site-key
:expired-callback #(swap! fields dissoc :captcha)
:callback #(do (swap! errors dissoc :captcha)
(swap! fields assoc :captcha %))})))))
(defn on-update [captcha-id errors]
(fn [this old-argv]
(when (and @captcha-id (:captcha @errors))
(.reset js/grecaptcha @captcha-id))))
(defn- html [errors]
(fn []
[:div.form-group
[:div]
]))
(defn- html-min-captcha [errors]
(fn []
[:div
[:div]
]))
(defn captcha [fields errors]
(let [captcha-id (atom nil)]
(r/create-class {:render (html errors)
:component-did-update (on-update captcha-id errors)
:component-did-mount (on-mount captcha-id fields errors)})))
(defn min-captcha [fields errors]
(let [captcha-id (atom nil)]
(r/create-class {:render (html-min-captcha errors)
:component-did-update (on-update captcha-id errors)
:component-did-mount (on-mount captcha-id fields errors)})))
| true | (ns franiwalksdogs.captcha
(:require
[reagent.core :as r]))
(def site-key "PI:KEY:<KEY>END_PI")
(defn- on-mount [captcha-id fields errors]
(fn [div]
(reset! captcha-id
(js/window.grecaptcha.render
(-> div r/dom-node .-firstChild)
(clj->js {:sitekey site-key
:expired-callback #(swap! fields dissoc :captcha)
:callback #(do (swap! errors dissoc :captcha)
(swap! fields assoc :captcha %))})))))
(defn on-update [captcha-id errors]
(fn [this old-argv]
(when (and @captcha-id (:captcha @errors))
(.reset js/grecaptcha @captcha-id))))
(defn- html [errors]
(fn []
[:div.form-group
[:div]
]))
(defn- html-min-captcha [errors]
(fn []
[:div
[:div]
]))
(defn captcha [fields errors]
(let [captcha-id (atom nil)]
(r/create-class {:render (html errors)
:component-did-update (on-update captcha-id errors)
:component-did-mount (on-mount captcha-id fields errors)})))
(defn min-captcha [fields errors]
(let [captcha-id (atom nil)]
(r/create-class {:render (html-min-captcha errors)
:component-did-update (on-update captcha-id errors)
:component-did-mount (on-mount captcha-id fields errors)})))
|
[
{
"context": "depic-d4d4x56.jpg\"\n :img-alt \"Map art by JaredBlando https://www.deviantart.com/jaredblando\"",
"end": 355,
"score": 0.5148109197616577,
"start": 354,
"tag": "NAME",
"value": "J"
},
{
"context": "Map art by JaredBlando https://www.deviantart.com/jaredblando\"}\n :dm? false\n :fog-of-war-mode :reveil\n ",
"end": 404,
"score": 0.8700947761535645,
"start": 393,
"tag": "USERNAME",
"value": "jaredblando"
},
{
"context": "ed-cells #{}\n :session-id nil\n :players {\"neg1\" {:id \"neg1\"\n :initiati",
"end": 547,
"score": 0.9548382759094238,
"start": 543,
"tag": "USERNAME",
"value": "neg1"
},
{
"context": " :session-id nil\n :players {\"neg1\" {:id \"neg1\"\n :initiative 10\n ",
"end": 561,
"score": 0.9984244108200073,
"start": 557,
"tag": "USERNAME",
"value": "neg1"
},
{
"context": " :hp 100\n :name \"Negwen\"\n :img-url \"https://media",
"end": 674,
"score": 0.997693657875061,
"start": 668,
"tag": "NAME",
"value": "Negwen"
},
{
"context": " :dead false}\n \"ikara1\" {:id \"ikara1\"\n :initiati",
"end": 1033,
"score": 0.9224371910095215,
"start": 1027,
"tag": "USERNAME",
"value": "ikara1"
},
{
"context": " :dead false}\n \"ikara1\" {:id \"ikara1\"\n :initiative 12\n ",
"end": 1047,
"score": 0.9982653260231018,
"start": 1041,
"tag": "USERNAME",
"value": "ikara1"
},
{
"context": " :hp 100\n :name \"Ikara\"\n :img-url \"https://media",
"end": 1159,
"score": 0.9906076192855835,
"start": 1154,
"tag": "NAME",
"value": "Ikara"
},
{
"context": " :dead false}\n \"Udrik\" {:id \"Udrik\"\n :initiati",
"end": 1516,
"score": 0.6387711763381958,
"start": 1513,
"tag": "USERNAME",
"value": "rik"
},
{
"context": " :dead false}\n \"Udrik\" {:id \"Udrik\"\n :initiative 14\n ",
"end": 1530,
"score": 0.9982332587242126,
"start": 1525,
"tag": "USERNAME",
"value": "Udrik"
},
{
"context": " :hp 100\n :name \"Udrik\"\n :img-url \"https://media",
"end": 1642,
"score": 0.9959368705749512,
"start": 1637,
"tag": "NAME",
"value": "Udrik"
},
{
"context": " :dead false}\n \"goblin\" {:id \"goblin\"\n :initiative 8\n ",
"end": 2012,
"score": 0.998668909072876,
"start": 2006,
"tag": "USERNAME",
"value": "goblin"
},
{
"context": " :hp 7\n :name \"Goblin 1\"\n :img-url \"https://i.img",
"end": 2124,
"score": 0.9988881349563599,
"start": 2116,
"tag": "NAME",
"value": "Goblin 1"
}
] | src/app/state.cljs | Velrok/dnd-mapper | 1 | (ns app.state)
(def initial-app-value
{:active-view-id :start
:highlight-overlay true
:map {:width 12
:height 15
:padding {:left 9 :right 11 :top 27 :bottom 57}
:img-url "https://pre00.deviantart.net/dee0/th/pre/i/2015/116/0/b/the_desecrated_temple_by_theredepic-d4d4x56.jpg"
:img-alt "Map art by JaredBlando https://www.deviantart.com/jaredblando"}
:dm? false
:fog-of-war-mode :reveil
:reveiled-cells #{}
:highlighted-cells #{}
:session-id nil
:players {"neg1" {:id "neg1"
:initiative 10
:hp 100
:name "Negwen"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/4729/162/150/300/636756769380492799.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"ikara1" {:id "ikara1"
:initiative 12
:hp 100
:name "Ikara"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/17/747/150/150/636378331895705713.jpeg"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"Udrik" {:id "Udrik"
:initiative 14
:hp 100
:name "Udrik"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/10/71/150/150/636339380148524382.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"goblin" {:id "goblin"
:initiative 8
:hp 7
:name "Goblin 1"
:img-url "https://i.imgur.com/kCysnYk.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}}})
| 61279 | (ns app.state)
(def initial-app-value
{:active-view-id :start
:highlight-overlay true
:map {:width 12
:height 15
:padding {:left 9 :right 11 :top 27 :bottom 57}
:img-url "https://pre00.deviantart.net/dee0/th/pre/i/2015/116/0/b/the_desecrated_temple_by_theredepic-d4d4x56.jpg"
:img-alt "Map art by <NAME>aredBlando https://www.deviantart.com/jaredblando"}
:dm? false
:fog-of-war-mode :reveil
:reveiled-cells #{}
:highlighted-cells #{}
:session-id nil
:players {"neg1" {:id "neg1"
:initiative 10
:hp 100
:name "<NAME>"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/4729/162/150/300/636756769380492799.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"ikara1" {:id "ikara1"
:initiative 12
:hp 100
:name "<NAME>"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/17/747/150/150/636378331895705713.jpeg"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"Udrik" {:id "Udrik"
:initiative 14
:hp 100
:name "<NAME>"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/10/71/150/150/636339380148524382.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"goblin" {:id "goblin"
:initiative 8
:hp 7
:name "<NAME>"
:img-url "https://i.imgur.com/kCysnYk.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}}})
| true | (ns app.state)
(def initial-app-value
{:active-view-id :start
:highlight-overlay true
:map {:width 12
:height 15
:padding {:left 9 :right 11 :top 27 :bottom 57}
:img-url "https://pre00.deviantart.net/dee0/th/pre/i/2015/116/0/b/the_desecrated_temple_by_theredepic-d4d4x56.jpg"
:img-alt "Map art by PI:NAME:<NAME>END_PIaredBlando https://www.deviantart.com/jaredblando"}
:dm? false
:fog-of-war-mode :reveil
:reveiled-cells #{}
:highlighted-cells #{}
:session-id nil
:players {"neg1" {:id "neg1"
:initiative 10
:hp 100
:name "PI:NAME:<NAME>END_PI"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/4729/162/150/300/636756769380492799.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"ikara1" {:id "ikara1"
:initiative 12
:hp 100
:name "PI:NAME:<NAME>END_PI"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/17/747/150/150/636378331895705713.jpeg"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"Udrik" {:id "Udrik"
:initiative 14
:hp 100
:name "PI:NAME:<NAME>END_PI"
:img-url "https://media-waterdeep.cursecdn.com/avatars/thumbnails/10/71/150/150/636339380148524382.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}
"goblin" {:id "goblin"
:initiative 8
:hp 7
:name "PI:NAME:<NAME>END_PI"
:img-url "https://i.imgur.com/kCysnYk.png"
:player-visible true
:on-map false
:position nil
:dm-focus false
:dead false}}})
|
[
{
"context": "h-superlifter]]))\n\n(def pet-db {\"abc-123\" {:name \"Lyra\"\n :age 11}\n \"d",
"end": 370,
"score": 0.9997380971908569,
"start": 366,
"tag": "NAME",
"value": "Lyra"
},
{
"context": " :age 11}\n \"def-234\" {:name \"Pantalaimon\"\n :age 11}\n \"g",
"end": 447,
"score": 0.9997355937957764,
"start": 436,
"tag": "NAME",
"value": "Pantalaimon"
},
{
"context": " :age 11}\n \"ghi-345\" {:name \"Iorek\"\n :age 41}\n \"p",
"end": 518,
"score": 0.9996633529663086,
"start": 513,
"tag": "NAME",
"value": "Iorek"
},
{
"context": " :age 41}\n \"pet1\" {:name \"ASDF\"\n :age 100}})\n\n;; without ",
"end": 588,
"score": 0.9344428777694702,
"start": 584,
"tag": "NAME",
"value": "ASDF"
}
] | src/main.clj | ssisksl77/superlifeter-poc | 0 | (ns main
(:require [clojure.tools.logging :as log]
[com.walmartlabs.lacinia.pedestal :as lacinia-pedestal]
[com.walmartlabs.lacinia.schema :as schema]
[io.pedestal.http :as http]
[superlifter.api :as s]
[superlifter.lacinia :refer [inject-superlifter with-superlifter]]))
(def pet-db {"abc-123" {:name "Lyra"
:age 11}
"def-234" {:name "Pantalaimon"
:age 11}
"ghi-345" {:name "Iorek"
:age 41}
"pet1" {:name "ASDF"
:age 100}})
;; without superlifter STRT
#_(defn- resolve-pets [context args parent]
(log/info "resolve-pets is called")
(let [ids (keys pet-db)]
(map (fn [id] {:id id}) ids)))
;; invoked n times, once for every id from the parent resolver
#_(defn- resolve-pet-details [context args {:keys [id]}]
(log/info "resolve-pet-details is called")
(get pet-db id))
;;;; without superlifter END
;;;; with superlifter START
(s/def-fetcher FetchPets []
(fn [_this env]
#_(log/info env)
(map (fn [id] {:id id})
(keys (:db env)))))
(s/def-superfetcher FetchPet [id]
(fn [many env]
#_(log/info env)
(log/info "pet-id를 이용하여 pet-detail을 가져오는 리퀘스트 " (count many) "개 합쳐짐.")
(map (:db env) (map :id many))))
(defn- resolve-pets [context _args _parent]
;; context는 그냥 request정보같은게 있음.
(with-superlifter context
(do (log/info "resolve-pets " context _parent)
(-> (s/enqueue! (->FetchPets)) ;; pets를 일괄로 가져옴. 그걸 큐에 넣음.
;; 트리거를 바로 부름.
;; 첫번째 인자는 promise
;; 이거로 트리거를 재설정한다.
;; 트리거 바꾸지 않으니까 하나씩 실행됨. threshold가 0이면 바로 실행되는 듯.
;; 이게 enqueue를 하자마자 동작하는 것이 아닌가봄. 좀 느림.
;; 그래서 update-trigger! 를 이렇게 수행해도 문제가 없나봄.
(s/update-trigger! :pet-details ; bucket-id
:elastic ; trigger-kind
(fn [trigger-opts pet-ids] ; opts-fn
;; opts-fn으로 동적으로 잠깐 threshold를 바꿀 수도 있음.
;; (println "update-trigger!" trigger-opts pet-ids)
;; pet-id 갯수만큼으로 임계를 바꿔줌으로써 pet-id가 꽉차면 알아서
;; pet-details를 가져옴.
(update trigger-opts :threshold + (count pet-ids))))))))
(defn- resolve-pet-details [context _args {:keys [id]}]
(with-superlifter context
(do
(log/info "resolve-pet-details" context id)
(s/enqueue! :pet-details (->FetchPet id)))))
;;;; with superlifter END
(def schema
{:objects {:PetDetails {:fields {:name {:type 'String}
:age {:type 'Int}}}
:Pet {:fields {:id {:type 'String}
:details {:type :PetDetails
:resolve resolve-pet-details}}}}
:queries {:pets
{:type '(list :Pet)
:resolve resolve-pets}}})
(def lacinia-opts {:graphiql true
:port 8888
:join? false})
(def superlifter-args
{:buckets {:default {:triggers {:queue-size {:threshold 1}}}
:pet-details {:triggers {:elastic {:threshold 0}}}}
;; superlifter는 내부적으로 urania를 사용한다.
;; urania에 환경을 넣어서 -fetcher들이 사용할 수 있게 한다. 대게는 db 커넥션을 넣는듯함.
;; db커넥션을 넣는다면 closure를 사용해야할 듯.
;; 즉, superlifter-args를 함수로 바꿔서 context를 인자로 넣어서 사용하는 것이 일반적일 듯.
:urania-opts {:env {:db pet-db}}})
(def service
(lacinia-pedestal/service-map
(fn [] (schema/compile schema))
(assoc lacinia-opts
:interceptors (into [(inject-superlifter superlifter-args)]
(lacinia-pedestal/default-interceptors (fn [] (schema/compile schema)) lacinia-opts)))))
(comment
(def runnable-service (http/create-server service))
(def running-server (http/start runnable-service))
(http/stop runnable-service)
(http/stop running-server)
;; curl -XPOST -H "Content-Type:application/graphql" localhost:8888/graphql -d '{pets {id details {name}}}'
)
| 25963 | (ns main
(:require [clojure.tools.logging :as log]
[com.walmartlabs.lacinia.pedestal :as lacinia-pedestal]
[com.walmartlabs.lacinia.schema :as schema]
[io.pedestal.http :as http]
[superlifter.api :as s]
[superlifter.lacinia :refer [inject-superlifter with-superlifter]]))
(def pet-db {"abc-123" {:name "<NAME>"
:age 11}
"def-234" {:name "<NAME>"
:age 11}
"ghi-345" {:name "<NAME>"
:age 41}
"pet1" {:name "<NAME>"
:age 100}})
;; without superlifter STRT
#_(defn- resolve-pets [context args parent]
(log/info "resolve-pets is called")
(let [ids (keys pet-db)]
(map (fn [id] {:id id}) ids)))
;; invoked n times, once for every id from the parent resolver
#_(defn- resolve-pet-details [context args {:keys [id]}]
(log/info "resolve-pet-details is called")
(get pet-db id))
;;;; without superlifter END
;;;; with superlifter START
(s/def-fetcher FetchPets []
(fn [_this env]
#_(log/info env)
(map (fn [id] {:id id})
(keys (:db env)))))
(s/def-superfetcher FetchPet [id]
(fn [many env]
#_(log/info env)
(log/info "pet-id를 이용하여 pet-detail을 가져오는 리퀘스트 " (count many) "개 합쳐짐.")
(map (:db env) (map :id many))))
(defn- resolve-pets [context _args _parent]
;; context는 그냥 request정보같은게 있음.
(with-superlifter context
(do (log/info "resolve-pets " context _parent)
(-> (s/enqueue! (->FetchPets)) ;; pets를 일괄로 가져옴. 그걸 큐에 넣음.
;; 트리거를 바로 부름.
;; 첫번째 인자는 promise
;; 이거로 트리거를 재설정한다.
;; 트리거 바꾸지 않으니까 하나씩 실행됨. threshold가 0이면 바로 실행되는 듯.
;; 이게 enqueue를 하자마자 동작하는 것이 아닌가봄. 좀 느림.
;; 그래서 update-trigger! 를 이렇게 수행해도 문제가 없나봄.
(s/update-trigger! :pet-details ; bucket-id
:elastic ; trigger-kind
(fn [trigger-opts pet-ids] ; opts-fn
;; opts-fn으로 동적으로 잠깐 threshold를 바꿀 수도 있음.
;; (println "update-trigger!" trigger-opts pet-ids)
;; pet-id 갯수만큼으로 임계를 바꿔줌으로써 pet-id가 꽉차면 알아서
;; pet-details를 가져옴.
(update trigger-opts :threshold + (count pet-ids))))))))
(defn- resolve-pet-details [context _args {:keys [id]}]
(with-superlifter context
(do
(log/info "resolve-pet-details" context id)
(s/enqueue! :pet-details (->FetchPet id)))))
;;;; with superlifter END
(def schema
{:objects {:PetDetails {:fields {:name {:type 'String}
:age {:type 'Int}}}
:Pet {:fields {:id {:type 'String}
:details {:type :PetDetails
:resolve resolve-pet-details}}}}
:queries {:pets
{:type '(list :Pet)
:resolve resolve-pets}}})
(def lacinia-opts {:graphiql true
:port 8888
:join? false})
(def superlifter-args
{:buckets {:default {:triggers {:queue-size {:threshold 1}}}
:pet-details {:triggers {:elastic {:threshold 0}}}}
;; superlifter는 내부적으로 urania를 사용한다.
;; urania에 환경을 넣어서 -fetcher들이 사용할 수 있게 한다. 대게는 db 커넥션을 넣는듯함.
;; db커넥션을 넣는다면 closure를 사용해야할 듯.
;; 즉, superlifter-args를 함수로 바꿔서 context를 인자로 넣어서 사용하는 것이 일반적일 듯.
:urania-opts {:env {:db pet-db}}})
(def service
(lacinia-pedestal/service-map
(fn [] (schema/compile schema))
(assoc lacinia-opts
:interceptors (into [(inject-superlifter superlifter-args)]
(lacinia-pedestal/default-interceptors (fn [] (schema/compile schema)) lacinia-opts)))))
(comment
(def runnable-service (http/create-server service))
(def running-server (http/start runnable-service))
(http/stop runnable-service)
(http/stop running-server)
;; curl -XPOST -H "Content-Type:application/graphql" localhost:8888/graphql -d '{pets {id details {name}}}'
)
| true | (ns main
(:require [clojure.tools.logging :as log]
[com.walmartlabs.lacinia.pedestal :as lacinia-pedestal]
[com.walmartlabs.lacinia.schema :as schema]
[io.pedestal.http :as http]
[superlifter.api :as s]
[superlifter.lacinia :refer [inject-superlifter with-superlifter]]))
(def pet-db {"abc-123" {:name "PI:NAME:<NAME>END_PI"
:age 11}
"def-234" {:name "PI:NAME:<NAME>END_PI"
:age 11}
"ghi-345" {:name "PI:NAME:<NAME>END_PI"
:age 41}
"pet1" {:name "PI:NAME:<NAME>END_PI"
:age 100}})
;; without superlifter STRT
#_(defn- resolve-pets [context args parent]
(log/info "resolve-pets is called")
(let [ids (keys pet-db)]
(map (fn [id] {:id id}) ids)))
;; invoked n times, once for every id from the parent resolver
#_(defn- resolve-pet-details [context args {:keys [id]}]
(log/info "resolve-pet-details is called")
(get pet-db id))
;;;; without superlifter END
;;;; with superlifter START
(s/def-fetcher FetchPets []
(fn [_this env]
#_(log/info env)
(map (fn [id] {:id id})
(keys (:db env)))))
(s/def-superfetcher FetchPet [id]
(fn [many env]
#_(log/info env)
(log/info "pet-id를 이용하여 pet-detail을 가져오는 리퀘스트 " (count many) "개 합쳐짐.")
(map (:db env) (map :id many))))
(defn- resolve-pets [context _args _parent]
;; context는 그냥 request정보같은게 있음.
(with-superlifter context
(do (log/info "resolve-pets " context _parent)
(-> (s/enqueue! (->FetchPets)) ;; pets를 일괄로 가져옴. 그걸 큐에 넣음.
;; 트리거를 바로 부름.
;; 첫번째 인자는 promise
;; 이거로 트리거를 재설정한다.
;; 트리거 바꾸지 않으니까 하나씩 실행됨. threshold가 0이면 바로 실행되는 듯.
;; 이게 enqueue를 하자마자 동작하는 것이 아닌가봄. 좀 느림.
;; 그래서 update-trigger! 를 이렇게 수행해도 문제가 없나봄.
(s/update-trigger! :pet-details ; bucket-id
:elastic ; trigger-kind
(fn [trigger-opts pet-ids] ; opts-fn
;; opts-fn으로 동적으로 잠깐 threshold를 바꿀 수도 있음.
;; (println "update-trigger!" trigger-opts pet-ids)
;; pet-id 갯수만큼으로 임계를 바꿔줌으로써 pet-id가 꽉차면 알아서
;; pet-details를 가져옴.
(update trigger-opts :threshold + (count pet-ids))))))))
(defn- resolve-pet-details [context _args {:keys [id]}]
(with-superlifter context
(do
(log/info "resolve-pet-details" context id)
(s/enqueue! :pet-details (->FetchPet id)))))
;;;; with superlifter END
(def schema
{:objects {:PetDetails {:fields {:name {:type 'String}
:age {:type 'Int}}}
:Pet {:fields {:id {:type 'String}
:details {:type :PetDetails
:resolve resolve-pet-details}}}}
:queries {:pets
{:type '(list :Pet)
:resolve resolve-pets}}})
(def lacinia-opts {:graphiql true
:port 8888
:join? false})
(def superlifter-args
{:buckets {:default {:triggers {:queue-size {:threshold 1}}}
:pet-details {:triggers {:elastic {:threshold 0}}}}
;; superlifter는 내부적으로 urania를 사용한다.
;; urania에 환경을 넣어서 -fetcher들이 사용할 수 있게 한다. 대게는 db 커넥션을 넣는듯함.
;; db커넥션을 넣는다면 closure를 사용해야할 듯.
;; 즉, superlifter-args를 함수로 바꿔서 context를 인자로 넣어서 사용하는 것이 일반적일 듯.
:urania-opts {:env {:db pet-db}}})
(def service
(lacinia-pedestal/service-map
(fn [] (schema/compile schema))
(assoc lacinia-opts
:interceptors (into [(inject-superlifter superlifter-args)]
(lacinia-pedestal/default-interceptors (fn [] (schema/compile schema)) lacinia-opts)))))
(comment
(def runnable-service (http/create-server service))
(def running-server (http/start runnable-service))
(http/stop runnable-service)
(http/stop running-server)
;; curl -XPOST -H "Content-Type:application/graphql" localhost:8888/graphql -d '{pets {id details {name}}}'
)
|
[
{
"context": "t.alert-danger error])\n [c/password-input \"password\" :pass \"enter a password\" fields]\n (when-l",
"end": 1185,
"score": 0.9602280259132385,
"start": 1177,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ror])\n [c/password-input \"password\" :pass \"enter a password\" fields]\n (when-let [error (first (:pass @",
"end": 1210,
"score": 0.9926897883415222,
"start": 1194,
"tag": "PASSWORD",
"value": "enter a password"
},
{
"context": " [c/password-input \"password\" :pass-confirm \"re-enter the password\" fields]\n (when-let [error (first (:pass-c",
"end": 1385,
"score": 0.9893099069595337,
"start": 1364,
"tag": "PASSWORD",
"value": "re-enter the password"
}
] | src/cljs/fcc_tracker/components/registration.cljs | achernyak/fcc-tracker | 2 | (ns fcc-tracker.components.registration
(:require [ajax.core :as ajax]
[fcc-tracker.components.common :as c]
[fcc-tracker.validation :as v]
[reagent.core :as r]
[reagent.session :as session]))
(defn register! [fields errors]
(reset! errors (v/registration-errors @fields))
(when-not @errors
(ajax/POST "/register"
{:params @fields
:handler #(do
(session/put! :identity (:id @fields))
(reset! fields {})
(session/remove! :modal))
:error-handler #(reset!
errors
{:server-error (get-in % [:response :message])})})))
(defn registration-form []
(let [fields (r/atom {})
error (r/atom nil)]
(fn []
[c/modal
[:div "Register to track members"]
[:div
[:div.well.well-sm
[:strong "* required field"]]
[c/text-input "name" :id "enter a user name" fields]
(when-let [error (first (:id @error))]
[:div.alert.alert-danger error])
[c/password-input "password" :pass "enter a password" fields]
(when-let [error (first (:pass @error))]
[:div.alert.alert-danger error])
[c/password-input "password" :pass-confirm "re-enter the password" fields]
(when-let [error (first (:pass-confirm @error))]
[:div.alert.alert-danger error])
(when-let [error (:server-error @error)]
[:div.alert.alert-danger error])]
[:div
[:button.btn.btn-primary
{:on-click #(register! fields error)}
"Register"]
[:button.btn.btn-danger
{:on-click #(session/remove! :modal)}
"Cancel"]]])))
(defn registration-button []
[:a
{:on-click #(session/put! :modal registration-form)}
"register"])
| 105949 | (ns fcc-tracker.components.registration
(:require [ajax.core :as ajax]
[fcc-tracker.components.common :as c]
[fcc-tracker.validation :as v]
[reagent.core :as r]
[reagent.session :as session]))
(defn register! [fields errors]
(reset! errors (v/registration-errors @fields))
(when-not @errors
(ajax/POST "/register"
{:params @fields
:handler #(do
(session/put! :identity (:id @fields))
(reset! fields {})
(session/remove! :modal))
:error-handler #(reset!
errors
{:server-error (get-in % [:response :message])})})))
(defn registration-form []
(let [fields (r/atom {})
error (r/atom nil)]
(fn []
[c/modal
[:div "Register to track members"]
[:div
[:div.well.well-sm
[:strong "* required field"]]
[c/text-input "name" :id "enter a user name" fields]
(when-let [error (first (:id @error))]
[:div.alert.alert-danger error])
[c/password-input "<PASSWORD>" :pass "<PASSWORD>" fields]
(when-let [error (first (:pass @error))]
[:div.alert.alert-danger error])
[c/password-input "password" :pass-confirm "<PASSWORD>" fields]
(when-let [error (first (:pass-confirm @error))]
[:div.alert.alert-danger error])
(when-let [error (:server-error @error)]
[:div.alert.alert-danger error])]
[:div
[:button.btn.btn-primary
{:on-click #(register! fields error)}
"Register"]
[:button.btn.btn-danger
{:on-click #(session/remove! :modal)}
"Cancel"]]])))
(defn registration-button []
[:a
{:on-click #(session/put! :modal registration-form)}
"register"])
| true | (ns fcc-tracker.components.registration
(:require [ajax.core :as ajax]
[fcc-tracker.components.common :as c]
[fcc-tracker.validation :as v]
[reagent.core :as r]
[reagent.session :as session]))
(defn register! [fields errors]
(reset! errors (v/registration-errors @fields))
(when-not @errors
(ajax/POST "/register"
{:params @fields
:handler #(do
(session/put! :identity (:id @fields))
(reset! fields {})
(session/remove! :modal))
:error-handler #(reset!
errors
{:server-error (get-in % [:response :message])})})))
(defn registration-form []
(let [fields (r/atom {})
error (r/atom nil)]
(fn []
[c/modal
[:div "Register to track members"]
[:div
[:div.well.well-sm
[:strong "* required field"]]
[c/text-input "name" :id "enter a user name" fields]
(when-let [error (first (:id @error))]
[:div.alert.alert-danger error])
[c/password-input "PI:PASSWORD:<PASSWORD>END_PI" :pass "PI:PASSWORD:<PASSWORD>END_PI" fields]
(when-let [error (first (:pass @error))]
[:div.alert.alert-danger error])
[c/password-input "password" :pass-confirm "PI:PASSWORD:<PASSWORD>END_PI" fields]
(when-let [error (first (:pass-confirm @error))]
[:div.alert.alert-danger error])
(when-let [error (:server-error @error)]
[:div.alert.alert-danger error])]
[:div
[:button.btn.btn-primary
{:on-click #(register! fields error)}
"Register"]
[:button.btn.btn-danger
{:on-click #(session/remove! :modal)}
"Cancel"]]])))
(defn registration-button []
[:a
{:on-click #(session/put! :modal registration-form)}
"register"])
|
[
{
"context": "like so:\n; \n; {#\"my\\.datomic\\.com\" {:username \"[USERNAME]\"\n; :password \"[LICENSE_K",
"end": 880,
"score": 0.9767773747444153,
"start": 872,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": "[USERNAME]\"\n; :password \"[LICENSE_KEY]\"}}\n; Then encrypt it with gpg:\n; \n; $ gpg --de",
"end": 932,
"score": 0.7641414999961853,
"start": 921,
"tag": "PASSWORD",
"value": "LICENSE_KEY"
}
] | priv/datomic_gen_server_peer/project.clj | venturecommunism/otp-datomic | 0 | (defproject datomic_gen_server/peer "2.2.5"
:description "Datomic peer server in Clojure, accepting edn strings which will be sent by Elixir"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/core.async "0.2.374"]
[org.clojure/core.match "0.3.0-alpha4"]
[org.clojure/tools.cli "0.3.3"]
[clojure-erlastic "0.3.1"]
[io.rkn/conformity "0.4.0"]
[com.datomic/datomic-free "0.9.5350"]
[vvvvalvalval/datomock "0.1.0"]
]
:main datomic_gen_server.peer
:aot :all)
; If you are using Datomic Pro, the repository above will be necessary and you'll
; need your credentials for it. You'll need to install gpg for this.
;
; First write your credentials map to ~/.lein/credentials.clj like so:
;
; {#"my\.datomic\.com" {:username "[USERNAME]"
; :password "[LICENSE_KEY]"}}
; Then encrypt it with gpg:
;
; $ gpg --default-recipient-self -e ~/.lein/credentials.clj > ~/.lein/credentials.clj.gpg
;
; Remember to delete the plaintext credentials.clj once you've encrypted it.
| 95608 | (defproject datomic_gen_server/peer "2.2.5"
:description "Datomic peer server in Clojure, accepting edn strings which will be sent by Elixir"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/core.async "0.2.374"]
[org.clojure/core.match "0.3.0-alpha4"]
[org.clojure/tools.cli "0.3.3"]
[clojure-erlastic "0.3.1"]
[io.rkn/conformity "0.4.0"]
[com.datomic/datomic-free "0.9.5350"]
[vvvvalvalval/datomock "0.1.0"]
]
:main datomic_gen_server.peer
:aot :all)
; If you are using Datomic Pro, the repository above will be necessary and you'll
; need your credentials for it. You'll need to install gpg for this.
;
; First write your credentials map to ~/.lein/credentials.clj like so:
;
; {#"my\.datomic\.com" {:username "[USERNAME]"
; :password "[<PASSWORD>]"}}
; Then encrypt it with gpg:
;
; $ gpg --default-recipient-self -e ~/.lein/credentials.clj > ~/.lein/credentials.clj.gpg
;
; Remember to delete the plaintext credentials.clj once you've encrypted it.
| true | (defproject datomic_gen_server/peer "2.2.5"
:description "Datomic peer server in Clojure, accepting edn strings which will be sent by Elixir"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/core.async "0.2.374"]
[org.clojure/core.match "0.3.0-alpha4"]
[org.clojure/tools.cli "0.3.3"]
[clojure-erlastic "0.3.1"]
[io.rkn/conformity "0.4.0"]
[com.datomic/datomic-free "0.9.5350"]
[vvvvalvalval/datomock "0.1.0"]
]
:main datomic_gen_server.peer
:aot :all)
; If you are using Datomic Pro, the repository above will be necessary and you'll
; need your credentials for it. You'll need to install gpg for this.
;
; First write your credentials map to ~/.lein/credentials.clj like so:
;
; {#"my\.datomic\.com" {:username "[USERNAME]"
; :password "[PI:PASSWORD:<PASSWORD>END_PI]"}}
; Then encrypt it with gpg:
;
; $ gpg --default-recipient-self -e ~/.lein/credentials.clj > ~/.lein/credentials.clj.gpg
;
; Remember to delete the plaintext credentials.clj once you've encrypted it.
|
[
{
"context": "to-key must be a map\"]\n {:host-to-key {\"a\" \"b\"} :sources []} false\n ,[\"must be a java.sec",
"end": 2344,
"score": 0.7067667245864868,
"start": 2343,
"tag": "KEY",
"value": "b"
}
] | test/hesokuri/config_test.clj | matvore/hesokuri | 0 | ; Copyright (C) 2013 Google Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns hesokuri.config-test
(:require [clojure.test :refer :all]
[hesokuri.config :refer :all]
[hesokuri.testing.data :refer :all]
[hesokuri.testing.temp :refer :all]
[hesokuri.testing.validation :refer :all]))
(deftest test-source-defs
(are [config sources]
(is (= sources (source-defs config)))
{:sources "foo"} "foo"
{:sources "bar", :comment "baz"} "bar"
["foo" "bar"] ["foo" "bar"]))
(deftest test-round-trip-validation-error
(are [data okay substrings]
(validation-is-correct
(#'hesokuri.config/round-trip-validation-error data) okay substrings)
["ok"] true []
[nil nil] true []
[true false] true []
{true :keyword, false 1.5} true []
[#{} #{} #{}] true []
[(list 'foo 'bar)] false ["(foo bar)"]
['(foo) "ok" '(bar)] false ["(foo)" "(bar)"]
#{[] [1] ["two"]} true []
{:a '(bad-value 1) :b '(bad-value 2)} false
["(bad-value 1)" "(bad-value 2)"]
{'(bad-key 1) :a '(bad-key 2) :b} false ["(bad-key 1)" "(bad-key 2)"]
{'(1) '(2) '(3) '(4)} false ["(1)" "(2)" "(3)" "(4)"]))
(deftest test-validation-error
(are [config okay substrings]
(validation-is-correct
(validation config) okay substrings)
*sources-eg* true []
*config-eg* true []
{:comment "missing sources"} false []
{:comment "sources is wrong type" :sources #{}} false []
{:comment ["not round-trippable" 'foo] :sources []} false ["foo"]
{:comment ["no sources is okay"] :sources []} true []
#{"must be a map or vector"} false ["PersistentHashSet"]
{:host-to-key [] :sources []} false [":host-to-key must be a map"]
{:host-to-key {"a" "b"} :sources []} false
,["must be a java.security.PublicKey"]))
(deftest test-normalize
(are [in out]
(= out (normalize in))
[] {:sources []}
[{"host" "/path"}]
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}
[{"host1" "/path1"}
{:host-to-path {"host2" "/path2"}
:unwanted-branches #{"a"}}]
{:sources [{:host-to-path {"host1" "/path1"}
:unwanted-branches {}}
{:host-to-path {"host2" "/path2"}
:unwanted-branches {"a" ["*"]}}]}
{:comment "foo"
:sources [{"host" "/path"}]}
{:comment "foo"
:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}))
(deftest test-from-file
(are [contents out]
(= out (from-file (temp-file-containing contents)))
"invalid!" nil
"{:sources []" nil
"{:sources [{:host-to-path {:fails-validation \"\"}}]}" nil
"{:sources [{\"host\" \"/path\"}]}"
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}
"{:sources [{:host-to-path {\"host\" \"/path\"}}]}"
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}))
| 92663 | ; Copyright (C) 2013 Google Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns hesokuri.config-test
(:require [clojure.test :refer :all]
[hesokuri.config :refer :all]
[hesokuri.testing.data :refer :all]
[hesokuri.testing.temp :refer :all]
[hesokuri.testing.validation :refer :all]))
(deftest test-source-defs
(are [config sources]
(is (= sources (source-defs config)))
{:sources "foo"} "foo"
{:sources "bar", :comment "baz"} "bar"
["foo" "bar"] ["foo" "bar"]))
(deftest test-round-trip-validation-error
(are [data okay substrings]
(validation-is-correct
(#'hesokuri.config/round-trip-validation-error data) okay substrings)
["ok"] true []
[nil nil] true []
[true false] true []
{true :keyword, false 1.5} true []
[#{} #{} #{}] true []
[(list 'foo 'bar)] false ["(foo bar)"]
['(foo) "ok" '(bar)] false ["(foo)" "(bar)"]
#{[] [1] ["two"]} true []
{:a '(bad-value 1) :b '(bad-value 2)} false
["(bad-value 1)" "(bad-value 2)"]
{'(bad-key 1) :a '(bad-key 2) :b} false ["(bad-key 1)" "(bad-key 2)"]
{'(1) '(2) '(3) '(4)} false ["(1)" "(2)" "(3)" "(4)"]))
(deftest test-validation-error
(are [config okay substrings]
(validation-is-correct
(validation config) okay substrings)
*sources-eg* true []
*config-eg* true []
{:comment "missing sources"} false []
{:comment "sources is wrong type" :sources #{}} false []
{:comment ["not round-trippable" 'foo] :sources []} false ["foo"]
{:comment ["no sources is okay"] :sources []} true []
#{"must be a map or vector"} false ["PersistentHashSet"]
{:host-to-key [] :sources []} false [":host-to-key must be a map"]
{:host-to-key {"a" "<KEY>"} :sources []} false
,["must be a java.security.PublicKey"]))
(deftest test-normalize
(are [in out]
(= out (normalize in))
[] {:sources []}
[{"host" "/path"}]
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}
[{"host1" "/path1"}
{:host-to-path {"host2" "/path2"}
:unwanted-branches #{"a"}}]
{:sources [{:host-to-path {"host1" "/path1"}
:unwanted-branches {}}
{:host-to-path {"host2" "/path2"}
:unwanted-branches {"a" ["*"]}}]}
{:comment "foo"
:sources [{"host" "/path"}]}
{:comment "foo"
:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}))
(deftest test-from-file
(are [contents out]
(= out (from-file (temp-file-containing contents)))
"invalid!" nil
"{:sources []" nil
"{:sources [{:host-to-path {:fails-validation \"\"}}]}" nil
"{:sources [{\"host\" \"/path\"}]}"
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}
"{:sources [{:host-to-path {\"host\" \"/path\"}}]}"
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}))
| true | ; Copyright (C) 2013 Google Inc.
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
(ns hesokuri.config-test
(:require [clojure.test :refer :all]
[hesokuri.config :refer :all]
[hesokuri.testing.data :refer :all]
[hesokuri.testing.temp :refer :all]
[hesokuri.testing.validation :refer :all]))
(deftest test-source-defs
(are [config sources]
(is (= sources (source-defs config)))
{:sources "foo"} "foo"
{:sources "bar", :comment "baz"} "bar"
["foo" "bar"] ["foo" "bar"]))
(deftest test-round-trip-validation-error
(are [data okay substrings]
(validation-is-correct
(#'hesokuri.config/round-trip-validation-error data) okay substrings)
["ok"] true []
[nil nil] true []
[true false] true []
{true :keyword, false 1.5} true []
[#{} #{} #{}] true []
[(list 'foo 'bar)] false ["(foo bar)"]
['(foo) "ok" '(bar)] false ["(foo)" "(bar)"]
#{[] [1] ["two"]} true []
{:a '(bad-value 1) :b '(bad-value 2)} false
["(bad-value 1)" "(bad-value 2)"]
{'(bad-key 1) :a '(bad-key 2) :b} false ["(bad-key 1)" "(bad-key 2)"]
{'(1) '(2) '(3) '(4)} false ["(1)" "(2)" "(3)" "(4)"]))
(deftest test-validation-error
(are [config okay substrings]
(validation-is-correct
(validation config) okay substrings)
*sources-eg* true []
*config-eg* true []
{:comment "missing sources"} false []
{:comment "sources is wrong type" :sources #{}} false []
{:comment ["not round-trippable" 'foo] :sources []} false ["foo"]
{:comment ["no sources is okay"] :sources []} true []
#{"must be a map or vector"} false ["PersistentHashSet"]
{:host-to-key [] :sources []} false [":host-to-key must be a map"]
{:host-to-key {"a" "PI:KEY:<KEY>END_PI"} :sources []} false
,["must be a java.security.PublicKey"]))
(deftest test-normalize
(are [in out]
(= out (normalize in))
[] {:sources []}
[{"host" "/path"}]
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}
[{"host1" "/path1"}
{:host-to-path {"host2" "/path2"}
:unwanted-branches #{"a"}}]
{:sources [{:host-to-path {"host1" "/path1"}
:unwanted-branches {}}
{:host-to-path {"host2" "/path2"}
:unwanted-branches {"a" ["*"]}}]}
{:comment "foo"
:sources [{"host" "/path"}]}
{:comment "foo"
:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}))
(deftest test-from-file
(are [contents out]
(= out (from-file (temp-file-containing contents)))
"invalid!" nil
"{:sources []" nil
"{:sources [{:host-to-path {:fails-validation \"\"}}]}" nil
"{:sources [{\"host\" \"/path\"}]}"
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}
"{:sources [{:host-to-path {\"host\" \"/path\"}}]}"
{:sources [{:host-to-path {"host" "/path"}
:unwanted-branches {}}]}))
|
[
{
"context": "universe\n :world counter-world}\n [:connect :Bob]\n [:connect :Alice])\n",
"end": 1017,
"score": 0.9967149496078491,
"start": 1014,
"tag": "NAME",
"value": "Bob"
},
{
"context": " counter-world}\n [:connect :Bob]\n [:connect :Alice])\n",
"end": 1037,
"score": 0.9980210065841675,
"start": 1032,
"tag": "NAME",
"value": "Alice"
}
] | src/goatverse/examples/counter_world.cljs | wanderley/goatverse | 0 | (ns goatverse.examples.counter-world
(:require [goatverse.core.test-universe :refer [defcard-universe]]
[goatverse.examples.counter-universe :refer [counter-universe]]))
(defmulti world-message (fn [type & _] type))
(defmethod world-message 'world-id [_ state _]
{:state state})
(defmethod world-message :state [_ state new-state]
{:state new-state})
(defmethod world-message :inc [_ state]
{:universe-dispatch [:inc]})
(defmethod world-message :dec [_ state]
{:universe-dispatch [:dec]})
(defn counter [state dispatch]
[:div
[:h1 "Counter"]
[:button {:on-click #(dispatch :inc)} "+"]
[:span {:style {:display "inline-block"
:min-width "2em"
:text-align "center"}}
state]
[:button {:on-click #(dispatch :dec)} "-"]])
(defonce counter-world
{:initial-state 0
:on-render counter
:on-message world-message})
(defcard-universe two-clients-on-same-room
{:universe counter-universe
:world counter-world}
[:connect :Bob]
[:connect :Alice])
| 61001 | (ns goatverse.examples.counter-world
(:require [goatverse.core.test-universe :refer [defcard-universe]]
[goatverse.examples.counter-universe :refer [counter-universe]]))
(defmulti world-message (fn [type & _] type))
(defmethod world-message 'world-id [_ state _]
{:state state})
(defmethod world-message :state [_ state new-state]
{:state new-state})
(defmethod world-message :inc [_ state]
{:universe-dispatch [:inc]})
(defmethod world-message :dec [_ state]
{:universe-dispatch [:dec]})
(defn counter [state dispatch]
[:div
[:h1 "Counter"]
[:button {:on-click #(dispatch :inc)} "+"]
[:span {:style {:display "inline-block"
:min-width "2em"
:text-align "center"}}
state]
[:button {:on-click #(dispatch :dec)} "-"]])
(defonce counter-world
{:initial-state 0
:on-render counter
:on-message world-message})
(defcard-universe two-clients-on-same-room
{:universe counter-universe
:world counter-world}
[:connect :<NAME>]
[:connect :<NAME>])
| true | (ns goatverse.examples.counter-world
(:require [goatverse.core.test-universe :refer [defcard-universe]]
[goatverse.examples.counter-universe :refer [counter-universe]]))
(defmulti world-message (fn [type & _] type))
(defmethod world-message 'world-id [_ state _]
{:state state})
(defmethod world-message :state [_ state new-state]
{:state new-state})
(defmethod world-message :inc [_ state]
{:universe-dispatch [:inc]})
(defmethod world-message :dec [_ state]
{:universe-dispatch [:dec]})
(defn counter [state dispatch]
[:div
[:h1 "Counter"]
[:button {:on-click #(dispatch :inc)} "+"]
[:span {:style {:display "inline-block"
:min-width "2em"
:text-align "center"}}
state]
[:button {:on-click #(dispatch :dec)} "-"]])
(defonce counter-world
{:initial-state 0
:on-render counter
:on-message world-message})
(defcard-universe two-clients-on-same-room
{:universe counter-universe
:world counter-world}
[:connect :PI:NAME:<NAME>END_PI]
[:connect :PI:NAME:<NAME>END_PI])
|
[
{
"context": "fake-config)))))\n\n(deftest test-send\n (let [key \"abc\"\n value 42\n\n producer-mock (mkto/re",
"end": 1503,
"score": 0.9977039098739624,
"start": 1500,
"tag": "KEY",
"value": "abc"
}
] | clstreams/test/clstreams/kafka/component_test.clj | MartinSoto/clojure-streams | 5 | (ns clstreams.kafka.component-test
(:require [clojure.test :refer :all]
[clstreams.kafka.component :as sut]
[clstreams.testutil.component :as tu-comp]
[clstreams.testutil.mockito :as mkto])
(:import [org.apache.kafka.clients.producer KafkaProducer ProducerRecord]
org.apache.kafka.streams.KafkaStreams
org.apache.kafka.streams.kstream.KStreamBuilder))
(def fake-config {"ze.config.option" "ze config value"})
(def prod-topic-name "ze-topic")
(deftest test-cycle-producer-component
(let [producer-mock (mkto/mock KafkaProducer)
kafka-producer-fn (mkto/on-call (mkto/mock-fn) [fake-config] producer-mock)]
(with-redefs [sut/kafka-producer kafka-producer-fn]
(tu-comp/cycle-component
[{:keys [config topic-name producer]} (sut/new-producer prod-topic-name fake-config)]
((is (= config fake-config))
(is (= topic-name prod-topic-name))
(is (nil? producer)))
[{:keys [producer]}]
((is (= producer producer-mock)))
[{:keys [producer]}]
((is (nil? producer))
(mkto/verify-> producer-mock .close))))))
(deftest test-idempotent-producer-component
(let [producer-mock (mkto/mock KafkaProducer)
kafka-producer-fn (mkto/on-call (mkto/mock-fn) [fake-config] producer-mock)]
(with-redefs [sut/kafka-producer kafka-producer-fn]
(tu-comp/check-idempotence (sut/new-producer prod-topic-name fake-config)))))
(deftest test-send
(let [key "abc"
value 42
producer-mock (mkto/return-> (mkto/mock KafkaProducer)
(.send (ProducerRecord. prod-topic-name key value))
(future :the-answer))
prod-system (assoc (sut/new-producer prod-topic-name fake-config)
:producer producer-mock)]
(is (= (sut/producer-send! prod-system [key value]) [:the-answer]))))
(deftest test-cycle-topology-component
(let [builder-mock (mkto/mock KStreamBuilder)
kstreams-mock (mkto/mock KafkaStreams)
kafka-streams-fn (mkto/on-call (mkto/mock-fn)
[builder-mock fake-config] kstreams-mock)]
(with-redefs [sut/kafka-streams kafka-streams-fn]
(tu-comp/cycle-component
[{:keys [config builder kstreams]} (sut/new-topology fake-config builder-mock)]
((is (= config fake-config))
(is (= builder builder-mock))
(is (nil? kstreams)))
[{:keys [kstreams]}]
((is (= kstreams kstreams-mock)))
[{:keys [kstreams]}]
((is (nil? kstreams))
(mkto/verify-> kstreams-mock .close))))))
(deftest test-idempotent-topology-component
(let [builder-mock (mkto/mock KStreamBuilder)
kstreams-mock (mkto/mock KafkaStreams)
kafka-streams-fn (mkto/on-call (mkto/mock-fn)
[builder-mock fake-config] kstreams-mock)]
(with-redefs [sut/kafka-streams kafka-streams-fn]
(tu-comp/check-idempotence (sut/new-topology fake-config builder-mock)))))
| 64992 | (ns clstreams.kafka.component-test
(:require [clojure.test :refer :all]
[clstreams.kafka.component :as sut]
[clstreams.testutil.component :as tu-comp]
[clstreams.testutil.mockito :as mkto])
(:import [org.apache.kafka.clients.producer KafkaProducer ProducerRecord]
org.apache.kafka.streams.KafkaStreams
org.apache.kafka.streams.kstream.KStreamBuilder))
(def fake-config {"ze.config.option" "ze config value"})
(def prod-topic-name "ze-topic")
(deftest test-cycle-producer-component
(let [producer-mock (mkto/mock KafkaProducer)
kafka-producer-fn (mkto/on-call (mkto/mock-fn) [fake-config] producer-mock)]
(with-redefs [sut/kafka-producer kafka-producer-fn]
(tu-comp/cycle-component
[{:keys [config topic-name producer]} (sut/new-producer prod-topic-name fake-config)]
((is (= config fake-config))
(is (= topic-name prod-topic-name))
(is (nil? producer)))
[{:keys [producer]}]
((is (= producer producer-mock)))
[{:keys [producer]}]
((is (nil? producer))
(mkto/verify-> producer-mock .close))))))
(deftest test-idempotent-producer-component
(let [producer-mock (mkto/mock KafkaProducer)
kafka-producer-fn (mkto/on-call (mkto/mock-fn) [fake-config] producer-mock)]
(with-redefs [sut/kafka-producer kafka-producer-fn]
(tu-comp/check-idempotence (sut/new-producer prod-topic-name fake-config)))))
(deftest test-send
(let [key "<KEY>"
value 42
producer-mock (mkto/return-> (mkto/mock KafkaProducer)
(.send (ProducerRecord. prod-topic-name key value))
(future :the-answer))
prod-system (assoc (sut/new-producer prod-topic-name fake-config)
:producer producer-mock)]
(is (= (sut/producer-send! prod-system [key value]) [:the-answer]))))
(deftest test-cycle-topology-component
(let [builder-mock (mkto/mock KStreamBuilder)
kstreams-mock (mkto/mock KafkaStreams)
kafka-streams-fn (mkto/on-call (mkto/mock-fn)
[builder-mock fake-config] kstreams-mock)]
(with-redefs [sut/kafka-streams kafka-streams-fn]
(tu-comp/cycle-component
[{:keys [config builder kstreams]} (sut/new-topology fake-config builder-mock)]
((is (= config fake-config))
(is (= builder builder-mock))
(is (nil? kstreams)))
[{:keys [kstreams]}]
((is (= kstreams kstreams-mock)))
[{:keys [kstreams]}]
((is (nil? kstreams))
(mkto/verify-> kstreams-mock .close))))))
(deftest test-idempotent-topology-component
(let [builder-mock (mkto/mock KStreamBuilder)
kstreams-mock (mkto/mock KafkaStreams)
kafka-streams-fn (mkto/on-call (mkto/mock-fn)
[builder-mock fake-config] kstreams-mock)]
(with-redefs [sut/kafka-streams kafka-streams-fn]
(tu-comp/check-idempotence (sut/new-topology fake-config builder-mock)))))
| true | (ns clstreams.kafka.component-test
(:require [clojure.test :refer :all]
[clstreams.kafka.component :as sut]
[clstreams.testutil.component :as tu-comp]
[clstreams.testutil.mockito :as mkto])
(:import [org.apache.kafka.clients.producer KafkaProducer ProducerRecord]
org.apache.kafka.streams.KafkaStreams
org.apache.kafka.streams.kstream.KStreamBuilder))
(def fake-config {"ze.config.option" "ze config value"})
(def prod-topic-name "ze-topic")
(deftest test-cycle-producer-component
(let [producer-mock (mkto/mock KafkaProducer)
kafka-producer-fn (mkto/on-call (mkto/mock-fn) [fake-config] producer-mock)]
(with-redefs [sut/kafka-producer kafka-producer-fn]
(tu-comp/cycle-component
[{:keys [config topic-name producer]} (sut/new-producer prod-topic-name fake-config)]
((is (= config fake-config))
(is (= topic-name prod-topic-name))
(is (nil? producer)))
[{:keys [producer]}]
((is (= producer producer-mock)))
[{:keys [producer]}]
((is (nil? producer))
(mkto/verify-> producer-mock .close))))))
(deftest test-idempotent-producer-component
(let [producer-mock (mkto/mock KafkaProducer)
kafka-producer-fn (mkto/on-call (mkto/mock-fn) [fake-config] producer-mock)]
(with-redefs [sut/kafka-producer kafka-producer-fn]
(tu-comp/check-idempotence (sut/new-producer prod-topic-name fake-config)))))
(deftest test-send
(let [key "PI:KEY:<KEY>END_PI"
value 42
producer-mock (mkto/return-> (mkto/mock KafkaProducer)
(.send (ProducerRecord. prod-topic-name key value))
(future :the-answer))
prod-system (assoc (sut/new-producer prod-topic-name fake-config)
:producer producer-mock)]
(is (= (sut/producer-send! prod-system [key value]) [:the-answer]))))
(deftest test-cycle-topology-component
(let [builder-mock (mkto/mock KStreamBuilder)
kstreams-mock (mkto/mock KafkaStreams)
kafka-streams-fn (mkto/on-call (mkto/mock-fn)
[builder-mock fake-config] kstreams-mock)]
(with-redefs [sut/kafka-streams kafka-streams-fn]
(tu-comp/cycle-component
[{:keys [config builder kstreams]} (sut/new-topology fake-config builder-mock)]
((is (= config fake-config))
(is (= builder builder-mock))
(is (nil? kstreams)))
[{:keys [kstreams]}]
((is (= kstreams kstreams-mock)))
[{:keys [kstreams]}]
((is (nil? kstreams))
(mkto/verify-> kstreams-mock .close))))))
(deftest test-idempotent-topology-component
(let [builder-mock (mkto/mock KStreamBuilder)
kstreams-mock (mkto/mock KafkaStreams)
kafka-streams-fn (mkto/on-call (mkto/mock-fn)
[builder-mock fake-config] kstreams-mock)]
(with-redefs [sut/kafka-streams kafka-streams-fn]
(tu-comp/check-idempotence (sut/new-topology fake-config builder-mock)))))
|
[
{
"context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License",
"end": 49,
"score": 0.9998882412910461,
"start": 37,
"tag": "NAME",
"value": "Ronen Narkis"
},
{
"context": "omment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version ",
"end": 62,
"score": 0.8672409653663635,
"start": 52,
"tag": "EMAIL",
"value": "arkisr.com"
}
] | src/re_core/persistency/common.clj | celestial-ops/core | 1 | (comment
re-core, Copyright 2012 Ronen Narkis, narkisr.com
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns re-core.persistency.common
"common persistency layer functions"
(:require
[clojure.string :refer (escape)]))
(defn args-of [s]
"grab args from string"
(into #{} (map #(escape % {\~ "" \{ "" \} ""}) (re-seq #"~\{\w+\}" s))))
(defn with-transform [t f & [a1 a2 & r :as args]]
(cond
(map? a1) (apply f (t a1) r)
(map? a2) (apply f a1 (t a2) r)
:else (apply f args)))
| 1960 | (comment
re-core, Copyright 2012 <NAME>, n<EMAIL>
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns re-core.persistency.common
"common persistency layer functions"
(:require
[clojure.string :refer (escape)]))
(defn args-of [s]
"grab args from string"
(into #{} (map #(escape % {\~ "" \{ "" \} ""}) (re-seq #"~\{\w+\}" s))))
(defn with-transform [t f & [a1 a2 & r :as args]]
(cond
(map? a1) (apply f (t a1) r)
(map? a2) (apply f a1 (t a2) r)
:else (apply f args)))
| true | (comment
re-core, Copyright 2012 PI:NAME:<NAME>END_PI, nPI:EMAIL:<EMAIL>END_PI
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns re-core.persistency.common
"common persistency layer functions"
(:require
[clojure.string :refer (escape)]))
(defn args-of [s]
"grab args from string"
(into #{} (map #(escape % {\~ "" \{ "" \} ""}) (re-seq #"~\{\w+\}" s))))
(defn with-transform [t f & [a1 a2 & r :as args]]
(cond
(map? a1) (apply f (t a1) r)
(map? a2) (apply f a1 (t a2) r)
:else (apply f args)))
|
[
{
"context": "ts&cacheRSMetadata=true\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n ",
"end": 968,
"score": 0.6718233227729797,
"start": 953,
"tag": "USERNAME",
"value": "benchmarkdbuser"
},
{
"context": "er \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n ;;OPTIONAL KEYS\n ",
"end": 1014,
"score": 0.9993376731872559,
"start": 999,
"tag": "PASSWORD",
"value": "benchmarkdbpass"
},
{
"context": "seServerPrepStmts&cacheRSMetadata=true\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"})\n\n(defn pool\n [",
"end": 2465,
"score": 0.7966084480285645,
"start": 2450,
"tag": "USERNAME",
"value": "benchmarkdbuser"
},
{
"context": "ta=true\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"})\n\n(defn pool\n [spec]\n (let [cpds (doto (Combo",
"end": 2496,
"score": 0.9993298649787903,
"start": 2481,
"tag": "PASSWORD",
"value": "benchmarkdbpass"
}
] | compojure/hello/src/hello/handler.clj | MalcolmEvershed/FrameworkBenchmarks | 1 | (ns hello.handler
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:use compojure.core
ring.middleware.json
ring.util.response
korma.db
korma.core
hiccup.core
hiccup.util)
(:require [compojure.handler :as handler]
[compojure.route :as route]
[clojure.java.jdbc :as jdbc]
[clojure.java.jdbc.sql :as sql]
[net.cgrand.enlive-html :as html]))
; 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
}))
; Set up entity World and the database representation
(defentity world
(pk :id)
(table :world)
(entity-fields :id :randomNumber)
(database db))
; Query a random World record from the database
(defn get-world []
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(select world
(fields :id :randomNumber)
(where {:id id }))))
; Run the specified number of queries, return the results
(defn run-queries [queries]
(vec ; Return as a vector
(flatten ; Make it a list of maps
(take
queries ; Number of queries to run
(repeatedly get-world)))))
; 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"})
(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)
; Query a random World record from the database
(defn get-world-raw []
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(jdbc/with-connection (db-raw)
(jdbc/with-query-results rs [(str "select * from world where id = ?") id]
(doall rs)))))
; Run the specified number of queries, return the results
(defn run-queries-raw [queries]
(vec ; Return as a vector
(flatten ; Make it a list of maps
(take
queries ; Number of queries to run
(repeatedly get-world-raw)))))
(defn get-query-count [queries]
"Parse provided string value of query count, clamping values to between 1 and 500."
(let [q (try (Integer/parseInt queries)
(catch Exception e 1))] ; default to 1 on parse failure
(if (> q 500)
500 ; clamp to 500 max
(if (< q 1)
1 ; clamp to 1 min
q)))) ; otherwise use provided value
; Set up entity World and the database representation
(defentity fortune
(pk :id)
(table :fortune)
(entity-fields :id :message)
(database db))
(defn get-all-fortunes []
"Query all Fortune records from the database."
(select fortune
(fields :id :message)))
(defn get-fortunes []
"Fetch the full list of Fortunes from the database, sort them by the fortune
message text, and then return the results."
(let [fortunes (conj (get-all-fortunes) {:id 0 :message "Additional fortune added at request time."} )]
(sort-by #(:message %) fortunes)))
(defn fortunes-hiccup [fortunes]
"Render the given fortunes to simple HTML using Hiccup."
(html
[:head
[:title "Fortunes"]]
[:body
[:table
[:tr
[:th "id"]
[:th "message"]]
(for [x fortunes]
[:tr
[:td (:id x)]
[:td (escape-html (:message x))]])
]]))
(defn fortunes-enlive [fortunes]
"Render the given fortunes to simple HTML using Enlive."
"todo")
; Define route handlers
(defroutes app-routes
(GET "/" [] "Hello, World!")
(GET "/plaintext" []
{:status 200
:headers {"Content-Type" "text/plain; charset=utf-8"}
:body "Hello, World!"})
(GET "/json" [] (response {:message "Hello, World!"}))
(GET "/db/:queries" [queries] (response (run-queries (get-query-count queries))))
(GET "/dbraw/:queries" [queries] (response (run-queries-raw (get-query-count queries))))
(GET "/fortune" [] (response (get-fortunes)))
(GET "/fortune-hiccup" [] (fortunes-hiccup (get-fortunes)))
(GET "/fortune-enlive" [] (fortunes-enlive (get-fortunes)))
(route/not-found "Not Found"))
; Format responses as JSON
(def app
(wrap-json-response app-routes))
| 25809 | (ns hello.handler
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:use compojure.core
ring.middleware.json
ring.util.response
korma.db
korma.core
hiccup.core
hiccup.util)
(:require [compojure.handler :as handler]
[compojure.route :as route]
[clojure.java.jdbc :as jdbc]
[clojure.java.jdbc.sql :as sql]
[net.cgrand.enlive-html :as html]))
; 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
}))
; Set up entity World and the database representation
(defentity world
(pk :id)
(table :world)
(entity-fields :id :randomNumber)
(database db))
; Query a random World record from the database
(defn get-world []
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(select world
(fields :id :randomNumber)
(where {:id id }))))
; Run the specified number of queries, return the results
(defn run-queries [queries]
(vec ; Return as a vector
(flatten ; Make it a list of maps
(take
queries ; Number of queries to run
(repeatedly get-world)))))
; 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>"})
(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)
; Query a random World record from the database
(defn get-world-raw []
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(jdbc/with-connection (db-raw)
(jdbc/with-query-results rs [(str "select * from world where id = ?") id]
(doall rs)))))
; Run the specified number of queries, return the results
(defn run-queries-raw [queries]
(vec ; Return as a vector
(flatten ; Make it a list of maps
(take
queries ; Number of queries to run
(repeatedly get-world-raw)))))
(defn get-query-count [queries]
"Parse provided string value of query count, clamping values to between 1 and 500."
(let [q (try (Integer/parseInt queries)
(catch Exception e 1))] ; default to 1 on parse failure
(if (> q 500)
500 ; clamp to 500 max
(if (< q 1)
1 ; clamp to 1 min
q)))) ; otherwise use provided value
; Set up entity World and the database representation
(defentity fortune
(pk :id)
(table :fortune)
(entity-fields :id :message)
(database db))
(defn get-all-fortunes []
"Query all Fortune records from the database."
(select fortune
(fields :id :message)))
(defn get-fortunes []
"Fetch the full list of Fortunes from the database, sort them by the fortune
message text, and then return the results."
(let [fortunes (conj (get-all-fortunes) {:id 0 :message "Additional fortune added at request time."} )]
(sort-by #(:message %) fortunes)))
(defn fortunes-hiccup [fortunes]
"Render the given fortunes to simple HTML using Hiccup."
(html
[:head
[:title "Fortunes"]]
[:body
[:table
[:tr
[:th "id"]
[:th "message"]]
(for [x fortunes]
[:tr
[:td (:id x)]
[:td (escape-html (:message x))]])
]]))
(defn fortunes-enlive [fortunes]
"Render the given fortunes to simple HTML using Enlive."
"todo")
; Define route handlers
(defroutes app-routes
(GET "/" [] "Hello, World!")
(GET "/plaintext" []
{:status 200
:headers {"Content-Type" "text/plain; charset=utf-8"}
:body "Hello, World!"})
(GET "/json" [] (response {:message "Hello, World!"}))
(GET "/db/:queries" [queries] (response (run-queries (get-query-count queries))))
(GET "/dbraw/:queries" [queries] (response (run-queries-raw (get-query-count queries))))
(GET "/fortune" [] (response (get-fortunes)))
(GET "/fortune-hiccup" [] (fortunes-hiccup (get-fortunes)))
(GET "/fortune-enlive" [] (fortunes-enlive (get-fortunes)))
(route/not-found "Not Found"))
; Format responses as JSON
(def app
(wrap-json-response app-routes))
| true | (ns hello.handler
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:use compojure.core
ring.middleware.json
ring.util.response
korma.db
korma.core
hiccup.core
hiccup.util)
(:require [compojure.handler :as handler]
[compojure.route :as route]
[clojure.java.jdbc :as jdbc]
[clojure.java.jdbc.sql :as sql]
[net.cgrand.enlive-html :as html]))
; 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
}))
; Set up entity World and the database representation
(defentity world
(pk :id)
(table :world)
(entity-fields :id :randomNumber)
(database db))
; Query a random World record from the database
(defn get-world []
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(select world
(fields :id :randomNumber)
(where {:id id }))))
; Run the specified number of queries, return the results
(defn run-queries [queries]
(vec ; Return as a vector
(flatten ; Make it a list of maps
(take
queries ; Number of queries to run
(repeatedly get-world)))))
; 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"})
(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)
; Query a random World record from the database
(defn get-world-raw []
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(jdbc/with-connection (db-raw)
(jdbc/with-query-results rs [(str "select * from world where id = ?") id]
(doall rs)))))
; Run the specified number of queries, return the results
(defn run-queries-raw [queries]
(vec ; Return as a vector
(flatten ; Make it a list of maps
(take
queries ; Number of queries to run
(repeatedly get-world-raw)))))
(defn get-query-count [queries]
"Parse provided string value of query count, clamping values to between 1 and 500."
(let [q (try (Integer/parseInt queries)
(catch Exception e 1))] ; default to 1 on parse failure
(if (> q 500)
500 ; clamp to 500 max
(if (< q 1)
1 ; clamp to 1 min
q)))) ; otherwise use provided value
; Set up entity World and the database representation
(defentity fortune
(pk :id)
(table :fortune)
(entity-fields :id :message)
(database db))
(defn get-all-fortunes []
"Query all Fortune records from the database."
(select fortune
(fields :id :message)))
(defn get-fortunes []
"Fetch the full list of Fortunes from the database, sort them by the fortune
message text, and then return the results."
(let [fortunes (conj (get-all-fortunes) {:id 0 :message "Additional fortune added at request time."} )]
(sort-by #(:message %) fortunes)))
(defn fortunes-hiccup [fortunes]
"Render the given fortunes to simple HTML using Hiccup."
(html
[:head
[:title "Fortunes"]]
[:body
[:table
[:tr
[:th "id"]
[:th "message"]]
(for [x fortunes]
[:tr
[:td (:id x)]
[:td (escape-html (:message x))]])
]]))
(defn fortunes-enlive [fortunes]
"Render the given fortunes to simple HTML using Enlive."
"todo")
; Define route handlers
(defroutes app-routes
(GET "/" [] "Hello, World!")
(GET "/plaintext" []
{:status 200
:headers {"Content-Type" "text/plain; charset=utf-8"}
:body "Hello, World!"})
(GET "/json" [] (response {:message "Hello, World!"}))
(GET "/db/:queries" [queries] (response (run-queries (get-query-count queries))))
(GET "/dbraw/:queries" [queries] (response (run-queries-raw (get-query-count queries))))
(GET "/fortune" [] (response (get-fortunes)))
(GET "/fortune-hiccup" [] (fortunes-hiccup (get-fortunes)))
(GET "/fortune-enlive" [] (fortunes-enlive (get-fortunes)))
(route/not-found "Not Found"))
; Format responses as JSON
(def app
(wrap-json-response app-routes))
|
[
{
"context": "s\n; Date: February 11, 2016.\n; Authors:\n; A0102031 Fernando Gómez Herrera\n;------------------------",
"end": 151,
"score": 0.993075966835022,
"start": 144,
"tag": "USERNAME",
"value": "A010203"
},
{
"context": " February 11, 2016.\n; Authors:\n; A0102031 Fernando Gómez Herrera\n;------------------------------------------------",
"end": 175,
"score": 0.9998739957809448,
"start": 153,
"tag": "NAME",
"value": "Fernando Gómez Herrera"
}
] | highorder.clj | gomezhyuuga/CEM_tc2006 | 1 | ;----------------------------------------------------------
; Activity: Higher-Order Functions
; Date: February 11, 2016.
; Authors:
; A0102031 Fernando Gómez Herrera
;----------------------------------------------------------
(use 'clojure.test)
(defn my-map-indexed
"Takes two arguments: a function f and a list lst. It returns a list
consisting of the result of applying f to 0 and the first item of lst,
followed by applying f to 1 and the second item in lst, and so on until lst
is exhausted. Function f should accept 2 arguments: index and item."
[f lst]
(loop [result ()
coll lst
index 0]
(if (empty? coll)
(reverse result)
(recur (cons (f index (first coll)) result) (rest coll) (inc index)))))
(defn my-drop-while
"Takes two arguments: a function f and a list lst. It returns a list of items
from lst dropping the initial items that evaluate to true when passed to f.
Once a false value is encountered, the rest of the list is returned. Function
f should accept one argument."
[f lst]
(loop [result ()
coll lst]
(if (empty? coll)
(reverse result)
(if (f (first coll))
(recur result (rest coll))
coll))))
(defn bisection
[a b f]
(loop [a a b b c (/ (+ a b) 2)]
; The algorithm must stop when a value of c is found such that: |f(c)| < 1.0×10-15.
(if (< (Math/abs (float (f c))) 1E-15)
c
; f(a) and f(c) have opposite signs
(if (< (* (f a) (f c)) 0)
(recur a c (/ (+ a b) 2))
; f(c) and f(b) have opposite signs
(recur c b (/ (+ c b) 2))))))
(defn deriv
"Takes f and h as its arguments, and returns a new function that takes x as
argument, and which represents the derivate of f given a certain value for h."
[f h]
(fn [x] (/ (- (f (+ x h)) (f x)) h)))
(defn integral
[a b n f]
(let [h (/ (- b a) n)
d (/ h 3)
y0 (f a)
yn (f b)]
(* d (+ y0 yn
(reduce + (for [k (range 1 n)
:let [yk (f (+ a (* k h)))
coef (if (even? k) 2 4)]]
(* coef yk)))))))
(defn aprox=
"Checks if x is approximately equal to y. Returns true
if |x - y| < epsilon, or false otherwise."
[epsilon x y]
(< (Math/abs (- x y)) epsilon))
(deftest test-my-map-indexed
(is (= () (my-map-indexed vector ())))
(is (= '([0 a] [1 b] [2 c] [3 d])
(my-map-indexed vector '(a b c d))))
(is (= '(10 4 -2 8 5 5 13)
(my-map-indexed + '(10 3 -4 5 1 0 7))))
(is (= '(0 1 -4 3 1 0 6)
(my-map-indexed min '(10 3 -4 5 1 0 7)))))
(deftest test-my-drop-while
(is (= () (my-drop-while neg? ())))
(is (= '(0 1 2 3 4)
(my-drop-while
neg?
'(-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4))))
(is (= '(2 three 4 five)
(my-drop-while
symbol?
'(zero one 2 three 4 five))))
(is (= '(0 one 2 three 4 five)
(my-drop-while
symbol?
'(0 one 2 three 4 five)))))
(deftest test-bisection
(is (aprox= 0.0001 3.0 (bisection 1 4 (fn [x] (* (- x 3) (+ x 4))))))
(is (aprox= 0.0001 -4.0 (bisection -5 0 (fn [x] (* (- x 3) (+ x 4))))))
(is (aprox= 0.0001 Math/PI (bisection 1 4 (fn [x] (Math/sin x)))))
(is (aprox= 0.0001 (* 2 Math/PI) (bisection 5 10 (fn [x] (Math/sin x)))))
(is (aprox= 0.0001 1.618033988749895
(bisection 1 2 (fn [x] (- (* x x) x 1)))))
(is (aprox= 0.0001 -0.6180339887498948
(bisection -10 1 (fn [x] (- (* x x) x 1))))))
(defn f [x] (* x x x))
(def df (deriv f 0.001))
(def ddf (deriv df 0.001))
(def dddf (deriv ddf 0.001))
(deftest test-deriv
(is (aprox= 0.05 75 (df 5)))
(is (aprox= 0.05 30 (ddf 5)))
(is (aprox= 0.05 6 (dddf 5))))
(deftest test-integral
(is (= 1/4 (integral 0 1 10 (fn [x] (* x x x)))))
(is (= 21/4
(integral 1 2 10
(fn [x]
(integral 3 4 10
(fn [y]
(* x y))))))))
(run-tests)
| 96048 | ;----------------------------------------------------------
; Activity: Higher-Order Functions
; Date: February 11, 2016.
; Authors:
; A0102031 <NAME>
;----------------------------------------------------------
(use 'clojure.test)
(defn my-map-indexed
"Takes two arguments: a function f and a list lst. It returns a list
consisting of the result of applying f to 0 and the first item of lst,
followed by applying f to 1 and the second item in lst, and so on until lst
is exhausted. Function f should accept 2 arguments: index and item."
[f lst]
(loop [result ()
coll lst
index 0]
(if (empty? coll)
(reverse result)
(recur (cons (f index (first coll)) result) (rest coll) (inc index)))))
(defn my-drop-while
"Takes two arguments: a function f and a list lst. It returns a list of items
from lst dropping the initial items that evaluate to true when passed to f.
Once a false value is encountered, the rest of the list is returned. Function
f should accept one argument."
[f lst]
(loop [result ()
coll lst]
(if (empty? coll)
(reverse result)
(if (f (first coll))
(recur result (rest coll))
coll))))
(defn bisection
[a b f]
(loop [a a b b c (/ (+ a b) 2)]
; The algorithm must stop when a value of c is found such that: |f(c)| < 1.0×10-15.
(if (< (Math/abs (float (f c))) 1E-15)
c
; f(a) and f(c) have opposite signs
(if (< (* (f a) (f c)) 0)
(recur a c (/ (+ a b) 2))
; f(c) and f(b) have opposite signs
(recur c b (/ (+ c b) 2))))))
(defn deriv
"Takes f and h as its arguments, and returns a new function that takes x as
argument, and which represents the derivate of f given a certain value for h."
[f h]
(fn [x] (/ (- (f (+ x h)) (f x)) h)))
(defn integral
[a b n f]
(let [h (/ (- b a) n)
d (/ h 3)
y0 (f a)
yn (f b)]
(* d (+ y0 yn
(reduce + (for [k (range 1 n)
:let [yk (f (+ a (* k h)))
coef (if (even? k) 2 4)]]
(* coef yk)))))))
(defn aprox=
"Checks if x is approximately equal to y. Returns true
if |x - y| < epsilon, or false otherwise."
[epsilon x y]
(< (Math/abs (- x y)) epsilon))
(deftest test-my-map-indexed
(is (= () (my-map-indexed vector ())))
(is (= '([0 a] [1 b] [2 c] [3 d])
(my-map-indexed vector '(a b c d))))
(is (= '(10 4 -2 8 5 5 13)
(my-map-indexed + '(10 3 -4 5 1 0 7))))
(is (= '(0 1 -4 3 1 0 6)
(my-map-indexed min '(10 3 -4 5 1 0 7)))))
(deftest test-my-drop-while
(is (= () (my-drop-while neg? ())))
(is (= '(0 1 2 3 4)
(my-drop-while
neg?
'(-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4))))
(is (= '(2 three 4 five)
(my-drop-while
symbol?
'(zero one 2 three 4 five))))
(is (= '(0 one 2 three 4 five)
(my-drop-while
symbol?
'(0 one 2 three 4 five)))))
(deftest test-bisection
(is (aprox= 0.0001 3.0 (bisection 1 4 (fn [x] (* (- x 3) (+ x 4))))))
(is (aprox= 0.0001 -4.0 (bisection -5 0 (fn [x] (* (- x 3) (+ x 4))))))
(is (aprox= 0.0001 Math/PI (bisection 1 4 (fn [x] (Math/sin x)))))
(is (aprox= 0.0001 (* 2 Math/PI) (bisection 5 10 (fn [x] (Math/sin x)))))
(is (aprox= 0.0001 1.618033988749895
(bisection 1 2 (fn [x] (- (* x x) x 1)))))
(is (aprox= 0.0001 -0.6180339887498948
(bisection -10 1 (fn [x] (- (* x x) x 1))))))
(defn f [x] (* x x x))
(def df (deriv f 0.001))
(def ddf (deriv df 0.001))
(def dddf (deriv ddf 0.001))
(deftest test-deriv
(is (aprox= 0.05 75 (df 5)))
(is (aprox= 0.05 30 (ddf 5)))
(is (aprox= 0.05 6 (dddf 5))))
(deftest test-integral
(is (= 1/4 (integral 0 1 10 (fn [x] (* x x x)))))
(is (= 21/4
(integral 1 2 10
(fn [x]
(integral 3 4 10
(fn [y]
(* x y))))))))
(run-tests)
| true | ;----------------------------------------------------------
; Activity: Higher-Order Functions
; Date: February 11, 2016.
; Authors:
; A0102031 PI:NAME:<NAME>END_PI
;----------------------------------------------------------
(use 'clojure.test)
(defn my-map-indexed
"Takes two arguments: a function f and a list lst. It returns a list
consisting of the result of applying f to 0 and the first item of lst,
followed by applying f to 1 and the second item in lst, and so on until lst
is exhausted. Function f should accept 2 arguments: index and item."
[f lst]
(loop [result ()
coll lst
index 0]
(if (empty? coll)
(reverse result)
(recur (cons (f index (first coll)) result) (rest coll) (inc index)))))
(defn my-drop-while
"Takes two arguments: a function f and a list lst. It returns a list of items
from lst dropping the initial items that evaluate to true when passed to f.
Once a false value is encountered, the rest of the list is returned. Function
f should accept one argument."
[f lst]
(loop [result ()
coll lst]
(if (empty? coll)
(reverse result)
(if (f (first coll))
(recur result (rest coll))
coll))))
(defn bisection
[a b f]
(loop [a a b b c (/ (+ a b) 2)]
; The algorithm must stop when a value of c is found such that: |f(c)| < 1.0×10-15.
(if (< (Math/abs (float (f c))) 1E-15)
c
; f(a) and f(c) have opposite signs
(if (< (* (f a) (f c)) 0)
(recur a c (/ (+ a b) 2))
; f(c) and f(b) have opposite signs
(recur c b (/ (+ c b) 2))))))
(defn deriv
"Takes f and h as its arguments, and returns a new function that takes x as
argument, and which represents the derivate of f given a certain value for h."
[f h]
(fn [x] (/ (- (f (+ x h)) (f x)) h)))
(defn integral
[a b n f]
(let [h (/ (- b a) n)
d (/ h 3)
y0 (f a)
yn (f b)]
(* d (+ y0 yn
(reduce + (for [k (range 1 n)
:let [yk (f (+ a (* k h)))
coef (if (even? k) 2 4)]]
(* coef yk)))))))
(defn aprox=
"Checks if x is approximately equal to y. Returns true
if |x - y| < epsilon, or false otherwise."
[epsilon x y]
(< (Math/abs (- x y)) epsilon))
(deftest test-my-map-indexed
(is (= () (my-map-indexed vector ())))
(is (= '([0 a] [1 b] [2 c] [3 d])
(my-map-indexed vector '(a b c d))))
(is (= '(10 4 -2 8 5 5 13)
(my-map-indexed + '(10 3 -4 5 1 0 7))))
(is (= '(0 1 -4 3 1 0 6)
(my-map-indexed min '(10 3 -4 5 1 0 7)))))
(deftest test-my-drop-while
(is (= () (my-drop-while neg? ())))
(is (= '(0 1 2 3 4)
(my-drop-while
neg?
'(-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4))))
(is (= '(2 three 4 five)
(my-drop-while
symbol?
'(zero one 2 three 4 five))))
(is (= '(0 one 2 three 4 five)
(my-drop-while
symbol?
'(0 one 2 three 4 five)))))
(deftest test-bisection
(is (aprox= 0.0001 3.0 (bisection 1 4 (fn [x] (* (- x 3) (+ x 4))))))
(is (aprox= 0.0001 -4.0 (bisection -5 0 (fn [x] (* (- x 3) (+ x 4))))))
(is (aprox= 0.0001 Math/PI (bisection 1 4 (fn [x] (Math/sin x)))))
(is (aprox= 0.0001 (* 2 Math/PI) (bisection 5 10 (fn [x] (Math/sin x)))))
(is (aprox= 0.0001 1.618033988749895
(bisection 1 2 (fn [x] (- (* x x) x 1)))))
(is (aprox= 0.0001 -0.6180339887498948
(bisection -10 1 (fn [x] (- (* x x) x 1))))))
(defn f [x] (* x x x))
(def df (deriv f 0.001))
(def ddf (deriv df 0.001))
(def dddf (deriv ddf 0.001))
(deftest test-deriv
(is (aprox= 0.05 75 (df 5)))
(is (aprox= 0.05 30 (ddf 5)))
(is (aprox= 0.05 6 (dddf 5))))
(deftest test-integral
(is (= 1/4 (integral 0 1 10 (fn [x] (* x x x)))))
(is (= 21/4
(integral 1 2 10
(fn [x]
(integral 3 4 10
(fn [y]
(* x y))))))))
(run-tests)
|
[
{
"context": "; Copyright (c) 2010-2021 Haifeng Li. All rights reserved.\n;\n; Smile is free softwar",
"end": 38,
"score": 0.999745786190033,
"start": 28,
"tag": "NAME",
"value": "Haifeng Li"
},
{
"context": "le.clustering\n \"Clustering Analysis\"\n {:author \"Haifeng Li\"}\n (:import [smile.clustering HierarchicalCluste",
"end": 765,
"score": 0.9997888207435608,
"start": 755,
"tag": "NAME",
"value": "Haifeng Li"
}
] | clojure/src/smile/clustering.clj | takanori-ugai/smile | 0 | ; Copyright (c) 2010-2021 Haifeng Li. All rights reserved.
;
; Smile is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; Smile is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with Smile. If not, see <https://www.gnu.org/licenses/>.
(ns smile.clustering
"Clustering Analysis"
{:author "Haifeng Li"}
(:import [smile.clustering HierarchicalClustering PartitionClustering
KMeans XMeans GMeans SIB DeterministicAnnealing
CLARANS DBSCAN DENCLUE MEC SpectralClustering]
[smile.clustering.linkage SingleLinkage CompleteLinkage
UPGMALinkage UPGMCLinkage
WPGMALinkage WPGMCLinkage WardLinkage]
[smile.math.distance EuclideanDistance]))
(defn hclust
"Agglomerative hierarchical clustering.
This method seeks to build a hierarchy of clusters in a bottom up approach:
each observation starts in its own cluster, and pairs of clusters are merged
as one moves up the hierarchy. The results of hierarchical clustering are
usually presented in a dendrogram.
In general, the merges are determined in a greedy manner. In order to decide
which clusters should be combined, a measure of dissimilarity between sets
of observations is required. In most methods of hierarchical clustering,
this is achieved by use of an appropriate metric, and a linkage criteria
which specifies the dissimilarity of sets as a function of the pairwise
distances of observations in the sets.
Hierarchical clustering has the distinct advantage that any valid measure
of distance can be used. In fact, the observations themselves are not
required: all that is used is a matrix of distances.
`data` is the data set.
`distance` is the distance/dissimilarity measure.
`method` is the agglomeration method to merge clusters. This should be one
of 'single', 'complete', 'upgma', 'upgmc', 'wpgma', 'wpgmc', and 'ward'."
[data method]
(let [linkage (case method
"single" (SingleLinkage/of data)
"complete" (CompleteLinkage/of data)
("upgma" "average") (UPGMALinkage/of data)
("upgmc" "centroid") (UPGMCLinkage/of data)
"wpgma" (WPGMALinkage/of data)
("wpgmc" "median") (WPGMCLinkage/of data)
"ward" (WardLinkage/of data)
(throw (IllegalArgumentException. (str "Unknown agglomeration method: " method))))]
(HierarchicalClustering/fit linkage)))
(defn kmeans
"K-Means clustering.
K-Means clustering. The algorithm partitions n observations into k clusters
in which each observation belongs to the cluster with the nearest mean.
Although finding an exact solution to the k-means problem for arbitrary
input is NP-hard, the standard approach to finding an approximate solution
(often called Lloyd's algorithm or the k-means algorithm) is used widely
and frequently finds reasonable solutions quickly.
However, the k-means algorithm has at least two major theoretic shortcomings:
- First, it has been shown that the worst case running time of the
algorithm is super-polynomial in the input size.
- Second, the approximation found can be arbitrarily bad with respect
to the objective function compared to the optimal learn.
In this implementation, we use k-means++ which addresses the second of these
obstacles by specifying a procedure to initialize the cluster centers before
proceeding with the standard k-means optimization iterations. With the
k-means++ initialization, the algorithm is guaranteed to find a solution
that is O(log k) competitive to the optimal k-means solution.
We also use k-d trees to speed up each k-means step as described in the
filter algorithm by Kanungo, et al.
K-means is a hard clustering method, i.e. each sample is assigned to
a specific cluster. In contrast, soft clustering, e.g. the
Expectation-Maximization algorithm for Gaussian mixtures, assign samples
to different clusters with different probabilities.
This method runs the algorithm for given times and return the best one with
smallest distortion.
`data` is the data set.
`k` is the number of clusters.
`max-iter` is the maximum number of iterations for each running.
`tol` is the tolerance of convergence test.
`runs` is the number of runs of K-Means algorithm."
([data k] (kmeans data k 100 1E-4 10))
([data k max-iter tol runs]
(PartitionClustering/run runs
(reify java.util.function.Supplier
(get [this] (KMeans/fit data k max-iter tol))))))
(defn xmeans
"X-Means clustering.
X-Means clustering algorithm is an extended K-Means which tries to
automatically determine the number of clusters based on BIC scores.
Starting with only one cluster, the X-Means algorithm goes into action
after each run of K-Means, making local decisions about which subset of the
current centroids should split themselves in order to better fit the data.
The splitting decision is done by computing the Bayesian Information
Criterion (BIC).
`data` is the data set.
`k` is the maximum number of clusters."
[data k] (XMeans/fit data k))
(defn gmeans
"G-Means clustering.
G-Means clustering algorithm is an extended K-Means which tries to
automatically determine the number of clusters by normality test.
The G-means algorithm is based on a statistical test for the hypothesis
that a subset of data follows a Gaussian distribution. G-means runs
k-means with increasing k in a hierarchical fashion until the test accepts
the hypothesis that the data assigned to each k-means center are Gaussian.
`data` is the data set.
`k` is the maximum number of clusters."
[data k] (GMeans/fit data k))
(defn sib
"Sequential Information Bottleneck algorithm.
SIB clusters co-occurrence data such as text documents vs words.
SIB is guaranteed to converge to a local maximum of the information.
Moreover, the time and space complexity are significantly improved
in contrast to the agglomerative IB algorithm.
In analogy to K-Means, SIB's update formulas are essentially same as the
EM algorithm for estimating finite Gaussian mixture model by replacing
regular Euclidean distance with Kullback-Leibler divergence, which is
clearly a better dissimilarity measure for co-occurrence data. However,
the common batch updating rule (assigning all instances to nearest centroids
and then updating centroids) of K-Means won't work in SIB, which has
to work in a sequential way (reassigning (if better) each instance then
immediately update related centroids). It might be because K-L divergence
is very sensitive and the centroids may be significantly changed in each
iteration in batch updating rule.
Note that this implementation has a little difference from the original
paper, in which a weighted Jensen-Shannon divergence is employed as a
criterion to assign a randomly-picked sample to a different cluster.
However, this doesn't work well in some cases as we experienced probably
because the weighted JS divergence gives too much weight to clusters which
is much larger than a single sample. In this implementation, we instead
use the regular/unweighted Jensen-Shannon divergence.
`data` is the data set.
`k` is the number of clusters.
`max-iter` is the maximum number of iterations.
`runs` is the number of runs of SIB algorithm."
([data k] (sib data k 100 8))
([data k max-iter runs]
(PartitionClustering/run runs
(reify java.util.function.Supplier
(get [this] (SIB/fit data k max-iter))))))
(defn dac
"Deterministic annealing clustering.
Deterministic annealing extends soft-clustering to an annealing process.
For each temperature value, the algorithm iterates between the calculation
of all posteriori probabilities and the update of the centroids vectors,
until convergence is reached. The annealing starts with a high temperature.
Here, all centroids vectors converge to the center of the pattern
distribution (independent of their initial positions). Below a critical
temperature the vectors start to split. Further decreasing the temperature
leads to more splittings until all centroids vectors are separate. The
annealing can therefore avoid (if it is sufficiently slow) the convergence
to local minima.
`data` is the data set.
`k` is the maximum number of clusters.
`alpha` is the temperature T is decreasing as T = T * alpha. alpha has
to be in (0, 1).
`tol` is the tolerance of convergence test.
`split-tol` is the tolerance to split a cluster."
([data k] (dac data k 0.9 100 1E-4 0.01))
([data k alpha max-iter tol split-tol]
(DeterministicAnnealing/fit data k alpha max-iter tol split-tol)))
(defn clarans
"Clustering Large Applications based upon RANdomized Search.
CLARANS is an efficient medoid-based clustering algorithm. The k-medoids
algorithm is an adaptation of the k-means algorithm. Rather than calculate
the mean of the items in each cluster, a representative item, or medoid, is
chosen for each cluster at each iteration. In CLARANS, the process of
finding k medoids from n objects is viewed abstractly as searching through
a certain graph. In the graph, a node is represented by a set of k objects
as selected medoids. Two nodes are neighbors if their sets differ by only
one object. In each iteration, CLARANS considers a set of randomly chosen
neighbor nodes as candidate of new medoids. We will move to the neighbor
node if the neighbor is a better choice for medoids. Otherwise, a local
optima is discovered. The entire process is repeated multiple time to find
better.
CLARANS has two parameters: the maximum number of neighbors examined
(maxNeighbor) and the number of local minima obtained (numLocal). The
higher the value of maxNeighbor, the closer is CLARANS to PAM, and the
longer is each search of a local minima. But the quality of such a local
minima is higher and fewer local minima needs to be obtained.
`data` is the data set.
`distance` is the distance/dissimilarity measure.
`k` is the number of clusters.
`max-neighbor` is the maximum number of neighbors examined during a random
search of local minima.
`num-local` is the number of local minima to search for."
([data distance k max-neighbor] (clarans data distance k max-neighbor 16))
([data distance k max-neighbor num-local]
(PartitionClustering/run num-local
(reify java.util.function.Supplier
(get [this] (CLARANS/fit data distance k max-neighbor))))))
(defn dbscan
"Density-Based Spatial Clustering of Applications with Noise.
DBSCAN finds a number of clusters starting from the estimated density
distribution of corresponding nodes.
DBSCAN requires two parameters: radius (i.e. neighborhood radius) and the
number of minimum points required to form a cluster (minPts). It starts
with an arbitrary starting point that has not been visited. This point's
neighborhood is retrieved, and if it contains sufficient number of points,
a cluster is started. Otherwise, the point is labeled as noise. Note that
this point might later be found in a sufficiently sized radius-environment
of a different point and hence be made part of a cluster.
If a point is found to be part of a cluster, its neighborhood is also
part of that cluster. Hence, all points that are found within the
neighborhood are added, as is their own neighborhood. This process
continues until the cluster is completely found. Then, a new unvisited point
is retrieved and processed, leading to the discovery of a further cluster
of noise.
DBSCAN visits each point of the database, possibly multiple times (e.g.,
as candidates to different clusters). For practical considerations, however,
the time complexity is mostly governed by the number of nearest neighbor
queries. DBSCAN executes exactly one such query for each point, and if
an indexing structure is used that executes such a neighborhood query
in O(log n), an overall runtime complexity of O(n log n) is obtained.
DBSCAN has many advantages such as
- DBSCAN does not need to know the number of clusters in the data
a priori, as opposed to k-means.
- DBSCAN can find arbitrarily shaped clusters. It can even find clusters
completely surrounded by (but not connected to) a different cluster.
Due to the MinPts parameter, the so-called single-link effect
(different clusters being connected by a thin line of points) is reduced.
- DBSCAN has a notion of noise.
- DBSCAN requires just two parameters and is mostly insensitive to the
ordering of the points in the database. (Only points sitting on the
edge of two different clusters might swap cluster membership if the
ordering of the points is changed, and the cluster assignment is unique
only up to isomorphism.)
On the other hand, DBSCAN has the disadvantages of
- In high dimensional space, the data are sparse everywhere
because of the curse of dimensionality. Therefore, DBSCAN doesn't
work well on high-dimensional data in general.
- DBSCAN does not respond well to data sets with varying densities.
`data` is the data set.
`distance` is the distance measure for neighborhood search or the data
structure for neighborhood search (e.g. k-d tree).
`min-pts` is the minimum number of neighbors for a core data point.
`radius` is the neighborhood radius."
([data min-pts radius] (dbscan data (EuclideanDistance.) min-pts radius))
([data distance min-pts radius] (DBSCAN/fit data distance min-pts radius)))
(defn denclue
"DENsity CLUstering.
The DENCLUE algorithm employs a cluster model based on kernel density
estimation. A cluster is defined by a local maximum of the estimated
density function. Data points going to the same local maximum are put
into the same cluster.
Clearly, DENCLUE doesn't work on data with uniform distribution. In high
dimensional space, the data always look like uniformly distributed because
of the curse of dimensionality. Therefore, DENCLUDE doesn't work well on
high-dimensional data in general.
`data` is the data set.
`sigma` is the smooth parameter in the Gaussian kernel. The user can
choose sigma such that number of density attractors is constant for a
long interval of sigma.
`m` is the number of selected samples used in the iteration.
This number should be much smaller than the number of data points
to speed up the algorithm. It should also be large enough to capture
the sufficient information of underlying distribution."
[data sigma m] (DENCLUE/fit data sigma m))
(defn mec
"Nonparametric minimum conditional entropy clustering.
This method performs very well especially when the exact number of clusters
is unknown. The method can also correctly reveal the structure of data and
effectively identify outliers simultaneously.
The clustering criterion is based on the conditional entropy H(C | x), where
C is the cluster label and x is an observation. According to Fano's
inequality, we can estimate C with a low probability of error only if the
conditional entropy H(C | X) is small. MEC also generalizes the criterion
by replacing Shannon's entropy with Havrda-Charvat's structural
α-entropy. Interestingly, the minimum entropy criterion based
on structural α-entropy is equal to the probability error of the
nearest neighbor method when α= 2. To estimate p(C | x), MEC employs
Parzen density estimation, a nonparametric approach.
MEC is an iterative algorithm starting with an initial partition given by
any other clustering methods, e.g. k-means, CLARNAS, hierarchical clustering,
etc. Note that a random initialization is NOT appropriate.
`data` is the data set.
`distance` is the distance measure for neighborhood search or the data
structure for neighborhood search (e.g. k-d tree).
`k` is the number of clusters. Note that this is just a hint. The final
number of clusters may be less.
`radius` is the neighborhood radius."
([data k radius] (mec data (EuclideanDistance.) k radius))
([data distance k radius] (MEC/fit data distance k radius)))
(defn specc
"Spectral clustering.
Given a set of data points, the similarity matrix may be defined as a
matrix S where S<sub>ij</sub> represents a measure of the similarity
between points. Spectral clustering techniques make use of the spectrum
of the similarity matrix of the data to perform dimensionality reduction
for clustering in fewer dimensions. Then the clustering will be performed
in the dimension-reduce space, in which clusters of non-convex shape may
become tight. There are some intriguing similarities between spectral
clustering methods and kernel PCA, which has been empirically observed
to perform clustering.
`W` is the adjacency matrix of graph or the original data.
`k` the number of clusters.
`l` is the number of random samples for Nystrom approximation.
`sigma` is the smooth/width parameter of Gaussian kernel, which
is a somewhat sensitive parameter. To search for the best setting,
one may pick the value that gives the tightest clusters (smallest
distortion, see { @link #distortion()}) in feature space."
([data k sigma] (SpectralClustering/fit data k sigma))
([data k l sigma] (SpectralClustering/fit data k l sigma)))
| 35062 | ; Copyright (c) 2010-2021 <NAME>. All rights reserved.
;
; Smile is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; Smile is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with Smile. If not, see <https://www.gnu.org/licenses/>.
(ns smile.clustering
"Clustering Analysis"
{:author "<NAME>"}
(:import [smile.clustering HierarchicalClustering PartitionClustering
KMeans XMeans GMeans SIB DeterministicAnnealing
CLARANS DBSCAN DENCLUE MEC SpectralClustering]
[smile.clustering.linkage SingleLinkage CompleteLinkage
UPGMALinkage UPGMCLinkage
WPGMALinkage WPGMCLinkage WardLinkage]
[smile.math.distance EuclideanDistance]))
(defn hclust
"Agglomerative hierarchical clustering.
This method seeks to build a hierarchy of clusters in a bottom up approach:
each observation starts in its own cluster, and pairs of clusters are merged
as one moves up the hierarchy. The results of hierarchical clustering are
usually presented in a dendrogram.
In general, the merges are determined in a greedy manner. In order to decide
which clusters should be combined, a measure of dissimilarity between sets
of observations is required. In most methods of hierarchical clustering,
this is achieved by use of an appropriate metric, and a linkage criteria
which specifies the dissimilarity of sets as a function of the pairwise
distances of observations in the sets.
Hierarchical clustering has the distinct advantage that any valid measure
of distance can be used. In fact, the observations themselves are not
required: all that is used is a matrix of distances.
`data` is the data set.
`distance` is the distance/dissimilarity measure.
`method` is the agglomeration method to merge clusters. This should be one
of 'single', 'complete', 'upgma', 'upgmc', 'wpgma', 'wpgmc', and 'ward'."
[data method]
(let [linkage (case method
"single" (SingleLinkage/of data)
"complete" (CompleteLinkage/of data)
("upgma" "average") (UPGMALinkage/of data)
("upgmc" "centroid") (UPGMCLinkage/of data)
"wpgma" (WPGMALinkage/of data)
("wpgmc" "median") (WPGMCLinkage/of data)
"ward" (WardLinkage/of data)
(throw (IllegalArgumentException. (str "Unknown agglomeration method: " method))))]
(HierarchicalClustering/fit linkage)))
(defn kmeans
"K-Means clustering.
K-Means clustering. The algorithm partitions n observations into k clusters
in which each observation belongs to the cluster with the nearest mean.
Although finding an exact solution to the k-means problem for arbitrary
input is NP-hard, the standard approach to finding an approximate solution
(often called Lloyd's algorithm or the k-means algorithm) is used widely
and frequently finds reasonable solutions quickly.
However, the k-means algorithm has at least two major theoretic shortcomings:
- First, it has been shown that the worst case running time of the
algorithm is super-polynomial in the input size.
- Second, the approximation found can be arbitrarily bad with respect
to the objective function compared to the optimal learn.
In this implementation, we use k-means++ which addresses the second of these
obstacles by specifying a procedure to initialize the cluster centers before
proceeding with the standard k-means optimization iterations. With the
k-means++ initialization, the algorithm is guaranteed to find a solution
that is O(log k) competitive to the optimal k-means solution.
We also use k-d trees to speed up each k-means step as described in the
filter algorithm by Kanungo, et al.
K-means is a hard clustering method, i.e. each sample is assigned to
a specific cluster. In contrast, soft clustering, e.g. the
Expectation-Maximization algorithm for Gaussian mixtures, assign samples
to different clusters with different probabilities.
This method runs the algorithm for given times and return the best one with
smallest distortion.
`data` is the data set.
`k` is the number of clusters.
`max-iter` is the maximum number of iterations for each running.
`tol` is the tolerance of convergence test.
`runs` is the number of runs of K-Means algorithm."
([data k] (kmeans data k 100 1E-4 10))
([data k max-iter tol runs]
(PartitionClustering/run runs
(reify java.util.function.Supplier
(get [this] (KMeans/fit data k max-iter tol))))))
(defn xmeans
"X-Means clustering.
X-Means clustering algorithm is an extended K-Means which tries to
automatically determine the number of clusters based on BIC scores.
Starting with only one cluster, the X-Means algorithm goes into action
after each run of K-Means, making local decisions about which subset of the
current centroids should split themselves in order to better fit the data.
The splitting decision is done by computing the Bayesian Information
Criterion (BIC).
`data` is the data set.
`k` is the maximum number of clusters."
[data k] (XMeans/fit data k))
(defn gmeans
"G-Means clustering.
G-Means clustering algorithm is an extended K-Means which tries to
automatically determine the number of clusters by normality test.
The G-means algorithm is based on a statistical test for the hypothesis
that a subset of data follows a Gaussian distribution. G-means runs
k-means with increasing k in a hierarchical fashion until the test accepts
the hypothesis that the data assigned to each k-means center are Gaussian.
`data` is the data set.
`k` is the maximum number of clusters."
[data k] (GMeans/fit data k))
(defn sib
"Sequential Information Bottleneck algorithm.
SIB clusters co-occurrence data such as text documents vs words.
SIB is guaranteed to converge to a local maximum of the information.
Moreover, the time and space complexity are significantly improved
in contrast to the agglomerative IB algorithm.
In analogy to K-Means, SIB's update formulas are essentially same as the
EM algorithm for estimating finite Gaussian mixture model by replacing
regular Euclidean distance with Kullback-Leibler divergence, which is
clearly a better dissimilarity measure for co-occurrence data. However,
the common batch updating rule (assigning all instances to nearest centroids
and then updating centroids) of K-Means won't work in SIB, which has
to work in a sequential way (reassigning (if better) each instance then
immediately update related centroids). It might be because K-L divergence
is very sensitive and the centroids may be significantly changed in each
iteration in batch updating rule.
Note that this implementation has a little difference from the original
paper, in which a weighted Jensen-Shannon divergence is employed as a
criterion to assign a randomly-picked sample to a different cluster.
However, this doesn't work well in some cases as we experienced probably
because the weighted JS divergence gives too much weight to clusters which
is much larger than a single sample. In this implementation, we instead
use the regular/unweighted Jensen-Shannon divergence.
`data` is the data set.
`k` is the number of clusters.
`max-iter` is the maximum number of iterations.
`runs` is the number of runs of SIB algorithm."
([data k] (sib data k 100 8))
([data k max-iter runs]
(PartitionClustering/run runs
(reify java.util.function.Supplier
(get [this] (SIB/fit data k max-iter))))))
(defn dac
"Deterministic annealing clustering.
Deterministic annealing extends soft-clustering to an annealing process.
For each temperature value, the algorithm iterates between the calculation
of all posteriori probabilities and the update of the centroids vectors,
until convergence is reached. The annealing starts with a high temperature.
Here, all centroids vectors converge to the center of the pattern
distribution (independent of their initial positions). Below a critical
temperature the vectors start to split. Further decreasing the temperature
leads to more splittings until all centroids vectors are separate. The
annealing can therefore avoid (if it is sufficiently slow) the convergence
to local minima.
`data` is the data set.
`k` is the maximum number of clusters.
`alpha` is the temperature T is decreasing as T = T * alpha. alpha has
to be in (0, 1).
`tol` is the tolerance of convergence test.
`split-tol` is the tolerance to split a cluster."
([data k] (dac data k 0.9 100 1E-4 0.01))
([data k alpha max-iter tol split-tol]
(DeterministicAnnealing/fit data k alpha max-iter tol split-tol)))
(defn clarans
"Clustering Large Applications based upon RANdomized Search.
CLARANS is an efficient medoid-based clustering algorithm. The k-medoids
algorithm is an adaptation of the k-means algorithm. Rather than calculate
the mean of the items in each cluster, a representative item, or medoid, is
chosen for each cluster at each iteration. In CLARANS, the process of
finding k medoids from n objects is viewed abstractly as searching through
a certain graph. In the graph, a node is represented by a set of k objects
as selected medoids. Two nodes are neighbors if their sets differ by only
one object. In each iteration, CLARANS considers a set of randomly chosen
neighbor nodes as candidate of new medoids. We will move to the neighbor
node if the neighbor is a better choice for medoids. Otherwise, a local
optima is discovered. The entire process is repeated multiple time to find
better.
CLARANS has two parameters: the maximum number of neighbors examined
(maxNeighbor) and the number of local minima obtained (numLocal). The
higher the value of maxNeighbor, the closer is CLARANS to PAM, and the
longer is each search of a local minima. But the quality of such a local
minima is higher and fewer local minima needs to be obtained.
`data` is the data set.
`distance` is the distance/dissimilarity measure.
`k` is the number of clusters.
`max-neighbor` is the maximum number of neighbors examined during a random
search of local minima.
`num-local` is the number of local minima to search for."
([data distance k max-neighbor] (clarans data distance k max-neighbor 16))
([data distance k max-neighbor num-local]
(PartitionClustering/run num-local
(reify java.util.function.Supplier
(get [this] (CLARANS/fit data distance k max-neighbor))))))
(defn dbscan
"Density-Based Spatial Clustering of Applications with Noise.
DBSCAN finds a number of clusters starting from the estimated density
distribution of corresponding nodes.
DBSCAN requires two parameters: radius (i.e. neighborhood radius) and the
number of minimum points required to form a cluster (minPts). It starts
with an arbitrary starting point that has not been visited. This point's
neighborhood is retrieved, and if it contains sufficient number of points,
a cluster is started. Otherwise, the point is labeled as noise. Note that
this point might later be found in a sufficiently sized radius-environment
of a different point and hence be made part of a cluster.
If a point is found to be part of a cluster, its neighborhood is also
part of that cluster. Hence, all points that are found within the
neighborhood are added, as is their own neighborhood. This process
continues until the cluster is completely found. Then, a new unvisited point
is retrieved and processed, leading to the discovery of a further cluster
of noise.
DBSCAN visits each point of the database, possibly multiple times (e.g.,
as candidates to different clusters). For practical considerations, however,
the time complexity is mostly governed by the number of nearest neighbor
queries. DBSCAN executes exactly one such query for each point, and if
an indexing structure is used that executes such a neighborhood query
in O(log n), an overall runtime complexity of O(n log n) is obtained.
DBSCAN has many advantages such as
- DBSCAN does not need to know the number of clusters in the data
a priori, as opposed to k-means.
- DBSCAN can find arbitrarily shaped clusters. It can even find clusters
completely surrounded by (but not connected to) a different cluster.
Due to the MinPts parameter, the so-called single-link effect
(different clusters being connected by a thin line of points) is reduced.
- DBSCAN has a notion of noise.
- DBSCAN requires just two parameters and is mostly insensitive to the
ordering of the points in the database. (Only points sitting on the
edge of two different clusters might swap cluster membership if the
ordering of the points is changed, and the cluster assignment is unique
only up to isomorphism.)
On the other hand, DBSCAN has the disadvantages of
- In high dimensional space, the data are sparse everywhere
because of the curse of dimensionality. Therefore, DBSCAN doesn't
work well on high-dimensional data in general.
- DBSCAN does not respond well to data sets with varying densities.
`data` is the data set.
`distance` is the distance measure for neighborhood search or the data
structure for neighborhood search (e.g. k-d tree).
`min-pts` is the minimum number of neighbors for a core data point.
`radius` is the neighborhood radius."
([data min-pts radius] (dbscan data (EuclideanDistance.) min-pts radius))
([data distance min-pts radius] (DBSCAN/fit data distance min-pts radius)))
(defn denclue
"DENsity CLUstering.
The DENCLUE algorithm employs a cluster model based on kernel density
estimation. A cluster is defined by a local maximum of the estimated
density function. Data points going to the same local maximum are put
into the same cluster.
Clearly, DENCLUE doesn't work on data with uniform distribution. In high
dimensional space, the data always look like uniformly distributed because
of the curse of dimensionality. Therefore, DENCLUDE doesn't work well on
high-dimensional data in general.
`data` is the data set.
`sigma` is the smooth parameter in the Gaussian kernel. The user can
choose sigma such that number of density attractors is constant for a
long interval of sigma.
`m` is the number of selected samples used in the iteration.
This number should be much smaller than the number of data points
to speed up the algorithm. It should also be large enough to capture
the sufficient information of underlying distribution."
[data sigma m] (DENCLUE/fit data sigma m))
(defn mec
"Nonparametric minimum conditional entropy clustering.
This method performs very well especially when the exact number of clusters
is unknown. The method can also correctly reveal the structure of data and
effectively identify outliers simultaneously.
The clustering criterion is based on the conditional entropy H(C | x), where
C is the cluster label and x is an observation. According to Fano's
inequality, we can estimate C with a low probability of error only if the
conditional entropy H(C | X) is small. MEC also generalizes the criterion
by replacing Shannon's entropy with Havrda-Charvat's structural
α-entropy. Interestingly, the minimum entropy criterion based
on structural α-entropy is equal to the probability error of the
nearest neighbor method when α= 2. To estimate p(C | x), MEC employs
Parzen density estimation, a nonparametric approach.
MEC is an iterative algorithm starting with an initial partition given by
any other clustering methods, e.g. k-means, CLARNAS, hierarchical clustering,
etc. Note that a random initialization is NOT appropriate.
`data` is the data set.
`distance` is the distance measure for neighborhood search or the data
structure for neighborhood search (e.g. k-d tree).
`k` is the number of clusters. Note that this is just a hint. The final
number of clusters may be less.
`radius` is the neighborhood radius."
([data k radius] (mec data (EuclideanDistance.) k radius))
([data distance k radius] (MEC/fit data distance k radius)))
(defn specc
"Spectral clustering.
Given a set of data points, the similarity matrix may be defined as a
matrix S where S<sub>ij</sub> represents a measure of the similarity
between points. Spectral clustering techniques make use of the spectrum
of the similarity matrix of the data to perform dimensionality reduction
for clustering in fewer dimensions. Then the clustering will be performed
in the dimension-reduce space, in which clusters of non-convex shape may
become tight. There are some intriguing similarities between spectral
clustering methods and kernel PCA, which has been empirically observed
to perform clustering.
`W` is the adjacency matrix of graph or the original data.
`k` the number of clusters.
`l` is the number of random samples for Nystrom approximation.
`sigma` is the smooth/width parameter of Gaussian kernel, which
is a somewhat sensitive parameter. To search for the best setting,
one may pick the value that gives the tightest clusters (smallest
distortion, see { @link #distortion()}) in feature space."
([data k sigma] (SpectralClustering/fit data k sigma))
([data k l sigma] (SpectralClustering/fit data k l sigma)))
| true | ; Copyright (c) 2010-2021 PI:NAME:<NAME>END_PI. All rights reserved.
;
; Smile is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; Smile is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with Smile. If not, see <https://www.gnu.org/licenses/>.
(ns smile.clustering
"Clustering Analysis"
{:author "PI:NAME:<NAME>END_PI"}
(:import [smile.clustering HierarchicalClustering PartitionClustering
KMeans XMeans GMeans SIB DeterministicAnnealing
CLARANS DBSCAN DENCLUE MEC SpectralClustering]
[smile.clustering.linkage SingleLinkage CompleteLinkage
UPGMALinkage UPGMCLinkage
WPGMALinkage WPGMCLinkage WardLinkage]
[smile.math.distance EuclideanDistance]))
(defn hclust
"Agglomerative hierarchical clustering.
This method seeks to build a hierarchy of clusters in a bottom up approach:
each observation starts in its own cluster, and pairs of clusters are merged
as one moves up the hierarchy. The results of hierarchical clustering are
usually presented in a dendrogram.
In general, the merges are determined in a greedy manner. In order to decide
which clusters should be combined, a measure of dissimilarity between sets
of observations is required. In most methods of hierarchical clustering,
this is achieved by use of an appropriate metric, and a linkage criteria
which specifies the dissimilarity of sets as a function of the pairwise
distances of observations in the sets.
Hierarchical clustering has the distinct advantage that any valid measure
of distance can be used. In fact, the observations themselves are not
required: all that is used is a matrix of distances.
`data` is the data set.
`distance` is the distance/dissimilarity measure.
`method` is the agglomeration method to merge clusters. This should be one
of 'single', 'complete', 'upgma', 'upgmc', 'wpgma', 'wpgmc', and 'ward'."
[data method]
(let [linkage (case method
"single" (SingleLinkage/of data)
"complete" (CompleteLinkage/of data)
("upgma" "average") (UPGMALinkage/of data)
("upgmc" "centroid") (UPGMCLinkage/of data)
"wpgma" (WPGMALinkage/of data)
("wpgmc" "median") (WPGMCLinkage/of data)
"ward" (WardLinkage/of data)
(throw (IllegalArgumentException. (str "Unknown agglomeration method: " method))))]
(HierarchicalClustering/fit linkage)))
(defn kmeans
"K-Means clustering.
K-Means clustering. The algorithm partitions n observations into k clusters
in which each observation belongs to the cluster with the nearest mean.
Although finding an exact solution to the k-means problem for arbitrary
input is NP-hard, the standard approach to finding an approximate solution
(often called Lloyd's algorithm or the k-means algorithm) is used widely
and frequently finds reasonable solutions quickly.
However, the k-means algorithm has at least two major theoretic shortcomings:
- First, it has been shown that the worst case running time of the
algorithm is super-polynomial in the input size.
- Second, the approximation found can be arbitrarily bad with respect
to the objective function compared to the optimal learn.
In this implementation, we use k-means++ which addresses the second of these
obstacles by specifying a procedure to initialize the cluster centers before
proceeding with the standard k-means optimization iterations. With the
k-means++ initialization, the algorithm is guaranteed to find a solution
that is O(log k) competitive to the optimal k-means solution.
We also use k-d trees to speed up each k-means step as described in the
filter algorithm by Kanungo, et al.
K-means is a hard clustering method, i.e. each sample is assigned to
a specific cluster. In contrast, soft clustering, e.g. the
Expectation-Maximization algorithm for Gaussian mixtures, assign samples
to different clusters with different probabilities.
This method runs the algorithm for given times and return the best one with
smallest distortion.
`data` is the data set.
`k` is the number of clusters.
`max-iter` is the maximum number of iterations for each running.
`tol` is the tolerance of convergence test.
`runs` is the number of runs of K-Means algorithm."
([data k] (kmeans data k 100 1E-4 10))
([data k max-iter tol runs]
(PartitionClustering/run runs
(reify java.util.function.Supplier
(get [this] (KMeans/fit data k max-iter tol))))))
(defn xmeans
"X-Means clustering.
X-Means clustering algorithm is an extended K-Means which tries to
automatically determine the number of clusters based on BIC scores.
Starting with only one cluster, the X-Means algorithm goes into action
after each run of K-Means, making local decisions about which subset of the
current centroids should split themselves in order to better fit the data.
The splitting decision is done by computing the Bayesian Information
Criterion (BIC).
`data` is the data set.
`k` is the maximum number of clusters."
[data k] (XMeans/fit data k))
(defn gmeans
"G-Means clustering.
G-Means clustering algorithm is an extended K-Means which tries to
automatically determine the number of clusters by normality test.
The G-means algorithm is based on a statistical test for the hypothesis
that a subset of data follows a Gaussian distribution. G-means runs
k-means with increasing k in a hierarchical fashion until the test accepts
the hypothesis that the data assigned to each k-means center are Gaussian.
`data` is the data set.
`k` is the maximum number of clusters."
[data k] (GMeans/fit data k))
(defn sib
"Sequential Information Bottleneck algorithm.
SIB clusters co-occurrence data such as text documents vs words.
SIB is guaranteed to converge to a local maximum of the information.
Moreover, the time and space complexity are significantly improved
in contrast to the agglomerative IB algorithm.
In analogy to K-Means, SIB's update formulas are essentially same as the
EM algorithm for estimating finite Gaussian mixture model by replacing
regular Euclidean distance with Kullback-Leibler divergence, which is
clearly a better dissimilarity measure for co-occurrence data. However,
the common batch updating rule (assigning all instances to nearest centroids
and then updating centroids) of K-Means won't work in SIB, which has
to work in a sequential way (reassigning (if better) each instance then
immediately update related centroids). It might be because K-L divergence
is very sensitive and the centroids may be significantly changed in each
iteration in batch updating rule.
Note that this implementation has a little difference from the original
paper, in which a weighted Jensen-Shannon divergence is employed as a
criterion to assign a randomly-picked sample to a different cluster.
However, this doesn't work well in some cases as we experienced probably
because the weighted JS divergence gives too much weight to clusters which
is much larger than a single sample. In this implementation, we instead
use the regular/unweighted Jensen-Shannon divergence.
`data` is the data set.
`k` is the number of clusters.
`max-iter` is the maximum number of iterations.
`runs` is the number of runs of SIB algorithm."
([data k] (sib data k 100 8))
([data k max-iter runs]
(PartitionClustering/run runs
(reify java.util.function.Supplier
(get [this] (SIB/fit data k max-iter))))))
(defn dac
"Deterministic annealing clustering.
Deterministic annealing extends soft-clustering to an annealing process.
For each temperature value, the algorithm iterates between the calculation
of all posteriori probabilities and the update of the centroids vectors,
until convergence is reached. The annealing starts with a high temperature.
Here, all centroids vectors converge to the center of the pattern
distribution (independent of their initial positions). Below a critical
temperature the vectors start to split. Further decreasing the temperature
leads to more splittings until all centroids vectors are separate. The
annealing can therefore avoid (if it is sufficiently slow) the convergence
to local minima.
`data` is the data set.
`k` is the maximum number of clusters.
`alpha` is the temperature T is decreasing as T = T * alpha. alpha has
to be in (0, 1).
`tol` is the tolerance of convergence test.
`split-tol` is the tolerance to split a cluster."
([data k] (dac data k 0.9 100 1E-4 0.01))
([data k alpha max-iter tol split-tol]
(DeterministicAnnealing/fit data k alpha max-iter tol split-tol)))
(defn clarans
"Clustering Large Applications based upon RANdomized Search.
CLARANS is an efficient medoid-based clustering algorithm. The k-medoids
algorithm is an adaptation of the k-means algorithm. Rather than calculate
the mean of the items in each cluster, a representative item, or medoid, is
chosen for each cluster at each iteration. In CLARANS, the process of
finding k medoids from n objects is viewed abstractly as searching through
a certain graph. In the graph, a node is represented by a set of k objects
as selected medoids. Two nodes are neighbors if their sets differ by only
one object. In each iteration, CLARANS considers a set of randomly chosen
neighbor nodes as candidate of new medoids. We will move to the neighbor
node if the neighbor is a better choice for medoids. Otherwise, a local
optima is discovered. The entire process is repeated multiple time to find
better.
CLARANS has two parameters: the maximum number of neighbors examined
(maxNeighbor) and the number of local minima obtained (numLocal). The
higher the value of maxNeighbor, the closer is CLARANS to PAM, and the
longer is each search of a local minima. But the quality of such a local
minima is higher and fewer local minima needs to be obtained.
`data` is the data set.
`distance` is the distance/dissimilarity measure.
`k` is the number of clusters.
`max-neighbor` is the maximum number of neighbors examined during a random
search of local minima.
`num-local` is the number of local minima to search for."
([data distance k max-neighbor] (clarans data distance k max-neighbor 16))
([data distance k max-neighbor num-local]
(PartitionClustering/run num-local
(reify java.util.function.Supplier
(get [this] (CLARANS/fit data distance k max-neighbor))))))
(defn dbscan
"Density-Based Spatial Clustering of Applications with Noise.
DBSCAN finds a number of clusters starting from the estimated density
distribution of corresponding nodes.
DBSCAN requires two parameters: radius (i.e. neighborhood radius) and the
number of minimum points required to form a cluster (minPts). It starts
with an arbitrary starting point that has not been visited. This point's
neighborhood is retrieved, and if it contains sufficient number of points,
a cluster is started. Otherwise, the point is labeled as noise. Note that
this point might later be found in a sufficiently sized radius-environment
of a different point and hence be made part of a cluster.
If a point is found to be part of a cluster, its neighborhood is also
part of that cluster. Hence, all points that are found within the
neighborhood are added, as is their own neighborhood. This process
continues until the cluster is completely found. Then, a new unvisited point
is retrieved and processed, leading to the discovery of a further cluster
of noise.
DBSCAN visits each point of the database, possibly multiple times (e.g.,
as candidates to different clusters). For practical considerations, however,
the time complexity is mostly governed by the number of nearest neighbor
queries. DBSCAN executes exactly one such query for each point, and if
an indexing structure is used that executes such a neighborhood query
in O(log n), an overall runtime complexity of O(n log n) is obtained.
DBSCAN has many advantages such as
- DBSCAN does not need to know the number of clusters in the data
a priori, as opposed to k-means.
- DBSCAN can find arbitrarily shaped clusters. It can even find clusters
completely surrounded by (but not connected to) a different cluster.
Due to the MinPts parameter, the so-called single-link effect
(different clusters being connected by a thin line of points) is reduced.
- DBSCAN has a notion of noise.
- DBSCAN requires just two parameters and is mostly insensitive to the
ordering of the points in the database. (Only points sitting on the
edge of two different clusters might swap cluster membership if the
ordering of the points is changed, and the cluster assignment is unique
only up to isomorphism.)
On the other hand, DBSCAN has the disadvantages of
- In high dimensional space, the data are sparse everywhere
because of the curse of dimensionality. Therefore, DBSCAN doesn't
work well on high-dimensional data in general.
- DBSCAN does not respond well to data sets with varying densities.
`data` is the data set.
`distance` is the distance measure for neighborhood search or the data
structure for neighborhood search (e.g. k-d tree).
`min-pts` is the minimum number of neighbors for a core data point.
`radius` is the neighborhood radius."
([data min-pts radius] (dbscan data (EuclideanDistance.) min-pts radius))
([data distance min-pts radius] (DBSCAN/fit data distance min-pts radius)))
(defn denclue
"DENsity CLUstering.
The DENCLUE algorithm employs a cluster model based on kernel density
estimation. A cluster is defined by a local maximum of the estimated
density function. Data points going to the same local maximum are put
into the same cluster.
Clearly, DENCLUE doesn't work on data with uniform distribution. In high
dimensional space, the data always look like uniformly distributed because
of the curse of dimensionality. Therefore, DENCLUDE doesn't work well on
high-dimensional data in general.
`data` is the data set.
`sigma` is the smooth parameter in the Gaussian kernel. The user can
choose sigma such that number of density attractors is constant for a
long interval of sigma.
`m` is the number of selected samples used in the iteration.
This number should be much smaller than the number of data points
to speed up the algorithm. It should also be large enough to capture
the sufficient information of underlying distribution."
[data sigma m] (DENCLUE/fit data sigma m))
(defn mec
"Nonparametric minimum conditional entropy clustering.
This method performs very well especially when the exact number of clusters
is unknown. The method can also correctly reveal the structure of data and
effectively identify outliers simultaneously.
The clustering criterion is based on the conditional entropy H(C | x), where
C is the cluster label and x is an observation. According to Fano's
inequality, we can estimate C with a low probability of error only if the
conditional entropy H(C | X) is small. MEC also generalizes the criterion
by replacing Shannon's entropy with Havrda-Charvat's structural
α-entropy. Interestingly, the minimum entropy criterion based
on structural α-entropy is equal to the probability error of the
nearest neighbor method when α= 2. To estimate p(C | x), MEC employs
Parzen density estimation, a nonparametric approach.
MEC is an iterative algorithm starting with an initial partition given by
any other clustering methods, e.g. k-means, CLARNAS, hierarchical clustering,
etc. Note that a random initialization is NOT appropriate.
`data` is the data set.
`distance` is the distance measure for neighborhood search or the data
structure for neighborhood search (e.g. k-d tree).
`k` is the number of clusters. Note that this is just a hint. The final
number of clusters may be less.
`radius` is the neighborhood radius."
([data k radius] (mec data (EuclideanDistance.) k radius))
([data distance k radius] (MEC/fit data distance k radius)))
(defn specc
"Spectral clustering.
Given a set of data points, the similarity matrix may be defined as a
matrix S where S<sub>ij</sub> represents a measure of the similarity
between points. Spectral clustering techniques make use of the spectrum
of the similarity matrix of the data to perform dimensionality reduction
for clustering in fewer dimensions. Then the clustering will be performed
in the dimension-reduce space, in which clusters of non-convex shape may
become tight. There are some intriguing similarities between spectral
clustering methods and kernel PCA, which has been empirically observed
to perform clustering.
`W` is the adjacency matrix of graph or the original data.
`k` the number of clusters.
`l` is the number of random samples for Nystrom approximation.
`sigma` is the smooth/width parameter of Gaussian kernel, which
is a somewhat sensitive parameter. To search for the best setting,
one may pick the value that gives the tightest clusters (smallest
distortion, see { @link #distortion()}) in feature space."
([data k sigma] (SpectralClustering/fit data k sigma))
([data k l sigma] (SpectralClustering/fit data k l sigma)))
|
[
{
"context": ")\n\n\n; The MIT License (MIT)\n;\n; Copyright (c) 2015 Jason Waag\n;\n; Permission is hereby granted, free of charge,",
"end": 1067,
"score": 0.999835193157196,
"start": 1057,
"tag": "NAME",
"value": "Jason Waag"
}
] | src/accounting/export.cljs | jaw977/accounting-cljs-om | 2 | (ns accounting.export
(:require [clojure.string :as str]
[om.dom :as dom :include-macros true]
[accounting.util :refer [assoc-last log log-clj fixpt->float balance-amount]]))
(defn export-part [{:keys [account amount unit]} last-account]
(let [amount (and amount (fixpt->float amount))]
(filter identity
[(if (not= account last-account) account)
(if amount
(if unit
[amount unit]
amount))])))
(defn export-parts [parts]
(apply concat
(map export-part
(if (= 0 (balance-amount parts))
(assoc-last parts [:amount] nil)
parts)
(into [nil] (map :account parts)))))
(defn export-txs [txs]
(str/join "\n"
(for [{:keys [date description parts]} txs]
(str (into [date description] (export-parts parts))))))
(defn render [txs]
(dom/textarea #js {:rows 40 :cols 100 :value (export-txs txs)}))
; The MIT License (MIT)
;
; Copyright (c) 2015 Jason Waag
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
; THE SOFTWARE.
| 79285 | (ns accounting.export
(:require [clojure.string :as str]
[om.dom :as dom :include-macros true]
[accounting.util :refer [assoc-last log log-clj fixpt->float balance-amount]]))
(defn export-part [{:keys [account amount unit]} last-account]
(let [amount (and amount (fixpt->float amount))]
(filter identity
[(if (not= account last-account) account)
(if amount
(if unit
[amount unit]
amount))])))
(defn export-parts [parts]
(apply concat
(map export-part
(if (= 0 (balance-amount parts))
(assoc-last parts [:amount] nil)
parts)
(into [nil] (map :account parts)))))
(defn export-txs [txs]
(str/join "\n"
(for [{:keys [date description parts]} txs]
(str (into [date description] (export-parts parts))))))
(defn render [txs]
(dom/textarea #js {:rows 40 :cols 100 :value (export-txs txs)}))
; The MIT License (MIT)
;
; Copyright (c) 2015 <NAME>
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
; THE SOFTWARE.
| true | (ns accounting.export
(:require [clojure.string :as str]
[om.dom :as dom :include-macros true]
[accounting.util :refer [assoc-last log log-clj fixpt->float balance-amount]]))
(defn export-part [{:keys [account amount unit]} last-account]
(let [amount (and amount (fixpt->float amount))]
(filter identity
[(if (not= account last-account) account)
(if amount
(if unit
[amount unit]
amount))])))
(defn export-parts [parts]
(apply concat
(map export-part
(if (= 0 (balance-amount parts))
(assoc-last parts [:amount] nil)
parts)
(into [nil] (map :account parts)))))
(defn export-txs [txs]
(str/join "\n"
(for [{:keys [date description parts]} txs]
(str (into [date description] (export-parts parts))))))
(defn render [txs]
(dom/textarea #js {:rows 40 :cols 100 :value (export-txs txs)}))
; The MIT License (MIT)
;
; Copyright (c) 2015 PI:NAME:<NAME>END_PI
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
; THE SOFTWARE.
|
[
{
"context": "ble random data generator.\n\n Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.\n\n The random",
"end": 321,
"score": 0.9999009966850281,
"start": 312,
"tag": "NAME",
"value": "Josh Faul"
},
{
"context": "Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.\n\n The random number genererator is bas",
"end": 347,
"score": 0.9996550679206848,
"start": 341,
"tag": "USERNAME",
"value": "jocafa"
},
{
"context": "ea PRNG, but is modified.\n - https://github.com/coverslide/node-alea\n - https://github.com/nquinlan/better",
"end": 469,
"score": 0.9985148310661316,
"start": 459,
"tag": "USERNAME",
"value": "coverslide"
},
{
"context": ".com/coverslide/node-alea\n - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror\n - ",
"end": 512,
"score": 0.9990441799163818,
"start": 504,
"tag": "USERNAME",
"value": "nquinlan"
}
] | src/phzr/random_data_generator.cljs | dparis/phzr | 120 | (ns phzr.random-data-generator
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [uuid]))
(defn ->RandomDataGenerator
"An extremely useful repeatable random data generator.
Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.
The random number genererator is based on the Alea PRNG, but is modified.
- https://github.com/coverslide/node-alea
- https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
- http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404)
Parameters:
* seeds (Array.<any>) {optional} - An array of values to use as the seed."
([]
(js/Phaser.RandomDataGenerator.))
([seeds]
(js/Phaser.RandomDataGenerator. (clj->phaser seeds))))
(defn angle
"Returns a random angle between -180 and 180.
Returns: number - A random number between -180 and 180."
([random-data-generator]
(phaser->clj
(.angle random-data-generator))))
(defn between
"Returns a random integer between and including min and max.
This method is an alias for RandomDataGenerator.integerInRange.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.between random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn frac
"Returns a random real number between 0 and 1.
Returns: number - A random real number between 0 and 1."
([random-data-generator]
(phaser->clj
(.frac random-data-generator))))
(defn integer
"Returns a random integer between 0 and 2^32.
Returns: number - A random integer between 0 and 2^32."
([random-data-generator]
(phaser->clj
(.integer random-data-generator))))
(defn integer-in-range
"Returns a random integer between and including min and max.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.integerInRange random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn normal
"Returns a random real number between -1 and 1.
Returns: number - A random real number between -1 and 1."
([random-data-generator]
(phaser->clj
(.normal random-data-generator))))
(defn pick
"Returns a random member of `array`.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* ary (Array) - An Array to pick a random member of.
Returns: any - A random member of the array."
([random-data-generator ary]
(phaser->clj
(.pick random-data-generator
(clj->phaser ary)))))
(defn real
"Returns a random real number between 0 and 2^32.
Returns: number - A random real number between 0 and 2^32."
([random-data-generator]
(phaser->clj
(.real random-data-generator))))
(defn real-in-range
"Returns a random real number between min and max.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.realInRange random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn sow
"Reset the seed of the random data generator.
_Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* seeds (Array.<any>) - The array of seeds: the `toString()` of each value is used."
([random-data-generator seeds]
(phaser->clj
(.sow random-data-generator
(clj->phaser seeds)))))
(defn timestamp
"Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random timestamp between min and max."
([random-data-generator min max]
(phaser->clj
(.timestamp random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn uuid
"Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
Returns: string - A valid RFC4122 version4 ID hex string"
([random-data-generator]
(phaser->clj
(.uuid random-data-generator))))
(defn weighted-pick
"Returns a random member of `array`, favoring the earlier entries.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* ary (Array) - An Array to pick a random member of.
Returns: any - A random member of the array."
([random-data-generator ary]
(phaser->clj
(.weightedPick random-data-generator
(clj->phaser ary))))) | 116761 | (ns phzr.random-data-generator
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [uuid]))
(defn ->RandomDataGenerator
"An extremely useful repeatable random data generator.
Based on Nonsense by <NAME> https://github.com/jocafa/Nonsense.
The random number genererator is based on the Alea PRNG, but is modified.
- https://github.com/coverslide/node-alea
- https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
- http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404)
Parameters:
* seeds (Array.<any>) {optional} - An array of values to use as the seed."
([]
(js/Phaser.RandomDataGenerator.))
([seeds]
(js/Phaser.RandomDataGenerator. (clj->phaser seeds))))
(defn angle
"Returns a random angle between -180 and 180.
Returns: number - A random number between -180 and 180."
([random-data-generator]
(phaser->clj
(.angle random-data-generator))))
(defn between
"Returns a random integer between and including min and max.
This method is an alias for RandomDataGenerator.integerInRange.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.between random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn frac
"Returns a random real number between 0 and 1.
Returns: number - A random real number between 0 and 1."
([random-data-generator]
(phaser->clj
(.frac random-data-generator))))
(defn integer
"Returns a random integer between 0 and 2^32.
Returns: number - A random integer between 0 and 2^32."
([random-data-generator]
(phaser->clj
(.integer random-data-generator))))
(defn integer-in-range
"Returns a random integer between and including min and max.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.integerInRange random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn normal
"Returns a random real number between -1 and 1.
Returns: number - A random real number between -1 and 1."
([random-data-generator]
(phaser->clj
(.normal random-data-generator))))
(defn pick
"Returns a random member of `array`.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* ary (Array) - An Array to pick a random member of.
Returns: any - A random member of the array."
([random-data-generator ary]
(phaser->clj
(.pick random-data-generator
(clj->phaser ary)))))
(defn real
"Returns a random real number between 0 and 2^32.
Returns: number - A random real number between 0 and 2^32."
([random-data-generator]
(phaser->clj
(.real random-data-generator))))
(defn real-in-range
"Returns a random real number between min and max.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.realInRange random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn sow
"Reset the seed of the random data generator.
_Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* seeds (Array.<any>) - The array of seeds: the `toString()` of each value is used."
([random-data-generator seeds]
(phaser->clj
(.sow random-data-generator
(clj->phaser seeds)))))
(defn timestamp
"Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random timestamp between min and max."
([random-data-generator min max]
(phaser->clj
(.timestamp random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn uuid
"Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
Returns: string - A valid RFC4122 version4 ID hex string"
([random-data-generator]
(phaser->clj
(.uuid random-data-generator))))
(defn weighted-pick
"Returns a random member of `array`, favoring the earlier entries.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* ary (Array) - An Array to pick a random member of.
Returns: any - A random member of the array."
([random-data-generator ary]
(phaser->clj
(.weightedPick random-data-generator
(clj->phaser ary))))) | true | (ns phzr.random-data-generator
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [uuid]))
(defn ->RandomDataGenerator
"An extremely useful repeatable random data generator.
Based on Nonsense by PI:NAME:<NAME>END_PI https://github.com/jocafa/Nonsense.
The random number genererator is based on the Alea PRNG, but is modified.
- https://github.com/coverslide/node-alea
- https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
- http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404)
Parameters:
* seeds (Array.<any>) {optional} - An array of values to use as the seed."
([]
(js/Phaser.RandomDataGenerator.))
([seeds]
(js/Phaser.RandomDataGenerator. (clj->phaser seeds))))
(defn angle
"Returns a random angle between -180 and 180.
Returns: number - A random number between -180 and 180."
([random-data-generator]
(phaser->clj
(.angle random-data-generator))))
(defn between
"Returns a random integer between and including min and max.
This method is an alias for RandomDataGenerator.integerInRange.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.between random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn frac
"Returns a random real number between 0 and 1.
Returns: number - A random real number between 0 and 1."
([random-data-generator]
(phaser->clj
(.frac random-data-generator))))
(defn integer
"Returns a random integer between 0 and 2^32.
Returns: number - A random integer between 0 and 2^32."
([random-data-generator]
(phaser->clj
(.integer random-data-generator))))
(defn integer-in-range
"Returns a random integer between and including min and max.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.integerInRange random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn normal
"Returns a random real number between -1 and 1.
Returns: number - A random real number between -1 and 1."
([random-data-generator]
(phaser->clj
(.normal random-data-generator))))
(defn pick
"Returns a random member of `array`.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* ary (Array) - An Array to pick a random member of.
Returns: any - A random member of the array."
([random-data-generator ary]
(phaser->clj
(.pick random-data-generator
(clj->phaser ary)))))
(defn real
"Returns a random real number between 0 and 2^32.
Returns: number - A random real number between 0 and 2^32."
([random-data-generator]
(phaser->clj
(.real random-data-generator))))
(defn real-in-range
"Returns a random real number between min and max.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random number between min and max."
([random-data-generator min max]
(phaser->clj
(.realInRange random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn sow
"Reset the seed of the random data generator.
_Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* seeds (Array.<any>) - The array of seeds: the `toString()` of each value is used."
([random-data-generator seeds]
(phaser->clj
(.sow random-data-generator
(clj->phaser seeds)))))
(defn timestamp
"Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* min (number) - The minimum value in the range.
* max (number) - The maximum value in the range.
Returns: number - A random timestamp between min and max."
([random-data-generator min max]
(phaser->clj
(.timestamp random-data-generator
(clj->phaser min)
(clj->phaser max)))))
(defn uuid
"Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
Returns: string - A valid RFC4122 version4 ID hex string"
([random-data-generator]
(phaser->clj
(.uuid random-data-generator))))
(defn weighted-pick
"Returns a random member of `array`, favoring the earlier entries.
Parameters:
* random-data-generator (Phaser.RandomDataGenerator) - Targeted instance for method
* ary (Array) - An Array to pick a random member of.
Returns: any - A random member of the array."
([random-data-generator ary]
(phaser->clj
(.weightedPick random-data-generator
(clj->phaser ary))))) |
[
{
"context": "\"hey!\"}))))\n\n(deftest test-get-players\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (map #(% :name) (util/ge",
"end": 3814,
"score": 0.9998467564582825,
"start": 3809,
"tag": "NAME",
"value": "Alice"
},
{
"context": ")))\n\n(deftest test-get-players\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (map #(% :name) (util/get-play",
"end": 3820,
"score": 0.9997867345809937,
"start": 3817,
"tag": "NAME",
"value": "Bob"
},
{
"context": "deftest test-get-players\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (map #(% :name) (util/get-players util",
"end": 3828,
"score": 0.9997020959854126,
"start": 3823,
"tag": "NAME",
"value": "Carol"
}
] | test/starlanes/util_test.clj | oubiwann/clj-starlanes | 1 | (ns starlanes.util-test
(:require [clojure.test :refer :all]
[starlanes.const :as const]
[starlanes.game :as game]
[starlanes.util :as util]))
(deftest test-mult-str
(let [result (util/mult-str 4 "ab")
expected "abababab"]
(is (= result expected))))
(deftest test-ord
(is (= 97 (util/ord "a")))
(is (= 122 (util/ord "z"))))
(deftest test-chr
(is (= "a" (util/chr 97)))
(is (= "z" (util/chr 122))))
(deftest test-rand-float
(let [random (util/random 314)
result (util/rand-float random)
expected 0.75192976]
(is (= (str result) (str expected)))))
(deftest test-rand-game
(let [game-data (game/game-data-factory)
result (util/rand-game game-data)
expected 0.75192976]
(is (= (str result) (str expected)))))
(deftest test-coord-open?
(is (= true (util/coord-open? [:a1 "."] ".")))
(is (= false (util/coord-open? [:a1 "."] "*")))
(is (= false (util/coord-open? [:a1 "."] "+")))
(is (= false (util/coord-open? [:a1 "."] "A"))))
(deftest test-string->xy
(is (= ["a" "1"] (util/string->xy "a1")))
(is (= ["b" "12"] (util/string->xy "b12")))
(is (= ["c" "123"] (util/string->xy "c123"))))
(deftest test-keyword->xy
(is (= ["a" "1"] (util/keyword->xy :a1)))
(is (= ["b" "12"] (util/keyword->xy :b12)))
(is (= ["c" "123"] (util/keyword->xy :c123))))
(deftest test-xy->keyword
(is (= :a1 (util/xy->keyword ["a" 1])))
(is (= :b12 (util/xy->keyword ["b" 12])))
(is (= :c123 (util/xy->keyword ["c" "123"]))))
(deftest test-move->string-coord
(is (= "a1" (util/move->string-coord "1a")))
(is (= "a12" (util/move->string-coord "12a")))
(is (= "a123" (util/move->string-coord "123a"))))
(deftest test-move->keyword
(is (= :a1 (util/move->keyword "1a")))
(is (= :a12 (util/move->keyword "12a")))
(is (= :a123 (util/move->keyword "123a"))))
(deftest test-get-friendly-coord
(is (= "1a" (util/get-friendly-coord :a1)))
(is (= "12b" (util/get-friendly-coord :b12)))
(is (= "123c" (util/get-friendly-coord :c123))))
(deftest test-is-item?
(is (= true (util/is-item? [:a1 "*"] (const/items :star))))
(is (= false (util/is-item? [:a1 "."] (const/items :star))))
(is (= true (util/is-item? [:a1 "+"] (const/items :outpost))))
(is (= true (util/is-item? [:a1 "."] (const/items :empty)))))
(deftest test-filter-item
(is (= [:a1 "*"] (util/filter-item [:a1 "*"] (const/items :star))))
(is (= [:a1 "+"] (util/filter-item [:a1 "+"] (const/items :outpost))))
(is (= nil (util/filter-item [:a1 "+"] (const/items :star))))
(is (= [[:a1 "*"] nil nil nil nil nil nil nil nil nil nil nil
[:c3 "*"] nil nil nil
[:d2 "*"] nil nil nil nil nil nil
[:e4 "*"] nil]
(->> (util/fake-game-data :star-map)
(sort)
(map util/filter-star)
(into [])))))
(deftest test-filter-allowed
(is (= #{2 3 4} (util/filter-allowed [1 2 3 4 5] [2 3 4])))
(is (= #{[:a2 "*"]} (util/filter-allowed [[:a1 "."] [:a2 "*"]] [[:a2 "*"]]))))
(deftest test-get-x-coord-range
(is (= ["a" "b" "c" "d" "e"] (util/get-x-coord-range))))
(deftest test-get-y-coord-range
(is (= [1 2 3 4 5] (util/get-y-coord-range))))
(deftest test-in?
(is (= true (util/in? [1 2] 1)))
(is (= true (util/in? [1 2] 2)))
(is (= false (util/in? [1 2] 0)))
(is (= false (util/in? [1 2] 3))))
(deftest test-x-coord?
(is (= true (util/x-coord? "a")))
(is (= true (util/x-coord? "e")))
(is (= false (util/x-coord? "f"))))
(deftest test-y-coord?
(is (= false (util/y-coord? 0)))
(is (= true (util/y-coord? 1)))
(is (= true (util/y-coord? 5)))
(is (= false (util/y-coord? 6))))
(deftest test-serialize-game-data
(is (= {:rand nil} (util/serialize-game-data {:rand "hey!"}))))
(deftest test-get-players
(is (= ["Alice" "Bob" "Carol"]
(map #(% :name) (util/get-players util/fake-game-data)))))
(deftest test-get-players
(is (= 3 (util/get-player-count util/fake-game-data))))
(deftest test-get-max-total-moves
(is (= 6 (util/get-max-total-moves util/fake-game-data)))
(is (= 9 (util/get-max-total-moves 3 3)))
(is (= 40 (util/get-max-total-moves 10 4)))
(is (= 15 (util/get-max-total-moves 1 15)))
(is (= 1 (util/get-max-total-moves 1 1)))
(is (= 0 (util/get-max-total-moves 0 0))))
(deftest test-get-company-name
(is (= "Altair Starways" (util/get-company-name :A)))
(is (= "Luyten, Ltd." (util/get-company-name :L))))
(deftest test-get-companies
(is (= ["Altair Starways"
"Betelgeuse, Ltd."
"Capella Cargo Co."
"Denebola Shippers"
"Eridani Expediters"]
(util/get-companies)))
(is (= ["Al" "Be" "Ca"]
(util/get-companies util/fake-game-data))))
(deftest test-get-companies-letters
(is (= ["A" "B" "C" "D" "E"]
(util/get-companies-letters)))
(is (= ["A" "B" "C"]
(util/get-companies-letters util/fake-game-data))))
(deftest test-count-occurances
(is (= {3 1, 2 2, 1 3}
(util/count-occurances [1 1 1 2 2 3]))))
(deftest test-company?
(is (= true (util/company? "A")))
(is (= false (util/company? "+"))))
(deftest test-star?
(is (= true (util/star? "*")))
(is (= false (util/star? "+"))))
(deftest test-outpost?
(is (= true (util/outpost? "+")))
(is (= false (util/outpost? "A"))))
(deftest test-get-color-tuple
(is (= "0;32" (util/get-color-tuple :green :dark)))
const/end-color
(is (= "1;32" (util/get-color-tuple :green :light)))
const/end-color
(is (= "0;30" (util/get-color-tuple :black :dark)))
const/end-color)
(deftest test-start-color
(is (= "\33[0;32m" (util/start-color :green :dark)))
const/end-color
(is (= "\33[1;32m" (util/start-color :green :light)))
const/end-color
(is (= "\33[0;30m" (util/start-color :black :dark)))
const/end-color)
(deftest test-colorize
(is (= "\33[1;37mSpace!\33[m" (util/colorize "Space!")))
(is (= "\33[0;30mSpace!\33[m" (util/colorize "Space!" :black)))
(is (= "\33[1;37mSpace!\33[m"
(util/colorize "Space!" :white))))
| 100112 | (ns starlanes.util-test
(:require [clojure.test :refer :all]
[starlanes.const :as const]
[starlanes.game :as game]
[starlanes.util :as util]))
(deftest test-mult-str
(let [result (util/mult-str 4 "ab")
expected "abababab"]
(is (= result expected))))
(deftest test-ord
(is (= 97 (util/ord "a")))
(is (= 122 (util/ord "z"))))
(deftest test-chr
(is (= "a" (util/chr 97)))
(is (= "z" (util/chr 122))))
(deftest test-rand-float
(let [random (util/random 314)
result (util/rand-float random)
expected 0.75192976]
(is (= (str result) (str expected)))))
(deftest test-rand-game
(let [game-data (game/game-data-factory)
result (util/rand-game game-data)
expected 0.75192976]
(is (= (str result) (str expected)))))
(deftest test-coord-open?
(is (= true (util/coord-open? [:a1 "."] ".")))
(is (= false (util/coord-open? [:a1 "."] "*")))
(is (= false (util/coord-open? [:a1 "."] "+")))
(is (= false (util/coord-open? [:a1 "."] "A"))))
(deftest test-string->xy
(is (= ["a" "1"] (util/string->xy "a1")))
(is (= ["b" "12"] (util/string->xy "b12")))
(is (= ["c" "123"] (util/string->xy "c123"))))
(deftest test-keyword->xy
(is (= ["a" "1"] (util/keyword->xy :a1)))
(is (= ["b" "12"] (util/keyword->xy :b12)))
(is (= ["c" "123"] (util/keyword->xy :c123))))
(deftest test-xy->keyword
(is (= :a1 (util/xy->keyword ["a" 1])))
(is (= :b12 (util/xy->keyword ["b" 12])))
(is (= :c123 (util/xy->keyword ["c" "123"]))))
(deftest test-move->string-coord
(is (= "a1" (util/move->string-coord "1a")))
(is (= "a12" (util/move->string-coord "12a")))
(is (= "a123" (util/move->string-coord "123a"))))
(deftest test-move->keyword
(is (= :a1 (util/move->keyword "1a")))
(is (= :a12 (util/move->keyword "12a")))
(is (= :a123 (util/move->keyword "123a"))))
(deftest test-get-friendly-coord
(is (= "1a" (util/get-friendly-coord :a1)))
(is (= "12b" (util/get-friendly-coord :b12)))
(is (= "123c" (util/get-friendly-coord :c123))))
(deftest test-is-item?
(is (= true (util/is-item? [:a1 "*"] (const/items :star))))
(is (= false (util/is-item? [:a1 "."] (const/items :star))))
(is (= true (util/is-item? [:a1 "+"] (const/items :outpost))))
(is (= true (util/is-item? [:a1 "."] (const/items :empty)))))
(deftest test-filter-item
(is (= [:a1 "*"] (util/filter-item [:a1 "*"] (const/items :star))))
(is (= [:a1 "+"] (util/filter-item [:a1 "+"] (const/items :outpost))))
(is (= nil (util/filter-item [:a1 "+"] (const/items :star))))
(is (= [[:a1 "*"] nil nil nil nil nil nil nil nil nil nil nil
[:c3 "*"] nil nil nil
[:d2 "*"] nil nil nil nil nil nil
[:e4 "*"] nil]
(->> (util/fake-game-data :star-map)
(sort)
(map util/filter-star)
(into [])))))
(deftest test-filter-allowed
(is (= #{2 3 4} (util/filter-allowed [1 2 3 4 5] [2 3 4])))
(is (= #{[:a2 "*"]} (util/filter-allowed [[:a1 "."] [:a2 "*"]] [[:a2 "*"]]))))
(deftest test-get-x-coord-range
(is (= ["a" "b" "c" "d" "e"] (util/get-x-coord-range))))
(deftest test-get-y-coord-range
(is (= [1 2 3 4 5] (util/get-y-coord-range))))
(deftest test-in?
(is (= true (util/in? [1 2] 1)))
(is (= true (util/in? [1 2] 2)))
(is (= false (util/in? [1 2] 0)))
(is (= false (util/in? [1 2] 3))))
(deftest test-x-coord?
(is (= true (util/x-coord? "a")))
(is (= true (util/x-coord? "e")))
(is (= false (util/x-coord? "f"))))
(deftest test-y-coord?
(is (= false (util/y-coord? 0)))
(is (= true (util/y-coord? 1)))
(is (= true (util/y-coord? 5)))
(is (= false (util/y-coord? 6))))
(deftest test-serialize-game-data
(is (= {:rand nil} (util/serialize-game-data {:rand "hey!"}))))
(deftest test-get-players
(is (= ["<NAME>" "<NAME>" "<NAME>"]
(map #(% :name) (util/get-players util/fake-game-data)))))
(deftest test-get-players
(is (= 3 (util/get-player-count util/fake-game-data))))
(deftest test-get-max-total-moves
(is (= 6 (util/get-max-total-moves util/fake-game-data)))
(is (= 9 (util/get-max-total-moves 3 3)))
(is (= 40 (util/get-max-total-moves 10 4)))
(is (= 15 (util/get-max-total-moves 1 15)))
(is (= 1 (util/get-max-total-moves 1 1)))
(is (= 0 (util/get-max-total-moves 0 0))))
(deftest test-get-company-name
(is (= "Altair Starways" (util/get-company-name :A)))
(is (= "Luyten, Ltd." (util/get-company-name :L))))
(deftest test-get-companies
(is (= ["Altair Starways"
"Betelgeuse, Ltd."
"Capella Cargo Co."
"Denebola Shippers"
"Eridani Expediters"]
(util/get-companies)))
(is (= ["Al" "Be" "Ca"]
(util/get-companies util/fake-game-data))))
(deftest test-get-companies-letters
(is (= ["A" "B" "C" "D" "E"]
(util/get-companies-letters)))
(is (= ["A" "B" "C"]
(util/get-companies-letters util/fake-game-data))))
(deftest test-count-occurances
(is (= {3 1, 2 2, 1 3}
(util/count-occurances [1 1 1 2 2 3]))))
(deftest test-company?
(is (= true (util/company? "A")))
(is (= false (util/company? "+"))))
(deftest test-star?
(is (= true (util/star? "*")))
(is (= false (util/star? "+"))))
(deftest test-outpost?
(is (= true (util/outpost? "+")))
(is (= false (util/outpost? "A"))))
(deftest test-get-color-tuple
(is (= "0;32" (util/get-color-tuple :green :dark)))
const/end-color
(is (= "1;32" (util/get-color-tuple :green :light)))
const/end-color
(is (= "0;30" (util/get-color-tuple :black :dark)))
const/end-color)
(deftest test-start-color
(is (= "\33[0;32m" (util/start-color :green :dark)))
const/end-color
(is (= "\33[1;32m" (util/start-color :green :light)))
const/end-color
(is (= "\33[0;30m" (util/start-color :black :dark)))
const/end-color)
(deftest test-colorize
(is (= "\33[1;37mSpace!\33[m" (util/colorize "Space!")))
(is (= "\33[0;30mSpace!\33[m" (util/colorize "Space!" :black)))
(is (= "\33[1;37mSpace!\33[m"
(util/colorize "Space!" :white))))
| true | (ns starlanes.util-test
(:require [clojure.test :refer :all]
[starlanes.const :as const]
[starlanes.game :as game]
[starlanes.util :as util]))
(deftest test-mult-str
(let [result (util/mult-str 4 "ab")
expected "abababab"]
(is (= result expected))))
(deftest test-ord
(is (= 97 (util/ord "a")))
(is (= 122 (util/ord "z"))))
(deftest test-chr
(is (= "a" (util/chr 97)))
(is (= "z" (util/chr 122))))
(deftest test-rand-float
(let [random (util/random 314)
result (util/rand-float random)
expected 0.75192976]
(is (= (str result) (str expected)))))
(deftest test-rand-game
(let [game-data (game/game-data-factory)
result (util/rand-game game-data)
expected 0.75192976]
(is (= (str result) (str expected)))))
(deftest test-coord-open?
(is (= true (util/coord-open? [:a1 "."] ".")))
(is (= false (util/coord-open? [:a1 "."] "*")))
(is (= false (util/coord-open? [:a1 "."] "+")))
(is (= false (util/coord-open? [:a1 "."] "A"))))
(deftest test-string->xy
(is (= ["a" "1"] (util/string->xy "a1")))
(is (= ["b" "12"] (util/string->xy "b12")))
(is (= ["c" "123"] (util/string->xy "c123"))))
(deftest test-keyword->xy
(is (= ["a" "1"] (util/keyword->xy :a1)))
(is (= ["b" "12"] (util/keyword->xy :b12)))
(is (= ["c" "123"] (util/keyword->xy :c123))))
(deftest test-xy->keyword
(is (= :a1 (util/xy->keyword ["a" 1])))
(is (= :b12 (util/xy->keyword ["b" 12])))
(is (= :c123 (util/xy->keyword ["c" "123"]))))
(deftest test-move->string-coord
(is (= "a1" (util/move->string-coord "1a")))
(is (= "a12" (util/move->string-coord "12a")))
(is (= "a123" (util/move->string-coord "123a"))))
(deftest test-move->keyword
(is (= :a1 (util/move->keyword "1a")))
(is (= :a12 (util/move->keyword "12a")))
(is (= :a123 (util/move->keyword "123a"))))
(deftest test-get-friendly-coord
(is (= "1a" (util/get-friendly-coord :a1)))
(is (= "12b" (util/get-friendly-coord :b12)))
(is (= "123c" (util/get-friendly-coord :c123))))
(deftest test-is-item?
(is (= true (util/is-item? [:a1 "*"] (const/items :star))))
(is (= false (util/is-item? [:a1 "."] (const/items :star))))
(is (= true (util/is-item? [:a1 "+"] (const/items :outpost))))
(is (= true (util/is-item? [:a1 "."] (const/items :empty)))))
(deftest test-filter-item
(is (= [:a1 "*"] (util/filter-item [:a1 "*"] (const/items :star))))
(is (= [:a1 "+"] (util/filter-item [:a1 "+"] (const/items :outpost))))
(is (= nil (util/filter-item [:a1 "+"] (const/items :star))))
(is (= [[:a1 "*"] nil nil nil nil nil nil nil nil nil nil nil
[:c3 "*"] nil nil nil
[:d2 "*"] nil nil nil nil nil nil
[:e4 "*"] nil]
(->> (util/fake-game-data :star-map)
(sort)
(map util/filter-star)
(into [])))))
(deftest test-filter-allowed
(is (= #{2 3 4} (util/filter-allowed [1 2 3 4 5] [2 3 4])))
(is (= #{[:a2 "*"]} (util/filter-allowed [[:a1 "."] [:a2 "*"]] [[:a2 "*"]]))))
(deftest test-get-x-coord-range
(is (= ["a" "b" "c" "d" "e"] (util/get-x-coord-range))))
(deftest test-get-y-coord-range
(is (= [1 2 3 4 5] (util/get-y-coord-range))))
(deftest test-in?
(is (= true (util/in? [1 2] 1)))
(is (= true (util/in? [1 2] 2)))
(is (= false (util/in? [1 2] 0)))
(is (= false (util/in? [1 2] 3))))
(deftest test-x-coord?
(is (= true (util/x-coord? "a")))
(is (= true (util/x-coord? "e")))
(is (= false (util/x-coord? "f"))))
(deftest test-y-coord?
(is (= false (util/y-coord? 0)))
(is (= true (util/y-coord? 1)))
(is (= true (util/y-coord? 5)))
(is (= false (util/y-coord? 6))))
(deftest test-serialize-game-data
(is (= {:rand nil} (util/serialize-game-data {:rand "hey!"}))))
(deftest test-get-players
(is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
(map #(% :name) (util/get-players util/fake-game-data)))))
(deftest test-get-players
(is (= 3 (util/get-player-count util/fake-game-data))))
(deftest test-get-max-total-moves
(is (= 6 (util/get-max-total-moves util/fake-game-data)))
(is (= 9 (util/get-max-total-moves 3 3)))
(is (= 40 (util/get-max-total-moves 10 4)))
(is (= 15 (util/get-max-total-moves 1 15)))
(is (= 1 (util/get-max-total-moves 1 1)))
(is (= 0 (util/get-max-total-moves 0 0))))
(deftest test-get-company-name
(is (= "Altair Starways" (util/get-company-name :A)))
(is (= "Luyten, Ltd." (util/get-company-name :L))))
(deftest test-get-companies
(is (= ["Altair Starways"
"Betelgeuse, Ltd."
"Capella Cargo Co."
"Denebola Shippers"
"Eridani Expediters"]
(util/get-companies)))
(is (= ["Al" "Be" "Ca"]
(util/get-companies util/fake-game-data))))
(deftest test-get-companies-letters
(is (= ["A" "B" "C" "D" "E"]
(util/get-companies-letters)))
(is (= ["A" "B" "C"]
(util/get-companies-letters util/fake-game-data))))
(deftest test-count-occurances
(is (= {3 1, 2 2, 1 3}
(util/count-occurances [1 1 1 2 2 3]))))
(deftest test-company?
(is (= true (util/company? "A")))
(is (= false (util/company? "+"))))
(deftest test-star?
(is (= true (util/star? "*")))
(is (= false (util/star? "+"))))
(deftest test-outpost?
(is (= true (util/outpost? "+")))
(is (= false (util/outpost? "A"))))
(deftest test-get-color-tuple
(is (= "0;32" (util/get-color-tuple :green :dark)))
const/end-color
(is (= "1;32" (util/get-color-tuple :green :light)))
const/end-color
(is (= "0;30" (util/get-color-tuple :black :dark)))
const/end-color)
(deftest test-start-color
(is (= "\33[0;32m" (util/start-color :green :dark)))
const/end-color
(is (= "\33[1;32m" (util/start-color :green :light)))
const/end-color
(is (= "\33[0;30m" (util/start-color :black :dark)))
const/end-color)
(deftest test-colorize
(is (= "\33[1;37mSpace!\33[m" (util/colorize "Space!")))
(is (= "\33[0;30mSpace!\33[m" (util/colorize "Space!" :black)))
(is (= "\33[1;37mSpace!\33[m"
(util/colorize "Space!" :white))))
|
[
{
"context": " {cognito-developer-provider-name \"noone@nowhere.com\"}\n 86400))\n {{:key",
"end": 993,
"score": 0.9998164176940918,
"start": 976,
"tag": "EMAIL",
"value": "noone@nowhere.com"
}
] | test/eulalie/test/sts.cljc | nervous-systems/eulalie | 93 | (ns eulalie.test.sts
(:require [eulalie.core :as eulalie]
[eulalie.sts]
[eulalie.test.common :as test.common]
[eulalie.util :refer [env!]]
#? (:clj [clojure.test :refer [deftest is]]
:cljs [cljs.test :refer-macros [deftest is]])
[eulalie.cognito.util :refer [get-open-id-token-for-developer-identity!]]
[glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]]))
(def cognito-developer-provider-name (env! "COGNITO_DEVELOPER_PROVIDER_NAME"))
(def cognito-identity-pool-id (env! "COGNITO_IDENTITY_POOL_ID"))
(def cognito-role-arn (env! "COGNITO_ROLE_ARN"))
(deftest test-assume-role-with-web-identity!
(test.common/with-aws
(fn [creds]
(go-catching
(let [{:keys [token]}
(<? (get-open-id-token-for-developer-identity!
creds
cognito-identity-pool-id
{cognito-developer-provider-name "noone@nowhere.com"}
86400))
{{:keys [access-key-id secret-access-key session-token]} :credentials}
(<? (test.common/sts!
creds
:assume-role-with-web-identity
{:role-arn cognito-role-arn
:web-identity-token token
:role-session-name "web-identity"}))]
(is (string? access-key-id))
(is (string? secret-access-key))
(is (string? session-token)))))))
| 81851 | (ns eulalie.test.sts
(:require [eulalie.core :as eulalie]
[eulalie.sts]
[eulalie.test.common :as test.common]
[eulalie.util :refer [env!]]
#? (:clj [clojure.test :refer [deftest is]]
:cljs [cljs.test :refer-macros [deftest is]])
[eulalie.cognito.util :refer [get-open-id-token-for-developer-identity!]]
[glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]]))
(def cognito-developer-provider-name (env! "COGNITO_DEVELOPER_PROVIDER_NAME"))
(def cognito-identity-pool-id (env! "COGNITO_IDENTITY_POOL_ID"))
(def cognito-role-arn (env! "COGNITO_ROLE_ARN"))
(deftest test-assume-role-with-web-identity!
(test.common/with-aws
(fn [creds]
(go-catching
(let [{:keys [token]}
(<? (get-open-id-token-for-developer-identity!
creds
cognito-identity-pool-id
{cognito-developer-provider-name "<EMAIL>"}
86400))
{{:keys [access-key-id secret-access-key session-token]} :credentials}
(<? (test.common/sts!
creds
:assume-role-with-web-identity
{:role-arn cognito-role-arn
:web-identity-token token
:role-session-name "web-identity"}))]
(is (string? access-key-id))
(is (string? secret-access-key))
(is (string? session-token)))))))
| true | (ns eulalie.test.sts
(:require [eulalie.core :as eulalie]
[eulalie.sts]
[eulalie.test.common :as test.common]
[eulalie.util :refer [env!]]
#? (:clj [clojure.test :refer [deftest is]]
:cljs [cljs.test :refer-macros [deftest is]])
[eulalie.cognito.util :refer [get-open-id-token-for-developer-identity!]]
[glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]]))
(def cognito-developer-provider-name (env! "COGNITO_DEVELOPER_PROVIDER_NAME"))
(def cognito-identity-pool-id (env! "COGNITO_IDENTITY_POOL_ID"))
(def cognito-role-arn (env! "COGNITO_ROLE_ARN"))
(deftest test-assume-role-with-web-identity!
(test.common/with-aws
(fn [creds]
(go-catching
(let [{:keys [token]}
(<? (get-open-id-token-for-developer-identity!
creds
cognito-identity-pool-id
{cognito-developer-provider-name "PI:EMAIL:<EMAIL>END_PI"}
86400))
{{:keys [access-key-id secret-access-key session-token]} :credentials}
(<? (test.common/sts!
creds
:assume-role-with-web-identity
{:role-arn cognito-role-arn
:web-identity-token token
:role-session-name "web-identity"}))]
(is (string? access-key-id))
(is (string? secret-access-key))
(is (string? session-token)))))))
|
[
{
"context": "state\n \"The state format:\n{:local {:username \\\"John\\\"\n :hand [\\\"♠2\\\" \\\"♥Q\\\"]}\n :game {:name \\",
"end": 67,
"score": 0.9979532361030579,
"start": 63,
"tag": "USERNAME",
"value": "John"
},
{
"context": "ayercount 2\n :joined 1\n :players (\\\"John\\\")\n :deck [\\\"♠A\\\" \\\"♥9\\\" \\\"♦6\\\" \\\"♣K\\\"]}\n}",
"end": 200,
"score": 0.9511545896530151,
"start": 196,
"tag": "NAME",
"value": "John"
}
] | src/cardgame/state.clj | ykarikos/cardgame | 0 | (ns cardgame.state
"The state format:
{:local {:username \"John\"
:hand [\"♠2\" \"♥Q\"]}
:game {:name \"evening-bridge\"
:playercount 2
:joined 1
:players (\"John\")
:deck [\"♠A\" \"♥9\" \"♦6\" \"♣K\"]}
}")
(def prompt-symbol "> ")
(def state (atom {}))
(defn initial-state [username]
(swap! state merge
{:local
{:hand []
:username username}}))
(defn- merge-state [state new-state]
(let [new-hand (-> new-state :local :hand)
new-game (:game new-state)
combined-hand (into (-> state :local :hand) new-hand)] ; TODO sort hand
{:local (merge (:local state) {:hand combined-hand})
:game (merge (:game state) new-game)}))
(defn change-state [new-state]
; (println "new state" new-state)
(swap! state merge-state new-state))
(defn game-full? []
(let [playercount (-> @state :game :playercount)
joined (-> @state :game :joined)]
(and joined playercount (= joined playercount))))
(defn join-player [username]
(let [state-change
{:game {:joined (+ 1 (-> @state :game :joined))
:players (cons username (-> @state :game :players))}}
new-game-state (:game (change-state state-change))]
{:game (dissoc new-game-state :deck)}))
(defn print-prompt []
(print (str (-> @state :game :name) prompt-symbol))
(flush))
(defn print-msg [message]
(when message
(println (str "\n" message))
(print-prompt)))
| 104787 | (ns cardgame.state
"The state format:
{:local {:username \"John\"
:hand [\"♠2\" \"♥Q\"]}
:game {:name \"evening-bridge\"
:playercount 2
:joined 1
:players (\"<NAME>\")
:deck [\"♠A\" \"♥9\" \"♦6\" \"♣K\"]}
}")
(def prompt-symbol "> ")
(def state (atom {}))
(defn initial-state [username]
(swap! state merge
{:local
{:hand []
:username username}}))
(defn- merge-state [state new-state]
(let [new-hand (-> new-state :local :hand)
new-game (:game new-state)
combined-hand (into (-> state :local :hand) new-hand)] ; TODO sort hand
{:local (merge (:local state) {:hand combined-hand})
:game (merge (:game state) new-game)}))
(defn change-state [new-state]
; (println "new state" new-state)
(swap! state merge-state new-state))
(defn game-full? []
(let [playercount (-> @state :game :playercount)
joined (-> @state :game :joined)]
(and joined playercount (= joined playercount))))
(defn join-player [username]
(let [state-change
{:game {:joined (+ 1 (-> @state :game :joined))
:players (cons username (-> @state :game :players))}}
new-game-state (:game (change-state state-change))]
{:game (dissoc new-game-state :deck)}))
(defn print-prompt []
(print (str (-> @state :game :name) prompt-symbol))
(flush))
(defn print-msg [message]
(when message
(println (str "\n" message))
(print-prompt)))
| true | (ns cardgame.state
"The state format:
{:local {:username \"John\"
:hand [\"♠2\" \"♥Q\"]}
:game {:name \"evening-bridge\"
:playercount 2
:joined 1
:players (\"PI:NAME:<NAME>END_PI\")
:deck [\"♠A\" \"♥9\" \"♦6\" \"♣K\"]}
}")
(def prompt-symbol "> ")
(def state (atom {}))
(defn initial-state [username]
(swap! state merge
{:local
{:hand []
:username username}}))
(defn- merge-state [state new-state]
(let [new-hand (-> new-state :local :hand)
new-game (:game new-state)
combined-hand (into (-> state :local :hand) new-hand)] ; TODO sort hand
{:local (merge (:local state) {:hand combined-hand})
:game (merge (:game state) new-game)}))
(defn change-state [new-state]
; (println "new state" new-state)
(swap! state merge-state new-state))
(defn game-full? []
(let [playercount (-> @state :game :playercount)
joined (-> @state :game :joined)]
(and joined playercount (= joined playercount))))
(defn join-player [username]
(let [state-change
{:game {:joined (+ 1 (-> @state :game :joined))
:players (cons username (-> @state :game :players))}}
new-game-state (:game (change-state state-change))]
{:game (dissoc new-game-state :deck)}))
(defn print-prompt []
(print (str (-> @state :game :name) prompt-symbol))
(flush))
(defn print-msg [message]
(when message
(println (str "\n" message))
(print-prompt)))
|
[
{
"context": "^{ :doc \"com.sb.auditor :: audit\"\n :author \"Istvan Szukacs\" }\nauditor.audit\n (:require\n [clojure.tools.",
"end": 673,
"score": 0.9998898506164551,
"start": 659,
"tag": "NAME",
"value": "Istvan Szukacs"
}
] | src/auditor/audit.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 :: audit"
:author "Istvan Szukacs" }
auditor.audit
(:require
[clojure.tools.logging :as log ]
[auditor.iam :as iam ]
[auditor.sts :as sts ]
[auditor.auth :as auth ]
)
(:import
[clojure.lang
PersistentArrayMap
PersistentList ]
[com.amazonaws
AmazonServiceException
ClientConfiguration ]
[com.amazonaws.auth
AWSCredentials
BasicAWSCredentials ]
[com.amazonaws.auth.profile
ProfileCredentialsProvider]
[com.amazonaws.services.identitymanagement
AmazonIdentityManagementAsyncClient]
)
(:gen-class))
;; this part can work two ways: either using a
;; credential (access key + secret key) or
;; using sts and getting a session that way
(def audits [:get-account-summary iam/get-account-summary])
(defn run-with-creds
"Runs audit with the supplied credentials"
[creds-file profile]
(let [^BasicAWSCredentials creds (auth/create-basic-aws-credentials-file creds-file profile)
^AmazonIdentityManagementAsyncClient iam-client (iam/create-iam-async-client creds)
;; audit first hm
account-summary (iam/get-account-summary iam-client)
users (iam/users->clj (iam/list-users iam-client))
groups (iam/groups->clj (iam/list-groups iam-client))
user-managed-polices (iam/get-user-managed-policies iam-client users)
group-managed-policies (iam/get-group-managed-policies iam-client groups) ]
{ :account-summary account-summary
:users users
:groups groups
:user-managed-polices user-managed-polices
:group-managed-policies group-managed-policies } ))
(defn run-with-sts [] :ok)
| 109911 | ;; 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 :: audit"
:author "<NAME>" }
auditor.audit
(:require
[clojure.tools.logging :as log ]
[auditor.iam :as iam ]
[auditor.sts :as sts ]
[auditor.auth :as auth ]
)
(:import
[clojure.lang
PersistentArrayMap
PersistentList ]
[com.amazonaws
AmazonServiceException
ClientConfiguration ]
[com.amazonaws.auth
AWSCredentials
BasicAWSCredentials ]
[com.amazonaws.auth.profile
ProfileCredentialsProvider]
[com.amazonaws.services.identitymanagement
AmazonIdentityManagementAsyncClient]
)
(:gen-class))
;; this part can work two ways: either using a
;; credential (access key + secret key) or
;; using sts and getting a session that way
(def audits [:get-account-summary iam/get-account-summary])
(defn run-with-creds
"Runs audit with the supplied credentials"
[creds-file profile]
(let [^BasicAWSCredentials creds (auth/create-basic-aws-credentials-file creds-file profile)
^AmazonIdentityManagementAsyncClient iam-client (iam/create-iam-async-client creds)
;; audit first hm
account-summary (iam/get-account-summary iam-client)
users (iam/users->clj (iam/list-users iam-client))
groups (iam/groups->clj (iam/list-groups iam-client))
user-managed-polices (iam/get-user-managed-policies iam-client users)
group-managed-policies (iam/get-group-managed-policies iam-client groups) ]
{ :account-summary account-summary
:users users
:groups groups
:user-managed-polices user-managed-polices
:group-managed-policies group-managed-policies } ))
(defn run-with-sts [] :ok)
| 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 :: audit"
:author "PI:NAME:<NAME>END_PI" }
auditor.audit
(:require
[clojure.tools.logging :as log ]
[auditor.iam :as iam ]
[auditor.sts :as sts ]
[auditor.auth :as auth ]
)
(:import
[clojure.lang
PersistentArrayMap
PersistentList ]
[com.amazonaws
AmazonServiceException
ClientConfiguration ]
[com.amazonaws.auth
AWSCredentials
BasicAWSCredentials ]
[com.amazonaws.auth.profile
ProfileCredentialsProvider]
[com.amazonaws.services.identitymanagement
AmazonIdentityManagementAsyncClient]
)
(:gen-class))
;; this part can work two ways: either using a
;; credential (access key + secret key) or
;; using sts and getting a session that way
(def audits [:get-account-summary iam/get-account-summary])
(defn run-with-creds
"Runs audit with the supplied credentials"
[creds-file profile]
(let [^BasicAWSCredentials creds (auth/create-basic-aws-credentials-file creds-file profile)
^AmazonIdentityManagementAsyncClient iam-client (iam/create-iam-async-client creds)
;; audit first hm
account-summary (iam/get-account-summary iam-client)
users (iam/users->clj (iam/list-users iam-client))
groups (iam/groups->clj (iam/list-groups iam-client))
user-managed-polices (iam/get-user-managed-policies iam-client users)
group-managed-policies (iam/get-group-managed-policies iam-client groups) ]
{ :account-summary account-summary
:users users
:groups groups
:user-managed-polices user-managed-polices
:group-managed-policies group-managed-policies } ))
(defn run-with-sts [] :ok)
|
[
{
"context": "event-key ;; keyword, like :player/player-toggle-sneak\n handler-fn ;; (fn [event]",
"end": 1398,
"score": 0.5843952894210815,
"start": 1398,
"tag": "KEY",
"value": ""
},
{
"context": "ey ;; keyword, like :player/player-toggle-sneak\n handler-fn ;; (fn [event] ...)\n ",
"end": 1405,
"score": 0.5615250468254089,
"start": 1405,
"tag": "KEY",
"value": ""
}
] | src/clojure/bukkitclj/event.clj | cpmcdaniel/Bukkit4Clojure | 3 | (ns bukkitclj.event
"Event handlers for Bukkit"
(:require [bukkitclj.util :as util]
[bukkitclj.logging :as log]
[bukkitclj.bukkit :as bk]
[clojure.string :as st])
(:import [org.bukkit.plugin Plugin]))
(defonce actions (util/map-enums 'action org.bukkit.event.block.Action))
(defonce priorities (util/map-enums 'priority org.bukkit.event.EventPriority))
(def event-package "org.bukkit.event")
(defn class->event-key [^Class cls]
(let [segments (-> cls
util/class->kebab-case
(subs (inc (count event-package)))
(.replaceAll "-event$" "")
(.split "\\."))
keyword-ns (st/join "." (butlast segments))]
(keyword keyword-ns (last segments))))
(defn event-key->class [event-key]
(util/kebab-case->class
(str event-package
"."
(namespace event-key)
"."
(name event-key)
"-event")))
(defonce events
(set (map class->event-key
(util/find-subclasses org.bukkit.event.Event event-package))))
(defn register-event
([plugin event-key handler-fn]
(register-event plugin event-key handler-fn :priority/normal false))
([plugin event-key handler-fn priority-key]
(register-event plugin event-key handler-fn priority-key false))
([^Plugin plugin
event-key ;; keyword, like :player/player-toggle-sneak
handler-fn ;; (fn [event] ...)
priority-key ;; :priority/normal, :priority/high, etc...
ignore-cancelled?] ;; defaults to false
(if-let [^Class event-class (event-key->class event-key)]
(.registerEvent
(bk/plugin-manager)
event-class
(proxy [org.bukkit.event.Listener] [])
(get priorities priority-key :priority/normal)
(proxy [org.bukkit.plugin.EventExecutor] []
(execute [_ e]
(handler-fn e)))
plugin
(boolean ignore-cancelled?))
(log/warning plugin "Unrecognized event-key %s. Ignoring event registration." event-key))))
;; Discovery methods
(defn find-event [^String search]
(filter #(.contains (str %) (.toLowerCase search)) events))
(def boring-methods #{"getClass"
"notify"
"notifyAll"
"isAsynchronous"
"toString"
"hashCode"
"equals"
"wait"
"callEvent"
"getEventName"
"getHandlers"
"getHandlerList"})
(defn describe-event [event-key]
(let [cls (event-key->class event-key)]
(set (remove boring-methods
(map #(.getName %) (seq (.getMethods cls)))))))
(comment
(take 6 events)
(find-event "player-toggle")
(describe-event :player/player-toggle-sneak)
;; use a reference to your own plugin instance here...
(let [plugin (deref bukkitclj.repl/plugin-ref)]
(register-event plugin
:player/player-toggle-sneak
(fn [e] (println "event triggered!"))
:priority/normal)))
| 122668 | (ns bukkitclj.event
"Event handlers for Bukkit"
(:require [bukkitclj.util :as util]
[bukkitclj.logging :as log]
[bukkitclj.bukkit :as bk]
[clojure.string :as st])
(:import [org.bukkit.plugin Plugin]))
(defonce actions (util/map-enums 'action org.bukkit.event.block.Action))
(defonce priorities (util/map-enums 'priority org.bukkit.event.EventPriority))
(def event-package "org.bukkit.event")
(defn class->event-key [^Class cls]
(let [segments (-> cls
util/class->kebab-case
(subs (inc (count event-package)))
(.replaceAll "-event$" "")
(.split "\\."))
keyword-ns (st/join "." (butlast segments))]
(keyword keyword-ns (last segments))))
(defn event-key->class [event-key]
(util/kebab-case->class
(str event-package
"."
(namespace event-key)
"."
(name event-key)
"-event")))
(defonce events
(set (map class->event-key
(util/find-subclasses org.bukkit.event.Event event-package))))
(defn register-event
([plugin event-key handler-fn]
(register-event plugin event-key handler-fn :priority/normal false))
([plugin event-key handler-fn priority-key]
(register-event plugin event-key handler-fn priority-key false))
([^Plugin plugin
event-key ;; keyword, like :player/player<KEY>-toggle<KEY>-sneak
handler-fn ;; (fn [event] ...)
priority-key ;; :priority/normal, :priority/high, etc...
ignore-cancelled?] ;; defaults to false
(if-let [^Class event-class (event-key->class event-key)]
(.registerEvent
(bk/plugin-manager)
event-class
(proxy [org.bukkit.event.Listener] [])
(get priorities priority-key :priority/normal)
(proxy [org.bukkit.plugin.EventExecutor] []
(execute [_ e]
(handler-fn e)))
plugin
(boolean ignore-cancelled?))
(log/warning plugin "Unrecognized event-key %s. Ignoring event registration." event-key))))
;; Discovery methods
(defn find-event [^String search]
(filter #(.contains (str %) (.toLowerCase search)) events))
(def boring-methods #{"getClass"
"notify"
"notifyAll"
"isAsynchronous"
"toString"
"hashCode"
"equals"
"wait"
"callEvent"
"getEventName"
"getHandlers"
"getHandlerList"})
(defn describe-event [event-key]
(let [cls (event-key->class event-key)]
(set (remove boring-methods
(map #(.getName %) (seq (.getMethods cls)))))))
(comment
(take 6 events)
(find-event "player-toggle")
(describe-event :player/player-toggle-sneak)
;; use a reference to your own plugin instance here...
(let [plugin (deref bukkitclj.repl/plugin-ref)]
(register-event plugin
:player/player-toggle-sneak
(fn [e] (println "event triggered!"))
:priority/normal)))
| true | (ns bukkitclj.event
"Event handlers for Bukkit"
(:require [bukkitclj.util :as util]
[bukkitclj.logging :as log]
[bukkitclj.bukkit :as bk]
[clojure.string :as st])
(:import [org.bukkit.plugin Plugin]))
(defonce actions (util/map-enums 'action org.bukkit.event.block.Action))
(defonce priorities (util/map-enums 'priority org.bukkit.event.EventPriority))
(def event-package "org.bukkit.event")
(defn class->event-key [^Class cls]
(let [segments (-> cls
util/class->kebab-case
(subs (inc (count event-package)))
(.replaceAll "-event$" "")
(.split "\\."))
keyword-ns (st/join "." (butlast segments))]
(keyword keyword-ns (last segments))))
(defn event-key->class [event-key]
(util/kebab-case->class
(str event-package
"."
(namespace event-key)
"."
(name event-key)
"-event")))
(defonce events
(set (map class->event-key
(util/find-subclasses org.bukkit.event.Event event-package))))
(defn register-event
([plugin event-key handler-fn]
(register-event plugin event-key handler-fn :priority/normal false))
([plugin event-key handler-fn priority-key]
(register-event plugin event-key handler-fn priority-key false))
([^Plugin plugin
event-key ;; keyword, like :player/playerPI:KEY:<KEY>END_PI-togglePI:KEY:<KEY>END_PI-sneak
handler-fn ;; (fn [event] ...)
priority-key ;; :priority/normal, :priority/high, etc...
ignore-cancelled?] ;; defaults to false
(if-let [^Class event-class (event-key->class event-key)]
(.registerEvent
(bk/plugin-manager)
event-class
(proxy [org.bukkit.event.Listener] [])
(get priorities priority-key :priority/normal)
(proxy [org.bukkit.plugin.EventExecutor] []
(execute [_ e]
(handler-fn e)))
plugin
(boolean ignore-cancelled?))
(log/warning plugin "Unrecognized event-key %s. Ignoring event registration." event-key))))
;; Discovery methods
(defn find-event [^String search]
(filter #(.contains (str %) (.toLowerCase search)) events))
(def boring-methods #{"getClass"
"notify"
"notifyAll"
"isAsynchronous"
"toString"
"hashCode"
"equals"
"wait"
"callEvent"
"getEventName"
"getHandlers"
"getHandlerList"})
(defn describe-event [event-key]
(let [cls (event-key->class event-key)]
(set (remove boring-methods
(map #(.getName %) (seq (.getMethods cls)))))))
(comment
(take 6 events)
(find-event "player-toggle")
(describe-event :player/player-toggle-sneak)
;; use a reference to your own plugin instance here...
(let [plugin (deref bukkitclj.repl/plugin-ref)]
(register-event plugin
:player/player-toggle-sneak
(fn [e] (println "event triggered!"))
:priority/normal)))
|
[
{
"context": " {\"EC2KeyName\" \"toms-cap-pre-prod\"\n ",
"end": 1345,
"score": 0.5601876974105835,
"start": 1339,
"tag": "KEY",
"value": "s-cap-"
}
] | project.clj | thomaswhitcomb/clojoku | 0 | (defproject clojoku "0.1.0"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [
[org.clojure/clojure "1.6.0"]
[ring/ring-core "1.3.0"]
[ring/ring-jetty-adapter "1.3.0"]
[compojure "1.1.6"]
[metosin/compojure-api "0.16.2"]
[com.amazonaws/aws-lambda-java-core "1.0.0"]
]
:main ^:skip-aot clojoku.core
:target-path "target/%s"
:plugins [[lein-ring "0.8.11"] [lein-beanstalk "0.2.7"]]
:ring {:handler clojoku.core/app}
:profiles {:uberjar {:aot :all}}
:aws {:beanstalk {:region "us-east-1"
:environments [{:name "development"
:stack {:name "clojoku-stack"
:options { "aws:autoscaling:launchconfiguration" {"IamInstanceProfile" "RootInstanceProfile" "SecurityGroups" "BeanstalkSecurityGroup"} "aws:ec2:vpc" {"VpcId" "VPC" "Subnets" "PrivateSubnet"}
}
}
:options {"aws:autoscaling:launchconfiguration"
{"EC2KeyName" "toms-cap-pre-prod"
"ImageId" "ami-1a249873"}}}
]
}
}
)
| 10987 | (defproject clojoku "0.1.0"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [
[org.clojure/clojure "1.6.0"]
[ring/ring-core "1.3.0"]
[ring/ring-jetty-adapter "1.3.0"]
[compojure "1.1.6"]
[metosin/compojure-api "0.16.2"]
[com.amazonaws/aws-lambda-java-core "1.0.0"]
]
:main ^:skip-aot clojoku.core
:target-path "target/%s"
:plugins [[lein-ring "0.8.11"] [lein-beanstalk "0.2.7"]]
:ring {:handler clojoku.core/app}
:profiles {:uberjar {:aot :all}}
:aws {:beanstalk {:region "us-east-1"
:environments [{:name "development"
:stack {:name "clojoku-stack"
:options { "aws:autoscaling:launchconfiguration" {"IamInstanceProfile" "RootInstanceProfile" "SecurityGroups" "BeanstalkSecurityGroup"} "aws:ec2:vpc" {"VpcId" "VPC" "Subnets" "PrivateSubnet"}
}
}
:options {"aws:autoscaling:launchconfiguration"
{"EC2KeyName" "tom<KEY>pre-prod"
"ImageId" "ami-1a249873"}}}
]
}
}
)
| true | (defproject clojoku "0.1.0"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [
[org.clojure/clojure "1.6.0"]
[ring/ring-core "1.3.0"]
[ring/ring-jetty-adapter "1.3.0"]
[compojure "1.1.6"]
[metosin/compojure-api "0.16.2"]
[com.amazonaws/aws-lambda-java-core "1.0.0"]
]
:main ^:skip-aot clojoku.core
:target-path "target/%s"
:plugins [[lein-ring "0.8.11"] [lein-beanstalk "0.2.7"]]
:ring {:handler clojoku.core/app}
:profiles {:uberjar {:aot :all}}
:aws {:beanstalk {:region "us-east-1"
:environments [{:name "development"
:stack {:name "clojoku-stack"
:options { "aws:autoscaling:launchconfiguration" {"IamInstanceProfile" "RootInstanceProfile" "SecurityGroups" "BeanstalkSecurityGroup"} "aws:ec2:vpc" {"VpcId" "VPC" "Subnets" "PrivateSubnet"}
}
}
:options {"aws:autoscaling:launchconfiguration"
{"EC2KeyName" "tomPI:KEY:<KEY>END_PIpre-prod"
"ImageId" "ami-1a249873"}}}
]
}
}
)
|
[
{
"context": "\n\n\n\n;;\n;; Initial state\n;;\n\n;; FIXME: [2022-02-15, ilshat@sultanov.team]\n;; - Add events to read user profile and tokens ",
"end": 402,
"score": 0.9999188184738159,
"start": 382,
"tag": "EMAIL",
"value": "ilshat@sultanov.team"
}
] | src/main/clojure/metaverse/renderer/db.cljs | sultanov-team/metaverse | 1 | (ns metaverse.renderer.db
(:require
[day8.re-frame.tracing :refer-macros [fn-traced]]
[metaverse.renderer.news.core]
[metaverse.renderer.profile.core]
[re-frame.core :as rf]))
;;
;; Defaults
;;
(def system-theme
(if (.. js/window (matchMedia "(prefers-color-scheme: dark)") -matches)
"dark"
"light"))
;;
;; Initial state
;;
;; FIXME: [2022-02-15, ilshat@sultanov.team]
;; - Add events to read user profile and tokens from the secret store
(rf/reg-event-fx
::init
[(rf/inject-cofx :local-storage/get-items [:metaverse/theme :metaverse/user])]
(fn-traced [{{:metaverse/keys [theme user]} :local-storage} _]
(let [theme (or theme system-theme)]
{:db {:app {:initialized? false}
:user user}
:fx [[:dispatch-later {:ms 1000 :dispatch [:app/initialized]}]
[:dispatch [:app/set-theme theme]]]})))
;; Initialization
(rf/reg-event-db
:app/initialized
(fn [db _]
(assoc-in db [:app :initialized?] true)))
(rf/reg-sub
:app/initialized?
(fn [db]
(get-in db [:app :initialized?] false)))
;; Readiness
(rf/reg-sub
:app/readiness
(fn [db]
(get-in db [:app :readiness])))
(rf/reg-event-fx
:set-readiness
(fn [{db :db} [_ key state]]
(case state
:ready {:db (assoc-in db [:app :readiness key] state)
:dispatch-later [{:ms 1500, :dispatch [:set-readiness key nil]}]}
nil {:db (update-in db [:app :readiness] dissoc key)}
{:db (assoc-in db [:app :readiness key] state)})))
;; Theme
(defn toggle-theme
[theme]
(case theme
"light" "dark"
"dark" "light"
system-theme))
(rf/reg-fx
:app/set-theme
(fn-traced [next-theme]
(let [previous-theme (toggle-theme next-theme)]
(when previous-theme
(.remove (.. js/document -documentElement -classList) (name previous-theme)))
(when next-theme
(.add (.. js/document -documentElement -classList) (name next-theme))))))
(rf/reg-event-fx
:app/set-theme
(fn-traced [{db :db} [_ theme]]
{:db (assoc-in db [:app :theme] theme)
:app/set-theme theme
:local-storage/set-item [:metaverse/theme theme]}))
(rf/reg-event-fx
:app/toggle-theme
(fn-traced [{db :db} _]
(let [current-theme (get-in db [:app :theme])
next-theme (toggle-theme current-theme)]
{:dispatch [:app/set-theme next-theme]})))
(rf/reg-sub
:app/theme
(fn [db]
(get-in db [:app :theme] system-theme)))
| 123709 | (ns metaverse.renderer.db
(:require
[day8.re-frame.tracing :refer-macros [fn-traced]]
[metaverse.renderer.news.core]
[metaverse.renderer.profile.core]
[re-frame.core :as rf]))
;;
;; Defaults
;;
(def system-theme
(if (.. js/window (matchMedia "(prefers-color-scheme: dark)") -matches)
"dark"
"light"))
;;
;; Initial state
;;
;; FIXME: [2022-02-15, <EMAIL>]
;; - Add events to read user profile and tokens from the secret store
(rf/reg-event-fx
::init
[(rf/inject-cofx :local-storage/get-items [:metaverse/theme :metaverse/user])]
(fn-traced [{{:metaverse/keys [theme user]} :local-storage} _]
(let [theme (or theme system-theme)]
{:db {:app {:initialized? false}
:user user}
:fx [[:dispatch-later {:ms 1000 :dispatch [:app/initialized]}]
[:dispatch [:app/set-theme theme]]]})))
;; Initialization
(rf/reg-event-db
:app/initialized
(fn [db _]
(assoc-in db [:app :initialized?] true)))
(rf/reg-sub
:app/initialized?
(fn [db]
(get-in db [:app :initialized?] false)))
;; Readiness
(rf/reg-sub
:app/readiness
(fn [db]
(get-in db [:app :readiness])))
(rf/reg-event-fx
:set-readiness
(fn [{db :db} [_ key state]]
(case state
:ready {:db (assoc-in db [:app :readiness key] state)
:dispatch-later [{:ms 1500, :dispatch [:set-readiness key nil]}]}
nil {:db (update-in db [:app :readiness] dissoc key)}
{:db (assoc-in db [:app :readiness key] state)})))
;; Theme
(defn toggle-theme
[theme]
(case theme
"light" "dark"
"dark" "light"
system-theme))
(rf/reg-fx
:app/set-theme
(fn-traced [next-theme]
(let [previous-theme (toggle-theme next-theme)]
(when previous-theme
(.remove (.. js/document -documentElement -classList) (name previous-theme)))
(when next-theme
(.add (.. js/document -documentElement -classList) (name next-theme))))))
(rf/reg-event-fx
:app/set-theme
(fn-traced [{db :db} [_ theme]]
{:db (assoc-in db [:app :theme] theme)
:app/set-theme theme
:local-storage/set-item [:metaverse/theme theme]}))
(rf/reg-event-fx
:app/toggle-theme
(fn-traced [{db :db} _]
(let [current-theme (get-in db [:app :theme])
next-theme (toggle-theme current-theme)]
{:dispatch [:app/set-theme next-theme]})))
(rf/reg-sub
:app/theme
(fn [db]
(get-in db [:app :theme] system-theme)))
| true | (ns metaverse.renderer.db
(:require
[day8.re-frame.tracing :refer-macros [fn-traced]]
[metaverse.renderer.news.core]
[metaverse.renderer.profile.core]
[re-frame.core :as rf]))
;;
;; Defaults
;;
(def system-theme
(if (.. js/window (matchMedia "(prefers-color-scheme: dark)") -matches)
"dark"
"light"))
;;
;; Initial state
;;
;; FIXME: [2022-02-15, PI:EMAIL:<EMAIL>END_PI]
;; - Add events to read user profile and tokens from the secret store
(rf/reg-event-fx
::init
[(rf/inject-cofx :local-storage/get-items [:metaverse/theme :metaverse/user])]
(fn-traced [{{:metaverse/keys [theme user]} :local-storage} _]
(let [theme (or theme system-theme)]
{:db {:app {:initialized? false}
:user user}
:fx [[:dispatch-later {:ms 1000 :dispatch [:app/initialized]}]
[:dispatch [:app/set-theme theme]]]})))
;; Initialization
(rf/reg-event-db
:app/initialized
(fn [db _]
(assoc-in db [:app :initialized?] true)))
(rf/reg-sub
:app/initialized?
(fn [db]
(get-in db [:app :initialized?] false)))
;; Readiness
(rf/reg-sub
:app/readiness
(fn [db]
(get-in db [:app :readiness])))
(rf/reg-event-fx
:set-readiness
(fn [{db :db} [_ key state]]
(case state
:ready {:db (assoc-in db [:app :readiness key] state)
:dispatch-later [{:ms 1500, :dispatch [:set-readiness key nil]}]}
nil {:db (update-in db [:app :readiness] dissoc key)}
{:db (assoc-in db [:app :readiness key] state)})))
;; Theme
(defn toggle-theme
[theme]
(case theme
"light" "dark"
"dark" "light"
system-theme))
(rf/reg-fx
:app/set-theme
(fn-traced [next-theme]
(let [previous-theme (toggle-theme next-theme)]
(when previous-theme
(.remove (.. js/document -documentElement -classList) (name previous-theme)))
(when next-theme
(.add (.. js/document -documentElement -classList) (name next-theme))))))
(rf/reg-event-fx
:app/set-theme
(fn-traced [{db :db} [_ theme]]
{:db (assoc-in db [:app :theme] theme)
:app/set-theme theme
:local-storage/set-item [:metaverse/theme theme]}))
(rf/reg-event-fx
:app/toggle-theme
(fn-traced [{db :db} _]
(let [current-theme (get-in db [:app :theme])
next-theme (toggle-theme current-theme)]
{:dispatch [:app/set-theme next-theme]})))
(rf/reg-sub
:app/theme
(fn [db]
(get-in db [:app :theme] system-theme)))
|
[
{
"context": "org.httpkit.client :as http]))\n\n(def example-key \"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY\")\n(def headers\n {\"X-Amz-Algorithm\" \"AWS4-HMA",
"end": 228,
"score": 0.9997602105140686,
"start": 188,
"tag": "KEY",
"value": "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"
},
{
"context": " \"AWS4-HMAC-SHA256\"\n \"X-Amz-Credential\" \"AKIDEXAMPLE/20150830/us-east-1/iam/aws4_request\"\n \"X-Amz-Date\" \"20150830T123600Z\"\n \"",
"end": 361,
"score": 0.9980363249778748,
"start": 314,
"tag": "KEY",
"value": "AKIDEXAMPLE/20150830/us-east-1/iam/aws4_request"
}
] | test/t/auth/headers.clj | peterromfeldhk/clj-cfn | 0 | (ns t.auth.headers
(:use midje.sweet)
(:require
[clojure.string :as s]
[clj-time.core :as t]
[clj-time.format :as f]
[org.httpkit.client :as http]))
(def example-key "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY")
(def headers
{"X-Amz-Algorithm" "AWS4-HMAC-SHA256"
"X-Amz-Credential" "AKIDEXAMPLE/20150830/us-east-1/iam/aws4_request"
"X-Amz-Date" "20150830T123600Z"
"X-Amz-SignedHeaders" "content-type;host;x-amz-date"})
(def params
{:headers headers
:query-params {"Action" "ListUsers"
"Version" "2010-05-08"}})
(def header-formatter (f/formatters :basic-date-time-no-ms))
(def component-formatter (f/formatters :basic-date))
(def suite-prefix (str (System/getenv "PWD") "/test/aws4_testsuite/"))
(defn decapitalize [string]
(apply str
(s/lower-case (first string))
(rest string)))
(defn req->creq [method url params date host signature]
(str method "\n"
url "\n"
params "\n"
(decapitalize date) "\n"
(decapitalize host) "\n\n"
signature))
(defn parse-req [req]
)
(fact "test 1"
(->> (slurp (str suite-prefix "get-vanilla-query-order-key-case.req"))
parse-req
(apply req->creq)) => (slurp (str suite-prefix "get-vanilla-query-order-key-case.creq")))
(-> (slurp (str suite-prefix "get-vanilla-query-order-key-case.req"))
s/split-lines
println)
(println (slurp (str suite-prefix "get-vanilla-query-order-key-case.creq")))
;(with-open [resp (-> (java.net.URL. "https://www.google.com")
; .openStream
; java.io.InputStreamReader.
; java.io.BufferedReader.)]
; (->> (line-seq resp)
; (apply str)
; ;println
; ))
| 124258 | (ns t.auth.headers
(:use midje.sweet)
(:require
[clojure.string :as s]
[clj-time.core :as t]
[clj-time.format :as f]
[org.httpkit.client :as http]))
(def example-key "<KEY>")
(def headers
{"X-Amz-Algorithm" "AWS4-HMAC-SHA256"
"X-Amz-Credential" "<KEY>"
"X-Amz-Date" "20150830T123600Z"
"X-Amz-SignedHeaders" "content-type;host;x-amz-date"})
(def params
{:headers headers
:query-params {"Action" "ListUsers"
"Version" "2010-05-08"}})
(def header-formatter (f/formatters :basic-date-time-no-ms))
(def component-formatter (f/formatters :basic-date))
(def suite-prefix (str (System/getenv "PWD") "/test/aws4_testsuite/"))
(defn decapitalize [string]
(apply str
(s/lower-case (first string))
(rest string)))
(defn req->creq [method url params date host signature]
(str method "\n"
url "\n"
params "\n"
(decapitalize date) "\n"
(decapitalize host) "\n\n"
signature))
(defn parse-req [req]
)
(fact "test 1"
(->> (slurp (str suite-prefix "get-vanilla-query-order-key-case.req"))
parse-req
(apply req->creq)) => (slurp (str suite-prefix "get-vanilla-query-order-key-case.creq")))
(-> (slurp (str suite-prefix "get-vanilla-query-order-key-case.req"))
s/split-lines
println)
(println (slurp (str suite-prefix "get-vanilla-query-order-key-case.creq")))
;(with-open [resp (-> (java.net.URL. "https://www.google.com")
; .openStream
; java.io.InputStreamReader.
; java.io.BufferedReader.)]
; (->> (line-seq resp)
; (apply str)
; ;println
; ))
| true | (ns t.auth.headers
(:use midje.sweet)
(:require
[clojure.string :as s]
[clj-time.core :as t]
[clj-time.format :as f]
[org.httpkit.client :as http]))
(def example-key "PI:KEY:<KEY>END_PI")
(def headers
{"X-Amz-Algorithm" "AWS4-HMAC-SHA256"
"X-Amz-Credential" "PI:KEY:<KEY>END_PI"
"X-Amz-Date" "20150830T123600Z"
"X-Amz-SignedHeaders" "content-type;host;x-amz-date"})
(def params
{:headers headers
:query-params {"Action" "ListUsers"
"Version" "2010-05-08"}})
(def header-formatter (f/formatters :basic-date-time-no-ms))
(def component-formatter (f/formatters :basic-date))
(def suite-prefix (str (System/getenv "PWD") "/test/aws4_testsuite/"))
(defn decapitalize [string]
(apply str
(s/lower-case (first string))
(rest string)))
(defn req->creq [method url params date host signature]
(str method "\n"
url "\n"
params "\n"
(decapitalize date) "\n"
(decapitalize host) "\n\n"
signature))
(defn parse-req [req]
)
(fact "test 1"
(->> (slurp (str suite-prefix "get-vanilla-query-order-key-case.req"))
parse-req
(apply req->creq)) => (slurp (str suite-prefix "get-vanilla-query-order-key-case.creq")))
(-> (slurp (str suite-prefix "get-vanilla-query-order-key-case.req"))
s/split-lines
println)
(println (slurp (str suite-prefix "get-vanilla-query-order-key-case.creq")))
;(with-open [resp (-> (java.net.URL. "https://www.google.com")
; .openStream
; java.io.InputStreamReader.
; java.io.BufferedReader.)]
; (->> (line-seq resp)
; (apply str)
; ;println
; ))
|
[
{
"context": " )\n )\n\n\n(defn hello [nn]\n (println \"Hello Ray\")\n (println nn)\n (let [res (.resolveAttribute n",
"end": 539,
"score": 0.9885271787643433,
"start": 536,
"tag": "NAME",
"value": "Ray"
}
] | src/hyauth/javainterop.clj | rsclison/hyauth | 0 | (ns hyauth.javainterop
(:import
(org.cocktail Pip))
(:gen-class
:name hyauth.javainterop
:methods [#^{:static true} [hello [org.cocktail.Pip] String]
#^{:static true} [isAuthorized [String org.cocktail.Pip] String]
#^{:static true} [init [org.cocktail.Pip] void]
]
)
(:require [hyauth.prp :as prp]
[hyauth.pdp :as pdp]
[hyauth.journal :as jrnl]
[clojure.data.json :as json]
)
)
(defn hello [nn]
(println "Hello Ray")
(println nn)
(let [res (.resolveAttribute nn "My" "God")]
(println "IN CLOJ " res)
(str "RESULT from CLOJ " res)
))
(defn -hello [nn]
(println "hello-")
(hello nn))
(defn -isAuthorized [req pip]
(println "isAuthorized")
(if (:result(pdp/evalRequest (json/read-str req :key-fn keyword)))
"allow"
"deny")
)
(defn -init [pip]
(let [attributes (.getAttributes pip)]
(pdp/init)
(prp/init)
(prp/addOrReplaceJavaPip attributes pip)
(jrnl/logClient pip)
)) | 13687 | (ns hyauth.javainterop
(:import
(org.cocktail Pip))
(:gen-class
:name hyauth.javainterop
:methods [#^{:static true} [hello [org.cocktail.Pip] String]
#^{:static true} [isAuthorized [String org.cocktail.Pip] String]
#^{:static true} [init [org.cocktail.Pip] void]
]
)
(:require [hyauth.prp :as prp]
[hyauth.pdp :as pdp]
[hyauth.journal :as jrnl]
[clojure.data.json :as json]
)
)
(defn hello [nn]
(println "Hello <NAME>")
(println nn)
(let [res (.resolveAttribute nn "My" "God")]
(println "IN CLOJ " res)
(str "RESULT from CLOJ " res)
))
(defn -hello [nn]
(println "hello-")
(hello nn))
(defn -isAuthorized [req pip]
(println "isAuthorized")
(if (:result(pdp/evalRequest (json/read-str req :key-fn keyword)))
"allow"
"deny")
)
(defn -init [pip]
(let [attributes (.getAttributes pip)]
(pdp/init)
(prp/init)
(prp/addOrReplaceJavaPip attributes pip)
(jrnl/logClient pip)
)) | true | (ns hyauth.javainterop
(:import
(org.cocktail Pip))
(:gen-class
:name hyauth.javainterop
:methods [#^{:static true} [hello [org.cocktail.Pip] String]
#^{:static true} [isAuthorized [String org.cocktail.Pip] String]
#^{:static true} [init [org.cocktail.Pip] void]
]
)
(:require [hyauth.prp :as prp]
[hyauth.pdp :as pdp]
[hyauth.journal :as jrnl]
[clojure.data.json :as json]
)
)
(defn hello [nn]
(println "Hello PI:NAME:<NAME>END_PI")
(println nn)
(let [res (.resolveAttribute nn "My" "God")]
(println "IN CLOJ " res)
(str "RESULT from CLOJ " res)
))
(defn -hello [nn]
(println "hello-")
(hello nn))
(defn -isAuthorized [req pip]
(println "isAuthorized")
(if (:result(pdp/evalRequest (json/read-str req :key-fn keyword)))
"allow"
"deny")
)
(defn -init [pip]
(let [attributes (.getAttributes pip)]
(pdp/init)
(prp/init)
(prp/addOrReplaceJavaPip attributes pip)
(jrnl/logClient pip)
)) |
[
{
"context": " :description \"A Clojure wrapper around FastDTW by Stan Salvador and Philip Chan.\"\n :dependencies [[org.clojure/c",
"end": 105,
"score": 0.9998223781585693,
"start": 92,
"tag": "NAME",
"value": "Stan Salvador"
},
{
"context": "lojure wrapper around FastDTW by Stan Salvador and Philip Chan.\"\n :dependencies [[org.clojure/clojure \"1.2.1\"]\n",
"end": 121,
"score": 0.9998371005058289,
"start": 110,
"tag": "NAME",
"value": "Philip Chan"
}
] | project.clj | tel/cljfastdtw | 1 | (defproject cljfastdtw "1.0.2-SNAPSHOT"
:description "A Clojure wrapper around FastDTW by Stan Salvador and Philip Chan."
:dependencies [[org.clojure/clojure "1.2.1"]
[com.googlecode.efficient-java-matrix-library/ejml "0.17"]]
:java-source-path "jsrc") | 95830 | (defproject cljfastdtw "1.0.2-SNAPSHOT"
:description "A Clojure wrapper around FastDTW by <NAME> and <NAME>."
:dependencies [[org.clojure/clojure "1.2.1"]
[com.googlecode.efficient-java-matrix-library/ejml "0.17"]]
:java-source-path "jsrc") | true | (defproject cljfastdtw "1.0.2-SNAPSHOT"
:description "A Clojure wrapper around FastDTW by PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI."
:dependencies [[org.clojure/clojure "1.2.1"]
[com.googlecode.efficient-java-matrix-library/ejml "0.17"]]
:java-source-path "jsrc") |
[
{
"context": "l\n :password password})\n {:signup/result \"OK\"})\n\n(def resolvers [curre",
"end": 2159,
"score": 0.721322774887085,
"start": 2151,
"tag": "PASSWORD",
"value": "password"
}
] | src/main/app/model/session.clj | randallard/fulcro-template-01 | 98 | (ns app.model.session
(:require
[app.model.mock-database :as db]
[datascript.core :as d]
[com.fulcrologic.guardrails.core :refer [>defn => | ?]]
[com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[com.fulcrologic.fulcro.server.api-middleware :as fmw]))
(defonce account-database (atom {}))
(defresolver current-session-resolver [env input]
{::pc/output [{::current-session [:session/valid? :account/name]}]}
(let [{:keys [account/name session/valid?]} (get-in env [:ring/request :session])]
(if valid?
(do
(log/info name "already logged in!")
{::current-session {:session/valid? true :account/name name}})
{::current-session {:session/valid? false}})))
(defn response-updating-session
"Uses `mutation-response` as the actual return value for a mutation, but also stores the data into the (cookie-based) session."
[mutation-env mutation-response]
(let [existing-session (some-> mutation-env :ring/request :session)]
(fmw/augment-response
mutation-response
(fn [resp]
(let [new-session (merge existing-session mutation-response)]
(assoc resp :session new-session))))))
(defmutation login [env {:keys [username password]}]
{::pc/output [:session/valid? :account/name]}
(log/info "Authenticating" username)
(let [{expected-email :email
expected-password :password} (get @account-database username)]
(if (and (= username expected-email) (= password expected-password))
(response-updating-session env
{:session/valid? true
:account/name username})
(do
(log/error "Invalid credentials supplied for" username)
(throw (ex-info "Invalid credentials" {:username username}))))))
(defmutation logout [env params]
{::pc/output [:session/valid?]}
(response-updating-session env {:session/valid? false :account/name ""}))
(defmutation signup! [env {:keys [email password]}]
{::pc/output [:signup/result]}
(swap! account-database assoc email {:email email
:password password})
{:signup/result "OK"})
(def resolvers [current-session-resolver login logout signup!])
| 62947 | (ns app.model.session
(:require
[app.model.mock-database :as db]
[datascript.core :as d]
[com.fulcrologic.guardrails.core :refer [>defn => | ?]]
[com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[com.fulcrologic.fulcro.server.api-middleware :as fmw]))
(defonce account-database (atom {}))
(defresolver current-session-resolver [env input]
{::pc/output [{::current-session [:session/valid? :account/name]}]}
(let [{:keys [account/name session/valid?]} (get-in env [:ring/request :session])]
(if valid?
(do
(log/info name "already logged in!")
{::current-session {:session/valid? true :account/name name}})
{::current-session {:session/valid? false}})))
(defn response-updating-session
"Uses `mutation-response` as the actual return value for a mutation, but also stores the data into the (cookie-based) session."
[mutation-env mutation-response]
(let [existing-session (some-> mutation-env :ring/request :session)]
(fmw/augment-response
mutation-response
(fn [resp]
(let [new-session (merge existing-session mutation-response)]
(assoc resp :session new-session))))))
(defmutation login [env {:keys [username password]}]
{::pc/output [:session/valid? :account/name]}
(log/info "Authenticating" username)
(let [{expected-email :email
expected-password :password} (get @account-database username)]
(if (and (= username expected-email) (= password expected-password))
(response-updating-session env
{:session/valid? true
:account/name username})
(do
(log/error "Invalid credentials supplied for" username)
(throw (ex-info "Invalid credentials" {:username username}))))))
(defmutation logout [env params]
{::pc/output [:session/valid?]}
(response-updating-session env {:session/valid? false :account/name ""}))
(defmutation signup! [env {:keys [email password]}]
{::pc/output [:signup/result]}
(swap! account-database assoc email {:email email
:password <PASSWORD>})
{:signup/result "OK"})
(def resolvers [current-session-resolver login logout signup!])
| true | (ns app.model.session
(:require
[app.model.mock-database :as db]
[datascript.core :as d]
[com.fulcrologic.guardrails.core :refer [>defn => | ?]]
[com.wsscode.pathom.connect :as pc :refer [defresolver defmutation]]
[taoensso.timbre :as log]
[clojure.spec.alpha :as s]
[com.fulcrologic.fulcro.server.api-middleware :as fmw]))
(defonce account-database (atom {}))
(defresolver current-session-resolver [env input]
{::pc/output [{::current-session [:session/valid? :account/name]}]}
(let [{:keys [account/name session/valid?]} (get-in env [:ring/request :session])]
(if valid?
(do
(log/info name "already logged in!")
{::current-session {:session/valid? true :account/name name}})
{::current-session {:session/valid? false}})))
(defn response-updating-session
"Uses `mutation-response` as the actual return value for a mutation, but also stores the data into the (cookie-based) session."
[mutation-env mutation-response]
(let [existing-session (some-> mutation-env :ring/request :session)]
(fmw/augment-response
mutation-response
(fn [resp]
(let [new-session (merge existing-session mutation-response)]
(assoc resp :session new-session))))))
(defmutation login [env {:keys [username password]}]
{::pc/output [:session/valid? :account/name]}
(log/info "Authenticating" username)
(let [{expected-email :email
expected-password :password} (get @account-database username)]
(if (and (= username expected-email) (= password expected-password))
(response-updating-session env
{:session/valid? true
:account/name username})
(do
(log/error "Invalid credentials supplied for" username)
(throw (ex-info "Invalid credentials" {:username username}))))))
(defmutation logout [env params]
{::pc/output [:session/valid?]}
(response-updating-session env {:session/valid? false :account/name ""}))
(defmutation signup! [env {:keys [email password]}]
{::pc/output [:signup/result]}
(swap! account-database assoc email {:email email
:password PI:PASSWORD:<PASSWORD>END_PI})
{:signup/result "OK"})
(def resolvers [current-session-resolver login logout signup!])
|
[
{
"context": "; Author: Ambrose Bonnaire-Sergeant\n(ns e30-devtools-via-event-filters\n (:require [c",
"end": 35,
"score": 0.9998642802238464,
"start": 10,
"tag": "NAME",
"value": "Ambrose Bonnaire-Sergeant"
}
] | examples/e30_devtools_via_event_filters.clj | bsless/cljfx | 817 | ; Author: Ambrose Bonnaire-Sergeant
(ns e30-devtools-via-event-filters
(:require [cljfx.api :as fx]
[clojure.core.cache :as cache])
(:import [javafx.scene.input MouseEvent]
[javafx.scene Node]
[javafx.event Event]))
;; Setting an event filter on a node allows that node to
;; intercept events intended for its children.
;;
;; Add `:event-filter` to any Node
;; to register a catch-all event filter.
;;
;; This example highlights hovered nodes by
;; setting an event filter on the root node that intercepts
;; MouseEvent's sent to inner nodes.
(set! *warn-on-reflection* true)
(def *context
(atom (fx/create-context
{:current-node nil}
cache/lru-cache-factory)))
; [(U nil Node) Event CSSClass -> (U nil node)]
(defn devtools-highlight-filter
"Takes the previously highlighted node (or nil),
an Event (via event filter), and the CSS class
to apply to highlighted nodes.
Returns the current highlighted node (or nil)
after highlighting it (and removing highlighting
on the previous node)."
[^Node hovered-node ^Event event css-class]
{:pre [(string? css-class)]}
(when (instance? MouseEvent event)
(let [^Node target (.getTarget event)
event-type (.getEventType event)]
(when (instance? Node target)
(if (#{MouseEvent/MOUSE_EXITED
MouseEvent/MOUSE_EXITED_TARGET}
event-type)
(let [_ (-> target .getStyleClass (.remove css-class))]
(when (not= hovered-node target)
hovered-node))
(let [_ (when (and hovered-node (not= hovered-node target))
(-> hovered-node .getStyleClass (.remove css-class)))
_ (when (not= hovered-node target)
(when-not (-> target .getStyleClass (.contains css-class))
(-> target .getStyleClass (.add css-class))))]
target))))))
(def mouse-over-css-class "mouse-over-highlight")
(defmulti handle-event :event/type)
(defmethod handle-event ::on-event-filter [{:keys [fx/context fx/event]}]
{:context (fx/swap-context context update :current-node
devtools-highlight-filter
event
mouse-over-css-class)})
(defn root-view [{:keys [fx/context]}]
{:fx/type :stage
:showing true
:width 600
:height 500
:scene {:fx/type :scene
:stylesheets #{"devtools.css"}
:root
{:fx/type :v-box
;; add an event filter to the root node
:event-filter {:event/type ::on-event-filter
; because we are changing observable lists in
; the event handler
:fx/sync true}
;; the UI
:children
[{:fx/type :label
:text (str "Current node: " (some-> (fx/sub-val context :current-node)
class
.getSimpleName))}
{:fx/type :label
:text (str "Has CSS classes: " (some-> ^Node (fx/sub-val context :current-node)
.getStyleClass
vec))}
; mouse over these nodes to highlight them
{:fx/type :split-pane
:divider-positions [0.5]
:items [{:fx/type :v-box
:padding 50
:children [{:fx/type :split-pane
:divider-positions [0.5]
:items [{:fx/type :v-box
:padding 50
:children [{:fx/type :h-box
:children [{:fx/type :label
:text "left 1"}]}
{:fx/type :label
:text "left 2"}]}
{:fx/type :h-box
:padding 50
:children [{:fx/type :label
:text "right"}]}]}
{:fx/type :label
:text "left 2"}]}
{:fx/type :h-box
:padding 50
:children [{:fx/type :label
:text "right"}]}]}]}}})
(def app
(fx/create-app *context
:event-handler handle-event
:desc-fn (fn [_]
{:fx/type root-view})))
| 45230 | ; Author: <NAME>
(ns e30-devtools-via-event-filters
(:require [cljfx.api :as fx]
[clojure.core.cache :as cache])
(:import [javafx.scene.input MouseEvent]
[javafx.scene Node]
[javafx.event Event]))
;; Setting an event filter on a node allows that node to
;; intercept events intended for its children.
;;
;; Add `:event-filter` to any Node
;; to register a catch-all event filter.
;;
;; This example highlights hovered nodes by
;; setting an event filter on the root node that intercepts
;; MouseEvent's sent to inner nodes.
(set! *warn-on-reflection* true)
(def *context
(atom (fx/create-context
{:current-node nil}
cache/lru-cache-factory)))
; [(U nil Node) Event CSSClass -> (U nil node)]
(defn devtools-highlight-filter
"Takes the previously highlighted node (or nil),
an Event (via event filter), and the CSS class
to apply to highlighted nodes.
Returns the current highlighted node (or nil)
after highlighting it (and removing highlighting
on the previous node)."
[^Node hovered-node ^Event event css-class]
{:pre [(string? css-class)]}
(when (instance? MouseEvent event)
(let [^Node target (.getTarget event)
event-type (.getEventType event)]
(when (instance? Node target)
(if (#{MouseEvent/MOUSE_EXITED
MouseEvent/MOUSE_EXITED_TARGET}
event-type)
(let [_ (-> target .getStyleClass (.remove css-class))]
(when (not= hovered-node target)
hovered-node))
(let [_ (when (and hovered-node (not= hovered-node target))
(-> hovered-node .getStyleClass (.remove css-class)))
_ (when (not= hovered-node target)
(when-not (-> target .getStyleClass (.contains css-class))
(-> target .getStyleClass (.add css-class))))]
target))))))
(def mouse-over-css-class "mouse-over-highlight")
(defmulti handle-event :event/type)
(defmethod handle-event ::on-event-filter [{:keys [fx/context fx/event]}]
{:context (fx/swap-context context update :current-node
devtools-highlight-filter
event
mouse-over-css-class)})
(defn root-view [{:keys [fx/context]}]
{:fx/type :stage
:showing true
:width 600
:height 500
:scene {:fx/type :scene
:stylesheets #{"devtools.css"}
:root
{:fx/type :v-box
;; add an event filter to the root node
:event-filter {:event/type ::on-event-filter
; because we are changing observable lists in
; the event handler
:fx/sync true}
;; the UI
:children
[{:fx/type :label
:text (str "Current node: " (some-> (fx/sub-val context :current-node)
class
.getSimpleName))}
{:fx/type :label
:text (str "Has CSS classes: " (some-> ^Node (fx/sub-val context :current-node)
.getStyleClass
vec))}
; mouse over these nodes to highlight them
{:fx/type :split-pane
:divider-positions [0.5]
:items [{:fx/type :v-box
:padding 50
:children [{:fx/type :split-pane
:divider-positions [0.5]
:items [{:fx/type :v-box
:padding 50
:children [{:fx/type :h-box
:children [{:fx/type :label
:text "left 1"}]}
{:fx/type :label
:text "left 2"}]}
{:fx/type :h-box
:padding 50
:children [{:fx/type :label
:text "right"}]}]}
{:fx/type :label
:text "left 2"}]}
{:fx/type :h-box
:padding 50
:children [{:fx/type :label
:text "right"}]}]}]}}})
(def app
(fx/create-app *context
:event-handler handle-event
:desc-fn (fn [_]
{:fx/type root-view})))
| true | ; Author: PI:NAME:<NAME>END_PI
(ns e30-devtools-via-event-filters
(:require [cljfx.api :as fx]
[clojure.core.cache :as cache])
(:import [javafx.scene.input MouseEvent]
[javafx.scene Node]
[javafx.event Event]))
;; Setting an event filter on a node allows that node to
;; intercept events intended for its children.
;;
;; Add `:event-filter` to any Node
;; to register a catch-all event filter.
;;
;; This example highlights hovered nodes by
;; setting an event filter on the root node that intercepts
;; MouseEvent's sent to inner nodes.
(set! *warn-on-reflection* true)
(def *context
(atom (fx/create-context
{:current-node nil}
cache/lru-cache-factory)))
; [(U nil Node) Event CSSClass -> (U nil node)]
(defn devtools-highlight-filter
"Takes the previously highlighted node (or nil),
an Event (via event filter), and the CSS class
to apply to highlighted nodes.
Returns the current highlighted node (or nil)
after highlighting it (and removing highlighting
on the previous node)."
[^Node hovered-node ^Event event css-class]
{:pre [(string? css-class)]}
(when (instance? MouseEvent event)
(let [^Node target (.getTarget event)
event-type (.getEventType event)]
(when (instance? Node target)
(if (#{MouseEvent/MOUSE_EXITED
MouseEvent/MOUSE_EXITED_TARGET}
event-type)
(let [_ (-> target .getStyleClass (.remove css-class))]
(when (not= hovered-node target)
hovered-node))
(let [_ (when (and hovered-node (not= hovered-node target))
(-> hovered-node .getStyleClass (.remove css-class)))
_ (when (not= hovered-node target)
(when-not (-> target .getStyleClass (.contains css-class))
(-> target .getStyleClass (.add css-class))))]
target))))))
(def mouse-over-css-class "mouse-over-highlight")
(defmulti handle-event :event/type)
(defmethod handle-event ::on-event-filter [{:keys [fx/context fx/event]}]
{:context (fx/swap-context context update :current-node
devtools-highlight-filter
event
mouse-over-css-class)})
(defn root-view [{:keys [fx/context]}]
{:fx/type :stage
:showing true
:width 600
:height 500
:scene {:fx/type :scene
:stylesheets #{"devtools.css"}
:root
{:fx/type :v-box
;; add an event filter to the root node
:event-filter {:event/type ::on-event-filter
; because we are changing observable lists in
; the event handler
:fx/sync true}
;; the UI
:children
[{:fx/type :label
:text (str "Current node: " (some-> (fx/sub-val context :current-node)
class
.getSimpleName))}
{:fx/type :label
:text (str "Has CSS classes: " (some-> ^Node (fx/sub-val context :current-node)
.getStyleClass
vec))}
; mouse over these nodes to highlight them
{:fx/type :split-pane
:divider-positions [0.5]
:items [{:fx/type :v-box
:padding 50
:children [{:fx/type :split-pane
:divider-positions [0.5]
:items [{:fx/type :v-box
:padding 50
:children [{:fx/type :h-box
:children [{:fx/type :label
:text "left 1"}]}
{:fx/type :label
:text "left 2"}]}
{:fx/type :h-box
:padding 50
:children [{:fx/type :label
:text "right"}]}]}
{:fx/type :label
:text "left 2"}]}
{:fx/type :h-box
:padding 50
:children [{:fx/type :label
:text "right"}]}]}]}}})
(def app
(fx/create-app *context
:event-handler handle-event
:desc-fn (fn [_]
{:fx/type root-view})))
|
[
{
"context": " joy-of-clojure)\n\n\n(in-ns 'joy.ns)\n(def authors [\"Chouser\"])\n\n\n(clojure.core/refer 'joy.ns)\njoy.ns/authors",
"end": 60,
"score": 0.7376710176467896,
"start": 53,
"tag": "NAME",
"value": "Chouser"
}
] | sand-box/src/sand_box/joy-of-clojure.clj | jaeyeon-jo-kr/clojure_practice | 0 | (ns joy-of-clojure)
(in-ns 'joy.ns)
(def authors ["Chouser"])
(clojure.core/refer 'joy.ns)
joy.ns/authors | 61253 | (ns joy-of-clojure)
(in-ns 'joy.ns)
(def authors ["<NAME>"])
(clojure.core/refer 'joy.ns)
joy.ns/authors | true | (ns joy-of-clojure)
(in-ns 'joy.ns)
(def authors ["PI:NAME:<NAME>END_PI"])
(clojure.core/refer 'joy.ns)
joy.ns/authors |
[
{
"context": "s that can be done on two expressions.\", :author \"Sean Dawson\"}\n nanoweave.parsers.binary-arithmetic\n (:requir",
"end": 100,
"score": 0.9998270273208618,
"start": 89,
"tag": "NAME",
"value": "Sean Dawson"
}
] | src/nanoweave/parsers/binary_arithmetic.clj | NoxHarmonium/nanoweave | 0 | (ns ^{:doc "Parses arithmetic operations that can be done on two expressions.", :author "Sean Dawson"}
nanoweave.parsers.binary-arithmetic
(:require [blancas.kern.core :refer [bind <?> return]]
[blancas.kern.lexer.java-style :refer [one-of]]
[nanoweave.ast.binary-arithmetic :refer
[->MultOp ->DivOp ->ModOp ->AddOp ->SubOp]]))
; Arithmetic Binary Operators
(def wrapped-mul-op
"Multiplicative operator: multiplication, division, or modulo."
(<?> (bind [op (one-of "*/%")]
(return ({\* ->MultOp \/ ->DivOp \% ->ModOp} op)))
"multiplication operator (*,/,%)"))
(def wrapped-add-op
"Additive operator: addition or subtraction."
(<?> (bind [op (one-of "+-")]
(return ({\+ ->AddOp \- ->SubOp} op)))
"addition operator (+,-)"))
| 65312 | (ns ^{:doc "Parses arithmetic operations that can be done on two expressions.", :author "<NAME>"}
nanoweave.parsers.binary-arithmetic
(:require [blancas.kern.core :refer [bind <?> return]]
[blancas.kern.lexer.java-style :refer [one-of]]
[nanoweave.ast.binary-arithmetic :refer
[->MultOp ->DivOp ->ModOp ->AddOp ->SubOp]]))
; Arithmetic Binary Operators
(def wrapped-mul-op
"Multiplicative operator: multiplication, division, or modulo."
(<?> (bind [op (one-of "*/%")]
(return ({\* ->MultOp \/ ->DivOp \% ->ModOp} op)))
"multiplication operator (*,/,%)"))
(def wrapped-add-op
"Additive operator: addition or subtraction."
(<?> (bind [op (one-of "+-")]
(return ({\+ ->AddOp \- ->SubOp} op)))
"addition operator (+,-)"))
| true | (ns ^{:doc "Parses arithmetic operations that can be done on two expressions.", :author "PI:NAME:<NAME>END_PI"}
nanoweave.parsers.binary-arithmetic
(:require [blancas.kern.core :refer [bind <?> return]]
[blancas.kern.lexer.java-style :refer [one-of]]
[nanoweave.ast.binary-arithmetic :refer
[->MultOp ->DivOp ->ModOp ->AddOp ->SubOp]]))
; Arithmetic Binary Operators
(def wrapped-mul-op
"Multiplicative operator: multiplication, division, or modulo."
(<?> (bind [op (one-of "*/%")]
(return ({\* ->MultOp \/ ->DivOp \% ->ModOp} op)))
"multiplication operator (*,/,%)"))
(def wrapped-add-op
"Additive operator: addition or subtraction."
(<?> (bind [op (one-of "+-")]
(return ({\+ ->AddOp \- ->SubOp} op)))
"addition operator (+,-)"))
|
[
{
"context": "SERIAL]\n [:user \"VARCHAR(20)\"]\n [:password \"CHAR(64)\"]]))\n (j/execute! @database [\"CREATE UNIQUE ",
"end": 292,
"score": 0.8919944763183594,
"start": 288,
"tag": "PASSWORD",
"value": "CHAR"
},
{
"context": "L]\n [:user \"VARCHAR(20)\"]\n [:password \"CHAR(64)\"]]))\n (j/execute! @database [\"CREATE UNIQUE INDE",
"end": 295,
"score": 0.915476381778717,
"start": 293,
"tag": "PASSWORD",
"value": "64"
}
] | auth/test/auth/test_db.clj | raymondpoling/rerun-tv | 0 | (ns auth.test-db
(:require [clojure.java.jdbc :as j]
[db.db :refer [database]]))
(defn create-h2-mem-tables []
(j/execute! @database ["CREATE SCHEMA AUTH"])
(j/execute! @database (j/create-table-ddl "auth.authorize"
[[:id :SERIAL]
[:user "VARCHAR(20)"]
[:password "CHAR(64)"]]))
(j/execute! @database ["CREATE UNIQUE INDEX by_user ON auth.authorize(user)"]))
| 78814 | (ns auth.test-db
(:require [clojure.java.jdbc :as j]
[db.db :refer [database]]))
(defn create-h2-mem-tables []
(j/execute! @database ["CREATE SCHEMA AUTH"])
(j/execute! @database (j/create-table-ddl "auth.authorize"
[[:id :SERIAL]
[:user "VARCHAR(20)"]
[:password "<PASSWORD>(<PASSWORD>)"]]))
(j/execute! @database ["CREATE UNIQUE INDEX by_user ON auth.authorize(user)"]))
| true | (ns auth.test-db
(:require [clojure.java.jdbc :as j]
[db.db :refer [database]]))
(defn create-h2-mem-tables []
(j/execute! @database ["CREATE SCHEMA AUTH"])
(j/execute! @database (j/create-table-ddl "auth.authorize"
[[:id :SERIAL]
[:user "VARCHAR(20)"]
[:password "PI:PASSWORD:<PASSWORD>END_PI(PI:PASSWORD:<PASSWORD>END_PI)"]]))
(j/execute! @database ["CREATE UNIQUE INDEX by_user ON auth.authorize(user)"]))
|
[
{
"context": "cs.io/xapi/statements\")\n (def kokea-api-key \"26589566c610a046c322f87cfcc1383032d09d0774d20b68\")\n (def kokea-api-key-secret \"d50f0b8711acc8",
"end": 291,
"score": 0.9997764229774475,
"start": 243,
"tag": "KEY",
"value": "26589566c610a046c322f87cfcc1383032d09d0774d20b68"
},
{
"context": "d09d0774d20b68\")\n (def kokea-api-key-secret \"d50f0b8711acc82793ed040d005f41ed571e2a1e69cf975339aa784d50ea8d1c\")\n (def viewed-verb-id \"https://xapinet.org/",
"end": 391,
"score": 0.9997064471244812,
"start": 327,
"tag": "KEY",
"value": "d50f0b8711acc82793ed040d005f41ed571e2a1e69cf975339aa784d50ea8d1c"
}
] | dev/user.clj | blakeplock/dave-1 | 25 | (ns user)
(comment
(require '[clj-http.client :as client]
'[cheshire.core :as json]
'[clojure.java.io :as io])
(do (def kokea-endpoint "https://demo-lrs.yetanalytics.io/xapi/statements")
(def kokea-api-key "26589566c610a046c322f87cfcc1383032d09d0774d20b68")
(def kokea-api-key-secret "d50f0b8711acc82793ed040d005f41ed571e2a1e69cf975339aa784d50ea8d1c")
(def viewed-verb-id "https://xapinet.org/kokea-concepts/verbs/viewed")
(def page-obj-id "https://xapinet.org/kokea-concepts/activities/Page-1-Listening-to-the-Customer")
(def query-params {:verb viewed-verb-id
:activity page-obj-id})
(defn query-lrs
[{:keys [endpoint api-key api-key-secret query-params]}]
(clj-http.client/get
endpoint
{:basic-auth [api-key api-key-secret]
:headers {"X-Experience-API-Version" "1.0.3"
"Content-Type" "application/json;"}
:query-params query-params})))
(def rate-of-completions-statements
(-> {:endpoint kokea-endpoint
:api-key kokea-api-key
:api-key-secret kokea-api-key-secret
:query-params {:verb "https://xapinet.org/kokea-concepts/verbs/completed"}}
query-lrs
:body
(cheshire.core/parse-string true)
:statements))
(with-open [w (io/writer (io/file "resources/public/data/kokea/rate_of_completions_16.json"))]
(json/generate-stream rate-of-completions-statements w))
(clojure.pprint/pprint rate-of-completions-statements)
(defn rate-of-completions
[stmts]
(let [c-per-obj (loop [accum {}
src stmts]
(if (empty? src)
accum
(let [cur-stmt (first src)
{{{{obj-name :en-US} :name} :definition
obj-id :id} :object} cur-stmt]
(recur
(update-in accum [obj-id]
(fn [old]
(if (nil? old)
{:name obj-name
:count 1}
(let [{c :count} old
updated-c (inc c)]
{:name obj-name
:count updated-c}))))
(rest src)))))]
(loop [accum []
src c-per-obj]
(if (empty? src)
accum
(let [[obj-id obj-info] (first src)
{obj-n :name
obj-c :count} obj-info]
(recur (conj accum [obj-id obj-n obj-c]) (rest src)))))))
(count (rate-of-completions rate-of-completions-statements)))
| 5911 | (ns user)
(comment
(require '[clj-http.client :as client]
'[cheshire.core :as json]
'[clojure.java.io :as io])
(do (def kokea-endpoint "https://demo-lrs.yetanalytics.io/xapi/statements")
(def kokea-api-key "<KEY>")
(def kokea-api-key-secret "<KEY>")
(def viewed-verb-id "https://xapinet.org/kokea-concepts/verbs/viewed")
(def page-obj-id "https://xapinet.org/kokea-concepts/activities/Page-1-Listening-to-the-Customer")
(def query-params {:verb viewed-verb-id
:activity page-obj-id})
(defn query-lrs
[{:keys [endpoint api-key api-key-secret query-params]}]
(clj-http.client/get
endpoint
{:basic-auth [api-key api-key-secret]
:headers {"X-Experience-API-Version" "1.0.3"
"Content-Type" "application/json;"}
:query-params query-params})))
(def rate-of-completions-statements
(-> {:endpoint kokea-endpoint
:api-key kokea-api-key
:api-key-secret kokea-api-key-secret
:query-params {:verb "https://xapinet.org/kokea-concepts/verbs/completed"}}
query-lrs
:body
(cheshire.core/parse-string true)
:statements))
(with-open [w (io/writer (io/file "resources/public/data/kokea/rate_of_completions_16.json"))]
(json/generate-stream rate-of-completions-statements w))
(clojure.pprint/pprint rate-of-completions-statements)
(defn rate-of-completions
[stmts]
(let [c-per-obj (loop [accum {}
src stmts]
(if (empty? src)
accum
(let [cur-stmt (first src)
{{{{obj-name :en-US} :name} :definition
obj-id :id} :object} cur-stmt]
(recur
(update-in accum [obj-id]
(fn [old]
(if (nil? old)
{:name obj-name
:count 1}
(let [{c :count} old
updated-c (inc c)]
{:name obj-name
:count updated-c}))))
(rest src)))))]
(loop [accum []
src c-per-obj]
(if (empty? src)
accum
(let [[obj-id obj-info] (first src)
{obj-n :name
obj-c :count} obj-info]
(recur (conj accum [obj-id obj-n obj-c]) (rest src)))))))
(count (rate-of-completions rate-of-completions-statements)))
| true | (ns user)
(comment
(require '[clj-http.client :as client]
'[cheshire.core :as json]
'[clojure.java.io :as io])
(do (def kokea-endpoint "https://demo-lrs.yetanalytics.io/xapi/statements")
(def kokea-api-key "PI:KEY:<KEY>END_PI")
(def kokea-api-key-secret "PI:KEY:<KEY>END_PI")
(def viewed-verb-id "https://xapinet.org/kokea-concepts/verbs/viewed")
(def page-obj-id "https://xapinet.org/kokea-concepts/activities/Page-1-Listening-to-the-Customer")
(def query-params {:verb viewed-verb-id
:activity page-obj-id})
(defn query-lrs
[{:keys [endpoint api-key api-key-secret query-params]}]
(clj-http.client/get
endpoint
{:basic-auth [api-key api-key-secret]
:headers {"X-Experience-API-Version" "1.0.3"
"Content-Type" "application/json;"}
:query-params query-params})))
(def rate-of-completions-statements
(-> {:endpoint kokea-endpoint
:api-key kokea-api-key
:api-key-secret kokea-api-key-secret
:query-params {:verb "https://xapinet.org/kokea-concepts/verbs/completed"}}
query-lrs
:body
(cheshire.core/parse-string true)
:statements))
(with-open [w (io/writer (io/file "resources/public/data/kokea/rate_of_completions_16.json"))]
(json/generate-stream rate-of-completions-statements w))
(clojure.pprint/pprint rate-of-completions-statements)
(defn rate-of-completions
[stmts]
(let [c-per-obj (loop [accum {}
src stmts]
(if (empty? src)
accum
(let [cur-stmt (first src)
{{{{obj-name :en-US} :name} :definition
obj-id :id} :object} cur-stmt]
(recur
(update-in accum [obj-id]
(fn [old]
(if (nil? old)
{:name obj-name
:count 1}
(let [{c :count} old
updated-c (inc c)]
{:name obj-name
:count updated-c}))))
(rest src)))))]
(loop [accum []
src c-per-obj]
(if (empty? src)
accum
(let [[obj-id obj-info] (first src)
{obj-n :name
obj-c :count} obj-info]
(recur (conj accum [obj-id obj-n obj-c]) (rest src)))))))
(count (rate-of-completions rate-of-completions-statements)))
|
[
{
"context": "; MIT License\n;\n; Copyright (c) 2017 Frederic Merizen & Kenny Williams\n;\n; Permission is hereby granted",
"end": 53,
"score": 0.9998453259468079,
"start": 37,
"tag": "NAME",
"value": "Frederic Merizen"
},
{
"context": " License\n;\n; Copyright (c) 2017 Frederic Merizen & Kenny Williams\n;\n; Permission is hereby granted, free of charge,",
"end": 70,
"score": 0.9997668266296387,
"start": 56,
"tag": "NAME",
"value": "Kenny Williams"
}
] | src/plumula/mimolette/alpha.cljc | plumula/mimolette | 3 | ; MIT License
;
; Copyright (c) 2017 Frederic Merizen & Kenny Williams
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
(ns plumula.mimolette.alpha
(:require [plumula.mimolette.impl :as impl]
[#?(:clj clojure.spec.test.alpha :cljs cljs.spec.test.alpha) :as stest]
[#?(:clj clojure.spec.alpha :cljs cljs.spec.alpha) :as spec])
#?(:cljs (:require-macros plumula.mimolette.alpha)))
(def spec-shim
"Wrap `clojure.spec.alpha` functions in a namespace-independent shim."
(reify impl/SpecShim
(abbrev-result [this x] (stest/abbrev-result x))
(explain-out [this ed] (spec/explain-out ed))
(failure-val [this failure] (::stest/val failure))))
(defmacro check
"Check functions against their specs, whether we’re running on Clojure or
ClojureScript.
"
[& args]
`(impl/if-cljs
(cljs.spec.test.alpha/check ~@args)
(clojure.spec.test.alpha/check ~@args)))
(defmacro defspec-test
"Create a test named `name`, that checks the function(s) named `sym-or-syms`
against their specs.
Arguments:
- `name` a symbol.
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test.alpha/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
([name sym-or-syms]
`(defspec-test ~name ~sym-or-syms nil))
([name sym-or-syms opts]
`(impl/defspec-test check spec-shim ~name ~sym-or-syms ~opts)))
| 28448 | ; MIT License
;
; Copyright (c) 2017 <NAME> & <NAME>
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
(ns plumula.mimolette.alpha
(:require [plumula.mimolette.impl :as impl]
[#?(:clj clojure.spec.test.alpha :cljs cljs.spec.test.alpha) :as stest]
[#?(:clj clojure.spec.alpha :cljs cljs.spec.alpha) :as spec])
#?(:cljs (:require-macros plumula.mimolette.alpha)))
(def spec-shim
"Wrap `clojure.spec.alpha` functions in a namespace-independent shim."
(reify impl/SpecShim
(abbrev-result [this x] (stest/abbrev-result x))
(explain-out [this ed] (spec/explain-out ed))
(failure-val [this failure] (::stest/val failure))))
(defmacro check
"Check functions against their specs, whether we’re running on Clojure or
ClojureScript.
"
[& args]
`(impl/if-cljs
(cljs.spec.test.alpha/check ~@args)
(clojure.spec.test.alpha/check ~@args)))
(defmacro defspec-test
"Create a test named `name`, that checks the function(s) named `sym-or-syms`
against their specs.
Arguments:
- `name` a symbol.
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test.alpha/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
([name sym-or-syms]
`(defspec-test ~name ~sym-or-syms nil))
([name sym-or-syms opts]
`(impl/defspec-test check spec-shim ~name ~sym-or-syms ~opts)))
| true | ; MIT License
;
; Copyright (c) 2017 PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
(ns plumula.mimolette.alpha
(:require [plumula.mimolette.impl :as impl]
[#?(:clj clojure.spec.test.alpha :cljs cljs.spec.test.alpha) :as stest]
[#?(:clj clojure.spec.alpha :cljs cljs.spec.alpha) :as spec])
#?(:cljs (:require-macros plumula.mimolette.alpha)))
(def spec-shim
"Wrap `clojure.spec.alpha` functions in a namespace-independent shim."
(reify impl/SpecShim
(abbrev-result [this x] (stest/abbrev-result x))
(explain-out [this ed] (spec/explain-out ed))
(failure-val [this failure] (::stest/val failure))))
(defmacro check
"Check functions against their specs, whether we’re running on Clojure or
ClojureScript.
"
[& args]
`(impl/if-cljs
(cljs.spec.test.alpha/check ~@args)
(clojure.spec.test.alpha/check ~@args)))
(defmacro defspec-test
"Create a test named `name`, that checks the function(s) named `sym-or-syms`
against their specs.
Arguments:
- `name` a symbol.
- `sym-or-syms` a fully qualified symbol, or a list of fully qualified symbols.
The name(s) of the functions to check.
- `opts` a map of options for `clojure.spec.test.alpha/check`.
- The `:gen` key is handled by `cljs.spec.test/check` (see its documentation).
- The contents of the `:opts` key is passed on to
`clojure.test.check/quick-check` (see its documentation).
- Special case: inside the `:opts` key, the `:num-tests` key, which is not
handled by `quick-check`, is the number of checks that will be run for
each function (defaults to 1000).
"
([name sym-or-syms]
`(defspec-test ~name ~sym-or-syms nil))
([name sym-or-syms opts]
`(impl/defspec-test check spec-shim ~name ~sym-or-syms ~opts)))
|
[
{
"context": "ME: write description\"\n :url \"https://github.com/chicoalmeida/mysqlx-clj\"\n :signing {:gpg-key \"francisco.rl.al",
"end": 131,
"score": 0.9987981915473938,
"start": 119,
"tag": "USERNAME",
"value": "chicoalmeida"
},
{
"context": "om/chicoalmeida/mysqlx-clj\"\n :signing {:gpg-key \"francisco.rl.almeida@gmail.com\"}\n :license {:name \"MIT\"\n :url \"http",
"end": 196,
"score": 0.9998944401741028,
"start": 166,
"tag": "EMAIL",
"value": "francisco.rl.almeida@gmail.com"
},
{
"context": "ources\"]\n :plugins [[com.jakemccrary/lein-test-refresh \"0.24.1\"]\n ",
"end": 623,
"score": 0.8510869145393372,
"start": 612,
"tag": "USERNAME",
"value": "jakemccrary"
},
{
"context": " \"1.2.7\"]\n [jonase/eastwood \"0.3.5\"]\n ",
"end": 871,
"score": 0.6982283592224121,
"start": 868,
"tag": "USERNAME",
"value": "ase"
},
{
"context": "\"s/\\\\\\\\[chicoalmeida/mysqlx-clj \\\"[0-9.]*\\\"\\\\\\\\]/[chicoalmeida/mysqlx-clj \\\"${:version}\\\"]/\" \"README.md\"]}\n :re",
"end": 1697,
"score": 0.9962903261184692,
"start": 1685,
"tag": "USERNAME",
"value": "chicoalmeida"
}
] | project.clj | chicoalmeida/mysqlx-clj | 4 | (defproject chicoalmeida/mysqlx-clj "0.0.1-beta3"
:description "FIXME: write description"
:url "https://github.com/chicoalmeida/mysqlx-clj"
:signing {:gpg-key "francisco.rl.almeida@gmail.com"}
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:dependencies [[cheshire "5.9.0"]
[mysql/mysql-connector-java "8.0.18"]]
:plugins [[lein-cloverage "1.0.13"]
[lein-shell "0.5.0"]
[lein-ancient "0.6.15"]
[lein-changelog "0.3.2"]]
:profiles {:dev {:resource-paths ["test/resources"]
:plugins [[com.jakemccrary/lein-test-refresh "0.24.1"]
[lein-cljfmt "0.6.4"]
[lein-cloverage "1.1.1"]
[test2junit "1.2.7"]
[jonase/eastwood "0.3.5"]
[lein-kibit "0.1.7"]]
:dependencies [[org.clojure/clojure "1.10.1"]
[circleci/bond "0.4.0"]
; logging
[ch.qos.logback/logback-classic "1.2.3" :exclusions [org.slf4j/slf4j-api]]
[org.slf4j/jul-to-slf4j "1.7.28"]
[org.slf4j/jcl-over-slf4j "1.7.28"]
[org.slf4j/log4j-over-slf4j "1.7.28"]
[org.testcontainers/testcontainers "1.12.2"]]}}
:deploy-repositories [["releases" :clojars]]
:aliases {"update-readme-version" ["shell" "sed" "-i" "s/\\\\[chicoalmeida/mysqlx-clj \"[0-9.]*\"\\\\]/[chicoalmeida/mysqlx-clj \"${:version}\"]/" "README.md"]}
:release-tasks [["shell" "git" "diff" "--exit-code"]
["change" "version" "leiningen.release/bump-version"]
["change" "version" "leiningen.release/bump-version" "release"]
["changelog" "release"]
["update-readme-version"]
["vcs" "commit"]
["vcs" "tag"]
["deploy"]
["vcs" "push"]])
| 28019 | (defproject chicoalmeida/mysqlx-clj "0.0.1-beta3"
:description "FIXME: write description"
:url "https://github.com/chicoalmeida/mysqlx-clj"
:signing {:gpg-key "<EMAIL>"}
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:dependencies [[cheshire "5.9.0"]
[mysql/mysql-connector-java "8.0.18"]]
:plugins [[lein-cloverage "1.0.13"]
[lein-shell "0.5.0"]
[lein-ancient "0.6.15"]
[lein-changelog "0.3.2"]]
:profiles {:dev {:resource-paths ["test/resources"]
:plugins [[com.jakemccrary/lein-test-refresh "0.24.1"]
[lein-cljfmt "0.6.4"]
[lein-cloverage "1.1.1"]
[test2junit "1.2.7"]
[jonase/eastwood "0.3.5"]
[lein-kibit "0.1.7"]]
:dependencies [[org.clojure/clojure "1.10.1"]
[circleci/bond "0.4.0"]
; logging
[ch.qos.logback/logback-classic "1.2.3" :exclusions [org.slf4j/slf4j-api]]
[org.slf4j/jul-to-slf4j "1.7.28"]
[org.slf4j/jcl-over-slf4j "1.7.28"]
[org.slf4j/log4j-over-slf4j "1.7.28"]
[org.testcontainers/testcontainers "1.12.2"]]}}
:deploy-repositories [["releases" :clojars]]
:aliases {"update-readme-version" ["shell" "sed" "-i" "s/\\\\[chicoalmeida/mysqlx-clj \"[0-9.]*\"\\\\]/[chicoalmeida/mysqlx-clj \"${:version}\"]/" "README.md"]}
:release-tasks [["shell" "git" "diff" "--exit-code"]
["change" "version" "leiningen.release/bump-version"]
["change" "version" "leiningen.release/bump-version" "release"]
["changelog" "release"]
["update-readme-version"]
["vcs" "commit"]
["vcs" "tag"]
["deploy"]
["vcs" "push"]])
| true | (defproject chicoalmeida/mysqlx-clj "0.0.1-beta3"
:description "FIXME: write description"
:url "https://github.com/chicoalmeida/mysqlx-clj"
:signing {:gpg-key "PI:EMAIL:<EMAIL>END_PI"}
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:dependencies [[cheshire "5.9.0"]
[mysql/mysql-connector-java "8.0.18"]]
:plugins [[lein-cloverage "1.0.13"]
[lein-shell "0.5.0"]
[lein-ancient "0.6.15"]
[lein-changelog "0.3.2"]]
:profiles {:dev {:resource-paths ["test/resources"]
:plugins [[com.jakemccrary/lein-test-refresh "0.24.1"]
[lein-cljfmt "0.6.4"]
[lein-cloverage "1.1.1"]
[test2junit "1.2.7"]
[jonase/eastwood "0.3.5"]
[lein-kibit "0.1.7"]]
:dependencies [[org.clojure/clojure "1.10.1"]
[circleci/bond "0.4.0"]
; logging
[ch.qos.logback/logback-classic "1.2.3" :exclusions [org.slf4j/slf4j-api]]
[org.slf4j/jul-to-slf4j "1.7.28"]
[org.slf4j/jcl-over-slf4j "1.7.28"]
[org.slf4j/log4j-over-slf4j "1.7.28"]
[org.testcontainers/testcontainers "1.12.2"]]}}
:deploy-repositories [["releases" :clojars]]
:aliases {"update-readme-version" ["shell" "sed" "-i" "s/\\\\[chicoalmeida/mysqlx-clj \"[0-9.]*\"\\\\]/[chicoalmeida/mysqlx-clj \"${:version}\"]/" "README.md"]}
:release-tasks [["shell" "git" "diff" "--exit-code"]
["change" "version" "leiningen.release/bump-version"]
["change" "version" "leiningen.release/bump-version" "release"]
["changelog" "release"]
["update-readme-version"]
["vcs" "commit"]
["vcs" "tag"]
["deploy"]
["vcs" "push"]])
|
[
{
"context": "\n println (str \"Hello, \" name \"!\"))\n\n(say-hello \"Luke\")\n; To read documentation (doc say-hello) \n\n; Get",
"end": 203,
"score": 0.9351575970649719,
"start": 199,
"tag": "NAME",
"value": "Luke"
}
] | src/app/functions/defn.clj | lucaslago/clojure-examples | 0 | (ns app.functions.defn)
; defn is used to bind a value to a symbol
(defn say-hello
"Takes a name as argument and says hello to that name"
[name]
println (str "Hello, " name "!"))
(say-hello "Luke")
; To read documentation (doc say-hello)
; Getting a function's meta data
(meta (var say-hello))
| 111970 | (ns app.functions.defn)
; defn is used to bind a value to a symbol
(defn say-hello
"Takes a name as argument and says hello to that name"
[name]
println (str "Hello, " name "!"))
(say-hello "<NAME>")
; To read documentation (doc say-hello)
; Getting a function's meta data
(meta (var say-hello))
| true | (ns app.functions.defn)
; defn is used to bind a value to a symbol
(defn say-hello
"Takes a name as argument and says hello to that name"
[name]
println (str "Hello, " name "!"))
(say-hello "PI:NAME:<NAME>END_PI")
; To read documentation (doc say-hello)
; Getting a function's meta data
(meta (var say-hello))
|
[
{
"context": ";; Copyright 2015 Ben Ashford\n;;\n;; Licensed under the Apache License, Version ",
"end": 29,
"score": 0.9998706579208374,
"start": 18,
"tag": "NAME",
"value": "Ben Ashford"
}
] | src/redis_async/core.clj | benashford/redis-async | 19 | ;; Copyright 2015 Ben Ashford
;;
;; 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 redis-async.core
(:refer-clojure :exclude [send])
(:require [clojure.core.async :as a]
[clojure.string :as s]
[redis-async.protocol :as protocol])
(:import [jresp Client Responses]
[jresp.pool Pool SingleCommandConnection]))
;; Defaults
(defn- default-redis []
{:host (or (System/getenv "REDIS_HOST") "localhost")
:port 6379})
;; is? functions
(defn is-error? [v]
(let [klass (class v)]
(= klass jresp.protocol.Err)))
(defn is-end-of-channel? [v]
(let [klass (class v)]
(= klass jresp.protocol.EndOfResponses)))
;; Response handlers
(defn- make-single-response-handler
"Make a response handler, that writes to a specific channel"
[ret-c]
(reify Responses
(responseReceived [this resp]
(a/put! ret-c resp)
(a/close! ret-c))))
(defn make-stream-response-handler
"Make a response handler that streams to a specific channel"
[ret-c]
(reify Responses
(responseReceived [this resp]
(if (is-end-of-channel? resp)
(a/close! ret-c)
(a/put! ret-c resp)))))
;; Commands
(defn send
"Send a command to a connection. Returns a channel which will contain the
result"
[^SingleCommandConnection con resp-msg]
(let [ret-c (a/chan)
resp-h (make-single-response-handler ret-c)]
(.write con resp-msg resp-h)
ret-c))
(defn get-connection
"Get a connection from the pool"
[^jresp.pool.Pool pool type]
(case type
:shared (.getShared pool)
:dedicated (.getDedicated pool)
:borrowed (.getBorrowed pool)
:pub-sub (.getPubSub pool)
(throw (ex-info (format "Unknown connection type: %s" type) {}))))
(defn finish-connection
"Return a borrowed connection to the pool"
[^jresp.pool.Pool pool
^jresp.pool.SingleCommandConnection con]
(.returnBorrowed pool con))
(defn close-connection
"Close a dedicated connection once finished"
[^jresp.Connection con]
(.stop con))
;; Standard send-command
(def ^:dynamic *trans-con* nil)
(defn send-cmd
"Send a command to the appropriate pool, will use the shared connection"
[pool command params]
(let [con (or *trans-con* (get-connection pool :shared))
payload (protocol/->resp (concat command params))]
(send con payload)))
(defn- finish-transaction [pool con finish-with]
(let [close-ch (send con (protocol/->resp [finish-with]))]
(a/go
(let [result (a/<! close-ch)]
(finish-connection pool con)
result))))
(defn do-with-transaction [pool work-f]
(let [con (get-connection pool :borrowed)
init-c (send con
(protocol/->resp ["MULTI"]))]
(try
(binding [*trans-con* con]
(work-f))
(finish-transaction pool con "EXEC")
(catch Throwable t
(finish-transaction pool con "DISCARD")
(throw t)))))
(defmacro with-transaction [pool & body]
`(do-with-transaction ~pool (fn [] ~@body)))
;; Pool management
(defn make-pool [connection-info]
(let [connection-info (merge (default-redis) connection-info)
{host :host
port :port} connection-info
client (Client. host port)]
(if-let [password (:password connection-info)]
(.setPassword client password))
(if-let [db (:db connection-info)]
(.setDb client (int db)))
(Pool. client)))
(defn close-pool [^Pool pool]
(.shutdown pool))
| 97001 | ;; 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 redis-async.core
(:refer-clojure :exclude [send])
(:require [clojure.core.async :as a]
[clojure.string :as s]
[redis-async.protocol :as protocol])
(:import [jresp Client Responses]
[jresp.pool Pool SingleCommandConnection]))
;; Defaults
(defn- default-redis []
{:host (or (System/getenv "REDIS_HOST") "localhost")
:port 6379})
;; is? functions
(defn is-error? [v]
(let [klass (class v)]
(= klass jresp.protocol.Err)))
(defn is-end-of-channel? [v]
(let [klass (class v)]
(= klass jresp.protocol.EndOfResponses)))
;; Response handlers
(defn- make-single-response-handler
"Make a response handler, that writes to a specific channel"
[ret-c]
(reify Responses
(responseReceived [this resp]
(a/put! ret-c resp)
(a/close! ret-c))))
(defn make-stream-response-handler
"Make a response handler that streams to a specific channel"
[ret-c]
(reify Responses
(responseReceived [this resp]
(if (is-end-of-channel? resp)
(a/close! ret-c)
(a/put! ret-c resp)))))
;; Commands
(defn send
"Send a command to a connection. Returns a channel which will contain the
result"
[^SingleCommandConnection con resp-msg]
(let [ret-c (a/chan)
resp-h (make-single-response-handler ret-c)]
(.write con resp-msg resp-h)
ret-c))
(defn get-connection
"Get a connection from the pool"
[^jresp.pool.Pool pool type]
(case type
:shared (.getShared pool)
:dedicated (.getDedicated pool)
:borrowed (.getBorrowed pool)
:pub-sub (.getPubSub pool)
(throw (ex-info (format "Unknown connection type: %s" type) {}))))
(defn finish-connection
"Return a borrowed connection to the pool"
[^jresp.pool.Pool pool
^jresp.pool.SingleCommandConnection con]
(.returnBorrowed pool con))
(defn close-connection
"Close a dedicated connection once finished"
[^jresp.Connection con]
(.stop con))
;; Standard send-command
(def ^:dynamic *trans-con* nil)
(defn send-cmd
"Send a command to the appropriate pool, will use the shared connection"
[pool command params]
(let [con (or *trans-con* (get-connection pool :shared))
payload (protocol/->resp (concat command params))]
(send con payload)))
(defn- finish-transaction [pool con finish-with]
(let [close-ch (send con (protocol/->resp [finish-with]))]
(a/go
(let [result (a/<! close-ch)]
(finish-connection pool con)
result))))
(defn do-with-transaction [pool work-f]
(let [con (get-connection pool :borrowed)
init-c (send con
(protocol/->resp ["MULTI"]))]
(try
(binding [*trans-con* con]
(work-f))
(finish-transaction pool con "EXEC")
(catch Throwable t
(finish-transaction pool con "DISCARD")
(throw t)))))
(defmacro with-transaction [pool & body]
`(do-with-transaction ~pool (fn [] ~@body)))
;; Pool management
(defn make-pool [connection-info]
(let [connection-info (merge (default-redis) connection-info)
{host :host
port :port} connection-info
client (Client. host port)]
(if-let [password (:password connection-info)]
(.setPassword client password))
(if-let [db (:db connection-info)]
(.setDb client (int db)))
(Pool. client)))
(defn close-pool [^Pool pool]
(.shutdown pool))
| 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 redis-async.core
(:refer-clojure :exclude [send])
(:require [clojure.core.async :as a]
[clojure.string :as s]
[redis-async.protocol :as protocol])
(:import [jresp Client Responses]
[jresp.pool Pool SingleCommandConnection]))
;; Defaults
(defn- default-redis []
{:host (or (System/getenv "REDIS_HOST") "localhost")
:port 6379})
;; is? functions
(defn is-error? [v]
(let [klass (class v)]
(= klass jresp.protocol.Err)))
(defn is-end-of-channel? [v]
(let [klass (class v)]
(= klass jresp.protocol.EndOfResponses)))
;; Response handlers
(defn- make-single-response-handler
"Make a response handler, that writes to a specific channel"
[ret-c]
(reify Responses
(responseReceived [this resp]
(a/put! ret-c resp)
(a/close! ret-c))))
(defn make-stream-response-handler
"Make a response handler that streams to a specific channel"
[ret-c]
(reify Responses
(responseReceived [this resp]
(if (is-end-of-channel? resp)
(a/close! ret-c)
(a/put! ret-c resp)))))
;; Commands
(defn send
"Send a command to a connection. Returns a channel which will contain the
result"
[^SingleCommandConnection con resp-msg]
(let [ret-c (a/chan)
resp-h (make-single-response-handler ret-c)]
(.write con resp-msg resp-h)
ret-c))
(defn get-connection
"Get a connection from the pool"
[^jresp.pool.Pool pool type]
(case type
:shared (.getShared pool)
:dedicated (.getDedicated pool)
:borrowed (.getBorrowed pool)
:pub-sub (.getPubSub pool)
(throw (ex-info (format "Unknown connection type: %s" type) {}))))
(defn finish-connection
"Return a borrowed connection to the pool"
[^jresp.pool.Pool pool
^jresp.pool.SingleCommandConnection con]
(.returnBorrowed pool con))
(defn close-connection
"Close a dedicated connection once finished"
[^jresp.Connection con]
(.stop con))
;; Standard send-command
(def ^:dynamic *trans-con* nil)
(defn send-cmd
"Send a command to the appropriate pool, will use the shared connection"
[pool command params]
(let [con (or *trans-con* (get-connection pool :shared))
payload (protocol/->resp (concat command params))]
(send con payload)))
(defn- finish-transaction [pool con finish-with]
(let [close-ch (send con (protocol/->resp [finish-with]))]
(a/go
(let [result (a/<! close-ch)]
(finish-connection pool con)
result))))
(defn do-with-transaction [pool work-f]
(let [con (get-connection pool :borrowed)
init-c (send con
(protocol/->resp ["MULTI"]))]
(try
(binding [*trans-con* con]
(work-f))
(finish-transaction pool con "EXEC")
(catch Throwable t
(finish-transaction pool con "DISCARD")
(throw t)))))
(defmacro with-transaction [pool & body]
`(do-with-transaction ~pool (fn [] ~@body)))
;; Pool management
(defn make-pool [connection-info]
(let [connection-info (merge (default-redis) connection-info)
{host :host
port :port} connection-info
client (Client. host port)]
(if-let [password (:password connection-info)]
(.setPassword client password))
(if-let [db (:db connection-info)]
(.setDb client (int db)))
(Pool. client)))
(defn close-pool [^Pool pool]
(.shutdown pool))
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns ^{:doc \"\"\n :autho",
"end": 597,
"score": 0.9998745918273926,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
},
{
"context": "ll rights reserved.\n\n(ns ^{:doc \"\"\n :author \"Kenneth Leung\"}\n\n czlab.loki.xpis\n\n (:require [czlab.basal.co",
"end": 663,
"score": 0.999882698059082,
"start": 650,
"tag": "NAME",
"value": "Kenneth Leung"
}
] | src/main/clojure/czlab/loki/xpis.clj | llnek/loki | 0 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.
(ns ^{:doc ""
:author "Kenneth Leung"}
czlab.loki.xpis
(:require [czlab.basal.core :as c]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def type-private 3)
(def type-public 2)
(defn msg-types
""
[v]
(case v
type-public "public"
type-private "private" ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def status-error 500)
(def status-ok 200)
(defn status-codes
""
[v]
(case v
status-ok "OK"
status-error "Internal Server Error" ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def playgame-req 600)
(def playreq-ok 601)
(def playreq-nok 602)
(def joingame-req 651)
(def joinreq-ok 652)
(def joinreq-nok 653)
(def user-nok 700)
(def game-nok 701)
(def room-nok 702)
(def room-filled 703)
(def rooms-full 704)
(def player-joined 800)
(def await-start 801)
(def connected 820)
(def started 821)
(def closed 822)
(def tear-down 823)
(def restart 840)
(def start 841)
(def stop 842)
(def start-nxt-round 843)
(def end-cur-round 844)
(def poke-rumble 860)
(def poke-move 861)
(def poke-wait 862)
(def sync-arena 863)
(def replay 880)
(def play-move 881)
(def play-scrubbed 882)
(def game-won 890)
(def game-tie 891)
(def quit 911)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn msg-codes
""
[v]
(case v
playgame-req "playgame-req"
playreq-ok "playreq-ok"
playreq-nok "playreq-nok"
joingame-req "joingame-req"
joinreq-ok "joinreq-ok"
joinreq-nok "joinreq-nok"
user-nok "user-nok"
game-nok "game-nok"
room-nok "room-nok"
room-filled "room-filled"
rooms-full "rooms-full"
player-joined "player-joined"
await-start "await-start"
connected "connected"
started "started"
closed "closed"
tear-down "tear-down"
restart "restart"
start "start"
stop "stop"
start-round "start-round"
end-round "end-round"
poke-rumble "poke-rumble"
poke-move "poke-move"
poke-wait "poke-wait"
sync-arena "sync-arena"
replay "replay"
play-move "play-move"
play-scrubbed "play-scrubbed"
game-won "game-won"
game-tie "game-tie"
quit "quit"
""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameBoard
""
(get-next-moves [_ game] "")
(game-over? [_ game] "")
(eval-score [_ game] "")
(unmake-move [_ game move] "")
(make-move [_ game move] "")
(switch-player [_ game] "")
(take-snap-shot [_] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameImpl
""
(get-player-gist [_ id] "")
(start-round [_ arg] "")
(end-round [_] "")
(on-game-event [_ evt] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol PubSub
""
(unsub-if-session [_ session] "")
(unsub [_ handler] "")
(sub [_ handler] "")
(pub-event [_ event] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameRoom
""
(broad-cast [_ evt] "")
(count-players [_] "")
(can-open-room? [_] "")
(on-room-event [_ evt] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 122061 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, <NAME>. All rights reserved.
(ns ^{:doc ""
:author "<NAME>"}
czlab.loki.xpis
(:require [czlab.basal.core :as c]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def type-private 3)
(def type-public 2)
(defn msg-types
""
[v]
(case v
type-public "public"
type-private "private" ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def status-error 500)
(def status-ok 200)
(defn status-codes
""
[v]
(case v
status-ok "OK"
status-error "Internal Server Error" ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def playgame-req 600)
(def playreq-ok 601)
(def playreq-nok 602)
(def joingame-req 651)
(def joinreq-ok 652)
(def joinreq-nok 653)
(def user-nok 700)
(def game-nok 701)
(def room-nok 702)
(def room-filled 703)
(def rooms-full 704)
(def player-joined 800)
(def await-start 801)
(def connected 820)
(def started 821)
(def closed 822)
(def tear-down 823)
(def restart 840)
(def start 841)
(def stop 842)
(def start-nxt-round 843)
(def end-cur-round 844)
(def poke-rumble 860)
(def poke-move 861)
(def poke-wait 862)
(def sync-arena 863)
(def replay 880)
(def play-move 881)
(def play-scrubbed 882)
(def game-won 890)
(def game-tie 891)
(def quit 911)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn msg-codes
""
[v]
(case v
playgame-req "playgame-req"
playreq-ok "playreq-ok"
playreq-nok "playreq-nok"
joingame-req "joingame-req"
joinreq-ok "joinreq-ok"
joinreq-nok "joinreq-nok"
user-nok "user-nok"
game-nok "game-nok"
room-nok "room-nok"
room-filled "room-filled"
rooms-full "rooms-full"
player-joined "player-joined"
await-start "await-start"
connected "connected"
started "started"
closed "closed"
tear-down "tear-down"
restart "restart"
start "start"
stop "stop"
start-round "start-round"
end-round "end-round"
poke-rumble "poke-rumble"
poke-move "poke-move"
poke-wait "poke-wait"
sync-arena "sync-arena"
replay "replay"
play-move "play-move"
play-scrubbed "play-scrubbed"
game-won "game-won"
game-tie "game-tie"
quit "quit"
""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameBoard
""
(get-next-moves [_ game] "")
(game-over? [_ game] "")
(eval-score [_ game] "")
(unmake-move [_ game move] "")
(make-move [_ game move] "")
(switch-player [_ game] "")
(take-snap-shot [_] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameImpl
""
(get-player-gist [_ id] "")
(start-round [_ arg] "")
(end-round [_] "")
(on-game-event [_ evt] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol PubSub
""
(unsub-if-session [_ session] "")
(unsub [_ handler] "")
(sub [_ handler] "")
(pub-event [_ event] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameRoom
""
(broad-cast [_ evt] "")
(count-players [_] "")
(can-open-room? [_] "")
(on-room-event [_ evt] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| true | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved.
(ns ^{:doc ""
:author "PI:NAME:<NAME>END_PI"}
czlab.loki.xpis
(:require [czlab.basal.core :as c]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def type-private 3)
(def type-public 2)
(defn msg-types
""
[v]
(case v
type-public "public"
type-private "private" ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def status-error 500)
(def status-ok 200)
(defn status-codes
""
[v]
(case v
status-ok "OK"
status-error "Internal Server Error" ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def playgame-req 600)
(def playreq-ok 601)
(def playreq-nok 602)
(def joingame-req 651)
(def joinreq-ok 652)
(def joinreq-nok 653)
(def user-nok 700)
(def game-nok 701)
(def room-nok 702)
(def room-filled 703)
(def rooms-full 704)
(def player-joined 800)
(def await-start 801)
(def connected 820)
(def started 821)
(def closed 822)
(def tear-down 823)
(def restart 840)
(def start 841)
(def stop 842)
(def start-nxt-round 843)
(def end-cur-round 844)
(def poke-rumble 860)
(def poke-move 861)
(def poke-wait 862)
(def sync-arena 863)
(def replay 880)
(def play-move 881)
(def play-scrubbed 882)
(def game-won 890)
(def game-tie 891)
(def quit 911)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn msg-codes
""
[v]
(case v
playgame-req "playgame-req"
playreq-ok "playreq-ok"
playreq-nok "playreq-nok"
joingame-req "joingame-req"
joinreq-ok "joinreq-ok"
joinreq-nok "joinreq-nok"
user-nok "user-nok"
game-nok "game-nok"
room-nok "room-nok"
room-filled "room-filled"
rooms-full "rooms-full"
player-joined "player-joined"
await-start "await-start"
connected "connected"
started "started"
closed "closed"
tear-down "tear-down"
restart "restart"
start "start"
stop "stop"
start-round "start-round"
end-round "end-round"
poke-rumble "poke-rumble"
poke-move "poke-move"
poke-wait "poke-wait"
sync-arena "sync-arena"
replay "replay"
play-move "play-move"
play-scrubbed "play-scrubbed"
game-won "game-won"
game-tie "game-tie"
quit "quit"
""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameBoard
""
(get-next-moves [_ game] "")
(game-over? [_ game] "")
(eval-score [_ game] "")
(unmake-move [_ game move] "")
(make-move [_ game move] "")
(switch-player [_ game] "")
(take-snap-shot [_] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameImpl
""
(get-player-gist [_ id] "")
(start-round [_ arg] "")
(end-round [_] "")
(on-game-event [_ evt] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol PubSub
""
(unsub-if-session [_ session] "")
(unsub [_ handler] "")
(sub [_ handler] "")
(pub-event [_ event] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol GameRoom
""
(broad-cast [_ evt] "")
(count-players [_] "")
(can-open-room? [_] "")
(on-room-event [_ evt] ""))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": " This file is part of gg4clj. Copyright (C) 2014-, Jony Hudson.\n;;;;\n;;;; gg4clj is licenced to you under the MI",
"end": 66,
"score": 0.999782145023346,
"start": 55,
"tag": "NAME",
"value": "Jony Hudson"
},
{
"context": "ure and Gorilla REPL.\"\n :url \"https://github.com/JonyEpsilon/gg4clj\"\n :license {:name \"MIT\"}\n :dependencies ",
"end": 315,
"score": 0.9994595050811768,
"start": 304,
"tag": "USERNAME",
"value": "JonyEpsilon"
}
] | project.clj | sbelak/gg4clj | 67 | ;;;; This file is part of gg4clj. Copyright (C) 2014-, Jony Hudson.
;;;;
;;;; gg4clj is licenced to you under the MIT licence. See the file LICENCE.txt for full details.
(defproject gg4clj "0.1.0"
:description "A simple wrapper for R's ggplot2 in Clojure and Gorilla REPL."
:url "https://github.com/JonyEpsilon/gg4clj"
:license {:name "MIT"}
:dependencies [[org.clojure/clojure "1.6.0"]
[gorilla-renderable "1.0.0"]]
:plugins [[lein-gorilla "0.3.4"]])
| 32245 | ;;;; This file is part of gg4clj. Copyright (C) 2014-, <NAME>.
;;;;
;;;; gg4clj is licenced to you under the MIT licence. See the file LICENCE.txt for full details.
(defproject gg4clj "0.1.0"
:description "A simple wrapper for R's ggplot2 in Clojure and Gorilla REPL."
:url "https://github.com/JonyEpsilon/gg4clj"
:license {:name "MIT"}
:dependencies [[org.clojure/clojure "1.6.0"]
[gorilla-renderable "1.0.0"]]
:plugins [[lein-gorilla "0.3.4"]])
| true | ;;;; This file is part of gg4clj. Copyright (C) 2014-, PI:NAME:<NAME>END_PI.
;;;;
;;;; gg4clj is licenced to you under the MIT licence. See the file LICENCE.txt for full details.
(defproject gg4clj "0.1.0"
:description "A simple wrapper for R's ggplot2 in Clojure and Gorilla REPL."
:url "https://github.com/JonyEpsilon/gg4clj"
:license {:name "MIT"}
:dependencies [[org.clojure/clojure "1.6.0"]
[gorilla-renderable "1.0.0"]]
:plugins [[lein-gorilla "0.3.4"]])
|
[
{
"context": ")\n\n;; 16: Hello World\n\n(= (#(str \"Hello, \" % \"!\")\"Dave\") \"Hello, Dave!\")",
"end": 1314,
"score": 0.6827212572097778,
"start": 1310,
"tag": "NAME",
"value": "Dave"
},
{
"context": "World\n\n(= (#(str \"Hello, \" % \"!\")\"Dave\") \"Hello, Dave!\")",
"end": 1329,
"score": 0.8846395611763,
"start": 1326,
"tag": "NAME",
"value": "ave"
}
] | answers_4clojure.clj | jvcanavarro/cleitonjure | 0 | ;; minhas respostas pros problemas do 4clojure
;; http://www.4clojure.com/problems
;; 01: Nothing but the Truth
(= true true)
;; 02: Simple Math
(= (- 10 (* 2 3)) 4)
;; 03: Intro to Strings
(= "HELLO WORLD" (.toUpperCase "hello world"))
;; 04: Intro to Lists
(= (list :a :b :c) '(:a :b :c))
;; 05: conj
(= '(1 2 3 4) (conj '(2 3 4) 1))
(= '(1 2 3 4) (conj '(3 4) 2 1))
;; 06: Intro to Vectors
(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))
;; 07: Vector: conj
(= [1 2 3 4] (conj [1 2 3] 4))
(= [1 2 3 4] (conj [1 2] 3 4))
;; 08: Intro to Sets
(= #{:c :b :d :a} (set '(:a :a :b :c :c :c :c :d :d)))
(= #{:c :b :d :a} (clojure.set/union #{:a :b :c} #{:b :c :d}))
;; 09: Sets: conj
(= #{1 2 3 4} (conj #{1 4 3} 2))
;; 10: Intro to Maps
(= 20 ((hash-map :a 10, :b 20, :c 30) :b))
(= 20 (:b {:a 10, :b 20, :c 30}))
;; 11: Maps: conj
(= {:a 1, :b 2, :c 3} (conj {:a 1} [:b 2] [:c 3]))
;; 12: Intro to Sequences
(= 3 (first '(3 2 1)))
(= 3 (second [2 3 4]))
(= 3 (last (list 1 2 3)))
;; 13: Sequences: rest
(= [20 30 40] (rest [10 20 30 40])
;; 14: Intro to Functions
(= 8 ((fn add-five [x] (+ x 5)) 3))
(= 8 ((fn [x] (+ x 5)) 3))
(= 8 (#(+ % 5) 3))
(= 8 ((partial + 5) 3))
;; 15: Double Down
(= (* 2 2) 4)
;; 16: Hello World
(= (#(str "Hello, " % "!")"Dave") "Hello, Dave!") | 78628 | ;; minhas respostas pros problemas do 4clojure
;; http://www.4clojure.com/problems
;; 01: Nothing but the Truth
(= true true)
;; 02: Simple Math
(= (- 10 (* 2 3)) 4)
;; 03: Intro to Strings
(= "HELLO WORLD" (.toUpperCase "hello world"))
;; 04: Intro to Lists
(= (list :a :b :c) '(:a :b :c))
;; 05: conj
(= '(1 2 3 4) (conj '(2 3 4) 1))
(= '(1 2 3 4) (conj '(3 4) 2 1))
;; 06: Intro to Vectors
(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))
;; 07: Vector: conj
(= [1 2 3 4] (conj [1 2 3] 4))
(= [1 2 3 4] (conj [1 2] 3 4))
;; 08: Intro to Sets
(= #{:c :b :d :a} (set '(:a :a :b :c :c :c :c :d :d)))
(= #{:c :b :d :a} (clojure.set/union #{:a :b :c} #{:b :c :d}))
;; 09: Sets: conj
(= #{1 2 3 4} (conj #{1 4 3} 2))
;; 10: Intro to Maps
(= 20 ((hash-map :a 10, :b 20, :c 30) :b))
(= 20 (:b {:a 10, :b 20, :c 30}))
;; 11: Maps: conj
(= {:a 1, :b 2, :c 3} (conj {:a 1} [:b 2] [:c 3]))
;; 12: Intro to Sequences
(= 3 (first '(3 2 1)))
(= 3 (second [2 3 4]))
(= 3 (last (list 1 2 3)))
;; 13: Sequences: rest
(= [20 30 40] (rest [10 20 30 40])
;; 14: Intro to Functions
(= 8 ((fn add-five [x] (+ x 5)) 3))
(= 8 ((fn [x] (+ x 5)) 3))
(= 8 (#(+ % 5) 3))
(= 8 ((partial + 5) 3))
;; 15: Double Down
(= (* 2 2) 4)
;; 16: Hello World
(= (#(str "Hello, " % "!")"<NAME>") "Hello, D<NAME>!") | true | ;; minhas respostas pros problemas do 4clojure
;; http://www.4clojure.com/problems
;; 01: Nothing but the Truth
(= true true)
;; 02: Simple Math
(= (- 10 (* 2 3)) 4)
;; 03: Intro to Strings
(= "HELLO WORLD" (.toUpperCase "hello world"))
;; 04: Intro to Lists
(= (list :a :b :c) '(:a :b :c))
;; 05: conj
(= '(1 2 3 4) (conj '(2 3 4) 1))
(= '(1 2 3 4) (conj '(3 4) 2 1))
;; 06: Intro to Vectors
(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))
;; 07: Vector: conj
(= [1 2 3 4] (conj [1 2 3] 4))
(= [1 2 3 4] (conj [1 2] 3 4))
;; 08: Intro to Sets
(= #{:c :b :d :a} (set '(:a :a :b :c :c :c :c :d :d)))
(= #{:c :b :d :a} (clojure.set/union #{:a :b :c} #{:b :c :d}))
;; 09: Sets: conj
(= #{1 2 3 4} (conj #{1 4 3} 2))
;; 10: Intro to Maps
(= 20 ((hash-map :a 10, :b 20, :c 30) :b))
(= 20 (:b {:a 10, :b 20, :c 30}))
;; 11: Maps: conj
(= {:a 1, :b 2, :c 3} (conj {:a 1} [:b 2] [:c 3]))
;; 12: Intro to Sequences
(= 3 (first '(3 2 1)))
(= 3 (second [2 3 4]))
(= 3 (last (list 1 2 3)))
;; 13: Sequences: rest
(= [20 30 40] (rest [10 20 30 40])
;; 14: Intro to Functions
(= 8 ((fn add-five [x] (+ x 5)) 3))
(= 8 ((fn [x] (+ x 5)) 3))
(= 8 (#(+ % 5) 3))
(= 8 ((partial + 5) 3))
;; 15: Double Down
(= (* 2 2) 4)
;; 16: Hello World
(= (#(str "Hello, " % "!")"PI:NAME:<NAME>END_PI") "Hello, DPI:NAME:<NAME>END_PI!") |
[
{
"context": "(do-game\n (new-game (default-contestant [(qty \"Meru Mati\" 2)])\n (default-challenger))\n (pl",
"end": 4055,
"score": 0.9980343580245972,
"start": 4046,
"tag": "NAME",
"value": "Meru Mati"
},
{
"context": "allenger))\n (play-from-hand state :contestant \"Meru Mati\" \"HQ\")\n (play-from-hand state :contestant \"Mer",
"end": 4146,
"score": 0.9990355372428894,
"start": 4137,
"tag": "NAME",
"value": "Meru Mati"
},
{
"context": "ati\" \"HQ\")\n (play-from-hand state :contestant \"Meru Mati\" \"R&D\")\n (core/reveal state :contestant (get-c",
"end": 4202,
"score": 0.9987386465072632,
"start": 4193,
"tag": "NAME",
"value": "Meru Mati"
},
{
"context": "current-strength (get-character state :hq 0))) \"HQ Meru Mati at 4 strength\")\n (is (= 1 (:current-strength ",
"end": 4413,
"score": 0.7657263875007629,
"start": 4405,
"tag": "NAME",
"value": "Meru Mat"
},
{
"context": "t [\"Waiver\"])\n (default-challenger [\"Corroder\" \"Dean Lister\" \"Ubax\" \"Caldera\"]))\n (play-from",
"end": 12786,
"score": 0.7990536093711853,
"start": 12778,
"tag": "NAME",
"value": "Corroder"
},
{
"context": "])\n (default-challenger [\"Corroder\" \"Dean Lister\" \"Ubax\" \"Caldera\"]))\n (play-from-hand state :c",
"end": 12800,
"score": 0.9895014762878418,
"start": 12789,
"tag": "NAME",
"value": "Dean Lister"
},
{
"context": "t-challenger [\"Corroder\" \"Dean Lister\" \"Ubax\" \"Caldera\"]))\n (play-from-hand state :contestant \"Waive",
"end": 12816,
"score": 0.5992363691329956,
"start": 12813,
"tag": "NAME",
"value": "der"
}
] | test/clj/game_test/cards/character.clj | rezwits/carncode | 15 | (ns game-test.cards.character
(:require [game.core :as core]
[game.utils :refer [has?]]
[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 "character"))
(deftest architect
(testing "Architect is undiscardable while placed and revealed, but discardable if hidden or from HQ"
(do-game
(new-game (default-contestant [(qty "Architect" 3)])
(default-challenger))
(play-from-hand state :contestant "Architect" "HQ")
(let [architect (get-character state :hq 0)]
(core/reveal state :contestant architect)
(core/discard state :contestant (refresh architect))
(is (not= nil (get-character state :hq 0)) "Architect was discarded, but should be undiscardable")
(core/hide state :contestant (refresh architect))
(core/discard state :contestant (refresh architect))
(is (= nil (get-character state :hq 0)) "Architect was not discarded, but should be discardable")
(core/discard state :contestant (get-in @state [:contestant :hand 0]))
(is (= (get-in @state [:contestant :discard 0 :title]) "Architect"))
(is (= (get-in @state [:contestant :discard 1 :title]) "Architect"))))))
(deftest curtain-wall
;; Curtain Wall - Strength boost when outermost Character
(do-game
(new-game (default-contestant ["Curtain Wall" "Paper Wall"])
(default-challenger))
(core/gain state :contestant :credit 10)
(play-from-hand state :contestant "Curtain Wall" "HQ")
(let [curt (get-character state :hq 0)]
(core/reveal state :contestant curt)
(is (= 10 (:current-strength (refresh curt)))
"Curtain Wall has +4 strength as outermost Character")
(play-from-hand state :contestant "Paper Wall" "HQ")
(let [paper (get-character state :hq 1)]
(core/reveal state :contestant paper)
(is (= 6 (:current-strength (refresh curt))) "Curtain Wall back to default 6 strength")))))
(deftest free-lunch
;; Free Lunch - Spend 1 power counter to make Challenger lose 1c
(do-game
(new-game (default-contestant ["Free Lunch"])
(default-challenger))
(play-from-hand state :contestant "Free Lunch" "HQ")
(let [fl (get-character state :hq 0)]
(core/reveal state :contestant fl)
(card-subroutine state :contestant fl 0)
(is (= 1 (get-counters (refresh fl) :power)) "Free Lunch has 1 power counter")
(card-subroutine state :contestant fl 0)
(is (= 2 (get-counters (refresh fl) :power)) "Free Lunch has 2 power counters")
(is (= 5 (:credit (get-challenger))))
(card-ability state :contestant (refresh fl) 0)
(is (= 1 (get-counters (refresh fl) :power)) "Free Lunch has 1 power counter")
(is (= 4 (:credit (get-challenger))) "Challenger lost 1 credit"))))
(deftest iq
;; IQ - Reveal cost and strength equal to cards in HQ
(do-game
(new-game (default-contestant [(qty "IQ" 3) (qty "Hedge Fund" 3)])
(default-challenger))
(play-from-hand state :contestant "Hedge Fund")
(play-from-hand state :contestant "IQ" "R&D")
(let [iq1 (get-character state :rd 0)]
(core/reveal state :contestant iq1)
(is (and (= 4 (count (:hand (get-contestant))))
(= 4 (:current-strength (refresh iq1)))
(= 5 (:credit (get-contestant)))) "4 cards in HQ: paid 4 to reveal, has 4 strength")
(play-from-hand state :contestant "IQ" "HQ")
(let [iq2 (get-character state :hq 0)]
(core/reveal state :contestant iq2)
(is (and (= 3 (count (:hand (get-contestant))))
(= 3 (:current-strength (refresh iq1)))
(= 3 (:current-strength (refresh iq2)))
(= 2 (:credit (get-contestant)))) "3 cards in HQ: paid 3 to reveal, both have 3 strength")))))
(deftest meru-mati
(do-game
(new-game (default-contestant [(qty "Meru Mati" 2)])
(default-challenger))
(play-from-hand state :contestant "Meru Mati" "HQ")
(play-from-hand state :contestant "Meru Mati" "R&D")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(is (= 4 (:current-strength (get-character state :hq 0))) "HQ Meru Mati at 4 strength")
(is (= 1 (:current-strength (get-character state :rd 0))) "R&D at 0 strength")))
(deftest mother-goddess
;; Mother Goddess - Gains other character subtypes
(do-game
(new-game (default-contestant ["Mother Goddess" "NEXT Bronze"])
(default-challenger))
(core/gain state :contestant :credit 1)
(play-from-hand state :contestant "Mother Goddess" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(let [mg (get-character state :hq 0)
nb (get-character state :rd 0)]
(core/reveal state :contestant mg)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has Mythic")
(is (not (core/has-subtype? (refresh mg) "Code Gate")) "Mother Goddess does not have Code Gate")
(is (not (core/has-subtype? (refresh mg) "NEXT")) "Mother Goddess does not have NEXT")
(core/reveal state :contestant nb)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has Mythic")
(is (core/has-subtype? (refresh mg) "Code Gate") "Mother Goddess has Code Gate")
(is (core/has-subtype? (refresh mg) "NEXT") "Mother Goddess has NEXT"))))
(deftest next-bronze
;; NEXT Bronze - Add 1 strength for every revealed NEXT character
(do-game
(new-game (default-contestant [(qty "NEXT Bronze" 2) "NEXT Silver"])
(default-challenger))
(core/gain state :contestant :credit 2)
(play-from-hand state :contestant "NEXT Bronze" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(play-from-hand state :contestant "NEXT Silver" "Archives")
(let [nb1 (get-character state :hq 0)
nb2 (get-character state :rd 0)
ns1 (get-character state :archives 0)]
(core/reveal state :contestant nb1)
(is (= 1 (:current-strength (refresh nb1)))
"NEXT Bronze at 1 strength: 1 revealed NEXT character")
(core/reveal state :contestant nb2)
(is (= 2 (:current-strength (refresh nb1)))
"NEXT Bronze at 2 strength: 2 revealed NEXT character")
(is (= 2 (:current-strength (refresh nb2)))
"NEXT Bronze at 2 strength: 2 revealed NEXT character")
(core/reveal state :contestant ns1)
(is (= 3 (:current-strength (refresh nb1)))
"NEXT Bronze at 3 strength: 3 revealed NEXT character")
(is (= 3 (:current-strength (refresh nb2)))
"NEXT Bronze at 3 strength: 3 revealed NEXT character"))))
(deftest next-diamond
;; NEXT Diamond - Reveal cost is lowered by 1 for each revealed NEXT character
(testing "Base reveal cost"
(do-game
(new-game (default-contestant ["NEXT Diamond"])
(default-challenger))
(core/gain state :contestant :credit 5)
(is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits")
(play-from-hand state :contestant "NEXT Diamond" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (zero? (:credit (get-contestant))) "Contestant spends 10 credits to reveal")))
(testing "Lowered reveal cost"
(do-game
(new-game (default-contestant ["NEXT Diamond" "NEXT Opal" "NEXT Bronze" "Kakugo"])
(default-challenger))
(core/gain state :contestant :credit 13 :click 1)
(play-from-hand state :contestant "NEXT Diamond" "HQ")
(play-from-hand state :contestant "NEXT Opal" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(play-from-hand state :contestant "Kakugo" "Archives")
(core/reveal state :contestant (get-character state :hq 1))
(core/reveal state :contestant (get-character state :archives 0))
(is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits")
(core/reveal state :contestant (get-character state :hq 0))
(is (zero? (:credit (get-contestant))) "Contestant spends 9 credits to reveal"))))
(deftest seidr-adaptive-barrier
;; Seidr Adaptive Barrier - +1 strength for every character protecting its locale
(do-game
(new-game (default-contestant ["Seidr Adaptive Barrier" (qty "Character Wall" 2)])
(default-challenger))
(core/gain state :contestant :credit 10)
(play-from-hand state :contestant "Seidr Adaptive Barrier" "HQ")
(let [sab (get-character state :hq 0)]
(core/reveal state :contestant sab)
(is (= 3 (:current-strength (refresh sab))) "Seidr gained 1 strength for itself")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 4 (:current-strength (refresh sab))) "+2 strength for 2 pieces of Character")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 5 (:current-strength (refresh sab))) "+3 strength for 3 pieces of Character")
(core/move-card state :contestant {:card (get-character state :hq 1) :locale "Archives"})
(is (= 4 (:current-strength (refresh sab))) "+2 strength for 2 pieces of Character"))))
(deftest surveyor
;; Surveyor character strength
(do-game
(new-game (default-contestant [(qty "Surveyor" 1) (qty "Character Wall" 2)])
(default-challenger))
(core/gain state :contestant :credit 10)
(core/gain state :challenger :credit 10)
(play-from-hand state :contestant "Surveyor" "HQ")
(let [surv (get-character state :hq 0)]
(core/reveal state :contestant surv)
(is (= 2 (:current-strength (refresh surv))) "Surveyor has 2 strength for itself")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 4 (:current-strength (refresh surv))) "Surveyor has 4 strength for 2 pieces of Character")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 6 (:current-strength (refresh surv))) "Surveyor has 6 strength for 3 pieces of Character")
(run-on state "HQ")
(card-subroutine state :contestant surv 0)
(is (= 6 (-> (get-contestant) :prompt first :base)) "Trace should be base 6")
(prompt-choice :contestant 0)
(prompt-choice :challenger 5)
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from Surveyor Trace 6 with boost 5")
(card-subroutine state :contestant surv 0)
(is (= 6 (-> (get-contestant) :prompt first :base)) "Trace should be base 6")
(prompt-choice :contestant 0)
(prompt-choice :challenger 6)
(is (= 2 (:tag (get-challenger))) "Challenger did not take tags from Surveyor Trace 6 with boost 6")
(core/move-card state :contestant {:card (get-character state :hq 1) :locale "Archives"})
(is (= 4 (:current-strength (refresh surv))) "Surveyor has 4 strength for 2 pieces of Character"))))
(deftest tmi
;; TMI
(testing "Basic test"
(do-game
(new-game (default-contestant ["TMI"])
(default-challenger))
(play-from-hand state :contestant "TMI" "HQ")
(let [tmi (get-character state :hq 0)]
(core/reveal state :contestant tmi)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (:revealed (refresh tmi))))))
(testing "Losing trace hides TMI"
(do-game
(new-game (default-contestant ["TMI"])
(make-deck "Sunny Lebeau: Security Specialist" [(qty "Blackmail" 3)]))
(play-from-hand state :contestant "TMI" "HQ")
(let [tmi (get-character state :hq 0)]
(core/reveal state :contestant tmi)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (not (:revealed (refresh tmi))))))))
(deftest turing
;; Turing - Strength boosted when protecting a party locale
(do-game
(new-game (default-contestant [(qty "Turing" 2) "Hedge Fund"])
(default-challenger))
(play-from-hand state :contestant "Hedge Fund")
(play-from-hand state :contestant "Turing" "HQ")
(play-from-hand state :contestant "Turing" "New party")
(let [t1 (get-character state :hq 0)
t2 (get-character state :party1 0)]
(core/reveal state :contestant t1)
(is (= 2 (:current-strength (refresh t1)))
"Turing default 2 strength over a central locale")
(core/reveal state :contestant t2)
(is (= 5 (:current-strength (refresh t2)))
"Turing increased to 5 strength over a party locale"))))
(deftest waiver
;; Waiver - Discard Challenger cards in grip with play/place cost <= trace exceed
(do-game
(new-game (default-contestant ["Waiver"])
(default-challenger ["Corroder" "Dean Lister" "Ubax" "Caldera"]))
(play-from-hand state :contestant "Waiver" "HQ")
(let [waiv (get-character state :hq 0)]
(core/reveal state :contestant waiv)
(card-subroutine state :contestant waiv 0)
(prompt-choice :contestant 0)
(prompt-choice :challenger 3)
(is (empty? (filter #(= "Ubax" (:title %)) (:discard (get-challenger)))) "Ubax not discarded")
(is (empty? (filter #(= "Caldera" (:title %)) (:discard (get-challenger)))) "Caldera not discarded")
(is (= 2 (count (:discard (get-challenger)))) "2 cards discarded"))))
| 88192 | (ns game-test.cards.character
(:require [game.core :as core]
[game.utils :refer [has?]]
[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 "character"))
(deftest architect
(testing "Architect is undiscardable while placed and revealed, but discardable if hidden or from HQ"
(do-game
(new-game (default-contestant [(qty "Architect" 3)])
(default-challenger))
(play-from-hand state :contestant "Architect" "HQ")
(let [architect (get-character state :hq 0)]
(core/reveal state :contestant architect)
(core/discard state :contestant (refresh architect))
(is (not= nil (get-character state :hq 0)) "Architect was discarded, but should be undiscardable")
(core/hide state :contestant (refresh architect))
(core/discard state :contestant (refresh architect))
(is (= nil (get-character state :hq 0)) "Architect was not discarded, but should be discardable")
(core/discard state :contestant (get-in @state [:contestant :hand 0]))
(is (= (get-in @state [:contestant :discard 0 :title]) "Architect"))
(is (= (get-in @state [:contestant :discard 1 :title]) "Architect"))))))
(deftest curtain-wall
;; Curtain Wall - Strength boost when outermost Character
(do-game
(new-game (default-contestant ["Curtain Wall" "Paper Wall"])
(default-challenger))
(core/gain state :contestant :credit 10)
(play-from-hand state :contestant "Curtain Wall" "HQ")
(let [curt (get-character state :hq 0)]
(core/reveal state :contestant curt)
(is (= 10 (:current-strength (refresh curt)))
"Curtain Wall has +4 strength as outermost Character")
(play-from-hand state :contestant "Paper Wall" "HQ")
(let [paper (get-character state :hq 1)]
(core/reveal state :contestant paper)
(is (= 6 (:current-strength (refresh curt))) "Curtain Wall back to default 6 strength")))))
(deftest free-lunch
;; Free Lunch - Spend 1 power counter to make Challenger lose 1c
(do-game
(new-game (default-contestant ["Free Lunch"])
(default-challenger))
(play-from-hand state :contestant "Free Lunch" "HQ")
(let [fl (get-character state :hq 0)]
(core/reveal state :contestant fl)
(card-subroutine state :contestant fl 0)
(is (= 1 (get-counters (refresh fl) :power)) "Free Lunch has 1 power counter")
(card-subroutine state :contestant fl 0)
(is (= 2 (get-counters (refresh fl) :power)) "Free Lunch has 2 power counters")
(is (= 5 (:credit (get-challenger))))
(card-ability state :contestant (refresh fl) 0)
(is (= 1 (get-counters (refresh fl) :power)) "Free Lunch has 1 power counter")
(is (= 4 (:credit (get-challenger))) "Challenger lost 1 credit"))))
(deftest iq
;; IQ - Reveal cost and strength equal to cards in HQ
(do-game
(new-game (default-contestant [(qty "IQ" 3) (qty "Hedge Fund" 3)])
(default-challenger))
(play-from-hand state :contestant "Hedge Fund")
(play-from-hand state :contestant "IQ" "R&D")
(let [iq1 (get-character state :rd 0)]
(core/reveal state :contestant iq1)
(is (and (= 4 (count (:hand (get-contestant))))
(= 4 (:current-strength (refresh iq1)))
(= 5 (:credit (get-contestant)))) "4 cards in HQ: paid 4 to reveal, has 4 strength")
(play-from-hand state :contestant "IQ" "HQ")
(let [iq2 (get-character state :hq 0)]
(core/reveal state :contestant iq2)
(is (and (= 3 (count (:hand (get-contestant))))
(= 3 (:current-strength (refresh iq1)))
(= 3 (:current-strength (refresh iq2)))
(= 2 (:credit (get-contestant)))) "3 cards in HQ: paid 3 to reveal, both have 3 strength")))))
(deftest meru-mati
(do-game
(new-game (default-contestant [(qty "<NAME>" 2)])
(default-challenger))
(play-from-hand state :contestant "<NAME>" "HQ")
(play-from-hand state :contestant "<NAME>" "R&D")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(is (= 4 (:current-strength (get-character state :hq 0))) "HQ <NAME>i at 4 strength")
(is (= 1 (:current-strength (get-character state :rd 0))) "R&D at 0 strength")))
(deftest mother-goddess
;; Mother Goddess - Gains other character subtypes
(do-game
(new-game (default-contestant ["Mother Goddess" "NEXT Bronze"])
(default-challenger))
(core/gain state :contestant :credit 1)
(play-from-hand state :contestant "Mother Goddess" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(let [mg (get-character state :hq 0)
nb (get-character state :rd 0)]
(core/reveal state :contestant mg)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has Mythic")
(is (not (core/has-subtype? (refresh mg) "Code Gate")) "Mother Goddess does not have Code Gate")
(is (not (core/has-subtype? (refresh mg) "NEXT")) "Mother Goddess does not have NEXT")
(core/reveal state :contestant nb)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has Mythic")
(is (core/has-subtype? (refresh mg) "Code Gate") "Mother Goddess has Code Gate")
(is (core/has-subtype? (refresh mg) "NEXT") "Mother Goddess has NEXT"))))
(deftest next-bronze
;; NEXT Bronze - Add 1 strength for every revealed NEXT character
(do-game
(new-game (default-contestant [(qty "NEXT Bronze" 2) "NEXT Silver"])
(default-challenger))
(core/gain state :contestant :credit 2)
(play-from-hand state :contestant "NEXT Bronze" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(play-from-hand state :contestant "NEXT Silver" "Archives")
(let [nb1 (get-character state :hq 0)
nb2 (get-character state :rd 0)
ns1 (get-character state :archives 0)]
(core/reveal state :contestant nb1)
(is (= 1 (:current-strength (refresh nb1)))
"NEXT Bronze at 1 strength: 1 revealed NEXT character")
(core/reveal state :contestant nb2)
(is (= 2 (:current-strength (refresh nb1)))
"NEXT Bronze at 2 strength: 2 revealed NEXT character")
(is (= 2 (:current-strength (refresh nb2)))
"NEXT Bronze at 2 strength: 2 revealed NEXT character")
(core/reveal state :contestant ns1)
(is (= 3 (:current-strength (refresh nb1)))
"NEXT Bronze at 3 strength: 3 revealed NEXT character")
(is (= 3 (:current-strength (refresh nb2)))
"NEXT Bronze at 3 strength: 3 revealed NEXT character"))))
(deftest next-diamond
;; NEXT Diamond - Reveal cost is lowered by 1 for each revealed NEXT character
(testing "Base reveal cost"
(do-game
(new-game (default-contestant ["NEXT Diamond"])
(default-challenger))
(core/gain state :contestant :credit 5)
(is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits")
(play-from-hand state :contestant "NEXT Diamond" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (zero? (:credit (get-contestant))) "Contestant spends 10 credits to reveal")))
(testing "Lowered reveal cost"
(do-game
(new-game (default-contestant ["NEXT Diamond" "NEXT Opal" "NEXT Bronze" "Kakugo"])
(default-challenger))
(core/gain state :contestant :credit 13 :click 1)
(play-from-hand state :contestant "NEXT Diamond" "HQ")
(play-from-hand state :contestant "NEXT Opal" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(play-from-hand state :contestant "Kakugo" "Archives")
(core/reveal state :contestant (get-character state :hq 1))
(core/reveal state :contestant (get-character state :archives 0))
(is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits")
(core/reveal state :contestant (get-character state :hq 0))
(is (zero? (:credit (get-contestant))) "Contestant spends 9 credits to reveal"))))
(deftest seidr-adaptive-barrier
;; Seidr Adaptive Barrier - +1 strength for every character protecting its locale
(do-game
(new-game (default-contestant ["Seidr Adaptive Barrier" (qty "Character Wall" 2)])
(default-challenger))
(core/gain state :contestant :credit 10)
(play-from-hand state :contestant "Seidr Adaptive Barrier" "HQ")
(let [sab (get-character state :hq 0)]
(core/reveal state :contestant sab)
(is (= 3 (:current-strength (refresh sab))) "Seidr gained 1 strength for itself")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 4 (:current-strength (refresh sab))) "+2 strength for 2 pieces of Character")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 5 (:current-strength (refresh sab))) "+3 strength for 3 pieces of Character")
(core/move-card state :contestant {:card (get-character state :hq 1) :locale "Archives"})
(is (= 4 (:current-strength (refresh sab))) "+2 strength for 2 pieces of Character"))))
(deftest surveyor
;; Surveyor character strength
(do-game
(new-game (default-contestant [(qty "Surveyor" 1) (qty "Character Wall" 2)])
(default-challenger))
(core/gain state :contestant :credit 10)
(core/gain state :challenger :credit 10)
(play-from-hand state :contestant "Surveyor" "HQ")
(let [surv (get-character state :hq 0)]
(core/reveal state :contestant surv)
(is (= 2 (:current-strength (refresh surv))) "Surveyor has 2 strength for itself")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 4 (:current-strength (refresh surv))) "Surveyor has 4 strength for 2 pieces of Character")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 6 (:current-strength (refresh surv))) "Surveyor has 6 strength for 3 pieces of Character")
(run-on state "HQ")
(card-subroutine state :contestant surv 0)
(is (= 6 (-> (get-contestant) :prompt first :base)) "Trace should be base 6")
(prompt-choice :contestant 0)
(prompt-choice :challenger 5)
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from Surveyor Trace 6 with boost 5")
(card-subroutine state :contestant surv 0)
(is (= 6 (-> (get-contestant) :prompt first :base)) "Trace should be base 6")
(prompt-choice :contestant 0)
(prompt-choice :challenger 6)
(is (= 2 (:tag (get-challenger))) "Challenger did not take tags from Surveyor Trace 6 with boost 6")
(core/move-card state :contestant {:card (get-character state :hq 1) :locale "Archives"})
(is (= 4 (:current-strength (refresh surv))) "Surveyor has 4 strength for 2 pieces of Character"))))
(deftest tmi
;; TMI
(testing "Basic test"
(do-game
(new-game (default-contestant ["TMI"])
(default-challenger))
(play-from-hand state :contestant "TMI" "HQ")
(let [tmi (get-character state :hq 0)]
(core/reveal state :contestant tmi)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (:revealed (refresh tmi))))))
(testing "Losing trace hides TMI"
(do-game
(new-game (default-contestant ["TMI"])
(make-deck "Sunny Lebeau: Security Specialist" [(qty "Blackmail" 3)]))
(play-from-hand state :contestant "TMI" "HQ")
(let [tmi (get-character state :hq 0)]
(core/reveal state :contestant tmi)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (not (:revealed (refresh tmi))))))))
(deftest turing
;; Turing - Strength boosted when protecting a party locale
(do-game
(new-game (default-contestant [(qty "Turing" 2) "Hedge Fund"])
(default-challenger))
(play-from-hand state :contestant "Hedge Fund")
(play-from-hand state :contestant "Turing" "HQ")
(play-from-hand state :contestant "Turing" "New party")
(let [t1 (get-character state :hq 0)
t2 (get-character state :party1 0)]
(core/reveal state :contestant t1)
(is (= 2 (:current-strength (refresh t1)))
"Turing default 2 strength over a central locale")
(core/reveal state :contestant t2)
(is (= 5 (:current-strength (refresh t2)))
"Turing increased to 5 strength over a party locale"))))
(deftest waiver
;; Waiver - Discard Challenger cards in grip with play/place cost <= trace exceed
(do-game
(new-game (default-contestant ["Waiver"])
(default-challenger ["<NAME>" "<NAME>" "Ubax" "Cal<NAME>a"]))
(play-from-hand state :contestant "Waiver" "HQ")
(let [waiv (get-character state :hq 0)]
(core/reveal state :contestant waiv)
(card-subroutine state :contestant waiv 0)
(prompt-choice :contestant 0)
(prompt-choice :challenger 3)
(is (empty? (filter #(= "Ubax" (:title %)) (:discard (get-challenger)))) "Ubax not discarded")
(is (empty? (filter #(= "Caldera" (:title %)) (:discard (get-challenger)))) "Caldera not discarded")
(is (= 2 (count (:discard (get-challenger)))) "2 cards discarded"))))
| true | (ns game-test.cards.character
(:require [game.core :as core]
[game.utils :refer [has?]]
[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 "character"))
(deftest architect
(testing "Architect is undiscardable while placed and revealed, but discardable if hidden or from HQ"
(do-game
(new-game (default-contestant [(qty "Architect" 3)])
(default-challenger))
(play-from-hand state :contestant "Architect" "HQ")
(let [architect (get-character state :hq 0)]
(core/reveal state :contestant architect)
(core/discard state :contestant (refresh architect))
(is (not= nil (get-character state :hq 0)) "Architect was discarded, but should be undiscardable")
(core/hide state :contestant (refresh architect))
(core/discard state :contestant (refresh architect))
(is (= nil (get-character state :hq 0)) "Architect was not discarded, but should be discardable")
(core/discard state :contestant (get-in @state [:contestant :hand 0]))
(is (= (get-in @state [:contestant :discard 0 :title]) "Architect"))
(is (= (get-in @state [:contestant :discard 1 :title]) "Architect"))))))
(deftest curtain-wall
;; Curtain Wall - Strength boost when outermost Character
(do-game
(new-game (default-contestant ["Curtain Wall" "Paper Wall"])
(default-challenger))
(core/gain state :contestant :credit 10)
(play-from-hand state :contestant "Curtain Wall" "HQ")
(let [curt (get-character state :hq 0)]
(core/reveal state :contestant curt)
(is (= 10 (:current-strength (refresh curt)))
"Curtain Wall has +4 strength as outermost Character")
(play-from-hand state :contestant "Paper Wall" "HQ")
(let [paper (get-character state :hq 1)]
(core/reveal state :contestant paper)
(is (= 6 (:current-strength (refresh curt))) "Curtain Wall back to default 6 strength")))))
(deftest free-lunch
;; Free Lunch - Spend 1 power counter to make Challenger lose 1c
(do-game
(new-game (default-contestant ["Free Lunch"])
(default-challenger))
(play-from-hand state :contestant "Free Lunch" "HQ")
(let [fl (get-character state :hq 0)]
(core/reveal state :contestant fl)
(card-subroutine state :contestant fl 0)
(is (= 1 (get-counters (refresh fl) :power)) "Free Lunch has 1 power counter")
(card-subroutine state :contestant fl 0)
(is (= 2 (get-counters (refresh fl) :power)) "Free Lunch has 2 power counters")
(is (= 5 (:credit (get-challenger))))
(card-ability state :contestant (refresh fl) 0)
(is (= 1 (get-counters (refresh fl) :power)) "Free Lunch has 1 power counter")
(is (= 4 (:credit (get-challenger))) "Challenger lost 1 credit"))))
(deftest iq
;; IQ - Reveal cost and strength equal to cards in HQ
(do-game
(new-game (default-contestant [(qty "IQ" 3) (qty "Hedge Fund" 3)])
(default-challenger))
(play-from-hand state :contestant "Hedge Fund")
(play-from-hand state :contestant "IQ" "R&D")
(let [iq1 (get-character state :rd 0)]
(core/reveal state :contestant iq1)
(is (and (= 4 (count (:hand (get-contestant))))
(= 4 (:current-strength (refresh iq1)))
(= 5 (:credit (get-contestant)))) "4 cards in HQ: paid 4 to reveal, has 4 strength")
(play-from-hand state :contestant "IQ" "HQ")
(let [iq2 (get-character state :hq 0)]
(core/reveal state :contestant iq2)
(is (and (= 3 (count (:hand (get-contestant))))
(= 3 (:current-strength (refresh iq1)))
(= 3 (:current-strength (refresh iq2)))
(= 2 (:credit (get-contestant)))) "3 cards in HQ: paid 3 to reveal, both have 3 strength")))))
(deftest meru-mati
(do-game
(new-game (default-contestant [(qty "PI:NAME:<NAME>END_PI" 2)])
(default-challenger))
(play-from-hand state :contestant "PI:NAME:<NAME>END_PI" "HQ")
(play-from-hand state :contestant "PI:NAME:<NAME>END_PI" "R&D")
(core/reveal state :contestant (get-character state :hq 0))
(core/reveal state :contestant (get-character state :rd 0))
(is (= 4 (:current-strength (get-character state :hq 0))) "HQ PI:NAME:<NAME>END_PIi at 4 strength")
(is (= 1 (:current-strength (get-character state :rd 0))) "R&D at 0 strength")))
(deftest mother-goddess
;; Mother Goddess - Gains other character subtypes
(do-game
(new-game (default-contestant ["Mother Goddess" "NEXT Bronze"])
(default-challenger))
(core/gain state :contestant :credit 1)
(play-from-hand state :contestant "Mother Goddess" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(let [mg (get-character state :hq 0)
nb (get-character state :rd 0)]
(core/reveal state :contestant mg)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has Mythic")
(is (not (core/has-subtype? (refresh mg) "Code Gate")) "Mother Goddess does not have Code Gate")
(is (not (core/has-subtype? (refresh mg) "NEXT")) "Mother Goddess does not have NEXT")
(core/reveal state :contestant nb)
(is (core/has-subtype? (refresh mg) "Mythic") "Mother Goddess has Mythic")
(is (core/has-subtype? (refresh mg) "Code Gate") "Mother Goddess has Code Gate")
(is (core/has-subtype? (refresh mg) "NEXT") "Mother Goddess has NEXT"))))
(deftest next-bronze
;; NEXT Bronze - Add 1 strength for every revealed NEXT character
(do-game
(new-game (default-contestant [(qty "NEXT Bronze" 2) "NEXT Silver"])
(default-challenger))
(core/gain state :contestant :credit 2)
(play-from-hand state :contestant "NEXT Bronze" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(play-from-hand state :contestant "NEXT Silver" "Archives")
(let [nb1 (get-character state :hq 0)
nb2 (get-character state :rd 0)
ns1 (get-character state :archives 0)]
(core/reveal state :contestant nb1)
(is (= 1 (:current-strength (refresh nb1)))
"NEXT Bronze at 1 strength: 1 revealed NEXT character")
(core/reveal state :contestant nb2)
(is (= 2 (:current-strength (refresh nb1)))
"NEXT Bronze at 2 strength: 2 revealed NEXT character")
(is (= 2 (:current-strength (refresh nb2)))
"NEXT Bronze at 2 strength: 2 revealed NEXT character")
(core/reveal state :contestant ns1)
(is (= 3 (:current-strength (refresh nb1)))
"NEXT Bronze at 3 strength: 3 revealed NEXT character")
(is (= 3 (:current-strength (refresh nb2)))
"NEXT Bronze at 3 strength: 3 revealed NEXT character"))))
(deftest next-diamond
;; NEXT Diamond - Reveal cost is lowered by 1 for each revealed NEXT character
(testing "Base reveal cost"
(do-game
(new-game (default-contestant ["NEXT Diamond"])
(default-challenger))
(core/gain state :contestant :credit 5)
(is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits")
(play-from-hand state :contestant "NEXT Diamond" "HQ")
(core/reveal state :contestant (get-character state :hq 0))
(is (zero? (:credit (get-contestant))) "Contestant spends 10 credits to reveal")))
(testing "Lowered reveal cost"
(do-game
(new-game (default-contestant ["NEXT Diamond" "NEXT Opal" "NEXT Bronze" "Kakugo"])
(default-challenger))
(core/gain state :contestant :credit 13 :click 1)
(play-from-hand state :contestant "NEXT Diamond" "HQ")
(play-from-hand state :contestant "NEXT Opal" "HQ")
(play-from-hand state :contestant "NEXT Bronze" "R&D")
(play-from-hand state :contestant "Kakugo" "Archives")
(core/reveal state :contestant (get-character state :hq 1))
(core/reveal state :contestant (get-character state :archives 0))
(is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits")
(core/reveal state :contestant (get-character state :hq 0))
(is (zero? (:credit (get-contestant))) "Contestant spends 9 credits to reveal"))))
(deftest seidr-adaptive-barrier
;; Seidr Adaptive Barrier - +1 strength for every character protecting its locale
(do-game
(new-game (default-contestant ["Seidr Adaptive Barrier" (qty "Character Wall" 2)])
(default-challenger))
(core/gain state :contestant :credit 10)
(play-from-hand state :contestant "Seidr Adaptive Barrier" "HQ")
(let [sab (get-character state :hq 0)]
(core/reveal state :contestant sab)
(is (= 3 (:current-strength (refresh sab))) "Seidr gained 1 strength for itself")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 4 (:current-strength (refresh sab))) "+2 strength for 2 pieces of Character")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 5 (:current-strength (refresh sab))) "+3 strength for 3 pieces of Character")
(core/move-card state :contestant {:card (get-character state :hq 1) :locale "Archives"})
(is (= 4 (:current-strength (refresh sab))) "+2 strength for 2 pieces of Character"))))
(deftest surveyor
;; Surveyor character strength
(do-game
(new-game (default-contestant [(qty "Surveyor" 1) (qty "Character Wall" 2)])
(default-challenger))
(core/gain state :contestant :credit 10)
(core/gain state :challenger :credit 10)
(play-from-hand state :contestant "Surveyor" "HQ")
(let [surv (get-character state :hq 0)]
(core/reveal state :contestant surv)
(is (= 2 (:current-strength (refresh surv))) "Surveyor has 2 strength for itself")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 4 (:current-strength (refresh surv))) "Surveyor has 4 strength for 2 pieces of Character")
(play-from-hand state :contestant "Character Wall" "HQ")
(is (= 6 (:current-strength (refresh surv))) "Surveyor has 6 strength for 3 pieces of Character")
(run-on state "HQ")
(card-subroutine state :contestant surv 0)
(is (= 6 (-> (get-contestant) :prompt first :base)) "Trace should be base 6")
(prompt-choice :contestant 0)
(prompt-choice :challenger 5)
(is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from Surveyor Trace 6 with boost 5")
(card-subroutine state :contestant surv 0)
(is (= 6 (-> (get-contestant) :prompt first :base)) "Trace should be base 6")
(prompt-choice :contestant 0)
(prompt-choice :challenger 6)
(is (= 2 (:tag (get-challenger))) "Challenger did not take tags from Surveyor Trace 6 with boost 6")
(core/move-card state :contestant {:card (get-character state :hq 1) :locale "Archives"})
(is (= 4 (:current-strength (refresh surv))) "Surveyor has 4 strength for 2 pieces of Character"))))
(deftest tmi
;; TMI
(testing "Basic test"
(do-game
(new-game (default-contestant ["TMI"])
(default-challenger))
(play-from-hand state :contestant "TMI" "HQ")
(let [tmi (get-character state :hq 0)]
(core/reveal state :contestant tmi)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (:revealed (refresh tmi))))))
(testing "Losing trace hides TMI"
(do-game
(new-game (default-contestant ["TMI"])
(make-deck "Sunny Lebeau: Security Specialist" [(qty "Blackmail" 3)]))
(play-from-hand state :contestant "TMI" "HQ")
(let [tmi (get-character state :hq 0)]
(core/reveal state :contestant tmi)
(prompt-choice :contestant 0)
(prompt-choice :challenger 0)
(is (not (:revealed (refresh tmi))))))))
(deftest turing
;; Turing - Strength boosted when protecting a party locale
(do-game
(new-game (default-contestant [(qty "Turing" 2) "Hedge Fund"])
(default-challenger))
(play-from-hand state :contestant "Hedge Fund")
(play-from-hand state :contestant "Turing" "HQ")
(play-from-hand state :contestant "Turing" "New party")
(let [t1 (get-character state :hq 0)
t2 (get-character state :party1 0)]
(core/reveal state :contestant t1)
(is (= 2 (:current-strength (refresh t1)))
"Turing default 2 strength over a central locale")
(core/reveal state :contestant t2)
(is (= 5 (:current-strength (refresh t2)))
"Turing increased to 5 strength over a party locale"))))
(deftest waiver
;; Waiver - Discard Challenger cards in grip with play/place cost <= trace exceed
(do-game
(new-game (default-contestant ["Waiver"])
(default-challenger ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Ubax" "CalPI:NAME:<NAME>END_PIa"]))
(play-from-hand state :contestant "Waiver" "HQ")
(let [waiv (get-character state :hq 0)]
(core/reveal state :contestant waiv)
(card-subroutine state :contestant waiv 0)
(prompt-choice :contestant 0)
(prompt-choice :challenger 3)
(is (empty? (filter #(= "Ubax" (:title %)) (:discard (get-challenger)))) "Ubax not discarded")
(is (empty? (filter #(= "Caldera" (:title %)) (:discard (get-challenger)))) "Caldera not discarded")
(is (= 2 (count (:discard (get-challenger)))) "2 cards discarded"))))
|
[
{
"context": "efn introduction []\n (println (str \"\n My name is Isla.\n Here are the stories I know:\\n\"))\n\n (write-ou",
"end": 814,
"score": 0.9997782111167908,
"start": 810,
"tag": "NAME",
"value": "Isla"
},
{
"context": "-----\\n\")\n (story-utils/output \"Hello. My name is Isla. It's terribly nice to meet you.\\n\")\n\n (repl)\n\n ",
"end": 1151,
"score": 0.9998031854629517,
"start": 1147,
"tag": "NAME",
"value": "Isla"
}
] | src/isla/cli.clj | maryrosecook/islaclj | 38 | (ns isla.cli
(:use [isla.parser])
(:use [isla.interpreter])
(:require [isla.story-utils :as story-utils])
(:require [isla.library :as library])
(:use [clojure.pprint])
(:import java.io.File)
(:require [clojure.string :as str]))
(declare repl)
(def story-dir "stories/")
(defn run-story [story-name]
(println " -----------------------------------")
(def file-path (str/lower-case (str story-dir story-name ".is")))
;; (pprint (parse (slurp file-path)))
(let [context (interpret (parse (slurp file-path)))]
context))
(defn get-stories []
(.listFiles (File. story-dir)))
(defn write-out-stories []
(doseq [file (get-stories)]
(story-utils/output (str " " (str/capitalize (first (str/split (.getName file) #"\.")))))))
(defn introduction []
(println (str "
My name is Isla.
Here are the stories I know:\n"))
(write-out-stories)
(println (str "
Which story would you like?\n")))
(defn -main [& args]
(def repl-context (ref (library/get-initial-context)))
(println)
(story-utils/output "-------------------------------------------------------\n")
(story-utils/output "Hello. My name is Isla. It's terribly nice to meet you.\n")
(repl)
(flush)) ;; empty return to stop last thing executed from being printed to console
(defn run [code]
(dosync (ref-set repl-context (interpret (parse code) (deref repl-context)))))
(defn repl []
(run (story-utils/take-input))
(repl))
;; (defn -main [& args]
;; (introduction)
;; (run-story (story-utils/take-input))
;; ;; (def first-story (first (str/split (.getName (first (get-stories))) #"\.")))
;; ;; (run-story first-story)
;; (flush)) ;; empty return to stop last thing executed from being printed to console
| 30566 | (ns isla.cli
(:use [isla.parser])
(:use [isla.interpreter])
(:require [isla.story-utils :as story-utils])
(:require [isla.library :as library])
(:use [clojure.pprint])
(:import java.io.File)
(:require [clojure.string :as str]))
(declare repl)
(def story-dir "stories/")
(defn run-story [story-name]
(println " -----------------------------------")
(def file-path (str/lower-case (str story-dir story-name ".is")))
;; (pprint (parse (slurp file-path)))
(let [context (interpret (parse (slurp file-path)))]
context))
(defn get-stories []
(.listFiles (File. story-dir)))
(defn write-out-stories []
(doseq [file (get-stories)]
(story-utils/output (str " " (str/capitalize (first (str/split (.getName file) #"\.")))))))
(defn introduction []
(println (str "
My name is <NAME>.
Here are the stories I know:\n"))
(write-out-stories)
(println (str "
Which story would you like?\n")))
(defn -main [& args]
(def repl-context (ref (library/get-initial-context)))
(println)
(story-utils/output "-------------------------------------------------------\n")
(story-utils/output "Hello. My name is <NAME>. It's terribly nice to meet you.\n")
(repl)
(flush)) ;; empty return to stop last thing executed from being printed to console
(defn run [code]
(dosync (ref-set repl-context (interpret (parse code) (deref repl-context)))))
(defn repl []
(run (story-utils/take-input))
(repl))
;; (defn -main [& args]
;; (introduction)
;; (run-story (story-utils/take-input))
;; ;; (def first-story (first (str/split (.getName (first (get-stories))) #"\.")))
;; ;; (run-story first-story)
;; (flush)) ;; empty return to stop last thing executed from being printed to console
| true | (ns isla.cli
(:use [isla.parser])
(:use [isla.interpreter])
(:require [isla.story-utils :as story-utils])
(:require [isla.library :as library])
(:use [clojure.pprint])
(:import java.io.File)
(:require [clojure.string :as str]))
(declare repl)
(def story-dir "stories/")
(defn run-story [story-name]
(println " -----------------------------------")
(def file-path (str/lower-case (str story-dir story-name ".is")))
;; (pprint (parse (slurp file-path)))
(let [context (interpret (parse (slurp file-path)))]
context))
(defn get-stories []
(.listFiles (File. story-dir)))
(defn write-out-stories []
(doseq [file (get-stories)]
(story-utils/output (str " " (str/capitalize (first (str/split (.getName file) #"\.")))))))
(defn introduction []
(println (str "
My name is PI:NAME:<NAME>END_PI.
Here are the stories I know:\n"))
(write-out-stories)
(println (str "
Which story would you like?\n")))
(defn -main [& args]
(def repl-context (ref (library/get-initial-context)))
(println)
(story-utils/output "-------------------------------------------------------\n")
(story-utils/output "Hello. My name is PI:NAME:<NAME>END_PI. It's terribly nice to meet you.\n")
(repl)
(flush)) ;; empty return to stop last thing executed from being printed to console
(defn run [code]
(dosync (ref-set repl-context (interpret (parse code) (deref repl-context)))))
(defn repl []
(run (story-utils/take-input))
(repl))
;; (defn -main [& args]
;; (introduction)
;; (run-story (story-utils/take-input))
;; ;; (def first-story (first (str/split (.getName (first (get-stories))) #"\.")))
;; ;; (run-story first-story)
;; (flush)) ;; empty return to stop last thing executed from being printed to console
|
[
{
"context": "ument:\n\n ```javascript\n sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 });",
"end": 28037,
"score": 0.6493187546730042,
"start": 28034,
"tag": "NAME",
"value": "Red"
},
{
"context": "\n ```javascript\n sprite.setData({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 });\n ```\n\n ",
"end": 28047,
"score": 0.7725677490234375,
"start": 28042,
"tag": "NAME",
"value": "Stone"
},
{
"context": "r example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerL",
"end": 28615,
"score": 0.9844713807106018,
"start": 28604,
"tag": "KEY",
"value": "PlayerLives"
}
] | src/phzr/game_objects/particles/particle_emitter_manager.cljs | sjcasey21/phzr | 1 | (ns phzr.game-objects.particles.particle-emitter-manager
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [update]))
(defn ->ParticleEmitterManager
" Parameters:
* scene (Phaser.Scene) - The Scene to which this Emitter Manager belongs.
* texture (string) - The key of the Texture this Emitter Manager will use to render particles, as stored in the Texture Manager.
* frame (string | integer) {optional} - An optional frame from the Texture this Emitter Manager will use to render particles.
* emitters (Phaser.Types.GameObjects.Particles.ParticleEmitterConfig | Array.<Phaser.Types.GameObjects.Particles.ParticleEmitterConfig>) {optional} - Configuration settings for one or more emitters to create."
([scene texture]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)))
([scene texture frame]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)
(clj->phaser frame)))
([scene texture frame emitters]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)
(clj->phaser frame)
(clj->phaser emitters))))
(defn add-emitter
"Adds an existing Particle Emitter to this Emitter Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* emitter (Phaser.GameObjects.Particles.ParticleEmitter) - The Particle Emitter to add to this Emitter Manager.
Returns: Phaser.GameObjects.Particles.ParticleEmitter - The Particle Emitter that was added to this Emitter Manager."
([particle-emitter-manager emitter]
(phaser->clj
(.addEmitter particle-emitter-manager
(clj->phaser emitter)))))
(defn add-gravity-well
"Adds an existing Gravity Well object to this Emitter Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* well (Phaser.GameObjects.Particles.GravityWell) - The Gravity Well to add to this Emitter Manager.
Returns: Phaser.GameObjects.Particles.GravityWell - The Gravity Well that was added to this Emitter Manager."
([particle-emitter-manager well]
(phaser->clj
(.addGravityWell particle-emitter-manager
(clj->phaser well)))))
(defn add-listener
"Add a listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.addListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.addListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn clear-mask
"Clears the mask that this Game Object was using.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* destroy-mask (boolean) {optional} - Destroy the mask before clearing it?
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.clearMask particle-emitter-manager)))
([particle-emitter-manager destroy-mask]
(phaser->clj
(.clearMask particle-emitter-manager
(clj->phaser destroy-mask)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.createBitmapMask particle-emitter-manager)))
([particle-emitter-manager renderable]
(phaser->clj
(.createBitmapMask particle-emitter-manager
(clj->phaser renderable)))))
(defn create-emitter
"Creates a new Particle Emitter object, adds it to this Emitter Manager and returns a reference to it.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* config (Phaser.Types.GameObjects.Particles.ParticleEmitterConfig) - Configuration settings for the Particle Emitter to create.
Returns: Phaser.GameObjects.Particles.ParticleEmitter - The Particle Emitter that was created."
([particle-emitter-manager config]
(phaser->clj
(.createEmitter particle-emitter-manager
(clj->phaser config)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.createGeometryMask particle-emitter-manager)))
([particle-emitter-manager graphics]
(phaser->clj
(.createGeometryMask particle-emitter-manager
(clj->phaser graphics)))))
(defn create-gravity-well
"Creates a new Gravity Well, adds it to this Emitter Manager and returns a reference to it.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* config (Phaser.Types.GameObjects.Particles.GravityWellConfig) - Configuration settings for the Gravity Well to create.
Returns: Phaser.GameObjects.Particles.GravityWell - The Gravity Well that was created."
([particle-emitter-manager config]
(phaser->clj
(.createGravityWell particle-emitter-manager
(clj->phaser config)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?"
([particle-emitter-manager]
(phaser->clj
(.destroy particle-emitter-manager)))
([particle-emitter-manager from-scene]
(phaser->clj
(.destroy particle-emitter-manager
(clj->phaser from-scene)))))
(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."
([particle-emitter-manager]
(phaser->clj
(.disableInteractive particle-emitter-manager))))
(defn emit
"Calls each of the listeners registered for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.emit particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event args]
(phaser->clj
(.emit particle-emitter-manager
(clj->phaser event)
(clj->phaser args)))))
(defn emit-particle
"Emits particles from each active emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* count (integer) {optional} - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}.
* x (number) {optional} - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location.
* y (number) {optional} - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.emitParticle particle-emitter-manager)))
([particle-emitter-manager count]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count))))
([particle-emitter-manager count x]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count)
(clj->phaser x))))
([particle-emitter-manager count x y]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count)
(clj->phaser x)
(clj->phaser y)))))
(defn emit-particle-at
"Emits particles from each active emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* x (number) {optional} - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location.
* y (number) {optional} - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location.
* count (integer) {optional} - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.emitParticleAt particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y count]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser count)))))
(defn event-names
"Return an array listing the events for which the emitter has registered listeners.
Returns: array - "
([particle-emitter-manager]
(phaser->clj
(.eventNames particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager key]
(phaser->clj
(.getData particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.getIndexList particle-emitter-manager))))
(defn get-local-transform-matrix
"Gets the local transform matrix for this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.getLocalTransformMatrix particle-emitter-manager)))
([particle-emitter-manager temp-matrix]
(phaser->clj
(.getLocalTransformMatrix particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.getParentRotation particle-emitter-manager))))
(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."
([particle-emitter-manager]
(phaser->clj
(.getPipelineName particle-emitter-manager))))
(defn get-processors
"Gets all active particle processors (gravity wells).
Returns: Array.<Phaser.GameObjects.Particles.GravityWell> - - The active gravity wells."
([particle-emitter-manager]
(phaser->clj
(.getProcessors particle-emitter-manager))))
(defn get-world-transform-matrix
"Gets the world transform matrix for this Game Object, factoring in any parent Containers.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager)))
([particle-emitter-manager temp-matrix]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager
(clj->phaser temp-matrix))))
([particle-emitter-manager temp-matrix parent-matrix]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager]
(phaser->clj
(.initPipeline particle-emitter-manager)))
([particle-emitter-manager pipeline-name]
(phaser->clj
(.initPipeline particle-emitter-manager
(clj->phaser pipeline-name)))))
(defn listener-count
"Return the number of listeners listening to a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: number - The number of listeners."
([particle-emitter-manager event]
(phaser->clj
(.listenerCount particle-emitter-manager
(clj->phaser event)))))
(defn listeners
"Return the listeners registered for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: array - The registered listeners."
([particle-emitter-manager event]
(phaser->clj
(.listeners particle-emitter-manager
(clj->phaser event)))))
(defn off
"Remove the listeners of a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event fn]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([particle-emitter-manager event fn context once]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn on
"Add a listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.on particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.on particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn once
"Add a one-time listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.once particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.once particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn pause
"Pauses this Emitter Manager.
This has the effect of pausing all emitters, and all particles of those emitters, currently under its control.
The particles will still render, but they will not have any of their logic updated.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.pause particle-emitter-manager))))
(defn pre-update
"Updates all active emitters.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* time (integer) - The current timestamp as generated by the Request Animation Frame or SetTimeout.
* delta (number) - The delta time, in ms, elapsed since the last frame."
([particle-emitter-manager time delta]
(phaser->clj
(.preUpdate particle-emitter-manager
(clj->phaser time)
(clj->phaser delta)))))
(defn remove-all-listeners
"Remove all listeners, or those of the specified event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) {optional} - The event name.
Returns: Phaser.Events.EventEmitter - `this`."
([particle-emitter-manager]
(phaser->clj
(.removeAllListeners particle-emitter-manager)))
([particle-emitter-manager event]
(phaser->clj
(.removeAllListeners particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.removeInteractive particle-emitter-manager))))
(defn remove-listener
"Remove the listeners of a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event fn]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([particle-emitter-manager event fn context once]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(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`."
([particle-emitter-manager]
(phaser->clj
(.resetPipeline particle-emitter-manager))))
(defn resume
"Resumes this Emitter Manager, should it have been previously paused.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.resume particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (boolean) - True if this Game Object should be set as active, false if not.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setActive particle-emitter-manager
(clj->phaser value)))))
(defn set-angle
"Sets the angle of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* degrees (number) {optional} - The rotation of this Game Object, in degrees.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setAngle particle-emitter-manager)))
([particle-emitter-manager degrees]
(phaser->clj
(.setAngle particle-emitter-manager
(clj->phaser degrees)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager key]
(phaser->clj
(.setData particle-emitter-manager
(clj->phaser key))))
([particle-emitter-manager key data]
(phaser->clj
(.setData particle-emitter-manager
(clj->phaser key)
(clj->phaser data)))))
(defn set-data-enabled
"Adds a Data Manager component to this Game Object.
Returns: this - This GameObject."
([particle-emitter-manager]
(phaser->clj
(.setDataEnabled particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (integer) - The depth of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager value]
(phaser->clj
(.setDepth particle-emitter-manager
(clj->phaser value)))))
(defn set-emitter-frames
"Assigns texture frames to an emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* frames (Phaser.Textures.Frame | Array.<Phaser.Textures.Frame>) - The texture frames.
* emitter (Phaser.GameObjects.Particles.ParticleEmitter) - The particle emitter to modify.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager frames emitter]
(phaser->clj
(.setEmitterFrames particle-emitter-manager
(clj->phaser frames)
(clj->phaser emitter)))))
(defn set-frame
"Sets the frame this Emitter Manager 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.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* frame (string | integer) {optional} - The name or index of the frame within the Texture.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.setFrame particle-emitter-manager)))
([particle-emitter-manager frame]
(phaser->clj
(.setFrame particle-emitter-manager
(clj->phaser frame)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setInteractive particle-emitter-manager)))
([particle-emitter-manager shape]
(phaser->clj
(.setInteractive particle-emitter-manager
(clj->phaser shape))))
([particle-emitter-manager shape callback]
(phaser->clj
(.setInteractive particle-emitter-manager
(clj->phaser shape)
(clj->phaser callback))))
([particle-emitter-manager shape callback drop-zone]
(phaser->clj
(.setInteractive particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager mask]
(phaser->clj
(.setMask particle-emitter-manager
(clj->phaser mask)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (string) - The name to be given to this Game Object.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setName particle-emitter-manager
(clj->phaser value)))))
(defn set-pipeline
"Sets the active WebGL Pipeline of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* pipeline-name (string) - The name of the pipeline to set on this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager pipeline-name]
(phaser->clj
(.setPipeline particle-emitter-manager
(clj->phaser pipeline-name)))))
(defn set-position
"Sets the position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setPosition particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y z]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser z))))
([particle-emitter-manager x y z w]
(phaser->clj
(.setPosition particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setRandomPosition particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y width]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([particle-emitter-manager x y width height]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-rotation
"Sets the rotation of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* radians (number) {optional} - The rotation of this Game Object, in radians.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setRotation particle-emitter-manager)))
([particle-emitter-manager radians]
(phaser->clj
(.setRotation particle-emitter-manager
(clj->phaser radians)))))
(defn set-scale
"Sets the scale of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager x]
(phaser->clj
(.setScale particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setScale particle-emitter-manager
(clj->phaser x)
(clj->phaser y)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (integer | string) - The state of the Game Object.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setState particle-emitter-manager
(clj->phaser value)))))
(defn set-texture
"Sets the texture and frame this Emitter Manager will use to render with.
Textures are referenced by their string-based keys, as stored in the Texture Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager key]
(phaser->clj
(.setTexture particle-emitter-manager
(clj->phaser key))))
([particle-emitter-manager key frame]
(phaser->clj
(.setTexture particle-emitter-manager
(clj->phaser key)
(clj->phaser frame)))))
(defn set-visible
"Sets the visibility of this Game Object.
An invisible Game Object will skip rendering, but will still process update logic.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (boolean) - The visible state of the Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager value]
(phaser->clj
(.setVisible particle-emitter-manager
(clj->phaser value)))))
(defn set-w
"Sets the w position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setW particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setW particle-emitter-manager
(clj->phaser value)))))
(defn set-x
"Sets the x position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The x position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setX particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setX particle-emitter-manager
(clj->phaser value)))))
(defn set-y
"Sets the y position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The y position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setY particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setY particle-emitter-manager
(clj->phaser value)))))
(defn set-z
"Sets the z position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The z position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setZ particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setZ particle-emitter-manager
(clj->phaser value)))))
(defn shutdown
"Removes all listeners."
([particle-emitter-manager]
(phaser->clj
(.shutdown particle-emitter-manager))))
(defn to-json
"Returns a JSON representation of the Game Object.
Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object."
([particle-emitter-manager]
(phaser->clj
(.toJSON particle-emitter-manager))))
(defn update
"To be overridden by custom GameObjects. Allows base objects to be used in a Pool.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* args (*) {optional} - args"
([particle-emitter-manager]
(phaser->clj
(.update particle-emitter-manager)))
([particle-emitter-manager args]
(phaser->clj
(.update particle-emitter-manager
(clj->phaser args)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager camera]
(phaser->clj
(.willRender particle-emitter-manager
(clj->phaser camera))))) | 60609 | (ns phzr.game-objects.particles.particle-emitter-manager
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [update]))
(defn ->ParticleEmitterManager
" Parameters:
* scene (Phaser.Scene) - The Scene to which this Emitter Manager belongs.
* texture (string) - The key of the Texture this Emitter Manager will use to render particles, as stored in the Texture Manager.
* frame (string | integer) {optional} - An optional frame from the Texture this Emitter Manager will use to render particles.
* emitters (Phaser.Types.GameObjects.Particles.ParticleEmitterConfig | Array.<Phaser.Types.GameObjects.Particles.ParticleEmitterConfig>) {optional} - Configuration settings for one or more emitters to create."
([scene texture]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)))
([scene texture frame]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)
(clj->phaser frame)))
([scene texture frame emitters]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)
(clj->phaser frame)
(clj->phaser emitters))))
(defn add-emitter
"Adds an existing Particle Emitter to this Emitter Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* emitter (Phaser.GameObjects.Particles.ParticleEmitter) - The Particle Emitter to add to this Emitter Manager.
Returns: Phaser.GameObjects.Particles.ParticleEmitter - The Particle Emitter that was added to this Emitter Manager."
([particle-emitter-manager emitter]
(phaser->clj
(.addEmitter particle-emitter-manager
(clj->phaser emitter)))))
(defn add-gravity-well
"Adds an existing Gravity Well object to this Emitter Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* well (Phaser.GameObjects.Particles.GravityWell) - The Gravity Well to add to this Emitter Manager.
Returns: Phaser.GameObjects.Particles.GravityWell - The Gravity Well that was added to this Emitter Manager."
([particle-emitter-manager well]
(phaser->clj
(.addGravityWell particle-emitter-manager
(clj->phaser well)))))
(defn add-listener
"Add a listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.addListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.addListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn clear-mask
"Clears the mask that this Game Object was using.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* destroy-mask (boolean) {optional} - Destroy the mask before clearing it?
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.clearMask particle-emitter-manager)))
([particle-emitter-manager destroy-mask]
(phaser->clj
(.clearMask particle-emitter-manager
(clj->phaser destroy-mask)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.createBitmapMask particle-emitter-manager)))
([particle-emitter-manager renderable]
(phaser->clj
(.createBitmapMask particle-emitter-manager
(clj->phaser renderable)))))
(defn create-emitter
"Creates a new Particle Emitter object, adds it to this Emitter Manager and returns a reference to it.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* config (Phaser.Types.GameObjects.Particles.ParticleEmitterConfig) - Configuration settings for the Particle Emitter to create.
Returns: Phaser.GameObjects.Particles.ParticleEmitter - The Particle Emitter that was created."
([particle-emitter-manager config]
(phaser->clj
(.createEmitter particle-emitter-manager
(clj->phaser config)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.createGeometryMask particle-emitter-manager)))
([particle-emitter-manager graphics]
(phaser->clj
(.createGeometryMask particle-emitter-manager
(clj->phaser graphics)))))
(defn create-gravity-well
"Creates a new Gravity Well, adds it to this Emitter Manager and returns a reference to it.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* config (Phaser.Types.GameObjects.Particles.GravityWellConfig) - Configuration settings for the Gravity Well to create.
Returns: Phaser.GameObjects.Particles.GravityWell - The Gravity Well that was created."
([particle-emitter-manager config]
(phaser->clj
(.createGravityWell particle-emitter-manager
(clj->phaser config)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?"
([particle-emitter-manager]
(phaser->clj
(.destroy particle-emitter-manager)))
([particle-emitter-manager from-scene]
(phaser->clj
(.destroy particle-emitter-manager
(clj->phaser from-scene)))))
(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."
([particle-emitter-manager]
(phaser->clj
(.disableInteractive particle-emitter-manager))))
(defn emit
"Calls each of the listeners registered for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.emit particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event args]
(phaser->clj
(.emit particle-emitter-manager
(clj->phaser event)
(clj->phaser args)))))
(defn emit-particle
"Emits particles from each active emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* count (integer) {optional} - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}.
* x (number) {optional} - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location.
* y (number) {optional} - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.emitParticle particle-emitter-manager)))
([particle-emitter-manager count]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count))))
([particle-emitter-manager count x]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count)
(clj->phaser x))))
([particle-emitter-manager count x y]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count)
(clj->phaser x)
(clj->phaser y)))))
(defn emit-particle-at
"Emits particles from each active emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* x (number) {optional} - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location.
* y (number) {optional} - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location.
* count (integer) {optional} - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.emitParticleAt particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y count]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser count)))))
(defn event-names
"Return an array listing the events for which the emitter has registered listeners.
Returns: array - "
([particle-emitter-manager]
(phaser->clj
(.eventNames particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager key]
(phaser->clj
(.getData particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.getIndexList particle-emitter-manager))))
(defn get-local-transform-matrix
"Gets the local transform matrix for this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.getLocalTransformMatrix particle-emitter-manager)))
([particle-emitter-manager temp-matrix]
(phaser->clj
(.getLocalTransformMatrix particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.getParentRotation particle-emitter-manager))))
(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."
([particle-emitter-manager]
(phaser->clj
(.getPipelineName particle-emitter-manager))))
(defn get-processors
"Gets all active particle processors (gravity wells).
Returns: Array.<Phaser.GameObjects.Particles.GravityWell> - - The active gravity wells."
([particle-emitter-manager]
(phaser->clj
(.getProcessors particle-emitter-manager))))
(defn get-world-transform-matrix
"Gets the world transform matrix for this Game Object, factoring in any parent Containers.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager)))
([particle-emitter-manager temp-matrix]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager
(clj->phaser temp-matrix))))
([particle-emitter-manager temp-matrix parent-matrix]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager]
(phaser->clj
(.initPipeline particle-emitter-manager)))
([particle-emitter-manager pipeline-name]
(phaser->clj
(.initPipeline particle-emitter-manager
(clj->phaser pipeline-name)))))
(defn listener-count
"Return the number of listeners listening to a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: number - The number of listeners."
([particle-emitter-manager event]
(phaser->clj
(.listenerCount particle-emitter-manager
(clj->phaser event)))))
(defn listeners
"Return the listeners registered for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: array - The registered listeners."
([particle-emitter-manager event]
(phaser->clj
(.listeners particle-emitter-manager
(clj->phaser event)))))
(defn off
"Remove the listeners of a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event fn]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([particle-emitter-manager event fn context once]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn on
"Add a listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.on particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.on particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn once
"Add a one-time listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.once particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.once particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn pause
"Pauses this Emitter Manager.
This has the effect of pausing all emitters, and all particles of those emitters, currently under its control.
The particles will still render, but they will not have any of their logic updated.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.pause particle-emitter-manager))))
(defn pre-update
"Updates all active emitters.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* time (integer) - The current timestamp as generated by the Request Animation Frame or SetTimeout.
* delta (number) - The delta time, in ms, elapsed since the last frame."
([particle-emitter-manager time delta]
(phaser->clj
(.preUpdate particle-emitter-manager
(clj->phaser time)
(clj->phaser delta)))))
(defn remove-all-listeners
"Remove all listeners, or those of the specified event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) {optional} - The event name.
Returns: Phaser.Events.EventEmitter - `this`."
([particle-emitter-manager]
(phaser->clj
(.removeAllListeners particle-emitter-manager)))
([particle-emitter-manager event]
(phaser->clj
(.removeAllListeners particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.removeInteractive particle-emitter-manager))))
(defn remove-listener
"Remove the listeners of a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event fn]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([particle-emitter-manager event fn context once]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(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`."
([particle-emitter-manager]
(phaser->clj
(.resetPipeline particle-emitter-manager))))
(defn resume
"Resumes this Emitter Manager, should it have been previously paused.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.resume particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (boolean) - True if this Game Object should be set as active, false if not.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setActive particle-emitter-manager
(clj->phaser value)))))
(defn set-angle
"Sets the angle of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* degrees (number) {optional} - The rotation of this Game Object, in degrees.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setAngle particle-emitter-manager)))
([particle-emitter-manager degrees]
(phaser->clj
(.setAngle particle-emitter-manager
(clj->phaser degrees)))))
(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: '<NAME> Gem <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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager key]
(phaser->clj
(.setData particle-emitter-manager
(clj->phaser key))))
([particle-emitter-manager key data]
(phaser->clj
(.setData particle-emitter-manager
(clj->phaser key)
(clj->phaser data)))))
(defn set-data-enabled
"Adds a Data Manager component to this Game Object.
Returns: this - This GameObject."
([particle-emitter-manager]
(phaser->clj
(.setDataEnabled particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (integer) - The depth of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager value]
(phaser->clj
(.setDepth particle-emitter-manager
(clj->phaser value)))))
(defn set-emitter-frames
"Assigns texture frames to an emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* frames (Phaser.Textures.Frame | Array.<Phaser.Textures.Frame>) - The texture frames.
* emitter (Phaser.GameObjects.Particles.ParticleEmitter) - The particle emitter to modify.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager frames emitter]
(phaser->clj
(.setEmitterFrames particle-emitter-manager
(clj->phaser frames)
(clj->phaser emitter)))))
(defn set-frame
"Sets the frame this Emitter Manager 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.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* frame (string | integer) {optional} - The name or index of the frame within the Texture.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.setFrame particle-emitter-manager)))
([particle-emitter-manager frame]
(phaser->clj
(.setFrame particle-emitter-manager
(clj->phaser frame)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setInteractive particle-emitter-manager)))
([particle-emitter-manager shape]
(phaser->clj
(.setInteractive particle-emitter-manager
(clj->phaser shape))))
([particle-emitter-manager shape callback]
(phaser->clj
(.setInteractive particle-emitter-manager
(clj->phaser shape)
(clj->phaser callback))))
([particle-emitter-manager shape callback drop-zone]
(phaser->clj
(.setInteractive particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager mask]
(phaser->clj
(.setMask particle-emitter-manager
(clj->phaser mask)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (string) - The name to be given to this Game Object.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setName particle-emitter-manager
(clj->phaser value)))))
(defn set-pipeline
"Sets the active WebGL Pipeline of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* pipeline-name (string) - The name of the pipeline to set on this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager pipeline-name]
(phaser->clj
(.setPipeline particle-emitter-manager
(clj->phaser pipeline-name)))))
(defn set-position
"Sets the position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setPosition particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y z]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser z))))
([particle-emitter-manager x y z w]
(phaser->clj
(.setPosition particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setRandomPosition particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y width]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([particle-emitter-manager x y width height]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-rotation
"Sets the rotation of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* radians (number) {optional} - The rotation of this Game Object, in radians.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setRotation particle-emitter-manager)))
([particle-emitter-manager radians]
(phaser->clj
(.setRotation particle-emitter-manager
(clj->phaser radians)))))
(defn set-scale
"Sets the scale of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager x]
(phaser->clj
(.setScale particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setScale particle-emitter-manager
(clj->phaser x)
(clj->phaser y)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (integer | string) - The state of the Game Object.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setState particle-emitter-manager
(clj->phaser value)))))
(defn set-texture
"Sets the texture and frame this Emitter Manager will use to render with.
Textures are referenced by their string-based keys, as stored in the Texture Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager key]
(phaser->clj
(.setTexture particle-emitter-manager
(clj->phaser key))))
([particle-emitter-manager key frame]
(phaser->clj
(.setTexture particle-emitter-manager
(clj->phaser key)
(clj->phaser frame)))))
(defn set-visible
"Sets the visibility of this Game Object.
An invisible Game Object will skip rendering, but will still process update logic.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (boolean) - The visible state of the Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager value]
(phaser->clj
(.setVisible particle-emitter-manager
(clj->phaser value)))))
(defn set-w
"Sets the w position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setW particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setW particle-emitter-manager
(clj->phaser value)))))
(defn set-x
"Sets the x position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The x position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setX particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setX particle-emitter-manager
(clj->phaser value)))))
(defn set-y
"Sets the y position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The y position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setY particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setY particle-emitter-manager
(clj->phaser value)))))
(defn set-z
"Sets the z position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The z position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setZ particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setZ particle-emitter-manager
(clj->phaser value)))))
(defn shutdown
"Removes all listeners."
([particle-emitter-manager]
(phaser->clj
(.shutdown particle-emitter-manager))))
(defn to-json
"Returns a JSON representation of the Game Object.
Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object."
([particle-emitter-manager]
(phaser->clj
(.toJSON particle-emitter-manager))))
(defn update
"To be overridden by custom GameObjects. Allows base objects to be used in a Pool.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* args (*) {optional} - args"
([particle-emitter-manager]
(phaser->clj
(.update particle-emitter-manager)))
([particle-emitter-manager args]
(phaser->clj
(.update particle-emitter-manager
(clj->phaser args)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager camera]
(phaser->clj
(.willRender particle-emitter-manager
(clj->phaser camera))))) | true | (ns phzr.game-objects.particles.particle-emitter-manager
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [update]))
(defn ->ParticleEmitterManager
" Parameters:
* scene (Phaser.Scene) - The Scene to which this Emitter Manager belongs.
* texture (string) - The key of the Texture this Emitter Manager will use to render particles, as stored in the Texture Manager.
* frame (string | integer) {optional} - An optional frame from the Texture this Emitter Manager will use to render particles.
* emitters (Phaser.Types.GameObjects.Particles.ParticleEmitterConfig | Array.<Phaser.Types.GameObjects.Particles.ParticleEmitterConfig>) {optional} - Configuration settings for one or more emitters to create."
([scene texture]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)))
([scene texture frame]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)
(clj->phaser frame)))
([scene texture frame emitters]
(js/Phaser.GameObjects.Particles.ParticleEmitterManager. (clj->phaser scene)
(clj->phaser texture)
(clj->phaser frame)
(clj->phaser emitters))))
(defn add-emitter
"Adds an existing Particle Emitter to this Emitter Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* emitter (Phaser.GameObjects.Particles.ParticleEmitter) - The Particle Emitter to add to this Emitter Manager.
Returns: Phaser.GameObjects.Particles.ParticleEmitter - The Particle Emitter that was added to this Emitter Manager."
([particle-emitter-manager emitter]
(phaser->clj
(.addEmitter particle-emitter-manager
(clj->phaser emitter)))))
(defn add-gravity-well
"Adds an existing Gravity Well object to this Emitter Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* well (Phaser.GameObjects.Particles.GravityWell) - The Gravity Well to add to this Emitter Manager.
Returns: Phaser.GameObjects.Particles.GravityWell - The Gravity Well that was added to this Emitter Manager."
([particle-emitter-manager well]
(phaser->clj
(.addGravityWell particle-emitter-manager
(clj->phaser well)))))
(defn add-listener
"Add a listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.addListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.addListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn clear-mask
"Clears the mask that this Game Object was using.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* destroy-mask (boolean) {optional} - Destroy the mask before clearing it?
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.clearMask particle-emitter-manager)))
([particle-emitter-manager destroy-mask]
(phaser->clj
(.clearMask particle-emitter-manager
(clj->phaser destroy-mask)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.createBitmapMask particle-emitter-manager)))
([particle-emitter-manager renderable]
(phaser->clj
(.createBitmapMask particle-emitter-manager
(clj->phaser renderable)))))
(defn create-emitter
"Creates a new Particle Emitter object, adds it to this Emitter Manager and returns a reference to it.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* config (Phaser.Types.GameObjects.Particles.ParticleEmitterConfig) - Configuration settings for the Particle Emitter to create.
Returns: Phaser.GameObjects.Particles.ParticleEmitter - The Particle Emitter that was created."
([particle-emitter-manager config]
(phaser->clj
(.createEmitter particle-emitter-manager
(clj->phaser config)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.createGeometryMask particle-emitter-manager)))
([particle-emitter-manager graphics]
(phaser->clj
(.createGeometryMask particle-emitter-manager
(clj->phaser graphics)))))
(defn create-gravity-well
"Creates a new Gravity Well, adds it to this Emitter Manager and returns a reference to it.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* config (Phaser.Types.GameObjects.Particles.GravityWellConfig) - Configuration settings for the Gravity Well to create.
Returns: Phaser.GameObjects.Particles.GravityWell - The Gravity Well that was created."
([particle-emitter-manager config]
(phaser->clj
(.createGravityWell particle-emitter-manager
(clj->phaser config)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* from-scene (boolean) {optional} - Is this Game Object being destroyed as the result of a Scene shutdown?"
([particle-emitter-manager]
(phaser->clj
(.destroy particle-emitter-manager)))
([particle-emitter-manager from-scene]
(phaser->clj
(.destroy particle-emitter-manager
(clj->phaser from-scene)))))
(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."
([particle-emitter-manager]
(phaser->clj
(.disableInteractive particle-emitter-manager))))
(defn emit
"Calls each of the listeners registered for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.emit particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event args]
(phaser->clj
(.emit particle-emitter-manager
(clj->phaser event)
(clj->phaser args)))))
(defn emit-particle
"Emits particles from each active emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* count (integer) {optional} - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}.
* x (number) {optional} - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location.
* y (number) {optional} - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.emitParticle particle-emitter-manager)))
([particle-emitter-manager count]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count))))
([particle-emitter-manager count x]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count)
(clj->phaser x))))
([particle-emitter-manager count x y]
(phaser->clj
(.emitParticle particle-emitter-manager
(clj->phaser count)
(clj->phaser x)
(clj->phaser y)))))
(defn emit-particle-at
"Emits particles from each active emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* x (number) {optional} - The x-coordinate to to emit particles from. The default is the x-coordinate of the emitter's current location.
* y (number) {optional} - The y-coordinate to to emit particles from. The default is the y-coordinate of the emitter's current location.
* count (integer) {optional} - The number of particles to release from each emitter. The default is the emitter's own {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.emitParticleAt particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y count]
(phaser->clj
(.emitParticleAt particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser count)))))
(defn event-names
"Return an array listing the events for which the emitter has registered listeners.
Returns: array - "
([particle-emitter-manager]
(phaser->clj
(.eventNames particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager key]
(phaser->clj
(.getData particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.getIndexList particle-emitter-manager))))
(defn get-local-transform-matrix
"Gets the local transform matrix for this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.getLocalTransformMatrix particle-emitter-manager)))
([particle-emitter-manager temp-matrix]
(phaser->clj
(.getLocalTransformMatrix particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.getParentRotation particle-emitter-manager))))
(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."
([particle-emitter-manager]
(phaser->clj
(.getPipelineName particle-emitter-manager))))
(defn get-processors
"Gets all active particle processors (gravity wells).
Returns: Array.<Phaser.GameObjects.Particles.GravityWell> - - The active gravity wells."
([particle-emitter-manager]
(phaser->clj
(.getProcessors particle-emitter-manager))))
(defn get-world-transform-matrix
"Gets the world transform matrix for this Game Object, factoring in any parent Containers.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager)))
([particle-emitter-manager temp-matrix]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager
(clj->phaser temp-matrix))))
([particle-emitter-manager temp-matrix parent-matrix]
(phaser->clj
(.getWorldTransformMatrix particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager]
(phaser->clj
(.initPipeline particle-emitter-manager)))
([particle-emitter-manager pipeline-name]
(phaser->clj
(.initPipeline particle-emitter-manager
(clj->phaser pipeline-name)))))
(defn listener-count
"Return the number of listeners listening to a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: number - The number of listeners."
([particle-emitter-manager event]
(phaser->clj
(.listenerCount particle-emitter-manager
(clj->phaser event)))))
(defn listeners
"Return the listeners registered for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) - The event name.
Returns: array - The registered listeners."
([particle-emitter-manager event]
(phaser->clj
(.listeners particle-emitter-manager
(clj->phaser event)))))
(defn off
"Remove the listeners of a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event fn]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([particle-emitter-manager event fn context once]
(phaser->clj
(.off particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(defn on
"Add a listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.on particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.on particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn once
"Add a one-time listener for a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event fn]
(phaser->clj
(.once particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.once particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)))))
(defn pause
"Pauses this Emitter Manager.
This has the effect of pausing all emitters, and all particles of those emitters, currently under its control.
The particles will still render, but they will not have any of their logic updated.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.pause particle-emitter-manager))))
(defn pre-update
"Updates all active emitters.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* time (integer) - The current timestamp as generated by the Request Animation Frame or SetTimeout.
* delta (number) - The delta time, in ms, elapsed since the last frame."
([particle-emitter-manager time delta]
(phaser->clj
(.preUpdate particle-emitter-manager
(clj->phaser time)
(clj->phaser delta)))))
(defn remove-all-listeners
"Remove all listeners, or those of the specified event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* event (string | symbol) {optional} - The event name.
Returns: Phaser.Events.EventEmitter - `this`."
([particle-emitter-manager]
(phaser->clj
(.removeAllListeners particle-emitter-manager)))
([particle-emitter-manager event]
(phaser->clj
(.removeAllListeners particle-emitter-manager
(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."
([particle-emitter-manager]
(phaser->clj
(.removeInteractive particle-emitter-manager))))
(defn remove-listener
"Remove the listeners of a given event.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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`."
([particle-emitter-manager event]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event))))
([particle-emitter-manager event fn]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn))))
([particle-emitter-manager event fn context]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context))))
([particle-emitter-manager event fn context once]
(phaser->clj
(.removeListener particle-emitter-manager
(clj->phaser event)
(clj->phaser fn)
(clj->phaser context)
(clj->phaser once)))))
(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`."
([particle-emitter-manager]
(phaser->clj
(.resetPipeline particle-emitter-manager))))
(defn resume
"Resumes this Emitter Manager, should it have been previously paused.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.resume particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (boolean) - True if this Game Object should be set as active, false if not.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setActive particle-emitter-manager
(clj->phaser value)))))
(defn set-angle
"Sets the angle of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* degrees (number) {optional} - The rotation of this Game Object, in degrees.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setAngle particle-emitter-manager)))
([particle-emitter-manager degrees]
(phaser->clj
(.setAngle particle-emitter-manager
(clj->phaser degrees)))))
(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: 'PI:NAME:<NAME>END_PI Gem 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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager key]
(phaser->clj
(.setData particle-emitter-manager
(clj->phaser key))))
([particle-emitter-manager key data]
(phaser->clj
(.setData particle-emitter-manager
(clj->phaser key)
(clj->phaser data)))))
(defn set-data-enabled
"Adds a Data Manager component to this Game Object.
Returns: this - This GameObject."
([particle-emitter-manager]
(phaser->clj
(.setDataEnabled particle-emitter-manager))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (integer) - The depth of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager value]
(phaser->clj
(.setDepth particle-emitter-manager
(clj->phaser value)))))
(defn set-emitter-frames
"Assigns texture frames to an emitter.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* frames (Phaser.Textures.Frame | Array.<Phaser.Textures.Frame>) - The texture frames.
* emitter (Phaser.GameObjects.Particles.ParticleEmitter) - The particle emitter to modify.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager frames emitter]
(phaser->clj
(.setEmitterFrames particle-emitter-manager
(clj->phaser frames)
(clj->phaser emitter)))))
(defn set-frame
"Sets the frame this Emitter Manager 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.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* frame (string | integer) {optional} - The name or index of the frame within the Texture.
Returns: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager]
(phaser->clj
(.setFrame particle-emitter-manager)))
([particle-emitter-manager frame]
(phaser->clj
(.setFrame particle-emitter-manager
(clj->phaser frame)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setInteractive particle-emitter-manager)))
([particle-emitter-manager shape]
(phaser->clj
(.setInteractive particle-emitter-manager
(clj->phaser shape))))
([particle-emitter-manager shape callback]
(phaser->clj
(.setInteractive particle-emitter-manager
(clj->phaser shape)
(clj->phaser callback))))
([particle-emitter-manager shape callback drop-zone]
(phaser->clj
(.setInteractive particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager mask]
(phaser->clj
(.setMask particle-emitter-manager
(clj->phaser mask)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (string) - The name to be given to this Game Object.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setName particle-emitter-manager
(clj->phaser value)))))
(defn set-pipeline
"Sets the active WebGL Pipeline of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* pipeline-name (string) - The name of the pipeline to set on this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager pipeline-name]
(phaser->clj
(.setPipeline particle-emitter-manager
(clj->phaser pipeline-name)))))
(defn set-position
"Sets the position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setPosition particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y z]
(phaser->clj
(.setPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser z))))
([particle-emitter-manager x y z w]
(phaser->clj
(.setPosition particle-emitter-manager
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager]
(phaser->clj
(.setRandomPosition particle-emitter-manager)))
([particle-emitter-manager x]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y))))
([particle-emitter-manager x y width]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser width))))
([particle-emitter-manager x y width height]
(phaser->clj
(.setRandomPosition particle-emitter-manager
(clj->phaser x)
(clj->phaser y)
(clj->phaser width)
(clj->phaser height)))))
(defn set-rotation
"Sets the rotation of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* radians (number) {optional} - The rotation of this Game Object, in radians.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setRotation particle-emitter-manager)))
([particle-emitter-manager radians]
(phaser->clj
(.setRotation particle-emitter-manager
(clj->phaser radians)))))
(defn set-scale
"Sets the scale of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager x]
(phaser->clj
(.setScale particle-emitter-manager
(clj->phaser x))))
([particle-emitter-manager x y]
(phaser->clj
(.setScale particle-emitter-manager
(clj->phaser x)
(clj->phaser y)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (integer | string) - The state of the Game Object.
Returns: this - This GameObject."
([particle-emitter-manager value]
(phaser->clj
(.setState particle-emitter-manager
(clj->phaser value)))))
(defn set-texture
"Sets the texture and frame this Emitter Manager will use to render with.
Textures are referenced by their string-based keys, as stored in the Texture Manager.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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: Phaser.GameObjects.Particles.ParticleEmitterManager - This Emitter Manager."
([particle-emitter-manager key]
(phaser->clj
(.setTexture particle-emitter-manager
(clj->phaser key))))
([particle-emitter-manager key frame]
(phaser->clj
(.setTexture particle-emitter-manager
(clj->phaser key)
(clj->phaser frame)))))
(defn set-visible
"Sets the visibility of this Game Object.
An invisible Game Object will skip rendering, but will still process update logic.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (boolean) - The visible state of the Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager value]
(phaser->clj
(.setVisible particle-emitter-manager
(clj->phaser value)))))
(defn set-w
"Sets the w position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The w position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setW particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setW particle-emitter-manager
(clj->phaser value)))))
(defn set-x
"Sets the x position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The x position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setX particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setX particle-emitter-manager
(clj->phaser value)))))
(defn set-y
"Sets the y position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The y position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setY particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setY particle-emitter-manager
(clj->phaser value)))))
(defn set-z
"Sets the z position of this Game Object.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* value (number) {optional} - The z position of this Game Object.
Returns: this - This Game Object instance."
([particle-emitter-manager]
(phaser->clj
(.setZ particle-emitter-manager)))
([particle-emitter-manager value]
(phaser->clj
(.setZ particle-emitter-manager
(clj->phaser value)))))
(defn shutdown
"Removes all listeners."
([particle-emitter-manager]
(phaser->clj
(.shutdown particle-emitter-manager))))
(defn to-json
"Returns a JSON representation of the Game Object.
Returns: Phaser.Types.GameObjects.JSONGameObject - A JSON representation of the Game Object."
([particle-emitter-manager]
(phaser->clj
(.toJSON particle-emitter-manager))))
(defn update
"To be overridden by custom GameObjects. Allows base objects to be used in a Pool.
Parameters:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - Targeted instance for method
* args (*) {optional} - args"
([particle-emitter-manager]
(phaser->clj
(.update particle-emitter-manager)))
([particle-emitter-manager args]
(phaser->clj
(.update particle-emitter-manager
(clj->phaser args)))))
(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:
* particle-emitter-manager (Phaser.GameObjects.Particles.ParticleEmitterManager) - 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."
([particle-emitter-manager camera]
(phaser->clj
(.willRender particle-emitter-manager
(clj->phaser camera))))) |
[
{
"context": "Tree\n; Date: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------",
"end": 153,
"score": 0.987040102481842,
"start": 144,
"tag": "USERNAME",
"value": "A01371743"
},
{
"context": "e: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------------------------------------",
"end": 183,
"score": 0.999843955039978,
"start": 154,
"tag": "NAME",
"value": "Luis Eduardo Ballinas Aguilar"
}
] | 4clojure/problem_95.clj | lu15v/TC2006 | 0 | ;----------------------------------------------------------
; Problem 95: To Tree, or not to Tree
; Date: March 17, 2016.
; Authors:
; A01371743 Luis Eduardo Ballinas Aguilar
;----------------------------------------------------------
(use 'clojure.test)
(def problem95
(fn
[t]
(cond
(nil? t) true
(or (not (coll? t)) (not= (count t) 3)) false
(and (= 3 (count t)) (problem95 (nth t 1)) (problem95 (nth t 2))) true
:else false)))
(deftest test-problem95
(is(=(problem95 '(:a (:b nil nil) nil)) true))
(is(=(problem95 '(:a (:b nil nil))) false))
(is(=(problem95 [1 nil [2 [3 nil nil] [4 nil nil]]]) true))
(is(=(problem95 [1 [2 nil nil] [3 nil nil] [4 nil nil]]) false))
(is(=(problem95 [1 [2 [3 [4 nil nil] nil] nil] nil]) true))
(is(=(problem95 [1 [2 [3 [4 false nil] nil] nil] nil]) false))
(is(= (problem95 '(:a nil ())) false)))
(run-tests)
| 103931 | ;----------------------------------------------------------
; Problem 95: To Tree, or not to Tree
; Date: March 17, 2016.
; Authors:
; A01371743 <NAME>
;----------------------------------------------------------
(use 'clojure.test)
(def problem95
(fn
[t]
(cond
(nil? t) true
(or (not (coll? t)) (not= (count t) 3)) false
(and (= 3 (count t)) (problem95 (nth t 1)) (problem95 (nth t 2))) true
:else false)))
(deftest test-problem95
(is(=(problem95 '(:a (:b nil nil) nil)) true))
(is(=(problem95 '(:a (:b nil nil))) false))
(is(=(problem95 [1 nil [2 [3 nil nil] [4 nil nil]]]) true))
(is(=(problem95 [1 [2 nil nil] [3 nil nil] [4 nil nil]]) false))
(is(=(problem95 [1 [2 [3 [4 nil nil] nil] nil] nil]) true))
(is(=(problem95 [1 [2 [3 [4 false nil] nil] nil] nil]) false))
(is(= (problem95 '(:a nil ())) false)))
(run-tests)
| true | ;----------------------------------------------------------
; Problem 95: To Tree, or not to Tree
; Date: March 17, 2016.
; Authors:
; A01371743 PI:NAME:<NAME>END_PI
;----------------------------------------------------------
(use 'clojure.test)
(def problem95
(fn
[t]
(cond
(nil? t) true
(or (not (coll? t)) (not= (count t) 3)) false
(and (= 3 (count t)) (problem95 (nth t 1)) (problem95 (nth t 2))) true
:else false)))
(deftest test-problem95
(is(=(problem95 '(:a (:b nil nil) nil)) true))
(is(=(problem95 '(:a (:b nil nil))) false))
(is(=(problem95 [1 nil [2 [3 nil nil] [4 nil nil]]]) true))
(is(=(problem95 [1 [2 nil nil] [3 nil nil] [4 nil nil]]) false))
(is(=(problem95 [1 [2 [3 [4 nil nil] nil] nil] nil]) true))
(is(=(problem95 [1 [2 [3 [4 false nil] nil] nil] nil]) false))
(is(= (problem95 '(:a nil ())) false)))
(run-tests)
|
[
{
"context": " :user \"patient_role\"\n;; :password \"patient123\"}))\n\n;; NA. NOTE\n;; - does not work? FIX. not fun",
"end": 478,
"score": 0.9994999766349792,
"start": 468,
"tag": "PASSWORD",
"value": "patient123"
},
{
"context": ":user \"patient_role\"\n;; :password \"patient123\"}))\n\n;; NA. NOTE\n;; - https://cljdoc.org/d/com.gi",
"end": 783,
"score": 0.9994968771934509,
"start": 773,
"tag": "PASSWORD",
"value": "patient123"
},
{
"context": " :user \"patient_role\"\n :password \"patient123\"})\n\n(def ds\n (jdbc/get-datasource db))\n\n(defn ge",
"end": 1020,
"score": 0.9994950890541077,
"start": 1010,
"tag": "PASSWORD",
"value": "patient123"
}
] | backend/src/hello_patient/core.clj | nalbarr/hello_patient_clj | 0 | (ns hello-patient.core
(:require
[next.jdbc :as jdbc]
[next.jdbc.sql :as sql]))
;[next.jdbc.result-set :as rs]))
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
;; NA. NOTE
;; - does not work? FIX. not function definition, needed to be local def
;; (defn ds [] (jdbc/get-datasource
;; {:dbtype "postgresql"
;; :dbname "hellopatientdb"
;; :user "patient_role"
;; :password "patient123"}))
;; NA. NOTE
;; - does not work? FIX. not function definition, needed to be local def
;; (defn ds [] (jdbc/get-datasource
;; {:subprotocol "postgresql"
;; :subname "//localhost/hellopatientdb"
;; :user "patient_role"
;; :password "patient123"}))
;; NA. NOTE
;; - https://cljdoc.org/d/com.github.seancorfield/next.jdbc/1.2.772/api/next.jdbc#get-datasource
(def db {:dbtype "postgres"
:dbname "hellopatientdb"
:user "patient_role"
:password "patient123"})
(def ds
(jdbc/get-datasource db))
(defn get-first-user [ds]
(first (sql/query ds ["select * from patient"])))
(defn get-users [ds]
(sql/query ds ["select * from patient"]))
(defn -main
[]
(foo 123)
(print ds)
(get-users ds))
| 17942 | (ns hello-patient.core
(:require
[next.jdbc :as jdbc]
[next.jdbc.sql :as sql]))
;[next.jdbc.result-set :as rs]))
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
;; NA. NOTE
;; - does not work? FIX. not function definition, needed to be local def
;; (defn ds [] (jdbc/get-datasource
;; {:dbtype "postgresql"
;; :dbname "hellopatientdb"
;; :user "patient_role"
;; :password "<PASSWORD>"}))
;; NA. NOTE
;; - does not work? FIX. not function definition, needed to be local def
;; (defn ds [] (jdbc/get-datasource
;; {:subprotocol "postgresql"
;; :subname "//localhost/hellopatientdb"
;; :user "patient_role"
;; :password "<PASSWORD>"}))
;; NA. NOTE
;; - https://cljdoc.org/d/com.github.seancorfield/next.jdbc/1.2.772/api/next.jdbc#get-datasource
(def db {:dbtype "postgres"
:dbname "hellopatientdb"
:user "patient_role"
:password "<PASSWORD>"})
(def ds
(jdbc/get-datasource db))
(defn get-first-user [ds]
(first (sql/query ds ["select * from patient"])))
(defn get-users [ds]
(sql/query ds ["select * from patient"]))
(defn -main
[]
(foo 123)
(print ds)
(get-users ds))
| true | (ns hello-patient.core
(:require
[next.jdbc :as jdbc]
[next.jdbc.sql :as sql]))
;[next.jdbc.result-set :as rs]))
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
;; NA. NOTE
;; - does not work? FIX. not function definition, needed to be local def
;; (defn ds [] (jdbc/get-datasource
;; {:dbtype "postgresql"
;; :dbname "hellopatientdb"
;; :user "patient_role"
;; :password "PI:PASSWORD:<PASSWORD>END_PI"}))
;; NA. NOTE
;; - does not work? FIX. not function definition, needed to be local def
;; (defn ds [] (jdbc/get-datasource
;; {:subprotocol "postgresql"
;; :subname "//localhost/hellopatientdb"
;; :user "patient_role"
;; :password "PI:PASSWORD:<PASSWORD>END_PI"}))
;; NA. NOTE
;; - https://cljdoc.org/d/com.github.seancorfield/next.jdbc/1.2.772/api/next.jdbc#get-datasource
(def db {:dbtype "postgres"
:dbname "hellopatientdb"
:user "patient_role"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(def ds
(jdbc/get-datasource db))
(defn get-first-user [ds]
(first (sql/query ds ["select * from patient"])))
(defn get-users [ds]
(sql/query ds ["select * from patient"]))
(defn -main
[]
(foo 123)
(print ds)
(get-users ds))
|
[
{
"context": " {:subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/b11d\"\n :user \"b11d_app\"\n ",
"end": 215,
"score": 0.9997196197509766,
"start": 206,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " :user \"b11d_app\"\n :password \"blackenedgold\"})\n(defn winnotice-url [sponsor-id]\n (str schema",
"end": 298,
"score": 0.9993556141853333,
"start": 285,
"tag": "PASSWORD",
"value": "blackenedgold"
}
] | src/b11d/config.clj | KeenS/b11d | 5 | (ns b11d.config
(:import [com.mchange.v2.c3p0 ComboPooledDataSource]))
(def schema "http")
(def hostname "localhost")
(def currency "JPY")
(def mysql-db {:subprotocol "mysql"
:subname "//127.0.0.1:3306/b11d"
:user "b11d_app"
:password "blackenedgold"})
(defn winnotice-url [sponsor-id]
(str schema "://" hostname "/api/rtb/1.0.0/winnotice/" sponsor-id))
(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-connection (pool mysql-db))
(defn db-connection [] pooled-connection)
(def adomain ["1" "2"])
| 44120 | (ns b11d.config
(:import [com.mchange.v2.c3p0 ComboPooledDataSource]))
(def schema "http")
(def hostname "localhost")
(def currency "JPY")
(def mysql-db {:subprotocol "mysql"
:subname "//127.0.0.1:3306/b11d"
:user "b11d_app"
:password "<PASSWORD>"})
(defn winnotice-url [sponsor-id]
(str schema "://" hostname "/api/rtb/1.0.0/winnotice/" sponsor-id))
(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-connection (pool mysql-db))
(defn db-connection [] pooled-connection)
(def adomain ["1" "2"])
| true | (ns b11d.config
(:import [com.mchange.v2.c3p0 ComboPooledDataSource]))
(def schema "http")
(def hostname "localhost")
(def currency "JPY")
(def mysql-db {:subprotocol "mysql"
:subname "//127.0.0.1:3306/b11d"
:user "b11d_app"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(defn winnotice-url [sponsor-id]
(str schema "://" hostname "/api/rtb/1.0.0/winnotice/" sponsor-id))
(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-connection (pool mysql-db))
(defn db-connection [] pooled-connection)
(def adomain ["1" "2"])
|
[
{
"context": "ts]])\n (:use tupelo.core))\n\n; https://github.com/stuartsierra/component.repl\n\n; see https://lambdaisland.com/bl",
"end": 557,
"score": 0.9995968341827393,
"start": 545,
"tag": "USERNAME",
"value": "stuartsierra"
},
{
"context": "ent\n (set! *print-length* 100)\n (cprint {:key1 'abc :key2 \"qwertz\" :key3 1.34})\n (pprint {:key1 'abc",
"end": 1810,
"score": 0.9814637303352356,
"start": 1807,
"tag": "KEY",
"value": "abc"
},
{
"context": " *print-length* 100)\n (cprint {:key1 'abc :key2 \"qwertz\" :key3 1.34})\n (pprint {:key1 'abc :key2 \"qwertz",
"end": 1824,
"score": 0.9968242645263672,
"start": 1818,
"tag": "KEY",
"value": "qwertz"
},
{
"context": "* 100)\n (cprint {:key1 'abc :key2 \"qwertz\" :key3 1.34})\n (pprint {:key1 'abc :key2 \"qwertz\" :key3 1.34",
"end": 1836,
"score": 0.9908765554428101,
"start": 1832,
"tag": "KEY",
"value": "1.34"
},
{
"context": "abc :key2 \"qwertz\" :key3 1.34})\n (pprint {:key1 'abc :key2 \"qwertz\" :key3 1.34})\n (/ 1 0)\n (pst)\n (",
"end": 1860,
"score": 0.9480739235877991,
"start": 1857,
"tag": "KEY",
"value": "abc"
},
{
"context": "qwertz\" :key3 1.34})\n (pprint {:key1 'abc :key2 \"qwertz\" :key3 1.34})\n (/ 1 0)\n (pst)\n (bels-test-runn",
"end": 1874,
"score": 0.997622013092041,
"start": 1868,
"tag": "KEY",
"value": "qwertz"
},
{
"context": "1.34})\n (pprint {:key1 'abc :key2 \"qwertz\" :key3 1.34})\n (/ 1 0)\n (pst)\n (bels-test-runner/call-curr",
"end": 1886,
"score": 0.9938257932662964,
"start": 1882,
"tag": "KEY",
"value": "1.34"
}
] | dev/user.clj | bennoloeffler/bel-learn-lib | 0 | (ns user
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer (pprint)]
[puget.printer :refer (cprint)]
[clojure.repl :refer :all]
[clojure.test :as test]
[clojure.tools.namespace.repl :refer (refresh refresh-all clear)]
[debux.core :refer :all]
[hashp.core :refer :all]
[bel.cpipe.system :as system]
[bels-test-runner :refer [call-current-tests]])
(:use tupelo.core))
; https://github.com/stuartsierra/component.repl
; see https://lambdaisland.com/blog/2018-02-09-reloading-woes
(def system nil)
(defn init
"Constructs the current development system."
[]
(alter-var-root #'system
(constantly (system/system))))
(defn start
"Starts the current development system."
[]
(alter-var-root #'system system/start))
(defn stop
"Shuts down and destroys the current development system."
[]
(alter-var-root #'system
(fn [s] (when s (system/stop s)))))
(defn go
"Initializes the current development system and starts it running."
[]
(init)
(start))
(defn reset []
(stop)
(refresh :after 'user/go))
(defn tests []
(println "__________________________________________________________________")
(println "")
(println "REFRESH and RUN ALL TESTS with bels-test-runner/call-current-tests")
(println "__________________________________________________________________")
(refresh :after 'bels-test-runner/call-current-tests))
(defn overview []
(bel-learn-lib.package-viewer/-main))
(comment
(go)
(stop)
(start)
(tests)
(init)
(reset)
(pprint system))
; RUNNING TESTs per WATCHER all the time
; lein bat-test auto
(comment
(set! *print-length* 100)
(cprint {:key1 'abc :key2 "qwertz" :key3 1.34})
(pprint {:key1 'abc :key2 "qwertz" :key3 1.34})
(/ 1 0)
(pst)
(bels-test-runner/call-current-tests)
(run-bels-tests)
(->> (all-ns) (filter #(re-find (re-pattern "datomic") (str %))))
(map #(ns-name %) (all-ns))
(dbg (->> (all-ns) (shuffle) (take 3) (map ns-name) sort (partition 4)))
(/ 10 #p (/ (- 12 10) (+ 10 1)))
(defn s []
(constantly (do (println "again...") (+ 20 100))))
((s) 1 2 3))
| 36579 | (ns user
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer (pprint)]
[puget.printer :refer (cprint)]
[clojure.repl :refer :all]
[clojure.test :as test]
[clojure.tools.namespace.repl :refer (refresh refresh-all clear)]
[debux.core :refer :all]
[hashp.core :refer :all]
[bel.cpipe.system :as system]
[bels-test-runner :refer [call-current-tests]])
(:use tupelo.core))
; https://github.com/stuartsierra/component.repl
; see https://lambdaisland.com/blog/2018-02-09-reloading-woes
(def system nil)
(defn init
"Constructs the current development system."
[]
(alter-var-root #'system
(constantly (system/system))))
(defn start
"Starts the current development system."
[]
(alter-var-root #'system system/start))
(defn stop
"Shuts down and destroys the current development system."
[]
(alter-var-root #'system
(fn [s] (when s (system/stop s)))))
(defn go
"Initializes the current development system and starts it running."
[]
(init)
(start))
(defn reset []
(stop)
(refresh :after 'user/go))
(defn tests []
(println "__________________________________________________________________")
(println "")
(println "REFRESH and RUN ALL TESTS with bels-test-runner/call-current-tests")
(println "__________________________________________________________________")
(refresh :after 'bels-test-runner/call-current-tests))
(defn overview []
(bel-learn-lib.package-viewer/-main))
(comment
(go)
(stop)
(start)
(tests)
(init)
(reset)
(pprint system))
; RUNNING TESTs per WATCHER all the time
; lein bat-test auto
(comment
(set! *print-length* 100)
(cprint {:key1 '<KEY> :key2 "<KEY>" :key3 <KEY>})
(pprint {:key1 '<KEY> :key2 "<KEY>" :key3 <KEY>})
(/ 1 0)
(pst)
(bels-test-runner/call-current-tests)
(run-bels-tests)
(->> (all-ns) (filter #(re-find (re-pattern "datomic") (str %))))
(map #(ns-name %) (all-ns))
(dbg (->> (all-ns) (shuffle) (take 3) (map ns-name) sort (partition 4)))
(/ 10 #p (/ (- 12 10) (+ 10 1)))
(defn s []
(constantly (do (println "again...") (+ 20 100))))
((s) 1 2 3))
| true | (ns user
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer (pprint)]
[puget.printer :refer (cprint)]
[clojure.repl :refer :all]
[clojure.test :as test]
[clojure.tools.namespace.repl :refer (refresh refresh-all clear)]
[debux.core :refer :all]
[hashp.core :refer :all]
[bel.cpipe.system :as system]
[bels-test-runner :refer [call-current-tests]])
(:use tupelo.core))
; https://github.com/stuartsierra/component.repl
; see https://lambdaisland.com/blog/2018-02-09-reloading-woes
(def system nil)
(defn init
"Constructs the current development system."
[]
(alter-var-root #'system
(constantly (system/system))))
(defn start
"Starts the current development system."
[]
(alter-var-root #'system system/start))
(defn stop
"Shuts down and destroys the current development system."
[]
(alter-var-root #'system
(fn [s] (when s (system/stop s)))))
(defn go
"Initializes the current development system and starts it running."
[]
(init)
(start))
(defn reset []
(stop)
(refresh :after 'user/go))
(defn tests []
(println "__________________________________________________________________")
(println "")
(println "REFRESH and RUN ALL TESTS with bels-test-runner/call-current-tests")
(println "__________________________________________________________________")
(refresh :after 'bels-test-runner/call-current-tests))
(defn overview []
(bel-learn-lib.package-viewer/-main))
(comment
(go)
(stop)
(start)
(tests)
(init)
(reset)
(pprint system))
; RUNNING TESTs per WATCHER all the time
; lein bat-test auto
(comment
(set! *print-length* 100)
(cprint {:key1 'PI:KEY:<KEY>END_PI :key2 "PI:KEY:<KEY>END_PI" :key3 PI:KEY:<KEY>END_PI})
(pprint {:key1 'PI:KEY:<KEY>END_PI :key2 "PI:KEY:<KEY>END_PI" :key3 PI:KEY:<KEY>END_PI})
(/ 1 0)
(pst)
(bels-test-runner/call-current-tests)
(run-bels-tests)
(->> (all-ns) (filter #(re-find (re-pattern "datomic") (str %))))
(map #(ns-name %) (all-ns))
(dbg (->> (all-ns) (shuffle) (take 3) (map ns-name) sort (partition 4)))
(/ 10 #p (/ (- 12 10) (+ 10 1)))
(defn s []
(constantly (do (println "again...") (+ 20 100))))
((s) 1 2 3))
|
[
{
"context": " :token \"token.localtest.me\"\n ",
"end": 2851,
"score": 0.733034074306488,
"start": 2836,
"tag": "KEY",
"value": "token.localtest"
},
{
"context": " :token \"token.localtest.me\"\n ",
"end": 2851,
"score": 0.5298764705657959,
"start": 2851,
"tag": "PASSWORD",
"value": ""
},
{
"context": " :token \"token.localtest.me\"\n :",
"end": 2854,
"score": 0.5383495688438416,
"start": 2852,
"tag": "KEY",
"value": "me"
},
{
"context": " :token \"token.localtest.me\"\n :",
"end": 3719,
"score": 0.709306001663208,
"start": 3701,
"tag": "KEY",
"value": "token.localtest.me"
},
{
"context": " :token \"token.localtest.me\"\n :",
"end": 4488,
"score": 0.7016337513923645,
"start": 4470,
"tag": "KEY",
"value": "token.localtest.me"
},
{
"context": " (let [test-request {:headers {\"host\" \"token.localtest.me\"}\n :scheme :https\n ",
"end": 4956,
"score": 0.8776469230651855,
"start": 4944,
"tag": "EMAIL",
"value": "localtest.me"
},
{
"context": " :token \"token.localtest.me\"\n ",
"end": 5213,
"score": 0.6679069399833679,
"start": 5208,
"tag": "KEY",
"value": "token"
},
{
"context": " :token \"token.localtest.me\"\n :",
"end": 5226,
"score": 0.6974402070045471,
"start": 5214,
"tag": "PASSWORD",
"value": "localtest.me"
},
{
"context": " :token \"token.localtest.me\"\n ",
"end": 6039,
"score": 0.6737069487571716,
"start": 6034,
"tag": "KEY",
"value": "token"
},
{
"context": " :token \"token.localtest.me\"\n :",
"end": 6052,
"score": 0.738766074180603,
"start": 6040,
"tag": "PASSWORD",
"value": "localtest.me"
},
{
"context": " :token \"token.localtest.me\"\n ",
"end": 6895,
"score": 0.7428884506225586,
"start": 6890,
"tag": "KEY",
"value": "token"
},
{
"context": " :token \"token.localtest.me\"\n :",
"end": 6908,
"score": 0.6055967211723328,
"start": 6896,
"tag": "PASSWORD",
"value": "localtest.me"
},
{
"context": " :token \"token.localtest.me\"\n ",
"end": 7697,
"score": 0.7278189063072205,
"start": 7692,
"tag": "KEY",
"value": "token"
},
{
"context": " :token \"token.localtest.me\"\n ",
"end": 7697,
"score": 0.4070589244365692,
"start": 7697,
"tag": "PASSWORD",
"value": ""
},
{
"context": " :token \"token.localtest.me\"\n ",
"end": 7703,
"score": 0.37486472725868225,
"start": 7698,
"tag": "EMAIL",
"value": "local"
},
{
"context": " :token \"token.localtest.me\"\n :",
"end": 7710,
"score": 0.6090299487113953,
"start": 7703,
"tag": "PASSWORD",
"value": "test.me"
},
{
"context": " :token \"token.localtest.me\"\n :",
"end": 8749,
"score": 0.768925666809082,
"start": 8731,
"tag": "KEY",
"value": "token.localtest.me"
},
{
"context": " {}\n :token \"token.localtest.me\"\n :token-met",
"end": 9915,
"score": 0.7972891330718994,
"start": 9897,
"tag": "KEY",
"value": "token.localtest.me"
},
{
"context": " {}\n :token \"token.localtest.me\"\n :to",
"end": 11018,
"score": 0.648946225643158,
"start": 11007,
"tag": "KEY",
"value": "token.local"
},
{
"context": " :token \"token.localtest.me\"\n :token-m",
"end": 11022,
"score": 0.46959301829338074,
"start": 11018,
"tag": "PASSWORD",
"value": "test"
},
{
"context": " :token \"token.localtest.me\"\n :token-met",
"end": 11025,
"score": 0.4962272644042969,
"start": 11023,
"tag": "KEY",
"value": "me"
},
{
"context": " {}\n :token \"token.localtest.me\"\n :to",
"end": 11931,
"score": 0.6706529259681702,
"start": 11920,
"tag": "KEY",
"value": "token.local"
},
{
"context": " :token \"token.localtest.me\"\n :token-met",
"end": 11938,
"score": 0.5040366649627686,
"start": 11931,
"tag": "PASSWORD",
"value": "test.me"
},
{
"context": " {}\n :token \"token.localtest.me\"\n :to",
"end": 12711,
"score": 0.6497976779937744,
"start": 12700,
"tag": "KEY",
"value": "token.local"
},
{
"context": " :token \"token.localtest.me\"\n :token-met",
"end": 12718,
"score": 0.5382985472679138,
"start": 12711,
"tag": "EMAIL",
"value": "test.me"
},
{
"context": " {}\n :token \"token.localtest.me\"\n :token-met",
"end": 13497,
"score": 0.6150873899459839,
"start": 13479,
"tag": "EMAIL",
"value": "token.localtest.me"
},
{
"context": " :authorization/user \"test-user\"\n :headers {\"accept\" ",
"end": 22653,
"score": 0.6772543787956238,
"start": 22649,
"tag": "USERNAME",
"value": "user"
},
{
"context": "DOMAIN\"\n :authorization/user \"test-user\"\n :headers {\"accept\" \"applica",
"end": 31341,
"score": 0.6882638931274414,
"start": 31332,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": " :authorization/user \"test-user\"\n :request-method req",
"end": 35360,
"score": 0.992121160030365,
"start": 35351,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "est test-list-services-handler\n (let [test-user \"test-user\"\n test-user-services #{\"service1\" \"service",
"end": 42524,
"score": 0.9991434216499329,
"start": 42515,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "ources [{:token \"t2.com\" :version \"v2\"} {:token \"t3.edu\" :version \"v3\"}]\n ",
"end": 43176,
"score": 0.446512371301651,
"start": 43175,
"tag": "KEY",
"value": "3"
},
{
"context": "urces [{:token \"t2.com\" :version \"v2\"} {:token \"t3.edu\" :version \"v3\"}]\n ",
"end": 43176,
"score": 0.46003127098083496,
"start": 43176,
"tag": "PASSWORD",
"value": ""
},
{
"context": "vice3\" [{:token \"t2.com\" :version \"v2\"} {:token \"t3.edu\" :version \"v3\"}]\n ",
"end": 44135,
"score": 0.43507125973701477,
"start": 44134,
"tag": "KEY",
"value": "3"
},
{
"context": "ice3\" [{:token \"t2.com\" :version \"v2\"} {:token \"t3.edu\" :version \"v3\"}]\n ",
"end": 44139,
"score": 0.4221090078353882,
"start": 44136,
"tag": "PASSWORD",
"value": "edu"
},
{
"context": " \"service4\" [{:token \"t1.org\" :version \"v1\"} {:token \"t2.com\" :version \"v2",
"end": 44215,
"score": 0.4759830832481384,
"start": 44214,
"tag": "KEY",
"value": "1"
},
{
"context": "vice4\" [{:token \"t1.org\" :version \"v1\"} {:token \"t2.com\" :version \"v2\"}]\n ",
"end": 44247,
"score": 0.471606582403183,
"start": 44246,
"tag": "KEY",
"value": "2"
},
{
"context": "vice5\" [{:token \"t1.org\" :version \"v1\"} {:token \"t3.edu\" :version \"v3\"}]\n ",
"end": 44359,
"score": 0.33677494525909424,
"start": 44358,
"tag": "KEY",
"value": "3"
},
{
"context": " \"service9\" [{:token \"t2.com\" :version \"v3\"}]}\n all-services (set/union",
"end": 44555,
"score": 0.943975567817688,
"start": 44549,
"tag": "PASSWORD",
"value": "t2.com"
},
{
"context": " :host (str \"127.0.0.\" (hash instance-id-1))\n ",
"end": 45306,
"score": 0.9513199925422668,
"start": 45299,
"tag": "IP_ADDRESS",
"value": "127.0.0"
},
{
"context": "er-services))\n request {:authorization/user test-user}\n instance-counts-present (fn [body]\n ",
"end": 46245,
"score": 0.7017644047737122,
"start": 46236,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "(let [request (assoc request :authorization/user \"test-user1\")]\n (let [{:keys [body] :as response}\n ",
"end": 49435,
"score": 0.984979510307312,
"start": 49425,
"tag": "USERNAME",
"value": "test-user1"
},
{
"context": "(let [request (assoc request :authorization/user \"test-user1\" :query-string \"run-as-user=test-user1.*\")]\n ",
"end": 50862,
"score": 0.9994184970855713,
"start": 50852,
"tag": "USERNAME",
"value": "test-user1"
},
{
"context": " request (assoc request :authorization/user \"another-user\" :query-string \"run-as-user=another-user\")]\n ",
"end": 62341,
"score": 0.6061186790466309,
"start": 62329,
"tag": "USERNAME",
"value": "another-user"
},
{
"context": " request (assoc request :authorization/user \"another-user\" :query-string \"run-as-user=.*user.*\")]\n ",
"end": 64489,
"score": 0.9791144728660583,
"start": 64477,
"tag": "USERNAME",
"value": "another-user"
},
{
"context": " request (assoc request :authorization/user \"another-user\" :query-string \"run-as-user=another.*\")]\n ",
"end": 65564,
"score": 0.9859785437583923,
"start": 65552,
"tag": "USERNAME",
"value": "another-user"
},
{
"context": "(let [request (assoc request :query-string \"token=t1&token-version=v1\")\n {:keys [body] :a",
"end": 72614,
"score": 0.9287526607513428,
"start": 72612,
"tag": "KEY",
"value": "t1"
},
{
"context": "oc request :query-string \"token=t1&token-version=v1\")\n {:keys [body] :as response}\n ",
"end": 72631,
"score": 0.6554522514343262,
"start": 72630,
"tag": "KEY",
"value": "1"
},
{
"context": "st test-delete-service-handler\n (let [test-user \"test-user\"\n test-service-id \"service-1\"\n test",
"end": 75268,
"score": 0.9986665844917297,
"start": 75259,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "ed!\"}))\n request {:authorization/user test-user}\n {:keys [body headers status]}",
"end": 76076,
"score": 0.6347520351409912,
"start": 76072,
"tag": "USERNAME",
"value": "test"
},
{
"context": "d\"}))\n request {:authorization/user \"another-user\"}]\n (is (thrown-with-msg?\n ",
"end": 76979,
"score": 0.7491740584373474,
"start": 76967,
"tag": "USERNAME",
"value": "another-user"
},
{
"context": " (constantly current-time-ms)\n test-token \"www.example.com\"\n test-service-description {\"cmd\" \"some-cm",
"end": 103437,
"score": 0.5053455829620361,
"start": 103422,
"tag": "PASSWORD",
"value": "www.example.com"
},
{
"context": "t (str service-description))))\n test-user \"test-user\"\n test-service-id (-> test-service-descrip",
"end": 104162,
"score": 0.9710955619812012,
"start": 104153,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": " :headers {\"host\" (str test-token \":1234\")\n \"origin\" \"http:/",
"end": 111255,
"score": 0.6802471280097961,
"start": 111251,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": " :headers {\"host\" (str test-token \":1234\")\n \"origin\" \"http:/",
"end": 112003,
"score": 0.5249714255332947,
"start": 112000,
"tag": "PASSWORD",
"value": "234"
},
{
"context": " request\"\n (let [request {:authorization/user test-user\n :headers {\"host\" (str t",
"end": 113507,
"score": 0.5066912174224854,
"start": 113503,
"tag": "USERNAME",
"value": "test"
},
{
"context": "der-consent-template\n (let [context {:auth-user \"test-user\"\n :consent-expiry-days 1\n ",
"end": 114982,
"score": 0.9994840621948242,
"start": 114973,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "mple.com:6789/some-path\"\n :token \"www.example.com\"}\n body (render-consent-template context)]",
"end": 115265,
"score": 0.6490648984909058,
"start": 115250,
"tag": "PASSWORD",
"value": "www.example.com"
},
{
"context": "\n consent-expiry-days 1\n test-user \"test-user\"\n request->consent-service-id (fn [request",
"end": 116635,
"score": 0.9993579983711243,
"start": 116626,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": " (is (= {:auth-user test-user\n :cons",
"end": 118489,
"score": 0.9915124773979187,
"start": 118480,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "cription\"\n (let [request {:authorization/user test-user\n :headers {\"host\" \"www.e",
"end": 119851,
"score": 0.6356571316719055,
"start": 119847,
"tag": "USERNAME",
"value": "test"
},
{
"context": "scheme\"\n (let [request {:authorization/user test-user\n :headers {\"host\" \"www.exam",
"end": 120592,
"score": 0.9419972896575928,
"start": 120583,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "scheme\"\n (let [request {:authorization/user test-user\n :headers {\"host\" \"www.exam",
"end": 121268,
"score": 0.950389564037323,
"start": 121259,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "-proto\"\n (let [request {:authorization/user test-user\n :headers {\"host\" \"www.exam",
"end": 121956,
"score": 0.8804318308830261,
"start": 121947,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "-proto\"\n (let [request {:authorization/user test-user\n :headers {\"host\" \"www.exam",
"end": 122672,
"score": 0.9950149655342102,
"start": 122663,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "-proto\"\n (let [request {:authorization/user test-user\n :headers {\"host\" \"www.exam",
"end": 123391,
"score": 0.9951232075691223,
"start": 123382,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": "-proto\"\n (let [request {:authorization/user test-user\n :headers {\"host\" \"www.exam",
"end": 124111,
"score": 0.9937153458595276,
"start": 124102,
"tag": "USERNAME",
"value": "test-user"
}
] | waiter/test/waiter/handler_test.clj | twosigma/waiter | 76 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.handler-test
(:require [clj-time.core :as t]
[clojure.core.async :as async]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.walk :as walk]
[full.async :as fa]
[plumbing.core :as pc]
[waiter.authorization :as authz]
[waiter.core :as core]
[waiter.handler :refer :all]
[waiter.interstitial :as interstitial]
[waiter.kv :as kv]
[waiter.scheduler :as scheduler]
[waiter.service-description :as sd]
[waiter.statsd :as statsd]
[waiter.status-codes :refer :all]
[waiter.test-helpers :refer :all]
[waiter.util.date-utils :as du]
[waiter.util.utils :as utils])
(:import (clojure.core.async.impl.channels ManyToManyChannel)
(clojure.lang ExceptionInfo)
(java.io StringBufferInputStream StringReader)
(java.util.concurrent Executors)))
(deftest test-wrap-https-redirect
(let [handler-response (Object.)
execute-request (fn execute-request-fn [test-request]
(let [request-handler-argument-atom (atom nil)
test-request-handler (fn request-handler-fn [request]
(reset! request-handler-argument-atom request)
handler-response)
test-response ((wrap-https-redirect test-request-handler) test-request)]
{:handled-request @request-handler-argument-atom
:response test-response}))]
(testing "no redirect"
(testing "http request with token https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"}
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "http request with waiter header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "true"}
:request-method :get
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" true}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with token https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with token https-redirect set to true"
(let [test-request {:headers {"host" "token.localtest.me"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with waiter-header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "false"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {"cpus" 1}
:token "token.localtest.me"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" false}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with waiter-header https-redirect set to true"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "true"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {"cpus" 1}
:token "token.localtest.me"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" true}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response)))))
(testing "https redirect"
(testing "http request with token https-redirect set to true"
(let [test-request {:headers {"host" "token.localtest.me:1234"}
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (nil? handled-request))
(is (= {:body ""
:headers {"Location" "https://token.localtest.me"}
:status http-307-temporary-redirect
:waiter/response-source :waiter}
response))))
(testing "http request with waiter header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "false"}
:request-method :get
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" true}
:waiter-headers {"x-waiter-https-redirect" false}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (nil? handled-request))
(is (= {:body ""
:headers {"Location" "https://token.localtest.me"}
:status http-301-moved-permanently
:waiter/response-source :waiter}
response)))))))
(deftest test-wrap-https-redirect-acceptor
(testing "returns 301 with proper url if ws and https-redirect is true and uri is nil"
(let [handler (wrap-wss-redirect (fn [_] (is false "Not supposed to call this handler") true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
response-status (handler request)]
(is (= http-301-moved-permanently response-status))
(is (= http-301-moved-permanently (.getStatusCode upgrade-response)))
(is (= "https://token.localtest.me" (.getHeader upgrade-response "location")))
(is (= "https-redirect is enabled" (.getStatusReason upgrade-response)))))
(testing "returns 301 with proper url if ws and https-redirect is true and uri is set"
(let [handler (wrap-wss-redirect (fn [_] (is false "Not supposed to call this handler") true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
response-status (handler request)]
(is (= http-301-moved-permanently response-status))
(is (= http-301-moved-permanently (.getStatusCode upgrade-response)))
(is (= "https://token.localtest.me/random/uri/path" (.getHeader upgrade-response "location")))
(is (= "https-redirect is enabled" (.getStatusReason upgrade-response)))))
(testing "passes on to next handler if wss and https-redirect is true"
(let [handler (wrap-wss-redirect (fn [_] true))
request {:headers {"host" "token.localtest.me"}
:scheme :wss
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?))))
(testing "passes on to next handler if https-redirect is false for wss request"
(let [handler (wrap-wss-redirect (fn [_] true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :wss
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?))))
(testing "passes on to next handler if https-redirect is false for ws request"
(let [handler (wrap-wss-redirect (fn [_] true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "token.localtest.me"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?)))))
(deftest test-complete-async-handler
(testing "missing-request-id"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request {:basic-authentication {:src-router-id src-router-id}
:headers {"accept" "application/json"}
:route-params {:service-id service-id}
:uri (str "/waiter-async/complete//" service-id)}
async-request-terminate-fn (fn [_] (throw (Exception. "unexpected call!")))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "No request-id specified"))))
(testing "missing-service-id"
(let [src-router-id "src-router-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:headers {"accept" "application/json"}
:route-params {:request-id request-id}
:uri (str "/waiter-async/complete/" request-id "/")}
async-request-terminate-fn (fn [_] (throw (Exception. "unexpected call!")))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "No service-id specified"))))
(testing "valid-request-id"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:route-params {:request-id request-id, :service-id service-id}
:uri (str "/waiter-async/complete/" request-id "/" service-id)}
async-request-terminate-fn (fn [in-request-id] (= request-id in-request-id))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-200-ok status))
(is (= expected-json-response-headers headers))
(is (= {:request-id request-id, :success true} (pc/keywordize-map (json/read-str body))))))
(testing "unable-to-terminate-request"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:route-params {:request-id request-id, :service-id service-id}
:uri (str "/waiter-async/complete/" request-id "/" service-id)}
async-request-terminate-fn (fn [_] false)
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-200-ok status))
(is (= expected-json-response-headers headers))
(is (= {:request-id request-id, :success false} (pc/keywordize-map (json/read-str body)))))))
(deftest test-async-result-handler-errors
(let [my-router-id "my-router-id"
service-id "test-service-id"
make-route-params (fn [code]
{:host "host"
:location (when (not= code "missing-location") "location/1234")
:port "port"
:request-id (when (not= code "missing-request-id") "req-1234")
:router-id (when (not= code "missing-router-id") my-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})]
(testing "missing-location"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-location")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-request-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-request-id")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-router-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-router-id")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "error-in-checking-backend-status"
(let [request {:authorization/pricipal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:request-method :http-method
:route-params (make-route-params "local")}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:error (ex-info "backend-status-error" {:status http-502-bad-gateway})}))
async-trigger-terminate-fn (fn [in-router-id in-service-id in-request-id]
(is (= my-router-id in-router-id))
(is (= service-id in-service-id))
(is (= "req-1234" in-request-id)))
{:keys [body headers status]}
(async/<!!
(async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
(is (= http-502-bad-gateway status))
(is (= expected-json-response-headers headers))
(is (every? #(str/includes? body %) ["backend-status-error"]))))))
(deftest test-async-result-handler-with-return-codes
(let [my-router-id "my-router-id"
service-id "test-service-id"
remote-router-id "remote-router-id"
make-route-params (fn [code]
{:host "host"
:location (if (= code "local") "location/1234" "location/6789")
:port "port"
:request-id (if (= code "local") "req-1234" "req-6789")
:router-id (if (= code "local") my-router-id remote-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})
request-id-fn (fn [router-type] (if (= router-type "local") "req-1234" "req-6789"))]
(letfn [(execute-async-result-check
[{:keys [request-method return-status router-type]}]
(let [terminate-call-atom (atom false)
async-trigger-terminate-fn (fn [target-router-id in-service-id request-id]
(reset! terminate-call-atom true)
(is (= (if (= router-type "local") my-router-id remote-router-id) target-router-id))
(is (= service-id in-service-id))
(is (= (request-id-fn router-type) request-id)))
request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:request-method request-method,
:route-params (make-route-params router-type)}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:body "async-result-response", :headers {}, :status return-status}))
{:keys [status headers]}
(async/<!!
(async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
{:terminated @terminate-call-atom, :return-status status, :return-headers headers}))]
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-303-see-other, :router-type "local"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-303-see-other, :router-type "remote"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-303-see-other, :router-type "local"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-303-see-other, :router-type "remote"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-204-no-content, :router-type "local"})))
(is (= {:terminated true, :return-status http-404-not-found, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-404-not-found, :router-type "local"})))
(is (= {:terminated true, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-204-no-content, :router-type "remote"})))
(is (= {:terminated true, :return-status http-404-not-found, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-404-not-found, :router-type "remote"})))
(is (= {:terminated true, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "remote"}))))))
(deftest test-async-status-handler-errors
(let [my-router-id "my-router-id"
service-id "test-service-id"
make-route-params (fn [code]
{:host "host"
:location (when (not= code "missing-location") "location/1234")
:port "port"
:request-id (when (not= code "missing-request-id") "req-1234")
:router-id (when (not= code "missing-router-id") my-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})]
(testing "missing-code"
(let [request {:headers {"accept" "application/json"}
:query-string ""}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-location"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-location")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-request-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-request-id")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-router-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-router-id")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "error-in-checking-backend-status"
(let [request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:route-params (make-route-params "local")
:request-method :http-method}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:error (ex-info "backend-status-error" {:status http-400-bad-request})}))
async-trigger-terminate-fn nil
{:keys [body headers status]} (async/<!! (async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (every? #(str/includes? body %) ["backend-status-error"]))))))
(deftest test-async-status-handler-with-return-codes
(let [my-router-id "my-router-id"
service-id "test-service-id"
remote-router-id "remote-router-id"
make-route-params (fn [code]
{:host "host"
:location (if (= code "local") "query/location/1234" "query/location/6789")
:port "port"
:request-id (if (= code "local") "req-1234" "req-6789")
:router-id (if (= code "local") my-router-id remote-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})
request-id-fn (fn [router-type] (if (= router-type "local") "req-1234" "req-6789"))
result-location-fn (fn [router-type & {:keys [include-host-port] :or {include-host-port false}}]
(str (when include-host-port "http://www.example.com:8521")
"/path/to/result-" (if (= router-type "local") "1234" "6789")))
async-result-location (fn [router-type & {:keys [include-host-port location] :or {include-host-port false}}]
(if include-host-port
(result-location-fn router-type :include-host-port include-host-port)
(str "/waiter-async/result/" (request-id-fn router-type) "/"
(if (= router-type "local") my-router-id remote-router-id) "/"
service-id "/host/port"
(or location (result-location-fn router-type :include-host-port false)))))]
(letfn [(execute-async-status-check
[{:keys [request-method result-location return-status router-type]}]
(let [terminate-call-atom (atom false)
async-trigger-terminate-fn (fn [target-router-id in-service-id request-id]
(reset! terminate-call-atom true)
(is (= (if (= router-type "local") my-router-id remote-router-id) target-router-id))
(is (= service-id in-service-id))
(is (= (request-id-fn router-type) request-id)))
request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:request-method request-method
:route-params (make-route-params router-type)}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:body "status-check-response"
:headers (if (= return-status http-303-see-other) {"location" (or result-location (result-location-fn router-type))} {})
:status return-status}))
{:keys [status headers]}
(async/<!!
(async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
{:terminated @terminate-call-atom, :return-status status, :return-headers headers}))]
(is (= {:terminated false, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-200-ok, :router-type "local"})))
(let [result-location (async-result-location "local" :include-host-port false)]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/location/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/location/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "./another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "../another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "../../another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (str "http://www.example.com:1234" (async-result-location "local" :include-host-port true))]
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location result-location, :return-status http-303-see-other, :router-type "local"}))))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated false, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-200-ok, :router-type "remote"})))
(let [result-location (async-result-location "remote" :include-host-port false)]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :return-status http-303-see-other, :router-type "remote"}))))
(let [result-location (str "http://www.example.com:1234" (async-result-location "remote" :include-host-port true))]
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location result-location, :return-status http-303-see-other, :router-type "remote"}))))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-204-no-content, :router-type "local"})))
(is (= {:terminated false, :return-status http-404-not-found, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-404-not-found, :router-type "local"})))
(is (= {:terminated false, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-204-no-content, :router-type "remote"})))
(is (= {:terminated false, :return-status http-404-not-found, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-404-not-found, :router-type "remote"})))
(is (= {:terminated false, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "remote"}))))))
(deftest test-list-services-handler
(let [test-user "test-user"
test-user-services #{"service1" "service2" "service3" "service7" "service8" "service9" "service10"}
other-user-services #{"service4" "service5" "service6" "service11"}
healthy-services #{"service1" "service2" "service4" "service6" "service7" "service8" "service9" "service10" "service11"}
unhealthy-services #{"service2" "service3" "service5"}
service-id->references {"service1" {:sources [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
:type :token}
"service3" {:sources [{:token "t2.com" :version "v2"} {:token "t3.edu" :version "v3"}]
:type :token}
"service4" {:sources [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
:type :token}
"service5" {:sources [{:token "t1.org" :version "v1"} {:token "t3.edu" :version "v3"}]
:type :token}
"service7" {:sources [{:token "t1.org" :version "v2"} {:token "t2.com" :version "v1"}]
:type :token}
"service9" {:sources [{:token "t2.com" :version "v3"}]
:type :token}}
service-id->source-tokens {"service1" [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
"service3" [{:token "t2.com" :version "v2"} {:token "t3.edu" :version "v3"}]
"service4" [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
"service5" [{:token "t1.org" :version "v1"} {:token "t3.edu" :version "v3"}]
"service7" [{:token "t1.org" :version "v2"} {:token "t2.com" :version "v1"}]
"service9" [{:token "t2.com" :version "v3"}]}
all-services (set/union other-user-services test-user-services)
current-time (t/now)
query-state-fn (constantly {:all-available-service-ids all-services
:service-id->healthy-instances (pc/map-from-keys
(fn [service-id]
(let [instance-id-1 (str service-id ".i1")]
[{:flags []
:healthy? true
:host (str "127.0.0." (hash instance-id-1))
:id instance-id-1
:port (+ 1000 (rand 1000))
:service-id service-id
:started-at (du/date-to-str current-time)}]))
healthy-services)
:service-id->unhealthy-instances (pc/map-from-keys (constantly []) unhealthy-services)})
query-autoscaler-state-fn (constantly
(pc/map-from-keys
(fn [_] {:scale-amount (rand-nth [-1 0 1])})
test-user-services))
request {:authorization/user test-user}
instance-counts-present (fn [body]
(let [parsed-body (-> body (str) (json/read-str) (walk/keywordize-keys))]
(every? (fn [service-entry]
(is (contains? service-entry :instance-counts))
(is (every? #(contains? (get service-entry :instance-counts) %)
[:healthy-instances, :unhealthy-instances])))
parsed-body)))
prepend-waiter-url identity
entitlement-manager (reify authz/EntitlementManager
(authorized? [_ user action {:keys [service-id]}]
(let [id (subs service-id (count "service"))]
(and (str/includes? (str test-user id) user)
(= action :manage)
(some #(= % service-id) test-user-services)))))
retrieve-token-based-fallback-fn (constantly nil)
token->token-hash (constantly nil)
list-services-handler (wrap-handler-json-response list-services-handler)
assert-successful-json-response (fn [{:keys [body headers status]}]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (instance-counts-present body)))]
(letfn [(service-id->metrics-fn []
{})
(service-id->references-fn [service-id]
(get service-id->references service-id))
(service-id->service-description-fn [service-id & _]
(let [id (subs service-id (count "service"))]
{"cpus" (Integer/parseInt id)
"env" {"E_ID" (str "id-" id)}
"mem" (* 10 (Integer/parseInt id))
"metadata" {"m-id" (str "id-" id)}
"metric-group" (str "mg" id)
"run-as-user" (if (contains? test-user-services service-id) (str test-user id) "another-user")}))
(service-id->source-tokens-entries-fn [service-id]
(when (contains? service-id->source-tokens service-id)
(let [source-tokens (-> service-id service-id->source-tokens walk/stringify-keys)]
#{source-tokens})))]
(testing "list-services-handler:success-regular-user"
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= test-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))
(let [request (assoc request :authorization/user "test-user1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service10"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :authorization/user "test-user1" :query-string "run-as-user=test-user1.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service10"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (conj other-user-services "service1")
(->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user1.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (conj other-user-services "service1" "service10")
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-cpus"
(let [request (assoc request :query-string "cpus=1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-metric-group"
(let [request (assoc request :query-string "metric-group=mg3")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service3"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-metric-groups"
(let [request (assoc request :query-string "metric-group=mg1&metric-group=mg2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-single-env-variable"
(let [request (assoc request :query-string "env.E_ID=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-env-variables"
(let [request (assoc request :query-string "env.E_ID=id-1&env.E_ID=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-single-metadata-variable"
(let [request (assoc request :query-string "metadata.m-id=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-metadata-variables"
(let [request (assoc request :query-string "metadata.m-id=id-1&metadata.m-id=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-nested-parameters"
(let [request (assoc request :query-string "env.E_ID=id-1&metadata.m-id=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "env.E_ID=id-1&metadata.m-id=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-same-user"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-prefix-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=.*user.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-suffix-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=another.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-different-run-as-user-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user test-user :query-string "run-as-user=another.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:failure"
(let [query-state-fn (constantly {:all-available-service-ids #{"service1"}
:service-id->healthy-instances {"service1" []}})
request {:authorization/user test-user}
exception-message "Custom message from test case"
prepend-waiter-url (fn [_] (throw (ex-info exception-message {:status http-400-bad-request})))
list-services-handler (core/wrap-error-handling
#(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash %))
{:keys [body headers status]} (list-services-handler request)]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (str/includes? (str body) exception-message))))
(testing "list-services-handler:success-super-user-sees-all-apps"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ user action {:keys [service-id]}]
(and (= user test-user)
(= :manage action)
(contains? all-services service-id))))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(testing "list-services-handler:success-filter-tokens"
(doseq [[query-param filter-fn]
{"t1.com" #(= % "t1.com")
"t2.org" #(= % "t2.org")
"tn.none" #(= % "tn.none")
".*o.*" #(str/includes? % "o")
".*t.*" #(str/includes? % "t")
"t.*" #(str/starts-with? % "t")
".*com" #(str/ends-with? % "com")
".*org" #(str/ends-with? % "org")}]
(let [request (assoc request :query-string (str "token=" query-param))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(->> source-tokens (map :token) (some filter-fn))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-filter-version"
(doseq [[query-param filter-fn]
{"v1" #(= % "v1")
"v2" #(= % "v2")
"vn" #(= % "vn")
".*v.*" #(str/includes? % "v")
"v.*" #(str/starts-with? % "v")
".*1" #(str/ends-with? % "1")
".*2" #(str/ends-with? % "2")}]
(let [request (assoc request :query-string (str "token-version=" query-param))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(->> source-tokens (map :version) (some filter-fn))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-filter-token-and-version"
(let [request (assoc request :query-string "token=t1&token-version=v1")
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(and (->> source-tokens (map :token) (some #(= % "t1")))
(->> source-tokens (map :version) (some #(= % "v1"))))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(testing "list-services-handler:include-healthy-instances"
(let [request (assoc request :query-string "include=healthy-instances")
{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)
service-id->healthy-instances (->> body
(json/read-str)
(walk/keywordize-keys)
(pc/map-from-vals :service-id)
(pc/map-vals #(get-in % [:instances :healthy-instances])))]
(assert-successful-json-response response)
(is (= test-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))
(doseq [service-id test-user-services]
(if (contains? healthy-services service-id)
(let [healthy-instances (get-in (query-state-fn) [:service-id->healthy-instances service-id])]
(is (= (map #(select-keys % [:host :id :port :started-at]) healthy-instances)
(get service-id->healthy-instances service-id))))
(is (empty? (get service-id->healthy-instances service-id))))))))))
(deftest test-delete-service-handler
(let [test-user "test-user"
test-service-id "service-1"
test-router-id "router-1"
allowed-to-manage-service?-fn (fn [service-id user] (and (= test-service-id service-id) (= test-user user)))
make-inter-router-requests-fn (constantly {})
fallback-state-atom (atom nil)]
(let [core-service-description {"run-as-user" test-user}
scheduler-interactions-thread-pool (Executors/newFixedThreadPool 1)]
(testing "delete-service-handler:success-regular-user"
(let [scheduler (reify scheduler/ServiceScheduler
(delete-service [_ service-id]
(is (= test-service-id service-id))
{:result :deleted
:message "Worked!"}))
request {:authorization/user test-user}
{:keys [body headers status]}
(async/<!!
(delete-service-handler test-router-id test-service-id core-service-description scheduler allowed-to-manage-service?-fn
scheduler-interactions-thread-pool make-inter-router-requests-fn fallback-state-atom request))]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (every? #(str/includes? (str body) (str %)) ["Worked!"]))))
(testing "delete-service-handler:success-regular-user-deleting-for-another-user"
(let [scheduler (reify scheduler/ServiceScheduler
(delete-service [_ service-id]
(is (= test-service-id service-id))
{:deploymentId "good"}))
request {:authorization/user "another-user"}]
(is (thrown-with-msg?
ExceptionInfo #"User not allowed to delete service"
(delete-service-handler test-router-id test-service-id core-service-description scheduler allowed-to-manage-service?-fn
scheduler-interactions-thread-pool make-inter-router-requests-fn fallback-state-atom request)))))
(.shutdown scheduler-interactions-thread-pool))))
(deftest test-service-await-handler
(let [handler-name "test-service-await-handler"
timeout 1000
request {:route-params {:service-id "s1" :goal-state "deleted"}
:basic-authentication {:src-router-id "r2"}
:request-method :get
:query-string (str "timeout=" 1000)}
assert-immediate-success
(fn [goal-state fallback-state-atom request expected-service-exists? expected-service-healthy?]
(let [request (assoc-in request [:route-params :goal-state] goal-state)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") expected-service-exists?))
(is (= (get parsed-body "service-healthy?") expected-service-healthy?))
(is (get parsed-body "goal-success?"))))
assert-force-timeout
(fn [timeout goal-state fallback-state-atom request expected-service-exists? expected-service-healthy?]
(let [request (assoc-in request [:route-params :goal-state] goal-state)
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") expected-service-exists?))
(is (= (get parsed-body "service-healthy?") expected-service-healthy?))
(is (not (get parsed-body "goal-success?")))
(is (>= (- end-time start-time) timeout))))]
(testing (str handler-name ":immediate-success-deleted")
(let [fallback-state-atom (atom {:available-service-ids #{"s0"} :healthy-service-ids #{"s0"}})]
(assert-immediate-success "deleted" fallback-state-atom request false false)))
(testing (str handler-name ":immediate-success-healthy")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{"s1"}})]
(assert-immediate-success "healthy" fallback-state-atom request true true)))
(testing (str handler-name ":immediate-success-exist")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})]
(assert-immediate-success "exist" fallback-state-atom request true false)))
(testing (str handler-name ":force-timeout-deleted")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{"s1"}})]
(assert-force-timeout timeout "deleted" fallback-state-atom request true true)))
(testing (str handler-name ":force-timeout-healthy")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})]
(assert-force-timeout timeout "healthy" fallback-state-atom request true false)))
(testing (str handler-name ":force-timeout-exist")
(let [fallback-state-atom (atom {:available-service-ids #{}} :healthy-service-ids #{})]
(assert-force-timeout timeout "exist" fallback-state-atom request false false)))
(testing (str handler-name ":success-with-large-sleep-duration")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})
goal-fallback-state {:available-service-ids #{} :healthy-service-ids #{}}
timeout 2000
update-delay 1000
request (assoc request :query-string (str "timeout=" timeout "&sleep-duration=" (* 10 timeout)))
_ (async/go
(async/<! (async/timeout update-delay))
(reset! fallback-state-atom goal-fallback-state))
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") false))
(is (= (get parsed-body "service-healthy?") false))
(is (get parsed-body "goal-success?"))
(is (<= update-delay (- timeout 50) (- end-time start-time) (+ timeout 50)))))
(testing (str handler-name ":success-with-update")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})
timeout 10000
update-delay 2000
request-query (assoc request :query-string (str "timeout=" timeout))
_ (async/go
(async/<! (async/timeout update-delay))
(reset! fallback-state-atom {:available-service-ids #{} :healthy-service-ids #{}}))
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request-query))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") false))
(is (= (get parsed-body "service-healthy?") false))
(is (get parsed-body "goal-success?"))
(is (<= update-delay (- end-time start-time) timeout))))
(testing (str handler-name ":non-integer-timeout-sleep-duration-params")
(let [fallback-state-atom (atom {:available-service-ids #{}})
timeout "Invalid timeout value"
sleep-duration "Invalid sleep-duration value"
request (assoc request :query-string (str "timeout=" timeout "&sleep-duration=" sleep-duration))
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (re-find #"timeout and sleep-duration must be integers" body))
(is (re-find (re-pattern (str ":timeout \"" timeout "\"")) body))
(is (re-find (re-pattern (str ":sleep-duration \"" sleep-duration "\"")) body))))
(testing (str handler-name ":timeout-required-param")
(let [fallback-state-atom (atom {:available-service-ids #{}})
request (assoc request :query-string "")
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (re-find #"timeout is a required query parameter" body))))))
(deftest test-work-stealing-handler
(let [test-service-id "test-service-id"
test-router-id "router-1"
instance-rpc-chan-factory (fn [response-status]
(let [instance-rpc-chan (async/chan 1)
work-stealing-chan (async/chan 1)]
(async/go
(let [instance-rpc-content (async/<! instance-rpc-chan)
{:keys [method service-id response-chan]} instance-rpc-content]
(is (= :offer method))
(is (= test-service-id service-id))
(async/>! response-chan work-stealing-chan)))
(async/go
(let [offer-params (async/<! work-stealing-chan)]
(is (= test-service-id (:service-id offer-params)))
(async/>!! (:response-chan offer-params) response-status)))
instance-rpc-chan))
test-cases [{:name "valid-parameters-rejected-response"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :promptly-rejected
:expected-status http-200-ok
:expected-body-fragments ["cid" "request-id" "response-status" "promptly-rejected"
test-service-id test-router-id]}
{:name "valid-parameters-success-response"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-200-ok
:expected-body-fragments ["cid" "request-id" "response-status" "success"
test-service-id test-router-id]}
{:name "missing-cid"
:request-body {:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-instance"
:request-body {:cid "cid-1"
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-request-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-router-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-service-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}]]
(doseq [{:keys [name request-body response-status expected-status expected-body-fragments]} test-cases]
(testing name
(let [instance-rpc-chan (instance-rpc-chan-factory response-status)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
request {:uri (str "/work-stealing")
:request-method :post
:body (StringBufferInputStream. (utils/clj->json (walk/stringify-keys request-body)))}
{:keys [status body]} (fa/<?? (work-stealing-handler populate-maintainer-chan! request))]
(is (= expected-status status))
(is (every? #(str/includes? (str body) %) expected-body-fragments)))))))
(deftest test-work-stealing-handler-cannot-find-channel
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"cid" "test-cid"
"instance" {"id" "test-instance-id", "service-id" test-service-id}
"request-id" "test-request-id"
"router-id" "test-router-id"
"service-id" test-service-id}))}
response-chan (work-stealing-handler populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :offer method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-404-not-found status)))))
(deftest test-work-stealing-handler-channel-put-failed
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"cid" "test-cid"
"instance" {"id" "test-instance-id", "service-id" test-service-id}
"request-id" "test-request-id"
"router-id" "test-router-id"
"service-id" test-service-id}))}
response-chan (work-stealing-handler populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)
work-stealing-chan (async/chan)]
(is (= :offer method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! work-stealing-chan)
(async/put! response-chan work-stealing-chan)
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-500-internal-server-error status)))))
(deftest test-get-router-state
(let [state-atom (atom nil)
query-state-fn (fn [] @state-atom)
test-fn (fn [router-id query-state-fn request]
(let [handler (wrap-handler-json-response get-router-state)]
(handler router-id query-state-fn request)))
router-id "test-router-id"]
(reset! state-atom {:state-data {}})
(testing "Getting router state"
(testing "should handle exceptions gracefully"
(let [bad-request {:scheme 1} ;; integer scheme will throw error
{:keys [status body]} (test-fn router-id query-state-fn bad-request)]
(is (str/includes? (str body) "Internal error"))
(is (= http-500-internal-server-error status))))
(testing "display router state"
(let [{:keys [status body]} (test-fn router-id query-state-fn {})]
(is (every? #(str/includes? (str body) %1)
["autoscaler" "autoscaling-multiplexer"
"codahale-reporters" "fallback" "interstitial" "kv-store" "leader" "local-usage"
"maintainer" "router-metrics" "scheduler" "statsd"])
(str "Body did not include necessary JSON keys:\n" body))
(is (= http-200-ok status)))))))
(deftest test-get-query-fn-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-query-fn-state)]
(testing "successful response"
(let [state {"autoscaler" "state"}
query-state-fn (constantly state)
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [query-state-fn (fn [] (throw (Exception. "from test")))
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-kv-store-state
(let [router-id "test-router-id"
include-flags #{}
test-fn (wrap-handler-json-response get-kv-store-state)]
(testing "successful response"
(let [kv-store (kv/new-local-kv-store {})
state (walk/stringify-keys (kv/state kv-store include-flags))
{:keys [body status]} (test-fn router-id kv-store {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [kv-store (Object.)
{:keys [body status]} (test-fn router-id kv-store {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-local-usage-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-local-usage-state)]
(testing "successful response"
(let [last-request-time-state {"foo" 1234, "bar" 7890}
last-request-time-agent (agent last-request-time-state)
{:keys [body status]} (test-fn router-id last-request-time-agent {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" last-request-time-state}))))
(testing "exception response"
(let [handler (core/wrap-error-handling #(test-fn router-id nil %))
{:keys [body status]} (handler {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-leader-state
(let [router-id "test-router-id"
leader-id-fn (constantly router-id)
test-fn (wrap-handler-json-response get-leader-state)]
(testing "successful response"
(let [leader?-fn (constantly true)
state {"leader?" (leader?-fn), "leader-id" (leader-id-fn)}
{:keys [body status]} (test-fn router-id leader?-fn leader-id-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [leader?-fn (fn [] (throw (Exception. "Test Exception")))
{:keys [body status]} (test-fn router-id leader?-fn leader-id-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-chan-latest-state-handler
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-chan-latest-state-handler)]
(testing "successful response"
(let [state-atom (atom nil)
query-state-fn (fn [] @state-atom)
state {"foo" "bar"}
_ (reset! state-atom state)
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-router-metrics-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-router-metrics-state)]
(testing "successful response"
(let [state {"router-metrics" "foo"}
router-metrics-state-fn (constantly state)
{:keys [body status]} (test-fn router-id router-metrics-state-fn {})]
(is (= http-200-ok status))
(is (= {"router-id" router-id "state" state}
(json/read-str body)))))
(testing "exception response"
(let [router-metrics-state-fn (fn [] (throw (Exception. "Test Exception")))
{:keys [body status]} (test-fn router-id router-metrics-state-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-query-chan-state-handler
(let [router-id "test-router-id"
test-fn (wrap-async-handler-json-response get-query-chan-state-handler)]
(testing "successful response"
(let [scheduler-chan (async/promise-chan)
state {"foo" "bar"}
_ (async/go
(let [{:keys [response-chan]} (async/<! scheduler-chan)]
(async/>! response-chan state)))
{:keys [body status]} (async/<!! (test-fn router-id scheduler-chan {}))]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-scheduler-state
(let [router-id "test-router-id"
scheduler (reify scheduler/ServiceScheduler
(state [_ _]
{:scheduler "state"}))
test-fn (wrap-handler-json-response get-scheduler-state)]
(testing "successful response"
(let [state (walk/stringify-keys (scheduler/state scheduler #{}))
{:keys [body status]} (test-fn router-id scheduler {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-statsd-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-statsd-state)]
(testing "successful response"
(let [state (walk/stringify-keys (statsd/state))
{:keys [body status]} (test-fn router-id {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-service-state
(let [router-id "router-id"
service-id "service-1"
local-usage-agent (agent {service-id {"last-request-time" "foo"}})
enable-work-stealing-support? (constantly true)]
(testing "returns 400 for missing service id"
(is (= http-400-bad-request
(:status (async/<!! (get-service-state router-id enable-work-stealing-support? nil local-usage-agent "" {} {}))))))
(let [instance-rpc-chan (async/chan 1)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
query-state-chan (async/chan 1)
query-work-stealing-chan (async/chan 1)
maintainer-state-chan (async/chan 1)
responder-state {:state "responder state"}
work-stealing-state {:state "work-stealing state"}
maintainer-state {:state "maintainer state"}
start-instance-rpc-fn (fn []
(async/go
(dotimes [_ 2]
(let [{:keys [method response-chan]} (async/<! instance-rpc-chan)]
(condp = method
:query-state (async/>! response-chan query-state-chan)
:query-work-stealing (async/>! response-chan query-work-stealing-chan))))))
start-query-chan-fn (fn []
(async/go
(let [{:keys [response-chan]} (async/<! query-state-chan)]
(async/>! response-chan responder-state)))
(async/go
(let [{:keys [response-chan]} (async/<! query-work-stealing-chan)]
(async/>! response-chan work-stealing-state))))
start-maintainer-fn (fn []
(async/go (let [{:keys [service-id response-chan]} (async/<! maintainer-state-chan)]
(async/>! response-chan (assoc maintainer-state :service-id service-id)))))
get-service-state (wrap-async-handler-json-response get-service-state)]
(start-instance-rpc-fn)
(start-query-chan-fn)
(start-maintainer-fn)
(let [query-sources {:autoscaler-state (fn [{:keys [service-id]}]
{:service-id service-id :source "autoscaler"})
:keyword-state :disabled
:maintainer-state maintainer-state-chan
:map-state {:foo "bar"}}
response (async/<!! (get-service-state router-id enable-work-stealing-support? populate-maintainer-chan!
local-usage-agent service-id query-sources {}))
service-state (json/read-str (:body response) :key-fn keyword)]
(is (= router-id (get-in service-state [:router-id])))
(is (= {:service-id service-id :source "autoscaler"} (get-in service-state [:state :autoscaler-state])))
(is (= (name :disabled) (get-in service-state [:state :keyword-state])))
(is (= {:last-request-time "foo"} (get-in service-state [:state :local-usage])))
(is (= (assoc maintainer-state :service-id service-id) (get-in service-state [:state :maintainer-state])))
(is (= {:foo "bar"} (get-in service-state [:state :map-state])))
(is (= responder-state (get-in service-state [:state :responder-state])))
(is (= work-stealing-state (get-in service-state [:state :work-stealing-state])))))))
(deftest test-acknowledge-consent-handler
(let [current-time-ms (System/currentTimeMillis)
clock (constantly current-time-ms)
test-token "www.example.com"
test-service-description {"cmd" "some-cmd", "cpus" 1, "mem" 1024}
token->service-description-template (fn [token]
(when (= token test-token)
(assoc test-service-description
"source-tokens" [(sd/source-tokens-entry test-token test-service-description)])))
token->token-metadata (fn [token] (when (= token test-token) {"owner" "user"}))
service-description->service-id (fn [service-description]
(str "service-" (count service-description) "." (count (str service-description))))
test-user "test-user"
test-service-id (-> test-service-description
(assoc "permitted-user" test-user
"run-as-user" test-user
"source-tokens" [(sd/source-tokens-entry test-token test-service-description)])
service-description->service-id)
request->consent-service-id (fn [request]
(if (some-> request (utils/request->host) (utils/authority->host) (= test-token))
test-service-id
"service-123.123456789"))
add-encoded-cookie (fn [response cookie-name cookie-value consent-expiry-days]
(assoc-in response [:cookie cookie-name] {:value cookie-value :age consent-expiry-days}))
consent-expiry-days 1
consent-cookie-value (fn consent-cookie-value [mode service-id token {:strs [owner]}]
(when mode
(-> [mode (clock)]
(concat (case mode
"service" (when service-id [service-id])
"token" (when (and owner token) [token owner])
nil))
vec)))
acknowledge-consent-handler-fn (fn [request]
(let [request' (-> request
(update :authorization/user #(or %1 test-user))
(update :request-method #(or %1 :post))
(update :scheme #(or %1 :http)))]
(acknowledge-consent-handler
token->service-description-template token->token-metadata
request->consent-service-id consent-cookie-value add-encoded-cookie
consent-expiry-days request')))]
(testing "unsupported request method"
(let [request {:request-method :get}
{:keys [body headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-405-method-not-allowed status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Only POST supported"))))
(testing "host and origin mismatch"
(let [request {:headers {"host" "www.example2.com"
"origin" (str "http://" test-token)}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Origin is not the same as the host"))))
(testing "referer and origin mismatch"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" "http://www.example2.com/consent"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Referer does not start with origin"))))
(testing "mismatch in x-requested-with"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "AJAX"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Header x-requested-with does not match expected value"))))
(testing "missing mode param"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing or invalid mode"))))
(testing "invalid mode param"
(let [request {:authorization/user test-user
:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "unsupported", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing or invalid mode"))))
(testing "missing service-id param"
(let [request {:authorization/user test-user
:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing service-id"))))
(testing "missing service description for token"
(let [test-host (str test-token ".test2")
request {:authorization/user test-user
:headers {"host" test-host
"origin" (str "http://" test-host)
"referer" (str "http://" test-host "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Unable to load description for token"))))
(testing "invalid service-id param"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Invalid service-id for specified token"))))
(testing "valid service mode request"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" test-service-id}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["service" current-time-ms test-service-id], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent") (str body))))
(testing "valid service mode request with missing origin"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" test-service-id}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["service" current-time-ms test-service-id], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent") (str body))))
(testing "valid token mode request"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "token"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["token" current-time-ms test-token "user"], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent"))))
(testing "valid token mode request with missing origin"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "token"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["token" current-time-ms test-token "user"], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent"))))))
(deftest test-render-consent-template
(let [context {:auth-user "test-user"
:consent-expiry-days 1
:service-description-template {"cmd" "some-cmd", "cpus" 1, "mem" 1024}
:service-id "service-5.97"
:target-url "http://www.example.com:6789/some-path"
:token "www.example.com"}
body (render-consent-template context)]
(is (str/includes? body "Run Web App? - Waiter"))
(is (str/includes? body "http://www.example.com:6789/some-path"))))
(deftest test-request-consent-handler
(let [request-time (t/now)
basic-service-description {"cmd" "some-cmd" "cpus" 1 "mem" 1024}
token->service-description-template
(fn [token]
(let [service-description (condp = token
"www.example.com" basic-service-description
"www.example-i0.com" (assoc basic-service-description
"interstitial-secs" 0)
"www.example-i10.com" (assoc basic-service-description
"interstitial-secs" 10)
nil)]
(cond-> service-description
(seq service-description)
(assoc "source-tokens" [(sd/source-tokens-entry token service-description)]))
service-description))
service-description->service-id (fn [service-description]
(str "service-" (count service-description) "." (count (str service-description))))
consent-expiry-days 1
test-user "test-user"
request->consent-service-id (fn [request]
(or (some-> request
(utils/request->host)
(utils/authority->host)
(token->service-description-template)
(assoc "permitted-user" test-user "run-as-user" test-user)
(service-description->service-id))
"service-123.123456789"))
request-consent-handler-fn (fn [request]
(let [request' (-> request
(update :authorization/user #(or %1 test-user))
(update :request-method #(or %1 :get)))]
(request-consent-handler
token->service-description-template request->consent-service-id
consent-expiry-days request')))
io-resource-fn (fn [file-path]
(is (= "web/consent.html" file-path))
(StringReader. "some-content"))
expected-service-id (fn [token]
(-> (token->service-description-template token)
(assoc "permitted-user" test-user "run-as-user" test-user)
service-description->service-id))
template-eval-factory (fn [scheme]
(fn [{:keys [token] :as data}]
(let [service-description-template (token->service-description-template token)]
(is (= {:auth-user test-user
:consent-expiry-days 1
:service-description-template service-description-template
:service-id (expected-service-id token)
:target-url (str scheme "://" token ":6789/some-path"
(when (some-> (get service-description-template "interstitial-secs") pos?)
(str "?" (interstitial/request-time->interstitial-param-string request-time))))
:token token}
data)))
"template:some-content"))]
(testing "unsupported request method"
(let [request {:authorization/user test-user
:request-method :post
:request-time request-time
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-405-method-not-allowed status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Only GET supported"))))
(testing "token without service description"
(let [request {:authorization/user test-user
:headers {"host" "www.example2.com:6789"}
:request-method :get
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-404-not-found status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Unable to load description for token"))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "http")]
(testing "token without service description - http scheme"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https scheme"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :https}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example-i0.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example-i10.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))))
(deftest test-eject-instance-cannot-find-channel
(let [notify-instance-killed-fn (fn [instance] (throw (ex-info "Unexpected call" {:instance instance})))
instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"instance" {"id" "test-instance-id", "service-id" test-service-id}
"period-in-ms" 1000
"reason" "eject"}))}
response-chan (eject-instance notify-instance-killed-fn populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :eject method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-400-bad-request status)))))
(deftest test-eject-killed-instance
(let [notify-instance-chan (async/promise-chan)
notify-instance-killed-fn (fn [instance] (async/>!! notify-instance-chan instance))
instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
instance {:id "test-instance-id"
:service-id test-service-id
:started-at nil}
request {:body (StringBufferInputStream.
(utils/clj->json
{"instance" instance
"period-in-ms" 1000
"reason" "killed"}))}]
(with-redefs []
(let [response-chan (eject-instance notify-instance-killed-fn populate-maintainer-chan! request)
eject-chan (async/promise-chan)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :eject method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/>!! response-chan eject-chan)))
(async/thread
(let [[{:keys [eject-period-ms instance-id]} repsonse-chan] (async/<!! eject-chan)]
(is (= 1000 eject-period-ms))
(is (= (:id instance) instance-id))
(async/>!! repsonse-chan :ejected)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-200-ok status))
(is (= instance (async/<!! notify-instance-chan))))))))
(deftest test-get-ejected-instances-cannot-find-channel
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
response-chan (get-ejected-instances populate-maintainer-chan! test-service-id {})]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :query-state method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-500-internal-server-error status)))))
| 69294 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.handler-test
(:require [clj-time.core :as t]
[clojure.core.async :as async]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.walk :as walk]
[full.async :as fa]
[plumbing.core :as pc]
[waiter.authorization :as authz]
[waiter.core :as core]
[waiter.handler :refer :all]
[waiter.interstitial :as interstitial]
[waiter.kv :as kv]
[waiter.scheduler :as scheduler]
[waiter.service-description :as sd]
[waiter.statsd :as statsd]
[waiter.status-codes :refer :all]
[waiter.test-helpers :refer :all]
[waiter.util.date-utils :as du]
[waiter.util.utils :as utils])
(:import (clojure.core.async.impl.channels ManyToManyChannel)
(clojure.lang ExceptionInfo)
(java.io StringBufferInputStream StringReader)
(java.util.concurrent Executors)))
(deftest test-wrap-https-redirect
(let [handler-response (Object.)
execute-request (fn execute-request-fn [test-request]
(let [request-handler-argument-atom (atom nil)
test-request-handler (fn request-handler-fn [request]
(reset! request-handler-argument-atom request)
handler-response)
test-response ((wrap-https-redirect test-request-handler) test-request)]
{:handled-request @request-handler-argument-atom
:response test-response}))]
(testing "no redirect"
(testing "http request with token https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"}
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY> <PASSWORD>.<KEY>"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "http request with waiter header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "true"}
:request-method :get
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY>"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" true}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with token https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY>"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with token https-redirect set to true"
(let [test-request {:headers {"host" "token.<EMAIL>"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY>.<EMAIL>"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with waiter-header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "false"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {"cpus" 1}
:token "<KEY>.<EMAIL>"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" false}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with waiter-header https-redirect set to true"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "true"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {"cpus" 1}
:token "<KEY>.<EMAIL>"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" true}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response)))))
(testing "https redirect"
(testing "http request with token https-redirect set to true"
(let [test-request {:headers {"host" "token.localtest.me:1234"}
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY> <PASSWORD>.<EMAIL> <PASSWORD>"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (nil? handled-request))
(is (= {:body ""
:headers {"Location" "https://token.localtest.me"}
:status http-307-temporary-redirect
:waiter/response-source :waiter}
response))))
(testing "http request with waiter header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "false"}
:request-method :get
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY>"
:token-metadata {"https-redirect" true}
:waiter-headers {"x-waiter-https-redirect" false}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (nil? handled-request))
(is (= {:body ""
:headers {"Location" "https://token.localtest.me"}
:status http-301-moved-permanently
:waiter/response-source :waiter}
response)))))))
(deftest test-wrap-https-redirect-acceptor
(testing "returns 301 with proper url if ws and https-redirect is true and uri is nil"
(let [handler (wrap-wss-redirect (fn [_] (is false "Not supposed to call this handler") true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY>"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
response-status (handler request)]
(is (= http-301-moved-permanently response-status))
(is (= http-301-moved-permanently (.getStatusCode upgrade-response)))
(is (= "https://token.localtest.me" (.getHeader upgrade-response "location")))
(is (= "https-redirect is enabled" (.getStatusReason upgrade-response)))))
(testing "returns 301 with proper url if ws and https-redirect is true and uri is set"
(let [handler (wrap-wss-redirect (fn [_] (is false "Not supposed to call this handler") true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY> <PASSWORD>.<KEY>"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
response-status (handler request)]
(is (= http-301-moved-permanently response-status))
(is (= http-301-moved-permanently (.getStatusCode upgrade-response)))
(is (= "https://token.localtest.me/random/uri/path" (.getHeader upgrade-response "location")))
(is (= "https-redirect is enabled" (.getStatusReason upgrade-response)))))
(testing "passes on to next handler if wss and https-redirect is true"
(let [handler (wrap-wss-redirect (fn [_] true))
request {:headers {"host" "token.localtest.me"}
:scheme :wss
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY> <PASSWORD>"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?))))
(testing "passes on to next handler if https-redirect is false for wss request"
(let [handler (wrap-wss-redirect (fn [_] true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :wss
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY> <PASSWORD>"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?))))
(testing "passes on to next handler if https-redirect is false for ws request"
(let [handler (wrap-wss-redirect (fn [_] true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "<KEY>"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?)))))
(deftest test-complete-async-handler
(testing "missing-request-id"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request {:basic-authentication {:src-router-id src-router-id}
:headers {"accept" "application/json"}
:route-params {:service-id service-id}
:uri (str "/waiter-async/complete//" service-id)}
async-request-terminate-fn (fn [_] (throw (Exception. "unexpected call!")))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "No request-id specified"))))
(testing "missing-service-id"
(let [src-router-id "src-router-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:headers {"accept" "application/json"}
:route-params {:request-id request-id}
:uri (str "/waiter-async/complete/" request-id "/")}
async-request-terminate-fn (fn [_] (throw (Exception. "unexpected call!")))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "No service-id specified"))))
(testing "valid-request-id"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:route-params {:request-id request-id, :service-id service-id}
:uri (str "/waiter-async/complete/" request-id "/" service-id)}
async-request-terminate-fn (fn [in-request-id] (= request-id in-request-id))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-200-ok status))
(is (= expected-json-response-headers headers))
(is (= {:request-id request-id, :success true} (pc/keywordize-map (json/read-str body))))))
(testing "unable-to-terminate-request"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:route-params {:request-id request-id, :service-id service-id}
:uri (str "/waiter-async/complete/" request-id "/" service-id)}
async-request-terminate-fn (fn [_] false)
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-200-ok status))
(is (= expected-json-response-headers headers))
(is (= {:request-id request-id, :success false} (pc/keywordize-map (json/read-str body)))))))
(deftest test-async-result-handler-errors
(let [my-router-id "my-router-id"
service-id "test-service-id"
make-route-params (fn [code]
{:host "host"
:location (when (not= code "missing-location") "location/1234")
:port "port"
:request-id (when (not= code "missing-request-id") "req-1234")
:router-id (when (not= code "missing-router-id") my-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})]
(testing "missing-location"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-location")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-request-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-request-id")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-router-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-router-id")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "error-in-checking-backend-status"
(let [request {:authorization/pricipal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:request-method :http-method
:route-params (make-route-params "local")}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:error (ex-info "backend-status-error" {:status http-502-bad-gateway})}))
async-trigger-terminate-fn (fn [in-router-id in-service-id in-request-id]
(is (= my-router-id in-router-id))
(is (= service-id in-service-id))
(is (= "req-1234" in-request-id)))
{:keys [body headers status]}
(async/<!!
(async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
(is (= http-502-bad-gateway status))
(is (= expected-json-response-headers headers))
(is (every? #(str/includes? body %) ["backend-status-error"]))))))
(deftest test-async-result-handler-with-return-codes
(let [my-router-id "my-router-id"
service-id "test-service-id"
remote-router-id "remote-router-id"
make-route-params (fn [code]
{:host "host"
:location (if (= code "local") "location/1234" "location/6789")
:port "port"
:request-id (if (= code "local") "req-1234" "req-6789")
:router-id (if (= code "local") my-router-id remote-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})
request-id-fn (fn [router-type] (if (= router-type "local") "req-1234" "req-6789"))]
(letfn [(execute-async-result-check
[{:keys [request-method return-status router-type]}]
(let [terminate-call-atom (atom false)
async-trigger-terminate-fn (fn [target-router-id in-service-id request-id]
(reset! terminate-call-atom true)
(is (= (if (= router-type "local") my-router-id remote-router-id) target-router-id))
(is (= service-id in-service-id))
(is (= (request-id-fn router-type) request-id)))
request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:request-method request-method,
:route-params (make-route-params router-type)}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:body "async-result-response", :headers {}, :status return-status}))
{:keys [status headers]}
(async/<!!
(async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
{:terminated @terminate-call-atom, :return-status status, :return-headers headers}))]
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-303-see-other, :router-type "local"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-303-see-other, :router-type "remote"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-303-see-other, :router-type "local"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-303-see-other, :router-type "remote"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-204-no-content, :router-type "local"})))
(is (= {:terminated true, :return-status http-404-not-found, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-404-not-found, :router-type "local"})))
(is (= {:terminated true, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-204-no-content, :router-type "remote"})))
(is (= {:terminated true, :return-status http-404-not-found, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-404-not-found, :router-type "remote"})))
(is (= {:terminated true, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "remote"}))))))
(deftest test-async-status-handler-errors
(let [my-router-id "my-router-id"
service-id "test-service-id"
make-route-params (fn [code]
{:host "host"
:location (when (not= code "missing-location") "location/1234")
:port "port"
:request-id (when (not= code "missing-request-id") "req-1234")
:router-id (when (not= code "missing-router-id") my-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})]
(testing "missing-code"
(let [request {:headers {"accept" "application/json"}
:query-string ""}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-location"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-location")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-request-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-request-id")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-router-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-router-id")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "error-in-checking-backend-status"
(let [request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:route-params (make-route-params "local")
:request-method :http-method}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:error (ex-info "backend-status-error" {:status http-400-bad-request})}))
async-trigger-terminate-fn nil
{:keys [body headers status]} (async/<!! (async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (every? #(str/includes? body %) ["backend-status-error"]))))))
(deftest test-async-status-handler-with-return-codes
(let [my-router-id "my-router-id"
service-id "test-service-id"
remote-router-id "remote-router-id"
make-route-params (fn [code]
{:host "host"
:location (if (= code "local") "query/location/1234" "query/location/6789")
:port "port"
:request-id (if (= code "local") "req-1234" "req-6789")
:router-id (if (= code "local") my-router-id remote-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})
request-id-fn (fn [router-type] (if (= router-type "local") "req-1234" "req-6789"))
result-location-fn (fn [router-type & {:keys [include-host-port] :or {include-host-port false}}]
(str (when include-host-port "http://www.example.com:8521")
"/path/to/result-" (if (= router-type "local") "1234" "6789")))
async-result-location (fn [router-type & {:keys [include-host-port location] :or {include-host-port false}}]
(if include-host-port
(result-location-fn router-type :include-host-port include-host-port)
(str "/waiter-async/result/" (request-id-fn router-type) "/"
(if (= router-type "local") my-router-id remote-router-id) "/"
service-id "/host/port"
(or location (result-location-fn router-type :include-host-port false)))))]
(letfn [(execute-async-status-check
[{:keys [request-method result-location return-status router-type]}]
(let [terminate-call-atom (atom false)
async-trigger-terminate-fn (fn [target-router-id in-service-id request-id]
(reset! terminate-call-atom true)
(is (= (if (= router-type "local") my-router-id remote-router-id) target-router-id))
(is (= service-id in-service-id))
(is (= (request-id-fn router-type) request-id)))
request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:request-method request-method
:route-params (make-route-params router-type)}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:body "status-check-response"
:headers (if (= return-status http-303-see-other) {"location" (or result-location (result-location-fn router-type))} {})
:status return-status}))
{:keys [status headers]}
(async/<!!
(async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
{:terminated @terminate-call-atom, :return-status status, :return-headers headers}))]
(is (= {:terminated false, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-200-ok, :router-type "local"})))
(let [result-location (async-result-location "local" :include-host-port false)]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/location/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/location/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "./another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "../another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "../../another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (str "http://www.example.com:1234" (async-result-location "local" :include-host-port true))]
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location result-location, :return-status http-303-see-other, :router-type "local"}))))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated false, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-200-ok, :router-type "remote"})))
(let [result-location (async-result-location "remote" :include-host-port false)]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :return-status http-303-see-other, :router-type "remote"}))))
(let [result-location (str "http://www.example.com:1234" (async-result-location "remote" :include-host-port true))]
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location result-location, :return-status http-303-see-other, :router-type "remote"}))))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-204-no-content, :router-type "local"})))
(is (= {:terminated false, :return-status http-404-not-found, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-404-not-found, :router-type "local"})))
(is (= {:terminated false, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-204-no-content, :router-type "remote"})))
(is (= {:terminated false, :return-status http-404-not-found, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-404-not-found, :router-type "remote"})))
(is (= {:terminated false, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "remote"}))))))
(deftest test-list-services-handler
(let [test-user "test-user"
test-user-services #{"service1" "service2" "service3" "service7" "service8" "service9" "service10"}
other-user-services #{"service4" "service5" "service6" "service11"}
healthy-services #{"service1" "service2" "service4" "service6" "service7" "service8" "service9" "service10" "service11"}
unhealthy-services #{"service2" "service3" "service5"}
service-id->references {"service1" {:sources [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
:type :token}
"service3" {:sources [{:token "t2.com" :version "v2"} {:token "t<KEY> <PASSWORD>.edu" :version "v3"}]
:type :token}
"service4" {:sources [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
:type :token}
"service5" {:sources [{:token "t1.org" :version "v1"} {:token "t3.edu" :version "v3"}]
:type :token}
"service7" {:sources [{:token "t1.org" :version "v2"} {:token "t2.com" :version "v1"}]
:type :token}
"service9" {:sources [{:token "t2.com" :version "v3"}]
:type :token}}
service-id->source-tokens {"service1" [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
"service3" [{:token "t2.com" :version "v2"} {:token "t<KEY>.<PASSWORD>" :version "v3"}]
"service4" [{:token "t<KEY>.org" :version "v1"} {:token "t<KEY>.com" :version "v2"}]
"service5" [{:token "t1.org" :version "v1"} {:token "t<KEY>.edu" :version "v3"}]
"service7" [{:token "t1.org" :version "v2"} {:token "t2.com" :version "v1"}]
"service9" [{:token "<PASSWORD>" :version "v3"}]}
all-services (set/union other-user-services test-user-services)
current-time (t/now)
query-state-fn (constantly {:all-available-service-ids all-services
:service-id->healthy-instances (pc/map-from-keys
(fn [service-id]
(let [instance-id-1 (str service-id ".i1")]
[{:flags []
:healthy? true
:host (str "127.0.0." (hash instance-id-1))
:id instance-id-1
:port (+ 1000 (rand 1000))
:service-id service-id
:started-at (du/date-to-str current-time)}]))
healthy-services)
:service-id->unhealthy-instances (pc/map-from-keys (constantly []) unhealthy-services)})
query-autoscaler-state-fn (constantly
(pc/map-from-keys
(fn [_] {:scale-amount (rand-nth [-1 0 1])})
test-user-services))
request {:authorization/user test-user}
instance-counts-present (fn [body]
(let [parsed-body (-> body (str) (json/read-str) (walk/keywordize-keys))]
(every? (fn [service-entry]
(is (contains? service-entry :instance-counts))
(is (every? #(contains? (get service-entry :instance-counts) %)
[:healthy-instances, :unhealthy-instances])))
parsed-body)))
prepend-waiter-url identity
entitlement-manager (reify authz/EntitlementManager
(authorized? [_ user action {:keys [service-id]}]
(let [id (subs service-id (count "service"))]
(and (str/includes? (str test-user id) user)
(= action :manage)
(some #(= % service-id) test-user-services)))))
retrieve-token-based-fallback-fn (constantly nil)
token->token-hash (constantly nil)
list-services-handler (wrap-handler-json-response list-services-handler)
assert-successful-json-response (fn [{:keys [body headers status]}]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (instance-counts-present body)))]
(letfn [(service-id->metrics-fn []
{})
(service-id->references-fn [service-id]
(get service-id->references service-id))
(service-id->service-description-fn [service-id & _]
(let [id (subs service-id (count "service"))]
{"cpus" (Integer/parseInt id)
"env" {"E_ID" (str "id-" id)}
"mem" (* 10 (Integer/parseInt id))
"metadata" {"m-id" (str "id-" id)}
"metric-group" (str "mg" id)
"run-as-user" (if (contains? test-user-services service-id) (str test-user id) "another-user")}))
(service-id->source-tokens-entries-fn [service-id]
(when (contains? service-id->source-tokens service-id)
(let [source-tokens (-> service-id service-id->source-tokens walk/stringify-keys)]
#{source-tokens})))]
(testing "list-services-handler:success-regular-user"
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= test-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))
(let [request (assoc request :authorization/user "test-user1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service10"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :authorization/user "test-user1" :query-string "run-as-user=test-user1.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service10"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (conj other-user-services "service1")
(->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user1.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (conj other-user-services "service1" "service10")
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-cpus"
(let [request (assoc request :query-string "cpus=1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-metric-group"
(let [request (assoc request :query-string "metric-group=mg3")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service3"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-metric-groups"
(let [request (assoc request :query-string "metric-group=mg1&metric-group=mg2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-single-env-variable"
(let [request (assoc request :query-string "env.E_ID=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-env-variables"
(let [request (assoc request :query-string "env.E_ID=id-1&env.E_ID=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-single-metadata-variable"
(let [request (assoc request :query-string "metadata.m-id=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-metadata-variables"
(let [request (assoc request :query-string "metadata.m-id=id-1&metadata.m-id=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-nested-parameters"
(let [request (assoc request :query-string "env.E_ID=id-1&metadata.m-id=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "env.E_ID=id-1&metadata.m-id=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-same-user"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-prefix-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=.*user.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-suffix-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=another.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-different-run-as-user-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user test-user :query-string "run-as-user=another.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:failure"
(let [query-state-fn (constantly {:all-available-service-ids #{"service1"}
:service-id->healthy-instances {"service1" []}})
request {:authorization/user test-user}
exception-message "Custom message from test case"
prepend-waiter-url (fn [_] (throw (ex-info exception-message {:status http-400-bad-request})))
list-services-handler (core/wrap-error-handling
#(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash %))
{:keys [body headers status]} (list-services-handler request)]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (str/includes? (str body) exception-message))))
(testing "list-services-handler:success-super-user-sees-all-apps"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ user action {:keys [service-id]}]
(and (= user test-user)
(= :manage action)
(contains? all-services service-id))))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(testing "list-services-handler:success-filter-tokens"
(doseq [[query-param filter-fn]
{"t1.com" #(= % "t1.com")
"t2.org" #(= % "t2.org")
"tn.none" #(= % "tn.none")
".*o.*" #(str/includes? % "o")
".*t.*" #(str/includes? % "t")
"t.*" #(str/starts-with? % "t")
".*com" #(str/ends-with? % "com")
".*org" #(str/ends-with? % "org")}]
(let [request (assoc request :query-string (str "token=" query-param))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(->> source-tokens (map :token) (some filter-fn))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-filter-version"
(doseq [[query-param filter-fn]
{"v1" #(= % "v1")
"v2" #(= % "v2")
"vn" #(= % "vn")
".*v.*" #(str/includes? % "v")
"v.*" #(str/starts-with? % "v")
".*1" #(str/ends-with? % "1")
".*2" #(str/ends-with? % "2")}]
(let [request (assoc request :query-string (str "token-version=" query-param))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(->> source-tokens (map :version) (some filter-fn))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-filter-token-and-version"
(let [request (assoc request :query-string "token=<KEY>&token-version=v<KEY>")
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(and (->> source-tokens (map :token) (some #(= % "t1")))
(->> source-tokens (map :version) (some #(= % "v1"))))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(testing "list-services-handler:include-healthy-instances"
(let [request (assoc request :query-string "include=healthy-instances")
{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)
service-id->healthy-instances (->> body
(json/read-str)
(walk/keywordize-keys)
(pc/map-from-vals :service-id)
(pc/map-vals #(get-in % [:instances :healthy-instances])))]
(assert-successful-json-response response)
(is (= test-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))
(doseq [service-id test-user-services]
(if (contains? healthy-services service-id)
(let [healthy-instances (get-in (query-state-fn) [:service-id->healthy-instances service-id])]
(is (= (map #(select-keys % [:host :id :port :started-at]) healthy-instances)
(get service-id->healthy-instances service-id))))
(is (empty? (get service-id->healthy-instances service-id))))))))))
(deftest test-delete-service-handler
(let [test-user "test-user"
test-service-id "service-1"
test-router-id "router-1"
allowed-to-manage-service?-fn (fn [service-id user] (and (= test-service-id service-id) (= test-user user)))
make-inter-router-requests-fn (constantly {})
fallback-state-atom (atom nil)]
(let [core-service-description {"run-as-user" test-user}
scheduler-interactions-thread-pool (Executors/newFixedThreadPool 1)]
(testing "delete-service-handler:success-regular-user"
(let [scheduler (reify scheduler/ServiceScheduler
(delete-service [_ service-id]
(is (= test-service-id service-id))
{:result :deleted
:message "Worked!"}))
request {:authorization/user test-user}
{:keys [body headers status]}
(async/<!!
(delete-service-handler test-router-id test-service-id core-service-description scheduler allowed-to-manage-service?-fn
scheduler-interactions-thread-pool make-inter-router-requests-fn fallback-state-atom request))]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (every? #(str/includes? (str body) (str %)) ["Worked!"]))))
(testing "delete-service-handler:success-regular-user-deleting-for-another-user"
(let [scheduler (reify scheduler/ServiceScheduler
(delete-service [_ service-id]
(is (= test-service-id service-id))
{:deploymentId "good"}))
request {:authorization/user "another-user"}]
(is (thrown-with-msg?
ExceptionInfo #"User not allowed to delete service"
(delete-service-handler test-router-id test-service-id core-service-description scheduler allowed-to-manage-service?-fn
scheduler-interactions-thread-pool make-inter-router-requests-fn fallback-state-atom request)))))
(.shutdown scheduler-interactions-thread-pool))))
(deftest test-service-await-handler
(let [handler-name "test-service-await-handler"
timeout 1000
request {:route-params {:service-id "s1" :goal-state "deleted"}
:basic-authentication {:src-router-id "r2"}
:request-method :get
:query-string (str "timeout=" 1000)}
assert-immediate-success
(fn [goal-state fallback-state-atom request expected-service-exists? expected-service-healthy?]
(let [request (assoc-in request [:route-params :goal-state] goal-state)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") expected-service-exists?))
(is (= (get parsed-body "service-healthy?") expected-service-healthy?))
(is (get parsed-body "goal-success?"))))
assert-force-timeout
(fn [timeout goal-state fallback-state-atom request expected-service-exists? expected-service-healthy?]
(let [request (assoc-in request [:route-params :goal-state] goal-state)
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") expected-service-exists?))
(is (= (get parsed-body "service-healthy?") expected-service-healthy?))
(is (not (get parsed-body "goal-success?")))
(is (>= (- end-time start-time) timeout))))]
(testing (str handler-name ":immediate-success-deleted")
(let [fallback-state-atom (atom {:available-service-ids #{"s0"} :healthy-service-ids #{"s0"}})]
(assert-immediate-success "deleted" fallback-state-atom request false false)))
(testing (str handler-name ":immediate-success-healthy")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{"s1"}})]
(assert-immediate-success "healthy" fallback-state-atom request true true)))
(testing (str handler-name ":immediate-success-exist")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})]
(assert-immediate-success "exist" fallback-state-atom request true false)))
(testing (str handler-name ":force-timeout-deleted")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{"s1"}})]
(assert-force-timeout timeout "deleted" fallback-state-atom request true true)))
(testing (str handler-name ":force-timeout-healthy")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})]
(assert-force-timeout timeout "healthy" fallback-state-atom request true false)))
(testing (str handler-name ":force-timeout-exist")
(let [fallback-state-atom (atom {:available-service-ids #{}} :healthy-service-ids #{})]
(assert-force-timeout timeout "exist" fallback-state-atom request false false)))
(testing (str handler-name ":success-with-large-sleep-duration")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})
goal-fallback-state {:available-service-ids #{} :healthy-service-ids #{}}
timeout 2000
update-delay 1000
request (assoc request :query-string (str "timeout=" timeout "&sleep-duration=" (* 10 timeout)))
_ (async/go
(async/<! (async/timeout update-delay))
(reset! fallback-state-atom goal-fallback-state))
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") false))
(is (= (get parsed-body "service-healthy?") false))
(is (get parsed-body "goal-success?"))
(is (<= update-delay (- timeout 50) (- end-time start-time) (+ timeout 50)))))
(testing (str handler-name ":success-with-update")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})
timeout 10000
update-delay 2000
request-query (assoc request :query-string (str "timeout=" timeout))
_ (async/go
(async/<! (async/timeout update-delay))
(reset! fallback-state-atom {:available-service-ids #{} :healthy-service-ids #{}}))
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request-query))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") false))
(is (= (get parsed-body "service-healthy?") false))
(is (get parsed-body "goal-success?"))
(is (<= update-delay (- end-time start-time) timeout))))
(testing (str handler-name ":non-integer-timeout-sleep-duration-params")
(let [fallback-state-atom (atom {:available-service-ids #{}})
timeout "Invalid timeout value"
sleep-duration "Invalid sleep-duration value"
request (assoc request :query-string (str "timeout=" timeout "&sleep-duration=" sleep-duration))
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (re-find #"timeout and sleep-duration must be integers" body))
(is (re-find (re-pattern (str ":timeout \"" timeout "\"")) body))
(is (re-find (re-pattern (str ":sleep-duration \"" sleep-duration "\"")) body))))
(testing (str handler-name ":timeout-required-param")
(let [fallback-state-atom (atom {:available-service-ids #{}})
request (assoc request :query-string "")
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (re-find #"timeout is a required query parameter" body))))))
(deftest test-work-stealing-handler
(let [test-service-id "test-service-id"
test-router-id "router-1"
instance-rpc-chan-factory (fn [response-status]
(let [instance-rpc-chan (async/chan 1)
work-stealing-chan (async/chan 1)]
(async/go
(let [instance-rpc-content (async/<! instance-rpc-chan)
{:keys [method service-id response-chan]} instance-rpc-content]
(is (= :offer method))
(is (= test-service-id service-id))
(async/>! response-chan work-stealing-chan)))
(async/go
(let [offer-params (async/<! work-stealing-chan)]
(is (= test-service-id (:service-id offer-params)))
(async/>!! (:response-chan offer-params) response-status)))
instance-rpc-chan))
test-cases [{:name "valid-parameters-rejected-response"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :promptly-rejected
:expected-status http-200-ok
:expected-body-fragments ["cid" "request-id" "response-status" "promptly-rejected"
test-service-id test-router-id]}
{:name "valid-parameters-success-response"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-200-ok
:expected-body-fragments ["cid" "request-id" "response-status" "success"
test-service-id test-router-id]}
{:name "missing-cid"
:request-body {:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-instance"
:request-body {:cid "cid-1"
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-request-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-router-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-service-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}]]
(doseq [{:keys [name request-body response-status expected-status expected-body-fragments]} test-cases]
(testing name
(let [instance-rpc-chan (instance-rpc-chan-factory response-status)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
request {:uri (str "/work-stealing")
:request-method :post
:body (StringBufferInputStream. (utils/clj->json (walk/stringify-keys request-body)))}
{:keys [status body]} (fa/<?? (work-stealing-handler populate-maintainer-chan! request))]
(is (= expected-status status))
(is (every? #(str/includes? (str body) %) expected-body-fragments)))))))
(deftest test-work-stealing-handler-cannot-find-channel
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"cid" "test-cid"
"instance" {"id" "test-instance-id", "service-id" test-service-id}
"request-id" "test-request-id"
"router-id" "test-router-id"
"service-id" test-service-id}))}
response-chan (work-stealing-handler populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :offer method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-404-not-found status)))))
(deftest test-work-stealing-handler-channel-put-failed
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"cid" "test-cid"
"instance" {"id" "test-instance-id", "service-id" test-service-id}
"request-id" "test-request-id"
"router-id" "test-router-id"
"service-id" test-service-id}))}
response-chan (work-stealing-handler populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)
work-stealing-chan (async/chan)]
(is (= :offer method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! work-stealing-chan)
(async/put! response-chan work-stealing-chan)
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-500-internal-server-error status)))))
(deftest test-get-router-state
(let [state-atom (atom nil)
query-state-fn (fn [] @state-atom)
test-fn (fn [router-id query-state-fn request]
(let [handler (wrap-handler-json-response get-router-state)]
(handler router-id query-state-fn request)))
router-id "test-router-id"]
(reset! state-atom {:state-data {}})
(testing "Getting router state"
(testing "should handle exceptions gracefully"
(let [bad-request {:scheme 1} ;; integer scheme will throw error
{:keys [status body]} (test-fn router-id query-state-fn bad-request)]
(is (str/includes? (str body) "Internal error"))
(is (= http-500-internal-server-error status))))
(testing "display router state"
(let [{:keys [status body]} (test-fn router-id query-state-fn {})]
(is (every? #(str/includes? (str body) %1)
["autoscaler" "autoscaling-multiplexer"
"codahale-reporters" "fallback" "interstitial" "kv-store" "leader" "local-usage"
"maintainer" "router-metrics" "scheduler" "statsd"])
(str "Body did not include necessary JSON keys:\n" body))
(is (= http-200-ok status)))))))
(deftest test-get-query-fn-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-query-fn-state)]
(testing "successful response"
(let [state {"autoscaler" "state"}
query-state-fn (constantly state)
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [query-state-fn (fn [] (throw (Exception. "from test")))
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-kv-store-state
(let [router-id "test-router-id"
include-flags #{}
test-fn (wrap-handler-json-response get-kv-store-state)]
(testing "successful response"
(let [kv-store (kv/new-local-kv-store {})
state (walk/stringify-keys (kv/state kv-store include-flags))
{:keys [body status]} (test-fn router-id kv-store {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [kv-store (Object.)
{:keys [body status]} (test-fn router-id kv-store {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-local-usage-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-local-usage-state)]
(testing "successful response"
(let [last-request-time-state {"foo" 1234, "bar" 7890}
last-request-time-agent (agent last-request-time-state)
{:keys [body status]} (test-fn router-id last-request-time-agent {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" last-request-time-state}))))
(testing "exception response"
(let [handler (core/wrap-error-handling #(test-fn router-id nil %))
{:keys [body status]} (handler {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-leader-state
(let [router-id "test-router-id"
leader-id-fn (constantly router-id)
test-fn (wrap-handler-json-response get-leader-state)]
(testing "successful response"
(let [leader?-fn (constantly true)
state {"leader?" (leader?-fn), "leader-id" (leader-id-fn)}
{:keys [body status]} (test-fn router-id leader?-fn leader-id-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [leader?-fn (fn [] (throw (Exception. "Test Exception")))
{:keys [body status]} (test-fn router-id leader?-fn leader-id-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-chan-latest-state-handler
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-chan-latest-state-handler)]
(testing "successful response"
(let [state-atom (atom nil)
query-state-fn (fn [] @state-atom)
state {"foo" "bar"}
_ (reset! state-atom state)
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-router-metrics-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-router-metrics-state)]
(testing "successful response"
(let [state {"router-metrics" "foo"}
router-metrics-state-fn (constantly state)
{:keys [body status]} (test-fn router-id router-metrics-state-fn {})]
(is (= http-200-ok status))
(is (= {"router-id" router-id "state" state}
(json/read-str body)))))
(testing "exception response"
(let [router-metrics-state-fn (fn [] (throw (Exception. "Test Exception")))
{:keys [body status]} (test-fn router-id router-metrics-state-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-query-chan-state-handler
(let [router-id "test-router-id"
test-fn (wrap-async-handler-json-response get-query-chan-state-handler)]
(testing "successful response"
(let [scheduler-chan (async/promise-chan)
state {"foo" "bar"}
_ (async/go
(let [{:keys [response-chan]} (async/<! scheduler-chan)]
(async/>! response-chan state)))
{:keys [body status]} (async/<!! (test-fn router-id scheduler-chan {}))]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-scheduler-state
(let [router-id "test-router-id"
scheduler (reify scheduler/ServiceScheduler
(state [_ _]
{:scheduler "state"}))
test-fn (wrap-handler-json-response get-scheduler-state)]
(testing "successful response"
(let [state (walk/stringify-keys (scheduler/state scheduler #{}))
{:keys [body status]} (test-fn router-id scheduler {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-statsd-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-statsd-state)]
(testing "successful response"
(let [state (walk/stringify-keys (statsd/state))
{:keys [body status]} (test-fn router-id {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-service-state
(let [router-id "router-id"
service-id "service-1"
local-usage-agent (agent {service-id {"last-request-time" "foo"}})
enable-work-stealing-support? (constantly true)]
(testing "returns 400 for missing service id"
(is (= http-400-bad-request
(:status (async/<!! (get-service-state router-id enable-work-stealing-support? nil local-usage-agent "" {} {}))))))
(let [instance-rpc-chan (async/chan 1)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
query-state-chan (async/chan 1)
query-work-stealing-chan (async/chan 1)
maintainer-state-chan (async/chan 1)
responder-state {:state "responder state"}
work-stealing-state {:state "work-stealing state"}
maintainer-state {:state "maintainer state"}
start-instance-rpc-fn (fn []
(async/go
(dotimes [_ 2]
(let [{:keys [method response-chan]} (async/<! instance-rpc-chan)]
(condp = method
:query-state (async/>! response-chan query-state-chan)
:query-work-stealing (async/>! response-chan query-work-stealing-chan))))))
start-query-chan-fn (fn []
(async/go
(let [{:keys [response-chan]} (async/<! query-state-chan)]
(async/>! response-chan responder-state)))
(async/go
(let [{:keys [response-chan]} (async/<! query-work-stealing-chan)]
(async/>! response-chan work-stealing-state))))
start-maintainer-fn (fn []
(async/go (let [{:keys [service-id response-chan]} (async/<! maintainer-state-chan)]
(async/>! response-chan (assoc maintainer-state :service-id service-id)))))
get-service-state (wrap-async-handler-json-response get-service-state)]
(start-instance-rpc-fn)
(start-query-chan-fn)
(start-maintainer-fn)
(let [query-sources {:autoscaler-state (fn [{:keys [service-id]}]
{:service-id service-id :source "autoscaler"})
:keyword-state :disabled
:maintainer-state maintainer-state-chan
:map-state {:foo "bar"}}
response (async/<!! (get-service-state router-id enable-work-stealing-support? populate-maintainer-chan!
local-usage-agent service-id query-sources {}))
service-state (json/read-str (:body response) :key-fn keyword)]
(is (= router-id (get-in service-state [:router-id])))
(is (= {:service-id service-id :source "autoscaler"} (get-in service-state [:state :autoscaler-state])))
(is (= (name :disabled) (get-in service-state [:state :keyword-state])))
(is (= {:last-request-time "foo"} (get-in service-state [:state :local-usage])))
(is (= (assoc maintainer-state :service-id service-id) (get-in service-state [:state :maintainer-state])))
(is (= {:foo "bar"} (get-in service-state [:state :map-state])))
(is (= responder-state (get-in service-state [:state :responder-state])))
(is (= work-stealing-state (get-in service-state [:state :work-stealing-state])))))))
(deftest test-acknowledge-consent-handler
(let [current-time-ms (System/currentTimeMillis)
clock (constantly current-time-ms)
test-token "<PASSWORD>"
test-service-description {"cmd" "some-cmd", "cpus" 1, "mem" 1024}
token->service-description-template (fn [token]
(when (= token test-token)
(assoc test-service-description
"source-tokens" [(sd/source-tokens-entry test-token test-service-description)])))
token->token-metadata (fn [token] (when (= token test-token) {"owner" "user"}))
service-description->service-id (fn [service-description]
(str "service-" (count service-description) "." (count (str service-description))))
test-user "test-user"
test-service-id (-> test-service-description
(assoc "permitted-user" test-user
"run-as-user" test-user
"source-tokens" [(sd/source-tokens-entry test-token test-service-description)])
service-description->service-id)
request->consent-service-id (fn [request]
(if (some-> request (utils/request->host) (utils/authority->host) (= test-token))
test-service-id
"service-123.123456789"))
add-encoded-cookie (fn [response cookie-name cookie-value consent-expiry-days]
(assoc-in response [:cookie cookie-name] {:value cookie-value :age consent-expiry-days}))
consent-expiry-days 1
consent-cookie-value (fn consent-cookie-value [mode service-id token {:strs [owner]}]
(when mode
(-> [mode (clock)]
(concat (case mode
"service" (when service-id [service-id])
"token" (when (and owner token) [token owner])
nil))
vec)))
acknowledge-consent-handler-fn (fn [request]
(let [request' (-> request
(update :authorization/user #(or %1 test-user))
(update :request-method #(or %1 :post))
(update :scheme #(or %1 :http)))]
(acknowledge-consent-handler
token->service-description-template token->token-metadata
request->consent-service-id consent-cookie-value add-encoded-cookie
consent-expiry-days request')))]
(testing "unsupported request method"
(let [request {:request-method :get}
{:keys [body headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-405-method-not-allowed status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Only POST supported"))))
(testing "host and origin mismatch"
(let [request {:headers {"host" "www.example2.com"
"origin" (str "http://" test-token)}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Origin is not the same as the host"))))
(testing "referer and origin mismatch"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" "http://www.example2.com/consent"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Referer does not start with origin"))))
(testing "mismatch in x-requested-with"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "AJAX"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Header x-requested-with does not match expected value"))))
(testing "missing mode param"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing or invalid mode"))))
(testing "invalid mode param"
(let [request {:authorization/user test-user
:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "unsupported", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing or invalid mode"))))
(testing "missing service-id param"
(let [request {:authorization/user test-user
:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing service-id"))))
(testing "missing service description for token"
(let [test-host (str test-token ".test2")
request {:authorization/user test-user
:headers {"host" test-host
"origin" (str "http://" test-host)
"referer" (str "http://" test-host "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Unable to load description for token"))))
(testing "invalid service-id param"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":<PASSWORD>")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Invalid service-id for specified token"))))
(testing "valid service mode request"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1<PASSWORD>")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" test-service-id}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["service" current-time-ms test-service-id], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent") (str body))))
(testing "valid service mode request with missing origin"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" test-service-id}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["service" current-time-ms test-service-id], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent") (str body))))
(testing "valid token mode request"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "token"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["token" current-time-ms test-token "user"], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent"))))
(testing "valid token mode request with missing origin"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "token"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["token" current-time-ms test-token "user"], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent"))))))
(deftest test-render-consent-template
(let [context {:auth-user "test-user"
:consent-expiry-days 1
:service-description-template {"cmd" "some-cmd", "cpus" 1, "mem" 1024}
:service-id "service-5.97"
:target-url "http://www.example.com:6789/some-path"
:token "<PASSWORD>"}
body (render-consent-template context)]
(is (str/includes? body "Run Web App? - Waiter"))
(is (str/includes? body "http://www.example.com:6789/some-path"))))
(deftest test-request-consent-handler
(let [request-time (t/now)
basic-service-description {"cmd" "some-cmd" "cpus" 1 "mem" 1024}
token->service-description-template
(fn [token]
(let [service-description (condp = token
"www.example.com" basic-service-description
"www.example-i0.com" (assoc basic-service-description
"interstitial-secs" 0)
"www.example-i10.com" (assoc basic-service-description
"interstitial-secs" 10)
nil)]
(cond-> service-description
(seq service-description)
(assoc "source-tokens" [(sd/source-tokens-entry token service-description)]))
service-description))
service-description->service-id (fn [service-description]
(str "service-" (count service-description) "." (count (str service-description))))
consent-expiry-days 1
test-user "test-user"
request->consent-service-id (fn [request]
(or (some-> request
(utils/request->host)
(utils/authority->host)
(token->service-description-template)
(assoc "permitted-user" test-user "run-as-user" test-user)
(service-description->service-id))
"service-123.123456789"))
request-consent-handler-fn (fn [request]
(let [request' (-> request
(update :authorization/user #(or %1 test-user))
(update :request-method #(or %1 :get)))]
(request-consent-handler
token->service-description-template request->consent-service-id
consent-expiry-days request')))
io-resource-fn (fn [file-path]
(is (= "web/consent.html" file-path))
(StringReader. "some-content"))
expected-service-id (fn [token]
(-> (token->service-description-template token)
(assoc "permitted-user" test-user "run-as-user" test-user)
service-description->service-id))
template-eval-factory (fn [scheme]
(fn [{:keys [token] :as data}]
(let [service-description-template (token->service-description-template token)]
(is (= {:auth-user test-user
:consent-expiry-days 1
:service-description-template service-description-template
:service-id (expected-service-id token)
:target-url (str scheme "://" token ":6789/some-path"
(when (some-> (get service-description-template "interstitial-secs") pos?)
(str "?" (interstitial/request-time->interstitial-param-string request-time))))
:token token}
data)))
"template:some-content"))]
(testing "unsupported request method"
(let [request {:authorization/user test-user
:request-method :post
:request-time request-time
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-405-method-not-allowed status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Only GET supported"))))
(testing "token without service description"
(let [request {:authorization/user test-user
:headers {"host" "www.example2.com:6789"}
:request-method :get
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-404-not-found status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Unable to load description for token"))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "http")]
(testing "token without service description - http scheme"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https scheme"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :https}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example-i0.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example-i10.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))))
(deftest test-eject-instance-cannot-find-channel
(let [notify-instance-killed-fn (fn [instance] (throw (ex-info "Unexpected call" {:instance instance})))
instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"instance" {"id" "test-instance-id", "service-id" test-service-id}
"period-in-ms" 1000
"reason" "eject"}))}
response-chan (eject-instance notify-instance-killed-fn populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :eject method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-400-bad-request status)))))
(deftest test-eject-killed-instance
(let [notify-instance-chan (async/promise-chan)
notify-instance-killed-fn (fn [instance] (async/>!! notify-instance-chan instance))
instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
instance {:id "test-instance-id"
:service-id test-service-id
:started-at nil}
request {:body (StringBufferInputStream.
(utils/clj->json
{"instance" instance
"period-in-ms" 1000
"reason" "killed"}))}]
(with-redefs []
(let [response-chan (eject-instance notify-instance-killed-fn populate-maintainer-chan! request)
eject-chan (async/promise-chan)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :eject method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/>!! response-chan eject-chan)))
(async/thread
(let [[{:keys [eject-period-ms instance-id]} repsonse-chan] (async/<!! eject-chan)]
(is (= 1000 eject-period-ms))
(is (= (:id instance) instance-id))
(async/>!! repsonse-chan :ejected)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-200-ok status))
(is (= instance (async/<!! notify-instance-chan))))))))
(deftest test-get-ejected-instances-cannot-find-channel
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
response-chan (get-ejected-instances populate-maintainer-chan! test-service-id {})]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :query-state method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-500-internal-server-error status)))))
| true | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.handler-test
(:require [clj-time.core :as t]
[clojure.core.async :as async]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.walk :as walk]
[full.async :as fa]
[plumbing.core :as pc]
[waiter.authorization :as authz]
[waiter.core :as core]
[waiter.handler :refer :all]
[waiter.interstitial :as interstitial]
[waiter.kv :as kv]
[waiter.scheduler :as scheduler]
[waiter.service-description :as sd]
[waiter.statsd :as statsd]
[waiter.status-codes :refer :all]
[waiter.test-helpers :refer :all]
[waiter.util.date-utils :as du]
[waiter.util.utils :as utils])
(:import (clojure.core.async.impl.channels ManyToManyChannel)
(clojure.lang ExceptionInfo)
(java.io StringBufferInputStream StringReader)
(java.util.concurrent Executors)))
(deftest test-wrap-https-redirect
(let [handler-response (Object.)
execute-request (fn execute-request-fn [test-request]
(let [request-handler-argument-atom (atom nil)
test-request-handler (fn request-handler-fn [request]
(reset! request-handler-argument-atom request)
handler-response)
test-response ((wrap-https-redirect test-request-handler) test-request)]
{:handled-request @request-handler-argument-atom
:response test-response}))]
(testing "no redirect"
(testing "http request with token https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"}
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI.PI:KEY:<KEY>END_PI"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "http request with waiter header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "true"}
:request-method :get
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" true}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with token https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with token https-redirect set to true"
(let [test-request {:headers {"host" "token.PI:EMAIL:<EMAIL>END_PI"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI.PI:PASSWORD:<EMAIL>END_PI"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with waiter-header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "false"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {"cpus" 1}
:token "PI:KEY:<KEY>END_PI.PI:PASSWORD:<EMAIL>END_PI"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" false}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response))))
(testing "https request with waiter-header https-redirect set to true"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "true"}
:scheme :https
:waiter-discovery {:passthrough-headers {}
:service-description-template {"cpus" 1}
:token "PI:KEY:<KEY>END_PI.PI:PASSWORD:<EMAIL>END_PI"
:token-metadata {"https-redirect" false}
:waiter-headers {"x-waiter-https-redirect" true}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (= test-request handled-request))
(is (= handler-response response)))))
(testing "https redirect"
(testing "http request with token https-redirect set to true"
(let [test-request {:headers {"host" "token.localtest.me:1234"}
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI.PI:EMAIL:<EMAIL>END_PI PI:PASSWORD:<PASSWORD>END_PI"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (nil? handled-request))
(is (= {:body ""
:headers {"Location" "https://token.localtest.me"}
:status http-307-temporary-redirect
:waiter/response-source :waiter}
response))))
(testing "http request with waiter header https-redirect set to false"
(let [test-request {:headers {"host" "token.localtest.me"
"x-waiter-https-redirect" "false"}
:request-method :get
:scheme :http
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI"
:token-metadata {"https-redirect" true}
:waiter-headers {"x-waiter-https-redirect" false}}}
{:keys [handled-request response]} (execute-request test-request)]
(is (nil? handled-request))
(is (= {:body ""
:headers {"Location" "https://token.localtest.me"}
:status http-301-moved-permanently
:waiter/response-source :waiter}
response)))))))
(deftest test-wrap-https-redirect-acceptor
(testing "returns 301 with proper url if ws and https-redirect is true and uri is nil"
(let [handler (wrap-wss-redirect (fn [_] (is false "Not supposed to call this handler") true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
response-status (handler request)]
(is (= http-301-moved-permanently response-status))
(is (= http-301-moved-permanently (.getStatusCode upgrade-response)))
(is (= "https://token.localtest.me" (.getHeader upgrade-response "location")))
(is (= "https-redirect is enabled" (.getStatusReason upgrade-response)))))
(testing "returns 301 with proper url if ws and https-redirect is true and uri is set"
(let [handler (wrap-wss-redirect (fn [_] (is false "Not supposed to call this handler") true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI.PI:KEY:<KEY>END_PI"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
response-status (handler request)]
(is (= http-301-moved-permanently response-status))
(is (= http-301-moved-permanently (.getStatusCode upgrade-response)))
(is (= "https://token.localtest.me/random/uri/path" (.getHeader upgrade-response "location")))
(is (= "https-redirect is enabled" (.getStatusReason upgrade-response)))))
(testing "passes on to next handler if wss and https-redirect is true"
(let [handler (wrap-wss-redirect (fn [_] true))
request {:headers {"host" "token.localtest.me"}
:scheme :wss
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI"
:token-metadata {"https-redirect" true}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?))))
(testing "passes on to next handler if https-redirect is false for wss request"
(let [handler (wrap-wss-redirect (fn [_] true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :wss
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:KEY:<KEY>END_PI PI:EMAIL:<PASSWORD>END_PI"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?))))
(testing "passes on to next handler if https-redirect is false for ws request"
(let [handler (wrap-wss-redirect (fn [_] true))
upgrade-response (reified-upgrade-response)
request {:headers {"host" "token.localtest.me"}
:scheme :ws
:upgrade-response upgrade-response
:uri "/random/uri/path"
:waiter-discovery {:passthrough-headers {}
:service-description-template {}
:token "PI:EMAIL:<KEY>END_PI"
:token-metadata {"https-redirect" false}
:waiter-headers {}}}
success? (handler request)]
(is (true? success?)))))
(deftest test-complete-async-handler
(testing "missing-request-id"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request {:basic-authentication {:src-router-id src-router-id}
:headers {"accept" "application/json"}
:route-params {:service-id service-id}
:uri (str "/waiter-async/complete//" service-id)}
async-request-terminate-fn (fn [_] (throw (Exception. "unexpected call!")))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "No request-id specified"))))
(testing "missing-service-id"
(let [src-router-id "src-router-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:headers {"accept" "application/json"}
:route-params {:request-id request-id}
:uri (str "/waiter-async/complete/" request-id "/")}
async-request-terminate-fn (fn [_] (throw (Exception. "unexpected call!")))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "No service-id specified"))))
(testing "valid-request-id"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:route-params {:request-id request-id, :service-id service-id}
:uri (str "/waiter-async/complete/" request-id "/" service-id)}
async-request-terminate-fn (fn [in-request-id] (= request-id in-request-id))
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-200-ok status))
(is (= expected-json-response-headers headers))
(is (= {:request-id request-id, :success true} (pc/keywordize-map (json/read-str body))))))
(testing "unable-to-terminate-request"
(let [src-router-id "src-router-id"
service-id "test-service-id"
request-id "test-req-123456"
request {:basic-authentication {:src-router-id src-router-id}
:route-params {:request-id request-id, :service-id service-id}
:uri (str "/waiter-async/complete/" request-id "/" service-id)}
async-request-terminate-fn (fn [_] false)
{:keys [body headers status]} (complete-async-handler async-request-terminate-fn request)]
(is (= http-200-ok status))
(is (= expected-json-response-headers headers))
(is (= {:request-id request-id, :success false} (pc/keywordize-map (json/read-str body)))))))
(deftest test-async-result-handler-errors
(let [my-router-id "my-router-id"
service-id "test-service-id"
make-route-params (fn [code]
{:host "host"
:location (when (not= code "missing-location") "location/1234")
:port "port"
:request-id (when (not= code "missing-request-id") "req-1234")
:router-id (when (not= code "missing-router-id") my-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})]
(testing "missing-location"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-location")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-request-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-request-id")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-router-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-router-id")}
{:keys [body headers status]}
(async/<!!
(async-result-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "error-in-checking-backend-status"
(let [request {:authorization/pricipal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:request-method :http-method
:route-params (make-route-params "local")}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:error (ex-info "backend-status-error" {:status http-502-bad-gateway})}))
async-trigger-terminate-fn (fn [in-router-id in-service-id in-request-id]
(is (= my-router-id in-router-id))
(is (= service-id in-service-id))
(is (= "req-1234" in-request-id)))
{:keys [body headers status]}
(async/<!!
(async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
(is (= http-502-bad-gateway status))
(is (= expected-json-response-headers headers))
(is (every? #(str/includes? body %) ["backend-status-error"]))))))
(deftest test-async-result-handler-with-return-codes
(let [my-router-id "my-router-id"
service-id "test-service-id"
remote-router-id "remote-router-id"
make-route-params (fn [code]
{:host "host"
:location (if (= code "local") "location/1234" "location/6789")
:port "port"
:request-id (if (= code "local") "req-1234" "req-6789")
:router-id (if (= code "local") my-router-id remote-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})
request-id-fn (fn [router-type] (if (= router-type "local") "req-1234" "req-6789"))]
(letfn [(execute-async-result-check
[{:keys [request-method return-status router-type]}]
(let [terminate-call-atom (atom false)
async-trigger-terminate-fn (fn [target-router-id in-service-id request-id]
(reset! terminate-call-atom true)
(is (= (if (= router-type "local") my-router-id remote-router-id) target-router-id))
(is (= service-id in-service-id))
(is (= (request-id-fn router-type) request-id)))
request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:request-method request-method,
:route-params (make-route-params router-type)}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:body "async-result-response", :headers {}, :status return-status}))
{:keys [status headers]}
(async/<!!
(async-result-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
{:terminated @terminate-call-atom, :return-status status, :return-headers headers}))]
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-303-see-other, :router-type "local"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-303-see-other, :router-type "remote"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :get, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-303-see-other, :router-type "local"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-303-see-other, :router-type "remote"})))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-result-check {:request-method :post, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-204-no-content, :router-type "local"})))
(is (= {:terminated true, :return-status http-404-not-found, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-404-not-found, :router-type "local"})))
(is (= {:terminated true, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-204-no-content, :router-type "remote"})))
(is (= {:terminated true, :return-status http-404-not-found, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-404-not-found, :router-type "remote"})))
(is (= {:terminated true, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-result-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "remote"}))))))
(deftest test-async-status-handler-errors
(let [my-router-id "my-router-id"
service-id "test-service-id"
make-route-params (fn [code]
{:host "host"
:location (when (not= code "missing-location") "location/1234")
:port "port"
:request-id (when (not= code "missing-request-id") "req-1234")
:router-id (when (not= code "missing-router-id") my-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})]
(testing "missing-code"
(let [request {:headers {"accept" "application/json"}
:query-string ""}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-location"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-location")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-request-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-request-id")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "missing-router-id"
(let [request {:headers {"accept" "application/json"}
:route-params (make-route-params "missing-router-id")}
{:keys [body headers status]} (async/<!! (async-status-handler nil nil service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (str/includes? body "Missing host, location, port, request-id, router-id or service-id in uri"))))
(testing "error-in-checking-backend-status"
(let [request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:headers {"accept" "application/json"}
:route-params (make-route-params "local")
:request-method :http-method}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:error (ex-info "backend-status-error" {:status http-400-bad-request})}))
async-trigger-terminate-fn nil
{:keys [body headers status]} (async/<!! (async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
(is (= http-400-bad-request status))
(is (= expected-json-response-headers headers))
(is (every? #(str/includes? body %) ["backend-status-error"]))))))
(deftest test-async-status-handler-with-return-codes
(let [my-router-id "my-router-id"
service-id "test-service-id"
remote-router-id "remote-router-id"
make-route-params (fn [code]
{:host "host"
:location (if (= code "local") "query/location/1234" "query/location/6789")
:port "port"
:request-id (if (= code "local") "req-1234" "req-6789")
:router-id (if (= code "local") my-router-id remote-router-id)
:service-id service-id})
service-id->service-description-fn (fn [in-service-id]
(is (= service-id in-service-id))
{"backend-proto" "http"
"metric-group" "test-metric-group"})
request-id-fn (fn [router-type] (if (= router-type "local") "req-1234" "req-6789"))
result-location-fn (fn [router-type & {:keys [include-host-port] :or {include-host-port false}}]
(str (when include-host-port "http://www.example.com:8521")
"/path/to/result-" (if (= router-type "local") "1234" "6789")))
async-result-location (fn [router-type & {:keys [include-host-port location] :or {include-host-port false}}]
(if include-host-port
(result-location-fn router-type :include-host-port include-host-port)
(str "/waiter-async/result/" (request-id-fn router-type) "/"
(if (= router-type "local") my-router-id remote-router-id) "/"
service-id "/host/port"
(or location (result-location-fn router-type :include-host-port false)))))]
(letfn [(execute-async-status-check
[{:keys [request-method result-location return-status router-type]}]
(let [terminate-call-atom (atom false)
async-trigger-terminate-fn (fn [target-router-id in-service-id request-id]
(reset! terminate-call-atom true)
(is (= (if (= router-type "local") my-router-id remote-router-id) target-router-id))
(is (= service-id in-service-id))
(is (= (request-id-fn router-type) request-id)))
request {:authorization/principal "test-user@DOMAIN"
:authorization/user "test-user"
:request-method request-method
:route-params (make-route-params router-type)}
make-http-request-fn (fn [instance in-request end-route metric-group backend-proto]
(is (= {:host "host" :port "port" :service-id service-id}
(select-keys instance [:host :port :service-id])))
(is (= request in-request))
(is (= (-> request :route-params :location) end-route))
(is (= "test-metric-group" metric-group))
(is (= "http" backend-proto))
(async/go {:body "status-check-response"
:headers (if (= return-status http-303-see-other) {"location" (or result-location (result-location-fn router-type))} {})
:status return-status}))
{:keys [status headers]}
(async/<!!
(async-status-handler async-trigger-terminate-fn make-http-request-fn service-id->service-description-fn request))]
{:terminated @terminate-call-atom, :return-status status, :return-headers headers}))]
(is (= {:terminated false, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-200-ok, :router-type "local"})))
(let [result-location (async-result-location "local" :include-host-port false)]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/location/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/location/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "./another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/query/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "../another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (async-result-location "local" :include-host-port false :location "/another/path/to/result")]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location "../../another/path/to/result", :return-status http-303-see-other, :router-type "local"}))))
(let [result-location (str "http://www.example.com:1234" (async-result-location "local" :include-host-port true))]
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location result-location, :return-status http-303-see-other, :router-type "local"}))))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-410-gone, :router-type "local"})))
(is (= {:terminated false, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-200-ok, :router-type "remote"})))
(let [result-location (async-result-location "remote" :include-host-port false)]
(is (= {:terminated false, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :return-status http-303-see-other, :router-type "remote"}))))
(let [result-location (str "http://www.example.com:1234" (async-result-location "remote" :include-host-port true))]
(is (= {:terminated true, :return-status http-303-see-other, :return-headers {"location" result-location}}
(execute-async-status-check {:request-method :get, :result-location result-location, :return-status http-303-see-other, :router-type "remote"}))))
(is (= {:terminated true, :return-status http-410-gone, :return-headers {}}
(execute-async-status-check {:request-method :get, :return-status http-410-gone, :router-type "remote"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-200-ok, :router-type "local"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-204-no-content, :router-type "local"})))
(is (= {:terminated false, :return-status http-404-not-found, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-404-not-found, :router-type "local"})))
(is (= {:terminated false, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "local"})))
(is (= {:terminated true, :return-status http-200-ok, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-200-ok, :router-type "remote"})))
(is (= {:terminated true, :return-status http-204-no-content, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-204-no-content, :router-type "remote"})))
(is (= {:terminated false, :return-status http-404-not-found, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-404-not-found, :router-type "remote"})))
(is (= {:terminated false, :return-status http-405-method-not-allowed, :return-headers {}}
(execute-async-status-check {:request-method :delete, :return-status http-405-method-not-allowed, :router-type "remote"}))))))
(deftest test-list-services-handler
(let [test-user "test-user"
test-user-services #{"service1" "service2" "service3" "service7" "service8" "service9" "service10"}
other-user-services #{"service4" "service5" "service6" "service11"}
healthy-services #{"service1" "service2" "service4" "service6" "service7" "service8" "service9" "service10" "service11"}
unhealthy-services #{"service2" "service3" "service5"}
service-id->references {"service1" {:sources [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
:type :token}
"service3" {:sources [{:token "t2.com" :version "v2"} {:token "tPI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI.edu" :version "v3"}]
:type :token}
"service4" {:sources [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
:type :token}
"service5" {:sources [{:token "t1.org" :version "v1"} {:token "t3.edu" :version "v3"}]
:type :token}
"service7" {:sources [{:token "t1.org" :version "v2"} {:token "t2.com" :version "v1"}]
:type :token}
"service9" {:sources [{:token "t2.com" :version "v3"}]
:type :token}}
service-id->source-tokens {"service1" [{:token "t1.org" :version "v1"} {:token "t2.com" :version "v2"}]
"service3" [{:token "t2.com" :version "v2"} {:token "tPI:KEY:<KEY>END_PI.PI:PASSWORD:<PASSWORD>END_PI" :version "v3"}]
"service4" [{:token "tPI:KEY:<KEY>END_PI.org" :version "v1"} {:token "tPI:KEY:<KEY>END_PI.com" :version "v2"}]
"service5" [{:token "t1.org" :version "v1"} {:token "tPI:KEY:<KEY>END_PI.edu" :version "v3"}]
"service7" [{:token "t1.org" :version "v2"} {:token "t2.com" :version "v1"}]
"service9" [{:token "PI:PASSWORD:<PASSWORD>END_PI" :version "v3"}]}
all-services (set/union other-user-services test-user-services)
current-time (t/now)
query-state-fn (constantly {:all-available-service-ids all-services
:service-id->healthy-instances (pc/map-from-keys
(fn [service-id]
(let [instance-id-1 (str service-id ".i1")]
[{:flags []
:healthy? true
:host (str "127.0.0." (hash instance-id-1))
:id instance-id-1
:port (+ 1000 (rand 1000))
:service-id service-id
:started-at (du/date-to-str current-time)}]))
healthy-services)
:service-id->unhealthy-instances (pc/map-from-keys (constantly []) unhealthy-services)})
query-autoscaler-state-fn (constantly
(pc/map-from-keys
(fn [_] {:scale-amount (rand-nth [-1 0 1])})
test-user-services))
request {:authorization/user test-user}
instance-counts-present (fn [body]
(let [parsed-body (-> body (str) (json/read-str) (walk/keywordize-keys))]
(every? (fn [service-entry]
(is (contains? service-entry :instance-counts))
(is (every? #(contains? (get service-entry :instance-counts) %)
[:healthy-instances, :unhealthy-instances])))
parsed-body)))
prepend-waiter-url identity
entitlement-manager (reify authz/EntitlementManager
(authorized? [_ user action {:keys [service-id]}]
(let [id (subs service-id (count "service"))]
(and (str/includes? (str test-user id) user)
(= action :manage)
(some #(= % service-id) test-user-services)))))
retrieve-token-based-fallback-fn (constantly nil)
token->token-hash (constantly nil)
list-services-handler (wrap-handler-json-response list-services-handler)
assert-successful-json-response (fn [{:keys [body headers status]}]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (instance-counts-present body)))]
(letfn [(service-id->metrics-fn []
{})
(service-id->references-fn [service-id]
(get service-id->references service-id))
(service-id->service-description-fn [service-id & _]
(let [id (subs service-id (count "service"))]
{"cpus" (Integer/parseInt id)
"env" {"E_ID" (str "id-" id)}
"mem" (* 10 (Integer/parseInt id))
"metadata" {"m-id" (str "id-" id)}
"metric-group" (str "mg" id)
"run-as-user" (if (contains? test-user-services service-id) (str test-user id) "another-user")}))
(service-id->source-tokens-entries-fn [service-id]
(when (contains? service-id->source-tokens service-id)
(let [source-tokens (-> service-id service-id->source-tokens walk/stringify-keys)]
#{source-tokens})))]
(testing "list-services-handler:success-regular-user"
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= test-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))
(let [request (assoc request :authorization/user "test-user1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service10"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :authorization/user "test-user1" :query-string "run-as-user=test-user1.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service10"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-another-user"
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (conj other-user-services "service1")
(->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "run-as-user=another-user&run-as-user=test-user1.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (conj other-user-services "service1" "service10")
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-cpus"
(let [request (assoc request :query-string "cpus=1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-metric-group"
(let [request (assoc request :query-string "metric-group=mg3")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service3"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-metric-groups"
(let [request (assoc request :query-string "metric-group=mg1&metric-group=mg2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-single-env-variable"
(let [request (assoc request :query-string "env.E_ID=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-env-variables"
(let [request (assoc request :query-string "env.E_ID=id-1&env.E_ID=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-single-metadata-variable"
(let [request (assoc request :query-string "metadata.m-id=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-metadata-variables"
(let [request (assoc request :query-string "metadata.m-id=id-1&metadata.m-id=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1" "service2"} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-with-filter-for-multiple-nested-parameters"
(let [request (assoc request :query-string "env.E_ID=id-1&metadata.m-id=id-1")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{"service1"} (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(let [request (assoc request :query-string "env.E_ID=id-1&metadata.m-id=id-2")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= #{} (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-filter-for-same-user"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=another-user")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-prefix-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=.*user.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-run-as-user-suffix-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user "another-user" :query-string "run-as-user=another.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-regular-user-with-different-run-as-user-star-filter"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ _ _ _]
; use (constantly true) for authorized? to verify that filter still applies
true))
request (assoc request :authorization/user test-user :query-string "run-as-user=another.*")]
(let [{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= other-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:failure"
(let [query-state-fn (constantly {:all-available-service-ids #{"service1"}
:service-id->healthy-instances {"service1" []}})
request {:authorization/user test-user}
exception-message "Custom message from test case"
prepend-waiter-url (fn [_] (throw (ex-info exception-message {:status http-400-bad-request})))
list-services-handler (core/wrap-error-handling
#(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash %))
{:keys [body headers status]} (list-services-handler request)]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (str/includes? (str body) exception-message))))
(testing "list-services-handler:success-super-user-sees-all-apps"
(let [entitlement-manager (reify authz/EntitlementManager
(authorized? [_ user action {:keys [service-id]}]
(and (= user test-user)
(= :manage action)
(contains? all-services service-id))))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= all-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(testing "list-services-handler:success-filter-tokens"
(doseq [[query-param filter-fn]
{"t1.com" #(= % "t1.com")
"t2.org" #(= % "t2.org")
"tn.none" #(= % "tn.none")
".*o.*" #(str/includes? % "o")
".*t.*" #(str/includes? % "t")
"t.*" #(str/starts-with? % "t")
".*com" #(str/ends-with? % "com")
".*org" #(str/ends-with? % "org")}]
(let [request (assoc request :query-string (str "token=" query-param))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(->> source-tokens (map :token) (some filter-fn))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-filter-version"
(doseq [[query-param filter-fn]
{"v1" #(= % "v1")
"v2" #(= % "v2")
"vn" #(= % "vn")
".*v.*" #(str/includes? % "v")
"v.*" #(str/starts-with? % "v")
".*1" #(str/ends-with? % "1")
".*2" #(str/ends-with? % "2")}]
(let [request (assoc request :query-string (str "token-version=" query-param))
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(->> source-tokens (map :version) (some filter-fn))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set))))))
(testing "list-services-handler:success-filter-token-and-version"
(let [request (assoc request :query-string "token=PI:KEY:<KEY>END_PI&token-version=vPI:KEY:<KEY>END_PI")
{:keys [body] :as response}
; without a run-as-user, should return all apps
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)]
(assert-successful-json-response response)
(is (= (->> service-id->source-tokens
(filter (fn [[_ source-tokens]]
(and (->> source-tokens (map :token) (some #(= % "t1")))
(->> source-tokens (map :version) (some #(= % "v1"))))))
keys
set
(set/intersection test-user-services))
(->> body json/read-str walk/keywordize-keys (map :service-id) set)))))
(testing "list-services-handler:include-healthy-instances"
(let [request (assoc request :query-string "include=healthy-instances")
{:keys [body] :as response}
(list-services-handler entitlement-manager query-state-fn query-autoscaler-state-fn prepend-waiter-url retrieve-token-based-fallback-fn
service-id->service-description-fn service-id->metrics-fn
service-id->references-fn service-id->source-tokens-entries-fn token->token-hash request)
service-id->healthy-instances (->> body
(json/read-str)
(walk/keywordize-keys)
(pc/map-from-vals :service-id)
(pc/map-vals #(get-in % [:instances :healthy-instances])))]
(assert-successful-json-response response)
(is (= test-user-services (->> body json/read-str walk/keywordize-keys (map :service-id) set)))
(doseq [service-id test-user-services]
(if (contains? healthy-services service-id)
(let [healthy-instances (get-in (query-state-fn) [:service-id->healthy-instances service-id])]
(is (= (map #(select-keys % [:host :id :port :started-at]) healthy-instances)
(get service-id->healthy-instances service-id))))
(is (empty? (get service-id->healthy-instances service-id))))))))))
(deftest test-delete-service-handler
(let [test-user "test-user"
test-service-id "service-1"
test-router-id "router-1"
allowed-to-manage-service?-fn (fn [service-id user] (and (= test-service-id service-id) (= test-user user)))
make-inter-router-requests-fn (constantly {})
fallback-state-atom (atom nil)]
(let [core-service-description {"run-as-user" test-user}
scheduler-interactions-thread-pool (Executors/newFixedThreadPool 1)]
(testing "delete-service-handler:success-regular-user"
(let [scheduler (reify scheduler/ServiceScheduler
(delete-service [_ service-id]
(is (= test-service-id service-id))
{:result :deleted
:message "Worked!"}))
request {:authorization/user test-user}
{:keys [body headers status]}
(async/<!!
(delete-service-handler test-router-id test-service-id core-service-description scheduler allowed-to-manage-service?-fn
scheduler-interactions-thread-pool make-inter-router-requests-fn fallback-state-atom request))]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (every? #(str/includes? (str body) (str %)) ["Worked!"]))))
(testing "delete-service-handler:success-regular-user-deleting-for-another-user"
(let [scheduler (reify scheduler/ServiceScheduler
(delete-service [_ service-id]
(is (= test-service-id service-id))
{:deploymentId "good"}))
request {:authorization/user "another-user"}]
(is (thrown-with-msg?
ExceptionInfo #"User not allowed to delete service"
(delete-service-handler test-router-id test-service-id core-service-description scheduler allowed-to-manage-service?-fn
scheduler-interactions-thread-pool make-inter-router-requests-fn fallback-state-atom request)))))
(.shutdown scheduler-interactions-thread-pool))))
(deftest test-service-await-handler
(let [handler-name "test-service-await-handler"
timeout 1000
request {:route-params {:service-id "s1" :goal-state "deleted"}
:basic-authentication {:src-router-id "r2"}
:request-method :get
:query-string (str "timeout=" 1000)}
assert-immediate-success
(fn [goal-state fallback-state-atom request expected-service-exists? expected-service-healthy?]
(let [request (assoc-in request [:route-params :goal-state] goal-state)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") expected-service-exists?))
(is (= (get parsed-body "service-healthy?") expected-service-healthy?))
(is (get parsed-body "goal-success?"))))
assert-force-timeout
(fn [timeout goal-state fallback-state-atom request expected-service-exists? expected-service-healthy?]
(let [request (assoc-in request [:route-params :goal-state] goal-state)
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") expected-service-exists?))
(is (= (get parsed-body "service-healthy?") expected-service-healthy?))
(is (not (get parsed-body "goal-success?")))
(is (>= (- end-time start-time) timeout))))]
(testing (str handler-name ":immediate-success-deleted")
(let [fallback-state-atom (atom {:available-service-ids #{"s0"} :healthy-service-ids #{"s0"}})]
(assert-immediate-success "deleted" fallback-state-atom request false false)))
(testing (str handler-name ":immediate-success-healthy")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{"s1"}})]
(assert-immediate-success "healthy" fallback-state-atom request true true)))
(testing (str handler-name ":immediate-success-exist")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})]
(assert-immediate-success "exist" fallback-state-atom request true false)))
(testing (str handler-name ":force-timeout-deleted")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{"s1"}})]
(assert-force-timeout timeout "deleted" fallback-state-atom request true true)))
(testing (str handler-name ":force-timeout-healthy")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})]
(assert-force-timeout timeout "healthy" fallback-state-atom request true false)))
(testing (str handler-name ":force-timeout-exist")
(let [fallback-state-atom (atom {:available-service-ids #{}} :healthy-service-ids #{})]
(assert-force-timeout timeout "exist" fallback-state-atom request false false)))
(testing (str handler-name ":success-with-large-sleep-duration")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})
goal-fallback-state {:available-service-ids #{} :healthy-service-ids #{}}
timeout 2000
update-delay 1000
request (assoc request :query-string (str "timeout=" timeout "&sleep-duration=" (* 10 timeout)))
_ (async/go
(async/<! (async/timeout update-delay))
(reset! fallback-state-atom goal-fallback-state))
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") false))
(is (= (get parsed-body "service-healthy?") false))
(is (get parsed-body "goal-success?"))
(is (<= update-delay (- timeout 50) (- end-time start-time) (+ timeout 50)))))
(testing (str handler-name ":success-with-update")
(let [fallback-state-atom (atom {:available-service-ids #{"s1"} :healthy-service-ids #{}})
timeout 10000
update-delay 2000
request-query (assoc request :query-string (str "timeout=" timeout))
_ (async/go
(async/<! (async/timeout update-delay))
(reset! fallback-state-atom {:available-service-ids #{} :healthy-service-ids #{}}))
start-time (System/currentTimeMillis)
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request-query))
end-time (System/currentTimeMillis)
parsed-body (json/read-str body)]
(is (= http-200-ok status))
(is (= "application/json" (get headers "content-type")))
(is (= (get parsed-body "service-exists?") false))
(is (= (get parsed-body "service-healthy?") false))
(is (get parsed-body "goal-success?"))
(is (<= update-delay (- end-time start-time) timeout))))
(testing (str handler-name ":non-integer-timeout-sleep-duration-params")
(let [fallback-state-atom (atom {:available-service-ids #{}})
timeout "Invalid timeout value"
sleep-duration "Invalid sleep-duration value"
request (assoc request :query-string (str "timeout=" timeout "&sleep-duration=" sleep-duration))
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (re-find #"timeout and sleep-duration must be integers" body))
(is (re-find (re-pattern (str ":timeout \"" timeout "\"")) body))
(is (re-find (re-pattern (str ":sleep-duration \"" sleep-duration "\"")) body))))
(testing (str handler-name ":timeout-required-param")
(let [fallback-state-atom (atom {:available-service-ids #{}})
request (assoc request :query-string "")
{:keys [body headers status]} (async/<!! (service-await-handler fallback-state-atom request))]
(is (= http-400-bad-request status))
(is (= "text/plain" (get headers "content-type")))
(is (re-find #"timeout is a required query parameter" body))))))
(deftest test-work-stealing-handler
(let [test-service-id "test-service-id"
test-router-id "router-1"
instance-rpc-chan-factory (fn [response-status]
(let [instance-rpc-chan (async/chan 1)
work-stealing-chan (async/chan 1)]
(async/go
(let [instance-rpc-content (async/<! instance-rpc-chan)
{:keys [method service-id response-chan]} instance-rpc-content]
(is (= :offer method))
(is (= test-service-id service-id))
(async/>! response-chan work-stealing-chan)))
(async/go
(let [offer-params (async/<! work-stealing-chan)]
(is (= test-service-id (:service-id offer-params)))
(async/>!! (:response-chan offer-params) response-status)))
instance-rpc-chan))
test-cases [{:name "valid-parameters-rejected-response"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :promptly-rejected
:expected-status http-200-ok
:expected-body-fragments ["cid" "request-id" "response-status" "promptly-rejected"
test-service-id test-router-id]}
{:name "valid-parameters-success-response"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-200-ok
:expected-body-fragments ["cid" "request-id" "response-status" "success"
test-service-id test-router-id]}
{:name "missing-cid"
:request-body {:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-instance"
:request-body {:cid "cid-1"
:request-id "request-1"
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-request-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:router-id test-router-id
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-router-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:service-id test-service-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}
{:name "missing-service-id"
:request-body {:cid "cid-1"
:instance {:id "instance-1", :service-id test-service-id}
:request-id "request-1"
:router-id test-router-id}
:response-status :success
:expected-status http-400-bad-request
:expected-body-fragments ["Missing one of"]}]]
(doseq [{:keys [name request-body response-status expected-status expected-body-fragments]} test-cases]
(testing name
(let [instance-rpc-chan (instance-rpc-chan-factory response-status)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
request {:uri (str "/work-stealing")
:request-method :post
:body (StringBufferInputStream. (utils/clj->json (walk/stringify-keys request-body)))}
{:keys [status body]} (fa/<?? (work-stealing-handler populate-maintainer-chan! request))]
(is (= expected-status status))
(is (every? #(str/includes? (str body) %) expected-body-fragments)))))))
(deftest test-work-stealing-handler-cannot-find-channel
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"cid" "test-cid"
"instance" {"id" "test-instance-id", "service-id" test-service-id}
"request-id" "test-request-id"
"router-id" "test-router-id"
"service-id" test-service-id}))}
response-chan (work-stealing-handler populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :offer method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-404-not-found status)))))
(deftest test-work-stealing-handler-channel-put-failed
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"cid" "test-cid"
"instance" {"id" "test-instance-id", "service-id" test-service-id}
"request-id" "test-request-id"
"router-id" "test-router-id"
"service-id" test-service-id}))}
response-chan (work-stealing-handler populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)
work-stealing-chan (async/chan)]
(is (= :offer method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! work-stealing-chan)
(async/put! response-chan work-stealing-chan)
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-500-internal-server-error status)))))
(deftest test-get-router-state
(let [state-atom (atom nil)
query-state-fn (fn [] @state-atom)
test-fn (fn [router-id query-state-fn request]
(let [handler (wrap-handler-json-response get-router-state)]
(handler router-id query-state-fn request)))
router-id "test-router-id"]
(reset! state-atom {:state-data {}})
(testing "Getting router state"
(testing "should handle exceptions gracefully"
(let [bad-request {:scheme 1} ;; integer scheme will throw error
{:keys [status body]} (test-fn router-id query-state-fn bad-request)]
(is (str/includes? (str body) "Internal error"))
(is (= http-500-internal-server-error status))))
(testing "display router state"
(let [{:keys [status body]} (test-fn router-id query-state-fn {})]
(is (every? #(str/includes? (str body) %1)
["autoscaler" "autoscaling-multiplexer"
"codahale-reporters" "fallback" "interstitial" "kv-store" "leader" "local-usage"
"maintainer" "router-metrics" "scheduler" "statsd"])
(str "Body did not include necessary JSON keys:\n" body))
(is (= http-200-ok status)))))))
(deftest test-get-query-fn-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-query-fn-state)]
(testing "successful response"
(let [state {"autoscaler" "state"}
query-state-fn (constantly state)
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [query-state-fn (fn [] (throw (Exception. "from test")))
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-kv-store-state
(let [router-id "test-router-id"
include-flags #{}
test-fn (wrap-handler-json-response get-kv-store-state)]
(testing "successful response"
(let [kv-store (kv/new-local-kv-store {})
state (walk/stringify-keys (kv/state kv-store include-flags))
{:keys [body status]} (test-fn router-id kv-store {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [kv-store (Object.)
{:keys [body status]} (test-fn router-id kv-store {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-local-usage-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-local-usage-state)]
(testing "successful response"
(let [last-request-time-state {"foo" 1234, "bar" 7890}
last-request-time-agent (agent last-request-time-state)
{:keys [body status]} (test-fn router-id last-request-time-agent {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" last-request-time-state}))))
(testing "exception response"
(let [handler (core/wrap-error-handling #(test-fn router-id nil %))
{:keys [body status]} (handler {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-leader-state
(let [router-id "test-router-id"
leader-id-fn (constantly router-id)
test-fn (wrap-handler-json-response get-leader-state)]
(testing "successful response"
(let [leader?-fn (constantly true)
state {"leader?" (leader?-fn), "leader-id" (leader-id-fn)}
{:keys [body status]} (test-fn router-id leader?-fn leader-id-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))
(testing "exception response"
(let [leader?-fn (fn [] (throw (Exception. "Test Exception")))
{:keys [body status]} (test-fn router-id leader?-fn leader-id-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-chan-latest-state-handler
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-chan-latest-state-handler)]
(testing "successful response"
(let [state-atom (atom nil)
query-state-fn (fn [] @state-atom)
state {"foo" "bar"}
_ (reset! state-atom state)
{:keys [body status]} (test-fn router-id query-state-fn {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-router-metrics-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-router-metrics-state)]
(testing "successful response"
(let [state {"router-metrics" "foo"}
router-metrics-state-fn (constantly state)
{:keys [body status]} (test-fn router-id router-metrics-state-fn {})]
(is (= http-200-ok status))
(is (= {"router-id" router-id "state" state}
(json/read-str body)))))
(testing "exception response"
(let [router-metrics-state-fn (fn [] (throw (Exception. "Test Exception")))
{:keys [body status]} (test-fn router-id router-metrics-state-fn {})]
(is (= http-500-internal-server-error status))
(is (str/includes? body "Waiter Error 500"))))))
(deftest test-get-query-chan-state-handler
(let [router-id "test-router-id"
test-fn (wrap-async-handler-json-response get-query-chan-state-handler)]
(testing "successful response"
(let [scheduler-chan (async/promise-chan)
state {"foo" "bar"}
_ (async/go
(let [{:keys [response-chan]} (async/<! scheduler-chan)]
(async/>! response-chan state)))
{:keys [body status]} (async/<!! (test-fn router-id scheduler-chan {}))]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-scheduler-state
(let [router-id "test-router-id"
scheduler (reify scheduler/ServiceScheduler
(state [_ _]
{:scheduler "state"}))
test-fn (wrap-handler-json-response get-scheduler-state)]
(testing "successful response"
(let [state (walk/stringify-keys (scheduler/state scheduler #{}))
{:keys [body status]} (test-fn router-id scheduler {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-statsd-state
(let [router-id "test-router-id"
test-fn (wrap-handler-json-response get-statsd-state)]
(testing "successful response"
(let [state (walk/stringify-keys (statsd/state))
{:keys [body status]} (test-fn router-id {})]
(is (= http-200-ok status))
(is (= (json/read-str body) {"router-id" router-id, "state" state}))))))
(deftest test-get-service-state
(let [router-id "router-id"
service-id "service-1"
local-usage-agent (agent {service-id {"last-request-time" "foo"}})
enable-work-stealing-support? (constantly true)]
(testing "returns 400 for missing service id"
(is (= http-400-bad-request
(:status (async/<!! (get-service-state router-id enable-work-stealing-support? nil local-usage-agent "" {} {}))))))
(let [instance-rpc-chan (async/chan 1)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
query-state-chan (async/chan 1)
query-work-stealing-chan (async/chan 1)
maintainer-state-chan (async/chan 1)
responder-state {:state "responder state"}
work-stealing-state {:state "work-stealing state"}
maintainer-state {:state "maintainer state"}
start-instance-rpc-fn (fn []
(async/go
(dotimes [_ 2]
(let [{:keys [method response-chan]} (async/<! instance-rpc-chan)]
(condp = method
:query-state (async/>! response-chan query-state-chan)
:query-work-stealing (async/>! response-chan query-work-stealing-chan))))))
start-query-chan-fn (fn []
(async/go
(let [{:keys [response-chan]} (async/<! query-state-chan)]
(async/>! response-chan responder-state)))
(async/go
(let [{:keys [response-chan]} (async/<! query-work-stealing-chan)]
(async/>! response-chan work-stealing-state))))
start-maintainer-fn (fn []
(async/go (let [{:keys [service-id response-chan]} (async/<! maintainer-state-chan)]
(async/>! response-chan (assoc maintainer-state :service-id service-id)))))
get-service-state (wrap-async-handler-json-response get-service-state)]
(start-instance-rpc-fn)
(start-query-chan-fn)
(start-maintainer-fn)
(let [query-sources {:autoscaler-state (fn [{:keys [service-id]}]
{:service-id service-id :source "autoscaler"})
:keyword-state :disabled
:maintainer-state maintainer-state-chan
:map-state {:foo "bar"}}
response (async/<!! (get-service-state router-id enable-work-stealing-support? populate-maintainer-chan!
local-usage-agent service-id query-sources {}))
service-state (json/read-str (:body response) :key-fn keyword)]
(is (= router-id (get-in service-state [:router-id])))
(is (= {:service-id service-id :source "autoscaler"} (get-in service-state [:state :autoscaler-state])))
(is (= (name :disabled) (get-in service-state [:state :keyword-state])))
(is (= {:last-request-time "foo"} (get-in service-state [:state :local-usage])))
(is (= (assoc maintainer-state :service-id service-id) (get-in service-state [:state :maintainer-state])))
(is (= {:foo "bar"} (get-in service-state [:state :map-state])))
(is (= responder-state (get-in service-state [:state :responder-state])))
(is (= work-stealing-state (get-in service-state [:state :work-stealing-state])))))))
(deftest test-acknowledge-consent-handler
(let [current-time-ms (System/currentTimeMillis)
clock (constantly current-time-ms)
test-token "PI:PASSWORD:<PASSWORD>END_PI"
test-service-description {"cmd" "some-cmd", "cpus" 1, "mem" 1024}
token->service-description-template (fn [token]
(when (= token test-token)
(assoc test-service-description
"source-tokens" [(sd/source-tokens-entry test-token test-service-description)])))
token->token-metadata (fn [token] (when (= token test-token) {"owner" "user"}))
service-description->service-id (fn [service-description]
(str "service-" (count service-description) "." (count (str service-description))))
test-user "test-user"
test-service-id (-> test-service-description
(assoc "permitted-user" test-user
"run-as-user" test-user
"source-tokens" [(sd/source-tokens-entry test-token test-service-description)])
service-description->service-id)
request->consent-service-id (fn [request]
(if (some-> request (utils/request->host) (utils/authority->host) (= test-token))
test-service-id
"service-123.123456789"))
add-encoded-cookie (fn [response cookie-name cookie-value consent-expiry-days]
(assoc-in response [:cookie cookie-name] {:value cookie-value :age consent-expiry-days}))
consent-expiry-days 1
consent-cookie-value (fn consent-cookie-value [mode service-id token {:strs [owner]}]
(when mode
(-> [mode (clock)]
(concat (case mode
"service" (when service-id [service-id])
"token" (when (and owner token) [token owner])
nil))
vec)))
acknowledge-consent-handler-fn (fn [request]
(let [request' (-> request
(update :authorization/user #(or %1 test-user))
(update :request-method #(or %1 :post))
(update :scheme #(or %1 :http)))]
(acknowledge-consent-handler
token->service-description-template token->token-metadata
request->consent-service-id consent-cookie-value add-encoded-cookie
consent-expiry-days request')))]
(testing "unsupported request method"
(let [request {:request-method :get}
{:keys [body headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-405-method-not-allowed status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Only POST supported"))))
(testing "host and origin mismatch"
(let [request {:headers {"host" "www.example2.com"
"origin" (str "http://" test-token)}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Origin is not the same as the host"))))
(testing "referer and origin mismatch"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" "http://www.example2.com/consent"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Referer does not start with origin"))))
(testing "mismatch in x-requested-with"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "AJAX"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Header x-requested-with does not match expected value"))))
(testing "missing mode param"
(let [request {:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing or invalid mode"))))
(testing "invalid mode param"
(let [request {:authorization/user test-user
:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "unsupported", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing or invalid mode"))))
(testing "missing service-id param"
(let [request {:authorization/user test-user
:headers {"host" test-token
"origin" (str "http://" test-token)
"referer" (str "http://" test-token "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Missing service-id"))))
(testing "missing service description for token"
(let [test-host (str test-token ".test2")
request {:authorization/user test-user
:headers {"host" test-host
"origin" (str "http://" test-host)
"referer" (str "http://" test-host "/consent")
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Unable to load description for token"))))
(testing "invalid service-id param"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":PI:PASSWORD:<PASSWORD>END_PI")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" "service-id-1"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-400-bad-request status))
(is (= expected-text-response-headers headers))
(is (nil? cookie))
(is (str/includes? body "Invalid service-id for specified token"))))
(testing "valid service mode request"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1PI:PASSWORD:<PASSWORD>END_PI")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" test-service-id}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["service" current-time-ms test-service-id], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent") (str body))))
(testing "valid service mode request with missing origin"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "service", "service-id" test-service-id}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["service" current-time-ms test-service-id], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent") (str body))))
(testing "valid token mode request"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"origin" "http://www.example.com:1234"
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "token"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["token" current-time-ms test-token "user"], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent"))))
(testing "valid token mode request with missing origin"
(let [request {:authorization/user test-user
:headers {"host" (str test-token ":1234")
"referer" "http://www.example.com:1234/consent"
"x-requested-with" "XMLHttpRequest"}
:params {"mode" "token"}}
{:keys [body cookie headers status]} (acknowledge-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"x-waiter-consent" {:value ["token" current-time-ms test-token "user"], :age consent-expiry-days}} cookie))
(is (= {} headers))
(is (str/includes? body "Added cookie x-waiter-consent"))))))
(deftest test-render-consent-template
(let [context {:auth-user "test-user"
:consent-expiry-days 1
:service-description-template {"cmd" "some-cmd", "cpus" 1, "mem" 1024}
:service-id "service-5.97"
:target-url "http://www.example.com:6789/some-path"
:token "PI:PASSWORD:<PASSWORD>END_PI"}
body (render-consent-template context)]
(is (str/includes? body "Run Web App? - Waiter"))
(is (str/includes? body "http://www.example.com:6789/some-path"))))
(deftest test-request-consent-handler
(let [request-time (t/now)
basic-service-description {"cmd" "some-cmd" "cpus" 1 "mem" 1024}
token->service-description-template
(fn [token]
(let [service-description (condp = token
"www.example.com" basic-service-description
"www.example-i0.com" (assoc basic-service-description
"interstitial-secs" 0)
"www.example-i10.com" (assoc basic-service-description
"interstitial-secs" 10)
nil)]
(cond-> service-description
(seq service-description)
(assoc "source-tokens" [(sd/source-tokens-entry token service-description)]))
service-description))
service-description->service-id (fn [service-description]
(str "service-" (count service-description) "." (count (str service-description))))
consent-expiry-days 1
test-user "test-user"
request->consent-service-id (fn [request]
(or (some-> request
(utils/request->host)
(utils/authority->host)
(token->service-description-template)
(assoc "permitted-user" test-user "run-as-user" test-user)
(service-description->service-id))
"service-123.123456789"))
request-consent-handler-fn (fn [request]
(let [request' (-> request
(update :authorization/user #(or %1 test-user))
(update :request-method #(or %1 :get)))]
(request-consent-handler
token->service-description-template request->consent-service-id
consent-expiry-days request')))
io-resource-fn (fn [file-path]
(is (= "web/consent.html" file-path))
(StringReader. "some-content"))
expected-service-id (fn [token]
(-> (token->service-description-template token)
(assoc "permitted-user" test-user "run-as-user" test-user)
service-description->service-id))
template-eval-factory (fn [scheme]
(fn [{:keys [token] :as data}]
(let [service-description-template (token->service-description-template token)]
(is (= {:auth-user test-user
:consent-expiry-days 1
:service-description-template service-description-template
:service-id (expected-service-id token)
:target-url (str scheme "://" token ":6789/some-path"
(when (some-> (get service-description-template "interstitial-secs") pos?)
(str "?" (interstitial/request-time->interstitial-param-string request-time))))
:token token}
data)))
"template:some-content"))]
(testing "unsupported request method"
(let [request {:authorization/user test-user
:request-method :post
:request-time request-time
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-405-method-not-allowed status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Only GET supported"))))
(testing "token without service description"
(let [request {:authorization/user test-user
:headers {"host" "www.example2.com:6789"}
:request-method :get
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-404-not-found status))
(is (= expected-text-response-headers headers))
(is (str/includes? body "Unable to load description for token"))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "http")]
(testing "token without service description - http scheme"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https scheme"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :https}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example-i0.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example-i10.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))
(with-redefs [io/resource io-resource-fn
render-consent-template (template-eval-factory "https")]
(testing "token without service description - https x-forwarded-proto"
(let [request {:authorization/user test-user
:headers {"host" "www.example.com:6789", "x-forwarded-proto" "https"}
:request-time request-time
:route-params {:path "some-path"}
:scheme :http}
{:keys [body headers status]} (request-consent-handler-fn request)]
(is (= http-200-ok status))
(is (= {"content-type" "text/html"} headers))
(is (= body "template:some-content")))))))
(deftest test-eject-instance-cannot-find-channel
(let [notify-instance-killed-fn (fn [instance] (throw (ex-info "Unexpected call" {:instance instance})))
instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
request {:body (StringBufferInputStream.
(utils/clj->json
{"instance" {"id" "test-instance-id", "service-id" test-service-id}
"period-in-ms" 1000
"reason" "eject"}))}
response-chan (eject-instance notify-instance-killed-fn populate-maintainer-chan! request)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :eject method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-400-bad-request status)))))
(deftest test-eject-killed-instance
(let [notify-instance-chan (async/promise-chan)
notify-instance-killed-fn (fn [instance] (async/>!! notify-instance-chan instance))
instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
instance {:id "test-instance-id"
:service-id test-service-id
:started-at nil}
request {:body (StringBufferInputStream.
(utils/clj->json
{"instance" instance
"period-in-ms" 1000
"reason" "killed"}))}]
(with-redefs []
(let [response-chan (eject-instance notify-instance-killed-fn populate-maintainer-chan! request)
eject-chan (async/promise-chan)]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :eject method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/>!! response-chan eject-chan)))
(async/thread
(let [[{:keys [eject-period-ms instance-id]} repsonse-chan] (async/<!! eject-chan)]
(is (= 1000 eject-period-ms))
(is (= (:id instance) instance-id))
(async/>!! repsonse-chan :ejected)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-200-ok status))
(is (= instance (async/<!! notify-instance-chan))))))))
(deftest test-get-ejected-instances-cannot-find-channel
(let [instance-rpc-chan (async/chan)
populate-maintainer-chan! (make-populate-maintainer-chan! instance-rpc-chan)
test-service-id "test-service-id"
response-chan (get-ejected-instances populate-maintainer-chan! test-service-id {})]
(async/thread
(let [{:keys [cid method response-chan service-id]} (async/<!! instance-rpc-chan)]
(is (= :query-state method))
(is (= test-service-id service-id))
(is cid)
(is (instance? ManyToManyChannel response-chan))
(async/close! response-chan)))
(let [{:keys [status]} (async/<!! response-chan)]
(is (= http-500-internal-server-error status)))))
|
[
{
"context": "set client\n (redis/password-reset-key \"brad-reset-token\")\n {:user/email-address \"brad",
"end": 556,
"score": 0.5522029399871826,
"start": 553,
"tag": "KEY",
"value": "ad-"
},
{
"context": "rad-reset-token\")\n {:user/email-address \"brad@example.com\" :user/id 2}))\n\n(defn system\n \"Provides a Compon",
"end": 618,
"score": 0.9999133944511414,
"start": 602,
"tag": "EMAIL",
"value": "brad@example.com"
}
] | test/server/com/grzm/sorty/server/test/system.clj | grzm/sorty | 0 | (ns com.grzm.sorty.server.test.system
(:require
[com.grzm.component.pedestal :as pedestal]
[com.grzm.sorty.server.config :as config]
[com.grzm.sorty.server.app :as app]
[com.stuartsierra.component :as component]
[com.grzm.sorty.server.api :as api]
[com.grzm.sorty.server.persistor :as persistor]
[com.grzm.sorty.server.redis :as redis]
[com.grzm.sorty.server.redis.predis :as predis]
[predis.core :as pc]))
(def http-port 8765)
(defn redis-init-fn [client]
(pc/set client
(redis/password-reset-key "brad-reset-token")
{:user/email-address "brad@example.com" :user/id 2}))
(defn system
"Provides a Component system map"
([]
(system {:pedestal {:config-fn (config/pedestal-config-fn :dev http-port)}
:redis {:init-fn redis-init-fn}}))
([{:keys [pedestal redis] :as _config}]
(component/system-map
:api (component/using (api/api-handler) [:app])
:app (app/app)
:pedestal (component/using
(pedestal/pedestal-servlet (:config-fn pedestal))
[:api :app])
:persistor (component/using (persistor/persistor)
[:redis])
:redis (predis/redis (:init-fn redis)))))
| 123998 | (ns com.grzm.sorty.server.test.system
(:require
[com.grzm.component.pedestal :as pedestal]
[com.grzm.sorty.server.config :as config]
[com.grzm.sorty.server.app :as app]
[com.stuartsierra.component :as component]
[com.grzm.sorty.server.api :as api]
[com.grzm.sorty.server.persistor :as persistor]
[com.grzm.sorty.server.redis :as redis]
[com.grzm.sorty.server.redis.predis :as predis]
[predis.core :as pc]))
(def http-port 8765)
(defn redis-init-fn [client]
(pc/set client
(redis/password-reset-key "br<KEY>reset-token")
{:user/email-address "<EMAIL>" :user/id 2}))
(defn system
"Provides a Component system map"
([]
(system {:pedestal {:config-fn (config/pedestal-config-fn :dev http-port)}
:redis {:init-fn redis-init-fn}}))
([{:keys [pedestal redis] :as _config}]
(component/system-map
:api (component/using (api/api-handler) [:app])
:app (app/app)
:pedestal (component/using
(pedestal/pedestal-servlet (:config-fn pedestal))
[:api :app])
:persistor (component/using (persistor/persistor)
[:redis])
:redis (predis/redis (:init-fn redis)))))
| true | (ns com.grzm.sorty.server.test.system
(:require
[com.grzm.component.pedestal :as pedestal]
[com.grzm.sorty.server.config :as config]
[com.grzm.sorty.server.app :as app]
[com.stuartsierra.component :as component]
[com.grzm.sorty.server.api :as api]
[com.grzm.sorty.server.persistor :as persistor]
[com.grzm.sorty.server.redis :as redis]
[com.grzm.sorty.server.redis.predis :as predis]
[predis.core :as pc]))
(def http-port 8765)
(defn redis-init-fn [client]
(pc/set client
(redis/password-reset-key "brPI:KEY:<KEY>END_PIreset-token")
{:user/email-address "PI:EMAIL:<EMAIL>END_PI" :user/id 2}))
(defn system
"Provides a Component system map"
([]
(system {:pedestal {:config-fn (config/pedestal-config-fn :dev http-port)}
:redis {:init-fn redis-init-fn}}))
([{:keys [pedestal redis] :as _config}]
(component/system-map
:api (component/using (api/api-handler) [:app])
:app (app/app)
:pedestal (component/using
(pedestal/pedestal-servlet (:config-fn pedestal))
[:api :app])
:persistor (component/using (persistor/persistor)
[:redis])
:redis (predis/redis (:init-fn redis)))))
|
[
{
"context": "-family-tree.utils.data)\n\n(def members\n [{:name \"André\" :family \"Troncy\" :generation 1 :s",
"end": 62,
"score": 0.9998208284378052,
"start": 57,
"tag": "NAME",
"value": "André"
},
{
"context": "od-line true :birth 1859 :death 1931}\n {:name \"Francine\" :family \"Valli\" :generation 1 :sex ",
"end": 186,
"score": 0.9998433589935303,
"start": 178,
"tag": "NAME",
"value": "Francine"
},
{
"context": "od-line false :birth 1872 :death 1954}\n {:name \"Charles\" :family \"Patay\" :generation 2 :sex",
"end": 306,
"score": 0.9998362064361572,
"start": 299,
"tag": "NAME",
"value": "Charles"
},
{
"context": "od-line false :birth 1884 :death 1959}\n {:name \"Francois\" :family \"Bonnet\" :generation 2 :sex ",
"end": 428,
"score": 0.999838650226593,
"start": 420,
"tag": "NAME",
"value": "Francois"
},
{
"context": "od-line false :birth 1884 :death 1970}\n {:name \"Jeanne\" :family \"Troncy\" :generation 2 :se",
"end": 547,
"score": 0.9998207092285156,
"start": 541,
"tag": "NAME",
"value": "Jeanne"
},
{
"context": "od-line true :birth 1894 :death 1979}\n {:name \"Claudia\" :family \"Troncy\" :generation 2 :sex",
"end": 669,
"score": 0.9998352527618408,
"start": 662,
"tag": "NAME",
"value": "Claudia"
},
{
"context": "od-line true :birth 1895 :death 1968}\n {:name \"Maurice\" :family \"Troncy\" :generation 2 :sex",
"end": 790,
"score": 0.9998348355293274,
"start": 783,
"tag": "NAME",
"value": "Maurice"
},
{
"context": "od-line true :birth 1896 :death 1942}\n {:name \"Gustave\" :family \"Troncy\" :generation 2 :sex",
"end": 911,
"score": 0.999847412109375,
"start": 904,
"tag": "NAME",
"value": "Gustave"
},
{
"context": "od-line true :birth 1898 :death 1972}\n {:name \"Claude\" :family \"Troncy\" :generation 2 :se",
"end": 1031,
"score": 0.9998523592948914,
"start": 1025,
"tag": "NAME",
"value": "Claude"
},
{
"context": "od-line true :birth 1900 :death 1964}\n {:name \"Madeleine\" :family \"Galtier\" :generation 2 :sex \"",
"end": 1155,
"score": 0.999847412109375,
"start": 1146,
"tag": "NAME",
"value": "Madeleine"
},
{
"context": "od-line false :birth 1900 :death 1983}\n {:name \"Marcelle\" :family \"Desrayaud\" :generation 2 :sex ",
"end": 1275,
"score": 0.999836266040802,
"start": 1267,
"tag": "NAME",
"value": "Marcelle"
},
{
"context": "od-line false :birth 1901 :death 1966}\n {:name \"Robert\" :family \"Troncy\" :generation 2 :se",
"end": 1394,
"score": 0.9998062252998352,
"start": 1388,
"tag": "NAME",
"value": "Robert"
},
{
"context": "od-line true :birth 1902 :death 1959}\n {:name \"Renée\" :family \"Pointet\" :generation 2 :s",
"end": 1514,
"score": 0.9998013973236084,
"start": 1509,
"tag": "NAME",
"value": "Renée"
},
{
"context": "od-line false :birth 1907 :death 2000}\n {:name \"Elisabeth\" :family \"de Veron\" :generation 2 :sex \"",
"end": 1639,
"score": 0.999800980091095,
"start": 1630,
"tag": "NAME",
"value": "Elisabeth"
},
{
"context": "od-line false :birth 1909 :death 1994}\n {:name \"Albert\" :family \"Bertin\" :generation 3 :se",
"end": 1757,
"score": 0.9997914433479309,
"start": 1751,
"tag": "NAME",
"value": "Albert"
},
{
"context": ":death 1994}\n {:name \"Albert\" :family \"Bertin\" :generation 3 :sex \"male\" :blood-line fal",
"end": 1783,
"score": 0.8782305717468262,
"start": 1777,
"tag": "NAME",
"value": "Bertin"
},
{
"context": "od-line false :birth 1914 :death 1997}\n {:name \"Marcel\" :family \"Rodier\" :generation 3 :se",
"end": 1878,
"score": 0.9998157024383545,
"start": 1872,
"tag": "NAME",
"value": "Marcel"
},
{
"context": ":death 1997}\n {:name \"Marcel\" :family \"Rodier\" :generation 3 :sex \"male\" :blood-line fal",
"end": 1904,
"score": 0.9559474587440491,
"start": 1898,
"tag": "NAME",
"value": "Rodier"
},
{
"context": "od-line false :birth 1916 :death 2004}\n {:name \"Simone\" :family \"Patay\" :generation 3 :se",
"end": 1999,
"score": 0.9998083114624023,
"start": 1993,
"tag": "NAME",
"value": "Simone"
},
{
"context": "od-line true :birth 1917 :death 2000}\n {:name \"Roger\" :family \"Dieterlé\" :generation 3 :s",
"end": 2119,
"score": 0.9997959733009338,
"start": 2114,
"tag": "NAME",
"value": "Roger"
},
{
"context": "eath 2000}\n {:name \"Roger\" :family \"Dieterlé\" :generation 3 :sex \"male\" :blood-line false",
"end": 2148,
"score": 0.9364511370658875,
"start": 2142,
"tag": "NAME",
"value": "eterlé"
},
{
"context": "od-line false :birth 1917 :death 1990}\n {:name \"André\" :family \"Patay\" :generation 3 :s",
"end": 2240,
"score": 0.999798595905304,
"start": 2235,
"tag": "NAME",
"value": "André"
},
{
"context": "od-line true :birth 1919 :death 1995}\n {:name \"Denise\" :family \"Morel\" :generation 3 :se",
"end": 2362,
"score": 0.9997995495796204,
"start": 2356,
"tag": "NAME",
"value": "Denise"
},
{
"context": "female\" :blood-line false :birth 1922}\n {:name \"Jean\" :family \"Pelletier\" :generation 3 :",
"end": 2469,
"score": 0.9997910261154175,
"start": 2465,
"tag": "NAME",
"value": "Jean"
},
{
"context": "od-line false :birth 1922 :death 1994}\n {:name \"Geneviéve\" :family \"Troncy\" :generation 3 :sex \"",
"end": 2595,
"score": 0.9998174905776978,
"start": 2586,
"tag": "NAME",
"value": "Geneviéve"
},
{
"context": "od-line true :birth 1923 :death 1925}\n {:name \"Alice\" :family \"Patay\" :generation 3 :s",
"end": 2712,
"score": 0.9998520016670227,
"start": 2707,
"tag": "NAME",
"value": "Alice"
},
{
"context": "female\" :blood-line true :birth 1924}\n {:name \"Georges\" :family \"Troncy\" :generation 3 :sex",
"end": 2823,
"score": 0.9998282790184021,
"start": 2816,
"tag": "NAME",
"value": "Georges"
},
{
"context": "od-line true :birth 1926 :death 1993}\n {:name \"Pierre\" :family \"Bonnet\" :generation 3 :se",
"end": 2943,
"score": 0.999823808670044,
"start": 2937,
"tag": "NAME",
"value": "Pierre"
},
{
"context": "od-line true :birth 1927 :death 2008}\n {:name \"Guitou\" :family \"Taithe\" :generation 3 :se",
"end": 3064,
"score": 0.9998502731323242,
"start": 3058,
"tag": "NAME",
"value": "Guitou"
},
{
"context": "od-line false :birth 1928 :death 2005}\n {:name \"Françoise\" :family \"Bonnet\" :generation 3 :sex \"",
"end": 3188,
"score": 0.9998129606246948,
"start": 3179,
"tag": "NAME",
"value": "Françoise"
},
{
"context": "female\" :blood-line true :birth 1929}\n {:name \"Christiane\" :family \"Troncy\" :generation 3 :sex \"f",
"end": 3298,
"score": 0.9998264312744141,
"start": 3288,
"tag": "NAME",
"value": "Christiane"
},
{
"context": "od-line true :birth 1929 :death 2014}\n {:name \"André\" :family \"Troncy\" :generation 3 :s",
"end": 3414,
"score": 0.9997801780700684,
"start": 3409,
"tag": "NAME",
"value": "André"
},
{
"context": "male\" :blood-line true :birth 1933}\n {:name \"Simone\" :family \"Bourel\" :generation 3 :se",
"end": 3524,
"score": 0.9998006820678711,
"start": 3518,
"tag": "NAME",
"value": "Simone"
},
{
"context": "female\" :blood-line false :birth 1936}\n {:name \"Robert\" :family \"Barrière\" :generation 4 :se",
"end": 3633,
"score": 0.999826192855835,
"start": 3627,
"tag": "NAME",
"value": "Robert"
},
{
"context": "od-line false :birth 1936 :death 1999}\n {:name \"Marie-Suzanne\" :family \"Saillet\" :generation 3 :sex \"fema",
"end": 3761,
"score": 0.999840259552002,
"start": 3748,
"tag": "NAME",
"value": "Marie-Suzanne"
},
{
"context": "female\" :blood-line false :birth 1937}\n {:name \"Jaques\" :family \"Troncy\" :generation 3 :se",
"end": 3863,
"score": 0.9998185634613037,
"start": 3857,
"tag": "NAME",
"value": "Jaques"
},
{
"context": "male\" :blood-line true :birth 1939}\n {:name \"Françoise\" :family \"Bonhour\" :generation 3 :sex \"",
"end": 3975,
"score": 0.9997806549072266,
"start": 3966,
"tag": "NAME",
"value": "Françoise"
},
{
"context": "female\" :blood-line false :birth 1939}\n {:name \"Bernard\" :family \"Troncy\" :generation 3 :sex",
"end": 4082,
"score": 0.9997878670692444,
"start": 4075,
"tag": "NAME",
"value": "Bernard"
},
{
"context": "od-line true :birth 1940 :death 1992}\n {:name \"Marie-France\" :family \"Troncy\" :generation 3 :sex \"fem",
"end": 4208,
"score": 0.9998164176940918,
"start": 4196,
"tag": "NAME",
"value": "Marie-France"
},
{
"context": "female\" :blood-line true :birth 1940}\n {:name \"Alain\" :family \"Bertin\" :generation 4 :s",
"end": 4310,
"score": 0.9998184442520142,
"start": 4305,
"tag": "NAME",
"value": "Alain"
},
{
"context": "male\" :blood-line true :birth 1940}\n {:name \"Françoise\" :family \"Jullien\" :generation 4 :sex \"",
"end": 4423,
"score": 0.9998188018798828,
"start": 4414,
"tag": "NAME",
"value": "Françoise"
},
{
"context": "female\" :blood-line false :birth 1941}\n {:name \"Philippe\" :family \"Bonin\" :generation 4 :sex ",
"end": 4531,
"score": 0.9997736215591431,
"start": 4523,
"tag": "NAME",
"value": "Philippe"
},
{
"context": "male\" :blood-line false :birth 1941}\n {:name \"Jean-François\" :family \"Troncy\" :generation 3 :sex \"male",
"end": 4645,
"score": 0.9997984766960144,
"start": 4632,
"tag": "NAME",
"value": "Jean-François"
},
{
"context": "od-line true :birth 1942 :death 1994}\n {:name \"Danielle\" :family \"Bertin\" :generation 4 :sex ",
"end": 4761,
"score": 0.9997861385345459,
"start": 4753,
"tag": "NAME",
"value": "Danielle"
},
{
"context": "female\" :blood-line true :birth 1943}\n {:name \"Didier\" :family \"Goudot\" :generation 4 :se",
"end": 4868,
"score": 0.9997987747192383,
"start": 4862,
"tag": "NAME",
"value": "Didier"
},
{
"context": "male\" :blood-line false :birth 1943}\n {:name \"Claude-Henry\" :family \"Perrin\" :generation 3 :sex \"mal",
"end": 4983,
"score": 0.9998133778572083,
"start": 4971,
"tag": "NAME",
"value": "Claude-Henry"
},
{
"context": "male\" :blood-line false :birth 1943}\n {:name \"Hubert\" :family \"Troncy\" :generation 3 :se",
"end": 5086,
"score": 0.9997966289520264,
"start": 5080,
"tag": "NAME",
"value": "Hubert"
},
{
"context": "male\" :blood-line true :birth 1945}\n {:name \"Brigitte\" :family \"Patay\" :generation 4 :sex ",
"end": 5197,
"score": 0.999823808670044,
"start": 5189,
"tag": "NAME",
"value": "Brigitte"
},
{
"context": "female\" :blood-line true :birth 1947}\n {:name \"François\" :family \"Beaudin\" :generation 4 :sex ",
"end": 5306,
"score": 0.9998006820678711,
"start": 5298,
"tag": "NAME",
"value": "François"
},
{
"context": "od-line false :birth 1947 :death 1998}\n {:name \"Maurice\" :family \"Bertin\" :generation 4 :sex",
"end": 5426,
"score": 0.9998289942741394,
"start": 5419,
"tag": "NAME",
"value": "Maurice"
},
{
"context": "death 1998}\n {:name \"Maurice\" :family \"Bertin\" :generation 4 :sex \"male\" :blood-line t",
"end": 5449,
"score": 0.6496840119361877,
"start": 5446,
"tag": "NAME",
"value": "ert"
},
{
"context": "od-line true :birth 1948 :death 1949}\n {:name \"Marie-Geneviéve\" :family \"Sommer\" :generation 3 :sex \"female",
"end": 5555,
"score": 0.9998546242713928,
"start": 5540,
"tag": "NAME",
"value": "Marie-Geneviéve"
},
{
"context": "female\" :blood-line false :birth 1949}\n {:name \"Catherine\" :family \"Rodier\" :generation 4 :sex \"",
"end": 5658,
"score": 0.9998433589935303,
"start": 5649,
"tag": "NAME",
"value": "Catherine"
},
{
"context": "female\" :blood-line true :birth 1949}\n {:name \"Patrick\" :family \"Le Blanc\" :generation 4 :sex",
"end": 5765,
"score": 0.999832034111023,
"start": 5758,
"tag": "NAME",
"value": "Patrick"
},
{
"context": "od-line false :birth 1949 :death 2012}\n {:name \"Rosamund\" :family \"Barnes\" :generation 3 :sex ",
"end": 5887,
"score": 0.9998329281806946,
"start": 5879,
"tag": "NAME",
"value": "Rosamund"
},
{
"context": "female\" :blood-line false :birth 1951}\n {:name \"Hiroshi\" :family \"Suzukawa\" :generation 4 :sex",
"end": 5995,
"score": 0.9998393058776855,
"start": 5988,
"tag": "NAME",
"value": "Hiroshi"
},
{
"context": "male\" :blood-line false :birth 1951}\n {:name \"Laurence\" :family \"Dieterlé\" :generation 4 :sex ",
"end": 6105,
"score": 0.9998183250427246,
"start": 6097,
"tag": "NAME",
"value": "Laurence"
},
{
"context": "female\" :blood-line true :birth 1951}\n {:name \"Michel\" :family \"Patay\" :generation 4 :se",
"end": 6212,
"score": 0.9998114109039307,
"start": 6206,
"tag": "NAME",
"value": "Michel"
},
{
"context": "male\" :blood-line true :birth 1951}\n {:name \"Cheryl\" :family \"Olds\" :generation 4 :se",
"end": 6321,
"score": 0.9998312592506409,
"start": 6315,
"tag": "NAME",
"value": "Cheryl"
},
{
"context": "female\" :blood-line false :birth 1951}\n {:name \"Philippe\" :family \"Rodier\" :generation 4 :sex ",
"end": 6432,
"score": 0.9997951984405518,
"start": 6424,
"tag": "NAME",
"value": "Philippe"
},
{
"context": "male\" :blood-line true :birth 1952}\n {:name \"Alain\" :family \"Perret\" :generation 4 :s",
"end": 6538,
"score": 0.9998029470443726,
"start": 6533,
"tag": "NAME",
"value": "Alain"
},
{
"context": "rth 1952}\n {:name \"Alain\" :family \"Perret\" :generation 4 :sex \"male\" :blood-line fal",
"end": 6565,
"score": 0.8972801566123962,
"start": 6562,
"tag": "NAME",
"value": "ret"
},
{
"context": "male\" :blood-line false :birth 1952}\n {:name \"Régis\" :family \"Dieterlé\" :generation 4 :s",
"end": 6647,
"score": 0.9998058676719666,
"start": 6642,
"tag": "NAME",
"value": "Régis"
},
{
"context": "od-line true :birth 1953 :death 1994}\n {:name \"Cécile\" :family \"Dieterlé\" :generation 4 :se",
"end": 6769,
"score": 0.9998120665550232,
"start": 6763,
"tag": "NAME",
"value": "Cécile"
},
{
"context": ":death 1994}\n {:name \"Cécile\" :family \"Dieterlé\" :generation 4 :sex \"female\" :blood-line true ",
"end": 6797,
"score": 0.8347365260124207,
"start": 6789,
"tag": "NAME",
"value": "Dieterlé"
},
{
"context": "female\" :blood-line true :birth 1955}\n {:name \"Fabienne\" :family \"Bonnet\" :generation 4 :sex ",
"end": 6880,
"score": 0.9998273253440857,
"start": 6872,
"tag": "NAME",
"value": "Fabienne"
},
{
"context": "female\" :blood-line true :birth 1957}\n {:name \"Agnés\" :family \"Dieterlé\" :generation 4 :s",
"end": 6986,
"score": 0.9998300671577454,
"start": 6981,
"tag": "NAME",
"value": "Agnés"
},
{
"context": "female\" :blood-line true :birth 1958}\n {:name \"Marie-Delphine\" :family \"Muzelli\" :generation 4 :sex \"femal",
"end": 7104,
"score": 0.9998341202735901,
"start": 7090,
"tag": "NAME",
"value": "Marie-Delphine"
},
{
"context": "female\" :blood-line false :birth 1958}\n {:name \"Lionel\" :family \"Pourtier\" :generation 5 :se",
"end": 7205,
"score": 0.9998264312744141,
"start": 7199,
"tag": "NAME",
"value": "Lionel"
},
{
"context": "male\" :blood-line false :birth 1958}\n {:name \"Anne\" :family \"Chapuis\" :generation 4 :",
"end": 7312,
"score": 0.9998171329498291,
"start": 7308,
"tag": "NAME",
"value": "Anne"
},
{
"context": "female\" :blood-line false :birth 1959}\n {:name \"Marielle\" :family \"Bonnet\" :generation 4 :sex ",
"end": 7425,
"score": 0.9998264312744141,
"start": 7417,
"tag": "NAME",
"value": "Marielle"
},
{
"context": "female\" :blood-line true :birth 1959}\n {:name \"Jean-Michel\" :family \"Giraud\" :generation 4 :sex \"ma",
"end": 7537,
"score": 0.9997900128364563,
"start": 7526,
"tag": "NAME",
"value": "Jean-Michel"
},
{
"context": "male\" :blood-line false :birth 1960}\n {:name \"Nadine\" :family \"Nesme\" :generation 4 :se",
"end": 7641,
"score": 0.9998257160186768,
"start": 7635,
"tag": "NAME",
"value": "Nadine"
},
{
"context": "female\" :blood-line false :birth 1961}\n {:name \"Chantal\" :family \"Bonnet\" :generation 4 :sex",
"end": 7751,
"score": 0.999841034412384,
"start": 7744,
"tag": "NAME",
"value": "Chantal"
},
{
"context": "female\" :blood-line true :birth 1962}\n {:name \"Christophe\" :family \"Morin\" :generation 5 :sex \"m",
"end": 7863,
"score": 0.9998164772987366,
"start": 7853,
"tag": "NAME",
"value": "Christophe"
},
{
"context": "male\" :blood-line false :birth 1963}\n {:name \"Jérôme\" :family \"Troncy\" :generation 4 :se",
"end": 7968,
"score": 0.9998264908790588,
"start": 7962,
"tag": "NAME",
"value": "Jérôme"
},
{
"context": "od-line true :birth 1965 :death 1989}\n {:name \"Laurence\" :family \"Bertin\" :generation 5 :sex ",
"end": 8091,
"score": 0.99981290102005,
"start": 8083,
"tag": "NAME",
"value": "Laurence"
},
{
"context": "female\" :blood-line true :birth 1966}\n {:name \"Franck\" :family \"Bonin\" :generation 5 :se",
"end": 8198,
"score": 0.9998106956481934,
"start": 8192,
"tag": "NAME",
"value": "Franck"
},
{
"context": "male\" :blood-line true :birth 1966}\n {:name \"Armelle\" :family \"Troncy\" :generation 4 :sex",
"end": 8308,
"score": 0.9998464584350586,
"start": 8301,
"tag": "NAME",
"value": "Armelle"
},
{
"context": "female\" :blood-line true :birth 1967}\n {:name \"Isabelle\" :family \"Chapuzet\" :generation 5 :sex ",
"end": 8418,
"score": 0.9998310208320618,
"start": 8410,
"tag": "NAME",
"value": "Isabelle"
},
{
"context": "female\" :blood-line false :birth 1967}\n {:name \"Béatrice\" :family \"Abadie\" :generation 4 :sex ",
"end": 8527,
"score": 0.999835729598999,
"start": 8519,
"tag": "NAME",
"value": "Béatrice"
},
{
"context": "female\" :blood-line false :birth 1967}\n {:name \"Frédéric\" :family \"Bertin\" :generation 5 :sex ",
"end": 8636,
"score": 0.999828577041626,
"start": 8628,
"tag": "NAME",
"value": "Frédéric"
},
{
"context": "male\" :blood-line true :birth 1968}\n {:name \"Jean-Marc\" :family \"Faivre\" :generation 4 :sex \"",
"end": 8746,
"score": 0.9998025894165039,
"start": 8737,
"tag": "NAME",
"value": "Jean-Marc"
},
{
"context": "male\" :blood-line false :birth 1968}\n {:name \"Erwan\" :family \"Le Mintier\" :generation 5 :s",
"end": 8851,
"score": 0.9998344779014587,
"start": 8846,
"tag": "NAME",
"value": "Erwan"
},
{
"context": "male\" :blood-line false :birth 1968}\n {:name \"Emmanuel\" :family \"Perrin\" :generation 4 :sex ",
"end": 8963,
"score": 0.9998186230659485,
"start": 8955,
"tag": "NAME",
"value": "Emmanuel"
},
{
"context": "male\" :blood-line true :birth 1968}\n {:name \"Fabrice\" :family \"Bonin\" :generation 5 :sex",
"end": 9071,
"score": 0.9998279809951782,
"start": 9064,
"tag": "NAME",
"value": "Fabrice"
},
{
"context": "male\" :blood-line true :birth 1968}\n {:name \"Antoine\" :family \"Troncy\" :generation 4 :sex",
"end": 9180,
"score": 0.9998294711112976,
"start": 9173,
"tag": "NAME",
"value": "Antoine"
},
{
"context": "male\" :blood-line true :birth 1969}\n {:name \"Laurence\" :family \"Sadoux\" :generation 4 :sex ",
"end": 9290,
"score": 0.9998307228088379,
"start": 9282,
"tag": "NAME",
"value": "Laurence"
},
{
"context": "female\" :blood-line false :birth 1969}\n {:name \"Alexandre\" :family \"Perrin\" :generation 4 :sex \"",
"end": 9400,
"score": 0.9998127818107605,
"start": 9391,
"tag": "NAME",
"value": "Alexandre"
},
{
"context": "male\" :blood-line true :birth 1969}\n {:name \"Françoise\" :family \"Cottin\" :generation 5 :sex \"",
"end": 9509,
"score": 0.9998012781143188,
"start": 9500,
"tag": "NAME",
"value": "Françoise"
},
{
"context": "female\" :blood-line false :birth 1969}\n {:name \"Nicolas\" :family \"Bonin\" :generation 5 :sex",
"end": 9616,
"score": 0.9998161792755127,
"start": 9609,
"tag": "NAME",
"value": "Nicolas"
},
{
"context": "male\" :blood-line true :birth 1970}\n {:name \"Anne-Laurie\" :family \"Troncy\" :generation 4 :sex \"fe",
"end": 9729,
"score": 0.999840497970581,
"start": 9718,
"tag": "NAME",
"value": "Anne-Laurie"
},
{
"context": "th 1970}\n {:name \"Anne-Laurie\" :family \"Troncy\" :generation 4 :sex \"female\" :blood-line tru",
"end": 9750,
"score": 0.8015734553337097,
"start": 9748,
"tag": "NAME",
"value": "cy"
},
{
"context": "female\" :blood-line true :birth 1971}\n {:name \"Clémentine\" :family \"Labaty\" :generation 4 :sex \"f",
"end": 9837,
"score": 0.9998493194580078,
"start": 9827,
"tag": "NAME",
"value": "Clémentine"
},
{
"context": "female\" :blood-line false :birth 1971}\n {:name \"Sophie\" :family \"Jullat\" :generation 4 :se",
"end": 9942,
"score": 0.9998518824577332,
"start": 9936,
"tag": "NAME",
"value": "Sophie"
},
{
"context": "female\" :blood-line false :birth 1971}\n {:name \"Anne\" :family \"Bertin\" :generation 5 :",
"end": 10049,
"score": 0.9998337030410767,
"start": 10045,
"tag": "NAME",
"value": "Anne"
},
{
"context": "female\" :blood-line true :birth 1971}\n {:name \"Charles-Eric\" :family \"Bonin\" :generation 5 :sex \"mal",
"end": 10166,
"score": 0.9998175501823425,
"start": 10154,
"tag": "NAME",
"value": "Charles-Eric"
},
{
"context": "od-line true :birth 1972 :death 1972}\n {:name \"Marianne\" :family \"Goudot\" :generation 5 :sex ",
"end": 10283,
"score": 0.9998397827148438,
"start": 10275,
"tag": "NAME",
"value": "Marianne"
},
{
"context": "female\" :blood-line true :birth 1972}\n {:name \"Vanessa\" :family \"Lebon\" :generation 5 :sex",
"end": 10391,
"score": 0.9998336434364319,
"start": 10384,
"tag": "NAME",
"value": "Vanessa"
},
{
"context": "female\" :blood-line false :birth 1973}\n {:name \"Xavier\" :family \"Bertin\" :generation 5 :se",
"end": 10499,
"score": 0.999824047088623,
"start": 10493,
"tag": "NAME",
"value": "Xavier"
},
{
"context": "male\" :blood-line true :birth 1974}\n {:name \"Valentine\" :family \"Le Blanc\" :generation 5 :sex \"",
"end": 10611,
"score": 0.9998398423194885,
"start": 10602,
"tag": "NAME",
"value": "Valentine"
},
{
"context": "female\" :blood-line true :birth 1974}\n {:name \"Bruno\" :family \"Cheilan\" :generation 5 :s",
"end": 10716,
"score": 0.9998500347137451,
"start": 10711,
"tag": "NAME",
"value": "Bruno"
},
{
"context": "male\" :blood-line false :birth 1974}\n {:name \"Matthieu\" :family \"Maria\" :generation 5 :sex ",
"end": 10828,
"score": 0.9998309016227722,
"start": 10820,
"tag": "NAME",
"value": "Matthieu"
},
{
"context": "male\" :blood-line false :birth 1974}\n {:name \"Julia\" :family \"Goudot\" :generation 5 :s",
"end": 10934,
"score": 0.9998782873153687,
"start": 10929,
"tag": "NAME",
"value": "Julia"
},
{
"context": "birth 1974}\n {:name \"Julia\" :family \"Goudot\" :generation 5 :sex \"female\" :blood-line tru",
"end": 10961,
"score": 0.999821662902832,
"start": 10956,
"tag": "NAME",
"value": "oudot"
},
{
"context": "female\" :blood-line true :birth 1975}\n {:name \"Michaël\" :family \"Calatraba\" :generation 5 :sex",
"end": 11045,
"score": 0.9997930526733398,
"start": 11038,
"tag": "NAME",
"value": "Michaël"
},
{
"context": "male\" :blood-line false :birth 1975}\n {:name \"Christelle\" :family \"Troncy\" :generation 4 :sex \"f",
"end": 11157,
"score": 0.9998058080673218,
"start": 11147,
"tag": "NAME",
"value": "Christelle"
},
{
"context": "female\" :blood-line true :birth 1975}\n {:name \"Valérie\" :family \"Barrière\" :generation 5 :sex",
"end": 11263,
"score": 0.9998171329498291,
"start": 11256,
"tag": "NAME",
"value": "Valérie"
},
{
"context": "od-line true :birth 1976 :death 1982}\n {:name \"Aurélie\" :family \"Le Blanc\" :generation 5 :sex",
"end": 11384,
"score": 0.9998178482055664,
"start": 11377,
"tag": "NAME",
"value": "Aurélie"
},
{
"context": "female\" :blood-line true :birth 1976}\n {:name \"Cyril\" :family \"Troncy\" :generation 4 :s",
"end": 11491,
"score": 0.9998063445091248,
"start": 11486,
"tag": "NAME",
"value": "Cyril"
},
{
"context": "male\" :blood-line true :birth 1976}\n {:name \"Camilla\" :family \"Maggialetti\" :generation 4 :sex",
"end": 11602,
"score": 0.9997993111610413,
"start": 11595,
"tag": "NAME",
"value": "Camilla"
},
{
"context": "female\" :blood-line false :birth 1976}\n {:name \"Guilhem\" :family \"Troncy\" :generation 4 :sex",
"end": 11711,
"score": 0.9998064041137695,
"start": 11704,
"tag": "NAME",
"value": "Guilhem"
},
{
"context": "male\" :blood-line true :birth 1976}\n {:name \"Pierrick\" :family \"Wolff\" :generation 5 :sex ",
"end": 11821,
"score": 0.9998164176940918,
"start": 11813,
"tag": "NAME",
"value": "Pierrick"
},
{
"context": "male\" :blood-line false :birth 1977}\n {:name \"Maud\" :family \"Russo\" :generation 4 :",
"end": 11926,
"score": 0.9998356103897095,
"start": 11922,
"tag": "NAME",
"value": "Maud"
},
{
"context": "female\" :blood-line false :birth 1977}\n {:name \"Anne-Claire\" :family \"Antoni\" :generation 4 :sex \"fe",
"end": 12042,
"score": 0.9998037219047546,
"start": 12031,
"tag": "NAME",
"value": "Anne-Claire"
},
{
"context": "female\" :blood-line false :birth 1977}\n {:name \"Mathieu\" :family \"Beaudin\" :generation 5 :sex",
"end": 12147,
"score": 0.9998135566711426,
"start": 12140,
"tag": "NAME",
"value": "Mathieu"
},
{
"context": "male\" :blood-line true :birth 1978}\n {:name \"Sandrine\" :family \"Barrière\" :generation 5 :sex ",
"end": 12257,
"score": 0.9998049736022949,
"start": 12249,
"tag": "NAME",
"value": "Sandrine"
},
{
"context": "female\" :blood-line true :birth 1979}\n {:name \"Mélanie\" :family \"Beaudin\" :generation 5 :sex",
"end": 12365,
"score": 0.9998126029968262,
"start": 12358,
"tag": "NAME",
"value": "Mélanie"
},
{
"context": "female\" :blood-line true :birth 1980}\n {:name \"Cédric\" :family \"Troncy\" :generation 4 :se",
"end": 12473,
"score": 0.9998221397399902,
"start": 12467,
"tag": "NAME",
"value": "Cédric"
},
{
"context": "male\" :blood-line true :birth 1980}\n {:name \"Romain\" :family \"Troncy\" :generation 4 :se",
"end": 12582,
"score": 0.9998271465301514,
"start": 12576,
"tag": "NAME",
"value": "Romain"
},
{
"context": "male\" :blood-line true :birth 1980}\n {:name \"Oliver\" :family \"Gaillet\" :generation 5 :se",
"end": 12691,
"score": 0.9998286962509155,
"start": 12685,
"tag": "NAME",
"value": "Oliver"
},
{
"context": "male\" :blood-line false :birth 1981}\n {:name \"Eric\" :family \"Barrière\" :generation 5 :",
"end": 12798,
"score": 0.9998195171356201,
"start": 12794,
"tag": "NAME",
"value": "Eric"
},
{
"context": "male\" :blood-line true :birth 1982}\n {:name \"Alice\" :family \"Beaudin\" :generation 5 :s",
"end": 12908,
"score": 0.9998471736907959,
"start": 12903,
"tag": "NAME",
"value": "Alice"
},
{
"context": "female\" :blood-line true :birth 1982}\n {:name \"Didier\" :family \"Troncy\" :generation 4 :se",
"end": 13018,
"score": 0.9998103380203247,
"start": 13012,
"tag": "NAME",
"value": "Didier"
},
{
"context": "male\" :blood-line true :birth 1982}\n {:name \"Olivier\" :family \"Troncy\" :generation 4 :sex",
"end": 13128,
"score": 0.9998071789741516,
"start": 13121,
"tag": "NAME",
"value": "Olivier"
},
{
"context": "male\" :blood-line true :birth 1982}\n {:name \"Thibault\" :family \"Dieterlé\" :generation 5 :sex ",
"end": 13238,
"score": 0.9998197555541992,
"start": 13230,
"tag": "NAME",
"value": "Thibault"
},
{
"context": "male\" :blood-line true :birth 1984}\n {:name \"Leïla\" :family \"Suzukawa\" :generation 5 :s",
"end": 13344,
"score": 0.999805748462677,
"start": 13339,
"tag": "NAME",
"value": "Leïla"
},
{
"context": "female\" :blood-line true :birth 1984}\n {:name \"Anne-Sophie\" :family \"Cappio\" :generation 5 :sex \"fe",
"end": 13459,
"score": 0.9998096823692322,
"start": 13448,
"tag": "NAME",
"value": "Anne-Sophie"
},
{
"context": "female\" :blood-line false :birth 1985}\n {:name \"Caroline\" :family \"Rodier\" :generation 5 :sex ",
"end": 13565,
"score": 0.9997957944869995,
"start": 13557,
"tag": "NAME",
"value": "Caroline"
},
{
"context": "female\" :blood-line true :birth 1985}\n {:name \"Marine\" :family \"Faivre\" :generation 5 :se",
"end": 13672,
"score": 0.9997992515563965,
"start": 13666,
"tag": "NAME",
"value": "Marine"
},
{
"context": "female\" :blood-line true :birth 1986}\n {:name \"Johanna\" :family \"Viosi\" :generation 5 :sex",
"end": 13782,
"score": 0.9998415112495422,
"start": 13775,
"tag": "NAME",
"value": "Johanna"
},
{
"context": "female\" :blood-line false :birth 1986}\n {:name \"Clément\" :family \"Beaudin\" :generation 5 :sex",
"end": 13891,
"score": 0.99983811378479,
"start": 13884,
"tag": "NAME",
"value": "Clément"
},
{
"context": "male\" :blood-line true :birth 1986}\n {:name \"Pierre\" :family \"Troncy\" :generation 4 :se",
"end": 13999,
"score": 0.9998375773429871,
"start": 13993,
"tag": "NAME",
"value": "Pierre"
},
{
"context": "irth 1986}\n {:name \"Pierre\" :family \"Troncy\" :generation 4 :sex \"male\" :blood-line tru",
"end": 14025,
"score": 0.6443443298339844,
"start": 14021,
"tag": "NAME",
"value": "oncy"
},
{
"context": "male\" :blood-line true :birth 1986}\n {:name \"Keigo\" :family \"Suzukawa\" :generation 5 :s",
"end": 14107,
"score": 0.9998465776443481,
"start": 14102,
"tag": "NAME",
"value": "Keigo"
},
{
"context": "male\" :blood-line true :birth 1986}\n {:name \"Laetitia\" :family \"Rodier\" :generation 5 :sex ",
"end": 14219,
"score": 0.9998341202735901,
"start": 14211,
"tag": "NAME",
"value": "Laetitia"
},
{
"context": "rth 1986}\n {:name \"Laetitia\" :family \"Rodier\" :generation 5 :sex \"female\" :blood-line tru",
"end": 14243,
"score": 0.7473196983337402,
"start": 14240,
"tag": "NAME",
"value": "ier"
},
{
"context": "female\" :blood-line true :birth 1987}\n {:name \"Grégoire\" :family \"Giraud\" :generation 5 :sex ",
"end": 14328,
"score": 0.9998401403427124,
"start": 14320,
"tag": "NAME",
"value": "Grégoire"
},
{
"context": "male\" :blood-line true :birth 1987}\n {:name \"Vincent\" :family \"Pourtier\" :generation 6 :sex",
"end": 14436,
"score": 0.9998278617858887,
"start": 14429,
"tag": "NAME",
"value": "Vincent"
},
{
"context": "male\" :blood-line true :birth 1988}\n {:name \"Kaya\" :family \"Suzukawa\" :generation 5 :",
"end": 14542,
"score": 0.9995212554931641,
"start": 14538,
"tag": "NAME",
"value": "Kaya"
},
{
"context": "female\" :blood-line true :birth 1988}\n {:name \"Blandine\" :family \"Patay\" :generation 5 :sex ",
"end": 14655,
"score": 0.9998435974121094,
"start": 14647,
"tag": "NAME",
"value": "Blandine"
},
{
"context": "female\" :blood-line true :birth 1989}\n {:name \"Charles-Henry\" :family \"Rodier\" :generation 5 :sex \"male",
"end": 14769,
"score": 0.9998487830162048,
"start": 14756,
"tag": "NAME",
"value": "Charles-Henry"
},
{
"context": "male\" :blood-line true :birth 1989}\n {:name \"Henry\" :family \"Perret\" :generation 5 :s",
"end": 14870,
"score": 0.9998427033424377,
"start": 14865,
"tag": "NAME",
"value": "Henry"
},
{
"context": "rth 1989}\n {:name \"Henry\" :family \"Perret\" :generation 5 :sex \"male\" :blood-line tru",
"end": 14897,
"score": 0.8420405387878418,
"start": 14894,
"tag": "NAME",
"value": "ret"
},
{
"context": "male\" :blood-line true :birth 1989}\n {:name \"Charles\" :family \"Patay\" :generation 5 :sex",
"end": 14981,
"score": 0.9998313188552856,
"start": 14974,
"tag": "NAME",
"value": "Charles"
},
{
"context": "male\" :blood-line true :birth 1990}\n {:name \"Hubert\" :family \"Giraud\" :generation 5 :se",
"end": 15089,
"score": 0.9998252391815186,
"start": 15083,
"tag": "NAME",
"value": "Hubert"
},
{
"context": "male\" :blood-line true :birth 1990}\n {:name \"Pierre\" :family \"Pourtier\" :generation 6 :se",
"end": 15198,
"score": 0.9997896552085876,
"start": 15192,
"tag": "NAME",
"value": "Pierre"
},
{
"context": "male\" :blood-line true :birth 1991}\n {:name \"Marine\" :family \"Troncy\" :generation 4 :se",
"end": 15307,
"score": 0.9998246431350708,
"start": 15301,
"tag": "NAME",
"value": "Marine"
},
{
"context": "female\" :blood-line true :birth 1991}\n {:name \"Jean\" :family \"Pourtier\" :generation 6 :",
"end": 15414,
"score": 0.9998046159744263,
"start": 15410,
"tag": "NAME",
"value": "Jean"
},
{
"context": "male\" :blood-line true :birth 1992}\n {:name \"Alix\" :family \"Perret\" :generation 5 :",
"end": 15523,
"score": 0.9997934103012085,
"start": 15519,
"tag": "NAME",
"value": "Alix"
},
{
"context": "male\" :blood-line true :birth 1992}\n {:name \"Ségolène\" :family \"Giraud\" :generation 5 :sex ",
"end": 15636,
"score": 0.9998317956924438,
"start": 15628,
"tag": "NAME",
"value": "Ségolène"
},
{
"context": "female\" :blood-line true :birth 1992}\n {:name \"Armelle\" :family \"Perret\" :generation 5 :sex",
"end": 15744,
"score": 0.9998300075531006,
"start": 15737,
"tag": "NAME",
"value": "Armelle"
},
{
"context": "female\" :blood-line true :birth 1994}\n {:name \"Charlotte\" :family \"Faivre\" :generation 5 :sex \"",
"end": 15855,
"score": 0.9998238682746887,
"start": 15846,
"tag": "NAME",
"value": "Charlotte"
},
{
"context": "female\" :blood-line true :birth 1994}\n {:name \"Emilie\" :family \"Bertin\" :generation 6 :se",
"end": 15961,
"score": 0.9998157620429993,
"start": 15955,
"tag": "NAME",
"value": "Emilie"
},
{
"context": "female\" :blood-line true :birth 1995}\n {:name \"Mathilde\" :family \"Perrin\" :generation 5 :sex ",
"end": 16072,
"score": 0.999809980392456,
"start": 16064,
"tag": "NAME",
"value": "Mathilde"
},
{
"context": "female\" :blood-line true :birth 1996}\n {:name \"Valérie\" :family \"Pourtier\" :generation 6 :sex",
"end": 16180,
"score": 0.9998158812522888,
"start": 16173,
"tag": "NAME",
"value": "Valérie"
},
{
"context": "female\" :blood-line true :birth 1997}\n {:name \"Prune\" :family \"Faivre\" :generation 5 :s",
"end": 16287,
"score": 0.9998233914375305,
"start": 16282,
"tag": "NAME",
"value": "Prune"
},
{
"context": "female\" :blood-line true :birth 1997}\n {:name \"Alexandre\" :family \"Bertin\" :generation 6 :sex \"",
"end": 16400,
"score": 0.9998083114624023,
"start": 16391,
"tag": "NAME",
"value": "Alexandre"
},
{
"context": "male\" :blood-line true :birth 1998}\n {:name \"Romain\" :family \"Bonin\" :generation 6 :se",
"end": 16506,
"score": 0.9997981786727905,
"start": 16500,
"tag": "NAME",
"value": "Romain"
},
{
"context": ":birth 1998}\n {:name \"Romain\" :family \"Bonin\" :generation 6 :sex \"male\" :blood-line tr",
"end": 16531,
"score": 0.9885263442993164,
"start": 16526,
"tag": "NAME",
"value": "Bonin"
},
{
"context": "male\" :blood-line true :birth 1999}\n {:name \"Florian\" :family \"Morin\" :generation 6 :sex",
"end": 16616,
"score": 0.9998102188110352,
"start": 16609,
"tag": "NAME",
"value": "Florian"
},
{
"context": "male\" :blood-line true :birth 2001}\n {:name \"Pauline\" :family \"Bonin\" :generation 6 :sex",
"end": 16725,
"score": 0.9998317360877991,
"start": 16718,
"tag": "NAME",
"value": "Pauline"
},
{
"context": "female\" :blood-line true :birth 2001}\n {:name \"Mathis\" :family \"Perrin\" :generation 5 :se",
"end": 16833,
"score": 0.9998111128807068,
"start": 16827,
"tag": "NAME",
"value": "Mathis"
},
{
"context": "male\" :blood-line true :birth 2001}\n {:name \"Idriss-Valentin\" :family \"Bonin\" :generation 6 :sex \"female",
"end": 16951,
"score": 0.9998208284378052,
"start": 16936,
"tag": "NAME",
"value": "Idriss-Valentin"
},
{
"context": "female\" :blood-line true :birth 2002}\n {:name \"Louis\" :family \"Troncy\" :generation 5 :s",
"end": 17050,
"score": 0.9997904300689697,
"start": 17045,
"tag": "NAME",
"value": "Louis"
},
{
"context": "male\" :blood-line true :birth 2002}\n {:name \"Ambre\" :family \"Bonin\" :generation 6 :s",
"end": 17159,
"score": 0.9998281598091125,
"start": 17154,
"tag": "NAME",
"value": "Ambre"
},
{
"context": "male\" :blood-line true :birth 2004}\n {:name \"Sébastien\" :family \"Troncy\" :generation 5 :sex \"",
"end": 17272,
"score": 0.999768853187561,
"start": 17263,
"tag": "NAME",
"value": "Sébastien"
},
{
"context": "male\" :blood-line true :birth 2004}\n {:name \"Gabrielle\" :family \"Cheilan\" :generation 6 :sex \"",
"end": 17381,
"score": 0.999809741973877,
"start": 17372,
"tag": "NAME",
"value": "Gabrielle"
},
{
"context": "female\" :blood-line true :birth 2005}\n {:name \"Aymeric\" :family \"Le Mintier\" :generation 6 :sex",
"end": 17488,
"score": 0.999793291091919,
"start": 17481,
"tag": "NAME",
"value": "Aymeric"
},
{
"context": "male\" :blood-line true :birth 2005}\n {:name \"Clémence\" :family \"Troncy\" :generation 5 :sex ",
"end": 17598,
"score": 0.9998144507408142,
"start": 17590,
"tag": "NAME",
"value": "Clémence"
},
{
"context": "female\" :blood-line true :birth 2005}\n {:name \"Louna\" :family \"Perrin\" :generation 5 :s",
"end": 17704,
"score": 0.9998220205307007,
"start": 17699,
"tag": "NAME",
"value": "Louna"
},
{
"context": "male\" :blood-line true :birth 2005}\n {:name \"Lucas\" :family \"Morin\" :generation 6 :s",
"end": 17813,
"score": 0.9997115135192871,
"start": 17808,
"tag": "NAME",
"value": "Lucas"
},
{
"context": "male\" :blood-line true :birth 2006}\n {:name \"Julien\" :family \"Bonin\" :generation 6 :se",
"end": 17923,
"score": 0.999769926071167,
"start": 17917,
"tag": "NAME",
"value": "Julien"
},
{
"context": "rth 2006}\n {:name \"Julien\" :family \"Bonin\" :generation 6 :sex \"male\" :blood-line tr",
"end": 17948,
"score": 0.5762839317321777,
"start": 17946,
"tag": "NAME",
"value": "in"
},
{
"context": "male\" :blood-line true :birth 2006}\n {:name \"Guillaume\" :family \"Troncy\" :generation 5 :sex \"",
"end": 18035,
"score": 0.9998010993003845,
"start": 18026,
"tag": "NAME",
"value": "Guillaume"
},
{
"context": "male\" :blood-line true :birth 2006}\n {:name \"Eva\" :family \"Perrin\" :generation 5 ",
"end": 18138,
"score": 0.999758243560791,
"start": 18135,
"tag": "NAME",
"value": "Eva"
},
{
"context": "female\" :blood-line true :birth 2006}\n {:name \"Milo\" :family \"Perrin\" :generation 5 :",
"end": 18248,
"score": 0.9997674822807312,
"start": 18244,
"tag": "NAME",
"value": "Milo"
},
{
"context": "male\" :blood-line true :birth 2006}\n {:name \"Jeanne\" :family \"Le Mintier\" :generation 6 :se",
"end": 18359,
"score": 0.9998024106025696,
"start": 18353,
"tag": "NAME",
"value": "Jeanne"
},
{
"context": "female\" :blood-line true :birth 2007}\n {:name \"Robin\" :family \"Cheilan\" :generation 6 :s",
"end": 18467,
"score": 0.9997700452804565,
"start": 18462,
"tag": "NAME",
"value": "Robin"
},
{
"context": "male\" :blood-line true :birth 2007}\n {:name \"Lola\" :family \"Morin\" :generation 6 :",
"end": 18575,
"score": 0.9997613430023193,
"start": 18571,
"tag": "NAME",
"value": "Lola"
},
{
"context": "female\" :blood-line true :birth 2008}\n {:name \"Hanaé\" :family \"Bonin\" :generation 6 :s",
"end": 18685,
"score": 0.9998156428337097,
"start": 18680,
"tag": "NAME",
"value": "Hanaé"
},
{
"context": "female\" :blood-line true :birth 2009}\n {:name \"Clara\" :family \"Le Mintier\" :generation 6 :s",
"end": 18794,
"score": 0.999773383140564,
"start": 18789,
"tag": "NAME",
"value": "Clara"
},
{
"context": "female\" :blood-line true :birth 2009}\n {:name \"Charles\" :family \"Troncy\" :generation 5 :sex",
"end": 18905,
"score": 0.9997722506523132,
"start": 18898,
"tag": "NAME",
"value": "Charles"
},
{
"context": "male\" :blood-line true :birth 2009}\n {:name \"Balian\" :family \"Perrin\" :generation 5 :se",
"end": 19013,
"score": 0.9997966289520264,
"start": 19007,
"tag": "NAME",
"value": "Balian"
},
{
"context": "male\" :blood-line true :birth 2009}\n {:name \"Simon\" :family \"Wolff\" :generation 6 :s",
"end": 19121,
"score": 0.9997285604476929,
"start": 19116,
"tag": "NAME",
"value": "Simon"
},
{
"context": "male\" :blood-line true :birth 2010}\n {:name \"Nell\" :family \"Calatraba\" :generation 6 :",
"end": 19229,
"score": 0.9996668100357056,
"start": 19225,
"tag": "NAME",
"value": "Nell"
},
{
"context": "female\" :blood-line true :birth 2010}\n {:name \"Caroline\" :family \"Bonin\" :generation 6 :sex ",
"end": 19342,
"score": 0.9997806549072266,
"start": 19334,
"tag": "NAME",
"value": "Caroline"
},
{
"context": "female\" :blood-line true :birth 2011}\n {:name \"Augustin\" :family \"Gaillet\" :generation 6 :sex ",
"end": 19451,
"score": 0.9997440576553345,
"start": 19443,
"tag": "NAME",
"value": "Augustin"
},
{
"context": "male\" :blood-line true :birth 2011}\n {:name \"Loïse\" :family \"Maria\" :generation 6 :s",
"end": 19557,
"score": 0.9997891783714294,
"start": 19552,
"tag": "NAME",
"value": "Loïse"
},
{
"context": ":birth 2011}\n {:name \"Loïse\" :family \"Maria\" :generation 6 :sex \"female\" :blood-line tr",
"end": 19583,
"score": 0.998896598815918,
"start": 19578,
"tag": "NAME",
"value": "Maria"
},
{
"context": "female\" :blood-line true :birth 2011}\n {:name \"Mathilde\" :family \"Troncy\" :generation 5 :sex ",
"end": 19669,
"score": 0.9997940063476562,
"start": 19661,
"tag": "NAME",
"value": "Mathilde"
},
{
"context": "female\" :blood-line true :birth 2012}\n {:name \"Lenny\" :family \"Dieterlé\" :generation 6 :s",
"end": 19775,
"score": 0.9997711777687073,
"start": 19770,
"tag": "NAME",
"value": "Lenny"
},
{
"context": "irth 2012}\n {:name \"Lenny\" :family \"Dieterlé\" :generation 6 :sex \"male\" :blood-line true ",
"end": 19804,
"score": 0.6195821762084961,
"start": 19798,
"tag": "NAME",
"value": "eterlé"
},
{
"context": "male\" :blood-line true :birth 2014}\n {:name \"Gaspard\" :family \"Maria\" :generation 6 :sex",
"end": 19886,
"score": 0.9997930526733398,
"start": 19879,
"tag": "NAME",
"value": "Gaspard"
},
{
"context": ":birth 2014}\n {:name \"Gaspard\" :family \"Maria\" :generation 6 :sex \"male\" :blood-line tr",
"end": 19910,
"score": 0.9985173344612122,
"start": 19905,
"tag": "NAME",
"value": "Maria"
},
{
"context": "{:source 50 :target 43 :type \"partner\" :family \"Troncy\"}\n {:source 52 :target 17 :type \"child\" :fa",
"end": 24514,
"score": 0.6639965176582336,
"start": 24508,
"tag": "NAME",
"value": "Troncy"
},
{
"context": "{:source 52 :target 49 :type \"partner\" :family \"Le Blanc\"}\n {:source 53 :target 18 :type \"child\" :fa",
"end": 24706,
"score": 0.6147332191467285,
"start": 24698,
"tag": "NAME",
"value": "Le Blanc"
},
{
"context": "{:source 54 :target 53 :type \"partner\" :family \"Patay\"}\n {:source 55 :target 15 :type \"child\" :fa",
"end": 24889,
"score": 0.5896040797233582,
"start": 24884,
"tag": "NAME",
"value": "Patay"
},
{
"context": "{:source 59 :target 56 :type \"partner\" :family \"Perret\"}\n {:source 60 :target 17 :type \"child\" :fa",
"end": 25518,
"score": 0.7083064317703247,
"start": 25512,
"tag": "NAME",
"value": "Perret"
},
{
"context": "{:source 61 :target 57 :type \"partner\" :family \"Dieterlé\"}\n {:source 63 :target 55 :type \"partner\" :fa",
"end": 25774,
"score": 0.9998403191566467,
"start": 25766,
"tag": "NAME",
"value": "Dieterlé"
},
{
"context": "{:source 63 :target 55 :type \"partner\" :family \"Rodier\"}\n {:source 64 :target 24 :type \"child\" :fa",
"end": 25836,
"score": 0.9982930421829224,
"start": 25830,
"tag": "NAME",
"value": "Rodier"
},
{
"context": "{:source 66 :target 53 :type \"partner\" :family \"Patay\"}\n {:source 67 :target 24 :type \"child\" :fa",
"end": 26083,
"score": 0.9841002821922302,
"start": 26078,
"tag": "NAME",
"value": "Patay"
},
{
"context": "ource 114 :target 95 :type \"partner\" :family \"Maria\"}\n {:source 115 :target 32 :type \"child\" :fa",
"end": 30942,
"score": 0.6599559187889099,
"start": 30940,
"tag": "NAME",
"value": "ia"
},
{
"context": "source 123 :target 58 :type \"child\" :family \"Beaudin\"}\n {:source 124 :target 43 :type \"child\" :fa",
"end": 32008,
"score": 0.9878981709480286,
"start": 32003,
"tag": "NAME",
"value": "audin"
},
{
"context": "{:source 133 :target 66 :type \"child\" :family \"Patay\"}\n {:source 134 :target 64 :type \"child\" :fa",
"end": 33256,
"score": 0.9989222288131714,
"start": 33251,
"tag": "NAME",
"value": "Patay"
},
{
"context": "{:source 175 :target 114 :type \"child\" :family \"Maria\"}\n {:source 175 :target 95 :type \"child\" :fa",
"end": 38365,
"score": 0.9861189126968384,
"start": 38360,
"tag": "NAME",
"value": "Maria"
},
{
"context": "{:source 175 :target 95 :type \"child\" :family \"Maria\"}\n {:source 176 :target 101 :type \"child\" :fa",
"end": 38426,
"score": 0.9929679036140442,
"start": 38421,
"tag": "NAME",
"value": "Maria"
},
{
"context": "{:source 178 :target 114 :type \"child\" :family \"Maria\"}\n {:source 178 :target 95 :type \"child\" :fa",
"end": 38739,
"score": 0.9953093528747559,
"start": 38734,
"tag": "NAME",
"value": "Maria"
},
{
"context": "{:source 178 :target 95 :type \"child\" :family \"Maria\"}])\n\n(def colour-scheme\n [{:family \"Patay\" ",
"end": 38800,
"score": 0.9892151355743408,
"start": 38795,
"tag": "NAME",
"value": "Maria"
},
{
"context": "amily \"Maria\"}])\n\n(def colour-scheme\n [{:family \"Patay\" :hard-colour \"#FF4A46\" :soft-colour \"#FFDB",
"end": 38843,
"score": 0.9991950988769531,
"start": 38838,
"tag": "NAME",
"value": "Patay"
},
{
"context": "ur \"#FF4A46\" :soft-colour \"#FFDBDA\"}\n {:family \"Maria\" :hard-colour \"#9B9700\" :soft-colour \"#EBEA",
"end": 38916,
"score": 0.9989151954650879,
"start": 38911,
"tag": "NAME",
"value": "Maria"
},
{
"context": "ur \"#9B9700\" :soft-colour \"#EBEACC\"}\n {:family \"Bonin\" :hard-colour \"#006FA6\" :soft-colour \"#CCE2",
"end": 38989,
"score": 0.9992508292198181,
"start": 38984,
"tag": "NAME",
"value": "Bonin"
},
{
"context": "ur \"#006FA6\" :soft-colour \"#CCE2ED\"}\n {:family \"Calatraba\" :hard-colour \"#E20027\" :soft-colour \"#F9CCD4\"}",
"end": 39066,
"score": 0.9992308020591736,
"start": 39057,
"tag": "NAME",
"value": "Calatraba"
},
{
"context": "ur \"#E20027\" :soft-colour \"#F9CCD4\"}\n {:family \"Barrière\" :hard-colour \"#B79762\" :soft-colour \"#F1EAE0\"",
"end": 39138,
"score": 0.9994404911994934,
"start": 39130,
"tag": "NAME",
"value": "Barrière"
},
{
"context": "ur \"#B79762\" :soft-colour \"#F1EAE0\"}\n {:family \"Wolff\" :hard-colour \"#D25B88\" :soft-colour \"#F6DE",
"end": 39208,
"score": 0.9993994832038879,
"start": 39203,
"tag": "NAME",
"value": "Wolff"
},
{
"context": "ur \"#D25B88\" :soft-colour \"#F6DEE7\"}\n {:family \"Rodier\" :hard-colour \"#953F00\" :soft-colour \"#EAD9C",
"end": 39282,
"score": 0.9995074272155762,
"start": 39276,
"tag": "NAME",
"value": "Rodier"
},
{
"context": "ur \"#7A7BFF\" :soft-colour \"#E4E5FF\"}\n {:family \"Pourtier\" :hard-colour \"#FFA0F2\" :soft-colour \"#FFECFC\"",
"end": 39430,
"score": 0.9987718462944031,
"start": 39422,
"tag": "NAME",
"value": "Pourtier"
},
{
"context": "ur \"#FFA0F2\" :soft-colour \"#FFECFC\"}\n {:family \"Le Blanc\" :hard-colour \"#8CC63F\" :soft-colour \"#E8F4D9\"",
"end": 39503,
"score": 0.9995761513710022,
"start": 39495,
"tag": "NAME",
"value": "Le Blanc"
},
{
"context": "ur \"#8CC63F\" :soft-colour \"#E8F4D9\"}\n {:family \"Cheilan\" :hard-colour \"#0CBD66\" :soft-colour \"#CEF2E0",
"end": 39575,
"score": 0.999616801738739,
"start": 39568,
"tag": "NAME",
"value": "Cheilan"
},
{
"context": "ur \"#0CBD66\" :soft-colour \"#CEF2E0\"}\n {:family \"Perrin\" :hard-colour \"#012C58\" :soft-colour \"#CCD5D",
"end": 39647,
"score": 0.9996960163116455,
"start": 39641,
"tag": "NAME",
"value": "Perrin"
},
{
"context": "ur \"#012C58\" :soft-colour \"#CCD5DE\"}\n {:family \"Faivre\" :hard-colour \"#F4D749\" :soft-colour \"#FDF7D",
"end": 39720,
"score": 0.9997155666351318,
"start": 39714,
"tag": "NAME",
"value": "Faivre"
},
{
"context": "ur \"#F4D749\" :soft-colour \"#FDF7DB\"}\n {:family \"Morin\" :hard-colour \"#2DBCF0\" :soft-colour \"#D5F2",
"end": 39792,
"score": 0.9996742606163025,
"start": 39787,
"tag": "NAME",
"value": "Morin"
},
{
"context": "ur \"#2DBCF0\" :soft-colour \"#D5F2FC\"}\n {:family \"Bonnet\" :hard-colour \"#FAA61A\" :soft-colour \"#FEEDD",
"end": 39866,
"score": 0.9996874928474426,
"start": 39860,
"tag": "NAME",
"value": "Bonnet"
},
{
"context": "ur \"#FAA61A\" :soft-colour \"#FEEDD1\"}\n {:family \"Giraud\" :hard-colour \"#958A9F\" :soft-colour \"#EAE8E",
"end": 39939,
"score": 0.9997000098228455,
"start": 39933,
"tag": "NAME",
"value": "Giraud"
},
{
"context": "ur \"#958A9F\" :soft-colour \"#EAE8EC\"}\n {:family \"Suzukawa\" :hard-colour \"#008080\" :soft-colour \"#CCE6E6\"",
"end": 40014,
"score": 0.9993209838867188,
"start": 40006,
"tag": "NAME",
"value": "Suzukawa"
},
{
"context": "ur \"#008080\" :soft-colour \"#CCE6E6\"}\n {:family \"Troncy\" :hard-colour \"#671190\" :soft-colour \"#E1CFE",
"end": 40085,
"score": 0.9996489882469177,
"start": 40079,
"tag": "NAME",
"value": "Troncy"
},
{
"context": "ur \"#671190\" :soft-colour \"#E1CFE9\"}\n {:family \"Goudot\" :hard-colour \"#1E6E00\" :soft-colour \"#D2E2C",
"end": 40158,
"score": 0.9996387958526611,
"start": 40152,
"tag": "NAME",
"value": "Goudot"
},
{
"context": "ur \"#1E6E00\" :soft-colour \"#D2E2CC\"}\n {:family \"Bertin\" :hard-colour \"#885578\" :soft-colour \"#E7DDE",
"end": 40231,
"score": 0.9996285438537598,
"start": 40225,
"tag": "NAME",
"value": "Bertin"
},
{
"context": "ur \"#885578\" :soft-colour \"#E7DDE4\"}\n {:family \"Perret\" :hard-colour \"#FF2F80\" :soft-colour \"#FFD5E",
"end": 40304,
"score": 0.9996349811553955,
"start": 40298,
"tag": "NAME",
"value": "Perret"
},
{
"context": "ur \"#FF2F80\" :soft-colour \"#FFD5E6\"}\n {:family \"Beaudin\" :hard-colour \"#800000\" :soft-colour \"#E6CCCC",
"end": 40378,
"score": 0.9996272921562195,
"start": 40371,
"tag": "NAME",
"value": "Beaudin"
},
{
"context": "ur \"#800000\" :soft-colour \"#E6CCCC\"}\n {:family \"Le Mintier\" :hard-colour \"#FF6832\" :soft-colour \"#FFE1D6\"}\n",
"end": 40454,
"score": 0.9995563626289368,
"start": 40444,
"tag": "NAME",
"value": "Le Mintier"
},
{
"context": "ur \"#FF6832\" :soft-colour \"#FFE1D6\"}\n {:family \"Dieterlé\" :hard-colour \"#D16100\" :soft-colour \"#F6DFCC\"",
"end": 40525,
"score": 0.9996497631072998,
"start": 40517,
"tag": "NAME",
"value": "Dieterlé"
},
{
"context": "ur \"#D16100\" :soft-colour \"#F6DFCC\"}\n {:family \"Bonhour\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5",
"end": 40597,
"score": 0.999302864074707,
"start": 40590,
"tag": "NAME",
"value": "Bonhour"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Abadie\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 40669,
"score": 0.9994730949401855,
"start": 40663,
"tag": "NAME",
"value": "Abadie"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Barnes\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 40742,
"score": 0.9732630848884583,
"start": 40736,
"tag": "NAME",
"value": "Barnes"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Desrayaud\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5\"}",
"end": 40818,
"score": 0.981673002243042,
"start": 40809,
"tag": "NAME",
"value": "Desrayaud"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Chapuzet\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5\"",
"end": 40890,
"score": 0.9182326197624207,
"start": 40882,
"tag": "NAME",
"value": "Chapuzet"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Labaty\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 40961,
"score": 0.9430899024009705,
"start": 40955,
"tag": "NAME",
"value": "Labaty"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Olds\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F",
"end": 41032,
"score": 0.9595215320587158,
"start": 41028,
"tag": "NAME",
"value": "Olds"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Lebon\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3",
"end": 41106,
"score": 0.9760335087776184,
"start": 41101,
"tag": "NAME",
"value": "Lebon"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Antoni\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 41180,
"score": 0.9713444709777832,
"start": 41174,
"tag": "NAME",
"value": "Antoni"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Galtier\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5",
"end": 41254,
"score": 0.9746745228767395,
"start": 41247,
"tag": "NAME",
"value": "Galtier"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Morel\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3",
"end": 41325,
"score": 0.9741319417953491,
"start": 41320,
"tag": "NAME",
"value": "Morel"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Muzelli\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5",
"end": 41400,
"score": 0.9759130477905273,
"start": 41393,
"tag": "NAME",
"value": "Muzelli"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"de Veron\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5\"",
"end": 41474,
"score": 0.9144105911254883,
"start": 41466,
"tag": "NAME",
"value": "de Veron"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Saillet\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5",
"end": 41546,
"score": 0.9647896885871887,
"start": 41539,
"tag": "NAME",
"value": "Saillet"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Cottin\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 41618,
"score": 0.9656071662902832,
"start": 41612,
"tag": "NAME",
"value": "Cottin"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Viosi\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3",
"end": 41690,
"score": 0.9645933508872986,
"start": 41685,
"tag": "NAME",
"value": "Viosi"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Maggialetti\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n ",
"end": 41769,
"score": 0.9348955154418945,
"start": 41758,
"tag": "NAME",
"value": "Maggialetti"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Taithe\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 41837,
"score": 0.9213905930519104,
"start": 41831,
"tag": "NAME",
"value": "Taithe"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Russo\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3",
"end": 41909,
"score": 0.9985254406929016,
"start": 41904,
"tag": "NAME",
"value": "Russo"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Jullien\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5",
"end": 41984,
"score": 0.9991800785064697,
"start": 41977,
"tag": "NAME",
"value": "Jullien"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Valli\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3",
"end": 42055,
"score": 0.9987605810165405,
"start": 42050,
"tag": "NAME",
"value": "Valli"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Pelletier\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5\"}",
"end": 42132,
"score": 0.9986875057220459,
"start": 42123,
"tag": "NAME",
"value": "Pelletier"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Pointet\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5",
"end": 42203,
"score": 0.9970028400421143,
"start": 42196,
"tag": "NAME",
"value": "Pointet"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Nesme\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3",
"end": 42274,
"score": 0.9984936714172363,
"start": 42269,
"tag": "NAME",
"value": "Nesme"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Bourel\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 42348,
"score": 0.9980103969573975,
"start": 42342,
"tag": "NAME",
"value": "Bourel"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Sommer\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 42421,
"score": 0.9977375864982605,
"start": 42415,
"tag": "NAME",
"value": "Sommer"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Chapuis\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F5",
"end": 42495,
"score": 0.9981679320335388,
"start": 42488,
"tag": "NAME",
"value": "Chapuis"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Jullat\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 42567,
"score": 0.9982245564460754,
"start": 42561,
"tag": "NAME",
"value": "Jullat"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Sadoux\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 42640,
"score": 0.9971820116043091,
"start": 42634,
"tag": "NAME",
"value": "Sadoux"
},
{
"context": "ur \"#BDC9D2\" :soft-colour \"#F1F3F5\"}\n {:family \"Cappio\" :hard-colour \"#BDC9D2\" :soft-colour \"#F1F3F",
"end": 42713,
"score": 0.9974517226219177,
"start": 42707,
"tag": "NAME",
"value": "Cappio"
}
] | src/the_family_tree/utils/data.cljs | kgxsz/the-family-tree | 3 | (ns the-family-tree.utils.data)
(def members
[{:name "André" :family "Troncy" :generation 1 :sex "male" :blood-line true :birth 1859 :death 1931}
{:name "Francine" :family "Valli" :generation 1 :sex "female" :blood-line false :birth 1872 :death 1954}
{:name "Charles" :family "Patay" :generation 2 :sex "male" :blood-line false :birth 1884 :death 1959}
{:name "Francois" :family "Bonnet" :generation 2 :sex "male" :blood-line false :birth 1884 :death 1970}
{:name "Jeanne" :family "Troncy" :generation 2 :sex "female" :blood-line true :birth 1894 :death 1979}
{:name "Claudia" :family "Troncy" :generation 2 :sex "female" :blood-line true :birth 1895 :death 1968}
{:name "Maurice" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1896 :death 1942}
{:name "Gustave" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1898 :death 1972}
{:name "Claude" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1900 :death 1964}
{:name "Madeleine" :family "Galtier" :generation 2 :sex "female" :blood-line false :birth 1900 :death 1983}
{:name "Marcelle" :family "Desrayaud" :generation 2 :sex "female" :blood-line false :birth 1901 :death 1966}
{:name "Robert" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1902 :death 1959}
{:name "Renée" :family "Pointet" :generation 2 :sex "female" :blood-line false :birth 1907 :death 2000}
{:name "Elisabeth" :family "de Veron" :generation 2 :sex "female" :blood-line false :birth 1909 :death 1994}
{:name "Albert" :family "Bertin" :generation 3 :sex "male" :blood-line false :birth 1914 :death 1997}
{:name "Marcel" :family "Rodier" :generation 3 :sex "male" :blood-line false :birth 1916 :death 2004}
{:name "Simone" :family "Patay" :generation 3 :sex "female" :blood-line true :birth 1917 :death 2000}
{:name "Roger" :family "Dieterlé" :generation 3 :sex "male" :blood-line false :birth 1917 :death 1990}
{:name "André" :family "Patay" :generation 3 :sex "male" :blood-line true :birth 1919 :death 1995}
{:name "Denise" :family "Morel" :generation 3 :sex "female" :blood-line false :birth 1922}
{:name "Jean" :family "Pelletier" :generation 3 :sex "male" :blood-line false :birth 1922 :death 1994}
{:name "Geneviéve" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1923 :death 1925}
{:name "Alice" :family "Patay" :generation 3 :sex "female" :blood-line true :birth 1924}
{:name "Georges" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1926 :death 1993}
{:name "Pierre" :family "Bonnet" :generation 3 :sex "male" :blood-line true :birth 1927 :death 2008}
{:name "Guitou" :family "Taithe" :generation 3 :sex "female" :blood-line false :birth 1928 :death 2005}
{:name "Françoise" :family "Bonnet" :generation 3 :sex "female" :blood-line true :birth 1929}
{:name "Christiane" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1929 :death 2014}
{:name "André" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1933}
{:name "Simone" :family "Bourel" :generation 3 :sex "female" :blood-line false :birth 1936}
{:name "Robert" :family "Barrière" :generation 4 :sex "male" :blood-line false :birth 1936 :death 1999}
{:name "Marie-Suzanne" :family "Saillet" :generation 3 :sex "female" :blood-line false :birth 1937}
{:name "Jaques" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1939}
{:name "Françoise" :family "Bonhour" :generation 3 :sex "female" :blood-line false :birth 1939}
{:name "Bernard" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1940 :death 1992}
{:name "Marie-France" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1940}
{:name "Alain" :family "Bertin" :generation 4 :sex "male" :blood-line true :birth 1940}
{:name "Françoise" :family "Jullien" :generation 4 :sex "female" :blood-line false :birth 1941}
{:name "Philippe" :family "Bonin" :generation 4 :sex "male" :blood-line false :birth 1941}
{:name "Jean-François" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1942 :death 1994}
{:name "Danielle" :family "Bertin" :generation 4 :sex "female" :blood-line true :birth 1943}
{:name "Didier" :family "Goudot" :generation 4 :sex "male" :blood-line false :birth 1943}
{:name "Claude-Henry" :family "Perrin" :generation 3 :sex "male" :blood-line false :birth 1943}
{:name "Hubert" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1945}
{:name "Brigitte" :family "Patay" :generation 4 :sex "female" :blood-line true :birth 1947}
{:name "François" :family "Beaudin" :generation 4 :sex "male" :blood-line false :birth 1947 :death 1998}
{:name "Maurice" :family "Bertin" :generation 4 :sex "male" :blood-line true :birth 1948 :death 1949}
{:name "Marie-Geneviéve" :family "Sommer" :generation 3 :sex "female" :blood-line false :birth 1949}
{:name "Catherine" :family "Rodier" :generation 4 :sex "female" :blood-line true :birth 1949}
{:name "Patrick" :family "Le Blanc" :generation 4 :sex "female" :blood-line false :birth 1949 :death 2012}
{:name "Rosamund" :family "Barnes" :generation 3 :sex "female" :blood-line false :birth 1951}
{:name "Hiroshi" :family "Suzukawa" :generation 4 :sex "male" :blood-line false :birth 1951}
{:name "Laurence" :family "Dieterlé" :generation 4 :sex "female" :blood-line true :birth 1951}
{:name "Michel" :family "Patay" :generation 4 :sex "male" :blood-line true :birth 1951}
{:name "Cheryl" :family "Olds" :generation 4 :sex "female" :blood-line false :birth 1951}
{:name "Philippe" :family "Rodier" :generation 4 :sex "male" :blood-line true :birth 1952}
{:name "Alain" :family "Perret" :generation 4 :sex "male" :blood-line false :birth 1952}
{:name "Régis" :family "Dieterlé" :generation 4 :sex "male" :blood-line true :birth 1953 :death 1994}
{:name "Cécile" :family "Dieterlé" :generation 4 :sex "female" :blood-line true :birth 1955}
{:name "Fabienne" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1957}
{:name "Agnés" :family "Dieterlé" :generation 4 :sex "female" :blood-line true :birth 1958}
{:name "Marie-Delphine" :family "Muzelli" :generation 4 :sex "female" :blood-line false :birth 1958}
{:name "Lionel" :family "Pourtier" :generation 5 :sex "male" :blood-line false :birth 1958}
{:name "Anne" :family "Chapuis" :generation 4 :sex "female" :blood-line false :birth 1959}
{:name "Marielle" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1959}
{:name "Jean-Michel" :family "Giraud" :generation 4 :sex "male" :blood-line false :birth 1960}
{:name "Nadine" :family "Nesme" :generation 4 :sex "female" :blood-line false :birth 1961}
{:name "Chantal" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1962}
{:name "Christophe" :family "Morin" :generation 5 :sex "male" :blood-line false :birth 1963}
{:name "Jérôme" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1965 :death 1989}
{:name "Laurence" :family "Bertin" :generation 5 :sex "female" :blood-line true :birth 1966}
{:name "Franck" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1966}
{:name "Armelle" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1967}
{:name "Isabelle" :family "Chapuzet" :generation 5 :sex "female" :blood-line false :birth 1967}
{:name "Béatrice" :family "Abadie" :generation 4 :sex "female" :blood-line false :birth 1967}
{:name "Frédéric" :family "Bertin" :generation 5 :sex "male" :blood-line true :birth 1968}
{:name "Jean-Marc" :family "Faivre" :generation 4 :sex "male" :blood-line false :birth 1968}
{:name "Erwan" :family "Le Mintier" :generation 5 :sex "male" :blood-line false :birth 1968}
{:name "Emmanuel" :family "Perrin" :generation 4 :sex "male" :blood-line true :birth 1968}
{:name "Fabrice" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1968}
{:name "Antoine" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1969}
{:name "Laurence" :family "Sadoux" :generation 4 :sex "female" :blood-line false :birth 1969}
{:name "Alexandre" :family "Perrin" :generation 4 :sex "male" :blood-line true :birth 1969}
{:name "Françoise" :family "Cottin" :generation 5 :sex "female" :blood-line false :birth 1969}
{:name "Nicolas" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1970}
{:name "Anne-Laurie" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1971}
{:name "Clémentine" :family "Labaty" :generation 4 :sex "female" :blood-line false :birth 1971}
{:name "Sophie" :family "Jullat" :generation 4 :sex "female" :blood-line false :birth 1971}
{:name "Anne" :family "Bertin" :generation 5 :sex "female" :blood-line true :birth 1971}
{:name "Charles-Eric" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1972 :death 1972}
{:name "Marianne" :family "Goudot" :generation 5 :sex "female" :blood-line true :birth 1972}
{:name "Vanessa" :family "Lebon" :generation 5 :sex "female" :blood-line false :birth 1973}
{:name "Xavier" :family "Bertin" :generation 5 :sex "male" :blood-line true :birth 1974}
{:name "Valentine" :family "Le Blanc" :generation 5 :sex "female" :blood-line true :birth 1974}
{:name "Bruno" :family "Cheilan" :generation 5 :sex "male" :blood-line false :birth 1974}
{:name "Matthieu" :family "Maria" :generation 5 :sex "male" :blood-line false :birth 1974}
{:name "Julia" :family "Goudot" :generation 5 :sex "female" :blood-line true :birth 1975}
{:name "Michaël" :family "Calatraba" :generation 5 :sex "male" :blood-line false :birth 1975}
{:name "Christelle" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1975}
{:name "Valérie" :family "Barrière" :generation 5 :sex "female" :blood-line true :birth 1976 :death 1982}
{:name "Aurélie" :family "Le Blanc" :generation 5 :sex "female" :blood-line true :birth 1976}
{:name "Cyril" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1976}
{:name "Camilla" :family "Maggialetti" :generation 4 :sex "female" :blood-line false :birth 1976}
{:name "Guilhem" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1976}
{:name "Pierrick" :family "Wolff" :generation 5 :sex "male" :blood-line false :birth 1977}
{:name "Maud" :family "Russo" :generation 4 :sex "female" :blood-line false :birth 1977}
{:name "Anne-Claire" :family "Antoni" :generation 4 :sex "female" :blood-line false :birth 1977}
{:name "Mathieu" :family "Beaudin" :generation 5 :sex "male" :blood-line true :birth 1978}
{:name "Sandrine" :family "Barrière" :generation 5 :sex "female" :blood-line true :birth 1979}
{:name "Mélanie" :family "Beaudin" :generation 5 :sex "female" :blood-line true :birth 1980}
{:name "Cédric" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1980}
{:name "Romain" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1980}
{:name "Oliver" :family "Gaillet" :generation 5 :sex "male" :blood-line false :birth 1981}
{:name "Eric" :family "Barrière" :generation 5 :sex "male" :blood-line true :birth 1982}
{:name "Alice" :family "Beaudin" :generation 5 :sex "female" :blood-line true :birth 1982}
{:name "Didier" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1982}
{:name "Olivier" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1982}
{:name "Thibault" :family "Dieterlé" :generation 5 :sex "male" :blood-line true :birth 1984}
{:name "Leïla" :family "Suzukawa" :generation 5 :sex "female" :blood-line true :birth 1984}
{:name "Anne-Sophie" :family "Cappio" :generation 5 :sex "female" :blood-line false :birth 1985}
{:name "Caroline" :family "Rodier" :generation 5 :sex "female" :blood-line true :birth 1985}
{:name "Marine" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1986}
{:name "Johanna" :family "Viosi" :generation 5 :sex "female" :blood-line false :birth 1986}
{:name "Clément" :family "Beaudin" :generation 5 :sex "male" :blood-line true :birth 1986}
{:name "Pierre" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1986}
{:name "Keigo" :family "Suzukawa" :generation 5 :sex "male" :blood-line true :birth 1986}
{:name "Laetitia" :family "Rodier" :generation 5 :sex "female" :blood-line true :birth 1987}
{:name "Grégoire" :family "Giraud" :generation 5 :sex "male" :blood-line true :birth 1987}
{:name "Vincent" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1988}
{:name "Kaya" :family "Suzukawa" :generation 5 :sex "female" :blood-line true :birth 1988}
{:name "Blandine" :family "Patay" :generation 5 :sex "female" :blood-line true :birth 1989}
{:name "Charles-Henry" :family "Rodier" :generation 5 :sex "male" :blood-line true :birth 1989}
{:name "Henry" :family "Perret" :generation 5 :sex "male" :blood-line true :birth 1989}
{:name "Charles" :family "Patay" :generation 5 :sex "male" :blood-line true :birth 1990}
{:name "Hubert" :family "Giraud" :generation 5 :sex "male" :blood-line true :birth 1990}
{:name "Pierre" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1991}
{:name "Marine" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1991}
{:name "Jean" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1992}
{:name "Alix" :family "Perret" :generation 5 :sex "male" :blood-line true :birth 1992}
{:name "Ségolène" :family "Giraud" :generation 5 :sex "female" :blood-line true :birth 1992}
{:name "Armelle" :family "Perret" :generation 5 :sex "female" :blood-line true :birth 1994}
{:name "Charlotte" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1994}
{:name "Emilie" :family "Bertin" :generation 6 :sex "female" :blood-line true :birth 1995}
{:name "Mathilde" :family "Perrin" :generation 5 :sex "female" :blood-line true :birth 1996}
{:name "Valérie" :family "Pourtier" :generation 6 :sex "female" :blood-line true :birth 1997}
{:name "Prune" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1997}
{:name "Alexandre" :family "Bertin" :generation 6 :sex "male" :blood-line true :birth 1998}
{:name "Romain" :family "Bonin" :generation 6 :sex "male" :blood-line true :birth 1999}
{:name "Florian" :family "Morin" :generation 6 :sex "male" :blood-line true :birth 2001}
{:name "Pauline" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2001}
{:name "Mathis" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2001}
{:name "Idriss-Valentin" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2002}
{:name "Louis" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2002}
{:name "Ambre" :family "Bonin" :generation 6 :sex "male" :blood-line true :birth 2004}
{:name "Sébastien" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2004}
{:name "Gabrielle" :family "Cheilan" :generation 6 :sex "female" :blood-line true :birth 2005}
{:name "Aymeric" :family "Le Mintier" :generation 6 :sex "male" :blood-line true :birth 2005}
{:name "Clémence" :family "Troncy" :generation 5 :sex "female" :blood-line true :birth 2005}
{:name "Louna" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2005}
{:name "Lucas" :family "Morin" :generation 6 :sex "male" :blood-line true :birth 2006}
{:name "Julien" :family "Bonin" :generation 6 :sex "male" :blood-line true :birth 2006}
{:name "Guillaume" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2006}
{:name "Eva" :family "Perrin" :generation 5 :sex "female" :blood-line true :birth 2006}
{:name "Milo" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2006}
{:name "Jeanne" :family "Le Mintier" :generation 6 :sex "female" :blood-line true :birth 2007}
{:name "Robin" :family "Cheilan" :generation 6 :sex "male" :blood-line true :birth 2007}
{:name "Lola" :family "Morin" :generation 6 :sex "female" :blood-line true :birth 2008}
{:name "Hanaé" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2009}
{:name "Clara" :family "Le Mintier" :generation 6 :sex "female" :blood-line true :birth 2009}
{:name "Charles" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2009}
{:name "Balian" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2009}
{:name "Simon" :family "Wolff" :generation 6 :sex "male" :blood-line true :birth 2010}
{:name "Nell" :family "Calatraba" :generation 6 :sex "female" :blood-line true :birth 2010}
{:name "Caroline" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2011}
{:name "Augustin" :family "Gaillet" :generation 6 :sex "male" :blood-line true :birth 2011}
{:name "Loïse" :family "Maria" :generation 6 :sex "female" :blood-line true :birth 2011}
{:name "Mathilde" :family "Troncy" :generation 5 :sex "female" :blood-line true :birth 2012}
{:name "Lenny" :family "Dieterlé" :generation 6 :sex "male" :blood-line true :birth 2014}
{:name "Gaspard" :family "Maria" :generation 6 :sex "male" :blood-line true :birth 2015}])
(def relations
[{:source 1 :target 0 :type "partner" :family "Troncy"}
{:source 4 :target 0 :type "child" :family "Troncy"}
{:source 4 :target 1 :type "child" :family "Troncy"}
{:source 4 :target 2 :type "partner" :family "Patay"}
{:source 5 :target 0 :type "child" :family "Troncy"}
{:source 5 :target 1 :type "child" :family "Troncy"}
{:source 5 :target 3 :type "partner" :family "Bonnet"}
{:source 6 :target 0 :type "child" :family "Troncy"}
{:source 6 :target 1 :type "child" :family "Troncy"}
{:source 7 :target 0 :type "child" :family "Troncy"}
{:source 7 :target 1 :type "child" :family "Troncy"}
{:source 8 :target 0 :type "child" :family "Troncy"}
{:source 8 :target 1 :type "child" :family "Troncy"}
{:source 9 :target 7 :type "partner" :family "Troncy"}
{:source 10 :target 6 :type "partner" :family "Troncy"}
{:source 11 :target 1 :type "child" :family "Troncy"}
{:source 11 :target 0 :type "child" :family "Troncy"}
{:source 12 :target 11 :type "partner" :family "Troncy"}
{:source 13 :target 8 :type "partner" :family "Troncy"}
{:source 16 :target 4 :type "child" :family "Patay"}
{:source 16 :target 2 :type "child" :family "Patay"}
{:source 16 :target 14 :type "partner" :family "Bertin"}
{:source 18 :target 4 :type "child" :family "Patay"}
{:source 18 :target 2 :type "child" :family "Patay"}
{:source 19 :target 18 :type "partner" :family "Patay"}
{:source 21 :target 6 :type "child" :family "Troncy"}
{:source 21 :target 10 :type "child" :family "Troncy"}
{:source 22 :target 4 :type "child" :family "Patay"}
{:source 22 :target 2 :type "child" :family "Patay"}
{:source 22 :target 15 :type "partner" :family "Rodier"}
{:source 23 :target 6 :type "child" :family "Troncy"}
{:source 23 :target 10 :type "child" :family "Troncy"}
{:source 24 :target 3 :type "child" :family "Bonnet"}
{:source 24 :target 5 :type "child" :family "Bonnet"}
{:source 25 :target 24 :type "partner" :family "Bonnet"}
{:source 26 :target 3 :type "child" :family "Bonnet"}
{:source 26 :target 5 :type "child" :family "Bonnet"}
{:source 26 :target 20 :type "partner" :family "Pelletier"}
{:source 27 :target 6 :type "child" :family "Troncy"}
{:source 27 :target 10 :type "child" :family "Troncy"}
{:source 27 :target 17 :type "partner" :family "Dieterlé"}
{:source 28 :target 8 :type "child" :family "Troncy"}
{:source 28 :target 13 :type "child" :family "Troncy"}
{:source 29 :target 28 :type "partner" :family "Troncy"}
{:source 31 :target 23 :type "partner" :family "Troncy"}
{:source 32 :target 11 :type "child" :family "Troncy"}
{:source 32 :target 12 :type "child" :family "Troncy"}
{:source 34 :target 11 :type "child" :family "Troncy"}
{:source 34 :target 12 :type "child" :family "Troncy"}
{:source 34 :target 33 :type "partner" :family "Troncy"}
{:source 35 :target 6 :type "child" :family "Troncy"}
{:source 35 :target 10 :type "child" :family "Troncy"}
{:source 36 :target 14 :type "child" :family "Bertin"}
{:source 36 :target 16 :type "child" :family "Bertin"}
{:source 37 :target 36 :type "partner" :family "Bertin"}
{:source 39 :target 11 :type "child" :family "Troncy"}
{:source 39 :target 12 :type "child" :family "Troncy"}
{:source 40 :target 14 :type "child" :family "Bertin"}
{:source 40 :target 16 :type "child" :family "Bertin"}
{:source 40 :target 38 :type "partner" :family "Bonin"}
{:source 42 :target 35 :type "partner" :family "Perrin"}
{:source 43 :target 11 :type "child" :family "Troncy"}
{:source 43 :target 12 :type "child" :family "Troncy"}
{:source 44 :target 18 :type "child" :family "Patay"}
{:source 44 :target 19 :type "child" :family "Patay"}
{:source 44 :target 41 :type "partner" :family "Goudot"}
{:source 46 :target 14 :type "child" :family "Bertin"}
{:source 46 :target 16 :type "child" :family "Bertin"}
{:source 47 :target 32 :type "partner" :family "Troncy"}
{:source 48 :target 15 :type "child" :family "Rodier"}
{:source 48 :target 22 :type "child" :family "Rodier"}
{:source 48 :target 30 :type "partner" :family "Barrière"}
{:source 50 :target 43 :type "partner" :family "Troncy"}
{:source 52 :target 17 :type "child" :family "Dieterlé"}
{:source 52 :target 27 :type "child" :family "Dieterlé"}
{:source 52 :target 49 :type "partner" :family "Le Blanc"}
{:source 53 :target 18 :type "child" :family "Patay"}
{:source 53 :target 19 :type "child" :family "Patay"}
{:source 54 :target 53 :type "partner" :family "Patay"}
{:source 55 :target 15 :type "child" :family "Rodier"}
{:source 55 :target 22 :type "child" :family "Rodier"}
{:source 57 :target 17 :type "child" :family "Dieterlé"}
{:source 57 :target 27 :type "child" :family "Dieterlé"}
{:source 58 :target 17 :type "child" :family "Dieterlé"}
{:source 58 :target 27 :type "child" :family "Dieterlé"}
{:source 58 :target 45 :type "partner" :family "Beaudin"}
{:source 59 :target 24 :type "child" :family "Bonnet"}
{:source 59 :target 25 :type "child" :family "Bonnet"}
{:source 59 :target 56 :type "partner" :family "Perret"}
{:source 60 :target 17 :type "child" :family "Dieterlé"}
{:source 60 :target 27 :type "child" :family "Dieterlé"}
{:source 60 :target 51 :type "partner" :family "Suzukawa"}
{:source 61 :target 57 :type "partner" :family "Dieterlé"}
{:source 63 :target 55 :type "partner" :family "Rodier"}
{:source 64 :target 24 :type "child" :family "Bonnet"}
{:source 64 :target 25 :type "child" :family "Bonnet"}
{:source 65 :target 64 :type "partner" :family "Giraud"}
{:source 66 :target 53 :type "partner" :family "Patay"}
{:source 67 :target 24 :type "child" :family "Bonnet"}
{:source 67 :target 25 :type "child" :family "Bonnet"}
{:source 69 :target 28 :type "child" :family "Troncy"}
{:source 69 :target 29 :type "child" :family "Troncy"}
{:source 70 :target 36 :type "child" :family "Bertin"}
{:source 70 :target 37 :type "child" :family "Bertin"}
{:source 70 :target 62 :type "partner" :family "Pourtier"}
{:source 71 :target 38 :type "child" :family "Bonin"}
{:source 71 :target 40 :type "child" :family "Bonin"}
{:source 72 :target 23 :type "child" :family "Troncy"}
{:source 72 :target 31 :type "child" :family "Troncy"}
{:source 75 :target 36 :type "child" :family "Bertin"}
{:source 75 :target 37 :type "child" :family "Bertin"}
{:source 75 :target 73 :type "partner" :family "Bertin"}
{:source 76 :target 72 :type "partner" :family "Faivre"}
{:source 78 :target 35 :type "child" :family "Perrin"}
{:source 78 :target 42 :type "child" :family "Perrin"}
{:source 78 :target 74 :type "partner" :family "Perrin"}
{:source 79 :target 38 :type "child" :family "Bonin"}
{:source 79 :target 40 :type "child" :family "Bonin"}
{:source 79 :target 83 :type "partner" :family "Bonin"}
{:source 80 :target 23 :type "child" :family "Troncy"}
{:source 80 :target 31 :type "child" :family "Troncy"}
{:source 81 :target 80 :type "partner" :family "Troncy"}
{:source 82 :target 35 :type "child" :family "Perrin"}
{:source 82 :target 42 :type "child" :family "Perrin"}
{:source 84 :target 38 :type "child" :family "Bonin"}
{:source 84 :target 40 :type "child" :family "Bonin"}
{:source 85 :target 28 :type "child" :family "Troncy"}
{:source 85 :target 29 :type "child" :family "Troncy"}
{:source 86 :target 78 :type "partner" :family "Perrin"}
{:source 87 :target 82 :type "partner" :family "Perrin"}
{:source 88 :target 36 :type "child" :family "Bertin"}
{:source 88 :target 37 :type "child" :family "Bertin"}
{:source 88 :target 68 :type "partner" :family "Morin"}
{:source 89 :target 38 :type "child" :family "Bonin"}
{:source 89 :target 40 :type "child" :family "Bonin"}
{:source 90 :target 41 :type "child" :family "Goudot"}
{:source 90 :target 44 :type "child" :family "Goudot"}
{:source 91 :target 84 :type "partner" :family "Bonin"}
{:source 92 :target 36 :type "child" :family "Bertin"}
{:source 92 :target 37 :type "child" :family "Bertin"}
{:source 93 :target 49 :type "child" :family "Le Blanc"}
{:source 93 :target 52 :type "child" :family "Le Blanc"}
{:source 93 :target 77 :type "partner" :family "Le Mintier"}
{:source 96 :target 41 :type "child" :family "Goudot"}
{:source 96 :target 44 :type "child" :family "Goudot"}
{:source 98 :target 32 :type "child" :family "Troncy"}
{:source 98 :target 47 :type "child" :family "Troncy"}
{:source 99 :target 30 :type "child" :family "Barrière"}
{:source 99 :target 48 :type "child" :family "Barrière"}
{:source 100 :target 49 :type "child" :family "Le Blanc"}
{:source 100 :target 52 :type "child" :family "Le Blanc"}
{:source 101 :target 32 :type "child" :family "Troncy"}
{:source 101 :target 47 :type "child" :family "Troncy"}
{:source 102 :target 101 :type "partner" :family "Troncy"}
{:source 103 :target 33 :type "child" :family "Troncy"}
{:source 103 :target 34 :type "child" :family "Troncy"}
{:source 104 :target 96 :type "partner" :family "Wolff"}
{:source 105 :target 103 :type "partner" :family "Troncy"}
{:source 106 :target 82 :type "partner" :family "Perrin"}
{:source 107 :target 45 :type "child" :family "Beaudin"}
{:source 107 :target 58 :type "child" :family "Beaudin"}
{:source 108 :target 30 :type "child" :family "Barrière"}
{:source 108 :target 48 :type "child" :family "Barrière"}
{:source 108 :target 97 :type "partner" :family "Calatraba"}
{:source 109 :target 45 :type "child" :family "Beaudin"}
{:source 109 :target 58 :type "child" :family "Beaudin"}
{:source 109 :target 94 :type "partner" :family "Cheilan"}
{:source 110 :target 32 :type "child" :family "Troncy"}
{:source 110 :target 47 :type "child" :family "Troncy"}
{:source 111 :target 43 :type "child" :family "Troncy"}
{:source 111 :target 50 :type "child" :family "Troncy"}
{:source 113 :target 30 :type "child" :family "Barrière"}
{:source 113 :target 48 :type "child" :family "Barrière"}
{:source 114 :target 45 :type "child" :family "Beaudin"}
{:source 114 :target 58 :type "child" :family "Beaudin"}
{:source 114 :target 95 :type "partner" :family "Maria"}
{:source 115 :target 32 :type "child" :family "Troncy"}
{:source 115 :target 47 :type "child" :family "Troncy"}
{:source 116 :target 43 :type "child" :family "Troncy"}
{:source 116 :target 50 :type "child" :family "Troncy"}
{:source 117 :target 57 :type "child" :family "Dieterlé"}
{:source 117 :target 61 :type "child" :family "Dieterlé"}
{:source 118 :target 51 :type "child" :family "Suzukawa"}
{:source 118 :target 60 :type "child" :family "Suzukawa"}
{:source 119 :target 71 :type "partner" :family "Bonin"}
{:source 120 :target 55 :type "child" :family "Rodier"}
{:source 120 :target 63 :type "child" :family "Rodier"}
{:source 120 :target 112 :type "partner" :family "Gaillet"}
{:source 121 :target 72 :type "child" :family "Faivre"}
{:source 121 :target 76 :type "child" :family "Faivre"}
{:source 122 :target 117 :type "partner" :family "Dieterlé"}
{:source 123 :target 45 :type "child" :family "Beaudin"}
{:source 123 :target 58 :type "child" :family "Beaudin"}
{:source 124 :target 43 :type "child" :family "Troncy"}
{:source 124 :target 50 :type "child" :family "Troncy"}
{:source 125 :target 51 :type "child" :family "Suzukawa"}
{:source 125 :target 60 :type "child" :family "Suzukawa"}
{:source 126 :target 55 :type "child" :family "Rodier"}
{:source 126 :target 63 :type "child" :family "Rodier"}
{:source 127 :target 64 :type "child" :family "Giraud"}
{:source 127 :target 65 :type "child" :family "Giraud"}
{:source 128 :target 62 :type "child" :family "Pourtier"}
{:source 128 :target 70 :type "child" :family "Pourtier"}
{:source 129 :target 51 :type "child" :family "Suzukawa"}
{:source 129 :target 60 :type "child" :family "Suzukawa"}
{:source 130 :target 53 :type "child" :family "Patay"}
{:source 130 :target 66 :type "child" :family "Patay"}
{:source 131 :target 55 :type "child" :family "Rodier"}
{:source 131 :target 63 :type "child" :family "Rodier"}
{:source 132 :target 56 :type "child" :family "Perret"}
{:source 132 :target 59 :type "child" :family "Perret"}
{:source 133 :target 53 :type "child" :family "Patay"}
{:source 133 :target 66 :type "child" :family "Patay"}
{:source 134 :target 64 :type "child" :family "Giraud"}
{:source 134 :target 65 :type "child" :family "Giraud"}
{:source 135 :target 62 :type "child" :family "Pourtier"}
{:source 135 :target 70 :type "child" :family "Pourtier"}
{:source 136 :target 32 :type "child" :family "Troncy"}
{:source 136 :target 47 :type "child" :family "Troncy"}
{:source 137 :target 62 :type "child" :family "Pourtier"}
{:source 137 :target 70 :type "child" :family "Pourtier"}
{:source 138 :target 56 :type "child" :family "Perret"}
{:source 138 :target 59 :type "child" :family "Perret"}
{:source 139 :target 64 :type "child" :family "Giraud"}
{:source 139 :target 65 :type "child" :family "Giraud"}
{:source 140 :target 56 :type "child" :family "Perret"}
{:source 140 :target 59 :type "child" :family "Perret"}
{:source 141 :target 72 :type "child" :family "Faivre"}
{:source 141 :target 76 :type "child" :family "Faivre"}
{:source 142 :target 73 :type "child" :family "Bertin"}
{:source 142 :target 75 :type "child" :family "Bertin"}
{:source 143 :target 78 :type "child" :family "Perrin"}
{:source 143 :target 86 :type "child" :family "Perrin"}
{:source 144 :target 62 :type "child" :family "Pourtier"}
{:source 144 :target 70 :type "child" :family "Pourtier"}
{:source 145 :target 72 :type "child" :family "Faivre"}
{:source 145 :target 76 :type "child" :family "Faivre"}
{:source 146 :target 73 :type "child" :family "Bertin"}
{:source 146 :target 75 :type "child" :family "Bertin"}
{:source 147 :target 79 :type "child" :family "Bonin"}
{:source 147 :target 83 :type "child" :family "Bonin"}
{:source 148 :target 68 :type "child" :family "Morin"}
{:source 148 :target 88 :type "child" :family "Morin"}
{:source 149 :target 79 :type "child" :family "Bonin"}
{:source 149 :target 83 :type "child" :family "Bonin"}
{:source 150 :target 82 :type "child" :family "Perrin"}
{:source 150 :target 106 :type "child" :family "Perrin"}
{:source 151 :target 84 :type "child" :family "Bonin"}
{:source 151 :target 91 :type "child" :family "Bonin"}
{:source 152 :target 80 :type "child" :family "Troncy"}
{:source 152 :target 81 :type "child" :family "Troncy"}
{:source 153 :target 84 :type "child" :family "Bonin"}
{:source 153 :target 91 :type "child" :family "Bonin"}
{:source 154 :target 80 :type "child" :family "Troncy"}
{:source 154 :target 81 :type "child" :family "Troncy"}
{:source 155 :target 94 :type "child" :family "Cheilan"}
{:source 155 :target 109 :type "child" :family "Cheilan"}
{:source 156 :target 93 :type "child" :family "Le Mintier"}
{:source 156 :target 77 :type "child" :family "Le Mintier"}
{:source 157 :target 98 :type "child" :family "Troncy"}
{:source 158 :target 82 :type "child" :family "Perrin"}
{:source 158 :target 87 :type "child" :family "Perrin"}
{:source 159 :target 68 :type "child" :family "Morin"}
{:source 159 :target 88 :type "child" :family "Morin"}
{:source 160 :target 79 :type "child" :family "Bonin"}
{:source 160 :target 83 :type "child" :family "Bonin"}
{:source 161 :target 80 :type "child" :family "Troncy"}
{:source 161 :target 81 :type "child" :family "Troncy"}
{:source 162 :target 78 :type "child" :family "Perrin"}
{:source 162 :target 74 :type "child" :family "Perrin"}
{:source 163 :target 78 :type "child" :family "Perrin"}
{:source 163 :target 74 :type "child" :family "Perrin"}
{:source 164 :target 93 :type "child" :family "Le Mintier"}
{:source 164 :target 77 :type "child" :family "Le Mintier"}
{:source 165 :target 94 :type "child" :family "Cheilan"}
{:source 165 :target 109 :type "child" :family "Cheilan"}
{:source 166 :target 68 :type "child" :family "Morin"}
{:source 166 :target 88 :type "child" :family "Morin"}
{:source 167 :target 84 :type "child" :family "Bonin"}
{:source 167 :target 91 :type "child" :family "Bonin"}
{:source 168 :target 77 :type "child" :family "Le Mintier"}
{:source 168 :target 93 :type "child" :family "Le Mintier"}
{:source 169 :target 103 :type "child" :family "Troncy"}
{:source 169 :target 105 :type "child" :family "Troncy"}
{:source 170 :target 82 :type "child" :family "Perrin"}
{:source 170 :target 87 :type "child" :family "Perrin"}
{:source 171 :target 96 :type "child" :family "Wolff"}
{:source 171 :target 104 :type "child" :family "Wolff"}
{:source 172 :target 97 :type "child" :family "Calatraba"}
{:source 172 :target 108 :type "child" :family "Calatraba"}
{:source 173 :target 71 :type "child" :family "Bonin"}
{:source 173 :target 119 :type "child" :family "Bonin"}
{:source 174 :target 112 :type "child" :family "Gaillet"}
{:source 174 :target 120 :type "child" :family "Gaillet"}
{:source 175 :target 114 :type "child" :family "Maria"}
{:source 175 :target 95 :type "child" :family "Maria"}
{:source 176 :target 101 :type "child" :family "Troncy"}
{:source 176 :target 102 :type "child" :family "Troncy"}
{:source 177 :target 117 :type "child" :family "Dieterlé"}
{:source 177 :target 122 :type "child" :family "Dieterlé"}
{:source 178 :target 114 :type "child" :family "Maria"}
{:source 178 :target 95 :type "child" :family "Maria"}])
(def colour-scheme
[{:family "Patay" :hard-colour "#FF4A46" :soft-colour "#FFDBDA"}
{:family "Maria" :hard-colour "#9B9700" :soft-colour "#EBEACC"}
{:family "Bonin" :hard-colour "#006FA6" :soft-colour "#CCE2ED"}
{:family "Calatraba" :hard-colour "#E20027" :soft-colour "#F9CCD4"}
{:family "Barrière" :hard-colour "#B79762" :soft-colour "#F1EAE0"}
{:family "Wolff" :hard-colour "#D25B88" :soft-colour "#F6DEE7"}
{:family "Rodier" :hard-colour "#953F00" :soft-colour "#EAD9CC"}
{:family "Gaillet" :hard-colour "#7A7BFF" :soft-colour "#E4E5FF"}
{:family "Pourtier" :hard-colour "#FFA0F2" :soft-colour "#FFECFC"}
{:family "Le Blanc" :hard-colour "#8CC63F" :soft-colour "#E8F4D9"}
{:family "Cheilan" :hard-colour "#0CBD66" :soft-colour "#CEF2E0"}
{:family "Perrin" :hard-colour "#012C58" :soft-colour "#CCD5DE"}
{:family "Faivre" :hard-colour "#F4D749" :soft-colour "#FDF7DB"}
{:family "Morin" :hard-colour "#2DBCF0" :soft-colour "#D5F2FC"}
{:family "Bonnet" :hard-colour "#FAA61A" :soft-colour "#FEEDD1"}
{:family "Giraud" :hard-colour "#958A9F" :soft-colour "#EAE8EC"}
{:family "Suzukawa" :hard-colour "#008080" :soft-colour "#CCE6E6"}
{:family "Troncy" :hard-colour "#671190" :soft-colour "#E1CFE9"}
{:family "Goudot" :hard-colour "#1E6E00" :soft-colour "#D2E2CC"}
{:family "Bertin" :hard-colour "#885578" :soft-colour "#E7DDE4"}
{:family "Perret" :hard-colour "#FF2F80" :soft-colour "#FFD5E6"}
{:family "Beaudin" :hard-colour "#800000" :soft-colour "#E6CCCC"}
{:family "Le Mintier" :hard-colour "#FF6832" :soft-colour "#FFE1D6"}
{:family "Dieterlé" :hard-colour "#D16100" :soft-colour "#F6DFCC"}
{:family "Bonhour" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Abadie" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Barnes" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Desrayaud" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Chapuzet" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Labaty" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Olds" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Lebon" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Antoni" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Galtier" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Morel" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Muzelli" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "de Veron" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Saillet" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Cottin" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Viosi" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Maggialetti" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Taithe" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Russo" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Jullien" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Valli" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Pelletier" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Pointet" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Nesme" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Bourel" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Sommer" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Chapuis" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Jullat" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Sadoux" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "Cappio" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}])
| 84298 | (ns the-family-tree.utils.data)
(def members
[{:name "<NAME>" :family "Troncy" :generation 1 :sex "male" :blood-line true :birth 1859 :death 1931}
{:name "<NAME>" :family "Valli" :generation 1 :sex "female" :blood-line false :birth 1872 :death 1954}
{:name "<NAME>" :family "Patay" :generation 2 :sex "male" :blood-line false :birth 1884 :death 1959}
{:name "<NAME>" :family "Bonnet" :generation 2 :sex "male" :blood-line false :birth 1884 :death 1970}
{:name "<NAME>" :family "Troncy" :generation 2 :sex "female" :blood-line true :birth 1894 :death 1979}
{:name "<NAME>" :family "Troncy" :generation 2 :sex "female" :blood-line true :birth 1895 :death 1968}
{:name "<NAME>" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1896 :death 1942}
{:name "<NAME>" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1898 :death 1972}
{:name "<NAME>" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1900 :death 1964}
{:name "<NAME>" :family "Galtier" :generation 2 :sex "female" :blood-line false :birth 1900 :death 1983}
{:name "<NAME>" :family "Desrayaud" :generation 2 :sex "female" :blood-line false :birth 1901 :death 1966}
{:name "<NAME>" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1902 :death 1959}
{:name "<NAME>" :family "Pointet" :generation 2 :sex "female" :blood-line false :birth 1907 :death 2000}
{:name "<NAME>" :family "de Veron" :generation 2 :sex "female" :blood-line false :birth 1909 :death 1994}
{:name "<NAME>" :family "<NAME>" :generation 3 :sex "male" :blood-line false :birth 1914 :death 1997}
{:name "<NAME>" :family "<NAME>" :generation 3 :sex "male" :blood-line false :birth 1916 :death 2004}
{:name "<NAME>" :family "Patay" :generation 3 :sex "female" :blood-line true :birth 1917 :death 2000}
{:name "<NAME>" :family "Di<NAME>" :generation 3 :sex "male" :blood-line false :birth 1917 :death 1990}
{:name "<NAME>" :family "Patay" :generation 3 :sex "male" :blood-line true :birth 1919 :death 1995}
{:name "<NAME>" :family "Morel" :generation 3 :sex "female" :blood-line false :birth 1922}
{:name "<NAME>" :family "Pelletier" :generation 3 :sex "male" :blood-line false :birth 1922 :death 1994}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1923 :death 1925}
{:name "<NAME>" :family "Patay" :generation 3 :sex "female" :blood-line true :birth 1924}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1926 :death 1993}
{:name "<NAME>" :family "Bonnet" :generation 3 :sex "male" :blood-line true :birth 1927 :death 2008}
{:name "<NAME>" :family "Taithe" :generation 3 :sex "female" :blood-line false :birth 1928 :death 2005}
{:name "<NAME>" :family "Bonnet" :generation 3 :sex "female" :blood-line true :birth 1929}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1929 :death 2014}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1933}
{:name "<NAME>" :family "Bourel" :generation 3 :sex "female" :blood-line false :birth 1936}
{:name "<NAME>" :family "Barrière" :generation 4 :sex "male" :blood-line false :birth 1936 :death 1999}
{:name "<NAME>" :family "Saillet" :generation 3 :sex "female" :blood-line false :birth 1937}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1939}
{:name "<NAME>" :family "Bonhour" :generation 3 :sex "female" :blood-line false :birth 1939}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1940 :death 1992}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1940}
{:name "<NAME>" :family "Bertin" :generation 4 :sex "male" :blood-line true :birth 1940}
{:name "<NAME>" :family "Jullien" :generation 4 :sex "female" :blood-line false :birth 1941}
{:name "<NAME>" :family "Bonin" :generation 4 :sex "male" :blood-line false :birth 1941}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1942 :death 1994}
{:name "<NAME>" :family "Bertin" :generation 4 :sex "female" :blood-line true :birth 1943}
{:name "<NAME>" :family "Goudot" :generation 4 :sex "male" :blood-line false :birth 1943}
{:name "<NAME>" :family "Perrin" :generation 3 :sex "male" :blood-line false :birth 1943}
{:name "<NAME>" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1945}
{:name "<NAME>" :family "Patay" :generation 4 :sex "female" :blood-line true :birth 1947}
{:name "<NAME>" :family "Beaudin" :generation 4 :sex "male" :blood-line false :birth 1947 :death 1998}
{:name "<NAME>" :family "B<NAME>in" :generation 4 :sex "male" :blood-line true :birth 1948 :death 1949}
{:name "<NAME>" :family "Sommer" :generation 3 :sex "female" :blood-line false :birth 1949}
{:name "<NAME>" :family "Rodier" :generation 4 :sex "female" :blood-line true :birth 1949}
{:name "<NAME>" :family "Le Blanc" :generation 4 :sex "female" :blood-line false :birth 1949 :death 2012}
{:name "<NAME>" :family "Barnes" :generation 3 :sex "female" :blood-line false :birth 1951}
{:name "<NAME>" :family "Suzukawa" :generation 4 :sex "male" :blood-line false :birth 1951}
{:name "<NAME>" :family "Dieterlé" :generation 4 :sex "female" :blood-line true :birth 1951}
{:name "<NAME>" :family "Patay" :generation 4 :sex "male" :blood-line true :birth 1951}
{:name "<NAME>" :family "Olds" :generation 4 :sex "female" :blood-line false :birth 1951}
{:name "<NAME>" :family "Rodier" :generation 4 :sex "male" :blood-line true :birth 1952}
{:name "<NAME>" :family "Per<NAME>" :generation 4 :sex "male" :blood-line false :birth 1952}
{:name "<NAME>" :family "Dieterlé" :generation 4 :sex "male" :blood-line true :birth 1953 :death 1994}
{:name "<NAME>" :family "<NAME>" :generation 4 :sex "female" :blood-line true :birth 1955}
{:name "<NAME>" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1957}
{:name "<NAME>" :family "Dieterlé" :generation 4 :sex "female" :blood-line true :birth 1958}
{:name "<NAME>" :family "Muzelli" :generation 4 :sex "female" :blood-line false :birth 1958}
{:name "<NAME>" :family "Pourtier" :generation 5 :sex "male" :blood-line false :birth 1958}
{:name "<NAME>" :family "Chapuis" :generation 4 :sex "female" :blood-line false :birth 1959}
{:name "<NAME>" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1959}
{:name "<NAME>" :family "Giraud" :generation 4 :sex "male" :blood-line false :birth 1960}
{:name "<NAME>" :family "Nesme" :generation 4 :sex "female" :blood-line false :birth 1961}
{:name "<NAME>" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1962}
{:name "<NAME>" :family "Morin" :generation 5 :sex "male" :blood-line false :birth 1963}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1965 :death 1989}
{:name "<NAME>" :family "Bertin" :generation 5 :sex "female" :blood-line true :birth 1966}
{:name "<NAME>" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1966}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1967}
{:name "<NAME>" :family "Chapuzet" :generation 5 :sex "female" :blood-line false :birth 1967}
{:name "<NAME>" :family "Abadie" :generation 4 :sex "female" :blood-line false :birth 1967}
{:name "<NAME>" :family "Bertin" :generation 5 :sex "male" :blood-line true :birth 1968}
{:name "<NAME>" :family "Faivre" :generation 4 :sex "male" :blood-line false :birth 1968}
{:name "<NAME>" :family "Le Mintier" :generation 5 :sex "male" :blood-line false :birth 1968}
{:name "<NAME>" :family "Perrin" :generation 4 :sex "male" :blood-line true :birth 1968}
{:name "<NAME>" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1968}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1969}
{:name "<NAME>" :family "Sadoux" :generation 4 :sex "female" :blood-line false :birth 1969}
{:name "<NAME>" :family "Perrin" :generation 4 :sex "male" :blood-line true :birth 1969}
{:name "<NAME>" :family "Cottin" :generation 5 :sex "female" :blood-line false :birth 1969}
{:name "<NAME>" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1970}
{:name "<NAME>" :family "Tron<NAME>" :generation 4 :sex "female" :blood-line true :birth 1971}
{:name "<NAME>" :family "Labaty" :generation 4 :sex "female" :blood-line false :birth 1971}
{:name "<NAME>" :family "Jullat" :generation 4 :sex "female" :blood-line false :birth 1971}
{:name "<NAME>" :family "Bertin" :generation 5 :sex "female" :blood-line true :birth 1971}
{:name "<NAME>" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1972 :death 1972}
{:name "<NAME>" :family "Goudot" :generation 5 :sex "female" :blood-line true :birth 1972}
{:name "<NAME>" :family "Lebon" :generation 5 :sex "female" :blood-line false :birth 1973}
{:name "<NAME>" :family "Bertin" :generation 5 :sex "male" :blood-line true :birth 1974}
{:name "<NAME>" :family "Le Blanc" :generation 5 :sex "female" :blood-line true :birth 1974}
{:name "<NAME>" :family "Cheilan" :generation 5 :sex "male" :blood-line false :birth 1974}
{:name "<NAME>" :family "Maria" :generation 5 :sex "male" :blood-line false :birth 1974}
{:name "<NAME>" :family "G<NAME>" :generation 5 :sex "female" :blood-line true :birth 1975}
{:name "<NAME>" :family "Calatraba" :generation 5 :sex "male" :blood-line false :birth 1975}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1975}
{:name "<NAME>" :family "Barrière" :generation 5 :sex "female" :blood-line true :birth 1976 :death 1982}
{:name "<NAME>" :family "Le Blanc" :generation 5 :sex "female" :blood-line true :birth 1976}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1976}
{:name "<NAME>" :family "Maggialetti" :generation 4 :sex "female" :blood-line false :birth 1976}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1976}
{:name "<NAME>" :family "Wolff" :generation 5 :sex "male" :blood-line false :birth 1977}
{:name "<NAME>" :family "Russo" :generation 4 :sex "female" :blood-line false :birth 1977}
{:name "<NAME>" :family "Antoni" :generation 4 :sex "female" :blood-line false :birth 1977}
{:name "<NAME>" :family "Beaudin" :generation 5 :sex "male" :blood-line true :birth 1978}
{:name "<NAME>" :family "Barrière" :generation 5 :sex "female" :blood-line true :birth 1979}
{:name "<NAME>" :family "Beaudin" :generation 5 :sex "female" :blood-line true :birth 1980}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1980}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1980}
{:name "<NAME>" :family "Gaillet" :generation 5 :sex "male" :blood-line false :birth 1981}
{:name "<NAME>" :family "Barrière" :generation 5 :sex "male" :blood-line true :birth 1982}
{:name "<NAME>" :family "Beaudin" :generation 5 :sex "female" :blood-line true :birth 1982}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1982}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1982}
{:name "<NAME>" :family "Dieterlé" :generation 5 :sex "male" :blood-line true :birth 1984}
{:name "<NAME>" :family "Suzukawa" :generation 5 :sex "female" :blood-line true :birth 1984}
{:name "<NAME>" :family "Cappio" :generation 5 :sex "female" :blood-line false :birth 1985}
{:name "<NAME>" :family "Rodier" :generation 5 :sex "female" :blood-line true :birth 1985}
{:name "<NAME>" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1986}
{:name "<NAME>" :family "Viosi" :generation 5 :sex "female" :blood-line false :birth 1986}
{:name "<NAME>" :family "Beaudin" :generation 5 :sex "male" :blood-line true :birth 1986}
{:name "<NAME>" :family "Tr<NAME>" :generation 4 :sex "male" :blood-line true :birth 1986}
{:name "<NAME>" :family "Suzukawa" :generation 5 :sex "male" :blood-line true :birth 1986}
{:name "<NAME>" :family "Rod<NAME>" :generation 5 :sex "female" :blood-line true :birth 1987}
{:name "<NAME>" :family "Giraud" :generation 5 :sex "male" :blood-line true :birth 1987}
{:name "<NAME>" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1988}
{:name "<NAME>" :family "Suzukawa" :generation 5 :sex "female" :blood-line true :birth 1988}
{:name "<NAME>" :family "Patay" :generation 5 :sex "female" :blood-line true :birth 1989}
{:name "<NAME>" :family "Rodier" :generation 5 :sex "male" :blood-line true :birth 1989}
{:name "<NAME>" :family "Per<NAME>" :generation 5 :sex "male" :blood-line true :birth 1989}
{:name "<NAME>" :family "Patay" :generation 5 :sex "male" :blood-line true :birth 1990}
{:name "<NAME>" :family "Giraud" :generation 5 :sex "male" :blood-line true :birth 1990}
{:name "<NAME>" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1991}
{:name "<NAME>" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1991}
{:name "<NAME>" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1992}
{:name "<NAME>" :family "Perret" :generation 5 :sex "male" :blood-line true :birth 1992}
{:name "<NAME>" :family "Giraud" :generation 5 :sex "female" :blood-line true :birth 1992}
{:name "<NAME>" :family "Perret" :generation 5 :sex "female" :blood-line true :birth 1994}
{:name "<NAME>" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1994}
{:name "<NAME>" :family "Bertin" :generation 6 :sex "female" :blood-line true :birth 1995}
{:name "<NAME>" :family "Perrin" :generation 5 :sex "female" :blood-line true :birth 1996}
{:name "<NAME>" :family "Pourtier" :generation 6 :sex "female" :blood-line true :birth 1997}
{:name "<NAME>" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1997}
{:name "<NAME>" :family "Bertin" :generation 6 :sex "male" :blood-line true :birth 1998}
{:name "<NAME>" :family "<NAME>" :generation 6 :sex "male" :blood-line true :birth 1999}
{:name "<NAME>" :family "Morin" :generation 6 :sex "male" :blood-line true :birth 2001}
{:name "<NAME>" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2001}
{:name "<NAME>" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2001}
{:name "<NAME>" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2002}
{:name "<NAME>" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2002}
{:name "<NAME>" :family "Bonin" :generation 6 :sex "male" :blood-line true :birth 2004}
{:name "<NAME>" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2004}
{:name "<NAME>" :family "Cheilan" :generation 6 :sex "female" :blood-line true :birth 2005}
{:name "<NAME>" :family "Le Mintier" :generation 6 :sex "male" :blood-line true :birth 2005}
{:name "<NAME>" :family "Troncy" :generation 5 :sex "female" :blood-line true :birth 2005}
{:name "<NAME>" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2005}
{:name "<NAME>" :family "Morin" :generation 6 :sex "male" :blood-line true :birth 2006}
{:name "<NAME>" :family "Bon<NAME>" :generation 6 :sex "male" :blood-line true :birth 2006}
{:name "<NAME>" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2006}
{:name "<NAME>" :family "Perrin" :generation 5 :sex "female" :blood-line true :birth 2006}
{:name "<NAME>" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2006}
{:name "<NAME>" :family "Le Mintier" :generation 6 :sex "female" :blood-line true :birth 2007}
{:name "<NAME>" :family "Cheilan" :generation 6 :sex "male" :blood-line true :birth 2007}
{:name "<NAME>" :family "Morin" :generation 6 :sex "female" :blood-line true :birth 2008}
{:name "<NAME>" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2009}
{:name "<NAME>" :family "Le Mintier" :generation 6 :sex "female" :blood-line true :birth 2009}
{:name "<NAME>" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2009}
{:name "<NAME>" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2009}
{:name "<NAME>" :family "Wolff" :generation 6 :sex "male" :blood-line true :birth 2010}
{:name "<NAME>" :family "Calatraba" :generation 6 :sex "female" :blood-line true :birth 2010}
{:name "<NAME>" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2011}
{:name "<NAME>" :family "Gaillet" :generation 6 :sex "male" :blood-line true :birth 2011}
{:name "<NAME>" :family "<NAME>" :generation 6 :sex "female" :blood-line true :birth 2011}
{:name "<NAME>" :family "Troncy" :generation 5 :sex "female" :blood-line true :birth 2012}
{:name "<NAME>" :family "Di<NAME>" :generation 6 :sex "male" :blood-line true :birth 2014}
{:name "<NAME>" :family "<NAME>" :generation 6 :sex "male" :blood-line true :birth 2015}])
(def relations
[{:source 1 :target 0 :type "partner" :family "Troncy"}
{:source 4 :target 0 :type "child" :family "Troncy"}
{:source 4 :target 1 :type "child" :family "Troncy"}
{:source 4 :target 2 :type "partner" :family "Patay"}
{:source 5 :target 0 :type "child" :family "Troncy"}
{:source 5 :target 1 :type "child" :family "Troncy"}
{:source 5 :target 3 :type "partner" :family "Bonnet"}
{:source 6 :target 0 :type "child" :family "Troncy"}
{:source 6 :target 1 :type "child" :family "Troncy"}
{:source 7 :target 0 :type "child" :family "Troncy"}
{:source 7 :target 1 :type "child" :family "Troncy"}
{:source 8 :target 0 :type "child" :family "Troncy"}
{:source 8 :target 1 :type "child" :family "Troncy"}
{:source 9 :target 7 :type "partner" :family "Troncy"}
{:source 10 :target 6 :type "partner" :family "Troncy"}
{:source 11 :target 1 :type "child" :family "Troncy"}
{:source 11 :target 0 :type "child" :family "Troncy"}
{:source 12 :target 11 :type "partner" :family "Troncy"}
{:source 13 :target 8 :type "partner" :family "Troncy"}
{:source 16 :target 4 :type "child" :family "Patay"}
{:source 16 :target 2 :type "child" :family "Patay"}
{:source 16 :target 14 :type "partner" :family "Bertin"}
{:source 18 :target 4 :type "child" :family "Patay"}
{:source 18 :target 2 :type "child" :family "Patay"}
{:source 19 :target 18 :type "partner" :family "Patay"}
{:source 21 :target 6 :type "child" :family "Troncy"}
{:source 21 :target 10 :type "child" :family "Troncy"}
{:source 22 :target 4 :type "child" :family "Patay"}
{:source 22 :target 2 :type "child" :family "Patay"}
{:source 22 :target 15 :type "partner" :family "Rodier"}
{:source 23 :target 6 :type "child" :family "Troncy"}
{:source 23 :target 10 :type "child" :family "Troncy"}
{:source 24 :target 3 :type "child" :family "Bonnet"}
{:source 24 :target 5 :type "child" :family "Bonnet"}
{:source 25 :target 24 :type "partner" :family "Bonnet"}
{:source 26 :target 3 :type "child" :family "Bonnet"}
{:source 26 :target 5 :type "child" :family "Bonnet"}
{:source 26 :target 20 :type "partner" :family "Pelletier"}
{:source 27 :target 6 :type "child" :family "Troncy"}
{:source 27 :target 10 :type "child" :family "Troncy"}
{:source 27 :target 17 :type "partner" :family "Dieterlé"}
{:source 28 :target 8 :type "child" :family "Troncy"}
{:source 28 :target 13 :type "child" :family "Troncy"}
{:source 29 :target 28 :type "partner" :family "Troncy"}
{:source 31 :target 23 :type "partner" :family "Troncy"}
{:source 32 :target 11 :type "child" :family "Troncy"}
{:source 32 :target 12 :type "child" :family "Troncy"}
{:source 34 :target 11 :type "child" :family "Troncy"}
{:source 34 :target 12 :type "child" :family "Troncy"}
{:source 34 :target 33 :type "partner" :family "Troncy"}
{:source 35 :target 6 :type "child" :family "Troncy"}
{:source 35 :target 10 :type "child" :family "Troncy"}
{:source 36 :target 14 :type "child" :family "Bertin"}
{:source 36 :target 16 :type "child" :family "Bertin"}
{:source 37 :target 36 :type "partner" :family "Bertin"}
{:source 39 :target 11 :type "child" :family "Troncy"}
{:source 39 :target 12 :type "child" :family "Troncy"}
{:source 40 :target 14 :type "child" :family "Bertin"}
{:source 40 :target 16 :type "child" :family "Bertin"}
{:source 40 :target 38 :type "partner" :family "Bonin"}
{:source 42 :target 35 :type "partner" :family "Perrin"}
{:source 43 :target 11 :type "child" :family "Troncy"}
{:source 43 :target 12 :type "child" :family "Troncy"}
{:source 44 :target 18 :type "child" :family "Patay"}
{:source 44 :target 19 :type "child" :family "Patay"}
{:source 44 :target 41 :type "partner" :family "Goudot"}
{:source 46 :target 14 :type "child" :family "Bertin"}
{:source 46 :target 16 :type "child" :family "Bertin"}
{:source 47 :target 32 :type "partner" :family "Troncy"}
{:source 48 :target 15 :type "child" :family "Rodier"}
{:source 48 :target 22 :type "child" :family "Rodier"}
{:source 48 :target 30 :type "partner" :family "Barrière"}
{:source 50 :target 43 :type "partner" :family "<NAME>"}
{:source 52 :target 17 :type "child" :family "Dieterlé"}
{:source 52 :target 27 :type "child" :family "Dieterlé"}
{:source 52 :target 49 :type "partner" :family "<NAME>"}
{:source 53 :target 18 :type "child" :family "Patay"}
{:source 53 :target 19 :type "child" :family "Patay"}
{:source 54 :target 53 :type "partner" :family "<NAME>"}
{:source 55 :target 15 :type "child" :family "Rodier"}
{:source 55 :target 22 :type "child" :family "Rodier"}
{:source 57 :target 17 :type "child" :family "Dieterlé"}
{:source 57 :target 27 :type "child" :family "Dieterlé"}
{:source 58 :target 17 :type "child" :family "Dieterlé"}
{:source 58 :target 27 :type "child" :family "Dieterlé"}
{:source 58 :target 45 :type "partner" :family "Beaudin"}
{:source 59 :target 24 :type "child" :family "Bonnet"}
{:source 59 :target 25 :type "child" :family "Bonnet"}
{:source 59 :target 56 :type "partner" :family "<NAME>"}
{:source 60 :target 17 :type "child" :family "Dieterlé"}
{:source 60 :target 27 :type "child" :family "Dieterlé"}
{:source 60 :target 51 :type "partner" :family "Suzukawa"}
{:source 61 :target 57 :type "partner" :family "<NAME>"}
{:source 63 :target 55 :type "partner" :family "<NAME>"}
{:source 64 :target 24 :type "child" :family "Bonnet"}
{:source 64 :target 25 :type "child" :family "Bonnet"}
{:source 65 :target 64 :type "partner" :family "Giraud"}
{:source 66 :target 53 :type "partner" :family "<NAME>"}
{:source 67 :target 24 :type "child" :family "Bonnet"}
{:source 67 :target 25 :type "child" :family "Bonnet"}
{:source 69 :target 28 :type "child" :family "Troncy"}
{:source 69 :target 29 :type "child" :family "Troncy"}
{:source 70 :target 36 :type "child" :family "Bertin"}
{:source 70 :target 37 :type "child" :family "Bertin"}
{:source 70 :target 62 :type "partner" :family "Pourtier"}
{:source 71 :target 38 :type "child" :family "Bonin"}
{:source 71 :target 40 :type "child" :family "Bonin"}
{:source 72 :target 23 :type "child" :family "Troncy"}
{:source 72 :target 31 :type "child" :family "Troncy"}
{:source 75 :target 36 :type "child" :family "Bertin"}
{:source 75 :target 37 :type "child" :family "Bertin"}
{:source 75 :target 73 :type "partner" :family "Bertin"}
{:source 76 :target 72 :type "partner" :family "Faivre"}
{:source 78 :target 35 :type "child" :family "Perrin"}
{:source 78 :target 42 :type "child" :family "Perrin"}
{:source 78 :target 74 :type "partner" :family "Perrin"}
{:source 79 :target 38 :type "child" :family "Bonin"}
{:source 79 :target 40 :type "child" :family "Bonin"}
{:source 79 :target 83 :type "partner" :family "Bonin"}
{:source 80 :target 23 :type "child" :family "Troncy"}
{:source 80 :target 31 :type "child" :family "Troncy"}
{:source 81 :target 80 :type "partner" :family "Troncy"}
{:source 82 :target 35 :type "child" :family "Perrin"}
{:source 82 :target 42 :type "child" :family "Perrin"}
{:source 84 :target 38 :type "child" :family "Bonin"}
{:source 84 :target 40 :type "child" :family "Bonin"}
{:source 85 :target 28 :type "child" :family "Troncy"}
{:source 85 :target 29 :type "child" :family "Troncy"}
{:source 86 :target 78 :type "partner" :family "Perrin"}
{:source 87 :target 82 :type "partner" :family "Perrin"}
{:source 88 :target 36 :type "child" :family "Bertin"}
{:source 88 :target 37 :type "child" :family "Bertin"}
{:source 88 :target 68 :type "partner" :family "Morin"}
{:source 89 :target 38 :type "child" :family "Bonin"}
{:source 89 :target 40 :type "child" :family "Bonin"}
{:source 90 :target 41 :type "child" :family "Goudot"}
{:source 90 :target 44 :type "child" :family "Goudot"}
{:source 91 :target 84 :type "partner" :family "Bonin"}
{:source 92 :target 36 :type "child" :family "Bertin"}
{:source 92 :target 37 :type "child" :family "Bertin"}
{:source 93 :target 49 :type "child" :family "Le Blanc"}
{:source 93 :target 52 :type "child" :family "Le Blanc"}
{:source 93 :target 77 :type "partner" :family "Le Mintier"}
{:source 96 :target 41 :type "child" :family "Goudot"}
{:source 96 :target 44 :type "child" :family "Goudot"}
{:source 98 :target 32 :type "child" :family "Troncy"}
{:source 98 :target 47 :type "child" :family "Troncy"}
{:source 99 :target 30 :type "child" :family "Barrière"}
{:source 99 :target 48 :type "child" :family "Barrière"}
{:source 100 :target 49 :type "child" :family "Le Blanc"}
{:source 100 :target 52 :type "child" :family "Le Blanc"}
{:source 101 :target 32 :type "child" :family "Troncy"}
{:source 101 :target 47 :type "child" :family "Troncy"}
{:source 102 :target 101 :type "partner" :family "Troncy"}
{:source 103 :target 33 :type "child" :family "Troncy"}
{:source 103 :target 34 :type "child" :family "Troncy"}
{:source 104 :target 96 :type "partner" :family "Wolff"}
{:source 105 :target 103 :type "partner" :family "Troncy"}
{:source 106 :target 82 :type "partner" :family "Perrin"}
{:source 107 :target 45 :type "child" :family "Beaudin"}
{:source 107 :target 58 :type "child" :family "Beaudin"}
{:source 108 :target 30 :type "child" :family "Barrière"}
{:source 108 :target 48 :type "child" :family "Barrière"}
{:source 108 :target 97 :type "partner" :family "Calatraba"}
{:source 109 :target 45 :type "child" :family "Beaudin"}
{:source 109 :target 58 :type "child" :family "Beaudin"}
{:source 109 :target 94 :type "partner" :family "Cheilan"}
{:source 110 :target 32 :type "child" :family "Troncy"}
{:source 110 :target 47 :type "child" :family "Troncy"}
{:source 111 :target 43 :type "child" :family "Troncy"}
{:source 111 :target 50 :type "child" :family "Troncy"}
{:source 113 :target 30 :type "child" :family "Barrière"}
{:source 113 :target 48 :type "child" :family "Barrière"}
{:source 114 :target 45 :type "child" :family "Beaudin"}
{:source 114 :target 58 :type "child" :family "Beaudin"}
{:source 114 :target 95 :type "partner" :family "Mar<NAME>"}
{:source 115 :target 32 :type "child" :family "Troncy"}
{:source 115 :target 47 :type "child" :family "Troncy"}
{:source 116 :target 43 :type "child" :family "Troncy"}
{:source 116 :target 50 :type "child" :family "Troncy"}
{:source 117 :target 57 :type "child" :family "Dieterlé"}
{:source 117 :target 61 :type "child" :family "Dieterlé"}
{:source 118 :target 51 :type "child" :family "Suzukawa"}
{:source 118 :target 60 :type "child" :family "Suzukawa"}
{:source 119 :target 71 :type "partner" :family "Bonin"}
{:source 120 :target 55 :type "child" :family "Rodier"}
{:source 120 :target 63 :type "child" :family "Rodier"}
{:source 120 :target 112 :type "partner" :family "Gaillet"}
{:source 121 :target 72 :type "child" :family "Faivre"}
{:source 121 :target 76 :type "child" :family "Faivre"}
{:source 122 :target 117 :type "partner" :family "Dieterlé"}
{:source 123 :target 45 :type "child" :family "Beaudin"}
{:source 123 :target 58 :type "child" :family "Be<NAME>"}
{:source 124 :target 43 :type "child" :family "Troncy"}
{:source 124 :target 50 :type "child" :family "Troncy"}
{:source 125 :target 51 :type "child" :family "Suzukawa"}
{:source 125 :target 60 :type "child" :family "Suzukawa"}
{:source 126 :target 55 :type "child" :family "Rodier"}
{:source 126 :target 63 :type "child" :family "Rodier"}
{:source 127 :target 64 :type "child" :family "Giraud"}
{:source 127 :target 65 :type "child" :family "Giraud"}
{:source 128 :target 62 :type "child" :family "Pourtier"}
{:source 128 :target 70 :type "child" :family "Pourtier"}
{:source 129 :target 51 :type "child" :family "Suzukawa"}
{:source 129 :target 60 :type "child" :family "Suzukawa"}
{:source 130 :target 53 :type "child" :family "Patay"}
{:source 130 :target 66 :type "child" :family "Patay"}
{:source 131 :target 55 :type "child" :family "Rodier"}
{:source 131 :target 63 :type "child" :family "Rodier"}
{:source 132 :target 56 :type "child" :family "Perret"}
{:source 132 :target 59 :type "child" :family "Perret"}
{:source 133 :target 53 :type "child" :family "Patay"}
{:source 133 :target 66 :type "child" :family "<NAME>"}
{:source 134 :target 64 :type "child" :family "Giraud"}
{:source 134 :target 65 :type "child" :family "Giraud"}
{:source 135 :target 62 :type "child" :family "Pourtier"}
{:source 135 :target 70 :type "child" :family "Pourtier"}
{:source 136 :target 32 :type "child" :family "Troncy"}
{:source 136 :target 47 :type "child" :family "Troncy"}
{:source 137 :target 62 :type "child" :family "Pourtier"}
{:source 137 :target 70 :type "child" :family "Pourtier"}
{:source 138 :target 56 :type "child" :family "Perret"}
{:source 138 :target 59 :type "child" :family "Perret"}
{:source 139 :target 64 :type "child" :family "Giraud"}
{:source 139 :target 65 :type "child" :family "Giraud"}
{:source 140 :target 56 :type "child" :family "Perret"}
{:source 140 :target 59 :type "child" :family "Perret"}
{:source 141 :target 72 :type "child" :family "Faivre"}
{:source 141 :target 76 :type "child" :family "Faivre"}
{:source 142 :target 73 :type "child" :family "Bertin"}
{:source 142 :target 75 :type "child" :family "Bertin"}
{:source 143 :target 78 :type "child" :family "Perrin"}
{:source 143 :target 86 :type "child" :family "Perrin"}
{:source 144 :target 62 :type "child" :family "Pourtier"}
{:source 144 :target 70 :type "child" :family "Pourtier"}
{:source 145 :target 72 :type "child" :family "Faivre"}
{:source 145 :target 76 :type "child" :family "Faivre"}
{:source 146 :target 73 :type "child" :family "Bertin"}
{:source 146 :target 75 :type "child" :family "Bertin"}
{:source 147 :target 79 :type "child" :family "Bonin"}
{:source 147 :target 83 :type "child" :family "Bonin"}
{:source 148 :target 68 :type "child" :family "Morin"}
{:source 148 :target 88 :type "child" :family "Morin"}
{:source 149 :target 79 :type "child" :family "Bonin"}
{:source 149 :target 83 :type "child" :family "Bonin"}
{:source 150 :target 82 :type "child" :family "Perrin"}
{:source 150 :target 106 :type "child" :family "Perrin"}
{:source 151 :target 84 :type "child" :family "Bonin"}
{:source 151 :target 91 :type "child" :family "Bonin"}
{:source 152 :target 80 :type "child" :family "Troncy"}
{:source 152 :target 81 :type "child" :family "Troncy"}
{:source 153 :target 84 :type "child" :family "Bonin"}
{:source 153 :target 91 :type "child" :family "Bonin"}
{:source 154 :target 80 :type "child" :family "Troncy"}
{:source 154 :target 81 :type "child" :family "Troncy"}
{:source 155 :target 94 :type "child" :family "Cheilan"}
{:source 155 :target 109 :type "child" :family "Cheilan"}
{:source 156 :target 93 :type "child" :family "Le Mintier"}
{:source 156 :target 77 :type "child" :family "Le Mintier"}
{:source 157 :target 98 :type "child" :family "Troncy"}
{:source 158 :target 82 :type "child" :family "Perrin"}
{:source 158 :target 87 :type "child" :family "Perrin"}
{:source 159 :target 68 :type "child" :family "Morin"}
{:source 159 :target 88 :type "child" :family "Morin"}
{:source 160 :target 79 :type "child" :family "Bonin"}
{:source 160 :target 83 :type "child" :family "Bonin"}
{:source 161 :target 80 :type "child" :family "Troncy"}
{:source 161 :target 81 :type "child" :family "Troncy"}
{:source 162 :target 78 :type "child" :family "Perrin"}
{:source 162 :target 74 :type "child" :family "Perrin"}
{:source 163 :target 78 :type "child" :family "Perrin"}
{:source 163 :target 74 :type "child" :family "Perrin"}
{:source 164 :target 93 :type "child" :family "Le Mintier"}
{:source 164 :target 77 :type "child" :family "Le Mintier"}
{:source 165 :target 94 :type "child" :family "Cheilan"}
{:source 165 :target 109 :type "child" :family "Cheilan"}
{:source 166 :target 68 :type "child" :family "Morin"}
{:source 166 :target 88 :type "child" :family "Morin"}
{:source 167 :target 84 :type "child" :family "Bonin"}
{:source 167 :target 91 :type "child" :family "Bonin"}
{:source 168 :target 77 :type "child" :family "Le Mintier"}
{:source 168 :target 93 :type "child" :family "Le Mintier"}
{:source 169 :target 103 :type "child" :family "Troncy"}
{:source 169 :target 105 :type "child" :family "Troncy"}
{:source 170 :target 82 :type "child" :family "Perrin"}
{:source 170 :target 87 :type "child" :family "Perrin"}
{:source 171 :target 96 :type "child" :family "Wolff"}
{:source 171 :target 104 :type "child" :family "Wolff"}
{:source 172 :target 97 :type "child" :family "Calatraba"}
{:source 172 :target 108 :type "child" :family "Calatraba"}
{:source 173 :target 71 :type "child" :family "Bonin"}
{:source 173 :target 119 :type "child" :family "Bonin"}
{:source 174 :target 112 :type "child" :family "Gaillet"}
{:source 174 :target 120 :type "child" :family "Gaillet"}
{:source 175 :target 114 :type "child" :family "<NAME>"}
{:source 175 :target 95 :type "child" :family "<NAME>"}
{:source 176 :target 101 :type "child" :family "Troncy"}
{:source 176 :target 102 :type "child" :family "Troncy"}
{:source 177 :target 117 :type "child" :family "Dieterlé"}
{:source 177 :target 122 :type "child" :family "Dieterlé"}
{:source 178 :target 114 :type "child" :family "<NAME>"}
{:source 178 :target 95 :type "child" :family "<NAME>"}])
(def colour-scheme
[{:family "<NAME>" :hard-colour "#FF4A46" :soft-colour "#FFDBDA"}
{:family "<NAME>" :hard-colour "#9B9700" :soft-colour "#EBEACC"}
{:family "<NAME>" :hard-colour "#006FA6" :soft-colour "#CCE2ED"}
{:family "<NAME>" :hard-colour "#E20027" :soft-colour "#F9CCD4"}
{:family "<NAME>" :hard-colour "#B79762" :soft-colour "#F1EAE0"}
{:family "<NAME>" :hard-colour "#D25B88" :soft-colour "#F6DEE7"}
{:family "<NAME>" :hard-colour "#953F00" :soft-colour "#EAD9CC"}
{:family "Gaillet" :hard-colour "#7A7BFF" :soft-colour "#E4E5FF"}
{:family "<NAME>" :hard-colour "#FFA0F2" :soft-colour "#FFECFC"}
{:family "<NAME>" :hard-colour "#8CC63F" :soft-colour "#E8F4D9"}
{:family "<NAME>" :hard-colour "#0CBD66" :soft-colour "#CEF2E0"}
{:family "<NAME>" :hard-colour "#012C58" :soft-colour "#CCD5DE"}
{:family "<NAME>" :hard-colour "#F4D749" :soft-colour "#FDF7DB"}
{:family "<NAME>" :hard-colour "#2DBCF0" :soft-colour "#D5F2FC"}
{:family "<NAME>" :hard-colour "#FAA61A" :soft-colour "#FEEDD1"}
{:family "<NAME>" :hard-colour "#958A9F" :soft-colour "#EAE8EC"}
{:family "<NAME>" :hard-colour "#008080" :soft-colour "#CCE6E6"}
{:family "<NAME>" :hard-colour "#671190" :soft-colour "#E1CFE9"}
{:family "<NAME>" :hard-colour "#1E6E00" :soft-colour "#D2E2CC"}
{:family "<NAME>" :hard-colour "#885578" :soft-colour "#E7DDE4"}
{:family "<NAME>" :hard-colour "#FF2F80" :soft-colour "#FFD5E6"}
{:family "<NAME>" :hard-colour "#800000" :soft-colour "#E6CCCC"}
{:family "<NAME>" :hard-colour "#FF6832" :soft-colour "#FFE1D6"}
{:family "<NAME>" :hard-colour "#D16100" :soft-colour "#F6DFCC"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "<NAME>" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}])
| true | (ns the-family-tree.utils.data)
(def members
[{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 1 :sex "male" :blood-line true :birth 1859 :death 1931}
{:name "PI:NAME:<NAME>END_PI" :family "Valli" :generation 1 :sex "female" :blood-line false :birth 1872 :death 1954}
{:name "PI:NAME:<NAME>END_PI" :family "Patay" :generation 2 :sex "male" :blood-line false :birth 1884 :death 1959}
{:name "PI:NAME:<NAME>END_PI" :family "Bonnet" :generation 2 :sex "male" :blood-line false :birth 1884 :death 1970}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 2 :sex "female" :blood-line true :birth 1894 :death 1979}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 2 :sex "female" :blood-line true :birth 1895 :death 1968}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1896 :death 1942}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1898 :death 1972}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1900 :death 1964}
{:name "PI:NAME:<NAME>END_PI" :family "Galtier" :generation 2 :sex "female" :blood-line false :birth 1900 :death 1983}
{:name "PI:NAME:<NAME>END_PI" :family "Desrayaud" :generation 2 :sex "female" :blood-line false :birth 1901 :death 1966}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 2 :sex "male" :blood-line true :birth 1902 :death 1959}
{:name "PI:NAME:<NAME>END_PI" :family "Pointet" :generation 2 :sex "female" :blood-line false :birth 1907 :death 2000}
{:name "PI:NAME:<NAME>END_PI" :family "de Veron" :generation 2 :sex "female" :blood-line false :birth 1909 :death 1994}
{:name "PI:NAME:<NAME>END_PI" :family "PI:NAME:<NAME>END_PI" :generation 3 :sex "male" :blood-line false :birth 1914 :death 1997}
{:name "PI:NAME:<NAME>END_PI" :family "PI:NAME:<NAME>END_PI" :generation 3 :sex "male" :blood-line false :birth 1916 :death 2004}
{:name "PI:NAME:<NAME>END_PI" :family "Patay" :generation 3 :sex "female" :blood-line true :birth 1917 :death 2000}
{:name "PI:NAME:<NAME>END_PI" :family "DiPI:NAME:<NAME>END_PI" :generation 3 :sex "male" :blood-line false :birth 1917 :death 1990}
{:name "PI:NAME:<NAME>END_PI" :family "Patay" :generation 3 :sex "male" :blood-line true :birth 1919 :death 1995}
{:name "PI:NAME:<NAME>END_PI" :family "Morel" :generation 3 :sex "female" :blood-line false :birth 1922}
{:name "PI:NAME:<NAME>END_PI" :family "Pelletier" :generation 3 :sex "male" :blood-line false :birth 1922 :death 1994}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1923 :death 1925}
{:name "PI:NAME:<NAME>END_PI" :family "Patay" :generation 3 :sex "female" :blood-line true :birth 1924}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1926 :death 1993}
{:name "PI:NAME:<NAME>END_PI" :family "Bonnet" :generation 3 :sex "male" :blood-line true :birth 1927 :death 2008}
{:name "PI:NAME:<NAME>END_PI" :family "Taithe" :generation 3 :sex "female" :blood-line false :birth 1928 :death 2005}
{:name "PI:NAME:<NAME>END_PI" :family "Bonnet" :generation 3 :sex "female" :blood-line true :birth 1929}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1929 :death 2014}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1933}
{:name "PI:NAME:<NAME>END_PI" :family "Bourel" :generation 3 :sex "female" :blood-line false :birth 1936}
{:name "PI:NAME:<NAME>END_PI" :family "Barrière" :generation 4 :sex "male" :blood-line false :birth 1936 :death 1999}
{:name "PI:NAME:<NAME>END_PI" :family "Saillet" :generation 3 :sex "female" :blood-line false :birth 1937}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1939}
{:name "PI:NAME:<NAME>END_PI" :family "Bonhour" :generation 3 :sex "female" :blood-line false :birth 1939}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1940 :death 1992}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "female" :blood-line true :birth 1940}
{:name "PI:NAME:<NAME>END_PI" :family "Bertin" :generation 4 :sex "male" :blood-line true :birth 1940}
{:name "PI:NAME:<NAME>END_PI" :family "Jullien" :generation 4 :sex "female" :blood-line false :birth 1941}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 4 :sex "male" :blood-line false :birth 1941}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1942 :death 1994}
{:name "PI:NAME:<NAME>END_PI" :family "Bertin" :generation 4 :sex "female" :blood-line true :birth 1943}
{:name "PI:NAME:<NAME>END_PI" :family "Goudot" :generation 4 :sex "male" :blood-line false :birth 1943}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 3 :sex "male" :blood-line false :birth 1943}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 3 :sex "male" :blood-line true :birth 1945}
{:name "PI:NAME:<NAME>END_PI" :family "Patay" :generation 4 :sex "female" :blood-line true :birth 1947}
{:name "PI:NAME:<NAME>END_PI" :family "Beaudin" :generation 4 :sex "male" :blood-line false :birth 1947 :death 1998}
{:name "PI:NAME:<NAME>END_PI" :family "BPI:NAME:<NAME>END_PIin" :generation 4 :sex "male" :blood-line true :birth 1948 :death 1949}
{:name "PI:NAME:<NAME>END_PI" :family "Sommer" :generation 3 :sex "female" :blood-line false :birth 1949}
{:name "PI:NAME:<NAME>END_PI" :family "Rodier" :generation 4 :sex "female" :blood-line true :birth 1949}
{:name "PI:NAME:<NAME>END_PI" :family "Le Blanc" :generation 4 :sex "female" :blood-line false :birth 1949 :death 2012}
{:name "PI:NAME:<NAME>END_PI" :family "Barnes" :generation 3 :sex "female" :blood-line false :birth 1951}
{:name "PI:NAME:<NAME>END_PI" :family "Suzukawa" :generation 4 :sex "male" :blood-line false :birth 1951}
{:name "PI:NAME:<NAME>END_PI" :family "Dieterlé" :generation 4 :sex "female" :blood-line true :birth 1951}
{:name "PI:NAME:<NAME>END_PI" :family "Patay" :generation 4 :sex "male" :blood-line true :birth 1951}
{:name "PI:NAME:<NAME>END_PI" :family "Olds" :generation 4 :sex "female" :blood-line false :birth 1951}
{:name "PI:NAME:<NAME>END_PI" :family "Rodier" :generation 4 :sex "male" :blood-line true :birth 1952}
{:name "PI:NAME:<NAME>END_PI" :family "PerPI:NAME:<NAME>END_PI" :generation 4 :sex "male" :blood-line false :birth 1952}
{:name "PI:NAME:<NAME>END_PI" :family "Dieterlé" :generation 4 :sex "male" :blood-line true :birth 1953 :death 1994}
{:name "PI:NAME:<NAME>END_PI" :family "PI:NAME:<NAME>END_PI" :generation 4 :sex "female" :blood-line true :birth 1955}
{:name "PI:NAME:<NAME>END_PI" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1957}
{:name "PI:NAME:<NAME>END_PI" :family "Dieterlé" :generation 4 :sex "female" :blood-line true :birth 1958}
{:name "PI:NAME:<NAME>END_PI" :family "Muzelli" :generation 4 :sex "female" :blood-line false :birth 1958}
{:name "PI:NAME:<NAME>END_PI" :family "Pourtier" :generation 5 :sex "male" :blood-line false :birth 1958}
{:name "PI:NAME:<NAME>END_PI" :family "Chapuis" :generation 4 :sex "female" :blood-line false :birth 1959}
{:name "PI:NAME:<NAME>END_PI" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1959}
{:name "PI:NAME:<NAME>END_PI" :family "Giraud" :generation 4 :sex "male" :blood-line false :birth 1960}
{:name "PI:NAME:<NAME>END_PI" :family "Nesme" :generation 4 :sex "female" :blood-line false :birth 1961}
{:name "PI:NAME:<NAME>END_PI" :family "Bonnet" :generation 4 :sex "female" :blood-line true :birth 1962}
{:name "PI:NAME:<NAME>END_PI" :family "Morin" :generation 5 :sex "male" :blood-line false :birth 1963}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1965 :death 1989}
{:name "PI:NAME:<NAME>END_PI" :family "Bertin" :generation 5 :sex "female" :blood-line true :birth 1966}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1966}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1967}
{:name "PI:NAME:<NAME>END_PI" :family "Chapuzet" :generation 5 :sex "female" :blood-line false :birth 1967}
{:name "PI:NAME:<NAME>END_PI" :family "Abadie" :generation 4 :sex "female" :blood-line false :birth 1967}
{:name "PI:NAME:<NAME>END_PI" :family "Bertin" :generation 5 :sex "male" :blood-line true :birth 1968}
{:name "PI:NAME:<NAME>END_PI" :family "Faivre" :generation 4 :sex "male" :blood-line false :birth 1968}
{:name "PI:NAME:<NAME>END_PI" :family "Le Mintier" :generation 5 :sex "male" :blood-line false :birth 1968}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 4 :sex "male" :blood-line true :birth 1968}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1968}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1969}
{:name "PI:NAME:<NAME>END_PI" :family "Sadoux" :generation 4 :sex "female" :blood-line false :birth 1969}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 4 :sex "male" :blood-line true :birth 1969}
{:name "PI:NAME:<NAME>END_PI" :family "Cottin" :generation 5 :sex "female" :blood-line false :birth 1969}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1970}
{:name "PI:NAME:<NAME>END_PI" :family "TronPI:NAME:<NAME>END_PI" :generation 4 :sex "female" :blood-line true :birth 1971}
{:name "PI:NAME:<NAME>END_PI" :family "Labaty" :generation 4 :sex "female" :blood-line false :birth 1971}
{:name "PI:NAME:<NAME>END_PI" :family "Jullat" :generation 4 :sex "female" :blood-line false :birth 1971}
{:name "PI:NAME:<NAME>END_PI" :family "Bertin" :generation 5 :sex "female" :blood-line true :birth 1971}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 5 :sex "male" :blood-line true :birth 1972 :death 1972}
{:name "PI:NAME:<NAME>END_PI" :family "Goudot" :generation 5 :sex "female" :blood-line true :birth 1972}
{:name "PI:NAME:<NAME>END_PI" :family "Lebon" :generation 5 :sex "female" :blood-line false :birth 1973}
{:name "PI:NAME:<NAME>END_PI" :family "Bertin" :generation 5 :sex "male" :blood-line true :birth 1974}
{:name "PI:NAME:<NAME>END_PI" :family "Le Blanc" :generation 5 :sex "female" :blood-line true :birth 1974}
{:name "PI:NAME:<NAME>END_PI" :family "Cheilan" :generation 5 :sex "male" :blood-line false :birth 1974}
{:name "PI:NAME:<NAME>END_PI" :family "Maria" :generation 5 :sex "male" :blood-line false :birth 1974}
{:name "PI:NAME:<NAME>END_PI" :family "GPI:NAME:<NAME>END_PI" :generation 5 :sex "female" :blood-line true :birth 1975}
{:name "PI:NAME:<NAME>END_PI" :family "Calatraba" :generation 5 :sex "male" :blood-line false :birth 1975}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1975}
{:name "PI:NAME:<NAME>END_PI" :family "Barrière" :generation 5 :sex "female" :blood-line true :birth 1976 :death 1982}
{:name "PI:NAME:<NAME>END_PI" :family "Le Blanc" :generation 5 :sex "female" :blood-line true :birth 1976}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1976}
{:name "PI:NAME:<NAME>END_PI" :family "Maggialetti" :generation 4 :sex "female" :blood-line false :birth 1976}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1976}
{:name "PI:NAME:<NAME>END_PI" :family "Wolff" :generation 5 :sex "male" :blood-line false :birth 1977}
{:name "PI:NAME:<NAME>END_PI" :family "Russo" :generation 4 :sex "female" :blood-line false :birth 1977}
{:name "PI:NAME:<NAME>END_PI" :family "Antoni" :generation 4 :sex "female" :blood-line false :birth 1977}
{:name "PI:NAME:<NAME>END_PI" :family "Beaudin" :generation 5 :sex "male" :blood-line true :birth 1978}
{:name "PI:NAME:<NAME>END_PI" :family "Barrière" :generation 5 :sex "female" :blood-line true :birth 1979}
{:name "PI:NAME:<NAME>END_PI" :family "Beaudin" :generation 5 :sex "female" :blood-line true :birth 1980}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1980}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1980}
{:name "PI:NAME:<NAME>END_PI" :family "Gaillet" :generation 5 :sex "male" :blood-line false :birth 1981}
{:name "PI:NAME:<NAME>END_PI" :family "Barrière" :generation 5 :sex "male" :blood-line true :birth 1982}
{:name "PI:NAME:<NAME>END_PI" :family "Beaudin" :generation 5 :sex "female" :blood-line true :birth 1982}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1982}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "male" :blood-line true :birth 1982}
{:name "PI:NAME:<NAME>END_PI" :family "Dieterlé" :generation 5 :sex "male" :blood-line true :birth 1984}
{:name "PI:NAME:<NAME>END_PI" :family "Suzukawa" :generation 5 :sex "female" :blood-line true :birth 1984}
{:name "PI:NAME:<NAME>END_PI" :family "Cappio" :generation 5 :sex "female" :blood-line false :birth 1985}
{:name "PI:NAME:<NAME>END_PI" :family "Rodier" :generation 5 :sex "female" :blood-line true :birth 1985}
{:name "PI:NAME:<NAME>END_PI" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1986}
{:name "PI:NAME:<NAME>END_PI" :family "Viosi" :generation 5 :sex "female" :blood-line false :birth 1986}
{:name "PI:NAME:<NAME>END_PI" :family "Beaudin" :generation 5 :sex "male" :blood-line true :birth 1986}
{:name "PI:NAME:<NAME>END_PI" :family "TrPI:NAME:<NAME>END_PI" :generation 4 :sex "male" :blood-line true :birth 1986}
{:name "PI:NAME:<NAME>END_PI" :family "Suzukawa" :generation 5 :sex "male" :blood-line true :birth 1986}
{:name "PI:NAME:<NAME>END_PI" :family "RodPI:NAME:<NAME>END_PI" :generation 5 :sex "female" :blood-line true :birth 1987}
{:name "PI:NAME:<NAME>END_PI" :family "Giraud" :generation 5 :sex "male" :blood-line true :birth 1987}
{:name "PI:NAME:<NAME>END_PI" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1988}
{:name "PI:NAME:<NAME>END_PI" :family "Suzukawa" :generation 5 :sex "female" :blood-line true :birth 1988}
{:name "PI:NAME:<NAME>END_PI" :family "Patay" :generation 5 :sex "female" :blood-line true :birth 1989}
{:name "PI:NAME:<NAME>END_PI" :family "Rodier" :generation 5 :sex "male" :blood-line true :birth 1989}
{:name "PI:NAME:<NAME>END_PI" :family "PerPI:NAME:<NAME>END_PI" :generation 5 :sex "male" :blood-line true :birth 1989}
{:name "PI:NAME:<NAME>END_PI" :family "Patay" :generation 5 :sex "male" :blood-line true :birth 1990}
{:name "PI:NAME:<NAME>END_PI" :family "Giraud" :generation 5 :sex "male" :blood-line true :birth 1990}
{:name "PI:NAME:<NAME>END_PI" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1991}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 4 :sex "female" :blood-line true :birth 1991}
{:name "PI:NAME:<NAME>END_PI" :family "Pourtier" :generation 6 :sex "male" :blood-line true :birth 1992}
{:name "PI:NAME:<NAME>END_PI" :family "Perret" :generation 5 :sex "male" :blood-line true :birth 1992}
{:name "PI:NAME:<NAME>END_PI" :family "Giraud" :generation 5 :sex "female" :blood-line true :birth 1992}
{:name "PI:NAME:<NAME>END_PI" :family "Perret" :generation 5 :sex "female" :blood-line true :birth 1994}
{:name "PI:NAME:<NAME>END_PI" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1994}
{:name "PI:NAME:<NAME>END_PI" :family "Bertin" :generation 6 :sex "female" :blood-line true :birth 1995}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 5 :sex "female" :blood-line true :birth 1996}
{:name "PI:NAME:<NAME>END_PI" :family "Pourtier" :generation 6 :sex "female" :blood-line true :birth 1997}
{:name "PI:NAME:<NAME>END_PI" :family "Faivre" :generation 5 :sex "female" :blood-line true :birth 1997}
{:name "PI:NAME:<NAME>END_PI" :family "Bertin" :generation 6 :sex "male" :blood-line true :birth 1998}
{:name "PI:NAME:<NAME>END_PI" :family "PI:NAME:<NAME>END_PI" :generation 6 :sex "male" :blood-line true :birth 1999}
{:name "PI:NAME:<NAME>END_PI" :family "Morin" :generation 6 :sex "male" :blood-line true :birth 2001}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2001}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2001}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2002}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2002}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 6 :sex "male" :blood-line true :birth 2004}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2004}
{:name "PI:NAME:<NAME>END_PI" :family "Cheilan" :generation 6 :sex "female" :blood-line true :birth 2005}
{:name "PI:NAME:<NAME>END_PI" :family "Le Mintier" :generation 6 :sex "male" :blood-line true :birth 2005}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 5 :sex "female" :blood-line true :birth 2005}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2005}
{:name "PI:NAME:<NAME>END_PI" :family "Morin" :generation 6 :sex "male" :blood-line true :birth 2006}
{:name "PI:NAME:<NAME>END_PI" :family "BonPI:NAME:<NAME>END_PI" :generation 6 :sex "male" :blood-line true :birth 2006}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2006}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 5 :sex "female" :blood-line true :birth 2006}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2006}
{:name "PI:NAME:<NAME>END_PI" :family "Le Mintier" :generation 6 :sex "female" :blood-line true :birth 2007}
{:name "PI:NAME:<NAME>END_PI" :family "Cheilan" :generation 6 :sex "male" :blood-line true :birth 2007}
{:name "PI:NAME:<NAME>END_PI" :family "Morin" :generation 6 :sex "female" :blood-line true :birth 2008}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2009}
{:name "PI:NAME:<NAME>END_PI" :family "Le Mintier" :generation 6 :sex "female" :blood-line true :birth 2009}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 5 :sex "male" :blood-line true :birth 2009}
{:name "PI:NAME:<NAME>END_PI" :family "Perrin" :generation 5 :sex "male" :blood-line true :birth 2009}
{:name "PI:NAME:<NAME>END_PI" :family "Wolff" :generation 6 :sex "male" :blood-line true :birth 2010}
{:name "PI:NAME:<NAME>END_PI" :family "Calatraba" :generation 6 :sex "female" :blood-line true :birth 2010}
{:name "PI:NAME:<NAME>END_PI" :family "Bonin" :generation 6 :sex "female" :blood-line true :birth 2011}
{:name "PI:NAME:<NAME>END_PI" :family "Gaillet" :generation 6 :sex "male" :blood-line true :birth 2011}
{:name "PI:NAME:<NAME>END_PI" :family "PI:NAME:<NAME>END_PI" :generation 6 :sex "female" :blood-line true :birth 2011}
{:name "PI:NAME:<NAME>END_PI" :family "Troncy" :generation 5 :sex "female" :blood-line true :birth 2012}
{:name "PI:NAME:<NAME>END_PI" :family "DiPI:NAME:<NAME>END_PI" :generation 6 :sex "male" :blood-line true :birth 2014}
{:name "PI:NAME:<NAME>END_PI" :family "PI:NAME:<NAME>END_PI" :generation 6 :sex "male" :blood-line true :birth 2015}])
(def relations
[{:source 1 :target 0 :type "partner" :family "Troncy"}
{:source 4 :target 0 :type "child" :family "Troncy"}
{:source 4 :target 1 :type "child" :family "Troncy"}
{:source 4 :target 2 :type "partner" :family "Patay"}
{:source 5 :target 0 :type "child" :family "Troncy"}
{:source 5 :target 1 :type "child" :family "Troncy"}
{:source 5 :target 3 :type "partner" :family "Bonnet"}
{:source 6 :target 0 :type "child" :family "Troncy"}
{:source 6 :target 1 :type "child" :family "Troncy"}
{:source 7 :target 0 :type "child" :family "Troncy"}
{:source 7 :target 1 :type "child" :family "Troncy"}
{:source 8 :target 0 :type "child" :family "Troncy"}
{:source 8 :target 1 :type "child" :family "Troncy"}
{:source 9 :target 7 :type "partner" :family "Troncy"}
{:source 10 :target 6 :type "partner" :family "Troncy"}
{:source 11 :target 1 :type "child" :family "Troncy"}
{:source 11 :target 0 :type "child" :family "Troncy"}
{:source 12 :target 11 :type "partner" :family "Troncy"}
{:source 13 :target 8 :type "partner" :family "Troncy"}
{:source 16 :target 4 :type "child" :family "Patay"}
{:source 16 :target 2 :type "child" :family "Patay"}
{:source 16 :target 14 :type "partner" :family "Bertin"}
{:source 18 :target 4 :type "child" :family "Patay"}
{:source 18 :target 2 :type "child" :family "Patay"}
{:source 19 :target 18 :type "partner" :family "Patay"}
{:source 21 :target 6 :type "child" :family "Troncy"}
{:source 21 :target 10 :type "child" :family "Troncy"}
{:source 22 :target 4 :type "child" :family "Patay"}
{:source 22 :target 2 :type "child" :family "Patay"}
{:source 22 :target 15 :type "partner" :family "Rodier"}
{:source 23 :target 6 :type "child" :family "Troncy"}
{:source 23 :target 10 :type "child" :family "Troncy"}
{:source 24 :target 3 :type "child" :family "Bonnet"}
{:source 24 :target 5 :type "child" :family "Bonnet"}
{:source 25 :target 24 :type "partner" :family "Bonnet"}
{:source 26 :target 3 :type "child" :family "Bonnet"}
{:source 26 :target 5 :type "child" :family "Bonnet"}
{:source 26 :target 20 :type "partner" :family "Pelletier"}
{:source 27 :target 6 :type "child" :family "Troncy"}
{:source 27 :target 10 :type "child" :family "Troncy"}
{:source 27 :target 17 :type "partner" :family "Dieterlé"}
{:source 28 :target 8 :type "child" :family "Troncy"}
{:source 28 :target 13 :type "child" :family "Troncy"}
{:source 29 :target 28 :type "partner" :family "Troncy"}
{:source 31 :target 23 :type "partner" :family "Troncy"}
{:source 32 :target 11 :type "child" :family "Troncy"}
{:source 32 :target 12 :type "child" :family "Troncy"}
{:source 34 :target 11 :type "child" :family "Troncy"}
{:source 34 :target 12 :type "child" :family "Troncy"}
{:source 34 :target 33 :type "partner" :family "Troncy"}
{:source 35 :target 6 :type "child" :family "Troncy"}
{:source 35 :target 10 :type "child" :family "Troncy"}
{:source 36 :target 14 :type "child" :family "Bertin"}
{:source 36 :target 16 :type "child" :family "Bertin"}
{:source 37 :target 36 :type "partner" :family "Bertin"}
{:source 39 :target 11 :type "child" :family "Troncy"}
{:source 39 :target 12 :type "child" :family "Troncy"}
{:source 40 :target 14 :type "child" :family "Bertin"}
{:source 40 :target 16 :type "child" :family "Bertin"}
{:source 40 :target 38 :type "partner" :family "Bonin"}
{:source 42 :target 35 :type "partner" :family "Perrin"}
{:source 43 :target 11 :type "child" :family "Troncy"}
{:source 43 :target 12 :type "child" :family "Troncy"}
{:source 44 :target 18 :type "child" :family "Patay"}
{:source 44 :target 19 :type "child" :family "Patay"}
{:source 44 :target 41 :type "partner" :family "Goudot"}
{:source 46 :target 14 :type "child" :family "Bertin"}
{:source 46 :target 16 :type "child" :family "Bertin"}
{:source 47 :target 32 :type "partner" :family "Troncy"}
{:source 48 :target 15 :type "child" :family "Rodier"}
{:source 48 :target 22 :type "child" :family "Rodier"}
{:source 48 :target 30 :type "partner" :family "Barrière"}
{:source 50 :target 43 :type "partner" :family "PI:NAME:<NAME>END_PI"}
{:source 52 :target 17 :type "child" :family "Dieterlé"}
{:source 52 :target 27 :type "child" :family "Dieterlé"}
{:source 52 :target 49 :type "partner" :family "PI:NAME:<NAME>END_PI"}
{:source 53 :target 18 :type "child" :family "Patay"}
{:source 53 :target 19 :type "child" :family "Patay"}
{:source 54 :target 53 :type "partner" :family "PI:NAME:<NAME>END_PI"}
{:source 55 :target 15 :type "child" :family "Rodier"}
{:source 55 :target 22 :type "child" :family "Rodier"}
{:source 57 :target 17 :type "child" :family "Dieterlé"}
{:source 57 :target 27 :type "child" :family "Dieterlé"}
{:source 58 :target 17 :type "child" :family "Dieterlé"}
{:source 58 :target 27 :type "child" :family "Dieterlé"}
{:source 58 :target 45 :type "partner" :family "Beaudin"}
{:source 59 :target 24 :type "child" :family "Bonnet"}
{:source 59 :target 25 :type "child" :family "Bonnet"}
{:source 59 :target 56 :type "partner" :family "PI:NAME:<NAME>END_PI"}
{:source 60 :target 17 :type "child" :family "Dieterlé"}
{:source 60 :target 27 :type "child" :family "Dieterlé"}
{:source 60 :target 51 :type "partner" :family "Suzukawa"}
{:source 61 :target 57 :type "partner" :family "PI:NAME:<NAME>END_PI"}
{:source 63 :target 55 :type "partner" :family "PI:NAME:<NAME>END_PI"}
{:source 64 :target 24 :type "child" :family "Bonnet"}
{:source 64 :target 25 :type "child" :family "Bonnet"}
{:source 65 :target 64 :type "partner" :family "Giraud"}
{:source 66 :target 53 :type "partner" :family "PI:NAME:<NAME>END_PI"}
{:source 67 :target 24 :type "child" :family "Bonnet"}
{:source 67 :target 25 :type "child" :family "Bonnet"}
{:source 69 :target 28 :type "child" :family "Troncy"}
{:source 69 :target 29 :type "child" :family "Troncy"}
{:source 70 :target 36 :type "child" :family "Bertin"}
{:source 70 :target 37 :type "child" :family "Bertin"}
{:source 70 :target 62 :type "partner" :family "Pourtier"}
{:source 71 :target 38 :type "child" :family "Bonin"}
{:source 71 :target 40 :type "child" :family "Bonin"}
{:source 72 :target 23 :type "child" :family "Troncy"}
{:source 72 :target 31 :type "child" :family "Troncy"}
{:source 75 :target 36 :type "child" :family "Bertin"}
{:source 75 :target 37 :type "child" :family "Bertin"}
{:source 75 :target 73 :type "partner" :family "Bertin"}
{:source 76 :target 72 :type "partner" :family "Faivre"}
{:source 78 :target 35 :type "child" :family "Perrin"}
{:source 78 :target 42 :type "child" :family "Perrin"}
{:source 78 :target 74 :type "partner" :family "Perrin"}
{:source 79 :target 38 :type "child" :family "Bonin"}
{:source 79 :target 40 :type "child" :family "Bonin"}
{:source 79 :target 83 :type "partner" :family "Bonin"}
{:source 80 :target 23 :type "child" :family "Troncy"}
{:source 80 :target 31 :type "child" :family "Troncy"}
{:source 81 :target 80 :type "partner" :family "Troncy"}
{:source 82 :target 35 :type "child" :family "Perrin"}
{:source 82 :target 42 :type "child" :family "Perrin"}
{:source 84 :target 38 :type "child" :family "Bonin"}
{:source 84 :target 40 :type "child" :family "Bonin"}
{:source 85 :target 28 :type "child" :family "Troncy"}
{:source 85 :target 29 :type "child" :family "Troncy"}
{:source 86 :target 78 :type "partner" :family "Perrin"}
{:source 87 :target 82 :type "partner" :family "Perrin"}
{:source 88 :target 36 :type "child" :family "Bertin"}
{:source 88 :target 37 :type "child" :family "Bertin"}
{:source 88 :target 68 :type "partner" :family "Morin"}
{:source 89 :target 38 :type "child" :family "Bonin"}
{:source 89 :target 40 :type "child" :family "Bonin"}
{:source 90 :target 41 :type "child" :family "Goudot"}
{:source 90 :target 44 :type "child" :family "Goudot"}
{:source 91 :target 84 :type "partner" :family "Bonin"}
{:source 92 :target 36 :type "child" :family "Bertin"}
{:source 92 :target 37 :type "child" :family "Bertin"}
{:source 93 :target 49 :type "child" :family "Le Blanc"}
{:source 93 :target 52 :type "child" :family "Le Blanc"}
{:source 93 :target 77 :type "partner" :family "Le Mintier"}
{:source 96 :target 41 :type "child" :family "Goudot"}
{:source 96 :target 44 :type "child" :family "Goudot"}
{:source 98 :target 32 :type "child" :family "Troncy"}
{:source 98 :target 47 :type "child" :family "Troncy"}
{:source 99 :target 30 :type "child" :family "Barrière"}
{:source 99 :target 48 :type "child" :family "Barrière"}
{:source 100 :target 49 :type "child" :family "Le Blanc"}
{:source 100 :target 52 :type "child" :family "Le Blanc"}
{:source 101 :target 32 :type "child" :family "Troncy"}
{:source 101 :target 47 :type "child" :family "Troncy"}
{:source 102 :target 101 :type "partner" :family "Troncy"}
{:source 103 :target 33 :type "child" :family "Troncy"}
{:source 103 :target 34 :type "child" :family "Troncy"}
{:source 104 :target 96 :type "partner" :family "Wolff"}
{:source 105 :target 103 :type "partner" :family "Troncy"}
{:source 106 :target 82 :type "partner" :family "Perrin"}
{:source 107 :target 45 :type "child" :family "Beaudin"}
{:source 107 :target 58 :type "child" :family "Beaudin"}
{:source 108 :target 30 :type "child" :family "Barrière"}
{:source 108 :target 48 :type "child" :family "Barrière"}
{:source 108 :target 97 :type "partner" :family "Calatraba"}
{:source 109 :target 45 :type "child" :family "Beaudin"}
{:source 109 :target 58 :type "child" :family "Beaudin"}
{:source 109 :target 94 :type "partner" :family "Cheilan"}
{:source 110 :target 32 :type "child" :family "Troncy"}
{:source 110 :target 47 :type "child" :family "Troncy"}
{:source 111 :target 43 :type "child" :family "Troncy"}
{:source 111 :target 50 :type "child" :family "Troncy"}
{:source 113 :target 30 :type "child" :family "Barrière"}
{:source 113 :target 48 :type "child" :family "Barrière"}
{:source 114 :target 45 :type "child" :family "Beaudin"}
{:source 114 :target 58 :type "child" :family "Beaudin"}
{:source 114 :target 95 :type "partner" :family "MarPI:NAME:<NAME>END_PI"}
{:source 115 :target 32 :type "child" :family "Troncy"}
{:source 115 :target 47 :type "child" :family "Troncy"}
{:source 116 :target 43 :type "child" :family "Troncy"}
{:source 116 :target 50 :type "child" :family "Troncy"}
{:source 117 :target 57 :type "child" :family "Dieterlé"}
{:source 117 :target 61 :type "child" :family "Dieterlé"}
{:source 118 :target 51 :type "child" :family "Suzukawa"}
{:source 118 :target 60 :type "child" :family "Suzukawa"}
{:source 119 :target 71 :type "partner" :family "Bonin"}
{:source 120 :target 55 :type "child" :family "Rodier"}
{:source 120 :target 63 :type "child" :family "Rodier"}
{:source 120 :target 112 :type "partner" :family "Gaillet"}
{:source 121 :target 72 :type "child" :family "Faivre"}
{:source 121 :target 76 :type "child" :family "Faivre"}
{:source 122 :target 117 :type "partner" :family "Dieterlé"}
{:source 123 :target 45 :type "child" :family "Beaudin"}
{:source 123 :target 58 :type "child" :family "BePI:NAME:<NAME>END_PI"}
{:source 124 :target 43 :type "child" :family "Troncy"}
{:source 124 :target 50 :type "child" :family "Troncy"}
{:source 125 :target 51 :type "child" :family "Suzukawa"}
{:source 125 :target 60 :type "child" :family "Suzukawa"}
{:source 126 :target 55 :type "child" :family "Rodier"}
{:source 126 :target 63 :type "child" :family "Rodier"}
{:source 127 :target 64 :type "child" :family "Giraud"}
{:source 127 :target 65 :type "child" :family "Giraud"}
{:source 128 :target 62 :type "child" :family "Pourtier"}
{:source 128 :target 70 :type "child" :family "Pourtier"}
{:source 129 :target 51 :type "child" :family "Suzukawa"}
{:source 129 :target 60 :type "child" :family "Suzukawa"}
{:source 130 :target 53 :type "child" :family "Patay"}
{:source 130 :target 66 :type "child" :family "Patay"}
{:source 131 :target 55 :type "child" :family "Rodier"}
{:source 131 :target 63 :type "child" :family "Rodier"}
{:source 132 :target 56 :type "child" :family "Perret"}
{:source 132 :target 59 :type "child" :family "Perret"}
{:source 133 :target 53 :type "child" :family "Patay"}
{:source 133 :target 66 :type "child" :family "PI:NAME:<NAME>END_PI"}
{:source 134 :target 64 :type "child" :family "Giraud"}
{:source 134 :target 65 :type "child" :family "Giraud"}
{:source 135 :target 62 :type "child" :family "Pourtier"}
{:source 135 :target 70 :type "child" :family "Pourtier"}
{:source 136 :target 32 :type "child" :family "Troncy"}
{:source 136 :target 47 :type "child" :family "Troncy"}
{:source 137 :target 62 :type "child" :family "Pourtier"}
{:source 137 :target 70 :type "child" :family "Pourtier"}
{:source 138 :target 56 :type "child" :family "Perret"}
{:source 138 :target 59 :type "child" :family "Perret"}
{:source 139 :target 64 :type "child" :family "Giraud"}
{:source 139 :target 65 :type "child" :family "Giraud"}
{:source 140 :target 56 :type "child" :family "Perret"}
{:source 140 :target 59 :type "child" :family "Perret"}
{:source 141 :target 72 :type "child" :family "Faivre"}
{:source 141 :target 76 :type "child" :family "Faivre"}
{:source 142 :target 73 :type "child" :family "Bertin"}
{:source 142 :target 75 :type "child" :family "Bertin"}
{:source 143 :target 78 :type "child" :family "Perrin"}
{:source 143 :target 86 :type "child" :family "Perrin"}
{:source 144 :target 62 :type "child" :family "Pourtier"}
{:source 144 :target 70 :type "child" :family "Pourtier"}
{:source 145 :target 72 :type "child" :family "Faivre"}
{:source 145 :target 76 :type "child" :family "Faivre"}
{:source 146 :target 73 :type "child" :family "Bertin"}
{:source 146 :target 75 :type "child" :family "Bertin"}
{:source 147 :target 79 :type "child" :family "Bonin"}
{:source 147 :target 83 :type "child" :family "Bonin"}
{:source 148 :target 68 :type "child" :family "Morin"}
{:source 148 :target 88 :type "child" :family "Morin"}
{:source 149 :target 79 :type "child" :family "Bonin"}
{:source 149 :target 83 :type "child" :family "Bonin"}
{:source 150 :target 82 :type "child" :family "Perrin"}
{:source 150 :target 106 :type "child" :family "Perrin"}
{:source 151 :target 84 :type "child" :family "Bonin"}
{:source 151 :target 91 :type "child" :family "Bonin"}
{:source 152 :target 80 :type "child" :family "Troncy"}
{:source 152 :target 81 :type "child" :family "Troncy"}
{:source 153 :target 84 :type "child" :family "Bonin"}
{:source 153 :target 91 :type "child" :family "Bonin"}
{:source 154 :target 80 :type "child" :family "Troncy"}
{:source 154 :target 81 :type "child" :family "Troncy"}
{:source 155 :target 94 :type "child" :family "Cheilan"}
{:source 155 :target 109 :type "child" :family "Cheilan"}
{:source 156 :target 93 :type "child" :family "Le Mintier"}
{:source 156 :target 77 :type "child" :family "Le Mintier"}
{:source 157 :target 98 :type "child" :family "Troncy"}
{:source 158 :target 82 :type "child" :family "Perrin"}
{:source 158 :target 87 :type "child" :family "Perrin"}
{:source 159 :target 68 :type "child" :family "Morin"}
{:source 159 :target 88 :type "child" :family "Morin"}
{:source 160 :target 79 :type "child" :family "Bonin"}
{:source 160 :target 83 :type "child" :family "Bonin"}
{:source 161 :target 80 :type "child" :family "Troncy"}
{:source 161 :target 81 :type "child" :family "Troncy"}
{:source 162 :target 78 :type "child" :family "Perrin"}
{:source 162 :target 74 :type "child" :family "Perrin"}
{:source 163 :target 78 :type "child" :family "Perrin"}
{:source 163 :target 74 :type "child" :family "Perrin"}
{:source 164 :target 93 :type "child" :family "Le Mintier"}
{:source 164 :target 77 :type "child" :family "Le Mintier"}
{:source 165 :target 94 :type "child" :family "Cheilan"}
{:source 165 :target 109 :type "child" :family "Cheilan"}
{:source 166 :target 68 :type "child" :family "Morin"}
{:source 166 :target 88 :type "child" :family "Morin"}
{:source 167 :target 84 :type "child" :family "Bonin"}
{:source 167 :target 91 :type "child" :family "Bonin"}
{:source 168 :target 77 :type "child" :family "Le Mintier"}
{:source 168 :target 93 :type "child" :family "Le Mintier"}
{:source 169 :target 103 :type "child" :family "Troncy"}
{:source 169 :target 105 :type "child" :family "Troncy"}
{:source 170 :target 82 :type "child" :family "Perrin"}
{:source 170 :target 87 :type "child" :family "Perrin"}
{:source 171 :target 96 :type "child" :family "Wolff"}
{:source 171 :target 104 :type "child" :family "Wolff"}
{:source 172 :target 97 :type "child" :family "Calatraba"}
{:source 172 :target 108 :type "child" :family "Calatraba"}
{:source 173 :target 71 :type "child" :family "Bonin"}
{:source 173 :target 119 :type "child" :family "Bonin"}
{:source 174 :target 112 :type "child" :family "Gaillet"}
{:source 174 :target 120 :type "child" :family "Gaillet"}
{:source 175 :target 114 :type "child" :family "PI:NAME:<NAME>END_PI"}
{:source 175 :target 95 :type "child" :family "PI:NAME:<NAME>END_PI"}
{:source 176 :target 101 :type "child" :family "Troncy"}
{:source 176 :target 102 :type "child" :family "Troncy"}
{:source 177 :target 117 :type "child" :family "Dieterlé"}
{:source 177 :target 122 :type "child" :family "Dieterlé"}
{:source 178 :target 114 :type "child" :family "PI:NAME:<NAME>END_PI"}
{:source 178 :target 95 :type "child" :family "PI:NAME:<NAME>END_PI"}])
(def colour-scheme
[{:family "PI:NAME:<NAME>END_PI" :hard-colour "#FF4A46" :soft-colour "#FFDBDA"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#9B9700" :soft-colour "#EBEACC"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#006FA6" :soft-colour "#CCE2ED"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#E20027" :soft-colour "#F9CCD4"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#B79762" :soft-colour "#F1EAE0"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#D25B88" :soft-colour "#F6DEE7"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#953F00" :soft-colour "#EAD9CC"}
{:family "Gaillet" :hard-colour "#7A7BFF" :soft-colour "#E4E5FF"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#FFA0F2" :soft-colour "#FFECFC"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#8CC63F" :soft-colour "#E8F4D9"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#0CBD66" :soft-colour "#CEF2E0"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#012C58" :soft-colour "#CCD5DE"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#F4D749" :soft-colour "#FDF7DB"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#2DBCF0" :soft-colour "#D5F2FC"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#FAA61A" :soft-colour "#FEEDD1"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#958A9F" :soft-colour "#EAE8EC"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#008080" :soft-colour "#CCE6E6"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#671190" :soft-colour "#E1CFE9"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#1E6E00" :soft-colour "#D2E2CC"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#885578" :soft-colour "#E7DDE4"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#FF2F80" :soft-colour "#FFD5E6"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#800000" :soft-colour "#E6CCCC"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#FF6832" :soft-colour "#FFE1D6"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#D16100" :soft-colour "#F6DFCC"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}
{:family "PI:NAME:<NAME>END_PI" :hard-colour "#BDC9D2" :soft-colour "#F1F3F5"}])
|
[
{
"context": "-new-stock-exchange [\"A\" \"B\" \"C\"])))))\n (is (= [\"Alice\" \"Bob\"]\n (sort\n (keys\n ",
"end": 530,
"score": 0.9995748400688171,
"start": 525,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ck-exchange [\"A\" \"B\" \"C\"])))))\n (is (= [\"Alice\" \"Bob\"]\n (sort\n (keys\n ((",
"end": 536,
"score": 0.9993549585342407,
"start": 533,
"tag": "NAME",
"value": "Bob"
},
{
"context": " ((stock/get-new-stock-exchange [\"A\"] [\"Alice\" \"Bob\"]) :A)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\"]",
"end": 628,
"score": 0.9995680451393127,
"start": 623,
"tag": "NAME",
"value": "Alice"
},
{
"context": " ((stock/get-new-stock-exchange [\"A\"] [\"Alice\" \"Bob\"]) :A)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n ",
"end": 634,
"score": 0.9991118311882019,
"start": 631,
"tag": "NAME",
"value": "Bob"
},
{
"context": "xchange [\"A\"] [\"Alice\" \"Bob\"]) :A)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (sort\n (keys\n ",
"end": 662,
"score": 0.999762237071991,
"start": 657,
"tag": "NAME",
"value": "Alice"
},
{
"context": "[\"A\"] [\"Alice\" \"Bob\"]) :A)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (sort\n (keys\n ",
"end": 668,
"score": 0.9997380375862122,
"start": 665,
"tag": "NAME",
"value": "Bob"
},
{
"context": "[\"Alice\" \"Bob\"]) :A)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (sort\n (keys\n ((st",
"end": 676,
"score": 0.9997646808624268,
"start": 671,
"tag": "NAME",
"value": "Carol"
},
{
"context": "-exchange\n [\"A\" \"B\"]\n [\"Alice\" \"Bob\" \"Carol\"]) :B)))))\n (is (= [\"Alice\" \"Bob\" ",
"end": 798,
"score": 0.9996851086616516,
"start": 793,
"tag": "NAME",
"value": "Alice"
},
{
"context": "e\n [\"A\" \"B\"]\n [\"Alice\" \"Bob\" \"Carol\"]) :B)))))\n (is (= [\"Alice\" \"Bob\" \"Carol",
"end": 804,
"score": 0.9997557997703552,
"start": 801,
"tag": "NAME",
"value": "Bob"
},
{
"context": " [\"A\" \"B\"]\n [\"Alice\" \"Bob\" \"Carol\"]) :B)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\" \"Dave\"",
"end": 812,
"score": 0.9997375011444092,
"start": 807,
"tag": "NAME",
"value": "Carol"
},
{
"context": " [\"Alice\" \"Bob\" \"Carol\"]) :B)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\" \"Dave\"]\n (sort\n (",
"end": 840,
"score": 0.9997465014457703,
"start": 835,
"tag": "NAME",
"value": "Alice"
},
{
"context": "Alice\" \"Bob\" \"Carol\"]) :B)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\" \"Dave\"]\n (sort\n (keys\n ",
"end": 846,
"score": 0.9997678399085999,
"start": 843,
"tag": "NAME",
"value": "Bob"
},
{
"context": " \"Bob\" \"Carol\"]) :B)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\" \"Dave\"]\n (sort\n (keys\n ",
"end": 854,
"score": 0.9997962713241577,
"start": 849,
"tag": "NAME",
"value": "Carol"
},
{
"context": "Carol\"]) :B)))))\n (is (= [\"Alice\" \"Bob\" \"Carol\" \"Dave\"]\n (sort\n (keys\n ((st",
"end": 861,
"score": 0.9997262954711914,
"start": 857,
"tag": "NAME",
"value": "Dave"
},
{
"context": "hange\n [\"A\" \"B\" \"C\"]\n [\"Alice\" \"Bob\" \"Carol\" \"Dave\"]) :C))))))\n\n(deftest test-g",
"end": 987,
"score": 0.9997789859771729,
"start": 982,
"tag": "NAME",
"value": "Alice"
},
{
"context": " [\"A\" \"B\" \"C\"]\n [\"Alice\" \"Bob\" \"Carol\" \"Dave\"]) :C))))))\n\n(deftest test-get-sto",
"end": 993,
"score": 0.9997639060020447,
"start": 990,
"tag": "NAME",
"value": "Bob"
},
{
"context": " [\"A\" \"B\" \"C\"]\n [\"Alice\" \"Bob\" \"Carol\" \"Dave\"]) :C))))))\n\n(deftest test-get-stock-excha",
"end": 1001,
"score": 0.99976646900177,
"start": 996,
"tag": "NAME",
"value": "Carol"
},
{
"context": "A\" \"B\" \"C\"]\n [\"Alice\" \"Bob\" \"Carol\" \"Dave\"]) :C))))))\n\n(deftest test-get-stock-exchange\n (",
"end": 1008,
"score": 0.9997411966323853,
"start": 1004,
"tag": "NAME",
"value": "Dave"
},
{
"context": "))\n\n(deftest test-get-company-holdings\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (sort\n (keys\n ",
"end": 1224,
"score": 0.9997784495353699,
"start": 1219,
"tag": "NAME",
"value": "Alice"
},
{
"context": "test test-get-company-holdings\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (sort\n (keys\n ",
"end": 1230,
"score": 0.9997761845588684,
"start": 1227,
"tag": "NAME",
"value": "Bob"
},
{
"context": "est-get-company-holdings\n (is (= [\"Alice\" \"Bob\" \"Carol\"]\n (sort\n (keys\n (s",
"end": 1238,
"score": 0.9997180700302124,
"start": 1233,
"tag": "NAME",
"value": "Carol"
},
{
"context": "-holdings \"A\" util/fake-game-data)))))\n (is (= [\"Carol\"]\n (sort\n (keys\n (s",
"end": 1359,
"score": 0.9994068145751953,
"start": 1354,
"tag": "NAME",
"value": "Carol"
},
{
"context": "-holdings \"B\" util/fake-game-data)))))\n (is (= [\"Bob\" \"Carol\"]\n (sort\n (keys\n ",
"end": 1478,
"score": 0.9997803568840027,
"start": 1475,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ngs \"B\" util/fake-game-data)))))\n (is (= [\"Bob\" \"Carol\"]\n (sort\n (keys\n (s",
"end": 1486,
"score": 0.9997488260269165,
"start": 1481,
"tag": "NAME",
"value": "Carol"
},
{
"context": "hares\n (is (= 1000 (stock/get-player-shares \"A\" \"Alice\" util/fake-game-data)))\n (is (= 500 (stock/get-p",
"end": 1912,
"score": 0.9977356791496277,
"start": 1907,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ata)))\n (is (= 500 (stock/get-player-shares \"A\" \"Bob\" util/fake-game-data)))\n (is (= 100 (stock/get-p",
"end": 1983,
"score": 0.9954055547714233,
"start": 1980,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ata)))\n (is (= 100 (stock/get-player-shares \"A\" \"Carol\" util/fake-game-data)))\n (is (= 0 (stock/get-pla",
"end": 2056,
"score": 0.9890124797821045,
"start": 2051,
"tag": "NAME",
"value": "Carol"
},
{
"context": "-data)))\n (is (= 0 (stock/get-player-shares \"B\" \"Alice\" util/fake-game-data)))\n (is (= 1000 (stock/get-",
"end": 2127,
"score": 0.9977026581764221,
"start": 2122,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ta)))\n (is (= 1000 (stock/get-player-shares \"B\" \"Carol\" util/fake-game-data)))\n (is (= 500 (stock/get-p",
"end": 2201,
"score": 0.9908332824707031,
"start": 2196,
"tag": "NAME",
"value": "Carol"
},
{
"context": "ata)))\n (is (= 500 (stock/get-player-shares \"C\" \"Bob\" util/fake-game-data)))\n (is (= 100 (stock/get-p",
"end": 2272,
"score": 0.9966036081314087,
"start": 2269,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ata)))\n (is (= 100 (stock/get-player-shares \"C\" \"Carol\" util/fake-game-data)))\n (is (= 0 (stock/get-pla",
"end": 2345,
"score": 0.9826277494430542,
"start": 2340,
"tag": "NAME",
"value": "Carol"
},
{
"context": "-data)))\n (is (= 0 (stock/get-player-shares \"Z\" \"Bob\" util/fake-game-data)))\n (is (= 5 (count (stock/",
"end": 2414,
"score": 0.9978314638137817,
"start": 2411,
"tag": "NAME",
"value": "Bob"
},
{
"context": "))\n (is (= 5 (count (stock/get-player-shares \"Carol\" util/fake-game-data)))))\n\n(deftest test-get-play",
"end": 2488,
"score": 0.8561497330665588,
"start": 2486,
"tag": "NAME",
"value": "ol"
},
{
"context": "ck/get-player-shares-with-company\n \"A\" \"Carol\" util/fake-game-data)))\n (is (= [:B 1000]\n ",
"end": 2647,
"score": 0.9687001705169678,
"start": 2642,
"tag": "NAME",
"value": "Carol"
},
{
"context": "ck/get-player-shares-with-company\n \"B\" \"Carol\" util/fake-game-data)))\n (is (= [:C 100]\n ",
"end": 2759,
"score": 0.9699414968490601,
"start": 2754,
"tag": "NAME",
"value": "Carol"
},
{
"context": "ck/get-player-shares-with-company\n \"C\" \"Carol\" util/fake-game-data))))\n\n(deftest test-get-playe",
"end": 2870,
"score": 0.9642986059188843,
"start": 2865,
"tag": "NAME",
"value": "Carol"
},
{
"context": "tock/get-player-shares-with-companies\n \"Carol\" util/fake-game-data)))\n (is (= [[:A 100] [:B 10",
"end": 3049,
"score": 0.9981212019920349,
"start": 3044,
"tag": "NAME",
"value": "Carol"
},
{
"context": "r-shares-with-companies\n [\"A\" \"B\" \"C\"] \"Carol\" util/fake-game-data))))\n\n(deftest test-get-playe",
"end": 3193,
"score": 0.9991628527641296,
"start": 3188,
"tag": "NAME",
"value": "Carol"
},
{
"context": "st test-get-players-shares-with-player\n (is (= [\"Carol\" {:A 100, :B 1000, :C 100}]\n (stock/get-p",
"end": 3281,
"score": 0.9993870258331299,
"start": 3276,
"tag": "NAME",
"value": "Carol"
},
{
"context": "yers-shares-with-player\n [\"A\" \"B\" \"C\"] \"Carol\" util/fake-game-data))))\n\n(deftest test-get-playe",
"end": 3388,
"score": 0.9993072152137756,
"start": 3383,
"tag": "NAME",
"value": "Carol"
},
{
"context": "))))\n\n(deftest test-get-players-shares\n (is (= {\"Alice\" {:A 1000, :B 0, :C 0, :D 0, :E 0},\n \"Bo",
"end": 3464,
"score": 0.9997351765632629,
"start": 3459,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ce\" {:A 1000, :B 0, :C 0, :D 0, :E 0},\n \"Bob\" {:A 500, :B 0, :C 500, :D 0, :E 0},\n \"C",
"end": 3515,
"score": 0.9997203350067139,
"start": 3512,
"tag": "NAME",
"value": "Bob"
},
{
"context": "b\" {:A 500, :B 0, :C 500, :D 0, :E 0},\n \"Carol\" {:A 100, :B 1000, :C 100, :D 0, :E 0}}\n ",
"end": 3569,
"score": 0.9994038343429565,
"start": 3564,
"tag": "NAME",
"value": "Carol"
},
{
"context": "-players-shares util/fake-game-data)))\n (is (= {\"Alice\" {:A 1000, :B 0, :C 0},\n \"Bob\" {:A 500, ",
"end": 3684,
"score": 0.9997297525405884,
"start": 3679,
"tag": "NAME",
"value": "Alice"
},
{
"context": "(is (= {\"Alice\" {:A 1000, :B 0, :C 0},\n \"Bob\" {:A 500, :B 0, :C 500},\n \"Carol\" {:A 10",
"end": 3723,
"score": 0.9997475147247314,
"start": 3720,
"tag": "NAME",
"value": "Bob"
},
{
"context": " \"Bob\" {:A 500, :B 0, :C 500},\n \"Carol\" {:A 100, :B 1000, :C 100}}\n (stock/get-p",
"end": 3765,
"score": 0.9994994401931763,
"start": 3760,
"tag": "NAME",
"value": "Carol"
},
{
"context": "shares\n (is (= 100 (stock/get-player-shares \"A\" \"Carol\" util/fake-game-data)))\n (let [game-data (stock/",
"end": 3948,
"score": 0.9979493021965027,
"start": 3943,
"tag": "NAME",
"value": "Carol"
},
{
"context": "(stock/add-player-shares\n \"A\" \"Carol\" 1000 util/fake-game-data)]\n (is (= 1100 (stoc",
"end": 4046,
"score": 0.9980652332305908,
"start": 4041,
"tag": "NAME",
"value": "Carol"
},
{
"context": "a)]\n (is (= 1100 (stock/get-player-shares \"A\" \"Carol\" game-data))))\n (is (= 0 (stock/get-player-share",
"end": 4126,
"score": 0.999174177646637,
"start": 4121,
"tag": "NAME",
"value": "Carol"
},
{
"context": "data))))\n (is (= 0 (stock/get-player-shares \"B\" \"Alice\" util/fake-game-data)))\n (let [game-data (stock/",
"end": 4188,
"score": 0.9998415112495422,
"start": 4183,
"tag": "NAME",
"value": "Alice"
},
{
"context": "(stock/add-player-shares\n \"B\" \"Alice\" 500 util/fake-game-data)]\n (is (= 500 (stock/",
"end": 4286,
"score": 0.9998332858085632,
"start": 4281,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ta)]\n (is (= 500 (stock/get-player-shares \"B\" \"Alice\" game-data)))))\n\n(deftest test-compute-value\n (l",
"end": 4364,
"score": 0.9998462200164795,
"start": 4359,
"tag": "NAME",
"value": "Alice"
}
] | test/starlanes/finance/stock_test.clj | oubiwann/clj-starlanes | 1 | (ns starlanes.finance.stock-test
(:require [clojure.test :refer :all]
[starlanes.finance.stock :as stock]
[starlanes.util :as util]))
(deftest test-get-new-exchange
(is (= [:A]
(sort
(keys
(stock/get-new-stock-exchange ["A"])))))
(is (= [:A :B]
(sort
(keys
(stock/get-new-stock-exchange ["A" "B"])))))
(is (= [:A :B :C]
(sort
(keys
(stock/get-new-stock-exchange ["A" "B" "C"])))))
(is (= ["Alice" "Bob"]
(sort
(keys
((stock/get-new-stock-exchange ["A"] ["Alice" "Bob"]) :A)))))
(is (= ["Alice" "Bob" "Carol"]
(sort
(keys
((stock/get-new-stock-exchange
["A" "B"]
["Alice" "Bob" "Carol"]) :B)))))
(is (= ["Alice" "Bob" "Carol" "Dave"]
(sort
(keys
((stock/get-new-stock-exchange
["A" "B" "C"]
["Alice" "Bob" "Carol" "Dave"]) :C))))))
(deftest test-get-stock-exchange
(is (= [:A :B :C]
(sort
(keys
(stock/get-stock-exchange util/fake-game-data))))))
(deftest test-get-company-holdings
(is (= ["Alice" "Bob" "Carol"]
(sort
(keys
(stock/get-company-holdings "A" util/fake-game-data)))))
(is (= ["Carol"]
(sort
(keys
(stock/get-company-holdings "B" util/fake-game-data)))))
(is (= ["Bob" "Carol"]
(sort
(keys
(stock/get-company-holdings "C" util/fake-game-data))))))
(deftest test-get-company-shares
(is (= 1600 (stock/get-company-shares "A" util/fake-game-data)))
(is (= 1000 (stock/get-company-shares "B" util/fake-game-data)))
(is (= 600 (stock/get-company-shares "C" util/fake-game-data)))
)
(deftest test-get-player-shares
(is (= 1000 (stock/get-player-shares "A" "Alice" util/fake-game-data)))
(is (= 500 (stock/get-player-shares "A" "Bob" util/fake-game-data)))
(is (= 100 (stock/get-player-shares "A" "Carol" util/fake-game-data)))
(is (= 0 (stock/get-player-shares "B" "Alice" util/fake-game-data)))
(is (= 1000 (stock/get-player-shares "B" "Carol" util/fake-game-data)))
(is (= 500 (stock/get-player-shares "C" "Bob" util/fake-game-data)))
(is (= 100 (stock/get-player-shares "C" "Carol" util/fake-game-data)))
(is (= 0 (stock/get-player-shares "Z" "Bob" util/fake-game-data)))
(is (= 5 (count (stock/get-player-shares "Carol" util/fake-game-data)))))
(deftest test-get-player-shares-with-company
(is (= [:A 100]
(stock/get-player-shares-with-company
"A" "Carol" util/fake-game-data)))
(is (= [:B 1000]
(stock/get-player-shares-with-company
"B" "Carol" util/fake-game-data)))
(is (= [:C 100]
(stock/get-player-shares-with-company
"C" "Carol" util/fake-game-data))))
(deftest test-get-player-shares-with-companies
(is (= [[:A 100] [:B 1000] [:C 100]]
(stock/get-player-shares-with-companies
"Carol" util/fake-game-data)))
(is (= [[:A 100] [:B 1000] [:C 100]]
(stock/get-player-shares-with-companies
["A" "B" "C"] "Carol" util/fake-game-data))))
(deftest test-get-players-shares-with-player
(is (= ["Carol" {:A 100, :B 1000, :C 100}]
(stock/get-players-shares-with-player
["A" "B" "C"] "Carol" util/fake-game-data))))
(deftest test-get-players-shares
(is (= {"Alice" {:A 1000, :B 0, :C 0, :D 0, :E 0},
"Bob" {:A 500, :B 0, :C 500, :D 0, :E 0},
"Carol" {:A 100, :B 1000, :C 100, :D 0, :E 0}}
(stock/get-players-shares util/fake-game-data)))
(is (= {"Alice" {:A 1000, :B 0, :C 0},
"Bob" {:A 500, :B 0, :C 500},
"Carol" {:A 100, :B 1000, :C 100}}
(stock/get-players-shares ["A" "B" "C"] util/fake-game-data))))
(deftest test-add-player-shares
(is (= 100 (stock/get-player-shares "A" "Carol" util/fake-game-data)))
(let [game-data (stock/add-player-shares
"A" "Carol" 1000 util/fake-game-data)]
(is (= 1100 (stock/get-player-shares "A" "Carol" game-data))))
(is (= 0 (stock/get-player-shares "B" "Alice" util/fake-game-data)))
(let [game-data (stock/add-player-shares
"B" "Alice" 500 util/fake-game-data)]
(is (= 500 (stock/get-player-shares "B" "Alice" game-data)))))
(deftest test-compute-value
(let [assets [1000 [{:stock 12 :value 23.50} {:stock 100 :value 50}]]]
(is (= 6282.0 (stock/compute-value assets)))
(is (= 6282.0 (stock/compute-value (first assets) (second assets))))))
| 95419 | (ns starlanes.finance.stock-test
(:require [clojure.test :refer :all]
[starlanes.finance.stock :as stock]
[starlanes.util :as util]))
(deftest test-get-new-exchange
(is (= [:A]
(sort
(keys
(stock/get-new-stock-exchange ["A"])))))
(is (= [:A :B]
(sort
(keys
(stock/get-new-stock-exchange ["A" "B"])))))
(is (= [:A :B :C]
(sort
(keys
(stock/get-new-stock-exchange ["A" "B" "C"])))))
(is (= ["<NAME>" "<NAME>"]
(sort
(keys
((stock/get-new-stock-exchange ["A"] ["<NAME>" "<NAME>"]) :A)))))
(is (= ["<NAME>" "<NAME>" "<NAME>"]
(sort
(keys
((stock/get-new-stock-exchange
["A" "B"]
["<NAME>" "<NAME>" "<NAME>"]) :B)))))
(is (= ["<NAME>" "<NAME>" "<NAME>" "<NAME>"]
(sort
(keys
((stock/get-new-stock-exchange
["A" "B" "C"]
["<NAME>" "<NAME>" "<NAME>" "<NAME>"]) :C))))))
(deftest test-get-stock-exchange
(is (= [:A :B :C]
(sort
(keys
(stock/get-stock-exchange util/fake-game-data))))))
(deftest test-get-company-holdings
(is (= ["<NAME>" "<NAME>" "<NAME>"]
(sort
(keys
(stock/get-company-holdings "A" util/fake-game-data)))))
(is (= ["<NAME>"]
(sort
(keys
(stock/get-company-holdings "B" util/fake-game-data)))))
(is (= ["<NAME>" "<NAME>"]
(sort
(keys
(stock/get-company-holdings "C" util/fake-game-data))))))
(deftest test-get-company-shares
(is (= 1600 (stock/get-company-shares "A" util/fake-game-data)))
(is (= 1000 (stock/get-company-shares "B" util/fake-game-data)))
(is (= 600 (stock/get-company-shares "C" util/fake-game-data)))
)
(deftest test-get-player-shares
(is (= 1000 (stock/get-player-shares "A" "<NAME>" util/fake-game-data)))
(is (= 500 (stock/get-player-shares "A" "<NAME>" util/fake-game-data)))
(is (= 100 (stock/get-player-shares "A" "<NAME>" util/fake-game-data)))
(is (= 0 (stock/get-player-shares "B" "<NAME>" util/fake-game-data)))
(is (= 1000 (stock/get-player-shares "B" "<NAME>" util/fake-game-data)))
(is (= 500 (stock/get-player-shares "C" "<NAME>" util/fake-game-data)))
(is (= 100 (stock/get-player-shares "C" "<NAME>" util/fake-game-data)))
(is (= 0 (stock/get-player-shares "Z" "<NAME>" util/fake-game-data)))
(is (= 5 (count (stock/get-player-shares "Car<NAME>" util/fake-game-data)))))
(deftest test-get-player-shares-with-company
(is (= [:A 100]
(stock/get-player-shares-with-company
"A" "<NAME>" util/fake-game-data)))
(is (= [:B 1000]
(stock/get-player-shares-with-company
"B" "<NAME>" util/fake-game-data)))
(is (= [:C 100]
(stock/get-player-shares-with-company
"C" "<NAME>" util/fake-game-data))))
(deftest test-get-player-shares-with-companies
(is (= [[:A 100] [:B 1000] [:C 100]]
(stock/get-player-shares-with-companies
"<NAME>" util/fake-game-data)))
(is (= [[:A 100] [:B 1000] [:C 100]]
(stock/get-player-shares-with-companies
["A" "B" "C"] "<NAME>" util/fake-game-data))))
(deftest test-get-players-shares-with-player
(is (= ["<NAME>" {:A 100, :B 1000, :C 100}]
(stock/get-players-shares-with-player
["A" "B" "C"] "<NAME>" util/fake-game-data))))
(deftest test-get-players-shares
(is (= {"<NAME>" {:A 1000, :B 0, :C 0, :D 0, :E 0},
"<NAME>" {:A 500, :B 0, :C 500, :D 0, :E 0},
"<NAME>" {:A 100, :B 1000, :C 100, :D 0, :E 0}}
(stock/get-players-shares util/fake-game-data)))
(is (= {"<NAME>" {:A 1000, :B 0, :C 0},
"<NAME>" {:A 500, :B 0, :C 500},
"<NAME>" {:A 100, :B 1000, :C 100}}
(stock/get-players-shares ["A" "B" "C"] util/fake-game-data))))
(deftest test-add-player-shares
(is (= 100 (stock/get-player-shares "A" "<NAME>" util/fake-game-data)))
(let [game-data (stock/add-player-shares
"A" "<NAME>" 1000 util/fake-game-data)]
(is (= 1100 (stock/get-player-shares "A" "<NAME>" game-data))))
(is (= 0 (stock/get-player-shares "B" "<NAME>" util/fake-game-data)))
(let [game-data (stock/add-player-shares
"B" "<NAME>" 500 util/fake-game-data)]
(is (= 500 (stock/get-player-shares "B" "<NAME>" game-data)))))
(deftest test-compute-value
(let [assets [1000 [{:stock 12 :value 23.50} {:stock 100 :value 50}]]]
(is (= 6282.0 (stock/compute-value assets)))
(is (= 6282.0 (stock/compute-value (first assets) (second assets))))))
| true | (ns starlanes.finance.stock-test
(:require [clojure.test :refer :all]
[starlanes.finance.stock :as stock]
[starlanes.util :as util]))
(deftest test-get-new-exchange
(is (= [:A]
(sort
(keys
(stock/get-new-stock-exchange ["A"])))))
(is (= [:A :B]
(sort
(keys
(stock/get-new-stock-exchange ["A" "B"])))))
(is (= [:A :B :C]
(sort
(keys
(stock/get-new-stock-exchange ["A" "B" "C"])))))
(is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
(sort
(keys
((stock/get-new-stock-exchange ["A"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) :A)))))
(is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
(sort
(keys
((stock/get-new-stock-exchange
["A" "B"]
["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) :B)))))
(is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
(sort
(keys
((stock/get-new-stock-exchange
["A" "B" "C"]
["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) :C))))))
(deftest test-get-stock-exchange
(is (= [:A :B :C]
(sort
(keys
(stock/get-stock-exchange util/fake-game-data))))))
(deftest test-get-company-holdings
(is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
(sort
(keys
(stock/get-company-holdings "A" util/fake-game-data)))))
(is (= ["PI:NAME:<NAME>END_PI"]
(sort
(keys
(stock/get-company-holdings "B" util/fake-game-data)))))
(is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
(sort
(keys
(stock/get-company-holdings "C" util/fake-game-data))))))
(deftest test-get-company-shares
(is (= 1600 (stock/get-company-shares "A" util/fake-game-data)))
(is (= 1000 (stock/get-company-shares "B" util/fake-game-data)))
(is (= 600 (stock/get-company-shares "C" util/fake-game-data)))
)
(deftest test-get-player-shares
(is (= 1000 (stock/get-player-shares "A" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= 500 (stock/get-player-shares "A" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= 100 (stock/get-player-shares "A" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= 0 (stock/get-player-shares "B" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= 1000 (stock/get-player-shares "B" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= 500 (stock/get-player-shares "C" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= 100 (stock/get-player-shares "C" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= 0 (stock/get-player-shares "Z" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= 5 (count (stock/get-player-shares "CarPI:NAME:<NAME>END_PI" util/fake-game-data)))))
(deftest test-get-player-shares-with-company
(is (= [:A 100]
(stock/get-player-shares-with-company
"A" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= [:B 1000]
(stock/get-player-shares-with-company
"B" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= [:C 100]
(stock/get-player-shares-with-company
"C" "PI:NAME:<NAME>END_PI" util/fake-game-data))))
(deftest test-get-player-shares-with-companies
(is (= [[:A 100] [:B 1000] [:C 100]]
(stock/get-player-shares-with-companies
"PI:NAME:<NAME>END_PI" util/fake-game-data)))
(is (= [[:A 100] [:B 1000] [:C 100]]
(stock/get-player-shares-with-companies
["A" "B" "C"] "PI:NAME:<NAME>END_PI" util/fake-game-data))))
(deftest test-get-players-shares-with-player
(is (= ["PI:NAME:<NAME>END_PI" {:A 100, :B 1000, :C 100}]
(stock/get-players-shares-with-player
["A" "B" "C"] "PI:NAME:<NAME>END_PI" util/fake-game-data))))
(deftest test-get-players-shares
(is (= {"PI:NAME:<NAME>END_PI" {:A 1000, :B 0, :C 0, :D 0, :E 0},
"PI:NAME:<NAME>END_PI" {:A 500, :B 0, :C 500, :D 0, :E 0},
"PI:NAME:<NAME>END_PI" {:A 100, :B 1000, :C 100, :D 0, :E 0}}
(stock/get-players-shares util/fake-game-data)))
(is (= {"PI:NAME:<NAME>END_PI" {:A 1000, :B 0, :C 0},
"PI:NAME:<NAME>END_PI" {:A 500, :B 0, :C 500},
"PI:NAME:<NAME>END_PI" {:A 100, :B 1000, :C 100}}
(stock/get-players-shares ["A" "B" "C"] util/fake-game-data))))
(deftest test-add-player-shares
(is (= 100 (stock/get-player-shares "A" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(let [game-data (stock/add-player-shares
"A" "PI:NAME:<NAME>END_PI" 1000 util/fake-game-data)]
(is (= 1100 (stock/get-player-shares "A" "PI:NAME:<NAME>END_PI" game-data))))
(is (= 0 (stock/get-player-shares "B" "PI:NAME:<NAME>END_PI" util/fake-game-data)))
(let [game-data (stock/add-player-shares
"B" "PI:NAME:<NAME>END_PI" 500 util/fake-game-data)]
(is (= 500 (stock/get-player-shares "B" "PI:NAME:<NAME>END_PI" game-data)))))
(deftest test-compute-value
(let [assets [1000 [{:stock 12 :value 23.50} {:stock 100 :value 50}]]]
(is (= 6282.0 (stock/compute-value assets)))
(is (= 6282.0 (stock/compute-value (first assets) (second assets))))))
|
[
{
"context": " [:> ui/Field\n [:> ui/Label \"Full Name\"]\n [:> ui/Control\n ",
"end": 1574,
"score": 0.9431635141372681,
"start": 1565,
"tag": "NAME",
"value": "Full Name"
},
{
"context": " :placeholder \"Joe Covfefe\"\n :onChange ",
"end": 1784,
"score": 0.9998765587806702,
"start": 1773,
"tag": "NAME",
"value": "Joe Covfefe"
},
{
"context": " :placeholder \"you@example.com\"\n :onChange ",
"end": 2219,
"score": 0.9999066591262817,
"start": 2204,
"tag": "EMAIL",
"value": "you@example.com"
},
{
"context": "ontAwesomeIcon {:icon \"copyright\"}]]\n \"2019 Bobby Calderwood\"]]]]))\n",
"end": 12489,
"score": 0.9998880624771118,
"start": 12473,
"tag": "NAME",
"value": "Bobby Calderwood"
}
] | storefront/src/redis_streams_clj/storefront/ui/views.cljs | bobby/redisconf19-demo | 26 | (ns redis-streams-clj.storefront.ui.views
(:require [goog.string :as gstring]
[goog.string.format]
[reagent.core :as reagent]
[re-frame.core :as re-frame]
[redis-streams-clj.storefront.ui.routes :as routes]
[redis-streams-clj.storefront.ui.subs :as subs]
[rbx :as ui]
["@fortawesome/fontawesome-svg-core" :as fontawesome]
["@fortawesome/free-solid-svg-icons" :as icons]
["@fortawesome/react-fontawesome" :refer [FontAwesomeIcon]]
["react-markdown" :as ReactMarkdown]))
;;;; Font Awesome Initialization
;; TODO: can probably be optimized by specifying the icons we actually
;; use
(fontawesome/library.add icons/fas)
;;;; Helpers
(defn input-value-from-event
[^js/Event event]
(some-> event .-target .-value))
(defn format-currency
[cents]
(gstring/format "$%.2f" (/ cents 100)))
;;;; Views
(defn page-view [{:keys [header content]}]
[:> ui/Container
[:> ui/Title header]
[:main content]])
(defn home []
(let [state (reagent/atom {})]
(fn []
[page-view
{:header "Welcome to our Coffee Shop."
:content [:> ui/Column.Group
[:> ui/Column {:size 6}
[:> ui/Title {:size 4} "Please sign in!"]
[:form {:onSubmit (fn [e]
(.preventDefault e)
(re-frame/dispatch [:command/upsert-customer! @state]))}
[:> ui/Field
[:> ui/Label "Full Name"]
[:> ui/Control
[:> ui/Input {:type "text"
:required true
:placeholder "Joe Covfefe"
:onChange #(swap! state assoc :name (input-value-from-event %))}]]]
[:> ui/Field
[:> ui/Label "Email"]
[:> ui/Field
[:> ui/Control
[:> ui/Input {:type "email"
:required true
:placeholder "you@example.com"
:onChange #(swap! state assoc :email (input-value-from-event %))}]]]]
[:> ui/Field {:kind "group"}
[:> ui/Control
[:> ui/Button {:color "primary"
:type "Submit"}
"Submit"]]
[:> ui/Control
[:> ui/Button {:inverted true
:onClick #(js/history.back)}
"Cancel"]]]]]]}])))
(defn menu-item
[{:keys [id title description price photo_url] :as item}]
[(let [state (reagent/atom {:menu_item_id id
:quantity 1})]
(fn []
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container
[:> ui/Image {:style {:width "auto"
:height "auto"
:max-height 150
:max-width 200}
:alt (str "image of " title)
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Content
[:> ui/Title {:size "4"} title]
[:> ui/Title {:subtitle true :size "5"} (format-currency price)]
[:> ReactMarkdown {:source description}]]]
[:> ui/Media.Item {:align "right"}
[:> ui/Field
[:> ui/Control
[:> ui/Textarea {:placeholder "How would you like it: milk, sugar, cream?"
:onChange #(swap! state assoc :customization (input-value-from-event %))}]]]
[:> ui/Field {:kind "group"}
[:> ui/Control {:expanded true}
[:> ui/Input {:type "number"
:required true
:defaultValue (:quantity @state)
:min 1
:max 100
:onChange #(swap! state assoc :quantity (js/parseInt (input-value-from-event %)))}]]
[:> ui/Control
[:> ui/Button {:color "info"
:onClick #(re-frame/dispatch [:command/add-items-to-basket! [@state]])}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "plus"}]]
"Add to Basket"]]]]]))])
(defn menu []
(let [menu @(re-frame/subscribe [::subs/menu])]
[page-view
{:header "Menu"
:content [:> ui/Column.Group
(into [:> ui/Column {:size 8}]
(map menu-item (vals menu)))]}]))
(defn basket-item-row
[{:keys [id menu_item quantity customization] :as order-item}]
(let [{:keys [title price photo_url]} menu_item]
[:> ui/Table.Row
[:> ui/Table.Cell
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container {:style {:max-width 100}}
[:> ui/Image {:alt title
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Title {:size 5} title]
[:p customization]]]]
[:> ui/Table.Cell (format-currency price)]
[:> ui/Table.Cell quantity]
[:> ui/Table.Cell (format-currency (* quantity price))]
[:> ui/Table.Cell
[:> ui/Button {:onClick #(re-frame/dispatch [:command/remove-items-from-basket! [id]])}
[:> ui/Icon
[:> FontAwesomeIcon {:icon "trash"}]]]]]))
(defn basket-table
[basket]
[:> ui/Table {:fullwidth true
:bordered true}
[:> ui/Table.Head
[:> ui/Table.Row
[:> ui/Table.Heading "Item"]
[:> ui/Table.Heading "Price"]
[:> ui/Table.Heading "Quantity"]
[:> ui/Table.Heading "Item Total"]
[:> ui/Table.Heading "Remove"]]]
[:> ui/Table.Foot
[:> ui/Table.Row
[:> ui/Table.Cell {:colSpan 3}]
[:> ui/Table.Heading (-> basket :total format-currency)]]]
(into [:> ui/Table.Body] (map basket-item-row (:items basket)))])
(defn basket
[]
(let [basket @(re-frame/subscribe [::subs/basket])]
[page-view
{:header "My Basket"
:content (if (-> basket :items seq)
[:> ui/Column.Group
[:> ui/Column {:size 8}
[basket-table basket]
[:> ui/Field
[:> ui/Control
[:> ui/Button {:color "primary"
:onClick #(re-frame/dispatch [:command/place-order!])}
"Place Order"]]]]]
[:> ui/Content
[:p
"Your shopping basket is empty. Please visit "
[:a {:href (routes/menu)} "our menu"]
" to add items to your basket."]])}]))
(defn order-item-row
[{:keys [menu_item quantity customization status] :as order-item}]
(let [{:keys [title price photo_url]} menu_item]
[:> ui/Table.Row
[:> ui/Table.Cell
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container {:style {:max-width 100}}
[:> ui/Image {:alt title
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Title {:size 5} title]
[:p customization]]]]
[:> ui/Table.Cell (format-currency price)]
[:> ui/Table.Cell quantity]
[:> ui/Table.Cell (format-currency (* quantity price))]
[:> ui/Table.Cell status]]))
(defn order-table
[order]
[:> ui/Table {:fullwidth true
:bordered true}
[:> ui/Table.Head
[:> ui/Table.Row
[:> ui/Table.Heading "Item"]
[:> ui/Table.Heading "Price"]
[:> ui/Table.Heading "Quantity"]
[:> ui/Table.Heading "Item Total"]
[:> ui/Table.Heading "Status"]]]
[:> ui/Table.Foot
[:> ui/Table.Row
[:> ui/Table.Cell {:colSpan 3}]
[:> ui/Table.Heading (-> order :total format-currency)]
[:> ui/Table.Heading (:status order)]]]
(into [:> ui/Table.Body] (map order-item-row (:items order)))])
(defn orders []
(let [orders @(re-frame/subscribe [::subs/orders])]
[page-view
{:header "My Orders"
:content [:> ui/Column.Group
(into [:> ui/Column {:size 8}]
(if (seq orders)
(for [{:keys [id items status] :as order} orders]
[:> ui/Card {:style {:margin-bottom "3em"}}
[:> ui/Card.Header
[:> ui/Card.Header.Title id]
[:> ui/Card.Header.Icon
[:> ui/Icon
[:> FontAwesomeIcon {:icon (case status
"placed" "user-clock"
"ready" "cash-register"
"paid" "check-circle"
"question")}]]]]
[:> ui/Card.Content
[order-table order]]
(into [:> ui/Card.Footer]
(case status
"placed" [[:> ui/Card.Footer.Item {:onClick #(js/alert "cancel!")}
"Cancel Order"]]
"ready" [[:> ui/Card.Footer.Item {:onClick #(js/alert "pay for!")}
"Pay for Order"]]
"paid" [[:> ui/Card.Footer.Item {:onClick #(js/alert "return items!")}
"Return Items"]]
[]))])
[[:> ui/Content
[:p
"You haven't placed any orders yet. Please visit "
[:a {:href (routes/basket)} "your basket"]
" to place an order."]]]))]}]))
(defn not-found []
[page-view
{:header "Not Found"
:content [:p "Whoops, we couldn't find the page you were looking for!"]}])
(defn navbar
[page]
(let [navbar @(re-frame/subscribe [::subs/navbar])]
[:> ui/Container
[:> ui/Navbar {:transparent true}
[:> ui/Navbar.Brand
[:> ui/Navbar.Item
{:href (routes/home)}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "coffee"}]]
"A Streaming Cup 'o Joe"]
[:> ui/Navbar.Burger]]
[:> ui/Navbar.Menu
[:> ui/Navbar.Segment {:align "start"}
[:> ui/Navbar.Item
{:href (routes/menu)
:active (= page :menu)
:managed true}
"Menu"]]
[:> ui/Navbar.Segment {:align "end"}
[:> ui/Navbar.Item
{:href (routes/basket)
:active (= page :basket)
:managed true}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "shopping-basket"}]]
"My Basket"
[:> ui/Tag {:color "success"
:style {:marginLeft "5px"}}
(:basket-count navbar)]]
[:> ui/Navbar.Item
{:href (routes/orders)
:active (= page :orders)
:managed true}
"My Orders"]]]]]))
(defn notifications
[]
(let [notifications @(re-frame/subscribe [::subs/notifications])]
[:> ui/Section
[:> ui/Container
[:> ui/Column.Group
(into [:> ui/Column {:size 4 :offset 8}]
(for [[id {:keys [color message] :as n}] notifications]
[:> ui/Notification {:color color}
[:> ui/Delete {:as "button"
:onClick #(re-frame/dispatch [:command/dismiss-notification id])}]
message]))]]]))
(defn app-root []
(let [{:keys [page]} @(re-frame/subscribe [::subs/app-view])]
[:div
[navbar page]
[notifications]
[:> ui/Section
(case page
:home
[home]
:menu
[menu]
:basket
[basket]
:orders
[orders]
[not-found])]
[:> ui/Footer {:id "footer"}
[:> ui/Container
[:> ui/Content {:size "small"}
[:> ui/Icon
[:> FontAwesomeIcon {:icon "copyright"}]]
"2019 Bobby Calderwood"]]]]))
| 7881 | (ns redis-streams-clj.storefront.ui.views
(:require [goog.string :as gstring]
[goog.string.format]
[reagent.core :as reagent]
[re-frame.core :as re-frame]
[redis-streams-clj.storefront.ui.routes :as routes]
[redis-streams-clj.storefront.ui.subs :as subs]
[rbx :as ui]
["@fortawesome/fontawesome-svg-core" :as fontawesome]
["@fortawesome/free-solid-svg-icons" :as icons]
["@fortawesome/react-fontawesome" :refer [FontAwesomeIcon]]
["react-markdown" :as ReactMarkdown]))
;;;; Font Awesome Initialization
;; TODO: can probably be optimized by specifying the icons we actually
;; use
(fontawesome/library.add icons/fas)
;;;; Helpers
(defn input-value-from-event
[^js/Event event]
(some-> event .-target .-value))
(defn format-currency
[cents]
(gstring/format "$%.2f" (/ cents 100)))
;;;; Views
(defn page-view [{:keys [header content]}]
[:> ui/Container
[:> ui/Title header]
[:main content]])
(defn home []
(let [state (reagent/atom {})]
(fn []
[page-view
{:header "Welcome to our Coffee Shop."
:content [:> ui/Column.Group
[:> ui/Column {:size 6}
[:> ui/Title {:size 4} "Please sign in!"]
[:form {:onSubmit (fn [e]
(.preventDefault e)
(re-frame/dispatch [:command/upsert-customer! @state]))}
[:> ui/Field
[:> ui/Label "<NAME>"]
[:> ui/Control
[:> ui/Input {:type "text"
:required true
:placeholder "<NAME>"
:onChange #(swap! state assoc :name (input-value-from-event %))}]]]
[:> ui/Field
[:> ui/Label "Email"]
[:> ui/Field
[:> ui/Control
[:> ui/Input {:type "email"
:required true
:placeholder "<EMAIL>"
:onChange #(swap! state assoc :email (input-value-from-event %))}]]]]
[:> ui/Field {:kind "group"}
[:> ui/Control
[:> ui/Button {:color "primary"
:type "Submit"}
"Submit"]]
[:> ui/Control
[:> ui/Button {:inverted true
:onClick #(js/history.back)}
"Cancel"]]]]]]}])))
(defn menu-item
[{:keys [id title description price photo_url] :as item}]
[(let [state (reagent/atom {:menu_item_id id
:quantity 1})]
(fn []
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container
[:> ui/Image {:style {:width "auto"
:height "auto"
:max-height 150
:max-width 200}
:alt (str "image of " title)
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Content
[:> ui/Title {:size "4"} title]
[:> ui/Title {:subtitle true :size "5"} (format-currency price)]
[:> ReactMarkdown {:source description}]]]
[:> ui/Media.Item {:align "right"}
[:> ui/Field
[:> ui/Control
[:> ui/Textarea {:placeholder "How would you like it: milk, sugar, cream?"
:onChange #(swap! state assoc :customization (input-value-from-event %))}]]]
[:> ui/Field {:kind "group"}
[:> ui/Control {:expanded true}
[:> ui/Input {:type "number"
:required true
:defaultValue (:quantity @state)
:min 1
:max 100
:onChange #(swap! state assoc :quantity (js/parseInt (input-value-from-event %)))}]]
[:> ui/Control
[:> ui/Button {:color "info"
:onClick #(re-frame/dispatch [:command/add-items-to-basket! [@state]])}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "plus"}]]
"Add to Basket"]]]]]))])
(defn menu []
(let [menu @(re-frame/subscribe [::subs/menu])]
[page-view
{:header "Menu"
:content [:> ui/Column.Group
(into [:> ui/Column {:size 8}]
(map menu-item (vals menu)))]}]))
(defn basket-item-row
[{:keys [id menu_item quantity customization] :as order-item}]
(let [{:keys [title price photo_url]} menu_item]
[:> ui/Table.Row
[:> ui/Table.Cell
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container {:style {:max-width 100}}
[:> ui/Image {:alt title
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Title {:size 5} title]
[:p customization]]]]
[:> ui/Table.Cell (format-currency price)]
[:> ui/Table.Cell quantity]
[:> ui/Table.Cell (format-currency (* quantity price))]
[:> ui/Table.Cell
[:> ui/Button {:onClick #(re-frame/dispatch [:command/remove-items-from-basket! [id]])}
[:> ui/Icon
[:> FontAwesomeIcon {:icon "trash"}]]]]]))
(defn basket-table
[basket]
[:> ui/Table {:fullwidth true
:bordered true}
[:> ui/Table.Head
[:> ui/Table.Row
[:> ui/Table.Heading "Item"]
[:> ui/Table.Heading "Price"]
[:> ui/Table.Heading "Quantity"]
[:> ui/Table.Heading "Item Total"]
[:> ui/Table.Heading "Remove"]]]
[:> ui/Table.Foot
[:> ui/Table.Row
[:> ui/Table.Cell {:colSpan 3}]
[:> ui/Table.Heading (-> basket :total format-currency)]]]
(into [:> ui/Table.Body] (map basket-item-row (:items basket)))])
(defn basket
[]
(let [basket @(re-frame/subscribe [::subs/basket])]
[page-view
{:header "My Basket"
:content (if (-> basket :items seq)
[:> ui/Column.Group
[:> ui/Column {:size 8}
[basket-table basket]
[:> ui/Field
[:> ui/Control
[:> ui/Button {:color "primary"
:onClick #(re-frame/dispatch [:command/place-order!])}
"Place Order"]]]]]
[:> ui/Content
[:p
"Your shopping basket is empty. Please visit "
[:a {:href (routes/menu)} "our menu"]
" to add items to your basket."]])}]))
(defn order-item-row
[{:keys [menu_item quantity customization status] :as order-item}]
(let [{:keys [title price photo_url]} menu_item]
[:> ui/Table.Row
[:> ui/Table.Cell
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container {:style {:max-width 100}}
[:> ui/Image {:alt title
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Title {:size 5} title]
[:p customization]]]]
[:> ui/Table.Cell (format-currency price)]
[:> ui/Table.Cell quantity]
[:> ui/Table.Cell (format-currency (* quantity price))]
[:> ui/Table.Cell status]]))
(defn order-table
[order]
[:> ui/Table {:fullwidth true
:bordered true}
[:> ui/Table.Head
[:> ui/Table.Row
[:> ui/Table.Heading "Item"]
[:> ui/Table.Heading "Price"]
[:> ui/Table.Heading "Quantity"]
[:> ui/Table.Heading "Item Total"]
[:> ui/Table.Heading "Status"]]]
[:> ui/Table.Foot
[:> ui/Table.Row
[:> ui/Table.Cell {:colSpan 3}]
[:> ui/Table.Heading (-> order :total format-currency)]
[:> ui/Table.Heading (:status order)]]]
(into [:> ui/Table.Body] (map order-item-row (:items order)))])
(defn orders []
(let [orders @(re-frame/subscribe [::subs/orders])]
[page-view
{:header "My Orders"
:content [:> ui/Column.Group
(into [:> ui/Column {:size 8}]
(if (seq orders)
(for [{:keys [id items status] :as order} orders]
[:> ui/Card {:style {:margin-bottom "3em"}}
[:> ui/Card.Header
[:> ui/Card.Header.Title id]
[:> ui/Card.Header.Icon
[:> ui/Icon
[:> FontAwesomeIcon {:icon (case status
"placed" "user-clock"
"ready" "cash-register"
"paid" "check-circle"
"question")}]]]]
[:> ui/Card.Content
[order-table order]]
(into [:> ui/Card.Footer]
(case status
"placed" [[:> ui/Card.Footer.Item {:onClick #(js/alert "cancel!")}
"Cancel Order"]]
"ready" [[:> ui/Card.Footer.Item {:onClick #(js/alert "pay for!")}
"Pay for Order"]]
"paid" [[:> ui/Card.Footer.Item {:onClick #(js/alert "return items!")}
"Return Items"]]
[]))])
[[:> ui/Content
[:p
"You haven't placed any orders yet. Please visit "
[:a {:href (routes/basket)} "your basket"]
" to place an order."]]]))]}]))
(defn not-found []
[page-view
{:header "Not Found"
:content [:p "Whoops, we couldn't find the page you were looking for!"]}])
(defn navbar
[page]
(let [navbar @(re-frame/subscribe [::subs/navbar])]
[:> ui/Container
[:> ui/Navbar {:transparent true}
[:> ui/Navbar.Brand
[:> ui/Navbar.Item
{:href (routes/home)}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "coffee"}]]
"A Streaming Cup 'o Joe"]
[:> ui/Navbar.Burger]]
[:> ui/Navbar.Menu
[:> ui/Navbar.Segment {:align "start"}
[:> ui/Navbar.Item
{:href (routes/menu)
:active (= page :menu)
:managed true}
"Menu"]]
[:> ui/Navbar.Segment {:align "end"}
[:> ui/Navbar.Item
{:href (routes/basket)
:active (= page :basket)
:managed true}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "shopping-basket"}]]
"My Basket"
[:> ui/Tag {:color "success"
:style {:marginLeft "5px"}}
(:basket-count navbar)]]
[:> ui/Navbar.Item
{:href (routes/orders)
:active (= page :orders)
:managed true}
"My Orders"]]]]]))
(defn notifications
[]
(let [notifications @(re-frame/subscribe [::subs/notifications])]
[:> ui/Section
[:> ui/Container
[:> ui/Column.Group
(into [:> ui/Column {:size 4 :offset 8}]
(for [[id {:keys [color message] :as n}] notifications]
[:> ui/Notification {:color color}
[:> ui/Delete {:as "button"
:onClick #(re-frame/dispatch [:command/dismiss-notification id])}]
message]))]]]))
(defn app-root []
(let [{:keys [page]} @(re-frame/subscribe [::subs/app-view])]
[:div
[navbar page]
[notifications]
[:> ui/Section
(case page
:home
[home]
:menu
[menu]
:basket
[basket]
:orders
[orders]
[not-found])]
[:> ui/Footer {:id "footer"}
[:> ui/Container
[:> ui/Content {:size "small"}
[:> ui/Icon
[:> FontAwesomeIcon {:icon "copyright"}]]
"2019 <NAME>"]]]]))
| true | (ns redis-streams-clj.storefront.ui.views
(:require [goog.string :as gstring]
[goog.string.format]
[reagent.core :as reagent]
[re-frame.core :as re-frame]
[redis-streams-clj.storefront.ui.routes :as routes]
[redis-streams-clj.storefront.ui.subs :as subs]
[rbx :as ui]
["@fortawesome/fontawesome-svg-core" :as fontawesome]
["@fortawesome/free-solid-svg-icons" :as icons]
["@fortawesome/react-fontawesome" :refer [FontAwesomeIcon]]
["react-markdown" :as ReactMarkdown]))
;;;; Font Awesome Initialization
;; TODO: can probably be optimized by specifying the icons we actually
;; use
(fontawesome/library.add icons/fas)
;;;; Helpers
(defn input-value-from-event
[^js/Event event]
(some-> event .-target .-value))
(defn format-currency
[cents]
(gstring/format "$%.2f" (/ cents 100)))
;;;; Views
(defn page-view [{:keys [header content]}]
[:> ui/Container
[:> ui/Title header]
[:main content]])
(defn home []
(let [state (reagent/atom {})]
(fn []
[page-view
{:header "Welcome to our Coffee Shop."
:content [:> ui/Column.Group
[:> ui/Column {:size 6}
[:> ui/Title {:size 4} "Please sign in!"]
[:form {:onSubmit (fn [e]
(.preventDefault e)
(re-frame/dispatch [:command/upsert-customer! @state]))}
[:> ui/Field
[:> ui/Label "PI:NAME:<NAME>END_PI"]
[:> ui/Control
[:> ui/Input {:type "text"
:required true
:placeholder "PI:NAME:<NAME>END_PI"
:onChange #(swap! state assoc :name (input-value-from-event %))}]]]
[:> ui/Field
[:> ui/Label "Email"]
[:> ui/Field
[:> ui/Control
[:> ui/Input {:type "email"
:required true
:placeholder "PI:EMAIL:<EMAIL>END_PI"
:onChange #(swap! state assoc :email (input-value-from-event %))}]]]]
[:> ui/Field {:kind "group"}
[:> ui/Control
[:> ui/Button {:color "primary"
:type "Submit"}
"Submit"]]
[:> ui/Control
[:> ui/Button {:inverted true
:onClick #(js/history.back)}
"Cancel"]]]]]]}])))
(defn menu-item
[{:keys [id title description price photo_url] :as item}]
[(let [state (reagent/atom {:menu_item_id id
:quantity 1})]
(fn []
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container
[:> ui/Image {:style {:width "auto"
:height "auto"
:max-height 150
:max-width 200}
:alt (str "image of " title)
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Content
[:> ui/Title {:size "4"} title]
[:> ui/Title {:subtitle true :size "5"} (format-currency price)]
[:> ReactMarkdown {:source description}]]]
[:> ui/Media.Item {:align "right"}
[:> ui/Field
[:> ui/Control
[:> ui/Textarea {:placeholder "How would you like it: milk, sugar, cream?"
:onChange #(swap! state assoc :customization (input-value-from-event %))}]]]
[:> ui/Field {:kind "group"}
[:> ui/Control {:expanded true}
[:> ui/Input {:type "number"
:required true
:defaultValue (:quantity @state)
:min 1
:max 100
:onChange #(swap! state assoc :quantity (js/parseInt (input-value-from-event %)))}]]
[:> ui/Control
[:> ui/Button {:color "info"
:onClick #(re-frame/dispatch [:command/add-items-to-basket! [@state]])}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "plus"}]]
"Add to Basket"]]]]]))])
(defn menu []
(let [menu @(re-frame/subscribe [::subs/menu])]
[page-view
{:header "Menu"
:content [:> ui/Column.Group
(into [:> ui/Column {:size 8}]
(map menu-item (vals menu)))]}]))
(defn basket-item-row
[{:keys [id menu_item quantity customization] :as order-item}]
(let [{:keys [title price photo_url]} menu_item]
[:> ui/Table.Row
[:> ui/Table.Cell
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container {:style {:max-width 100}}
[:> ui/Image {:alt title
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Title {:size 5} title]
[:p customization]]]]
[:> ui/Table.Cell (format-currency price)]
[:> ui/Table.Cell quantity]
[:> ui/Table.Cell (format-currency (* quantity price))]
[:> ui/Table.Cell
[:> ui/Button {:onClick #(re-frame/dispatch [:command/remove-items-from-basket! [id]])}
[:> ui/Icon
[:> FontAwesomeIcon {:icon "trash"}]]]]]))
(defn basket-table
[basket]
[:> ui/Table {:fullwidth true
:bordered true}
[:> ui/Table.Head
[:> ui/Table.Row
[:> ui/Table.Heading "Item"]
[:> ui/Table.Heading "Price"]
[:> ui/Table.Heading "Quantity"]
[:> ui/Table.Heading "Item Total"]
[:> ui/Table.Heading "Remove"]]]
[:> ui/Table.Foot
[:> ui/Table.Row
[:> ui/Table.Cell {:colSpan 3}]
[:> ui/Table.Heading (-> basket :total format-currency)]]]
(into [:> ui/Table.Body] (map basket-item-row (:items basket)))])
(defn basket
[]
(let [basket @(re-frame/subscribe [::subs/basket])]
[page-view
{:header "My Basket"
:content (if (-> basket :items seq)
[:> ui/Column.Group
[:> ui/Column {:size 8}
[basket-table basket]
[:> ui/Field
[:> ui/Control
[:> ui/Button {:color "primary"
:onClick #(re-frame/dispatch [:command/place-order!])}
"Place Order"]]]]]
[:> ui/Content
[:p
"Your shopping basket is empty. Please visit "
[:a {:href (routes/menu)} "our menu"]
" to add items to your basket."]])}]))
(defn order-item-row
[{:keys [menu_item quantity customization status] :as order-item}]
(let [{:keys [title price photo_url]} menu_item]
[:> ui/Table.Row
[:> ui/Table.Cell
[:> ui/Media
[:> ui/Media.Item {:align "left"}
[:> ui/Image.Container {:style {:max-width 100}}
[:> ui/Image {:alt title
:src photo_url}]]]
[:> ui/Media.Item {:align "content"}
[:> ui/Title {:size 5} title]
[:p customization]]]]
[:> ui/Table.Cell (format-currency price)]
[:> ui/Table.Cell quantity]
[:> ui/Table.Cell (format-currency (* quantity price))]
[:> ui/Table.Cell status]]))
(defn order-table
[order]
[:> ui/Table {:fullwidth true
:bordered true}
[:> ui/Table.Head
[:> ui/Table.Row
[:> ui/Table.Heading "Item"]
[:> ui/Table.Heading "Price"]
[:> ui/Table.Heading "Quantity"]
[:> ui/Table.Heading "Item Total"]
[:> ui/Table.Heading "Status"]]]
[:> ui/Table.Foot
[:> ui/Table.Row
[:> ui/Table.Cell {:colSpan 3}]
[:> ui/Table.Heading (-> order :total format-currency)]
[:> ui/Table.Heading (:status order)]]]
(into [:> ui/Table.Body] (map order-item-row (:items order)))])
(defn orders []
(let [orders @(re-frame/subscribe [::subs/orders])]
[page-view
{:header "My Orders"
:content [:> ui/Column.Group
(into [:> ui/Column {:size 8}]
(if (seq orders)
(for [{:keys [id items status] :as order} orders]
[:> ui/Card {:style {:margin-bottom "3em"}}
[:> ui/Card.Header
[:> ui/Card.Header.Title id]
[:> ui/Card.Header.Icon
[:> ui/Icon
[:> FontAwesomeIcon {:icon (case status
"placed" "user-clock"
"ready" "cash-register"
"paid" "check-circle"
"question")}]]]]
[:> ui/Card.Content
[order-table order]]
(into [:> ui/Card.Footer]
(case status
"placed" [[:> ui/Card.Footer.Item {:onClick #(js/alert "cancel!")}
"Cancel Order"]]
"ready" [[:> ui/Card.Footer.Item {:onClick #(js/alert "pay for!")}
"Pay for Order"]]
"paid" [[:> ui/Card.Footer.Item {:onClick #(js/alert "return items!")}
"Return Items"]]
[]))])
[[:> ui/Content
[:p
"You haven't placed any orders yet. Please visit "
[:a {:href (routes/basket)} "your basket"]
" to place an order."]]]))]}]))
(defn not-found []
[page-view
{:header "Not Found"
:content [:p "Whoops, we couldn't find the page you were looking for!"]}])
(defn navbar
[page]
(let [navbar @(re-frame/subscribe [::subs/navbar])]
[:> ui/Container
[:> ui/Navbar {:transparent true}
[:> ui/Navbar.Brand
[:> ui/Navbar.Item
{:href (routes/home)}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "coffee"}]]
"A Streaming Cup 'o Joe"]
[:> ui/Navbar.Burger]]
[:> ui/Navbar.Menu
[:> ui/Navbar.Segment {:align "start"}
[:> ui/Navbar.Item
{:href (routes/menu)
:active (= page :menu)
:managed true}
"Menu"]]
[:> ui/Navbar.Segment {:align "end"}
[:> ui/Navbar.Item
{:href (routes/basket)
:active (= page :basket)
:managed true}
[:> ui/Icon {:style {:marginRight "5px"}}
[:> FontAwesomeIcon {:icon "shopping-basket"}]]
"My Basket"
[:> ui/Tag {:color "success"
:style {:marginLeft "5px"}}
(:basket-count navbar)]]
[:> ui/Navbar.Item
{:href (routes/orders)
:active (= page :orders)
:managed true}
"My Orders"]]]]]))
(defn notifications
[]
(let [notifications @(re-frame/subscribe [::subs/notifications])]
[:> ui/Section
[:> ui/Container
[:> ui/Column.Group
(into [:> ui/Column {:size 4 :offset 8}]
(for [[id {:keys [color message] :as n}] notifications]
[:> ui/Notification {:color color}
[:> ui/Delete {:as "button"
:onClick #(re-frame/dispatch [:command/dismiss-notification id])}]
message]))]]]))
(defn app-root []
(let [{:keys [page]} @(re-frame/subscribe [::subs/app-view])]
[:div
[navbar page]
[notifications]
[:> ui/Section
(case page
:home
[home]
:menu
[menu]
:basket
[basket]
:orders
[orders]
[not-found])]
[:> ui/Footer {:id "footer"}
[:> ui/Container
[:> ui/Content {:size "small"}
[:> ui/Icon
[:> FontAwesomeIcon {:icon "copyright"}]]
"2019 PI:NAME:<NAME>END_PI"]]]]))
|
[
{
"context": "\" :secondname \"jones\"}) \"firstname=bob&secondname=jones\"))))\n\n(deftest regional-proxy?-test\n (testing \"r",
"end": 1641,
"score": 0.9990347623825073,
"start": 1636,
"tag": "NAME",
"value": "jones"
}
] | test/blitzcrank/util_test.clj | elken/lol-api | 0 | (ns blitzcrank.util-test
(:require [clojure.test :refer :all]
[blitzcrank.util :refer :all]))
(def ^{:private true} complex-map {:first-parent {:first-child "first-value"
:second-child "second-value"
:third-child "third-value"}
:second-parent {:fourth-child "fourth-value"}})
(def ^{:private true} simple-map {:400 "Bad request"
:401 "Unauthorized"
:403 "Forbidden"})
(deftest indicies-test
(testing "indicies with nil? on (nil nil 1 nil)"
(is (= (indicies nil? '(nil nil 1 nil)) '(0 1 3))))
(testing "indicies with #(not (= nil %1)) on (nil 1 2 \"a\" nil)"
(is (= (indicies #(not (= nil %1)) '(nil 1 2 "a" nil)) '(1 2 3)))))
(deftest get-key-by-value-test
(testing "get-key-by-value with key 401 on {:400 \"Bad request\" :401 \"Unauthorized\" :402 \"Forbidden\"}"
(is (= (get-key-by-value 400 simple-map) "Bad request")))
(testing "get-key-by-value with a complex-map"
[(is (= (get-key-by-value "first-parent" complex-map) {:first-child "first-value", :second-child "second-value", :third-child "third-value"}))
(is (= (get-key-by-value "second-parent" complex-map) {:fourth-child "fourth-value"}))
(is (= (get-key-by-value "third-parent" complex-map) nil))]))
(deftest map-to-query-string-test
(testing "map-to-query-string with {:firstname \"bob\" :secondname \"jones\"}"
(is (= (map-to-query-string {:firstname "bob" :secondname "jones"}) "firstname=bob&secondname=jones"))))
(deftest regional-proxy?-test
(testing "regional-proxy? with all valid proxies and one invalid"
[(is (regional-proxy? "europe"))
(is (regional-proxy? "americas"))
(is (regional-proxy? "asia"))
(not (regional-proxy? "fail"))]))
(deftest region-codes-test
(testing "region-codes returns expected"
(is (= (region-codes) '("br1" "eun1" "euw1" "jp1" "kr" "la1" "la2" "na" "na1" "oc1" "pbe1" "ru" "tr1")))))
(deftest region-code?-test
(testing "region-code? on 3 valid region codes and one invalid"
[(is (region-code? "br1"))
(is (region-code? "kr"))
(is (region-code? "ru"))
(not (region-code? "fail"))]))
(deftest subregions-test
(testing "subregions for all valid proxies and an invalid proxy"
[(is (= (subregions "europe") {:eun1 "Europe Nordic & East", :euw1 "Europe West", :tr1 "Turkey", :ru "Russia"}))
(is (= (subregions "americas") {:br1 "Brazil",
:la1 "Latin America North",
:la2 "Latin America South",
:na "North America (older)",
:na1 "North America"}))
(is (= (subregions "asia") {:jp1 "Japan", :kr "Korea", :oc1 "Oceanic"}))
(not (= (subregions "europe") nil))]))
(deftest region-to-proxy-test
(testing "region-to-proxy for 3 valid regions and an invalid one"
[(is (= (region-to-proxy "kr") "asia"))
(is (= (region-to-proxy "la1") "americas"))
(is (= (region-to-proxy "tr1") "europe"))
(not (= (region-to-proxy "fail") nil))])) | 55112 | (ns blitzcrank.util-test
(:require [clojure.test :refer :all]
[blitzcrank.util :refer :all]))
(def ^{:private true} complex-map {:first-parent {:first-child "first-value"
:second-child "second-value"
:third-child "third-value"}
:second-parent {:fourth-child "fourth-value"}})
(def ^{:private true} simple-map {:400 "Bad request"
:401 "Unauthorized"
:403 "Forbidden"})
(deftest indicies-test
(testing "indicies with nil? on (nil nil 1 nil)"
(is (= (indicies nil? '(nil nil 1 nil)) '(0 1 3))))
(testing "indicies with #(not (= nil %1)) on (nil 1 2 \"a\" nil)"
(is (= (indicies #(not (= nil %1)) '(nil 1 2 "a" nil)) '(1 2 3)))))
(deftest get-key-by-value-test
(testing "get-key-by-value with key 401 on {:400 \"Bad request\" :401 \"Unauthorized\" :402 \"Forbidden\"}"
(is (= (get-key-by-value 400 simple-map) "Bad request")))
(testing "get-key-by-value with a complex-map"
[(is (= (get-key-by-value "first-parent" complex-map) {:first-child "first-value", :second-child "second-value", :third-child "third-value"}))
(is (= (get-key-by-value "second-parent" complex-map) {:fourth-child "fourth-value"}))
(is (= (get-key-by-value "third-parent" complex-map) nil))]))
(deftest map-to-query-string-test
(testing "map-to-query-string with {:firstname \"bob\" :secondname \"jones\"}"
(is (= (map-to-query-string {:firstname "bob" :secondname "jones"}) "firstname=bob&secondname=<NAME>"))))
(deftest regional-proxy?-test
(testing "regional-proxy? with all valid proxies and one invalid"
[(is (regional-proxy? "europe"))
(is (regional-proxy? "americas"))
(is (regional-proxy? "asia"))
(not (regional-proxy? "fail"))]))
(deftest region-codes-test
(testing "region-codes returns expected"
(is (= (region-codes) '("br1" "eun1" "euw1" "jp1" "kr" "la1" "la2" "na" "na1" "oc1" "pbe1" "ru" "tr1")))))
(deftest region-code?-test
(testing "region-code? on 3 valid region codes and one invalid"
[(is (region-code? "br1"))
(is (region-code? "kr"))
(is (region-code? "ru"))
(not (region-code? "fail"))]))
(deftest subregions-test
(testing "subregions for all valid proxies and an invalid proxy"
[(is (= (subregions "europe") {:eun1 "Europe Nordic & East", :euw1 "Europe West", :tr1 "Turkey", :ru "Russia"}))
(is (= (subregions "americas") {:br1 "Brazil",
:la1 "Latin America North",
:la2 "Latin America South",
:na "North America (older)",
:na1 "North America"}))
(is (= (subregions "asia") {:jp1 "Japan", :kr "Korea", :oc1 "Oceanic"}))
(not (= (subregions "europe") nil))]))
(deftest region-to-proxy-test
(testing "region-to-proxy for 3 valid regions and an invalid one"
[(is (= (region-to-proxy "kr") "asia"))
(is (= (region-to-proxy "la1") "americas"))
(is (= (region-to-proxy "tr1") "europe"))
(not (= (region-to-proxy "fail") nil))])) | true | (ns blitzcrank.util-test
(:require [clojure.test :refer :all]
[blitzcrank.util :refer :all]))
(def ^{:private true} complex-map {:first-parent {:first-child "first-value"
:second-child "second-value"
:third-child "third-value"}
:second-parent {:fourth-child "fourth-value"}})
(def ^{:private true} simple-map {:400 "Bad request"
:401 "Unauthorized"
:403 "Forbidden"})
(deftest indicies-test
(testing "indicies with nil? on (nil nil 1 nil)"
(is (= (indicies nil? '(nil nil 1 nil)) '(0 1 3))))
(testing "indicies with #(not (= nil %1)) on (nil 1 2 \"a\" nil)"
(is (= (indicies #(not (= nil %1)) '(nil 1 2 "a" nil)) '(1 2 3)))))
(deftest get-key-by-value-test
(testing "get-key-by-value with key 401 on {:400 \"Bad request\" :401 \"Unauthorized\" :402 \"Forbidden\"}"
(is (= (get-key-by-value 400 simple-map) "Bad request")))
(testing "get-key-by-value with a complex-map"
[(is (= (get-key-by-value "first-parent" complex-map) {:first-child "first-value", :second-child "second-value", :third-child "third-value"}))
(is (= (get-key-by-value "second-parent" complex-map) {:fourth-child "fourth-value"}))
(is (= (get-key-by-value "third-parent" complex-map) nil))]))
(deftest map-to-query-string-test
(testing "map-to-query-string with {:firstname \"bob\" :secondname \"jones\"}"
(is (= (map-to-query-string {:firstname "bob" :secondname "jones"}) "firstname=bob&secondname=PI:NAME:<NAME>END_PI"))))
(deftest regional-proxy?-test
(testing "regional-proxy? with all valid proxies and one invalid"
[(is (regional-proxy? "europe"))
(is (regional-proxy? "americas"))
(is (regional-proxy? "asia"))
(not (regional-proxy? "fail"))]))
(deftest region-codes-test
(testing "region-codes returns expected"
(is (= (region-codes) '("br1" "eun1" "euw1" "jp1" "kr" "la1" "la2" "na" "na1" "oc1" "pbe1" "ru" "tr1")))))
(deftest region-code?-test
(testing "region-code? on 3 valid region codes and one invalid"
[(is (region-code? "br1"))
(is (region-code? "kr"))
(is (region-code? "ru"))
(not (region-code? "fail"))]))
(deftest subregions-test
(testing "subregions for all valid proxies and an invalid proxy"
[(is (= (subregions "europe") {:eun1 "Europe Nordic & East", :euw1 "Europe West", :tr1 "Turkey", :ru "Russia"}))
(is (= (subregions "americas") {:br1 "Brazil",
:la1 "Latin America North",
:la2 "Latin America South",
:na "North America (older)",
:na1 "North America"}))
(is (= (subregions "asia") {:jp1 "Japan", :kr "Korea", :oc1 "Oceanic"}))
(not (= (subregions "europe") nil))]))
(deftest region-to-proxy-test
(testing "region-to-proxy for 3 valid regions and an invalid one"
[(is (= (region-to-proxy "kr") "asia"))
(is (= (region-to-proxy "la1") "americas"))
(is (= (region-to-proxy "tr1") "europe"))
(not (= (region-to-proxy "fail") nil))])) |
[
{
"context": "(ns ^{:author \"Seth\"} forex.backend.mql.utils \n (:use forex.util.ge",
"end": 19,
"score": 0.9916080236434937,
"start": 15,
"tag": "NAME",
"value": "Seth"
}
] | src/forex/backend/mql/utils.clj | Storkle/clj-forex | 16 | (ns ^{:author "Seth"} forex.backend.mql.utils
(:use forex.util.general)
(:import (java.io DataInputStream ByteArrayInputStream))
(:use forex.util.log))
(defonce *msg-id* (atom 0))
(defn msg-id
"Generate a new message id string."
[]
(str (swap! *msg-id* inc)))
(defn parse-int
"Convert string to integer or return string if exception is thrown."
[string]
(try (Integer/parseInt string) (catch Exception e string)))
(defmacro catch-unexpected
"Catch and warn on any unexpected errors."
[& body]
`(try (do ~@body)
(catch Exception e# (.printStackTrace e#) (warn e#))))
(defn into-doubles
"Convert a byte array into a clojure double vector."
[^bytes array]
(let [stream (DataInputStream. (ByteArrayInputStream. array))
length (/ (alength array) 8)]
(loop [i 0 v (transient [])]
(if (< i length)
(recur (inc i) (conj! v (.readDouble stream)))
(persistent! v)))))
| 115076 | (ns ^{:author "<NAME>"} forex.backend.mql.utils
(:use forex.util.general)
(:import (java.io DataInputStream ByteArrayInputStream))
(:use forex.util.log))
(defonce *msg-id* (atom 0))
(defn msg-id
"Generate a new message id string."
[]
(str (swap! *msg-id* inc)))
(defn parse-int
"Convert string to integer or return string if exception is thrown."
[string]
(try (Integer/parseInt string) (catch Exception e string)))
(defmacro catch-unexpected
"Catch and warn on any unexpected errors."
[& body]
`(try (do ~@body)
(catch Exception e# (.printStackTrace e#) (warn e#))))
(defn into-doubles
"Convert a byte array into a clojure double vector."
[^bytes array]
(let [stream (DataInputStream. (ByteArrayInputStream. array))
length (/ (alength array) 8)]
(loop [i 0 v (transient [])]
(if (< i length)
(recur (inc i) (conj! v (.readDouble stream)))
(persistent! v)))))
| true | (ns ^{:author "PI:NAME:<NAME>END_PI"} forex.backend.mql.utils
(:use forex.util.general)
(:import (java.io DataInputStream ByteArrayInputStream))
(:use forex.util.log))
(defonce *msg-id* (atom 0))
(defn msg-id
"Generate a new message id string."
[]
(str (swap! *msg-id* inc)))
(defn parse-int
"Convert string to integer or return string if exception is thrown."
[string]
(try (Integer/parseInt string) (catch Exception e string)))
(defmacro catch-unexpected
"Catch and warn on any unexpected errors."
[& body]
`(try (do ~@body)
(catch Exception e# (.printStackTrace e#) (warn e#))))
(defn into-doubles
"Convert a byte array into a clojure double vector."
[^bytes array]
(let [stream (DataInputStream. (ByteArrayInputStream. array))
length (/ (alength array) 8)]
(loop [i 0 v (transient [])]
(if (< i length)
(recur (inc i) (conj! v (.readDouble stream)))
(persistent! v)))))
|
[
{
"context": " :email \"me@nail.com\"})))]\n (is (= (:status response) 200))\n ",
"end": 595,
"score": 0.9999201893806458,
"start": 584,
"tag": "EMAIL",
"value": "me@nail.com"
},
{
"context": " (mock/json-body {:email \"me3@nail.com\"})))]\n (is (= (:status response) 200))\n ",
"end": 884,
"score": 0.9999043345451355,
"start": 872,
"tag": "EMAIL",
"value": "me3@nail.com"
},
{
"context": " \"user\" \"test-user3\"\n \"e",
"end": 1335,
"score": 0.9988983273506165,
"start": 1325,
"tag": "USERNAME",
"value": "test-user3"
},
{
"context": " \"email\" \"me3@nail.com\"}))))\n\n (testing \"email required for creating a ",
"end": 1404,
"score": 0.9999145865440369,
"start": 1392,
"tag": "EMAIL",
"value": "me3@nail.com"
},
{
"context": " :email \"me@nail.com\"})))]\n (is (= (:status response) 400))\n ",
"end": 1955,
"score": 0.9999176859855652,
"start": 1944,
"tag": "EMAIL",
"value": "me@nail.com"
},
{
"context": " :email \"me@nail.com\"})))]\n (is (= (:status response) 400))\n ",
"end": 2612,
"score": 0.9999030828475952,
"start": 2601,
"tag": "EMAIL",
"value": "me@nail.com"
},
{
"context": " :email \"me4@nail.com\"})))]\n (is (= (:status response) 200))\n ",
"end": 3785,
"score": 0.9998944401741028,
"start": 3773,
"tag": "EMAIL",
"value": "me4@nail.com"
},
{
"context": " \"user\" \"test-user\"\n \"e",
"end": 4876,
"score": 0.9995977282524109,
"start": 4867,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": " \"email\" \"me@nail.com\"\n \"r",
"end": 4944,
"score": 0.9999237060546875,
"start": 4933,
"tag": "EMAIL",
"value": "me@nail.com"
},
{
"context": " \"user\" \"test-user3\"\n \"e",
"end": 5276,
"score": 0.9996128082275391,
"start": 5266,
"tag": "USERNAME",
"value": "test-user3"
},
{
"context": " \"email\" \"me3@nail.com\"\n \"r",
"end": 5345,
"score": 0.999926745891571,
"start": 5333,
"tag": "EMAIL",
"value": "me3@nail.com"
},
{
"context": " \"user\" \"test-user4\"\n \"e",
"end": 5576,
"score": 0.999610424041748,
"start": 5566,
"tag": "USERNAME",
"value": "test-user4"
},
{
"context": " \"email\" \"me4@nail.com\"\n \"r",
"end": 5645,
"score": 0.9999275207519531,
"start": 5633,
"tag": "EMAIL",
"value": "me4@nail.com"
},
{
"context": " \"users\"[{\"user\" \"test-user\"\n ",
"end": 5970,
"score": 0.999525785446167,
"start": 5961,
"tag": "USERNAME",
"value": "test-user"
},
{
"context": " \"email\" \"me@nail.com\"\n ",
"end": 6040,
"score": 0.999923586845398,
"start": 6029,
"tag": "EMAIL",
"value": "me@nail.com"
},
{
"context": " {\"user\" \"test-user3\"\n ",
"end": 6173,
"score": 0.9995530843734741,
"start": 6163,
"tag": "USERNAME",
"value": "test-user3"
},
{
"context": " \"email\" \"me3@nail.com\"\n ",
"end": 6244,
"score": 0.9999222159385681,
"start": 6232,
"tag": "EMAIL",
"value": "me3@nail.com"
},
{
"context": " {\"user\" \"test-user4\"\n ",
"end": 6382,
"score": 0.9995341300964355,
"start": 6372,
"tag": "USERNAME",
"value": "test-user4"
},
{
"context": " \"email\" \"me4@nail.com\"\n ",
"end": 6453,
"score": 0.9999225735664368,
"start": 6441,
"tag": "EMAIL",
"value": "me4@nail.com"
}
] | identity/test/identity/handler_test.clj | raymondpoling/rerun-tv | 0 | (ns identity.handler-test
(:require [clojure.test :refer [deftest is testing]]
[ring.mock.request :as mock]
[db.db :refer [initialize]]
[identity.test-db :refer [create-h2-mem-tables]]
[identity.handler :refer [app]]
[cheshire.core :refer [parse-string]]))
(deftest test-app
(initialize)
(create-h2-mem-tables)
(testing "create a user"
(let [response (app (-> (mock/request :post "/user/test-user")
(mock/json-body {:role "user"
:email "me@nail.com"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "create a user with default role"
(let [response (app (-> (mock/request :post "/user/test-user3")
(mock/json-body {:email "me3@nail.com"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "make sure user is the default role"
(let [response (app (-> (mock/request :get "/user/test-user3")))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"
"role" "user"
"user" "test-user3"
"email" "me3@nail.com"}))))
(testing "email required for creating a user"
(let [response (app (-> (mock/request :post "/user/test-user4")
(mock/json-body {})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "user must have an email address"}))))
(testing "do not recreate user"
(let [response (app (-> (mock/request :post "/user/test-user")
(mock/json-body {:role "user"
:email "me@nail.com"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "user already exists"}))))
(testing "change user role"
(let [response (app (-> (mock/request :put "/user/test-user")
(mock/json-body {:role "media"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "reject non-existant roles on create"
(let [response (app (-> (mock/request :post "/user/test-user2")
(mock/json-body {:role "media-czar"
:email "me@nail.com"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "role [media-czar] does not exist"}))))
(testing "reject non-existant roles on update"
(let [response (app (-> (mock/request :put "/user/test-user")
(mock/json-body {:role "media-czar"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "role [media-czar] does not exist"}))))
(testing "create new role"
(let [response (app (mock/request :post "/role/media-czar"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "fail to recreate role"
(let [response (app (mock/request :post "/role/media-czar"))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "cannot create role"}))))
(testing "create user with new role"
(let [response (app (-> (mock/request :post "/user/test-user4")
(mock/json-body {:role "media-czar"
:email "me4@nail.com"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "update user with new role"
(let [response (app (-> (mock/request :put "/user/test-user3")
(mock/json-body {:role "media-czar"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "get all roles"
(let [response (app (mock/request :get "/role"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok" "roles" ["admin","media","media-czar","user"]}))))
(testing "get role for user"
(let [response1 (app (-> (mock/request :get "/user/test-user")))
response2 (app (-> (mock/request :get "/user/test-user2")))
response3 (app (-> (mock/request :get "/user/test-user3")))
response4 (app (-> (mock/request :get "/user/test-user4")))]
(is (= (:status response1) 200))
(is (= (parse-string (:body response1)) {"status" "ok"
"user" "test-user"
"email" "me@nail.com"
"role" "media"}))
(is (= (:status response2) 404))
(is (= (parse-string (:body response2)) {"status" "not-found"}))
(is (= (:status response3) 200))
(is (= (parse-string (:body response3)) {"status" "ok"
"user" "test-user3"
"email" "me3@nail.com"
"role" "media-czar"}))
(is (= (:status response4) 200))
(is (= (parse-string (:body response4)) {"status" "ok"
"user" "test-user4"
"email" "me4@nail.com"
"role" "media-czar"}))))
(testing "get all users"
(let [response (app (mock/request :get "/user"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"
"users"[{"user" "test-user"
"email" "me@nail.com"
"role" "media"}
{"user" "test-user3"
"email" "me3@nail.com"
"role" "media-czar"}
{"user" "test-user4"
"email" "me4@nail.com"
"role" "media-czar"}]}))))
(testing "not-found route"
(let [response (app (mock/request :get "/"))]
(is (= (:status response) 404)))))
| 28559 | (ns identity.handler-test
(:require [clojure.test :refer [deftest is testing]]
[ring.mock.request :as mock]
[db.db :refer [initialize]]
[identity.test-db :refer [create-h2-mem-tables]]
[identity.handler :refer [app]]
[cheshire.core :refer [parse-string]]))
(deftest test-app
(initialize)
(create-h2-mem-tables)
(testing "create a user"
(let [response (app (-> (mock/request :post "/user/test-user")
(mock/json-body {:role "user"
:email "<EMAIL>"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "create a user with default role"
(let [response (app (-> (mock/request :post "/user/test-user3")
(mock/json-body {:email "<EMAIL>"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "make sure user is the default role"
(let [response (app (-> (mock/request :get "/user/test-user3")))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"
"role" "user"
"user" "test-user3"
"email" "<EMAIL>"}))))
(testing "email required for creating a user"
(let [response (app (-> (mock/request :post "/user/test-user4")
(mock/json-body {})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "user must have an email address"}))))
(testing "do not recreate user"
(let [response (app (-> (mock/request :post "/user/test-user")
(mock/json-body {:role "user"
:email "<EMAIL>"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "user already exists"}))))
(testing "change user role"
(let [response (app (-> (mock/request :put "/user/test-user")
(mock/json-body {:role "media"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "reject non-existant roles on create"
(let [response (app (-> (mock/request :post "/user/test-user2")
(mock/json-body {:role "media-czar"
:email "<EMAIL>"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "role [media-czar] does not exist"}))))
(testing "reject non-existant roles on update"
(let [response (app (-> (mock/request :put "/user/test-user")
(mock/json-body {:role "media-czar"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "role [media-czar] does not exist"}))))
(testing "create new role"
(let [response (app (mock/request :post "/role/media-czar"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "fail to recreate role"
(let [response (app (mock/request :post "/role/media-czar"))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "cannot create role"}))))
(testing "create user with new role"
(let [response (app (-> (mock/request :post "/user/test-user4")
(mock/json-body {:role "media-czar"
:email "<EMAIL>"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "update user with new role"
(let [response (app (-> (mock/request :put "/user/test-user3")
(mock/json-body {:role "media-czar"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "get all roles"
(let [response (app (mock/request :get "/role"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok" "roles" ["admin","media","media-czar","user"]}))))
(testing "get role for user"
(let [response1 (app (-> (mock/request :get "/user/test-user")))
response2 (app (-> (mock/request :get "/user/test-user2")))
response3 (app (-> (mock/request :get "/user/test-user3")))
response4 (app (-> (mock/request :get "/user/test-user4")))]
(is (= (:status response1) 200))
(is (= (parse-string (:body response1)) {"status" "ok"
"user" "test-user"
"email" "<EMAIL>"
"role" "media"}))
(is (= (:status response2) 404))
(is (= (parse-string (:body response2)) {"status" "not-found"}))
(is (= (:status response3) 200))
(is (= (parse-string (:body response3)) {"status" "ok"
"user" "test-user3"
"email" "<EMAIL>"
"role" "media-czar"}))
(is (= (:status response4) 200))
(is (= (parse-string (:body response4)) {"status" "ok"
"user" "test-user4"
"email" "<EMAIL>"
"role" "media-czar"}))))
(testing "get all users"
(let [response (app (mock/request :get "/user"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"
"users"[{"user" "test-user"
"email" "<EMAIL>"
"role" "media"}
{"user" "test-user3"
"email" "<EMAIL>"
"role" "media-czar"}
{"user" "test-user4"
"email" "<EMAIL>"
"role" "media-czar"}]}))))
(testing "not-found route"
(let [response (app (mock/request :get "/"))]
(is (= (:status response) 404)))))
| true | (ns identity.handler-test
(:require [clojure.test :refer [deftest is testing]]
[ring.mock.request :as mock]
[db.db :refer [initialize]]
[identity.test-db :refer [create-h2-mem-tables]]
[identity.handler :refer [app]]
[cheshire.core :refer [parse-string]]))
(deftest test-app
(initialize)
(create-h2-mem-tables)
(testing "create a user"
(let [response (app (-> (mock/request :post "/user/test-user")
(mock/json-body {:role "user"
:email "PI:EMAIL:<EMAIL>END_PI"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "create a user with default role"
(let [response (app (-> (mock/request :post "/user/test-user3")
(mock/json-body {:email "PI:EMAIL:<EMAIL>END_PI"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "make sure user is the default role"
(let [response (app (-> (mock/request :get "/user/test-user3")))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"
"role" "user"
"user" "test-user3"
"email" "PI:EMAIL:<EMAIL>END_PI"}))))
(testing "email required for creating a user"
(let [response (app (-> (mock/request :post "/user/test-user4")
(mock/json-body {})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "user must have an email address"}))))
(testing "do not recreate user"
(let [response (app (-> (mock/request :post "/user/test-user")
(mock/json-body {:role "user"
:email "PI:EMAIL:<EMAIL>END_PI"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "user already exists"}))))
(testing "change user role"
(let [response (app (-> (mock/request :put "/user/test-user")
(mock/json-body {:role "media"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "reject non-existant roles on create"
(let [response (app (-> (mock/request :post "/user/test-user2")
(mock/json-body {:role "media-czar"
:email "PI:EMAIL:<EMAIL>END_PI"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "role [media-czar] does not exist"}))))
(testing "reject non-existant roles on update"
(let [response (app (-> (mock/request :put "/user/test-user")
(mock/json-body {:role "media-czar"})))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "role [media-czar] does not exist"}))))
(testing "create new role"
(let [response (app (mock/request :post "/role/media-czar"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "fail to recreate role"
(let [response (app (mock/request :post "/role/media-czar"))]
(is (= (:status response) 400))
(is (= (parse-string (:body response)) {"status" "failed" "message" "cannot create role"}))))
(testing "create user with new role"
(let [response (app (-> (mock/request :post "/user/test-user4")
(mock/json-body {:role "media-czar"
:email "PI:EMAIL:<EMAIL>END_PI"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "update user with new role"
(let [response (app (-> (mock/request :put "/user/test-user3")
(mock/json-body {:role "media-czar"})))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"}))))
(testing "get all roles"
(let [response (app (mock/request :get "/role"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok" "roles" ["admin","media","media-czar","user"]}))))
(testing "get role for user"
(let [response1 (app (-> (mock/request :get "/user/test-user")))
response2 (app (-> (mock/request :get "/user/test-user2")))
response3 (app (-> (mock/request :get "/user/test-user3")))
response4 (app (-> (mock/request :get "/user/test-user4")))]
(is (= (:status response1) 200))
(is (= (parse-string (:body response1)) {"status" "ok"
"user" "test-user"
"email" "PI:EMAIL:<EMAIL>END_PI"
"role" "media"}))
(is (= (:status response2) 404))
(is (= (parse-string (:body response2)) {"status" "not-found"}))
(is (= (:status response3) 200))
(is (= (parse-string (:body response3)) {"status" "ok"
"user" "test-user3"
"email" "PI:EMAIL:<EMAIL>END_PI"
"role" "media-czar"}))
(is (= (:status response4) 200))
(is (= (parse-string (:body response4)) {"status" "ok"
"user" "test-user4"
"email" "PI:EMAIL:<EMAIL>END_PI"
"role" "media-czar"}))))
(testing "get all users"
(let [response (app (mock/request :get "/user"))]
(is (= (:status response) 200))
(is (= (parse-string (:body response)) {"status" "ok"
"users"[{"user" "test-user"
"email" "PI:EMAIL:<EMAIL>END_PI"
"role" "media"}
{"user" "test-user3"
"email" "PI:EMAIL:<EMAIL>END_PI"
"role" "media-czar"}
{"user" "test-user4"
"email" "PI:EMAIL:<EMAIL>END_PI"
"role" "media-czar"}]}))))
(testing "not-found route"
(let [response (app (mock/request :get "/"))]
(is (= (:status response) 404)))))
|
[
{
"context": "sageHeader (@tr [:success])]\n [:p (@tr [@success-message])]])\n\n [ui/Form\n [ui/FormInput",
"end": 3142,
"score": 0.8918588161468506,
"start": 3125,
"tag": "USERNAME",
"value": "[@success-message"
},
{
"context": " (str \"mailto:support@sixsq.com?subject=[\"\n ",
"end": 5845,
"score": 0.9999043345451355,
"start": 5828,
"tag": "EMAIL",
"value": "support@sixsq.com"
},
{
"context": "tonGroup {:primary true}\n [ui/Button {:id \"nuvla-username-button\" :on-click profile-fn}\n [ui/Icon {:name (",
"end": 7122,
"score": 0.9940537214279175,
"start": 7101,
"tag": "USERNAME",
"value": "nuvla-username-button"
},
{
"context": "is-group? \"group\" \"user\")}]\n [:span {:id \"nuvla-username\"} (general-utils/truncate (utils/remove-group-pre",
"end": 7240,
"score": 0.9962887763977051,
"start": 7226,
"tag": "USERNAME",
"value": "nuvla-username"
},
{
"context": "nd %))\n [[\"linkedin\" @linkedin]\n [\"twitter\" @twitte",
"end": 8291,
"score": 0.4992859363555908,
"start": 8283,
"tag": "USERNAME",
"value": "linkedin"
},
{
"context": "kedin\" @linkedin]\n [\"twitter\" @twitter]\n [\"facebo",
"end": 8332,
"score": 0.5064082741737366,
"start": 8325,
"tag": "USERNAME",
"value": "twitter"
},
{
"context": "nkedin]\n [\"twitter\" @twitter]\n [\"facebook\" @faceb",
"end": 8342,
"score": 0.9763609170913696,
"start": 8335,
"tag": "USERNAME",
"value": "twitter"
},
{
"context": "itter]\n [\"facebook\" @facebook]\n [\"youtube\" @youtub",
"end": 8395,
"score": 0.6521018147468567,
"start": 8387,
"tag": "USERNAME",
"value": "facebook"
}
] | code/src/cljs/sixsq/nuvla/ui/session/views.cljs | nuvla/ui | 8 | (ns sixsq.nuvla.ui.session.views
(:require
[clojure.spec.alpha :as s]
[clojure.string :as str]
[form-validator.core :as fv]
[re-frame.core :refer [dispatch subscribe]]
[sixsq.nuvla.ui.cimi-api.effects :as cimi-api-fx]
[sixsq.nuvla.ui.config :as config]
[sixsq.nuvla.ui.history.events :as history-events]
[sixsq.nuvla.ui.i18n.subs :as i18n-subs]
[sixsq.nuvla.ui.main.subs :as main-subs]
[sixsq.nuvla.ui.session.events :as events]
[sixsq.nuvla.ui.session.reset-password-views :as reset-password-views]
[sixsq.nuvla.ui.session.set-password-views :as set-password-views]
[sixsq.nuvla.ui.session.sign-in-views :as sign-in-views]
[sixsq.nuvla.ui.session.sign-up-views :as sign-up-views]
[sixsq.nuvla.ui.session.subs :as subs]
[sixsq.nuvla.ui.session.utils :as utils]
[sixsq.nuvla.ui.utils.general :as general-utils]
[sixsq.nuvla.ui.utils.semantic-ui :as ui]
[sixsq.nuvla.ui.utils.semantic-ui-extensions :as uix]
[sixsq.nuvla.ui.utils.spec :as us]))
;;; VALIDATION SPEC
(s/def ::email (s/and string? us/email?))
(s/def ::user-template-email-invitation
(s/keys :req-un [::email]))
(defn modal-create-user []
(let [tr (subscribe [::i18n-subs/tr])
open-modal (subscribe [::subs/open-modal])
error-message (subscribe [::subs/error-message])
success-message (subscribe [::subs/success-message])
loading? (subscribe [::subs/loading?])
form-conf {:form-spec ::user-template-email-invitation}
form (fv/init-form form-conf)
spec->msg {::email (@tr [:email-invalid-format])}]
(fn []
(let [submit-fn #(when (fv/validate-form-and-show? form)
(dispatch [::events/submit utils/user-tmpl-email-invitation
(:names->value @form)
{:success-msg :invitation-email-success-msg
:close-modal false
:redirect-url (str @config/path-prefix
"/set-password")}]))]
[ui/Modal
{:id "modal-create-user"
:size :tiny
:open (= @open-modal :invite-user)
:closeIcon true
:on-close #(do
(dispatch [::events/close-modal])
(reset! form @(fv/init-form form-conf)))}
[uix/ModalHeader {:header (@tr [:invite-user])}]
[ui/ModalContent
(when @error-message
[ui/Message {:negative true
:size "tiny"
:onDismiss #(dispatch [::events/set-error-message nil])}
[ui/MessageHeader (@tr [:error-occured])]
[:p @error-message]])
(when @success-message
[ui/Message {:negative false
:size "tiny"
:onDismiss #(dispatch [::events/set-success-message nil])}
[ui/MessageHeader (@tr [:success])]
[:p (@tr [@success-message])]])
[ui/Form
[ui/FormInput {:name :email
:label "Email"
:required true
:icon "mail"
:icon-position "left"
:auto-focus true
:auto-complete "on"
:on-change (partial fv/event->names->value! form)
:on-blur (partial fv/event->show-message form)
:error (fv/?show-message form :email spec->msg)}]]
[:div {:style {:padding "10px 0"}} (@tr [:invite-user-inst])]]
[ui/ModalActions
[uix/Button
{:text (@tr [:invite-user])
:positive true
:loading @loading?
:on-click submit-fn}]]]))))
(defn authn-dropdown-menu
[]
(let [tr (subscribe [::i18n-subs/tr])
user (subscribe [::subs/user])
sign-out-fn #(dispatch [::events/logout])
create-user-fn #(dispatch [::events/open-modal :invite-user])
logged-in? (boolean @user)
invitation-template? (subscribe [::subs/user-template-exist?
utils/user-tmpl-email-invitation])
switch-group-options (subscribe [::subs/switch-group-options])]
[ui/DropdownMenu
(when (seq @switch-group-options)
[:<>
[ui/DropdownHeader (@tr [:switch-group])]
(for [account @switch-group-options]
^{:key account}
[ui/DropdownItem {:text (utils/remove-group-prefix account)
:icon (if (str/starts-with? account "group/") "group" "user")
:on-click #(dispatch [::events/switch-group account])}])
[ui/DropdownDivider]])
(when @invitation-template?
[:<>
[ui/DropdownItem
{:key "invite"
:text (@tr [:invite-user])
:icon "user add"
:on-click create-user-fn}]
[ui/DropdownDivider]])
[ui/DropdownItem {:aria-label (@tr [:documentation])
:icon "book"
:text (@tr [:documentation])
:href "https://docs.nuvla.io/"
:target "_blank"
:rel "noreferrer"}]
[ui/DropdownItem {:aria-label (@tr [:support])
:icon "mail"
:text (@tr [:support])
:href (js/encodeURI
(str "mailto:support@sixsq.com?subject=["
@cimi-api-fx/NUVLA_URL
"] Support question - "
(if logged-in? @user "Not logged in")))}]
(when logged-in?
[:<>
[ui/DropdownDivider]
[ui/DropdownItem
{:key "sign-out"
:text (@tr [:logout])
:icon "sign out"
:on-click sign-out-fn}]])]))
(defn authn-menu
[]
(let [tr (subscribe [::i18n-subs/tr])
user (subscribe [::subs/user])
profile-fn #(dispatch [::history-events/navigate "profile"])
logged-in? (subscribe [::subs/logged-in?])
is-group? (subscribe [::subs/active-claim-is-group?])
signup-template? (subscribe [::subs/user-template-exist? utils/user-tmpl-email-password])
dropdown-menu [ui/Dropdown {:inline true
:button true
:pointing "top right"
:className "icon"}
(authn-dropdown-menu)]]
[:<>
(if @logged-in?
[ui/ButtonGroup {:primary true}
[ui/Button {:id "nuvla-username-button" :on-click profile-fn}
[ui/Icon {:name (if @is-group? "group" "user")}]
[:span {:id "nuvla-username"} (general-utils/truncate (utils/remove-group-prefix @user))]]
dropdown-menu]
[:div
(when @signup-template?
[:span {:style {:padding-right "10px"
:cursor "pointer"}
:on-click #(dispatch [::history-events/navigate "sign-up"])}
[ui/Icon {:name "signup"}]
(@tr [:sign-up])])
[ui/ButtonGroup {:primary true}
[ui/Button {:on-click #(dispatch [::history-events/navigate "sign-in"])}
[ui/Icon {:name "sign in"}]
(@tr [:login])]
dropdown-menu]])
[modal-create-user]]))
(defn follow-us
[]
(let [tr (subscribe [::i18n-subs/tr])
linkedin (subscribe [::main-subs/config :linkedin])
twitter (subscribe [::main-subs/config :twitter])
facebook (subscribe [::main-subs/config :facebook])
youtube (subscribe [::main-subs/config :youtube])
social-media (remove #(nil? (second %))
[["linkedin" @linkedin]
["twitter" @twitter]
["facebook" @facebook]
["youtube" @youtube]])]
[:<>
(when (seq social-media)
(@tr [:follow-us-on]))
[:span
(for [[icon url] social-media]
[:a {:key url
:href url
:target "_blank"
:style {:color "white"}}
[ui/Icon {:name icon}]])]]))
(defn LeftPanel
[]
(let [tr (subscribe [::i18n-subs/tr])
first-path (subscribe [::main-subs/nav-path-first])
signup-template? (subscribe [::subs/user-template-exist? utils/user-tmpl-email-password])
eula (subscribe [::main-subs/config :eula])
terms-and-conditions (subscribe [::main-subs/config :terms-and-conditions])]
[:div {:class "nuvla-ui-session-left"}
[ui/Image {:alt "logo"
:src "/ui/images/nuvla-logo.png"
:size "medium"
:centered false}]
[:br]
[:div {:style {:line-height "normal"
:font-size "2em"}}
(@tr [:edge-platform-as-a-service])]
[:br]
[:p {:style {:font-size "1.4em"}} (@tr [:start-journey-to-the-edge])]
[:br] [:br]
[:div
[uix/Button
{:text (@tr [:sign-in])
:inverted true
:active (= @first-path "sign-in")
:on-click #(dispatch [::history-events/navigate "sign-in"])}]
(when @signup-template?
[:span
[uix/Button
{:text (@tr [:sign-up])
:inverted true
:active (= @first-path "sign-up")
:on-click #(dispatch [::history-events/navigate "sign-up"])}]
[:br]
[:br]
(when @terms-and-conditions
[:a {:href @terms-and-conditions
:target "_blank"
:style {:margin-top 20 :color "white" :font-style "italic"}}
(@tr [:terms-and-conditions])])
(when (and @terms-and-conditions @eula) " and ")
(when @eula
[:a {:href @eula
:target "_blank"
:style {:margin-top 20 :color "white" :font-style "italic"}}
(@tr [:terms-end-user-license-agreement])])])]
[:br]
[:a {:href "https://docs.nuvla.io"
:target "_blank"
:style {:color "white"}}
[:p {:style {:font-size "1.2em" :text-decoration "underline"}}
(@tr [:getting-started-docs])]]
[:div {:style {:margin-top 20
:line-height "normal"}}
(@tr [:keep-data-control])]
[:div {:style {:position "absolute"
:bottom 40}}
[follow-us]]]))
(defn RightPanel
[]
(let [first-path (subscribe [::main-subs/nav-path-first])]
(case @first-path
"sign-in" [sign-in-views/Form]
"sign-up" [sign-up-views/Form]
"reset-password" [reset-password-views/Form]
"set-password" [set-password-views/Form]
[sign-in-views/Form])))
(defn SessionPage
[navigate?]
(let [session (subscribe [::subs/session])
query-params (subscribe [::main-subs/nav-query-params])
tr (subscribe [::i18n-subs/tr])
error (some-> @query-params :error keyword)
message (some-> @query-params :message keyword)]
(when (and navigate? @session)
(dispatch [::history-events/navigate "welcome"]))
(when error
(dispatch [::events/set-error-message (or (@tr [(keyword error)]) error)]))
(when message
(dispatch [::events/set-success-message (or (@tr [(keyword message)]) message)]))
[ui/Grid {:stackable true
:columns 2
:style {:margin 0
:background-color "white"}}
[ui/GridColumn {:style {:background-image "url(/ui/images/session.png)"
:background-size "cover"
:background-position "left"
:background-repeat "no-repeat"
:color "white"
:min-height "100vh"}}
[LeftPanel]]
[ui/GridColumn
[RightPanel]]]))
| 92577 | (ns sixsq.nuvla.ui.session.views
(:require
[clojure.spec.alpha :as s]
[clojure.string :as str]
[form-validator.core :as fv]
[re-frame.core :refer [dispatch subscribe]]
[sixsq.nuvla.ui.cimi-api.effects :as cimi-api-fx]
[sixsq.nuvla.ui.config :as config]
[sixsq.nuvla.ui.history.events :as history-events]
[sixsq.nuvla.ui.i18n.subs :as i18n-subs]
[sixsq.nuvla.ui.main.subs :as main-subs]
[sixsq.nuvla.ui.session.events :as events]
[sixsq.nuvla.ui.session.reset-password-views :as reset-password-views]
[sixsq.nuvla.ui.session.set-password-views :as set-password-views]
[sixsq.nuvla.ui.session.sign-in-views :as sign-in-views]
[sixsq.nuvla.ui.session.sign-up-views :as sign-up-views]
[sixsq.nuvla.ui.session.subs :as subs]
[sixsq.nuvla.ui.session.utils :as utils]
[sixsq.nuvla.ui.utils.general :as general-utils]
[sixsq.nuvla.ui.utils.semantic-ui :as ui]
[sixsq.nuvla.ui.utils.semantic-ui-extensions :as uix]
[sixsq.nuvla.ui.utils.spec :as us]))
;;; VALIDATION SPEC
(s/def ::email (s/and string? us/email?))
(s/def ::user-template-email-invitation
(s/keys :req-un [::email]))
(defn modal-create-user []
(let [tr (subscribe [::i18n-subs/tr])
open-modal (subscribe [::subs/open-modal])
error-message (subscribe [::subs/error-message])
success-message (subscribe [::subs/success-message])
loading? (subscribe [::subs/loading?])
form-conf {:form-spec ::user-template-email-invitation}
form (fv/init-form form-conf)
spec->msg {::email (@tr [:email-invalid-format])}]
(fn []
(let [submit-fn #(when (fv/validate-form-and-show? form)
(dispatch [::events/submit utils/user-tmpl-email-invitation
(:names->value @form)
{:success-msg :invitation-email-success-msg
:close-modal false
:redirect-url (str @config/path-prefix
"/set-password")}]))]
[ui/Modal
{:id "modal-create-user"
:size :tiny
:open (= @open-modal :invite-user)
:closeIcon true
:on-close #(do
(dispatch [::events/close-modal])
(reset! form @(fv/init-form form-conf)))}
[uix/ModalHeader {:header (@tr [:invite-user])}]
[ui/ModalContent
(when @error-message
[ui/Message {:negative true
:size "tiny"
:onDismiss #(dispatch [::events/set-error-message nil])}
[ui/MessageHeader (@tr [:error-occured])]
[:p @error-message]])
(when @success-message
[ui/Message {:negative false
:size "tiny"
:onDismiss #(dispatch [::events/set-success-message nil])}
[ui/MessageHeader (@tr [:success])]
[:p (@tr [@success-message])]])
[ui/Form
[ui/FormInput {:name :email
:label "Email"
:required true
:icon "mail"
:icon-position "left"
:auto-focus true
:auto-complete "on"
:on-change (partial fv/event->names->value! form)
:on-blur (partial fv/event->show-message form)
:error (fv/?show-message form :email spec->msg)}]]
[:div {:style {:padding "10px 0"}} (@tr [:invite-user-inst])]]
[ui/ModalActions
[uix/Button
{:text (@tr [:invite-user])
:positive true
:loading @loading?
:on-click submit-fn}]]]))))
(defn authn-dropdown-menu
[]
(let [tr (subscribe [::i18n-subs/tr])
user (subscribe [::subs/user])
sign-out-fn #(dispatch [::events/logout])
create-user-fn #(dispatch [::events/open-modal :invite-user])
logged-in? (boolean @user)
invitation-template? (subscribe [::subs/user-template-exist?
utils/user-tmpl-email-invitation])
switch-group-options (subscribe [::subs/switch-group-options])]
[ui/DropdownMenu
(when (seq @switch-group-options)
[:<>
[ui/DropdownHeader (@tr [:switch-group])]
(for [account @switch-group-options]
^{:key account}
[ui/DropdownItem {:text (utils/remove-group-prefix account)
:icon (if (str/starts-with? account "group/") "group" "user")
:on-click #(dispatch [::events/switch-group account])}])
[ui/DropdownDivider]])
(when @invitation-template?
[:<>
[ui/DropdownItem
{:key "invite"
:text (@tr [:invite-user])
:icon "user add"
:on-click create-user-fn}]
[ui/DropdownDivider]])
[ui/DropdownItem {:aria-label (@tr [:documentation])
:icon "book"
:text (@tr [:documentation])
:href "https://docs.nuvla.io/"
:target "_blank"
:rel "noreferrer"}]
[ui/DropdownItem {:aria-label (@tr [:support])
:icon "mail"
:text (@tr [:support])
:href (js/encodeURI
(str "mailto:<EMAIL>?subject=["
@cimi-api-fx/NUVLA_URL
"] Support question - "
(if logged-in? @user "Not logged in")))}]
(when logged-in?
[:<>
[ui/DropdownDivider]
[ui/DropdownItem
{:key "sign-out"
:text (@tr [:logout])
:icon "sign out"
:on-click sign-out-fn}]])]))
(defn authn-menu
[]
(let [tr (subscribe [::i18n-subs/tr])
user (subscribe [::subs/user])
profile-fn #(dispatch [::history-events/navigate "profile"])
logged-in? (subscribe [::subs/logged-in?])
is-group? (subscribe [::subs/active-claim-is-group?])
signup-template? (subscribe [::subs/user-template-exist? utils/user-tmpl-email-password])
dropdown-menu [ui/Dropdown {:inline true
:button true
:pointing "top right"
:className "icon"}
(authn-dropdown-menu)]]
[:<>
(if @logged-in?
[ui/ButtonGroup {:primary true}
[ui/Button {:id "nuvla-username-button" :on-click profile-fn}
[ui/Icon {:name (if @is-group? "group" "user")}]
[:span {:id "nuvla-username"} (general-utils/truncate (utils/remove-group-prefix @user))]]
dropdown-menu]
[:div
(when @signup-template?
[:span {:style {:padding-right "10px"
:cursor "pointer"}
:on-click #(dispatch [::history-events/navigate "sign-up"])}
[ui/Icon {:name "signup"}]
(@tr [:sign-up])])
[ui/ButtonGroup {:primary true}
[ui/Button {:on-click #(dispatch [::history-events/navigate "sign-in"])}
[ui/Icon {:name "sign in"}]
(@tr [:login])]
dropdown-menu]])
[modal-create-user]]))
(defn follow-us
[]
(let [tr (subscribe [::i18n-subs/tr])
linkedin (subscribe [::main-subs/config :linkedin])
twitter (subscribe [::main-subs/config :twitter])
facebook (subscribe [::main-subs/config :facebook])
youtube (subscribe [::main-subs/config :youtube])
social-media (remove #(nil? (second %))
[["linkedin" @linkedin]
["twitter" @twitter]
["facebook" @facebook]
["youtube" @youtube]])]
[:<>
(when (seq social-media)
(@tr [:follow-us-on]))
[:span
(for [[icon url] social-media]
[:a {:key url
:href url
:target "_blank"
:style {:color "white"}}
[ui/Icon {:name icon}]])]]))
(defn LeftPanel
[]
(let [tr (subscribe [::i18n-subs/tr])
first-path (subscribe [::main-subs/nav-path-first])
signup-template? (subscribe [::subs/user-template-exist? utils/user-tmpl-email-password])
eula (subscribe [::main-subs/config :eula])
terms-and-conditions (subscribe [::main-subs/config :terms-and-conditions])]
[:div {:class "nuvla-ui-session-left"}
[ui/Image {:alt "logo"
:src "/ui/images/nuvla-logo.png"
:size "medium"
:centered false}]
[:br]
[:div {:style {:line-height "normal"
:font-size "2em"}}
(@tr [:edge-platform-as-a-service])]
[:br]
[:p {:style {:font-size "1.4em"}} (@tr [:start-journey-to-the-edge])]
[:br] [:br]
[:div
[uix/Button
{:text (@tr [:sign-in])
:inverted true
:active (= @first-path "sign-in")
:on-click #(dispatch [::history-events/navigate "sign-in"])}]
(when @signup-template?
[:span
[uix/Button
{:text (@tr [:sign-up])
:inverted true
:active (= @first-path "sign-up")
:on-click #(dispatch [::history-events/navigate "sign-up"])}]
[:br]
[:br]
(when @terms-and-conditions
[:a {:href @terms-and-conditions
:target "_blank"
:style {:margin-top 20 :color "white" :font-style "italic"}}
(@tr [:terms-and-conditions])])
(when (and @terms-and-conditions @eula) " and ")
(when @eula
[:a {:href @eula
:target "_blank"
:style {:margin-top 20 :color "white" :font-style "italic"}}
(@tr [:terms-end-user-license-agreement])])])]
[:br]
[:a {:href "https://docs.nuvla.io"
:target "_blank"
:style {:color "white"}}
[:p {:style {:font-size "1.2em" :text-decoration "underline"}}
(@tr [:getting-started-docs])]]
[:div {:style {:margin-top 20
:line-height "normal"}}
(@tr [:keep-data-control])]
[:div {:style {:position "absolute"
:bottom 40}}
[follow-us]]]))
(defn RightPanel
[]
(let [first-path (subscribe [::main-subs/nav-path-first])]
(case @first-path
"sign-in" [sign-in-views/Form]
"sign-up" [sign-up-views/Form]
"reset-password" [reset-password-views/Form]
"set-password" [set-password-views/Form]
[sign-in-views/Form])))
(defn SessionPage
[navigate?]
(let [session (subscribe [::subs/session])
query-params (subscribe [::main-subs/nav-query-params])
tr (subscribe [::i18n-subs/tr])
error (some-> @query-params :error keyword)
message (some-> @query-params :message keyword)]
(when (and navigate? @session)
(dispatch [::history-events/navigate "welcome"]))
(when error
(dispatch [::events/set-error-message (or (@tr [(keyword error)]) error)]))
(when message
(dispatch [::events/set-success-message (or (@tr [(keyword message)]) message)]))
[ui/Grid {:stackable true
:columns 2
:style {:margin 0
:background-color "white"}}
[ui/GridColumn {:style {:background-image "url(/ui/images/session.png)"
:background-size "cover"
:background-position "left"
:background-repeat "no-repeat"
:color "white"
:min-height "100vh"}}
[LeftPanel]]
[ui/GridColumn
[RightPanel]]]))
| true | (ns sixsq.nuvla.ui.session.views
(:require
[clojure.spec.alpha :as s]
[clojure.string :as str]
[form-validator.core :as fv]
[re-frame.core :refer [dispatch subscribe]]
[sixsq.nuvla.ui.cimi-api.effects :as cimi-api-fx]
[sixsq.nuvla.ui.config :as config]
[sixsq.nuvla.ui.history.events :as history-events]
[sixsq.nuvla.ui.i18n.subs :as i18n-subs]
[sixsq.nuvla.ui.main.subs :as main-subs]
[sixsq.nuvla.ui.session.events :as events]
[sixsq.nuvla.ui.session.reset-password-views :as reset-password-views]
[sixsq.nuvla.ui.session.set-password-views :as set-password-views]
[sixsq.nuvla.ui.session.sign-in-views :as sign-in-views]
[sixsq.nuvla.ui.session.sign-up-views :as sign-up-views]
[sixsq.nuvla.ui.session.subs :as subs]
[sixsq.nuvla.ui.session.utils :as utils]
[sixsq.nuvla.ui.utils.general :as general-utils]
[sixsq.nuvla.ui.utils.semantic-ui :as ui]
[sixsq.nuvla.ui.utils.semantic-ui-extensions :as uix]
[sixsq.nuvla.ui.utils.spec :as us]))
;;; VALIDATION SPEC
(s/def ::email (s/and string? us/email?))
(s/def ::user-template-email-invitation
(s/keys :req-un [::email]))
(defn modal-create-user []
(let [tr (subscribe [::i18n-subs/tr])
open-modal (subscribe [::subs/open-modal])
error-message (subscribe [::subs/error-message])
success-message (subscribe [::subs/success-message])
loading? (subscribe [::subs/loading?])
form-conf {:form-spec ::user-template-email-invitation}
form (fv/init-form form-conf)
spec->msg {::email (@tr [:email-invalid-format])}]
(fn []
(let [submit-fn #(when (fv/validate-form-and-show? form)
(dispatch [::events/submit utils/user-tmpl-email-invitation
(:names->value @form)
{:success-msg :invitation-email-success-msg
:close-modal false
:redirect-url (str @config/path-prefix
"/set-password")}]))]
[ui/Modal
{:id "modal-create-user"
:size :tiny
:open (= @open-modal :invite-user)
:closeIcon true
:on-close #(do
(dispatch [::events/close-modal])
(reset! form @(fv/init-form form-conf)))}
[uix/ModalHeader {:header (@tr [:invite-user])}]
[ui/ModalContent
(when @error-message
[ui/Message {:negative true
:size "tiny"
:onDismiss #(dispatch [::events/set-error-message nil])}
[ui/MessageHeader (@tr [:error-occured])]
[:p @error-message]])
(when @success-message
[ui/Message {:negative false
:size "tiny"
:onDismiss #(dispatch [::events/set-success-message nil])}
[ui/MessageHeader (@tr [:success])]
[:p (@tr [@success-message])]])
[ui/Form
[ui/FormInput {:name :email
:label "Email"
:required true
:icon "mail"
:icon-position "left"
:auto-focus true
:auto-complete "on"
:on-change (partial fv/event->names->value! form)
:on-blur (partial fv/event->show-message form)
:error (fv/?show-message form :email spec->msg)}]]
[:div {:style {:padding "10px 0"}} (@tr [:invite-user-inst])]]
[ui/ModalActions
[uix/Button
{:text (@tr [:invite-user])
:positive true
:loading @loading?
:on-click submit-fn}]]]))))
(defn authn-dropdown-menu
[]
(let [tr (subscribe [::i18n-subs/tr])
user (subscribe [::subs/user])
sign-out-fn #(dispatch [::events/logout])
create-user-fn #(dispatch [::events/open-modal :invite-user])
logged-in? (boolean @user)
invitation-template? (subscribe [::subs/user-template-exist?
utils/user-tmpl-email-invitation])
switch-group-options (subscribe [::subs/switch-group-options])]
[ui/DropdownMenu
(when (seq @switch-group-options)
[:<>
[ui/DropdownHeader (@tr [:switch-group])]
(for [account @switch-group-options]
^{:key account}
[ui/DropdownItem {:text (utils/remove-group-prefix account)
:icon (if (str/starts-with? account "group/") "group" "user")
:on-click #(dispatch [::events/switch-group account])}])
[ui/DropdownDivider]])
(when @invitation-template?
[:<>
[ui/DropdownItem
{:key "invite"
:text (@tr [:invite-user])
:icon "user add"
:on-click create-user-fn}]
[ui/DropdownDivider]])
[ui/DropdownItem {:aria-label (@tr [:documentation])
:icon "book"
:text (@tr [:documentation])
:href "https://docs.nuvla.io/"
:target "_blank"
:rel "noreferrer"}]
[ui/DropdownItem {:aria-label (@tr [:support])
:icon "mail"
:text (@tr [:support])
:href (js/encodeURI
(str "mailto:PI:EMAIL:<EMAIL>END_PI?subject=["
@cimi-api-fx/NUVLA_URL
"] Support question - "
(if logged-in? @user "Not logged in")))}]
(when logged-in?
[:<>
[ui/DropdownDivider]
[ui/DropdownItem
{:key "sign-out"
:text (@tr [:logout])
:icon "sign out"
:on-click sign-out-fn}]])]))
(defn authn-menu
[]
(let [tr (subscribe [::i18n-subs/tr])
user (subscribe [::subs/user])
profile-fn #(dispatch [::history-events/navigate "profile"])
logged-in? (subscribe [::subs/logged-in?])
is-group? (subscribe [::subs/active-claim-is-group?])
signup-template? (subscribe [::subs/user-template-exist? utils/user-tmpl-email-password])
dropdown-menu [ui/Dropdown {:inline true
:button true
:pointing "top right"
:className "icon"}
(authn-dropdown-menu)]]
[:<>
(if @logged-in?
[ui/ButtonGroup {:primary true}
[ui/Button {:id "nuvla-username-button" :on-click profile-fn}
[ui/Icon {:name (if @is-group? "group" "user")}]
[:span {:id "nuvla-username"} (general-utils/truncate (utils/remove-group-prefix @user))]]
dropdown-menu]
[:div
(when @signup-template?
[:span {:style {:padding-right "10px"
:cursor "pointer"}
:on-click #(dispatch [::history-events/navigate "sign-up"])}
[ui/Icon {:name "signup"}]
(@tr [:sign-up])])
[ui/ButtonGroup {:primary true}
[ui/Button {:on-click #(dispatch [::history-events/navigate "sign-in"])}
[ui/Icon {:name "sign in"}]
(@tr [:login])]
dropdown-menu]])
[modal-create-user]]))
(defn follow-us
[]
(let [tr (subscribe [::i18n-subs/tr])
linkedin (subscribe [::main-subs/config :linkedin])
twitter (subscribe [::main-subs/config :twitter])
facebook (subscribe [::main-subs/config :facebook])
youtube (subscribe [::main-subs/config :youtube])
social-media (remove #(nil? (second %))
[["linkedin" @linkedin]
["twitter" @twitter]
["facebook" @facebook]
["youtube" @youtube]])]
[:<>
(when (seq social-media)
(@tr [:follow-us-on]))
[:span
(for [[icon url] social-media]
[:a {:key url
:href url
:target "_blank"
:style {:color "white"}}
[ui/Icon {:name icon}]])]]))
(defn LeftPanel
[]
(let [tr (subscribe [::i18n-subs/tr])
first-path (subscribe [::main-subs/nav-path-first])
signup-template? (subscribe [::subs/user-template-exist? utils/user-tmpl-email-password])
eula (subscribe [::main-subs/config :eula])
terms-and-conditions (subscribe [::main-subs/config :terms-and-conditions])]
[:div {:class "nuvla-ui-session-left"}
[ui/Image {:alt "logo"
:src "/ui/images/nuvla-logo.png"
:size "medium"
:centered false}]
[:br]
[:div {:style {:line-height "normal"
:font-size "2em"}}
(@tr [:edge-platform-as-a-service])]
[:br]
[:p {:style {:font-size "1.4em"}} (@tr [:start-journey-to-the-edge])]
[:br] [:br]
[:div
[uix/Button
{:text (@tr [:sign-in])
:inverted true
:active (= @first-path "sign-in")
:on-click #(dispatch [::history-events/navigate "sign-in"])}]
(when @signup-template?
[:span
[uix/Button
{:text (@tr [:sign-up])
:inverted true
:active (= @first-path "sign-up")
:on-click #(dispatch [::history-events/navigate "sign-up"])}]
[:br]
[:br]
(when @terms-and-conditions
[:a {:href @terms-and-conditions
:target "_blank"
:style {:margin-top 20 :color "white" :font-style "italic"}}
(@tr [:terms-and-conditions])])
(when (and @terms-and-conditions @eula) " and ")
(when @eula
[:a {:href @eula
:target "_blank"
:style {:margin-top 20 :color "white" :font-style "italic"}}
(@tr [:terms-end-user-license-agreement])])])]
[:br]
[:a {:href "https://docs.nuvla.io"
:target "_blank"
:style {:color "white"}}
[:p {:style {:font-size "1.2em" :text-decoration "underline"}}
(@tr [:getting-started-docs])]]
[:div {:style {:margin-top 20
:line-height "normal"}}
(@tr [:keep-data-control])]
[:div {:style {:position "absolute"
:bottom 40}}
[follow-us]]]))
(defn RightPanel
[]
(let [first-path (subscribe [::main-subs/nav-path-first])]
(case @first-path
"sign-in" [sign-in-views/Form]
"sign-up" [sign-up-views/Form]
"reset-password" [reset-password-views/Form]
"set-password" [set-password-views/Form]
[sign-in-views/Form])))
(defn SessionPage
[navigate?]
(let [session (subscribe [::subs/session])
query-params (subscribe [::main-subs/nav-query-params])
tr (subscribe [::i18n-subs/tr])
error (some-> @query-params :error keyword)
message (some-> @query-params :message keyword)]
(when (and navigate? @session)
(dispatch [::history-events/navigate "welcome"]))
(when error
(dispatch [::events/set-error-message (or (@tr [(keyword error)]) error)]))
(when message
(dispatch [::events/set-success-message (or (@tr [(keyword message)]) message)]))
[ui/Grid {:stackable true
:columns 2
:style {:margin 0
:background-color "white"}}
[ui/GridColumn {:style {:background-image "url(/ui/images/session.png)"
:background-size "cover"
:background-position "left"
:background-repeat "no-repeat"
:color "white"
:min-height "100vh"}}
[LeftPanel]]
[ui/GridColumn
[RightPanel]]]))
|
[
{
"context": " :value [[0 0 0 0]]}}}}\n \"Würfel\" {\"Würfel\"\n {:points (let [a 20 b -",
"end": 569,
"score": 0.5961493849754333,
"start": 565,
"tag": "NAME",
"value": "Würf"
},
{
"context": " :value [[0 0 0 0]]}}}}\n \"Würfel\" {\"Würfel\"\n {:points (let [a 20 b -20 c 20 d -2",
"end": 581,
"score": 0.8516578674316406,
"start": 575,
"tag": "NAME",
"value": "Würfel"
},
{
"context": " :value [[0 0 0 0]]}}}}\n \"Pentachoron\" {\"Pentachoron\"\n {:points (mapv ",
"end": 1169,
"score": 0.8672353625297546,
"start": 1158,
"tag": "NAME",
"value": "Pentachoron"
},
{
"context": " :value [[0 0 0 0]]}}}}\n \"Pentachoron\" {\"Pentachoron\"\n {:points (mapv (fn [v] (mapv (",
"end": 1184,
"score": 0.935142993927002,
"start": 1173,
"tag": "NAME",
"value": "Pentachoron"
}
] | src/cljs/drawer/scenes.cljs | maxi-k/drawer | 0 | (ns drawer.scenes
(:require [drawer.api :as api]
[drawer.geometry :as g]
[drawer.math :as math]
[drawer.lang :as lang]))
(def seminar-scenes
"The scenes used for the seminary work."
{"Punkt" {"Punkt"
{:points [[20 20 0 0]]
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [1 4]
:deg 0.5
:center {:type :points
:value [[0 0 0 0]]}}}}
"Würfel" {"Würfel"
{:points (let [a 20 b -20 c 20 d -20 e 20 f -20]
[[a a d e] [b a d e] [b b d e] [a b d e]
[a a c f] [b a c f] [b b c f] [a b c f]])
:connections {0 [1 3 4], 1 [2 5], 2 [3 6], 3 [7], 4 [5 7], 5 [6], 6 [7]}
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [3 4]
:deg 0.5
:center {:type :points
:value [[0 0 0 0]]}}}}
"Pentachoron" {"Pentachoron"
{:points (mapv (fn [v] (mapv (partial * 30) v))
[[1 1 1 -1] [1 -1 -1 -1] [-1 1 -1 -1]
[-1 -1 1 -1] [0 0 0 (- (math/sqrt 5) 1)]])
:connections {0 [1 2 3 4], 1 [2 3 4], 2 [3 4], 3 [4]}
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [1 2]
:deg 0.4
:center {:type :points
:value [[0 0 0 0] [0 0 0 20]
[0 0 20 0]]}}}}})
| 115541 | (ns drawer.scenes
(:require [drawer.api :as api]
[drawer.geometry :as g]
[drawer.math :as math]
[drawer.lang :as lang]))
(def seminar-scenes
"The scenes used for the seminary work."
{"Punkt" {"Punkt"
{:points [[20 20 0 0]]
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [1 4]
:deg 0.5
:center {:type :points
:value [[0 0 0 0]]}}}}
"<NAME>el" {"<NAME>"
{:points (let [a 20 b -20 c 20 d -20 e 20 f -20]
[[a a d e] [b a d e] [b b d e] [a b d e]
[a a c f] [b a c f] [b b c f] [a b c f]])
:connections {0 [1 3 4], 1 [2 5], 2 [3 6], 3 [7], 4 [5 7], 5 [6], 6 [7]}
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [3 4]
:deg 0.5
:center {:type :points
:value [[0 0 0 0]]}}}}
"<NAME>" {"<NAME>"
{:points (mapv (fn [v] (mapv (partial * 30) v))
[[1 1 1 -1] [1 -1 -1 -1] [-1 1 -1 -1]
[-1 -1 1 -1] [0 0 0 (- (math/sqrt 5) 1)]])
:connections {0 [1 2 3 4], 1 [2 3 4], 2 [3 4], 3 [4]}
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [1 2]
:deg 0.4
:center {:type :points
:value [[0 0 0 0] [0 0 0 20]
[0 0 20 0]]}}}}})
| true | (ns drawer.scenes
(:require [drawer.api :as api]
[drawer.geometry :as g]
[drawer.math :as math]
[drawer.lang :as lang]))
(def seminar-scenes
"The scenes used for the seminary work."
{"Punkt" {"Punkt"
{:points [[20 20 0 0]]
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [1 4]
:deg 0.5
:center {:type :points
:value [[0 0 0 0]]}}}}
"PI:NAME:<NAME>END_PIel" {"PI:NAME:<NAME>END_PI"
{:points (let [a 20 b -20 c 20 d -20 e 20 f -20]
[[a a d e] [b a d e] [b b d e] [a b d e]
[a a c f] [b a c f] [b b c f] [a b c f]])
:connections {0 [1 3 4], 1 [2 5], 2 [3 6], 3 [7], 4 [5 7], 5 [6], 6 [7]}
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [3 4]
:deg 0.5
:center {:type :points
:value [[0 0 0 0]]}}}}
"PI:NAME:<NAME>END_PI" {"PI:NAME:<NAME>END_PI"
{:points (mapv (fn [v] (mapv (partial * 30) v))
[[1 1 1 -1] [1 -1 -1 -1] [-1 1 -1 -1]
[-1 -1 1 -1] [0 0 0 (- (math/sqrt 5) 1)]])
:connections {0 [1 2 3 4], 1 [2 3 4], 2 [3 4], 3 [4]}
:rotation {:active true
:max-deg nil
:done-deg 0
:plane [1 2]
:deg 0.4
:center {:type :points
:value [[0 0 0 0] [0 0 0 20]
[0 0 20 0]]}}}}})
|
[
{
"context": "\n :trailers {\"Meta\" \"test\"}\n :body {:key \"clojure is awesome\"}})\n\n(defn- echo-params [{{:keys [content]} :para",
"end": 1589,
"score": 0.9404212832450867,
"start": 1571,
"tag": "KEY",
"value": "clojure is awesome"
},
{
"context": " :key-password \"password\"}}]\n\n (let [server (http/create-server desc)]\n",
"end": 3813,
"score": 0.9620901346206665,
"start": 3805,
"tag": "PASSWORD",
"value": "password"
}
] | test/test/protojure/pedestal_test.clj | gitslim/lib | 0 | ;; Copyright © 2019 State Street Bank and Trust Company. All rights reserved
;; Copyright © 2019-2022 Manetu, Inc. All rights reserved
;;
;; SPDX-License-Identifier: Apache-2.0
(ns protojure.pedestal-test
(:require [clojure.test :refer :all]
[clojure.core.async :as async :refer [go >! <!! >!!]]
[io.pedestal.http :as http]
[io.pedestal.http.body-params :as body-params]
[protojure.pedestal.core :as protojure.pedestal]
[protojure.test.utils :as test.utils]
[protojure.internal.io :as pio]
[clj-http.client :as client]
[clojure.java.io :as io])
(:import [java.nio ByteBuffer]))
;;-----------------------------------------------------------------------------
;; Data
;;-----------------------------------------------------------------------------
(defonce test-svc (atom {}))
(defn- get-healthz [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body "OK"})
(defn- get-bytes [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body (byte-array [(byte 0x43)
(byte 0x6c)
(byte 0x6f)
(byte 0x6a)
(byte 0x75)
(byte 0x72)
(byte 0x65)
(byte 0x21)])})
(defn- get-edn [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body {:key "clojure is awesome"}})
(defn- echo-params [{{:keys [content]} :params}]
{:status 200 :body content})
(defn- echo-body [{:keys [body]}]
{:status 200 :body body})
(defn- echo-async [{{:keys [content]} :params}]
(let [ch (async/chan 1)]
(go
(>! ch (byte-array (map byte content)))
(async/close! ch))
{:status 200 :body ch}))
(defn- testdata-download [_]
{:status 200 :body (io/as-file (io/resource "testdata.txt"))})
(defn routes [interceptors]
[["/healthz" :get (conj interceptors `get-healthz)]
["/echo" :get (conj interceptors `echo-params)]
["/echo" :post (conj interceptors `echo-body)]
["/echo/async" :get (conj interceptors `echo-async)]
["/testdata" :get (conj interceptors `testdata-download)]
["/bytes" :get (conj interceptors `get-bytes)]
["/edn" :get (conj interceptors `get-edn)]])
;;-----------------------------------------------------------------------------
;; Utilities
;;-----------------------------------------------------------------------------
(defn service-url
[& rest]
(apply str "http://localhost:" (:port @test-svc) rest))
(defn service-url-ssl
[& rest]
(apply str "https://localhost:" (:ssl-port @test-svc) rest))
;;-----------------------------------------------------------------------------
;; Fixtures
;;-----------------------------------------------------------------------------
(defn create-service []
(let [port (test.utils/get-free-port)
ssl-port (test.utils/get-free-port)
interceptors [(body-params/body-params)
http/html-body]
desc {:env :prod
::http/routes (into #{} (routes interceptors))
::http/port port
::http/type protojure.pedestal/config
::http/chain-provider protojure.pedestal/provider
::http/container-options {:ssl-port ssl-port
; keystore may be either string denoting file path (relative or
; absolute) or actual KeyStore instance
:keystore (io/resource "https/keystore.jks")
:key-password "password"}}]
(let [server (http/create-server desc)]
(http/start server)
(swap! test-svc assoc :port port :ssl-port ssl-port :server server))))
(defn destroy-service []
(swap! test-svc update :server http/stop))
(defn wrap-service [test-fn]
(create-service)
(test-fn)
(destroy-service))
(use-fixtures :once wrap-service)
;;-----------------------------------------------------------------------------
;; Tests
;;-----------------------------------------------------------------------------
(deftest healthz-check
(testing "Check that basic connectivity works"
(is (-> (client/get (service-url "/healthz")) :body (= "OK")))))
(comment deftest ssl-check ;; FIXME: re-enable after we figure out why it fails on new JDK
(testing "Check that SSL works"
(is (-> (client/get (service-url-ssl "/healthz") {:insecure? true}) :body (= "OK")))))
(deftest query-param-check
(testing "Check that query-parameters work"
(is (-> (client/get (service-url "/echo") {:query-params {"content" "FOO"}}) :body (= "FOO")))))
(deftest body-check
(testing "Check that response/request body work"
(is (-> (client/post (service-url "/echo") {:body "BAR"}) :body (= "BAR")))))
(deftest async-check
(testing "Check that async-body works"
(is (-> (client/get (service-url "/echo/async") {:query-params {"content" "FOO"}}) :body (= "FOO")))))
(deftest file-download-check
(testing "Check that we can download a file"
(is (->> (client/get (service-url "/testdata")) :body (re-find #"testdata!") some?))))
(deftest bytes-check
(testing "Check that bytes transfer correctly"
(is (-> (client/get (service-url "/bytes")) :body (= "Clojure!")))))
(deftest edn-check
(testing "Check that EDN format transfers"
(is (-> (client/get (service-url "/edn")) :body clojure.edn/read-string (= {:key "clojure is awesome"})))))
(deftest notfound-check
(testing "Check that a request for an invalid resource correctly propagates the error code"
(is (thrown? clojure.lang.ExceptionInfo (client/get (service-url "/invalid"))))))
(deftest read-check
(testing "Check that bytes entered to channel are properly read from InputStream"
(let [test-string "Hello"
test-channel (async/chan 8096)
in-stream (pio/new-inputstream {:ch test-channel})
buff (byte-array 5)]
(>!! test-channel (ByteBuffer/wrap (.getBytes test-string)))
(async/close! test-channel)
(.read in-stream buff 0 5)
(is (= "Hello" (String. buff))))))
| 75464 | ;; Copyright © 2019 State Street Bank and Trust Company. All rights reserved
;; Copyright © 2019-2022 Manetu, Inc. All rights reserved
;;
;; SPDX-License-Identifier: Apache-2.0
(ns protojure.pedestal-test
(:require [clojure.test :refer :all]
[clojure.core.async :as async :refer [go >! <!! >!!]]
[io.pedestal.http :as http]
[io.pedestal.http.body-params :as body-params]
[protojure.pedestal.core :as protojure.pedestal]
[protojure.test.utils :as test.utils]
[protojure.internal.io :as pio]
[clj-http.client :as client]
[clojure.java.io :as io])
(:import [java.nio ByteBuffer]))
;;-----------------------------------------------------------------------------
;; Data
;;-----------------------------------------------------------------------------
(defonce test-svc (atom {}))
(defn- get-healthz [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body "OK"})
(defn- get-bytes [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body (byte-array [(byte 0x43)
(byte 0x6c)
(byte 0x6f)
(byte 0x6a)
(byte 0x75)
(byte 0x72)
(byte 0x65)
(byte 0x21)])})
(defn- get-edn [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body {:key "<KEY>"}})
(defn- echo-params [{{:keys [content]} :params}]
{:status 200 :body content})
(defn- echo-body [{:keys [body]}]
{:status 200 :body body})
(defn- echo-async [{{:keys [content]} :params}]
(let [ch (async/chan 1)]
(go
(>! ch (byte-array (map byte content)))
(async/close! ch))
{:status 200 :body ch}))
(defn- testdata-download [_]
{:status 200 :body (io/as-file (io/resource "testdata.txt"))})
(defn routes [interceptors]
[["/healthz" :get (conj interceptors `get-healthz)]
["/echo" :get (conj interceptors `echo-params)]
["/echo" :post (conj interceptors `echo-body)]
["/echo/async" :get (conj interceptors `echo-async)]
["/testdata" :get (conj interceptors `testdata-download)]
["/bytes" :get (conj interceptors `get-bytes)]
["/edn" :get (conj interceptors `get-edn)]])
;;-----------------------------------------------------------------------------
;; Utilities
;;-----------------------------------------------------------------------------
(defn service-url
[& rest]
(apply str "http://localhost:" (:port @test-svc) rest))
(defn service-url-ssl
[& rest]
(apply str "https://localhost:" (:ssl-port @test-svc) rest))
;;-----------------------------------------------------------------------------
;; Fixtures
;;-----------------------------------------------------------------------------
(defn create-service []
(let [port (test.utils/get-free-port)
ssl-port (test.utils/get-free-port)
interceptors [(body-params/body-params)
http/html-body]
desc {:env :prod
::http/routes (into #{} (routes interceptors))
::http/port port
::http/type protojure.pedestal/config
::http/chain-provider protojure.pedestal/provider
::http/container-options {:ssl-port ssl-port
; keystore may be either string denoting file path (relative or
; absolute) or actual KeyStore instance
:keystore (io/resource "https/keystore.jks")
:key-password "<PASSWORD>"}}]
(let [server (http/create-server desc)]
(http/start server)
(swap! test-svc assoc :port port :ssl-port ssl-port :server server))))
(defn destroy-service []
(swap! test-svc update :server http/stop))
(defn wrap-service [test-fn]
(create-service)
(test-fn)
(destroy-service))
(use-fixtures :once wrap-service)
;;-----------------------------------------------------------------------------
;; Tests
;;-----------------------------------------------------------------------------
(deftest healthz-check
(testing "Check that basic connectivity works"
(is (-> (client/get (service-url "/healthz")) :body (= "OK")))))
(comment deftest ssl-check ;; FIXME: re-enable after we figure out why it fails on new JDK
(testing "Check that SSL works"
(is (-> (client/get (service-url-ssl "/healthz") {:insecure? true}) :body (= "OK")))))
(deftest query-param-check
(testing "Check that query-parameters work"
(is (-> (client/get (service-url "/echo") {:query-params {"content" "FOO"}}) :body (= "FOO")))))
(deftest body-check
(testing "Check that response/request body work"
(is (-> (client/post (service-url "/echo") {:body "BAR"}) :body (= "BAR")))))
(deftest async-check
(testing "Check that async-body works"
(is (-> (client/get (service-url "/echo/async") {:query-params {"content" "FOO"}}) :body (= "FOO")))))
(deftest file-download-check
(testing "Check that we can download a file"
(is (->> (client/get (service-url "/testdata")) :body (re-find #"testdata!") some?))))
(deftest bytes-check
(testing "Check that bytes transfer correctly"
(is (-> (client/get (service-url "/bytes")) :body (= "Clojure!")))))
(deftest edn-check
(testing "Check that EDN format transfers"
(is (-> (client/get (service-url "/edn")) :body clojure.edn/read-string (= {:key "clojure is awesome"})))))
(deftest notfound-check
(testing "Check that a request for an invalid resource correctly propagates the error code"
(is (thrown? clojure.lang.ExceptionInfo (client/get (service-url "/invalid"))))))
(deftest read-check
(testing "Check that bytes entered to channel are properly read from InputStream"
(let [test-string "Hello"
test-channel (async/chan 8096)
in-stream (pio/new-inputstream {:ch test-channel})
buff (byte-array 5)]
(>!! test-channel (ByteBuffer/wrap (.getBytes test-string)))
(async/close! test-channel)
(.read in-stream buff 0 5)
(is (= "Hello" (String. buff))))))
| true | ;; Copyright © 2019 State Street Bank and Trust Company. All rights reserved
;; Copyright © 2019-2022 Manetu, Inc. All rights reserved
;;
;; SPDX-License-Identifier: Apache-2.0
(ns protojure.pedestal-test
(:require [clojure.test :refer :all]
[clojure.core.async :as async :refer [go >! <!! >!!]]
[io.pedestal.http :as http]
[io.pedestal.http.body-params :as body-params]
[protojure.pedestal.core :as protojure.pedestal]
[protojure.test.utils :as test.utils]
[protojure.internal.io :as pio]
[clj-http.client :as client]
[clojure.java.io :as io])
(:import [java.nio ByteBuffer]))
;;-----------------------------------------------------------------------------
;; Data
;;-----------------------------------------------------------------------------
(defonce test-svc (atom {}))
(defn- get-healthz [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body "OK"})
(defn- get-bytes [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body (byte-array [(byte 0x43)
(byte 0x6c)
(byte 0x6f)
(byte 0x6a)
(byte 0x75)
(byte 0x72)
(byte 0x65)
(byte 0x21)])})
(defn- get-edn [_]
{:status 200
:headers {"Content-Type" "application/text"}
:trailers {"Meta" "test"}
:body {:key "PI:KEY:<KEY>END_PI"}})
(defn- echo-params [{{:keys [content]} :params}]
{:status 200 :body content})
(defn- echo-body [{:keys [body]}]
{:status 200 :body body})
(defn- echo-async [{{:keys [content]} :params}]
(let [ch (async/chan 1)]
(go
(>! ch (byte-array (map byte content)))
(async/close! ch))
{:status 200 :body ch}))
(defn- testdata-download [_]
{:status 200 :body (io/as-file (io/resource "testdata.txt"))})
(defn routes [interceptors]
[["/healthz" :get (conj interceptors `get-healthz)]
["/echo" :get (conj interceptors `echo-params)]
["/echo" :post (conj interceptors `echo-body)]
["/echo/async" :get (conj interceptors `echo-async)]
["/testdata" :get (conj interceptors `testdata-download)]
["/bytes" :get (conj interceptors `get-bytes)]
["/edn" :get (conj interceptors `get-edn)]])
;;-----------------------------------------------------------------------------
;; Utilities
;;-----------------------------------------------------------------------------
(defn service-url
[& rest]
(apply str "http://localhost:" (:port @test-svc) rest))
(defn service-url-ssl
[& rest]
(apply str "https://localhost:" (:ssl-port @test-svc) rest))
;;-----------------------------------------------------------------------------
;; Fixtures
;;-----------------------------------------------------------------------------
(defn create-service []
(let [port (test.utils/get-free-port)
ssl-port (test.utils/get-free-port)
interceptors [(body-params/body-params)
http/html-body]
desc {:env :prod
::http/routes (into #{} (routes interceptors))
::http/port port
::http/type protojure.pedestal/config
::http/chain-provider protojure.pedestal/provider
::http/container-options {:ssl-port ssl-port
; keystore may be either string denoting file path (relative or
; absolute) or actual KeyStore instance
:keystore (io/resource "https/keystore.jks")
:key-password "PI:PASSWORD:<PASSWORD>END_PI"}}]
(let [server (http/create-server desc)]
(http/start server)
(swap! test-svc assoc :port port :ssl-port ssl-port :server server))))
(defn destroy-service []
(swap! test-svc update :server http/stop))
(defn wrap-service [test-fn]
(create-service)
(test-fn)
(destroy-service))
(use-fixtures :once wrap-service)
;;-----------------------------------------------------------------------------
;; Tests
;;-----------------------------------------------------------------------------
(deftest healthz-check
(testing "Check that basic connectivity works"
(is (-> (client/get (service-url "/healthz")) :body (= "OK")))))
(comment deftest ssl-check ;; FIXME: re-enable after we figure out why it fails on new JDK
(testing "Check that SSL works"
(is (-> (client/get (service-url-ssl "/healthz") {:insecure? true}) :body (= "OK")))))
(deftest query-param-check
(testing "Check that query-parameters work"
(is (-> (client/get (service-url "/echo") {:query-params {"content" "FOO"}}) :body (= "FOO")))))
(deftest body-check
(testing "Check that response/request body work"
(is (-> (client/post (service-url "/echo") {:body "BAR"}) :body (= "BAR")))))
(deftest async-check
(testing "Check that async-body works"
(is (-> (client/get (service-url "/echo/async") {:query-params {"content" "FOO"}}) :body (= "FOO")))))
(deftest file-download-check
(testing "Check that we can download a file"
(is (->> (client/get (service-url "/testdata")) :body (re-find #"testdata!") some?))))
(deftest bytes-check
(testing "Check that bytes transfer correctly"
(is (-> (client/get (service-url "/bytes")) :body (= "Clojure!")))))
(deftest edn-check
(testing "Check that EDN format transfers"
(is (-> (client/get (service-url "/edn")) :body clojure.edn/read-string (= {:key "clojure is awesome"})))))
(deftest notfound-check
(testing "Check that a request for an invalid resource correctly propagates the error code"
(is (thrown? clojure.lang.ExceptionInfo (client/get (service-url "/invalid"))))))
(deftest read-check
(testing "Check that bytes entered to channel are properly read from InputStream"
(let [test-string "Hello"
test-channel (async/chan 8096)
in-stream (pio/new-inputstream {:ch test-channel})
buff (byte-array 5)]
(>!! test-channel (ByteBuffer/wrap (.getBytes test-string)))
(async/close! test-channel)
(.read in-stream buff 0 5)
(is (= "Hello" (String. buff))))))
|
[
{
"context": "ubprotocol \"postgresql\"\n :subname \"//127.0.0.1:5432/pgtest\"\n :user \"pgtest\"\n ",
"end": 354,
"score": 0.9983068108558655,
"start": 345,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " :user \"pgtest\"\n :password \"pgtest\"})\n\n(def basic-config {:db db-spec})\n\n(def config",
"end": 428,
"score": 0.999504804611206,
"start": 422,
"tag": "PASSWORD",
"value": "pgtest"
}
] | test/pgqueue/core_test.clj | tomjkidd/pgqueue | 70 | (ns pgqueue.core-test
(:require [clojure.test :refer :all]
[pgqueue.core :as pgq]
[pgqueue.serializer.nippy :as nippy-serializer]
[pgqueue.serializer.fressian :as fressian-serializer]);
(:import [pgqueue.core PGQueue PGQueueLockedItem]))
(def db-spec {:subprotocol "postgresql"
:subname "//127.0.0.1:5432/pgtest"
:user "pgtest"
:password "pgtest"})
(def basic-config {:db db-spec})
(def configs
{:basic basic-config
:no-delete (merge basic-config
{:schema "public"
:table "no_delete_queues"
:delete false})
:nippy (merge basic-config
{:schema "public"
:table "nippy_queues"
:serializer (nippy-serializer/nippy-serializer)})
:fressian (merge basic-config
{:schema "public"
:table "fressian_queues"
:serializer (fressian-serializer/fressian-serializer)})})
(deftest pgqueue-basic-tests
(doseq [[name config] configs]
(testing (str "pgqueue w/ config: " name)
(let [q (pgq/queue :test config)]
(testing "queue"
(is (instance? PGQueue q)))
(testing "put, take, count"
(is (= 0 (pgq/count q)))
(is (= true (pgq/put q 1)))
(is (= 1 (pgq/count q)))
(is (= 1 (pgq/take q)))
(is (= 0 (pgq/count q)))
(is (= nil (pgq/take q)))
(is (= true (pgq/put q [1 2])))
(is (= [1 2] (pgq/take q)))
(is (= true (pgq/put q {:a 1})))
(is (= {:a 1} (pgq/take q)))
(testing "put nil"
(is (= 0 (pgq/count q)))
(is (= nil (pgq/put q nil)))
(is (= 0 (pgq/count q)))))
(testing "priority"
(dotimes [n 50] (pgq/put q (- 50 n) n))
(is (= 50 (pgq/count q)))
(is (= 49 (pgq/take q)))
(is (= 48 (pgq/take q)))
(dotimes [n 47] (pgq/take q))
(is (= 0 (pgq/take q)))
(is (= 0 (pgq/count q)))
(is (= nil (pgq/take q))))
(testing "take-with"
(pgq/put q :a)
(pgq/take-with [item q]
(is (= :a item))))
(testing "put-batch, take-batch"
(is (= true (pgq/put-batch q (range 4))))
(is (= 4 (pgq/count q)))
(is (= [0 1 2] (pgq/take-batch q 3)))
(is (= 3 (pgq/take q))))
(testing "delete behavior"
(if (= name :no-delete)
(do (pgq/purge-deleted q)
(is (= true (pgq/put q :a)))
(is (= 1 (pgq/count q)))
(is (= :a (pgq/take q)))
(is (= 1 (pgq/count-deleted q)))
(is (= 1 (pgq/purge-deleted q)))
(is (= 0 (pgq/count-deleted q))))
(do (is (= true (pgq/put q :b)))
(is (= 1 (pgq/count q)))
(is (= 0 (pgq/count-deleted q)))
(is (= :b (pgq/take q)))
(is (= 0 (pgq/count-deleted q))))))
(testing "destroying"
(pgq/destroy-queue! q)
(pgq/destroy-all-queues! config))))))
(defn put-in-new-thread
[name config item]
(deref
(future
(let [q (pgq/queue name config)]
(pgq/put q item)))))
(defn take-in-new-thread
[name config]
(deref
(future
(let [q (pgq/queue name config)]
(pgq/take q)))))
(deftest pgqueue-concurrent-tests
(testing "concurrent takers"
(let [c (:basic configs)
q (pgq/queue :test-concurrent c)]
(testing "locking-take"
(pgq/put q :a)
(pgq/put q :b)
(let [locked-item (pgq/locking-take q)]
(is (instance? PGQueueLockedItem locked-item))
(is (= :a (get-in locked-item [:item :data])))
(testing "different thread CAN NOT take locked item"
(is (= :b (take-in-new-thread :test-concurrent c))))
(testing "same thread CAN NOT re-take the item"
(is (not (= :a (pgq/take q)))))
(is (= true (pgq/delete (:item locked-item))))
(is (= true (pgq/unlock (:lock locked-item))))
))
(testing "take-with"
(pgq/put q :c)
(pgq/put q :d)
(pgq/take-with [item q]
(is (= :c item))
(testing "nested take in different thread CAN NOT take same locked item"
(is (not (= :c (take-in-new-thread :test-concurrent c)))))
(testing "nested take-with in same thread CAN NOT re-take same locked item"
(pgq/take-with [item q]
(is (not (= :c item)))))))
(testing "ensure failure during work is safe"
(pgq/put q :failme)
(is (thrown? clojure.lang.ExceptionInfo
(pgq/take-with [item q]
(throw (ex-info "failure when we have item locked" {})))))
(is (= :failme (pgq/take q))))
(pgq/destroy-queue! q)
(pgq/destroy-all-queues! c))))
| 41654 | (ns pgqueue.core-test
(:require [clojure.test :refer :all]
[pgqueue.core :as pgq]
[pgqueue.serializer.nippy :as nippy-serializer]
[pgqueue.serializer.fressian :as fressian-serializer]);
(:import [pgqueue.core PGQueue PGQueueLockedItem]))
(def db-spec {:subprotocol "postgresql"
:subname "//127.0.0.1:5432/pgtest"
:user "pgtest"
:password "<PASSWORD>"})
(def basic-config {:db db-spec})
(def configs
{:basic basic-config
:no-delete (merge basic-config
{:schema "public"
:table "no_delete_queues"
:delete false})
:nippy (merge basic-config
{:schema "public"
:table "nippy_queues"
:serializer (nippy-serializer/nippy-serializer)})
:fressian (merge basic-config
{:schema "public"
:table "fressian_queues"
:serializer (fressian-serializer/fressian-serializer)})})
(deftest pgqueue-basic-tests
(doseq [[name config] configs]
(testing (str "pgqueue w/ config: " name)
(let [q (pgq/queue :test config)]
(testing "queue"
(is (instance? PGQueue q)))
(testing "put, take, count"
(is (= 0 (pgq/count q)))
(is (= true (pgq/put q 1)))
(is (= 1 (pgq/count q)))
(is (= 1 (pgq/take q)))
(is (= 0 (pgq/count q)))
(is (= nil (pgq/take q)))
(is (= true (pgq/put q [1 2])))
(is (= [1 2] (pgq/take q)))
(is (= true (pgq/put q {:a 1})))
(is (= {:a 1} (pgq/take q)))
(testing "put nil"
(is (= 0 (pgq/count q)))
(is (= nil (pgq/put q nil)))
(is (= 0 (pgq/count q)))))
(testing "priority"
(dotimes [n 50] (pgq/put q (- 50 n) n))
(is (= 50 (pgq/count q)))
(is (= 49 (pgq/take q)))
(is (= 48 (pgq/take q)))
(dotimes [n 47] (pgq/take q))
(is (= 0 (pgq/take q)))
(is (= 0 (pgq/count q)))
(is (= nil (pgq/take q))))
(testing "take-with"
(pgq/put q :a)
(pgq/take-with [item q]
(is (= :a item))))
(testing "put-batch, take-batch"
(is (= true (pgq/put-batch q (range 4))))
(is (= 4 (pgq/count q)))
(is (= [0 1 2] (pgq/take-batch q 3)))
(is (= 3 (pgq/take q))))
(testing "delete behavior"
(if (= name :no-delete)
(do (pgq/purge-deleted q)
(is (= true (pgq/put q :a)))
(is (= 1 (pgq/count q)))
(is (= :a (pgq/take q)))
(is (= 1 (pgq/count-deleted q)))
(is (= 1 (pgq/purge-deleted q)))
(is (= 0 (pgq/count-deleted q))))
(do (is (= true (pgq/put q :b)))
(is (= 1 (pgq/count q)))
(is (= 0 (pgq/count-deleted q)))
(is (= :b (pgq/take q)))
(is (= 0 (pgq/count-deleted q))))))
(testing "destroying"
(pgq/destroy-queue! q)
(pgq/destroy-all-queues! config))))))
(defn put-in-new-thread
[name config item]
(deref
(future
(let [q (pgq/queue name config)]
(pgq/put q item)))))
(defn take-in-new-thread
[name config]
(deref
(future
(let [q (pgq/queue name config)]
(pgq/take q)))))
(deftest pgqueue-concurrent-tests
(testing "concurrent takers"
(let [c (:basic configs)
q (pgq/queue :test-concurrent c)]
(testing "locking-take"
(pgq/put q :a)
(pgq/put q :b)
(let [locked-item (pgq/locking-take q)]
(is (instance? PGQueueLockedItem locked-item))
(is (= :a (get-in locked-item [:item :data])))
(testing "different thread CAN NOT take locked item"
(is (= :b (take-in-new-thread :test-concurrent c))))
(testing "same thread CAN NOT re-take the item"
(is (not (= :a (pgq/take q)))))
(is (= true (pgq/delete (:item locked-item))))
(is (= true (pgq/unlock (:lock locked-item))))
))
(testing "take-with"
(pgq/put q :c)
(pgq/put q :d)
(pgq/take-with [item q]
(is (= :c item))
(testing "nested take in different thread CAN NOT take same locked item"
(is (not (= :c (take-in-new-thread :test-concurrent c)))))
(testing "nested take-with in same thread CAN NOT re-take same locked item"
(pgq/take-with [item q]
(is (not (= :c item)))))))
(testing "ensure failure during work is safe"
(pgq/put q :failme)
(is (thrown? clojure.lang.ExceptionInfo
(pgq/take-with [item q]
(throw (ex-info "failure when we have item locked" {})))))
(is (= :failme (pgq/take q))))
(pgq/destroy-queue! q)
(pgq/destroy-all-queues! c))))
| true | (ns pgqueue.core-test
(:require [clojure.test :refer :all]
[pgqueue.core :as pgq]
[pgqueue.serializer.nippy :as nippy-serializer]
[pgqueue.serializer.fressian :as fressian-serializer]);
(:import [pgqueue.core PGQueue PGQueueLockedItem]))
(def db-spec {:subprotocol "postgresql"
:subname "//127.0.0.1:5432/pgtest"
:user "pgtest"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(def basic-config {:db db-spec})
(def configs
{:basic basic-config
:no-delete (merge basic-config
{:schema "public"
:table "no_delete_queues"
:delete false})
:nippy (merge basic-config
{:schema "public"
:table "nippy_queues"
:serializer (nippy-serializer/nippy-serializer)})
:fressian (merge basic-config
{:schema "public"
:table "fressian_queues"
:serializer (fressian-serializer/fressian-serializer)})})
(deftest pgqueue-basic-tests
(doseq [[name config] configs]
(testing (str "pgqueue w/ config: " name)
(let [q (pgq/queue :test config)]
(testing "queue"
(is (instance? PGQueue q)))
(testing "put, take, count"
(is (= 0 (pgq/count q)))
(is (= true (pgq/put q 1)))
(is (= 1 (pgq/count q)))
(is (= 1 (pgq/take q)))
(is (= 0 (pgq/count q)))
(is (= nil (pgq/take q)))
(is (= true (pgq/put q [1 2])))
(is (= [1 2] (pgq/take q)))
(is (= true (pgq/put q {:a 1})))
(is (= {:a 1} (pgq/take q)))
(testing "put nil"
(is (= 0 (pgq/count q)))
(is (= nil (pgq/put q nil)))
(is (= 0 (pgq/count q)))))
(testing "priority"
(dotimes [n 50] (pgq/put q (- 50 n) n))
(is (= 50 (pgq/count q)))
(is (= 49 (pgq/take q)))
(is (= 48 (pgq/take q)))
(dotimes [n 47] (pgq/take q))
(is (= 0 (pgq/take q)))
(is (= 0 (pgq/count q)))
(is (= nil (pgq/take q))))
(testing "take-with"
(pgq/put q :a)
(pgq/take-with [item q]
(is (= :a item))))
(testing "put-batch, take-batch"
(is (= true (pgq/put-batch q (range 4))))
(is (= 4 (pgq/count q)))
(is (= [0 1 2] (pgq/take-batch q 3)))
(is (= 3 (pgq/take q))))
(testing "delete behavior"
(if (= name :no-delete)
(do (pgq/purge-deleted q)
(is (= true (pgq/put q :a)))
(is (= 1 (pgq/count q)))
(is (= :a (pgq/take q)))
(is (= 1 (pgq/count-deleted q)))
(is (= 1 (pgq/purge-deleted q)))
(is (= 0 (pgq/count-deleted q))))
(do (is (= true (pgq/put q :b)))
(is (= 1 (pgq/count q)))
(is (= 0 (pgq/count-deleted q)))
(is (= :b (pgq/take q)))
(is (= 0 (pgq/count-deleted q))))))
(testing "destroying"
(pgq/destroy-queue! q)
(pgq/destroy-all-queues! config))))))
(defn put-in-new-thread
[name config item]
(deref
(future
(let [q (pgq/queue name config)]
(pgq/put q item)))))
(defn take-in-new-thread
[name config]
(deref
(future
(let [q (pgq/queue name config)]
(pgq/take q)))))
(deftest pgqueue-concurrent-tests
(testing "concurrent takers"
(let [c (:basic configs)
q (pgq/queue :test-concurrent c)]
(testing "locking-take"
(pgq/put q :a)
(pgq/put q :b)
(let [locked-item (pgq/locking-take q)]
(is (instance? PGQueueLockedItem locked-item))
(is (= :a (get-in locked-item [:item :data])))
(testing "different thread CAN NOT take locked item"
(is (= :b (take-in-new-thread :test-concurrent c))))
(testing "same thread CAN NOT re-take the item"
(is (not (= :a (pgq/take q)))))
(is (= true (pgq/delete (:item locked-item))))
(is (= true (pgq/unlock (:lock locked-item))))
))
(testing "take-with"
(pgq/put q :c)
(pgq/put q :d)
(pgq/take-with [item q]
(is (= :c item))
(testing "nested take in different thread CAN NOT take same locked item"
(is (not (= :c (take-in-new-thread :test-concurrent c)))))
(testing "nested take-with in same thread CAN NOT re-take same locked item"
(pgq/take-with [item q]
(is (not (= :c item)))))))
(testing "ensure failure during work is safe"
(pgq/put q :failme)
(is (thrown? clojure.lang.ExceptionInfo
(pgq/take-with [item q]
(throw (ex-info "failure when we have item locked" {})))))
(is (= :failme (pgq/take q))))
(pgq/destroy-queue! q)
(pgq/destroy-all-queues! c))))
|
[
{
"context": ";;; Copyright 2019 Mitchell Kember. Subject to the MIT License.\n\n(ns twenty48.ui\n (",
"end": 34,
"score": 0.9998891949653625,
"start": 19,
"tag": "NAME",
"value": "Mitchell Kember"
}
] | src/twenty48/ui.clj | mk12/twenty48 | 0 | ;;; Copyright 2019 Mitchell Kember. Subject to the MIT License.
(ns twenty48.ui
(:require [clojure.java.io :as io]
[seesaw.core :as s]
[seesaw.icon :as i]
[twenty48.common :as c]))
;;;;; Frame and views
(defn frame
"Creates the application's one and only frame."
[env]
(s/frame :title "Twenty48"
:size [600 :by 700]
:on-close ({:dev :hide, :prod :exit} env)))
(defn show-view!
"Shows a new view."
[sys view]
(s/config! (:frame @sys) :content view)
(s/request-focus! view))
(defn show-view-by-id!
"Gets the view with the given identifier from the system and shows it."
[sys id]
(show-view! sys (force (get-in @sys [:views id]))))
;;;;; HiDPI display support
(defn display-scale-factor
"Returns the display scale factor (1 for non-HiDPI displays)."
[]
(let [device (.. java.awt.GraphicsEnvironment
getLocalGraphicsEnvironment
getDefaultScreenDevice)]
(try
(.getScaleFactor device)
(catch IllegalArgumentException e 1))))
(defn hidpi-icon
"Creates an ImageIcon with HiDPI support using the @2x image file."
[filename extension]
(let [scale-factor (display-scale-factor)]
(if (<= scale-factor 1)
(-> (str filename "." extension) io/resource io/file i/icon)
(let [image-2x (-> (str filename "@2x." extension)
io/resource
javax.imageio.ImageIO/read)]
(proxy [javax.swing.ImageIcon] [image-2x]
(getIconWidth []
(c/round (/ (proxy-super getIconWidth) scale-factor)))
(getIconHeight []
(c/round (/ (proxy-super getIconHeight) scale-factor)))
(paintIcon [c ^java.awt.Graphics2D g x y]
(let [^java.awt.Graphics2D g2 (.create g)
recip (/ 1.0 scale-factor)]
(.scale g2 recip recip)
(proxy-super
paintIcon c g2 (* scale-factor x) (* scale-factor y))
(.dispose g2))))))))
;;;;; User interface elements
(defn label
"Creates a label with the given text and font size. Extra arguments are passed
on to seesaw.core/label (they must be key/value pairs)."
[text size & more]
(apply s/label
:text text
:font {:name "Lucida Grande" :size size}
more))
(defn slider
"Creates a slider with the most important options set. Extra arguments are
passed on to seesaw.core/slider (they must be key/value pairs)."
[from to major minor & more]
(apply s/slider
:min from
:max to
:major-tick-spacing major
:minor-tick-spacing minor
:snap-to-ticks? true
:paint-labels? true
:paint-ticks? true
more))
(defn image
"Loads an image located at the given path relative to the resouces folder.
Returns a component containing the image. Extra arugments are passed on to
seesaw.core/label (they must be key/value pairs)."
[filename extension & more]
(apply s/label
:icon (hidpi-icon filename extension)
more))
(defn button
"Creates a button with an action handler. Extra arugments are passed on to
seesaw.core/button (they must be key/value pairs)."
[text action & more]
(apply s/button
:text text
:size [80 :by 40]
:listen [:action action]
more))
(defn nav-button
"Creates a button for navigating to the screen with the given identifer."
[sys id text]
(letfn [(action [_] (show-view-by-id! sys id))]
(s/button :text text
:size [80 :by 40]
:listen [:action action])))
| 103713 | ;;; Copyright 2019 <NAME>. Subject to the MIT License.
(ns twenty48.ui
(:require [clojure.java.io :as io]
[seesaw.core :as s]
[seesaw.icon :as i]
[twenty48.common :as c]))
;;;;; Frame and views
(defn frame
"Creates the application's one and only frame."
[env]
(s/frame :title "Twenty48"
:size [600 :by 700]
:on-close ({:dev :hide, :prod :exit} env)))
(defn show-view!
"Shows a new view."
[sys view]
(s/config! (:frame @sys) :content view)
(s/request-focus! view))
(defn show-view-by-id!
"Gets the view with the given identifier from the system and shows it."
[sys id]
(show-view! sys (force (get-in @sys [:views id]))))
;;;;; HiDPI display support
(defn display-scale-factor
"Returns the display scale factor (1 for non-HiDPI displays)."
[]
(let [device (.. java.awt.GraphicsEnvironment
getLocalGraphicsEnvironment
getDefaultScreenDevice)]
(try
(.getScaleFactor device)
(catch IllegalArgumentException e 1))))
(defn hidpi-icon
"Creates an ImageIcon with HiDPI support using the @2x image file."
[filename extension]
(let [scale-factor (display-scale-factor)]
(if (<= scale-factor 1)
(-> (str filename "." extension) io/resource io/file i/icon)
(let [image-2x (-> (str filename "@2x." extension)
io/resource
javax.imageio.ImageIO/read)]
(proxy [javax.swing.ImageIcon] [image-2x]
(getIconWidth []
(c/round (/ (proxy-super getIconWidth) scale-factor)))
(getIconHeight []
(c/round (/ (proxy-super getIconHeight) scale-factor)))
(paintIcon [c ^java.awt.Graphics2D g x y]
(let [^java.awt.Graphics2D g2 (.create g)
recip (/ 1.0 scale-factor)]
(.scale g2 recip recip)
(proxy-super
paintIcon c g2 (* scale-factor x) (* scale-factor y))
(.dispose g2))))))))
;;;;; User interface elements
(defn label
"Creates a label with the given text and font size. Extra arguments are passed
on to seesaw.core/label (they must be key/value pairs)."
[text size & more]
(apply s/label
:text text
:font {:name "Lucida Grande" :size size}
more))
(defn slider
"Creates a slider with the most important options set. Extra arguments are
passed on to seesaw.core/slider (they must be key/value pairs)."
[from to major minor & more]
(apply s/slider
:min from
:max to
:major-tick-spacing major
:minor-tick-spacing minor
:snap-to-ticks? true
:paint-labels? true
:paint-ticks? true
more))
(defn image
"Loads an image located at the given path relative to the resouces folder.
Returns a component containing the image. Extra arugments are passed on to
seesaw.core/label (they must be key/value pairs)."
[filename extension & more]
(apply s/label
:icon (hidpi-icon filename extension)
more))
(defn button
"Creates a button with an action handler. Extra arugments are passed on to
seesaw.core/button (they must be key/value pairs)."
[text action & more]
(apply s/button
:text text
:size [80 :by 40]
:listen [:action action]
more))
(defn nav-button
"Creates a button for navigating to the screen with the given identifer."
[sys id text]
(letfn [(action [_] (show-view-by-id! sys id))]
(s/button :text text
:size [80 :by 40]
:listen [:action action])))
| true | ;;; Copyright 2019 PI:NAME:<NAME>END_PI. Subject to the MIT License.
(ns twenty48.ui
(:require [clojure.java.io :as io]
[seesaw.core :as s]
[seesaw.icon :as i]
[twenty48.common :as c]))
;;;;; Frame and views
(defn frame
"Creates the application's one and only frame."
[env]
(s/frame :title "Twenty48"
:size [600 :by 700]
:on-close ({:dev :hide, :prod :exit} env)))
(defn show-view!
"Shows a new view."
[sys view]
(s/config! (:frame @sys) :content view)
(s/request-focus! view))
(defn show-view-by-id!
"Gets the view with the given identifier from the system and shows it."
[sys id]
(show-view! sys (force (get-in @sys [:views id]))))
;;;;; HiDPI display support
(defn display-scale-factor
"Returns the display scale factor (1 for non-HiDPI displays)."
[]
(let [device (.. java.awt.GraphicsEnvironment
getLocalGraphicsEnvironment
getDefaultScreenDevice)]
(try
(.getScaleFactor device)
(catch IllegalArgumentException e 1))))
(defn hidpi-icon
"Creates an ImageIcon with HiDPI support using the @2x image file."
[filename extension]
(let [scale-factor (display-scale-factor)]
(if (<= scale-factor 1)
(-> (str filename "." extension) io/resource io/file i/icon)
(let [image-2x (-> (str filename "@2x." extension)
io/resource
javax.imageio.ImageIO/read)]
(proxy [javax.swing.ImageIcon] [image-2x]
(getIconWidth []
(c/round (/ (proxy-super getIconWidth) scale-factor)))
(getIconHeight []
(c/round (/ (proxy-super getIconHeight) scale-factor)))
(paintIcon [c ^java.awt.Graphics2D g x y]
(let [^java.awt.Graphics2D g2 (.create g)
recip (/ 1.0 scale-factor)]
(.scale g2 recip recip)
(proxy-super
paintIcon c g2 (* scale-factor x) (* scale-factor y))
(.dispose g2))))))))
;;;;; User interface elements
(defn label
"Creates a label with the given text and font size. Extra arguments are passed
on to seesaw.core/label (they must be key/value pairs)."
[text size & more]
(apply s/label
:text text
:font {:name "Lucida Grande" :size size}
more))
(defn slider
"Creates a slider with the most important options set. Extra arguments are
passed on to seesaw.core/slider (they must be key/value pairs)."
[from to major minor & more]
(apply s/slider
:min from
:max to
:major-tick-spacing major
:minor-tick-spacing minor
:snap-to-ticks? true
:paint-labels? true
:paint-ticks? true
more))
(defn image
"Loads an image located at the given path relative to the resouces folder.
Returns a component containing the image. Extra arugments are passed on to
seesaw.core/label (they must be key/value pairs)."
[filename extension & more]
(apply s/label
:icon (hidpi-icon filename extension)
more))
(defn button
"Creates a button with an action handler. Extra arugments are passed on to
seesaw.core/button (they must be key/value pairs)."
[text action & more]
(apply s/button
:text text
:size [80 :by 40]
:listen [:action action]
more))
(defn nav-button
"Creates a button for navigating to the screen with the given identifer."
[sys id text]
(letfn [(action [_] (show-view-by-id! sys id))]
(s/button :text text
:size [80 :by 40]
:listen [:action action])))
|
[
{
"context": "; Copyright 2016-2019 Peter Schwarz\n;\n; Licensed under the Apache License, Version 2.",
"end": 35,
"score": 0.9998196363449097,
"start": 22,
"tag": "NAME",
"value": "Peter Schwarz"
}
] | test/virtua/core_test.cljs | peterschwarz/virtua | 4 | ; Copyright 2016-2019 Peter Schwarz
;
; 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 virtua.core-test
(:require [cljs.test :refer-macros [deftest testing async is are use-fixtures]]
[virtua.dom :refer [child-at child-count]]
[virtua.core :as v]
[virtua.test-utils :refer-macros [wait with-container]]
[goog.dom :as gdom]))
(defn text-content [el]
(when el
(gdom/getTextContent el)))
(defn tag [el]
(when el
(.. el -tagName toLowerCase)))
(defn css-class [el]
(when el
(.. el -className)))
(deftest test-render-single-element
(testing "rendering a simple element"
(with-container el
(v/attach! [:div "hello"] {} el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "hello" (-> (child-at el 0)
text-content))))))
(deftest test-render-nested-elements
(testing "rendering nested elements"
(with-container el
(v/attach!
[:div
[:p "paragraph1"]
[:p "paragraph2"]]
{}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 2 (child-count div)))
(is (= "paragraph1"
(-> (child-at div 0)
text-content)))
(is (= "paragraph2"
(-> (child-at div 1)
text-content)))))))
(deftest test-render-with-fn
(testing "rendering a function"
(with-container el
(v/attach!
(fn [_]
[:div
[:p "paragraph1"]])
{}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 1 (child-count div)))
(is (= "paragraph1"
(-> (child-at div 0)
text-content)))))))
(deftest test-render-with-fn-using-state
(testing "rendering a function using the state"
(with-container el
(v/attach!
(fn [state]
[:div (:text state)])
{:text "Test Text"}
el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "Test Text"
(-> (child-at el 0)
text-content))))))
(deftest test-render-with-nested-fn
(testing "rendering a function nested in the tree"
(with-container el
(let [a-component (fn [state] [:div (:text state)])]
(v/attach!
[:div a-component]
{:text "Component Text"}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 1 (child-count div)))
(is (= "div" (-> (child-at div 0) tag)))
(is (= "Component Text"
(-> (child-at div 0)
text-content))))))))
(deftest test-render-with-state-updates
(let [done identity] ; async done
(testing "rendering a function using atom state"
(with-container el
(let [app-state (atom {:text "Test Text"})]
(v/attach!
(fn [state]
[:div (:text state)])
app-state
el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "Test Text"
(-> (child-at el 0)
text-content)))
(swap! app-state assoc :text "Changed Text")
(do ;wait
(is (= "Changed Text"
(-> (child-at el 0)
text-content)))
(done)))))))
(deftest test-render-with-state-updates-additive
(let [done identity] ;async done
(testing "rendering a function using additive state change"
(with-container el
(let [app-state (atom {:show-it? false})]
(v/attach!
(fn [state]
[:ul
[:li "always shown"]
(when (:show-it? state) [:li "Now showing: additive"])])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(swap! app-state assoc :show-it? true)
(do; wait
(is (= 2 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(is (= "Now showing: additive"
(-> (child-at ul 1)
text-content)))
(done))))))))
(deftest test-render-with-state-updates-reductive
(let [done identity] ;async done
(testing "rendering a function using a reductive state change"
(with-container el
(let [app-state (atom {:show-it? true})]
(v/attach!
(fn [state]
[:ul
[:li "always shown"]
(when (:show-it? state) [:li "Now showing: reductive"])])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(is (= "Now showing: reductive"
(-> (child-at ul 1)
text-content)))
(swap! app-state assoc :show-it? false)
(do; wait
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(done))))))))
(deftest test-render-with-state-updates-insertive
(testing "rendering a function using a insertive state change"
(with-container el
(let [app-state (atom {:show-it? false})]
(v/attach!
(fn [state]
[:ul
(when (:show-it? state) [:li "Now showing: insertive"])
[:li "always shown"]])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(swap! app-state assoc :show-it? true)
(is (= 2 (child-count ul)))
(is (= "Now showing: insertive"
(-> (child-at ul 0)
text-content)))
(is (= "always shown"
(-> (child-at ul 1)
text-content))))))))
(deftest test-render-with-state-updates-attribute-change
(testing "rendering a change in attributes on a state change"
(with-container el
(let [app-state (atom {:classname "text-success"})]
(v/attach!
(fn [state]
[:p {:class (:classname state)} "Text"])
app-state
el)
(is (= 1 (child-count el)))
(let [p (child-at el 0)]
(is (= "text-success" (css-class p)))
(is (= "Text" (text-content p)))
(swap! app-state assoc :classname "text-danger")
(is (= "text-danger" (css-class p)))
(is (= "Text" (text-content p))))))))
| 80151 | ; Copyright 2016-2019 <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 virtua.core-test
(:require [cljs.test :refer-macros [deftest testing async is are use-fixtures]]
[virtua.dom :refer [child-at child-count]]
[virtua.core :as v]
[virtua.test-utils :refer-macros [wait with-container]]
[goog.dom :as gdom]))
(defn text-content [el]
(when el
(gdom/getTextContent el)))
(defn tag [el]
(when el
(.. el -tagName toLowerCase)))
(defn css-class [el]
(when el
(.. el -className)))
(deftest test-render-single-element
(testing "rendering a simple element"
(with-container el
(v/attach! [:div "hello"] {} el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "hello" (-> (child-at el 0)
text-content))))))
(deftest test-render-nested-elements
(testing "rendering nested elements"
(with-container el
(v/attach!
[:div
[:p "paragraph1"]
[:p "paragraph2"]]
{}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 2 (child-count div)))
(is (= "paragraph1"
(-> (child-at div 0)
text-content)))
(is (= "paragraph2"
(-> (child-at div 1)
text-content)))))))
(deftest test-render-with-fn
(testing "rendering a function"
(with-container el
(v/attach!
(fn [_]
[:div
[:p "paragraph1"]])
{}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 1 (child-count div)))
(is (= "paragraph1"
(-> (child-at div 0)
text-content)))))))
(deftest test-render-with-fn-using-state
(testing "rendering a function using the state"
(with-container el
(v/attach!
(fn [state]
[:div (:text state)])
{:text "Test Text"}
el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "Test Text"
(-> (child-at el 0)
text-content))))))
(deftest test-render-with-nested-fn
(testing "rendering a function nested in the tree"
(with-container el
(let [a-component (fn [state] [:div (:text state)])]
(v/attach!
[:div a-component]
{:text "Component Text"}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 1 (child-count div)))
(is (= "div" (-> (child-at div 0) tag)))
(is (= "Component Text"
(-> (child-at div 0)
text-content))))))))
(deftest test-render-with-state-updates
(let [done identity] ; async done
(testing "rendering a function using atom state"
(with-container el
(let [app-state (atom {:text "Test Text"})]
(v/attach!
(fn [state]
[:div (:text state)])
app-state
el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "Test Text"
(-> (child-at el 0)
text-content)))
(swap! app-state assoc :text "Changed Text")
(do ;wait
(is (= "Changed Text"
(-> (child-at el 0)
text-content)))
(done)))))))
(deftest test-render-with-state-updates-additive
(let [done identity] ;async done
(testing "rendering a function using additive state change"
(with-container el
(let [app-state (atom {:show-it? false})]
(v/attach!
(fn [state]
[:ul
[:li "always shown"]
(when (:show-it? state) [:li "Now showing: additive"])])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(swap! app-state assoc :show-it? true)
(do; wait
(is (= 2 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(is (= "Now showing: additive"
(-> (child-at ul 1)
text-content)))
(done))))))))
(deftest test-render-with-state-updates-reductive
(let [done identity] ;async done
(testing "rendering a function using a reductive state change"
(with-container el
(let [app-state (atom {:show-it? true})]
(v/attach!
(fn [state]
[:ul
[:li "always shown"]
(when (:show-it? state) [:li "Now showing: reductive"])])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(is (= "Now showing: reductive"
(-> (child-at ul 1)
text-content)))
(swap! app-state assoc :show-it? false)
(do; wait
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(done))))))))
(deftest test-render-with-state-updates-insertive
(testing "rendering a function using a insertive state change"
(with-container el
(let [app-state (atom {:show-it? false})]
(v/attach!
(fn [state]
[:ul
(when (:show-it? state) [:li "Now showing: insertive"])
[:li "always shown"]])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(swap! app-state assoc :show-it? true)
(is (= 2 (child-count ul)))
(is (= "Now showing: insertive"
(-> (child-at ul 0)
text-content)))
(is (= "always shown"
(-> (child-at ul 1)
text-content))))))))
(deftest test-render-with-state-updates-attribute-change
(testing "rendering a change in attributes on a state change"
(with-container el
(let [app-state (atom {:classname "text-success"})]
(v/attach!
(fn [state]
[:p {:class (:classname state)} "Text"])
app-state
el)
(is (= 1 (child-count el)))
(let [p (child-at el 0)]
(is (= "text-success" (css-class p)))
(is (= "Text" (text-content p)))
(swap! app-state assoc :classname "text-danger")
(is (= "text-danger" (css-class p)))
(is (= "Text" (text-content p))))))))
| true | ; Copyright 2016-2019 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 virtua.core-test
(:require [cljs.test :refer-macros [deftest testing async is are use-fixtures]]
[virtua.dom :refer [child-at child-count]]
[virtua.core :as v]
[virtua.test-utils :refer-macros [wait with-container]]
[goog.dom :as gdom]))
(defn text-content [el]
(when el
(gdom/getTextContent el)))
(defn tag [el]
(when el
(.. el -tagName toLowerCase)))
(defn css-class [el]
(when el
(.. el -className)))
(deftest test-render-single-element
(testing "rendering a simple element"
(with-container el
(v/attach! [:div "hello"] {} el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "hello" (-> (child-at el 0)
text-content))))))
(deftest test-render-nested-elements
(testing "rendering nested elements"
(with-container el
(v/attach!
[:div
[:p "paragraph1"]
[:p "paragraph2"]]
{}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 2 (child-count div)))
(is (= "paragraph1"
(-> (child-at div 0)
text-content)))
(is (= "paragraph2"
(-> (child-at div 1)
text-content)))))))
(deftest test-render-with-fn
(testing "rendering a function"
(with-container el
(v/attach!
(fn [_]
[:div
[:p "paragraph1"]])
{}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 1 (child-count div)))
(is (= "paragraph1"
(-> (child-at div 0)
text-content)))))))
(deftest test-render-with-fn-using-state
(testing "rendering a function using the state"
(with-container el
(v/attach!
(fn [state]
[:div (:text state)])
{:text "Test Text"}
el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "Test Text"
(-> (child-at el 0)
text-content))))))
(deftest test-render-with-nested-fn
(testing "rendering a function nested in the tree"
(with-container el
(let [a-component (fn [state] [:div (:text state)])]
(v/attach!
[:div a-component]
{:text "Component Text"}
el)
(is (= 1 (child-count el)))
(let [div (child-at el 0)]
(is (= "div" (tag div)))
(is (= 1 (child-count div)))
(is (= "div" (-> (child-at div 0) tag)))
(is (= "Component Text"
(-> (child-at div 0)
text-content))))))))
(deftest test-render-with-state-updates
(let [done identity] ; async done
(testing "rendering a function using atom state"
(with-container el
(let [app-state (atom {:text "Test Text"})]
(v/attach!
(fn [state]
[:div (:text state)])
app-state
el)
(is (= 1 (child-count el)))
(is (= "div" (tag (child-at el 0))))
(is (= "Test Text"
(-> (child-at el 0)
text-content)))
(swap! app-state assoc :text "Changed Text")
(do ;wait
(is (= "Changed Text"
(-> (child-at el 0)
text-content)))
(done)))))))
(deftest test-render-with-state-updates-additive
(let [done identity] ;async done
(testing "rendering a function using additive state change"
(with-container el
(let [app-state (atom {:show-it? false})]
(v/attach!
(fn [state]
[:ul
[:li "always shown"]
(when (:show-it? state) [:li "Now showing: additive"])])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(swap! app-state assoc :show-it? true)
(do; wait
(is (= 2 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(is (= "Now showing: additive"
(-> (child-at ul 1)
text-content)))
(done))))))))
(deftest test-render-with-state-updates-reductive
(let [done identity] ;async done
(testing "rendering a function using a reductive state change"
(with-container el
(let [app-state (atom {:show-it? true})]
(v/attach!
(fn [state]
[:ul
[:li "always shown"]
(when (:show-it? state) [:li "Now showing: reductive"])])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(is (= "Now showing: reductive"
(-> (child-at ul 1)
text-content)))
(swap! app-state assoc :show-it? false)
(do; wait
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(done))))))))
(deftest test-render-with-state-updates-insertive
(testing "rendering a function using a insertive state change"
(with-container el
(let [app-state (atom {:show-it? false})]
(v/attach!
(fn [state]
[:ul
(when (:show-it? state) [:li "Now showing: insertive"])
[:li "always shown"]])
app-state
el)
(is (= 1 (child-count el)))
(let [ul (child-at el 0)]
(is (= 1 (child-count ul)))
(is (= "always shown"
(-> (child-at ul 0)
text-content)))
(swap! app-state assoc :show-it? true)
(is (= 2 (child-count ul)))
(is (= "Now showing: insertive"
(-> (child-at ul 0)
text-content)))
(is (= "always shown"
(-> (child-at ul 1)
text-content))))))))
(deftest test-render-with-state-updates-attribute-change
(testing "rendering a change in attributes on a state change"
(with-container el
(let [app-state (atom {:classname "text-success"})]
(v/attach!
(fn [state]
[:p {:class (:classname state)} "Text"])
app-state
el)
(is (= 1 (child-count el)))
(let [p (child-at el 0)]
(is (= "text-success" (css-class p)))
(is (= "Text" (text-content p)))
(swap! app-state assoc :classname "text-danger")
(is (= "text-danger" (css-class p)))
(is (= "Text" (text-content p))))))))
|
[
{
"context": "rasta), :common_name \"Rasta Toucan\", :first_name \"Rasta\", :last_name \"Toucan\"}))\n\n(defn- get-revisions [e",
"end": 855,
"score": 0.996330976486206,
"start": 850,
"tag": "NAME",
"value": "Rasta"
},
{
"context": " \"Rasta Toucan\", :first_name \"Rasta\", :last_name \"Toucan\"}))\n\n(defn- get-revisions [entity object-id]\n (f",
"end": 876,
"score": 0.9508048892021179,
"start": 870,
"tag": "NAME",
"value": "Toucan"
},
{
"context": " :message nil\n :user @rasta-revision-info\n :diff nil\n :desc",
"end": 2271,
"score": 0.9937906265258789,
"start": 2251,
"tag": "USERNAME",
"value": "@rasta-revision-info"
},
{
"context": "\"because i wanted to\"\n :user @rasta-revision-info\n :diff {:before {:name \"som",
"end": 2876,
"score": 0.995682418346405,
"start": 2856,
"tag": "USERNAME",
"value": "@rasta-revision-info"
},
{
"context": " :message nil\n :user @rasta-revision-info\n :diff {:before {:name name",
"end": 3243,
"score": 0.9960770010948181,
"start": 3223,
"tag": "USERNAME",
"value": "@rasta-revision-info"
},
{
"context": " :message nil\n :user @rasta-revision-info\n :diff nil\n :",
"end": 3609,
"score": 0.9958566427230835,
"start": 3589,
"tag": "USERNAME",
"value": "@rasta-revision-info"
},
{
"context": " :message nil\n :user @rasta-revision-info\n :diff {:before {:cards nil",
"end": 4675,
"score": 0.9974828958511353,
"start": 4655,
"tag": "USERNAME",
"value": "@rasta-revision-info"
},
{
"context": " :message nil\n :user @rasta-revision-info\n :diff {:before {:cards [{:",
"end": 5042,
"score": 0.9981508851051331,
"start": 5022,
"tag": "USERNAME",
"value": "@rasta-revision-info"
},
{
"context": " :message nil\n :user @rasta-revision-info\n :diff {:before {:cards nil",
"end": 5410,
"score": 0.9982012510299683,
"start": 5390,
"tag": "USERNAME",
"value": "@rasta-revision-info"
},
{
"context": " :message nil\n :user @rasta-revision-info\n :diff nil\n :",
"end": 5775,
"score": 0.9984703660011292,
"start": 5755,
"tag": "USERNAME",
"value": "@rasta-revision-info"
}
] | c#-metabase/test/metabase/api/revision_test.clj | hanakhry/Crime_Admin | 0 | (ns metabase.api.revision-test
(:require [clojure.test :refer :all]
[metabase.models.card :refer [Card serialize-instance]]
[metabase.models.collection :refer [Collection]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.dashboard-card :refer [DashboardCard]]
[metabase.models.revision :refer [push-revision! Revision revisions]]
[metabase.test :as mt]
[metabase.test.data.users :as test-users]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(use-fixtures :once (fixtures/initialize :db :test-users :web-server))
(def ^:private rasta-revision-info
(delay
{:id (test-users/user->id :rasta), :common_name "Rasta Toucan", :first_name "Rasta", :last_name "Toucan"}))
(defn- get-revisions [entity object-id]
(for [revision (mt/user-http-request :rasta :get "revision" :entity entity, :id object-id)]
(dissoc revision :timestamp :id)))
(defn- create-card-revision [card is-creation? user]
(push-revision!
:object card
:entity Card
:id (:id card)
:user-id (test-users/user->id user)
:is-creation? is-creation?))
(defn- create-dashboard-revision! [dash is-creation? user]
(push-revision!
:object (Dashboard (:id dash))
:entity Dashboard
:id (:id dash)
:user-id (test-users/user->id user)
:is-creation? is-creation?))
;;; # GET /revision
; Things we are testing for:
; 1. ordered by timestamp DESC
; 2. :user is hydrated
; 3. :description is calculated
;; case with no revisions (maintains backwards compatibility with old installs before revisions)
(deftest no-revisions-test
(testing "Loading revisions, where there are no revisions, should work"
(is (= [{:user {}, :diff nil, :description nil}]
(tt/with-temp Card [{:keys [id]}]
(get-revisions :card id))))))
;; case with single creation revision
(deftest single-revision-test
(testing "Loading a single revision works"
(is (= [{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(tt/with-temp Card [{:keys [id] :as card}]
(create-card-revision card true :rasta)
(get-revisions :card id))))))
;; case with multiple revisions, including reversion
(deftest multiple-revisions-with-reversion-test
(testing "Creating multiple revisions, with a reversion, works"
(tt/with-temp Card [{:keys [id name], :as card}]
(is (= [{:is_reversion true
:is_creation false
:message "because i wanted to"
:user @rasta-revision-info
:diff {:before {:name "something else"}
:after {:name name}}
:description (format "renamed this Card from \"something else\" to \"%s\"." name)}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:name name}
:after {:name "something else"}}
:description (format "renamed this Card from \"%s\" to \"something else\"." name)}
{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(do
(create-card-revision card true :rasta)
(create-card-revision (assoc card :name "something else") false :rasta)
(db/insert! Revision
:model (:name Card)
:model_id id
:user_id (test-users/user->id :rasta)
:object (serialize-instance Card (:id card) card)
:message "because i wanted to"
:is_creation false
:is_reversion true)
(get-revisions :card id)))))))
;;; # POST /revision/revert
(defn- strip-ids
[objects]
(mapv #(dissoc % :id) objects))
(deftest revert-test
(testing "Reverting through API works"
(tt/with-temp* [Dashboard [{:keys [id] :as dash}]
Card [{card-id :id, :as card}]]
(is (= [{:is_reversion true
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards nil}
:after {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}}
:description "added a card."}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}
:after {:cards nil}}
:description "removed a card."}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards nil}
:after {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}}
:description "added a card."}
{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(do
(create-dashboard-revision! dash true :rasta)
(let [dashcard (db/insert! DashboardCard :dashboard_id id :card_id (:id card))]
(create-dashboard-revision! dash false :rasta)
(db/simple-delete! DashboardCard, :id (:id dashcard)))
(create-dashboard-revision! dash false :rasta)
(let [[_ {previous-revision-id :id}] (revisions Dashboard id)]
;; Revert to the previous revision, allowed because rasta has permissions on parent collection
(mt/user-http-request :rasta :post "revision/revert" {:entity :dashboard
:id id
:revision_id previous-revision-id}))
(->> (get-revisions :dashboard id)
(mapv (fn [rev]
(if-not (:diff rev) rev
(if (get-in rev [:diff :before :cards])
(update-in rev [:diff :before :cards] strip-ids)
(update-in rev [:diff :after :cards] strip-ids))))))))))))
(deftest permission-check-on-revert-test
(testing "Are permissions enforced by the revert action in the revision api?"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp* [Collection [collection {:name "Personal collection"}]
Dashboard [dashboard {:collection_id (u/the-id collection) :name "Personal dashboard"}]]
(create-dashboard-revision! dashboard true :crowberto)
(create-dashboard-revision! dashboard false :crowberto)
(let [dashboard-id (u/the-id dashboard)
[_ {prev-rev-id :id}] (revisions Dashboard dashboard-id)
update-req {:entity :dashboard, :id dashboard-id, :revision_id prev-rev-id}]
;; rasta should not have permissions to update the dashboard (i.e. revert), because they are not admin and do
;; not have any particular permission on the collection where it lives (because of the
;; with-non-admin-groups-no-root-collection-perms wrapper)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post "revision/revert" update-req))))))))
| 41927 | (ns metabase.api.revision-test
(:require [clojure.test :refer :all]
[metabase.models.card :refer [Card serialize-instance]]
[metabase.models.collection :refer [Collection]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.dashboard-card :refer [DashboardCard]]
[metabase.models.revision :refer [push-revision! Revision revisions]]
[metabase.test :as mt]
[metabase.test.data.users :as test-users]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(use-fixtures :once (fixtures/initialize :db :test-users :web-server))
(def ^:private rasta-revision-info
(delay
{:id (test-users/user->id :rasta), :common_name "Rasta Toucan", :first_name "<NAME>", :last_name "<NAME>"}))
(defn- get-revisions [entity object-id]
(for [revision (mt/user-http-request :rasta :get "revision" :entity entity, :id object-id)]
(dissoc revision :timestamp :id)))
(defn- create-card-revision [card is-creation? user]
(push-revision!
:object card
:entity Card
:id (:id card)
:user-id (test-users/user->id user)
:is-creation? is-creation?))
(defn- create-dashboard-revision! [dash is-creation? user]
(push-revision!
:object (Dashboard (:id dash))
:entity Dashboard
:id (:id dash)
:user-id (test-users/user->id user)
:is-creation? is-creation?))
;;; # GET /revision
; Things we are testing for:
; 1. ordered by timestamp DESC
; 2. :user is hydrated
; 3. :description is calculated
;; case with no revisions (maintains backwards compatibility with old installs before revisions)
(deftest no-revisions-test
(testing "Loading revisions, where there are no revisions, should work"
(is (= [{:user {}, :diff nil, :description nil}]
(tt/with-temp Card [{:keys [id]}]
(get-revisions :card id))))))
;; case with single creation revision
(deftest single-revision-test
(testing "Loading a single revision works"
(is (= [{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(tt/with-temp Card [{:keys [id] :as card}]
(create-card-revision card true :rasta)
(get-revisions :card id))))))
;; case with multiple revisions, including reversion
(deftest multiple-revisions-with-reversion-test
(testing "Creating multiple revisions, with a reversion, works"
(tt/with-temp Card [{:keys [id name], :as card}]
(is (= [{:is_reversion true
:is_creation false
:message "because i wanted to"
:user @rasta-revision-info
:diff {:before {:name "something else"}
:after {:name name}}
:description (format "renamed this Card from \"something else\" to \"%s\"." name)}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:name name}
:after {:name "something else"}}
:description (format "renamed this Card from \"%s\" to \"something else\"." name)}
{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(do
(create-card-revision card true :rasta)
(create-card-revision (assoc card :name "something else") false :rasta)
(db/insert! Revision
:model (:name Card)
:model_id id
:user_id (test-users/user->id :rasta)
:object (serialize-instance Card (:id card) card)
:message "because i wanted to"
:is_creation false
:is_reversion true)
(get-revisions :card id)))))))
;;; # POST /revision/revert
(defn- strip-ids
[objects]
(mapv #(dissoc % :id) objects))
(deftest revert-test
(testing "Reverting through API works"
(tt/with-temp* [Dashboard [{:keys [id] :as dash}]
Card [{card-id :id, :as card}]]
(is (= [{:is_reversion true
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards nil}
:after {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}}
:description "added a card."}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}
:after {:cards nil}}
:description "removed a card."}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards nil}
:after {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}}
:description "added a card."}
{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(do
(create-dashboard-revision! dash true :rasta)
(let [dashcard (db/insert! DashboardCard :dashboard_id id :card_id (:id card))]
(create-dashboard-revision! dash false :rasta)
(db/simple-delete! DashboardCard, :id (:id dashcard)))
(create-dashboard-revision! dash false :rasta)
(let [[_ {previous-revision-id :id}] (revisions Dashboard id)]
;; Revert to the previous revision, allowed because rasta has permissions on parent collection
(mt/user-http-request :rasta :post "revision/revert" {:entity :dashboard
:id id
:revision_id previous-revision-id}))
(->> (get-revisions :dashboard id)
(mapv (fn [rev]
(if-not (:diff rev) rev
(if (get-in rev [:diff :before :cards])
(update-in rev [:diff :before :cards] strip-ids)
(update-in rev [:diff :after :cards] strip-ids))))))))))))
(deftest permission-check-on-revert-test
(testing "Are permissions enforced by the revert action in the revision api?"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp* [Collection [collection {:name "Personal collection"}]
Dashboard [dashboard {:collection_id (u/the-id collection) :name "Personal dashboard"}]]
(create-dashboard-revision! dashboard true :crowberto)
(create-dashboard-revision! dashboard false :crowberto)
(let [dashboard-id (u/the-id dashboard)
[_ {prev-rev-id :id}] (revisions Dashboard dashboard-id)
update-req {:entity :dashboard, :id dashboard-id, :revision_id prev-rev-id}]
;; rasta should not have permissions to update the dashboard (i.e. revert), because they are not admin and do
;; not have any particular permission on the collection where it lives (because of the
;; with-non-admin-groups-no-root-collection-perms wrapper)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post "revision/revert" update-req))))))))
| true | (ns metabase.api.revision-test
(:require [clojure.test :refer :all]
[metabase.models.card :refer [Card serialize-instance]]
[metabase.models.collection :refer [Collection]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.dashboard-card :refer [DashboardCard]]
[metabase.models.revision :refer [push-revision! Revision revisions]]
[metabase.test :as mt]
[metabase.test.data.users :as test-users]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(use-fixtures :once (fixtures/initialize :db :test-users :web-server))
(def ^:private rasta-revision-info
(delay
{:id (test-users/user->id :rasta), :common_name "Rasta Toucan", :first_name "PI:NAME:<NAME>END_PI", :last_name "PI:NAME:<NAME>END_PI"}))
(defn- get-revisions [entity object-id]
(for [revision (mt/user-http-request :rasta :get "revision" :entity entity, :id object-id)]
(dissoc revision :timestamp :id)))
(defn- create-card-revision [card is-creation? user]
(push-revision!
:object card
:entity Card
:id (:id card)
:user-id (test-users/user->id user)
:is-creation? is-creation?))
(defn- create-dashboard-revision! [dash is-creation? user]
(push-revision!
:object (Dashboard (:id dash))
:entity Dashboard
:id (:id dash)
:user-id (test-users/user->id user)
:is-creation? is-creation?))
;;; # GET /revision
; Things we are testing for:
; 1. ordered by timestamp DESC
; 2. :user is hydrated
; 3. :description is calculated
;; case with no revisions (maintains backwards compatibility with old installs before revisions)
(deftest no-revisions-test
(testing "Loading revisions, where there are no revisions, should work"
(is (= [{:user {}, :diff nil, :description nil}]
(tt/with-temp Card [{:keys [id]}]
(get-revisions :card id))))))
;; case with single creation revision
(deftest single-revision-test
(testing "Loading a single revision works"
(is (= [{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(tt/with-temp Card [{:keys [id] :as card}]
(create-card-revision card true :rasta)
(get-revisions :card id))))))
;; case with multiple revisions, including reversion
(deftest multiple-revisions-with-reversion-test
(testing "Creating multiple revisions, with a reversion, works"
(tt/with-temp Card [{:keys [id name], :as card}]
(is (= [{:is_reversion true
:is_creation false
:message "because i wanted to"
:user @rasta-revision-info
:diff {:before {:name "something else"}
:after {:name name}}
:description (format "renamed this Card from \"something else\" to \"%s\"." name)}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:name name}
:after {:name "something else"}}
:description (format "renamed this Card from \"%s\" to \"something else\"." name)}
{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(do
(create-card-revision card true :rasta)
(create-card-revision (assoc card :name "something else") false :rasta)
(db/insert! Revision
:model (:name Card)
:model_id id
:user_id (test-users/user->id :rasta)
:object (serialize-instance Card (:id card) card)
:message "because i wanted to"
:is_creation false
:is_reversion true)
(get-revisions :card id)))))))
;;; # POST /revision/revert
(defn- strip-ids
[objects]
(mapv #(dissoc % :id) objects))
(deftest revert-test
(testing "Reverting through API works"
(tt/with-temp* [Dashboard [{:keys [id] :as dash}]
Card [{card-id :id, :as card}]]
(is (= [{:is_reversion true
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards nil}
:after {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}}
:description "added a card."}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}
:after {:cards nil}}
:description "removed a card."}
{:is_reversion false
:is_creation false
:message nil
:user @rasta-revision-info
:diff {:before {:cards nil}
:after {:cards [{:sizeX 2, :sizeY 2, :row 0, :col 0, :card_id card-id, :series []}]}}
:description "added a card."}
{:is_reversion false
:is_creation true
:message nil
:user @rasta-revision-info
:diff nil
:description nil}]
(do
(create-dashboard-revision! dash true :rasta)
(let [dashcard (db/insert! DashboardCard :dashboard_id id :card_id (:id card))]
(create-dashboard-revision! dash false :rasta)
(db/simple-delete! DashboardCard, :id (:id dashcard)))
(create-dashboard-revision! dash false :rasta)
(let [[_ {previous-revision-id :id}] (revisions Dashboard id)]
;; Revert to the previous revision, allowed because rasta has permissions on parent collection
(mt/user-http-request :rasta :post "revision/revert" {:entity :dashboard
:id id
:revision_id previous-revision-id}))
(->> (get-revisions :dashboard id)
(mapv (fn [rev]
(if-not (:diff rev) rev
(if (get-in rev [:diff :before :cards])
(update-in rev [:diff :before :cards] strip-ids)
(update-in rev [:diff :after :cards] strip-ids))))))))))))
(deftest permission-check-on-revert-test
(testing "Are permissions enforced by the revert action in the revision api?"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp* [Collection [collection {:name "Personal collection"}]
Dashboard [dashboard {:collection_id (u/the-id collection) :name "Personal dashboard"}]]
(create-dashboard-revision! dashboard true :crowberto)
(create-dashboard-revision! dashboard false :crowberto)
(let [dashboard-id (u/the-id dashboard)
[_ {prev-rev-id :id}] (revisions Dashboard dashboard-id)
update-req {:entity :dashboard, :id dashboard-id, :revision_id prev-rev-id}]
;; rasta should not have permissions to update the dashboard (i.e. revert), because they are not admin and do
;; not have any particular permission on the collection where it lives (because of the
;; with-non-admin-groups-no-root-collection-perms wrapper)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post "revision/revert" update-req))))))))
|
[
{
"context": "rs\"\n {:body (pr-str {:first_name \"Boris\"\n :surname \"Be",
"end": 348,
"score": 0.9998217821121216,
"start": 343,
"tag": "NAME",
"value": "Boris"
},
{
"context": "is\"\n :surname \"Becker\"\n :height 191",
"end": 402,
"score": 0.9995881915092468,
"start": 396,
"tag": "NAME",
"value": "Becker"
}
] | Chapter14/Exercise14.06/src/packt_clj/exercises/application_layer_integration.clj | transducer/The-Clojure-Workshop | 55 | (ns packt-clj.exercises.application-layer-integration
(:require
[clj-http.client :as http]
[packt-clj.fitness.api :as api]))
; commented out to avoid spinning up a jetty server on compilation
#_(def app (api/run))
(defn add-new-user
[]
(-> (http/post "http://localhost:8080/users"
{:body (pr-str {:first_name "Boris"
:surname "Becker"
:height 191
:weight 85})})
:headers
(get "Link")))
(defn add-new-activity
[]
(-> (http/post "http://localhost:8080/activities"
{:body (pr-str {:user_id 4
:activity_type "run"
:activity_date "2019-03-25"
:distance 4970
:duration 1200})})
:headers
(get "Link")))
| 94304 | (ns packt-clj.exercises.application-layer-integration
(:require
[clj-http.client :as http]
[packt-clj.fitness.api :as api]))
; commented out to avoid spinning up a jetty server on compilation
#_(def app (api/run))
(defn add-new-user
[]
(-> (http/post "http://localhost:8080/users"
{:body (pr-str {:first_name "<NAME>"
:surname "<NAME>"
:height 191
:weight 85})})
:headers
(get "Link")))
(defn add-new-activity
[]
(-> (http/post "http://localhost:8080/activities"
{:body (pr-str {:user_id 4
:activity_type "run"
:activity_date "2019-03-25"
:distance 4970
:duration 1200})})
:headers
(get "Link")))
| true | (ns packt-clj.exercises.application-layer-integration
(:require
[clj-http.client :as http]
[packt-clj.fitness.api :as api]))
; commented out to avoid spinning up a jetty server on compilation
#_(def app (api/run))
(defn add-new-user
[]
(-> (http/post "http://localhost:8080/users"
{:body (pr-str {:first_name "PI:NAME:<NAME>END_PI"
:surname "PI:NAME:<NAME>END_PI"
:height 191
:weight 85})})
:headers
(get "Link")))
(defn add-new-activity
[]
(-> (http/post "http://localhost:8080/activities"
{:body (pr-str {:user_id 4
:activity_type "run"
:activity_date "2019-03-25"
:distance 4970
:duration 1200})})
:headers
(get "Link")))
|
[
{
"context": "rl)\n (http/post {:username username :password password})))\n\n(defn register\n [username password]\n (-> \"",
"end": 293,
"score": 0.8767145872116089,
"start": 285,
"tag": "PASSWORD",
"value": "password"
}
] | src/baoqu/api.cljs | baoqu/baoqu-front | 4 | (ns baoqu.api
(:require [baoqu.http :as http]
[baoqu.utils :refer [->url]]))
(enable-console-print!)
;;--------------------
;; USER
;;--------------------
(defn login
[username password]
(-> "/api/login"
(->url)
(http/post {:username username :password password})))
(defn register
[username password]
(-> "/api/register"
(->url)
(http/post {:username username :password password})))
;;--------------------
;; EVENT
;;--------------------
(defn join-event
[event-id username]
(let [path (str "/api/events/" event-id "/users")
url (->url path)
body {:name username}]
(http/post url body)))
(defn get-all-events
[]
(let [path "/api/events/"
url (->url path)]
(http/get url)))
(defn get-event
[event-id]
(let [path (str "/api/events/" event-id)
url (->url path)]
(http/get url)))
(defn get-event-circles
[event-id]
(let [path (str "/api/events/" event-id "/circles")
url (->url path)]
(http/get url)))
(defn get-event-users
[event-id]
(let [path (str "/api/events/" event-id "/users")
url (->url path)]
(http/get url)))
(defn get-event-ideas
[event-id]
(let [path (str "/api/events/" event-id "/ideas")
url (->url path)]
(http/get url)))
(defn get-event-comments
[event-id]
(let [path (str "/api/events/" event-id "/comments")
url (->url path)]
(http/get url)))
;;--------------------
;; CIRCLE
;;--------------------
(defn get-user-circle
[user-id]
(let [path (str "/api/user-circle/" user-id)
url (->url path)]
(http/get url)))
(defn get-circle-ideas-for-user
[circle-id user-id]
(let [params {:user-id user-id}
path (str "/api/circles/" circle-id "/ideas")
url (->url path params)]
(http/get url)))
(defn get-comments-for-circle
[circle-id]
(let [path (str "/api/circles/" circle-id "/comments")
url (->url path)]
(http/get url)))
;;--------------------
;; IDEA
;;--------------------
(defn upvote-idea
[user-id body event-id]
(let [url (->url "/api/ideas/upvote")
data {:user-id user-id :idea-name body :event-id event-id}]
(http/post url data)))
(defn downvote-idea
[user-id body event-id]
(let [url (->url "/api/ideas/downvote")
data {:user-id user-id :idea-name body :event-id event-id}]
(http/post url data)))
(defn get-event-votes
[id]
(let [path (str "/api/events/" id "/votes")
url (->url path)]
(http/get url)))
;;--------------------
;; COMMENT
;;--------------------
(defn create-comment
[circle-id name body]
(let [path (str "/api/circles/" circle-id "/comments")
url (->url path)
data {:name name :comment-body body}]
(http/post url data)))
;;--------------------
;; USER
;;--------------------
(defn get-user-path
[user-id]
(let [path (str "/api/users/" user-id "/path")
url (->url path)]
(http/get url)))
| 8271 | (ns baoqu.api
(:require [baoqu.http :as http]
[baoqu.utils :refer [->url]]))
(enable-console-print!)
;;--------------------
;; USER
;;--------------------
(defn login
[username password]
(-> "/api/login"
(->url)
(http/post {:username username :password <PASSWORD>})))
(defn register
[username password]
(-> "/api/register"
(->url)
(http/post {:username username :password password})))
;;--------------------
;; EVENT
;;--------------------
(defn join-event
[event-id username]
(let [path (str "/api/events/" event-id "/users")
url (->url path)
body {:name username}]
(http/post url body)))
(defn get-all-events
[]
(let [path "/api/events/"
url (->url path)]
(http/get url)))
(defn get-event
[event-id]
(let [path (str "/api/events/" event-id)
url (->url path)]
(http/get url)))
(defn get-event-circles
[event-id]
(let [path (str "/api/events/" event-id "/circles")
url (->url path)]
(http/get url)))
(defn get-event-users
[event-id]
(let [path (str "/api/events/" event-id "/users")
url (->url path)]
(http/get url)))
(defn get-event-ideas
[event-id]
(let [path (str "/api/events/" event-id "/ideas")
url (->url path)]
(http/get url)))
(defn get-event-comments
[event-id]
(let [path (str "/api/events/" event-id "/comments")
url (->url path)]
(http/get url)))
;;--------------------
;; CIRCLE
;;--------------------
(defn get-user-circle
[user-id]
(let [path (str "/api/user-circle/" user-id)
url (->url path)]
(http/get url)))
(defn get-circle-ideas-for-user
[circle-id user-id]
(let [params {:user-id user-id}
path (str "/api/circles/" circle-id "/ideas")
url (->url path params)]
(http/get url)))
(defn get-comments-for-circle
[circle-id]
(let [path (str "/api/circles/" circle-id "/comments")
url (->url path)]
(http/get url)))
;;--------------------
;; IDEA
;;--------------------
(defn upvote-idea
[user-id body event-id]
(let [url (->url "/api/ideas/upvote")
data {:user-id user-id :idea-name body :event-id event-id}]
(http/post url data)))
(defn downvote-idea
[user-id body event-id]
(let [url (->url "/api/ideas/downvote")
data {:user-id user-id :idea-name body :event-id event-id}]
(http/post url data)))
(defn get-event-votes
[id]
(let [path (str "/api/events/" id "/votes")
url (->url path)]
(http/get url)))
;;--------------------
;; COMMENT
;;--------------------
(defn create-comment
[circle-id name body]
(let [path (str "/api/circles/" circle-id "/comments")
url (->url path)
data {:name name :comment-body body}]
(http/post url data)))
;;--------------------
;; USER
;;--------------------
(defn get-user-path
[user-id]
(let [path (str "/api/users/" user-id "/path")
url (->url path)]
(http/get url)))
| true | (ns baoqu.api
(:require [baoqu.http :as http]
[baoqu.utils :refer [->url]]))
(enable-console-print!)
;;--------------------
;; USER
;;--------------------
(defn login
[username password]
(-> "/api/login"
(->url)
(http/post {:username username :password PI:PASSWORD:<PASSWORD>END_PI})))
(defn register
[username password]
(-> "/api/register"
(->url)
(http/post {:username username :password password})))
;;--------------------
;; EVENT
;;--------------------
(defn join-event
[event-id username]
(let [path (str "/api/events/" event-id "/users")
url (->url path)
body {:name username}]
(http/post url body)))
(defn get-all-events
[]
(let [path "/api/events/"
url (->url path)]
(http/get url)))
(defn get-event
[event-id]
(let [path (str "/api/events/" event-id)
url (->url path)]
(http/get url)))
(defn get-event-circles
[event-id]
(let [path (str "/api/events/" event-id "/circles")
url (->url path)]
(http/get url)))
(defn get-event-users
[event-id]
(let [path (str "/api/events/" event-id "/users")
url (->url path)]
(http/get url)))
(defn get-event-ideas
[event-id]
(let [path (str "/api/events/" event-id "/ideas")
url (->url path)]
(http/get url)))
(defn get-event-comments
[event-id]
(let [path (str "/api/events/" event-id "/comments")
url (->url path)]
(http/get url)))
;;--------------------
;; CIRCLE
;;--------------------
(defn get-user-circle
[user-id]
(let [path (str "/api/user-circle/" user-id)
url (->url path)]
(http/get url)))
(defn get-circle-ideas-for-user
[circle-id user-id]
(let [params {:user-id user-id}
path (str "/api/circles/" circle-id "/ideas")
url (->url path params)]
(http/get url)))
(defn get-comments-for-circle
[circle-id]
(let [path (str "/api/circles/" circle-id "/comments")
url (->url path)]
(http/get url)))
;;--------------------
;; IDEA
;;--------------------
(defn upvote-idea
[user-id body event-id]
(let [url (->url "/api/ideas/upvote")
data {:user-id user-id :idea-name body :event-id event-id}]
(http/post url data)))
(defn downvote-idea
[user-id body event-id]
(let [url (->url "/api/ideas/downvote")
data {:user-id user-id :idea-name body :event-id event-id}]
(http/post url data)))
(defn get-event-votes
[id]
(let [path (str "/api/events/" id "/votes")
url (->url path)]
(http/get url)))
;;--------------------
;; COMMENT
;;--------------------
(defn create-comment
[circle-id name body]
(let [path (str "/api/circles/" circle-id "/comments")
url (->url path)
data {:name name :comment-body body}]
(http/post url data)))
;;--------------------
;; USER
;;--------------------
(defn get-user-path
[user-id]
(let [path (str "/api/users/" user-id "/path")
url (->url path)]
(http/get url)))
|
[
{
"context": "defs [session/random-anti-csrf-token (constantly \"315c1279c6f9f873bf1face7afeee420\")]\n (is (= {:id \"092797dd-a82",
"end": 1443,
"score": 0.9882809519767761,
"start": 1411,
"tag": "KEY",
"value": "315c1279c6f9f873bf1face7afeee420"
},
{
"context": " (= {:id \"092797dd-a82a-4748-b393-697d7bb9ab65\"\n :user_id (mt/user->id :t",
"end": 1517,
"score": 0.7670057415962219,
"start": 1508,
"tag": "PASSWORD",
"value": "d7bb9ab65"
},
{
"context": "5\"\n :user_id (mt/user->id :trashbird)\n :anti_csrf_token \"315c1279c6f9f8",
"end": 1575,
"score": 0.9557688236236572,
"start": 1566,
"tag": "USERNAME",
"value": "trashbird"
},
{
"context": ">id :trashbird)\n :anti_csrf_token \"315c1279c6f9f873bf1face7afeee420\"\n :type :full-app-embed",
"end": 1643,
"score": 0.8385507464408875,
"start": 1611,
"tag": "KEY",
"value": "315c1279c6f9f873bf1face7afeee420"
}
] | c#-metabase/test/metabase/models/session_test.clj | hanakhry/Crime_Admin | 0 | (ns metabase.models.session-test
(:require [clojure.test :refer :all]
[metabase.models.session :as session :refer [Session]]
[metabase.server.middleware.misc :as mw.misc]
[metabase.test :as mt]
[toucan.db :as db]
[toucan.models :as t.models]))
(def ^:private test-uuid #uuid "092797dd-a82a-4748-b393-697d7bb9ab65")
;; for some reason Toucan seems to be busted with models with non-integer IDs and `with-temp` doesn't seem to work
;; the way we'd expect :/
(defn- new-session []
(try
(db/insert! Session {:id (str test-uuid), :user_id (mt/user->id :trashbird)})
(-> (Session (str test-uuid)) t.models/post-insert (dissoc :created_at))
(finally
(db/delete! Session :id (str test-uuid)))))
(deftest new-session-include-test-test
(testing "when creating a new Session, it should come back with an added `:type` key"
(is (= {:id "092797dd-a82a-4748-b393-697d7bb9ab65"
:user_id (mt/user->id :trashbird)
:anti_csrf_token nil
:type :normal}
(mt/derecordize
(new-session))))))
(deftest embedding-test
(testing "if request is an embedding request, we should get ourselves an embedded Session"
(binding [mw.misc/*request* {:headers {"x-metabase-embedded" "true"}}]
(with-redefs [session/random-anti-csrf-token (constantly "315c1279c6f9f873bf1face7afeee420")]
(is (= {:id "092797dd-a82a-4748-b393-697d7bb9ab65"
:user_id (mt/user->id :trashbird)
:anti_csrf_token "315c1279c6f9f873bf1face7afeee420"
:type :full-app-embed}
(mt/derecordize
(new-session))))))))
| 123217 | (ns metabase.models.session-test
(:require [clojure.test :refer :all]
[metabase.models.session :as session :refer [Session]]
[metabase.server.middleware.misc :as mw.misc]
[metabase.test :as mt]
[toucan.db :as db]
[toucan.models :as t.models]))
(def ^:private test-uuid #uuid "092797dd-a82a-4748-b393-697d7bb9ab65")
;; for some reason Toucan seems to be busted with models with non-integer IDs and `with-temp` doesn't seem to work
;; the way we'd expect :/
(defn- new-session []
(try
(db/insert! Session {:id (str test-uuid), :user_id (mt/user->id :trashbird)})
(-> (Session (str test-uuid)) t.models/post-insert (dissoc :created_at))
(finally
(db/delete! Session :id (str test-uuid)))))
(deftest new-session-include-test-test
(testing "when creating a new Session, it should come back with an added `:type` key"
(is (= {:id "092797dd-a82a-4748-b393-697d7bb9ab65"
:user_id (mt/user->id :trashbird)
:anti_csrf_token nil
:type :normal}
(mt/derecordize
(new-session))))))
(deftest embedding-test
(testing "if request is an embedding request, we should get ourselves an embedded Session"
(binding [mw.misc/*request* {:headers {"x-metabase-embedded" "true"}}]
(with-redefs [session/random-anti-csrf-token (constantly "<KEY>")]
(is (= {:id "092797dd-a82a-4748-b393-697<PASSWORD>"
:user_id (mt/user->id :trashbird)
:anti_csrf_token "<KEY>"
:type :full-app-embed}
(mt/derecordize
(new-session))))))))
| true | (ns metabase.models.session-test
(:require [clojure.test :refer :all]
[metabase.models.session :as session :refer [Session]]
[metabase.server.middleware.misc :as mw.misc]
[metabase.test :as mt]
[toucan.db :as db]
[toucan.models :as t.models]))
(def ^:private test-uuid #uuid "092797dd-a82a-4748-b393-697d7bb9ab65")
;; for some reason Toucan seems to be busted with models with non-integer IDs and `with-temp` doesn't seem to work
;; the way we'd expect :/
(defn- new-session []
(try
(db/insert! Session {:id (str test-uuid), :user_id (mt/user->id :trashbird)})
(-> (Session (str test-uuid)) t.models/post-insert (dissoc :created_at))
(finally
(db/delete! Session :id (str test-uuid)))))
(deftest new-session-include-test-test
(testing "when creating a new Session, it should come back with an added `:type` key"
(is (= {:id "092797dd-a82a-4748-b393-697d7bb9ab65"
:user_id (mt/user->id :trashbird)
:anti_csrf_token nil
:type :normal}
(mt/derecordize
(new-session))))))
(deftest embedding-test
(testing "if request is an embedding request, we should get ourselves an embedded Session"
(binding [mw.misc/*request* {:headers {"x-metabase-embedded" "true"}}]
(with-redefs [session/random-anti-csrf-token (constantly "PI:KEY:<KEY>END_PI")]
(is (= {:id "092797dd-a82a-4748-b393-697PI:PASSWORD:<PASSWORD>END_PI"
:user_id (mt/user->id :trashbird)
:anti_csrf_token "PI:KEY:<KEY>END_PI"
:type :full-app-embed}
(mt/derecordize
(new-session))))))))
|
[
{
"context": "lient\n []\n (salt/client {::s/master-url \"http://192.168.50.10:8000\"\n ::s/username \"saltapi\"\n ",
"end": 261,
"score": 0.9830542802810669,
"start": 248,
"tag": "IP_ADDRESS",
"value": "192.168.50.10"
},
{
"context": "192.168.50.10:8000\"\n ::s/username \"saltapi\"\n ::s/password \"saltapi\"\n ",
"end": 305,
"score": 0.9992387890815735,
"start": 298,
"tag": "USERNAME",
"value": "saltapi"
},
{
"context": "/username \"saltapi\"\n ::s/password \"saltapi\"\n ::s/max-sse-retries 3\n ",
"end": 344,
"score": 0.9993849992752075,
"start": 337,
"tag": "PASSWORD",
"value": "saltapi"
}
] | examples/samples.clj | mkurtak/clj-salt-api | 9 | (ns samples
(:require [clojure.core.async :as a]
[salt.client :as salt]
[salt.core :as s]
[samples-utils :refer [print-and-close throw-err]]))
(defn- example-client
[]
(salt/client {::s/master-url "http://192.168.50.10:8000"
::s/username "saltapi"
::s/password "saltapi"
::s/max-sse-retries 3
::s/sse-keep-alive? true
::s/default-http-request {:connection-timeout 3000
:request-timeout 5000}}))
(defn local-test-ping
"Ping minions with local sync client using list matcher,
print all values at once.
If one of minion ids is invalid, its printed in result."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request
cl
{:form-params {:client "local"
:tgt "minion1,minion2,minion3"
:tgt_type "list"
:fun "test.ping"}}))))
(defn local-async-test-ping
"Ping minions with local async client using list matcher,
print values as they come.
If one of minion ids is invalid, its not printed in the result."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "minion1,minion2,minion3"
:tgt_type "list"
:fun "test.ping"}}))))
(defn local-async-pkg-show
"Ping all minions with local async client using list matcher,
print values as they come.
If one of minion ids is invalid, its not printed in the result."
[]
(let [cl (example-client)]
(print-and-close
cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "pkg.show"
:arg ["emacs", "salt-minion"]
:kwarg {:filter ["description-en", "installed-size"]}}}))))
(defn local-async-in-parallel
"Demonstrates how to execute two different modules with local async client in
parallel, print results from commands as they come and block until all commands
return."
[]
(let [cl (example-client)
res-chan (a/merge [(salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "cmd.run"
:arg ["sleep 5 && echo $FOO"]
:kwarg {:env {:FOO "bar"}}}})
(salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "pkg.show"
:arg ["emacs"]
:kwarg {:filter ["description-en"]}}})])]
(print-and-close cl res-chan)))
(defn local-async-locate
"Locate files and limit results to 10 with local async client and locate module."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "locate.locate"
:arg ["ld.*", "", 10]
:kwarg {:count false
:regex true}}}))))
(defn local-async-batch-glob-test-ping
"Ping all minions with batch 10% with local sync client.
Print all results at once."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request
cl
{:form-params {:client "local_batch"
:tgt "*"
:batch "10%"
:fun "test.ping"}}))))
(defn local-async-grains-items
"Get grans with local async client and pass response channel with transducer.
Tranducer throws error if any and create concatenated string from all grains."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "grains.items"}}
(a/chan 1 (comp
(map throw-err)
(map
(fn [{:keys [:minion :return]}]
(str "Listing grains for '" minion "':\n"
(reduce-kv
#(str %1 %2 ":" %3 "\n") "" return)))))
identity)
1))))
(defn runner-async-manage-present
"Demonstrates runner async client."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "runner_async"
:fun "manage.present"}}))))
(defn wheel-async-key-list-all
"Demonstrates wheel async client."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async cl
{:form-params {:client "wheel_async"
:fun "key.list_all"}}))))
(defn local-async-graceful-shutdown
"Demonstrates behavior when client is closed during the async request."
[]
(let [cl (example-client)
res-chan (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "cmd.run"
:arg ["sleep 20"]}})]
(a/<!! (a/timeout 3000))
(salt/close cl)
(print-and-close cl res-chan)))
(defn- read-channel-quiet
"Read channel and ignore responses until channel is empty."
[resp-chan]
(a/go-loop []
(when (a/<! resp-chan)
(recur))))
(defn- read-events-and-cancel
"Take 3 messages from `events-chan`, then put empty string to `cancel-chan`"
[events-chan cancel-chan]
(a/go-loop [c 0]
(when-let [res (a/<! events-chan)]
(println "stream" res)
(if (< c 2)
(recur (inc c))
(do
(println "cancelling events")
(a/>! cancel-chan ""))))))
(defn- events-stream
"Demonstrates listening to all saltstack data events.
Listen to 3 events and cancel listening."
[]
(let [cl (example-client)
cancel-chan (a/chan)
events-chan (salt/events cl cancel-chan)
resp-chan (salt/request-async cl {:form-params {:client "local_async"
:tgt "*"
:fun "test.ping"}})]
(read-channel-quiet resp-chan) ;read resp-chan to prevent sse backpressure
(a/<!! (read-events-and-cancel events-chan cancel-chan))
(salt/close cl)))
(comment
(local-test-ping)
(local-async-test-ping)
(local-async-pkg-show)
(local-async-in-parallel)
(local-async-locate)
(local-async-batch-glob-test-ping)
(local-async-grains-items)
(runner-async-manage-present)
(wheel-async-key-list-all)
(local-async-graceful-shutdown)
(events-stream)
)
| 45796 | (ns samples
(:require [clojure.core.async :as a]
[salt.client :as salt]
[salt.core :as s]
[samples-utils :refer [print-and-close throw-err]]))
(defn- example-client
[]
(salt/client {::s/master-url "http://192.168.50.10:8000"
::s/username "saltapi"
::s/password "<PASSWORD>"
::s/max-sse-retries 3
::s/sse-keep-alive? true
::s/default-http-request {:connection-timeout 3000
:request-timeout 5000}}))
(defn local-test-ping
"Ping minions with local sync client using list matcher,
print all values at once.
If one of minion ids is invalid, its printed in result."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request
cl
{:form-params {:client "local"
:tgt "minion1,minion2,minion3"
:tgt_type "list"
:fun "test.ping"}}))))
(defn local-async-test-ping
"Ping minions with local async client using list matcher,
print values as they come.
If one of minion ids is invalid, its not printed in the result."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "minion1,minion2,minion3"
:tgt_type "list"
:fun "test.ping"}}))))
(defn local-async-pkg-show
"Ping all minions with local async client using list matcher,
print values as they come.
If one of minion ids is invalid, its not printed in the result."
[]
(let [cl (example-client)]
(print-and-close
cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "pkg.show"
:arg ["emacs", "salt-minion"]
:kwarg {:filter ["description-en", "installed-size"]}}}))))
(defn local-async-in-parallel
"Demonstrates how to execute two different modules with local async client in
parallel, print results from commands as they come and block until all commands
return."
[]
(let [cl (example-client)
res-chan (a/merge [(salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "cmd.run"
:arg ["sleep 5 && echo $FOO"]
:kwarg {:env {:FOO "bar"}}}})
(salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "pkg.show"
:arg ["emacs"]
:kwarg {:filter ["description-en"]}}})])]
(print-and-close cl res-chan)))
(defn local-async-locate
"Locate files and limit results to 10 with local async client and locate module."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "locate.locate"
:arg ["ld.*", "", 10]
:kwarg {:count false
:regex true}}}))))
(defn local-async-batch-glob-test-ping
"Ping all minions with batch 10% with local sync client.
Print all results at once."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request
cl
{:form-params {:client "local_batch"
:tgt "*"
:batch "10%"
:fun "test.ping"}}))))
(defn local-async-grains-items
"Get grans with local async client and pass response channel with transducer.
Tranducer throws error if any and create concatenated string from all grains."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "grains.items"}}
(a/chan 1 (comp
(map throw-err)
(map
(fn [{:keys [:minion :return]}]
(str "Listing grains for '" minion "':\n"
(reduce-kv
#(str %1 %2 ":" %3 "\n") "" return)))))
identity)
1))))
(defn runner-async-manage-present
"Demonstrates runner async client."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "runner_async"
:fun "manage.present"}}))))
(defn wheel-async-key-list-all
"Demonstrates wheel async client."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async cl
{:form-params {:client "wheel_async"
:fun "key.list_all"}}))))
(defn local-async-graceful-shutdown
"Demonstrates behavior when client is closed during the async request."
[]
(let [cl (example-client)
res-chan (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "cmd.run"
:arg ["sleep 20"]}})]
(a/<!! (a/timeout 3000))
(salt/close cl)
(print-and-close cl res-chan)))
(defn- read-channel-quiet
"Read channel and ignore responses until channel is empty."
[resp-chan]
(a/go-loop []
(when (a/<! resp-chan)
(recur))))
(defn- read-events-and-cancel
"Take 3 messages from `events-chan`, then put empty string to `cancel-chan`"
[events-chan cancel-chan]
(a/go-loop [c 0]
(when-let [res (a/<! events-chan)]
(println "stream" res)
(if (< c 2)
(recur (inc c))
(do
(println "cancelling events")
(a/>! cancel-chan ""))))))
(defn- events-stream
"Demonstrates listening to all saltstack data events.
Listen to 3 events and cancel listening."
[]
(let [cl (example-client)
cancel-chan (a/chan)
events-chan (salt/events cl cancel-chan)
resp-chan (salt/request-async cl {:form-params {:client "local_async"
:tgt "*"
:fun "test.ping"}})]
(read-channel-quiet resp-chan) ;read resp-chan to prevent sse backpressure
(a/<!! (read-events-and-cancel events-chan cancel-chan))
(salt/close cl)))
(comment
(local-test-ping)
(local-async-test-ping)
(local-async-pkg-show)
(local-async-in-parallel)
(local-async-locate)
(local-async-batch-glob-test-ping)
(local-async-grains-items)
(runner-async-manage-present)
(wheel-async-key-list-all)
(local-async-graceful-shutdown)
(events-stream)
)
| true | (ns samples
(:require [clojure.core.async :as a]
[salt.client :as salt]
[salt.core :as s]
[samples-utils :refer [print-and-close throw-err]]))
(defn- example-client
[]
(salt/client {::s/master-url "http://192.168.50.10:8000"
::s/username "saltapi"
::s/password "PI:PASSWORD:<PASSWORD>END_PI"
::s/max-sse-retries 3
::s/sse-keep-alive? true
::s/default-http-request {:connection-timeout 3000
:request-timeout 5000}}))
(defn local-test-ping
"Ping minions with local sync client using list matcher,
print all values at once.
If one of minion ids is invalid, its printed in result."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request
cl
{:form-params {:client "local"
:tgt "minion1,minion2,minion3"
:tgt_type "list"
:fun "test.ping"}}))))
(defn local-async-test-ping
"Ping minions with local async client using list matcher,
print values as they come.
If one of minion ids is invalid, its not printed in the result."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "minion1,minion2,minion3"
:tgt_type "list"
:fun "test.ping"}}))))
(defn local-async-pkg-show
"Ping all minions with local async client using list matcher,
print values as they come.
If one of minion ids is invalid, its not printed in the result."
[]
(let [cl (example-client)]
(print-and-close
cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "pkg.show"
:arg ["emacs", "salt-minion"]
:kwarg {:filter ["description-en", "installed-size"]}}}))))
(defn local-async-in-parallel
"Demonstrates how to execute two different modules with local async client in
parallel, print results from commands as they come and block until all commands
return."
[]
(let [cl (example-client)
res-chan (a/merge [(salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "cmd.run"
:arg ["sleep 5 && echo $FOO"]
:kwarg {:env {:FOO "bar"}}}})
(salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "pkg.show"
:arg ["emacs"]
:kwarg {:filter ["description-en"]}}})])]
(print-and-close cl res-chan)))
(defn local-async-locate
"Locate files and limit results to 10 with local async client and locate module."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "locate.locate"
:arg ["ld.*", "", 10]
:kwarg {:count false
:regex true}}}))))
(defn local-async-batch-glob-test-ping
"Ping all minions with batch 10% with local sync client.
Print all results at once."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request
cl
{:form-params {:client "local_batch"
:tgt "*"
:batch "10%"
:fun "test.ping"}}))))
(defn local-async-grains-items
"Get grans with local async client and pass response channel with transducer.
Tranducer throws error if any and create concatenated string from all grains."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "grains.items"}}
(a/chan 1 (comp
(map throw-err)
(map
(fn [{:keys [:minion :return]}]
(str "Listing grains for '" minion "':\n"
(reduce-kv
#(str %1 %2 ":" %3 "\n") "" return)))))
identity)
1))))
(defn runner-async-manage-present
"Demonstrates runner async client."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async
cl
{:form-params {:client "runner_async"
:fun "manage.present"}}))))
(defn wheel-async-key-list-all
"Demonstrates wheel async client."
[]
(let [cl (example-client)]
(print-and-close cl (salt/request-async cl
{:form-params {:client "wheel_async"
:fun "key.list_all"}}))))
(defn local-async-graceful-shutdown
"Demonstrates behavior when client is closed during the async request."
[]
(let [cl (example-client)
res-chan (salt/request-async
cl
{:form-params {:client "local_async"
:tgt "*"
:fun "cmd.run"
:arg ["sleep 20"]}})]
(a/<!! (a/timeout 3000))
(salt/close cl)
(print-and-close cl res-chan)))
(defn- read-channel-quiet
"Read channel and ignore responses until channel is empty."
[resp-chan]
(a/go-loop []
(when (a/<! resp-chan)
(recur))))
(defn- read-events-and-cancel
"Take 3 messages from `events-chan`, then put empty string to `cancel-chan`"
[events-chan cancel-chan]
(a/go-loop [c 0]
(when-let [res (a/<! events-chan)]
(println "stream" res)
(if (< c 2)
(recur (inc c))
(do
(println "cancelling events")
(a/>! cancel-chan ""))))))
(defn- events-stream
"Demonstrates listening to all saltstack data events.
Listen to 3 events and cancel listening."
[]
(let [cl (example-client)
cancel-chan (a/chan)
events-chan (salt/events cl cancel-chan)
resp-chan (salt/request-async cl {:form-params {:client "local_async"
:tgt "*"
:fun "test.ping"}})]
(read-channel-quiet resp-chan) ;read resp-chan to prevent sse backpressure
(a/<!! (read-events-and-cancel events-chan cancel-chan))
(salt/close cl)))
(comment
(local-test-ping)
(local-async-test-ping)
(local-async-pkg-show)
(local-async-in-parallel)
(local-async-locate)
(local-async-batch-glob-test-ping)
(local-async-grains-items)
(runner-async-manage-present)
(wheel-async-key-list-all)
(local-async-graceful-shutdown)
(events-stream)
)
|
[
{
"context": "Each game is recorded as a hash-map, e.g.\n {:b \\\"Alice\\\" :w \\\"Bob\\\" :r \\\"b+1.5\\\"}.\n K - the factor for ",
"end": 406,
"score": 0.9996517896652222,
"start": 401,
"tag": "NAME",
"value": "Alice"
},
{
"context": "recorded as a hash-map, e.g.\n {:b \\\"Alice\\\" :w \\\"Bob\\\" :r \\\"b+1.5\\\"}.\n K - the factor for Elo calcula",
"end": 417,
"score": 0.999624490737915,
"start": 414,
"tag": "NAME",
"value": "Bob"
}
] | src/lgo/league.clj | egri-nagy/lambdago | 2 | (ns lgo.league
"Function for managing a league. Calculating updates in ranking for players."
(:require [lgo.elo :refer [rating-adjustment EA]]
[lgo.stats :refer [mean]]))
(defn process-games
"Batch processing game results. Games should be stored in a sequence.
The players' database is a hash-map of names (strings) to ratings.
Each game is recorded as a hash-map, e.g.
{:b \"Alice\" :w \"Bob\" :r \"b+1.5\"}.
K - the factor for Elo calculation."
[players games K]
(reduce (fn [plyrs {b :b w :w r :r}]
(let [Rb (plyrs b)
Rw (plyrs w)
S (if ( = (first r) \b) 1.0 0.0)
Db (rating-adjustment S (EA Rb Rw) K)]
(-> plyrs
(update-in [b] + Db)
(update-in [w] - Db))))
players
games))
(defn process-team-games
"Batch processing game results played by teams, pair go, rengo."
[players games K]
(reduce (fn [plyrs {b :b w :w r :r}]
(let [Rb (mean (map plyrs b))
Rw (mean (map plyrs w))
S (if ( = (first r) \b) 1.0 0.0)
Db (rating-adjustment S (EA Rb Rw) K)
rfn (fn [plyrs team delta op]
(reduce (fn [m x] (update-in m [x] op delta))
plyrs
team))]
(-> plyrs
(rfn b Db +)
(rfn w Db -))))
players
games))
(defn print-ratings
"Prints the names and the ratings to the console."
[players]
(doseq [[name rating] (reverse (sort-by second players))]
(println name " " rating)))
(defn even-pairings
"Gives a pairing for the players based on their ratings for even games
with nigiri. Missing players are ignored.
The top player can end up as a bye, or play a simul."
[players missing]
(let [names (map first players)
present (remove (set missing) names)
ordered (sort-by players present)]
(partition 2 ordered)))
(defn handicap-pairings
"Cuts the players into an upper and loewr part and pairs them systematically
by folding for handicap games."
[players missing]
(let [names (map first players)
present (remove (set missing) names)
ordered (sort-by players present)
h (int (/ (count ordered) 2))]
(apply map vector (partition h ordered))))
| 27180 | (ns lgo.league
"Function for managing a league. Calculating updates in ranking for players."
(:require [lgo.elo :refer [rating-adjustment EA]]
[lgo.stats :refer [mean]]))
(defn process-games
"Batch processing game results. Games should be stored in a sequence.
The players' database is a hash-map of names (strings) to ratings.
Each game is recorded as a hash-map, e.g.
{:b \"<NAME>\" :w \"<NAME>\" :r \"b+1.5\"}.
K - the factor for Elo calculation."
[players games K]
(reduce (fn [plyrs {b :b w :w r :r}]
(let [Rb (plyrs b)
Rw (plyrs w)
S (if ( = (first r) \b) 1.0 0.0)
Db (rating-adjustment S (EA Rb Rw) K)]
(-> plyrs
(update-in [b] + Db)
(update-in [w] - Db))))
players
games))
(defn process-team-games
"Batch processing game results played by teams, pair go, rengo."
[players games K]
(reduce (fn [plyrs {b :b w :w r :r}]
(let [Rb (mean (map plyrs b))
Rw (mean (map plyrs w))
S (if ( = (first r) \b) 1.0 0.0)
Db (rating-adjustment S (EA Rb Rw) K)
rfn (fn [plyrs team delta op]
(reduce (fn [m x] (update-in m [x] op delta))
plyrs
team))]
(-> plyrs
(rfn b Db +)
(rfn w Db -))))
players
games))
(defn print-ratings
"Prints the names and the ratings to the console."
[players]
(doseq [[name rating] (reverse (sort-by second players))]
(println name " " rating)))
(defn even-pairings
"Gives a pairing for the players based on their ratings for even games
with nigiri. Missing players are ignored.
The top player can end up as a bye, or play a simul."
[players missing]
(let [names (map first players)
present (remove (set missing) names)
ordered (sort-by players present)]
(partition 2 ordered)))
(defn handicap-pairings
"Cuts the players into an upper and loewr part and pairs them systematically
by folding for handicap games."
[players missing]
(let [names (map first players)
present (remove (set missing) names)
ordered (sort-by players present)
h (int (/ (count ordered) 2))]
(apply map vector (partition h ordered))))
| true | (ns lgo.league
"Function for managing a league. Calculating updates in ranking for players."
(:require [lgo.elo :refer [rating-adjustment EA]]
[lgo.stats :refer [mean]]))
(defn process-games
"Batch processing game results. Games should be stored in a sequence.
The players' database is a hash-map of names (strings) to ratings.
Each game is recorded as a hash-map, e.g.
{:b \"PI:NAME:<NAME>END_PI\" :w \"PI:NAME:<NAME>END_PI\" :r \"b+1.5\"}.
K - the factor for Elo calculation."
[players games K]
(reduce (fn [plyrs {b :b w :w r :r}]
(let [Rb (plyrs b)
Rw (plyrs w)
S (if ( = (first r) \b) 1.0 0.0)
Db (rating-adjustment S (EA Rb Rw) K)]
(-> plyrs
(update-in [b] + Db)
(update-in [w] - Db))))
players
games))
(defn process-team-games
"Batch processing game results played by teams, pair go, rengo."
[players games K]
(reduce (fn [plyrs {b :b w :w r :r}]
(let [Rb (mean (map plyrs b))
Rw (mean (map plyrs w))
S (if ( = (first r) \b) 1.0 0.0)
Db (rating-adjustment S (EA Rb Rw) K)
rfn (fn [plyrs team delta op]
(reduce (fn [m x] (update-in m [x] op delta))
plyrs
team))]
(-> plyrs
(rfn b Db +)
(rfn w Db -))))
players
games))
(defn print-ratings
"Prints the names and the ratings to the console."
[players]
(doseq [[name rating] (reverse (sort-by second players))]
(println name " " rating)))
(defn even-pairings
"Gives a pairing for the players based on their ratings for even games
with nigiri. Missing players are ignored.
The top player can end up as a bye, or play a simul."
[players missing]
(let [names (map first players)
present (remove (set missing) names)
ordered (sort-by players present)]
(partition 2 ordered)))
(defn handicap-pairings
"Cuts the players into an upper and loewr part and pairs them systematically
by folding for handicap games."
[players missing]
(let [names (map first players)
present (remove (set missing) names)
ordered (sort-by players present)
h (int (/ (count ordered) 2))]
(apply map vector (partition h ordered))))
|
[
{
"context": "Linear Temporal Logic\n\n; Copyright (c) 2016 - 2017 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu",
"end": 90,
"score": 0.9998689293861389,
"start": 76,
"tag": "NAME",
"value": "Burkhardt Renz"
}
] | src/lwb/ltl.clj | esb-lwb/lwb | 22 | ; lwb Logic WorkBench -- Linear Temporal Logic
; Copyright (c) 2016 - 2017 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.ltl
(:require [lwb.prop :as prop]
[potemkin :as pot]
[lwb.vis :as vis]
[clojure.spec.alpha :as s]
[clojure.java.browse :as browse]))
(defn man
"Manual"
[]
(browse/browse-url "https://github.com/esb-lwb/lwb/wiki/ltl"))
;; # Representation of formulas of ltl
;; The representation is like in propositional logic
;; We have 5 more operators in ltl:
;; * always -- unary
;; * atnext -- unary
;; * finally -- unary
;; * until -- binary
;; * release -- binary
;; We import the operators and so forth from propositional logic
(pot/import-vars
[lwb.prop impl equiv xor ite])
(defn op?
"Is `symb` an operator of ltl?"
[symb]
(let [operators '#{always atnext finally until release}]
(or (prop/op? symb) (contains? operators symb))))
(defn atom?
"Is `symb` an atomar proposition?"
[symb]
(and (symbol? symb) (not (op? symb))))
(defn arity
"Arity of operator `op`.
-1 means n-ary.
requires: `op` an operator."
[op]
(if
(prop/op? op) (prop/arity op)
(if (contains? '#{until release} op) 2
1)))
(defn atoms-of-phi
"Set of the propositional atoms of formula `phi`."
[phi]
(if (coll? phi)
(set (filter #(not (or (op? %) (boolean? %))) (flatten phi)))
(if (boolean? phi)
#{}
#{phi})))
;; A simple expression is an atom or a boolean constant.
(s/def ::simple-expr (s/or :bool boolean?
:atom atom?))
;; A compound expression is a list of an operator together with
;; several formulas as arguments whose number matches the arity of the operator.
(defn- arity-ok? [{:keys [op params]}]
(let [arity (arity op)]
(if (= arity -1) true
(= arity (count params)))))
(s/def ::compl-expr (s/and list? (s/& (s/cat :op op? :params (s/* ::fml)) arity-ok?)))
;; A formula is a simple or a complex expression.
(s/def ::fml (s/or :simple-expr ::simple-expr
:compl-expr ::compl-expr))
;; For natural deduction in ltl we need a special form of an ltl formula at a certain state
(s/def ::at-fml (s/cat :at #{'at} :state (s/coll-of symbol? :kind vector? :count 1) :fml ::fml))
;; ## Is a formula well-formed?
(defn wff?
"Is the formula `phi` well-formed?
`(wff? phi)` returns true or false.
`(wff? phi :exception-if-not)` returns true or throws an exception describing the error in `phi`."
([phi]
(wff? phi :bool))
([phi mode]
(let [result (s/valid? ::fml phi)]
(or result (if (= mode :exception-if-not) (throw (Exception. ^String (s/explain-str ::fml phi))) result)))))
(s/fdef wff?
:args (s/cat :phi any? :mode (s/? #{:bool :exception-if-not}))
:ret boolean?)
;; ## Negation normal form
;; ### Specification of a literal
(s/def ::literal (s/or :simple-expr ::simple-expr
:neg (s/and list? (s/cat :not #{'not} :simple-expr ::simple-expr))))
(defn literal?
"Checks whether `phi` is a literal, i.e. a propositional atom or its negation."
[phi]
(s/valid? ::literal phi))
;; ### Specification of negation normal form nnf
(s/def ::nnf-op '#{and or atnext until release})
(s/def ::nnf-compl-expr (s/and list? (s/& (s/cat :op ::nnf-op :params (s/* ::nnf-fml)) arity-ok?)))
(s/def ::nnf-fml (s/or :literal ::literal
:compl-expr ::nnf-compl-expr))
;; ### Reduction to the set of operators for nnf
(defn- impl-free
"Normalize formula `phi` such that just the operators `not`, `and`, `or`, `atnext`, `until`, `release` are used."
[phi]
(if (literal? phi)
phi
(let [op (first phi)]
(cond (contains? #{'and 'or 'not 'atnext 'until 'release} op) (apply list op (map impl-free (rest phi)))
(= op 'finally) (apply list 'until true (map impl-free (rest phi)))
(= op 'always) (apply list 'release false (map impl-free (rest phi)))
:else (let [exp-phi (binding [*ns* (find-ns 'lwb.prop)] (macroexpand-1 phi))]
(apply list (first exp-phi) (map impl-free (rest exp-phi))))))))
;; ### Transformation to nnf
(defn nnf
"Transforms `phi` into negation normal form."
[phi]
(let [phi' (impl-free phi)]
(if (literal? phi')
phi'
(let [[op & more] phi']
(if (= op 'not)
(let [[inner-op & inner-more] (second phi')]
(cond
(= inner-op 'and) (nnf (apply list 'or (map #(list 'not %) inner-more)))
(= inner-op 'or) (nnf (apply list 'and (map #(list 'not %) inner-more)))
(= inner-op 'atnext) (nnf (apply list 'atnext (map #(list 'not %) inner-more)))
(= inner-op 'until) (nnf (apply list 'release (map #(list 'not %) inner-more)))
(= inner-op 'release) (nnf (apply list 'until (map #(list 'not %) inner-more)))
:else (nnf (first inner-more))))
(apply list op (map nnf more)))))))
(s/fdef nnf
:args (s/cat :phi wff?)
:ret (s/alt :nnf ::nnf-fml :bool boolean?))
;; ### Check for nnf
(defn nnf?
"Is `phi` in negation normal form?
`(nnf? phi)` returns true or false.
`(nnf? phi :exception-if-not)` returns true or throws an exception describing the error in `phi`."
([phi]
(nnf? phi :bool))
([phi mode]
(let [result (s/valid? ::nnf-fml phi)]
(or result (if (= mode :exception-if-not) (throw (Exception. ^String (s/explain-str ::nnf-fml phi))) result)))))
(s/fdef nnf?
:args (s/cat :phi wff? :mode (s/? #{:bool :exception-if-not}))
:ret boolean?)
;; ## Visualisation of a formula
(defn texify
"Generates TeX code for TikZ or a pdf file if filename given.
Requires: TeX installation, commands in `lwb.util.shell`."
([phi]
(vis/texify phi))
([phi filename]
(vis/texify phi filename)))
(s/fdef texify
:args (s/cat :phi wff? :filename (s/? string?))
:ret nil?)
| 122021 | ; lwb Logic WorkBench -- Linear Temporal Logic
; Copyright (c) 2016 - 2017 <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.ltl
(:require [lwb.prop :as prop]
[potemkin :as pot]
[lwb.vis :as vis]
[clojure.spec.alpha :as s]
[clojure.java.browse :as browse]))
(defn man
"Manual"
[]
(browse/browse-url "https://github.com/esb-lwb/lwb/wiki/ltl"))
;; # Representation of formulas of ltl
;; The representation is like in propositional logic
;; We have 5 more operators in ltl:
;; * always -- unary
;; * atnext -- unary
;; * finally -- unary
;; * until -- binary
;; * release -- binary
;; We import the operators and so forth from propositional logic
(pot/import-vars
[lwb.prop impl equiv xor ite])
(defn op?
"Is `symb` an operator of ltl?"
[symb]
(let [operators '#{always atnext finally until release}]
(or (prop/op? symb) (contains? operators symb))))
(defn atom?
"Is `symb` an atomar proposition?"
[symb]
(and (symbol? symb) (not (op? symb))))
(defn arity
"Arity of operator `op`.
-1 means n-ary.
requires: `op` an operator."
[op]
(if
(prop/op? op) (prop/arity op)
(if (contains? '#{until release} op) 2
1)))
(defn atoms-of-phi
"Set of the propositional atoms of formula `phi`."
[phi]
(if (coll? phi)
(set (filter #(not (or (op? %) (boolean? %))) (flatten phi)))
(if (boolean? phi)
#{}
#{phi})))
;; A simple expression is an atom or a boolean constant.
(s/def ::simple-expr (s/or :bool boolean?
:atom atom?))
;; A compound expression is a list of an operator together with
;; several formulas as arguments whose number matches the arity of the operator.
(defn- arity-ok? [{:keys [op params]}]
(let [arity (arity op)]
(if (= arity -1) true
(= arity (count params)))))
(s/def ::compl-expr (s/and list? (s/& (s/cat :op op? :params (s/* ::fml)) arity-ok?)))
;; A formula is a simple or a complex expression.
(s/def ::fml (s/or :simple-expr ::simple-expr
:compl-expr ::compl-expr))
;; For natural deduction in ltl we need a special form of an ltl formula at a certain state
(s/def ::at-fml (s/cat :at #{'at} :state (s/coll-of symbol? :kind vector? :count 1) :fml ::fml))
;; ## Is a formula well-formed?
(defn wff?
"Is the formula `phi` well-formed?
`(wff? phi)` returns true or false.
`(wff? phi :exception-if-not)` returns true or throws an exception describing the error in `phi`."
([phi]
(wff? phi :bool))
([phi mode]
(let [result (s/valid? ::fml phi)]
(or result (if (= mode :exception-if-not) (throw (Exception. ^String (s/explain-str ::fml phi))) result)))))
(s/fdef wff?
:args (s/cat :phi any? :mode (s/? #{:bool :exception-if-not}))
:ret boolean?)
;; ## Negation normal form
;; ### Specification of a literal
(s/def ::literal (s/or :simple-expr ::simple-expr
:neg (s/and list? (s/cat :not #{'not} :simple-expr ::simple-expr))))
(defn literal?
"Checks whether `phi` is a literal, i.e. a propositional atom or its negation."
[phi]
(s/valid? ::literal phi))
;; ### Specification of negation normal form nnf
(s/def ::nnf-op '#{and or atnext until release})
(s/def ::nnf-compl-expr (s/and list? (s/& (s/cat :op ::nnf-op :params (s/* ::nnf-fml)) arity-ok?)))
(s/def ::nnf-fml (s/or :literal ::literal
:compl-expr ::nnf-compl-expr))
;; ### Reduction to the set of operators for nnf
(defn- impl-free
"Normalize formula `phi` such that just the operators `not`, `and`, `or`, `atnext`, `until`, `release` are used."
[phi]
(if (literal? phi)
phi
(let [op (first phi)]
(cond (contains? #{'and 'or 'not 'atnext 'until 'release} op) (apply list op (map impl-free (rest phi)))
(= op 'finally) (apply list 'until true (map impl-free (rest phi)))
(= op 'always) (apply list 'release false (map impl-free (rest phi)))
:else (let [exp-phi (binding [*ns* (find-ns 'lwb.prop)] (macroexpand-1 phi))]
(apply list (first exp-phi) (map impl-free (rest exp-phi))))))))
;; ### Transformation to nnf
(defn nnf
"Transforms `phi` into negation normal form."
[phi]
(let [phi' (impl-free phi)]
(if (literal? phi')
phi'
(let [[op & more] phi']
(if (= op 'not)
(let [[inner-op & inner-more] (second phi')]
(cond
(= inner-op 'and) (nnf (apply list 'or (map #(list 'not %) inner-more)))
(= inner-op 'or) (nnf (apply list 'and (map #(list 'not %) inner-more)))
(= inner-op 'atnext) (nnf (apply list 'atnext (map #(list 'not %) inner-more)))
(= inner-op 'until) (nnf (apply list 'release (map #(list 'not %) inner-more)))
(= inner-op 'release) (nnf (apply list 'until (map #(list 'not %) inner-more)))
:else (nnf (first inner-more))))
(apply list op (map nnf more)))))))
(s/fdef nnf
:args (s/cat :phi wff?)
:ret (s/alt :nnf ::nnf-fml :bool boolean?))
;; ### Check for nnf
(defn nnf?
"Is `phi` in negation normal form?
`(nnf? phi)` returns true or false.
`(nnf? phi :exception-if-not)` returns true or throws an exception describing the error in `phi`."
([phi]
(nnf? phi :bool))
([phi mode]
(let [result (s/valid? ::nnf-fml phi)]
(or result (if (= mode :exception-if-not) (throw (Exception. ^String (s/explain-str ::nnf-fml phi))) result)))))
(s/fdef nnf?
:args (s/cat :phi wff? :mode (s/? #{:bool :exception-if-not}))
:ret boolean?)
;; ## Visualisation of a formula
(defn texify
"Generates TeX code for TikZ or a pdf file if filename given.
Requires: TeX installation, commands in `lwb.util.shell`."
([phi]
(vis/texify phi))
([phi filename]
(vis/texify phi filename)))
(s/fdef texify
:args (s/cat :phi wff? :filename (s/? string?))
:ret nil?)
| true | ; lwb Logic WorkBench -- Linear Temporal Logic
; Copyright (c) 2016 - 2017 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.ltl
(:require [lwb.prop :as prop]
[potemkin :as pot]
[lwb.vis :as vis]
[clojure.spec.alpha :as s]
[clojure.java.browse :as browse]))
(defn man
"Manual"
[]
(browse/browse-url "https://github.com/esb-lwb/lwb/wiki/ltl"))
;; # Representation of formulas of ltl
;; The representation is like in propositional logic
;; We have 5 more operators in ltl:
;; * always -- unary
;; * atnext -- unary
;; * finally -- unary
;; * until -- binary
;; * release -- binary
;; We import the operators and so forth from propositional logic
(pot/import-vars
[lwb.prop impl equiv xor ite])
(defn op?
"Is `symb` an operator of ltl?"
[symb]
(let [operators '#{always atnext finally until release}]
(or (prop/op? symb) (contains? operators symb))))
(defn atom?
"Is `symb` an atomar proposition?"
[symb]
(and (symbol? symb) (not (op? symb))))
(defn arity
"Arity of operator `op`.
-1 means n-ary.
requires: `op` an operator."
[op]
(if
(prop/op? op) (prop/arity op)
(if (contains? '#{until release} op) 2
1)))
(defn atoms-of-phi
"Set of the propositional atoms of formula `phi`."
[phi]
(if (coll? phi)
(set (filter #(not (or (op? %) (boolean? %))) (flatten phi)))
(if (boolean? phi)
#{}
#{phi})))
;; A simple expression is an atom or a boolean constant.
(s/def ::simple-expr (s/or :bool boolean?
:atom atom?))
;; A compound expression is a list of an operator together with
;; several formulas as arguments whose number matches the arity of the operator.
(defn- arity-ok? [{:keys [op params]}]
(let [arity (arity op)]
(if (= arity -1) true
(= arity (count params)))))
(s/def ::compl-expr (s/and list? (s/& (s/cat :op op? :params (s/* ::fml)) arity-ok?)))
;; A formula is a simple or a complex expression.
(s/def ::fml (s/or :simple-expr ::simple-expr
:compl-expr ::compl-expr))
;; For natural deduction in ltl we need a special form of an ltl formula at a certain state
(s/def ::at-fml (s/cat :at #{'at} :state (s/coll-of symbol? :kind vector? :count 1) :fml ::fml))
;; ## Is a formula well-formed?
(defn wff?
"Is the formula `phi` well-formed?
`(wff? phi)` returns true or false.
`(wff? phi :exception-if-not)` returns true or throws an exception describing the error in `phi`."
([phi]
(wff? phi :bool))
([phi mode]
(let [result (s/valid? ::fml phi)]
(or result (if (= mode :exception-if-not) (throw (Exception. ^String (s/explain-str ::fml phi))) result)))))
(s/fdef wff?
:args (s/cat :phi any? :mode (s/? #{:bool :exception-if-not}))
:ret boolean?)
;; ## Negation normal form
;; ### Specification of a literal
(s/def ::literal (s/or :simple-expr ::simple-expr
:neg (s/and list? (s/cat :not #{'not} :simple-expr ::simple-expr))))
(defn literal?
"Checks whether `phi` is a literal, i.e. a propositional atom or its negation."
[phi]
(s/valid? ::literal phi))
;; ### Specification of negation normal form nnf
(s/def ::nnf-op '#{and or atnext until release})
(s/def ::nnf-compl-expr (s/and list? (s/& (s/cat :op ::nnf-op :params (s/* ::nnf-fml)) arity-ok?)))
(s/def ::nnf-fml (s/or :literal ::literal
:compl-expr ::nnf-compl-expr))
;; ### Reduction to the set of operators for nnf
(defn- impl-free
"Normalize formula `phi` such that just the operators `not`, `and`, `or`, `atnext`, `until`, `release` are used."
[phi]
(if (literal? phi)
phi
(let [op (first phi)]
(cond (contains? #{'and 'or 'not 'atnext 'until 'release} op) (apply list op (map impl-free (rest phi)))
(= op 'finally) (apply list 'until true (map impl-free (rest phi)))
(= op 'always) (apply list 'release false (map impl-free (rest phi)))
:else (let [exp-phi (binding [*ns* (find-ns 'lwb.prop)] (macroexpand-1 phi))]
(apply list (first exp-phi) (map impl-free (rest exp-phi))))))))
;; ### Transformation to nnf
(defn nnf
"Transforms `phi` into negation normal form."
[phi]
(let [phi' (impl-free phi)]
(if (literal? phi')
phi'
(let [[op & more] phi']
(if (= op 'not)
(let [[inner-op & inner-more] (second phi')]
(cond
(= inner-op 'and) (nnf (apply list 'or (map #(list 'not %) inner-more)))
(= inner-op 'or) (nnf (apply list 'and (map #(list 'not %) inner-more)))
(= inner-op 'atnext) (nnf (apply list 'atnext (map #(list 'not %) inner-more)))
(= inner-op 'until) (nnf (apply list 'release (map #(list 'not %) inner-more)))
(= inner-op 'release) (nnf (apply list 'until (map #(list 'not %) inner-more)))
:else (nnf (first inner-more))))
(apply list op (map nnf more)))))))
(s/fdef nnf
:args (s/cat :phi wff?)
:ret (s/alt :nnf ::nnf-fml :bool boolean?))
;; ### Check for nnf
(defn nnf?
"Is `phi` in negation normal form?
`(nnf? phi)` returns true or false.
`(nnf? phi :exception-if-not)` returns true or throws an exception describing the error in `phi`."
([phi]
(nnf? phi :bool))
([phi mode]
(let [result (s/valid? ::nnf-fml phi)]
(or result (if (= mode :exception-if-not) (throw (Exception. ^String (s/explain-str ::nnf-fml phi))) result)))))
(s/fdef nnf?
:args (s/cat :phi wff? :mode (s/? #{:bool :exception-if-not}))
:ret boolean?)
;; ## Visualisation of a formula
(defn texify
"Generates TeX code for TikZ or a pdf file if filename given.
Requires: TeX installation, commands in `lwb.util.shell`."
([phi]
(vis/texify phi))
([phi filename]
(vis/texify phi filename)))
(s/fdef texify
:args (s/cat :phi wff? :filename (s/? string?))
:ret nil?)
|
[
{
"context": " (r/atom (core/start-game (core/init-game-state [\"Allan\" \"Adi\" \"Quan\" \"Lucy\"]))))\n\n(defn play-move [card]",
"end": 194,
"score": 0.9996907114982605,
"start": 189,
"tag": "NAME",
"value": "Allan"
},
{
"context": " (core/start-game (core/init-game-state [\"Allan\" \"Adi\" \"Quan\" \"Lucy\"]))))\n\n(defn play-move [card]\n (tr",
"end": 200,
"score": 0.9993962049484253,
"start": 197,
"tag": "NAME",
"value": "Adi"
},
{
"context": "/start-game (core/init-game-state [\"Allan\" \"Adi\" \"Quan\" \"Lucy\"]))))\n\n(defn play-move [card]\n (try\n (",
"end": 207,
"score": 0.9993506669998169,
"start": 203,
"tag": "NAME",
"value": "Quan"
},
{
"context": "game (core/init-game-state [\"Allan\" \"Adi\" \"Quan\" \"Lucy\"]))))\n\n(defn play-move [card]\n (try\n (doto st",
"end": 214,
"score": 0.9986090660095215,
"start": 210,
"tag": "NAME",
"value": "Lucy"
}
] | src/hearts/view.cljs | jiangts/hearts-clojure | 0 | (ns hearts.view
(:require
[reagent.core :as r]
[hearts.utils :as utils :refer [spy]]
[hearts.core :as core]))
(defonce state (r/atom (core/start-game (core/init-game-state ["Allan" "Adi" "Quan" "Lucy"]))))
(defn play-move [card]
(try
(doto state
(swap! core/play-turn card)
(swap! dissoc :exception))
(catch js/Object e
(swap! state assoc :exception e))))
(add-watch state :lifecycle
(fn [_ _ old-state new-state]
(when (core/game-over? new-state)
(core/game-winner new-state))))
(enable-console-print!)
(def scale 1)
(def card-width (* 80 scale))
(def card-height (* 120 scale))
(def board-size (* 600 scale))
(def rank->name
(let [numbers (map str (range 2 10))]
(merge {"T" "10"
"A" "ace"
"J" "jack"
"Q" "queen"
"K" "king"}
(zipmap numbers numbers))))
(def suit->name {"D" "diamonds"
"H" "hearts"
"S" "spades"
"C" "clubs"})
(defn card->svg [card]
(if (= card "XX")
"img/cards/card_back.svg"
(let [[rank suit] card]
(str "img/cards/" (rank->name rank) "_of_" (suit->name suit) ".svg"))))
(defn card
([c]
[card {} c])
([opts c]
(let [default {:src (card->svg c)
:style {:width card-width
:height card-height
:position :absolute}
:on-click #(play-move c)}]
[:img (merge-with conj default opts)])))
(defn hand
([cards]
[hand {} cards])
([opts cards]
(let [offset #(identity {:style {:left (* (/ card-width 5) %)}})
default-style {:style {:height card-height
:position :relative}}]
(into [:div (merge-with conj default-style opts)]
(map-indexed #(identity [card (offset %1) %2]) cards)))))
(defn trick
([cards]
[trick {} cards])
([opts {:keys [N E S W] :as cards}]
(let [separation card-width
-separation (- separation)
x-offset (/ card-height 4)
style-map {N {:class "rot-180"
:style {:top -separation}}
W {:class "rot-90"
:style {:left -separation}}
E {:class "rot-90"
:style {:left separation}}
S {:style {:top separation}}}
items (remove #(nil? (key %)) style-map)
default {:style {:height (* 2 card-height)
:position :relative}}]
(when (seq cards)
(into [:div (merge-with conj default opts)]
(map #(into [card] (reverse %)) items))))))
(defn one-hand [[_ opt] cards]
[hand (merge-with conj {:style {:position :absolute}} opt) cards])
(defn center-trick [cards]
(let [offset #(-> board-size (- %) (/ 2))]
[trick {:style {:top (offset card-height)
:right (- (offset card-width))
:pointer-events :none}}
cards]))
(defn score [index player]
[:div {:style {:display :inline-block
:width (/ board-size 4)}}
[:h3 "Player " (inc index) ": " (:name player)]
[:p "Score: " (+ (core/player-score player) (:score player))]])
(defn game [state]
(fn [state]
(let [{:keys [ntrick turn players trick exception]} @state
positions (zipmap [:S :E :N :W] players)
hands (map :hand players)
rot-x-offset (/ card-height 2)
rot-y-offset (-> board-size (- (/ card-height 2)))
dir-order [:S :E :N :W]
dir-opts {:S {:style {:bottom 0}}
:E {:class "rot-270"
:style {:right rot-x-offset
:top rot-y-offset}}
:N {:class "rot-180"
:style {:left board-size}}
:W {:class "rot-90"
:style {:left rot-x-offset
:bottom rot-y-offset}}}
n-players (count players)
start-dir (- n-players (mod (- ntrick turn) n-players))]
[:div
[:h1 "Player " (inc turn) "'s move (" (nth dir-order turn) ")"]
[:h3 {:style {:color :red}}
(when exception (.-message exception))]
[:div {:style {:width board-size
:height board-size
:background-color "#265C33"
:position :relative}}
(into [:div] (mapv one-hand dir-opts hands))
[center-trick (zipmap (drop start-dir (cycle dir-order)) trick)]]
(into [:div] (map-indexed score players))])))
| 114786 | (ns hearts.view
(:require
[reagent.core :as r]
[hearts.utils :as utils :refer [spy]]
[hearts.core :as core]))
(defonce state (r/atom (core/start-game (core/init-game-state ["<NAME>" "<NAME>" "<NAME>" "<NAME>"]))))
(defn play-move [card]
(try
(doto state
(swap! core/play-turn card)
(swap! dissoc :exception))
(catch js/Object e
(swap! state assoc :exception e))))
(add-watch state :lifecycle
(fn [_ _ old-state new-state]
(when (core/game-over? new-state)
(core/game-winner new-state))))
(enable-console-print!)
(def scale 1)
(def card-width (* 80 scale))
(def card-height (* 120 scale))
(def board-size (* 600 scale))
(def rank->name
(let [numbers (map str (range 2 10))]
(merge {"T" "10"
"A" "ace"
"J" "jack"
"Q" "queen"
"K" "king"}
(zipmap numbers numbers))))
(def suit->name {"D" "diamonds"
"H" "hearts"
"S" "spades"
"C" "clubs"})
(defn card->svg [card]
(if (= card "XX")
"img/cards/card_back.svg"
(let [[rank suit] card]
(str "img/cards/" (rank->name rank) "_of_" (suit->name suit) ".svg"))))
(defn card
([c]
[card {} c])
([opts c]
(let [default {:src (card->svg c)
:style {:width card-width
:height card-height
:position :absolute}
:on-click #(play-move c)}]
[:img (merge-with conj default opts)])))
(defn hand
([cards]
[hand {} cards])
([opts cards]
(let [offset #(identity {:style {:left (* (/ card-width 5) %)}})
default-style {:style {:height card-height
:position :relative}}]
(into [:div (merge-with conj default-style opts)]
(map-indexed #(identity [card (offset %1) %2]) cards)))))
(defn trick
([cards]
[trick {} cards])
([opts {:keys [N E S W] :as cards}]
(let [separation card-width
-separation (- separation)
x-offset (/ card-height 4)
style-map {N {:class "rot-180"
:style {:top -separation}}
W {:class "rot-90"
:style {:left -separation}}
E {:class "rot-90"
:style {:left separation}}
S {:style {:top separation}}}
items (remove #(nil? (key %)) style-map)
default {:style {:height (* 2 card-height)
:position :relative}}]
(when (seq cards)
(into [:div (merge-with conj default opts)]
(map #(into [card] (reverse %)) items))))))
(defn one-hand [[_ opt] cards]
[hand (merge-with conj {:style {:position :absolute}} opt) cards])
(defn center-trick [cards]
(let [offset #(-> board-size (- %) (/ 2))]
[trick {:style {:top (offset card-height)
:right (- (offset card-width))
:pointer-events :none}}
cards]))
(defn score [index player]
[:div {:style {:display :inline-block
:width (/ board-size 4)}}
[:h3 "Player " (inc index) ": " (:name player)]
[:p "Score: " (+ (core/player-score player) (:score player))]])
(defn game [state]
(fn [state]
(let [{:keys [ntrick turn players trick exception]} @state
positions (zipmap [:S :E :N :W] players)
hands (map :hand players)
rot-x-offset (/ card-height 2)
rot-y-offset (-> board-size (- (/ card-height 2)))
dir-order [:S :E :N :W]
dir-opts {:S {:style {:bottom 0}}
:E {:class "rot-270"
:style {:right rot-x-offset
:top rot-y-offset}}
:N {:class "rot-180"
:style {:left board-size}}
:W {:class "rot-90"
:style {:left rot-x-offset
:bottom rot-y-offset}}}
n-players (count players)
start-dir (- n-players (mod (- ntrick turn) n-players))]
[:div
[:h1 "Player " (inc turn) "'s move (" (nth dir-order turn) ")"]
[:h3 {:style {:color :red}}
(when exception (.-message exception))]
[:div {:style {:width board-size
:height board-size
:background-color "#265C33"
:position :relative}}
(into [:div] (mapv one-hand dir-opts hands))
[center-trick (zipmap (drop start-dir (cycle dir-order)) trick)]]
(into [:div] (map-indexed score players))])))
| true | (ns hearts.view
(:require
[reagent.core :as r]
[hearts.utils :as utils :refer [spy]]
[hearts.core :as core]))
(defonce state (r/atom (core/start-game (core/init-game-state ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]))))
(defn play-move [card]
(try
(doto state
(swap! core/play-turn card)
(swap! dissoc :exception))
(catch js/Object e
(swap! state assoc :exception e))))
(add-watch state :lifecycle
(fn [_ _ old-state new-state]
(when (core/game-over? new-state)
(core/game-winner new-state))))
(enable-console-print!)
(def scale 1)
(def card-width (* 80 scale))
(def card-height (* 120 scale))
(def board-size (* 600 scale))
(def rank->name
(let [numbers (map str (range 2 10))]
(merge {"T" "10"
"A" "ace"
"J" "jack"
"Q" "queen"
"K" "king"}
(zipmap numbers numbers))))
(def suit->name {"D" "diamonds"
"H" "hearts"
"S" "spades"
"C" "clubs"})
(defn card->svg [card]
(if (= card "XX")
"img/cards/card_back.svg"
(let [[rank suit] card]
(str "img/cards/" (rank->name rank) "_of_" (suit->name suit) ".svg"))))
(defn card
([c]
[card {} c])
([opts c]
(let [default {:src (card->svg c)
:style {:width card-width
:height card-height
:position :absolute}
:on-click #(play-move c)}]
[:img (merge-with conj default opts)])))
(defn hand
([cards]
[hand {} cards])
([opts cards]
(let [offset #(identity {:style {:left (* (/ card-width 5) %)}})
default-style {:style {:height card-height
:position :relative}}]
(into [:div (merge-with conj default-style opts)]
(map-indexed #(identity [card (offset %1) %2]) cards)))))
(defn trick
([cards]
[trick {} cards])
([opts {:keys [N E S W] :as cards}]
(let [separation card-width
-separation (- separation)
x-offset (/ card-height 4)
style-map {N {:class "rot-180"
:style {:top -separation}}
W {:class "rot-90"
:style {:left -separation}}
E {:class "rot-90"
:style {:left separation}}
S {:style {:top separation}}}
items (remove #(nil? (key %)) style-map)
default {:style {:height (* 2 card-height)
:position :relative}}]
(when (seq cards)
(into [:div (merge-with conj default opts)]
(map #(into [card] (reverse %)) items))))))
(defn one-hand [[_ opt] cards]
[hand (merge-with conj {:style {:position :absolute}} opt) cards])
(defn center-trick [cards]
(let [offset #(-> board-size (- %) (/ 2))]
[trick {:style {:top (offset card-height)
:right (- (offset card-width))
:pointer-events :none}}
cards]))
(defn score [index player]
[:div {:style {:display :inline-block
:width (/ board-size 4)}}
[:h3 "Player " (inc index) ": " (:name player)]
[:p "Score: " (+ (core/player-score player) (:score player))]])
(defn game [state]
(fn [state]
(let [{:keys [ntrick turn players trick exception]} @state
positions (zipmap [:S :E :N :W] players)
hands (map :hand players)
rot-x-offset (/ card-height 2)
rot-y-offset (-> board-size (- (/ card-height 2)))
dir-order [:S :E :N :W]
dir-opts {:S {:style {:bottom 0}}
:E {:class "rot-270"
:style {:right rot-x-offset
:top rot-y-offset}}
:N {:class "rot-180"
:style {:left board-size}}
:W {:class "rot-90"
:style {:left rot-x-offset
:bottom rot-y-offset}}}
n-players (count players)
start-dir (- n-players (mod (- ntrick turn) n-players))]
[:div
[:h1 "Player " (inc turn) "'s move (" (nth dir-order turn) ")"]
[:h3 {:style {:color :red}}
(when exception (.-message exception))]
[:div {:style {:width board-size
:height board-size
:background-color "#265C33"
:position :relative}}
(into [:div] (mapv one-hand dir-opts hands))
[center-trick (zipmap (drop start-dir (cycle dir-order)) trick)]]
(into [:div] (map-indexed score players))])))
|
[
{
"context": "masq instance expected to be available at https://192.168.1.10:8444\"\n (:require \n [re-core.persistency.syste",
"end": 118,
"score": 0.9996476769447327,
"start": 106,
"tag": "IP_ADDRESS",
"value": "192.168.1.10"
},
{
"context": "(def conf {\n :domain \"local\" :tinymasq \"https://192.168.1.10:8444\" :user \"admin\" :password \"foobar\"\n })\n\n(def ",
"end": 475,
"score": 0.9996242523193359,
"start": 463,
"tag": "IP_ADDRESS",
"value": "192.168.1.10"
},
{
"context": "cal\" :tinymasq \"https://192.168.1.10:8444\" :user \"admin\" :password \"foobar\"\n })\n\n(def create (merge conf ",
"end": 494,
"score": 0.6428444981575012,
"start": 489,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "tps://192.168.1.10:8444\" :user \"admin\" :password \"foobar\"\n })\n\n(def create (merge conf {:event :success :w",
"end": 513,
"score": 0.9993082284927368,
"start": 507,
"tag": "PASSWORD",
"value": "foobar"
},
{
"context": "ate-changes [(before :facts (set-user {:username \"admin\"} (populate-all)))]\n (fact \"adding a new host\"",
"end": 844,
"score": 0.9986950755119324,
"start": 839,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "ion :hooks :tinymasq \n (set-user {:username \"admin\"}\n (s/update-system 1 (merge-with merge (s",
"end": 959,
"score": 0.9986841082572937,
"start": 954,
"tag": "USERNAME",
"value": "admin"
}
] | test/re_core/integration/hooks.clj | celestial-ops/core | 1 | (ns re-core.integration.hooks
"Updating an actual tinymasq instance expected to be available at https://192.168.1.10:8444"
(:require
[re-core.persistency.systems :as s]
[re-core.fixtures.populate :refer (populate-all)]
[re-core.security :refer (set-user)]
[re-core.fixtures.core :refer (with-defaults with-conf)]
[hooks.tinymasq :refer (update-dns remove-host)])
(:use midje.sweet)
)
(def conf {
:domain "local" :tinymasq "https://192.168.1.10:8444" :user "admin" :password "foobar"
})
(def create (merge conf {:event :success :workflow :create :system-id 1}))
(def reload (merge conf {:event :success :workflow :reload :system-id 1}))
(def machine {:machine {:hostname "dummy" "ip" "1.2.3.4"}})
(def delete (merge conf machine))
(with-conf
(with-state-changes [(before :facts (set-user {:username "admin"} (populate-all)))]
(fact "adding a new host" :integration :hooks :tinymasq
(set-user {:username "admin"}
(s/update-system 1 (merge-with merge (s/get-system 1) machine))
(update-dns create) => "host added"
(update-dns reload) => "host updated"
(remove-host delete) => "host removed"))))
| 16907 | (ns re-core.integration.hooks
"Updating an actual tinymasq instance expected to be available at https://192.168.1.10:8444"
(:require
[re-core.persistency.systems :as s]
[re-core.fixtures.populate :refer (populate-all)]
[re-core.security :refer (set-user)]
[re-core.fixtures.core :refer (with-defaults with-conf)]
[hooks.tinymasq :refer (update-dns remove-host)])
(:use midje.sweet)
)
(def conf {
:domain "local" :tinymasq "https://192.168.1.10:8444" :user "admin" :password "<PASSWORD>"
})
(def create (merge conf {:event :success :workflow :create :system-id 1}))
(def reload (merge conf {:event :success :workflow :reload :system-id 1}))
(def machine {:machine {:hostname "dummy" "ip" "1.2.3.4"}})
(def delete (merge conf machine))
(with-conf
(with-state-changes [(before :facts (set-user {:username "admin"} (populate-all)))]
(fact "adding a new host" :integration :hooks :tinymasq
(set-user {:username "admin"}
(s/update-system 1 (merge-with merge (s/get-system 1) machine))
(update-dns create) => "host added"
(update-dns reload) => "host updated"
(remove-host delete) => "host removed"))))
| true | (ns re-core.integration.hooks
"Updating an actual tinymasq instance expected to be available at https://192.168.1.10:8444"
(:require
[re-core.persistency.systems :as s]
[re-core.fixtures.populate :refer (populate-all)]
[re-core.security :refer (set-user)]
[re-core.fixtures.core :refer (with-defaults with-conf)]
[hooks.tinymasq :refer (update-dns remove-host)])
(:use midje.sweet)
)
(def conf {
:domain "local" :tinymasq "https://192.168.1.10:8444" :user "admin" :password "PI:PASSWORD:<PASSWORD>END_PI"
})
(def create (merge conf {:event :success :workflow :create :system-id 1}))
(def reload (merge conf {:event :success :workflow :reload :system-id 1}))
(def machine {:machine {:hostname "dummy" "ip" "1.2.3.4"}})
(def delete (merge conf machine))
(with-conf
(with-state-changes [(before :facts (set-user {:username "admin"} (populate-all)))]
(fact "adding a new host" :integration :hooks :tinymasq
(set-user {:username "admin"}
(s/update-system 1 (merge-with merge (s/get-system 1) machine))
(update-dns create) => "host added"
(update-dns reload) => "host updated"
(remove-host delete) => "host removed"))))
|
[
{
"context": "========================\n; Copyright (C) 2017-2022 Radislav (Radicchio) Golubtsov\n;\n; (See the LICENSE file at the top of",
"end": 560,
"score": 0.9740314483642578,
"start": 541,
"tag": "NAME",
"value": "Radislav (Radicchio"
},
{
"context": "===\n; Copyright (C) 2017-2022 Radislav (Radicchio) Golubtsov\n;\n; (See the LICENSE file at the top of the sourc",
"end": 571,
"score": 0.999455988407135,
"start": 562,
"tag": "NAME",
"value": "Golubtsov"
}
] | src/clojure/srcs/dnsresolvd.clj | rgolubtsov/dnsresolvd-multilang | 2 | ;
; src/clojure/src/dnsresolvd.clj
; =============================================================================
; DNS Resolver Daemon (dnsresolvd). Version 0.9.9
; =============================================================================
; A daemon that performs DNS lookups for the given hostname
; passed in an HTTP request, with the focus on its implementation
; using various programming languages. (HTTP Kit-boosted impl.)
; =============================================================================
; Copyright (C) 2017-2022 Radislav (Radicchio) Golubtsov
;
; (See the LICENSE file at the top of the source tree.)
;
(ns dnsresolvd
"The main module of the daemon."
(:require
[dnsresolvh :as AUX]
[clojure.walk :refer [
keywordize-keys
]]
[org.httpkit.server :refer [
run-server
with-channel
send!
]]
[clojure.data.json :refer [
write-str
]]
)
(:import [java.net InetAddress ])
(:import [java.net Inet4Address])
(:import [java.net Inet6Address])
)
(defn dns-lookup
"Performs DNS lookup action for the given hostname,
i.e. (in this case) IP address retrieval by hostname.
Args:
hostname: The effective hostname to look up for.
Returns:
The list containing IP address of the analyzed host/service
and a corresponding IP version (family) used to look up in DNS:
"4" for IPv4-only hosts, "6" for IPv6-capable hosts.
" [hostname]
; Trying to get an A record (IPv4) for the host or its AAAA record (IPv6).
(try
(let [hostent (InetAddress/getByName hostname)]
(list
(.getHostAddress hostent)
(cond
(instance? Inet4Address hostent) 4
(instance? Inet6Address hostent) 6
)
))
(catch
java.net.UnknownHostException e (list (AUX/ERR-PREFIX) nil)
))
)
(defn reqhandler
"The request handler callback.
Gets called when a new incoming HTTP request is received.
Args:
req: The incoming HTTP request object.
Returns:
The HTTP status code, response headers, and a body of the response.
" [req]
(let [mtd (get req :request-method)]
; -------------------------------------------------------------------------
; --- Parsing and validating request params - Begin -----------------------
; -------------------------------------------------------------------------
(let [params- (cond
(= mtd :get )
(let [params0 (get req :query-string)]
(if (nil? params0) (AUX/EMPTY-STRING) params0))
(= mtd :post)
(let [params0 (get req :body )]
(if (nil? params0) (AUX/EMPTY-STRING) (slurp params0)))
:else
(AUX/EMPTY-STRING)
)]
(let [params (keywordize-keys
(try
(apply hash-map (clojure.string/split params- (AUX/PARAMS-SEPS)))
(catch
IllegalArgumentException e {
:h (AUX/DEF-HOSTNAME)
:f (AUX/PRM-FMT-JSON)
}
))
)]
(let [hostname
(let [hostname0 (get params :h)] ; <------+----------------------+
(if (nil? hostname0) (AUX/DEF-HOSTNAME) ; | |
hostname0))] ; | |
; +----GET----+-----+-----+ | |
; | | | | | | |
; | | | | | +---+ +-------------+-+
; v v v v v | | | |
; $ curl 'http://localhost:<port-number>/?h=<hostname>&f=<fmt>' | |
; $ | |
; $ curl -d 'h=<hostname>&f=<fmt>' http://localhost:<port-number> | |
; ^ | | | |
; | +------------+------------------------------------------+ |
; | | |
; POST----+ +------+ |
; | |
(let [fmt- ; v |
(let [fmt0 (get params :f)] ; <-------------------------------+
(if (nil? fmt0 ) (AUX/PRM-FMT-JSON)
(clojure.string/lower-case fmt0)))]
(let [fmt
(if (not (some #{fmt-} (list
(AUX/PRM-FMT-HTML)
(AUX/PRM-FMT-JSON)
))) (AUX/PRM-FMT-JSON) fmt-)]
; -------------------------------------------------------------------------
; --- Parsing and validating request params - End -------------------------
; -------------------------------------------------------------------------
; Performing DNS lookup for the given hostname.
(let [addr-ver (dns-lookup hostname)]
(let [addr (nth addr-ver 0)]
(let [ver (nth addr-ver 1)]
(let [resp-buffer- (cond
(= fmt (AUX/PRM-FMT-HTML))
(str "<!DOCTYPE html>" (AUX/NEW-LINE)
"<html lang=\"en-US\" dir=\"ltr\">" (AUX/NEW-LINE)
"<head>" (AUX/NEW-LINE)
"<meta http-equiv=\"" (AUX/HDR-CONTENT-TYPE-N ) "\" content=\""
(AUX/HDR-CONTENT-TYPE-V-HTML) "\" />" (AUX/NEW-LINE)
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />" (AUX/NEW-LINE)
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />" (AUX/NEW-LINE)
"<title>" (AUX/DMN-NAME ) "</title>" (AUX/NEW-LINE)
"</head>" (AUX/NEW-LINE)
"<body>" (AUX/NEW-LINE)
"<div>" hostname (AUX/ONE-SPACE-STRING ))
(= fmt (AUX/PRM-FMT-JSON))
(hash-map (AUX/DAT-HOSTNAME-N )
hostname)
)]
; If lookup error occurred.
(let [resp-buffer0 (cond
(= addr (AUX/ERR-PREFIX)) (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer- (AUX/ERR-PREFIX )
(AUX/COLON-SPACE-SEP )
(AUX/ERR-COULD-NOT-LOOKUP))
(= fmt (AUX/PRM-FMT-JSON))
(assoc resp-buffer- (AUX/ERR-PREFIX )
(AUX/ERR-COULD-NOT-LOOKUP))
) :else (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer- addr
(AUX/ONE-SPACE-STRING )
(AUX/DAT-VERSION-V )
ver )
(= fmt (AUX/PRM-FMT-JSON))
(assoc resp-buffer- (AUX/DAT-ADDRESS-N )
addr
(AUX/DAT-VERSION-N )
(str (AUX/DAT-VERSION-V )
ver ))
)
)]
(let [resp-buffer (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer0 "</div>" (AUX/NEW-LINE)
"</body>" (AUX/NEW-LINE)
"</html>" (AUX/NEW-LINE))
(= fmt (AUX/PRM-FMT-JSON))
(write-str resp-buffer0)
)]
; Returning the HTTP status code, response headers,
; and a body of the response.
(with-channel req channel (send! channel { ; <== Async mode !
:status (AUX/RSC-HTTP-200-OK)
:headers (AUX/add-response-headers fmt)
:body resp-buffer
} )
)
)
)
)
) ) )
) ) )
)))
)
(defn startup
"Starts up the daemon.
Args:
args: A list containing the server port number to listen on
as the first element.
Returns:
The exit code indicating the daemon overall termination status.
" [args]
(let [port-number (nth args 0)]
(let [daemon-name (nth args 1)]
(let [log (nth args 2)]
; Trying to start up the HTTP Kit server on <port-number>.
(try
(run-server reqhandler {
:port port-number
})
(println (str (AUX/MSG-SERVER-STARTED-1) port-number (AUX/NEW-LINE)
(AUX/MSG-SERVER-STARTED-2)))
(.info log (str (AUX/MSG-SERVER-STARTED-1) port-number (AUX/NEW-LINE)
(AUX/MSG-SERVER-STARTED-2)))
(.join (Thread/currentThread)) ; <== Important !
(catch java.net.BindException e
(binding [*out* *err*]
(println (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-PORT-IS-IN-USE )
(AUX/NEW-LINE)))
(.error log (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-PORT-IS-IN-USE )
(AUX/NEW-LINE)))
)
) (catch Exception e
(binding [*out* *err*]
(println (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-UNKNOWN-REASON )
(AUX/NEW-LINE)))
(.error log (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-UNKNOWN-REASON )
(AUX/NEW-LINE)))
)
) (finally
(let [ret0 (AUX/EXIT-FAILURE)]
(AUX/cleanups-fixate log)
(System/exit ret0)
)
)))))
)
; vim:set nu et ts=4 sw=4:
| 105104 | ;
; src/clojure/src/dnsresolvd.clj
; =============================================================================
; DNS Resolver Daemon (dnsresolvd). Version 0.9.9
; =============================================================================
; A daemon that performs DNS lookups for the given hostname
; passed in an HTTP request, with the focus on its implementation
; using various programming languages. (HTTP Kit-boosted impl.)
; =============================================================================
; Copyright (C) 2017-2022 <NAME>) <NAME>
;
; (See the LICENSE file at the top of the source tree.)
;
(ns dnsresolvd
"The main module of the daemon."
(:require
[dnsresolvh :as AUX]
[clojure.walk :refer [
keywordize-keys
]]
[org.httpkit.server :refer [
run-server
with-channel
send!
]]
[clojure.data.json :refer [
write-str
]]
)
(:import [java.net InetAddress ])
(:import [java.net Inet4Address])
(:import [java.net Inet6Address])
)
(defn dns-lookup
"Performs DNS lookup action for the given hostname,
i.e. (in this case) IP address retrieval by hostname.
Args:
hostname: The effective hostname to look up for.
Returns:
The list containing IP address of the analyzed host/service
and a corresponding IP version (family) used to look up in DNS:
"4" for IPv4-only hosts, "6" for IPv6-capable hosts.
" [hostname]
; Trying to get an A record (IPv4) for the host or its AAAA record (IPv6).
(try
(let [hostent (InetAddress/getByName hostname)]
(list
(.getHostAddress hostent)
(cond
(instance? Inet4Address hostent) 4
(instance? Inet6Address hostent) 6
)
))
(catch
java.net.UnknownHostException e (list (AUX/ERR-PREFIX) nil)
))
)
(defn reqhandler
"The request handler callback.
Gets called when a new incoming HTTP request is received.
Args:
req: The incoming HTTP request object.
Returns:
The HTTP status code, response headers, and a body of the response.
" [req]
(let [mtd (get req :request-method)]
; -------------------------------------------------------------------------
; --- Parsing and validating request params - Begin -----------------------
; -------------------------------------------------------------------------
(let [params- (cond
(= mtd :get )
(let [params0 (get req :query-string)]
(if (nil? params0) (AUX/EMPTY-STRING) params0))
(= mtd :post)
(let [params0 (get req :body )]
(if (nil? params0) (AUX/EMPTY-STRING) (slurp params0)))
:else
(AUX/EMPTY-STRING)
)]
(let [params (keywordize-keys
(try
(apply hash-map (clojure.string/split params- (AUX/PARAMS-SEPS)))
(catch
IllegalArgumentException e {
:h (AUX/DEF-HOSTNAME)
:f (AUX/PRM-FMT-JSON)
}
))
)]
(let [hostname
(let [hostname0 (get params :h)] ; <------+----------------------+
(if (nil? hostname0) (AUX/DEF-HOSTNAME) ; | |
hostname0))] ; | |
; +----GET----+-----+-----+ | |
; | | | | | | |
; | | | | | +---+ +-------------+-+
; v v v v v | | | |
; $ curl 'http://localhost:<port-number>/?h=<hostname>&f=<fmt>' | |
; $ | |
; $ curl -d 'h=<hostname>&f=<fmt>' http://localhost:<port-number> | |
; ^ | | | |
; | +------------+------------------------------------------+ |
; | | |
; POST----+ +------+ |
; | |
(let [fmt- ; v |
(let [fmt0 (get params :f)] ; <-------------------------------+
(if (nil? fmt0 ) (AUX/PRM-FMT-JSON)
(clojure.string/lower-case fmt0)))]
(let [fmt
(if (not (some #{fmt-} (list
(AUX/PRM-FMT-HTML)
(AUX/PRM-FMT-JSON)
))) (AUX/PRM-FMT-JSON) fmt-)]
; -------------------------------------------------------------------------
; --- Parsing and validating request params - End -------------------------
; -------------------------------------------------------------------------
; Performing DNS lookup for the given hostname.
(let [addr-ver (dns-lookup hostname)]
(let [addr (nth addr-ver 0)]
(let [ver (nth addr-ver 1)]
(let [resp-buffer- (cond
(= fmt (AUX/PRM-FMT-HTML))
(str "<!DOCTYPE html>" (AUX/NEW-LINE)
"<html lang=\"en-US\" dir=\"ltr\">" (AUX/NEW-LINE)
"<head>" (AUX/NEW-LINE)
"<meta http-equiv=\"" (AUX/HDR-CONTENT-TYPE-N ) "\" content=\""
(AUX/HDR-CONTENT-TYPE-V-HTML) "\" />" (AUX/NEW-LINE)
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />" (AUX/NEW-LINE)
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />" (AUX/NEW-LINE)
"<title>" (AUX/DMN-NAME ) "</title>" (AUX/NEW-LINE)
"</head>" (AUX/NEW-LINE)
"<body>" (AUX/NEW-LINE)
"<div>" hostname (AUX/ONE-SPACE-STRING ))
(= fmt (AUX/PRM-FMT-JSON))
(hash-map (AUX/DAT-HOSTNAME-N )
hostname)
)]
; If lookup error occurred.
(let [resp-buffer0 (cond
(= addr (AUX/ERR-PREFIX)) (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer- (AUX/ERR-PREFIX )
(AUX/COLON-SPACE-SEP )
(AUX/ERR-COULD-NOT-LOOKUP))
(= fmt (AUX/PRM-FMT-JSON))
(assoc resp-buffer- (AUX/ERR-PREFIX )
(AUX/ERR-COULD-NOT-LOOKUP))
) :else (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer- addr
(AUX/ONE-SPACE-STRING )
(AUX/DAT-VERSION-V )
ver )
(= fmt (AUX/PRM-FMT-JSON))
(assoc resp-buffer- (AUX/DAT-ADDRESS-N )
addr
(AUX/DAT-VERSION-N )
(str (AUX/DAT-VERSION-V )
ver ))
)
)]
(let [resp-buffer (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer0 "</div>" (AUX/NEW-LINE)
"</body>" (AUX/NEW-LINE)
"</html>" (AUX/NEW-LINE))
(= fmt (AUX/PRM-FMT-JSON))
(write-str resp-buffer0)
)]
; Returning the HTTP status code, response headers,
; and a body of the response.
(with-channel req channel (send! channel { ; <== Async mode !
:status (AUX/RSC-HTTP-200-OK)
:headers (AUX/add-response-headers fmt)
:body resp-buffer
} )
)
)
)
)
) ) )
) ) )
)))
)
(defn startup
"Starts up the daemon.
Args:
args: A list containing the server port number to listen on
as the first element.
Returns:
The exit code indicating the daemon overall termination status.
" [args]
(let [port-number (nth args 0)]
(let [daemon-name (nth args 1)]
(let [log (nth args 2)]
; Trying to start up the HTTP Kit server on <port-number>.
(try
(run-server reqhandler {
:port port-number
})
(println (str (AUX/MSG-SERVER-STARTED-1) port-number (AUX/NEW-LINE)
(AUX/MSG-SERVER-STARTED-2)))
(.info log (str (AUX/MSG-SERVER-STARTED-1) port-number (AUX/NEW-LINE)
(AUX/MSG-SERVER-STARTED-2)))
(.join (Thread/currentThread)) ; <== Important !
(catch java.net.BindException e
(binding [*out* *err*]
(println (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-PORT-IS-IN-USE )
(AUX/NEW-LINE)))
(.error log (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-PORT-IS-IN-USE )
(AUX/NEW-LINE)))
)
) (catch Exception e
(binding [*out* *err*]
(println (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-UNKNOWN-REASON )
(AUX/NEW-LINE)))
(.error log (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-UNKNOWN-REASON )
(AUX/NEW-LINE)))
)
) (finally
(let [ret0 (AUX/EXIT-FAILURE)]
(AUX/cleanups-fixate log)
(System/exit ret0)
)
)))))
)
; vim:set nu et ts=4 sw=4:
| true | ;
; src/clojure/src/dnsresolvd.clj
; =============================================================================
; DNS Resolver Daemon (dnsresolvd). Version 0.9.9
; =============================================================================
; A daemon that performs DNS lookups for the given hostname
; passed in an HTTP request, with the focus on its implementation
; using various programming languages. (HTTP Kit-boosted impl.)
; =============================================================================
; Copyright (C) 2017-2022 PI:NAME:<NAME>END_PI) PI:NAME:<NAME>END_PI
;
; (See the LICENSE file at the top of the source tree.)
;
(ns dnsresolvd
"The main module of the daemon."
(:require
[dnsresolvh :as AUX]
[clojure.walk :refer [
keywordize-keys
]]
[org.httpkit.server :refer [
run-server
with-channel
send!
]]
[clojure.data.json :refer [
write-str
]]
)
(:import [java.net InetAddress ])
(:import [java.net Inet4Address])
(:import [java.net Inet6Address])
)
(defn dns-lookup
"Performs DNS lookup action for the given hostname,
i.e. (in this case) IP address retrieval by hostname.
Args:
hostname: The effective hostname to look up for.
Returns:
The list containing IP address of the analyzed host/service
and a corresponding IP version (family) used to look up in DNS:
"4" for IPv4-only hosts, "6" for IPv6-capable hosts.
" [hostname]
; Trying to get an A record (IPv4) for the host or its AAAA record (IPv6).
(try
(let [hostent (InetAddress/getByName hostname)]
(list
(.getHostAddress hostent)
(cond
(instance? Inet4Address hostent) 4
(instance? Inet6Address hostent) 6
)
))
(catch
java.net.UnknownHostException e (list (AUX/ERR-PREFIX) nil)
))
)
(defn reqhandler
"The request handler callback.
Gets called when a new incoming HTTP request is received.
Args:
req: The incoming HTTP request object.
Returns:
The HTTP status code, response headers, and a body of the response.
" [req]
(let [mtd (get req :request-method)]
; -------------------------------------------------------------------------
; --- Parsing and validating request params - Begin -----------------------
; -------------------------------------------------------------------------
(let [params- (cond
(= mtd :get )
(let [params0 (get req :query-string)]
(if (nil? params0) (AUX/EMPTY-STRING) params0))
(= mtd :post)
(let [params0 (get req :body )]
(if (nil? params0) (AUX/EMPTY-STRING) (slurp params0)))
:else
(AUX/EMPTY-STRING)
)]
(let [params (keywordize-keys
(try
(apply hash-map (clojure.string/split params- (AUX/PARAMS-SEPS)))
(catch
IllegalArgumentException e {
:h (AUX/DEF-HOSTNAME)
:f (AUX/PRM-FMT-JSON)
}
))
)]
(let [hostname
(let [hostname0 (get params :h)] ; <------+----------------------+
(if (nil? hostname0) (AUX/DEF-HOSTNAME) ; | |
hostname0))] ; | |
; +----GET----+-----+-----+ | |
; | | | | | | |
; | | | | | +---+ +-------------+-+
; v v v v v | | | |
; $ curl 'http://localhost:<port-number>/?h=<hostname>&f=<fmt>' | |
; $ | |
; $ curl -d 'h=<hostname>&f=<fmt>' http://localhost:<port-number> | |
; ^ | | | |
; | +------------+------------------------------------------+ |
; | | |
; POST----+ +------+ |
; | |
(let [fmt- ; v |
(let [fmt0 (get params :f)] ; <-------------------------------+
(if (nil? fmt0 ) (AUX/PRM-FMT-JSON)
(clojure.string/lower-case fmt0)))]
(let [fmt
(if (not (some #{fmt-} (list
(AUX/PRM-FMT-HTML)
(AUX/PRM-FMT-JSON)
))) (AUX/PRM-FMT-JSON) fmt-)]
; -------------------------------------------------------------------------
; --- Parsing and validating request params - End -------------------------
; -------------------------------------------------------------------------
; Performing DNS lookup for the given hostname.
(let [addr-ver (dns-lookup hostname)]
(let [addr (nth addr-ver 0)]
(let [ver (nth addr-ver 1)]
(let [resp-buffer- (cond
(= fmt (AUX/PRM-FMT-HTML))
(str "<!DOCTYPE html>" (AUX/NEW-LINE)
"<html lang=\"en-US\" dir=\"ltr\">" (AUX/NEW-LINE)
"<head>" (AUX/NEW-LINE)
"<meta http-equiv=\"" (AUX/HDR-CONTENT-TYPE-N ) "\" content=\""
(AUX/HDR-CONTENT-TYPE-V-HTML) "\" />" (AUX/NEW-LINE)
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />" (AUX/NEW-LINE)
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\" />" (AUX/NEW-LINE)
"<title>" (AUX/DMN-NAME ) "</title>" (AUX/NEW-LINE)
"</head>" (AUX/NEW-LINE)
"<body>" (AUX/NEW-LINE)
"<div>" hostname (AUX/ONE-SPACE-STRING ))
(= fmt (AUX/PRM-FMT-JSON))
(hash-map (AUX/DAT-HOSTNAME-N )
hostname)
)]
; If lookup error occurred.
(let [resp-buffer0 (cond
(= addr (AUX/ERR-PREFIX)) (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer- (AUX/ERR-PREFIX )
(AUX/COLON-SPACE-SEP )
(AUX/ERR-COULD-NOT-LOOKUP))
(= fmt (AUX/PRM-FMT-JSON))
(assoc resp-buffer- (AUX/ERR-PREFIX )
(AUX/ERR-COULD-NOT-LOOKUP))
) :else (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer- addr
(AUX/ONE-SPACE-STRING )
(AUX/DAT-VERSION-V )
ver )
(= fmt (AUX/PRM-FMT-JSON))
(assoc resp-buffer- (AUX/DAT-ADDRESS-N )
addr
(AUX/DAT-VERSION-N )
(str (AUX/DAT-VERSION-V )
ver ))
)
)]
(let [resp-buffer (cond
(= fmt (AUX/PRM-FMT-HTML))
(str resp-buffer0 "</div>" (AUX/NEW-LINE)
"</body>" (AUX/NEW-LINE)
"</html>" (AUX/NEW-LINE))
(= fmt (AUX/PRM-FMT-JSON))
(write-str resp-buffer0)
)]
; Returning the HTTP status code, response headers,
; and a body of the response.
(with-channel req channel (send! channel { ; <== Async mode !
:status (AUX/RSC-HTTP-200-OK)
:headers (AUX/add-response-headers fmt)
:body resp-buffer
} )
)
)
)
)
) ) )
) ) )
)))
)
(defn startup
"Starts up the daemon.
Args:
args: A list containing the server port number to listen on
as the first element.
Returns:
The exit code indicating the daemon overall termination status.
" [args]
(let [port-number (nth args 0)]
(let [daemon-name (nth args 1)]
(let [log (nth args 2)]
; Trying to start up the HTTP Kit server on <port-number>.
(try
(run-server reqhandler {
:port port-number
})
(println (str (AUX/MSG-SERVER-STARTED-1) port-number (AUX/NEW-LINE)
(AUX/MSG-SERVER-STARTED-2)))
(.info log (str (AUX/MSG-SERVER-STARTED-1) port-number (AUX/NEW-LINE)
(AUX/MSG-SERVER-STARTED-2)))
(.join (Thread/currentThread)) ; <== Important !
(catch java.net.BindException e
(binding [*out* *err*]
(println (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-PORT-IS-IN-USE )
(AUX/NEW-LINE)))
(.error log (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-PORT-IS-IN-USE )
(AUX/NEW-LINE)))
)
) (catch Exception e
(binding [*out* *err*]
(println (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-UNKNOWN-REASON )
(AUX/NEW-LINE)))
(.error log (str daemon-name (AUX/ERR-CANNOT-START-SERVER)
(AUX/ERR-SRV-UNKNOWN-REASON )
(AUX/NEW-LINE)))
)
) (finally
(let [ret0 (AUX/EXIT-FAILURE)]
(AUX/cleanups-fixate log)
(System/exit ret0)
)
)))))
)
; vim:set nu et ts=4 sw=4:
|
[
{
"context": " (str \":@\" db-host \"/\" db-name)\n :user \"scott\"\n :password \"tiger\"})\n\n (with-connecti",
"end": 1618,
"score": 0.9985711574554443,
"start": 1613,
"tag": "USERNAME",
"value": "scott"
},
{
"context": "e)\n :user \"scott\"\n :password \"tiger\"})\n\n (with-connection db\n (drop-table :cities",
"end": 1647,
"score": 0.9987266063690186,
"start": 1642,
"tag": "PASSWORD",
"value": "tiger"
}
] | oracle/clojure/create/oracle_create.clj | ekzemplaro/data_base_language | 3 | ; -----------------------------------------------------------------
;
; oracle_create.clj
;
; Sep/29/2010
;
; -----------------------------------------------------------------
(import '(java.util Date))
(import '(java.text SimpleDateFormat))
(use 'clojure.contrib.sql)
(use '[clojure.contrib.str-utils :only (str-join)])
; -----------------------------------------------------------------
(defn insert_proc []
(insert-values :cities
[:id :name :population :date_mod] [131 "函館" 34200 "1991-8-14"])
(insert-values :cities
[:id :name :population :date_mod] [132 "札幌" 71400 "1991-5-23"])
(insert-values :cities
[:id :name :population :date_mod] [133 "帯広" 21700 "1991-9-15"])
(insert-values :citie
[:id :name :population :date_mod] [134 "釧路" 52900 "1991-11-21"])
(insert-values :cities
[:id :name :population :date_mod] [135 "旭川" 61500 "1991-10-7"])
(insert-values :cities
[:id :name :population :date_mod] [136 "北見" 42000 "1991-7-12"])
(insert-values :cities
[:id :name :population :date_mod] [137 "室蘭" 52000 "1991-2-24"])
(insert-values :cities
[:id :name :population :date_mod] [138 "根室" 41000 "1991-5-21"])
(insert-values :cities
[:id :name :population :date_mod] [139 "稚内" 73500 "1991-9-17"])
)
; -----------------------------------------------------------------
(println "*** 開始 ***")
(let [db-host "spn109:1521"
db-name "xe"
]
(def db {:classname "oracle.jdbc.driver.OracleDriver"
:subprotocol "oracle:thin"
:subname (str ":@" db-host "/" db-name)
:user "scott"
:password "tiger"})
(with-connection db
(drop-table :cities)
(create-table :cities
[:id :int "PRIMARY KEY"]
[:name :varchar]
[:population :int]
[:date_mod :date])
(insert_proc)
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
| 94256 | ; -----------------------------------------------------------------
;
; oracle_create.clj
;
; Sep/29/2010
;
; -----------------------------------------------------------------
(import '(java.util Date))
(import '(java.text SimpleDateFormat))
(use 'clojure.contrib.sql)
(use '[clojure.contrib.str-utils :only (str-join)])
; -----------------------------------------------------------------
(defn insert_proc []
(insert-values :cities
[:id :name :population :date_mod] [131 "函館" 34200 "1991-8-14"])
(insert-values :cities
[:id :name :population :date_mod] [132 "札幌" 71400 "1991-5-23"])
(insert-values :cities
[:id :name :population :date_mod] [133 "帯広" 21700 "1991-9-15"])
(insert-values :citie
[:id :name :population :date_mod] [134 "釧路" 52900 "1991-11-21"])
(insert-values :cities
[:id :name :population :date_mod] [135 "旭川" 61500 "1991-10-7"])
(insert-values :cities
[:id :name :population :date_mod] [136 "北見" 42000 "1991-7-12"])
(insert-values :cities
[:id :name :population :date_mod] [137 "室蘭" 52000 "1991-2-24"])
(insert-values :cities
[:id :name :population :date_mod] [138 "根室" 41000 "1991-5-21"])
(insert-values :cities
[:id :name :population :date_mod] [139 "稚内" 73500 "1991-9-17"])
)
; -----------------------------------------------------------------
(println "*** 開始 ***")
(let [db-host "spn109:1521"
db-name "xe"
]
(def db {:classname "oracle.jdbc.driver.OracleDriver"
:subprotocol "oracle:thin"
:subname (str ":@" db-host "/" db-name)
:user "scott"
:password "<PASSWORD>"})
(with-connection db
(drop-table :cities)
(create-table :cities
[:id :int "PRIMARY KEY"]
[:name :varchar]
[:population :int]
[:date_mod :date])
(insert_proc)
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
| true | ; -----------------------------------------------------------------
;
; oracle_create.clj
;
; Sep/29/2010
;
; -----------------------------------------------------------------
(import '(java.util Date))
(import '(java.text SimpleDateFormat))
(use 'clojure.contrib.sql)
(use '[clojure.contrib.str-utils :only (str-join)])
; -----------------------------------------------------------------
(defn insert_proc []
(insert-values :cities
[:id :name :population :date_mod] [131 "函館" 34200 "1991-8-14"])
(insert-values :cities
[:id :name :population :date_mod] [132 "札幌" 71400 "1991-5-23"])
(insert-values :cities
[:id :name :population :date_mod] [133 "帯広" 21700 "1991-9-15"])
(insert-values :citie
[:id :name :population :date_mod] [134 "釧路" 52900 "1991-11-21"])
(insert-values :cities
[:id :name :population :date_mod] [135 "旭川" 61500 "1991-10-7"])
(insert-values :cities
[:id :name :population :date_mod] [136 "北見" 42000 "1991-7-12"])
(insert-values :cities
[:id :name :population :date_mod] [137 "室蘭" 52000 "1991-2-24"])
(insert-values :cities
[:id :name :population :date_mod] [138 "根室" 41000 "1991-5-21"])
(insert-values :cities
[:id :name :population :date_mod] [139 "稚内" 73500 "1991-9-17"])
)
; -----------------------------------------------------------------
(println "*** 開始 ***")
(let [db-host "spn109:1521"
db-name "xe"
]
(def db {:classname "oracle.jdbc.driver.OracleDriver"
:subprotocol "oracle:thin"
:subname (str ":@" db-host "/" db-name)
:user "scott"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(with-connection db
(drop-table :cities)
(create-table :cities
[:id :int "PRIMARY KEY"]
[:name :varchar]
[:population :int]
[:date_mod :date])
(insert_proc)
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
|
[
{
"context": "ion \"osi core library\"\n :url \"https://github.com/optimis/osi-clj.git\"\n :license {:name \"MIT\"\n ",
"end": 93,
"score": 0.9242019057273865,
"start": 86,
"tag": "USERNAME",
"value": "optimis"
},
{
"context": "o\"\n :username [\"uchouhan@optimiscorp.com\"]\n :password [\"",
"end": 328,
"score": 0.9999198913574219,
"start": 304,
"tag": "EMAIL",
"value": "uchouhan@optimiscorp.com"
},
{
"context": "\"]\n :password [\"2a11de94-a230-4914-b64c-af4019f9d7d8\"]}\n \"private\" {:sign-releases fal",
"end": 414,
"score": 0.9992104768753052,
"start": 378,
"tag": "PASSWORD",
"value": "2a11de94-a230-4914-b64c-af4019f9d7d8"
},
{
"context": " [com.pupeno/jar-copier \"0.4.0\"]\n [com.andrewmcveigh/lein-auto-release \"0.1.10\"]]\n :scm {:dir \"..\"}\n ",
"end": 1826,
"score": 0.9974328875541687,
"start": 1813,
"tag": "USERNAME",
"value": "andrewmcveigh"
}
] | osi/project.clj | optimis/osi-clj | 1 | (defproject osi "2.0.14"
:description "osi core library"
:url "https://github.com/optimis/osi-clj.git"
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:repositories {"my.datomic.com" {:url "https://my.datomic.com/repo"
:username ["uchouhan@optimiscorp.com"]
:password ["2a11de94-a230-4914-b64c-af4019f9d7d8"]}
"private" {:sign-releases false
:url "s3p://osi-leiningen/releases/"
:username :env/aws_access_key
:passphrase :env/aws_secret_key}}
:dependencies [[org.clojure/clojure "1.9.0-alpha17"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/math.combinatorics "0.0.7"]
[environ "1.1.0"]
[mysql/mysql-connector-java "6.0.6"]
[com.datomic/datomic-pro "0.9.5544"
:exclusions [joda-time]]
[datomic-schema "1.3.0"]
[http-kit "2.2.0"]
[com.cognitect/transit-clj "0.8.300"]
[ring/ring "1.6.3"]
[ring-middleware-format "0.7.2"]
[spootnik/unilog "0.7.19"]
[ring-logger "0.7.7"]
[compojure "1.6.0"]
[cheshire "5.8.0"]
[prismatic/schema "1.1.7"]
[ring-honeybadger "0.1.0"]
[yleisradio/new-reliquary "1.0.0"]
[me.raynes/conch "0.8.0"]
[wharf "0.2.0-SNAPSHOT"]]
:plugins [[lein-ancient "0.6.14"]
[lein-cloverage "1.0.9"]
[lein-environ "1.1.0"]
[s3-wagon-private "1.3.0"]
[com.pupeno/jar-copier "0.4.0"]
[com.andrewmcveigh/lein-auto-release "0.1.10"]]
:scm {:dir ".."}
:release-tasks [["auto-release" "checkout" "master"]
["auto-release" "merge" "develop"]
["vcs" "assert-committed"]
["change" "version"
"leiningen.release/bump-version" "release"]
["ancient" "upgrade" ":interactive"]
["vcs" "commit"]
["vcs" "tag" "v" "--no-sign"]
["vcs" "push"]
["auto-release" "checkout" "develop"]
["auto-release" "merge" "master"]
["change" "version"
"leiningen.release/bump-version"]
["ancient" "upgrade" ":interactive"]
["vcs" "commit"]
["vcs" "push"]]
:uberjar-name "standalone.jar"
:prep-tasks ["javac" "compile" "jar-copier"]
:jar-copier {:java-agents true
:destination "resources/jars"}
:java-agents [[com.newrelic.agent.java/newrelic-agent "3.33.0"]])
| 122834 | (defproject osi "2.0.14"
:description "osi core library"
:url "https://github.com/optimis/osi-clj.git"
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:repositories {"my.datomic.com" {:url "https://my.datomic.com/repo"
:username ["<EMAIL>"]
:password ["<PASSWORD>"]}
"private" {:sign-releases false
:url "s3p://osi-leiningen/releases/"
:username :env/aws_access_key
:passphrase :env/aws_secret_key}}
:dependencies [[org.clojure/clojure "1.9.0-alpha17"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/math.combinatorics "0.0.7"]
[environ "1.1.0"]
[mysql/mysql-connector-java "6.0.6"]
[com.datomic/datomic-pro "0.9.5544"
:exclusions [joda-time]]
[datomic-schema "1.3.0"]
[http-kit "2.2.0"]
[com.cognitect/transit-clj "0.8.300"]
[ring/ring "1.6.3"]
[ring-middleware-format "0.7.2"]
[spootnik/unilog "0.7.19"]
[ring-logger "0.7.7"]
[compojure "1.6.0"]
[cheshire "5.8.0"]
[prismatic/schema "1.1.7"]
[ring-honeybadger "0.1.0"]
[yleisradio/new-reliquary "1.0.0"]
[me.raynes/conch "0.8.0"]
[wharf "0.2.0-SNAPSHOT"]]
:plugins [[lein-ancient "0.6.14"]
[lein-cloverage "1.0.9"]
[lein-environ "1.1.0"]
[s3-wagon-private "1.3.0"]
[com.pupeno/jar-copier "0.4.0"]
[com.andrewmcveigh/lein-auto-release "0.1.10"]]
:scm {:dir ".."}
:release-tasks [["auto-release" "checkout" "master"]
["auto-release" "merge" "develop"]
["vcs" "assert-committed"]
["change" "version"
"leiningen.release/bump-version" "release"]
["ancient" "upgrade" ":interactive"]
["vcs" "commit"]
["vcs" "tag" "v" "--no-sign"]
["vcs" "push"]
["auto-release" "checkout" "develop"]
["auto-release" "merge" "master"]
["change" "version"
"leiningen.release/bump-version"]
["ancient" "upgrade" ":interactive"]
["vcs" "commit"]
["vcs" "push"]]
:uberjar-name "standalone.jar"
:prep-tasks ["javac" "compile" "jar-copier"]
:jar-copier {:java-agents true
:destination "resources/jars"}
:java-agents [[com.newrelic.agent.java/newrelic-agent "3.33.0"]])
| true | (defproject osi "2.0.14"
:description "osi core library"
:url "https://github.com/optimis/osi-clj.git"
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:repositories {"my.datomic.com" {:url "https://my.datomic.com/repo"
:username ["PI:EMAIL:<EMAIL>END_PI"]
:password ["PI:PASSWORD:<PASSWORD>END_PI"]}
"private" {:sign-releases false
:url "s3p://osi-leiningen/releases/"
:username :env/aws_access_key
:passphrase :env/aws_secret_key}}
:dependencies [[org.clojure/clojure "1.9.0-alpha17"]
[org.clojure/tools.logging "0.3.1"]
[org.clojure/math.combinatorics "0.0.7"]
[environ "1.1.0"]
[mysql/mysql-connector-java "6.0.6"]
[com.datomic/datomic-pro "0.9.5544"
:exclusions [joda-time]]
[datomic-schema "1.3.0"]
[http-kit "2.2.0"]
[com.cognitect/transit-clj "0.8.300"]
[ring/ring "1.6.3"]
[ring-middleware-format "0.7.2"]
[spootnik/unilog "0.7.19"]
[ring-logger "0.7.7"]
[compojure "1.6.0"]
[cheshire "5.8.0"]
[prismatic/schema "1.1.7"]
[ring-honeybadger "0.1.0"]
[yleisradio/new-reliquary "1.0.0"]
[me.raynes/conch "0.8.0"]
[wharf "0.2.0-SNAPSHOT"]]
:plugins [[lein-ancient "0.6.14"]
[lein-cloverage "1.0.9"]
[lein-environ "1.1.0"]
[s3-wagon-private "1.3.0"]
[com.pupeno/jar-copier "0.4.0"]
[com.andrewmcveigh/lein-auto-release "0.1.10"]]
:scm {:dir ".."}
:release-tasks [["auto-release" "checkout" "master"]
["auto-release" "merge" "develop"]
["vcs" "assert-committed"]
["change" "version"
"leiningen.release/bump-version" "release"]
["ancient" "upgrade" ":interactive"]
["vcs" "commit"]
["vcs" "tag" "v" "--no-sign"]
["vcs" "push"]
["auto-release" "checkout" "develop"]
["auto-release" "merge" "master"]
["change" "version"
"leiningen.release/bump-version"]
["ancient" "upgrade" ":interactive"]
["vcs" "commit"]
["vcs" "push"]]
:uberjar-name "standalone.jar"
:prep-tasks ["javac" "compile" "jar-copier"]
:jar-copier {:java-agents true
:destination "resources/jars"}
:java-agents [[com.newrelic.agent.java/newrelic-agent "3.33.0"]])
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998054504394531,
"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.99982088804245,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/internal/history.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 internal.history)
(set! *warn-on-reflection* true)
(defprotocol Iterator
(inext [this] "Advance cursor to the next-most-recent item")
(iprev [this] "Step cursor backward to the previous-to-current item")
(ivalue [this] "Return the current item")
(before [this] "Return a seq of the items up and including the current value")
(after [this] "Return a seq of the items after the current value"))
(defprotocol Truncate
(truncate [this] "Drop all values after the current one"))
(defprotocol Drop
(drop-current [this] "Drops the current value"))
(deftype PaperTape [limit limiter on-drop left right]
clojure.lang.IPersistentCollection
(seq [this] (concat left right))
(count [this] (+ (count left) (count right)))
(cons [this o] (PaperTape. limit limiter on-drop (limiter (conj left o)) []))
(empty [this] (PaperTape. limit limiter on-drop [] []))
(equiv [this o] (let [is-paper-tape? (and (instance? PaperTape o) o)
^PaperTape that (when is-paper-tape? o)]
(when that
(= limit (.limit that))
(= left (.left that))
(= right (.right that)))))
Iterator
;; Move one from right to left
(inext [this]
(if-let [v (peek right)]
(PaperTape. limit limiter on-drop (conj left v) (pop right))
this))
;; Move one from left to right
(iprev [this]
(if-let [v (peek left)]
(PaperTape. limit limiter on-drop (pop left) (conj right v))
this))
(ivalue [this] (peek left))
(before [this] left)
(after [this] right)
Truncate
(truncate [this]
(PaperTape. limit limiter on-drop left []))
Drop
(drop-current [this]
(PaperTape. limit limiter on-drop (pop left) right)))
(defn- make-limiter
[limit]
(if-not limit
identity
(fn [v]
(if (> (count v) limit)
(subvec v (- (count v) limit))
v))))
(defn paper-tape
([limit]
(paper-tape limit (fn [v])))
([limit on-drop]
(PaperTape. limit (make-limiter limit) on-drop [] [])))
| 52442 | ;; 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 internal.history)
(set! *warn-on-reflection* true)
(defprotocol Iterator
(inext [this] "Advance cursor to the next-most-recent item")
(iprev [this] "Step cursor backward to the previous-to-current item")
(ivalue [this] "Return the current item")
(before [this] "Return a seq of the items up and including the current value")
(after [this] "Return a seq of the items after the current value"))
(defprotocol Truncate
(truncate [this] "Drop all values after the current one"))
(defprotocol Drop
(drop-current [this] "Drops the current value"))
(deftype PaperTape [limit limiter on-drop left right]
clojure.lang.IPersistentCollection
(seq [this] (concat left right))
(count [this] (+ (count left) (count right)))
(cons [this o] (PaperTape. limit limiter on-drop (limiter (conj left o)) []))
(empty [this] (PaperTape. limit limiter on-drop [] []))
(equiv [this o] (let [is-paper-tape? (and (instance? PaperTape o) o)
^PaperTape that (when is-paper-tape? o)]
(when that
(= limit (.limit that))
(= left (.left that))
(= right (.right that)))))
Iterator
;; Move one from right to left
(inext [this]
(if-let [v (peek right)]
(PaperTape. limit limiter on-drop (conj left v) (pop right))
this))
;; Move one from left to right
(iprev [this]
(if-let [v (peek left)]
(PaperTape. limit limiter on-drop (pop left) (conj right v))
this))
(ivalue [this] (peek left))
(before [this] left)
(after [this] right)
Truncate
(truncate [this]
(PaperTape. limit limiter on-drop left []))
Drop
(drop-current [this]
(PaperTape. limit limiter on-drop (pop left) right)))
(defn- make-limiter
[limit]
(if-not limit
identity
(fn [v]
(if (> (count v) limit)
(subvec v (- (count v) limit))
v))))
(defn paper-tape
([limit]
(paper-tape limit (fn [v])))
([limit on-drop]
(PaperTape. limit (make-limiter limit) on-drop [] [])))
| 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 internal.history)
(set! *warn-on-reflection* true)
(defprotocol Iterator
(inext [this] "Advance cursor to the next-most-recent item")
(iprev [this] "Step cursor backward to the previous-to-current item")
(ivalue [this] "Return the current item")
(before [this] "Return a seq of the items up and including the current value")
(after [this] "Return a seq of the items after the current value"))
(defprotocol Truncate
(truncate [this] "Drop all values after the current one"))
(defprotocol Drop
(drop-current [this] "Drops the current value"))
(deftype PaperTape [limit limiter on-drop left right]
clojure.lang.IPersistentCollection
(seq [this] (concat left right))
(count [this] (+ (count left) (count right)))
(cons [this o] (PaperTape. limit limiter on-drop (limiter (conj left o)) []))
(empty [this] (PaperTape. limit limiter on-drop [] []))
(equiv [this o] (let [is-paper-tape? (and (instance? PaperTape o) o)
^PaperTape that (when is-paper-tape? o)]
(when that
(= limit (.limit that))
(= left (.left that))
(= right (.right that)))))
Iterator
;; Move one from right to left
(inext [this]
(if-let [v (peek right)]
(PaperTape. limit limiter on-drop (conj left v) (pop right))
this))
;; Move one from left to right
(iprev [this]
(if-let [v (peek left)]
(PaperTape. limit limiter on-drop (pop left) (conj right v))
this))
(ivalue [this] (peek left))
(before [this] left)
(after [this] right)
Truncate
(truncate [this]
(PaperTape. limit limiter on-drop left []))
Drop
(drop-current [this]
(PaperTape. limit limiter on-drop (pop left) right)))
(defn- make-limiter
[limit]
(if-not limit
identity
(fn [v]
(if (> (count v) limit)
(subvec v (- (count v) limit))
v))))
(defn paper-tape
([limit]
(paper-tape limit (fn [v])))
([limit on-drop]
(PaperTape. limit (make-limiter limit) on-drop [] [])))
|
[
{
"context": " :name \"New Field\"\n ",
"end": 11329,
"score": 0.8845450282096863,
"start": 11326,
"tag": "NAME",
"value": "New"
}
] | c#-metabase/test/metabase/models/on_demand_test.clj | hanakhry/Crime_Admin | 0 | (ns metabase.models.on-demand-test
"Tests for On-Demand FieldValues updating behavior for Cards and Dashboards."
(:require [clojure.test :refer :all]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :as dashboard :refer [Dashboard]]
[metabase.models.database :refer [Database]]
[metabase.models.field :refer [Field]]
[metabase.models.field-values :as field-values]
[metabase.models.table :refer [Table]]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
[toucan.db :as db]))
(defn- do-with-mocked-field-values-updating
"Run F the function responsible for updating FieldValues bound to a mock function that instead just records the names
of Fields that should have been updated. Returns the set of updated Field names."
{:style/indent 0}
[f]
(let [updated-field-names (atom #{})]
(with-redefs [field-values/create-or-update-field-values! (fn [field]
(swap! updated-field-names conj (:name field)))]
(f updated-field-names)
@updated-field-names)))
(defn- basic-native-query []
{:database (data/id)
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS"}})
(defn- native-query-with-template-tag [field-or-id]
{:database (data/id)
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS nWHERE {{category}}"
:template-tags {:category {:name "category"
:display-name "Category"
:type "dimension"
:dimension [:field (u/the-id field-or-id) nil]
:widget-type "category"
:default "Widget"}}}})
(defn- do-with-updated-fields-for-card {:style/indent 1} [options & [f]]
(mt/with-temp* [Database [db (:db options)]
Table [table (merge {:db_id (u/the-id db)}
(:table options))]
Field [field (merge {:table_id (u/the-id table), :has_field_values "list"}
(:field options))]]
(do-with-mocked-field-values-updating
(fn [updated-field-names]
(mt/with-temp Card [card (merge {:dataset_query (native-query-with-template-tag field)}
(:card options))]
(when f
(f {:db db, :table table, :field field, :card card, :updated-field-names updated-field-names})))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | CARDS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- field-values-were-updated-for-new-card? [options]
(not (empty? (do-with-updated-fields-for-card options))))
(deftest newly-created-card-test
(testing "Newly created Card with param referencing Field"
(testing "in On-Demand DB should get updated FieldValues"
(is (= true
(field-values-were-updated-for-new-card? {:db {:is_on_demand true}}))))
(testing "in non-On-Demand DB should *not* get updated FieldValues"
(is (= false
(field-values-were-updated-for-new-card? {:db {:is_on_demand false}}))))))
(deftest existing-card-test
(testing "Existing Card"
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create Parameterized Card with field in On-Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [card updated-field-names]}]
;; clear out the list of updated field names
(reset! updated-field-names #{})
;; now update the Card... since param didn't change at all FieldValues
;; should not be updated
(db/update! Card (u/the-id card) card))))))
(testing "with changed param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; create parameterized Card with Field in On-Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [table card updated-field-names]}]
;; clear out the list of updated field names
(reset! updated-field-names #{})
;; now Change the Field that is referenced by the Card's SQL param
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; create a Card with non-parameterized query
(do-with-updated-fields-for-card
{:db {:is_on_demand true}
:card {:dataset_query (basic-native-query)}
:field {:name "New Field"}}
(fn [{:keys [table field card]}]
;; now change the query to one that references our Field in a
;; on-demand DB. Field should have updated values
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a parameterized Card with a Field that belongs to a non-on-demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [card]}]
;; update the Card. Field should get updated values
(db/update! Card (u/the-id card) card))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a Card with non-parameterized query
(do-with-updated-fields-for-card
{:db {:is_on_demand false}
:card {:dataset_query (basic-native-query)}}
(fn [{:keys [field card]}]
;; now change the query to one that references a Field. Field should
;; not get values since DB is not On-Demand
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a parameterized Card with a Field that belongs to a non-on-demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [table card]}]
;; change the query to one referencing a different Field. Field should
;; not get values since DB is not On-Demand
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DASHBOARDS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- basic-mbql-query []
{:database (data/id)
:type :query
:query {:source-table (data/id :venues)
:aggregation [[:count]]}})
(defn- parameter-mappings-for-card-and-field [card-or-id field-or-id]
[{:card_id (u/the-id card-or-id)
:target [:dimension [:field-id (u/the-id field-or-id)]]}])
(defn- add-dashcard-with-parameter-mapping! [dashboard-or-id card-or-id field-or-id]
(dashboard/add-dashcard! dashboard-or-id card-or-id
{:parameter_mappings (parameter-mappings-for-card-and-field card-or-id field-or-id)}))
(defn- do-with-updated-fields-for-dashboard {:style/indent 1} [options & [f]]
(do-with-updated-fields-for-card (merge {:card {:dataset_query (basic-mbql-query)}}
options)
(fn [objects]
(mt/with-temp Dashboard [dash]
(let [dashcard (add-dashcard-with-parameter-mapping! dash (:card objects) (:field objects))]
(when f
(f (assoc objects
:dash dash
:dashcard dashcard))))))))
(deftest existing-dashboard-test
(testing "Existing Dashboard"
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"My Cool Field"}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}
:field {:name "My Cool Field"}}))))
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [field card dash updated-field-names]}]
;; clear out the list of updated Field Names
(reset! updated-field-names #{})
;; ok, now add a new Card with a param that references the same field
;; The field shouldn't get new values because the set of referenced Fields didn't change
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [table field card dash dashcard updated-field-names]}]
;; create a Dashboard and add a DashboardCard with a param mapping
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:name "New Field"
:has_field_values "list"}]
;; clear out the list of updated Field Names
(reset! updated-field-names #{})
;; ok, now update the parameter mapping to the new field. The new Field should get new values
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [field card dash updated-field-names]}]
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [table field card dash dashcard updated-field-names]}]
(mt/with-temp Field [new-field {:table_id (u/the-id table), :has_field_values "list"}]
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))))
| 32120 | (ns metabase.models.on-demand-test
"Tests for On-Demand FieldValues updating behavior for Cards and Dashboards."
(:require [clojure.test :refer :all]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :as dashboard :refer [Dashboard]]
[metabase.models.database :refer [Database]]
[metabase.models.field :refer [Field]]
[metabase.models.field-values :as field-values]
[metabase.models.table :refer [Table]]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
[toucan.db :as db]))
(defn- do-with-mocked-field-values-updating
"Run F the function responsible for updating FieldValues bound to a mock function that instead just records the names
of Fields that should have been updated. Returns the set of updated Field names."
{:style/indent 0}
[f]
(let [updated-field-names (atom #{})]
(with-redefs [field-values/create-or-update-field-values! (fn [field]
(swap! updated-field-names conj (:name field)))]
(f updated-field-names)
@updated-field-names)))
(defn- basic-native-query []
{:database (data/id)
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS"}})
(defn- native-query-with-template-tag [field-or-id]
{:database (data/id)
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS nWHERE {{category}}"
:template-tags {:category {:name "category"
:display-name "Category"
:type "dimension"
:dimension [:field (u/the-id field-or-id) nil]
:widget-type "category"
:default "Widget"}}}})
(defn- do-with-updated-fields-for-card {:style/indent 1} [options & [f]]
(mt/with-temp* [Database [db (:db options)]
Table [table (merge {:db_id (u/the-id db)}
(:table options))]
Field [field (merge {:table_id (u/the-id table), :has_field_values "list"}
(:field options))]]
(do-with-mocked-field-values-updating
(fn [updated-field-names]
(mt/with-temp Card [card (merge {:dataset_query (native-query-with-template-tag field)}
(:card options))]
(when f
(f {:db db, :table table, :field field, :card card, :updated-field-names updated-field-names})))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | CARDS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- field-values-were-updated-for-new-card? [options]
(not (empty? (do-with-updated-fields-for-card options))))
(deftest newly-created-card-test
(testing "Newly created Card with param referencing Field"
(testing "in On-Demand DB should get updated FieldValues"
(is (= true
(field-values-were-updated-for-new-card? {:db {:is_on_demand true}}))))
(testing "in non-On-Demand DB should *not* get updated FieldValues"
(is (= false
(field-values-were-updated-for-new-card? {:db {:is_on_demand false}}))))))
(deftest existing-card-test
(testing "Existing Card"
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create Parameterized Card with field in On-Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [card updated-field-names]}]
;; clear out the list of updated field names
(reset! updated-field-names #{})
;; now update the Card... since param didn't change at all FieldValues
;; should not be updated
(db/update! Card (u/the-id card) card))))))
(testing "with changed param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; create parameterized Card with Field in On-Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [table card updated-field-names]}]
;; clear out the list of updated field names
(reset! updated-field-names #{})
;; now Change the Field that is referenced by the Card's SQL param
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; create a Card with non-parameterized query
(do-with-updated-fields-for-card
{:db {:is_on_demand true}
:card {:dataset_query (basic-native-query)}
:field {:name "New Field"}}
(fn [{:keys [table field card]}]
;; now change the query to one that references our Field in a
;; on-demand DB. Field should have updated values
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a parameterized Card with a Field that belongs to a non-on-demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [card]}]
;; update the Card. Field should get updated values
(db/update! Card (u/the-id card) card))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a Card with non-parameterized query
(do-with-updated-fields-for-card
{:db {:is_on_demand false}
:card {:dataset_query (basic-native-query)}}
(fn [{:keys [field card]}]
;; now change the query to one that references a Field. Field should
;; not get values since DB is not On-Demand
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a parameterized Card with a Field that belongs to a non-on-demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [table card]}]
;; change the query to one referencing a different Field. Field should
;; not get values since DB is not On-Demand
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DASHBOARDS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- basic-mbql-query []
{:database (data/id)
:type :query
:query {:source-table (data/id :venues)
:aggregation [[:count]]}})
(defn- parameter-mappings-for-card-and-field [card-or-id field-or-id]
[{:card_id (u/the-id card-or-id)
:target [:dimension [:field-id (u/the-id field-or-id)]]}])
(defn- add-dashcard-with-parameter-mapping! [dashboard-or-id card-or-id field-or-id]
(dashboard/add-dashcard! dashboard-or-id card-or-id
{:parameter_mappings (parameter-mappings-for-card-and-field card-or-id field-or-id)}))
(defn- do-with-updated-fields-for-dashboard {:style/indent 1} [options & [f]]
(do-with-updated-fields-for-card (merge {:card {:dataset_query (basic-mbql-query)}}
options)
(fn [objects]
(mt/with-temp Dashboard [dash]
(let [dashcard (add-dashcard-with-parameter-mapping! dash (:card objects) (:field objects))]
(when f
(f (assoc objects
:dash dash
:dashcard dashcard))))))))
(deftest existing-dashboard-test
(testing "Existing Dashboard"
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"My Cool Field"}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}
:field {:name "My Cool Field"}}))))
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [field card dash updated-field-names]}]
;; clear out the list of updated Field Names
(reset! updated-field-names #{})
;; ok, now add a new Card with a param that references the same field
;; The field shouldn't get new values because the set of referenced Fields didn't change
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [table field card dash dashcard updated-field-names]}]
;; create a Dashboard and add a DashboardCard with a param mapping
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:name "<NAME> Field"
:has_field_values "list"}]
;; clear out the list of updated Field Names
(reset! updated-field-names #{})
;; ok, now update the parameter mapping to the new field. The new Field should get new values
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [field card dash updated-field-names]}]
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [table field card dash dashcard updated-field-names]}]
(mt/with-temp Field [new-field {:table_id (u/the-id table), :has_field_values "list"}]
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))))
| true | (ns metabase.models.on-demand-test
"Tests for On-Demand FieldValues updating behavior for Cards and Dashboards."
(:require [clojure.test :refer :all]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :as dashboard :refer [Dashboard]]
[metabase.models.database :refer [Database]]
[metabase.models.field :refer [Field]]
[metabase.models.field-values :as field-values]
[metabase.models.table :refer [Table]]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
[toucan.db :as db]))
(defn- do-with-mocked-field-values-updating
"Run F the function responsible for updating FieldValues bound to a mock function that instead just records the names
of Fields that should have been updated. Returns the set of updated Field names."
{:style/indent 0}
[f]
(let [updated-field-names (atom #{})]
(with-redefs [field-values/create-or-update-field-values! (fn [field]
(swap! updated-field-names conj (:name field)))]
(f updated-field-names)
@updated-field-names)))
(defn- basic-native-query []
{:database (data/id)
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS"}})
(defn- native-query-with-template-tag [field-or-id]
{:database (data/id)
:type "native"
:native {:query "SELECT AVG(SUBTOTAL) AS \"Average Price\"\nFROM ORDERS nWHERE {{category}}"
:template-tags {:category {:name "category"
:display-name "Category"
:type "dimension"
:dimension [:field (u/the-id field-or-id) nil]
:widget-type "category"
:default "Widget"}}}})
(defn- do-with-updated-fields-for-card {:style/indent 1} [options & [f]]
(mt/with-temp* [Database [db (:db options)]
Table [table (merge {:db_id (u/the-id db)}
(:table options))]
Field [field (merge {:table_id (u/the-id table), :has_field_values "list"}
(:field options))]]
(do-with-mocked-field-values-updating
(fn [updated-field-names]
(mt/with-temp Card [card (merge {:dataset_query (native-query-with-template-tag field)}
(:card options))]
(when f
(f {:db db, :table table, :field field, :card card, :updated-field-names updated-field-names})))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | CARDS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- field-values-were-updated-for-new-card? [options]
(not (empty? (do-with-updated-fields-for-card options))))
(deftest newly-created-card-test
(testing "Newly created Card with param referencing Field"
(testing "in On-Demand DB should get updated FieldValues"
(is (= true
(field-values-were-updated-for-new-card? {:db {:is_on_demand true}}))))
(testing "in non-On-Demand DB should *not* get updated FieldValues"
(is (= false
(field-values-were-updated-for-new-card? {:db {:is_on_demand false}}))))))
(deftest existing-card-test
(testing "Existing Card"
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create Parameterized Card with field in On-Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [card updated-field-names]}]
;; clear out the list of updated field names
(reset! updated-field-names #{})
;; now update the Card... since param didn't change at all FieldValues
;; should not be updated
(db/update! Card (u/the-id card) card))))))
(testing "with changed param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; create parameterized Card with Field in On-Demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand true}}
(fn [{:keys [table card updated-field-names]}]
;; clear out the list of updated field names
(reset! updated-field-names #{})
;; now Change the Field that is referenced by the Card's SQL param
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; create a Card with non-parameterized query
(do-with-updated-fields-for-card
{:db {:is_on_demand true}
:card {:dataset_query (basic-native-query)}
:field {:name "New Field"}}
(fn [{:keys [table field card]}]
;; now change the query to one that references our Field in a
;; on-demand DB. Field should have updated values
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a parameterized Card with a Field that belongs to a non-on-demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [card]}]
;; update the Card. Field should get updated values
(db/update! Card (u/the-id card) card))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a Card with non-parameterized query
(do-with-updated-fields-for-card
{:db {:is_on_demand false}
:card {:dataset_query (basic-native-query)}}
(fn [{:keys [field card]}]
;; now change the query to one that references a Field. Field should
;; not get values since DB is not On-Demand
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag field)))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; create a parameterized Card with a Field that belongs to a non-on-demand DB
(do-with-updated-fields-for-card
{:db {:is_on_demand false}}
(fn [{:keys [table card]}]
;; change the query to one referencing a different Field. Field should
;; not get values since DB is not On-Demand
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:has_field_values "list"
:name "New Field"}]
(db/update! Card (u/the-id card)
:dataset_query (native-query-with-template-tag new-field))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DASHBOARDS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- basic-mbql-query []
{:database (data/id)
:type :query
:query {:source-table (data/id :venues)
:aggregation [[:count]]}})
(defn- parameter-mappings-for-card-and-field [card-or-id field-or-id]
[{:card_id (u/the-id card-or-id)
:target [:dimension [:field-id (u/the-id field-or-id)]]}])
(defn- add-dashcard-with-parameter-mapping! [dashboard-or-id card-or-id field-or-id]
(dashboard/add-dashcard! dashboard-or-id card-or-id
{:parameter_mappings (parameter-mappings-for-card-and-field card-or-id field-or-id)}))
(defn- do-with-updated-fields-for-dashboard {:style/indent 1} [options & [f]]
(do-with-updated-fields-for-card (merge {:card {:dataset_query (basic-mbql-query)}}
options)
(fn [objects]
(mt/with-temp Dashboard [dash]
(let [dashcard (add-dashcard-with-parameter-mapping! dash (:card objects) (:field objects))]
(when f
(f (assoc objects
:dash dash
:dashcard dashcard))))))))
(deftest existing-dashboard-test
(testing "Existing Dashboard"
(testing "with newly added param referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"My Cool Field"}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}
:field {:name "My Cool Field"}}))))
(testing "with unchanged param referencing Field in On-Demand DB should *not* get updated FieldValues"
(is (= #{}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [field card dash updated-field-names]}]
;; clear out the list of updated Field Names
(reset! updated-field-names #{})
;; ok, now add a new Card with a param that references the same field
;; The field shouldn't get new values because the set of referenced Fields didn't change
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed referencing Field in On-Demand DB should get updated FieldValues"
(is (= #{"New Field"}
;; Create a On-Demand DB and MBQL Card
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand true}}
(fn [{:keys [table field card dash dashcard updated-field-names]}]
;; create a Dashboard and add a DashboardCard with a param mapping
(mt/with-temp Field [new-field {:table_id (u/the-id table)
:name "PI:NAME:<NAME>END_PI Field"
:has_field_values "list"}]
;; clear out the list of updated Field Names
(reset! updated-field-names #{})
;; ok, now update the parameter mapping to the new field. The new Field should get new values
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))
(testing "with newly added param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}))))
(testing "with unchanged param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [field card dash updated-field-names]}]
(add-dashcard-with-parameter-mapping! dash card field))))))
(testing "with changed param referencing Field in non-On-Demand DB should *not* get updated FieldValues"
(is (= #{}
(do-with-updated-fields-for-dashboard
{:db {:is_on_demand false}}
(fn [{:keys [table field card dash dashcard updated-field-names]}]
(mt/with-temp Field [new-field {:table_id (u/the-id table), :has_field_values "list"}]
(dashboard/update-dashcards! dash
[(assoc dashcard :parameter_mappings (parameter-mappings-for-card-and-field card new-field))])))))))))
|
[
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Bill the Pony\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 634,
"score": 0.7958345413208008,
"start": 621,
"tag": "NAME",
"value": "Bill the Pony"
},
{
"context": " #(and (character? %) (revealed? %))}}\n \"Black Horse\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 708,
"score": 0.5226138234138489,
"start": 704,
"tag": "NAME",
"value": "orse"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Cave Troll\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 853,
"score": 0.8118116855621338,
"start": 843,
"tag": "NAME",
"value": "Cave Troll"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Goldberry\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 1098,
"score": 0.7249528169631958,
"start": 1089,
"tag": "NAME",
"value": "Goldberry"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Gollum\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 1167,
"score": 0.8014049530029297,
"start": 1161,
"tag": "NAME",
"value": "Gollum"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Gwaihir\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 1472,
"score": 0.6851902008056641,
"start": 1465,
"tag": "NAME",
"value": "Gwaihir"
},
{
"context": ":req #(and (character? %) (revealed? %))}}\n \"Kheleglin\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 1544,
"score": 0.9759517312049866,
"start": 1538,
"tag": "NAME",
"value": "leglin"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Leaflock\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 1701,
"score": 0.8959337472915649,
"start": 1693,
"tag": "NAME",
"value": "Leaflock"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Lindion the Oronín\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 1782,
"score": 0.8987016677856445,
"start": 1764,
"tag": "NAME",
"value": "Lindion the Oronín"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Mistress Lobelia\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 1861,
"score": 0.9197330474853516,
"start": 1845,
"tag": "NAME",
"value": "Mistress Lobelia"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Nenseldë the Wingild\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2024,
"score": 0.92476487159729,
"start": 2004,
"tag": "NAME",
"value": "Nenseldë the Wingild"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Noble Hound\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2098,
"score": 0.9678179621696472,
"start": 2087,
"tag": "NAME",
"value": "Noble Hound"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Noble Steed\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2172,
"score": 0.9322137832641602,
"start": 2161,
"tag": "NAME",
"value": "Noble Steed"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Quickbeam\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2244,
"score": 0.9345767498016357,
"start": 2235,
"tag": "NAME",
"value": "Quickbeam"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Radagast's Black Bird\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2328,
"score": 0.8329726457595825,
"start": 2307,
"tag": "NAME",
"value": "Radagast's Black Bird"
},
{
"context": "{:req #(and (character? %) (revealed? %))}}\n \"Roäc the Raven\"\n {:hosting {:req #(and (character? %",
"end": 2481,
"score": 0.6348334550857544,
"start": 2479,
"tag": "NAME",
"value": "äc"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Shadowfax\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2563,
"score": 0.8747559785842896,
"start": 2554,
"tag": "NAME",
"value": "Shadowfax"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Skinbark\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2634,
"score": 0.788929283618927,
"start": 2626,
"tag": "NAME",
"value": "Skinbark"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Stinker\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2704,
"score": 0.9123383164405823,
"start": 2697,
"tag": "NAME",
"value": "Stinker"
},
{
"context": "g {:req #(and (character? %) (revealed? %))}}\n \"Tom Bombadil\"\n {:hosting {:req #(and (character? %) (reveale",
"end": 2928,
"score": 0.9957928657531738,
"start": 2916,
"tag": "NAME",
"value": "Tom Bombadil"
}
] | src/clj/game/cards/allies.clj | rezwits/carncode | 15 | (ns game.cards.allies
(:require [game.core :refer :all]
[game.utils :refer :all]
[game.macros :refer [effect req msg wait-for continue-ability]]
[clojure.string :refer [split-lines split join lower-case includes? starts-with?]]
[clojure.stacktrace :refer [print-stack-trace]]
[cardnum.utils :refer [str->int]]
[cardnum.cards :refer [all-cards]]))
(def card-definitions
{"\"Two-headed\" Troll"
{:hosting {:req #(and (character? %) (revealed? %))}}
"A More or Less Decent Giant"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Bill the Pony"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Black Horse"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Blackbole"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Cave Troll"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Creature of an Older World"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Evil Things Lingering"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Goldberry"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Gollum"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Bats"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Lord of Goblin-gate"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Troll"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Gwaihir"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Kheleglin"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Last Child of Ungoliant"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Leaflock"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Lindion the Oronín"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Mistress Lobelia"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Nasty Slimy Thing"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Nenseldë the Wingild"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Noble Hound"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Noble Steed"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Quickbeam"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Radagast's Black Bird"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Regiment of Black Crows"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Roäc the Raven"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Shadowfax"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Skinbark"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Stinker"
{:hosting {:req #(and (character? %) (revealed? %))}}
"The Balrog"
{:hosting {:req #(and (character? %) (revealed? %))}}
"The Warg-king"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Tom Bombadil"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Treebeard"
{:hosting {:req #(and (character? %) (revealed? %))}}
"War-warg"
{:hosting {:req #(and (character? %) (revealed? %))}}
"War-wolf"
{:hosting {:req #(and (character? %) (revealed? %))}}}) | 3645 | (ns game.cards.allies
(:require [game.core :refer :all]
[game.utils :refer :all]
[game.macros :refer [effect req msg wait-for continue-ability]]
[clojure.string :refer [split-lines split join lower-case includes? starts-with?]]
[clojure.stacktrace :refer [print-stack-trace]]
[cardnum.utils :refer [str->int]]
[cardnum.cards :refer [all-cards]]))
(def card-definitions
{"\"Two-headed\" Troll"
{:hosting {:req #(and (character? %) (revealed? %))}}
"A More or Less Decent Giant"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Black H<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Blackbole"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Creature of an Older World"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Evil Things Lingering"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Bats"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Lord of Goblin-gate"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Troll"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Khe<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Last Child of Ungoliant"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Nasty Slimy Thing"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Regiment of Black Crows"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Ro<NAME> the Raven"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"The Balrog"
{:hosting {:req #(and (character? %) (revealed? %))}}
"The Warg-king"
{:hosting {:req #(and (character? %) (revealed? %))}}
"<NAME>"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Treebeard"
{:hosting {:req #(and (character? %) (revealed? %))}}
"War-warg"
{:hosting {:req #(and (character? %) (revealed? %))}}
"War-wolf"
{:hosting {:req #(and (character? %) (revealed? %))}}}) | true | (ns game.cards.allies
(:require [game.core :refer :all]
[game.utils :refer :all]
[game.macros :refer [effect req msg wait-for continue-ability]]
[clojure.string :refer [split-lines split join lower-case includes? starts-with?]]
[clojure.stacktrace :refer [print-stack-trace]]
[cardnum.utils :refer [str->int]]
[cardnum.cards :refer [all-cards]]))
(def card-definitions
{"\"Two-headed\" Troll"
{:hosting {:req #(and (character? %) (revealed? %))}}
"A More or Less Decent Giant"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Black HPI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Blackbole"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Creature of an Older World"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Evil Things Lingering"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Bats"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Lord of Goblin-gate"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Great Troll"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"KhePI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Last Child of Ungoliant"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Nasty Slimy Thing"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Regiment of Black Crows"
{:hosting {:req #(and (character? %) (revealed? %))}}
"RoPI:NAME:<NAME>END_PI the Raven"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"The Balrog"
{:hosting {:req #(and (character? %) (revealed? %))}}
"The Warg-king"
{:hosting {:req #(and (character? %) (revealed? %))}}
"PI:NAME:<NAME>END_PI"
{:hosting {:req #(and (character? %) (revealed? %))}}
"Treebeard"
{:hosting {:req #(and (character? %) (revealed? %))}}
"War-warg"
{:hosting {:req #(and (character? %) (revealed? %))}}
"War-wolf"
{:hosting {:req #(and (character? %) (revealed? %))}}}) |
[
{
"context": "\n [:label {:for \"password\"} \"Password\"]\n [:input\n ",
"end": 1696,
"score": 0.6944930553436279,
"start": 1688,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": " {:id \"password\"\n :type \"password\"\n :class \"form-control\"\n ",
"end": 1807,
"score": 0.9402439594268799,
"start": 1799,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "rm-control\"\n :placeholder \"Password\"}]]\n submit-button\n ",
"end": 1901,
"score": 0.9750959873199463,
"start": 1893,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "il\n :password password}))\n (partial xhrio-wrapper process-login)",
"end": 2528,
"score": 0.9975767135620117,
"start": 2520,
"tag": "PASSWORD",
"value": "password"
}
] | src/dashboard_cljs/login.cljs | Purple-Services/dashboard-cljs | 6 | (ns dashboard-cljs.login
(:require [crate.core :as crate]
[dashboard-cljs.xhr :refer [retrieve-url xhrio-wrapper]]
[dashboard-cljs.cookies :as cookies]
[dashboard-cljs.utils :refer [base-url]]))
(defn process-login
"Process the response used when logging in"
[response]
(let [error-div (.querySelector js/document "#error-message")
cljs-response (js->clj response :keywordize-keys true)]
(if (:success cljs-response)
(do
(cookies/set-cookie! "token" (:token cljs-response)
7776000)
(cookies/set-cookie! "user-id" (get-in cljs-response
[:user :id])
7776000)
(aset js/window "location" base-url))
(aset error-div "textContent"
(str "Error: " (:message cljs-response))))))
(defn login-form
"A form for logging into the dashboard"
[]
(let [submit-button (crate/html
[:button {:id "login"
:type "submit"
:class "btn btn-default"
} "Login"])
login-form (crate/html
[:div {:id "login-form"}
[:div {:class "form-group"}
[:label {:for "email-address"}
"Email Address"]
[:input
{:id "email"
:type "text"
:class "form-control"
:placeholder "Email"}]]
[:div {:class "form-group"}
[:label {:for "password"} "Password"]
[:input
{:id "password"
:type "password"
:class "form-control"
:placeholder "Password"}]]
submit-button
[:div {:class "has-error"}
[:div {:id "error-message"
:class "control-label"}]]])]
(.addEventListener
submit-button
"click"
#(let [email (aget (.querySelector js/document "#email")
"value")
password (aget (.querySelector js/document "#password")
"value")]
(retrieve-url
(str base-url "login")
"POST"
(js/JSON.stringify (clj->js {:email email
:password password}))
(partial xhrio-wrapper process-login))))
login-form))
(defn login
"Set up the login form"
[]
(let [login-div (.getElementById js/document "login")]
(.appendChild login-div
(crate/html
[:div {:class "container-fluid"}
[:div {:class "row"}
[:div {:class "col-lg-6"}
[:div {:class "panel panel-default"}
[:div {:class "panel-body"}
(login-form)]]]]]))))
| 94711 | (ns dashboard-cljs.login
(:require [crate.core :as crate]
[dashboard-cljs.xhr :refer [retrieve-url xhrio-wrapper]]
[dashboard-cljs.cookies :as cookies]
[dashboard-cljs.utils :refer [base-url]]))
(defn process-login
"Process the response used when logging in"
[response]
(let [error-div (.querySelector js/document "#error-message")
cljs-response (js->clj response :keywordize-keys true)]
(if (:success cljs-response)
(do
(cookies/set-cookie! "token" (:token cljs-response)
7776000)
(cookies/set-cookie! "user-id" (get-in cljs-response
[:user :id])
7776000)
(aset js/window "location" base-url))
(aset error-div "textContent"
(str "Error: " (:message cljs-response))))))
(defn login-form
"A form for logging into the dashboard"
[]
(let [submit-button (crate/html
[:button {:id "login"
:type "submit"
:class "btn btn-default"
} "Login"])
login-form (crate/html
[:div {:id "login-form"}
[:div {:class "form-group"}
[:label {:for "email-address"}
"Email Address"]
[:input
{:id "email"
:type "text"
:class "form-control"
:placeholder "Email"}]]
[:div {:class "form-group"}
[:label {:for "password"} "<PASSWORD>"]
[:input
{:id "password"
:type "<PASSWORD>"
:class "form-control"
:placeholder "<PASSWORD>"}]]
submit-button
[:div {:class "has-error"}
[:div {:id "error-message"
:class "control-label"}]]])]
(.addEventListener
submit-button
"click"
#(let [email (aget (.querySelector js/document "#email")
"value")
password (aget (.querySelector js/document "#password")
"value")]
(retrieve-url
(str base-url "login")
"POST"
(js/JSON.stringify (clj->js {:email email
:password <PASSWORD>}))
(partial xhrio-wrapper process-login))))
login-form))
(defn login
"Set up the login form"
[]
(let [login-div (.getElementById js/document "login")]
(.appendChild login-div
(crate/html
[:div {:class "container-fluid"}
[:div {:class "row"}
[:div {:class "col-lg-6"}
[:div {:class "panel panel-default"}
[:div {:class "panel-body"}
(login-form)]]]]]))))
| true | (ns dashboard-cljs.login
(:require [crate.core :as crate]
[dashboard-cljs.xhr :refer [retrieve-url xhrio-wrapper]]
[dashboard-cljs.cookies :as cookies]
[dashboard-cljs.utils :refer [base-url]]))
(defn process-login
"Process the response used when logging in"
[response]
(let [error-div (.querySelector js/document "#error-message")
cljs-response (js->clj response :keywordize-keys true)]
(if (:success cljs-response)
(do
(cookies/set-cookie! "token" (:token cljs-response)
7776000)
(cookies/set-cookie! "user-id" (get-in cljs-response
[:user :id])
7776000)
(aset js/window "location" base-url))
(aset error-div "textContent"
(str "Error: " (:message cljs-response))))))
(defn login-form
"A form for logging into the dashboard"
[]
(let [submit-button (crate/html
[:button {:id "login"
:type "submit"
:class "btn btn-default"
} "Login"])
login-form (crate/html
[:div {:id "login-form"}
[:div {:class "form-group"}
[:label {:for "email-address"}
"Email Address"]
[:input
{:id "email"
:type "text"
:class "form-control"
:placeholder "Email"}]]
[:div {:class "form-group"}
[:label {:for "password"} "PI:PASSWORD:<PASSWORD>END_PI"]
[:input
{:id "password"
:type "PI:PASSWORD:<PASSWORD>END_PI"
:class "form-control"
:placeholder "PI:PASSWORD:<PASSWORD>END_PI"}]]
submit-button
[:div {:class "has-error"}
[:div {:id "error-message"
:class "control-label"}]]])]
(.addEventListener
submit-button
"click"
#(let [email (aget (.querySelector js/document "#email")
"value")
password (aget (.querySelector js/document "#password")
"value")]
(retrieve-url
(str base-url "login")
"POST"
(js/JSON.stringify (clj->js {:email email
:password PI:PASSWORD:<PASSWORD>END_PI}))
(partial xhrio-wrapper process-login))))
login-form))
(defn login
"Set up the login form"
[]
(let [login-div (.getElementById js/document "login")]
(.appendChild login-div
(crate/html
[:div {:class "container-fluid"}
[:div {:class "row"}
[:div {:class "col-lg-6"}
[:div {:class "panel panel-default"}
[:div {:class "panel-body"}
(login-form)]]]]]))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.