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": "ux/submit-tx\n (sys)\n {[:user] {:user/email \"foo@example.com\"}})\n\n ; Inspect transactions before running them", "end": 752, "score": 0.9999063611030579, "start": 737, "tag": "EMAIL", "value": "foo@example.com" }, { "context": "d)\n {[:user] {:user/email \"foo@example.com\"}})]\n (bu/pprint crux-tx)\n ; See if this tr", "end": 1078, "score": 0.9999106526374817, "start": 1063, "tag": "EMAIL", "value": "foo@example.com" } ]
libs/tasks/resources/biff/template/src/{{parent-path}}/admin.clj
modelingcooperation/biff
273
(ns {{parent-ns}}.admin (:require [biff.crux :as bcrux] [biff.util :as bu] [crux.api :as crux])) (defn sys [] (let [{:keys [biff.crux/node] :as sys} @bu/system] (assoc sys :biff.crux/db (delay (crux/db node))))) (comment ; This namespace isn't required from anywhere. You can use it as a ; repl-driven admin console and for experimenting. ; Inspect the db (let [{:keys [biff.crux/db]} (sys)] (crux/q @db '{:find [(pull user [*])] :where [[user :user/email]]})) ; Submit transactions (this will bypass authorization rules since we don't ; set :biff.crux/authorize true. i.e. it's a trusted transaction) (bcrux/submit-tx (sys) {[:user] {:user/email "foo@example.com"}}) ; Inspect transactions before running them (let [s (sys) uid "some-uuid" ; In actual usage, you would query this from the db first. {:keys [crux-tx] :as tx-info} (bcrux/get-tx-info (assoc s :biff/uid uid) {[:user] {:user/email "foo@example.com"}})] (bu/pprint crux-tx) ; See if this transaction would pass authorization rules (when-some [bad-doc (bcrux/check-write s tx-info)] (println "The transaction is unauthorized:") (bu/pprint bad-doc))) ; Test out subscribable queries (including authorization) (bcrux/biff-q (sys) {:doc-type :msg :where '[[:msg/sent-at t] [(<= #inst "1970" t)]]}) ; Test out Girouette classes (only works in dev, not prod) ((requiring-resolve '{{parent-ns}}.dev.css/class-name->garden) "bg-blue-200") )
19236
(ns {{parent-ns}}.admin (:require [biff.crux :as bcrux] [biff.util :as bu] [crux.api :as crux])) (defn sys [] (let [{:keys [biff.crux/node] :as sys} @bu/system] (assoc sys :biff.crux/db (delay (crux/db node))))) (comment ; This namespace isn't required from anywhere. You can use it as a ; repl-driven admin console and for experimenting. ; Inspect the db (let [{:keys [biff.crux/db]} (sys)] (crux/q @db '{:find [(pull user [*])] :where [[user :user/email]]})) ; Submit transactions (this will bypass authorization rules since we don't ; set :biff.crux/authorize true. i.e. it's a trusted transaction) (bcrux/submit-tx (sys) {[:user] {:user/email "<EMAIL>"}}) ; Inspect transactions before running them (let [s (sys) uid "some-uuid" ; In actual usage, you would query this from the db first. {:keys [crux-tx] :as tx-info} (bcrux/get-tx-info (assoc s :biff/uid uid) {[:user] {:user/email "<EMAIL>"}})] (bu/pprint crux-tx) ; See if this transaction would pass authorization rules (when-some [bad-doc (bcrux/check-write s tx-info)] (println "The transaction is unauthorized:") (bu/pprint bad-doc))) ; Test out subscribable queries (including authorization) (bcrux/biff-q (sys) {:doc-type :msg :where '[[:msg/sent-at t] [(<= #inst "1970" t)]]}) ; Test out Girouette classes (only works in dev, not prod) ((requiring-resolve '{{parent-ns}}.dev.css/class-name->garden) "bg-blue-200") )
true
(ns {{parent-ns}}.admin (:require [biff.crux :as bcrux] [biff.util :as bu] [crux.api :as crux])) (defn sys [] (let [{:keys [biff.crux/node] :as sys} @bu/system] (assoc sys :biff.crux/db (delay (crux/db node))))) (comment ; This namespace isn't required from anywhere. You can use it as a ; repl-driven admin console and for experimenting. ; Inspect the db (let [{:keys [biff.crux/db]} (sys)] (crux/q @db '{:find [(pull user [*])] :where [[user :user/email]]})) ; Submit transactions (this will bypass authorization rules since we don't ; set :biff.crux/authorize true. i.e. it's a trusted transaction) (bcrux/submit-tx (sys) {[:user] {:user/email "PI:EMAIL:<EMAIL>END_PI"}}) ; Inspect transactions before running them (let [s (sys) uid "some-uuid" ; In actual usage, you would query this from the db first. {:keys [crux-tx] :as tx-info} (bcrux/get-tx-info (assoc s :biff/uid uid) {[:user] {:user/email "PI:EMAIL:<EMAIL>END_PI"}})] (bu/pprint crux-tx) ; See if this transaction would pass authorization rules (when-some [bad-doc (bcrux/check-write s tx-info)] (println "The transaction is unauthorized:") (bu/pprint bad-doc))) ; Test out subscribable queries (including authorization) (bcrux/biff-q (sys) {:doc-type :msg :where '[[:msg/sent-at t] [(<= #inst "1970" t)]]}) ; Test out Girouette classes (only works in dev, not prod) ((requiring-resolve '{{parent-ns}}.dev.css/class-name->garden) "bg-blue-200") )
[ { "context": "]\n [:user_name {:display_name \"User\", :base_type :type/Text, :remapped_", "end": 7868, "score": 0.9944064617156982, "start": 7864, "tag": "NAME", "value": "User" } ]
c#-metabase/enterprise/backend/src/metabase_enterprise/audit/pages/downloads.clj
hanakhry/Crime_Admin
0
(ns metabase-enterprise.audit.pages.downloads "Audit queries returning info about query downloads. Query downloads are any query executions whose results are returned as CSV/JSON/XLS." (:require [honeysql.core :as hsql] [metabase-enterprise.audit.pages.common :as common] [metabase.db :as mdb] [metabase.driver.sql.query-processor :as sql.qp] [metabase.util.honeysql-extensions :as hx] [schema.core :as s])) ;;; ------------------------------------------------ per-day-by-size ------------------------------------------------- (s/defn ^:internal-query-fn per-day-by-size "Pairs of count of rows downloaded and date downloaded for the 1000 largest (in terms of row count) queries over the past 30 days. Intended to power scatter plot." [] {:metadata [[:date {:display_name "Day", :base_type :type/DateTime}] [:rows {:display_name "Rows in Query", :base_type :type/Integer}] [:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "User", :base_type :type/Text, :remapped_from :user_id}]] :results (common/reducible-query {:select [[:qe.started_at :date] [:qe.result_rows :rows] [:qe.executor_id :user_id] [(common/user-full-name :u) :user_name]] :from [[:query_execution :qe]] :left-join [[:core_user :u] [:= :qe.executor_id :u.id]] :where [:and [:> :qe.started_at (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -30 :day)] (common/query-execution-is-download :qe)] :order-by [[:qe.result_rows :desc]] :limit 1000})}) ;;; ---------------------------------------------------- per-user ---------------------------------------------------- (s/defn ^:internal-query-fn per-user "Total count of query downloads broken out by user, ordered by highest total, for the top 10 users." [] {:metadata [[:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "User", :base_type :type/Text, :remapped_from :user_id}] [:downloads {:display_name "Downloads", :base_type :type/Integer}]] :results (common/reducible-query {:with [[:downloads_by_user {:select [[:qe.executor_id :user_id] [:%count.* :downloads]] :from [[:query_execution :qe]] :where (common/query-execution-is-download :qe) :group-by [:qe.executor_id] :order-by [[:%count.* :desc]] :limit 10}]] :select [[:d.user_id :user_id] [(common/user-full-name :u) :user_name] [:d.downloads :downloads]] :from [[:downloads_by_user :d]] :join [[:core_user :u] [:= :d.user_id :u.id]] :order-by [[:d.downloads :desc]]})}) ;;; ---------------------------------------------------- by-size ----------------------------------------------------- (def ^:private bucket-maxes "Add/remove numbers here to adjust buckets returned by the `by-size` query." [ 10 100 1000 5000 10000 50000 100000 500000 1000000]) (def ^:private rows->bucket-case-expression "`CASE` expression to put `result_rows` in appropriate buckets. Looks something like: CASE ... result_rows <= 100 THEN 100 ..." (apply hsql/call :case (concat (mapcat (fn [bucket-max] [[:<= :result_rows bucket-max] bucket-max]) bucket-maxes) [:else -1]))) (def ^:private bucket-ranges "Pairs like [[0 10], [11 100], ...]" (reduce (fn [acc bucket-max] (conj acc [(or (some-> acc last last inc) 0) ; get min from last pair in acc or 0 bucket-max])) [] bucket-maxes)) (defn- format-number-add-commas "Format number to string adding commas as thousands separators." [^Number n] (.format (java.text.DecimalFormat. "#,###") n)) (defn- bucket-range->literal "Given a bucket range pair like [101 1000] return a formatted string including commas like `101-1,000`." [[bucket-min bucket-max]] (hx/literal (format "%s-%s" (format-number-add-commas bucket-min) (format-number-add-commas bucket-max)))) (def ^:private bucket->range-str-case-expression "`CASE` expression to generate range strings for each bucket. Looks something like: CASE ... (rows_bucket_max = 1000) THEN '101-1,000' ..." (apply hsql/call :case (concat (mapcat (fn [[_ bucket-max :as bucket-range]] [[:= :rows_bucket_max bucket-max] (bucket-range->literal bucket-range)]) bucket-ranges) [[:= :rows_bucket_max -1] (hx/literal (format "> %s" (format-number-add-commas (last bucket-maxes))))]))) (s/defn ^:internal-query-fn by-size "Query download count broken out by bucketed number of rows of query. E.g. 10 downloads of queries with 0-10 rows, 15 downloads of queries with 11-100, etc. Intended to power bar chart." [] {:metadata [[:rows {:display_name "Rows Downloaded", :base_type :type/Text}] [:downloads {:display_name "Downloads", :base_type :type/Integer}]] :results (common/reducible-query {:with [[:bucketed_downloads {:select [[rows->bucket-case-expression :rows_bucket_max]] :from [:query_execution] :where [:and (common/query-execution-is-download :query_execution) [:not= :result_rows nil]]}]] :select [[bucket->range-str-case-expression :rows] [:%count.* :downloads]] :from [:bucketed_downloads] :group-by [:rows_bucket_max] :order-by [[:rows_bucket_max :asc]]})}) ;;; ----------------------------------------------------- table ------------------------------------------------------ (s/defn ^:internal-query-fn table "Table showing all query downloads ordered by most recent." [] {:metadata [[:downloaded_at {:display_name "Downloaded At", :base_type :type/DateTime}] [:rows_downloaded {:display_name "Rows Downloaded", :base_type :type/Integer}] [:card_id {:display_name "Card ID", :base_type :type/Integer, :remapped_to :card_name}] [:card_name {:display_name "Query", :base_type :type/Text, :remapped_from :card_id}] [:query_type {:display_name "Query Type", :base_type :type/Text}] [:database_id {:display_name "Database ID", :base_type :type/Integer, :remapped_to :database}] [:database {:display_name "Database", :base_type :type/Text, :remapped_from :database_id}] [:source_table_id {:display_name "Source Table ID", :base_type :type/Integer, :remapped_to :source_table}] [:source_table {:display_name "Source Table", :base_type :type/Text, :remapped_from :source_table_id}] [:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "User", :base_type :type/Text, :remapped_from :user_id}]] :results (common/reducible-query {:select [[:qe.started_at :downloaded_at] [:qe.result_rows :rows_downloaded] [:card.id :card_id] [(common/card-name-or-ad-hoc :card) :card_name] [(common/native-or-gui :qe) :query_type] [:db.id :database_id] [:db.name :database] [:t.id :source_table_id] [:t.name :source_table] [:qe.executor_id :user_id] [(common/user-full-name :u) :user_name]] :from [[:query_execution :qe]] :left-join [[:report_card :card] [:= :card.id :qe.card_id] [:metabase_database :db] [:= :qe.database_id :db.id] [:metabase_table :t] [:= :card.table_id :t.id] [:core_user :u] [:= :qe.executor_id :u.id]] :where (common/query-execution-is-download :qe) :order-by [[:qe.started_at :desc]]})})
57463
(ns metabase-enterprise.audit.pages.downloads "Audit queries returning info about query downloads. Query downloads are any query executions whose results are returned as CSV/JSON/XLS." (:require [honeysql.core :as hsql] [metabase-enterprise.audit.pages.common :as common] [metabase.db :as mdb] [metabase.driver.sql.query-processor :as sql.qp] [metabase.util.honeysql-extensions :as hx] [schema.core :as s])) ;;; ------------------------------------------------ per-day-by-size ------------------------------------------------- (s/defn ^:internal-query-fn per-day-by-size "Pairs of count of rows downloaded and date downloaded for the 1000 largest (in terms of row count) queries over the past 30 days. Intended to power scatter plot." [] {:metadata [[:date {:display_name "Day", :base_type :type/DateTime}] [:rows {:display_name "Rows in Query", :base_type :type/Integer}] [:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "User", :base_type :type/Text, :remapped_from :user_id}]] :results (common/reducible-query {:select [[:qe.started_at :date] [:qe.result_rows :rows] [:qe.executor_id :user_id] [(common/user-full-name :u) :user_name]] :from [[:query_execution :qe]] :left-join [[:core_user :u] [:= :qe.executor_id :u.id]] :where [:and [:> :qe.started_at (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -30 :day)] (common/query-execution-is-download :qe)] :order-by [[:qe.result_rows :desc]] :limit 1000})}) ;;; ---------------------------------------------------- per-user ---------------------------------------------------- (s/defn ^:internal-query-fn per-user "Total count of query downloads broken out by user, ordered by highest total, for the top 10 users." [] {:metadata [[:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "User", :base_type :type/Text, :remapped_from :user_id}] [:downloads {:display_name "Downloads", :base_type :type/Integer}]] :results (common/reducible-query {:with [[:downloads_by_user {:select [[:qe.executor_id :user_id] [:%count.* :downloads]] :from [[:query_execution :qe]] :where (common/query-execution-is-download :qe) :group-by [:qe.executor_id] :order-by [[:%count.* :desc]] :limit 10}]] :select [[:d.user_id :user_id] [(common/user-full-name :u) :user_name] [:d.downloads :downloads]] :from [[:downloads_by_user :d]] :join [[:core_user :u] [:= :d.user_id :u.id]] :order-by [[:d.downloads :desc]]})}) ;;; ---------------------------------------------------- by-size ----------------------------------------------------- (def ^:private bucket-maxes "Add/remove numbers here to adjust buckets returned by the `by-size` query." [ 10 100 1000 5000 10000 50000 100000 500000 1000000]) (def ^:private rows->bucket-case-expression "`CASE` expression to put `result_rows` in appropriate buckets. Looks something like: CASE ... result_rows <= 100 THEN 100 ..." (apply hsql/call :case (concat (mapcat (fn [bucket-max] [[:<= :result_rows bucket-max] bucket-max]) bucket-maxes) [:else -1]))) (def ^:private bucket-ranges "Pairs like [[0 10], [11 100], ...]" (reduce (fn [acc bucket-max] (conj acc [(or (some-> acc last last inc) 0) ; get min from last pair in acc or 0 bucket-max])) [] bucket-maxes)) (defn- format-number-add-commas "Format number to string adding commas as thousands separators." [^Number n] (.format (java.text.DecimalFormat. "#,###") n)) (defn- bucket-range->literal "Given a bucket range pair like [101 1000] return a formatted string including commas like `101-1,000`." [[bucket-min bucket-max]] (hx/literal (format "%s-%s" (format-number-add-commas bucket-min) (format-number-add-commas bucket-max)))) (def ^:private bucket->range-str-case-expression "`CASE` expression to generate range strings for each bucket. Looks something like: CASE ... (rows_bucket_max = 1000) THEN '101-1,000' ..." (apply hsql/call :case (concat (mapcat (fn [[_ bucket-max :as bucket-range]] [[:= :rows_bucket_max bucket-max] (bucket-range->literal bucket-range)]) bucket-ranges) [[:= :rows_bucket_max -1] (hx/literal (format "> %s" (format-number-add-commas (last bucket-maxes))))]))) (s/defn ^:internal-query-fn by-size "Query download count broken out by bucketed number of rows of query. E.g. 10 downloads of queries with 0-10 rows, 15 downloads of queries with 11-100, etc. Intended to power bar chart." [] {:metadata [[:rows {:display_name "Rows Downloaded", :base_type :type/Text}] [:downloads {:display_name "Downloads", :base_type :type/Integer}]] :results (common/reducible-query {:with [[:bucketed_downloads {:select [[rows->bucket-case-expression :rows_bucket_max]] :from [:query_execution] :where [:and (common/query-execution-is-download :query_execution) [:not= :result_rows nil]]}]] :select [[bucket->range-str-case-expression :rows] [:%count.* :downloads]] :from [:bucketed_downloads] :group-by [:rows_bucket_max] :order-by [[:rows_bucket_max :asc]]})}) ;;; ----------------------------------------------------- table ------------------------------------------------------ (s/defn ^:internal-query-fn table "Table showing all query downloads ordered by most recent." [] {:metadata [[:downloaded_at {:display_name "Downloaded At", :base_type :type/DateTime}] [:rows_downloaded {:display_name "Rows Downloaded", :base_type :type/Integer}] [:card_id {:display_name "Card ID", :base_type :type/Integer, :remapped_to :card_name}] [:card_name {:display_name "Query", :base_type :type/Text, :remapped_from :card_id}] [:query_type {:display_name "Query Type", :base_type :type/Text}] [:database_id {:display_name "Database ID", :base_type :type/Integer, :remapped_to :database}] [:database {:display_name "Database", :base_type :type/Text, :remapped_from :database_id}] [:source_table_id {:display_name "Source Table ID", :base_type :type/Integer, :remapped_to :source_table}] [:source_table {:display_name "Source Table", :base_type :type/Text, :remapped_from :source_table_id}] [:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "<NAME>", :base_type :type/Text, :remapped_from :user_id}]] :results (common/reducible-query {:select [[:qe.started_at :downloaded_at] [:qe.result_rows :rows_downloaded] [:card.id :card_id] [(common/card-name-or-ad-hoc :card) :card_name] [(common/native-or-gui :qe) :query_type] [:db.id :database_id] [:db.name :database] [:t.id :source_table_id] [:t.name :source_table] [:qe.executor_id :user_id] [(common/user-full-name :u) :user_name]] :from [[:query_execution :qe]] :left-join [[:report_card :card] [:= :card.id :qe.card_id] [:metabase_database :db] [:= :qe.database_id :db.id] [:metabase_table :t] [:= :card.table_id :t.id] [:core_user :u] [:= :qe.executor_id :u.id]] :where (common/query-execution-is-download :qe) :order-by [[:qe.started_at :desc]]})})
true
(ns metabase-enterprise.audit.pages.downloads "Audit queries returning info about query downloads. Query downloads are any query executions whose results are returned as CSV/JSON/XLS." (:require [honeysql.core :as hsql] [metabase-enterprise.audit.pages.common :as common] [metabase.db :as mdb] [metabase.driver.sql.query-processor :as sql.qp] [metabase.util.honeysql-extensions :as hx] [schema.core :as s])) ;;; ------------------------------------------------ per-day-by-size ------------------------------------------------- (s/defn ^:internal-query-fn per-day-by-size "Pairs of count of rows downloaded and date downloaded for the 1000 largest (in terms of row count) queries over the past 30 days. Intended to power scatter plot." [] {:metadata [[:date {:display_name "Day", :base_type :type/DateTime}] [:rows {:display_name "Rows in Query", :base_type :type/Integer}] [:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "User", :base_type :type/Text, :remapped_from :user_id}]] :results (common/reducible-query {:select [[:qe.started_at :date] [:qe.result_rows :rows] [:qe.executor_id :user_id] [(common/user-full-name :u) :user_name]] :from [[:query_execution :qe]] :left-join [[:core_user :u] [:= :qe.executor_id :u.id]] :where [:and [:> :qe.started_at (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -30 :day)] (common/query-execution-is-download :qe)] :order-by [[:qe.result_rows :desc]] :limit 1000})}) ;;; ---------------------------------------------------- per-user ---------------------------------------------------- (s/defn ^:internal-query-fn per-user "Total count of query downloads broken out by user, ordered by highest total, for the top 10 users." [] {:metadata [[:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "User", :base_type :type/Text, :remapped_from :user_id}] [:downloads {:display_name "Downloads", :base_type :type/Integer}]] :results (common/reducible-query {:with [[:downloads_by_user {:select [[:qe.executor_id :user_id] [:%count.* :downloads]] :from [[:query_execution :qe]] :where (common/query-execution-is-download :qe) :group-by [:qe.executor_id] :order-by [[:%count.* :desc]] :limit 10}]] :select [[:d.user_id :user_id] [(common/user-full-name :u) :user_name] [:d.downloads :downloads]] :from [[:downloads_by_user :d]] :join [[:core_user :u] [:= :d.user_id :u.id]] :order-by [[:d.downloads :desc]]})}) ;;; ---------------------------------------------------- by-size ----------------------------------------------------- (def ^:private bucket-maxes "Add/remove numbers here to adjust buckets returned by the `by-size` query." [ 10 100 1000 5000 10000 50000 100000 500000 1000000]) (def ^:private rows->bucket-case-expression "`CASE` expression to put `result_rows` in appropriate buckets. Looks something like: CASE ... result_rows <= 100 THEN 100 ..." (apply hsql/call :case (concat (mapcat (fn [bucket-max] [[:<= :result_rows bucket-max] bucket-max]) bucket-maxes) [:else -1]))) (def ^:private bucket-ranges "Pairs like [[0 10], [11 100], ...]" (reduce (fn [acc bucket-max] (conj acc [(or (some-> acc last last inc) 0) ; get min from last pair in acc or 0 bucket-max])) [] bucket-maxes)) (defn- format-number-add-commas "Format number to string adding commas as thousands separators." [^Number n] (.format (java.text.DecimalFormat. "#,###") n)) (defn- bucket-range->literal "Given a bucket range pair like [101 1000] return a formatted string including commas like `101-1,000`." [[bucket-min bucket-max]] (hx/literal (format "%s-%s" (format-number-add-commas bucket-min) (format-number-add-commas bucket-max)))) (def ^:private bucket->range-str-case-expression "`CASE` expression to generate range strings for each bucket. Looks something like: CASE ... (rows_bucket_max = 1000) THEN '101-1,000' ..." (apply hsql/call :case (concat (mapcat (fn [[_ bucket-max :as bucket-range]] [[:= :rows_bucket_max bucket-max] (bucket-range->literal bucket-range)]) bucket-ranges) [[:= :rows_bucket_max -1] (hx/literal (format "> %s" (format-number-add-commas (last bucket-maxes))))]))) (s/defn ^:internal-query-fn by-size "Query download count broken out by bucketed number of rows of query. E.g. 10 downloads of queries with 0-10 rows, 15 downloads of queries with 11-100, etc. Intended to power bar chart." [] {:metadata [[:rows {:display_name "Rows Downloaded", :base_type :type/Text}] [:downloads {:display_name "Downloads", :base_type :type/Integer}]] :results (common/reducible-query {:with [[:bucketed_downloads {:select [[rows->bucket-case-expression :rows_bucket_max]] :from [:query_execution] :where [:and (common/query-execution-is-download :query_execution) [:not= :result_rows nil]]}]] :select [[bucket->range-str-case-expression :rows] [:%count.* :downloads]] :from [:bucketed_downloads] :group-by [:rows_bucket_max] :order-by [[:rows_bucket_max :asc]]})}) ;;; ----------------------------------------------------- table ------------------------------------------------------ (s/defn ^:internal-query-fn table "Table showing all query downloads ordered by most recent." [] {:metadata [[:downloaded_at {:display_name "Downloaded At", :base_type :type/DateTime}] [:rows_downloaded {:display_name "Rows Downloaded", :base_type :type/Integer}] [:card_id {:display_name "Card ID", :base_type :type/Integer, :remapped_to :card_name}] [:card_name {:display_name "Query", :base_type :type/Text, :remapped_from :card_id}] [:query_type {:display_name "Query Type", :base_type :type/Text}] [:database_id {:display_name "Database ID", :base_type :type/Integer, :remapped_to :database}] [:database {:display_name "Database", :base_type :type/Text, :remapped_from :database_id}] [:source_table_id {:display_name "Source Table ID", :base_type :type/Integer, :remapped_to :source_table}] [:source_table {:display_name "Source Table", :base_type :type/Text, :remapped_from :source_table_id}] [:user_id {:display_name "User ID", :base_type :type/Integer, :remapped_to :user_name}] [:user_name {:display_name "PI:NAME:<NAME>END_PI", :base_type :type/Text, :remapped_from :user_id}]] :results (common/reducible-query {:select [[:qe.started_at :downloaded_at] [:qe.result_rows :rows_downloaded] [:card.id :card_id] [(common/card-name-or-ad-hoc :card) :card_name] [(common/native-or-gui :qe) :query_type] [:db.id :database_id] [:db.name :database] [:t.id :source_table_id] [:t.name :source_table] [:qe.executor_id :user_id] [(common/user-full-name :u) :user_name]] :from [[:query_execution :qe]] :left-join [[:report_card :card] [:= :card.id :qe.card_id] [:metabase_database :db] [:= :qe.database_id :db.id] [:metabase_table :t] [:= :card.table_id :t.id] [:core_user :u] [:= :qe.executor_id :u.id]] :where (common/query-execution-is-download :qe) :order-by [[:qe.started_at :desc]]})})
[ { "context": "(ns ^{:doc \"Site footer.\"\n :author \"Eric Weinstein <eric.q.weinstein@gmail.com>\"}\n cityshelf.compon", "end": 55, "score": 0.9998852014541626, "start": 41, "tag": "NAME", "value": "Eric Weinstein" }, { "context": "doc \"Site footer.\"\n :author \"Eric Weinstein <eric.q.weinstein@gmail.com>\"}\n cityshelf.components.footer)\n\n(defn footer\n ", "end": 83, "score": 0.9999294877052307, "start": 57, "tag": "EMAIL", "value": "eric.q.weinstein@gmail.com" }, { "context": "er.\"\n []\n [:div.footer\n [:p [:a {:href \"mailto:info@cityshelf.com\"} \"info@cityshelf.com\"]\n (str \" / \" (.getFullYe", "end": 212, "score": 0.999930202960968, "start": 194, "tag": "EMAIL", "value": "info@cityshelf.com" }, { "context": "er\n [:p [:a {:href \"mailto:info@cityshelf.com\"} \"info@cityshelf.com\"]\n (str \" / \" (.getFullYear (js/Date.)) \" CityS", "end": 234, "score": 0.9999310374259949, "start": 216, "tag": "EMAIL", "value": "info@cityshelf.com" } ]
src/cityshelf/components/footer.cljs
ericqweinstein/cityshelf
0
(ns ^{:doc "Site footer." :author "Eric Weinstein <eric.q.weinstein@gmail.com>"} cityshelf.components.footer) (defn footer "Site footer." [] [:div.footer [:p [:a {:href "mailto:info@cityshelf.com"} "info@cityshelf.com"] (str " / " (.getFullYear (js/Date.)) " CityShelf™")]])
22895
(ns ^{:doc "Site footer." :author "<NAME> <<EMAIL>>"} cityshelf.components.footer) (defn footer "Site footer." [] [:div.footer [:p [:a {:href "mailto:<EMAIL>"} "<EMAIL>"] (str " / " (.getFullYear (js/Date.)) " CityShelf™")]])
true
(ns ^{:doc "Site footer." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"} cityshelf.components.footer) (defn footer "Site footer." [] [:div.footer [:p [:a {:href "mailto:PI:EMAIL:<EMAIL>END_PI"} "PI:EMAIL:<EMAIL>END_PI"] (str " / " (.getFullYear (js/Date.)) " CityShelf™")]])
[ { "context": "ave-and-true.chapter05)\n\n(def character\n {:name \"Smooches McCutes\"\n :attributes {:intelligence 10\n ", "end": 76, "score": 0.9998709559440613, "start": 60, "tag": "NAME", "value": "Smooches McCutes" } ]
src/clj_brave_and_true/chapter05.clj
artemy/clj-brave-and-true-exercises
0
(ns clj-brave-and-true.chapter05) (def character {:name "Smooches McCutes" :attributes {:intelligence 10 :strength 4 :dexterity 5}}) (def c-int (comp :intelligence :attributes)) (c-int character) ;; Exercise 1: You used (comp :intelligence :attributes) ;; to create a function that returns a character’s intelligence. ;; Create a new function, attr, that you can call ;; like (attr :intelligence) and that does the same thing. (defn attr [key] (comp key :attributes)) ;; Exercise 2: Implement the comp function. (defn my-comp ([] identity) ([f] f) ([f g] (fn ([] (f (g))) ([arg] (f (g arg))) ([arg1 arg2] (f (g arg1 arg2))) ([arg1 arg2 & args] (f apply (g arg1 arg2 args))))) ([f g & funcs] (reduce my-comp (list* f g funcs)))) ;; Exercise 3: Implement the assoc-in function. ;; Hint: use the assoc function and define its parameters as [m [k & ks] v]. (defn my-assoc-in [m [k & ks] v] (if ks (assoc m k (my-assoc-in (get m k) ks v)) (assoc m k v))) ;; Exercise 5: Implement update-in. (defn my-update-in [m [k & ks] f & args] (if ks (assoc m k (apply my-update-in (get m k) ks f args)) (assoc m k (apply f (get m k) args))))
73290
(ns clj-brave-and-true.chapter05) (def character {:name "<NAME>" :attributes {:intelligence 10 :strength 4 :dexterity 5}}) (def c-int (comp :intelligence :attributes)) (c-int character) ;; Exercise 1: You used (comp :intelligence :attributes) ;; to create a function that returns a character’s intelligence. ;; Create a new function, attr, that you can call ;; like (attr :intelligence) and that does the same thing. (defn attr [key] (comp key :attributes)) ;; Exercise 2: Implement the comp function. (defn my-comp ([] identity) ([f] f) ([f g] (fn ([] (f (g))) ([arg] (f (g arg))) ([arg1 arg2] (f (g arg1 arg2))) ([arg1 arg2 & args] (f apply (g arg1 arg2 args))))) ([f g & funcs] (reduce my-comp (list* f g funcs)))) ;; Exercise 3: Implement the assoc-in function. ;; Hint: use the assoc function and define its parameters as [m [k & ks] v]. (defn my-assoc-in [m [k & ks] v] (if ks (assoc m k (my-assoc-in (get m k) ks v)) (assoc m k v))) ;; Exercise 5: Implement update-in. (defn my-update-in [m [k & ks] f & args] (if ks (assoc m k (apply my-update-in (get m k) ks f args)) (assoc m k (apply f (get m k) args))))
true
(ns clj-brave-and-true.chapter05) (def character {:name "PI:NAME:<NAME>END_PI" :attributes {:intelligence 10 :strength 4 :dexterity 5}}) (def c-int (comp :intelligence :attributes)) (c-int character) ;; Exercise 1: You used (comp :intelligence :attributes) ;; to create a function that returns a character’s intelligence. ;; Create a new function, attr, that you can call ;; like (attr :intelligence) and that does the same thing. (defn attr [key] (comp key :attributes)) ;; Exercise 2: Implement the comp function. (defn my-comp ([] identity) ([f] f) ([f g] (fn ([] (f (g))) ([arg] (f (g arg))) ([arg1 arg2] (f (g arg1 arg2))) ([arg1 arg2 & args] (f apply (g arg1 arg2 args))))) ([f g & funcs] (reduce my-comp (list* f g funcs)))) ;; Exercise 3: Implement the assoc-in function. ;; Hint: use the assoc function and define its parameters as [m [k & ks] v]. (defn my-assoc-in [m [k & ks] v] (if ks (assoc m k (my-assoc-in (get m k) ks v)) (assoc m k v))) ;; Exercise 5: Implement update-in. (defn my-update-in [m [k & ks] f & args] (if ks (assoc m k (apply my-update-in (get m k) ks f args)) (assoc m k (apply f (get m k) args))))
[ { "context": " :key-alias \"vif-alias\"\n\n ", "end": 1876, "score": 0.9976733922958374, "start": 1867, "tag": "KEY", "value": "vif-alias" } ]
vif-navigator/project.clj
zheludkovm/VifNavigator
0
(defproject vif-navigator/vif-navigator "0.0.1-SNAPSHOT" :description "Vif navigator" :url "http://example.com/FIXME" :global-vars {*warn-on-reflection* true} :resource-paths ["res"] :source-paths ["src/clojure" "src"] :java-source-paths ["src/java"] :javac-options ["-target" "1.6" "-source" "1.6" "-Xlint:-options"] :plugins [[lein-droid "0.3.5"]] :dependencies [[org.clojure-android/clojure "1.7.0-alpha6" :use-resources true] [neko/neko "3.2.0"] [org.jsoup/jsoup "1.8.2" :use-resources true] [vif-navigator-libs "0.1.0-SNAPSHOT" :use-resources true] ] :profiles {:default [:dev] :dev [:android-common :android-user {:dependencies [[org.clojure-android/tools.nrepl "0.2.6"]] :target-path "target/debug" :android {:aot :all-with-unused :manifest-options {:app-name "VifNavigator - debug"}}}] :release [:android-common {:target-path "target/release" :android {;; Specify the path to your private keystore ;; and the the alias of the key you want to ;; sign APKs with. :keystore-path "/home/mikl/.android/release-keysore" :key-alias "vif-alias" :ignore-log-priority [:debug :verbose] :aot :all-with-unused :build-type :release}}] :lean [:release {:dependencies ^:replace [[org.skummet/clojure-android "1.7.0-alpha5-r2" :use-resources true] [neko/neko "3.2.0"] [vif-navigator-libs "0.1.0-SNAPSHOT" :use-resources true] ] :exclusions [[org.clojure/clojure]] :jvm-opts ["-Dclojure.compile.ignore-lean-classes=true"] :global-vars ^:replace {clojure.core/*warn-on-reflection* true} :android {:lean-compile true :skummet-skip-vars ["#'neko.init/init" "#'neko.context/context" "#'neko.resource/package-name" "#'neko.-utils/keyword->static-field" "#'neko.-utils/keyword->setter" "#'neko.ui.traits/get-display-metrics" "#'test.leindroid.sample.main/MainActivity-onCreate" "#'test.leindroid.sample.main/MainActivity-init"]}}] } :android {;; Specify the path to the Android SDK directory. :sdk-path "/media/mikl/storage/projects/android/android-sdk-linux" ;:sdk-path "/home/mzheludkov/work/clojure/android-sdk-linux" ;; Try increasing this value if dexer fails with ;; OutOfMemoryException. Set the value according to your ;; available RAM. :dex-opts ["-JXmx4096M"] ;; If previous option didn't work, uncomment this as well. ;; :force-dex-optimize true :target-version "19" :aot-exclude-ns ["clojure.parallel" "clojure.core.reducers" "cljs-tooling.complete" "cljs-tooling.info" "cljs-tooling.util.analysis" "cljs-tooling.util.misc" "cider.nrepl" "cider-nrepl.plugin" "ru.vif.http-client"] } :aliases {"build" [["droid" "doall" "-e"]]} )
33798
(defproject vif-navigator/vif-navigator "0.0.1-SNAPSHOT" :description "Vif navigator" :url "http://example.com/FIXME" :global-vars {*warn-on-reflection* true} :resource-paths ["res"] :source-paths ["src/clojure" "src"] :java-source-paths ["src/java"] :javac-options ["-target" "1.6" "-source" "1.6" "-Xlint:-options"] :plugins [[lein-droid "0.3.5"]] :dependencies [[org.clojure-android/clojure "1.7.0-alpha6" :use-resources true] [neko/neko "3.2.0"] [org.jsoup/jsoup "1.8.2" :use-resources true] [vif-navigator-libs "0.1.0-SNAPSHOT" :use-resources true] ] :profiles {:default [:dev] :dev [:android-common :android-user {:dependencies [[org.clojure-android/tools.nrepl "0.2.6"]] :target-path "target/debug" :android {:aot :all-with-unused :manifest-options {:app-name "VifNavigator - debug"}}}] :release [:android-common {:target-path "target/release" :android {;; Specify the path to your private keystore ;; and the the alias of the key you want to ;; sign APKs with. :keystore-path "/home/mikl/.android/release-keysore" :key-alias "<KEY>" :ignore-log-priority [:debug :verbose] :aot :all-with-unused :build-type :release}}] :lean [:release {:dependencies ^:replace [[org.skummet/clojure-android "1.7.0-alpha5-r2" :use-resources true] [neko/neko "3.2.0"] [vif-navigator-libs "0.1.0-SNAPSHOT" :use-resources true] ] :exclusions [[org.clojure/clojure]] :jvm-opts ["-Dclojure.compile.ignore-lean-classes=true"] :global-vars ^:replace {clojure.core/*warn-on-reflection* true} :android {:lean-compile true :skummet-skip-vars ["#'neko.init/init" "#'neko.context/context" "#'neko.resource/package-name" "#'neko.-utils/keyword->static-field" "#'neko.-utils/keyword->setter" "#'neko.ui.traits/get-display-metrics" "#'test.leindroid.sample.main/MainActivity-onCreate" "#'test.leindroid.sample.main/MainActivity-init"]}}] } :android {;; Specify the path to the Android SDK directory. :sdk-path "/media/mikl/storage/projects/android/android-sdk-linux" ;:sdk-path "/home/mzheludkov/work/clojure/android-sdk-linux" ;; Try increasing this value if dexer fails with ;; OutOfMemoryException. Set the value according to your ;; available RAM. :dex-opts ["-JXmx4096M"] ;; If previous option didn't work, uncomment this as well. ;; :force-dex-optimize true :target-version "19" :aot-exclude-ns ["clojure.parallel" "clojure.core.reducers" "cljs-tooling.complete" "cljs-tooling.info" "cljs-tooling.util.analysis" "cljs-tooling.util.misc" "cider.nrepl" "cider-nrepl.plugin" "ru.vif.http-client"] } :aliases {"build" [["droid" "doall" "-e"]]} )
true
(defproject vif-navigator/vif-navigator "0.0.1-SNAPSHOT" :description "Vif navigator" :url "http://example.com/FIXME" :global-vars {*warn-on-reflection* true} :resource-paths ["res"] :source-paths ["src/clojure" "src"] :java-source-paths ["src/java"] :javac-options ["-target" "1.6" "-source" "1.6" "-Xlint:-options"] :plugins [[lein-droid "0.3.5"]] :dependencies [[org.clojure-android/clojure "1.7.0-alpha6" :use-resources true] [neko/neko "3.2.0"] [org.jsoup/jsoup "1.8.2" :use-resources true] [vif-navigator-libs "0.1.0-SNAPSHOT" :use-resources true] ] :profiles {:default [:dev] :dev [:android-common :android-user {:dependencies [[org.clojure-android/tools.nrepl "0.2.6"]] :target-path "target/debug" :android {:aot :all-with-unused :manifest-options {:app-name "VifNavigator - debug"}}}] :release [:android-common {:target-path "target/release" :android {;; Specify the path to your private keystore ;; and the the alias of the key you want to ;; sign APKs with. :keystore-path "/home/mikl/.android/release-keysore" :key-alias "PI:KEY:<KEY>END_PI" :ignore-log-priority [:debug :verbose] :aot :all-with-unused :build-type :release}}] :lean [:release {:dependencies ^:replace [[org.skummet/clojure-android "1.7.0-alpha5-r2" :use-resources true] [neko/neko "3.2.0"] [vif-navigator-libs "0.1.0-SNAPSHOT" :use-resources true] ] :exclusions [[org.clojure/clojure]] :jvm-opts ["-Dclojure.compile.ignore-lean-classes=true"] :global-vars ^:replace {clojure.core/*warn-on-reflection* true} :android {:lean-compile true :skummet-skip-vars ["#'neko.init/init" "#'neko.context/context" "#'neko.resource/package-name" "#'neko.-utils/keyword->static-field" "#'neko.-utils/keyword->setter" "#'neko.ui.traits/get-display-metrics" "#'test.leindroid.sample.main/MainActivity-onCreate" "#'test.leindroid.sample.main/MainActivity-init"]}}] } :android {;; Specify the path to the Android SDK directory. :sdk-path "/media/mikl/storage/projects/android/android-sdk-linux" ;:sdk-path "/home/mzheludkov/work/clojure/android-sdk-linux" ;; Try increasing this value if dexer fails with ;; OutOfMemoryException. Set the value according to your ;; available RAM. :dex-opts ["-JXmx4096M"] ;; If previous option didn't work, uncomment this as well. ;; :force-dex-optimize true :target-version "19" :aot-exclude-ns ["clojure.parallel" "clojure.core.reducers" "cljs-tooling.complete" "cljs-tooling.info" "cljs-tooling.util.analysis" "cljs-tooling.util.misc" "cider.nrepl" "cider-nrepl.plugin" "ru.vif.http-client"] } :aliases {"build" [["droid" "doall" "-e"]]} )
[ { "context": "\n (nbc/input {:key (str qualified-key)\n :placeholder (str\n ", "end": 1551, "score": 0.5377863049507141, "start": 1551, "tag": "KEY", "value": "" } ]
src/main/com/fulcrologic/rad/rendering/nativebase/field.cljc
fulcrologic/fulcro-rad-nativebase-ui
0
(ns com.fulcrologic.rad.rendering.nativebase.field (:require [clojure.string :as str] [com.fulcrologic.rad.rendering.nativebase.raw-controls :as nbc] [com.fulcrologic.fulcro.components :as comp] [com.fulcrologic.rad.attributes :as attr] [com.fulcrologic.rad.form :as form] [com.fulcrologic.rad.ui-validation :as validation] [taoensso.timbre :as log])) (defn render-field-factory "Create a general field factory using the given input factory as the function to call to draw an input." ([input-factory] (render-field-factory {} input-factory)) ([addl-props input-factory] (fn [{::form/keys [form-instance] :as env} {::attr/keys [type qualified-key] :as attribute}] (let [props (comp/props form-instance) value (or (form/computed-value env attribute) (and attribute (get props qualified-key))) invalid? (validation/invalid-attribute-value? env attribute) validation-message (when invalid? (validation/validation-error-message env attribute)) user-props (form/field-style-config env attribute :input/props) field-label (form/field-label env attribute) visible? (form/field-visible? form-instance attribute) read-only? (form/read-only? form-instance attribute) addl-props (if read-only? (assoc addl-props :readOnly "readonly") addl-props)] (when visible? (nbc/input {:key (str qualified-key) :placeholder (str (or field-label (some-> qualified-key name str/capitalize)) ;; TASK: validation display (when validation-message (str " (" validation-message ")"))) :value value :enabled (not read-only?) :onEndEditing (fn [] (form/input-blur! env qualified-key value)) :onChangeText (fn [v] (form/input-changed! env qualified-key v))}))))))
114180
(ns com.fulcrologic.rad.rendering.nativebase.field (:require [clojure.string :as str] [com.fulcrologic.rad.rendering.nativebase.raw-controls :as nbc] [com.fulcrologic.fulcro.components :as comp] [com.fulcrologic.rad.attributes :as attr] [com.fulcrologic.rad.form :as form] [com.fulcrologic.rad.ui-validation :as validation] [taoensso.timbre :as log])) (defn render-field-factory "Create a general field factory using the given input factory as the function to call to draw an input." ([input-factory] (render-field-factory {} input-factory)) ([addl-props input-factory] (fn [{::form/keys [form-instance] :as env} {::attr/keys [type qualified-key] :as attribute}] (let [props (comp/props form-instance) value (or (form/computed-value env attribute) (and attribute (get props qualified-key))) invalid? (validation/invalid-attribute-value? env attribute) validation-message (when invalid? (validation/validation-error-message env attribute)) user-props (form/field-style-config env attribute :input/props) field-label (form/field-label env attribute) visible? (form/field-visible? form-instance attribute) read-only? (form/read-only? form-instance attribute) addl-props (if read-only? (assoc addl-props :readOnly "readonly") addl-props)] (when visible? (nbc/input {:key (str qualified<KEY>-key) :placeholder (str (or field-label (some-> qualified-key name str/capitalize)) ;; TASK: validation display (when validation-message (str " (" validation-message ")"))) :value value :enabled (not read-only?) :onEndEditing (fn [] (form/input-blur! env qualified-key value)) :onChangeText (fn [v] (form/input-changed! env qualified-key v))}))))))
true
(ns com.fulcrologic.rad.rendering.nativebase.field (:require [clojure.string :as str] [com.fulcrologic.rad.rendering.nativebase.raw-controls :as nbc] [com.fulcrologic.fulcro.components :as comp] [com.fulcrologic.rad.attributes :as attr] [com.fulcrologic.rad.form :as form] [com.fulcrologic.rad.ui-validation :as validation] [taoensso.timbre :as log])) (defn render-field-factory "Create a general field factory using the given input factory as the function to call to draw an input." ([input-factory] (render-field-factory {} input-factory)) ([addl-props input-factory] (fn [{::form/keys [form-instance] :as env} {::attr/keys [type qualified-key] :as attribute}] (let [props (comp/props form-instance) value (or (form/computed-value env attribute) (and attribute (get props qualified-key))) invalid? (validation/invalid-attribute-value? env attribute) validation-message (when invalid? (validation/validation-error-message env attribute)) user-props (form/field-style-config env attribute :input/props) field-label (form/field-label env attribute) visible? (form/field-visible? form-instance attribute) read-only? (form/read-only? form-instance attribute) addl-props (if read-only? (assoc addl-props :readOnly "readonly") addl-props)] (when visible? (nbc/input {:key (str qualifiedPI:KEY:<KEY>END_PI-key) :placeholder (str (or field-label (some-> qualified-key name str/capitalize)) ;; TASK: validation display (when validation-message (str " (" validation-message ")"))) :value value :enabled (not read-only?) :onEndEditing (fn [] (form/input-blur! env qualified-key value)) :onChangeText (fn [v] (form/input-changed! env qualified-key v))}))))))
[ { "context": " ;;\n;; Author: Jon Anthony ", "end": 1839, "score": 0.9998424053192139, "start": 1828, "tag": "NAME", "value": "Jon Anthony" } ]
src/aerobio/htseq/rnaseq.clj
jsa-aerial/aerobio
3
;;--------------------------------------------------------------------------;; ;; ;; ;; A E R O B I O . H T S E Q . R N A S E Q ;; ;; ;; ;; Permission is hereby granted, free of charge, to any person obtaining ;; ;; a copy of this software and associated documentation files (the ;; ;; "Software"), to deal in the Software without restriction, including ;; ;; without limitation the rights to use, copy, modify, merge, publish, ;; ;; distribute, sublicense, and/or sell copies of the Software, and to ;; ;; permit persons to whom the Software is furnished to do so, subject to ;; ;; the following conditions: ;; ;; ;; ;; The above copyright notice and this permission notice shall be ;; ;; included in all copies or substantial portions of the Software. ;; ;; ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ;; ;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ;; ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ;; ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;; ;; ;; ;; Author: Jon Anthony ;; ;; ;; ;;--------------------------------------------------------------------------;; ;; (ns aerobio.htseq.rnaseq [:require [clojure.core.reducers :as r] [clojure.data.csv :as csv] [clojure.string :as cljstr] [aerial.fs :as fs] [aerial.utils.coll :refer [vfold] :as coll] [aerial.utils.string :as str] [aerial.utils.io :refer [letio] :as io] [aerial.utils.math.probs-stats :as p] [aerial.utils.math.infoth :as it] [aerial.bio.utils.filters :as fil] [aerobio.params :as pams] [aerobio.htseq.common :as cmn] [aerobio.pgmgraph :as pg]] ) ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX" ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX/Docs/SampleSheet.csv" ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX/Docs/Exp-AntibioticsRTS_KZ_SD_index.csv" (defn get-comparison-files- "Compute the set of comparison bams and the corresponding output csv for the count table matrix. Comparison sets are based on the ComparisonSheet.csv for the experiment of eid (the experiment id). If rep? is true, returns the comparison sets for replicates of comparison pairs, else returns comparison sets for combined bams." ([eid rep?] (get-comparison-files- eid "ComparisonSheet.csv" rep?)) ([eid comp-filename rep?] (let [bpath (if rep? [:rep :bams] [:bams]) fpath (if rep? [:rep :fcnts] [:fcnts]) bams (apply cmn/get-exp-info eid bpath) fcnts (apply cmn/get-exp-info eid fpath) bam-regex (if rep? "-*.bam" "*.bam") compvec (->> comp-filename (fs/join (pams/get-params :nextseq-base) eid) slurp csv/read-csv rest) bamsvec (mapv (fn[v] (mapcat #(-> (fs/join bams (str % bam-regex)) fs/glob sort) v)) compvec) otcsvs (mapv (fn[v] (fs/join fcnts (str (cljstr/join "-" v) ".csv"))) compvec)] (mapv #(vector %1 %2) bamsvec otcsvs)))) (defmethod cmn/get-comparison-files :rnaseq [_ & args] (apply get-comparison-files- args)) (defn ensure-exp-set [eid] (when (not (cmn/get-exp eid)) (cmn/set-exp eid))) (defn get-xcomparison-files- "Compute the set of Cross Experiment comparison bams and the corresponding output csv for the count table matrix. Cross comparison sets are based on the CrossComparisonSheet.csv for the pseudo experiment of eid (the pseudo experiment id). If rep? is true, returns the comparison sets for replicates of comparison pairs, else returns comparison sets for combined bams." ([eid rep?] (get-xcomparison-files- eid "ComparisonSheet.csv" rep?)) ([eid comp-filename rep?] (let [bpath (if rep? [:rep :bams] [:bams]) fpath (if rep? [:rep :fcnts] [:fcnts]) fcnts (apply cmn/get-exp-info eid fpath) compvec (->> comp-filename (fs/join (pams/get-params :nextseq-base) eid) slurp csv/read-csv rest (map (fn[[c1 c2]] (let [[eid1 strain cond1] (str/split #"-" c1) _ (ensure-exp-set eid1) gb1 (str strain "-" cond1 "*.bam") c1bams (apply cmn/get-exp-info eid1 bpath) [eid2 strain cond2] (str/split #"-" c2) _ (ensure-exp-set eid2) gb2 (str strain "-" cond2 "*.bam") c2bams (apply cmn/get-exp-info eid2 bpath)] [(fs/join c1bams gb1) (fs/join c2bams gb2)])))) bamsvec (mapv (fn[v] (mapcat #(-> % fs/glob sort) v)) compvec) otcsvs (mapv (fn[v] (fs/join fcnts (str (cljstr/join "-" (mapv #(->> % fs/basename (str/split #"\*") first) v)) ".csv"))) compvec)] (mapv #(vector %1 %2) bamsvec otcsvs)))) (defmethod cmn/get-xcomparison-files :rnaseq [_ & args] (apply get-xcomparison-files- args)) (defn split-filter-fastqs [eid] (cmn/split-filter-fastqs eid identity)) (defn run-rnaseq-phase-0 [eid recipient get-toolinfo template] (let [rnas0 template cfg (-> (assoc-in rnas0 [:nodes :ph0 :args] [eid recipient]) (pg/config-pgm-graph-nodes get-toolinfo nil nil) pg/config-pgm-graph) ;;_ (clojure.pprint/pprint cfg) futs-vec (->> cfg pg/make-flow-graph pg/run-flow-program)] (mapv (fn[fut] (deref fut)) futs-vec))) ;;; Get primary phase 1 arguments. These are the bowtie index, the ;;; fastq set, output bam and bai file names (defmethod cmn/get-phase-1-args :rnaseq [_ eid repname & {:keys [repk star paired]}] (let [{:keys [R1 R2]} (cmn/get-paired-fqs eid repname repk) refnm (cmn/replicate-name->strain-name eid repname) btindex (fs/join (cmn/get-exp-info eid :index) refnm) starindex (when star (fs/join (cmn/get-exp-info eid :starindex) refnm)) starprefix (when star (fs/join (cmn/get-exp-info eid repk :star) repname)) otbam (fs/join (cmn/get-exp-info eid repk :bams) (str repname ".bam")) otbai (str otbam ".bai") refgtf (fs/join (cmn/get-exp-info eid :refs) (str refnm ".gtf"))] (apply cmn/ensure-dirs (map fs/dirname [otbam otbai])) (when star (cmn/ensure-dirs (fs/dirname starprefix))) (if star (if (and paired R2) [starindex R1 R2 otbam otbai starprefix] [starindex R1 otbam otbai starprefix]) (if (and paired R2) [btindex R1 R2 otbam otbai] [btindex R1 otbam otbai])))) (defn get-phase-2-dirs [eid repk] (let [fcnts (fs/join (cmn/get-exp-info eid repk :fcnts)) charts (fs/join (cmn/get-exp-info eid repk :charts)) ;;charts (fs/join charts nm) ] (cmn/ensure-dirs charts fcnts) [fcnts charts])) (defn run-rnaseq-comparison "Run a condition/replicate set of comparisons based on an experiment designated by eid (experiement id) and the input comparison sheet CSV comparison-sheet" [eid recipient comparison-file get-toolinfo template status-atom] (let [_ (get-phase-2-dirs eid nil) _ (get-phase-2-dirs eid :rep) ftype "CDS" ; <-- BAD 'magic number' cfg (assoc-in template [:nodes :ph2 :args] [eid comparison-file true ftype :NA recipient]) futs-vec (cmn/flow-program cfg get-toolinfo :run true)] (cmn/job-flow-node-results futs-vec status-atom) (@status-atom :done))) #_(defmethod cmn/run-xcomparison :rnaseq [_ eid recipient compfile get-toolinfo template] (run-rnaseq-comparison eid recipient compfile get-toolinfo template)) (defmethod cmn/run-comparison :rnaseq [_ eid recipient compfile get-toolinfo template status-atom] (run-rnaseq-comparison eid recipient compfile get-toolinfo template status-atom)) (defmethod cmn/run-phase-2 :rnaseq [_ eid recipient get-toolinfo template status-atom] (run-rnaseq-comparison eid recipient "ComparisonSheet.csv" get-toolinfo template status-atom))
47215
;;--------------------------------------------------------------------------;; ;; ;; ;; A E R O B I O . H T S E Q . R N A S E Q ;; ;; ;; ;; Permission is hereby granted, free of charge, to any person obtaining ;; ;; a copy of this software and associated documentation files (the ;; ;; "Software"), to deal in the Software without restriction, including ;; ;; without limitation the rights to use, copy, modify, merge, publish, ;; ;; distribute, sublicense, and/or sell copies of the Software, and to ;; ;; permit persons to whom the Software is furnished to do so, subject to ;; ;; the following conditions: ;; ;; ;; ;; The above copyright notice and this permission notice shall be ;; ;; included in all copies or substantial portions of the Software. ;; ;; ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ;; ;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ;; ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ;; ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;; ;; ;; ;; Author: <NAME> ;; ;; ;; ;;--------------------------------------------------------------------------;; ;; (ns aerobio.htseq.rnaseq [:require [clojure.core.reducers :as r] [clojure.data.csv :as csv] [clojure.string :as cljstr] [aerial.fs :as fs] [aerial.utils.coll :refer [vfold] :as coll] [aerial.utils.string :as str] [aerial.utils.io :refer [letio] :as io] [aerial.utils.math.probs-stats :as p] [aerial.utils.math.infoth :as it] [aerial.bio.utils.filters :as fil] [aerobio.params :as pams] [aerobio.htseq.common :as cmn] [aerobio.pgmgraph :as pg]] ) ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX" ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX/Docs/SampleSheet.csv" ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX/Docs/Exp-AntibioticsRTS_KZ_SD_index.csv" (defn get-comparison-files- "Compute the set of comparison bams and the corresponding output csv for the count table matrix. Comparison sets are based on the ComparisonSheet.csv for the experiment of eid (the experiment id). If rep? is true, returns the comparison sets for replicates of comparison pairs, else returns comparison sets for combined bams." ([eid rep?] (get-comparison-files- eid "ComparisonSheet.csv" rep?)) ([eid comp-filename rep?] (let [bpath (if rep? [:rep :bams] [:bams]) fpath (if rep? [:rep :fcnts] [:fcnts]) bams (apply cmn/get-exp-info eid bpath) fcnts (apply cmn/get-exp-info eid fpath) bam-regex (if rep? "-*.bam" "*.bam") compvec (->> comp-filename (fs/join (pams/get-params :nextseq-base) eid) slurp csv/read-csv rest) bamsvec (mapv (fn[v] (mapcat #(-> (fs/join bams (str % bam-regex)) fs/glob sort) v)) compvec) otcsvs (mapv (fn[v] (fs/join fcnts (str (cljstr/join "-" v) ".csv"))) compvec)] (mapv #(vector %1 %2) bamsvec otcsvs)))) (defmethod cmn/get-comparison-files :rnaseq [_ & args] (apply get-comparison-files- args)) (defn ensure-exp-set [eid] (when (not (cmn/get-exp eid)) (cmn/set-exp eid))) (defn get-xcomparison-files- "Compute the set of Cross Experiment comparison bams and the corresponding output csv for the count table matrix. Cross comparison sets are based on the CrossComparisonSheet.csv for the pseudo experiment of eid (the pseudo experiment id). If rep? is true, returns the comparison sets for replicates of comparison pairs, else returns comparison sets for combined bams." ([eid rep?] (get-xcomparison-files- eid "ComparisonSheet.csv" rep?)) ([eid comp-filename rep?] (let [bpath (if rep? [:rep :bams] [:bams]) fpath (if rep? [:rep :fcnts] [:fcnts]) fcnts (apply cmn/get-exp-info eid fpath) compvec (->> comp-filename (fs/join (pams/get-params :nextseq-base) eid) slurp csv/read-csv rest (map (fn[[c1 c2]] (let [[eid1 strain cond1] (str/split #"-" c1) _ (ensure-exp-set eid1) gb1 (str strain "-" cond1 "*.bam") c1bams (apply cmn/get-exp-info eid1 bpath) [eid2 strain cond2] (str/split #"-" c2) _ (ensure-exp-set eid2) gb2 (str strain "-" cond2 "*.bam") c2bams (apply cmn/get-exp-info eid2 bpath)] [(fs/join c1bams gb1) (fs/join c2bams gb2)])))) bamsvec (mapv (fn[v] (mapcat #(-> % fs/glob sort) v)) compvec) otcsvs (mapv (fn[v] (fs/join fcnts (str (cljstr/join "-" (mapv #(->> % fs/basename (str/split #"\*") first) v)) ".csv"))) compvec)] (mapv #(vector %1 %2) bamsvec otcsvs)))) (defmethod cmn/get-xcomparison-files :rnaseq [_ & args] (apply get-xcomparison-files- args)) (defn split-filter-fastqs [eid] (cmn/split-filter-fastqs eid identity)) (defn run-rnaseq-phase-0 [eid recipient get-toolinfo template] (let [rnas0 template cfg (-> (assoc-in rnas0 [:nodes :ph0 :args] [eid recipient]) (pg/config-pgm-graph-nodes get-toolinfo nil nil) pg/config-pgm-graph) ;;_ (clojure.pprint/pprint cfg) futs-vec (->> cfg pg/make-flow-graph pg/run-flow-program)] (mapv (fn[fut] (deref fut)) futs-vec))) ;;; Get primary phase 1 arguments. These are the bowtie index, the ;;; fastq set, output bam and bai file names (defmethod cmn/get-phase-1-args :rnaseq [_ eid repname & {:keys [repk star paired]}] (let [{:keys [R1 R2]} (cmn/get-paired-fqs eid repname repk) refnm (cmn/replicate-name->strain-name eid repname) btindex (fs/join (cmn/get-exp-info eid :index) refnm) starindex (when star (fs/join (cmn/get-exp-info eid :starindex) refnm)) starprefix (when star (fs/join (cmn/get-exp-info eid repk :star) repname)) otbam (fs/join (cmn/get-exp-info eid repk :bams) (str repname ".bam")) otbai (str otbam ".bai") refgtf (fs/join (cmn/get-exp-info eid :refs) (str refnm ".gtf"))] (apply cmn/ensure-dirs (map fs/dirname [otbam otbai])) (when star (cmn/ensure-dirs (fs/dirname starprefix))) (if star (if (and paired R2) [starindex R1 R2 otbam otbai starprefix] [starindex R1 otbam otbai starprefix]) (if (and paired R2) [btindex R1 R2 otbam otbai] [btindex R1 otbam otbai])))) (defn get-phase-2-dirs [eid repk] (let [fcnts (fs/join (cmn/get-exp-info eid repk :fcnts)) charts (fs/join (cmn/get-exp-info eid repk :charts)) ;;charts (fs/join charts nm) ] (cmn/ensure-dirs charts fcnts) [fcnts charts])) (defn run-rnaseq-comparison "Run a condition/replicate set of comparisons based on an experiment designated by eid (experiement id) and the input comparison sheet CSV comparison-sheet" [eid recipient comparison-file get-toolinfo template status-atom] (let [_ (get-phase-2-dirs eid nil) _ (get-phase-2-dirs eid :rep) ftype "CDS" ; <-- BAD 'magic number' cfg (assoc-in template [:nodes :ph2 :args] [eid comparison-file true ftype :NA recipient]) futs-vec (cmn/flow-program cfg get-toolinfo :run true)] (cmn/job-flow-node-results futs-vec status-atom) (@status-atom :done))) #_(defmethod cmn/run-xcomparison :rnaseq [_ eid recipient compfile get-toolinfo template] (run-rnaseq-comparison eid recipient compfile get-toolinfo template)) (defmethod cmn/run-comparison :rnaseq [_ eid recipient compfile get-toolinfo template status-atom] (run-rnaseq-comparison eid recipient compfile get-toolinfo template status-atom)) (defmethod cmn/run-phase-2 :rnaseq [_ eid recipient get-toolinfo template status-atom] (run-rnaseq-comparison eid recipient "ComparisonSheet.csv" get-toolinfo template status-atom))
true
;;--------------------------------------------------------------------------;; ;; ;; ;; A E R O B I O . H T S E Q . R N A S E Q ;; ;; ;; ;; Permission is hereby granted, free of charge, to any person obtaining ;; ;; a copy of this software and associated documentation files (the ;; ;; "Software"), to deal in the Software without restriction, including ;; ;; without limitation the rights to use, copy, modify, merge, publish, ;; ;; distribute, sublicense, and/or sell copies of the Software, and to ;; ;; permit persons to whom the Software is furnished to do so, subject to ;; ;; the following conditions: ;; ;; ;; ;; The above copyright notice and this permission notice shall be ;; ;; included in all copies or substantial portions of the Software. ;; ;; ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ;; ;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ;; ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ;; ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;; ;; ;; ;; Author: PI:NAME:<NAME>END_PI ;; ;; ;; ;;--------------------------------------------------------------------------;; ;; (ns aerobio.htseq.rnaseq [:require [clojure.core.reducers :as r] [clojure.data.csv :as csv] [clojure.string :as cljstr] [aerial.fs :as fs] [aerial.utils.coll :refer [vfold] :as coll] [aerial.utils.string :as str] [aerial.utils.io :refer [letio] :as io] [aerial.utils.math.probs-stats :as p] [aerial.utils.math.infoth :as it] [aerial.bio.utils.filters :as fil] [aerobio.params :as pams] [aerobio.htseq.common :as cmn] [aerobio.pgmgraph :as pg]] ) ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX" ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX/Docs/SampleSheet.csv" ;;; "/data1/NextSeq/TVOLab/AHL7L3BGXX/Docs/Exp-AntibioticsRTS_KZ_SD_index.csv" (defn get-comparison-files- "Compute the set of comparison bams and the corresponding output csv for the count table matrix. Comparison sets are based on the ComparisonSheet.csv for the experiment of eid (the experiment id). If rep? is true, returns the comparison sets for replicates of comparison pairs, else returns comparison sets for combined bams." ([eid rep?] (get-comparison-files- eid "ComparisonSheet.csv" rep?)) ([eid comp-filename rep?] (let [bpath (if rep? [:rep :bams] [:bams]) fpath (if rep? [:rep :fcnts] [:fcnts]) bams (apply cmn/get-exp-info eid bpath) fcnts (apply cmn/get-exp-info eid fpath) bam-regex (if rep? "-*.bam" "*.bam") compvec (->> comp-filename (fs/join (pams/get-params :nextseq-base) eid) slurp csv/read-csv rest) bamsvec (mapv (fn[v] (mapcat #(-> (fs/join bams (str % bam-regex)) fs/glob sort) v)) compvec) otcsvs (mapv (fn[v] (fs/join fcnts (str (cljstr/join "-" v) ".csv"))) compvec)] (mapv #(vector %1 %2) bamsvec otcsvs)))) (defmethod cmn/get-comparison-files :rnaseq [_ & args] (apply get-comparison-files- args)) (defn ensure-exp-set [eid] (when (not (cmn/get-exp eid)) (cmn/set-exp eid))) (defn get-xcomparison-files- "Compute the set of Cross Experiment comparison bams and the corresponding output csv for the count table matrix. Cross comparison sets are based on the CrossComparisonSheet.csv for the pseudo experiment of eid (the pseudo experiment id). If rep? is true, returns the comparison sets for replicates of comparison pairs, else returns comparison sets for combined bams." ([eid rep?] (get-xcomparison-files- eid "ComparisonSheet.csv" rep?)) ([eid comp-filename rep?] (let [bpath (if rep? [:rep :bams] [:bams]) fpath (if rep? [:rep :fcnts] [:fcnts]) fcnts (apply cmn/get-exp-info eid fpath) compvec (->> comp-filename (fs/join (pams/get-params :nextseq-base) eid) slurp csv/read-csv rest (map (fn[[c1 c2]] (let [[eid1 strain cond1] (str/split #"-" c1) _ (ensure-exp-set eid1) gb1 (str strain "-" cond1 "*.bam") c1bams (apply cmn/get-exp-info eid1 bpath) [eid2 strain cond2] (str/split #"-" c2) _ (ensure-exp-set eid2) gb2 (str strain "-" cond2 "*.bam") c2bams (apply cmn/get-exp-info eid2 bpath)] [(fs/join c1bams gb1) (fs/join c2bams gb2)])))) bamsvec (mapv (fn[v] (mapcat #(-> % fs/glob sort) v)) compvec) otcsvs (mapv (fn[v] (fs/join fcnts (str (cljstr/join "-" (mapv #(->> % fs/basename (str/split #"\*") first) v)) ".csv"))) compvec)] (mapv #(vector %1 %2) bamsvec otcsvs)))) (defmethod cmn/get-xcomparison-files :rnaseq [_ & args] (apply get-xcomparison-files- args)) (defn split-filter-fastqs [eid] (cmn/split-filter-fastqs eid identity)) (defn run-rnaseq-phase-0 [eid recipient get-toolinfo template] (let [rnas0 template cfg (-> (assoc-in rnas0 [:nodes :ph0 :args] [eid recipient]) (pg/config-pgm-graph-nodes get-toolinfo nil nil) pg/config-pgm-graph) ;;_ (clojure.pprint/pprint cfg) futs-vec (->> cfg pg/make-flow-graph pg/run-flow-program)] (mapv (fn[fut] (deref fut)) futs-vec))) ;;; Get primary phase 1 arguments. These are the bowtie index, the ;;; fastq set, output bam and bai file names (defmethod cmn/get-phase-1-args :rnaseq [_ eid repname & {:keys [repk star paired]}] (let [{:keys [R1 R2]} (cmn/get-paired-fqs eid repname repk) refnm (cmn/replicate-name->strain-name eid repname) btindex (fs/join (cmn/get-exp-info eid :index) refnm) starindex (when star (fs/join (cmn/get-exp-info eid :starindex) refnm)) starprefix (when star (fs/join (cmn/get-exp-info eid repk :star) repname)) otbam (fs/join (cmn/get-exp-info eid repk :bams) (str repname ".bam")) otbai (str otbam ".bai") refgtf (fs/join (cmn/get-exp-info eid :refs) (str refnm ".gtf"))] (apply cmn/ensure-dirs (map fs/dirname [otbam otbai])) (when star (cmn/ensure-dirs (fs/dirname starprefix))) (if star (if (and paired R2) [starindex R1 R2 otbam otbai starprefix] [starindex R1 otbam otbai starprefix]) (if (and paired R2) [btindex R1 R2 otbam otbai] [btindex R1 otbam otbai])))) (defn get-phase-2-dirs [eid repk] (let [fcnts (fs/join (cmn/get-exp-info eid repk :fcnts)) charts (fs/join (cmn/get-exp-info eid repk :charts)) ;;charts (fs/join charts nm) ] (cmn/ensure-dirs charts fcnts) [fcnts charts])) (defn run-rnaseq-comparison "Run a condition/replicate set of comparisons based on an experiment designated by eid (experiement id) and the input comparison sheet CSV comparison-sheet" [eid recipient comparison-file get-toolinfo template status-atom] (let [_ (get-phase-2-dirs eid nil) _ (get-phase-2-dirs eid :rep) ftype "CDS" ; <-- BAD 'magic number' cfg (assoc-in template [:nodes :ph2 :args] [eid comparison-file true ftype :NA recipient]) futs-vec (cmn/flow-program cfg get-toolinfo :run true)] (cmn/job-flow-node-results futs-vec status-atom) (@status-atom :done))) #_(defmethod cmn/run-xcomparison :rnaseq [_ eid recipient compfile get-toolinfo template] (run-rnaseq-comparison eid recipient compfile get-toolinfo template)) (defmethod cmn/run-comparison :rnaseq [_ eid recipient compfile get-toolinfo template status-atom] (run-rnaseq-comparison eid recipient compfile get-toolinfo template status-atom)) (defmethod cmn/run-phase-2 :rnaseq [_ eid recipient get-toolinfo template status-atom] (run-rnaseq-comparison eid recipient "ComparisonSheet.csv" get-toolinfo template status-atom))
[ { "context": "]],\n :current-person/by-id {:person/first-name \"Guy\"\n :person/last-name \"Ru", "end": 294, "score": 0.999470055103302, "start": 291, "tag": "NAME", "value": "Guy" }, { "context": "uy\"\n :person/last-name \"Rundle\"}\n :code-type/by-id\n {1", "end": 348, "score": 0.999679446220398, "start": 342, "tag": "NAME", "value": "Rundle" } ]
test/examples/medical_records.cljc
chrismurrph/default-db-format
7
(ns examples.medical-records) (def irrelevant-keys #{:app/route :om.next/tables}) (comment :acceptable-table-value-fn? (fn [v] (= keyword? v))) (def norm-state {:code/list [[:code/by-id 17592186045430]], :current-person/by-id {:person/first-name "Guy" :person/last-name "Rundle"} :code-type/by-id {17592186045423 {:db/id 17592186045423, :code/name :codes/allergy, :code/type "allergy" :code/owner [:current-person/by-id '_]}, 17592186045424 {:db/id 17592186045424, :code/name :codes/diagnosis, :code/type "diagnosis"}, 17592186045421 {:db/id 17592186045421, :code/name :codes/history, :code/type "history"}, 17592186045422 {:db/id 17592186045422, :code/name :codes/medicine, :code/type "medicine"}, 17592186045425 {:db/id 17592186045425, :code/name :codes/locale, :code/type "locale"}}, :app/route [:new-clinic '_], :om.next/tables #{:code-type/by-id}, :app/args nil, :code-type/list [[:code-type/by-id 17592186045423] [:code-type/by-id 17592186045424] [:code-type/by-id 17592186045421] [:code-type/by-id 17592186045422] [:code-type/by-id 17592186045425]], :code/by-id {17592186045430 {:db/id 17592186045430, :entity/deleted? false, :code/name "Taha", :code/type [:code-type/by-id 17592186045423]}}, :clinic/by-id {Double/NaN {:db/id nil}}})
36669
(ns examples.medical-records) (def irrelevant-keys #{:app/route :om.next/tables}) (comment :acceptable-table-value-fn? (fn [v] (= keyword? v))) (def norm-state {:code/list [[:code/by-id 17592186045430]], :current-person/by-id {:person/first-name "<NAME>" :person/last-name "<NAME>"} :code-type/by-id {17592186045423 {:db/id 17592186045423, :code/name :codes/allergy, :code/type "allergy" :code/owner [:current-person/by-id '_]}, 17592186045424 {:db/id 17592186045424, :code/name :codes/diagnosis, :code/type "diagnosis"}, 17592186045421 {:db/id 17592186045421, :code/name :codes/history, :code/type "history"}, 17592186045422 {:db/id 17592186045422, :code/name :codes/medicine, :code/type "medicine"}, 17592186045425 {:db/id 17592186045425, :code/name :codes/locale, :code/type "locale"}}, :app/route [:new-clinic '_], :om.next/tables #{:code-type/by-id}, :app/args nil, :code-type/list [[:code-type/by-id 17592186045423] [:code-type/by-id 17592186045424] [:code-type/by-id 17592186045421] [:code-type/by-id 17592186045422] [:code-type/by-id 17592186045425]], :code/by-id {17592186045430 {:db/id 17592186045430, :entity/deleted? false, :code/name "Taha", :code/type [:code-type/by-id 17592186045423]}}, :clinic/by-id {Double/NaN {:db/id nil}}})
true
(ns examples.medical-records) (def irrelevant-keys #{:app/route :om.next/tables}) (comment :acceptable-table-value-fn? (fn [v] (= keyword? v))) (def norm-state {:code/list [[:code/by-id 17592186045430]], :current-person/by-id {:person/first-name "PI:NAME:<NAME>END_PI" :person/last-name "PI:NAME:<NAME>END_PI"} :code-type/by-id {17592186045423 {:db/id 17592186045423, :code/name :codes/allergy, :code/type "allergy" :code/owner [:current-person/by-id '_]}, 17592186045424 {:db/id 17592186045424, :code/name :codes/diagnosis, :code/type "diagnosis"}, 17592186045421 {:db/id 17592186045421, :code/name :codes/history, :code/type "history"}, 17592186045422 {:db/id 17592186045422, :code/name :codes/medicine, :code/type "medicine"}, 17592186045425 {:db/id 17592186045425, :code/name :codes/locale, :code/type "locale"}}, :app/route [:new-clinic '_], :om.next/tables #{:code-type/by-id}, :app/args nil, :code-type/list [[:code-type/by-id 17592186045423] [:code-type/by-id 17592186045424] [:code-type/by-id 17592186045421] [:code-type/by-id 17592186045422] [:code-type/by-id 17592186045425]], :code/by-id {17592186045430 {:db/id 17592186045430, :entity/deleted? false, :code/name "Taha", :code/type [:code-type/by-id 17592186045423]}}, :clinic/by-id {Double/NaN {:db/id nil}}})
[ { "context": ";;\n;; Copyright Christophe Roeder, August 2014\n\n;; This namespace contains function", "end": 33, "score": 0.9998742938041687, "start": 16, "tag": "NAME", "value": "Christophe Roeder" } ]
src/clojure_craft/analyze-terms.clj
croeder/clojure_craft
0
;; ;; Copyright Christophe Roeder, August 2014 ;; This namespace contains functions analyzing or counting ;; the terms, their POS, depdency types and frequency without ;; regard to the dependency patterns. (ns clojure-craft.analyze-terms) (use 'clojure.java.io) (use '[clojure.string :only (join split)]) (use '[clojure-craft.craft-pos]) (use '[clojure-craft.craft-xml]) (use '[clojure-craft.craft-dep]) (use '[clojure-craft.craft-unify]) (defn run-unify-pos-dep [id] (let [txtfile (str txt-base "/" id ".txt") posfile (str pos-base "/" id ".txt.xml") depfile (str dep-base "/" id ".dep")] (unify-pos-dep txtfile posfile depfile))) (defn- annotated-sentence? [sentence] (reduce (fn [collector token] (or collector (:anno-list token))) false (:tokens sentence))) (defn- create-triples-from-sentence "take a list of Token records and build a SOS of pos, dep and ontology is" [sentence] (reduce (fn [collector token] (cond (:anno-list token) (conj collector (list (:pos (:dependency token)) (:dep-type (:dependency token)) (:anno-list token))) :t collector)) [] (:tokens sentence))) (defn- get-type-pos-dep "for the given document id, for each ontology, build a sequence of Sentence records containing sequenes of Token records (data), then cull Records down to triples" [sample-id] (let [base (run-unify-pos-dep sample-id) ;; reduce here? TODO data (loop [ontology (first data-dirs) remaining-ontologies (rest data-dirs) sentences base] (cond (not (empty? remaining-ontologies)) (recur (first remaining-ontologies) (rest remaining-ontologies) (run-unify-annotations sentences sample-id ontology)) :t sentences)) ] (map (fn [sentence] (cond (annotated-sentence? sentence) ;; TODO, run without this (create-triples-from-sentence sentence) :t nil)) data)) ) ;;;;;;;;;;;;;;;;;;;;;;;;; (defn create-ontology-pos-dep-triples "distributes triple creation over a list of files" [sample-id] (reduce (fn [collector item] (cond (> (count item) 0) ;;; small to-do: can this be eliminated with nil punning? (reduce conj collector item) :t collector)) [] (get-type-pos-dep sample-id) )) (def id-list [ 11532192 15207008 15876356 16362077 17022820 11597317 15314655 15917436 16433929 17069463 11897010 15921521 16462940 17078885 12079497 15320950 15938754 16504143 17083276 12546709 15328533 16098226 16504174 12585968 15345036 16103912 16507151 17244351 12925238 15492776 16109169 16539743 17425782 14609438 15550985 16110338 16579849 17447844 15588329 16121255 16628246 17590087 14723793 15630473 16121256 16670015 17608565 14737183 15676071 16216087 16700629 17696610 15005800 16221973 16870721 15040800 15819996 16255782 17002498 15061865 15836427 16279840 17020410 ;15314659 ;17194222 ;14611657 ;15760270 ]) (defn triples-from-files "" [] (reduce (fn [collector id] (println "looking to do: " id) (create-ontology-pos-dep-triples id)) {} id-list) ) (defn run-basic "" [] (doseq [x (triples-from-files)] (println x))) ;(NN NMOD (PR:000007164 Entrez Gene sequence)) (defn ontology-id-frequency "" [] (reduce (fn [collector item ] (let [ont-id (first (nth item 2))] (assoc collector ont-id (inc (cond (collector ont-id) (collector ont-id) :t 0))))) {} (triples-from-files) )) (defn run-ontology-id-frequency "" [] (let [results (ontology-id-frequency)] (doseq [x (into (sorted-map-by (fn [key1 key2] (compare [(get results key2) key2] [(get results key1) key1]))) results)] (println x)))) ;;;;;;;;;; (defn onotology-id-pos-distribution "" []) (defn ontology-id-dep-type-distribution "just the roots for now" [] (reduce (fn [collector item ] (let [ont-id (first (nth item 2))] (assoc collector ont-id (inc (cond (collector ont-id) (collector ont-id) :t 0))))) {} (filter (fn [x] (.equals (second x) "ROOT")) (triples-from-files)))) (defn run-sorted-xx "" [] (let [results (ontology-id-dep-type-distribution)] (doseq [x (into (sorted-map-by (fn [key1 key2] (compare [(get results key2) key2] [(get results key1) key1]))) results)] (println x)))) (defn list-roots "" [] (doseq [x (filter (fn [x] (.equals (second x) "ROOT")) (triples-from-files))] (println x)))
117235
;; ;; Copyright <NAME>, August 2014 ;; This namespace contains functions analyzing or counting ;; the terms, their POS, depdency types and frequency without ;; regard to the dependency patterns. (ns clojure-craft.analyze-terms) (use 'clojure.java.io) (use '[clojure.string :only (join split)]) (use '[clojure-craft.craft-pos]) (use '[clojure-craft.craft-xml]) (use '[clojure-craft.craft-dep]) (use '[clojure-craft.craft-unify]) (defn run-unify-pos-dep [id] (let [txtfile (str txt-base "/" id ".txt") posfile (str pos-base "/" id ".txt.xml") depfile (str dep-base "/" id ".dep")] (unify-pos-dep txtfile posfile depfile))) (defn- annotated-sentence? [sentence] (reduce (fn [collector token] (or collector (:anno-list token))) false (:tokens sentence))) (defn- create-triples-from-sentence "take a list of Token records and build a SOS of pos, dep and ontology is" [sentence] (reduce (fn [collector token] (cond (:anno-list token) (conj collector (list (:pos (:dependency token)) (:dep-type (:dependency token)) (:anno-list token))) :t collector)) [] (:tokens sentence))) (defn- get-type-pos-dep "for the given document id, for each ontology, build a sequence of Sentence records containing sequenes of Token records (data), then cull Records down to triples" [sample-id] (let [base (run-unify-pos-dep sample-id) ;; reduce here? TODO data (loop [ontology (first data-dirs) remaining-ontologies (rest data-dirs) sentences base] (cond (not (empty? remaining-ontologies)) (recur (first remaining-ontologies) (rest remaining-ontologies) (run-unify-annotations sentences sample-id ontology)) :t sentences)) ] (map (fn [sentence] (cond (annotated-sentence? sentence) ;; TODO, run without this (create-triples-from-sentence sentence) :t nil)) data)) ) ;;;;;;;;;;;;;;;;;;;;;;;;; (defn create-ontology-pos-dep-triples "distributes triple creation over a list of files" [sample-id] (reduce (fn [collector item] (cond (> (count item) 0) ;;; small to-do: can this be eliminated with nil punning? (reduce conj collector item) :t collector)) [] (get-type-pos-dep sample-id) )) (def id-list [ 11532192 15207008 15876356 16362077 17022820 11597317 15314655 15917436 16433929 17069463 11897010 15921521 16462940 17078885 12079497 15320950 15938754 16504143 17083276 12546709 15328533 16098226 16504174 12585968 15345036 16103912 16507151 17244351 12925238 15492776 16109169 16539743 17425782 14609438 15550985 16110338 16579849 17447844 15588329 16121255 16628246 17590087 14723793 15630473 16121256 16670015 17608565 14737183 15676071 16216087 16700629 17696610 15005800 16221973 16870721 15040800 15819996 16255782 17002498 15061865 15836427 16279840 17020410 ;15314659 ;17194222 ;14611657 ;15760270 ]) (defn triples-from-files "" [] (reduce (fn [collector id] (println "looking to do: " id) (create-ontology-pos-dep-triples id)) {} id-list) ) (defn run-basic "" [] (doseq [x (triples-from-files)] (println x))) ;(NN NMOD (PR:000007164 Entrez Gene sequence)) (defn ontology-id-frequency "" [] (reduce (fn [collector item ] (let [ont-id (first (nth item 2))] (assoc collector ont-id (inc (cond (collector ont-id) (collector ont-id) :t 0))))) {} (triples-from-files) )) (defn run-ontology-id-frequency "" [] (let [results (ontology-id-frequency)] (doseq [x (into (sorted-map-by (fn [key1 key2] (compare [(get results key2) key2] [(get results key1) key1]))) results)] (println x)))) ;;;;;;;;;; (defn onotology-id-pos-distribution "" []) (defn ontology-id-dep-type-distribution "just the roots for now" [] (reduce (fn [collector item ] (let [ont-id (first (nth item 2))] (assoc collector ont-id (inc (cond (collector ont-id) (collector ont-id) :t 0))))) {} (filter (fn [x] (.equals (second x) "ROOT")) (triples-from-files)))) (defn run-sorted-xx "" [] (let [results (ontology-id-dep-type-distribution)] (doseq [x (into (sorted-map-by (fn [key1 key2] (compare [(get results key2) key2] [(get results key1) key1]))) results)] (println x)))) (defn list-roots "" [] (doseq [x (filter (fn [x] (.equals (second x) "ROOT")) (triples-from-files))] (println x)))
true
;; ;; Copyright PI:NAME:<NAME>END_PI, August 2014 ;; This namespace contains functions analyzing or counting ;; the terms, their POS, depdency types and frequency without ;; regard to the dependency patterns. (ns clojure-craft.analyze-terms) (use 'clojure.java.io) (use '[clojure.string :only (join split)]) (use '[clojure-craft.craft-pos]) (use '[clojure-craft.craft-xml]) (use '[clojure-craft.craft-dep]) (use '[clojure-craft.craft-unify]) (defn run-unify-pos-dep [id] (let [txtfile (str txt-base "/" id ".txt") posfile (str pos-base "/" id ".txt.xml") depfile (str dep-base "/" id ".dep")] (unify-pos-dep txtfile posfile depfile))) (defn- annotated-sentence? [sentence] (reduce (fn [collector token] (or collector (:anno-list token))) false (:tokens sentence))) (defn- create-triples-from-sentence "take a list of Token records and build a SOS of pos, dep and ontology is" [sentence] (reduce (fn [collector token] (cond (:anno-list token) (conj collector (list (:pos (:dependency token)) (:dep-type (:dependency token)) (:anno-list token))) :t collector)) [] (:tokens sentence))) (defn- get-type-pos-dep "for the given document id, for each ontology, build a sequence of Sentence records containing sequenes of Token records (data), then cull Records down to triples" [sample-id] (let [base (run-unify-pos-dep sample-id) ;; reduce here? TODO data (loop [ontology (first data-dirs) remaining-ontologies (rest data-dirs) sentences base] (cond (not (empty? remaining-ontologies)) (recur (first remaining-ontologies) (rest remaining-ontologies) (run-unify-annotations sentences sample-id ontology)) :t sentences)) ] (map (fn [sentence] (cond (annotated-sentence? sentence) ;; TODO, run without this (create-triples-from-sentence sentence) :t nil)) data)) ) ;;;;;;;;;;;;;;;;;;;;;;;;; (defn create-ontology-pos-dep-triples "distributes triple creation over a list of files" [sample-id] (reduce (fn [collector item] (cond (> (count item) 0) ;;; small to-do: can this be eliminated with nil punning? (reduce conj collector item) :t collector)) [] (get-type-pos-dep sample-id) )) (def id-list [ 11532192 15207008 15876356 16362077 17022820 11597317 15314655 15917436 16433929 17069463 11897010 15921521 16462940 17078885 12079497 15320950 15938754 16504143 17083276 12546709 15328533 16098226 16504174 12585968 15345036 16103912 16507151 17244351 12925238 15492776 16109169 16539743 17425782 14609438 15550985 16110338 16579849 17447844 15588329 16121255 16628246 17590087 14723793 15630473 16121256 16670015 17608565 14737183 15676071 16216087 16700629 17696610 15005800 16221973 16870721 15040800 15819996 16255782 17002498 15061865 15836427 16279840 17020410 ;15314659 ;17194222 ;14611657 ;15760270 ]) (defn triples-from-files "" [] (reduce (fn [collector id] (println "looking to do: " id) (create-ontology-pos-dep-triples id)) {} id-list) ) (defn run-basic "" [] (doseq [x (triples-from-files)] (println x))) ;(NN NMOD (PR:000007164 Entrez Gene sequence)) (defn ontology-id-frequency "" [] (reduce (fn [collector item ] (let [ont-id (first (nth item 2))] (assoc collector ont-id (inc (cond (collector ont-id) (collector ont-id) :t 0))))) {} (triples-from-files) )) (defn run-ontology-id-frequency "" [] (let [results (ontology-id-frequency)] (doseq [x (into (sorted-map-by (fn [key1 key2] (compare [(get results key2) key2] [(get results key1) key1]))) results)] (println x)))) ;;;;;;;;;; (defn onotology-id-pos-distribution "" []) (defn ontology-id-dep-type-distribution "just the roots for now" [] (reduce (fn [collector item ] (let [ont-id (first (nth item 2))] (assoc collector ont-id (inc (cond (collector ont-id) (collector ont-id) :t 0))))) {} (filter (fn [x] (.equals (second x) "ROOT")) (triples-from-files)))) (defn run-sorted-xx "" [] (let [results (ontology-id-dep-type-distribution)] (doseq [x (into (sorted-map-by (fn [key1 key2] (compare [(get results key2) key2] [(get results key1) key1]))) results)] (println x)))) (defn list-roots "" [] (doseq [x (filter (fn [x] (.equals (second x) "ROOT")) (triples-from-files))] (println x)))
[ { "context": "et-db-info this branch))\n {:keys [token-to-token-info-data-id]} db-info\n src-storage (get-storage th", "end": 49916, "score": 0.7518500089645386, "start": 49895, "tag": "KEY", "value": "to-token-info-data-id" } ]
src/com/dept24c/vivo/server.clj
CambodianCoder/vivo
0
(ns com.dept24c.vivo.server (:require [clojure.core.async :as ca] [clojure.string :as str] [cognitect.aws.client.api :as aws] [cognitect.aws.client.api.async :as aws-async] [com.dept24c.vivo.bristlecone.block-ids :as block-ids] [com.dept24c.vivo.bristlecone.data-block-storage :as data-block-storage] [com.dept24c.vivo.bristlecone.data-storage :as data-storage] [com.dept24c.vivo.bristlecone.ddb-block-storage :as ddb-block-storage] [com.dept24c.vivo.bristlecone.mem-block-storage :as mem-block-storage] [com.dept24c.vivo.commands :as commands] [com.dept24c.vivo.utils :as u] [crypto.password.bcrypt :as bcrypt] [deercreeklabs.async-utils :as au] [deercreeklabs.baracus :as ba] [deercreeklabs.capsule.endpoint :as ep] [deercreeklabs.capsule.logging :as log] [deercreeklabs.capsule.server :as cs] [deercreeklabs.lancaster :as l] [deercreeklabs.tube.connection :as tc] [deercreeklabs.stockroom :as sr]) (:import (clojure.lang ExceptionInfo) (java.security SecureRandom) (java.util UUID) (java.util.concurrent ConcurrentLinkedQueue))) (set! *warn-on-reflection* true) (def work-factor 12) (defprotocol IVivoServer (<add-subject [this arg metadata]) (<add-subject* [this identifier secret subject-id branch conn-id]) (<add-subject-identifier [this arg metadata]) (<change-secret [this arg metadata]) (<change-secret* [this branch subject-id old-secret new-secret]) (<create-branch [this arg metadata]) (<delete-branch [this branch metadata]) (<fp->schema [this fp conn-id]) (<get-all-branches [this]) (<get-db-id [this branch]) (<get-db-info [this branch]) (<get-in [this db-id path]) (<get-log [this branch limit]) (<get-num-commits [this branch]) (<get-schema-pcf [this arg metadata]) (<get-state [this arg metadata]) (<get-state-and-expanded-path [this db-id path]) (<get-subject-id-for-identifier [this identifier branch]) (<log-in [this arg metadata]) (<log-in* [this identifier secret minutes-valid conn-id branch]) (<log-in-w-token [this arg metadata]) (<log-out [this arg metadata]) (<log-out-w-token [this token metadata]) (<modify-db! [this <update-fn msg subject-id branch conn-id]) (<remove-subject-identifier [this identifier metadata]) (<handle-request-db-changed-msg [this arg metadata]) (<rpc [this arg metadata]) (<set-state-source [this arg metadata]) (<store-schema-pcf [this arg metadata]) (<update-db [this update-cmds msg subject-id branch]) (<update-state [this arg metadata]) (<scmds->cmds [this scmds conn-id]) (get-storage [this branch-or-db-id]) (publish-msg [this arg metadata]) (set-rpc-handler! [this rpc-name-kw handler]) (shutdown! [this])) (defn generate-token [] (let [rng (SecureRandom.) bytes (byte-array 32)] (.nextBytes rng bytes) (ba/byte-array->b64 bytes))) (defn branch->reference [branch] (str u/branch-reference-root branch)) (defn throw-branch-name-too-long [branch] (throw (ex-info (str "Branch names must be " u/max-branch-name-len " characters or less. " "Branch " branch " is " (count branch) " characters.") (u/sym-map branch)))) (defn <update-storage [data-id schema update-commands prefix branch temp-storage perm-storage] ;; TODO: Support structural sharing (when data-id ;; Allow nil for creating a new data item (u/check-data-id data-id)) (au/go (let [dest-storage (if (str/starts-with? branch "-") temp-storage perm-storage) old-state (when data-id (let [src-storage (if (str/starts-with? data-id "-") temp-storage perm-storage)] (au/<? (data-storage/<read-data src-storage data-id schema)))) uc-ret (reduce (fn [{:keys [state] :as acc} cmd] (let [ret (commands/eval-cmd state cmd prefix)] (-> acc (assoc :state (:state ret)) (update :update-infos conj (:update-info ret))))) {:state old-state :update-infos []} update-commands) {:keys [update-infos state]} uc-ret new-data-id (au/<? (data-storage/<write-data dest-storage schema state))] (u/sym-map new-data-id update-infos state)))) (defn <add-subject-update-fn [requested-subject-id identifier hashed-secret dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id subject-id-to-hashed-secret-data-id]} dbi new-dbi (assoc dbi :subject-id-to-hashed-secret-data-id (:new-data-id (au/<? (<update-storage subject-id-to-hashed-secret-data-id u/string-map-schema [{:path [requested-subject-id] :op :set :arg hashed-secret}] nil branch temp-storage perm-storage))) :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :set :arg requested-subject-id}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <add-subject-identifier-update-fn [identifier dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id]} dbi new-dbi (assoc dbi :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :set :arg subject-id}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <remove-subject-identifier-update-fn [identifier dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id]} dbi new-dbi (assoc dbi :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :remove}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <change-secret-update-fn [hashed-secret dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [subject-id-to-hashed-secret-data-id subject-id-to-tokens-data-id token-to-token-info-data-id]} dbi dbi* (assoc dbi :subject-id-to-hashed-secret-data-id (:new-data-id (au/<? (<update-storage subject-id-to-hashed-secret-data-id u/string-map-schema [{:path [subject-id] :op :set :arg hashed-secret}] nil branch temp-storage perm-storage)))) src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) ;; Invalidate existing tokens for this user tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) ;; Use loop here to stay in go block new-dbi (loop [new-dbi dbi* [token & more] tokens] (let [new-dbi* (assoc new-dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))))] (if (seq more) (recur new-dbi* more) new-dbi*)))] {:dbi new-dbi :update-infos []}))) (defn <log-in-update-fn [token token-info dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi new-dbi (assoc dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :set :arg token-info}] nil branch temp-storage perm-storage))) :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id -1] :op :insert-after :arg token}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <log-out-update-fn [dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi dbi* (assoc dbi :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id] :op :remove}] nil branch temp-storage perm-storage)))) src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) ;; Use loop here to stay in go block new-dbi (loop [new-dbi dbi* [token & more] tokens] (let [new-dbi* (assoc new-dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))))] (if (seq more) (recur new-dbi* more) new-dbi*)))] {:dbi new-dbi :update-infos []}))) (defn <delete-token-update-fn [token dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) new-tokens (remove #(= token %) tokens) new-dbi (assoc dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))) ;; TODO: Improve this when `find` is implemented :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id] :op :set :arg new-tokens}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <update-state-update-fn [state-schema update-cmds dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [data-id]} dbi ret (au/<? (<update-storage data-id state-schema update-cmds :sys branch temp-storage perm-storage)) {:keys [new-data-id update-infos state]} ret] {:dbi (assoc dbi :data-id new-data-id) :update-infos update-infos :update-state-rpc? true :state state}))) (defn <delete-branch* [branch storage] (au/go (let [all-branches (au/<? (u/<get-in-reference storage u/all-branches-reference u/all-branches-schema nil nil)) new-branches (or (-> (set all-branches) (disj branch) (seq)) []) branch-reference (branch->reference branch)] ;; TODO: Improve this when `find` is implemented (au/<? (u/<update-reference! storage u/all-branches-reference u/all-branches-schema [{:path nil :op :set :arg new-branches}] nil)) (au/<? (u/<delete-reference! storage branch-reference)) true))) (defn notify-conns! [update-state-rpc? update-infos conn-id conn-ids db-id prev-db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info] ;; For update-state, notify all conns except the originator, ;; who gets the information sent to them directly. ;; This allows local+sys updates to be atomic. (let [conn-ids* (if update-state-rpc? (disj (set conn-ids) conn-id) conn-ids)] (ca/go (try (doseq [conn-id* conn-ids*] (let [{:keys [subject-id]} (@*conn-id->info conn-id*) new-state (when whole-state (redaction-fn subject-id whole-state)) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (when whole-state (l/serialize state-schema new-state)) serialized-state (when whole-state (u/sym-map fp bytes)) info (u/sym-map db-id prev-db-id serialized-state subject-id update-infos)] (ep/send-msg vc-ep conn-id* :db-changed info))) (catch Exception e (log/error (str "Error in notify-conns!:\n" (u/ex-msg-and-stacktrace e)))))))) (defn <modify-db!* [branch conn-id subject-id <update-fn msg redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info] (au/go (let [num-tries 10 {:keys [conn-ids]} (@*branch->info branch) branch-reference (branch->reference branch) dest-storage (if (str/starts-with? branch "-") temp-storage perm-storage)] ;; Use loop to stay in go block (loop [num-tries-left (dec num-tries)] (let [prev-db-id (au/<? (u/<get-data-id dest-storage branch-reference)) src-storage (cond (nil? prev-db-id) nil (str/starts-with? prev-db-id "-") temp-storage :else perm-storage) prev-dbi (when src-storage (au/<? (u/<get-in src-storage prev-db-id u/db-info-schema nil nil))) {:keys [num-prev-dbs data-id]} prev-dbi uf-ret (au/<? (<update-fn prev-dbi subject-id branch temp-storage perm-storage)) {:keys [dbi update-infos update-state-rpc?]} uf-ret new-dbi (assoc dbi :msg msg :timestamp-ms (u/current-time-ms) :num-prev-dbs (if num-prev-dbs (inc num-prev-dbs) 0) :prev-db-id prev-db-id) update-ret (au/<? (<update-storage prev-db-id u/db-info-schema [{:path [] :op :set :arg new-dbi}] nil branch temp-storage perm-storage)) new-db-id (:new-data-id update-ret) whole-state (:state uf-ret)] (if (au/<? (u/<compare-and-set! dest-storage branch-reference l/string-schema prev-db-id new-db-id)) (do (notify-conns! update-state-rpc? update-infos conn-id conn-ids new-db-id prev-db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info) (u/sym-map new-db-id prev-db-id whole-state update-infos)) (if (zero? num-tries-left) (throw (ex-info (str "Failed to commit to branch `" branch-reference "` after " num-tries " tries.") (u/sym-map branch-reference num-tries))) (do (au/<? (ca/timeout (rand-int 100))) (recur (dec num-tries-left)))))))))) (defn start-modify-db-loop [^ConcurrentLinkedQueue q redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info] (ca/go (while true (try (if-let [info (.poll q)] (let [{:keys [cb branch conn-id subject-id <update-fn msg]} info] (try (cb (au/<? (<modify-db!* branch conn-id subject-id <update-fn msg redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info))) (catch Exception e (cb e)))) (ca/<! (ca/timeout 5))) (catch Exception e (log/error (str "Unexpected error in txn-loop:\n" (u/ex-msg-and-stacktrace e)))))))) (defn <ks-at-path [kw <get-at-path p full-path] (au/go (let [coll (au/<? (<get-at-path p))] (cond (map? coll) (keys coll) (sequential? coll) (range (count coll)) (nil? coll) [] :else (throw (ex-info (str "`" kw "` is in path, but there is not " "a collection at " p ".") {:full-path full-path :missing-collection-path p :value coll})))))) (defn <count-at-path [<get-at-path p full-path] (au/go (let [coll (au/<? (<get-at-path p))] (cond (or (map? coll) (sequential? coll)) (count coll) (nil? coll) 0 :else (throw (ex-info (str "`:vivo/count` terminates path, but " "there is not a collection at " p ".") {:full-path full-path :missing-collection-path p :value coll})))))) (defn <do-concat [<get-at-path p full-path] (au/go (let [seqs (au/<? (<get-at-path p))] (when (and (not (nil? seqs)) (or (not (sequential? seqs)) (not (sequential? (first seqs))))) (throw (ex-info (str "`:vivo/concat` terminates path, but there " "is not a sequence of sequences at " p ".") {:full-path full-path :missing-collection-path p :value seqs}))) (apply concat seqs)))) (defn <do-login [vs conn-id branch identifier secret login-identifier-case-sensitive? login-lifetime-mins *conn-id->info *branch->info] (au/go (u/check-secret-len secret) (let [identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) db-info (au/<? (<get-db-info vs branch)) {id->sid-data-id :identifier-to-subject-id-data-id sid->hs-data-id :subject-id-to-hashed-secret-data-id} db-info subject-id (when id->sid-data-id (let [src-storage (get-storage vs id->sid-data-id)] (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier*] nil)))) hashed-secret (when (and subject-id sid->hs-data-id) (let [src-storage (get-storage vs sid->hs-data-id)] (au/<? (u/<get-in src-storage sid->hs-data-id u/string-map-schema [subject-id] nil))))] (if-not (and hashed-secret (bcrypt/check secret hashed-secret)) {:subject-id nil :token nil} (let [token (generate-token) expiration-time-mins (+ (u/ms->mins (u/current-time-ms)) login-lifetime-mins) token-info (u/sym-map expiration-time-mins subject-id) _ (when conn-id (swap! *conn-id->info update conn-id assoc :subject-id subject-id) (swap! *branch->info update branch update :subject-id->conn-ids update subject-id (fn [conn-ids] (conj (or conn-ids #{}) conn-id)))) ret (au/<? (<modify-db! vs (partial <log-in-update-fn token token-info) "Log in" subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id subject-id :token token}))))) (defn <log-out-subject! [vs subject-id branch *branch->info *conn-id->info] (au/go (let [conn-ids (some-> (@*branch->info branch) (:subject-id->conn-ids) (get subject-id))] (swap! *branch->info update branch update :subject-id->conn-ids dissoc subject-id) (doseq [conn-id conn-ids] (swap! *conn-id->info update conn-id dissoc :subject-id) (au/<? (<modify-db! vs <log-out-update-fn "Log out" subject-id branch nil))) true))) (defn <do-add-subject [vs identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?] (au/go (u/check-secret-len secret) (let [hashed-secret (bcrypt/encrypt secret work-factor) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) ret (au/<? (<modify-db! vs (partial <add-subject-update-fn subject-id identifier* hashed-secret) (str "Add subject " subject-id) subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id subject-id}))) (defn <do-change-secret! [vs branch subject-id old-secret new-secret] (au/go (u/check-secret-len old-secret) (u/check-secret-len new-secret) (let [branch-reference (branch->reference branch) storage (get-storage vs branch) db-id (au/<? (u/<get-data-id storage branch-reference)) db-info (au/<? (u/<get-in storage db-id u/db-info-schema nil nil)) {sid->hs-data-id :subject-id-to-hashed-secret-data-id} db-info hashed-old-secret (when (and subject-id old-secret) (au/<? (u/<get-in storage sid->hs-data-id u/string-map-schema [subject-id] nil))) old-secret-ok? (if-not hashed-old-secret true (bcrypt/check old-secret hashed-old-secret))] (if-not old-secret-ok? false (let [hashed-new-secret (bcrypt/encrypt new-secret work-factor)] (-> (au/<? (<modify-db! vs (partial <change-secret-update-fn hashed-new-secret) "Change secret" subject-id branch nil)) :new-db-id)))))) (defn <do-update-state [vs arg metadata authorization-fn redaction-fn state-schema perm-storage *conn-id->info] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) update-cmds (au/<? (<scmds->cmds vs arg conn-id)) all-authed? (if (empty? update-cmds) true (loop [i 0] ; Use loop to stay in same go block (let [{:keys [path arg]} (nth update-cmds i) auth-ret (authorization-fn subject-id path :write arg) authed? (if (au/channel? auth-ret) (au/<? auth-ret) auth-ret) new-i (inc i)] (cond (not authed?) false (= (count update-cmds) new-i) true :else (recur new-i)))))] (if-not all-authed? :vivo/unauthorized (let [ret (au/<? (<modify-db! vs (partial <update-state-update-fn state-schema update-cmds) "Update state" subject-id branch conn-id)) {:keys [new-db-id prev-db-id whole-state update-infos]} ret state (redaction-fn subject-id whole-state) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (l/serialize state-schema state) serialized-state (u/sym-map fp bytes)] {:db-id new-db-id :prev-db-id prev-db-id :serialized-state serialized-state :update-infos update-infos}))))) (defn <log-in-w-token* [vivo-server state-schema redaction-fn vc-ep perm-storage token metadata *conn-id->info] (au/go (let [{:keys [conn-id]} metadata {:keys [*conn-id->info *branch->info]} vivo-server {:keys [branch]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info vivo-server branch)) {:keys [token-to-token-info-data-id db-id]} db-info info (when token-to-token-info-data-id (let [src-storage (get-storage vivo-server token-to-token-info-data-id)] (au/<? (u/<get-in src-storage token-to-token-info-data-id u/token-map-schema [token] nil)))) {:keys [expiration-time-mins subject-id]} info now-mins (-> (u/current-time-ms) (u/ms->mins))] (when info (if (>= now-mins expiration-time-mins) (let [ret (au/<? (<modify-db! vivo-server (partial <delete-token-update-fn token) "Delete expired token" subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id nil :token nil}) (do (swap! *conn-id->info update conn-id assoc :subject-id subject-id) (swap! *branch->info update branch update :subject-id->conn-ids update subject-id (fn [conn-ids] (conj (or conn-ids #{}) conn-id))) ;; When subject-id changes but not the db, we need to send a new db ;; with the results of the redaction-fn. db-id doesn't change. (let [update-infos [{:norm-path [:sys] :op :set} {:norm-path [:vivo/subject-id] :op :set}] db-id (au/<? (<get-db-id vivo-server branch)) whole-state (first (au/<? (<get-state-and-expanded-path vivo-server db-id [:sys])))] (notify-conns! false update-infos conn-id [conn-id] db-id db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info) (u/sym-map db-id subject-id token)))))))) (defn <set-state-source* [vivo-server source metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [perm-storage state-schema *branch->info *conn-id->info]} vivo-server perm-branch (:branch/name source) branch (if perm-branch (let [branch-reference (branch->reference perm-branch) storage (get-storage vivo-server perm-branch)] (when-not (au/<? (u/<get-data-id storage branch-reference)) (au/<? (<create-branch vivo-server {:branch perm-branch :db-id nil} metadata))) perm-branch) (let [branch* (str "-temp-branch-" (rand-int 1e9))] (au/<? (<create-branch vivo-server {:branch branch* :db-id (:temp-branch/db-id source)} metadata)) branch*))] (swap! *conn-id->info update conn-id assoc :branch branch :temp-branch? (not perm-branch)) (swap! *branch->info update branch (fn [{:keys [conn-ids] :as info}] (if conn-ids (update info :conn-ids conj conn-id) (assoc info :conn-ids #{conn-id})))) true))) (defn publish-msg* [vc-ep *conn-id->info arg metadata] (let [{:keys [conn-id]} metadata conn-ids (keys @*conn-id->info)] (doseq [conn-id* (disj (set conn-ids) conn-id)] (ep/send-msg vc-ep conn-id* :publish-msg arg)) true)) (defrecord VivoServer [authorization-fn login-identifier-case-sensitive? login-lifetime-mins modify-q path->schema-cache perm-storage rpcs vc-ep redaction-fn repository-name state-schema stop-server temp-storage *conn-id->info *branch->info *rpc->handler] IVivoServer (<modify-db! [this <update-fn msg subject-id branch conn-id] (au/go (let [modify-ch (ca/chan) cb #(ca/put! modify-ch %) update-info (u/sym-map cb branch conn-id subject-id <update-fn msg) _ (.add ^ConcurrentLinkedQueue modify-q update-info) change-info (au/<? modify-ch)] change-info))) (<get-db-info [this branch] (au/go (let [branch-reference (branch->reference branch) dest-storage (get-storage this branch) db-id (au/<? (u/<get-data-id dest-storage branch-reference)) src-storage (get-storage this db-id)] (-> (u/<get-in src-storage db-id u/db-info-schema nil nil) (au/<?) (assoc :db-id db-id))))) (<add-subject [this arg metadata] (let [{:keys [identifier secret subject-id] :or {subject-id (.toString ^UUID (UUID/randomUUID))}} arg {:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id)] (u/check-secret-len secret) (<do-add-subject this identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?))) (<add-subject* [this identifier secret subject-id branch conn-id] (<do-add-subject this identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?)) (<add-subject-identifier [this identifier metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier))] (if-not subject-id false ;; Must be logged in (-> (au/<? (<modify-db! this (partial <add-subject-identifier-update-fn identifier*) (str "Add subject indentifier `" identifier*) subject-id branch conn-id)) :new-db-id))))) (<remove-subject-identifier [this identifier metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info this branch)) id->sid-data-id (:identifier-to-subject-id-data-id db-info) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) src-storage (get-storage this id->sid-data-id) id-subject-id (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier*] nil)) my-identifier? (and subject-id (= subject-id id-subject-id))] (if-not my-identifier? false (-> (<modify-db! this (partial <remove-subject-identifier-update-fn identifier*) (str "Remove subject indentifier `" identifier*) subject-id branch conn-id) (au/<?) (:new-db-id)))))) (<change-secret* [this branch subject-id old-secret new-secret] (<do-change-secret! this branch subject-id old-secret new-secret)) (<change-secret [this arg metadata] (let [{:keys [old-secret new-secret]} arg {:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id)] (<change-secret* this branch subject-id old-secret new-secret))) (<create-branch [this arg metadata] (au/go (let [{:keys [branch db-id]} arg {:keys [subject-id]} metadata _ (when (empty? branch) (throw (ex-info "Branch name is nil or empty." arg))) _ (when (> (count branch) u/max-branch-name-len) (throw-branch-name-too-long branch)) temp-dest? (str/starts-with? branch "-") src-storage (get-storage this db-id) dest-storage (get-storage this branch) temp-src? (and db-id (block-ids/temp-block-id? db-id)) branch-reference (branch->reference branch) _ (when (and db-id (not (try (au/<? (u/<get-in src-storage db-id u/db-info-schema [:data-id] nil)) (catch ExceptionInfo e (if (re-find #"not match given writer schema" (ex-message e)) false (throw e)))))) (throw (ex-info (str "Source db-id `" db-id "` does not exist.") arg))) _ (when (and temp-src? (not temp-dest?)) (throw (ex-info (str "Cannot create a permanent branch from a " "temporary db-id.") (u/sym-map branch db-id temp-dest?)))) _ (when (au/<? (u/<get-data-id dest-storage branch-reference)) (throw (ex-info (str "A branch named `" branch "` already " "exists in the repository.") (u/sym-map branch db-id temp-dest?)))) _ (au/<? (u/<update-reference! dest-storage u/all-branches-reference u/all-branches-schema [{:path [-1] :op :insert-after :arg branch}] nil)) db-id* (or db-id (let [create-db-ch (ca/chan) cb #(ca/put! create-db-ch %) default-data (l/default-data state-schema) update-cmds [{:path [:sys] :op :set :arg default-data}] <update-fn (partial <update-state-update-fn state-schema update-cmds) msg "Create initial db for branch" create-info (u/sym-map cb branch subject-id <update-fn msg)] (.add ^ConcurrentLinkedQueue modify-q create-info) (:new-db-id (au/<? create-db-ch))))] (au/<? (u/<set-reference! dest-storage branch-reference db-id*))))) (<delete-branch [this branch metadata] (<delete-branch* branch (get-storage this branch))) (<fp->schema [this fp conn-id] (au/go (or (au/<? (u/<fp->schema perm-storage fp)) (let [pcf (au/<? (ep/<send-msg vc-ep conn-id :get-schema-pcf fp))] (l/json->schema pcf))))) ;; TODO: Fix <get-all-branches to use a scan. ;; Get rid of all-branches-reference (<get-all-branches [this] (au/go (let [perm-branches (au/<? (u/<get-in-reference perm-storage u/all-branches-reference u/all-branches-schema nil nil)) temp-branches (au/<? (u/<get-in-reference temp-storage u/all-branches-reference u/all-branches-schema nil nil)) all-branches (concat perm-branches temp-branches)] (seq all-branches)))) (<get-db-id [this branch] (let [storage (get-storage this branch) branch-reference (branch->reference branch)] (u/<get-data-id storage branch-reference))) (<get-in [this db-id path] (au/go (let [state-and-path (au/<? (<get-state-and-expanded-path this db-id path))] (first state-and-path)))) (<get-state-and-expanded-path [this db-id path] (au/go (when-not (string? db-id) (throw (ex-info (str "Bad db-id `" db-id "`. db-id must be a string.") {:db-id db-id}))) (when (and path (not (sequential? path))) (throw (ex-info (str "Bad path `" path "`. Path must be nil or a sequence.") {:path path}))) (let [path (or path [:sys]) db-id-storage (get-storage this db-id) data-id (au/<? (u/<get-in db-id-storage db-id u/db-info-schema [:data-id] nil)) data-id-storage (get-storage this data-id) <get-at-path #(u/<get-in data-id-storage data-id state-schema % :sys) last-path-k (last path) join? (u/has-join? path) term-kw? (u/terminal-kw-ops last-path-k)] (cond (or (not data-id) (u/empty-sequence-in-path? path)) [nil [path]] (and (not term-kw?) (not join?)) (let [val (au/<? (<get-at-path path))] [val [path]]) (and term-kw? (not join?)) (let [path* (butlast path) val (case last-path-k :vivo/keys (au/<? (<ks-at-path :vivo/keys <get-at-path path* path)) :vivo/count (au/<? (<count-at-path <get-at-path path* path)) :vivo/concat (au/<? (<do-concat <get-at-path path* path)))] [val [path]]) (and (not term-kw?) join?) (when-not (u/empty-sequence-in-path? path) (let [expanded-path (au/<? (u/<expand-path #(<ks-at-path :vivo/* <get-at-path % path) path)) num-results (count expanded-path)] (if (zero? num-results) [[] []] ;; Use loop to stay in the go block (loop [out [] i 0] (let [filled-in-path (nth expanded-path i) v (au/<? (u/<get-in data-id-storage data-id state-schema filled-in-path :sys)) new-out (conj out v) new-i (inc i)] (if (= num-results new-i) [new-out expanded-path] (recur new-out new-i))))))) (and term-kw? join?) (let [expanded-path (au/<? (u/<expand-path #(<ks-at-path :vivo/* <get-at-path % path) (butlast path))) num-results (count expanded-path)] (if (zero? num-results) [[] []] (let [results (loop [out [] i 0] (let [filled-in-path (nth expanded-path i) v (au/<? (u/<get-in data-id-storage data-id state-schema filled-in-path :sys)) new-out (conj out v) new-i (inc i)] (if (= num-results new-i) new-out (recur new-out new-i)))) value (case last-path-k :vivo/keys (range (count results)) :vivo/count (count results) :vivo/concat (apply concat results))] [value expanded-path]))))))) (<get-log [this branch limit] (au/go (let [storage (get-storage this branch) db-id (au/<? (<get-db-id this branch)) dbi (au/<? (u/<get-in storage db-id u/db-info-schema nil nil)) make-log-rec #(select-keys % [:msg :timestamp-ms])] (when dbi (loop [out [(make-log-rec dbi)] i 1] (let [{:keys [prev-db-id]} (peek out)] (if (or (not prev-db-id) (= limit i)) out (let [prev-dbi (au/<? (u/<get-in storage prev-db-id u/db-info-schema nil nil))] (recur (conj out (make-log-rec dbi)) (inc i)))))))))) (<get-num-commits [this branch] (au/go (let [storage (get-storage this branch) db-id (au/<? (<get-db-id this branch)) dbi (au/<? (u/<get-in storage db-id u/db-info-schema nil nil))] (if dbi (inc (:num-prev-dbs dbi)) 0)))) (<get-state [this arg metadata] ;; TODO: Figure this out for non-locally-cached state lookups ;; Figure out how to unify authorization-fn and redaction-fn #_ (au/go (let [{:keys [path db-id]} arg {:keys [conn-id]} metadata {:keys [subject-id]} (@*conn-id->info conn-id) [v xp] (au/<? (<get-state-and-expanded-path this db-id path)) authorized? (let [ret (authorization-fn subject-id path :read v)] (if (au/channel? ret) (au/<? ret) ret))] (if (or (not authorized?) (= :vivo/unauthorized v)) :vivo/unauthorized (when v (let [schema-path (rest path) ; Ignore :sys schema (u/path->schema path->schema-cache state-schema schema-path) fp (when schema (au/<? (u/<schema->fp perm-storage schema)))] (when schema {:serialized-value {:fp fp :bytes (l/serialize schema v)} :expanded-path xp}))))))) (<get-subject-id-for-identifier [this identifier branch] (au/go (let [db-info (au/<? (<get-db-info this branch)) id->sid-data-id (:identifier-to-subject-id-data-id db-info) src-storage (get-storage this id->sid-data-id)] (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier] nil))))) (<log-in* [this identifier secret minutes-valid conn-id branch] (<do-login this conn-id branch identifier secret login-identifier-case-sensitive? minutes-valid *conn-id->info *branch->info)) (<log-in [this arg metadata] (let [{:keys [identifier secret]} arg {:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id)] (<log-in* this identifier secret login-lifetime-mins conn-id branch))) (<log-in-w-token [this token metadata] (<log-in-w-token* this state-schema redaction-fn vc-ep perm-storage token metadata *conn-id->info)) (<log-out [this arg metadata] (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id)] (<log-out-subject! this subject-id branch *branch->info *conn-id->info))) (<log-out-w-token [this token metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info this branch)) {:keys [token-to-token-info-data-id]} db-info src-storage (get-storage this token-to-token-info-data-id) info (when token-to-token-info-data-id (au/<? (u/<get-in src-storage token-to-token-info-data-id u/token-map-schema [token] nil)))] (if-not info false (let [{:keys [subject-id]} info] (au/<? (<log-out-subject! this subject-id branch *branch->info *conn-id->info))))))) (<set-state-source [this source metadata] (<set-state-source* this source metadata)) (<rpc [this msg-arg metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) db-id (au/<? (<get-db-id this branch)) {:keys [rpc-name-kw-ns rpc-name-kw-name arg]} msg-arg rpc-name-kw (keyword rpc-name-kw-ns rpc-name-kw-name) rpc-info (rpcs rpc-name-kw) _ (when-not rpc-info (throw (ex-info (str "No RPC with name `" rpc-name-kw "` is registered. " "Either this is a typo or you need to add `" rpc-name-kw "` to the :rpcs map when " "creating the Vivo server.") {:known-rpcs (keys rpcs) :given-rpc rpc-name-kw}))) handler (@*rpc->handler rpc-name-kw) _ (when-not handler (throw (ex-info (str "No RPC handler for `" rpc-name-kw "` is registered. " "Call `set-rpc-handler!` on the server instance to " "set an RPC handler.") {:known-rpcs (keys rpcs) :given-rpc rpc-name-kw}))) {:keys [arg-schema ret-schema]} rpc-info {:keys [fp bytes]} arg w-schema (au/<? (<fp->schema this fp conn-id)) rpc-arg (l/deserialize arg-schema w-schema bytes) authorized? (let [path [:vivo/rpcs rpc-name-kw] ret (authorization-fn subject-id path :call rpc-arg)] (if (au/channel? ret) (au/<? ret) ret))] (if-not authorized? :vivo/unauthorized (let [rpc-metadata (assoc (u/sym-map conn-id subject-id branch db-id repository-name) :vivo-server this) ret* (handler rpc-arg rpc-metadata) ret (if (au/channel? ret*) (au/<? ret*) ret*)] {:fp (au/<? (u/<schema->fp perm-storage ret-schema)) :bytes (l/serialize ret-schema ret)}))))) (<handle-request-db-changed-msg [this arg metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) db-id (au/<? (<get-db-id this branch)) [whole-state xp] (au/<? (<get-state-and-expanded-path this db-id [:sys])) new-state (when whole-state (redaction-fn subject-id whole-state)) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (when new-state (l/serialize state-schema new-state)) serialized-state (u/sym-map fp bytes) info (-> (u/sym-map db-id serialized-state subject-id) (assoc :prev-db-id db-id) (assoc :update-infos []))] (ep/send-msg vc-ep conn-id :db-changed info)))) (<scmds->cmds [this scmds conn-id] (au/go (if-not (seq scmds) [] ;; Use loop/recur to stay in single go block (loop [scmd (first scmds) i 0 out []] (let [{:keys [path arg]} scmd arg-sch (u/path->schema path->schema-cache state-schema (rest path)) ; Ignore :sys new-i (inc i) last? (= (count scmds) new-i)] (if-not arg-sch ; Skip cmd if we don't have schema (evolution) (if last? out (recur (nth scmds new-i) new-i out)) (let [writer-arg-sch (when arg (au/<? (<fp->schema this (:fp arg) conn-id))) arg* (when arg (l/deserialize arg-sch writer-arg-sch (:bytes arg))) cmd (cond-> scmd arg (assoc :arg arg*)) new-out (conj out cmd)] (if last? new-out (recur (nth scmds new-i) new-i new-out))))))))) (<update-db [this update-cmds msg subject-id branch] (<modify-db! this (partial <update-state-update-fn state-schema update-cmds) "Update db" subject-id branch nil)) (<update-state [this arg metadata] (<do-update-state this arg metadata authorization-fn redaction-fn state-schema perm-storage *conn-id->info)) (<get-schema-pcf [this fp metadata] (au/go (if-let [schema (au/<? (u/<fp->schema perm-storage fp))] (l/pcf schema) (do (log/error (str "Could not find PCF for fingerprint `" fp "`.")) nil)))) (<store-schema-pcf [this pcf metadata] (au/go (au/<? (u/<schema->fp perm-storage (l/json->schema pcf))) true)) (get-storage [this branch-or-db-id] (when branch-or-db-id (if (str/starts-with? branch-or-db-id "-") temp-storage perm-storage))) (set-rpc-handler! [this rpc-name-kw handler] (swap! *rpc->handler assoc rpc-name-kw handler)) (publish-msg [this arg metadata] (publish-msg* vc-ep *conn-id->info arg metadata)) (shutdown! [this] (stop-server))) (defn default-health-http-handler [req] (if (= "/health" (:uri req)) {:status 200 :headers {"content-type" "text/plain" "Access-Control-Allow-Origin" "*"} :body "I am healthy"} {:status 404 :body "I still haven't found what you're looking for..."})) (def default-config {:additional-endpoints [] :authenticate-admin-client (constantly false) :handle-http default-health-http-handler :http-timeout-ms 60000 :login-lifetime-mins (* 60 24 15) ;; 15 days :redaction-fn (fn [subject-id db] db)}) (defn check-config [config] (let [required-ks [:authorization-fn :port :repository-name :state-schema]] (doseq [k required-ks] (when-not (config k) (throw (ex-info (str "Missing " k " in config.") (u/sym-map k config)))))) (when-let [rpcs (:rpcs config)] (when-not (map? rpcs) (throw (ex-info (str "In config, the value of the :rpcs key " "must be a map. Got `" rpcs "`.") config))) (u/check-rpcs rpcs))) (defn on-disconnect [*conn-id->info *branch->info temp-storage tube-conn code reason conn-count] (ca/go (let [conn-id (when tube-conn (tc/get-conn-id tube-conn))] (try (let [conn-info (@*conn-id->info conn-id) {:keys [branch subject-id temp-branch?]} conn-info] (swap! *conn-id->info dissoc conn-id) (swap! *branch->info update branch (fn [info] (-> info (update :conn-ids disj conn-id) (update :subject-id->conn-ids dissoc subject-id)))) (when temp-branch? (au/<? (<delete-branch* branch temp-storage)))) (catch Throwable e (log/error (str "Error in on-disconnect (conn-id: " conn-id ")\n" (u/ex-msg-and-stacktrace e)))))))) (defn <get-subject-id-for-identifier* [vivo-server identifier metadata] (let [{:keys [branch]} (@(:*conn-id->info vivo-server) (:conn-id metadata))] (<get-subject-id-for-identifier vivo-server identifier branch))) (defn set-handlers! [vivo-server vc-ep admin-ep] (ep/set-handler admin-ep :create-branch (partial <create-branch vivo-server)) (ep/set-handler admin-ep :delete-branch (partial <delete-branch vivo-server)) (ep/set-handler admin-ep :get-db-id-for-branch (fn [arg metadata] (<get-db-id vivo-server arg))) (ep/set-handler vc-ep :add-subject (partial <add-subject vivo-server)) (ep/set-handler vc-ep :add-subject-identifier (partial <add-subject-identifier vivo-server)) (ep/set-handler vc-ep :change-secret (partial <change-secret vivo-server)) (ep/set-handler vc-ep :get-schema-pcf (partial <get-schema-pcf vivo-server)) (ep/set-handler vc-ep :get-subject-id-for-identifier (partial <get-subject-id-for-identifier* vivo-server)) (ep/set-handler vc-ep :get-state (partial <get-state vivo-server)) (ep/set-handler vc-ep :log-in (partial <log-in vivo-server)) (ep/set-handler vc-ep :log-in-w-token (partial <log-in-w-token vivo-server)) (ep/set-handler vc-ep :log-out (partial <log-out vivo-server)) (ep/set-handler vc-ep :log-out-w-token (partial <log-out-w-token vivo-server)) (ep/set-handler vc-ep :publish-msg (partial publish-msg vivo-server)) (ep/set-handler vc-ep :remove-subject-identifier (partial <remove-subject-identifier vivo-server)) (ep/set-handler vc-ep :request-db-changed-msg (partial <handle-request-db-changed-msg vivo-server)) (ep/set-handler vc-ep :rpc (partial <rpc vivo-server)) (ep/set-handler vc-ep :set-state-source (partial <set-state-source vivo-server)) (ep/set-handler vc-ep :store-schema-pcf (partial <store-schema-pcf vivo-server)) (ep/set-handler vc-ep :update-state (partial <update-state vivo-server))) (defn vivo-server [config] (when-not (map? config) (throw (ex-info (str "`config` argument must be a map. Got: `" config "`.") (u/sym-map config)))) (let [config* (merge default-config config) _ (check-config config*) {:keys [additional-endpoints authenticate-admin-client authorization-fn certificate-str disable-ddb? handle-http http-timeout-ms login-identifier-case-sensitive? login-lifetime-mins port private-key-str redaction-fn repository-name rpcs state-schema]} config* perm-storage (data-storage/data-storage (data-block-storage/data-block-storage (if disable-ddb? (mem-block-storage/mem-block-storage false) (au/<?? (ddb-block-storage/<ddb-block-storage repository-name))))) temp-storage (data-storage/data-storage (data-block-storage/data-block-storage (mem-block-storage/mem-block-storage true))) modify-q (ConcurrentLinkedQueue.) path->schema-cache (sr/stockroom 1000) *conn-id->info (atom {}) *branch->info (atom {}) *rpc->handler (atom {}) vc-ep-opts {:on-disconnect (partial on-disconnect *conn-id->info *branch->info temp-storage)} vc-ep (ep/endpoint "vivo-client" (constantly true) u/client-server-protocol :server vc-ep-opts) admin-ep (ep/endpoint "admin-client" authenticate-admin-client u/admin-client-server-protocol :server) cs-opts (u/sym-map handle-http http-timeout-ms certificate-str private-key-str) stop-server (cs/server (conj additional-endpoints vc-ep admin-ep) port cs-opts) vivo-server (->VivoServer authorization-fn login-identifier-case-sensitive? login-lifetime-mins modify-q path->schema-cache perm-storage (or rpcs {}) vc-ep redaction-fn repository-name state-schema stop-server temp-storage *conn-id->info *branch->info *rpc->handler)] (au/<?? (<store-schema-pcf vivo-server (l/pcf state-schema) nil)) (start-modify-db-loop modify-q redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info) (set-handlers! vivo-server vc-ep admin-ep) (log/info (str "Vivo server started on port " port ".")) vivo-server))
121476
(ns com.dept24c.vivo.server (:require [clojure.core.async :as ca] [clojure.string :as str] [cognitect.aws.client.api :as aws] [cognitect.aws.client.api.async :as aws-async] [com.dept24c.vivo.bristlecone.block-ids :as block-ids] [com.dept24c.vivo.bristlecone.data-block-storage :as data-block-storage] [com.dept24c.vivo.bristlecone.data-storage :as data-storage] [com.dept24c.vivo.bristlecone.ddb-block-storage :as ddb-block-storage] [com.dept24c.vivo.bristlecone.mem-block-storage :as mem-block-storage] [com.dept24c.vivo.commands :as commands] [com.dept24c.vivo.utils :as u] [crypto.password.bcrypt :as bcrypt] [deercreeklabs.async-utils :as au] [deercreeklabs.baracus :as ba] [deercreeklabs.capsule.endpoint :as ep] [deercreeklabs.capsule.logging :as log] [deercreeklabs.capsule.server :as cs] [deercreeklabs.lancaster :as l] [deercreeklabs.tube.connection :as tc] [deercreeklabs.stockroom :as sr]) (:import (clojure.lang ExceptionInfo) (java.security SecureRandom) (java.util UUID) (java.util.concurrent ConcurrentLinkedQueue))) (set! *warn-on-reflection* true) (def work-factor 12) (defprotocol IVivoServer (<add-subject [this arg metadata]) (<add-subject* [this identifier secret subject-id branch conn-id]) (<add-subject-identifier [this arg metadata]) (<change-secret [this arg metadata]) (<change-secret* [this branch subject-id old-secret new-secret]) (<create-branch [this arg metadata]) (<delete-branch [this branch metadata]) (<fp->schema [this fp conn-id]) (<get-all-branches [this]) (<get-db-id [this branch]) (<get-db-info [this branch]) (<get-in [this db-id path]) (<get-log [this branch limit]) (<get-num-commits [this branch]) (<get-schema-pcf [this arg metadata]) (<get-state [this arg metadata]) (<get-state-and-expanded-path [this db-id path]) (<get-subject-id-for-identifier [this identifier branch]) (<log-in [this arg metadata]) (<log-in* [this identifier secret minutes-valid conn-id branch]) (<log-in-w-token [this arg metadata]) (<log-out [this arg metadata]) (<log-out-w-token [this token metadata]) (<modify-db! [this <update-fn msg subject-id branch conn-id]) (<remove-subject-identifier [this identifier metadata]) (<handle-request-db-changed-msg [this arg metadata]) (<rpc [this arg metadata]) (<set-state-source [this arg metadata]) (<store-schema-pcf [this arg metadata]) (<update-db [this update-cmds msg subject-id branch]) (<update-state [this arg metadata]) (<scmds->cmds [this scmds conn-id]) (get-storage [this branch-or-db-id]) (publish-msg [this arg metadata]) (set-rpc-handler! [this rpc-name-kw handler]) (shutdown! [this])) (defn generate-token [] (let [rng (SecureRandom.) bytes (byte-array 32)] (.nextBytes rng bytes) (ba/byte-array->b64 bytes))) (defn branch->reference [branch] (str u/branch-reference-root branch)) (defn throw-branch-name-too-long [branch] (throw (ex-info (str "Branch names must be " u/max-branch-name-len " characters or less. " "Branch " branch " is " (count branch) " characters.") (u/sym-map branch)))) (defn <update-storage [data-id schema update-commands prefix branch temp-storage perm-storage] ;; TODO: Support structural sharing (when data-id ;; Allow nil for creating a new data item (u/check-data-id data-id)) (au/go (let [dest-storage (if (str/starts-with? branch "-") temp-storage perm-storage) old-state (when data-id (let [src-storage (if (str/starts-with? data-id "-") temp-storage perm-storage)] (au/<? (data-storage/<read-data src-storage data-id schema)))) uc-ret (reduce (fn [{:keys [state] :as acc} cmd] (let [ret (commands/eval-cmd state cmd prefix)] (-> acc (assoc :state (:state ret)) (update :update-infos conj (:update-info ret))))) {:state old-state :update-infos []} update-commands) {:keys [update-infos state]} uc-ret new-data-id (au/<? (data-storage/<write-data dest-storage schema state))] (u/sym-map new-data-id update-infos state)))) (defn <add-subject-update-fn [requested-subject-id identifier hashed-secret dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id subject-id-to-hashed-secret-data-id]} dbi new-dbi (assoc dbi :subject-id-to-hashed-secret-data-id (:new-data-id (au/<? (<update-storage subject-id-to-hashed-secret-data-id u/string-map-schema [{:path [requested-subject-id] :op :set :arg hashed-secret}] nil branch temp-storage perm-storage))) :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :set :arg requested-subject-id}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <add-subject-identifier-update-fn [identifier dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id]} dbi new-dbi (assoc dbi :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :set :arg subject-id}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <remove-subject-identifier-update-fn [identifier dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id]} dbi new-dbi (assoc dbi :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :remove}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <change-secret-update-fn [hashed-secret dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [subject-id-to-hashed-secret-data-id subject-id-to-tokens-data-id token-to-token-info-data-id]} dbi dbi* (assoc dbi :subject-id-to-hashed-secret-data-id (:new-data-id (au/<? (<update-storage subject-id-to-hashed-secret-data-id u/string-map-schema [{:path [subject-id] :op :set :arg hashed-secret}] nil branch temp-storage perm-storage)))) src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) ;; Invalidate existing tokens for this user tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) ;; Use loop here to stay in go block new-dbi (loop [new-dbi dbi* [token & more] tokens] (let [new-dbi* (assoc new-dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))))] (if (seq more) (recur new-dbi* more) new-dbi*)))] {:dbi new-dbi :update-infos []}))) (defn <log-in-update-fn [token token-info dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi new-dbi (assoc dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :set :arg token-info}] nil branch temp-storage perm-storage))) :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id -1] :op :insert-after :arg token}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <log-out-update-fn [dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi dbi* (assoc dbi :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id] :op :remove}] nil branch temp-storage perm-storage)))) src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) ;; Use loop here to stay in go block new-dbi (loop [new-dbi dbi* [token & more] tokens] (let [new-dbi* (assoc new-dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))))] (if (seq more) (recur new-dbi* more) new-dbi*)))] {:dbi new-dbi :update-infos []}))) (defn <delete-token-update-fn [token dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) new-tokens (remove #(= token %) tokens) new-dbi (assoc dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))) ;; TODO: Improve this when `find` is implemented :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id] :op :set :arg new-tokens}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <update-state-update-fn [state-schema update-cmds dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [data-id]} dbi ret (au/<? (<update-storage data-id state-schema update-cmds :sys branch temp-storage perm-storage)) {:keys [new-data-id update-infos state]} ret] {:dbi (assoc dbi :data-id new-data-id) :update-infos update-infos :update-state-rpc? true :state state}))) (defn <delete-branch* [branch storage] (au/go (let [all-branches (au/<? (u/<get-in-reference storage u/all-branches-reference u/all-branches-schema nil nil)) new-branches (or (-> (set all-branches) (disj branch) (seq)) []) branch-reference (branch->reference branch)] ;; TODO: Improve this when `find` is implemented (au/<? (u/<update-reference! storage u/all-branches-reference u/all-branches-schema [{:path nil :op :set :arg new-branches}] nil)) (au/<? (u/<delete-reference! storage branch-reference)) true))) (defn notify-conns! [update-state-rpc? update-infos conn-id conn-ids db-id prev-db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info] ;; For update-state, notify all conns except the originator, ;; who gets the information sent to them directly. ;; This allows local+sys updates to be atomic. (let [conn-ids* (if update-state-rpc? (disj (set conn-ids) conn-id) conn-ids)] (ca/go (try (doseq [conn-id* conn-ids*] (let [{:keys [subject-id]} (@*conn-id->info conn-id*) new-state (when whole-state (redaction-fn subject-id whole-state)) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (when whole-state (l/serialize state-schema new-state)) serialized-state (when whole-state (u/sym-map fp bytes)) info (u/sym-map db-id prev-db-id serialized-state subject-id update-infos)] (ep/send-msg vc-ep conn-id* :db-changed info))) (catch Exception e (log/error (str "Error in notify-conns!:\n" (u/ex-msg-and-stacktrace e)))))))) (defn <modify-db!* [branch conn-id subject-id <update-fn msg redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info] (au/go (let [num-tries 10 {:keys [conn-ids]} (@*branch->info branch) branch-reference (branch->reference branch) dest-storage (if (str/starts-with? branch "-") temp-storage perm-storage)] ;; Use loop to stay in go block (loop [num-tries-left (dec num-tries)] (let [prev-db-id (au/<? (u/<get-data-id dest-storage branch-reference)) src-storage (cond (nil? prev-db-id) nil (str/starts-with? prev-db-id "-") temp-storage :else perm-storage) prev-dbi (when src-storage (au/<? (u/<get-in src-storage prev-db-id u/db-info-schema nil nil))) {:keys [num-prev-dbs data-id]} prev-dbi uf-ret (au/<? (<update-fn prev-dbi subject-id branch temp-storage perm-storage)) {:keys [dbi update-infos update-state-rpc?]} uf-ret new-dbi (assoc dbi :msg msg :timestamp-ms (u/current-time-ms) :num-prev-dbs (if num-prev-dbs (inc num-prev-dbs) 0) :prev-db-id prev-db-id) update-ret (au/<? (<update-storage prev-db-id u/db-info-schema [{:path [] :op :set :arg new-dbi}] nil branch temp-storage perm-storage)) new-db-id (:new-data-id update-ret) whole-state (:state uf-ret)] (if (au/<? (u/<compare-and-set! dest-storage branch-reference l/string-schema prev-db-id new-db-id)) (do (notify-conns! update-state-rpc? update-infos conn-id conn-ids new-db-id prev-db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info) (u/sym-map new-db-id prev-db-id whole-state update-infos)) (if (zero? num-tries-left) (throw (ex-info (str "Failed to commit to branch `" branch-reference "` after " num-tries " tries.") (u/sym-map branch-reference num-tries))) (do (au/<? (ca/timeout (rand-int 100))) (recur (dec num-tries-left)))))))))) (defn start-modify-db-loop [^ConcurrentLinkedQueue q redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info] (ca/go (while true (try (if-let [info (.poll q)] (let [{:keys [cb branch conn-id subject-id <update-fn msg]} info] (try (cb (au/<? (<modify-db!* branch conn-id subject-id <update-fn msg redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info))) (catch Exception e (cb e)))) (ca/<! (ca/timeout 5))) (catch Exception e (log/error (str "Unexpected error in txn-loop:\n" (u/ex-msg-and-stacktrace e)))))))) (defn <ks-at-path [kw <get-at-path p full-path] (au/go (let [coll (au/<? (<get-at-path p))] (cond (map? coll) (keys coll) (sequential? coll) (range (count coll)) (nil? coll) [] :else (throw (ex-info (str "`" kw "` is in path, but there is not " "a collection at " p ".") {:full-path full-path :missing-collection-path p :value coll})))))) (defn <count-at-path [<get-at-path p full-path] (au/go (let [coll (au/<? (<get-at-path p))] (cond (or (map? coll) (sequential? coll)) (count coll) (nil? coll) 0 :else (throw (ex-info (str "`:vivo/count` terminates path, but " "there is not a collection at " p ".") {:full-path full-path :missing-collection-path p :value coll})))))) (defn <do-concat [<get-at-path p full-path] (au/go (let [seqs (au/<? (<get-at-path p))] (when (and (not (nil? seqs)) (or (not (sequential? seqs)) (not (sequential? (first seqs))))) (throw (ex-info (str "`:vivo/concat` terminates path, but there " "is not a sequence of sequences at " p ".") {:full-path full-path :missing-collection-path p :value seqs}))) (apply concat seqs)))) (defn <do-login [vs conn-id branch identifier secret login-identifier-case-sensitive? login-lifetime-mins *conn-id->info *branch->info] (au/go (u/check-secret-len secret) (let [identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) db-info (au/<? (<get-db-info vs branch)) {id->sid-data-id :identifier-to-subject-id-data-id sid->hs-data-id :subject-id-to-hashed-secret-data-id} db-info subject-id (when id->sid-data-id (let [src-storage (get-storage vs id->sid-data-id)] (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier*] nil)))) hashed-secret (when (and subject-id sid->hs-data-id) (let [src-storage (get-storage vs sid->hs-data-id)] (au/<? (u/<get-in src-storage sid->hs-data-id u/string-map-schema [subject-id] nil))))] (if-not (and hashed-secret (bcrypt/check secret hashed-secret)) {:subject-id nil :token nil} (let [token (generate-token) expiration-time-mins (+ (u/ms->mins (u/current-time-ms)) login-lifetime-mins) token-info (u/sym-map expiration-time-mins subject-id) _ (when conn-id (swap! *conn-id->info update conn-id assoc :subject-id subject-id) (swap! *branch->info update branch update :subject-id->conn-ids update subject-id (fn [conn-ids] (conj (or conn-ids #{}) conn-id)))) ret (au/<? (<modify-db! vs (partial <log-in-update-fn token token-info) "Log in" subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id subject-id :token token}))))) (defn <log-out-subject! [vs subject-id branch *branch->info *conn-id->info] (au/go (let [conn-ids (some-> (@*branch->info branch) (:subject-id->conn-ids) (get subject-id))] (swap! *branch->info update branch update :subject-id->conn-ids dissoc subject-id) (doseq [conn-id conn-ids] (swap! *conn-id->info update conn-id dissoc :subject-id) (au/<? (<modify-db! vs <log-out-update-fn "Log out" subject-id branch nil))) true))) (defn <do-add-subject [vs identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?] (au/go (u/check-secret-len secret) (let [hashed-secret (bcrypt/encrypt secret work-factor) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) ret (au/<? (<modify-db! vs (partial <add-subject-update-fn subject-id identifier* hashed-secret) (str "Add subject " subject-id) subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id subject-id}))) (defn <do-change-secret! [vs branch subject-id old-secret new-secret] (au/go (u/check-secret-len old-secret) (u/check-secret-len new-secret) (let [branch-reference (branch->reference branch) storage (get-storage vs branch) db-id (au/<? (u/<get-data-id storage branch-reference)) db-info (au/<? (u/<get-in storage db-id u/db-info-schema nil nil)) {sid->hs-data-id :subject-id-to-hashed-secret-data-id} db-info hashed-old-secret (when (and subject-id old-secret) (au/<? (u/<get-in storage sid->hs-data-id u/string-map-schema [subject-id] nil))) old-secret-ok? (if-not hashed-old-secret true (bcrypt/check old-secret hashed-old-secret))] (if-not old-secret-ok? false (let [hashed-new-secret (bcrypt/encrypt new-secret work-factor)] (-> (au/<? (<modify-db! vs (partial <change-secret-update-fn hashed-new-secret) "Change secret" subject-id branch nil)) :new-db-id)))))) (defn <do-update-state [vs arg metadata authorization-fn redaction-fn state-schema perm-storage *conn-id->info] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) update-cmds (au/<? (<scmds->cmds vs arg conn-id)) all-authed? (if (empty? update-cmds) true (loop [i 0] ; Use loop to stay in same go block (let [{:keys [path arg]} (nth update-cmds i) auth-ret (authorization-fn subject-id path :write arg) authed? (if (au/channel? auth-ret) (au/<? auth-ret) auth-ret) new-i (inc i)] (cond (not authed?) false (= (count update-cmds) new-i) true :else (recur new-i)))))] (if-not all-authed? :vivo/unauthorized (let [ret (au/<? (<modify-db! vs (partial <update-state-update-fn state-schema update-cmds) "Update state" subject-id branch conn-id)) {:keys [new-db-id prev-db-id whole-state update-infos]} ret state (redaction-fn subject-id whole-state) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (l/serialize state-schema state) serialized-state (u/sym-map fp bytes)] {:db-id new-db-id :prev-db-id prev-db-id :serialized-state serialized-state :update-infos update-infos}))))) (defn <log-in-w-token* [vivo-server state-schema redaction-fn vc-ep perm-storage token metadata *conn-id->info] (au/go (let [{:keys [conn-id]} metadata {:keys [*conn-id->info *branch->info]} vivo-server {:keys [branch]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info vivo-server branch)) {:keys [token-to-token-info-data-id db-id]} db-info info (when token-to-token-info-data-id (let [src-storage (get-storage vivo-server token-to-token-info-data-id)] (au/<? (u/<get-in src-storage token-to-token-info-data-id u/token-map-schema [token] nil)))) {:keys [expiration-time-mins subject-id]} info now-mins (-> (u/current-time-ms) (u/ms->mins))] (when info (if (>= now-mins expiration-time-mins) (let [ret (au/<? (<modify-db! vivo-server (partial <delete-token-update-fn token) "Delete expired token" subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id nil :token nil}) (do (swap! *conn-id->info update conn-id assoc :subject-id subject-id) (swap! *branch->info update branch update :subject-id->conn-ids update subject-id (fn [conn-ids] (conj (or conn-ids #{}) conn-id))) ;; When subject-id changes but not the db, we need to send a new db ;; with the results of the redaction-fn. db-id doesn't change. (let [update-infos [{:norm-path [:sys] :op :set} {:norm-path [:vivo/subject-id] :op :set}] db-id (au/<? (<get-db-id vivo-server branch)) whole-state (first (au/<? (<get-state-and-expanded-path vivo-server db-id [:sys])))] (notify-conns! false update-infos conn-id [conn-id] db-id db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info) (u/sym-map db-id subject-id token)))))))) (defn <set-state-source* [vivo-server source metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [perm-storage state-schema *branch->info *conn-id->info]} vivo-server perm-branch (:branch/name source) branch (if perm-branch (let [branch-reference (branch->reference perm-branch) storage (get-storage vivo-server perm-branch)] (when-not (au/<? (u/<get-data-id storage branch-reference)) (au/<? (<create-branch vivo-server {:branch perm-branch :db-id nil} metadata))) perm-branch) (let [branch* (str "-temp-branch-" (rand-int 1e9))] (au/<? (<create-branch vivo-server {:branch branch* :db-id (:temp-branch/db-id source)} metadata)) branch*))] (swap! *conn-id->info update conn-id assoc :branch branch :temp-branch? (not perm-branch)) (swap! *branch->info update branch (fn [{:keys [conn-ids] :as info}] (if conn-ids (update info :conn-ids conj conn-id) (assoc info :conn-ids #{conn-id})))) true))) (defn publish-msg* [vc-ep *conn-id->info arg metadata] (let [{:keys [conn-id]} metadata conn-ids (keys @*conn-id->info)] (doseq [conn-id* (disj (set conn-ids) conn-id)] (ep/send-msg vc-ep conn-id* :publish-msg arg)) true)) (defrecord VivoServer [authorization-fn login-identifier-case-sensitive? login-lifetime-mins modify-q path->schema-cache perm-storage rpcs vc-ep redaction-fn repository-name state-schema stop-server temp-storage *conn-id->info *branch->info *rpc->handler] IVivoServer (<modify-db! [this <update-fn msg subject-id branch conn-id] (au/go (let [modify-ch (ca/chan) cb #(ca/put! modify-ch %) update-info (u/sym-map cb branch conn-id subject-id <update-fn msg) _ (.add ^ConcurrentLinkedQueue modify-q update-info) change-info (au/<? modify-ch)] change-info))) (<get-db-info [this branch] (au/go (let [branch-reference (branch->reference branch) dest-storage (get-storage this branch) db-id (au/<? (u/<get-data-id dest-storage branch-reference)) src-storage (get-storage this db-id)] (-> (u/<get-in src-storage db-id u/db-info-schema nil nil) (au/<?) (assoc :db-id db-id))))) (<add-subject [this arg metadata] (let [{:keys [identifier secret subject-id] :or {subject-id (.toString ^UUID (UUID/randomUUID))}} arg {:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id)] (u/check-secret-len secret) (<do-add-subject this identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?))) (<add-subject* [this identifier secret subject-id branch conn-id] (<do-add-subject this identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?)) (<add-subject-identifier [this identifier metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier))] (if-not subject-id false ;; Must be logged in (-> (au/<? (<modify-db! this (partial <add-subject-identifier-update-fn identifier*) (str "Add subject indentifier `" identifier*) subject-id branch conn-id)) :new-db-id))))) (<remove-subject-identifier [this identifier metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info this branch)) id->sid-data-id (:identifier-to-subject-id-data-id db-info) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) src-storage (get-storage this id->sid-data-id) id-subject-id (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier*] nil)) my-identifier? (and subject-id (= subject-id id-subject-id))] (if-not my-identifier? false (-> (<modify-db! this (partial <remove-subject-identifier-update-fn identifier*) (str "Remove subject indentifier `" identifier*) subject-id branch conn-id) (au/<?) (:new-db-id)))))) (<change-secret* [this branch subject-id old-secret new-secret] (<do-change-secret! this branch subject-id old-secret new-secret)) (<change-secret [this arg metadata] (let [{:keys [old-secret new-secret]} arg {:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id)] (<change-secret* this branch subject-id old-secret new-secret))) (<create-branch [this arg metadata] (au/go (let [{:keys [branch db-id]} arg {:keys [subject-id]} metadata _ (when (empty? branch) (throw (ex-info "Branch name is nil or empty." arg))) _ (when (> (count branch) u/max-branch-name-len) (throw-branch-name-too-long branch)) temp-dest? (str/starts-with? branch "-") src-storage (get-storage this db-id) dest-storage (get-storage this branch) temp-src? (and db-id (block-ids/temp-block-id? db-id)) branch-reference (branch->reference branch) _ (when (and db-id (not (try (au/<? (u/<get-in src-storage db-id u/db-info-schema [:data-id] nil)) (catch ExceptionInfo e (if (re-find #"not match given writer schema" (ex-message e)) false (throw e)))))) (throw (ex-info (str "Source db-id `" db-id "` does not exist.") arg))) _ (when (and temp-src? (not temp-dest?)) (throw (ex-info (str "Cannot create a permanent branch from a " "temporary db-id.") (u/sym-map branch db-id temp-dest?)))) _ (when (au/<? (u/<get-data-id dest-storage branch-reference)) (throw (ex-info (str "A branch named `" branch "` already " "exists in the repository.") (u/sym-map branch db-id temp-dest?)))) _ (au/<? (u/<update-reference! dest-storage u/all-branches-reference u/all-branches-schema [{:path [-1] :op :insert-after :arg branch}] nil)) db-id* (or db-id (let [create-db-ch (ca/chan) cb #(ca/put! create-db-ch %) default-data (l/default-data state-schema) update-cmds [{:path [:sys] :op :set :arg default-data}] <update-fn (partial <update-state-update-fn state-schema update-cmds) msg "Create initial db for branch" create-info (u/sym-map cb branch subject-id <update-fn msg)] (.add ^ConcurrentLinkedQueue modify-q create-info) (:new-db-id (au/<? create-db-ch))))] (au/<? (u/<set-reference! dest-storage branch-reference db-id*))))) (<delete-branch [this branch metadata] (<delete-branch* branch (get-storage this branch))) (<fp->schema [this fp conn-id] (au/go (or (au/<? (u/<fp->schema perm-storage fp)) (let [pcf (au/<? (ep/<send-msg vc-ep conn-id :get-schema-pcf fp))] (l/json->schema pcf))))) ;; TODO: Fix <get-all-branches to use a scan. ;; Get rid of all-branches-reference (<get-all-branches [this] (au/go (let [perm-branches (au/<? (u/<get-in-reference perm-storage u/all-branches-reference u/all-branches-schema nil nil)) temp-branches (au/<? (u/<get-in-reference temp-storage u/all-branches-reference u/all-branches-schema nil nil)) all-branches (concat perm-branches temp-branches)] (seq all-branches)))) (<get-db-id [this branch] (let [storage (get-storage this branch) branch-reference (branch->reference branch)] (u/<get-data-id storage branch-reference))) (<get-in [this db-id path] (au/go (let [state-and-path (au/<? (<get-state-and-expanded-path this db-id path))] (first state-and-path)))) (<get-state-and-expanded-path [this db-id path] (au/go (when-not (string? db-id) (throw (ex-info (str "Bad db-id `" db-id "`. db-id must be a string.") {:db-id db-id}))) (when (and path (not (sequential? path))) (throw (ex-info (str "Bad path `" path "`. Path must be nil or a sequence.") {:path path}))) (let [path (or path [:sys]) db-id-storage (get-storage this db-id) data-id (au/<? (u/<get-in db-id-storage db-id u/db-info-schema [:data-id] nil)) data-id-storage (get-storage this data-id) <get-at-path #(u/<get-in data-id-storage data-id state-schema % :sys) last-path-k (last path) join? (u/has-join? path) term-kw? (u/terminal-kw-ops last-path-k)] (cond (or (not data-id) (u/empty-sequence-in-path? path)) [nil [path]] (and (not term-kw?) (not join?)) (let [val (au/<? (<get-at-path path))] [val [path]]) (and term-kw? (not join?)) (let [path* (butlast path) val (case last-path-k :vivo/keys (au/<? (<ks-at-path :vivo/keys <get-at-path path* path)) :vivo/count (au/<? (<count-at-path <get-at-path path* path)) :vivo/concat (au/<? (<do-concat <get-at-path path* path)))] [val [path]]) (and (not term-kw?) join?) (when-not (u/empty-sequence-in-path? path) (let [expanded-path (au/<? (u/<expand-path #(<ks-at-path :vivo/* <get-at-path % path) path)) num-results (count expanded-path)] (if (zero? num-results) [[] []] ;; Use loop to stay in the go block (loop [out [] i 0] (let [filled-in-path (nth expanded-path i) v (au/<? (u/<get-in data-id-storage data-id state-schema filled-in-path :sys)) new-out (conj out v) new-i (inc i)] (if (= num-results new-i) [new-out expanded-path] (recur new-out new-i))))))) (and term-kw? join?) (let [expanded-path (au/<? (u/<expand-path #(<ks-at-path :vivo/* <get-at-path % path) (butlast path))) num-results (count expanded-path)] (if (zero? num-results) [[] []] (let [results (loop [out [] i 0] (let [filled-in-path (nth expanded-path i) v (au/<? (u/<get-in data-id-storage data-id state-schema filled-in-path :sys)) new-out (conj out v) new-i (inc i)] (if (= num-results new-i) new-out (recur new-out new-i)))) value (case last-path-k :vivo/keys (range (count results)) :vivo/count (count results) :vivo/concat (apply concat results))] [value expanded-path]))))))) (<get-log [this branch limit] (au/go (let [storage (get-storage this branch) db-id (au/<? (<get-db-id this branch)) dbi (au/<? (u/<get-in storage db-id u/db-info-schema nil nil)) make-log-rec #(select-keys % [:msg :timestamp-ms])] (when dbi (loop [out [(make-log-rec dbi)] i 1] (let [{:keys [prev-db-id]} (peek out)] (if (or (not prev-db-id) (= limit i)) out (let [prev-dbi (au/<? (u/<get-in storage prev-db-id u/db-info-schema nil nil))] (recur (conj out (make-log-rec dbi)) (inc i)))))))))) (<get-num-commits [this branch] (au/go (let [storage (get-storage this branch) db-id (au/<? (<get-db-id this branch)) dbi (au/<? (u/<get-in storage db-id u/db-info-schema nil nil))] (if dbi (inc (:num-prev-dbs dbi)) 0)))) (<get-state [this arg metadata] ;; TODO: Figure this out for non-locally-cached state lookups ;; Figure out how to unify authorization-fn and redaction-fn #_ (au/go (let [{:keys [path db-id]} arg {:keys [conn-id]} metadata {:keys [subject-id]} (@*conn-id->info conn-id) [v xp] (au/<? (<get-state-and-expanded-path this db-id path)) authorized? (let [ret (authorization-fn subject-id path :read v)] (if (au/channel? ret) (au/<? ret) ret))] (if (or (not authorized?) (= :vivo/unauthorized v)) :vivo/unauthorized (when v (let [schema-path (rest path) ; Ignore :sys schema (u/path->schema path->schema-cache state-schema schema-path) fp (when schema (au/<? (u/<schema->fp perm-storage schema)))] (when schema {:serialized-value {:fp fp :bytes (l/serialize schema v)} :expanded-path xp}))))))) (<get-subject-id-for-identifier [this identifier branch] (au/go (let [db-info (au/<? (<get-db-info this branch)) id->sid-data-id (:identifier-to-subject-id-data-id db-info) src-storage (get-storage this id->sid-data-id)] (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier] nil))))) (<log-in* [this identifier secret minutes-valid conn-id branch] (<do-login this conn-id branch identifier secret login-identifier-case-sensitive? minutes-valid *conn-id->info *branch->info)) (<log-in [this arg metadata] (let [{:keys [identifier secret]} arg {:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id)] (<log-in* this identifier secret login-lifetime-mins conn-id branch))) (<log-in-w-token [this token metadata] (<log-in-w-token* this state-schema redaction-fn vc-ep perm-storage token metadata *conn-id->info)) (<log-out [this arg metadata] (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id)] (<log-out-subject! this subject-id branch *branch->info *conn-id->info))) (<log-out-w-token [this token metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info this branch)) {:keys [token-<KEY>]} db-info src-storage (get-storage this token-to-token-info-data-id) info (when token-to-token-info-data-id (au/<? (u/<get-in src-storage token-to-token-info-data-id u/token-map-schema [token] nil)))] (if-not info false (let [{:keys [subject-id]} info] (au/<? (<log-out-subject! this subject-id branch *branch->info *conn-id->info))))))) (<set-state-source [this source metadata] (<set-state-source* this source metadata)) (<rpc [this msg-arg metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) db-id (au/<? (<get-db-id this branch)) {:keys [rpc-name-kw-ns rpc-name-kw-name arg]} msg-arg rpc-name-kw (keyword rpc-name-kw-ns rpc-name-kw-name) rpc-info (rpcs rpc-name-kw) _ (when-not rpc-info (throw (ex-info (str "No RPC with name `" rpc-name-kw "` is registered. " "Either this is a typo or you need to add `" rpc-name-kw "` to the :rpcs map when " "creating the Vivo server.") {:known-rpcs (keys rpcs) :given-rpc rpc-name-kw}))) handler (@*rpc->handler rpc-name-kw) _ (when-not handler (throw (ex-info (str "No RPC handler for `" rpc-name-kw "` is registered. " "Call `set-rpc-handler!` on the server instance to " "set an RPC handler.") {:known-rpcs (keys rpcs) :given-rpc rpc-name-kw}))) {:keys [arg-schema ret-schema]} rpc-info {:keys [fp bytes]} arg w-schema (au/<? (<fp->schema this fp conn-id)) rpc-arg (l/deserialize arg-schema w-schema bytes) authorized? (let [path [:vivo/rpcs rpc-name-kw] ret (authorization-fn subject-id path :call rpc-arg)] (if (au/channel? ret) (au/<? ret) ret))] (if-not authorized? :vivo/unauthorized (let [rpc-metadata (assoc (u/sym-map conn-id subject-id branch db-id repository-name) :vivo-server this) ret* (handler rpc-arg rpc-metadata) ret (if (au/channel? ret*) (au/<? ret*) ret*)] {:fp (au/<? (u/<schema->fp perm-storage ret-schema)) :bytes (l/serialize ret-schema ret)}))))) (<handle-request-db-changed-msg [this arg metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) db-id (au/<? (<get-db-id this branch)) [whole-state xp] (au/<? (<get-state-and-expanded-path this db-id [:sys])) new-state (when whole-state (redaction-fn subject-id whole-state)) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (when new-state (l/serialize state-schema new-state)) serialized-state (u/sym-map fp bytes) info (-> (u/sym-map db-id serialized-state subject-id) (assoc :prev-db-id db-id) (assoc :update-infos []))] (ep/send-msg vc-ep conn-id :db-changed info)))) (<scmds->cmds [this scmds conn-id] (au/go (if-not (seq scmds) [] ;; Use loop/recur to stay in single go block (loop [scmd (first scmds) i 0 out []] (let [{:keys [path arg]} scmd arg-sch (u/path->schema path->schema-cache state-schema (rest path)) ; Ignore :sys new-i (inc i) last? (= (count scmds) new-i)] (if-not arg-sch ; Skip cmd if we don't have schema (evolution) (if last? out (recur (nth scmds new-i) new-i out)) (let [writer-arg-sch (when arg (au/<? (<fp->schema this (:fp arg) conn-id))) arg* (when arg (l/deserialize arg-sch writer-arg-sch (:bytes arg))) cmd (cond-> scmd arg (assoc :arg arg*)) new-out (conj out cmd)] (if last? new-out (recur (nth scmds new-i) new-i new-out))))))))) (<update-db [this update-cmds msg subject-id branch] (<modify-db! this (partial <update-state-update-fn state-schema update-cmds) "Update db" subject-id branch nil)) (<update-state [this arg metadata] (<do-update-state this arg metadata authorization-fn redaction-fn state-schema perm-storage *conn-id->info)) (<get-schema-pcf [this fp metadata] (au/go (if-let [schema (au/<? (u/<fp->schema perm-storage fp))] (l/pcf schema) (do (log/error (str "Could not find PCF for fingerprint `" fp "`.")) nil)))) (<store-schema-pcf [this pcf metadata] (au/go (au/<? (u/<schema->fp perm-storage (l/json->schema pcf))) true)) (get-storage [this branch-or-db-id] (when branch-or-db-id (if (str/starts-with? branch-or-db-id "-") temp-storage perm-storage))) (set-rpc-handler! [this rpc-name-kw handler] (swap! *rpc->handler assoc rpc-name-kw handler)) (publish-msg [this arg metadata] (publish-msg* vc-ep *conn-id->info arg metadata)) (shutdown! [this] (stop-server))) (defn default-health-http-handler [req] (if (= "/health" (:uri req)) {:status 200 :headers {"content-type" "text/plain" "Access-Control-Allow-Origin" "*"} :body "I am healthy"} {:status 404 :body "I still haven't found what you're looking for..."})) (def default-config {:additional-endpoints [] :authenticate-admin-client (constantly false) :handle-http default-health-http-handler :http-timeout-ms 60000 :login-lifetime-mins (* 60 24 15) ;; 15 days :redaction-fn (fn [subject-id db] db)}) (defn check-config [config] (let [required-ks [:authorization-fn :port :repository-name :state-schema]] (doseq [k required-ks] (when-not (config k) (throw (ex-info (str "Missing " k " in config.") (u/sym-map k config)))))) (when-let [rpcs (:rpcs config)] (when-not (map? rpcs) (throw (ex-info (str "In config, the value of the :rpcs key " "must be a map. Got `" rpcs "`.") config))) (u/check-rpcs rpcs))) (defn on-disconnect [*conn-id->info *branch->info temp-storage tube-conn code reason conn-count] (ca/go (let [conn-id (when tube-conn (tc/get-conn-id tube-conn))] (try (let [conn-info (@*conn-id->info conn-id) {:keys [branch subject-id temp-branch?]} conn-info] (swap! *conn-id->info dissoc conn-id) (swap! *branch->info update branch (fn [info] (-> info (update :conn-ids disj conn-id) (update :subject-id->conn-ids dissoc subject-id)))) (when temp-branch? (au/<? (<delete-branch* branch temp-storage)))) (catch Throwable e (log/error (str "Error in on-disconnect (conn-id: " conn-id ")\n" (u/ex-msg-and-stacktrace e)))))))) (defn <get-subject-id-for-identifier* [vivo-server identifier metadata] (let [{:keys [branch]} (@(:*conn-id->info vivo-server) (:conn-id metadata))] (<get-subject-id-for-identifier vivo-server identifier branch))) (defn set-handlers! [vivo-server vc-ep admin-ep] (ep/set-handler admin-ep :create-branch (partial <create-branch vivo-server)) (ep/set-handler admin-ep :delete-branch (partial <delete-branch vivo-server)) (ep/set-handler admin-ep :get-db-id-for-branch (fn [arg metadata] (<get-db-id vivo-server arg))) (ep/set-handler vc-ep :add-subject (partial <add-subject vivo-server)) (ep/set-handler vc-ep :add-subject-identifier (partial <add-subject-identifier vivo-server)) (ep/set-handler vc-ep :change-secret (partial <change-secret vivo-server)) (ep/set-handler vc-ep :get-schema-pcf (partial <get-schema-pcf vivo-server)) (ep/set-handler vc-ep :get-subject-id-for-identifier (partial <get-subject-id-for-identifier* vivo-server)) (ep/set-handler vc-ep :get-state (partial <get-state vivo-server)) (ep/set-handler vc-ep :log-in (partial <log-in vivo-server)) (ep/set-handler vc-ep :log-in-w-token (partial <log-in-w-token vivo-server)) (ep/set-handler vc-ep :log-out (partial <log-out vivo-server)) (ep/set-handler vc-ep :log-out-w-token (partial <log-out-w-token vivo-server)) (ep/set-handler vc-ep :publish-msg (partial publish-msg vivo-server)) (ep/set-handler vc-ep :remove-subject-identifier (partial <remove-subject-identifier vivo-server)) (ep/set-handler vc-ep :request-db-changed-msg (partial <handle-request-db-changed-msg vivo-server)) (ep/set-handler vc-ep :rpc (partial <rpc vivo-server)) (ep/set-handler vc-ep :set-state-source (partial <set-state-source vivo-server)) (ep/set-handler vc-ep :store-schema-pcf (partial <store-schema-pcf vivo-server)) (ep/set-handler vc-ep :update-state (partial <update-state vivo-server))) (defn vivo-server [config] (when-not (map? config) (throw (ex-info (str "`config` argument must be a map. Got: `" config "`.") (u/sym-map config)))) (let [config* (merge default-config config) _ (check-config config*) {:keys [additional-endpoints authenticate-admin-client authorization-fn certificate-str disable-ddb? handle-http http-timeout-ms login-identifier-case-sensitive? login-lifetime-mins port private-key-str redaction-fn repository-name rpcs state-schema]} config* perm-storage (data-storage/data-storage (data-block-storage/data-block-storage (if disable-ddb? (mem-block-storage/mem-block-storage false) (au/<?? (ddb-block-storage/<ddb-block-storage repository-name))))) temp-storage (data-storage/data-storage (data-block-storage/data-block-storage (mem-block-storage/mem-block-storage true))) modify-q (ConcurrentLinkedQueue.) path->schema-cache (sr/stockroom 1000) *conn-id->info (atom {}) *branch->info (atom {}) *rpc->handler (atom {}) vc-ep-opts {:on-disconnect (partial on-disconnect *conn-id->info *branch->info temp-storage)} vc-ep (ep/endpoint "vivo-client" (constantly true) u/client-server-protocol :server vc-ep-opts) admin-ep (ep/endpoint "admin-client" authenticate-admin-client u/admin-client-server-protocol :server) cs-opts (u/sym-map handle-http http-timeout-ms certificate-str private-key-str) stop-server (cs/server (conj additional-endpoints vc-ep admin-ep) port cs-opts) vivo-server (->VivoServer authorization-fn login-identifier-case-sensitive? login-lifetime-mins modify-q path->schema-cache perm-storage (or rpcs {}) vc-ep redaction-fn repository-name state-schema stop-server temp-storage *conn-id->info *branch->info *rpc->handler)] (au/<?? (<store-schema-pcf vivo-server (l/pcf state-schema) nil)) (start-modify-db-loop modify-q redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info) (set-handlers! vivo-server vc-ep admin-ep) (log/info (str "Vivo server started on port " port ".")) vivo-server))
true
(ns com.dept24c.vivo.server (:require [clojure.core.async :as ca] [clojure.string :as str] [cognitect.aws.client.api :as aws] [cognitect.aws.client.api.async :as aws-async] [com.dept24c.vivo.bristlecone.block-ids :as block-ids] [com.dept24c.vivo.bristlecone.data-block-storage :as data-block-storage] [com.dept24c.vivo.bristlecone.data-storage :as data-storage] [com.dept24c.vivo.bristlecone.ddb-block-storage :as ddb-block-storage] [com.dept24c.vivo.bristlecone.mem-block-storage :as mem-block-storage] [com.dept24c.vivo.commands :as commands] [com.dept24c.vivo.utils :as u] [crypto.password.bcrypt :as bcrypt] [deercreeklabs.async-utils :as au] [deercreeklabs.baracus :as ba] [deercreeklabs.capsule.endpoint :as ep] [deercreeklabs.capsule.logging :as log] [deercreeklabs.capsule.server :as cs] [deercreeklabs.lancaster :as l] [deercreeklabs.tube.connection :as tc] [deercreeklabs.stockroom :as sr]) (:import (clojure.lang ExceptionInfo) (java.security SecureRandom) (java.util UUID) (java.util.concurrent ConcurrentLinkedQueue))) (set! *warn-on-reflection* true) (def work-factor 12) (defprotocol IVivoServer (<add-subject [this arg metadata]) (<add-subject* [this identifier secret subject-id branch conn-id]) (<add-subject-identifier [this arg metadata]) (<change-secret [this arg metadata]) (<change-secret* [this branch subject-id old-secret new-secret]) (<create-branch [this arg metadata]) (<delete-branch [this branch metadata]) (<fp->schema [this fp conn-id]) (<get-all-branches [this]) (<get-db-id [this branch]) (<get-db-info [this branch]) (<get-in [this db-id path]) (<get-log [this branch limit]) (<get-num-commits [this branch]) (<get-schema-pcf [this arg metadata]) (<get-state [this arg metadata]) (<get-state-and-expanded-path [this db-id path]) (<get-subject-id-for-identifier [this identifier branch]) (<log-in [this arg metadata]) (<log-in* [this identifier secret minutes-valid conn-id branch]) (<log-in-w-token [this arg metadata]) (<log-out [this arg metadata]) (<log-out-w-token [this token metadata]) (<modify-db! [this <update-fn msg subject-id branch conn-id]) (<remove-subject-identifier [this identifier metadata]) (<handle-request-db-changed-msg [this arg metadata]) (<rpc [this arg metadata]) (<set-state-source [this arg metadata]) (<store-schema-pcf [this arg metadata]) (<update-db [this update-cmds msg subject-id branch]) (<update-state [this arg metadata]) (<scmds->cmds [this scmds conn-id]) (get-storage [this branch-or-db-id]) (publish-msg [this arg metadata]) (set-rpc-handler! [this rpc-name-kw handler]) (shutdown! [this])) (defn generate-token [] (let [rng (SecureRandom.) bytes (byte-array 32)] (.nextBytes rng bytes) (ba/byte-array->b64 bytes))) (defn branch->reference [branch] (str u/branch-reference-root branch)) (defn throw-branch-name-too-long [branch] (throw (ex-info (str "Branch names must be " u/max-branch-name-len " characters or less. " "Branch " branch " is " (count branch) " characters.") (u/sym-map branch)))) (defn <update-storage [data-id schema update-commands prefix branch temp-storage perm-storage] ;; TODO: Support structural sharing (when data-id ;; Allow nil for creating a new data item (u/check-data-id data-id)) (au/go (let [dest-storage (if (str/starts-with? branch "-") temp-storage perm-storage) old-state (when data-id (let [src-storage (if (str/starts-with? data-id "-") temp-storage perm-storage)] (au/<? (data-storage/<read-data src-storage data-id schema)))) uc-ret (reduce (fn [{:keys [state] :as acc} cmd] (let [ret (commands/eval-cmd state cmd prefix)] (-> acc (assoc :state (:state ret)) (update :update-infos conj (:update-info ret))))) {:state old-state :update-infos []} update-commands) {:keys [update-infos state]} uc-ret new-data-id (au/<? (data-storage/<write-data dest-storage schema state))] (u/sym-map new-data-id update-infos state)))) (defn <add-subject-update-fn [requested-subject-id identifier hashed-secret dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id subject-id-to-hashed-secret-data-id]} dbi new-dbi (assoc dbi :subject-id-to-hashed-secret-data-id (:new-data-id (au/<? (<update-storage subject-id-to-hashed-secret-data-id u/string-map-schema [{:path [requested-subject-id] :op :set :arg hashed-secret}] nil branch temp-storage perm-storage))) :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :set :arg requested-subject-id}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <add-subject-identifier-update-fn [identifier dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id]} dbi new-dbi (assoc dbi :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :set :arg subject-id}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <remove-subject-identifier-update-fn [identifier dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [identifier-to-subject-id-data-id]} dbi new-dbi (assoc dbi :identifier-to-subject-id-data-id (:new-data-id (au/<? (<update-storage identifier-to-subject-id-data-id u/string-map-schema [{:path [identifier] :op :remove}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <change-secret-update-fn [hashed-secret dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [subject-id-to-hashed-secret-data-id subject-id-to-tokens-data-id token-to-token-info-data-id]} dbi dbi* (assoc dbi :subject-id-to-hashed-secret-data-id (:new-data-id (au/<? (<update-storage subject-id-to-hashed-secret-data-id u/string-map-schema [{:path [subject-id] :op :set :arg hashed-secret}] nil branch temp-storage perm-storage)))) src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) ;; Invalidate existing tokens for this user tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) ;; Use loop here to stay in go block new-dbi (loop [new-dbi dbi* [token & more] tokens] (let [new-dbi* (assoc new-dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))))] (if (seq more) (recur new-dbi* more) new-dbi*)))] {:dbi new-dbi :update-infos []}))) (defn <log-in-update-fn [token token-info dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi new-dbi (assoc dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :set :arg token-info}] nil branch temp-storage perm-storage))) :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id -1] :op :insert-after :arg token}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <log-out-update-fn [dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi dbi* (assoc dbi :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id] :op :remove}] nil branch temp-storage perm-storage)))) src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) ;; Use loop here to stay in go block new-dbi (loop [new-dbi dbi* [token & more] tokens] (let [new-dbi* (assoc new-dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))))] (if (seq more) (recur new-dbi* more) new-dbi*)))] {:dbi new-dbi :update-infos []}))) (defn <delete-token-update-fn [token dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [token-to-token-info-data-id subject-id-to-tokens-data-id]} dbi src-storage (if (str/starts-with? subject-id-to-tokens-data-id "-") temp-storage perm-storage) tokens (au/<? (u/<get-in src-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [subject-id] nil)) new-tokens (remove #(= token %) tokens) new-dbi (assoc dbi :token-to-token-info-data-id (:new-data-id (au/<? (<update-storage token-to-token-info-data-id u/token-map-schema [{:path [token] :op :remove}] nil branch temp-storage perm-storage))) ;; TODO: Improve this when `find` is implemented :subject-id-to-tokens-data-id (:new-data-id (au/<? (<update-storage subject-id-to-tokens-data-id u/subject-id-to-tokens-schema [{:path [subject-id] :op :set :arg new-tokens}] nil branch temp-storage perm-storage))))] {:dbi new-dbi :update-infos []}))) (defn <update-state-update-fn [state-schema update-cmds dbi subject-id branch temp-storage perm-storage] (au/go (let [{:keys [data-id]} dbi ret (au/<? (<update-storage data-id state-schema update-cmds :sys branch temp-storage perm-storage)) {:keys [new-data-id update-infos state]} ret] {:dbi (assoc dbi :data-id new-data-id) :update-infos update-infos :update-state-rpc? true :state state}))) (defn <delete-branch* [branch storage] (au/go (let [all-branches (au/<? (u/<get-in-reference storage u/all-branches-reference u/all-branches-schema nil nil)) new-branches (or (-> (set all-branches) (disj branch) (seq)) []) branch-reference (branch->reference branch)] ;; TODO: Improve this when `find` is implemented (au/<? (u/<update-reference! storage u/all-branches-reference u/all-branches-schema [{:path nil :op :set :arg new-branches}] nil)) (au/<? (u/<delete-reference! storage branch-reference)) true))) (defn notify-conns! [update-state-rpc? update-infos conn-id conn-ids db-id prev-db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info] ;; For update-state, notify all conns except the originator, ;; who gets the information sent to them directly. ;; This allows local+sys updates to be atomic. (let [conn-ids* (if update-state-rpc? (disj (set conn-ids) conn-id) conn-ids)] (ca/go (try (doseq [conn-id* conn-ids*] (let [{:keys [subject-id]} (@*conn-id->info conn-id*) new-state (when whole-state (redaction-fn subject-id whole-state)) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (when whole-state (l/serialize state-schema new-state)) serialized-state (when whole-state (u/sym-map fp bytes)) info (u/sym-map db-id prev-db-id serialized-state subject-id update-infos)] (ep/send-msg vc-ep conn-id* :db-changed info))) (catch Exception e (log/error (str "Error in notify-conns!:\n" (u/ex-msg-and-stacktrace e)))))))) (defn <modify-db!* [branch conn-id subject-id <update-fn msg redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info] (au/go (let [num-tries 10 {:keys [conn-ids]} (@*branch->info branch) branch-reference (branch->reference branch) dest-storage (if (str/starts-with? branch "-") temp-storage perm-storage)] ;; Use loop to stay in go block (loop [num-tries-left (dec num-tries)] (let [prev-db-id (au/<? (u/<get-data-id dest-storage branch-reference)) src-storage (cond (nil? prev-db-id) nil (str/starts-with? prev-db-id "-") temp-storage :else perm-storage) prev-dbi (when src-storage (au/<? (u/<get-in src-storage prev-db-id u/db-info-schema nil nil))) {:keys [num-prev-dbs data-id]} prev-dbi uf-ret (au/<? (<update-fn prev-dbi subject-id branch temp-storage perm-storage)) {:keys [dbi update-infos update-state-rpc?]} uf-ret new-dbi (assoc dbi :msg msg :timestamp-ms (u/current-time-ms) :num-prev-dbs (if num-prev-dbs (inc num-prev-dbs) 0) :prev-db-id prev-db-id) update-ret (au/<? (<update-storage prev-db-id u/db-info-schema [{:path [] :op :set :arg new-dbi}] nil branch temp-storage perm-storage)) new-db-id (:new-data-id update-ret) whole-state (:state uf-ret)] (if (au/<? (u/<compare-and-set! dest-storage branch-reference l/string-schema prev-db-id new-db-id)) (do (notify-conns! update-state-rpc? update-infos conn-id conn-ids new-db-id prev-db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info) (u/sym-map new-db-id prev-db-id whole-state update-infos)) (if (zero? num-tries-left) (throw (ex-info (str "Failed to commit to branch `" branch-reference "` after " num-tries " tries.") (u/sym-map branch-reference num-tries))) (do (au/<? (ca/timeout (rand-int 100))) (recur (dec num-tries-left)))))))))) (defn start-modify-db-loop [^ConcurrentLinkedQueue q redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info] (ca/go (while true (try (if-let [info (.poll q)] (let [{:keys [cb branch conn-id subject-id <update-fn msg]} info] (try (cb (au/<? (<modify-db!* branch conn-id subject-id <update-fn msg redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info))) (catch Exception e (cb e)))) (ca/<! (ca/timeout 5))) (catch Exception e (log/error (str "Unexpected error in txn-loop:\n" (u/ex-msg-and-stacktrace e)))))))) (defn <ks-at-path [kw <get-at-path p full-path] (au/go (let [coll (au/<? (<get-at-path p))] (cond (map? coll) (keys coll) (sequential? coll) (range (count coll)) (nil? coll) [] :else (throw (ex-info (str "`" kw "` is in path, but there is not " "a collection at " p ".") {:full-path full-path :missing-collection-path p :value coll})))))) (defn <count-at-path [<get-at-path p full-path] (au/go (let [coll (au/<? (<get-at-path p))] (cond (or (map? coll) (sequential? coll)) (count coll) (nil? coll) 0 :else (throw (ex-info (str "`:vivo/count` terminates path, but " "there is not a collection at " p ".") {:full-path full-path :missing-collection-path p :value coll})))))) (defn <do-concat [<get-at-path p full-path] (au/go (let [seqs (au/<? (<get-at-path p))] (when (and (not (nil? seqs)) (or (not (sequential? seqs)) (not (sequential? (first seqs))))) (throw (ex-info (str "`:vivo/concat` terminates path, but there " "is not a sequence of sequences at " p ".") {:full-path full-path :missing-collection-path p :value seqs}))) (apply concat seqs)))) (defn <do-login [vs conn-id branch identifier secret login-identifier-case-sensitive? login-lifetime-mins *conn-id->info *branch->info] (au/go (u/check-secret-len secret) (let [identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) db-info (au/<? (<get-db-info vs branch)) {id->sid-data-id :identifier-to-subject-id-data-id sid->hs-data-id :subject-id-to-hashed-secret-data-id} db-info subject-id (when id->sid-data-id (let [src-storage (get-storage vs id->sid-data-id)] (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier*] nil)))) hashed-secret (when (and subject-id sid->hs-data-id) (let [src-storage (get-storage vs sid->hs-data-id)] (au/<? (u/<get-in src-storage sid->hs-data-id u/string-map-schema [subject-id] nil))))] (if-not (and hashed-secret (bcrypt/check secret hashed-secret)) {:subject-id nil :token nil} (let [token (generate-token) expiration-time-mins (+ (u/ms->mins (u/current-time-ms)) login-lifetime-mins) token-info (u/sym-map expiration-time-mins subject-id) _ (when conn-id (swap! *conn-id->info update conn-id assoc :subject-id subject-id) (swap! *branch->info update branch update :subject-id->conn-ids update subject-id (fn [conn-ids] (conj (or conn-ids #{}) conn-id)))) ret (au/<? (<modify-db! vs (partial <log-in-update-fn token token-info) "Log in" subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id subject-id :token token}))))) (defn <log-out-subject! [vs subject-id branch *branch->info *conn-id->info] (au/go (let [conn-ids (some-> (@*branch->info branch) (:subject-id->conn-ids) (get subject-id))] (swap! *branch->info update branch update :subject-id->conn-ids dissoc subject-id) (doseq [conn-id conn-ids] (swap! *conn-id->info update conn-id dissoc :subject-id) (au/<? (<modify-db! vs <log-out-update-fn "Log out" subject-id branch nil))) true))) (defn <do-add-subject [vs identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?] (au/go (u/check-secret-len secret) (let [hashed-secret (bcrypt/encrypt secret work-factor) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) ret (au/<? (<modify-db! vs (partial <add-subject-update-fn subject-id identifier* hashed-secret) (str "Add subject " subject-id) subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id subject-id}))) (defn <do-change-secret! [vs branch subject-id old-secret new-secret] (au/go (u/check-secret-len old-secret) (u/check-secret-len new-secret) (let [branch-reference (branch->reference branch) storage (get-storage vs branch) db-id (au/<? (u/<get-data-id storage branch-reference)) db-info (au/<? (u/<get-in storage db-id u/db-info-schema nil nil)) {sid->hs-data-id :subject-id-to-hashed-secret-data-id} db-info hashed-old-secret (when (and subject-id old-secret) (au/<? (u/<get-in storage sid->hs-data-id u/string-map-schema [subject-id] nil))) old-secret-ok? (if-not hashed-old-secret true (bcrypt/check old-secret hashed-old-secret))] (if-not old-secret-ok? false (let [hashed-new-secret (bcrypt/encrypt new-secret work-factor)] (-> (au/<? (<modify-db! vs (partial <change-secret-update-fn hashed-new-secret) "Change secret" subject-id branch nil)) :new-db-id)))))) (defn <do-update-state [vs arg metadata authorization-fn redaction-fn state-schema perm-storage *conn-id->info] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) update-cmds (au/<? (<scmds->cmds vs arg conn-id)) all-authed? (if (empty? update-cmds) true (loop [i 0] ; Use loop to stay in same go block (let [{:keys [path arg]} (nth update-cmds i) auth-ret (authorization-fn subject-id path :write arg) authed? (if (au/channel? auth-ret) (au/<? auth-ret) auth-ret) new-i (inc i)] (cond (not authed?) false (= (count update-cmds) new-i) true :else (recur new-i)))))] (if-not all-authed? :vivo/unauthorized (let [ret (au/<? (<modify-db! vs (partial <update-state-update-fn state-schema update-cmds) "Update state" subject-id branch conn-id)) {:keys [new-db-id prev-db-id whole-state update-infos]} ret state (redaction-fn subject-id whole-state) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (l/serialize state-schema state) serialized-state (u/sym-map fp bytes)] {:db-id new-db-id :prev-db-id prev-db-id :serialized-state serialized-state :update-infos update-infos}))))) (defn <log-in-w-token* [vivo-server state-schema redaction-fn vc-ep perm-storage token metadata *conn-id->info] (au/go (let [{:keys [conn-id]} metadata {:keys [*conn-id->info *branch->info]} vivo-server {:keys [branch]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info vivo-server branch)) {:keys [token-to-token-info-data-id db-id]} db-info info (when token-to-token-info-data-id (let [src-storage (get-storage vivo-server token-to-token-info-data-id)] (au/<? (u/<get-in src-storage token-to-token-info-data-id u/token-map-schema [token] nil)))) {:keys [expiration-time-mins subject-id]} info now-mins (-> (u/current-time-ms) (u/ms->mins))] (when info (if (>= now-mins expiration-time-mins) (let [ret (au/<? (<modify-db! vivo-server (partial <delete-token-update-fn token) "Delete expired token" subject-id branch conn-id))] {:db-id (:new-db-id ret) :subject-id nil :token nil}) (do (swap! *conn-id->info update conn-id assoc :subject-id subject-id) (swap! *branch->info update branch update :subject-id->conn-ids update subject-id (fn [conn-ids] (conj (or conn-ids #{}) conn-id))) ;; When subject-id changes but not the db, we need to send a new db ;; with the results of the redaction-fn. db-id doesn't change. (let [update-infos [{:norm-path [:sys] :op :set} {:norm-path [:vivo/subject-id] :op :set}] db-id (au/<? (<get-db-id vivo-server branch)) whole-state (first (au/<? (<get-state-and-expanded-path vivo-server db-id [:sys])))] (notify-conns! false update-infos conn-id [conn-id] db-id db-id whole-state state-schema redaction-fn vc-ep perm-storage *conn-id->info) (u/sym-map db-id subject-id token)))))))) (defn <set-state-source* [vivo-server source metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [perm-storage state-schema *branch->info *conn-id->info]} vivo-server perm-branch (:branch/name source) branch (if perm-branch (let [branch-reference (branch->reference perm-branch) storage (get-storage vivo-server perm-branch)] (when-not (au/<? (u/<get-data-id storage branch-reference)) (au/<? (<create-branch vivo-server {:branch perm-branch :db-id nil} metadata))) perm-branch) (let [branch* (str "-temp-branch-" (rand-int 1e9))] (au/<? (<create-branch vivo-server {:branch branch* :db-id (:temp-branch/db-id source)} metadata)) branch*))] (swap! *conn-id->info update conn-id assoc :branch branch :temp-branch? (not perm-branch)) (swap! *branch->info update branch (fn [{:keys [conn-ids] :as info}] (if conn-ids (update info :conn-ids conj conn-id) (assoc info :conn-ids #{conn-id})))) true))) (defn publish-msg* [vc-ep *conn-id->info arg metadata] (let [{:keys [conn-id]} metadata conn-ids (keys @*conn-id->info)] (doseq [conn-id* (disj (set conn-ids) conn-id)] (ep/send-msg vc-ep conn-id* :publish-msg arg)) true)) (defrecord VivoServer [authorization-fn login-identifier-case-sensitive? login-lifetime-mins modify-q path->schema-cache perm-storage rpcs vc-ep redaction-fn repository-name state-schema stop-server temp-storage *conn-id->info *branch->info *rpc->handler] IVivoServer (<modify-db! [this <update-fn msg subject-id branch conn-id] (au/go (let [modify-ch (ca/chan) cb #(ca/put! modify-ch %) update-info (u/sym-map cb branch conn-id subject-id <update-fn msg) _ (.add ^ConcurrentLinkedQueue modify-q update-info) change-info (au/<? modify-ch)] change-info))) (<get-db-info [this branch] (au/go (let [branch-reference (branch->reference branch) dest-storage (get-storage this branch) db-id (au/<? (u/<get-data-id dest-storage branch-reference)) src-storage (get-storage this db-id)] (-> (u/<get-in src-storage db-id u/db-info-schema nil nil) (au/<?) (assoc :db-id db-id))))) (<add-subject [this arg metadata] (let [{:keys [identifier secret subject-id] :or {subject-id (.toString ^UUID (UUID/randomUUID))}} arg {:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id)] (u/check-secret-len secret) (<do-add-subject this identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?))) (<add-subject* [this identifier secret subject-id branch conn-id] (<do-add-subject this identifier secret subject-id branch conn-id work-factor login-identifier-case-sensitive?)) (<add-subject-identifier [this identifier metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier))] (if-not subject-id false ;; Must be logged in (-> (au/<? (<modify-db! this (partial <add-subject-identifier-update-fn identifier*) (str "Add subject indentifier `" identifier*) subject-id branch conn-id)) :new-db-id))))) (<remove-subject-identifier [this identifier metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info this branch)) id->sid-data-id (:identifier-to-subject-id-data-id db-info) identifier* (if login-identifier-case-sensitive? identifier (str/lower-case identifier)) src-storage (get-storage this id->sid-data-id) id-subject-id (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier*] nil)) my-identifier? (and subject-id (= subject-id id-subject-id))] (if-not my-identifier? false (-> (<modify-db! this (partial <remove-subject-identifier-update-fn identifier*) (str "Remove subject indentifier `" identifier*) subject-id branch conn-id) (au/<?) (:new-db-id)))))) (<change-secret* [this branch subject-id old-secret new-secret] (<do-change-secret! this branch subject-id old-secret new-secret)) (<change-secret [this arg metadata] (let [{:keys [old-secret new-secret]} arg {:keys [conn-id]} metadata {:keys [branch subject-id]} (@*conn-id->info conn-id)] (<change-secret* this branch subject-id old-secret new-secret))) (<create-branch [this arg metadata] (au/go (let [{:keys [branch db-id]} arg {:keys [subject-id]} metadata _ (when (empty? branch) (throw (ex-info "Branch name is nil or empty." arg))) _ (when (> (count branch) u/max-branch-name-len) (throw-branch-name-too-long branch)) temp-dest? (str/starts-with? branch "-") src-storage (get-storage this db-id) dest-storage (get-storage this branch) temp-src? (and db-id (block-ids/temp-block-id? db-id)) branch-reference (branch->reference branch) _ (when (and db-id (not (try (au/<? (u/<get-in src-storage db-id u/db-info-schema [:data-id] nil)) (catch ExceptionInfo e (if (re-find #"not match given writer schema" (ex-message e)) false (throw e)))))) (throw (ex-info (str "Source db-id `" db-id "` does not exist.") arg))) _ (when (and temp-src? (not temp-dest?)) (throw (ex-info (str "Cannot create a permanent branch from a " "temporary db-id.") (u/sym-map branch db-id temp-dest?)))) _ (when (au/<? (u/<get-data-id dest-storage branch-reference)) (throw (ex-info (str "A branch named `" branch "` already " "exists in the repository.") (u/sym-map branch db-id temp-dest?)))) _ (au/<? (u/<update-reference! dest-storage u/all-branches-reference u/all-branches-schema [{:path [-1] :op :insert-after :arg branch}] nil)) db-id* (or db-id (let [create-db-ch (ca/chan) cb #(ca/put! create-db-ch %) default-data (l/default-data state-schema) update-cmds [{:path [:sys] :op :set :arg default-data}] <update-fn (partial <update-state-update-fn state-schema update-cmds) msg "Create initial db for branch" create-info (u/sym-map cb branch subject-id <update-fn msg)] (.add ^ConcurrentLinkedQueue modify-q create-info) (:new-db-id (au/<? create-db-ch))))] (au/<? (u/<set-reference! dest-storage branch-reference db-id*))))) (<delete-branch [this branch metadata] (<delete-branch* branch (get-storage this branch))) (<fp->schema [this fp conn-id] (au/go (or (au/<? (u/<fp->schema perm-storage fp)) (let [pcf (au/<? (ep/<send-msg vc-ep conn-id :get-schema-pcf fp))] (l/json->schema pcf))))) ;; TODO: Fix <get-all-branches to use a scan. ;; Get rid of all-branches-reference (<get-all-branches [this] (au/go (let [perm-branches (au/<? (u/<get-in-reference perm-storage u/all-branches-reference u/all-branches-schema nil nil)) temp-branches (au/<? (u/<get-in-reference temp-storage u/all-branches-reference u/all-branches-schema nil nil)) all-branches (concat perm-branches temp-branches)] (seq all-branches)))) (<get-db-id [this branch] (let [storage (get-storage this branch) branch-reference (branch->reference branch)] (u/<get-data-id storage branch-reference))) (<get-in [this db-id path] (au/go (let [state-and-path (au/<? (<get-state-and-expanded-path this db-id path))] (first state-and-path)))) (<get-state-and-expanded-path [this db-id path] (au/go (when-not (string? db-id) (throw (ex-info (str "Bad db-id `" db-id "`. db-id must be a string.") {:db-id db-id}))) (when (and path (not (sequential? path))) (throw (ex-info (str "Bad path `" path "`. Path must be nil or a sequence.") {:path path}))) (let [path (or path [:sys]) db-id-storage (get-storage this db-id) data-id (au/<? (u/<get-in db-id-storage db-id u/db-info-schema [:data-id] nil)) data-id-storage (get-storage this data-id) <get-at-path #(u/<get-in data-id-storage data-id state-schema % :sys) last-path-k (last path) join? (u/has-join? path) term-kw? (u/terminal-kw-ops last-path-k)] (cond (or (not data-id) (u/empty-sequence-in-path? path)) [nil [path]] (and (not term-kw?) (not join?)) (let [val (au/<? (<get-at-path path))] [val [path]]) (and term-kw? (not join?)) (let [path* (butlast path) val (case last-path-k :vivo/keys (au/<? (<ks-at-path :vivo/keys <get-at-path path* path)) :vivo/count (au/<? (<count-at-path <get-at-path path* path)) :vivo/concat (au/<? (<do-concat <get-at-path path* path)))] [val [path]]) (and (not term-kw?) join?) (when-not (u/empty-sequence-in-path? path) (let [expanded-path (au/<? (u/<expand-path #(<ks-at-path :vivo/* <get-at-path % path) path)) num-results (count expanded-path)] (if (zero? num-results) [[] []] ;; Use loop to stay in the go block (loop [out [] i 0] (let [filled-in-path (nth expanded-path i) v (au/<? (u/<get-in data-id-storage data-id state-schema filled-in-path :sys)) new-out (conj out v) new-i (inc i)] (if (= num-results new-i) [new-out expanded-path] (recur new-out new-i))))))) (and term-kw? join?) (let [expanded-path (au/<? (u/<expand-path #(<ks-at-path :vivo/* <get-at-path % path) (butlast path))) num-results (count expanded-path)] (if (zero? num-results) [[] []] (let [results (loop [out [] i 0] (let [filled-in-path (nth expanded-path i) v (au/<? (u/<get-in data-id-storage data-id state-schema filled-in-path :sys)) new-out (conj out v) new-i (inc i)] (if (= num-results new-i) new-out (recur new-out new-i)))) value (case last-path-k :vivo/keys (range (count results)) :vivo/count (count results) :vivo/concat (apply concat results))] [value expanded-path]))))))) (<get-log [this branch limit] (au/go (let [storage (get-storage this branch) db-id (au/<? (<get-db-id this branch)) dbi (au/<? (u/<get-in storage db-id u/db-info-schema nil nil)) make-log-rec #(select-keys % [:msg :timestamp-ms])] (when dbi (loop [out [(make-log-rec dbi)] i 1] (let [{:keys [prev-db-id]} (peek out)] (if (or (not prev-db-id) (= limit i)) out (let [prev-dbi (au/<? (u/<get-in storage prev-db-id u/db-info-schema nil nil))] (recur (conj out (make-log-rec dbi)) (inc i)))))))))) (<get-num-commits [this branch] (au/go (let [storage (get-storage this branch) db-id (au/<? (<get-db-id this branch)) dbi (au/<? (u/<get-in storage db-id u/db-info-schema nil nil))] (if dbi (inc (:num-prev-dbs dbi)) 0)))) (<get-state [this arg metadata] ;; TODO: Figure this out for non-locally-cached state lookups ;; Figure out how to unify authorization-fn and redaction-fn #_ (au/go (let [{:keys [path db-id]} arg {:keys [conn-id]} metadata {:keys [subject-id]} (@*conn-id->info conn-id) [v xp] (au/<? (<get-state-and-expanded-path this db-id path)) authorized? (let [ret (authorization-fn subject-id path :read v)] (if (au/channel? ret) (au/<? ret) ret))] (if (or (not authorized?) (= :vivo/unauthorized v)) :vivo/unauthorized (when v (let [schema-path (rest path) ; Ignore :sys schema (u/path->schema path->schema-cache state-schema schema-path) fp (when schema (au/<? (u/<schema->fp perm-storage schema)))] (when schema {:serialized-value {:fp fp :bytes (l/serialize schema v)} :expanded-path xp}))))))) (<get-subject-id-for-identifier [this identifier branch] (au/go (let [db-info (au/<? (<get-db-info this branch)) id->sid-data-id (:identifier-to-subject-id-data-id db-info) src-storage (get-storage this id->sid-data-id)] (au/<? (u/<get-in src-storage id->sid-data-id u/string-map-schema [identifier] nil))))) (<log-in* [this identifier secret minutes-valid conn-id branch] (<do-login this conn-id branch identifier secret login-identifier-case-sensitive? minutes-valid *conn-id->info *branch->info)) (<log-in [this arg metadata] (let [{:keys [identifier secret]} arg {:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id)] (<log-in* this identifier secret login-lifetime-mins conn-id branch))) (<log-in-w-token [this token metadata] (<log-in-w-token* this state-schema redaction-fn vc-ep perm-storage token metadata *conn-id->info)) (<log-out [this arg metadata] (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id)] (<log-out-subject! this subject-id branch *branch->info *conn-id->info))) (<log-out-w-token [this token metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [branch]} (@*conn-id->info conn-id) db-info (au/<? (<get-db-info this branch)) {:keys [token-PI:KEY:<KEY>END_PI]} db-info src-storage (get-storage this token-to-token-info-data-id) info (when token-to-token-info-data-id (au/<? (u/<get-in src-storage token-to-token-info-data-id u/token-map-schema [token] nil)))] (if-not info false (let [{:keys [subject-id]} info] (au/<? (<log-out-subject! this subject-id branch *branch->info *conn-id->info))))))) (<set-state-source [this source metadata] (<set-state-source* this source metadata)) (<rpc [this msg-arg metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) db-id (au/<? (<get-db-id this branch)) {:keys [rpc-name-kw-ns rpc-name-kw-name arg]} msg-arg rpc-name-kw (keyword rpc-name-kw-ns rpc-name-kw-name) rpc-info (rpcs rpc-name-kw) _ (when-not rpc-info (throw (ex-info (str "No RPC with name `" rpc-name-kw "` is registered. " "Either this is a typo or you need to add `" rpc-name-kw "` to the :rpcs map when " "creating the Vivo server.") {:known-rpcs (keys rpcs) :given-rpc rpc-name-kw}))) handler (@*rpc->handler rpc-name-kw) _ (when-not handler (throw (ex-info (str "No RPC handler for `" rpc-name-kw "` is registered. " "Call `set-rpc-handler!` on the server instance to " "set an RPC handler.") {:known-rpcs (keys rpcs) :given-rpc rpc-name-kw}))) {:keys [arg-schema ret-schema]} rpc-info {:keys [fp bytes]} arg w-schema (au/<? (<fp->schema this fp conn-id)) rpc-arg (l/deserialize arg-schema w-schema bytes) authorized? (let [path [:vivo/rpcs rpc-name-kw] ret (authorization-fn subject-id path :call rpc-arg)] (if (au/channel? ret) (au/<? ret) ret))] (if-not authorized? :vivo/unauthorized (let [rpc-metadata (assoc (u/sym-map conn-id subject-id branch db-id repository-name) :vivo-server this) ret* (handler rpc-arg rpc-metadata) ret (if (au/channel? ret*) (au/<? ret*) ret*)] {:fp (au/<? (u/<schema->fp perm-storage ret-schema)) :bytes (l/serialize ret-schema ret)}))))) (<handle-request-db-changed-msg [this arg metadata] (au/go (let [{:keys [conn-id]} metadata {:keys [subject-id branch]} (@*conn-id->info conn-id) db-id (au/<? (<get-db-id this branch)) [whole-state xp] (au/<? (<get-state-and-expanded-path this db-id [:sys])) new-state (when whole-state (redaction-fn subject-id whole-state)) fp (au/<? (u/<schema->fp perm-storage state-schema)) bytes (when new-state (l/serialize state-schema new-state)) serialized-state (u/sym-map fp bytes) info (-> (u/sym-map db-id serialized-state subject-id) (assoc :prev-db-id db-id) (assoc :update-infos []))] (ep/send-msg vc-ep conn-id :db-changed info)))) (<scmds->cmds [this scmds conn-id] (au/go (if-not (seq scmds) [] ;; Use loop/recur to stay in single go block (loop [scmd (first scmds) i 0 out []] (let [{:keys [path arg]} scmd arg-sch (u/path->schema path->schema-cache state-schema (rest path)) ; Ignore :sys new-i (inc i) last? (= (count scmds) new-i)] (if-not arg-sch ; Skip cmd if we don't have schema (evolution) (if last? out (recur (nth scmds new-i) new-i out)) (let [writer-arg-sch (when arg (au/<? (<fp->schema this (:fp arg) conn-id))) arg* (when arg (l/deserialize arg-sch writer-arg-sch (:bytes arg))) cmd (cond-> scmd arg (assoc :arg arg*)) new-out (conj out cmd)] (if last? new-out (recur (nth scmds new-i) new-i new-out))))))))) (<update-db [this update-cmds msg subject-id branch] (<modify-db! this (partial <update-state-update-fn state-schema update-cmds) "Update db" subject-id branch nil)) (<update-state [this arg metadata] (<do-update-state this arg metadata authorization-fn redaction-fn state-schema perm-storage *conn-id->info)) (<get-schema-pcf [this fp metadata] (au/go (if-let [schema (au/<? (u/<fp->schema perm-storage fp))] (l/pcf schema) (do (log/error (str "Could not find PCF for fingerprint `" fp "`.")) nil)))) (<store-schema-pcf [this pcf metadata] (au/go (au/<? (u/<schema->fp perm-storage (l/json->schema pcf))) true)) (get-storage [this branch-or-db-id] (when branch-or-db-id (if (str/starts-with? branch-or-db-id "-") temp-storage perm-storage))) (set-rpc-handler! [this rpc-name-kw handler] (swap! *rpc->handler assoc rpc-name-kw handler)) (publish-msg [this arg metadata] (publish-msg* vc-ep *conn-id->info arg metadata)) (shutdown! [this] (stop-server))) (defn default-health-http-handler [req] (if (= "/health" (:uri req)) {:status 200 :headers {"content-type" "text/plain" "Access-Control-Allow-Origin" "*"} :body "I am healthy"} {:status 404 :body "I still haven't found what you're looking for..."})) (def default-config {:additional-endpoints [] :authenticate-admin-client (constantly false) :handle-http default-health-http-handler :http-timeout-ms 60000 :login-lifetime-mins (* 60 24 15) ;; 15 days :redaction-fn (fn [subject-id db] db)}) (defn check-config [config] (let [required-ks [:authorization-fn :port :repository-name :state-schema]] (doseq [k required-ks] (when-not (config k) (throw (ex-info (str "Missing " k " in config.") (u/sym-map k config)))))) (when-let [rpcs (:rpcs config)] (when-not (map? rpcs) (throw (ex-info (str "In config, the value of the :rpcs key " "must be a map. Got `" rpcs "`.") config))) (u/check-rpcs rpcs))) (defn on-disconnect [*conn-id->info *branch->info temp-storage tube-conn code reason conn-count] (ca/go (let [conn-id (when tube-conn (tc/get-conn-id tube-conn))] (try (let [conn-info (@*conn-id->info conn-id) {:keys [branch subject-id temp-branch?]} conn-info] (swap! *conn-id->info dissoc conn-id) (swap! *branch->info update branch (fn [info] (-> info (update :conn-ids disj conn-id) (update :subject-id->conn-ids dissoc subject-id)))) (when temp-branch? (au/<? (<delete-branch* branch temp-storage)))) (catch Throwable e (log/error (str "Error in on-disconnect (conn-id: " conn-id ")\n" (u/ex-msg-and-stacktrace e)))))))) (defn <get-subject-id-for-identifier* [vivo-server identifier metadata] (let [{:keys [branch]} (@(:*conn-id->info vivo-server) (:conn-id metadata))] (<get-subject-id-for-identifier vivo-server identifier branch))) (defn set-handlers! [vivo-server vc-ep admin-ep] (ep/set-handler admin-ep :create-branch (partial <create-branch vivo-server)) (ep/set-handler admin-ep :delete-branch (partial <delete-branch vivo-server)) (ep/set-handler admin-ep :get-db-id-for-branch (fn [arg metadata] (<get-db-id vivo-server arg))) (ep/set-handler vc-ep :add-subject (partial <add-subject vivo-server)) (ep/set-handler vc-ep :add-subject-identifier (partial <add-subject-identifier vivo-server)) (ep/set-handler vc-ep :change-secret (partial <change-secret vivo-server)) (ep/set-handler vc-ep :get-schema-pcf (partial <get-schema-pcf vivo-server)) (ep/set-handler vc-ep :get-subject-id-for-identifier (partial <get-subject-id-for-identifier* vivo-server)) (ep/set-handler vc-ep :get-state (partial <get-state vivo-server)) (ep/set-handler vc-ep :log-in (partial <log-in vivo-server)) (ep/set-handler vc-ep :log-in-w-token (partial <log-in-w-token vivo-server)) (ep/set-handler vc-ep :log-out (partial <log-out vivo-server)) (ep/set-handler vc-ep :log-out-w-token (partial <log-out-w-token vivo-server)) (ep/set-handler vc-ep :publish-msg (partial publish-msg vivo-server)) (ep/set-handler vc-ep :remove-subject-identifier (partial <remove-subject-identifier vivo-server)) (ep/set-handler vc-ep :request-db-changed-msg (partial <handle-request-db-changed-msg vivo-server)) (ep/set-handler vc-ep :rpc (partial <rpc vivo-server)) (ep/set-handler vc-ep :set-state-source (partial <set-state-source vivo-server)) (ep/set-handler vc-ep :store-schema-pcf (partial <store-schema-pcf vivo-server)) (ep/set-handler vc-ep :update-state (partial <update-state vivo-server))) (defn vivo-server [config] (when-not (map? config) (throw (ex-info (str "`config` argument must be a map. Got: `" config "`.") (u/sym-map config)))) (let [config* (merge default-config config) _ (check-config config*) {:keys [additional-endpoints authenticate-admin-client authorization-fn certificate-str disable-ddb? handle-http http-timeout-ms login-identifier-case-sensitive? login-lifetime-mins port private-key-str redaction-fn repository-name rpcs state-schema]} config* perm-storage (data-storage/data-storage (data-block-storage/data-block-storage (if disable-ddb? (mem-block-storage/mem-block-storage false) (au/<?? (ddb-block-storage/<ddb-block-storage repository-name))))) temp-storage (data-storage/data-storage (data-block-storage/data-block-storage (mem-block-storage/mem-block-storage true))) modify-q (ConcurrentLinkedQueue.) path->schema-cache (sr/stockroom 1000) *conn-id->info (atom {}) *branch->info (atom {}) *rpc->handler (atom {}) vc-ep-opts {:on-disconnect (partial on-disconnect *conn-id->info *branch->info temp-storage)} vc-ep (ep/endpoint "vivo-client" (constantly true) u/client-server-protocol :server vc-ep-opts) admin-ep (ep/endpoint "admin-client" authenticate-admin-client u/admin-client-server-protocol :server) cs-opts (u/sym-map handle-http http-timeout-ms certificate-str private-key-str) stop-server (cs/server (conj additional-endpoints vc-ep admin-ep) port cs-opts) vivo-server (->VivoServer authorization-fn login-identifier-case-sensitive? login-lifetime-mins modify-q path->schema-cache perm-storage (or rpcs {}) vc-ep redaction-fn repository-name state-schema stop-server temp-storage *conn-id->info *branch->info *rpc->handler)] (au/<?? (<store-schema-pcf vivo-server (l/pcf state-schema) nil)) (start-modify-db-loop modify-q redaction-fn state-schema vc-ep temp-storage perm-storage *branch->info *conn-id->info) (set-handlers! vivo-server vc-ep admin-ep) (log/info (str "Vivo server started on port " port ".")) vivo-server))
[ { "context": "2/hello_world\"\n :user \"benchmarkdbuser\"\n :password \"benchmark", "end": 2238, "score": 0.9854944348335266, "start": 2223, "tag": "USERNAME", "value": "benchmarkdbuser" }, { "context": "arkdbuser\"\n :password \"benchmarkdbpass\"\n :size 1})))\n ", "end": 2294, "score": 0.9994524121284485, "start": 2279, "tag": "PASSWORD", "value": "benchmarkdbpass" }, { "context": "llo_world\"\n :username \"benchmarkdbuser\"\n :password \"benchmark", "end": 2762, "score": 0.9962949156761169, "start": 2747, "tag": "USERNAME", "value": "benchmarkdbuser" }, { "context": "arkdbuser\"\n :password \"benchmarkdbpass\"\n :maximum-pool-size (", "end": 2818, "score": 0.9994633197784424, "start": 2803, "tag": "PASSWORD", "value": "benchmarkdbpass" }, { "context": "er/create\n {:port 8080\n :host \"0.0.0.0\"\n :io-threads (* 2 cpus)\n :wo", "end": 3323, "score": 0.9991498589515686, "start": 3316, "tag": "IP_ADDRESS", "value": "0.0.0.0" } ]
frameworks/Clojure/reitit/src/hello/handler.clj
xsoheilalizadeh/FrameworkBenchmarks
5,300
(ns hello.handler (:require [pohjavirta.server :as server] [pohjavirta.exchange :as exchange] [hikari-cp.core :as hikari] [reitit.ring :as ring] [porsas.jdbc :as jdbc] [porsas.async :as async] [jsonista.core :as j]) (:import (java.util.concurrent ThreadLocalRandom) (java.util.function Supplier) (clojure.lang IDeref)) (:gen-class)) ;; ;; utils ;; (defn random [] (unchecked-inc (.nextInt (ThreadLocalRandom/current) 10000))) (defmacro thread-local [& body] `(let [tl# (ThreadLocal/withInitial (reify Supplier (get [_] ~@body)))] (reify IDeref (deref [_] (.get tl#))))) ;; ;; handlers ;; (defn plain-text-handler [_] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello, World!"}) (defn json-handler [_] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes {:message "Hello, World!"})}) (defn sync-db-handler [mapper pool] (fn [_] (let [world (with-open [con (jdbc/get-connection pool)] (jdbc/query-one mapper con ["SELECT id, randomnumber from WORLD where id=?" (random)]))] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes world)}))) (defn async-db-handler [mapper pool-ref] (fn [_] (-> (async/query-one mapper @pool-ref ["SELECT id, randomnumber from WORLD where id=$1" (random)]) (async/then (fn [world] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes world)}))))) ;; ;; server ;; (defn -main [& [mode]] (let [cpus (.availableProcessors (Runtime/getRuntime)) db-handler (cond ;; reactive pg-client in NIO-pool (= mode "async") (async-db-handler (async/context {:row (async/rs->compiled-record)}) ;; thread local pool provider (thread-local (async/pool {:uri "postgresql://tfb-database:5432/hello_world" :user "benchmarkdbuser" :password "benchmarkdbpass" :size 1}))) ;; jdbc in worker-pool (= mode "sync") (exchange/dispatch (sync-db-handler (jdbc/context {:row (jdbc/rs->compiled-record)}) (hikari/make-datasource {:jdbc-url "jdbc:postgresql://tfb-database:5432/hello_world" :username "benchmarkdbuser" :password "benchmarkdbpass" :maximum-pool-size (* 8 cpus)}))) ;; none :else (constantly nil))] (-> (ring/ring-handler (ring/router [["/plaintext" (exchange/constantly plain-text-handler)] ["/json" json-handler] ["/db" db-handler]]) (ring/create-default-handler) {:inject-match? false :inject-router? false}) (server/create {:port 8080 :host "0.0.0.0" :io-threads (* 2 cpus) :worker-threads (* 8 cpus)}) (server/start))))
97910
(ns hello.handler (:require [pohjavirta.server :as server] [pohjavirta.exchange :as exchange] [hikari-cp.core :as hikari] [reitit.ring :as ring] [porsas.jdbc :as jdbc] [porsas.async :as async] [jsonista.core :as j]) (:import (java.util.concurrent ThreadLocalRandom) (java.util.function Supplier) (clojure.lang IDeref)) (:gen-class)) ;; ;; utils ;; (defn random [] (unchecked-inc (.nextInt (ThreadLocalRandom/current) 10000))) (defmacro thread-local [& body] `(let [tl# (ThreadLocal/withInitial (reify Supplier (get [_] ~@body)))] (reify IDeref (deref [_] (.get tl#))))) ;; ;; handlers ;; (defn plain-text-handler [_] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello, World!"}) (defn json-handler [_] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes {:message "Hello, World!"})}) (defn sync-db-handler [mapper pool] (fn [_] (let [world (with-open [con (jdbc/get-connection pool)] (jdbc/query-one mapper con ["SELECT id, randomnumber from WORLD where id=?" (random)]))] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes world)}))) (defn async-db-handler [mapper pool-ref] (fn [_] (-> (async/query-one mapper @pool-ref ["SELECT id, randomnumber from WORLD where id=$1" (random)]) (async/then (fn [world] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes world)}))))) ;; ;; server ;; (defn -main [& [mode]] (let [cpus (.availableProcessors (Runtime/getRuntime)) db-handler (cond ;; reactive pg-client in NIO-pool (= mode "async") (async-db-handler (async/context {:row (async/rs->compiled-record)}) ;; thread local pool provider (thread-local (async/pool {:uri "postgresql://tfb-database:5432/hello_world" :user "benchmarkdbuser" :password "<PASSWORD>" :size 1}))) ;; jdbc in worker-pool (= mode "sync") (exchange/dispatch (sync-db-handler (jdbc/context {:row (jdbc/rs->compiled-record)}) (hikari/make-datasource {:jdbc-url "jdbc:postgresql://tfb-database:5432/hello_world" :username "benchmarkdbuser" :password "<PASSWORD>" :maximum-pool-size (* 8 cpus)}))) ;; none :else (constantly nil))] (-> (ring/ring-handler (ring/router [["/plaintext" (exchange/constantly plain-text-handler)] ["/json" json-handler] ["/db" db-handler]]) (ring/create-default-handler) {:inject-match? false :inject-router? false}) (server/create {:port 8080 :host "0.0.0.0" :io-threads (* 2 cpus) :worker-threads (* 8 cpus)}) (server/start))))
true
(ns hello.handler (:require [pohjavirta.server :as server] [pohjavirta.exchange :as exchange] [hikari-cp.core :as hikari] [reitit.ring :as ring] [porsas.jdbc :as jdbc] [porsas.async :as async] [jsonista.core :as j]) (:import (java.util.concurrent ThreadLocalRandom) (java.util.function Supplier) (clojure.lang IDeref)) (:gen-class)) ;; ;; utils ;; (defn random [] (unchecked-inc (.nextInt (ThreadLocalRandom/current) 10000))) (defmacro thread-local [& body] `(let [tl# (ThreadLocal/withInitial (reify Supplier (get [_] ~@body)))] (reify IDeref (deref [_] (.get tl#))))) ;; ;; handlers ;; (defn plain-text-handler [_] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello, World!"}) (defn json-handler [_] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes {:message "Hello, World!"})}) (defn sync-db-handler [mapper pool] (fn [_] (let [world (with-open [con (jdbc/get-connection pool)] (jdbc/query-one mapper con ["SELECT id, randomnumber from WORLD where id=?" (random)]))] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes world)}))) (defn async-db-handler [mapper pool-ref] (fn [_] (-> (async/query-one mapper @pool-ref ["SELECT id, randomnumber from WORLD where id=$1" (random)]) (async/then (fn [world] {:status 200 :headers {"Content-Type" "application/json"} :body (j/write-value-as-bytes world)}))))) ;; ;; server ;; (defn -main [& [mode]] (let [cpus (.availableProcessors (Runtime/getRuntime)) db-handler (cond ;; reactive pg-client in NIO-pool (= mode "async") (async-db-handler (async/context {:row (async/rs->compiled-record)}) ;; thread local pool provider (thread-local (async/pool {:uri "postgresql://tfb-database:5432/hello_world" :user "benchmarkdbuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :size 1}))) ;; jdbc in worker-pool (= mode "sync") (exchange/dispatch (sync-db-handler (jdbc/context {:row (jdbc/rs->compiled-record)}) (hikari/make-datasource {:jdbc-url "jdbc:postgresql://tfb-database:5432/hello_world" :username "benchmarkdbuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :maximum-pool-size (* 8 cpus)}))) ;; none :else (constantly nil))] (-> (ring/ring-handler (ring/router [["/plaintext" (exchange/constantly plain-text-handler)] ["/json" json-handler] ["/db" db-handler]]) (ring/create-default-handler) {:inject-match? false :inject-router? false}) (server/create {:port 8080 :host "0.0.0.0" :io-threads (* 2 cpus) :worker-threads (* 8 cpus)}) (server/start))))
[ { "context": "\n(defn authenticated? [name pass]\n (and (= name \"mage\")\n (= pass \"priest\")))\n\n\n(def riemann-clien", "end": 1012, "score": 0.9942318201065063, "start": 1008, "tag": "USERNAME", "value": "mage" }, { "context": "name pass]\n (and (= name \"mage\")\n (= pass \"priest\")))\n\n\n(def riemann-client (atom nil))\n\n(defn form", "end": 1037, "score": 0.9934986233711243, "start": 1031, "tag": "PASSWORD", "value": "priest" }, { "context": " [[\"-l\" \"--listen\" \"listen on\" :default \"127.0.0.1\"]\n [\"-p\" \"--listen-port\" \"listen port\" :parse", "end": 2457, "score": 0.9997515082359314, "start": 2448, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " [\"-H\" \"--riemann-host\" \"riemann host\" :default \"127.0.0.1\"]\n [\"-P\" \"--riemann-port\" \"riemann port\" :parse", "end": 2600, "score": 0.9997522830963135, "start": 2591, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
src/riemann_grid/core.clj
codemomentum/riemann-grid
1
(ns riemann-grid.core (:require [compojure.core :refer [GET POST PUT DELETE defroutes]] [clojure.tools.cli :refer [cli]] [riemann.client :refer [tcp-client query]] [ring.middleware.json :refer [wrap-json-body wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]] [ring.middleware.stacktrace :refer [wrap-stacktrace]] [ring.middleware.reload :refer [wrap-reload]] [ring.util.response :refer [response status content-type charset]] [ring.adapter.jetty :refer [run-jetty]] [riemann-grid.views :as views] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]]) (:gen-class)) (defn authenticated? [name pass] (and (= name "mage") (= pass "priest"))) (def riemann-client (atom nil)) (defn format-host-states [[host states]] [host (->> states (group-by :service) (map (juxt key (comp first val))) (reduce merge {}))]) (defn format-states [states] {:hosts (->> states (group-by :host) keys sort) :services (->> states (group-by :service) keys sort) :events (->> states (group-by :host) (map format-host-states) (reduce merge {}))}) (defroutes main-routes (POST "/api/states" {{:keys [q]} :body} (->> (query @riemann-client q) (map #(->> % seq (map (partial apply hash-map)) (reduce merge))) (vec) format-states response)) (GET "/" [] (-> (response (views/main)) (content-type "text/html") (charset "UTF-8"))) (GET "/tpl/host.html" [] (-> (response (views/host)) (content-type "text/html") (charset "UTF-8"))) (GET "/tpl/grid.html" [] (-> (response (views/grid)) (content-type "text/html") (charset "UTF-8")))) (def api-handler (-> main-routes (wrap-json-body {:keywords? true}) (wrap-json-response) (wrap-resource "public") (wrap-basic-authentication authenticated?))) (def cli-opts [["-l" "--listen" "listen on" :default "127.0.0.1"] ["-p" "--listen-port" "listen port" :parse-fn #(Integer. %) :default 8484] ["-H" "--riemann-host" "riemann host" :default "127.0.0.1"] ["-P" "--riemann-port" "riemann port" :parse-fn #(Integer. %) :default 5555] ["-h" "--help" "show help" :flag true :default false] ["-e" "--env" "environment" :default "production"]]) (defn -main [& args] (let [[options args banner] (apply cli args cli-opts)] (when (:help options) (println banner) (System/exit 0)) (reset! riemann-client (tcp-client :host (:riemann-host options) :port (:riemann-port options))) (run-jetty (if (= "development" (:env options)) (-> api-handler (wrap-reload)) api-handler) {:address (:listen options) :port (:listen-port options)})))
99517
(ns riemann-grid.core (:require [compojure.core :refer [GET POST PUT DELETE defroutes]] [clojure.tools.cli :refer [cli]] [riemann.client :refer [tcp-client query]] [ring.middleware.json :refer [wrap-json-body wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]] [ring.middleware.stacktrace :refer [wrap-stacktrace]] [ring.middleware.reload :refer [wrap-reload]] [ring.util.response :refer [response status content-type charset]] [ring.adapter.jetty :refer [run-jetty]] [riemann-grid.views :as views] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]]) (:gen-class)) (defn authenticated? [name pass] (and (= name "mage") (= pass "<PASSWORD>"))) (def riemann-client (atom nil)) (defn format-host-states [[host states]] [host (->> states (group-by :service) (map (juxt key (comp first val))) (reduce merge {}))]) (defn format-states [states] {:hosts (->> states (group-by :host) keys sort) :services (->> states (group-by :service) keys sort) :events (->> states (group-by :host) (map format-host-states) (reduce merge {}))}) (defroutes main-routes (POST "/api/states" {{:keys [q]} :body} (->> (query @riemann-client q) (map #(->> % seq (map (partial apply hash-map)) (reduce merge))) (vec) format-states response)) (GET "/" [] (-> (response (views/main)) (content-type "text/html") (charset "UTF-8"))) (GET "/tpl/host.html" [] (-> (response (views/host)) (content-type "text/html") (charset "UTF-8"))) (GET "/tpl/grid.html" [] (-> (response (views/grid)) (content-type "text/html") (charset "UTF-8")))) (def api-handler (-> main-routes (wrap-json-body {:keywords? true}) (wrap-json-response) (wrap-resource "public") (wrap-basic-authentication authenticated?))) (def cli-opts [["-l" "--listen" "listen on" :default "127.0.0.1"] ["-p" "--listen-port" "listen port" :parse-fn #(Integer. %) :default 8484] ["-H" "--riemann-host" "riemann host" :default "127.0.0.1"] ["-P" "--riemann-port" "riemann port" :parse-fn #(Integer. %) :default 5555] ["-h" "--help" "show help" :flag true :default false] ["-e" "--env" "environment" :default "production"]]) (defn -main [& args] (let [[options args banner] (apply cli args cli-opts)] (when (:help options) (println banner) (System/exit 0)) (reset! riemann-client (tcp-client :host (:riemann-host options) :port (:riemann-port options))) (run-jetty (if (= "development" (:env options)) (-> api-handler (wrap-reload)) api-handler) {:address (:listen options) :port (:listen-port options)})))
true
(ns riemann-grid.core (:require [compojure.core :refer [GET POST PUT DELETE defroutes]] [clojure.tools.cli :refer [cli]] [riemann.client :refer [tcp-client query]] [ring.middleware.json :refer [wrap-json-body wrap-json-response]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]] [ring.middleware.stacktrace :refer [wrap-stacktrace]] [ring.middleware.reload :refer [wrap-reload]] [ring.util.response :refer [response status content-type charset]] [ring.adapter.jetty :refer [run-jetty]] [riemann-grid.views :as views] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]]) (:gen-class)) (defn authenticated? [name pass] (and (= name "mage") (= pass "PI:PASSWORD:<PASSWORD>END_PI"))) (def riemann-client (atom nil)) (defn format-host-states [[host states]] [host (->> states (group-by :service) (map (juxt key (comp first val))) (reduce merge {}))]) (defn format-states [states] {:hosts (->> states (group-by :host) keys sort) :services (->> states (group-by :service) keys sort) :events (->> states (group-by :host) (map format-host-states) (reduce merge {}))}) (defroutes main-routes (POST "/api/states" {{:keys [q]} :body} (->> (query @riemann-client q) (map #(->> % seq (map (partial apply hash-map)) (reduce merge))) (vec) format-states response)) (GET "/" [] (-> (response (views/main)) (content-type "text/html") (charset "UTF-8"))) (GET "/tpl/host.html" [] (-> (response (views/host)) (content-type "text/html") (charset "UTF-8"))) (GET "/tpl/grid.html" [] (-> (response (views/grid)) (content-type "text/html") (charset "UTF-8")))) (def api-handler (-> main-routes (wrap-json-body {:keywords? true}) (wrap-json-response) (wrap-resource "public") (wrap-basic-authentication authenticated?))) (def cli-opts [["-l" "--listen" "listen on" :default "127.0.0.1"] ["-p" "--listen-port" "listen port" :parse-fn #(Integer. %) :default 8484] ["-H" "--riemann-host" "riemann host" :default "127.0.0.1"] ["-P" "--riemann-port" "riemann port" :parse-fn #(Integer. %) :default 5555] ["-h" "--help" "show help" :flag true :default false] ["-e" "--env" "environment" :default "production"]]) (defn -main [& args] (let [[options args banner] (apply cli args cli-opts)] (when (:help options) (println banner) (System/exit 0)) (reset! riemann-client (tcp-client :host (:riemann-host options) :port (:riemann-port options))) (run-jetty (if (= "development" (:env options)) (-> api-handler (wrap-reload)) api-handler) {:address (:listen options) :port (:listen-port options)})))
[ { "context": "--------------------\n;; File def.clj\n;; Written by Chris\n;; \n;; Created 30 Aug 2012\n;; Last modified 20 Oc", "end": 108, "score": 0.9998192191123962, "start": 103, "tag": "NAME", "value": "Chris" } ]
src/ctco/expr/def.clj
cjfrisz/clojure-tco
64
;;---------------------------------------------------------------------- ;; File def.clj ;; Written by Chris ;; ;; Created 30 Aug 2012 ;; Last modified 20 Oct 2012 ;; ;; Defines the DefSrs, DefTriv, and DefCps record types for representing ;; 'def' expression in the Clojure TCO compiler. ;; ;; DefCps implements the following protocols: ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefCps with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefCps with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PThunkify: ;; Applies thunkify to the init expression, generating a ;; new DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; DefSrs implements the following protocols: ;; ;; PCpsSrs: ;; Applies cps-srs to the init expression, generating a new ;; DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefSrs with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefSrs with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; DefTriv implements the following protocols: ;; ;; PCpsTriv: ;; Applies cps-srs to the init expression, generating a new ;; DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefTriv with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefTriv with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; DefCps, DefSrs, and DefTriv have the same implementations for the ;; following protocols: ;; ;; PUnparse: ;; Returns a sequence representing the expression as an ;; s-expression, recursively unparsing the symbol and init ;; value. I.e., `(def ~(unparse sym) ~(unparse init)) ;; ;; PWalkable: ;; Applies the given function to the init expression, ;; returning a new DefCps, DefSrs, or DefTriv with the same ;; symbol name depending on the given constructor. ;;---------------------------------------------------------------------- (ns ctco.expr.def (:require [ctco.protocol :as proto] [ctco.util :as util])) (defrecord DefCps [sym init] proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefCps. %1 %2))) proto/PThunkify (thunkify [this] (proto/walk-expr this proto/thunkify #(DefCps. %1 %2)))) (defrecord DefSrs [sym init] proto/PCpsSrs (cps-srs [this k] (proto/walk-expr this #(proto/cps-srs % k) #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefSrs. %1 %2))) proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefSrs. %1 %2))) proto/PUnRecurify (unrecurify [this name] (proto/walk-expr this #(proto/unrecurify % name) #(DefSrs. %1 %2)))) (defrecord DefTriv [sym init] proto/PCpsTriv (cps-triv [this] (proto/walk-expr this proto/cps-triv #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefTriv. %1 %2))) proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefTriv. %1 %2))) proto/PUnRecurify (unrecurify [this name] (proto/walk-expr this #(proto/unrecurify % name) #(DefTriv. %1 %2)))) (util/extend-multi (DefCps DefSrs DefTriv) proto/PUnparse (unparse [this] `(def ~(proto/unparse (:sym this)) ~(proto/unparse (:init this)))) proto/PWalkable (walk-expr [this f ctor] (ctor (:sym this) (f (:init this)))))
93677
;;---------------------------------------------------------------------- ;; File def.clj ;; Written by <NAME> ;; ;; Created 30 Aug 2012 ;; Last modified 20 Oct 2012 ;; ;; Defines the DefSrs, DefTriv, and DefCps record types for representing ;; 'def' expression in the Clojure TCO compiler. ;; ;; DefCps implements the following protocols: ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefCps with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefCps with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PThunkify: ;; Applies thunkify to the init expression, generating a ;; new DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; DefSrs implements the following protocols: ;; ;; PCpsSrs: ;; Applies cps-srs to the init expression, generating a new ;; DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefSrs with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefSrs with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; DefTriv implements the following protocols: ;; ;; PCpsTriv: ;; Applies cps-srs to the init expression, generating a new ;; DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefTriv with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefTriv with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; DefCps, DefSrs, and DefTriv have the same implementations for the ;; following protocols: ;; ;; PUnparse: ;; Returns a sequence representing the expression as an ;; s-expression, recursively unparsing the symbol and init ;; value. I.e., `(def ~(unparse sym) ~(unparse init)) ;; ;; PWalkable: ;; Applies the given function to the init expression, ;; returning a new DefCps, DefSrs, or DefTriv with the same ;; symbol name depending on the given constructor. ;;---------------------------------------------------------------------- (ns ctco.expr.def (:require [ctco.protocol :as proto] [ctco.util :as util])) (defrecord DefCps [sym init] proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefCps. %1 %2))) proto/PThunkify (thunkify [this] (proto/walk-expr this proto/thunkify #(DefCps. %1 %2)))) (defrecord DefSrs [sym init] proto/PCpsSrs (cps-srs [this k] (proto/walk-expr this #(proto/cps-srs % k) #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefSrs. %1 %2))) proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefSrs. %1 %2))) proto/PUnRecurify (unrecurify [this name] (proto/walk-expr this #(proto/unrecurify % name) #(DefSrs. %1 %2)))) (defrecord DefTriv [sym init] proto/PCpsTriv (cps-triv [this] (proto/walk-expr this proto/cps-triv #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefTriv. %1 %2))) proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefTriv. %1 %2))) proto/PUnRecurify (unrecurify [this name] (proto/walk-expr this #(proto/unrecurify % name) #(DefTriv. %1 %2)))) (util/extend-multi (DefCps DefSrs DefTriv) proto/PUnparse (unparse [this] `(def ~(proto/unparse (:sym this)) ~(proto/unparse (:init this)))) proto/PWalkable (walk-expr [this f ctor] (ctor (:sym this) (f (:init this)))))
true
;;---------------------------------------------------------------------- ;; File def.clj ;; Written by PI:NAME:<NAME>END_PI ;; ;; Created 30 Aug 2012 ;; Last modified 20 Oct 2012 ;; ;; Defines the DefSrs, DefTriv, and DefCps record types for representing ;; 'def' expression in the Clojure TCO compiler. ;; ;; DefCps implements the following protocols: ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefCps with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefCps with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PThunkify: ;; Applies thunkify to the init expression, generating a ;; new DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; DefSrs implements the following protocols: ;; ;; PCpsSrs: ;; Applies cps-srs to the init expression, generating a new ;; DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefSrs with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefSrs with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; DefTriv implements the following protocols: ;; ;; PCpsTriv: ;; Applies cps-srs to the init expression, generating a new ;; DefCps with the same symbol name. Uses the walk-expr ;; function provided by PWalkable. ;; ;; PRecurify: ;; Applies recurify to the init expression, generating a ;; new DefTriv with the same symbol name. Since a 'def' ;; expression is not considered a tail call, uses 'false' ;; for the 'tail?' value in the recursive calls and 'nil' ;; for name. Uses the walk-expr function provided by ;; PWalkable. ;; ;; PLoadTrampoline: ;; Applies load-tramp to the init expression for the given ;; trampoline function name, generating a new DefTriv with ;; the same symbol name. Uses the walk-expr function ;; provided by PWalkable. ;; ;; DefCps, DefSrs, and DefTriv have the same implementations for the ;; following protocols: ;; ;; PUnparse: ;; Returns a sequence representing the expression as an ;; s-expression, recursively unparsing the symbol and init ;; value. I.e., `(def ~(unparse sym) ~(unparse init)) ;; ;; PWalkable: ;; Applies the given function to the init expression, ;; returning a new DefCps, DefSrs, or DefTriv with the same ;; symbol name depending on the given constructor. ;;---------------------------------------------------------------------- (ns ctco.expr.def (:require [ctco.protocol :as proto] [ctco.util :as util])) (defrecord DefCps [sym init] proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefCps. %1 %2))) proto/PThunkify (thunkify [this] (proto/walk-expr this proto/thunkify #(DefCps. %1 %2)))) (defrecord DefSrs [sym init] proto/PCpsSrs (cps-srs [this k] (proto/walk-expr this #(proto/cps-srs % k) #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefSrs. %1 %2))) proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefSrs. %1 %2))) proto/PUnRecurify (unrecurify [this name] (proto/walk-expr this #(proto/unrecurify % name) #(DefSrs. %1 %2)))) (defrecord DefTriv [sym init] proto/PCpsTriv (cps-triv [this] (proto/walk-expr this proto/cps-triv #(DefCps. %1 %2))) proto/PRecurify (recurify [this name arity tail?] (proto/walk-expr this #(proto/recurify % nil nil false) #(DefTriv. %1 %2))) proto/PLoadTrampoline (load-tramp [this tramp] (proto/walk-expr this #(proto/load-tramp % tramp) #(DefTriv. %1 %2))) proto/PUnRecurify (unrecurify [this name] (proto/walk-expr this #(proto/unrecurify % name) #(DefTriv. %1 %2)))) (util/extend-multi (DefCps DefSrs DefTriv) proto/PUnparse (unparse [this] `(def ~(proto/unparse (:sym this)) ~(proto/unparse (:init this)))) proto/PWalkable (walk-expr [this f ctor] (ctor (:sym this) (f (:init this)))))
[ { "context": " be solved by another level of\n;; indirection.\" -- David Wheeler\n;; \n\n;;; Exercise 4\n\n\n(def apply-message-to\n ", "end": 3103, "score": 0.9960737228393555, "start": 3090, "tag": "NAME", "value": "David Wheeler" } ]
func-prog/fp-oo/solutions/class.clj
tannerwelsh/code-training
5
;;; Exercise 1 (def method-from-message (fn [message class] (message (:__instance_methods__ class)))) (def class-from-instance (fn [instance] (eval (:__class_symbol__ instance)))) (def apply-message-to (fn [class instance message args] (apply (method-from-message message class) instance args))) (def make (fn [class & args] (let [seeded {:__class_symbol__ (:__own_symbol__ class)}] (apply-message-to class seeded :add-instance-values args)))) (def send-to (fn [instance message & args] (apply-message-to (class-from-instance instance) instance message args))) ;; For example: (prn (send-to (make Point 1 2) :class)) (prn (send-to (make Point 1 2) :shift -1 -2)) ;;; Exercise 2 (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) ;; ^^^^^== New :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to (make Point 1 2) :class-name) (send-to (make Point 1 2) :class) ;;; Exercise 3 (def my-point (make Point 1 2)) (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :origin (fn [this] (make Point 0 0)) ;; ^^^^^== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to my-point :origin) ;; Redefining a class changes the behavior of existing instances ;; because having an instance's :__class_symbol__ be a symbol that's ;; later `eval`ed adds a level of indirection. If the value were a ;; class map itself, changing the binding or association of `Point` ;; would have no effect on existing instances, just new ones. ;; ;; You could see that with this code: ;; user=> (def Point "the original definition of Point") ;; user=> (def a-point {:__class_NOT_symbol__ Point}) ;; user=> (def Point "the new definition of Point") ;; user=> a-point ;; {:__class_NOT_symbol__ "the original definition of Point"} ;; ;; If that's not clear, apply the substitution rule to the `def` lines. ;; (Note that `def` is another special symbol. It does not evaluate its ;; first argument, just the second.) ;; ;; "All problems in computer science can be solved by another level of ;; indirection." -- David Wheeler ;; ;;; Exercise 4 (def apply-message-to (fn [class instance message args] (let [method (or (method-from-message message class) message)] (apply method instance args)))) (prn (send-to (make Holder "stuff") :held))
2212
;;; Exercise 1 (def method-from-message (fn [message class] (message (:__instance_methods__ class)))) (def class-from-instance (fn [instance] (eval (:__class_symbol__ instance)))) (def apply-message-to (fn [class instance message args] (apply (method-from-message message class) instance args))) (def make (fn [class & args] (let [seeded {:__class_symbol__ (:__own_symbol__ class)}] (apply-message-to class seeded :add-instance-values args)))) (def send-to (fn [instance message & args] (apply-message-to (class-from-instance instance) instance message args))) ;; For example: (prn (send-to (make Point 1 2) :class)) (prn (send-to (make Point 1 2) :shift -1 -2)) ;;; Exercise 2 (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) ;; ^^^^^== New :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to (make Point 1 2) :class-name) (send-to (make Point 1 2) :class) ;;; Exercise 3 (def my-point (make Point 1 2)) (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :origin (fn [this] (make Point 0 0)) ;; ^^^^^== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to my-point :origin) ;; Redefining a class changes the behavior of existing instances ;; because having an instance's :__class_symbol__ be a symbol that's ;; later `eval`ed adds a level of indirection. If the value were a ;; class map itself, changing the binding or association of `Point` ;; would have no effect on existing instances, just new ones. ;; ;; You could see that with this code: ;; user=> (def Point "the original definition of Point") ;; user=> (def a-point {:__class_NOT_symbol__ Point}) ;; user=> (def Point "the new definition of Point") ;; user=> a-point ;; {:__class_NOT_symbol__ "the original definition of Point"} ;; ;; If that's not clear, apply the substitution rule to the `def` lines. ;; (Note that `def` is another special symbol. It does not evaluate its ;; first argument, just the second.) ;; ;; "All problems in computer science can be solved by another level of ;; indirection." -- <NAME> ;; ;;; Exercise 4 (def apply-message-to (fn [class instance message args] (let [method (or (method-from-message message class) message)] (apply method instance args)))) (prn (send-to (make Holder "stuff") :held))
true
;;; Exercise 1 (def method-from-message (fn [message class] (message (:__instance_methods__ class)))) (def class-from-instance (fn [instance] (eval (:__class_symbol__ instance)))) (def apply-message-to (fn [class instance message args] (apply (method-from-message message class) instance args))) (def make (fn [class & args] (let [seeded {:__class_symbol__ (:__own_symbol__ class)}] (apply-message-to class seeded :add-instance-values args)))) (def send-to (fn [instance message & args] (apply-message-to (class-from-instance instance) instance message args))) ;; For example: (prn (send-to (make Point 1 2) :class)) (prn (send-to (make Point 1 2) :shift -1 -2)) ;;; Exercise 2 (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) ;; ^^^^^== New :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to (make Point 1 2) :class-name) (send-to (make Point 1 2) :class) ;;; Exercise 3 (def my-point (make Point 1 2)) (def Point { :__own_symbol__ 'Point :__instance_methods__ { :add-instance-values (fn [this x y] (assoc this :x x :y y)) ;; vvvvv== New :origin (fn [this] (make Point 0 0)) ;; ^^^^^== New :class-name :__class_symbol__ :class (fn [this] (class-from-instance this)) :shift (fn [this xinc yinc] (make Point (+ (:x this) xinc) (+ (:y this) yinc))) :add (fn [this other] (send-to this :shift (:x other) (:y other))) } }) (send-to my-point :origin) ;; Redefining a class changes the behavior of existing instances ;; because having an instance's :__class_symbol__ be a symbol that's ;; later `eval`ed adds a level of indirection. If the value were a ;; class map itself, changing the binding or association of `Point` ;; would have no effect on existing instances, just new ones. ;; ;; You could see that with this code: ;; user=> (def Point "the original definition of Point") ;; user=> (def a-point {:__class_NOT_symbol__ Point}) ;; user=> (def Point "the new definition of Point") ;; user=> a-point ;; {:__class_NOT_symbol__ "the original definition of Point"} ;; ;; If that's not clear, apply the substitution rule to the `def` lines. ;; (Note that `def` is another special symbol. It does not evaluate its ;; first argument, just the second.) ;; ;; "All problems in computer science can be solved by another level of ;; indirection." -- PI:NAME:<NAME>END_PI ;; ;;; Exercise 4 (def apply-message-to (fn [class instance message args] (let [method (or (method-from-message message class) message)] (apply method instance args)))) (prn (send-to (make Holder "stuff") :held))
[ { "context": "ed on 4 By 4 Skyscrapers and 6 By 6 Skyscrapers by FrankK.\n; By now, examples should be superfluous; you sh", "end": 670, "score": 0.9228473901748657, "start": 664, "tag": "NAME", "value": "FrankK" } ]
src/main/clojure/pl/tomaszgigiel/palestra/codewars/skyscrapers7.clj
tomaszgigiel/palestra
0
(ns pl.tomaszgigiel.palestra.codewars.skyscrapers7 (:gen-class)) ; https://www.codewars.com/kata/7x7-skyscrapers/train/clojure ; In a grid of 7 by 7 squares you want to place a skyscraper in each square with only some clues: ; The height of the skyscrapers is between 1 and 7 ; No two skyscrapers in a row or column may have the same number of floors ; A clue is the number of skyscrapers that you can see in a row or column from the outside ; Higher skyscrapers block the view of lower skyscrapers located behind them ; Can you write a program that can solve this puzzle in time? ; This kata is based on 4 By 4 Skyscrapers and 6 By 6 Skyscrapers by FrankK. ; By now, examples should be superfluous; you should really solve Frank's kata first, and then probably optimise some more. ; A naive solution that solved a 4×4 puzzle within 12 seconds might need time somewhere beyond the Heat Death of the Universe for this size. ; It's quite bad. ; Task ; Create ; (defn solve-puzzle [clues] ) ; Clues are passed in as a vector[28] of ints The return value is a vector[7] of vector[7] of ints ; All puzzles have one possible solution. ; All this is the same as with the earlier kata. ; Caveat: The tests for this kata have been tailored to run in ~10 seconds with the JavaScript reference solution. ; You'll need to do better than that! Please note the optimization tag. ; Conceptis Puzzles have heaps of these puzzles, from 5×5 (they don't even bother with 4×4) up to 7×7 ; and unsolvable within CodeWars time constraints. Old puzzles from there were used for the tests. ; They also have lots of other logic, numbers and mathematical puzzles, and their puzzle user interface is generally nice, very nice. ; (It is, however, Flash, and their mobile offerings are far fewer. Desktop PC recommended.) (defn solve-puzzle [clues] ; Start your coding here... )
87021
(ns pl.tomaszgigiel.palestra.codewars.skyscrapers7 (:gen-class)) ; https://www.codewars.com/kata/7x7-skyscrapers/train/clojure ; In a grid of 7 by 7 squares you want to place a skyscraper in each square with only some clues: ; The height of the skyscrapers is between 1 and 7 ; No two skyscrapers in a row or column may have the same number of floors ; A clue is the number of skyscrapers that you can see in a row or column from the outside ; Higher skyscrapers block the view of lower skyscrapers located behind them ; Can you write a program that can solve this puzzle in time? ; This kata is based on 4 By 4 Skyscrapers and 6 By 6 Skyscrapers by <NAME>. ; By now, examples should be superfluous; you should really solve Frank's kata first, and then probably optimise some more. ; A naive solution that solved a 4×4 puzzle within 12 seconds might need time somewhere beyond the Heat Death of the Universe for this size. ; It's quite bad. ; Task ; Create ; (defn solve-puzzle [clues] ) ; Clues are passed in as a vector[28] of ints The return value is a vector[7] of vector[7] of ints ; All puzzles have one possible solution. ; All this is the same as with the earlier kata. ; Caveat: The tests for this kata have been tailored to run in ~10 seconds with the JavaScript reference solution. ; You'll need to do better than that! Please note the optimization tag. ; Conceptis Puzzles have heaps of these puzzles, from 5×5 (they don't even bother with 4×4) up to 7×7 ; and unsolvable within CodeWars time constraints. Old puzzles from there were used for the tests. ; They also have lots of other logic, numbers and mathematical puzzles, and their puzzle user interface is generally nice, very nice. ; (It is, however, Flash, and their mobile offerings are far fewer. Desktop PC recommended.) (defn solve-puzzle [clues] ; Start your coding here... )
true
(ns pl.tomaszgigiel.palestra.codewars.skyscrapers7 (:gen-class)) ; https://www.codewars.com/kata/7x7-skyscrapers/train/clojure ; In a grid of 7 by 7 squares you want to place a skyscraper in each square with only some clues: ; The height of the skyscrapers is between 1 and 7 ; No two skyscrapers in a row or column may have the same number of floors ; A clue is the number of skyscrapers that you can see in a row or column from the outside ; Higher skyscrapers block the view of lower skyscrapers located behind them ; Can you write a program that can solve this puzzle in time? ; This kata is based on 4 By 4 Skyscrapers and 6 By 6 Skyscrapers by PI:NAME:<NAME>END_PI. ; By now, examples should be superfluous; you should really solve Frank's kata first, and then probably optimise some more. ; A naive solution that solved a 4×4 puzzle within 12 seconds might need time somewhere beyond the Heat Death of the Universe for this size. ; It's quite bad. ; Task ; Create ; (defn solve-puzzle [clues] ) ; Clues are passed in as a vector[28] of ints The return value is a vector[7] of vector[7] of ints ; All puzzles have one possible solution. ; All this is the same as with the earlier kata. ; Caveat: The tests for this kata have been tailored to run in ~10 seconds with the JavaScript reference solution. ; You'll need to do better than that! Please note the optimization tag. ; Conceptis Puzzles have heaps of these puzzles, from 5×5 (they don't even bother with 4×4) up to 7×7 ; and unsolvable within CodeWars time constraints. Old puzzles from there were used for the tests. ; They also have lots of other logic, numbers and mathematical puzzles, and their puzzle user interface is generally nice, very nice. ; (It is, however, Flash, and their mobile offerings are far fewer. Desktop PC recommended.) (defn solve-puzzle [clues] ; Start your coding here... )
[ { "context": "e hello method\n; all evaluations are lazy\n(hello \"Super Suave\")\n\n", "end": 290, "score": 0.9860925674438477, "start": 279, "tag": "NAME", "value": "Super Suave" } ]
clojure/methods/methods.clj
miroadamy/language-matrix
15
(comment defn defines a method hello is the name of the method [name] is the argument, dynamically typed println is another method call that will println out the name) (defn hello [name] (println "Hello,", name)) ; calling the hello method ; all evaluations are lazy (hello "Super Suave")
48705
(comment defn defines a method hello is the name of the method [name] is the argument, dynamically typed println is another method call that will println out the name) (defn hello [name] (println "Hello,", name)) ; calling the hello method ; all evaluations are lazy (hello "<NAME>")
true
(comment defn defines a method hello is the name of the method [name] is the argument, dynamically typed println is another method call that will println out the name) (defn hello [name] (println "Hello,", name)) ; calling the hello method ; all evaluations are lazy (hello "PI:NAME:<NAME>END_PI")
[ { "context": "t:45432/demo?currentSchema=repl&user=dev&password=ts3rs\"\n :server-port 5001})\n\n(defonce app (start-app!", "end": 168, "score": 0.9983393549919128, "start": 163, "tag": "PASSWORD", "value": "ts3rs" } ]
dev/src/dev_repl.clj
tav10102/clojure-ui-testing-demo
1
(ns dev-repl (:require [tunk.main :refer [start-app!]])) (def repl-conf {:db-uri "postgresql://localhost:45432/demo?currentSchema=repl&user=dev&password=ts3rs" :server-port 5001}) (defonce app (start-app! repl-conf)) (def ctx (:ctx app))
68188
(ns dev-repl (:require [tunk.main :refer [start-app!]])) (def repl-conf {:db-uri "postgresql://localhost:45432/demo?currentSchema=repl&user=dev&password=<PASSWORD>" :server-port 5001}) (defonce app (start-app! repl-conf)) (def ctx (:ctx app))
true
(ns dev-repl (:require [tunk.main :refer [start-app!]])) (def repl-conf {:db-uri "postgresql://localhost:45432/demo?currentSchema=repl&user=dev&password=PI:PASSWORD:<PASSWORD>END_PI" :server-port 5001}) (defonce app (start-app! repl-conf)) (def ctx (:ctx app))
[ { "context": "ServerName jira.meissa-gmbh.de\"\r\n \" ServerAdmin admin@jira.meissa-gmbh.de\"\r\n \" \"\r\n \" ErrorLog \\\"/var/l", "end": 1153, "score": 0.9478259682655334, "start": 1143, "tag": "EMAIL", "value": "admin@jira" }, { "context": "ira.meissa-gmbh.de\"\r\n \" ServerAdmin admin@jira.meissa-gmbh.de\"\r\n \" \"\r\n \" ErrorLog \\\"/var/log/apache2/erro", "end": 1168, "score": 0.7885556817054749, "start": 1154, "tag": "EMAIL", "value": "meissa-gmbh.de" }, { "context": "ServerName jira.politaktiv.org\"\r\n \" ServerAdmin admin@jira.politaktiv.org\"\r\n \" \"\r\n \" ErrorLog \\\"/var/log/apache2/erro", "end": 1633, "score": 0.9993377923965454, "start": 1608, "tag": "EMAIL", "value": "admin@jira.politaktiv.org" }, { "context": "ServerName jira.meissa-gmbh.de\"\r\n \" ServerAdmin admin@jira.meissa-gmbh.de\"\r\n \" \"\r\n \" ProxyPreserveHost", "end": 2084, "score": 0.9055454134941101, "start": 2074, "tag": "EMAIL", "value": "admin@jira" }, { "context": "ira.meissa-gmbh.de\"\r\n \" ServerAdmin admin@jira.meissa-gmbh.de\"\r\n \" \"\r\n \" ProxyPreserveHost On\"\r\n \" Pro", "end": 2099, "score": 0.8253175020217896, "start": 2085, "tag": "EMAIL", "value": "meissa-gmbh.de" }, { "context": "ServerName jira.meissa-gmbh.de\"\r\n \" ServerAdmin admin@jira.meissa-gmbh.de\"\r\n \" \"\r\n \" Header set A", "end": 2906, "score": 0.810863733291626, "start": 2901, "tag": "EMAIL", "value": "admin" }, { "context": "ame jira.meissa-gmbh.de\"\r\n \" ServerAdmin admin@jira.meissa-gmbh.de\"\r\n \" \"\r\n \" Header set Access", "end": 2911, "score": 0.5227834582328796, "start": 2907, "tag": "EMAIL", "value": "jira" }, { "context": "ServerName jira.politaktiv.org\"\r\n \" ServerAdmin admin@jira.politaktiv.org\"\r\n \" \"\r\n \" ProxyPreserveHost On\"\r\n \" Pro", "end": 3827, "score": 0.9760963916778564, "start": 3802, "tag": "EMAIL", "value": "admin@jira.politaktiv.org" }, { "context": "t.domaindrivenarchitecture.org\"\r\n \" ServerAdmin admin@domaindrivenarchitecture.org\"\r\n \" \"\r\n \" DocumentRoot \\\"/var/www/test.dom", "end": 4659, "score": 0.9997667074203491, "start": 4625, "tag": "EMAIL", "value": "admin@domaindrivenarchitecture.org" }, { "context": " :listening-port \"443\"\r\n :server-admin-email \"admin@jira.meissa-gmbh.de\"\r\n :proxy {:target-port \"8080\"\r\n :add", "end": 5529, "score": 0.9991967082023621, "start": 5504, "tag": "EMAIL", "value": "admin@jira.meissa-gmbh.de" }, { "context": "equests Off\"]}\r\n :cert-letsencrypt {:email \"test.mail@m.de\"\r\n :domains [\"jira.meissa-gm", "end": 5729, "score": 0.9995110630989075, "start": 5715, "tag": "EMAIL", "value": "test.mail@m.de" }, { "context": " :listening-port \"443\"\r\n :server-admin-email \"admin@jira.meissa-gmbh.de\"\r\n :allow-origin \"*.meissa-gmbh.de\"\r\n :proxy ", "end": 5951, "score": 0.9998255372047424, "start": 5926, "tag": "EMAIL", "value": "admin@jira.meissa-gmbh.de" }, { "context": "equests Off\"]}\r\n :cert-letsencrypt {:email \"test.mail@m.de\"\r\n :domains [\"jira.meissa-gm", "end": 6188, "score": 0.999757707118988, "start": 6174, "tag": "EMAIL", "value": "test.mail@m.de" }, { "context": " :listening-port \"443\"\r\n :server-admin-email \"admin@jira.politaktiv.org\"\r\n :proxy {:target-port \"8180\"\r\n :add", "end": 6404, "score": 0.9999150037765503, "start": 6379, "tag": "EMAIL", "value": "admin@jira.politaktiv.org" }, { "context": " :listening-port \"443\",\r\n :server-admin-email \"admin@domaindrivenarchitecture.org\",\r\n :document-root \"/var/www/test.domaindrivena", "end": 6864, "score": 0.9999181032180786, "start": 6830, "tag": "EMAIL", "value": "admin@domaindrivenarchitecture.org" }, { "context": "lowOverride All\"]}\r\n :cert-letsencrypt {:email \"admin@domaindrivenarchitecture.org\",\r\n :domains [\"test.domaindr", "end": 7116, "score": 0.9999122619628906, "start": 7082, "tag": "EMAIL", "value": "admin@domaindrivenarchitecture.org" } ]
test/src/dda/pallet/dda_httpd_crate/infra/vhost_simple_test.clj
DomainDrivenArchitecture/dda-httpd-crate
2
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-httpd-crate.infra.vhost-simple-test (:require [clojure.test :refer :all] [schema.core :as s] [dda.pallet.dda-httpd-crate.infra.vhost :as sut] [httpd.crate.vhost :as vhost])) (def etc-apache2-sites-enabled-000-meissa-conf ["<VirtualHost *:80>" " ServerName jira.meissa-gmbh.de" " ServerAdmin admin@jira.meissa-gmbh.de" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/access.log\" combined" " " " RewriteEngine on" " RewriteCond %{HTTPS} !on" " RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-politaktiv-conf ["<VirtualHost *:80>" " ServerName jira.politaktiv.org" " ServerAdmin admin@jira.politaktiv.org" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/access.log\" combined" " " " RewriteEngine on" " RewriteCond %{HTTPS} !on" " RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-meissa-ssl-conf ["<VirtualHost *:443>" " ServerName jira.meissa-gmbh.de" " ServerAdmin admin@jira.meissa-gmbh.de" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8080/" " ProxyPassReverse / http://localhost:8080/" " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/jira.meissa-gmbh.de/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/jira.meissa-gmbh.de/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-meissa-ssl-with-origin ["<VirtualHost *:443>" " ServerName jira.meissa-gmbh.de" " ServerAdmin admin@jira.meissa-gmbh.de" " " " Header set Access-Control-Allow-Origin \"*.meissa-gmbh.de\"" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8080/" " ProxyPassReverse / http://localhost:8080/" " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/jira.meissa-gmbh.de/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/jira.meissa-gmbh.de/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-politaktiv-ssl-conf ["<VirtualHost *:443>" " ServerName jira.politaktiv.org" " ServerAdmin admin@jira.politaktiv.org" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8180/" " ProxyPassReverse / http://localhost:8180/" ;" " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/apache2/ssl.crt/jira.politaktiv.org.certs" " GnuTLSKeyFile /etc/apache2/ssl.key/jira.politaktiv.org.key" " " "</VirtualHost>"]) (def simple-with-directory-000-default-ssl-conf ["<VirtualHost *:443>" " ServerName test.domaindrivenarchitecture.org" " ServerAdmin admin@domaindrivenarchitecture.org" " " " DocumentRoot \"/var/www/test.domaindrivenarchitecture.org\"" " " " <Location />" " Options FollowSymLinks" " AllowOverride All" " </Location>" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/test.domaindrivenarchitecture.org/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/test.domaindrivenarchitecture.org/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-meissa-config {:domain-name "jira.meissa-gmbh.de" :listening-port "443" :server-admin-email "admin@jira.meissa-gmbh.de" :proxy {:target-port "8080" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-letsencrypt {:email "test.mail@m.de" :domains ["jira.meissa-gmbh.de"]}}) (def etc-apache2-meissa-config-with-origin {:domain-name "jira.meissa-gmbh.de" :listening-port "443" :server-admin-email "admin@jira.meissa-gmbh.de" :allow-origin "*.meissa-gmbh.de" :proxy {:target-port "8080" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-letsencrypt {:email "test.mail@m.de" :domains ["jira.meissa-gmbh.de"]}}) (def etc-apache2-politaktiv-config {:domain-name "jira.politaktiv.org" :listening-port "443" :server-admin-email "admin@jira.politaktiv.org" :proxy {:target-port "8180" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-manual {:domain-cert "domaincert" :domain-key "domainkey" :ca-cert "optional-ca-cert"}}) (def simple-with-directory {:domain-name "test.domaindrivenarchitecture.org", :listening-port "443", :server-admin-email "admin@domaindrivenarchitecture.org", :document-root "/var/www/test.domaindrivenarchitecture.org", :location {:locations-override ["Options FollowSymLinks" "AllowOverride All"]} :cert-letsencrypt {:email "admin@domaindrivenarchitecture.org", :domains ["test.domaindrivenarchitecture.org"]},}) (deftest vhost (testing "Test the creation of an example vhost from configuration." (is (= etc-apache2-sites-enabled-000-meissa-conf (vhost/vhost-conf-default-redirect-to-https-only :domain-name (get-in etc-apache2-meissa-config [:domain-name]) :server-admin-email (get-in etc-apache2-meissa-config [:server-admin-email])))) (is (= etc-apache2-sites-enabled-000-politaktiv-conf (vhost/vhost-conf-default-redirect-to-https-only :domain-name (get-in etc-apache2-politaktiv-config [:domain-name]) :server-admin-email (get-in etc-apache2-politaktiv-config [:server-admin-email])))) (is (= etc-apache2-sites-enabled-000-meissa-ssl-conf (sut/vhost etc-apache2-meissa-config))) (is (= etc-apache2-sites-enabled-000-politaktiv-ssl-conf (sut/vhost etc-apache2-politaktiv-config))) (is (= simple-with-directory-000-default-ssl-conf (sut/vhost simple-with-directory))) (is (= etc-apache2-sites-enabled-000-meissa-ssl-with-origin (sut/vhost etc-apache2-meissa-config-with-origin)))))
57560
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-httpd-crate.infra.vhost-simple-test (:require [clojure.test :refer :all] [schema.core :as s] [dda.pallet.dda-httpd-crate.infra.vhost :as sut] [httpd.crate.vhost :as vhost])) (def etc-apache2-sites-enabled-000-meissa-conf ["<VirtualHost *:80>" " ServerName jira.meissa-gmbh.de" " ServerAdmin <EMAIL>.<EMAIL>" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/access.log\" combined" " " " RewriteEngine on" " RewriteCond %{HTTPS} !on" " RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-politaktiv-conf ["<VirtualHost *:80>" " ServerName jira.politaktiv.org" " ServerAdmin <EMAIL>" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/access.log\" combined" " " " RewriteEngine on" " RewriteCond %{HTTPS} !on" " RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-meissa-ssl-conf ["<VirtualHost *:443>" " ServerName jira.meissa-gmbh.de" " ServerAdmin <EMAIL>.<EMAIL>" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8080/" " ProxyPassReverse / http://localhost:8080/" " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/jira.meissa-gmbh.de/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/jira.meissa-gmbh.de/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-meissa-ssl-with-origin ["<VirtualHost *:443>" " ServerName jira.meissa-gmbh.de" " ServerAdmin <EMAIL>@<EMAIL>.meissa-gmbh.de" " " " Header set Access-Control-Allow-Origin \"*.meissa-gmbh.de\"" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8080/" " ProxyPassReverse / http://localhost:8080/" " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/jira.meissa-gmbh.de/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/jira.meissa-gmbh.de/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-politaktiv-ssl-conf ["<VirtualHost *:443>" " ServerName jira.politaktiv.org" " ServerAdmin <EMAIL>" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8180/" " ProxyPassReverse / http://localhost:8180/" ;" " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/apache2/ssl.crt/jira.politaktiv.org.certs" " GnuTLSKeyFile /etc/apache2/ssl.key/jira.politaktiv.org.key" " " "</VirtualHost>"]) (def simple-with-directory-000-default-ssl-conf ["<VirtualHost *:443>" " ServerName test.domaindrivenarchitecture.org" " ServerAdmin <EMAIL>" " " " DocumentRoot \"/var/www/test.domaindrivenarchitecture.org\"" " " " <Location />" " Options FollowSymLinks" " AllowOverride All" " </Location>" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/test.domaindrivenarchitecture.org/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/test.domaindrivenarchitecture.org/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-meissa-config {:domain-name "jira.meissa-gmbh.de" :listening-port "443" :server-admin-email "<EMAIL>" :proxy {:target-port "8080" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-letsencrypt {:email "<EMAIL>" :domains ["jira.meissa-gmbh.de"]}}) (def etc-apache2-meissa-config-with-origin {:domain-name "jira.meissa-gmbh.de" :listening-port "443" :server-admin-email "<EMAIL>" :allow-origin "*.meissa-gmbh.de" :proxy {:target-port "8080" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-letsencrypt {:email "<EMAIL>" :domains ["jira.meissa-gmbh.de"]}}) (def etc-apache2-politaktiv-config {:domain-name "jira.politaktiv.org" :listening-port "443" :server-admin-email "<EMAIL>" :proxy {:target-port "8180" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-manual {:domain-cert "domaincert" :domain-key "domainkey" :ca-cert "optional-ca-cert"}}) (def simple-with-directory {:domain-name "test.domaindrivenarchitecture.org", :listening-port "443", :server-admin-email "<EMAIL>", :document-root "/var/www/test.domaindrivenarchitecture.org", :location {:locations-override ["Options FollowSymLinks" "AllowOverride All"]} :cert-letsencrypt {:email "<EMAIL>", :domains ["test.domaindrivenarchitecture.org"]},}) (deftest vhost (testing "Test the creation of an example vhost from configuration." (is (= etc-apache2-sites-enabled-000-meissa-conf (vhost/vhost-conf-default-redirect-to-https-only :domain-name (get-in etc-apache2-meissa-config [:domain-name]) :server-admin-email (get-in etc-apache2-meissa-config [:server-admin-email])))) (is (= etc-apache2-sites-enabled-000-politaktiv-conf (vhost/vhost-conf-default-redirect-to-https-only :domain-name (get-in etc-apache2-politaktiv-config [:domain-name]) :server-admin-email (get-in etc-apache2-politaktiv-config [:server-admin-email])))) (is (= etc-apache2-sites-enabled-000-meissa-ssl-conf (sut/vhost etc-apache2-meissa-config))) (is (= etc-apache2-sites-enabled-000-politaktiv-ssl-conf (sut/vhost etc-apache2-politaktiv-config))) (is (= simple-with-directory-000-default-ssl-conf (sut/vhost simple-with-directory))) (is (= etc-apache2-sites-enabled-000-meissa-ssl-with-origin (sut/vhost etc-apache2-meissa-config-with-origin)))))
true
; Licensed to the Apache Software Foundation (ASF) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file ; to you under the Apache License, Version 2.0 (the ; "License"); you may not use this file except in compliance ; with the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns dda.pallet.dda-httpd-crate.infra.vhost-simple-test (:require [clojure.test :refer :all] [schema.core :as s] [dda.pallet.dda-httpd-crate.infra.vhost :as sut] [httpd.crate.vhost :as vhost])) (def etc-apache2-sites-enabled-000-meissa-conf ["<VirtualHost *:80>" " ServerName jira.meissa-gmbh.de" " ServerAdmin PI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/access.log\" combined" " " " RewriteEngine on" " RewriteCond %{HTTPS} !on" " RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-politaktiv-conf ["<VirtualHost *:80>" " ServerName jira.politaktiv.org" " ServerAdmin PI:EMAIL:<EMAIL>END_PI" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/access.log\" combined" " " " RewriteEngine on" " RewriteCond %{HTTPS} !on" " RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-meissa-ssl-conf ["<VirtualHost *:443>" " ServerName jira.meissa-gmbh.de" " ServerAdmin PI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8080/" " ProxyPassReverse / http://localhost:8080/" " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/jira.meissa-gmbh.de/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/jira.meissa-gmbh.de/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-meissa-ssl-with-origin ["<VirtualHost *:443>" " ServerName jira.meissa-gmbh.de" " ServerAdmin PI:EMAIL:<EMAIL>END_PI@PI:EMAIL:<EMAIL>END_PI.meissa-gmbh.de" " " " Header set Access-Control-Allow-Origin \"*.meissa-gmbh.de\"" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8080/" " ProxyPassReverse / http://localhost:8080/" " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/jira.meissa-gmbh.de/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/jira.meissa-gmbh.de/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-sites-enabled-000-politaktiv-ssl-conf ["<VirtualHost *:443>" " ServerName jira.politaktiv.org" " ServerAdmin PI:EMAIL:<EMAIL>END_PI" " " " ProxyPreserveHost On" " ProxyRequests Off" " ProxyPass / http://localhost:8180/" " ProxyPassReverse / http://localhost:8180/" ;" " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/apache2/ssl.crt/jira.politaktiv.org.certs" " GnuTLSKeyFile /etc/apache2/ssl.key/jira.politaktiv.org.key" " " "</VirtualHost>"]) (def simple-with-directory-000-default-ssl-conf ["<VirtualHost *:443>" " ServerName test.domaindrivenarchitecture.org" " ServerAdmin PI:EMAIL:<EMAIL>END_PI" " " " DocumentRoot \"/var/www/test.domaindrivenarchitecture.org\"" " " " <Location />" " Options FollowSymLinks" " AllowOverride All" " </Location>" " " " ErrorLog \"/var/log/apache2/error.log\"" " LogLevel warn" " CustomLog \"/var/log/apache2/ssl-access.log\" combined" " " " GnuTLSEnable on" " GnuTLSPriorities SECURE:!VERS-SSL3.0:!MD5:!DHE-RSA:!DHE-DSS:!AES-256-CBC:%COMPAT" " GnuTLSExportCertificates on" " " " GnuTLSCertificateFile /etc/letsencrypt/live/test.domaindrivenarchitecture.org/fullchain.pem" " GnuTLSKeyFile /etc/letsencrypt/live/test.domaindrivenarchitecture.org/privkey.pem" " " "</VirtualHost>"]) (def etc-apache2-meissa-config {:domain-name "jira.meissa-gmbh.de" :listening-port "443" :server-admin-email "PI:EMAIL:<EMAIL>END_PI" :proxy {:target-port "8080" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-letsencrypt {:email "PI:EMAIL:<EMAIL>END_PI" :domains ["jira.meissa-gmbh.de"]}}) (def etc-apache2-meissa-config-with-origin {:domain-name "jira.meissa-gmbh.de" :listening-port "443" :server-admin-email "PI:EMAIL:<EMAIL>END_PI" :allow-origin "*.meissa-gmbh.de" :proxy {:target-port "8080" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-letsencrypt {:email "PI:EMAIL:<EMAIL>END_PI" :domains ["jira.meissa-gmbh.de"]}}) (def etc-apache2-politaktiv-config {:domain-name "jira.politaktiv.org" :listening-port "443" :server-admin-email "PI:EMAIL:<EMAIL>END_PI" :proxy {:target-port "8180" :additional-directives ["ProxyPreserveHost On" "ProxyRequests Off"]} :cert-manual {:domain-cert "domaincert" :domain-key "domainkey" :ca-cert "optional-ca-cert"}}) (def simple-with-directory {:domain-name "test.domaindrivenarchitecture.org", :listening-port "443", :server-admin-email "PI:EMAIL:<EMAIL>END_PI", :document-root "/var/www/test.domaindrivenarchitecture.org", :location {:locations-override ["Options FollowSymLinks" "AllowOverride All"]} :cert-letsencrypt {:email "PI:EMAIL:<EMAIL>END_PI", :domains ["test.domaindrivenarchitecture.org"]},}) (deftest vhost (testing "Test the creation of an example vhost from configuration." (is (= etc-apache2-sites-enabled-000-meissa-conf (vhost/vhost-conf-default-redirect-to-https-only :domain-name (get-in etc-apache2-meissa-config [:domain-name]) :server-admin-email (get-in etc-apache2-meissa-config [:server-admin-email])))) (is (= etc-apache2-sites-enabled-000-politaktiv-conf (vhost/vhost-conf-default-redirect-to-https-only :domain-name (get-in etc-apache2-politaktiv-config [:domain-name]) :server-admin-email (get-in etc-apache2-politaktiv-config [:server-admin-email])))) (is (= etc-apache2-sites-enabled-000-meissa-ssl-conf (sut/vhost etc-apache2-meissa-config))) (is (= etc-apache2-sites-enabled-000-politaktiv-ssl-conf (sut/vhost etc-apache2-politaktiv-config))) (is (= simple-with-directory-000-default-ssl-conf (sut/vhost simple-with-directory))) (is (= etc-apache2-sites-enabled-000-meissa-ssl-with-origin (sut/vhost etc-apache2-meissa-config-with-origin)))))
[ { "context": "ster full-name))\n\n(def person-data {::first-name \"Anne\" ::last-name \"Frank\"})\n\n(def smart-map (psm/smart", "end": 416, "score": 0.9998470544815063, "start": 412, "tag": "NAME", "value": "Anne" }, { "context": "def person-data {::first-name \"Anne\" ::last-name \"Frank\"})\n\n(def smart-map (psm/smart-map indexes person-", "end": 436, "score": 0.9998321533203125, "start": 431, "tag": "NAME", "value": "Frank" }, { "context": "y as a regular map\n(::first-name smart-map) ; => \"Anne\"\n\n; but when you read something that's not there,", "end": 615, "score": 0.9998425245285034, "start": 611, "tag": "NAME", "value": "Anne" }, { "context": "lfill the attribute\n(::full-name smart-map) ; => \"Anne Frank\"\n\n;; 02: Nested maps\n\n(pco/defresolver full-name ", "end": 767, "score": 0.9998557567596436, "start": 757, "tag": "NAME", "value": "Anne Frank" }, { "context": "(pco/defresolver anne []\n {::anne {::first-name \"Anne\" ::last-name \"Frank\"}})\n\n(def indexes (pci/regist", "end": 954, "score": 0.9998509883880615, "start": 950, "tag": "NAME", "value": "Anne" }, { "context": "ne []\n {::anne {::first-name \"Anne\" ::last-name \"Frank\"}})\n\n(def indexes (pci/register [full-name anne])", "end": 974, "score": 0.9998412132263184, "start": 969, "tag": "NAME", "value": "Frank" }, { "context": "indexes))\n\n(::anne smart-map) ; => {::first-name \"Anne\" ::last-name \"Frank\"}\n\n; nested access\n(-> smart-", "end": 1111, "score": 0.999848484992981, "start": 1107, "tag": "NAME", "value": "Anne" }, { "context": "smart-map) ; => {::first-name \"Anne\" ::last-name \"Frank\"}\n\n; nested access\n(-> smart-map ::anne ::full-na", "end": 1131, "score": 0.9998403191566467, "start": 1126, "tag": "NAME", "value": "Frank" }, { "context": "ed access\n(-> smart-map ::anne ::full-name) ; => \"Anne Frank\"\n\n;; 03: Nested sequences\n\n(pco/defresolver full-", "end": 1201, "score": 0.999840259552002, "start": 1191, "tag": "NAME", "value": "Anne Frank" }, { "context": "s []\n {::star-wars-characters\n [{::first-name \"Luke\" ::last-name \"Skywalker\"}\n {::first-name \"Dart", "end": 1414, "score": 0.9998056292533875, "start": 1410, "tag": "NAME", "value": "Luke" }, { "context": "-characters\n [{::first-name \"Luke\" ::last-name \"Skywalker\"}\n {::first-name \"Darth\" ::last-name \"Vader\"}\n", "end": 1438, "score": 0.999710738658905, "start": 1429, "tag": "NAME", "value": "Skywalker" }, { "context": "Luke\" ::last-name \"Skywalker\"}\n {::first-name \"Darth\" ::last-name \"Vader\"}\n {::first-name \"Han\" ::l", "end": 1465, "score": 0.9998131990432739, "start": 1460, "tag": "NAME", "value": "Darth" }, { "context": "kywalker\"}\n {::first-name \"Darth\" ::last-name \"Vader\"}\n {::first-name \"Han\" ::last-name \"Solo\"}]})\n", "end": 1485, "score": 0.9013011455535889, "start": 1480, "tag": "NAME", "value": "Vader" }, { "context": "e \"Darth\" ::last-name \"Vader\"}\n {::first-name \"Han\" ::last-name \"Solo\"}]})\n\n(def indexes (pci/regist", "end": 1510, "score": 0.9997903108596802, "start": 1507, "tag": "NAME", "value": "Han" }, { "context": "ame \"Vader\"}\n {::first-name \"Han\" ::last-name \"Solo\"}]})\n\n(def indexes (pci/register [full-name stars", "end": 1529, "score": 0.9907191395759583, "start": 1525, "tag": "NAME", "value": "Solo" }, { "context": "l-name (::star-wars-characters smart-map))\n; => [\"Luke Skywalker\"\n; \"Darth Vader\"\n; \"Han Solo\"]", "end": 1729, "score": 0.9996669292449951, "start": 1715, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "racters smart-map))\n; => [\"Luke Skywalker\"\n; \"Darth Vader\"\n; \"Han Solo\"]", "end": 1749, "score": 0.9998396635055542, "start": 1738, "tag": "NAME", "value": "Darth Vader" }, { "context": "; => [\"Luke Skywalker\"\n; \"Darth Vader\"\n; \"Han Solo\"]", "end": 1766, "score": 0.9996287822723389, "start": 1758, "tag": "NAME", "value": "Han Solo" } ]
clj/ex/study_pathom/pathom01/src/main/smart_maps01.clj
mertnuhoglu/study
1
(ns main.smart-maps01 (:require [com.wsscode.pathom3.connect.indexes :as pci] [com.wsscode.pathom3.connect.operation :as pco] [com.wsscode.pathom3.interface.smart-map :as psm])) ;; 01: Using smart maps (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (def indexes (pci/register full-name)) (def person-data {::first-name "Anne" ::last-name "Frank"}) (def smart-map (psm/smart-map indexes person-data)) ; if you lookup for a key in the initial data, it works the same way as a regular map (::first-name smart-map) ; => "Anne" ; but when you read something that's not there, it will trigger the Pathom engine to ; fulfill the attribute (::full-name smart-map) ; => "Anne Frank" ;; 02: Nested maps (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (pco/defresolver anne [] {::anne {::first-name "Anne" ::last-name "Frank"}}) (def indexes (pci/register [full-name anne])) (def smart-map (psm/smart-map indexes)) (::anne smart-map) ; => {::first-name "Anne" ::last-name "Frank"} ; nested access (-> smart-map ::anne ::full-name) ; => "Anne Frank" ;; 03: Nested sequences (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (pco/defresolver stars [] {::star-wars-characters [{::first-name "Luke" ::last-name "Skywalker"} {::first-name "Darth" ::last-name "Vader"} {::first-name "Han" ::last-name "Solo"}]}) (def indexes (pci/register [full-name stars])) (def smart-map (psm/smart-map indexes)) ; nested access on sequences (mapv ::full-name (::star-wars-characters smart-map)) ; => ["Luke Skywalker" ; "Darth Vader" ; "Han Solo"]
84049
(ns main.smart-maps01 (:require [com.wsscode.pathom3.connect.indexes :as pci] [com.wsscode.pathom3.connect.operation :as pco] [com.wsscode.pathom3.interface.smart-map :as psm])) ;; 01: Using smart maps (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (def indexes (pci/register full-name)) (def person-data {::first-name "<NAME>" ::last-name "<NAME>"}) (def smart-map (psm/smart-map indexes person-data)) ; if you lookup for a key in the initial data, it works the same way as a regular map (::first-name smart-map) ; => "<NAME>" ; but when you read something that's not there, it will trigger the Pathom engine to ; fulfill the attribute (::full-name smart-map) ; => "<NAME>" ;; 02: Nested maps (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (pco/defresolver anne [] {::anne {::first-name "<NAME>" ::last-name "<NAME>"}}) (def indexes (pci/register [full-name anne])) (def smart-map (psm/smart-map indexes)) (::anne smart-map) ; => {::first-name "<NAME>" ::last-name "<NAME>"} ; nested access (-> smart-map ::anne ::full-name) ; => "<NAME>" ;; 03: Nested sequences (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (pco/defresolver stars [] {::star-wars-characters [{::first-name "<NAME>" ::last-name "<NAME>"} {::first-name "<NAME>" ::last-name "<NAME>"} {::first-name "<NAME>" ::last-name "<NAME>"}]}) (def indexes (pci/register [full-name stars])) (def smart-map (psm/smart-map indexes)) ; nested access on sequences (mapv ::full-name (::star-wars-characters smart-map)) ; => ["<NAME>" ; "<NAME>" ; "<NAME>"]
true
(ns main.smart-maps01 (:require [com.wsscode.pathom3.connect.indexes :as pci] [com.wsscode.pathom3.connect.operation :as pco] [com.wsscode.pathom3.interface.smart-map :as psm])) ;; 01: Using smart maps (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (def indexes (pci/register full-name)) (def person-data {::first-name "PI:NAME:<NAME>END_PI" ::last-name "PI:NAME:<NAME>END_PI"}) (def smart-map (psm/smart-map indexes person-data)) ; if you lookup for a key in the initial data, it works the same way as a regular map (::first-name smart-map) ; => "PI:NAME:<NAME>END_PI" ; but when you read something that's not there, it will trigger the Pathom engine to ; fulfill the attribute (::full-name smart-map) ; => "PI:NAME:<NAME>END_PI" ;; 02: Nested maps (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (pco/defresolver anne [] {::anne {::first-name "PI:NAME:<NAME>END_PI" ::last-name "PI:NAME:<NAME>END_PI"}}) (def indexes (pci/register [full-name anne])) (def smart-map (psm/smart-map indexes)) (::anne smart-map) ; => {::first-name "PI:NAME:<NAME>END_PI" ::last-name "PI:NAME:<NAME>END_PI"} ; nested access (-> smart-map ::anne ::full-name) ; => "PI:NAME:<NAME>END_PI" ;; 03: Nested sequences (pco/defresolver full-name [{::keys [first-name last-name]}] {::full-name (str first-name " " last-name)}) (pco/defresolver stars [] {::star-wars-characters [{::first-name "PI:NAME:<NAME>END_PI" ::last-name "PI:NAME:<NAME>END_PI"} {::first-name "PI:NAME:<NAME>END_PI" ::last-name "PI:NAME:<NAME>END_PI"} {::first-name "PI:NAME:<NAME>END_PI" ::last-name "PI:NAME:<NAME>END_PI"}]}) (def indexes (pci/register [full-name stars])) (def smart-map (psm/smart-map indexes)) ; nested access on sequences (mapv ::full-name (::star-wars-characters smart-map)) ; => ["PI:NAME:<NAME>END_PI" ; "PI:NAME:<NAME>END_PI" ; "PI:NAME:<NAME>END_PI"]
[ { "context": "[:describe.core/empty]]}\n\n(d/describe {:username \"b3\"} new-user-describers)\n;; #{[:username [:describe", "end": 1529, "score": 0.9991100430488586, "start": 1527, "tag": "USERNAME", "value": "b3" }, { "context": "[:describe.core/empty]]}\n\n(d/describe {:username \"bubba56\"}\n new-user-describers\n {:d", "end": 1684, "score": 0.9995530247688293, "start": 1677, "tag": "USERNAME", "value": "bubba56" }, { "context": "new-user-describers\n {:db [{:username \"bubba56\"}]})\n;; #{[:username [:examples/username-taken]]\n", "end": 1756, "score": 0.9995701909065247, "start": 1749, "tag": "USERNAME", "value": "bubba56" }, { "context": "sting-password) passed in\n(d/describe {:password \"blub\"}\n change-password-describer\n ", "end": 2868, "score": 0.9955308437347412, "start": 2864, "tag": "PASSWORD", "value": "blub" }, { "context": "criber\n {:encrypted-existing-password \"blib\"})\n;; #{[:password [:examples/passwords-dont-matc", "end": 2956, "score": 0.9792670011520386, "start": 2952, "tag": "PASSWORD", "value": "blib" } ]
examples/src/examples.clj
flyingmachine/describe
10
(ns examples (:require [sweet-tooth.describe :as d] [clojure.spec.alpha :as s])) ;;----------------- ;; Describer setup ;;----------------- (defn username-taken? [username db] (some #(= username (:username %)) db)) (def username-empty (d/empty :username)) (def username-invalid-length (d/count-not-in-range :username 6 24)) (def username-not-alnum (d/not-alnum :username)) (def username-taken {:pred username-taken? :args [:username (d/context :db)] :dscr [::username-taken]}) (def password-empty (d/empty :password)) (def passwords-dont-match (-> (d/not= :password :confirmation) (assoc :dscr [::passwords-dont-match]))) (def password-no-special-chars (-> (d/does-not-match :password #"[^a-zA-Z\d\s:]") (assoc :dscr [::no-special-chars]))) (def ignore-when-empty {:pred empty? :args [identity] :dscr [::d/ignore]}) (def street-empty (d/empty :street)) (def city-empty (d/empty :city)) (def address-invalid (d/key-rule :address #{{ignore-when-empty [street-empty city-empty]}})) (def new-user-describers [[username-empty username-invalid-length username-taken] [username-empty username-not-alnum username-taken] {password-empty [password-no-special-chars passwords-dont-match]} address-invalid]) ;;----------------- ;; Example describe calls ;;----------------- (d/describe {} new-user-describers) ;; #{[:username [:describe.core/empty]] ;; [:password [:describe.core/empty]]} (d/describe {:username "b3"} new-user-describers) ;; #{[:username [:describe.core/count-not-in-range 6 24]] ;; [:password [:describe.core/empty]]} (d/describe {:username "bubba56"} new-user-describers {:db [{:username "bubba56"}]}) ;; #{[:username [:examples/username-taken]] ;; [:password [:sweet-tooth.describe/empty]]} (d/describe {:address {:street "street"}} new-user-describers) ;; #{[:address #{[:city [:describe.core/empty]]}] ;; [:username [:describe.core/empty]] ;; [:password [:describe.core/empty]]} (d/describe {:password "x"} new-user-describers) ;; #{[:username [:describe.core/empty]] ;; [:password [:examples/passwords-dont-match]] ;; [:password [:examples/no-special-chars]]} ;;----------------- ;; Describer illustrating context ;;----------------- (def encrypt reverse) (def current-password-incorrect {:pred (fn [current-password encrypted-existing-password] (not= (encrypt current-password) encrypted-existing-password)) :args [:current-password (d/context :encrypted-existing-password)] :dscr [::current-password-incorrect]}) (def change-password-describer [{password-empty [password-no-special-chars passwords-dont-match]} current-password-incorrect]) ;; Example of calling a describer with "context" ;; (:encrypted-existing-password) passed in (d/describe {:password "blub"} change-password-describer {:encrypted-existing-password "blib"}) ;; #{[:password [:examples/passwords-dont-match]] ;; [:current-password [:examples/current-password-incorrect]] ;; [:password [:examples/no-special-chars]]}
14885
(ns examples (:require [sweet-tooth.describe :as d] [clojure.spec.alpha :as s])) ;;----------------- ;; Describer setup ;;----------------- (defn username-taken? [username db] (some #(= username (:username %)) db)) (def username-empty (d/empty :username)) (def username-invalid-length (d/count-not-in-range :username 6 24)) (def username-not-alnum (d/not-alnum :username)) (def username-taken {:pred username-taken? :args [:username (d/context :db)] :dscr [::username-taken]}) (def password-empty (d/empty :password)) (def passwords-dont-match (-> (d/not= :password :confirmation) (assoc :dscr [::passwords-dont-match]))) (def password-no-special-chars (-> (d/does-not-match :password #"[^a-zA-Z\d\s:]") (assoc :dscr [::no-special-chars]))) (def ignore-when-empty {:pred empty? :args [identity] :dscr [::d/ignore]}) (def street-empty (d/empty :street)) (def city-empty (d/empty :city)) (def address-invalid (d/key-rule :address #{{ignore-when-empty [street-empty city-empty]}})) (def new-user-describers [[username-empty username-invalid-length username-taken] [username-empty username-not-alnum username-taken] {password-empty [password-no-special-chars passwords-dont-match]} address-invalid]) ;;----------------- ;; Example describe calls ;;----------------- (d/describe {} new-user-describers) ;; #{[:username [:describe.core/empty]] ;; [:password [:describe.core/empty]]} (d/describe {:username "b3"} new-user-describers) ;; #{[:username [:describe.core/count-not-in-range 6 24]] ;; [:password [:describe.core/empty]]} (d/describe {:username "bubba56"} new-user-describers {:db [{:username "bubba56"}]}) ;; #{[:username [:examples/username-taken]] ;; [:password [:sweet-tooth.describe/empty]]} (d/describe {:address {:street "street"}} new-user-describers) ;; #{[:address #{[:city [:describe.core/empty]]}] ;; [:username [:describe.core/empty]] ;; [:password [:describe.core/empty]]} (d/describe {:password "x"} new-user-describers) ;; #{[:username [:describe.core/empty]] ;; [:password [:examples/passwords-dont-match]] ;; [:password [:examples/no-special-chars]]} ;;----------------- ;; Describer illustrating context ;;----------------- (def encrypt reverse) (def current-password-incorrect {:pred (fn [current-password encrypted-existing-password] (not= (encrypt current-password) encrypted-existing-password)) :args [:current-password (d/context :encrypted-existing-password)] :dscr [::current-password-incorrect]}) (def change-password-describer [{password-empty [password-no-special-chars passwords-dont-match]} current-password-incorrect]) ;; Example of calling a describer with "context" ;; (:encrypted-existing-password) passed in (d/describe {:password "<PASSWORD>"} change-password-describer {:encrypted-existing-password "<PASSWORD>"}) ;; #{[:password [:examples/passwords-dont-match]] ;; [:current-password [:examples/current-password-incorrect]] ;; [:password [:examples/no-special-chars]]}
true
(ns examples (:require [sweet-tooth.describe :as d] [clojure.spec.alpha :as s])) ;;----------------- ;; Describer setup ;;----------------- (defn username-taken? [username db] (some #(= username (:username %)) db)) (def username-empty (d/empty :username)) (def username-invalid-length (d/count-not-in-range :username 6 24)) (def username-not-alnum (d/not-alnum :username)) (def username-taken {:pred username-taken? :args [:username (d/context :db)] :dscr [::username-taken]}) (def password-empty (d/empty :password)) (def passwords-dont-match (-> (d/not= :password :confirmation) (assoc :dscr [::passwords-dont-match]))) (def password-no-special-chars (-> (d/does-not-match :password #"[^a-zA-Z\d\s:]") (assoc :dscr [::no-special-chars]))) (def ignore-when-empty {:pred empty? :args [identity] :dscr [::d/ignore]}) (def street-empty (d/empty :street)) (def city-empty (d/empty :city)) (def address-invalid (d/key-rule :address #{{ignore-when-empty [street-empty city-empty]}})) (def new-user-describers [[username-empty username-invalid-length username-taken] [username-empty username-not-alnum username-taken] {password-empty [password-no-special-chars passwords-dont-match]} address-invalid]) ;;----------------- ;; Example describe calls ;;----------------- (d/describe {} new-user-describers) ;; #{[:username [:describe.core/empty]] ;; [:password [:describe.core/empty]]} (d/describe {:username "b3"} new-user-describers) ;; #{[:username [:describe.core/count-not-in-range 6 24]] ;; [:password [:describe.core/empty]]} (d/describe {:username "bubba56"} new-user-describers {:db [{:username "bubba56"}]}) ;; #{[:username [:examples/username-taken]] ;; [:password [:sweet-tooth.describe/empty]]} (d/describe {:address {:street "street"}} new-user-describers) ;; #{[:address #{[:city [:describe.core/empty]]}] ;; [:username [:describe.core/empty]] ;; [:password [:describe.core/empty]]} (d/describe {:password "x"} new-user-describers) ;; #{[:username [:describe.core/empty]] ;; [:password [:examples/passwords-dont-match]] ;; [:password [:examples/no-special-chars]]} ;;----------------- ;; Describer illustrating context ;;----------------- (def encrypt reverse) (def current-password-incorrect {:pred (fn [current-password encrypted-existing-password] (not= (encrypt current-password) encrypted-existing-password)) :args [:current-password (d/context :encrypted-existing-password)] :dscr [::current-password-incorrect]}) (def change-password-describer [{password-empty [password-no-special-chars passwords-dont-match]} current-password-incorrect]) ;; Example of calling a describer with "context" ;; (:encrypted-existing-password) passed in (d/describe {:password "PI:PASSWORD:<PASSWORD>END_PI"} change-password-describer {:encrypted-existing-password "PI:PASSWORD:<PASSWORD>END_PI"}) ;; #{[:password [:examples/passwords-dont-match]] ;; [:current-password [:examples/current-password-incorrect]] ;; [:password [:examples/no-special-chars]]}
[ { "context": "ions and limitations there under.\n\n;;;; Author: Mark Butler (mailto:support@snowplowanalytics.com)\n;;;; Copyr", "end": 746, "score": 0.9998108744621277, "start": 735, "tag": "NAME", "value": "Mark Butler" }, { "context": "there under.\n\n;;;; Author: Mark Butler (mailto:support@snowplowanalytics.com)\n;;;; Copyright: Copyright (c) 2012-2013 Snowplow", "end": 784, "score": 0.9999279379844666, "start": 755, "tag": "EMAIL", "value": "support@snowplowanalytics.com" } ]
2-collectors/clojure-collector/java-servlet/tasks/leiningen/aws.clj
omenocal/snowplow
2
;;;; Copyright (c) 2012-2013 Snowplow Analytics Ltd. All rights reserved. ;;;; ;;;; This program is licensed to you under the Apache License Version 2.0, ;;;; and you may not use this file except in compliance with the Apache License Version 2.0. ;;;; You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. ;;;; ;;;; Unless required by applicable law or agreed to in writing, ;;;; software distributed under the Apache License Version 2.0 is distributed on an ;;;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. ;;;; Author: Mark Butler (mailto:support@snowplowanalytics.com) ;;;; Copyright: Copyright (c) 2012-2013 Snowplow Analytics Ltd ;;;; License: Apache License Version 2.0 (ns leiningen.aws (:require [leiningen.core.classpath :as classpath] [leiningen.ring.uberwar] [leiningen.ring.war] [robert.hooke])) (defn skip-file? [original_func project war-path file] (and (not (re-find #".ebextensions.*" war-path)) (original_func project war-path file))) (def hooked (atom 0)) (defn aws "Creates a valid Amazon web services WAR that is deployable to servlet containers." [project & args] (if (= 0 @hooked) (do (robert.hooke/add-hook #'leiningen.ring.war/skip-file? #'skip-file?) (swap! hooked inc))) (leiningen.ring.uberwar/uberwar project))
60868
;;;; Copyright (c) 2012-2013 Snowplow Analytics Ltd. All rights reserved. ;;;; ;;;; This program is licensed to you under the Apache License Version 2.0, ;;;; and you may not use this file except in compliance with the Apache License Version 2.0. ;;;; You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. ;;;; ;;;; Unless required by applicable law or agreed to in writing, ;;;; software distributed under the Apache License Version 2.0 is distributed on an ;;;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. ;;;; Author: <NAME> (mailto:<EMAIL>) ;;;; Copyright: Copyright (c) 2012-2013 Snowplow Analytics Ltd ;;;; License: Apache License Version 2.0 (ns leiningen.aws (:require [leiningen.core.classpath :as classpath] [leiningen.ring.uberwar] [leiningen.ring.war] [robert.hooke])) (defn skip-file? [original_func project war-path file] (and (not (re-find #".ebextensions.*" war-path)) (original_func project war-path file))) (def hooked (atom 0)) (defn aws "Creates a valid Amazon web services WAR that is deployable to servlet containers." [project & args] (if (= 0 @hooked) (do (robert.hooke/add-hook #'leiningen.ring.war/skip-file? #'skip-file?) (swap! hooked inc))) (leiningen.ring.uberwar/uberwar project))
true
;;;; Copyright (c) 2012-2013 Snowplow Analytics Ltd. All rights reserved. ;;;; ;;;; This program is licensed to you under the Apache License Version 2.0, ;;;; and you may not use this file except in compliance with the Apache License Version 2.0. ;;;; You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. ;;;; ;;;; Unless required by applicable law or agreed to in writing, ;;;; software distributed under the Apache License Version 2.0 is distributed on an ;;;; "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;;; See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. ;;;; Author: PI:NAME:<NAME>END_PI (mailto:PI:EMAIL:<EMAIL>END_PI) ;;;; Copyright: Copyright (c) 2012-2013 Snowplow Analytics Ltd ;;;; License: Apache License Version 2.0 (ns leiningen.aws (:require [leiningen.core.classpath :as classpath] [leiningen.ring.uberwar] [leiningen.ring.war] [robert.hooke])) (defn skip-file? [original_func project war-path file] (and (not (re-find #".ebextensions.*" war-path)) (original_func project war-path file))) (def hooked (atom 0)) (defn aws "Creates a valid Amazon web services WAR that is deployable to servlet containers." [project & args] (if (= 0 @hooked) (do (robert.hooke/add-hook #'leiningen.ring.war/skip-file? #'skip-file?) (swap! hooked inc))) (leiningen.ring.uberwar/uberwar project))
[ { "context": "t/autodoc/\"\n :copyright \"Copyright 2012 Hubert Iwaniuk\"}\n :licence {:name \"Apache License, Version 2.0\"", "end": 1177, "score": 0.9998776316642761, "start": 1163, "tag": "NAME", "value": "Hubert Iwaniuk" } ]
project.clj
jcrossley3/http.async.client
1
(defproject http.async.client "0.5.3-SNAPSHOT" :name "http.async.client" :description "Asynchronous HTTP Client for Clojure" :url "http://neotyk.github.com/http.async.client/" :source-paths ["src/clj"] :java-source-paths ["src/jvm"] :dependencies [[org.clojure/clojure "1.4.0"] [com.ning/async-http-client "1.7.10"]] :min-lein-version "2.0.0" :plugins [[codox "0.6.1"] [lein-difftest "1.3.3" :exclusions [org.clojure/clojure org.clojure/clojure-contrib]]] :profiles {:dev {:resource-paths ["test-resources"], :dependencies [[org.eclipse.jetty/jetty-server "7.1.4.v20100610"] [org.eclipse.jetty/jetty-security "7.1.4.v20100610"] [log4j "1.2.13"] [org.slf4j/slf4j-log4j12 "1.6.4"]]}} ;; :repositories {"snapshots" "http://oss.sonatype.org/content/repositories/snapshots/"} :codox {:output-dir "doc"} :autodoc {:web-src-dir "http://github.com/neotyk/http.async.client/blob/" :web-home "http://neotyk.github.com/http.async.client/autodoc/" :copyright "Copyright 2012 Hubert Iwaniuk"} :licence {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo})
109919
(defproject http.async.client "0.5.3-SNAPSHOT" :name "http.async.client" :description "Asynchronous HTTP Client for Clojure" :url "http://neotyk.github.com/http.async.client/" :source-paths ["src/clj"] :java-source-paths ["src/jvm"] :dependencies [[org.clojure/clojure "1.4.0"] [com.ning/async-http-client "1.7.10"]] :min-lein-version "2.0.0" :plugins [[codox "0.6.1"] [lein-difftest "1.3.3" :exclusions [org.clojure/clojure org.clojure/clojure-contrib]]] :profiles {:dev {:resource-paths ["test-resources"], :dependencies [[org.eclipse.jetty/jetty-server "7.1.4.v20100610"] [org.eclipse.jetty/jetty-security "7.1.4.v20100610"] [log4j "1.2.13"] [org.slf4j/slf4j-log4j12 "1.6.4"]]}} ;; :repositories {"snapshots" "http://oss.sonatype.org/content/repositories/snapshots/"} :codox {:output-dir "doc"} :autodoc {:web-src-dir "http://github.com/neotyk/http.async.client/blob/" :web-home "http://neotyk.github.com/http.async.client/autodoc/" :copyright "Copyright 2012 <NAME>"} :licence {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo})
true
(defproject http.async.client "0.5.3-SNAPSHOT" :name "http.async.client" :description "Asynchronous HTTP Client for Clojure" :url "http://neotyk.github.com/http.async.client/" :source-paths ["src/clj"] :java-source-paths ["src/jvm"] :dependencies [[org.clojure/clojure "1.4.0"] [com.ning/async-http-client "1.7.10"]] :min-lein-version "2.0.0" :plugins [[codox "0.6.1"] [lein-difftest "1.3.3" :exclusions [org.clojure/clojure org.clojure/clojure-contrib]]] :profiles {:dev {:resource-paths ["test-resources"], :dependencies [[org.eclipse.jetty/jetty-server "7.1.4.v20100610"] [org.eclipse.jetty/jetty-security "7.1.4.v20100610"] [log4j "1.2.13"] [org.slf4j/slf4j-log4j12 "1.6.4"]]}} ;; :repositories {"snapshots" "http://oss.sonatype.org/content/repositories/snapshots/"} :codox {:output-dir "doc"} :autodoc {:web-src-dir "http://github.com/neotyk/http.async.client/blob/" :web-home "http://neotyk.github.com/http.async.client/autodoc/" :copyright "Copyright 2012 PI:NAME:<NAME>END_PI"} :licence {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo})
[ { "context": "kes ordering assumptions about representation\n;; - David\n\n;; START HERE\n\n(let [x (lvar 'x)\n y (lvar '", "end": 4261, "score": 0.9294204115867615, "start": 4256, "tag": "NAME", "value": "David" } ]
src/test/cljs/cljs/core/logic/tests.cljs
jduey/arrowed-logic
1
(ns cljs.core.logic.tests (:refer-clojure :exclude [==]) (:use-macros [cljs.core.logic.macros :only [run run* == conde conda condu fresh defne matche all]]) (:require-macros [cljs.core.logic.macros :as m] [clojure.tools.macro :as mu]) (:use [cljs.core.logic :only [pair lvar lcons -unify -ext-no-check -walk -walk* -reify-lvar-name empty-s to-s succeed fail s# u# conso nilo firsto resto emptyo appendo membero *occurs-check* unifier binding-map partial-map failed?]])) (defn js-print [& args] (if (js* "typeof console != 'undefined'") (.log js/console (apply str args)) (js/print (apply str args)))) (set! *print-fn* js-print) ;; ============================================================================= ;; unify ;; ----------------------------------------------------------------------------- ;; unify with nil (println "unify with nil") (let [x (lvar 'x)] (assert (= (pair x nil) (pair x nil)))) (let [x (lvar 'x)] (assert (false? (= (pair x nil) (pair nil x))))) (assert (failed? (-unify empty-s nil 1))) (let [x (lvar 'x) a (-ext-no-check empty-s x nil) b (-unify empty-s nil x)] (assert (= a b))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil (lcons 1 x))))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil {})))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil #{})))) ;; ----------------------------------------------------------------------------- ;; unify with object (println "unify with object") (assert (failed? (-unify empty-s 1 nil))) (assert (= (-unify empty-s 1 1) empty-s)) (assert (= (-unify empty-s :foo :foo) empty-s)) (assert (= (-unify empty-s 'foo 'foo) empty-s)) (assert (= (-unify empty-s "foo" "foo") empty-s)) (assert (failed? (-unify empty-s 1 2))) (assert (failed? (-unify empty-s 2 1))) (assert (failed? (-unify empty-s :foo :bar))) (assert (failed? (-unify empty-s 'foo 'bar))) (assert (failed? (-unify empty-s "foo" "bar"))) (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s 1 x) os))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s 1 (lcons 1 'x))))) (assert (failed? (-unify empty-s 1 '()))) (assert (failed? (-unify empty-s 1 '[]))) (assert (failed? (-unify empty-s 1 {}))) (assert (failed? (-unify empty-s 1 #{}))) ;; ----------------------------------------------------------------------------- ;; unify with lvar (println "unify with lvar") (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s x 1) os))) (let [x (lvar 'x) y (lvar 'y) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s x y) os))) (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (-ext-no-check empty-s x l)] (assert (= (-unify empty-s x l) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s x []) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [1 2 3])] (assert (= (-unify empty-s x [1 2 3]) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x '())] (assert (= (-unify empty-s x '()) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x '(1 2 3))] (assert (= (-unify empty-s x '(1 2 3)) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x {})] (assert (= (-unify empty-s x {}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x {1 2 3 4})] (assert (= (-unify empty-s x {1 2 3 4}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x #{})] (assert (= (-unify empty-s x #{}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x #{1 2 3})] (assert (= (-unify empty-s x #{1 2 3}) os))) ;; ----------------------------------------------------------------------------- ;; unify with lcons (println "unify with lcons") (let [x (lvar 'x)] (assert (failed? (-unify empty-s (lcons 1 x) 1)))) (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (-ext-no-check empty-s x l)] (assert (= (-unify empty-s l x) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 x) lc2 (lcons 1 y) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s lc1 lc2) os))) ;; NOTE: sketchy tests that makes ordering assumptions about representation ;; - David ;; START HERE (let [x (lvar 'x) y (lvar 'y) z (lvar 'z) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons z y)) os (-> empty-s (-ext-no-check z 2) (-ext-no-check x y))] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 (lcons 3 y))) os (-ext-no-check empty-s x (lcons 3 y))] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 3 (lcons 4 y)))] (assert (failed? (-unify empty-s lc1 lc2)))) (let [x (lvar 'x) y (lvar 'y) lc2 (lcons 1 (lcons 2 x)) lc1 (lcons 1 (lcons 3 (lcons 4 y)))] (assert (failed? (-unify empty-s lc1 lc2)))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 y)) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (-ext-no-check empty-s x '(3 4))] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons y (lcons 3 x))) l1 '(1 2 3 4) os (-> empty-s (-ext-no-check y 2) (-ext-no-check x '(4)))] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 (lcons 3 x))) l1 '(1 2 3) os (-ext-no-check empty-s x '())] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 3 x)) l1 '(1 2 3 4)] (assert (failed? (-unify empty-s lc1 l1)))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 3 4 5)] (assert (failed? (-unify empty-s lc1 l1)))) (assert (failed? (-unify empty-s (lcons 1 (lvar 'x)) {}))) (assert (failed? (-unify empty-s (lcons 1 (lvar 'x)) #{}))) ;; ----------------------------------------------------------------------------- ;; unify with sequential (println "unify with sequential") (assert (failed? (-unify empty-s '() 1))) (assert (failed? (-unify empty-s [] 1))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s [] x) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s [] x) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (-ext-no-check empty-s x '(3 4))] (assert (= (-unify empty-s l1 lc1) os))) (assert (= (-unify empty-s [1 2 3] [1 2 3]) empty-s)) (assert (= (-unify empty-s '(1 2 3) [1 2 3]) empty-s)) (assert (= (-unify empty-s '(1 2 3) '(1 2 3)) empty-s)) (let [x (lvar 'x) os (-ext-no-check empty-s x 2)] (assert (= (-unify empty-s `(1 ~x 3) `(1 2 3)) os))) (assert (failed? (-unify empty-s [1 2] [1 2 3]))) (assert (failed? (-unify empty-s '(1 2) [1 2 3]))) (assert (failed? (-unify empty-s [1 2 3] [3 2 1]))) (assert (= (-unify empty-s '() '()) empty-s)) (assert (failed? (-unify empty-s '() '(1)))) (assert (failed? (-unify empty-s '(1) '()))) (assert (= (-unify empty-s [[1 2]] [[1 2]]) empty-s)) (assert (failed? (-unify empty-s [[1 2]] [[2 1]]))) (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s [[x 2]] [[1 2]]) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [1 2])] (assert (= (-unify empty-s [x] [[1 2]]) os))) (let [x (lvar 'x) y (lvar 'y) u (lvar 'u) v (lvar 'v) os (-> empty-s (-ext-no-check y 'a) (-ext-no-check x 'b))] (assert (= (-unify empty-s ['a x] [y 'b]) os))) (assert (failed? (-unify empty-s [] {}))) (assert (failed? (-unify empty-s '() {}))) (assert (failed? (-unify empty-s [] #{}))) (assert (failed? (-unify empty-s '() #{}))) ;; ----------------------------------------------------------------------------- ;; unify with map (println "unify with map") (assert (failed? (-unify empty-s {} 1))) (let [x (lvar 'x) os (-ext-no-check empty-s x {})] (assert (= (-unify empty-s {} x) os))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s {} (lcons 1 x))))) (assert (failed? (-unify empty-s {} '()))) (assert (= (-unify empty-s {} {}) empty-s)) (assert (= (-unify empty-s {1 2 3 4} {1 2 3 4}) empty-s)) (assert (failed? (-unify empty-s {1 2} {1 2 3 4}))) (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 2 3 x} os (-ext-no-check empty-s x 4)] (assert (= (-unify empty-s m1 m2) os))) (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 4 3 x}] (assert (failed? (-unify empty-s m1 m2)))) (assert (failed? (-unify empty-s {} #{}))) ;; ============================================================================= ;; walk (println "walk") (assert (= (let [x (lvar 'x) y (lvar 'y) s (to-s [[x 5] [y x]])] (-walk s y)) 5)) (assert (= (let [[x y z c b a :as s] (map lvar '[x y z c b a]) s (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])] (-walk s a)) 5)) ;; ============================================================================= ;; reify (println "reify") (assert (= (let [x (lvar 'x) y (lvar 'y)] (-reify-lvar-name (to-s [[x 5] [y x]]))) '_.2)) ;; ============================================================================= ;; walk* (println "walk*") (assert (= (let [x (lvar 'x) y (lvar 'y)] (-walk* (to-s [[x 5] [y x]]) `(~x ~y))) '(5 5))) ;; ============================================================================= ;; run and unify (println "run and unify") (assert (= (run* [q] (m/== true q)) '(true))) (assert (= (run* [q] (fresh [x y] (m/== [x y] [1 5]) (m/== [x y] q))) [[1 5]])) (assert (= (run* [q] (fresh [x y] (m/== [x y] q))) '[[_.0 _.1]])) ;; ============================================================================= ;; fail (println "fail") (assert (= (run* [q] fail (m/== true q)) [])) ;; ============================================================================= ;; Basic (println "basic") (assert (= (run* [q] (all (m/== 1 1) (m/== q true))) '(true))) ;; ============================================================================= ;; TRS (println "trs") (defn pairo [p] (fresh [a d] (m/== (lcons a d) p))) (defn twino [p] (fresh [x] (conso x x p))) (defn listo [l] (conde [(emptyo l) s#] [(pairo l) (fresh [d] (resto l d) (listo d))])) (defn flatteno [s out] (conde [(emptyo s) (m/== '() out)] [(pairo s) (fresh [a d res-a res-d] (conso a d s) (flatteno a res-a) (flatteno d res-d) (appendo res-a res-d out))] [(conso s '() out)])) (defn rembero [x l out] (conde [(m/== '() l) (m/== '() out)] [(fresh [a d] (conso a d l) (m/== x a) (m/== d out))] [(fresh [a d res] (conso a d l) (conso a res out) (rembero x d res))])) ;; ============================================================================= ;; conde (println "conde") (assert (= (run* [x] (conde [(m/== x 'olive) succeed] [succeed succeed] [(m/== x 'oil) succeed])) '[olive _.0 oil])) (assert (= (run* [r] (fresh [x y] (conde [(m/== 'split x) (m/== 'pea y)] [(m/== 'navy x) (m/== 'bean y)]) (m/== (cons x (cons y ())) r))) '[(split pea) (navy bean)])) (defn teacupo [x] (conde [(m/== 'tea x) s#] [(m/== 'cup x) s#])) (assert (= (run* [r] (fresh [x y] (conde [(teacupo x) (m/== true y) s#] [(m/== false x) (m/== true y)]) (m/== (cons x (cons y ())) r))) '((false true) (tea true) (cup true)))) ;; ============================================================================= ;; conso (println "conso") (assert (= (run* [q] (fresh [a d] (conso a d ()) (m/== (cons a d) q))) [])) (let [a (lvar 'a) d (lvar 'd)] (assert (= (run* [q] (conso a d q)) [(lcons a d)]))) (assert (= (run* [q] (m/== [q] nil)) [])) (assert (= (run* [q] (conso 'a nil q)) '[(a)])) (assert (= (run* [q] (conso 'a '(d) q)) '[(a d)])) (assert (= (run* [q] (conso 'a q '(a))) '[()])) (assert (= (run* [q] (conso q '(b c) '(a b c))) '[a])) ;; ============================================================================= ;; firsto (println "firsto") (assert (= (run* [q] (firsto q '(1 2))) (list (lcons '(1 2) (lvar 'x))))) ;; ============================================================================= ;; resto (println "resto") (assert (= (run* [q] (resto q '(1 2))) '[(_.0 1 2)])) (assert (= (run* [q] (resto q [1 2])) '[(_.0 1 2)])) (assert (= (run* [q] (resto [1 2] q)) '[(2)])) (assert (= (run* [q] (resto [1 2 3 4 5 6 7 8] q)) '[(2 3 4 5 6 7 8)])) ;; ============================================================================= ;; flatteno (println "flatteno") (assert (= (run* [x] (flatteno '[[a b] c] x)) '(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ()) (a (b) (c)) (a (b) c) (a (b) c ()) (a b (c)) (a b () (c)) (a b c) (a b c ()) (a b () c) (a b () c ())))) ;; ============================================================================= ;; membero (println "membero") (assert (= (run* [q] (all (m/== q [(lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar]]))) (assert (= (run* [q] (all (m/== q [(lvar) (lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar] _.0] [[foo _.0] [_.1 bar]] [[_.0 bar] [foo _.1]] [_.0 [foo bar]]))) ;; ----------------------------------------------------------------------------- ;; rembero (println "rembero") (assert (= (run 1 [q] (rembero 'b '(a b c b d) q)) '((a c b d)))) ;; ----------------------------------------------------------------------------- ;; conde clause count (println "conde clause count") (defn digit-1 [x] (conde [(m/== 0 x)])) (defn digit-4 [x] (conde [(m/== 0 x)] [(m/== 1 x)] [(m/== 2 x)] [(m/== 3 x)])) (assert (= (run* [q] (fresh [x y] (digit-1 x) (digit-1 y) (m/== q [x y]))) '([0 0]))) (assert (= (run* [q] (fresh [x y] (digit-4 x) (digit-4 y) (m/== q [x y]))) '([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0] [1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3]))) ;; ----------------------------------------------------------------------------- ;; anyo (println "anyo") (defn anyo [q] (conde [q s#] [(anyo q)])) (assert (= (run 1 [q] (anyo s#) (m/== true q)) (list true))) (assert (= (run 5 [q] (anyo s#) (m/== true q)) (list true true true true true))) ;; ----------------------------------------------------------------------------- ;; divergence (println "divergence") (def f1 (fresh [] f1)) (assert (= (run 1 [q] (conde [f1] [(m/== false false)])) '(_.0))) (assert (= (run 1 [q] (conde [f1 (m/== false false)] [(m/== false false)])) '(_.0))) (def f2 (fresh [] (conde [f2 (conde [f2] [(m/== false false)])] [(m/== false false)]))) (assert (= (run 5 [q] f2) '(_.0 _.0 _.0 _.0 _.0))) ;; ----------------------------------------------------------------------------- ;; conda (soft-cut) (println "conda") (assert (= (run* [x] (conda [(m/== 'olive x) s#] [(m/== 'oil x) s#] [u#])) '(olive))) (assert (= (run* [x] (conda [(m/== 'virgin x) u#] [(m/== 'olive x) s#] [(m/== 'oil x) s#] [u#])) '())) (assert (= (run* [x] (fresh (x y) (m/== 'split x) (m/== 'pea y) (conda [(m/== 'split x) (m/== x y)] [s#])) (m/== true x)) '())) (assert (= (run* [x] (fresh (x y) (m/== 'split x) (m/== 'pea y) (conda [(m/== x y) (m/== 'split x)] [s#])) (m/== true x)) '(true))) (defn not-pastao [x] (conda [(m/== 'pasta x) u#] [s#])) (assert (= (run* [x] (conda [(not-pastao x)] [(m/== 'spaghetti x)])) '(spaghetti))) ;; ----------------------------------------------------------------------------- ;; condu (committed-choice) (println "condu") (defn onceo [g] (condu (g s#))) (assert (= (run* [x] (onceo (teacupo x))) '(tea))) (assert (= (run* [r] (conde [(teacupo r) s#] [(m/== false r) s#])) '(false tea cup))) (assert (= (run* [r] (conda [(teacupo r) s#] [(m/== false r) s#])) '(tea cup))) ;; ----------------------------------------------------------------------------- ;; nil in collection (println "nil in collection") (assert (= (run* [q] (m/== q [nil])) '([nil]))) (assert (= (run* [q] (m/== q [1 nil])) '([1 nil]))) (assert (= (run* [q] (m/== q [nil 1])) '([nil 1]))) (assert (= (run* [q] (m/== q '(nil))) '((nil)))) (assert (= (run* [q] (m/== q {:foo nil})) '({:foo nil}))) (assert (= (run* [q] (m/== q {nil :foo})) '({nil :foo}))) ;; ----------------------------------------------------------------------------- ;; Unifier (println "simple unifier") ; test-unifier-1 (assert (= (unifier '(?x ?y) '(1 2)) '(1 2))) ; test-unifier-2 (assert (= (unifier '(?x ?y 3) '(1 2 ?z)) '(1 2 3))) ; test-unifier-3 (assert (= (unifier '[(?x . ?y) 3] [[1 2] 3]) '[(1 2) 3])) ; test-unifier-4 (assert (= (unifier '(?x . ?y) '(1 . ?z)) (lcons 1 '_.0))) ; test-unifier-5 (assert (= (unifier '(?x 2 . ?y) '(1 2 3 4 5)) '(1 2 3 4 5))) ; test-unifier-6 (assert (= (unifier '(?x 2 . ?y) '(1 9 3 4 5)) nil)) ; test-binding-map-1 (assert (= (binding-map '(?x ?y) '(1 2)) '{?x 1 ?y 2})) ; test-binding-map-2 (assert (= (binding-map '(?x ?y 3) '(1 2 ?z)) '{?x 1 ?y 2 ?z 3})) ; test-binding-map-3 (assert (= (binding-map '[(?x . ?y) 3] [[1 2] 3]) '{?x 1 ?y (2)})) ; test-binding-map-4 (assert (= (binding-map '(?x . ?y) '(1 . ?z)) '{?z _.0, ?x 1, ?y _.0})) ; test-binding-map-5 (assert (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5)) '{?x 1 ?y (3 4 5)})) ; test-binding-map-6 (assert (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5)) nil)) ;; ----------------------------------------------------------------------------- ;; Occurs Check (println "occurs check") (assert (= (run* [q] (m/== q [q])) ())) ;; ----------------------------------------------------------------------------- ;; Unifications that should fail (println "unifications that sould fail") (assert (= (run* [p] (fresh [a b] (m/== b ()) (m/== '(0 1) (lcons a b)) (m/== p [a b]))) ())) (assert (= (run* [p] (fresh [a b] (m/== b '(1)) (m/== '(0) (lcons a b)) (m/== p [a b]))) ())) (assert (= (run* [p] (fresh [a b c d] (m/== () b) (m/== '(1) d) (m/== (lcons a b) (lcons c d)) (m/== p [a b c d]))) ())) ;; ----------------------------------------------------------------------------- ;; Pattern matching other data structures (println "pattern matching") (defne match-map [m o] ([{:foo {:bar o}} _])) (assert (= (run* [q] (match-map {:foo {:bar 1}} q)) '(1))) (defne match-set [s o] ([#{:cat :bird :dog} _])) (assert (= (run* [q] (match-set #{:cat :bird :dog} q)) '(_.0))) ;; ----------------------------------------------------------------------------- ;; Partial maps (println "partial maps") (assert (= '({:a 1}) (run* [q] (fresh [pm x] (== pm (partial-map {:a x})) (== pm {:a 1 :b 2}) (== pm q))))) (assert (= '(1) (run* [q] (fresh [pm x] (== pm (partial-map {:a x})) (== pm {:a 1 :b 2}) (== x q))))) (comment ;; FIXME: for some reason set #{:cat :bird} works on match-set call - David ) ;; ============================================================================= ;; zebrao (println "zebrao") (defne righto [x y l] ([_ _ [x y . r]]) ([_ _ [_ . r]] (righto x y r))) (defn nexto [x y l] (conde [(righto x y l)] [(righto y x l)])) (defn zebrao [hs] (mu/symbol-macrolet [_ (lvar)] (all (m/== (list _ _ (list _ _ 'milk _ _) _ _) hs) (firsto hs (list 'norwegian _ _ _ _)) (nexto (list 'norwegian _ _ _ _) (list _ _ _ _ 'blue) hs) (righto (list _ _ _ _ 'ivory) (list _ _ _ _ 'green) hs) (membero (list 'englishman _ _ _ 'red) hs) (membero (list _ 'kools _ _ 'yellow) hs) (membero (list 'spaniard _ _ 'dog _) hs) (membero (list _ _ 'coffee _ 'green) hs) (membero (list 'ukrainian _ 'tea _ _) hs) (membero (list _ 'lucky-strikes 'oj _ _) hs) (membero (list 'japanese 'parliaments _ _ _) hs) (membero (list _ 'oldgolds _ 'snails _) hs) (nexto (list _ _ _ 'horse _) (list _ 'kools _ _ _) hs) (nexto (list _ _ _ 'fox _) (list _ 'chesterfields _ _ _) hs)))) (defn ^:export run_zebra [] (binding [*occurs-check* false] (doall (run 1 [q] (zebrao q))))) (println (pr-str (run 1 [q] (zebrao q)))) (binding [*occurs-check* false] (time (dotimes [_ 1000] (run 1 [q] (zebrao q))))) (println (pr-str (run 10 [q] (nexto 'dog 'cat q)))) ;; ============================================================================= ;; matche (defn map-geto [m k v] (matche [m] ([[[k v] . _]]) ([[_ . tail]] (map-geto tail k v)))) (assert (= (run* [q] (map-geto (seq {:title "Blub"}) :title q)) '("Blub"))) (println "ok")
96263
(ns cljs.core.logic.tests (:refer-clojure :exclude [==]) (:use-macros [cljs.core.logic.macros :only [run run* == conde conda condu fresh defne matche all]]) (:require-macros [cljs.core.logic.macros :as m] [clojure.tools.macro :as mu]) (:use [cljs.core.logic :only [pair lvar lcons -unify -ext-no-check -walk -walk* -reify-lvar-name empty-s to-s succeed fail s# u# conso nilo firsto resto emptyo appendo membero *occurs-check* unifier binding-map partial-map failed?]])) (defn js-print [& args] (if (js* "typeof console != 'undefined'") (.log js/console (apply str args)) (js/print (apply str args)))) (set! *print-fn* js-print) ;; ============================================================================= ;; unify ;; ----------------------------------------------------------------------------- ;; unify with nil (println "unify with nil") (let [x (lvar 'x)] (assert (= (pair x nil) (pair x nil)))) (let [x (lvar 'x)] (assert (false? (= (pair x nil) (pair nil x))))) (assert (failed? (-unify empty-s nil 1))) (let [x (lvar 'x) a (-ext-no-check empty-s x nil) b (-unify empty-s nil x)] (assert (= a b))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil (lcons 1 x))))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil {})))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil #{})))) ;; ----------------------------------------------------------------------------- ;; unify with object (println "unify with object") (assert (failed? (-unify empty-s 1 nil))) (assert (= (-unify empty-s 1 1) empty-s)) (assert (= (-unify empty-s :foo :foo) empty-s)) (assert (= (-unify empty-s 'foo 'foo) empty-s)) (assert (= (-unify empty-s "foo" "foo") empty-s)) (assert (failed? (-unify empty-s 1 2))) (assert (failed? (-unify empty-s 2 1))) (assert (failed? (-unify empty-s :foo :bar))) (assert (failed? (-unify empty-s 'foo 'bar))) (assert (failed? (-unify empty-s "foo" "bar"))) (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s 1 x) os))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s 1 (lcons 1 'x))))) (assert (failed? (-unify empty-s 1 '()))) (assert (failed? (-unify empty-s 1 '[]))) (assert (failed? (-unify empty-s 1 {}))) (assert (failed? (-unify empty-s 1 #{}))) ;; ----------------------------------------------------------------------------- ;; unify with lvar (println "unify with lvar") (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s x 1) os))) (let [x (lvar 'x) y (lvar 'y) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s x y) os))) (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (-ext-no-check empty-s x l)] (assert (= (-unify empty-s x l) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s x []) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [1 2 3])] (assert (= (-unify empty-s x [1 2 3]) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x '())] (assert (= (-unify empty-s x '()) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x '(1 2 3))] (assert (= (-unify empty-s x '(1 2 3)) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x {})] (assert (= (-unify empty-s x {}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x {1 2 3 4})] (assert (= (-unify empty-s x {1 2 3 4}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x #{})] (assert (= (-unify empty-s x #{}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x #{1 2 3})] (assert (= (-unify empty-s x #{1 2 3}) os))) ;; ----------------------------------------------------------------------------- ;; unify with lcons (println "unify with lcons") (let [x (lvar 'x)] (assert (failed? (-unify empty-s (lcons 1 x) 1)))) (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (-ext-no-check empty-s x l)] (assert (= (-unify empty-s l x) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 x) lc2 (lcons 1 y) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s lc1 lc2) os))) ;; NOTE: sketchy tests that makes ordering assumptions about representation ;; - <NAME> ;; START HERE (let [x (lvar 'x) y (lvar 'y) z (lvar 'z) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons z y)) os (-> empty-s (-ext-no-check z 2) (-ext-no-check x y))] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 (lcons 3 y))) os (-ext-no-check empty-s x (lcons 3 y))] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 3 (lcons 4 y)))] (assert (failed? (-unify empty-s lc1 lc2)))) (let [x (lvar 'x) y (lvar 'y) lc2 (lcons 1 (lcons 2 x)) lc1 (lcons 1 (lcons 3 (lcons 4 y)))] (assert (failed? (-unify empty-s lc1 lc2)))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 y)) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (-ext-no-check empty-s x '(3 4))] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons y (lcons 3 x))) l1 '(1 2 3 4) os (-> empty-s (-ext-no-check y 2) (-ext-no-check x '(4)))] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 (lcons 3 x))) l1 '(1 2 3) os (-ext-no-check empty-s x '())] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 3 x)) l1 '(1 2 3 4)] (assert (failed? (-unify empty-s lc1 l1)))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 3 4 5)] (assert (failed? (-unify empty-s lc1 l1)))) (assert (failed? (-unify empty-s (lcons 1 (lvar 'x)) {}))) (assert (failed? (-unify empty-s (lcons 1 (lvar 'x)) #{}))) ;; ----------------------------------------------------------------------------- ;; unify with sequential (println "unify with sequential") (assert (failed? (-unify empty-s '() 1))) (assert (failed? (-unify empty-s [] 1))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s [] x) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s [] x) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (-ext-no-check empty-s x '(3 4))] (assert (= (-unify empty-s l1 lc1) os))) (assert (= (-unify empty-s [1 2 3] [1 2 3]) empty-s)) (assert (= (-unify empty-s '(1 2 3) [1 2 3]) empty-s)) (assert (= (-unify empty-s '(1 2 3) '(1 2 3)) empty-s)) (let [x (lvar 'x) os (-ext-no-check empty-s x 2)] (assert (= (-unify empty-s `(1 ~x 3) `(1 2 3)) os))) (assert (failed? (-unify empty-s [1 2] [1 2 3]))) (assert (failed? (-unify empty-s '(1 2) [1 2 3]))) (assert (failed? (-unify empty-s [1 2 3] [3 2 1]))) (assert (= (-unify empty-s '() '()) empty-s)) (assert (failed? (-unify empty-s '() '(1)))) (assert (failed? (-unify empty-s '(1) '()))) (assert (= (-unify empty-s [[1 2]] [[1 2]]) empty-s)) (assert (failed? (-unify empty-s [[1 2]] [[2 1]]))) (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s [[x 2]] [[1 2]]) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [1 2])] (assert (= (-unify empty-s [x] [[1 2]]) os))) (let [x (lvar 'x) y (lvar 'y) u (lvar 'u) v (lvar 'v) os (-> empty-s (-ext-no-check y 'a) (-ext-no-check x 'b))] (assert (= (-unify empty-s ['a x] [y 'b]) os))) (assert (failed? (-unify empty-s [] {}))) (assert (failed? (-unify empty-s '() {}))) (assert (failed? (-unify empty-s [] #{}))) (assert (failed? (-unify empty-s '() #{}))) ;; ----------------------------------------------------------------------------- ;; unify with map (println "unify with map") (assert (failed? (-unify empty-s {} 1))) (let [x (lvar 'x) os (-ext-no-check empty-s x {})] (assert (= (-unify empty-s {} x) os))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s {} (lcons 1 x))))) (assert (failed? (-unify empty-s {} '()))) (assert (= (-unify empty-s {} {}) empty-s)) (assert (= (-unify empty-s {1 2 3 4} {1 2 3 4}) empty-s)) (assert (failed? (-unify empty-s {1 2} {1 2 3 4}))) (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 2 3 x} os (-ext-no-check empty-s x 4)] (assert (= (-unify empty-s m1 m2) os))) (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 4 3 x}] (assert (failed? (-unify empty-s m1 m2)))) (assert (failed? (-unify empty-s {} #{}))) ;; ============================================================================= ;; walk (println "walk") (assert (= (let [x (lvar 'x) y (lvar 'y) s (to-s [[x 5] [y x]])] (-walk s y)) 5)) (assert (= (let [[x y z c b a :as s] (map lvar '[x y z c b a]) s (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])] (-walk s a)) 5)) ;; ============================================================================= ;; reify (println "reify") (assert (= (let [x (lvar 'x) y (lvar 'y)] (-reify-lvar-name (to-s [[x 5] [y x]]))) '_.2)) ;; ============================================================================= ;; walk* (println "walk*") (assert (= (let [x (lvar 'x) y (lvar 'y)] (-walk* (to-s [[x 5] [y x]]) `(~x ~y))) '(5 5))) ;; ============================================================================= ;; run and unify (println "run and unify") (assert (= (run* [q] (m/== true q)) '(true))) (assert (= (run* [q] (fresh [x y] (m/== [x y] [1 5]) (m/== [x y] q))) [[1 5]])) (assert (= (run* [q] (fresh [x y] (m/== [x y] q))) '[[_.0 _.1]])) ;; ============================================================================= ;; fail (println "fail") (assert (= (run* [q] fail (m/== true q)) [])) ;; ============================================================================= ;; Basic (println "basic") (assert (= (run* [q] (all (m/== 1 1) (m/== q true))) '(true))) ;; ============================================================================= ;; TRS (println "trs") (defn pairo [p] (fresh [a d] (m/== (lcons a d) p))) (defn twino [p] (fresh [x] (conso x x p))) (defn listo [l] (conde [(emptyo l) s#] [(pairo l) (fresh [d] (resto l d) (listo d))])) (defn flatteno [s out] (conde [(emptyo s) (m/== '() out)] [(pairo s) (fresh [a d res-a res-d] (conso a d s) (flatteno a res-a) (flatteno d res-d) (appendo res-a res-d out))] [(conso s '() out)])) (defn rembero [x l out] (conde [(m/== '() l) (m/== '() out)] [(fresh [a d] (conso a d l) (m/== x a) (m/== d out))] [(fresh [a d res] (conso a d l) (conso a res out) (rembero x d res))])) ;; ============================================================================= ;; conde (println "conde") (assert (= (run* [x] (conde [(m/== x 'olive) succeed] [succeed succeed] [(m/== x 'oil) succeed])) '[olive _.0 oil])) (assert (= (run* [r] (fresh [x y] (conde [(m/== 'split x) (m/== 'pea y)] [(m/== 'navy x) (m/== 'bean y)]) (m/== (cons x (cons y ())) r))) '[(split pea) (navy bean)])) (defn teacupo [x] (conde [(m/== 'tea x) s#] [(m/== 'cup x) s#])) (assert (= (run* [r] (fresh [x y] (conde [(teacupo x) (m/== true y) s#] [(m/== false x) (m/== true y)]) (m/== (cons x (cons y ())) r))) '((false true) (tea true) (cup true)))) ;; ============================================================================= ;; conso (println "conso") (assert (= (run* [q] (fresh [a d] (conso a d ()) (m/== (cons a d) q))) [])) (let [a (lvar 'a) d (lvar 'd)] (assert (= (run* [q] (conso a d q)) [(lcons a d)]))) (assert (= (run* [q] (m/== [q] nil)) [])) (assert (= (run* [q] (conso 'a nil q)) '[(a)])) (assert (= (run* [q] (conso 'a '(d) q)) '[(a d)])) (assert (= (run* [q] (conso 'a q '(a))) '[()])) (assert (= (run* [q] (conso q '(b c) '(a b c))) '[a])) ;; ============================================================================= ;; firsto (println "firsto") (assert (= (run* [q] (firsto q '(1 2))) (list (lcons '(1 2) (lvar 'x))))) ;; ============================================================================= ;; resto (println "resto") (assert (= (run* [q] (resto q '(1 2))) '[(_.0 1 2)])) (assert (= (run* [q] (resto q [1 2])) '[(_.0 1 2)])) (assert (= (run* [q] (resto [1 2] q)) '[(2)])) (assert (= (run* [q] (resto [1 2 3 4 5 6 7 8] q)) '[(2 3 4 5 6 7 8)])) ;; ============================================================================= ;; flatteno (println "flatteno") (assert (= (run* [x] (flatteno '[[a b] c] x)) '(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ()) (a (b) (c)) (a (b) c) (a (b) c ()) (a b (c)) (a b () (c)) (a b c) (a b c ()) (a b () c) (a b () c ())))) ;; ============================================================================= ;; membero (println "membero") (assert (= (run* [q] (all (m/== q [(lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar]]))) (assert (= (run* [q] (all (m/== q [(lvar) (lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar] _.0] [[foo _.0] [_.1 bar]] [[_.0 bar] [foo _.1]] [_.0 [foo bar]]))) ;; ----------------------------------------------------------------------------- ;; rembero (println "rembero") (assert (= (run 1 [q] (rembero 'b '(a b c b d) q)) '((a c b d)))) ;; ----------------------------------------------------------------------------- ;; conde clause count (println "conde clause count") (defn digit-1 [x] (conde [(m/== 0 x)])) (defn digit-4 [x] (conde [(m/== 0 x)] [(m/== 1 x)] [(m/== 2 x)] [(m/== 3 x)])) (assert (= (run* [q] (fresh [x y] (digit-1 x) (digit-1 y) (m/== q [x y]))) '([0 0]))) (assert (= (run* [q] (fresh [x y] (digit-4 x) (digit-4 y) (m/== q [x y]))) '([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0] [1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3]))) ;; ----------------------------------------------------------------------------- ;; anyo (println "anyo") (defn anyo [q] (conde [q s#] [(anyo q)])) (assert (= (run 1 [q] (anyo s#) (m/== true q)) (list true))) (assert (= (run 5 [q] (anyo s#) (m/== true q)) (list true true true true true))) ;; ----------------------------------------------------------------------------- ;; divergence (println "divergence") (def f1 (fresh [] f1)) (assert (= (run 1 [q] (conde [f1] [(m/== false false)])) '(_.0))) (assert (= (run 1 [q] (conde [f1 (m/== false false)] [(m/== false false)])) '(_.0))) (def f2 (fresh [] (conde [f2 (conde [f2] [(m/== false false)])] [(m/== false false)]))) (assert (= (run 5 [q] f2) '(_.0 _.0 _.0 _.0 _.0))) ;; ----------------------------------------------------------------------------- ;; conda (soft-cut) (println "conda") (assert (= (run* [x] (conda [(m/== 'olive x) s#] [(m/== 'oil x) s#] [u#])) '(olive))) (assert (= (run* [x] (conda [(m/== 'virgin x) u#] [(m/== 'olive x) s#] [(m/== 'oil x) s#] [u#])) '())) (assert (= (run* [x] (fresh (x y) (m/== 'split x) (m/== 'pea y) (conda [(m/== 'split x) (m/== x y)] [s#])) (m/== true x)) '())) (assert (= (run* [x] (fresh (x y) (m/== 'split x) (m/== 'pea y) (conda [(m/== x y) (m/== 'split x)] [s#])) (m/== true x)) '(true))) (defn not-pastao [x] (conda [(m/== 'pasta x) u#] [s#])) (assert (= (run* [x] (conda [(not-pastao x)] [(m/== 'spaghetti x)])) '(spaghetti))) ;; ----------------------------------------------------------------------------- ;; condu (committed-choice) (println "condu") (defn onceo [g] (condu (g s#))) (assert (= (run* [x] (onceo (teacupo x))) '(tea))) (assert (= (run* [r] (conde [(teacupo r) s#] [(m/== false r) s#])) '(false tea cup))) (assert (= (run* [r] (conda [(teacupo r) s#] [(m/== false r) s#])) '(tea cup))) ;; ----------------------------------------------------------------------------- ;; nil in collection (println "nil in collection") (assert (= (run* [q] (m/== q [nil])) '([nil]))) (assert (= (run* [q] (m/== q [1 nil])) '([1 nil]))) (assert (= (run* [q] (m/== q [nil 1])) '([nil 1]))) (assert (= (run* [q] (m/== q '(nil))) '((nil)))) (assert (= (run* [q] (m/== q {:foo nil})) '({:foo nil}))) (assert (= (run* [q] (m/== q {nil :foo})) '({nil :foo}))) ;; ----------------------------------------------------------------------------- ;; Unifier (println "simple unifier") ; test-unifier-1 (assert (= (unifier '(?x ?y) '(1 2)) '(1 2))) ; test-unifier-2 (assert (= (unifier '(?x ?y 3) '(1 2 ?z)) '(1 2 3))) ; test-unifier-3 (assert (= (unifier '[(?x . ?y) 3] [[1 2] 3]) '[(1 2) 3])) ; test-unifier-4 (assert (= (unifier '(?x . ?y) '(1 . ?z)) (lcons 1 '_.0))) ; test-unifier-5 (assert (= (unifier '(?x 2 . ?y) '(1 2 3 4 5)) '(1 2 3 4 5))) ; test-unifier-6 (assert (= (unifier '(?x 2 . ?y) '(1 9 3 4 5)) nil)) ; test-binding-map-1 (assert (= (binding-map '(?x ?y) '(1 2)) '{?x 1 ?y 2})) ; test-binding-map-2 (assert (= (binding-map '(?x ?y 3) '(1 2 ?z)) '{?x 1 ?y 2 ?z 3})) ; test-binding-map-3 (assert (= (binding-map '[(?x . ?y) 3] [[1 2] 3]) '{?x 1 ?y (2)})) ; test-binding-map-4 (assert (= (binding-map '(?x . ?y) '(1 . ?z)) '{?z _.0, ?x 1, ?y _.0})) ; test-binding-map-5 (assert (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5)) '{?x 1 ?y (3 4 5)})) ; test-binding-map-6 (assert (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5)) nil)) ;; ----------------------------------------------------------------------------- ;; Occurs Check (println "occurs check") (assert (= (run* [q] (m/== q [q])) ())) ;; ----------------------------------------------------------------------------- ;; Unifications that should fail (println "unifications that sould fail") (assert (= (run* [p] (fresh [a b] (m/== b ()) (m/== '(0 1) (lcons a b)) (m/== p [a b]))) ())) (assert (= (run* [p] (fresh [a b] (m/== b '(1)) (m/== '(0) (lcons a b)) (m/== p [a b]))) ())) (assert (= (run* [p] (fresh [a b c d] (m/== () b) (m/== '(1) d) (m/== (lcons a b) (lcons c d)) (m/== p [a b c d]))) ())) ;; ----------------------------------------------------------------------------- ;; Pattern matching other data structures (println "pattern matching") (defne match-map [m o] ([{:foo {:bar o}} _])) (assert (= (run* [q] (match-map {:foo {:bar 1}} q)) '(1))) (defne match-set [s o] ([#{:cat :bird :dog} _])) (assert (= (run* [q] (match-set #{:cat :bird :dog} q)) '(_.0))) ;; ----------------------------------------------------------------------------- ;; Partial maps (println "partial maps") (assert (= '({:a 1}) (run* [q] (fresh [pm x] (== pm (partial-map {:a x})) (== pm {:a 1 :b 2}) (== pm q))))) (assert (= '(1) (run* [q] (fresh [pm x] (== pm (partial-map {:a x})) (== pm {:a 1 :b 2}) (== x q))))) (comment ;; FIXME: for some reason set #{:cat :bird} works on match-set call - David ) ;; ============================================================================= ;; zebrao (println "zebrao") (defne righto [x y l] ([_ _ [x y . r]]) ([_ _ [_ . r]] (righto x y r))) (defn nexto [x y l] (conde [(righto x y l)] [(righto y x l)])) (defn zebrao [hs] (mu/symbol-macrolet [_ (lvar)] (all (m/== (list _ _ (list _ _ 'milk _ _) _ _) hs) (firsto hs (list 'norwegian _ _ _ _)) (nexto (list 'norwegian _ _ _ _) (list _ _ _ _ 'blue) hs) (righto (list _ _ _ _ 'ivory) (list _ _ _ _ 'green) hs) (membero (list 'englishman _ _ _ 'red) hs) (membero (list _ 'kools _ _ 'yellow) hs) (membero (list 'spaniard _ _ 'dog _) hs) (membero (list _ _ 'coffee _ 'green) hs) (membero (list 'ukrainian _ 'tea _ _) hs) (membero (list _ 'lucky-strikes 'oj _ _) hs) (membero (list 'japanese 'parliaments _ _ _) hs) (membero (list _ 'oldgolds _ 'snails _) hs) (nexto (list _ _ _ 'horse _) (list _ 'kools _ _ _) hs) (nexto (list _ _ _ 'fox _) (list _ 'chesterfields _ _ _) hs)))) (defn ^:export run_zebra [] (binding [*occurs-check* false] (doall (run 1 [q] (zebrao q))))) (println (pr-str (run 1 [q] (zebrao q)))) (binding [*occurs-check* false] (time (dotimes [_ 1000] (run 1 [q] (zebrao q))))) (println (pr-str (run 10 [q] (nexto 'dog 'cat q)))) ;; ============================================================================= ;; matche (defn map-geto [m k v] (matche [m] ([[[k v] . _]]) ([[_ . tail]] (map-geto tail k v)))) (assert (= (run* [q] (map-geto (seq {:title "Blub"}) :title q)) '("Blub"))) (println "ok")
true
(ns cljs.core.logic.tests (:refer-clojure :exclude [==]) (:use-macros [cljs.core.logic.macros :only [run run* == conde conda condu fresh defne matche all]]) (:require-macros [cljs.core.logic.macros :as m] [clojure.tools.macro :as mu]) (:use [cljs.core.logic :only [pair lvar lcons -unify -ext-no-check -walk -walk* -reify-lvar-name empty-s to-s succeed fail s# u# conso nilo firsto resto emptyo appendo membero *occurs-check* unifier binding-map partial-map failed?]])) (defn js-print [& args] (if (js* "typeof console != 'undefined'") (.log js/console (apply str args)) (js/print (apply str args)))) (set! *print-fn* js-print) ;; ============================================================================= ;; unify ;; ----------------------------------------------------------------------------- ;; unify with nil (println "unify with nil") (let [x (lvar 'x)] (assert (= (pair x nil) (pair x nil)))) (let [x (lvar 'x)] (assert (false? (= (pair x nil) (pair nil x))))) (assert (failed? (-unify empty-s nil 1))) (let [x (lvar 'x) a (-ext-no-check empty-s x nil) b (-unify empty-s nil x)] (assert (= a b))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil (lcons 1 x))))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil {})))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s nil #{})))) ;; ----------------------------------------------------------------------------- ;; unify with object (println "unify with object") (assert (failed? (-unify empty-s 1 nil))) (assert (= (-unify empty-s 1 1) empty-s)) (assert (= (-unify empty-s :foo :foo) empty-s)) (assert (= (-unify empty-s 'foo 'foo) empty-s)) (assert (= (-unify empty-s "foo" "foo") empty-s)) (assert (failed? (-unify empty-s 1 2))) (assert (failed? (-unify empty-s 2 1))) (assert (failed? (-unify empty-s :foo :bar))) (assert (failed? (-unify empty-s 'foo 'bar))) (assert (failed? (-unify empty-s "foo" "bar"))) (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s 1 x) os))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s 1 (lcons 1 'x))))) (assert (failed? (-unify empty-s 1 '()))) (assert (failed? (-unify empty-s 1 '[]))) (assert (failed? (-unify empty-s 1 {}))) (assert (failed? (-unify empty-s 1 #{}))) ;; ----------------------------------------------------------------------------- ;; unify with lvar (println "unify with lvar") (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s x 1) os))) (let [x (lvar 'x) y (lvar 'y) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s x y) os))) (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (-ext-no-check empty-s x l)] (assert (= (-unify empty-s x l) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s x []) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [1 2 3])] (assert (= (-unify empty-s x [1 2 3]) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x '())] (assert (= (-unify empty-s x '()) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x '(1 2 3))] (assert (= (-unify empty-s x '(1 2 3)) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x {})] (assert (= (-unify empty-s x {}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x {1 2 3 4})] (assert (= (-unify empty-s x {1 2 3 4}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x #{})] (assert (= (-unify empty-s x #{}) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x #{1 2 3})] (assert (= (-unify empty-s x #{1 2 3}) os))) ;; ----------------------------------------------------------------------------- ;; unify with lcons (println "unify with lcons") (let [x (lvar 'x)] (assert (failed? (-unify empty-s (lcons 1 x) 1)))) (let [x (lvar 'x) y (lvar 'y) l (lcons 1 y) os (-ext-no-check empty-s x l)] (assert (= (-unify empty-s l x) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 x) lc2 (lcons 1 y) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s lc1 lc2) os))) ;; NOTE: sketchy tests that makes ordering assumptions about representation ;; - PI:NAME:<NAME>END_PI ;; START HERE (let [x (lvar 'x) y (lvar 'y) z (lvar 'z) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons z y)) os (-> empty-s (-ext-no-check z 2) (-ext-no-check x y))] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 (lcons 3 y))) os (-ext-no-check empty-s x (lcons 3 y))] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 3 (lcons 4 y)))] (assert (failed? (-unify empty-s lc1 lc2)))) (let [x (lvar 'x) y (lvar 'y) lc2 (lcons 1 (lcons 2 x)) lc1 (lcons 1 (lcons 3 (lcons 4 y)))] (assert (failed? (-unify empty-s lc1 lc2)))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons 2 x)) lc2 (lcons 1 (lcons 2 y)) os (-ext-no-check empty-s x y)] (assert (= (-unify empty-s lc1 lc2) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (-ext-no-check empty-s x '(3 4))] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) y (lvar 'y) lc1 (lcons 1 (lcons y (lcons 3 x))) l1 '(1 2 3 4) os (-> empty-s (-ext-no-check y 2) (-ext-no-check x '(4)))] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 (lcons 3 x))) l1 '(1 2 3) os (-ext-no-check empty-s x '())] (assert (= (-unify empty-s lc1 l1) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 3 x)) l1 '(1 2 3 4)] (assert (failed? (-unify empty-s lc1 l1)))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 3 4 5)] (assert (failed? (-unify empty-s lc1 l1)))) (assert (failed? (-unify empty-s (lcons 1 (lvar 'x)) {}))) (assert (failed? (-unify empty-s (lcons 1 (lvar 'x)) #{}))) ;; ----------------------------------------------------------------------------- ;; unify with sequential (println "unify with sequential") (assert (failed? (-unify empty-s '() 1))) (assert (failed? (-unify empty-s [] 1))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s [] x) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [])] (assert (= (-unify empty-s [] x) os))) (let [x (lvar 'x) lc1 (lcons 1 (lcons 2 x)) l1 '(1 2 3 4) os (-ext-no-check empty-s x '(3 4))] (assert (= (-unify empty-s l1 lc1) os))) (assert (= (-unify empty-s [1 2 3] [1 2 3]) empty-s)) (assert (= (-unify empty-s '(1 2 3) [1 2 3]) empty-s)) (assert (= (-unify empty-s '(1 2 3) '(1 2 3)) empty-s)) (let [x (lvar 'x) os (-ext-no-check empty-s x 2)] (assert (= (-unify empty-s `(1 ~x 3) `(1 2 3)) os))) (assert (failed? (-unify empty-s [1 2] [1 2 3]))) (assert (failed? (-unify empty-s '(1 2) [1 2 3]))) (assert (failed? (-unify empty-s [1 2 3] [3 2 1]))) (assert (= (-unify empty-s '() '()) empty-s)) (assert (failed? (-unify empty-s '() '(1)))) (assert (failed? (-unify empty-s '(1) '()))) (assert (= (-unify empty-s [[1 2]] [[1 2]]) empty-s)) (assert (failed? (-unify empty-s [[1 2]] [[2 1]]))) (let [x (lvar 'x) os (-ext-no-check empty-s x 1)] (assert (= (-unify empty-s [[x 2]] [[1 2]]) os))) (let [x (lvar 'x) os (-ext-no-check empty-s x [1 2])] (assert (= (-unify empty-s [x] [[1 2]]) os))) (let [x (lvar 'x) y (lvar 'y) u (lvar 'u) v (lvar 'v) os (-> empty-s (-ext-no-check y 'a) (-ext-no-check x 'b))] (assert (= (-unify empty-s ['a x] [y 'b]) os))) (assert (failed? (-unify empty-s [] {}))) (assert (failed? (-unify empty-s '() {}))) (assert (failed? (-unify empty-s [] #{}))) (assert (failed? (-unify empty-s '() #{}))) ;; ----------------------------------------------------------------------------- ;; unify with map (println "unify with map") (assert (failed? (-unify empty-s {} 1))) (let [x (lvar 'x) os (-ext-no-check empty-s x {})] (assert (= (-unify empty-s {} x) os))) (let [x (lvar 'x)] (assert (failed? (-unify empty-s {} (lcons 1 x))))) (assert (failed? (-unify empty-s {} '()))) (assert (= (-unify empty-s {} {}) empty-s)) (assert (= (-unify empty-s {1 2 3 4} {1 2 3 4}) empty-s)) (assert (failed? (-unify empty-s {1 2} {1 2 3 4}))) (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 2 3 x} os (-ext-no-check empty-s x 4)] (assert (= (-unify empty-s m1 m2) os))) (let [x (lvar 'x) m1 {1 2 3 4} m2 {1 4 3 x}] (assert (failed? (-unify empty-s m1 m2)))) (assert (failed? (-unify empty-s {} #{}))) ;; ============================================================================= ;; walk (println "walk") (assert (= (let [x (lvar 'x) y (lvar 'y) s (to-s [[x 5] [y x]])] (-walk s y)) 5)) (assert (= (let [[x y z c b a :as s] (map lvar '[x y z c b a]) s (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])] (-walk s a)) 5)) ;; ============================================================================= ;; reify (println "reify") (assert (= (let [x (lvar 'x) y (lvar 'y)] (-reify-lvar-name (to-s [[x 5] [y x]]))) '_.2)) ;; ============================================================================= ;; walk* (println "walk*") (assert (= (let [x (lvar 'x) y (lvar 'y)] (-walk* (to-s [[x 5] [y x]]) `(~x ~y))) '(5 5))) ;; ============================================================================= ;; run and unify (println "run and unify") (assert (= (run* [q] (m/== true q)) '(true))) (assert (= (run* [q] (fresh [x y] (m/== [x y] [1 5]) (m/== [x y] q))) [[1 5]])) (assert (= (run* [q] (fresh [x y] (m/== [x y] q))) '[[_.0 _.1]])) ;; ============================================================================= ;; fail (println "fail") (assert (= (run* [q] fail (m/== true q)) [])) ;; ============================================================================= ;; Basic (println "basic") (assert (= (run* [q] (all (m/== 1 1) (m/== q true))) '(true))) ;; ============================================================================= ;; TRS (println "trs") (defn pairo [p] (fresh [a d] (m/== (lcons a d) p))) (defn twino [p] (fresh [x] (conso x x p))) (defn listo [l] (conde [(emptyo l) s#] [(pairo l) (fresh [d] (resto l d) (listo d))])) (defn flatteno [s out] (conde [(emptyo s) (m/== '() out)] [(pairo s) (fresh [a d res-a res-d] (conso a d s) (flatteno a res-a) (flatteno d res-d) (appendo res-a res-d out))] [(conso s '() out)])) (defn rembero [x l out] (conde [(m/== '() l) (m/== '() out)] [(fresh [a d] (conso a d l) (m/== x a) (m/== d out))] [(fresh [a d res] (conso a d l) (conso a res out) (rembero x d res))])) ;; ============================================================================= ;; conde (println "conde") (assert (= (run* [x] (conde [(m/== x 'olive) succeed] [succeed succeed] [(m/== x 'oil) succeed])) '[olive _.0 oil])) (assert (= (run* [r] (fresh [x y] (conde [(m/== 'split x) (m/== 'pea y)] [(m/== 'navy x) (m/== 'bean y)]) (m/== (cons x (cons y ())) r))) '[(split pea) (navy bean)])) (defn teacupo [x] (conde [(m/== 'tea x) s#] [(m/== 'cup x) s#])) (assert (= (run* [r] (fresh [x y] (conde [(teacupo x) (m/== true y) s#] [(m/== false x) (m/== true y)]) (m/== (cons x (cons y ())) r))) '((false true) (tea true) (cup true)))) ;; ============================================================================= ;; conso (println "conso") (assert (= (run* [q] (fresh [a d] (conso a d ()) (m/== (cons a d) q))) [])) (let [a (lvar 'a) d (lvar 'd)] (assert (= (run* [q] (conso a d q)) [(lcons a d)]))) (assert (= (run* [q] (m/== [q] nil)) [])) (assert (= (run* [q] (conso 'a nil q)) '[(a)])) (assert (= (run* [q] (conso 'a '(d) q)) '[(a d)])) (assert (= (run* [q] (conso 'a q '(a))) '[()])) (assert (= (run* [q] (conso q '(b c) '(a b c))) '[a])) ;; ============================================================================= ;; firsto (println "firsto") (assert (= (run* [q] (firsto q '(1 2))) (list (lcons '(1 2) (lvar 'x))))) ;; ============================================================================= ;; resto (println "resto") (assert (= (run* [q] (resto q '(1 2))) '[(_.0 1 2)])) (assert (= (run* [q] (resto q [1 2])) '[(_.0 1 2)])) (assert (= (run* [q] (resto [1 2] q)) '[(2)])) (assert (= (run* [q] (resto [1 2 3 4 5 6 7 8] q)) '[(2 3 4 5 6 7 8)])) ;; ============================================================================= ;; flatteno (println "flatteno") (assert (= (run* [x] (flatteno '[[a b] c] x)) '(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ()) (a (b) (c)) (a (b) c) (a (b) c ()) (a b (c)) (a b () (c)) (a b c) (a b c ()) (a b () c) (a b () c ())))) ;; ============================================================================= ;; membero (println "membero") (assert (= (run* [q] (all (m/== q [(lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar]]))) (assert (= (run* [q] (all (m/== q [(lvar) (lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar] _.0] [[foo _.0] [_.1 bar]] [[_.0 bar] [foo _.1]] [_.0 [foo bar]]))) ;; ----------------------------------------------------------------------------- ;; rembero (println "rembero") (assert (= (run 1 [q] (rembero 'b '(a b c b d) q)) '((a c b d)))) ;; ----------------------------------------------------------------------------- ;; conde clause count (println "conde clause count") (defn digit-1 [x] (conde [(m/== 0 x)])) (defn digit-4 [x] (conde [(m/== 0 x)] [(m/== 1 x)] [(m/== 2 x)] [(m/== 3 x)])) (assert (= (run* [q] (fresh [x y] (digit-1 x) (digit-1 y) (m/== q [x y]))) '([0 0]))) (assert (= (run* [q] (fresh [x y] (digit-4 x) (digit-4 y) (m/== q [x y]))) '([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0] [1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3]))) ;; ----------------------------------------------------------------------------- ;; anyo (println "anyo") (defn anyo [q] (conde [q s#] [(anyo q)])) (assert (= (run 1 [q] (anyo s#) (m/== true q)) (list true))) (assert (= (run 5 [q] (anyo s#) (m/== true q)) (list true true true true true))) ;; ----------------------------------------------------------------------------- ;; divergence (println "divergence") (def f1 (fresh [] f1)) (assert (= (run 1 [q] (conde [f1] [(m/== false false)])) '(_.0))) (assert (= (run 1 [q] (conde [f1 (m/== false false)] [(m/== false false)])) '(_.0))) (def f2 (fresh [] (conde [f2 (conde [f2] [(m/== false false)])] [(m/== false false)]))) (assert (= (run 5 [q] f2) '(_.0 _.0 _.0 _.0 _.0))) ;; ----------------------------------------------------------------------------- ;; conda (soft-cut) (println "conda") (assert (= (run* [x] (conda [(m/== 'olive x) s#] [(m/== 'oil x) s#] [u#])) '(olive))) (assert (= (run* [x] (conda [(m/== 'virgin x) u#] [(m/== 'olive x) s#] [(m/== 'oil x) s#] [u#])) '())) (assert (= (run* [x] (fresh (x y) (m/== 'split x) (m/== 'pea y) (conda [(m/== 'split x) (m/== x y)] [s#])) (m/== true x)) '())) (assert (= (run* [x] (fresh (x y) (m/== 'split x) (m/== 'pea y) (conda [(m/== x y) (m/== 'split x)] [s#])) (m/== true x)) '(true))) (defn not-pastao [x] (conda [(m/== 'pasta x) u#] [s#])) (assert (= (run* [x] (conda [(not-pastao x)] [(m/== 'spaghetti x)])) '(spaghetti))) ;; ----------------------------------------------------------------------------- ;; condu (committed-choice) (println "condu") (defn onceo [g] (condu (g s#))) (assert (= (run* [x] (onceo (teacupo x))) '(tea))) (assert (= (run* [r] (conde [(teacupo r) s#] [(m/== false r) s#])) '(false tea cup))) (assert (= (run* [r] (conda [(teacupo r) s#] [(m/== false r) s#])) '(tea cup))) ;; ----------------------------------------------------------------------------- ;; nil in collection (println "nil in collection") (assert (= (run* [q] (m/== q [nil])) '([nil]))) (assert (= (run* [q] (m/== q [1 nil])) '([1 nil]))) (assert (= (run* [q] (m/== q [nil 1])) '([nil 1]))) (assert (= (run* [q] (m/== q '(nil))) '((nil)))) (assert (= (run* [q] (m/== q {:foo nil})) '({:foo nil}))) (assert (= (run* [q] (m/== q {nil :foo})) '({nil :foo}))) ;; ----------------------------------------------------------------------------- ;; Unifier (println "simple unifier") ; test-unifier-1 (assert (= (unifier '(?x ?y) '(1 2)) '(1 2))) ; test-unifier-2 (assert (= (unifier '(?x ?y 3) '(1 2 ?z)) '(1 2 3))) ; test-unifier-3 (assert (= (unifier '[(?x . ?y) 3] [[1 2] 3]) '[(1 2) 3])) ; test-unifier-4 (assert (= (unifier '(?x . ?y) '(1 . ?z)) (lcons 1 '_.0))) ; test-unifier-5 (assert (= (unifier '(?x 2 . ?y) '(1 2 3 4 5)) '(1 2 3 4 5))) ; test-unifier-6 (assert (= (unifier '(?x 2 . ?y) '(1 9 3 4 5)) nil)) ; test-binding-map-1 (assert (= (binding-map '(?x ?y) '(1 2)) '{?x 1 ?y 2})) ; test-binding-map-2 (assert (= (binding-map '(?x ?y 3) '(1 2 ?z)) '{?x 1 ?y 2 ?z 3})) ; test-binding-map-3 (assert (= (binding-map '[(?x . ?y) 3] [[1 2] 3]) '{?x 1 ?y (2)})) ; test-binding-map-4 (assert (= (binding-map '(?x . ?y) '(1 . ?z)) '{?z _.0, ?x 1, ?y _.0})) ; test-binding-map-5 (assert (= (binding-map '(?x 2 . ?y) '(1 2 3 4 5)) '{?x 1 ?y (3 4 5)})) ; test-binding-map-6 (assert (= (binding-map '(?x 2 . ?y) '(1 9 3 4 5)) nil)) ;; ----------------------------------------------------------------------------- ;; Occurs Check (println "occurs check") (assert (= (run* [q] (m/== q [q])) ())) ;; ----------------------------------------------------------------------------- ;; Unifications that should fail (println "unifications that sould fail") (assert (= (run* [p] (fresh [a b] (m/== b ()) (m/== '(0 1) (lcons a b)) (m/== p [a b]))) ())) (assert (= (run* [p] (fresh [a b] (m/== b '(1)) (m/== '(0) (lcons a b)) (m/== p [a b]))) ())) (assert (= (run* [p] (fresh [a b c d] (m/== () b) (m/== '(1) d) (m/== (lcons a b) (lcons c d)) (m/== p [a b c d]))) ())) ;; ----------------------------------------------------------------------------- ;; Pattern matching other data structures (println "pattern matching") (defne match-map [m o] ([{:foo {:bar o}} _])) (assert (= (run* [q] (match-map {:foo {:bar 1}} q)) '(1))) (defne match-set [s o] ([#{:cat :bird :dog} _])) (assert (= (run* [q] (match-set #{:cat :bird :dog} q)) '(_.0))) ;; ----------------------------------------------------------------------------- ;; Partial maps (println "partial maps") (assert (= '({:a 1}) (run* [q] (fresh [pm x] (== pm (partial-map {:a x})) (== pm {:a 1 :b 2}) (== pm q))))) (assert (= '(1) (run* [q] (fresh [pm x] (== pm (partial-map {:a x})) (== pm {:a 1 :b 2}) (== x q))))) (comment ;; FIXME: for some reason set #{:cat :bird} works on match-set call - David ) ;; ============================================================================= ;; zebrao (println "zebrao") (defne righto [x y l] ([_ _ [x y . r]]) ([_ _ [_ . r]] (righto x y r))) (defn nexto [x y l] (conde [(righto x y l)] [(righto y x l)])) (defn zebrao [hs] (mu/symbol-macrolet [_ (lvar)] (all (m/== (list _ _ (list _ _ 'milk _ _) _ _) hs) (firsto hs (list 'norwegian _ _ _ _)) (nexto (list 'norwegian _ _ _ _) (list _ _ _ _ 'blue) hs) (righto (list _ _ _ _ 'ivory) (list _ _ _ _ 'green) hs) (membero (list 'englishman _ _ _ 'red) hs) (membero (list _ 'kools _ _ 'yellow) hs) (membero (list 'spaniard _ _ 'dog _) hs) (membero (list _ _ 'coffee _ 'green) hs) (membero (list 'ukrainian _ 'tea _ _) hs) (membero (list _ 'lucky-strikes 'oj _ _) hs) (membero (list 'japanese 'parliaments _ _ _) hs) (membero (list _ 'oldgolds _ 'snails _) hs) (nexto (list _ _ _ 'horse _) (list _ 'kools _ _ _) hs) (nexto (list _ _ _ 'fox _) (list _ 'chesterfields _ _ _) hs)))) (defn ^:export run_zebra [] (binding [*occurs-check* false] (doall (run 1 [q] (zebrao q))))) (println (pr-str (run 1 [q] (zebrao q)))) (binding [*occurs-check* false] (time (dotimes [_ 1000] (run 1 [q] (zebrao q))))) (println (pr-str (run 10 [q] (nexto 'dog 'cat q)))) ;; ============================================================================= ;; matche (defn map-geto [m k v] (matche [m] ([[[k v] . _]]) ([[_ . tail]] (map-geto tail k v)))) (assert (= (run* [q] (map-geto (seq {:title "Blub"}) :title q)) '("Blub"))) (println "ok")
[ { "context": " {:Name \"charlie\" :DataType \"STRING\"}])]\n (h/assert-in", "end": 1472, "score": 0.5685949325561523, "start": 1468, "tag": "NAME", "value": "char" } ]
umm-spec-lib/test/cmr/umm_spec/test/validation/additional_attribute.clj
daniel-zamora/Common-Metadata-Repository
294
(ns cmr.umm-spec.test.validation.additional-attribute "This has tests for UMM validations." (:require [clojure.test :refer :all] [cmr.umm-spec.validation.umm-spec-validation-core :as v] [cmr.umm-spec.models.umm-common-models :as c] [cmr.umm-spec.models.umm-collection-models :as coll] [cmr.umm-spec.test.validation.umm-spec-validation-test-helpers :as h] [cmr.umm-spec.additional-attribute :as aa] [cmr.common.services.errors :as e])) (defn- coll-with-add-attribs [attributes] (aa/add-parsed-values (coll/map->UMM-C {:AdditionalAttributes (map c/map->AdditionalAttributeType attributes)}))) (deftest collection-additional-attributes-validation (testing "additional attributes names" (testing "valid additional attributes names" (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType "STRING"} {:Name "bar" :DataType "STRING"}]))) (testing "invalid additional attributes names" (testing "duplicate names" (let [coll (coll-with-add-attribs [{:Name "foo" :DataType "STRING"} {:Name "foo" :DataType "STRING"} {:Name "bar" :DataType "STRING"} {:Name "bar" :DataType "STRING"} {:Name "charlie" :DataType "STRING"}])] (h/assert-invalid coll [:AdditionalAttributes] ["Additional Attributes must be unique. This contains duplicates named [foo, bar]."]))))) (testing "additional attributes data type" (testing "valid data types" (are [data-type] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type}])) "STRING" "FLOAT" "INT" "BOOLEAN" "DATE" "TIME" "DATETIME" "DATE_STRING" "TIME_STRING" "DATETIME_STRING")) (testing "invalid data type" (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType "F"}]) [:AdditionalAttributes 0 :DataType] ["Additional Attribute Data Type [F] is not a valid data type."]))) (testing "additional attributes values match data type" (testing "valid values" (are [data-type value] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :Value value}])) "STRING" "string value" "FLOAT" "1.0" "FLOAT" "1" "INT" "1" "BOOLEAN" "true" "DATE" "1986-10-14" "TIME" "04:03:27.123Z" "DATETIME" "1986-10-14T04:03:27.0Z" "DATE_STRING" "1986-10-14" "TIME_STRING" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "STRING" nil "FLOAT" nil "INT" nil "BOOLEAN" nil "DATE" nil "TIME" nil "DATETIME" nil "DATE_STRING" nil "TIME_STRING" nil "DATETIME_STRING" nil) (are [data-type value] (and (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParamteterRangeBegin value}])) (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeEnd value}]))) "FLOAT" "1.0" "INT" "1" "DATE" "1986-10-14" "TIME" "04:03:27.123Z" "DATETIME" "1986-10-14T04:03:27.0Z" "DATE_STRING" "1986-10-14" "TIME_STRING" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "STRING" nil "FLOAT" nil "INT" nil "BOOLEAN" nil "DATE" nil "TIME" nil "DATETIME" nil "DATE_STRING" nil "TIME_STRING" nil "DATETIME_STRING" nil)) (testing "invalid values" (are [data-type value field errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type field value}]) [:AdditionalAttributes 0] errors) "BOOLEAN" "true" :ParameterRangeBegin ["Parameter Range Begin is not allowed for type [BOOLEAN]"] "FLOAT" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [INT]."] "DATE" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [DATE]."] "TIME" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :ParameterRangeBegin ["Parameter Range Begin [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01] is not a valid value for type [TIME]."] "BOOLEAN" "true" :ParameterRangeEnd ["Parameter Range End is not allowed for type [BOOLEAN]"] "FLOAT" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [INT]."] "DATE" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [DATE]."] "TIME" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :ParameterRangeEnd ["Parameter Range End [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :ParameterRangeEnd ["Parameter Range End [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :ParameterRangeEnd ["Parameter Range End [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :ParameterRangeEnd ["Parameter Range End [2002-01-01] is not a valid value for type [TIME]."] "BOOLEAN" "bar" :Value ["Value [bar] is not a valid value for type [BOOLEAN]."] "FLOAT" "bar" :Value ["Value [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :Value ["Value [bar] is not a valid value for type [INT]."] "DATE" "bar" :Value ["Value [bar] is not a valid value for type [DATE]."] "TIME" "bar" :Value ["Value [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :Value ["Value [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :Value ["Value [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :Value ["Value [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :Value ["Value [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :Value ["Value [2002-01-01] is not a valid value for type [TIME]."])) (testing "multiple invalid values" (h/assert-multiple-invalid (coll-with-add-attribs [{:Name "foo" :DataType "FLOAT" :Value "str"} {:Name "bar" :DataType "FLOAT" :Value "1.0"} {:Name "baz" :DataType "INT" :Value "1.0"}]) [{:path [:AdditionalAttributes 0] :errors ["Value [str] is not a valid value for type [FLOAT]."]} {:path [:AdditionalAttributes 2] :errors ["Value [1.0] is not a valid value for type [INT]."]}])) (testing "additional attributes range values" (testing "valid range values" (are [data-type begin end value] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}])) "STRING" nil nil "string value" "FLOAT" "1.0" "3.0" "2.0" "INT" "1" "3" "2" "INT" "1" "1" "1" "BOOLEAN" nil nil "true" "DATE" "1986-10-14" "1986-10-16" "1986-10-15" "TIME" "04:03:27.123Z" "04:03:29Z" "04:03:28Z" "DATETIME" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:29Z" "1986-10-14T04:03:28Z" "DATE_STRING" "1986-10-14" "1986-10-14" "1986-10-14" "TIME_STRING" "04:03:27.123" "04:03:27.123" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:27.0Z")) (testing "invalid range values" (testing "parameter range begin is greater than parameter range end" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "3.0" "1.0" "2.0" ["Parameter Range Begin [3.0] cannot be greater than Parameter Range End [1.0]."] "INT" "3" "1" "2" ["Parameter Range Begin [3] cannot be greater than Parameter Range End [1]."] "DATE" "1986-10-16" "1986-10-14" "1986-10-15" ["Parameter Range Begin [1986-10-16] cannot be greater than Parameter Range End [1986-10-14]."] "TIME" "04:03:29Z" "04:03:27Z" "04:03:28Z" ["Parameter Range Begin [04:03:29Z] cannot be greater than Parameter Range End [04:03:27Z]."] "DATETIME" "1986-10-14T04:03:29.0Z" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:28Z" ["Parameter Range Begin [1986-10-14T04:03:29.0Z] cannot be greater than Parameter Range End [1986-10-14T04:03:27.0Z]."])) (testing "value is less than parameter range begin" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "2.0" "3.0" "1.0" ["Value [1.0] cannot be less than Parameter Range Begin [2.0]."] "INT" "2" "3" "1" ["Value [1] cannot be less than Parameter Range Begin [2]."] "DATE" "1986-10-15" "1986-10-16" "1986-10-14" ["Value [1986-10-14] cannot be less than Parameter Range Begin [1986-10-15]."] "TIME" "04:03:28Z" "04:03:29Z" "04:03:27Z" ["Value [04:03:27Z] cannot be less than Parameter Range Begin [04:03:28Z]."] "DATETIME" "1986-10-14T04:03:28Z" "1986-10-14T04:03:29Z" "1986-10-14T04:03:27Z" ["Value [1986-10-14T04:03:27Z] cannot be less than Parameter Range Begin [1986-10-14T04:03:28Z]."])) (testing "value is greater than parameter range end" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "1.0" "2.0" "3.0" ["Value [3.0] cannot be greater than Parameter Range End [2.0]."] "INT" "1" "2" "3" ["Value [3] cannot be greater than Parameter Range End [2]."] "DATE" "1986-10-14" "1986-10-15" "1986-10-16" ["Value [1986-10-16] cannot be greater than Parameter Range End [1986-10-15]."] "TIME" "04:03:27Z" "04:03:28Z" "04:03:29Z" ["Value [04:03:29Z] cannot be greater than Parameter Range End [04:03:28Z]."] "DATETIME" "1986-10-14T04:03:27Z" "1986-10-14T04:03:28Z" "1986-10-14T04:03:29Z" ["Value [1986-10-14T04:03:29Z] cannot be greater than Parameter Range End [1986-10-14T04:03:28Z]."]))))))
91603
(ns cmr.umm-spec.test.validation.additional-attribute "This has tests for UMM validations." (:require [clojure.test :refer :all] [cmr.umm-spec.validation.umm-spec-validation-core :as v] [cmr.umm-spec.models.umm-common-models :as c] [cmr.umm-spec.models.umm-collection-models :as coll] [cmr.umm-spec.test.validation.umm-spec-validation-test-helpers :as h] [cmr.umm-spec.additional-attribute :as aa] [cmr.common.services.errors :as e])) (defn- coll-with-add-attribs [attributes] (aa/add-parsed-values (coll/map->UMM-C {:AdditionalAttributes (map c/map->AdditionalAttributeType attributes)}))) (deftest collection-additional-attributes-validation (testing "additional attributes names" (testing "valid additional attributes names" (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType "STRING"} {:Name "bar" :DataType "STRING"}]))) (testing "invalid additional attributes names" (testing "duplicate names" (let [coll (coll-with-add-attribs [{:Name "foo" :DataType "STRING"} {:Name "foo" :DataType "STRING"} {:Name "bar" :DataType "STRING"} {:Name "bar" :DataType "STRING"} {:Name "<NAME>lie" :DataType "STRING"}])] (h/assert-invalid coll [:AdditionalAttributes] ["Additional Attributes must be unique. This contains duplicates named [foo, bar]."]))))) (testing "additional attributes data type" (testing "valid data types" (are [data-type] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type}])) "STRING" "FLOAT" "INT" "BOOLEAN" "DATE" "TIME" "DATETIME" "DATE_STRING" "TIME_STRING" "DATETIME_STRING")) (testing "invalid data type" (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType "F"}]) [:AdditionalAttributes 0 :DataType] ["Additional Attribute Data Type [F] is not a valid data type."]))) (testing "additional attributes values match data type" (testing "valid values" (are [data-type value] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :Value value}])) "STRING" "string value" "FLOAT" "1.0" "FLOAT" "1" "INT" "1" "BOOLEAN" "true" "DATE" "1986-10-14" "TIME" "04:03:27.123Z" "DATETIME" "1986-10-14T04:03:27.0Z" "DATE_STRING" "1986-10-14" "TIME_STRING" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "STRING" nil "FLOAT" nil "INT" nil "BOOLEAN" nil "DATE" nil "TIME" nil "DATETIME" nil "DATE_STRING" nil "TIME_STRING" nil "DATETIME_STRING" nil) (are [data-type value] (and (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParamteterRangeBegin value}])) (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeEnd value}]))) "FLOAT" "1.0" "INT" "1" "DATE" "1986-10-14" "TIME" "04:03:27.123Z" "DATETIME" "1986-10-14T04:03:27.0Z" "DATE_STRING" "1986-10-14" "TIME_STRING" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "STRING" nil "FLOAT" nil "INT" nil "BOOLEAN" nil "DATE" nil "TIME" nil "DATETIME" nil "DATE_STRING" nil "TIME_STRING" nil "DATETIME_STRING" nil)) (testing "invalid values" (are [data-type value field errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type field value}]) [:AdditionalAttributes 0] errors) "BOOLEAN" "true" :ParameterRangeBegin ["Parameter Range Begin is not allowed for type [BOOLEAN]"] "FLOAT" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [INT]."] "DATE" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [DATE]."] "TIME" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :ParameterRangeBegin ["Parameter Range Begin [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01] is not a valid value for type [TIME]."] "BOOLEAN" "true" :ParameterRangeEnd ["Parameter Range End is not allowed for type [BOOLEAN]"] "FLOAT" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [INT]."] "DATE" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [DATE]."] "TIME" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :ParameterRangeEnd ["Parameter Range End [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :ParameterRangeEnd ["Parameter Range End [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :ParameterRangeEnd ["Parameter Range End [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :ParameterRangeEnd ["Parameter Range End [2002-01-01] is not a valid value for type [TIME]."] "BOOLEAN" "bar" :Value ["Value [bar] is not a valid value for type [BOOLEAN]."] "FLOAT" "bar" :Value ["Value [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :Value ["Value [bar] is not a valid value for type [INT]."] "DATE" "bar" :Value ["Value [bar] is not a valid value for type [DATE]."] "TIME" "bar" :Value ["Value [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :Value ["Value [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :Value ["Value [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :Value ["Value [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :Value ["Value [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :Value ["Value [2002-01-01] is not a valid value for type [TIME]."])) (testing "multiple invalid values" (h/assert-multiple-invalid (coll-with-add-attribs [{:Name "foo" :DataType "FLOAT" :Value "str"} {:Name "bar" :DataType "FLOAT" :Value "1.0"} {:Name "baz" :DataType "INT" :Value "1.0"}]) [{:path [:AdditionalAttributes 0] :errors ["Value [str] is not a valid value for type [FLOAT]."]} {:path [:AdditionalAttributes 2] :errors ["Value [1.0] is not a valid value for type [INT]."]}])) (testing "additional attributes range values" (testing "valid range values" (are [data-type begin end value] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}])) "STRING" nil nil "string value" "FLOAT" "1.0" "3.0" "2.0" "INT" "1" "3" "2" "INT" "1" "1" "1" "BOOLEAN" nil nil "true" "DATE" "1986-10-14" "1986-10-16" "1986-10-15" "TIME" "04:03:27.123Z" "04:03:29Z" "04:03:28Z" "DATETIME" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:29Z" "1986-10-14T04:03:28Z" "DATE_STRING" "1986-10-14" "1986-10-14" "1986-10-14" "TIME_STRING" "04:03:27.123" "04:03:27.123" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:27.0Z")) (testing "invalid range values" (testing "parameter range begin is greater than parameter range end" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "3.0" "1.0" "2.0" ["Parameter Range Begin [3.0] cannot be greater than Parameter Range End [1.0]."] "INT" "3" "1" "2" ["Parameter Range Begin [3] cannot be greater than Parameter Range End [1]."] "DATE" "1986-10-16" "1986-10-14" "1986-10-15" ["Parameter Range Begin [1986-10-16] cannot be greater than Parameter Range End [1986-10-14]."] "TIME" "04:03:29Z" "04:03:27Z" "04:03:28Z" ["Parameter Range Begin [04:03:29Z] cannot be greater than Parameter Range End [04:03:27Z]."] "DATETIME" "1986-10-14T04:03:29.0Z" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:28Z" ["Parameter Range Begin [1986-10-14T04:03:29.0Z] cannot be greater than Parameter Range End [1986-10-14T04:03:27.0Z]."])) (testing "value is less than parameter range begin" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "2.0" "3.0" "1.0" ["Value [1.0] cannot be less than Parameter Range Begin [2.0]."] "INT" "2" "3" "1" ["Value [1] cannot be less than Parameter Range Begin [2]."] "DATE" "1986-10-15" "1986-10-16" "1986-10-14" ["Value [1986-10-14] cannot be less than Parameter Range Begin [1986-10-15]."] "TIME" "04:03:28Z" "04:03:29Z" "04:03:27Z" ["Value [04:03:27Z] cannot be less than Parameter Range Begin [04:03:28Z]."] "DATETIME" "1986-10-14T04:03:28Z" "1986-10-14T04:03:29Z" "1986-10-14T04:03:27Z" ["Value [1986-10-14T04:03:27Z] cannot be less than Parameter Range Begin [1986-10-14T04:03:28Z]."])) (testing "value is greater than parameter range end" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "1.0" "2.0" "3.0" ["Value [3.0] cannot be greater than Parameter Range End [2.0]."] "INT" "1" "2" "3" ["Value [3] cannot be greater than Parameter Range End [2]."] "DATE" "1986-10-14" "1986-10-15" "1986-10-16" ["Value [1986-10-16] cannot be greater than Parameter Range End [1986-10-15]."] "TIME" "04:03:27Z" "04:03:28Z" "04:03:29Z" ["Value [04:03:29Z] cannot be greater than Parameter Range End [04:03:28Z]."] "DATETIME" "1986-10-14T04:03:27Z" "1986-10-14T04:03:28Z" "1986-10-14T04:03:29Z" ["Value [1986-10-14T04:03:29Z] cannot be greater than Parameter Range End [1986-10-14T04:03:28Z]."]))))))
true
(ns cmr.umm-spec.test.validation.additional-attribute "This has tests for UMM validations." (:require [clojure.test :refer :all] [cmr.umm-spec.validation.umm-spec-validation-core :as v] [cmr.umm-spec.models.umm-common-models :as c] [cmr.umm-spec.models.umm-collection-models :as coll] [cmr.umm-spec.test.validation.umm-spec-validation-test-helpers :as h] [cmr.umm-spec.additional-attribute :as aa] [cmr.common.services.errors :as e])) (defn- coll-with-add-attribs [attributes] (aa/add-parsed-values (coll/map->UMM-C {:AdditionalAttributes (map c/map->AdditionalAttributeType attributes)}))) (deftest collection-additional-attributes-validation (testing "additional attributes names" (testing "valid additional attributes names" (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType "STRING"} {:Name "bar" :DataType "STRING"}]))) (testing "invalid additional attributes names" (testing "duplicate names" (let [coll (coll-with-add-attribs [{:Name "foo" :DataType "STRING"} {:Name "foo" :DataType "STRING"} {:Name "bar" :DataType "STRING"} {:Name "bar" :DataType "STRING"} {:Name "PI:NAME:<NAME>END_PIlie" :DataType "STRING"}])] (h/assert-invalid coll [:AdditionalAttributes] ["Additional Attributes must be unique. This contains duplicates named [foo, bar]."]))))) (testing "additional attributes data type" (testing "valid data types" (are [data-type] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type}])) "STRING" "FLOAT" "INT" "BOOLEAN" "DATE" "TIME" "DATETIME" "DATE_STRING" "TIME_STRING" "DATETIME_STRING")) (testing "invalid data type" (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType "F"}]) [:AdditionalAttributes 0 :DataType] ["Additional Attribute Data Type [F] is not a valid data type."]))) (testing "additional attributes values match data type" (testing "valid values" (are [data-type value] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :Value value}])) "STRING" "string value" "FLOAT" "1.0" "FLOAT" "1" "INT" "1" "BOOLEAN" "true" "DATE" "1986-10-14" "TIME" "04:03:27.123Z" "DATETIME" "1986-10-14T04:03:27.0Z" "DATE_STRING" "1986-10-14" "TIME_STRING" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "STRING" nil "FLOAT" nil "INT" nil "BOOLEAN" nil "DATE" nil "TIME" nil "DATETIME" nil "DATE_STRING" nil "TIME_STRING" nil "DATETIME_STRING" nil) (are [data-type value] (and (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParamteterRangeBegin value}])) (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeEnd value}]))) "FLOAT" "1.0" "INT" "1" "DATE" "1986-10-14" "TIME" "04:03:27.123Z" "DATETIME" "1986-10-14T04:03:27.0Z" "DATE_STRING" "1986-10-14" "TIME_STRING" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "STRING" nil "FLOAT" nil "INT" nil "BOOLEAN" nil "DATE" nil "TIME" nil "DATETIME" nil "DATE_STRING" nil "TIME_STRING" nil "DATETIME_STRING" nil)) (testing "invalid values" (are [data-type value field errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type field value}]) [:AdditionalAttributes 0] errors) "BOOLEAN" "true" :ParameterRangeBegin ["Parameter Range Begin is not allowed for type [BOOLEAN]"] "FLOAT" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [INT]."] "DATE" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [DATE]."] "TIME" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :ParameterRangeBegin ["Parameter Range Begin [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :ParameterRangeBegin ["Parameter Range Begin [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :ParameterRangeBegin ["Parameter Range Begin [2002-01-01] is not a valid value for type [TIME]."] "BOOLEAN" "true" :ParameterRangeEnd ["Parameter Range End is not allowed for type [BOOLEAN]"] "FLOAT" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [INT]."] "DATE" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [DATE]."] "TIME" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :ParameterRangeEnd ["Parameter Range End [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :ParameterRangeEnd ["Parameter Range End [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :ParameterRangeEnd ["Parameter Range End [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :ParameterRangeEnd ["Parameter Range End [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :ParameterRangeEnd ["Parameter Range End [2002-01-01] is not a valid value for type [TIME]."] "BOOLEAN" "bar" :Value ["Value [bar] is not a valid value for type [BOOLEAN]."] "FLOAT" "bar" :Value ["Value [bar] is not a valid value for type [FLOAT]."] "INT" "bar" :Value ["Value [bar] is not a valid value for type [INT]."] "DATE" "bar" :Value ["Value [bar] is not a valid value for type [DATE]."] "TIME" "bar" :Value ["Value [bar] is not a valid value for type [TIME]."] "DATETIME" "bar" :Value ["Value [bar] is not a valid value for type [DATETIME]."] "DATE" "2002-01-01T00:00:00.000Z" :Value ["Value [2002-01-01T00:00:00.000Z] is not a valid value for type [DATE]."] "TIME" "2002-01-01T00:00:00.000Z" :Value ["Value [2002-01-01T00:00:00.000Z] is not a valid value for type [TIME]."] "DATE" "00:03:01.000" :Value ["Value [00:03:01.000] is not a valid value for type [DATE]."] "TIME" "2002-01-01" :Value ["Value [2002-01-01] is not a valid value for type [TIME]."])) (testing "multiple invalid values" (h/assert-multiple-invalid (coll-with-add-attribs [{:Name "foo" :DataType "FLOAT" :Value "str"} {:Name "bar" :DataType "FLOAT" :Value "1.0"} {:Name "baz" :DataType "INT" :Value "1.0"}]) [{:path [:AdditionalAttributes 0] :errors ["Value [str] is not a valid value for type [FLOAT]."]} {:path [:AdditionalAttributes 2] :errors ["Value [1.0] is not a valid value for type [INT]."]}])) (testing "additional attributes range values" (testing "valid range values" (are [data-type begin end value] (h/assert-valid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}])) "STRING" nil nil "string value" "FLOAT" "1.0" "3.0" "2.0" "INT" "1" "3" "2" "INT" "1" "1" "1" "BOOLEAN" nil nil "true" "DATE" "1986-10-14" "1986-10-16" "1986-10-15" "TIME" "04:03:27.123Z" "04:03:29Z" "04:03:28Z" "DATETIME" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:29Z" "1986-10-14T04:03:28Z" "DATE_STRING" "1986-10-14" "1986-10-14" "1986-10-14" "TIME_STRING" "04:03:27.123" "04:03:27.123" "04:03:27.123" "DATETIME_STRING" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:27.0Z")) (testing "invalid range values" (testing "parameter range begin is greater than parameter range end" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "3.0" "1.0" "2.0" ["Parameter Range Begin [3.0] cannot be greater than Parameter Range End [1.0]."] "INT" "3" "1" "2" ["Parameter Range Begin [3] cannot be greater than Parameter Range End [1]."] "DATE" "1986-10-16" "1986-10-14" "1986-10-15" ["Parameter Range Begin [1986-10-16] cannot be greater than Parameter Range End [1986-10-14]."] "TIME" "04:03:29Z" "04:03:27Z" "04:03:28Z" ["Parameter Range Begin [04:03:29Z] cannot be greater than Parameter Range End [04:03:27Z]."] "DATETIME" "1986-10-14T04:03:29.0Z" "1986-10-14T04:03:27.0Z" "1986-10-14T04:03:28Z" ["Parameter Range Begin [1986-10-14T04:03:29.0Z] cannot be greater than Parameter Range End [1986-10-14T04:03:27.0Z]."])) (testing "value is less than parameter range begin" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "2.0" "3.0" "1.0" ["Value [1.0] cannot be less than Parameter Range Begin [2.0]."] "INT" "2" "3" "1" ["Value [1] cannot be less than Parameter Range Begin [2]."] "DATE" "1986-10-15" "1986-10-16" "1986-10-14" ["Value [1986-10-14] cannot be less than Parameter Range Begin [1986-10-15]."] "TIME" "04:03:28Z" "04:03:29Z" "04:03:27Z" ["Value [04:03:27Z] cannot be less than Parameter Range Begin [04:03:28Z]."] "DATETIME" "1986-10-14T04:03:28Z" "1986-10-14T04:03:29Z" "1986-10-14T04:03:27Z" ["Value [1986-10-14T04:03:27Z] cannot be less than Parameter Range Begin [1986-10-14T04:03:28Z]."])) (testing "value is greater than parameter range end" (are [data-type begin end value errors] (h/assert-invalid (coll-with-add-attribs [{:Name "foo" :DataType data-type :ParameterRangeBegin begin :ParameterRangeEnd end :Value value}]) [:AdditionalAttributes 0] errors) "FLOAT" "1.0" "2.0" "3.0" ["Value [3.0] cannot be greater than Parameter Range End [2.0]."] "INT" "1" "2" "3" ["Value [3] cannot be greater than Parameter Range End [2]."] "DATE" "1986-10-14" "1986-10-15" "1986-10-16" ["Value [1986-10-16] cannot be greater than Parameter Range End [1986-10-15]."] "TIME" "04:03:27Z" "04:03:28Z" "04:03:29Z" ["Value [04:03:29Z] cannot be greater than Parameter Range End [04:03:28Z]."] "DATETIME" "1986-10-14T04:03:27Z" "1986-10-14T04:03:28Z" "1986-10-14T04:03:29Z" ["Value [1986-10-14T04:03:29Z] cannot be greater than Parameter Range End [1986-10-14T04:03:28Z]."]))))))
[ { "context": "ogramming\n;;hosted within the java universe.\n;;\n;;christian.meichsner@informatik.tu-chemnitz.de\n(ns prologtocorelogic.core\n (:refer-clojure :exc", "end": 298, "score": 0.9999224543571472, "start": 253, "tag": "EMAIL", "value": "christian.meichsner@informatik.tu-chemnitz.de" }, { "context": "))\n\n\n;;Relational Programming in core.logic\n;;\n\n;;mann(adam).\n;;mann(tobias).\n;;(frank).\n;; frau(eva)", "end": 534, "score": 0.6567367315292358, "start": 530, "tag": "NAME", "value": "mann" }, { "context": ";;Relational Programming in core.logic\n;;\n\n;;mann(adam).\n;;mann(tobias).\n;;(frank).\n;; frau(eva).\n;; ", "end": 539, "score": 0.9771654605865479, "start": 535, "tag": "NAME", "value": "adam" }, { "context": "nal Programming in core.logic\n;;\n\n;;mann(adam).\n;;mann(tobias).\n;;(frank).\n;; frau(eva).\n;; frau(d", "end": 548, "score": 0.6906644701957703, "start": 544, "tag": "NAME", "value": "mann" }, { "context": "rogramming in core.logic\n;;\n\n;;mann(adam).\n;;mann(tobias).\n;;(frank).\n;; frau(eva).\n;; frau(daniela)", "end": 555, "score": 0.978731095790863, "start": 549, "tag": "NAME", "value": "tobias" }, { "context": "n core.logic\n;;\n\n;;mann(adam).\n;;mann(tobias).\n;;(frank).\n;; frau(eva).\n;; frau(daniela).\n;; fra", "end": 566, "score": 0.9934781789779663, "start": 561, "tag": "NAME", "value": "frank" }, { "context": " frau(daniela).\n;; frau(ulrike).\n;; vater(adam,tobias).\n;; vater(tobias,frank).\n;; vater(t", "end": 643, "score": 0.9819980263710022, "start": 639, "tag": "NAME", "value": "adam" }, { "context": "au(daniela).\n;; frau(ulrike).\n;; vater(adam,tobias).\n;; vater(tobias,frank).\n;; vater(tobias,u", "end": 650, "score": 0.9837626218795776, "start": 644, "tag": "NAME", "value": "tobias" }, { "context": "au(ulrike).\n;; vater(adam,tobias).\n;; vater(tobias,frank).\n;; vater(tobias,ulrike).\n;; mutter(", "end": 671, "score": 0.969617486000061, "start": 665, "tag": "NAME", "value": "tobias" }, { "context": "ke).\n;; vater(adam,tobias).\n;; vater(tobias,frank).\n;; vater(tobias,ulrike).\n;; mutter(eva,to", "end": 677, "score": 0.9980840682983398, "start": 672, "tag": "NAME", "value": "frank" }, { "context": ",frank).\n;; vater(tobias,ulrike).\n;; mutter(eva,tobias).\n;; mutter(daniela,frank).\n;; mutte", "end": 724, "score": 0.6981383562088013, "start": 721, "tag": "NAME", "value": "eva" }, { "context": "nk).\n;; vater(tobias,ulrike).\n;; mutter(eva,tobias).\n;; mutter(daniela,frank).\n;; mutter(danie", "end": 731, "score": 0.8960554599761963, "start": 725, "tag": "NAME", "value": "tobias" }, { "context": "s,ulrike).\n;; mutter(eva,tobias).\n;; mutter(daniela,frank).\n;; mutter(daniela,ulrike).\n;;\n(facts/d", "end": 754, "score": 0.8246685266494751, "start": 747, "tag": "NAME", "value": "daniela" }, { "context": ").\n;; mutter(eva,tobias).\n;; mutter(daniela,frank).\n;; mutter(daniela,ulrike).\n;;\n(facts/db-rel ", "end": 760, "score": 0.9879944920539856, "start": 755, "tag": "NAME", "value": "frank" }, { "context": "mutter m k)\n\n(def factbase\n (facts/db\n [mann :adam]\n [mann :tobias]\n [mann :frank]\n [frau :", "end": 933, "score": 0.9799529314041138, "start": 929, "tag": "NAME", "value": "adam" }, { "context": "\n\n(def factbase\n (facts/db\n [mann :adam]\n [mann :tobias]\n [mann :frank]\n [frau :eva]\n [f", "end": 944, "score": 0.5441692471504211, "start": 940, "tag": "NAME", "value": "mann" }, { "context": " factbase\n (facts/db\n [mann :adam]\n [mann :tobias]\n [mann :frank]\n [frau :eva]\n [frau :dan", "end": 952, "score": 0.8582162261009216, "start": 946, "tag": "NAME", "value": "tobias" }, { "context": "db\n [mann :adam]\n [mann :tobias]\n [mann :frank]\n [frau :eva]\n [frau :daniela]\n [frau :u", "end": 970, "score": 0.9816649556159973, "start": 965, "tag": "NAME", "value": "frank" }, { "context": " [frau :daniela]\n [frau :ulrike]\n [vater :adam :tobias]\n [vater :tobias :frank]\n [vater :t", "end": 1043, "score": 0.924372673034668, "start": 1039, "tag": "NAME", "value": "adam" }, { "context": "au :daniela]\n [frau :ulrike]\n [vater :adam :tobias]\n [vater :tobias :frank]\n [vater :tobias :u", "end": 1051, "score": 0.9027525186538696, "start": 1045, "tag": "NAME", "value": "tobias" }, { "context": "ke]\n [vater :adam :tobias]\n [vater :tobias :frank]\n [vater :tobias :ulrike]\n [mutter :eva :to", "end": 1078, "score": 0.9641271829605103, "start": 1073, "tag": "NAME", "value": "frank" }, { "context": "s :ulrike]\n [mutter :eva :tobias]\n [mutter :daniela :frank]\n [mutter :daniela :ulrike]))\n\n(facts/", "end": 1153, "score": 0.5449445247650146, "start": 1147, "tag": "NAME", "value": "daniel" }, { "context": "]\n [mutter :eva :tobias]\n [mutter :daniela :frank]\n [mutter :daniela :ulrike]))\n\n(facts/with-db\n", "end": 1161, "score": 0.9484745264053345, "start": 1156, "tag": "NAME", "value": "frank" }, { "context": "cts/with-db\n factbase\n (run* [q]\n (mann :tobias)\n (== q true)))\n\n(facts/with-db\n factbase", "end": 1255, "score": 0.625176191329956, "start": 1249, "tag": "NAME", "value": "tobias" } ]
prolog-to-corelogic/src/prologtocorelogic/core.clj
gixxi/talks-and-slides
0
;;Prolog to clojure's core.logic ;;Prolog is the topdog in terms of logical programming ;;while core.logic is prolog-like programming within the ;;lisp-implementation clojure. clojure is a functional programming ;;hosted within the java universe. ;; ;;christian.meichsner@informatik.tu-chemnitz.de (ns prologtocorelogic.core (:refer-clojure :exclude [==]) (:use [clojure.core.logic]) (:require [clojure.core.logic.pldb :as facts]) (:require [clojure.core.logic.fd :as fd])) ;;Relational Programming in core.logic ;; ;;mann(adam). ;;mann(tobias). ;;(frank). ;; frau(eva). ;; frau(daniela). ;; frau(ulrike). ;; vater(adam,tobias). ;; vater(tobias,frank). ;; vater(tobias,ulrike). ;; mutter(eva,tobias). ;; mutter(daniela,frank). ;; mutter(daniela,ulrike). ;; (facts/db-rel mann n) (facts/db-rel frau n) (facts/db-rel vater v k) (facts/db-rel mutter m k) (def factbase (facts/db [mann :adam] [mann :tobias] [mann :frank] [frau :eva] [frau :daniela] [frau :ulrike] [vater :adam :tobias] [vater :tobias :frank] [vater :tobias :ulrike] [mutter :eva :tobias] [mutter :daniela :frank] [mutter :daniela :ulrike])) (facts/with-db factbase (run* [q] (mann :tobias) (== q true))) (facts/with-db factbase (run* [q] (mann :heinrich) (== q true))) (facts/with-db factbase (run* [q] (frau q))) (facts/with-db factbase (run* [q] (fresh [x y z] (vater x y) (vater y z) (== q [x z]))))
21235
;;Prolog to clojure's core.logic ;;Prolog is the topdog in terms of logical programming ;;while core.logic is prolog-like programming within the ;;lisp-implementation clojure. clojure is a functional programming ;;hosted within the java universe. ;; ;;<EMAIL> (ns prologtocorelogic.core (:refer-clojure :exclude [==]) (:use [clojure.core.logic]) (:require [clojure.core.logic.pldb :as facts]) (:require [clojure.core.logic.fd :as fd])) ;;Relational Programming in core.logic ;; ;;<NAME>(<NAME>). ;;<NAME>(<NAME>). ;;(<NAME>). ;; frau(eva). ;; frau(daniela). ;; frau(ulrike). ;; vater(<NAME>,<NAME>). ;; vater(<NAME>,<NAME>). ;; vater(tobias,ulrike). ;; mutter(<NAME>,<NAME>). ;; mutter(<NAME>,<NAME>). ;; mutter(daniela,ulrike). ;; (facts/db-rel mann n) (facts/db-rel frau n) (facts/db-rel vater v k) (facts/db-rel mutter m k) (def factbase (facts/db [mann :<NAME>] [<NAME> :<NAME>] [mann :<NAME>] [frau :eva] [frau :daniela] [frau :ulrike] [vater :<NAME> :<NAME>] [vater :tobias :<NAME>] [vater :tobias :ulrike] [mutter :eva :tobias] [mutter :<NAME>a :<NAME>] [mutter :daniela :ulrike])) (facts/with-db factbase (run* [q] (mann :<NAME>) (== q true))) (facts/with-db factbase (run* [q] (mann :heinrich) (== q true))) (facts/with-db factbase (run* [q] (frau q))) (facts/with-db factbase (run* [q] (fresh [x y z] (vater x y) (vater y z) (== q [x z]))))
true
;;Prolog to clojure's core.logic ;;Prolog is the topdog in terms of logical programming ;;while core.logic is prolog-like programming within the ;;lisp-implementation clojure. clojure is a functional programming ;;hosted within the java universe. ;; ;;PI:EMAIL:<EMAIL>END_PI (ns prologtocorelogic.core (:refer-clojure :exclude [==]) (:use [clojure.core.logic]) (:require [clojure.core.logic.pldb :as facts]) (:require [clojure.core.logic.fd :as fd])) ;;Relational Programming in core.logic ;; ;;PI:NAME:<NAME>END_PI(PI:NAME:<NAME>END_PI). ;;PI:NAME:<NAME>END_PI(PI:NAME:<NAME>END_PI). ;;(PI:NAME:<NAME>END_PI). ;; frau(eva). ;; frau(daniela). ;; frau(ulrike). ;; vater(PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI). ;; vater(PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI). ;; vater(tobias,ulrike). ;; mutter(PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI). ;; mutter(PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI). ;; mutter(daniela,ulrike). ;; (facts/db-rel mann n) (facts/db-rel frau n) (facts/db-rel vater v k) (facts/db-rel mutter m k) (def factbase (facts/db [mann :PI:NAME:<NAME>END_PI] [PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI] [mann :PI:NAME:<NAME>END_PI] [frau :eva] [frau :daniela] [frau :ulrike] [vater :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI] [vater :tobias :PI:NAME:<NAME>END_PI] [vater :tobias :ulrike] [mutter :eva :tobias] [mutter :PI:NAME:<NAME>END_PIa :PI:NAME:<NAME>END_PI] [mutter :daniela :ulrike])) (facts/with-db factbase (run* [q] (mann :PI:NAME:<NAME>END_PI) (== q true))) (facts/with-db factbase (run* [q] (mann :heinrich) (== q true))) (facts/with-db factbase (run* [q] (frau q))) (facts/with-db factbase (run* [q] (fresh [x y z] (vater x y) (vater y z) (== q [x z]))))
[ { "context": " (atom\n {:default {:users {1 {:user_id 1 :name \"Dave\"}\n 2 {:user_id 2 :name \"Yoko", "end": 179, "score": 0.9996652007102966, "start": 175, "tag": "NAME", "value": "Dave" }, { "context": "Dave\"}\n 2 {:user_id 2 :name \"Yoko\"}\n 3 {:user_id 3 :name \"Harv", "end": 229, "score": 0.9968194365501404, "start": 225, "tag": "NAME", "value": "Yoko" }, { "context": "Yoko\"}\n 3 {:user_id 3 :name \"Harvey\"}}}\n :views {}\n ;; :send-fn ; set in core\n ", "end": 281, "score": 0.9997379183769226, "start": 275, "tag": "NAME", "value": "Harvey" } ]
src/petrol_test/server/views.clj
ddellacosta/petrol-test
1
(ns petrol-test.server.views (:require [views.core :as views] [views.protocols :refer [IView]])) (def memory-store (atom {:default {:users {1 {:user_id 1 :name "Dave"} 2 {:user_id 2 :name "Yoko"} 3 {:user_id 3 :name "Harvey"}}} :views {} ;; :send-fn ; set in core })) (defrecord MemoryView [id ks] IView (id [_] id) (data [_ namespace parameters] (println "? w " (-> [namespace] (into ks) (into parameters))) (get-in @memory-store (-> [namespace] (into ks) (into parameters)))) (relevant? [_ namespace parameters hints] (some #(and (= namespace (:namespace %)) (= ks (:hint %))) hints))) ;; Add "all users" view (swap! memory-store assoc-in [:views :users] (MemoryView. :users []))
61284
(ns petrol-test.server.views (:require [views.core :as views] [views.protocols :refer [IView]])) (def memory-store (atom {:default {:users {1 {:user_id 1 :name "<NAME>"} 2 {:user_id 2 :name "<NAME>"} 3 {:user_id 3 :name "<NAME>"}}} :views {} ;; :send-fn ; set in core })) (defrecord MemoryView [id ks] IView (id [_] id) (data [_ namespace parameters] (println "? w " (-> [namespace] (into ks) (into parameters))) (get-in @memory-store (-> [namespace] (into ks) (into parameters)))) (relevant? [_ namespace parameters hints] (some #(and (= namespace (:namespace %)) (= ks (:hint %))) hints))) ;; Add "all users" view (swap! memory-store assoc-in [:views :users] (MemoryView. :users []))
true
(ns petrol-test.server.views (:require [views.core :as views] [views.protocols :refer [IView]])) (def memory-store (atom {:default {:users {1 {:user_id 1 :name "PI:NAME:<NAME>END_PI"} 2 {:user_id 2 :name "PI:NAME:<NAME>END_PI"} 3 {:user_id 3 :name "PI:NAME:<NAME>END_PI"}}} :views {} ;; :send-fn ; set in core })) (defrecord MemoryView [id ks] IView (id [_] id) (data [_ namespace parameters] (println "? w " (-> [namespace] (into ks) (into parameters))) (get-in @memory-store (-> [namespace] (into ks) (into parameters)))) (relevant? [_ namespace parameters hints] (some #(and (= namespace (:namespace %)) (= ks (:hint %))) hints))) ;; Add "all users" view (swap! memory-store assoc-in [:views :users] (MemoryView. :users []))
[ { "context": " just an accident of history. Lisp was invented by John McCarthy,\nwho also invented the term \\\"artificial intellig", "end": 298, "score": 0.9997559189796448, "start": 285, "tag": "NAME", "value": "John McCarthy" }, { "context": " done by a small group. In The Mythical\nMan-Month, Frederick Brooks proposed that the productivity of a group of prog", "end": 10326, "score": 0.9787155985832214, "start": 10310, "tag": "NAME", "value": "Frederick Brooks" } ]
example/code.analysis/test/documentation/on_lisp/ch1_the_extensible_language.clj
willcohen/lucidity
3
(ns documentation.on-lisp.ch1-the-extensible-language (:use hara.test)) "Not long ago, if you asked what Lisp was for, many people would have answered \"for artificial intelligence.\" In fact, the association between Lisp and AI is just an accident of history. Lisp was invented by John McCarthy, who also invented the term \"artificial intelligence.\" His students and colleagues wrote their programs in Lisp, and so it began to be spoken of as an AI language. This line was taken up and repeated so often during the brief AI boom in the 1980s that it became almost an institution. Fortunately, word has begun to spread that AI is not what Lisp is all about. Recent advances in hardware and software have made Lisp commercially viable: it is now used in Gnu Emacs, the best Unix text-editor; Autocad, the industry standard desktop CAD program; and Interleaf, a leading high-end publishing program. The way Lisp is used in these programs has nothing whatever to do with AI. If Lisp is not the language of AI, what is it? Instead of judging Lisp by the company it keeps, let's look at the language itself. What can you do in Lisp that you can't do in other languages? One of the most distinctive qualities of Lisp is the way it can be tailored to suit the program being written in it. Lisp itself is a Lisp program, and Lisp programs can be expressed as lists, which are Lisp data structures. Together, these two principles mean that any user can add operators to Lisp which are indistinguishable from the ones that come built-in." [[:section {:title "Design by Evolution"}]] "Because Lisp gives you the freedom to define your own operators, you can mold it into just the language you need. If you're writing a text-editor, you can turn Lisp into a language for writing text-editors. If you're writing a CAD program, you can turn Lisp into a language for writing CAD programs. And if you're not sure yet what kind of program you're writing, it's a safe bet to write it in Lisp. Whatever kind of program yours turns out to be, Lisp will, during the writing of it, have evolved into a language for writing that kind of program. If you're not sure yet what kind of program you're writing? To some ears that sentence has an odd ring to it. It is in jarring contrast with a certain model of doing things wherein you (1) carefully plan what you're going to do, and then (2) do it. According to this model, if Lisp encourages you to start writing your program before you've decided how it should work, it merely encourages sloppy thinking. Well, it just ain't so. The plan-and-implement method may have been a good way of building dams or launching invasions, but experience has not shown it to be as good a way of writing programs. Why? Perhaps it's because computers are so exacting. Perhaps there is more variation between programs than there is between dams or invasions. Or perhaps the old methods don't work because old concepts of redundancy have no analogue in software development: if a dam contains 30% too much concrete, that's a margin for error, but if a program does 30% too much work, that is an error. It may be difficult to say why the old method fails, but that it does fail, anyone can see. When is software delivered on time? Experienced programmers know that no matter how carefully you plan a program, when you write it the plans will turn out to be imperfect in some way. Sometimes the plans will be hopelessly wrong. Yet few of the victims of the plan-and-implement method question its basic soundness. Instead they blame human failings: if only the plans had been made with more foresight, all this trouble could have been avoided. Since even the very best programmers run into problems when they turn to implementation, perhaps it's too much to hope that people will ever have that much foresight. Perhaps the plan-and-implement method could be replaced with another approach which better suits our limitations. We can approach programming in a different way, if we have the right tools. Why do we plan before implementing? The big danger in plunging right into a project is the possibility that we will paint ourselves into a corner. If we had a more flexible language, could this worry be lessened? We do, and it is. The flexibility of Lisp has spawned a whole new style of programming. In Lisp, you can do much of your planning as you write the program. Why wait for hindsight? As Montaigne found, nothing clarifies your ideas like trying to write them down. Once you're freed from the worry that you'll paint yourself into a corner, you can take full advantage of this possibility. The ability to plan programs as you write them has two momentous consequences: programs take less time to write, because when you plan and write at the same time, you have a real program to focus your attention; and they turn out better, because the final design is always a product of evolution. So long as you maintain a certain discipline while searching for your program's destiny--so long as you always rewrite mistaken parts as soon as it becomes clear that they're mistaken--the final product will be a program more elegant than if you had spent weeks planning it beforehand. Lisp's versatility makes this kind of programming a practical alternative. Indeed, the greatest danger of Lisp is that it may spoil you. Once you've used Lisp for a while, you may become so sensitive to the fit between language and application that you won't be able to go back to another language without always feeling that it doesn't give you quite the flexibility you need." [[:section {:title "Programming Bottom-Up"}]] "It's a long-standing principle of programming style that the functional elements of a program should not be too large. If some component of a program grows beyond the stage where it's readily comprehensible, it becomes a mass of complexity which conceals errors as easily as a big city conceals fugitives. Such software will be hard to read, hard to test, and hard to debug. In accordance with this principle, a large program must be divided into pieces, and the larger the program, the more it must be divided. How do you divide a program? The traditional approach is called top-down design: you say \"the purpose of the program is to do these seven things, so I divide it into seven major subroutines. The first subroutine has to do these four things, so it in turn will have four of its own subroutines,\" and so on. This process continues until the whole program has the right level of granularity--each part large enough to do something substantial, but small enough to be understood as a single unit. Experienced Lisp programmers divide up their programs differently. As well as top-down design, they follow a principle which could be called bottom-up design--changing the language to suit the problem. In Lisp, you don't just write your program down toward the language, you also build the language up toward your program. As you're writing a program you may think \"I wish Lisp had such-and-such an operator.\" So you go and write it. Afterward you realize that using the new operator would simplify the design of another part of the program, and so on. Language and program evolve together. Like the border between two warring states, the boundary between language and program is drawn and redrawn, until eventually it comes to rest along the mountains and rivers, the natural frontiers of your problem. In the end your program will look as if the language had been designed for it. And when language and program fit one another well, you end up with code which is clear, small, and efficient. It's worth emphasizing that bottom-up design doesn't mean just writing the same program in a different order. When you work bottom-up, you usually end up with a different program. Instead of a single, monolithic program, you will get a larger language with more abstract operators, and a smaller program written in it. Instead of a lintel, you'll get an arch. In typical code, once you abstract out the parts which are merely bookkeeping, what's left is much shorter; the higher you build up the language, the less distance you will have to travel from the top down to it. This brings several advantages: - By making the language do more of the work, bottom-up design yields programs which are smaller and more agile. A shorter program doesn't have to be divided into so many components, and fewer components means programs which are easier to read or modify. Fewer components also means fewer connections between components, and thus less chance for errors there. As industrial designers strive to reduce the number of moving parts in a machine, experienced Lisp programmers use bottom-up design to reduce the size and complexity of their programs. - Bottom-up design promotes code re-use. When you write two or more programs, many of the utilities you wrote for the first program will also be useful in the succeeding ones. Once you've acquired a large substrate of utilities, writing a new program can take only a fraction of the effort it would require if you had to start with raw Lisp. - Bottom-up design makes programs easier to read. An instance of this type of abstraction asks the reader to understand a general-purpose operator; an instance of functional abstraction asks the reader to understand a special-purpose subroutine.(1) - Because it causes you always to be on the lookout for patterns in your code, working bottom-up helps to clarify your ideas about the design of your program. If two distant components of a program are similar in form, you'll be led to notice the similarity and perhaps to redesign the program in a simpler way. - Bottom-up design is possible to a certain degree in languages other than Lisp. Whenever you see library functions, bottom-up design is happening. However, Lisp gives you much broader powers in this department, and augmenting the language plays a proportionately larger role in Lisp style--so much so that Lisp is not just a different language, but a whole different way of programming. It's true that this style of development is better suited to programs which can be written by small groups. However, at the same time, it extends the limits of what can be done by a small group. In The Mythical Man-Month, Frederick Brooks proposed that the productivity of a group of programmers does not grow linearly with its size. As the size of the group increases, the productivity of individual programmers goes down. The experience of Lisp programming suggests a more cheerful way to phrase this law: as the size of the group decreases, the productivity of individual programmers goes up. A small group wins, relatively speaking, simply because it's smaller. When a small group also takes advantage of the techniques that Lisp makes possible, it can win outright." [[:section {:title "Extensible Software"}]] "The Lisp style of programming is one that has grown in importance as software has grown in complexity. Sophisticated users now demand so much from software that we can't possibly anticipate all their needs. They themselves can't anticipate all their needs. But if we can't give them software which does everything they want right out of the box, we can give them software which is extensible. We transform our software from a mere program into a programming language, and advanced users can build upon it the extra features that they need. Bottom-up design leads naturally to extensible programs. The simplest bottom-up programs consist of two layers: language and program. Complex programs may be written as a series of layers, each one acting as a programming language for the one above. If this philosophy is carried all the way up to the topmost layer, that layer becomes a programming language for the user. Such a program, where extensibility permeates every level, is likely to make a much better programming language than a system which was written as a traditional black box, and then made extensible as an afterthought. X Windows and T E X are early examples of programs based on this principle. In the 1980s better hardware made possible a new generation of programs which had Lisp as their extension language. The first was Gnu Emacs, the popular Unix text-editor. Later came Autocad, the first large-scale commercial product to provide Lisp as an extension language. In 1991 Interleaf released a new version of its software that not only had Lisp as an extension language, but was largely implemented in Lisp. Lisp is an especially good language for writing extensible programs because it is itself an extensible program. If you write your Lisp programs so as to pass this extensibility on to the user, you effectively get an extension language for free. And the difference between extending a Lisp program in Lisp, and doing the same thing in a traditional language, is like the difference between meeting someone in person and conversing by letters. In a program which is made extensible simply by providing access to outside programs, the best we can hope for is two black boxes communicating with one another through some predefined channel. In Lisp, extensions can have direct access to the entire underlying program. This is not to say that you have to give users access to every part of your program--just that you now have a choice about whether to give them access or not. When this degree of access is combined with an interactive environment, you have extensibility at its best. Any program that you might use as a foundation for extensions of your own is likely to be fairly big--too big, probably, for you to have a complete mental picture of it. What happens when you're unsure of something? If the original program is written in Lisp, you can probe it interactively: you can inspect its data structures; you can call its functions; you may even be able to look at the original source code. This kind of feedback allows you to program with a high degree of confidence--to write more ambitious extensions, and to write them faster. An interactive environment always makes programming easier, but it is nowhere more valuable than when one is writing extensions. An extensible program is a double-edged sword, but recent experience has shown that users prefer a double-edged sword to a blunt one. Extensible programs seem to prevail, whatever their inherent dangers." [[:section {:title "Extending Lisp"}]] "There are two ways to add new operators to Lisp: functions and macros. In Lisp, functions you define have the same status as the built-in ones. If you want a new variant of mapcar, you can define one yourself and use it just as you would use mapcar. For example, if you want a list of the values returned by some function when it is applied to all the integers from 1 to 10, you could create a new list and pass it to map:"
125106
(ns documentation.on-lisp.ch1-the-extensible-language (:use hara.test)) "Not long ago, if you asked what Lisp was for, many people would have answered \"for artificial intelligence.\" In fact, the association between Lisp and AI is just an accident of history. Lisp was invented by <NAME>, who also invented the term \"artificial intelligence.\" His students and colleagues wrote their programs in Lisp, and so it began to be spoken of as an AI language. This line was taken up and repeated so often during the brief AI boom in the 1980s that it became almost an institution. Fortunately, word has begun to spread that AI is not what Lisp is all about. Recent advances in hardware and software have made Lisp commercially viable: it is now used in Gnu Emacs, the best Unix text-editor; Autocad, the industry standard desktop CAD program; and Interleaf, a leading high-end publishing program. The way Lisp is used in these programs has nothing whatever to do with AI. If Lisp is not the language of AI, what is it? Instead of judging Lisp by the company it keeps, let's look at the language itself. What can you do in Lisp that you can't do in other languages? One of the most distinctive qualities of Lisp is the way it can be tailored to suit the program being written in it. Lisp itself is a Lisp program, and Lisp programs can be expressed as lists, which are Lisp data structures. Together, these two principles mean that any user can add operators to Lisp which are indistinguishable from the ones that come built-in." [[:section {:title "Design by Evolution"}]] "Because Lisp gives you the freedom to define your own operators, you can mold it into just the language you need. If you're writing a text-editor, you can turn Lisp into a language for writing text-editors. If you're writing a CAD program, you can turn Lisp into a language for writing CAD programs. And if you're not sure yet what kind of program you're writing, it's a safe bet to write it in Lisp. Whatever kind of program yours turns out to be, Lisp will, during the writing of it, have evolved into a language for writing that kind of program. If you're not sure yet what kind of program you're writing? To some ears that sentence has an odd ring to it. It is in jarring contrast with a certain model of doing things wherein you (1) carefully plan what you're going to do, and then (2) do it. According to this model, if Lisp encourages you to start writing your program before you've decided how it should work, it merely encourages sloppy thinking. Well, it just ain't so. The plan-and-implement method may have been a good way of building dams or launching invasions, but experience has not shown it to be as good a way of writing programs. Why? Perhaps it's because computers are so exacting. Perhaps there is more variation between programs than there is between dams or invasions. Or perhaps the old methods don't work because old concepts of redundancy have no analogue in software development: if a dam contains 30% too much concrete, that's a margin for error, but if a program does 30% too much work, that is an error. It may be difficult to say why the old method fails, but that it does fail, anyone can see. When is software delivered on time? Experienced programmers know that no matter how carefully you plan a program, when you write it the plans will turn out to be imperfect in some way. Sometimes the plans will be hopelessly wrong. Yet few of the victims of the plan-and-implement method question its basic soundness. Instead they blame human failings: if only the plans had been made with more foresight, all this trouble could have been avoided. Since even the very best programmers run into problems when they turn to implementation, perhaps it's too much to hope that people will ever have that much foresight. Perhaps the plan-and-implement method could be replaced with another approach which better suits our limitations. We can approach programming in a different way, if we have the right tools. Why do we plan before implementing? The big danger in plunging right into a project is the possibility that we will paint ourselves into a corner. If we had a more flexible language, could this worry be lessened? We do, and it is. The flexibility of Lisp has spawned a whole new style of programming. In Lisp, you can do much of your planning as you write the program. Why wait for hindsight? As Montaigne found, nothing clarifies your ideas like trying to write them down. Once you're freed from the worry that you'll paint yourself into a corner, you can take full advantage of this possibility. The ability to plan programs as you write them has two momentous consequences: programs take less time to write, because when you plan and write at the same time, you have a real program to focus your attention; and they turn out better, because the final design is always a product of evolution. So long as you maintain a certain discipline while searching for your program's destiny--so long as you always rewrite mistaken parts as soon as it becomes clear that they're mistaken--the final product will be a program more elegant than if you had spent weeks planning it beforehand. Lisp's versatility makes this kind of programming a practical alternative. Indeed, the greatest danger of Lisp is that it may spoil you. Once you've used Lisp for a while, you may become so sensitive to the fit between language and application that you won't be able to go back to another language without always feeling that it doesn't give you quite the flexibility you need." [[:section {:title "Programming Bottom-Up"}]] "It's a long-standing principle of programming style that the functional elements of a program should not be too large. If some component of a program grows beyond the stage where it's readily comprehensible, it becomes a mass of complexity which conceals errors as easily as a big city conceals fugitives. Such software will be hard to read, hard to test, and hard to debug. In accordance with this principle, a large program must be divided into pieces, and the larger the program, the more it must be divided. How do you divide a program? The traditional approach is called top-down design: you say \"the purpose of the program is to do these seven things, so I divide it into seven major subroutines. The first subroutine has to do these four things, so it in turn will have four of its own subroutines,\" and so on. This process continues until the whole program has the right level of granularity--each part large enough to do something substantial, but small enough to be understood as a single unit. Experienced Lisp programmers divide up their programs differently. As well as top-down design, they follow a principle which could be called bottom-up design--changing the language to suit the problem. In Lisp, you don't just write your program down toward the language, you also build the language up toward your program. As you're writing a program you may think \"I wish Lisp had such-and-such an operator.\" So you go and write it. Afterward you realize that using the new operator would simplify the design of another part of the program, and so on. Language and program evolve together. Like the border between two warring states, the boundary between language and program is drawn and redrawn, until eventually it comes to rest along the mountains and rivers, the natural frontiers of your problem. In the end your program will look as if the language had been designed for it. And when language and program fit one another well, you end up with code which is clear, small, and efficient. It's worth emphasizing that bottom-up design doesn't mean just writing the same program in a different order. When you work bottom-up, you usually end up with a different program. Instead of a single, monolithic program, you will get a larger language with more abstract operators, and a smaller program written in it. Instead of a lintel, you'll get an arch. In typical code, once you abstract out the parts which are merely bookkeeping, what's left is much shorter; the higher you build up the language, the less distance you will have to travel from the top down to it. This brings several advantages: - By making the language do more of the work, bottom-up design yields programs which are smaller and more agile. A shorter program doesn't have to be divided into so many components, and fewer components means programs which are easier to read or modify. Fewer components also means fewer connections between components, and thus less chance for errors there. As industrial designers strive to reduce the number of moving parts in a machine, experienced Lisp programmers use bottom-up design to reduce the size and complexity of their programs. - Bottom-up design promotes code re-use. When you write two or more programs, many of the utilities you wrote for the first program will also be useful in the succeeding ones. Once you've acquired a large substrate of utilities, writing a new program can take only a fraction of the effort it would require if you had to start with raw Lisp. - Bottom-up design makes programs easier to read. An instance of this type of abstraction asks the reader to understand a general-purpose operator; an instance of functional abstraction asks the reader to understand a special-purpose subroutine.(1) - Because it causes you always to be on the lookout for patterns in your code, working bottom-up helps to clarify your ideas about the design of your program. If two distant components of a program are similar in form, you'll be led to notice the similarity and perhaps to redesign the program in a simpler way. - Bottom-up design is possible to a certain degree in languages other than Lisp. Whenever you see library functions, bottom-up design is happening. However, Lisp gives you much broader powers in this department, and augmenting the language plays a proportionately larger role in Lisp style--so much so that Lisp is not just a different language, but a whole different way of programming. It's true that this style of development is better suited to programs which can be written by small groups. However, at the same time, it extends the limits of what can be done by a small group. In The Mythical Man-Month, <NAME> proposed that the productivity of a group of programmers does not grow linearly with its size. As the size of the group increases, the productivity of individual programmers goes down. The experience of Lisp programming suggests a more cheerful way to phrase this law: as the size of the group decreases, the productivity of individual programmers goes up. A small group wins, relatively speaking, simply because it's smaller. When a small group also takes advantage of the techniques that Lisp makes possible, it can win outright." [[:section {:title "Extensible Software"}]] "The Lisp style of programming is one that has grown in importance as software has grown in complexity. Sophisticated users now demand so much from software that we can't possibly anticipate all their needs. They themselves can't anticipate all their needs. But if we can't give them software which does everything they want right out of the box, we can give them software which is extensible. We transform our software from a mere program into a programming language, and advanced users can build upon it the extra features that they need. Bottom-up design leads naturally to extensible programs. The simplest bottom-up programs consist of two layers: language and program. Complex programs may be written as a series of layers, each one acting as a programming language for the one above. If this philosophy is carried all the way up to the topmost layer, that layer becomes a programming language for the user. Such a program, where extensibility permeates every level, is likely to make a much better programming language than a system which was written as a traditional black box, and then made extensible as an afterthought. X Windows and T E X are early examples of programs based on this principle. In the 1980s better hardware made possible a new generation of programs which had Lisp as their extension language. The first was Gnu Emacs, the popular Unix text-editor. Later came Autocad, the first large-scale commercial product to provide Lisp as an extension language. In 1991 Interleaf released a new version of its software that not only had Lisp as an extension language, but was largely implemented in Lisp. Lisp is an especially good language for writing extensible programs because it is itself an extensible program. If you write your Lisp programs so as to pass this extensibility on to the user, you effectively get an extension language for free. And the difference between extending a Lisp program in Lisp, and doing the same thing in a traditional language, is like the difference between meeting someone in person and conversing by letters. In a program which is made extensible simply by providing access to outside programs, the best we can hope for is two black boxes communicating with one another through some predefined channel. In Lisp, extensions can have direct access to the entire underlying program. This is not to say that you have to give users access to every part of your program--just that you now have a choice about whether to give them access or not. When this degree of access is combined with an interactive environment, you have extensibility at its best. Any program that you might use as a foundation for extensions of your own is likely to be fairly big--too big, probably, for you to have a complete mental picture of it. What happens when you're unsure of something? If the original program is written in Lisp, you can probe it interactively: you can inspect its data structures; you can call its functions; you may even be able to look at the original source code. This kind of feedback allows you to program with a high degree of confidence--to write more ambitious extensions, and to write them faster. An interactive environment always makes programming easier, but it is nowhere more valuable than when one is writing extensions. An extensible program is a double-edged sword, but recent experience has shown that users prefer a double-edged sword to a blunt one. Extensible programs seem to prevail, whatever their inherent dangers." [[:section {:title "Extending Lisp"}]] "There are two ways to add new operators to Lisp: functions and macros. In Lisp, functions you define have the same status as the built-in ones. If you want a new variant of mapcar, you can define one yourself and use it just as you would use mapcar. For example, if you want a list of the values returned by some function when it is applied to all the integers from 1 to 10, you could create a new list and pass it to map:"
true
(ns documentation.on-lisp.ch1-the-extensible-language (:use hara.test)) "Not long ago, if you asked what Lisp was for, many people would have answered \"for artificial intelligence.\" In fact, the association between Lisp and AI is just an accident of history. Lisp was invented by PI:NAME:<NAME>END_PI, who also invented the term \"artificial intelligence.\" His students and colleagues wrote their programs in Lisp, and so it began to be spoken of as an AI language. This line was taken up and repeated so often during the brief AI boom in the 1980s that it became almost an institution. Fortunately, word has begun to spread that AI is not what Lisp is all about. Recent advances in hardware and software have made Lisp commercially viable: it is now used in Gnu Emacs, the best Unix text-editor; Autocad, the industry standard desktop CAD program; and Interleaf, a leading high-end publishing program. The way Lisp is used in these programs has nothing whatever to do with AI. If Lisp is not the language of AI, what is it? Instead of judging Lisp by the company it keeps, let's look at the language itself. What can you do in Lisp that you can't do in other languages? One of the most distinctive qualities of Lisp is the way it can be tailored to suit the program being written in it. Lisp itself is a Lisp program, and Lisp programs can be expressed as lists, which are Lisp data structures. Together, these two principles mean that any user can add operators to Lisp which are indistinguishable from the ones that come built-in." [[:section {:title "Design by Evolution"}]] "Because Lisp gives you the freedom to define your own operators, you can mold it into just the language you need. If you're writing a text-editor, you can turn Lisp into a language for writing text-editors. If you're writing a CAD program, you can turn Lisp into a language for writing CAD programs. And if you're not sure yet what kind of program you're writing, it's a safe bet to write it in Lisp. Whatever kind of program yours turns out to be, Lisp will, during the writing of it, have evolved into a language for writing that kind of program. If you're not sure yet what kind of program you're writing? To some ears that sentence has an odd ring to it. It is in jarring contrast with a certain model of doing things wherein you (1) carefully plan what you're going to do, and then (2) do it. According to this model, if Lisp encourages you to start writing your program before you've decided how it should work, it merely encourages sloppy thinking. Well, it just ain't so. The plan-and-implement method may have been a good way of building dams or launching invasions, but experience has not shown it to be as good a way of writing programs. Why? Perhaps it's because computers are so exacting. Perhaps there is more variation between programs than there is between dams or invasions. Or perhaps the old methods don't work because old concepts of redundancy have no analogue in software development: if a dam contains 30% too much concrete, that's a margin for error, but if a program does 30% too much work, that is an error. It may be difficult to say why the old method fails, but that it does fail, anyone can see. When is software delivered on time? Experienced programmers know that no matter how carefully you plan a program, when you write it the plans will turn out to be imperfect in some way. Sometimes the plans will be hopelessly wrong. Yet few of the victims of the plan-and-implement method question its basic soundness. Instead they blame human failings: if only the plans had been made with more foresight, all this trouble could have been avoided. Since even the very best programmers run into problems when they turn to implementation, perhaps it's too much to hope that people will ever have that much foresight. Perhaps the plan-and-implement method could be replaced with another approach which better suits our limitations. We can approach programming in a different way, if we have the right tools. Why do we plan before implementing? The big danger in plunging right into a project is the possibility that we will paint ourselves into a corner. If we had a more flexible language, could this worry be lessened? We do, and it is. The flexibility of Lisp has spawned a whole new style of programming. In Lisp, you can do much of your planning as you write the program. Why wait for hindsight? As Montaigne found, nothing clarifies your ideas like trying to write them down. Once you're freed from the worry that you'll paint yourself into a corner, you can take full advantage of this possibility. The ability to plan programs as you write them has two momentous consequences: programs take less time to write, because when you plan and write at the same time, you have a real program to focus your attention; and they turn out better, because the final design is always a product of evolution. So long as you maintain a certain discipline while searching for your program's destiny--so long as you always rewrite mistaken parts as soon as it becomes clear that they're mistaken--the final product will be a program more elegant than if you had spent weeks planning it beforehand. Lisp's versatility makes this kind of programming a practical alternative. Indeed, the greatest danger of Lisp is that it may spoil you. Once you've used Lisp for a while, you may become so sensitive to the fit between language and application that you won't be able to go back to another language without always feeling that it doesn't give you quite the flexibility you need." [[:section {:title "Programming Bottom-Up"}]] "It's a long-standing principle of programming style that the functional elements of a program should not be too large. If some component of a program grows beyond the stage where it's readily comprehensible, it becomes a mass of complexity which conceals errors as easily as a big city conceals fugitives. Such software will be hard to read, hard to test, and hard to debug. In accordance with this principle, a large program must be divided into pieces, and the larger the program, the more it must be divided. How do you divide a program? The traditional approach is called top-down design: you say \"the purpose of the program is to do these seven things, so I divide it into seven major subroutines. The first subroutine has to do these four things, so it in turn will have four of its own subroutines,\" and so on. This process continues until the whole program has the right level of granularity--each part large enough to do something substantial, but small enough to be understood as a single unit. Experienced Lisp programmers divide up their programs differently. As well as top-down design, they follow a principle which could be called bottom-up design--changing the language to suit the problem. In Lisp, you don't just write your program down toward the language, you also build the language up toward your program. As you're writing a program you may think \"I wish Lisp had such-and-such an operator.\" So you go and write it. Afterward you realize that using the new operator would simplify the design of another part of the program, and so on. Language and program evolve together. Like the border between two warring states, the boundary between language and program is drawn and redrawn, until eventually it comes to rest along the mountains and rivers, the natural frontiers of your problem. In the end your program will look as if the language had been designed for it. And when language and program fit one another well, you end up with code which is clear, small, and efficient. It's worth emphasizing that bottom-up design doesn't mean just writing the same program in a different order. When you work bottom-up, you usually end up with a different program. Instead of a single, monolithic program, you will get a larger language with more abstract operators, and a smaller program written in it. Instead of a lintel, you'll get an arch. In typical code, once you abstract out the parts which are merely bookkeeping, what's left is much shorter; the higher you build up the language, the less distance you will have to travel from the top down to it. This brings several advantages: - By making the language do more of the work, bottom-up design yields programs which are smaller and more agile. A shorter program doesn't have to be divided into so many components, and fewer components means programs which are easier to read or modify. Fewer components also means fewer connections between components, and thus less chance for errors there. As industrial designers strive to reduce the number of moving parts in a machine, experienced Lisp programmers use bottom-up design to reduce the size and complexity of their programs. - Bottom-up design promotes code re-use. When you write two or more programs, many of the utilities you wrote for the first program will also be useful in the succeeding ones. Once you've acquired a large substrate of utilities, writing a new program can take only a fraction of the effort it would require if you had to start with raw Lisp. - Bottom-up design makes programs easier to read. An instance of this type of abstraction asks the reader to understand a general-purpose operator; an instance of functional abstraction asks the reader to understand a special-purpose subroutine.(1) - Because it causes you always to be on the lookout for patterns in your code, working bottom-up helps to clarify your ideas about the design of your program. If two distant components of a program are similar in form, you'll be led to notice the similarity and perhaps to redesign the program in a simpler way. - Bottom-up design is possible to a certain degree in languages other than Lisp. Whenever you see library functions, bottom-up design is happening. However, Lisp gives you much broader powers in this department, and augmenting the language plays a proportionately larger role in Lisp style--so much so that Lisp is not just a different language, but a whole different way of programming. It's true that this style of development is better suited to programs which can be written by small groups. However, at the same time, it extends the limits of what can be done by a small group. In The Mythical Man-Month, PI:NAME:<NAME>END_PI proposed that the productivity of a group of programmers does not grow linearly with its size. As the size of the group increases, the productivity of individual programmers goes down. The experience of Lisp programming suggests a more cheerful way to phrase this law: as the size of the group decreases, the productivity of individual programmers goes up. A small group wins, relatively speaking, simply because it's smaller. When a small group also takes advantage of the techniques that Lisp makes possible, it can win outright." [[:section {:title "Extensible Software"}]] "The Lisp style of programming is one that has grown in importance as software has grown in complexity. Sophisticated users now demand so much from software that we can't possibly anticipate all their needs. They themselves can't anticipate all their needs. But if we can't give them software which does everything they want right out of the box, we can give them software which is extensible. We transform our software from a mere program into a programming language, and advanced users can build upon it the extra features that they need. Bottom-up design leads naturally to extensible programs. The simplest bottom-up programs consist of two layers: language and program. Complex programs may be written as a series of layers, each one acting as a programming language for the one above. If this philosophy is carried all the way up to the topmost layer, that layer becomes a programming language for the user. Such a program, where extensibility permeates every level, is likely to make a much better programming language than a system which was written as a traditional black box, and then made extensible as an afterthought. X Windows and T E X are early examples of programs based on this principle. In the 1980s better hardware made possible a new generation of programs which had Lisp as their extension language. The first was Gnu Emacs, the popular Unix text-editor. Later came Autocad, the first large-scale commercial product to provide Lisp as an extension language. In 1991 Interleaf released a new version of its software that not only had Lisp as an extension language, but was largely implemented in Lisp. Lisp is an especially good language for writing extensible programs because it is itself an extensible program. If you write your Lisp programs so as to pass this extensibility on to the user, you effectively get an extension language for free. And the difference between extending a Lisp program in Lisp, and doing the same thing in a traditional language, is like the difference between meeting someone in person and conversing by letters. In a program which is made extensible simply by providing access to outside programs, the best we can hope for is two black boxes communicating with one another through some predefined channel. In Lisp, extensions can have direct access to the entire underlying program. This is not to say that you have to give users access to every part of your program--just that you now have a choice about whether to give them access or not. When this degree of access is combined with an interactive environment, you have extensibility at its best. Any program that you might use as a foundation for extensions of your own is likely to be fairly big--too big, probably, for you to have a complete mental picture of it. What happens when you're unsure of something? If the original program is written in Lisp, you can probe it interactively: you can inspect its data structures; you can call its functions; you may even be able to look at the original source code. This kind of feedback allows you to program with a high degree of confidence--to write more ambitious extensions, and to write them faster. An interactive environment always makes programming easier, but it is nowhere more valuable than when one is writing extensions. An extensible program is a double-edged sword, but recent experience has shown that users prefer a double-edged sword to a blunt one. Extensible programs seem to prevail, whatever their inherent dangers." [[:section {:title "Extending Lisp"}]] "There are two ways to add new operators to Lisp: functions and macros. In Lisp, functions you define have the same status as the built-in ones. If you want a new variant of mapcar, you can define one yourself and use it just as you would use mapcar. For example, if you want a list of the values returned by some function when it is applied to all the integers from 1 to 10, you could create a new list and pass it to map:"
[ { "context": "DELAY=-1\"\n :user \"test\"\n :password \"sav\"})\n\n\n(def H2DB\n {:connection (jdbc/get-connectio", "end": 571, "score": 0.9992114305496216, "start": 568, "tag": "PASSWORD", "value": "sav" }, { "context": " H2DB\n {:name \"Richard\" :weight 0})))))\n\n (testing \"select character wi", "end": 2132, "score": 0.997686505317688, "start": 2125, "tag": "NAME", "value": "Richard" }, { "context": "rt-character H2DB\n {:name \"Chris\" :weight i}))\n (is (= 10 (count (async/<!! (ra", "end": 2603, "score": 0.9972724914550781, "start": 2598, "tag": "NAME", "value": "Chris" } ]
data/test/clojure/ae2eaa59bd1b904b4b457ba51e432bffddd56bfbjdbc_test.clj
harshp8l/deep-learning-lang-detection
84
(ns hugsql-finagle-async.jdbc-test (:require [clojure.core.async :as async] [clojure.test :refer :all] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [hugsql.core :as hugsql] [hugsql-finagle-async.jdbc :as jdbc-adapter] [clojure.string :as str])) (hugsql/set-adapter! (jdbc-adapter/hugsql-adapter-clojure-async-jdbc)) (def h2-config {:classname "org.h2.Driver" :subprotocol "h2:mem" :subname "testdb0;MODE=MySQL;DB_CLOSE_DELAY=-1" :user "test" :password "sav"}) (def H2DB {:connection (jdbc/get-connection h2-config)}) (hugsql/def-db-fns (io/file "test/resources/fns.sql")) (deftest integrate-test (testing "select character with no database" (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (select-character-star H2DB {:id 1}))))) (testing "create character table" ;; TODO: manage it to a specific test and a fixture in this function (is (= (async/<!! (create-characters-table H2DB)) [0])) ;; Create a existed table will return a nil. (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (create-characters-table H2DB))))) (testing "select character with no data" (is (nil? (async/<!! (select-character-star H2DB {:id 0}))))) (testing "insert a weight 0 character" (is (= (async/<!! (insert-character H2DB {:name "Chris" :weight 0})) [1]))) (testing "select character with 1 record" (is (async/<!! (select-character-star H2DB {:id 1})))) (testing "select the weight 0 character with dynamic table-name" (is (= (zero? (:weight (async/<!! (select-character-by-weight H2DB {:weight 0 :table-name "characters"}))))))) (testing "test the unique constaints by insert another weight 0 character" (is (instance? org.h2.jdbc.JdbcBatchUpdateException (async/<!! (insert-character H2DB {:name "Richard" :weight 0}))))) (testing "select character with not exist DB" (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (select-character-by-weight H2DB {:weight 0 :table-name "characters1"}))))) (testing "raw return query with multiple recoreds returning" (doseq [i (range 10)] (insert-character H2DB {:name "Chris" :weight i})) (is (= 10 (count (async/<!! (raw-query-character-less-than H2DB {:weight 10})))))) (testing "drop character table" (async/<!! (drop-characters-table H2DB))))
70356
(ns hugsql-finagle-async.jdbc-test (:require [clojure.core.async :as async] [clojure.test :refer :all] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [hugsql.core :as hugsql] [hugsql-finagle-async.jdbc :as jdbc-adapter] [clojure.string :as str])) (hugsql/set-adapter! (jdbc-adapter/hugsql-adapter-clojure-async-jdbc)) (def h2-config {:classname "org.h2.Driver" :subprotocol "h2:mem" :subname "testdb0;MODE=MySQL;DB_CLOSE_DELAY=-1" :user "test" :password "<PASSWORD>"}) (def H2DB {:connection (jdbc/get-connection h2-config)}) (hugsql/def-db-fns (io/file "test/resources/fns.sql")) (deftest integrate-test (testing "select character with no database" (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (select-character-star H2DB {:id 1}))))) (testing "create character table" ;; TODO: manage it to a specific test and a fixture in this function (is (= (async/<!! (create-characters-table H2DB)) [0])) ;; Create a existed table will return a nil. (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (create-characters-table H2DB))))) (testing "select character with no data" (is (nil? (async/<!! (select-character-star H2DB {:id 0}))))) (testing "insert a weight 0 character" (is (= (async/<!! (insert-character H2DB {:name "Chris" :weight 0})) [1]))) (testing "select character with 1 record" (is (async/<!! (select-character-star H2DB {:id 1})))) (testing "select the weight 0 character with dynamic table-name" (is (= (zero? (:weight (async/<!! (select-character-by-weight H2DB {:weight 0 :table-name "characters"}))))))) (testing "test the unique constaints by insert another weight 0 character" (is (instance? org.h2.jdbc.JdbcBatchUpdateException (async/<!! (insert-character H2DB {:name "<NAME>" :weight 0}))))) (testing "select character with not exist DB" (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (select-character-by-weight H2DB {:weight 0 :table-name "characters1"}))))) (testing "raw return query with multiple recoreds returning" (doseq [i (range 10)] (insert-character H2DB {:name "<NAME>" :weight i})) (is (= 10 (count (async/<!! (raw-query-character-less-than H2DB {:weight 10})))))) (testing "drop character table" (async/<!! (drop-characters-table H2DB))))
true
(ns hugsql-finagle-async.jdbc-test (:require [clojure.core.async :as async] [clojure.test :refer :all] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [hugsql.core :as hugsql] [hugsql-finagle-async.jdbc :as jdbc-adapter] [clojure.string :as str])) (hugsql/set-adapter! (jdbc-adapter/hugsql-adapter-clojure-async-jdbc)) (def h2-config {:classname "org.h2.Driver" :subprotocol "h2:mem" :subname "testdb0;MODE=MySQL;DB_CLOSE_DELAY=-1" :user "test" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (def H2DB {:connection (jdbc/get-connection h2-config)}) (hugsql/def-db-fns (io/file "test/resources/fns.sql")) (deftest integrate-test (testing "select character with no database" (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (select-character-star H2DB {:id 1}))))) (testing "create character table" ;; TODO: manage it to a specific test and a fixture in this function (is (= (async/<!! (create-characters-table H2DB)) [0])) ;; Create a existed table will return a nil. (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (create-characters-table H2DB))))) (testing "select character with no data" (is (nil? (async/<!! (select-character-star H2DB {:id 0}))))) (testing "insert a weight 0 character" (is (= (async/<!! (insert-character H2DB {:name "Chris" :weight 0})) [1]))) (testing "select character with 1 record" (is (async/<!! (select-character-star H2DB {:id 1})))) (testing "select the weight 0 character with dynamic table-name" (is (= (zero? (:weight (async/<!! (select-character-by-weight H2DB {:weight 0 :table-name "characters"}))))))) (testing "test the unique constaints by insert another weight 0 character" (is (instance? org.h2.jdbc.JdbcBatchUpdateException (async/<!! (insert-character H2DB {:name "PI:NAME:<NAME>END_PI" :weight 0}))))) (testing "select character with not exist DB" (is (instance? org.h2.jdbc.JdbcSQLException (async/<!! (select-character-by-weight H2DB {:weight 0 :table-name "characters1"}))))) (testing "raw return query with multiple recoreds returning" (doseq [i (range 10)] (insert-character H2DB {:name "PI:NAME:<NAME>END_PI" :weight i})) (is (= 10 (count (async/<!! (raw-query-character-less-than H2DB {:weight 10})))))) (testing "drop character table" (async/<!! (drop-characters-table H2DB))))
[ { "context": " [message-options]]\n (let [message {:from_email \"kyu@revress.com\"\n :from_name \"Kyu Lee\"\n ", "end": 1383, "score": 0.9999099373817444, "start": 1368, "tag": "EMAIL", "value": "kyu@revress.com" }, { "context": "l \"kyu@revress.com\"\n :from_name \"Kyu Lee\"\n :to [{:email email-addr", "end": 1422, "score": 0.9998498558998108, "start": 1415, "tag": "NAME", "value": "Kyu Lee" } ]
src/clj/happinessmailer/core.clj
smailq/happinessmailer
0
(ns happinessmailer.core (:require ; Make http requests [clj-http.client :as client] ; HTTP [compojure.core :refer [GET POST defroutes]] [compojure.handler :refer [site]] [compojure.route :as route] ; Environment variables [environ.core :refer [env]] ; Templating lib [hiccup.element :as e] [hiccup.page :as p] ; Web server [ring.adapter.jetty :as jetty] ; Middleware [ring.middleware.content-type :refer [wrap-content-type]] [ring.middleware.not-modified :refer [wrap-not-modified]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]] [ring.middleware.session :refer [wrap-session]] [ring.middleware.session.cookie :refer [cookie-store]] ; Various response types [ring.util.response :refer [redirect response content-type]] ; happinessmailer modules [happinessmailer.emails :as emails])) (defn mandrill-message-send "Sends email using Mandrill's REST API. content-fn must provide :subject, :tags, :text/html, :text/plain" [email-address content-fn & [message-options]] (let [message {:from_email "kyu@revress.com" :from_name "Kyu Lee" :to [{:email email-address :type "to"}] :subject (content-fn :subject) :tags (content-fn :tags) :html (content-fn :text/html) :text (content-fn :text/plain)}] (client/post "https://mandrillapp.com/api/1.0/messages/send.json" {:content-type :json :form-params {:key (System/getenv "MANDRILL_API_KEY") :message (merge message message-options)}}))) (defn landing-page "landing page" [] (p/html5 [:head [:meta {:charset "utf-8"}] [:title "Happiness Mailer"] ;(p/include-css "vendor/bootstrap/css/bootstrap.min.css") (p/include-css "css/compiled/screen.css")] [:body [:div "Welcome! Under construction."]])) (defroutes handler (GET "/" [] (landing-page))) (def app "This app is loaded by figwheel on dev environment." (-> handler (wrap-resource "public") ; Serve files under /public folder (wrap-content-type) ; TODO desc (wrap-not-modified) ; TODO desc (wrap-params) ; TODO desc (wrap-session {:store (cookie-store {:key (System/getenv "COOKIE_KEY")}) :cookie-attrs {:max-age (* 60 60 24 7)}}))) ; 7 days in sec (defn -main [& [port]] (let [port (Integer. (or port (env :port) 5000))] (jetty/run-jetty (site #'app) {:port port :join? false})))
62057
(ns happinessmailer.core (:require ; Make http requests [clj-http.client :as client] ; HTTP [compojure.core :refer [GET POST defroutes]] [compojure.handler :refer [site]] [compojure.route :as route] ; Environment variables [environ.core :refer [env]] ; Templating lib [hiccup.element :as e] [hiccup.page :as p] ; Web server [ring.adapter.jetty :as jetty] ; Middleware [ring.middleware.content-type :refer [wrap-content-type]] [ring.middleware.not-modified :refer [wrap-not-modified]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]] [ring.middleware.session :refer [wrap-session]] [ring.middleware.session.cookie :refer [cookie-store]] ; Various response types [ring.util.response :refer [redirect response content-type]] ; happinessmailer modules [happinessmailer.emails :as emails])) (defn mandrill-message-send "Sends email using Mandrill's REST API. content-fn must provide :subject, :tags, :text/html, :text/plain" [email-address content-fn & [message-options]] (let [message {:from_email "<EMAIL>" :from_name "<NAME>" :to [{:email email-address :type "to"}] :subject (content-fn :subject) :tags (content-fn :tags) :html (content-fn :text/html) :text (content-fn :text/plain)}] (client/post "https://mandrillapp.com/api/1.0/messages/send.json" {:content-type :json :form-params {:key (System/getenv "MANDRILL_API_KEY") :message (merge message message-options)}}))) (defn landing-page "landing page" [] (p/html5 [:head [:meta {:charset "utf-8"}] [:title "Happiness Mailer"] ;(p/include-css "vendor/bootstrap/css/bootstrap.min.css") (p/include-css "css/compiled/screen.css")] [:body [:div "Welcome! Under construction."]])) (defroutes handler (GET "/" [] (landing-page))) (def app "This app is loaded by figwheel on dev environment." (-> handler (wrap-resource "public") ; Serve files under /public folder (wrap-content-type) ; TODO desc (wrap-not-modified) ; TODO desc (wrap-params) ; TODO desc (wrap-session {:store (cookie-store {:key (System/getenv "COOKIE_KEY")}) :cookie-attrs {:max-age (* 60 60 24 7)}}))) ; 7 days in sec (defn -main [& [port]] (let [port (Integer. (or port (env :port) 5000))] (jetty/run-jetty (site #'app) {:port port :join? false})))
true
(ns happinessmailer.core (:require ; Make http requests [clj-http.client :as client] ; HTTP [compojure.core :refer [GET POST defroutes]] [compojure.handler :refer [site]] [compojure.route :as route] ; Environment variables [environ.core :refer [env]] ; Templating lib [hiccup.element :as e] [hiccup.page :as p] ; Web server [ring.adapter.jetty :as jetty] ; Middleware [ring.middleware.content-type :refer [wrap-content-type]] [ring.middleware.not-modified :refer [wrap-not-modified]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]] [ring.middleware.session :refer [wrap-session]] [ring.middleware.session.cookie :refer [cookie-store]] ; Various response types [ring.util.response :refer [redirect response content-type]] ; happinessmailer modules [happinessmailer.emails :as emails])) (defn mandrill-message-send "Sends email using Mandrill's REST API. content-fn must provide :subject, :tags, :text/html, :text/plain" [email-address content-fn & [message-options]] (let [message {:from_email "PI:EMAIL:<EMAIL>END_PI" :from_name "PI:NAME:<NAME>END_PI" :to [{:email email-address :type "to"}] :subject (content-fn :subject) :tags (content-fn :tags) :html (content-fn :text/html) :text (content-fn :text/plain)}] (client/post "https://mandrillapp.com/api/1.0/messages/send.json" {:content-type :json :form-params {:key (System/getenv "MANDRILL_API_KEY") :message (merge message message-options)}}))) (defn landing-page "landing page" [] (p/html5 [:head [:meta {:charset "utf-8"}] [:title "Happiness Mailer"] ;(p/include-css "vendor/bootstrap/css/bootstrap.min.css") (p/include-css "css/compiled/screen.css")] [:body [:div "Welcome! Under construction."]])) (defroutes handler (GET "/" [] (landing-page))) (def app "This app is loaded by figwheel on dev environment." (-> handler (wrap-resource "public") ; Serve files under /public folder (wrap-content-type) ; TODO desc (wrap-not-modified) ; TODO desc (wrap-params) ; TODO desc (wrap-session {:store (cookie-store {:key (System/getenv "COOKIE_KEY")}) :cookie-attrs {:max-age (* 60 60 24 7)}}))) ; 7 days in sec (defn -main [& [port]] (let [port (Integer. (or port (env :port) 5000))] (jetty/run-jetty (site #'app) {:port port :join? false})))
[ { "context": ";; From https://github.com/Lambda-X/replumb/blob/master/src/node/replumb/nodejs/io.cl", "end": 35, "score": 0.9997000098228455, "start": 27, "tag": "USERNAME", "value": "Lambda-X" }, { "context": "nse, the same as Clojure.\n;; Copyright (C) 2015-16 Scalac Sp. z o.o.\n\n(ns replumb.nodejs.io\n (:require [", "end": 331, "score": 0.6690465807914734, "start": 327, "tag": "NAME", "value": "Scal" } ]
proto-repl-client-cljs/src-cljs/replumb/nodejs/io.cljs
emmanuj/proto-repl
640
;; From https://github.com/Lambda-X/replumb/blob/master/src/node/replumb/nodejs/io.cljs ;; Copied based on README text: "There are examples of this in both ;; replumb.browser.io and replumb.nodejs.io that you can freely copy over." ;; Distributed under the Eclipse Public License, the same as Clojure. ;; Copyright (C) 2015-16 Scalac Sp. z o.o. (ns replumb.nodejs.io (:require [cljs.nodejs :as nodejs] [replumb.common :as common])) (def require-fs "Delay containing the call to \"require fs\". It returns the File System Node.js module object." (delay (nodejs/require "fs"))) (defn read-file! "Accepts the fs module object, encoding or file options, file name to read and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback." ([file-path src-cb] (read-file! (force require-fs) "utf-8" file-path src-cb)) ([encoding-or-opts file-path src-cb] (read-file! (force require-fs) encoding-or-opts file-path src-cb)) ([fs-module encoding-or-opts file-path src-cb] (try ;; AR the async readFile had weird behavior and was wreaking havoc (src-cb (.readFileSync fs-module file-path encoding-or-opts)) (catch :default e (src-cb nil))))) (defn write-file! "Accepts the fs module object, encoding or file options, file name to write and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". It is synchronous and returns undefined as per Node.js doc. For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback." ([file-path data] (write-file! "utf-8" file-path data)) ([encoding-or-opts file-path data] (write-file! (force require-fs) encoding-or-opts file-path data)) ([fs-module encoding-or-opts file-path data] (try (.writeFileSync fs-module file-path data encoding-or-opts) (catch :default e (println (.-stack e)))))) (defn delete-file! "Accepts the fs module object, encoding or file options, file name to write and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". It is synchronous and returns undefined as per Node.js doc. For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback." ([file-path] (delete-file! (force require-fs) file-path)) ([fs-module file-path] (try (.unlinkSync fs-module file-path) (catch :default e (println (.-stack e)))))) (defn file-exists? "Check if the file on the given path exists. It is synchronous." ([path] (file-exists? (force require-fs) path)) ([fs-module path] (try (not (nil? (.statSync fs-module path))) (catch :default e ;; ENOENT -> No such file or directory, see https://nodejs.org/api/errors.html (if (re-find #"ENOENT" (common/extract-message e)) false (println (.-stack e))))))) (defn safely-delete! "Before deleting, checks if the file exists." [path] (when (file-exists? path) (delete-file! path))) (defn rename-file! "Renames synchronously a file." ([old-path new-path] (rename-file! (force require-fs) old-path new-path)) ([fs-module old-path new-path] (.renameSync fs-module old-path new-path))) (defn safely-rename-file! "Before renaming, checks if the file exists." [old-path new-path] (when (file-exists? old-path) (rename-file! old-path new-path)))
117175
;; From https://github.com/Lambda-X/replumb/blob/master/src/node/replumb/nodejs/io.cljs ;; Copied based on README text: "There are examples of this in both ;; replumb.browser.io and replumb.nodejs.io that you can freely copy over." ;; Distributed under the Eclipse Public License, the same as Clojure. ;; Copyright (C) 2015-16 <NAME>ac Sp. z o.o. (ns replumb.nodejs.io (:require [cljs.nodejs :as nodejs] [replumb.common :as common])) (def require-fs "Delay containing the call to \"require fs\". It returns the File System Node.js module object." (delay (nodejs/require "fs"))) (defn read-file! "Accepts the fs module object, encoding or file options, file name to read and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback." ([file-path src-cb] (read-file! (force require-fs) "utf-8" file-path src-cb)) ([encoding-or-opts file-path src-cb] (read-file! (force require-fs) encoding-or-opts file-path src-cb)) ([fs-module encoding-or-opts file-path src-cb] (try ;; AR the async readFile had weird behavior and was wreaking havoc (src-cb (.readFileSync fs-module file-path encoding-or-opts)) (catch :default e (src-cb nil))))) (defn write-file! "Accepts the fs module object, encoding or file options, file name to write and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". It is synchronous and returns undefined as per Node.js doc. For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback." ([file-path data] (write-file! "utf-8" file-path data)) ([encoding-or-opts file-path data] (write-file! (force require-fs) encoding-or-opts file-path data)) ([fs-module encoding-or-opts file-path data] (try (.writeFileSync fs-module file-path data encoding-or-opts) (catch :default e (println (.-stack e)))))) (defn delete-file! "Accepts the fs module object, encoding or file options, file name to write and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". It is synchronous and returns undefined as per Node.js doc. For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback." ([file-path] (delete-file! (force require-fs) file-path)) ([fs-module file-path] (try (.unlinkSync fs-module file-path) (catch :default e (println (.-stack e)))))) (defn file-exists? "Check if the file on the given path exists. It is synchronous." ([path] (file-exists? (force require-fs) path)) ([fs-module path] (try (not (nil? (.statSync fs-module path))) (catch :default e ;; ENOENT -> No such file or directory, see https://nodejs.org/api/errors.html (if (re-find #"ENOENT" (common/extract-message e)) false (println (.-stack e))))))) (defn safely-delete! "Before deleting, checks if the file exists." [path] (when (file-exists? path) (delete-file! path))) (defn rename-file! "Renames synchronously a file." ([old-path new-path] (rename-file! (force require-fs) old-path new-path)) ([fs-module old-path new-path] (.renameSync fs-module old-path new-path))) (defn safely-rename-file! "Before renaming, checks if the file exists." [old-path new-path] (when (file-exists? old-path) (rename-file! old-path new-path)))
true
;; From https://github.com/Lambda-X/replumb/blob/master/src/node/replumb/nodejs/io.cljs ;; Copied based on README text: "There are examples of this in both ;; replumb.browser.io and replumb.nodejs.io that you can freely copy over." ;; Distributed under the Eclipse Public License, the same as Clojure. ;; Copyright (C) 2015-16 PI:NAME:<NAME>END_PIac Sp. z o.o. (ns replumb.nodejs.io (:require [cljs.nodejs :as nodejs] [replumb.common :as common])) (def require-fs "Delay containing the call to \"require fs\". It returns the File System Node.js module object." (delay (nodejs/require "fs"))) (defn read-file! "Accepts the fs module object, encoding or file options, file name to read and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback." ([file-path src-cb] (read-file! (force require-fs) "utf-8" file-path src-cb)) ([encoding-or-opts file-path src-cb] (read-file! (force require-fs) encoding-or-opts file-path src-cb)) ([fs-module encoding-or-opts file-path src-cb] (try ;; AR the async readFile had weird behavior and was wreaking havoc (src-cb (.readFileSync fs-module file-path encoding-or-opts)) (catch :default e (src-cb nil))))) (defn write-file! "Accepts the fs module object, encoding or file options, file name to write and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". It is synchronous and returns undefined as per Node.js doc. For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback." ([file-path data] (write-file! "utf-8" file-path data)) ([encoding-or-opts file-path data] (write-file! (force require-fs) encoding-or-opts file-path data)) ([fs-module encoding-or-opts file-path data] (try (.writeFileSync fs-module file-path data encoding-or-opts) (catch :default e (println (.-stack e)))))) (defn delete-file! "Accepts the fs module object, encoding or file options, file name to write and a callback. Upon success, invokes the callback with the source of the file. Otherwise invokes the callback with nil. The arity without explicit module will call require the first time only. The arity without encoding-or-opts will default to no file options and encoding \"UTF-8\". It is synchronous and returns undefined as per Node.js doc. For encoding-or-opts, see https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback." ([file-path] (delete-file! (force require-fs) file-path)) ([fs-module file-path] (try (.unlinkSync fs-module file-path) (catch :default e (println (.-stack e)))))) (defn file-exists? "Check if the file on the given path exists. It is synchronous." ([path] (file-exists? (force require-fs) path)) ([fs-module path] (try (not (nil? (.statSync fs-module path))) (catch :default e ;; ENOENT -> No such file or directory, see https://nodejs.org/api/errors.html (if (re-find #"ENOENT" (common/extract-message e)) false (println (.-stack e))))))) (defn safely-delete! "Before deleting, checks if the file exists." [path] (when (file-exists? path) (delete-file! path))) (defn rename-file! "Renames synchronously a file." ([old-path new-path] (rename-file! (force require-fs) old-path new-path)) ([fs-module old-path new-path] (.renameSync fs-module old-path new-path))) (defn safely-rename-file! "Before renaming, checks if the file exists." [old-path new-path] (when (file-exists? old-path) (rename-file! old-path new-path)))
[ { "context": ";;; clods.core\n\n;; Copyright 2015 Tom Regan\n;;\n;; Licensed under the Apache License, Version ", "end": 43, "score": 0.9998505711555481, "start": 34, "tag": "NAME", "value": "Tom Regan" } ]
clods/src/clods/core.clj
TomRegan/hollaen
0
;;; clods.core ;; Copyright 2015 Tom Regan ;; ;; 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. ;;; Commentary: ;; The lein of best fit... ;;; Code: (ns clods.core (:gen-class) (require [clods.fizzbuzz :refer [fizzbuzz]] [clods.bonjour :refer [bonjour]] [clods.http :refer [request]])) (defn -main [& args] (cond (some #{"bonjour"} *command-line-args*) (bonjour) (some #{"fizzbuzz"} *command-line-args*) (fizzbuzz) (some #{"request"} *command-line-args*) (request "http://www.example.com/") :else (println "command" *command-line-args* "doesn't exist."))) ;;; clods.core ends here
114327
;;; clods.core ;; 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. ;;; Commentary: ;; The lein of best fit... ;;; Code: (ns clods.core (:gen-class) (require [clods.fizzbuzz :refer [fizzbuzz]] [clods.bonjour :refer [bonjour]] [clods.http :refer [request]])) (defn -main [& args] (cond (some #{"bonjour"} *command-line-args*) (bonjour) (some #{"fizzbuzz"} *command-line-args*) (fizzbuzz) (some #{"request"} *command-line-args*) (request "http://www.example.com/") :else (println "command" *command-line-args* "doesn't exist."))) ;;; clods.core ends here
true
;;; clods.core ;; 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. ;;; Commentary: ;; The lein of best fit... ;;; Code: (ns clods.core (:gen-class) (require [clods.fizzbuzz :refer [fizzbuzz]] [clods.bonjour :refer [bonjour]] [clods.http :refer [request]])) (defn -main [& args] (cond (some #{"bonjour"} *command-line-args*) (bonjour) (some #{"fizzbuzz"} *command-line-args*) (fizzbuzz) (some #{"request"} *command-line-args*) (request "http://www.example.com/") :else (println "command" *command-line-args* "doesn't exist."))) ;;; clods.core ends here
[ { "context": "]\n [\"Fred\" (rand-nth addresses)]\n ", "end": 6919, "score": 0.9994480609893799, "start": 6915, "tag": "NAME", "value": "Fred" }, { "context": "]\n [\"Adam\" (rand-nth addresses)]\n ", "end": 7070, "score": 0.9992871880531311, "start": 7066, "tag": "NAME", "value": "Adam" }, { "context": " [\"Szczepan\" (rand-nth addresses)]]}\n ", "end": 7146, "score": 0.5915438532829285, "start": 7144, "tag": "NAME", "value": "cz" }, { "context": "00001\"\n :article/author \"pkoza\"}})\n (update :body slurp))\n\n ;; wszystkie a", "end": 8487, "score": 0.9977409243583679, "start": 8482, "tag": "USERNAME", "value": "pkoza" } ]
src/clj/reitit_db_fun/main.clj
rotaliator/reitit-db-fun
7
(ns reitit-db-fun.main (:gen-class) (:require [clojure.java.io :as io] [integrant.core :as ig] [aleph.http :as http] [reitit.ring :as ring] [muuntaja.core :as m] [reitit.ring.middleware.muuntaja :as muuntaja] [reitit.ring.middleware.parameters] [reitit.coercion.malli] [reitit.coercion :as coercion] [clojure.tools.logging :as log] [reitit-db-fun.model] [reitit-db-fun.model-impl] [reitit-db-fun.storage] ;; XTDB #_[xtdb.api :as xt] ;; Datalevin ;;[datalevin.core :as d] ;; JDBC [next.jdbc :as jdbc] [next.jdbc.sql :as jdbc-sql] [honey.sql :as sql] [honey.sql.helpers :as h] ;; Datoms [reitit-db-fun.datom :as datom] ;; UUID [reitit-db-fun.uuid :as uuid] ;; Datascript [datascript.core :as d] [datascript.db :as db] ;; core.async [clojure.core.async :as async] ;; Middleware'y wymagane przez Sente ;; TODO [ring.middleware.anti-forgery :refer [wrap-anti-forgery]] ; <--- for SENTE! [ring.middleware.keyword-params] [ring.middleware.params] [ring.middleware.session] [reitit-db-fun.sente-functions :as sente-fn])) ;; ==== Config ==== (def config {:app/handler {:keys-to-wrap {:model (ig/ref :model/article-sql) :sente-functions (ig/ref :reitit-db-fun.sente-functions/sente-functions)} :sente (ig/ref :reitit-db-fun.sente/sente)} :reitit-db-fun.sente/sente {} :reitit-db-fun.msg-handlers/msg-handlers {:sente-state (ig/ref :reitit-db-fun.sente/sente) :sente-functions (ig/ref :reitit-db-fun.sente-functions/sente-functions) :model (ig/ref :model/article-sql)} :reitit-db-fun.sente-functions/sente-functions {:sente-state (ig/ref :reitit-db-fun.sente/sente) :model (ig/ref :model/article-sql)} :model/article-sql {:datasource (ig/ref :storage/sql)} :adapter/aleph {:port 8080 :handler (ig/ref :app/handler)} :storage/sql {:conn-options {:jdbc-url "jdbc:sqlite:database.sqlite"} :migrations-dir "migrations"}}) (defn wrap-keys [keys-to-wrap] (fn [handler] (fn [request] (handler (merge request keys-to-wrap))))) (defn get-article-handler [{:keys [model path-params]}] (println "DEBUG:" (pr-str path-params)) ;; TODO proper coercion {:body (reitit-db-fun.model/get-article model (:article-id path-params))}) (defn get-articles-handler [{:keys [model]}] {:body (reitit-db-fun.model/get-articles model)}) (defn update-article-handler [{:keys [model body-params sente-functions]}] (let [datoms (reitit-db-fun.model/update-article model body-params)] (sente-fn/send-datoms-to-all-clients sente-functions datoms) {:body "Updated"})) (defn get-app-handler [{:keys [keys-to-wrap sente sente-functions]}] (ring/ring-handler (ring/router [ ["/api" ["/articles" {:get get-articles-handler}] ["/article" {:post update-article-handler}] ["/article/:article-id" {:get get-article-handler}] ["/ping" {:get {:handler (fn [req] {:status 200 :body {:message "pong" :request (pr-str req)}})}}] ["/status" {:get {:handler (fn [req] {:status 200 :body {:message "status" :model (pr-str (:model req))}})}}]] ;; Sente ["/chsk" {:get {:handler (:ring-ajax-get-or-ws-handshake sente)} :post {:handler (:ring-ajax-post sente)}}]] ;; router data affecting all routes {:data {:muuntaja m/instance :middleware [ ring.middleware.session/wrap-session reitit.ring.middleware.parameters/parameters-middleware ring.middleware.keyword-params/wrap-keyword-params muuntaja/format-middleware muuntaja/format-response-middleware (wrap-keys keys-to-wrap) ]}}) (ring/routes (ring/create-resource-handler {:path "/"}) (ring/create-default-handler)))) (defonce main-system (atom nil)) (defmethod ig/init-key :adapter/aleph [key {:keys [handler port]}] (log/info "Starting" key) (http/start-server handler {:port port})) (defmethod ig/halt-key! :adapter/aleph [key server] (log/info "Stopping" key) (.close server)) (defmethod ig/init-key :app/handler [key {:keys [keys-to-wrap sente]}] (log/info "Starting" key) (get-app-handler {:keys-to-wrap keys-to-wrap :sente sente})) (defn start-system [system-atom config] (log/info "Starting system") (let [system @system-atom] (when-not system (ig/load-namespaces config) (reset! system-atom (ig/init config))))) (defn stop-system [system-atom] (log/info "Stopping system") (let [system @system-atom] (when system (reset! system-atom (ig/halt! system))))) (defn -main [& args] (log/debug "Server starting...") (start-system main-system config) (.addShutdownHook (Runtime/getRuntime) (Thread. #(stop-system main-system)))) (defn restart-system [] (stop-system main-system) (start-system main-system config)) (comment ;; przygotowuję dane. ;; Przykładowe adresy (let [datasource (:storage/sql @main-system) query (sql/format {:insert-into [:address] :columns [:street :city] :values [["Wróbla" "Puławy"] ["Kołłątaja" "Puławy"] ["Jaworowa" "Puławy"] ["Prusa" "Puławy"]]} {:pretty true})] (->> (jdbc/execute! datasource query))) ;; przykładowi userzy (let [datasource (:storage/sql @main-system) addresses (->> {:select :* :from :address} sql/format (jdbc/execute! datasource) (mapv :address/id)) query (sql/format {:insert-into [:user] :columns [:name :address] :values [["Wacław" (rand-nth addresses)] ["Fred" (rand-nth addresses)] ["Ewa" (rand-nth addresses)] ["Adam" (rand-nth addresses)] ["Szczepan" (rand-nth addresses)]]} {:pretty true})] (->> (jdbc/execute! datasource query))) ;; tworzę artykuły, tym razem poprzez api (let [datasource (:storage/sql @main-system) authors (->> {:select :* :from :user} sql/format (jdbc/execute! datasource) (mapv :user/id)) app (:app/handler @main-system)] (doseq [idx (range 2)] (app {:request-method :post :uri "/api/article" :body-params {:article/title (str "Test-" (inc idx)) :article/body (str "Treść artykułu " (inc idx)) :article/author (rand-nth authors)}}))) ;; sprawdzam pojedynczy artykuł (-> ((:app/handler @main-system) {:request-method :get :uri "/api/article/3000001"}) (update :body slurp)) ;; aktualizacja danych (-> ((:app/handler @main-system) {:request-method :post :uri "/api/article" :body-params {:article/id "3000002" :article/title "Title zmieniony 2" :article/body "Treść po zmiania" :article/address "2000001" :article/author "pkoza"}}) (update :body slurp)) ;; wszystkie arty (-> ((:app/handler @main-system) {:request-method :get :uri "/api/articles"} :body) slurp) ;; Baza SQL na Datomy! (def initial-datoms (let [datasource (:storage/sql @main-system) query (sql/format {:select [:article/* :address/* :user/*] :from [:article :address :user] :where [:and [:= :article/author :user/id] [:= :user/address :address/id] ] :limit 20})] (->> (jdbc/execute! datasource query) datom/resultset-into-datoms))) (let [datasource (:storage/sql @main-system) query (sql/format {:select [:article/*] :from [:article] :where [:= :article/id 3000015] :limit 20})] (->> (jdbc/execute! datasource query) datom/resultset-into-datoms)) ;; Datascript test db (def test-db (db/init-db (mapv #(apply d/datom %) initial-datoms))) (d/q '[:find (pull ?e [* {:article/author [:user/name {:user/address [*]}]}]) :where [?e :article/id _]] test-db) ;; test pojedynczego arta (let [model (:model/article-sql @main-system) datoms (reitit-db-fun.model/get-articles-datoms model) sente-state (:reitit-db-fun.sente/sente @main-system) chsk-send! (:chsk-send! sente-state) client (-> sente-state :connected-uids deref :any first)] (log/info :sending-datoms-to client) (chsk-send! client [:datoms/save! datoms])) (let [sente-state (:reitit-db-fun.sente/sente @main-system) clients (-> sente-state :connected-uids)] @clients) (do (stop-system main-system) (start-system main-system config)) (-main) )
32000
(ns reitit-db-fun.main (:gen-class) (:require [clojure.java.io :as io] [integrant.core :as ig] [aleph.http :as http] [reitit.ring :as ring] [muuntaja.core :as m] [reitit.ring.middleware.muuntaja :as muuntaja] [reitit.ring.middleware.parameters] [reitit.coercion.malli] [reitit.coercion :as coercion] [clojure.tools.logging :as log] [reitit-db-fun.model] [reitit-db-fun.model-impl] [reitit-db-fun.storage] ;; XTDB #_[xtdb.api :as xt] ;; Datalevin ;;[datalevin.core :as d] ;; JDBC [next.jdbc :as jdbc] [next.jdbc.sql :as jdbc-sql] [honey.sql :as sql] [honey.sql.helpers :as h] ;; Datoms [reitit-db-fun.datom :as datom] ;; UUID [reitit-db-fun.uuid :as uuid] ;; Datascript [datascript.core :as d] [datascript.db :as db] ;; core.async [clojure.core.async :as async] ;; Middleware'y wymagane przez Sente ;; TODO [ring.middleware.anti-forgery :refer [wrap-anti-forgery]] ; <--- for SENTE! [ring.middleware.keyword-params] [ring.middleware.params] [ring.middleware.session] [reitit-db-fun.sente-functions :as sente-fn])) ;; ==== Config ==== (def config {:app/handler {:keys-to-wrap {:model (ig/ref :model/article-sql) :sente-functions (ig/ref :reitit-db-fun.sente-functions/sente-functions)} :sente (ig/ref :reitit-db-fun.sente/sente)} :reitit-db-fun.sente/sente {} :reitit-db-fun.msg-handlers/msg-handlers {:sente-state (ig/ref :reitit-db-fun.sente/sente) :sente-functions (ig/ref :reitit-db-fun.sente-functions/sente-functions) :model (ig/ref :model/article-sql)} :reitit-db-fun.sente-functions/sente-functions {:sente-state (ig/ref :reitit-db-fun.sente/sente) :model (ig/ref :model/article-sql)} :model/article-sql {:datasource (ig/ref :storage/sql)} :adapter/aleph {:port 8080 :handler (ig/ref :app/handler)} :storage/sql {:conn-options {:jdbc-url "jdbc:sqlite:database.sqlite"} :migrations-dir "migrations"}}) (defn wrap-keys [keys-to-wrap] (fn [handler] (fn [request] (handler (merge request keys-to-wrap))))) (defn get-article-handler [{:keys [model path-params]}] (println "DEBUG:" (pr-str path-params)) ;; TODO proper coercion {:body (reitit-db-fun.model/get-article model (:article-id path-params))}) (defn get-articles-handler [{:keys [model]}] {:body (reitit-db-fun.model/get-articles model)}) (defn update-article-handler [{:keys [model body-params sente-functions]}] (let [datoms (reitit-db-fun.model/update-article model body-params)] (sente-fn/send-datoms-to-all-clients sente-functions datoms) {:body "Updated"})) (defn get-app-handler [{:keys [keys-to-wrap sente sente-functions]}] (ring/ring-handler (ring/router [ ["/api" ["/articles" {:get get-articles-handler}] ["/article" {:post update-article-handler}] ["/article/:article-id" {:get get-article-handler}] ["/ping" {:get {:handler (fn [req] {:status 200 :body {:message "pong" :request (pr-str req)}})}}] ["/status" {:get {:handler (fn [req] {:status 200 :body {:message "status" :model (pr-str (:model req))}})}}]] ;; Sente ["/chsk" {:get {:handler (:ring-ajax-get-or-ws-handshake sente)} :post {:handler (:ring-ajax-post sente)}}]] ;; router data affecting all routes {:data {:muuntaja m/instance :middleware [ ring.middleware.session/wrap-session reitit.ring.middleware.parameters/parameters-middleware ring.middleware.keyword-params/wrap-keyword-params muuntaja/format-middleware muuntaja/format-response-middleware (wrap-keys keys-to-wrap) ]}}) (ring/routes (ring/create-resource-handler {:path "/"}) (ring/create-default-handler)))) (defonce main-system (atom nil)) (defmethod ig/init-key :adapter/aleph [key {:keys [handler port]}] (log/info "Starting" key) (http/start-server handler {:port port})) (defmethod ig/halt-key! :adapter/aleph [key server] (log/info "Stopping" key) (.close server)) (defmethod ig/init-key :app/handler [key {:keys [keys-to-wrap sente]}] (log/info "Starting" key) (get-app-handler {:keys-to-wrap keys-to-wrap :sente sente})) (defn start-system [system-atom config] (log/info "Starting system") (let [system @system-atom] (when-not system (ig/load-namespaces config) (reset! system-atom (ig/init config))))) (defn stop-system [system-atom] (log/info "Stopping system") (let [system @system-atom] (when system (reset! system-atom (ig/halt! system))))) (defn -main [& args] (log/debug "Server starting...") (start-system main-system config) (.addShutdownHook (Runtime/getRuntime) (Thread. #(stop-system main-system)))) (defn restart-system [] (stop-system main-system) (start-system main-system config)) (comment ;; przygotowuję dane. ;; Przykładowe adresy (let [datasource (:storage/sql @main-system) query (sql/format {:insert-into [:address] :columns [:street :city] :values [["Wróbla" "Puławy"] ["Kołłątaja" "Puławy"] ["Jaworowa" "Puławy"] ["Prusa" "Puławy"]]} {:pretty true})] (->> (jdbc/execute! datasource query))) ;; przykładowi userzy (let [datasource (:storage/sql @main-system) addresses (->> {:select :* :from :address} sql/format (jdbc/execute! datasource) (mapv :address/id)) query (sql/format {:insert-into [:user] :columns [:name :address] :values [["Wacław" (rand-nth addresses)] ["<NAME>" (rand-nth addresses)] ["Ewa" (rand-nth addresses)] ["<NAME>" (rand-nth addresses)] ["Sz<NAME>epan" (rand-nth addresses)]]} {:pretty true})] (->> (jdbc/execute! datasource query))) ;; tworzę artykuły, tym razem poprzez api (let [datasource (:storage/sql @main-system) authors (->> {:select :* :from :user} sql/format (jdbc/execute! datasource) (mapv :user/id)) app (:app/handler @main-system)] (doseq [idx (range 2)] (app {:request-method :post :uri "/api/article" :body-params {:article/title (str "Test-" (inc idx)) :article/body (str "Treść artykułu " (inc idx)) :article/author (rand-nth authors)}}))) ;; sprawdzam pojedynczy artykuł (-> ((:app/handler @main-system) {:request-method :get :uri "/api/article/3000001"}) (update :body slurp)) ;; aktualizacja danych (-> ((:app/handler @main-system) {:request-method :post :uri "/api/article" :body-params {:article/id "3000002" :article/title "Title zmieniony 2" :article/body "Treść po zmiania" :article/address "2000001" :article/author "pkoza"}}) (update :body slurp)) ;; wszystkie arty (-> ((:app/handler @main-system) {:request-method :get :uri "/api/articles"} :body) slurp) ;; Baza SQL na Datomy! (def initial-datoms (let [datasource (:storage/sql @main-system) query (sql/format {:select [:article/* :address/* :user/*] :from [:article :address :user] :where [:and [:= :article/author :user/id] [:= :user/address :address/id] ] :limit 20})] (->> (jdbc/execute! datasource query) datom/resultset-into-datoms))) (let [datasource (:storage/sql @main-system) query (sql/format {:select [:article/*] :from [:article] :where [:= :article/id 3000015] :limit 20})] (->> (jdbc/execute! datasource query) datom/resultset-into-datoms)) ;; Datascript test db (def test-db (db/init-db (mapv #(apply d/datom %) initial-datoms))) (d/q '[:find (pull ?e [* {:article/author [:user/name {:user/address [*]}]}]) :where [?e :article/id _]] test-db) ;; test pojedynczego arta (let [model (:model/article-sql @main-system) datoms (reitit-db-fun.model/get-articles-datoms model) sente-state (:reitit-db-fun.sente/sente @main-system) chsk-send! (:chsk-send! sente-state) client (-> sente-state :connected-uids deref :any first)] (log/info :sending-datoms-to client) (chsk-send! client [:datoms/save! datoms])) (let [sente-state (:reitit-db-fun.sente/sente @main-system) clients (-> sente-state :connected-uids)] @clients) (do (stop-system main-system) (start-system main-system config)) (-main) )
true
(ns reitit-db-fun.main (:gen-class) (:require [clojure.java.io :as io] [integrant.core :as ig] [aleph.http :as http] [reitit.ring :as ring] [muuntaja.core :as m] [reitit.ring.middleware.muuntaja :as muuntaja] [reitit.ring.middleware.parameters] [reitit.coercion.malli] [reitit.coercion :as coercion] [clojure.tools.logging :as log] [reitit-db-fun.model] [reitit-db-fun.model-impl] [reitit-db-fun.storage] ;; XTDB #_[xtdb.api :as xt] ;; Datalevin ;;[datalevin.core :as d] ;; JDBC [next.jdbc :as jdbc] [next.jdbc.sql :as jdbc-sql] [honey.sql :as sql] [honey.sql.helpers :as h] ;; Datoms [reitit-db-fun.datom :as datom] ;; UUID [reitit-db-fun.uuid :as uuid] ;; Datascript [datascript.core :as d] [datascript.db :as db] ;; core.async [clojure.core.async :as async] ;; Middleware'y wymagane przez Sente ;; TODO [ring.middleware.anti-forgery :refer [wrap-anti-forgery]] ; <--- for SENTE! [ring.middleware.keyword-params] [ring.middleware.params] [ring.middleware.session] [reitit-db-fun.sente-functions :as sente-fn])) ;; ==== Config ==== (def config {:app/handler {:keys-to-wrap {:model (ig/ref :model/article-sql) :sente-functions (ig/ref :reitit-db-fun.sente-functions/sente-functions)} :sente (ig/ref :reitit-db-fun.sente/sente)} :reitit-db-fun.sente/sente {} :reitit-db-fun.msg-handlers/msg-handlers {:sente-state (ig/ref :reitit-db-fun.sente/sente) :sente-functions (ig/ref :reitit-db-fun.sente-functions/sente-functions) :model (ig/ref :model/article-sql)} :reitit-db-fun.sente-functions/sente-functions {:sente-state (ig/ref :reitit-db-fun.sente/sente) :model (ig/ref :model/article-sql)} :model/article-sql {:datasource (ig/ref :storage/sql)} :adapter/aleph {:port 8080 :handler (ig/ref :app/handler)} :storage/sql {:conn-options {:jdbc-url "jdbc:sqlite:database.sqlite"} :migrations-dir "migrations"}}) (defn wrap-keys [keys-to-wrap] (fn [handler] (fn [request] (handler (merge request keys-to-wrap))))) (defn get-article-handler [{:keys [model path-params]}] (println "DEBUG:" (pr-str path-params)) ;; TODO proper coercion {:body (reitit-db-fun.model/get-article model (:article-id path-params))}) (defn get-articles-handler [{:keys [model]}] {:body (reitit-db-fun.model/get-articles model)}) (defn update-article-handler [{:keys [model body-params sente-functions]}] (let [datoms (reitit-db-fun.model/update-article model body-params)] (sente-fn/send-datoms-to-all-clients sente-functions datoms) {:body "Updated"})) (defn get-app-handler [{:keys [keys-to-wrap sente sente-functions]}] (ring/ring-handler (ring/router [ ["/api" ["/articles" {:get get-articles-handler}] ["/article" {:post update-article-handler}] ["/article/:article-id" {:get get-article-handler}] ["/ping" {:get {:handler (fn [req] {:status 200 :body {:message "pong" :request (pr-str req)}})}}] ["/status" {:get {:handler (fn [req] {:status 200 :body {:message "status" :model (pr-str (:model req))}})}}]] ;; Sente ["/chsk" {:get {:handler (:ring-ajax-get-or-ws-handshake sente)} :post {:handler (:ring-ajax-post sente)}}]] ;; router data affecting all routes {:data {:muuntaja m/instance :middleware [ ring.middleware.session/wrap-session reitit.ring.middleware.parameters/parameters-middleware ring.middleware.keyword-params/wrap-keyword-params muuntaja/format-middleware muuntaja/format-response-middleware (wrap-keys keys-to-wrap) ]}}) (ring/routes (ring/create-resource-handler {:path "/"}) (ring/create-default-handler)))) (defonce main-system (atom nil)) (defmethod ig/init-key :adapter/aleph [key {:keys [handler port]}] (log/info "Starting" key) (http/start-server handler {:port port})) (defmethod ig/halt-key! :adapter/aleph [key server] (log/info "Stopping" key) (.close server)) (defmethod ig/init-key :app/handler [key {:keys [keys-to-wrap sente]}] (log/info "Starting" key) (get-app-handler {:keys-to-wrap keys-to-wrap :sente sente})) (defn start-system [system-atom config] (log/info "Starting system") (let [system @system-atom] (when-not system (ig/load-namespaces config) (reset! system-atom (ig/init config))))) (defn stop-system [system-atom] (log/info "Stopping system") (let [system @system-atom] (when system (reset! system-atom (ig/halt! system))))) (defn -main [& args] (log/debug "Server starting...") (start-system main-system config) (.addShutdownHook (Runtime/getRuntime) (Thread. #(stop-system main-system)))) (defn restart-system [] (stop-system main-system) (start-system main-system config)) (comment ;; przygotowuję dane. ;; Przykładowe adresy (let [datasource (:storage/sql @main-system) query (sql/format {:insert-into [:address] :columns [:street :city] :values [["Wróbla" "Puławy"] ["Kołłątaja" "Puławy"] ["Jaworowa" "Puławy"] ["Prusa" "Puławy"]]} {:pretty true})] (->> (jdbc/execute! datasource query))) ;; przykładowi userzy (let [datasource (:storage/sql @main-system) addresses (->> {:select :* :from :address} sql/format (jdbc/execute! datasource) (mapv :address/id)) query (sql/format {:insert-into [:user] :columns [:name :address] :values [["Wacław" (rand-nth addresses)] ["PI:NAME:<NAME>END_PI" (rand-nth addresses)] ["Ewa" (rand-nth addresses)] ["PI:NAME:<NAME>END_PI" (rand-nth addresses)] ["SzPI:NAME:<NAME>END_PIepan" (rand-nth addresses)]]} {:pretty true})] (->> (jdbc/execute! datasource query))) ;; tworzę artykuły, tym razem poprzez api (let [datasource (:storage/sql @main-system) authors (->> {:select :* :from :user} sql/format (jdbc/execute! datasource) (mapv :user/id)) app (:app/handler @main-system)] (doseq [idx (range 2)] (app {:request-method :post :uri "/api/article" :body-params {:article/title (str "Test-" (inc idx)) :article/body (str "Treść artykułu " (inc idx)) :article/author (rand-nth authors)}}))) ;; sprawdzam pojedynczy artykuł (-> ((:app/handler @main-system) {:request-method :get :uri "/api/article/3000001"}) (update :body slurp)) ;; aktualizacja danych (-> ((:app/handler @main-system) {:request-method :post :uri "/api/article" :body-params {:article/id "3000002" :article/title "Title zmieniony 2" :article/body "Treść po zmiania" :article/address "2000001" :article/author "pkoza"}}) (update :body slurp)) ;; wszystkie arty (-> ((:app/handler @main-system) {:request-method :get :uri "/api/articles"} :body) slurp) ;; Baza SQL na Datomy! (def initial-datoms (let [datasource (:storage/sql @main-system) query (sql/format {:select [:article/* :address/* :user/*] :from [:article :address :user] :where [:and [:= :article/author :user/id] [:= :user/address :address/id] ] :limit 20})] (->> (jdbc/execute! datasource query) datom/resultset-into-datoms))) (let [datasource (:storage/sql @main-system) query (sql/format {:select [:article/*] :from [:article] :where [:= :article/id 3000015] :limit 20})] (->> (jdbc/execute! datasource query) datom/resultset-into-datoms)) ;; Datascript test db (def test-db (db/init-db (mapv #(apply d/datom %) initial-datoms))) (d/q '[:find (pull ?e [* {:article/author [:user/name {:user/address [*]}]}]) :where [?e :article/id _]] test-db) ;; test pojedynczego arta (let [model (:model/article-sql @main-system) datoms (reitit-db-fun.model/get-articles-datoms model) sente-state (:reitit-db-fun.sente/sente @main-system) chsk-send! (:chsk-send! sente-state) client (-> sente-state :connected-uids deref :any first)] (log/info :sending-datoms-to client) (chsk-send! client [:datoms/save! datoms])) (let [sente-state (:reitit-db-fun.sente/sente @main-system) clients (-> sente-state :connected-uids)] @clients) (do (stop-system main-system) (start-system main-system config)) (-main) )
[ { "context": " [k nil])) @config*)))\n\n(def localstore-key \"logger-config\")\n\n(add-watch config* ::logger-config (fn [_k _r ", "end": 863, "score": 0.977404773235321, "start": 850, "tag": "KEY", "value": "logger-config" } ]
src/lib/log.cljs
milelo/yetipad-app
2
(ns lib.log (:require [cljs.core.async :as async :refer [put! chan]] [cljs.reader :refer [read-string]] [cljs.pprint :refer [pprint]] [clojure.data :refer [diff]] ["localforage" :as local-forage] )) (def log-levels [:default :trace :debug :info :warn :error :fatal]) (def base-default-config {:default-level :trace :console-enable? nil ;default to true :buffer-enable? nil ;default to true - trace to buffer }) (defonce ref-time* (atom (js/Date.now))) (defonce loggers* (atom {})) (defonce config* (atom base-default-config)) (defn default-config [] (into base-default-config (keep (fn [[k v]] (when (and (symbol? k) v) [k nil])) @config*))) (def localstore-key "logger-config") (add-watch config* ::logger-config (fn [_k _r o n] (when (not= o n) (.setItem local-forage localstore-key (pr-str (into {} (filter second n))) (fn [err] (when err (js/console.error err)) ))))) (defn pprint-out [object] (with-out-str (pprint object))) (defn pprintl "pprint for use as log argument. Will only be evaluated when rendering log." [o] #(str \newline (pprint-out o))) (defn trace-diff [ma a mb b & [{:keys [include-match include-both]}]] (fn [] (let [[a b both] (diff a b)] (if (or a b) (str "\nDiff " ma \newline (pprint-out a) "Diff " mb \newline (pprint-out b) (when include-both (str "both:" \newline (pprint-out both)))) (str "Diff match: " ma \space mb (when (or include-match) (str "both:" \newline (pprint-out both))) ))))) (defn- error? [x] ;ExceptionInfo is also an error! (instance? js/Error x)) (defn- js-apply [f target args] (.apply f target (to-array args))) (defn arg-to-str [arg] (cond (string? arg) arg (error? arg) arg (fn? arg) (arg) :default (pr-str arg))) (defn- print-to-console! [level package method time args] ;only error log source-map stack traces, alternatively use stack fn. (let [args (concat [time level package] args)] (js-apply method js/console (map arg-to-str args)) (when-let [cause (ex-cause (last args))] (.call method js/console "cause: " cause)) )) (defonce <logger (chan (async/sliding-buffer 30))) (defn- trace-to-channel! [level package time args] (put! <logger {:package package :time time :args args :level level })) (defn- configure-logger! [logger* package level {:keys [console-enable? buffer-enable?]}] (let [console-enable? (or console-enable? true) buffer-enable? (or buffer-enable? true) level-tracers (fn [level method] [(when buffer-enable? (partial trace-to-channel! level package)) (when console-enable? (partial print-to-console! (name level) (name package) method)) ]) tracers {:trace (level-tracers :trace (.-log js/console)) :debug (level-tracers :debug (.-debug js/console)) :info (level-tracers :info (.-info js/console)) :warn (level-tracers :warn (.-warn js/console)) :error (level-tracers :error (.-error js/console)) :fatal (level-tracers :fatal (.-error js/console)) }] (reset! logger* (case level :trace tracers :debug (dissoc tracers :trace) :info (dissoc tracers :trace :debug) :warn (dissoc tracers :trace :debug :info) :error (dissoc tracers :trace :debug :info :warn) :fatal (dissoc tracers :trace :debug :info :warn :error) )) )) (defn- reconfigure-loggers! [config] (doseq [[option level] config] (when-let [logger* (get @loggers* option)] ;(js/console.log ::set-config! package level) (configure-logger! logger* option (or level (:default-level config)) config)))) (.getItem local-forage localstore-key (fn [err v] (if err (js/console.error err) (let [config-changes (read-string v) config (swap! config* merge config-changes) ] (js/console.info (str ::localstore-init-log) (pr-str config-changes)) (reconfigure-loggers! config) )))) (defn set-config! [config-changes] (let [config (swap! config* merge (into {} (for [[package level :as e] config-changes] (if (= level :default) [package nil] e))))] (reconfigure-loggers! config) )) (defn logger [package] (let [logger* (atom {}) [_ package-config :as entry] (find @config* package) package-config (or package-config (get @config* :default-level)) ] (swap! loggers* assoc package logger*) (when-not entry ;ensure package is registered (swap! config* assoc package nil)) (configure-logger! logger* package package-config @config*) logger*)) (defn- trace! [logger* level args] (let [[l1 l2] (get @logger* level) time (when (or l1 l2) (- (js/Date.now) @ref-time*)) ] (when l1 (l1 time args)) (when l2 (l2 time args)) )) (defn trace [logger* & args] ((partial trace! logger* :trace) args)) (defn debug [logger* & args] ((partial trace! logger* :debug) args)) (defn info [logger* & args] ((partial trace! logger* :info) args)) (defn warn [logger* & args] ((partial trace! logger* :warn) args)) (defn error [logger* & args] ((partial trace! logger* :error) args)) (defn fatal [logger* & args] ((partial trace! logger* :fatal) args))
78477
(ns lib.log (:require [cljs.core.async :as async :refer [put! chan]] [cljs.reader :refer [read-string]] [cljs.pprint :refer [pprint]] [clojure.data :refer [diff]] ["localforage" :as local-forage] )) (def log-levels [:default :trace :debug :info :warn :error :fatal]) (def base-default-config {:default-level :trace :console-enable? nil ;default to true :buffer-enable? nil ;default to true - trace to buffer }) (defonce ref-time* (atom (js/Date.now))) (defonce loggers* (atom {})) (defonce config* (atom base-default-config)) (defn default-config [] (into base-default-config (keep (fn [[k v]] (when (and (symbol? k) v) [k nil])) @config*))) (def localstore-key "<KEY>") (add-watch config* ::logger-config (fn [_k _r o n] (when (not= o n) (.setItem local-forage localstore-key (pr-str (into {} (filter second n))) (fn [err] (when err (js/console.error err)) ))))) (defn pprint-out [object] (with-out-str (pprint object))) (defn pprintl "pprint for use as log argument. Will only be evaluated when rendering log." [o] #(str \newline (pprint-out o))) (defn trace-diff [ma a mb b & [{:keys [include-match include-both]}]] (fn [] (let [[a b both] (diff a b)] (if (or a b) (str "\nDiff " ma \newline (pprint-out a) "Diff " mb \newline (pprint-out b) (when include-both (str "both:" \newline (pprint-out both)))) (str "Diff match: " ma \space mb (when (or include-match) (str "both:" \newline (pprint-out both))) ))))) (defn- error? [x] ;ExceptionInfo is also an error! (instance? js/Error x)) (defn- js-apply [f target args] (.apply f target (to-array args))) (defn arg-to-str [arg] (cond (string? arg) arg (error? arg) arg (fn? arg) (arg) :default (pr-str arg))) (defn- print-to-console! [level package method time args] ;only error log source-map stack traces, alternatively use stack fn. (let [args (concat [time level package] args)] (js-apply method js/console (map arg-to-str args)) (when-let [cause (ex-cause (last args))] (.call method js/console "cause: " cause)) )) (defonce <logger (chan (async/sliding-buffer 30))) (defn- trace-to-channel! [level package time args] (put! <logger {:package package :time time :args args :level level })) (defn- configure-logger! [logger* package level {:keys [console-enable? buffer-enable?]}] (let [console-enable? (or console-enable? true) buffer-enable? (or buffer-enable? true) level-tracers (fn [level method] [(when buffer-enable? (partial trace-to-channel! level package)) (when console-enable? (partial print-to-console! (name level) (name package) method)) ]) tracers {:trace (level-tracers :trace (.-log js/console)) :debug (level-tracers :debug (.-debug js/console)) :info (level-tracers :info (.-info js/console)) :warn (level-tracers :warn (.-warn js/console)) :error (level-tracers :error (.-error js/console)) :fatal (level-tracers :fatal (.-error js/console)) }] (reset! logger* (case level :trace tracers :debug (dissoc tracers :trace) :info (dissoc tracers :trace :debug) :warn (dissoc tracers :trace :debug :info) :error (dissoc tracers :trace :debug :info :warn) :fatal (dissoc tracers :trace :debug :info :warn :error) )) )) (defn- reconfigure-loggers! [config] (doseq [[option level] config] (when-let [logger* (get @loggers* option)] ;(js/console.log ::set-config! package level) (configure-logger! logger* option (or level (:default-level config)) config)))) (.getItem local-forage localstore-key (fn [err v] (if err (js/console.error err) (let [config-changes (read-string v) config (swap! config* merge config-changes) ] (js/console.info (str ::localstore-init-log) (pr-str config-changes)) (reconfigure-loggers! config) )))) (defn set-config! [config-changes] (let [config (swap! config* merge (into {} (for [[package level :as e] config-changes] (if (= level :default) [package nil] e))))] (reconfigure-loggers! config) )) (defn logger [package] (let [logger* (atom {}) [_ package-config :as entry] (find @config* package) package-config (or package-config (get @config* :default-level)) ] (swap! loggers* assoc package logger*) (when-not entry ;ensure package is registered (swap! config* assoc package nil)) (configure-logger! logger* package package-config @config*) logger*)) (defn- trace! [logger* level args] (let [[l1 l2] (get @logger* level) time (when (or l1 l2) (- (js/Date.now) @ref-time*)) ] (when l1 (l1 time args)) (when l2 (l2 time args)) )) (defn trace [logger* & args] ((partial trace! logger* :trace) args)) (defn debug [logger* & args] ((partial trace! logger* :debug) args)) (defn info [logger* & args] ((partial trace! logger* :info) args)) (defn warn [logger* & args] ((partial trace! logger* :warn) args)) (defn error [logger* & args] ((partial trace! logger* :error) args)) (defn fatal [logger* & args] ((partial trace! logger* :fatal) args))
true
(ns lib.log (:require [cljs.core.async :as async :refer [put! chan]] [cljs.reader :refer [read-string]] [cljs.pprint :refer [pprint]] [clojure.data :refer [diff]] ["localforage" :as local-forage] )) (def log-levels [:default :trace :debug :info :warn :error :fatal]) (def base-default-config {:default-level :trace :console-enable? nil ;default to true :buffer-enable? nil ;default to true - trace to buffer }) (defonce ref-time* (atom (js/Date.now))) (defonce loggers* (atom {})) (defonce config* (atom base-default-config)) (defn default-config [] (into base-default-config (keep (fn [[k v]] (when (and (symbol? k) v) [k nil])) @config*))) (def localstore-key "PI:KEY:<KEY>END_PI") (add-watch config* ::logger-config (fn [_k _r o n] (when (not= o n) (.setItem local-forage localstore-key (pr-str (into {} (filter second n))) (fn [err] (when err (js/console.error err)) ))))) (defn pprint-out [object] (with-out-str (pprint object))) (defn pprintl "pprint for use as log argument. Will only be evaluated when rendering log." [o] #(str \newline (pprint-out o))) (defn trace-diff [ma a mb b & [{:keys [include-match include-both]}]] (fn [] (let [[a b both] (diff a b)] (if (or a b) (str "\nDiff " ma \newline (pprint-out a) "Diff " mb \newline (pprint-out b) (when include-both (str "both:" \newline (pprint-out both)))) (str "Diff match: " ma \space mb (when (or include-match) (str "both:" \newline (pprint-out both))) ))))) (defn- error? [x] ;ExceptionInfo is also an error! (instance? js/Error x)) (defn- js-apply [f target args] (.apply f target (to-array args))) (defn arg-to-str [arg] (cond (string? arg) arg (error? arg) arg (fn? arg) (arg) :default (pr-str arg))) (defn- print-to-console! [level package method time args] ;only error log source-map stack traces, alternatively use stack fn. (let [args (concat [time level package] args)] (js-apply method js/console (map arg-to-str args)) (when-let [cause (ex-cause (last args))] (.call method js/console "cause: " cause)) )) (defonce <logger (chan (async/sliding-buffer 30))) (defn- trace-to-channel! [level package time args] (put! <logger {:package package :time time :args args :level level })) (defn- configure-logger! [logger* package level {:keys [console-enable? buffer-enable?]}] (let [console-enable? (or console-enable? true) buffer-enable? (or buffer-enable? true) level-tracers (fn [level method] [(when buffer-enable? (partial trace-to-channel! level package)) (when console-enable? (partial print-to-console! (name level) (name package) method)) ]) tracers {:trace (level-tracers :trace (.-log js/console)) :debug (level-tracers :debug (.-debug js/console)) :info (level-tracers :info (.-info js/console)) :warn (level-tracers :warn (.-warn js/console)) :error (level-tracers :error (.-error js/console)) :fatal (level-tracers :fatal (.-error js/console)) }] (reset! logger* (case level :trace tracers :debug (dissoc tracers :trace) :info (dissoc tracers :trace :debug) :warn (dissoc tracers :trace :debug :info) :error (dissoc tracers :trace :debug :info :warn) :fatal (dissoc tracers :trace :debug :info :warn :error) )) )) (defn- reconfigure-loggers! [config] (doseq [[option level] config] (when-let [logger* (get @loggers* option)] ;(js/console.log ::set-config! package level) (configure-logger! logger* option (or level (:default-level config)) config)))) (.getItem local-forage localstore-key (fn [err v] (if err (js/console.error err) (let [config-changes (read-string v) config (swap! config* merge config-changes) ] (js/console.info (str ::localstore-init-log) (pr-str config-changes)) (reconfigure-loggers! config) )))) (defn set-config! [config-changes] (let [config (swap! config* merge (into {} (for [[package level :as e] config-changes] (if (= level :default) [package nil] e))))] (reconfigure-loggers! config) )) (defn logger [package] (let [logger* (atom {}) [_ package-config :as entry] (find @config* package) package-config (or package-config (get @config* :default-level)) ] (swap! loggers* assoc package logger*) (when-not entry ;ensure package is registered (swap! config* assoc package nil)) (configure-logger! logger* package package-config @config*) logger*)) (defn- trace! [logger* level args] (let [[l1 l2] (get @logger* level) time (when (or l1 l2) (- (js/Date.now) @ref-time*)) ] (when l1 (l1 time args)) (when l2 (l2 time args)) )) (defn trace [logger* & args] ((partial trace! logger* :trace) args)) (defn debug [logger* & args] ((partial trace! logger* :debug) args)) (defn info [logger* & args] ((partial trace! logger* :info) args)) (defn warn [logger* & args] ((partial trace! logger* :warn) args)) (defn error [logger* & args] ((partial trace! logger* :error) args)) (defn fatal [logger* & args] ((partial trace! logger* :fatal) args))
[ { "context": " {\"example\" {:elements [{:type :citation :author \"Chris\"}]}}}\n \"example\")\n => {:articles {\"example\" {:", "end": 2064, "score": 0.9995005130767822, "start": 2059, "tag": "NAME", "value": "Chris" }, { "context": " :citations [{:type :citation, :author \"Chris\"}]}}})\n\n;;(lucid.unit/import)\n", "end": 2199, "score": 0.9995870590209961, "start": 2194, "tag": "NAME", "value": "Chris" } ]
test/lucid/publish/collect/base_test.clj
willcohen/lucidity
3
(ns lucid.publish.collect.base-test (:use hara.test) (:require [lucid.publish.collect.base :refer :all])) ^{:refer lucid.publish.collect.base/collect-namespaces :added "1.2"} (fact "combines `:ns-form` directives into a namespace map for easy referral" (collect-namespaces {:articles {"example" {:elements [{:type :ns-form :ns 'clojure.core}]}}} "example") => '{:articles {"example" {:elements () :meta {}}} :namespaces {clojure.core {:type :ns-form :ns clojure.core}}}) ^{:refer lucid.publish.collect.base/collect-article :added "1.2"} (fact "shunts `:article` directives into a seperate `:meta` section" (collect-article-metas {:articles {"example" {:elements [{:type :article :options {:color :light}}]}}} "example") => '{:articles {"example" {:elements [] :meta {:options {:color :light}}}}}) ^{:refer lucid.publish.collect.base/collect-global :added "1.2"} (fact "shunts `:global` directives into a globally available `:meta` section" (collect-global-metas {:articles {"example" {:elements [{:type :global :options {:color :light}}]}}} "example") => {:articles {"example" {:elements ()}} :global {:options {:color :light}}}) ^{:refer lucid.publish.collect.base/collect-tags :added "1.2"} (fact "puts any element with `:tag` attribute into a seperate `:tag` set" (collect-tags {:articles {"example" {:elements [{:type :chapter :tag "hello"} {:type :chapter :tag "world"}]}}} "example") => {:articles {"example" {:elements [{:type :chapter :tag "hello"} {:type :chapter :tag "world"}] :tags #{"hello" "world"}}}}) ^{:refer lucid.publish.collect.base/collect-citations :added "1.2"} (fact "shunts `:citation` directives into a seperate `:citation` section" (collect-citations {:articles {"example" {:elements [{:type :citation :author "Chris"}]}}} "example") => {:articles {"example" {:elements [], :citations [{:type :citation, :author "Chris"}]}}}) ;;(lucid.unit/import)
87517
(ns lucid.publish.collect.base-test (:use hara.test) (:require [lucid.publish.collect.base :refer :all])) ^{:refer lucid.publish.collect.base/collect-namespaces :added "1.2"} (fact "combines `:ns-form` directives into a namespace map for easy referral" (collect-namespaces {:articles {"example" {:elements [{:type :ns-form :ns 'clojure.core}]}}} "example") => '{:articles {"example" {:elements () :meta {}}} :namespaces {clojure.core {:type :ns-form :ns clojure.core}}}) ^{:refer lucid.publish.collect.base/collect-article :added "1.2"} (fact "shunts `:article` directives into a seperate `:meta` section" (collect-article-metas {:articles {"example" {:elements [{:type :article :options {:color :light}}]}}} "example") => '{:articles {"example" {:elements [] :meta {:options {:color :light}}}}}) ^{:refer lucid.publish.collect.base/collect-global :added "1.2"} (fact "shunts `:global` directives into a globally available `:meta` section" (collect-global-metas {:articles {"example" {:elements [{:type :global :options {:color :light}}]}}} "example") => {:articles {"example" {:elements ()}} :global {:options {:color :light}}}) ^{:refer lucid.publish.collect.base/collect-tags :added "1.2"} (fact "puts any element with `:tag` attribute into a seperate `:tag` set" (collect-tags {:articles {"example" {:elements [{:type :chapter :tag "hello"} {:type :chapter :tag "world"}]}}} "example") => {:articles {"example" {:elements [{:type :chapter :tag "hello"} {:type :chapter :tag "world"}] :tags #{"hello" "world"}}}}) ^{:refer lucid.publish.collect.base/collect-citations :added "1.2"} (fact "shunts `:citation` directives into a seperate `:citation` section" (collect-citations {:articles {"example" {:elements [{:type :citation :author "<NAME>"}]}}} "example") => {:articles {"example" {:elements [], :citations [{:type :citation, :author "<NAME>"}]}}}) ;;(lucid.unit/import)
true
(ns lucid.publish.collect.base-test (:use hara.test) (:require [lucid.publish.collect.base :refer :all])) ^{:refer lucid.publish.collect.base/collect-namespaces :added "1.2"} (fact "combines `:ns-form` directives into a namespace map for easy referral" (collect-namespaces {:articles {"example" {:elements [{:type :ns-form :ns 'clojure.core}]}}} "example") => '{:articles {"example" {:elements () :meta {}}} :namespaces {clojure.core {:type :ns-form :ns clojure.core}}}) ^{:refer lucid.publish.collect.base/collect-article :added "1.2"} (fact "shunts `:article` directives into a seperate `:meta` section" (collect-article-metas {:articles {"example" {:elements [{:type :article :options {:color :light}}]}}} "example") => '{:articles {"example" {:elements [] :meta {:options {:color :light}}}}}) ^{:refer lucid.publish.collect.base/collect-global :added "1.2"} (fact "shunts `:global` directives into a globally available `:meta` section" (collect-global-metas {:articles {"example" {:elements [{:type :global :options {:color :light}}]}}} "example") => {:articles {"example" {:elements ()}} :global {:options {:color :light}}}) ^{:refer lucid.publish.collect.base/collect-tags :added "1.2"} (fact "puts any element with `:tag` attribute into a seperate `:tag` set" (collect-tags {:articles {"example" {:elements [{:type :chapter :tag "hello"} {:type :chapter :tag "world"}]}}} "example") => {:articles {"example" {:elements [{:type :chapter :tag "hello"} {:type :chapter :tag "world"}] :tags #{"hello" "world"}}}}) ^{:refer lucid.publish.collect.base/collect-citations :added "1.2"} (fact "shunts `:citation` directives into a seperate `:citation` section" (collect-citations {:articles {"example" {:elements [{:type :citation :author "PI:NAME:<NAME>END_PI"}]}}} "example") => {:articles {"example" {:elements [], :citations [{:type :citation, :author "PI:NAME:<NAME>END_PI"}]}}}) ;;(lucid.unit/import)
[ { "context": " Can be passed a email address as a string like 'foo@bar.com' or\n 'Foo Bar <foo@bar.com>', or a seq of such s", "end": 957, "score": 0.9999061822891235, "start": 946, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": "ess as a string like 'foo@bar.com' or\n 'Foo Bar <foo@bar.com>', or a seq of such strings.\"\n [to]\n (when to\n ", "end": 985, "score": 0.9999200105667114, "start": 974, "tag": "EMAIL", "value": "foo@bar.com" } ]
src/postmark/core.clj
danielcompton/clojure-postmark
5
(ns postmark.core (:require [clj-http.client :as client] [clojure.string :as string] [cheshire.core :as json])) (defn- mail-to-json "Return the JSON for the given mail map. Falsey values will be removed from the map before serializing." [mail] (->> mail (filter (comp some? val)) ;; Filter out keys with nil values (into {}) (json/generate-string))) (defn- send-to-postmark [path api-key mail] (client/post (str "https://api.postmarkapp.com/" path) {:body (mail-to-json mail) :headers {"X-Postmark-Server-Token" api-key} :content-type :json :accept :json :coerce :always :as :json})) (defn- to-string "Create a string appropriate for the to/cc/bcc fields in a Postmark call. Can be passed a email address as a string like 'foo@bar.com' or 'Foo Bar <foo@bar.com>', or a seq of such strings." [to] (when to (if (string? to) to (string/join "," to)))) (defn- no-more-than-50-recipients [to] (or (string? to) (<= (count to) 50))) (defn- mail "Send an email with the Postmark API. Remember: Postmark only lets you send to at most fifty addresses at once." [api-key default-from {:keys [to subject cc bcc from tag text html reply-to headers]}] {:pre [(no-more-than-50-recipients to)]} (send-to-postmark "email/" api-key {"From" (or from default-from) "To" (to-string to) "Subject" subject "Cc" (to-string cc) "Bcc" (to-string bcc) "Tag" tag "TextBody" text "HtmlBody" html "ReplyTo" reply-to "Headers" headers})) (defn postmark [api-key from] (partial mail api-key from)) (def postmark-test-api-key "POSTMARK_API_TEST") (defn postmark-test [from] (postmark postmark-test-api-key from)) (defn mail-with-template [api-key from {:keys [to cc bcc tag reply-to template-id template-model]}] (send-to-postmark "email/withTemplate/" api-key {"From" from "To" (to-string to) "Cc" (to-string cc) "Bcc" (to-string bcc) "Tag" tag "ReplyTo" reply-to "TemplateId" template-id "TemplateModel" template-model}))
69017
(ns postmark.core (:require [clj-http.client :as client] [clojure.string :as string] [cheshire.core :as json])) (defn- mail-to-json "Return the JSON for the given mail map. Falsey values will be removed from the map before serializing." [mail] (->> mail (filter (comp some? val)) ;; Filter out keys with nil values (into {}) (json/generate-string))) (defn- send-to-postmark [path api-key mail] (client/post (str "https://api.postmarkapp.com/" path) {:body (mail-to-json mail) :headers {"X-Postmark-Server-Token" api-key} :content-type :json :accept :json :coerce :always :as :json})) (defn- to-string "Create a string appropriate for the to/cc/bcc fields in a Postmark call. Can be passed a email address as a string like '<EMAIL>' or 'Foo Bar <<EMAIL>>', or a seq of such strings." [to] (when to (if (string? to) to (string/join "," to)))) (defn- no-more-than-50-recipients [to] (or (string? to) (<= (count to) 50))) (defn- mail "Send an email with the Postmark API. Remember: Postmark only lets you send to at most fifty addresses at once." [api-key default-from {:keys [to subject cc bcc from tag text html reply-to headers]}] {:pre [(no-more-than-50-recipients to)]} (send-to-postmark "email/" api-key {"From" (or from default-from) "To" (to-string to) "Subject" subject "Cc" (to-string cc) "Bcc" (to-string bcc) "Tag" tag "TextBody" text "HtmlBody" html "ReplyTo" reply-to "Headers" headers})) (defn postmark [api-key from] (partial mail api-key from)) (def postmark-test-api-key "POSTMARK_API_TEST") (defn postmark-test [from] (postmark postmark-test-api-key from)) (defn mail-with-template [api-key from {:keys [to cc bcc tag reply-to template-id template-model]}] (send-to-postmark "email/withTemplate/" api-key {"From" from "To" (to-string to) "Cc" (to-string cc) "Bcc" (to-string bcc) "Tag" tag "ReplyTo" reply-to "TemplateId" template-id "TemplateModel" template-model}))
true
(ns postmark.core (:require [clj-http.client :as client] [clojure.string :as string] [cheshire.core :as json])) (defn- mail-to-json "Return the JSON for the given mail map. Falsey values will be removed from the map before serializing." [mail] (->> mail (filter (comp some? val)) ;; Filter out keys with nil values (into {}) (json/generate-string))) (defn- send-to-postmark [path api-key mail] (client/post (str "https://api.postmarkapp.com/" path) {:body (mail-to-json mail) :headers {"X-Postmark-Server-Token" api-key} :content-type :json :accept :json :coerce :always :as :json})) (defn- to-string "Create a string appropriate for the to/cc/bcc fields in a Postmark call. Can be passed a email address as a string like 'PI:EMAIL:<EMAIL>END_PI' or 'Foo Bar <PI:EMAIL:<EMAIL>END_PI>', or a seq of such strings." [to] (when to (if (string? to) to (string/join "," to)))) (defn- no-more-than-50-recipients [to] (or (string? to) (<= (count to) 50))) (defn- mail "Send an email with the Postmark API. Remember: Postmark only lets you send to at most fifty addresses at once." [api-key default-from {:keys [to subject cc bcc from tag text html reply-to headers]}] {:pre [(no-more-than-50-recipients to)]} (send-to-postmark "email/" api-key {"From" (or from default-from) "To" (to-string to) "Subject" subject "Cc" (to-string cc) "Bcc" (to-string bcc) "Tag" tag "TextBody" text "HtmlBody" html "ReplyTo" reply-to "Headers" headers})) (defn postmark [api-key from] (partial mail api-key from)) (def postmark-test-api-key "POSTMARK_API_TEST") (defn postmark-test [from] (postmark postmark-test-api-key from)) (defn mail-with-template [api-key from {:keys [to cc bcc tag reply-to template-id template-model]}] (send-to-postmark "email/withTemplate/" api-key {"From" from "To" (to-string to) "Cc" (to-string cc) "Bcc" (to-string bcc) "Tag" tag "ReplyTo" reply-to "TemplateId" template-id "TemplateModel" template-model}))
[ { "context": "ine-def-structure [{:name \"foo\"\n :type ", "end": 645, "score": 0.7358850836753845, "start": 642, "tag": "NAME", "value": "foo" }, { "context": " [{:name \"bar\"\n ", "end": 1029, "score": 0.8207042217254639, "start": 1026, "tag": "NAME", "value": "bar" } ]
test/clj/lambdacd/state/core_test.clj
Mattlk13/lambdacd
705
(ns lambdacd.state.core-test (:require [clojure.test :refer :all] [shrubbery.core :refer [mock received?]] [lambdacd.state.core :as s] [lambdacd.testsupport.data :refer [some-ctx-with]] [lambdacd.state.protocols :as state-protocols])) (def some-build-number 42) (def some-step-id [0]) (def some-step-result {:foo :bat}) (def some-structure {:some :structure}) (def some-metadata {:some :metadata}) (defn ^{:display-type :container} foo [& _]) (defn bar [& _]) (def some-pipeline-def `((foo bar))) (def some-pipeline-def-structure [{:name "foo" :type :container :has-dependencies false :pipeline-structure-fallback true :step-id `(1) :children [{:name "bar" :type :step :has-dependencies false :pipeline-structure-fallback true :step-id `(1 1)}]}]) (deftest consume-step-result-update-test (testing "that calls to a StepResultUpdateConsumer will just pass through" (let [component (mock state-protocols/StepResultUpdateConsumer)] (s/consume-step-result-update (some-ctx-with :pipeline-state-component component) some-build-number some-step-id some-step-result) (is (received? component state-protocols/consume-step-result-update [some-build-number some-step-id some-step-result]))))) (deftest consume-pipeline-structure-test (testing "that calls to a PipelineStructureConsumer will just pass through" (let [component (mock state-protocols/PipelineStructureConsumer)] (s/consume-pipeline-structure (some-ctx-with :pipeline-state-component component) some-build-number some-structure) (is (received? component state-protocols/consume-pipeline-structure [some-build-number some-structure]))))) (deftest consume-build-metadata-test (testing "that calls to a BuildMetadataConsumer will just pass through" (let [component (mock state-protocols/BuildMetadataConsumer)] (s/consume-build-metadata (some-ctx-with :pipeline-state-component component) some-build-number some-metadata) (is (received? component state-protocols/consume-build-metadata [some-build-number some-metadata]))))) (deftest next-build-number-test (testing "that calls to a BuildNumberSource will just pass through" (let [component (mock state-protocols/NextBuildNumberSource)] (s/next-build-number (some-ctx-with :pipeline-state-component component)) (is (received? component state-protocols/next-build-number []))))) (deftest all-build-numbers-test (testing "that calls to QueryAllBuildNumbersSource will just pass through" (let [component (mock state-protocols/QueryAllBuildNumbersSource)] (s/all-build-numbers (some-ctx-with :pipeline-state-component component)) (is (received? component state-protocols/all-build-numbers []))))) (deftest get-step-results-test (testing "that calls to QueryStepResultSource will just pass through" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some {:step :results :status :success}}})] (is (= {:some {:step :results :status :success}} (s/get-step-results (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-step-results [1])))) (testing "that dead steps that are still active in persistence are marked as dead" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some {:step :results :status :running}}})] (is (= {:some {:step :results :status :dead}} (s/get-step-results (some-ctx-with :pipeline-state-component component :started-steps (atom #{})) 1))) (is (received? component state-protocols/get-step-results [1]))))) (deftest get-step-result-test (testing "that we can get a simple step-result" (with-redefs [s/get-step-results (constantly {[2 1] {:step :result}})] (is (= {:step :result} (s/get-step-result nil 1 [2 1])))))) (deftest get-pipeline-structure-test (testing "that calls to PipelineStructureSource will just pass through" (let [component (mock state-protocols/PipelineStructureSource {:get-pipeline-structure {:some :pipeline-structure}})] (is (= {:some :pipeline-structure} (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-pipeline-structure [1])))) (testing "that we get the current pipeline structure if the component doesn't support PipelineStructures" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some :step-results}})] (is (= some-pipeline-def-structure (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component :pipeline-def some-pipeline-def) 1))))) (testing "that we get the current pipeline structure if the component returns :fallback and annotate the structure accordingly" (let [component (mock state-protocols/PipelineStructureSource {:get-pipeline-structure :fallback})] (is (= some-pipeline-def-structure (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component :pipeline-def some-pipeline-def) 1)))))) (deftest get-pipeline-structure-test (testing "that calls to BuildMetadataSource will just pass through" (let [component (mock state-protocols/BuildMetadataSource {:get-build-metadata {:some :metadata}})] (is (= {:some :metadata} (s/get-build-metadata (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-build-metadata [1])))) (testing "that we get an empty map if the component returns :fallback" (let [component (mock state-protocols/PipelineStructureSource {:get-build-metadata :fallback})] (is (= {} (s/get-build-metadata (some-ctx-with :pipeline-state-component component) 1))))))
122955
(ns lambdacd.state.core-test (:require [clojure.test :refer :all] [shrubbery.core :refer [mock received?]] [lambdacd.state.core :as s] [lambdacd.testsupport.data :refer [some-ctx-with]] [lambdacd.state.protocols :as state-protocols])) (def some-build-number 42) (def some-step-id [0]) (def some-step-result {:foo :bat}) (def some-structure {:some :structure}) (def some-metadata {:some :metadata}) (defn ^{:display-type :container} foo [& _]) (defn bar [& _]) (def some-pipeline-def `((foo bar))) (def some-pipeline-def-structure [{:name "<NAME>" :type :container :has-dependencies false :pipeline-structure-fallback true :step-id `(1) :children [{:name "<NAME>" :type :step :has-dependencies false :pipeline-structure-fallback true :step-id `(1 1)}]}]) (deftest consume-step-result-update-test (testing "that calls to a StepResultUpdateConsumer will just pass through" (let [component (mock state-protocols/StepResultUpdateConsumer)] (s/consume-step-result-update (some-ctx-with :pipeline-state-component component) some-build-number some-step-id some-step-result) (is (received? component state-protocols/consume-step-result-update [some-build-number some-step-id some-step-result]))))) (deftest consume-pipeline-structure-test (testing "that calls to a PipelineStructureConsumer will just pass through" (let [component (mock state-protocols/PipelineStructureConsumer)] (s/consume-pipeline-structure (some-ctx-with :pipeline-state-component component) some-build-number some-structure) (is (received? component state-protocols/consume-pipeline-structure [some-build-number some-structure]))))) (deftest consume-build-metadata-test (testing "that calls to a BuildMetadataConsumer will just pass through" (let [component (mock state-protocols/BuildMetadataConsumer)] (s/consume-build-metadata (some-ctx-with :pipeline-state-component component) some-build-number some-metadata) (is (received? component state-protocols/consume-build-metadata [some-build-number some-metadata]))))) (deftest next-build-number-test (testing "that calls to a BuildNumberSource will just pass through" (let [component (mock state-protocols/NextBuildNumberSource)] (s/next-build-number (some-ctx-with :pipeline-state-component component)) (is (received? component state-protocols/next-build-number []))))) (deftest all-build-numbers-test (testing "that calls to QueryAllBuildNumbersSource will just pass through" (let [component (mock state-protocols/QueryAllBuildNumbersSource)] (s/all-build-numbers (some-ctx-with :pipeline-state-component component)) (is (received? component state-protocols/all-build-numbers []))))) (deftest get-step-results-test (testing "that calls to QueryStepResultSource will just pass through" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some {:step :results :status :success}}})] (is (= {:some {:step :results :status :success}} (s/get-step-results (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-step-results [1])))) (testing "that dead steps that are still active in persistence are marked as dead" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some {:step :results :status :running}}})] (is (= {:some {:step :results :status :dead}} (s/get-step-results (some-ctx-with :pipeline-state-component component :started-steps (atom #{})) 1))) (is (received? component state-protocols/get-step-results [1]))))) (deftest get-step-result-test (testing "that we can get a simple step-result" (with-redefs [s/get-step-results (constantly {[2 1] {:step :result}})] (is (= {:step :result} (s/get-step-result nil 1 [2 1])))))) (deftest get-pipeline-structure-test (testing "that calls to PipelineStructureSource will just pass through" (let [component (mock state-protocols/PipelineStructureSource {:get-pipeline-structure {:some :pipeline-structure}})] (is (= {:some :pipeline-structure} (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-pipeline-structure [1])))) (testing "that we get the current pipeline structure if the component doesn't support PipelineStructures" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some :step-results}})] (is (= some-pipeline-def-structure (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component :pipeline-def some-pipeline-def) 1))))) (testing "that we get the current pipeline structure if the component returns :fallback and annotate the structure accordingly" (let [component (mock state-protocols/PipelineStructureSource {:get-pipeline-structure :fallback})] (is (= some-pipeline-def-structure (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component :pipeline-def some-pipeline-def) 1)))))) (deftest get-pipeline-structure-test (testing "that calls to BuildMetadataSource will just pass through" (let [component (mock state-protocols/BuildMetadataSource {:get-build-metadata {:some :metadata}})] (is (= {:some :metadata} (s/get-build-metadata (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-build-metadata [1])))) (testing "that we get an empty map if the component returns :fallback" (let [component (mock state-protocols/PipelineStructureSource {:get-build-metadata :fallback})] (is (= {} (s/get-build-metadata (some-ctx-with :pipeline-state-component component) 1))))))
true
(ns lambdacd.state.core-test (:require [clojure.test :refer :all] [shrubbery.core :refer [mock received?]] [lambdacd.state.core :as s] [lambdacd.testsupport.data :refer [some-ctx-with]] [lambdacd.state.protocols :as state-protocols])) (def some-build-number 42) (def some-step-id [0]) (def some-step-result {:foo :bat}) (def some-structure {:some :structure}) (def some-metadata {:some :metadata}) (defn ^{:display-type :container} foo [& _]) (defn bar [& _]) (def some-pipeline-def `((foo bar))) (def some-pipeline-def-structure [{:name "PI:NAME:<NAME>END_PI" :type :container :has-dependencies false :pipeline-structure-fallback true :step-id `(1) :children [{:name "PI:NAME:<NAME>END_PI" :type :step :has-dependencies false :pipeline-structure-fallback true :step-id `(1 1)}]}]) (deftest consume-step-result-update-test (testing "that calls to a StepResultUpdateConsumer will just pass through" (let [component (mock state-protocols/StepResultUpdateConsumer)] (s/consume-step-result-update (some-ctx-with :pipeline-state-component component) some-build-number some-step-id some-step-result) (is (received? component state-protocols/consume-step-result-update [some-build-number some-step-id some-step-result]))))) (deftest consume-pipeline-structure-test (testing "that calls to a PipelineStructureConsumer will just pass through" (let [component (mock state-protocols/PipelineStructureConsumer)] (s/consume-pipeline-structure (some-ctx-with :pipeline-state-component component) some-build-number some-structure) (is (received? component state-protocols/consume-pipeline-structure [some-build-number some-structure]))))) (deftest consume-build-metadata-test (testing "that calls to a BuildMetadataConsumer will just pass through" (let [component (mock state-protocols/BuildMetadataConsumer)] (s/consume-build-metadata (some-ctx-with :pipeline-state-component component) some-build-number some-metadata) (is (received? component state-protocols/consume-build-metadata [some-build-number some-metadata]))))) (deftest next-build-number-test (testing "that calls to a BuildNumberSource will just pass through" (let [component (mock state-protocols/NextBuildNumberSource)] (s/next-build-number (some-ctx-with :pipeline-state-component component)) (is (received? component state-protocols/next-build-number []))))) (deftest all-build-numbers-test (testing "that calls to QueryAllBuildNumbersSource will just pass through" (let [component (mock state-protocols/QueryAllBuildNumbersSource)] (s/all-build-numbers (some-ctx-with :pipeline-state-component component)) (is (received? component state-protocols/all-build-numbers []))))) (deftest get-step-results-test (testing "that calls to QueryStepResultSource will just pass through" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some {:step :results :status :success}}})] (is (= {:some {:step :results :status :success}} (s/get-step-results (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-step-results [1])))) (testing "that dead steps that are still active in persistence are marked as dead" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some {:step :results :status :running}}})] (is (= {:some {:step :results :status :dead}} (s/get-step-results (some-ctx-with :pipeline-state-component component :started-steps (atom #{})) 1))) (is (received? component state-protocols/get-step-results [1]))))) (deftest get-step-result-test (testing "that we can get a simple step-result" (with-redefs [s/get-step-results (constantly {[2 1] {:step :result}})] (is (= {:step :result} (s/get-step-result nil 1 [2 1])))))) (deftest get-pipeline-structure-test (testing "that calls to PipelineStructureSource will just pass through" (let [component (mock state-protocols/PipelineStructureSource {:get-pipeline-structure {:some :pipeline-structure}})] (is (= {:some :pipeline-structure} (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-pipeline-structure [1])))) (testing "that we get the current pipeline structure if the component doesn't support PipelineStructures" (let [component (mock state-protocols/QueryStepResultsSource {:get-step-results {:some :step-results}})] (is (= some-pipeline-def-structure (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component :pipeline-def some-pipeline-def) 1))))) (testing "that we get the current pipeline structure if the component returns :fallback and annotate the structure accordingly" (let [component (mock state-protocols/PipelineStructureSource {:get-pipeline-structure :fallback})] (is (= some-pipeline-def-structure (s/get-pipeline-structure (some-ctx-with :pipeline-state-component component :pipeline-def some-pipeline-def) 1)))))) (deftest get-pipeline-structure-test (testing "that calls to BuildMetadataSource will just pass through" (let [component (mock state-protocols/BuildMetadataSource {:get-build-metadata {:some :metadata}})] (is (= {:some :metadata} (s/get-build-metadata (some-ctx-with :pipeline-state-component component) 1))) (is (received? component state-protocols/get-build-metadata [1])))) (testing "that we get an empty map if the component returns :fallback" (let [component (mock state-protocols/PipelineStructureSource {:get-build-metadata :fallback})] (is (= {} (s/get-build-metadata (some-ctx-with :pipeline-state-component component) 1))))))
[ { "context": " :args [{l \"carrots\"}]})\n;; => #{[:you \"carrots\"] [:me \"carrots\"]}\n\n(try (mapv first (api/q (api/", "end": 842, "score": 0.9585959315299988, "start": 835, "tag": "USERNAME", "value": "carrots" }, { "context": " [{l \"carrots\"}]})\n;; => #{[:you \"carrots\"] [:me \"carrots\"]}\n\n(try (mapv first (api/q (api/db node) '{:find", "end": 858, "score": 0.6703300476074219, "start": 851, "tag": "NAME", "value": "carrots" } ]
crux-dev/dev/tmt/maplistq.clj
Antonelli712/crux
1
(ns tmt.maplistq (:require [crux.api :as api])) (def opts {:crux.node/topology :crux.standalone/topology :crux.node/kv-store "crux.kv.memdb/kv" :crux.kv/db-dir "data/db-dir-1" :crux.standalone/event-log-dir "data/eventlog-1" :crux.standalone/event-log-kv-store "crux.kv.memdb/kv"}) (def node (api/start-node opts)) (api/submit-tx node [[:crux.tx/put {:crux.db/id :me :change 20 :list ["carrots" "peas" "shampoo"] :pockets/left ["lint" "change"] :pockets/right ["phone"]}] [:crux.tx/put {:crux.db/id :you :change 30 :list ["carrots" "tomatoes" "wig"] :pockets/left ["wallet" "watch"] :pockets/right ["spectacles"]}]]) (api/q (api/db node) '{:find [e l] :where [[e :list l]] :args [{l "carrots"}]}) ;; => #{[:you "carrots"] [:me "carrots"]} (try (mapv first (api/q (api/db node) '{:find [e p] :where [[e :pockets/left p] [e :change c]] :args [{p "watch"}] :order-by [[c :asc]]})) (catch IllegalArgumentException e (re-find #"Order by requires a var from :find\. unreturned var:" (.getMessage e)))) ;; => #{[:you "watch"]}
99502
(ns tmt.maplistq (:require [crux.api :as api])) (def opts {:crux.node/topology :crux.standalone/topology :crux.node/kv-store "crux.kv.memdb/kv" :crux.kv/db-dir "data/db-dir-1" :crux.standalone/event-log-dir "data/eventlog-1" :crux.standalone/event-log-kv-store "crux.kv.memdb/kv"}) (def node (api/start-node opts)) (api/submit-tx node [[:crux.tx/put {:crux.db/id :me :change 20 :list ["carrots" "peas" "shampoo"] :pockets/left ["lint" "change"] :pockets/right ["phone"]}] [:crux.tx/put {:crux.db/id :you :change 30 :list ["carrots" "tomatoes" "wig"] :pockets/left ["wallet" "watch"] :pockets/right ["spectacles"]}]]) (api/q (api/db node) '{:find [e l] :where [[e :list l]] :args [{l "carrots"}]}) ;; => #{[:you "carrots"] [:me "<NAME>"]} (try (mapv first (api/q (api/db node) '{:find [e p] :where [[e :pockets/left p] [e :change c]] :args [{p "watch"}] :order-by [[c :asc]]})) (catch IllegalArgumentException e (re-find #"Order by requires a var from :find\. unreturned var:" (.getMessage e)))) ;; => #{[:you "watch"]}
true
(ns tmt.maplistq (:require [crux.api :as api])) (def opts {:crux.node/topology :crux.standalone/topology :crux.node/kv-store "crux.kv.memdb/kv" :crux.kv/db-dir "data/db-dir-1" :crux.standalone/event-log-dir "data/eventlog-1" :crux.standalone/event-log-kv-store "crux.kv.memdb/kv"}) (def node (api/start-node opts)) (api/submit-tx node [[:crux.tx/put {:crux.db/id :me :change 20 :list ["carrots" "peas" "shampoo"] :pockets/left ["lint" "change"] :pockets/right ["phone"]}] [:crux.tx/put {:crux.db/id :you :change 30 :list ["carrots" "tomatoes" "wig"] :pockets/left ["wallet" "watch"] :pockets/right ["spectacles"]}]]) (api/q (api/db node) '{:find [e l] :where [[e :list l]] :args [{l "carrots"}]}) ;; => #{[:you "carrots"] [:me "PI:NAME:<NAME>END_PI"]} (try (mapv first (api/q (api/db node) '{:find [e p] :where [[e :pockets/left p] [e :change c]] :args [{p "watch"}] :order-by [[c :asc]]})) (catch IllegalArgumentException e (re-find #"Order by requires a var from :find\. unreturned var:" (.getMessage e)))) ;; => #{[:you "watch"]}
[ { "context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright 2015 Xebia B.V.\n;\n; Licensed under the Apache License, Version 2", "end": 107, "score": 0.9609068036079407, "start": 98, "tag": "NAME", "value": "Xebia B.V" } ]
src/test/clojure/com/xebia/visualreview/service/middleware_test.clj
andstepanuk/VisualReview
290
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 Xebia B.V. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.service.middleware-test (:require [clojure.test :refer :all] [com.xebia.visualreview.service.service-util :as service-util] [com.xebia.visualreview.test-util :refer :all] [com.xebia.visualreview.config :as config] [clojure.tools.logging :as log] [com.xebia.visualreview.middleware :as middleware]) (:import (java.sql SQLException) (java.io StringReader) (clojure.tools.logging.impl Logger LoggerFactory))) (deftest wrap-exception (testing "wraps generic exceptions and outputs it as a 500 response" (is (= {:status 500 :headers {} :body "Internal error occured"} ((middleware/wrap-exception (fn [_] (throw (new Exception "my message")))) {})) "Converts unhandled exceptions to a 500 response") (is (= {:status 500 :headers {} :body "Internal database error occured"} ((middleware/wrap-exception (fn [_] (throw (new SQLException "my sql message")))) {})) "Converts unhandled database exceptions to a 500 response") (is (= {:status 500 :headers {} :body "Internal service error occured"} ((middleware/wrap-exception (fn [_] (service-util/throw-service-exception "my message" 1234))) {})) "Converts unhandled service exceptions to a 500 response"))) (defn logs-collector [atm] (fn [& args] (let [args-map {:level (nth args 1) :message (last args)}] (swap! atm #(conj % args-map))))) (def mock-logger (reify Logger (enabled? [_ _] true) Object (toString [_] "fake-logger"))) (def mock-logger-factory (reify LoggerFactory (get-logger [_ logger-ns] mock-logger))) (defn setup-mock-logger [logging-config-enabled handler-response body] (binding [log/*logger-factory* mock-logger-factory] (let [log*-args (atom [])] (with-redefs [log/log* (logs-collector log*-args) config/env {:enable-http-logging logging-config-enabled}] (let [handler (fn [_] handler-response) logger (middleware/http-logger handler)] (body logger log*-args)))))) (deftest http-logger (testing "Logs request and response headers and body when enabled" (setup-mock-logger true {:headers {:headera "valuea" :headerb "valueb"} :body "response body"} (fn [logger log-args] (is (= {:level :info :message "HTTP logging enabled"} (nth @log-args 0)) "Should log that HTTP logging has been enabled") (logger {:uri "someUri" :body (StringReader. "someBody") :method " someMethod " :content-type " someContentType " :headers {:header1 " value1 " :header2 " value2 "}}) (is (= 3 (count @log-args))) (is (= {:level :info :message (str "Request: \n" "# uri: someUri\n" "# method: \n" "# content-type: someContentType \n" "# headers: \n" "header2: value2 \n" "header1: value1 \n" "# body: \n" "someBody")} (nth @log-args 1)) "Should log request headers and body") (is (= {:level :info :message (str "Response: \n" "# headers: \n" "headera: valuea\n" "headerb: valueb\n" "# body: \n" "response body\n")} (nth @log-args 2)) "Should log response headers and body")))) (testing "Does not logs request and response headers and body when disabled" (setup-mock-logger false {:headers {:headera "valuea" :headerb "valueb"} :body "response body"} (fn [logger log-args] (is (= 0 (count @log-args))) (logger {:uri "someUri" :body (StringReader. "someBody") :method " someMethod " :content-type " someContentType " :headers {:header1 " value1 " :header2 " value2 "}}) (is (= 0 (count @log-args)))))))
86924
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 <NAME>. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.service.middleware-test (:require [clojure.test :refer :all] [com.xebia.visualreview.service.service-util :as service-util] [com.xebia.visualreview.test-util :refer :all] [com.xebia.visualreview.config :as config] [clojure.tools.logging :as log] [com.xebia.visualreview.middleware :as middleware]) (:import (java.sql SQLException) (java.io StringReader) (clojure.tools.logging.impl Logger LoggerFactory))) (deftest wrap-exception (testing "wraps generic exceptions and outputs it as a 500 response" (is (= {:status 500 :headers {} :body "Internal error occured"} ((middleware/wrap-exception (fn [_] (throw (new Exception "my message")))) {})) "Converts unhandled exceptions to a 500 response") (is (= {:status 500 :headers {} :body "Internal database error occured"} ((middleware/wrap-exception (fn [_] (throw (new SQLException "my sql message")))) {})) "Converts unhandled database exceptions to a 500 response") (is (= {:status 500 :headers {} :body "Internal service error occured"} ((middleware/wrap-exception (fn [_] (service-util/throw-service-exception "my message" 1234))) {})) "Converts unhandled service exceptions to a 500 response"))) (defn logs-collector [atm] (fn [& args] (let [args-map {:level (nth args 1) :message (last args)}] (swap! atm #(conj % args-map))))) (def mock-logger (reify Logger (enabled? [_ _] true) Object (toString [_] "fake-logger"))) (def mock-logger-factory (reify LoggerFactory (get-logger [_ logger-ns] mock-logger))) (defn setup-mock-logger [logging-config-enabled handler-response body] (binding [log/*logger-factory* mock-logger-factory] (let [log*-args (atom [])] (with-redefs [log/log* (logs-collector log*-args) config/env {:enable-http-logging logging-config-enabled}] (let [handler (fn [_] handler-response) logger (middleware/http-logger handler)] (body logger log*-args)))))) (deftest http-logger (testing "Logs request and response headers and body when enabled" (setup-mock-logger true {:headers {:headera "valuea" :headerb "valueb"} :body "response body"} (fn [logger log-args] (is (= {:level :info :message "HTTP logging enabled"} (nth @log-args 0)) "Should log that HTTP logging has been enabled") (logger {:uri "someUri" :body (StringReader. "someBody") :method " someMethod " :content-type " someContentType " :headers {:header1 " value1 " :header2 " value2 "}}) (is (= 3 (count @log-args))) (is (= {:level :info :message (str "Request: \n" "# uri: someUri\n" "# method: \n" "# content-type: someContentType \n" "# headers: \n" "header2: value2 \n" "header1: value1 \n" "# body: \n" "someBody")} (nth @log-args 1)) "Should log request headers and body") (is (= {:level :info :message (str "Response: \n" "# headers: \n" "headera: valuea\n" "headerb: valueb\n" "# body: \n" "response body\n")} (nth @log-args 2)) "Should log response headers and body")))) (testing "Does not logs request and response headers and body when disabled" (setup-mock-logger false {:headers {:headera "valuea" :headerb "valueb"} :body "response body"} (fn [logger log-args] (is (= 0 (count @log-args))) (logger {:uri "someUri" :body (StringReader. "someBody") :method " someMethod " :content-type " someContentType " :headers {:header1 " value1 " :header2 " value2 "}}) (is (= 0 (count @log-args)))))))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 PI:NAME:<NAME>END_PI. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.service.middleware-test (:require [clojure.test :refer :all] [com.xebia.visualreview.service.service-util :as service-util] [com.xebia.visualreview.test-util :refer :all] [com.xebia.visualreview.config :as config] [clojure.tools.logging :as log] [com.xebia.visualreview.middleware :as middleware]) (:import (java.sql SQLException) (java.io StringReader) (clojure.tools.logging.impl Logger LoggerFactory))) (deftest wrap-exception (testing "wraps generic exceptions and outputs it as a 500 response" (is (= {:status 500 :headers {} :body "Internal error occured"} ((middleware/wrap-exception (fn [_] (throw (new Exception "my message")))) {})) "Converts unhandled exceptions to a 500 response") (is (= {:status 500 :headers {} :body "Internal database error occured"} ((middleware/wrap-exception (fn [_] (throw (new SQLException "my sql message")))) {})) "Converts unhandled database exceptions to a 500 response") (is (= {:status 500 :headers {} :body "Internal service error occured"} ((middleware/wrap-exception (fn [_] (service-util/throw-service-exception "my message" 1234))) {})) "Converts unhandled service exceptions to a 500 response"))) (defn logs-collector [atm] (fn [& args] (let [args-map {:level (nth args 1) :message (last args)}] (swap! atm #(conj % args-map))))) (def mock-logger (reify Logger (enabled? [_ _] true) Object (toString [_] "fake-logger"))) (def mock-logger-factory (reify LoggerFactory (get-logger [_ logger-ns] mock-logger))) (defn setup-mock-logger [logging-config-enabled handler-response body] (binding [log/*logger-factory* mock-logger-factory] (let [log*-args (atom [])] (with-redefs [log/log* (logs-collector log*-args) config/env {:enable-http-logging logging-config-enabled}] (let [handler (fn [_] handler-response) logger (middleware/http-logger handler)] (body logger log*-args)))))) (deftest http-logger (testing "Logs request and response headers and body when enabled" (setup-mock-logger true {:headers {:headera "valuea" :headerb "valueb"} :body "response body"} (fn [logger log-args] (is (= {:level :info :message "HTTP logging enabled"} (nth @log-args 0)) "Should log that HTTP logging has been enabled") (logger {:uri "someUri" :body (StringReader. "someBody") :method " someMethod " :content-type " someContentType " :headers {:header1 " value1 " :header2 " value2 "}}) (is (= 3 (count @log-args))) (is (= {:level :info :message (str "Request: \n" "# uri: someUri\n" "# method: \n" "# content-type: someContentType \n" "# headers: \n" "header2: value2 \n" "header1: value1 \n" "# body: \n" "someBody")} (nth @log-args 1)) "Should log request headers and body") (is (= {:level :info :message (str "Response: \n" "# headers: \n" "headera: valuea\n" "headerb: valueb\n" "# body: \n" "response body\n")} (nth @log-args 2)) "Should log response headers and body")))) (testing "Does not logs request and response headers and body when disabled" (setup-mock-logger false {:headers {:headera "valuea" :headerb "valueb"} :body "response body"} (fn [logger log-args] (is (= 0 (count @log-args))) (logger {:uri "someUri" :body (StringReader. "someBody") :method " someMethod " :content-type " someContentType " :headers {:header1 " value1 " :header2 " value2 "}}) (is (= 0 (count @log-args)))))))
[ { "context": "----\n\n(defn- compartment-list-start-key [{:keys [c-hash res-id]} tid start-id]\n (if start-id\n (co", "end": 2227, "score": 0.5441232919692993, "start": 2227, "tag": "KEY", "value": "" }, { "context": "tid)))\n\n\n(defn- compartment-list-cmp-key [{:keys [c-hash res-id]} tid]\n (codec/compartment-resource-type-key ", "end": 2455, "score": 0.7248823642730713, "start": 2445, "tag": "KEY", "value": "c-hash res" }, { "context": "efn- compartment-list-cmp-key [{:keys [c-hash res-id]} tid]\n (codec/compartment-resource-type-key c-h", "end": 2458, "score": 0.7334950566291809, "start": 2456, "tag": "KEY", "value": "id" } ]
modules/db/src/blaze/db/impl/index.clj
EmteZogaf/blaze
0
(ns blaze.db.impl.index (:require [blaze.coll.core :as coll] [blaze.db.impl.bytes :as bytes] [blaze.db.impl.codec :as codec] [blaze.db.impl.index.resource :as resource] [blaze.db.impl.index.resource-as-of :as resource-as-of] [blaze.db.impl.iterators :as i] [blaze.db.impl.search-param :as search-param] [blaze.db.kv :as kv] [taoensso.nippy :as nippy]) (:import [blaze.db.impl.index.resource Hash] [clojure.lang IReduceInit])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn tx [kv-store t] (resource/tx kv-store t)) (defn load-resource-content [kv-store ^Hash hash] (some-> (kv/get kv-store :resource-index (.hash hash)) (nippy/fast-thaw))) (defn- t-by-instant* [iter instant] (kv/seek! iter (codec/tx-by-instant-key instant)) (when (kv/valid? iter) (codec/decode-t (kv/value iter)))) (defn t-by-instant [snapshot instant] (with-open [iter (kv/new-iterator snapshot :t-by-instant-index)] (t-by-instant* iter instant))) ;; ---- Type-Level Functions ------------------------------------------------ (defn- other-clauses-filter [snapshot tid clauses] (if (seq clauses) (filter (fn [resource] (let [id (codec/id-bytes (:id resource)) hash (resource/hash resource)] (loop [[[search-param modifier values] & clauses] clauses] (if search-param (when (search-param/matches? search-param snapshot tid id hash modifier values) (recur clauses)) resource))))) identity)) (defn type-query [node snapshot svri rsvi raoi tid clauses t] (let [[[search-param modifier values] & other-clauses] clauses] (coll/eduction (other-clauses-filter snapshot tid other-clauses) (search-param/resources search-param node snapshot svri rsvi raoi tid modifier values t)))) ;; ---- System-Level Functions ------------------------------------------------ (defn system-query [_ _ _ _ _ _ _] ;; TODO: implement []) ;; ---- Compartment-Level Functions ------------------------------------------- (defn- compartment-list-start-key [{:keys [c-hash res-id]} tid start-id] (if start-id (codec/compartment-resource-type-key c-hash res-id tid start-id) (codec/compartment-resource-type-key c-hash res-id tid))) (defn- compartment-list-cmp-key [{:keys [c-hash res-id]} tid] (codec/compartment-resource-type-key c-hash res-id tid)) (defn compartment-list "Returns a reducible collection of all resources of type with `tid` linked to `compartment` and ordered by resource id. The list starts at `start-id`. The implementation uses the :resource-type-index to obtain an iterator over all resources of the type with `tid` ever known (independent from `t`). It then looks up the newest version of each resource in the :resource-as-of-index not newer then `t`." ^IReduceInit [node cri raoi compartment tid start-id t] (let [start-key (compartment-list-start-key compartment tid start-id) cmp-key (compartment-list-cmp-key compartment tid)] (coll/eduction (comp (take-while (fn [[prefix]] (bytes/= prefix cmp-key))) (map (fn [[_ id]] (resource-as-of/resource node raoi tid id t))) (remove nil?) (remove resource/deleted?)) (i/keys cri codec/decode-compartment-resource-type-key start-key)))) (defn compartment-query "Iterates over the CSV index " [node snapshot csvri raoi compartment tid clauses t] (let [[[search-param _ values] & other-clauses] clauses] (coll/eduction (other-clauses-filter snapshot tid other-clauses) (search-param/compartment-resources node search-param csvri raoi compartment tid values t))))
61423
(ns blaze.db.impl.index (:require [blaze.coll.core :as coll] [blaze.db.impl.bytes :as bytes] [blaze.db.impl.codec :as codec] [blaze.db.impl.index.resource :as resource] [blaze.db.impl.index.resource-as-of :as resource-as-of] [blaze.db.impl.iterators :as i] [blaze.db.impl.search-param :as search-param] [blaze.db.kv :as kv] [taoensso.nippy :as nippy]) (:import [blaze.db.impl.index.resource Hash] [clojure.lang IReduceInit])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn tx [kv-store t] (resource/tx kv-store t)) (defn load-resource-content [kv-store ^Hash hash] (some-> (kv/get kv-store :resource-index (.hash hash)) (nippy/fast-thaw))) (defn- t-by-instant* [iter instant] (kv/seek! iter (codec/tx-by-instant-key instant)) (when (kv/valid? iter) (codec/decode-t (kv/value iter)))) (defn t-by-instant [snapshot instant] (with-open [iter (kv/new-iterator snapshot :t-by-instant-index)] (t-by-instant* iter instant))) ;; ---- Type-Level Functions ------------------------------------------------ (defn- other-clauses-filter [snapshot tid clauses] (if (seq clauses) (filter (fn [resource] (let [id (codec/id-bytes (:id resource)) hash (resource/hash resource)] (loop [[[search-param modifier values] & clauses] clauses] (if search-param (when (search-param/matches? search-param snapshot tid id hash modifier values) (recur clauses)) resource))))) identity)) (defn type-query [node snapshot svri rsvi raoi tid clauses t] (let [[[search-param modifier values] & other-clauses] clauses] (coll/eduction (other-clauses-filter snapshot tid other-clauses) (search-param/resources search-param node snapshot svri rsvi raoi tid modifier values t)))) ;; ---- System-Level Functions ------------------------------------------------ (defn system-query [_ _ _ _ _ _ _] ;; TODO: implement []) ;; ---- Compartment-Level Functions ------------------------------------------- (defn- compartment-list-start-key [{:keys [c<KEY>-hash res-id]} tid start-id] (if start-id (codec/compartment-resource-type-key c-hash res-id tid start-id) (codec/compartment-resource-type-key c-hash res-id tid))) (defn- compartment-list-cmp-key [{:keys [<KEY>-<KEY>]} tid] (codec/compartment-resource-type-key c-hash res-id tid)) (defn compartment-list "Returns a reducible collection of all resources of type with `tid` linked to `compartment` and ordered by resource id. The list starts at `start-id`. The implementation uses the :resource-type-index to obtain an iterator over all resources of the type with `tid` ever known (independent from `t`). It then looks up the newest version of each resource in the :resource-as-of-index not newer then `t`." ^IReduceInit [node cri raoi compartment tid start-id t] (let [start-key (compartment-list-start-key compartment tid start-id) cmp-key (compartment-list-cmp-key compartment tid)] (coll/eduction (comp (take-while (fn [[prefix]] (bytes/= prefix cmp-key))) (map (fn [[_ id]] (resource-as-of/resource node raoi tid id t))) (remove nil?) (remove resource/deleted?)) (i/keys cri codec/decode-compartment-resource-type-key start-key)))) (defn compartment-query "Iterates over the CSV index " [node snapshot csvri raoi compartment tid clauses t] (let [[[search-param _ values] & other-clauses] clauses] (coll/eduction (other-clauses-filter snapshot tid other-clauses) (search-param/compartment-resources node search-param csvri raoi compartment tid values t))))
true
(ns blaze.db.impl.index (:require [blaze.coll.core :as coll] [blaze.db.impl.bytes :as bytes] [blaze.db.impl.codec :as codec] [blaze.db.impl.index.resource :as resource] [blaze.db.impl.index.resource-as-of :as resource-as-of] [blaze.db.impl.iterators :as i] [blaze.db.impl.search-param :as search-param] [blaze.db.kv :as kv] [taoensso.nippy :as nippy]) (:import [blaze.db.impl.index.resource Hash] [clojure.lang IReduceInit])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn tx [kv-store t] (resource/tx kv-store t)) (defn load-resource-content [kv-store ^Hash hash] (some-> (kv/get kv-store :resource-index (.hash hash)) (nippy/fast-thaw))) (defn- t-by-instant* [iter instant] (kv/seek! iter (codec/tx-by-instant-key instant)) (when (kv/valid? iter) (codec/decode-t (kv/value iter)))) (defn t-by-instant [snapshot instant] (with-open [iter (kv/new-iterator snapshot :t-by-instant-index)] (t-by-instant* iter instant))) ;; ---- Type-Level Functions ------------------------------------------------ (defn- other-clauses-filter [snapshot tid clauses] (if (seq clauses) (filter (fn [resource] (let [id (codec/id-bytes (:id resource)) hash (resource/hash resource)] (loop [[[search-param modifier values] & clauses] clauses] (if search-param (when (search-param/matches? search-param snapshot tid id hash modifier values) (recur clauses)) resource))))) identity)) (defn type-query [node snapshot svri rsvi raoi tid clauses t] (let [[[search-param modifier values] & other-clauses] clauses] (coll/eduction (other-clauses-filter snapshot tid other-clauses) (search-param/resources search-param node snapshot svri rsvi raoi tid modifier values t)))) ;; ---- System-Level Functions ------------------------------------------------ (defn system-query [_ _ _ _ _ _ _] ;; TODO: implement []) ;; ---- Compartment-Level Functions ------------------------------------------- (defn- compartment-list-start-key [{:keys [cPI:KEY:<KEY>END_PI-hash res-id]} tid start-id] (if start-id (codec/compartment-resource-type-key c-hash res-id tid start-id) (codec/compartment-resource-type-key c-hash res-id tid))) (defn- compartment-list-cmp-key [{:keys [PI:KEY:<KEY>END_PI-PI:KEY:<KEY>END_PI]} tid] (codec/compartment-resource-type-key c-hash res-id tid)) (defn compartment-list "Returns a reducible collection of all resources of type with `tid` linked to `compartment` and ordered by resource id. The list starts at `start-id`. The implementation uses the :resource-type-index to obtain an iterator over all resources of the type with `tid` ever known (independent from `t`). It then looks up the newest version of each resource in the :resource-as-of-index not newer then `t`." ^IReduceInit [node cri raoi compartment tid start-id t] (let [start-key (compartment-list-start-key compartment tid start-id) cmp-key (compartment-list-cmp-key compartment tid)] (coll/eduction (comp (take-while (fn [[prefix]] (bytes/= prefix cmp-key))) (map (fn [[_ id]] (resource-as-of/resource node raoi tid id t))) (remove nil?) (remove resource/deleted?)) (i/keys cri codec/decode-compartment-resource-type-key start-key)))) (defn compartment-query "Iterates over the CSV index " [node snapshot csvri raoi compartment tid clauses t] (let [[[search-param _ values] & other-clauses] clauses] (coll/eduction (other-clauses-filter snapshot tid other-clauses) (search-param/compartment-resources node search-param csvri raoi compartment tid values t))))
[ { "context": "ail-addresses user-by-md))\n :name (:full-name user-by-md)\n :org (or (:organization-nam", "end": 3710, "score": 0.44689062237739563, "start": 3706, "tag": "NAME", "value": "name" }, { "context": "addresses user-by-md))\n :name (:full-name user-by-md)\n :org (or (:organization-name (fi", "end": 3715, "score": 0.5256035327911377, "start": 3711, "tag": "NAME", "value": "user" } ]
src/metadata_tool/tools/parsers.clj
finos/metadata-tool
11
; ; Copyright 2017 Fintech Open Source Foundation ; SPDX-License-Identifier: Apache-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. ; (ns metadata-tool.tools.parsers (:require [clojure.string :as str] [clojure.pprint :as pp] [clojure.java.io :as io] [clojure.set :as set] [clojure.data.json :as json] [clojure.data.csv :as csv] [hickory.core :as html] [hickory.select :as sel] [metadata-tool.sources.confluence :as cfl] [metadata-tool.config :as cfg] [metadata-tool.sources.metadata :as md])) (def not-nil? (complement nil?)) (defn parse-string [s] (if (empty? s) "" (-> s (str/replace "&nbsp;" " ") (str/replace "\u00A0" " ") str/trim))) (defn resolve-acronym [s] (get (:acronyms (:meetings cfg/config)) s s)) (defn parse-name [s to-remove] (when-not (str/blank? s) (if (empty? to-remove) s (parse-name (str/replace s (first to-remove) "") (rest to-remove))))) (defn parse-date [title] (let [title-parsed (str/replace title "." "-") indexes (filter #(>= % 0) (keep #(str/index-of title-parsed %) (:years (:meetings cfg/config))))] (if (not-empty indexes) (first (str/split (subs title-parsed (first indexes)) #" ")) title))) (defn id-and-title [payload] {:id (:id payload) :title (:title payload) :url (:webui (:_links payload))}) (defn skip-page [page-title] (pos? (count (filter #(str/includes? (str/upper-case page-title) (str/upper-case %)) (:skip-pages (:meetings cfg/config)))))) (defn extract-full-name [element] (let [ancor (sel/select (sel/tag :a) element)] (if (empty? ancor) (let [span (sel/select (sel/descendant (sel/tag :span)) element)] (if (empty? span) (let [p (sel/select (sel/descendant (sel/tag :p)) element)] (if (empty? p) (let [any (sel/select (sel/descendant sel/any sel/any) element)] (if (empty? any) (first (:content element)) (first (:content any)))) (first (:content (first p))))) (first (:content (first span))))) (first (:content (first ancor)))))) (defn debug [x] (println "--- START DEBUG ---") (pp/pprint x) (println "--- END DEBUG ---") x) (defn row-to-user [row program activity type meeting-date] (let [raw-name (extract-full-name row) ignored-names (:ignore-names (:meetings cfg/config))] (if-let [name (resolve-acronym (parse-name (parse-string raw-name) (:remove-from-names (:meetings cfg/config))))] (if-not (contains? ignored-names (str/trim name)) (if-let [user-by-md (md/person-metadata-by-fn nil (str/trim name) nil)] { :email (first (:email-addresses user-by-md)) :name (:full-name user-by-md) :org (or (:organization-name (first (md/current-affiliations (:person-id user-by-md))))) :ghid (or (first (:github-logins user-by-md))) :program program :activity activity :type type :meeting-date meeting-date } (println "[USER NOT FOUND] " (str "'" (str/trim name) "'") "on activity" activity "date" meeting-date)))))) (defn meeting-roster [raw-table-html page-title program activity type] (let [meeting-date (parse-date page-title) table-html (str "<table>" raw-table-html "</table>") selector (sel/and (sel/class :confluenceTd) sel/first-child)] (let [table (html/as-hickory (html/parse table-html)) rows (sel/select selector table)] (map #(row-to-user % program activity type meeting-date) rows)))) (defn parse-page [page-data program activity type] (let [title (:title page-data) meeting-date (parse-date title)] (if (not (= meeting-date title)) (let [content (cfl/content (:url page-data))] (if-not (skip-page title) (do (println (str "Scanning for meeting attendance on page " (:title page-data))) (if-not (empty? content) (meeting-roster content title program activity type)))))))) (defn ids-and-titles [id] (let [children (map id-and-title (cfl/children id))] (flatten (concat children (map #(ids-and-titles (:id %)) children))))) (defn meetings-rosters [program activity type url] (println (str "Generating meeting attendance for activity " activity)) (let [page-id (cfl/page-id url) sub-pages (ids-and-titles page-id)] (flatten (keep #(parse-page % program activity type) sub-pages)))) (defn roster-to-csv [roster-data] (with-open [writer (io/writer "finos-meetings.csv")] (.write writer "email, name, org, github ID, cm_program, cm_title, cm_type, date\n") (doall (map #(.write writer (str (str/join ", " (vals %)) "\n")) ; DEBUG - Check on :name instead of :email if you want to debug output (remove #(or (nil? %) (nil? (:email %))) roster-data))) (.flush writer))) ;; Utility functions for gen-meeting-github-roster-data ;; (defn string-keys-to-symbols [map] (reduce #(assoc %1 (-> (key %2) keyword) (val %2)) {} map)) (defn csv-item-to-str [item] (if-not (empty? item) (str (str/join ", " (map #(str/trim %) item))))) (defn str-to-csv-item [s] (map #(str/trim %) (str/split s #","))) (defn contains-not [list item] (not (some #(= item %) list))) (defn get-json [path] (json/read-str (slurp path))) (defn to-json [o] (json/write-str o)) (defn get-reader [path] (io/reader path)) (defn get-writer [path] (io/writer path)) (defn read-csv [reader] (csv/read-csv reader)) (defn write-csv [writer items] (csv/write-csv writer items)) (defn has-meeting-config [] (and (.exists (io/as-file "./meeting-attendance.json")) (.exists (io/as-file "./github-finos-meetings.csv")))) (defn match-project [project data] (and (some #(= (str/lower-case (:repo data)) (str/lower-case %)) (:github-repos project)) (some #(str/includes? % (str "/" (:org data) "/")) (:github-urls project)))) (defn get-csv-delta [new-csv] (with-open [reader (io/reader "./github-finos-meetings.csv")] (let [items (set (map #(csv-item-to-str %) (csv/read-csv reader))) new-items (set (map #(csv-item-to-str (vals %)) new-csv)) exist-str (set/intersection items new-items) existing (map #(str-to-csv-item %) exist-str) missing (map #(str-to-csv-item %) (set/difference new-items exist-str))] [existing missing]))) (defn single-attendance [person project meeting-date] (if-let [email (cond (> (count (:email-addresses person)) 0) (first (:email-addresses person)) (> (count (:github-logins person)) 0) (str (first (:github-logins person)) "@users.noreply.github.com"))] {:email email :name (:full-name person) :org (or (:organization-name (first (md/current-affiliations (:person-id person))))) :ghid (or (first (:github-logins person))) :program (:program-short-name project) :activity (:activity-name project) :type (:type project) :meeting-date meeting-date})) (defn remove-existing-entries [to-remove current] (let [remove-str (set (map #(csv-item-to-str %) to-remove)) curr-str (map #(csv-item-to-str %) current) diff-str (filter #(contains-not remove-str %) curr-str)] (map #(str-to-csv-item %) diff-str)))
41411
; ; Copyright 2017 Fintech Open Source Foundation ; SPDX-License-Identifier: Apache-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. ; (ns metadata-tool.tools.parsers (:require [clojure.string :as str] [clojure.pprint :as pp] [clojure.java.io :as io] [clojure.set :as set] [clojure.data.json :as json] [clojure.data.csv :as csv] [hickory.core :as html] [hickory.select :as sel] [metadata-tool.sources.confluence :as cfl] [metadata-tool.config :as cfg] [metadata-tool.sources.metadata :as md])) (def not-nil? (complement nil?)) (defn parse-string [s] (if (empty? s) "" (-> s (str/replace "&nbsp;" " ") (str/replace "\u00A0" " ") str/trim))) (defn resolve-acronym [s] (get (:acronyms (:meetings cfg/config)) s s)) (defn parse-name [s to-remove] (when-not (str/blank? s) (if (empty? to-remove) s (parse-name (str/replace s (first to-remove) "") (rest to-remove))))) (defn parse-date [title] (let [title-parsed (str/replace title "." "-") indexes (filter #(>= % 0) (keep #(str/index-of title-parsed %) (:years (:meetings cfg/config))))] (if (not-empty indexes) (first (str/split (subs title-parsed (first indexes)) #" ")) title))) (defn id-and-title [payload] {:id (:id payload) :title (:title payload) :url (:webui (:_links payload))}) (defn skip-page [page-title] (pos? (count (filter #(str/includes? (str/upper-case page-title) (str/upper-case %)) (:skip-pages (:meetings cfg/config)))))) (defn extract-full-name [element] (let [ancor (sel/select (sel/tag :a) element)] (if (empty? ancor) (let [span (sel/select (sel/descendant (sel/tag :span)) element)] (if (empty? span) (let [p (sel/select (sel/descendant (sel/tag :p)) element)] (if (empty? p) (let [any (sel/select (sel/descendant sel/any sel/any) element)] (if (empty? any) (first (:content element)) (first (:content any)))) (first (:content (first p))))) (first (:content (first span))))) (first (:content (first ancor)))))) (defn debug [x] (println "--- START DEBUG ---") (pp/pprint x) (println "--- END DEBUG ---") x) (defn row-to-user [row program activity type meeting-date] (let [raw-name (extract-full-name row) ignored-names (:ignore-names (:meetings cfg/config))] (if-let [name (resolve-acronym (parse-name (parse-string raw-name) (:remove-from-names (:meetings cfg/config))))] (if-not (contains? ignored-names (str/trim name)) (if-let [user-by-md (md/person-metadata-by-fn nil (str/trim name) nil)] { :email (first (:email-addresses user-by-md)) :name (:full-<NAME> <NAME>-by-md) :org (or (:organization-name (first (md/current-affiliations (:person-id user-by-md))))) :ghid (or (first (:github-logins user-by-md))) :program program :activity activity :type type :meeting-date meeting-date } (println "[USER NOT FOUND] " (str "'" (str/trim name) "'") "on activity" activity "date" meeting-date)))))) (defn meeting-roster [raw-table-html page-title program activity type] (let [meeting-date (parse-date page-title) table-html (str "<table>" raw-table-html "</table>") selector (sel/and (sel/class :confluenceTd) sel/first-child)] (let [table (html/as-hickory (html/parse table-html)) rows (sel/select selector table)] (map #(row-to-user % program activity type meeting-date) rows)))) (defn parse-page [page-data program activity type] (let [title (:title page-data) meeting-date (parse-date title)] (if (not (= meeting-date title)) (let [content (cfl/content (:url page-data))] (if-not (skip-page title) (do (println (str "Scanning for meeting attendance on page " (:title page-data))) (if-not (empty? content) (meeting-roster content title program activity type)))))))) (defn ids-and-titles [id] (let [children (map id-and-title (cfl/children id))] (flatten (concat children (map #(ids-and-titles (:id %)) children))))) (defn meetings-rosters [program activity type url] (println (str "Generating meeting attendance for activity " activity)) (let [page-id (cfl/page-id url) sub-pages (ids-and-titles page-id)] (flatten (keep #(parse-page % program activity type) sub-pages)))) (defn roster-to-csv [roster-data] (with-open [writer (io/writer "finos-meetings.csv")] (.write writer "email, name, org, github ID, cm_program, cm_title, cm_type, date\n") (doall (map #(.write writer (str (str/join ", " (vals %)) "\n")) ; DEBUG - Check on :name instead of :email if you want to debug output (remove #(or (nil? %) (nil? (:email %))) roster-data))) (.flush writer))) ;; Utility functions for gen-meeting-github-roster-data ;; (defn string-keys-to-symbols [map] (reduce #(assoc %1 (-> (key %2) keyword) (val %2)) {} map)) (defn csv-item-to-str [item] (if-not (empty? item) (str (str/join ", " (map #(str/trim %) item))))) (defn str-to-csv-item [s] (map #(str/trim %) (str/split s #","))) (defn contains-not [list item] (not (some #(= item %) list))) (defn get-json [path] (json/read-str (slurp path))) (defn to-json [o] (json/write-str o)) (defn get-reader [path] (io/reader path)) (defn get-writer [path] (io/writer path)) (defn read-csv [reader] (csv/read-csv reader)) (defn write-csv [writer items] (csv/write-csv writer items)) (defn has-meeting-config [] (and (.exists (io/as-file "./meeting-attendance.json")) (.exists (io/as-file "./github-finos-meetings.csv")))) (defn match-project [project data] (and (some #(= (str/lower-case (:repo data)) (str/lower-case %)) (:github-repos project)) (some #(str/includes? % (str "/" (:org data) "/")) (:github-urls project)))) (defn get-csv-delta [new-csv] (with-open [reader (io/reader "./github-finos-meetings.csv")] (let [items (set (map #(csv-item-to-str %) (csv/read-csv reader))) new-items (set (map #(csv-item-to-str (vals %)) new-csv)) exist-str (set/intersection items new-items) existing (map #(str-to-csv-item %) exist-str) missing (map #(str-to-csv-item %) (set/difference new-items exist-str))] [existing missing]))) (defn single-attendance [person project meeting-date] (if-let [email (cond (> (count (:email-addresses person)) 0) (first (:email-addresses person)) (> (count (:github-logins person)) 0) (str (first (:github-logins person)) "@users.noreply.github.com"))] {:email email :name (:full-name person) :org (or (:organization-name (first (md/current-affiliations (:person-id person))))) :ghid (or (first (:github-logins person))) :program (:program-short-name project) :activity (:activity-name project) :type (:type project) :meeting-date meeting-date})) (defn remove-existing-entries [to-remove current] (let [remove-str (set (map #(csv-item-to-str %) to-remove)) curr-str (map #(csv-item-to-str %) current) diff-str (filter #(contains-not remove-str %) curr-str)] (map #(str-to-csv-item %) diff-str)))
true
; ; Copyright 2017 Fintech Open Source Foundation ; SPDX-License-Identifier: Apache-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. ; (ns metadata-tool.tools.parsers (:require [clojure.string :as str] [clojure.pprint :as pp] [clojure.java.io :as io] [clojure.set :as set] [clojure.data.json :as json] [clojure.data.csv :as csv] [hickory.core :as html] [hickory.select :as sel] [metadata-tool.sources.confluence :as cfl] [metadata-tool.config :as cfg] [metadata-tool.sources.metadata :as md])) (def not-nil? (complement nil?)) (defn parse-string [s] (if (empty? s) "" (-> s (str/replace "&nbsp;" " ") (str/replace "\u00A0" " ") str/trim))) (defn resolve-acronym [s] (get (:acronyms (:meetings cfg/config)) s s)) (defn parse-name [s to-remove] (when-not (str/blank? s) (if (empty? to-remove) s (parse-name (str/replace s (first to-remove) "") (rest to-remove))))) (defn parse-date [title] (let [title-parsed (str/replace title "." "-") indexes (filter #(>= % 0) (keep #(str/index-of title-parsed %) (:years (:meetings cfg/config))))] (if (not-empty indexes) (first (str/split (subs title-parsed (first indexes)) #" ")) title))) (defn id-and-title [payload] {:id (:id payload) :title (:title payload) :url (:webui (:_links payload))}) (defn skip-page [page-title] (pos? (count (filter #(str/includes? (str/upper-case page-title) (str/upper-case %)) (:skip-pages (:meetings cfg/config)))))) (defn extract-full-name [element] (let [ancor (sel/select (sel/tag :a) element)] (if (empty? ancor) (let [span (sel/select (sel/descendant (sel/tag :span)) element)] (if (empty? span) (let [p (sel/select (sel/descendant (sel/tag :p)) element)] (if (empty? p) (let [any (sel/select (sel/descendant sel/any sel/any) element)] (if (empty? any) (first (:content element)) (first (:content any)))) (first (:content (first p))))) (first (:content (first span))))) (first (:content (first ancor)))))) (defn debug [x] (println "--- START DEBUG ---") (pp/pprint x) (println "--- END DEBUG ---") x) (defn row-to-user [row program activity type meeting-date] (let [raw-name (extract-full-name row) ignored-names (:ignore-names (:meetings cfg/config))] (if-let [name (resolve-acronym (parse-name (parse-string raw-name) (:remove-from-names (:meetings cfg/config))))] (if-not (contains? ignored-names (str/trim name)) (if-let [user-by-md (md/person-metadata-by-fn nil (str/trim name) nil)] { :email (first (:email-addresses user-by-md)) :name (:full-PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI-by-md) :org (or (:organization-name (first (md/current-affiliations (:person-id user-by-md))))) :ghid (or (first (:github-logins user-by-md))) :program program :activity activity :type type :meeting-date meeting-date } (println "[USER NOT FOUND] " (str "'" (str/trim name) "'") "on activity" activity "date" meeting-date)))))) (defn meeting-roster [raw-table-html page-title program activity type] (let [meeting-date (parse-date page-title) table-html (str "<table>" raw-table-html "</table>") selector (sel/and (sel/class :confluenceTd) sel/first-child)] (let [table (html/as-hickory (html/parse table-html)) rows (sel/select selector table)] (map #(row-to-user % program activity type meeting-date) rows)))) (defn parse-page [page-data program activity type] (let [title (:title page-data) meeting-date (parse-date title)] (if (not (= meeting-date title)) (let [content (cfl/content (:url page-data))] (if-not (skip-page title) (do (println (str "Scanning for meeting attendance on page " (:title page-data))) (if-not (empty? content) (meeting-roster content title program activity type)))))))) (defn ids-and-titles [id] (let [children (map id-and-title (cfl/children id))] (flatten (concat children (map #(ids-and-titles (:id %)) children))))) (defn meetings-rosters [program activity type url] (println (str "Generating meeting attendance for activity " activity)) (let [page-id (cfl/page-id url) sub-pages (ids-and-titles page-id)] (flatten (keep #(parse-page % program activity type) sub-pages)))) (defn roster-to-csv [roster-data] (with-open [writer (io/writer "finos-meetings.csv")] (.write writer "email, name, org, github ID, cm_program, cm_title, cm_type, date\n") (doall (map #(.write writer (str (str/join ", " (vals %)) "\n")) ; DEBUG - Check on :name instead of :email if you want to debug output (remove #(or (nil? %) (nil? (:email %))) roster-data))) (.flush writer))) ;; Utility functions for gen-meeting-github-roster-data ;; (defn string-keys-to-symbols [map] (reduce #(assoc %1 (-> (key %2) keyword) (val %2)) {} map)) (defn csv-item-to-str [item] (if-not (empty? item) (str (str/join ", " (map #(str/trim %) item))))) (defn str-to-csv-item [s] (map #(str/trim %) (str/split s #","))) (defn contains-not [list item] (not (some #(= item %) list))) (defn get-json [path] (json/read-str (slurp path))) (defn to-json [o] (json/write-str o)) (defn get-reader [path] (io/reader path)) (defn get-writer [path] (io/writer path)) (defn read-csv [reader] (csv/read-csv reader)) (defn write-csv [writer items] (csv/write-csv writer items)) (defn has-meeting-config [] (and (.exists (io/as-file "./meeting-attendance.json")) (.exists (io/as-file "./github-finos-meetings.csv")))) (defn match-project [project data] (and (some #(= (str/lower-case (:repo data)) (str/lower-case %)) (:github-repos project)) (some #(str/includes? % (str "/" (:org data) "/")) (:github-urls project)))) (defn get-csv-delta [new-csv] (with-open [reader (io/reader "./github-finos-meetings.csv")] (let [items (set (map #(csv-item-to-str %) (csv/read-csv reader))) new-items (set (map #(csv-item-to-str (vals %)) new-csv)) exist-str (set/intersection items new-items) existing (map #(str-to-csv-item %) exist-str) missing (map #(str-to-csv-item %) (set/difference new-items exist-str))] [existing missing]))) (defn single-attendance [person project meeting-date] (if-let [email (cond (> (count (:email-addresses person)) 0) (first (:email-addresses person)) (> (count (:github-logins person)) 0) (str (first (:github-logins person)) "@users.noreply.github.com"))] {:email email :name (:full-name person) :org (or (:organization-name (first (md/current-affiliations (:person-id person))))) :ghid (or (first (:github-logins person))) :program (:program-short-name project) :activity (:activity-name project) :type (:type project) :meeting-date meeting-date})) (defn remove-existing-entries [to-remove current] (let [remove-str (set (map #(csv-item-to-str %) to-remove)) curr-str (map #(csv-item-to-str %) current) diff-str (filter #(contains-not remove-str %) curr-str)] (map #(str-to-csv-item %) diff-str)))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.999810516834259, "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.9998195767402649, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/editor/defold_project_test.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.defold-project-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [dynamo.graph :as g] [editor.defold-project :as project] [editor.resource :as resource] [editor.resource-node :as resource-node] [editor.workspace :as workspace] [integration.test-util :as test-util] [support.test-support :refer [with-clean-system tx-nodes]])) (def ^:private load-counter (atom 0)) (g/defnode ANode (inherits resource-node/ResourceNode) (property value-piece g/Str) (property value g/Str (set (fn [evaluation-context self old-value new-value] (let [input (g/node-value self :value-input evaluation-context)] (g/set-property self :value-piece (str (first input))))))) (property source-resource resource/Resource (set (fn [evaluation-context self _old-value new-value] (let [project (project/get-project (:basis evaluation-context) self)] (:tx-data (project/connect-resource-node evaluation-context project new-value self [[:value :value-input]])))))) (input value-input g/Str)) (g/defnode BNode (inherits resource-node/ResourceNode) (property value g/Str)) (defn- read-a [resource] (read-string (slurp resource))) (defn- dependencies-a [source-value] (keep source-value [:b])) (defn- load-a [project self resource] (swap! load-counter inc) (let [data (read-string (slurp resource)) source-resource (workspace/resolve-resource resource (:b data))] (concat (g/set-property self :value-piece "set incorrectly") (g/set-property self :source-resource source-resource) (g/set-property self :value "bogus value")))) (defn- load-b [project self resource] (swap! load-counter inc) (let [data (read-string (slurp resource))] (g/set-property self :value (:value data)))) (defn- register-resource-types [workspace types] (for [type types] (apply workspace/register-resource-type workspace (flatten (vec type))))) (deftest loading (reset! load-counter 0) (with-clean-system (test-util/with-ui-run-later-rebound (let [workspace (workspace/make-workspace world (.getAbsolutePath (io/file "test/resources/load_project")) {})] (g/transact (register-resource-types workspace [{:ext "type_a" :node-type ANode :read-fn read-a :dependencies-fn dependencies-a :load-fn load-a :label "Type A"} {:ext "type_b" :node-type BNode :load-fn load-b :label "Type B"}])) (workspace/resource-sync! workspace) (let [project (test-util/setup-project! workspace) a1 (project/get-resource-node project "/a1.type_a")] (is (= 3 @load-counter)) (is (= "t" (g/node-value a1 :value-piece))))))))
101853
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 <NAME>, <NAME> ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.defold-project-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [dynamo.graph :as g] [editor.defold-project :as project] [editor.resource :as resource] [editor.resource-node :as resource-node] [editor.workspace :as workspace] [integration.test-util :as test-util] [support.test-support :refer [with-clean-system tx-nodes]])) (def ^:private load-counter (atom 0)) (g/defnode ANode (inherits resource-node/ResourceNode) (property value-piece g/Str) (property value g/Str (set (fn [evaluation-context self old-value new-value] (let [input (g/node-value self :value-input evaluation-context)] (g/set-property self :value-piece (str (first input))))))) (property source-resource resource/Resource (set (fn [evaluation-context self _old-value new-value] (let [project (project/get-project (:basis evaluation-context) self)] (:tx-data (project/connect-resource-node evaluation-context project new-value self [[:value :value-input]])))))) (input value-input g/Str)) (g/defnode BNode (inherits resource-node/ResourceNode) (property value g/Str)) (defn- read-a [resource] (read-string (slurp resource))) (defn- dependencies-a [source-value] (keep source-value [:b])) (defn- load-a [project self resource] (swap! load-counter inc) (let [data (read-string (slurp resource)) source-resource (workspace/resolve-resource resource (:b data))] (concat (g/set-property self :value-piece "set incorrectly") (g/set-property self :source-resource source-resource) (g/set-property self :value "bogus value")))) (defn- load-b [project self resource] (swap! load-counter inc) (let [data (read-string (slurp resource))] (g/set-property self :value (:value data)))) (defn- register-resource-types [workspace types] (for [type types] (apply workspace/register-resource-type workspace (flatten (vec type))))) (deftest loading (reset! load-counter 0) (with-clean-system (test-util/with-ui-run-later-rebound (let [workspace (workspace/make-workspace world (.getAbsolutePath (io/file "test/resources/load_project")) {})] (g/transact (register-resource-types workspace [{:ext "type_a" :node-type ANode :read-fn read-a :dependencies-fn dependencies-a :load-fn load-a :label "Type A"} {:ext "type_b" :node-type BNode :load-fn load-b :label "Type B"}])) (workspace/resource-sync! workspace) (let [project (test-util/setup-project! workspace) a1 (project/get-resource-node project "/a1.type_a")] (is (= 3 @load-counter)) (is (= "t" (g/node-value a1 :value-piece))))))))
true
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.defold-project-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [dynamo.graph :as g] [editor.defold-project :as project] [editor.resource :as resource] [editor.resource-node :as resource-node] [editor.workspace :as workspace] [integration.test-util :as test-util] [support.test-support :refer [with-clean-system tx-nodes]])) (def ^:private load-counter (atom 0)) (g/defnode ANode (inherits resource-node/ResourceNode) (property value-piece g/Str) (property value g/Str (set (fn [evaluation-context self old-value new-value] (let [input (g/node-value self :value-input evaluation-context)] (g/set-property self :value-piece (str (first input))))))) (property source-resource resource/Resource (set (fn [evaluation-context self _old-value new-value] (let [project (project/get-project (:basis evaluation-context) self)] (:tx-data (project/connect-resource-node evaluation-context project new-value self [[:value :value-input]])))))) (input value-input g/Str)) (g/defnode BNode (inherits resource-node/ResourceNode) (property value g/Str)) (defn- read-a [resource] (read-string (slurp resource))) (defn- dependencies-a [source-value] (keep source-value [:b])) (defn- load-a [project self resource] (swap! load-counter inc) (let [data (read-string (slurp resource)) source-resource (workspace/resolve-resource resource (:b data))] (concat (g/set-property self :value-piece "set incorrectly") (g/set-property self :source-resource source-resource) (g/set-property self :value "bogus value")))) (defn- load-b [project self resource] (swap! load-counter inc) (let [data (read-string (slurp resource))] (g/set-property self :value (:value data)))) (defn- register-resource-types [workspace types] (for [type types] (apply workspace/register-resource-type workspace (flatten (vec type))))) (deftest loading (reset! load-counter 0) (with-clean-system (test-util/with-ui-run-later-rebound (let [workspace (workspace/make-workspace world (.getAbsolutePath (io/file "test/resources/load_project")) {})] (g/transact (register-resource-types workspace [{:ext "type_a" :node-type ANode :read-fn read-a :dependencies-fn dependencies-a :load-fn load-a :label "Type A"} {:ext "type_b" :node-type BNode :load-fn load-b :label "Type B"}])) (workspace/resource-sync! workspace) (let [project (test-util/setup-project! workspace) a1 (project/get-resource-node project "/a1.type_a")] (is (= 3 @load-counter)) (is (= "t" (g/node-value a1 :value-piece))))))))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2016-11-28\"\n ", "end": 97, "score": 0.7954860925674438, "start": 88, "tag": "EMAIL", "value": "wahpenayo" }, { "context": "-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2016-11-28\"\n :date \"2017-11-", "end": 114, "score": 0.7613449096679688, "start": 101, "tag": "EMAIL", "value": "gmail dot com" } ]
src/main/clojure/taigabench/summary.clj
wahpenayo/taigabench
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "wahpenayo at gmail dot com" :since "2016-11-28" :date "2017-11-20" :doc "Compute summary statistics for sanity checking." } taigabench.summary (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z])) ;;------------------------------------------------------------------------------ (defn- distinct-missing-summary [z data] (let [n (z/count data) not-missing (z/drop-missing z data) distinct (z/count (z/distinct z not-missing)) not-missing (z/count not-missing) missing-fraction (if (zero? n) 0.0 (- 1.0 (double (/ not-missing n))))] {:n n :not-missing not-missing :distinct distinct :missing-fraction missing-fraction})) (defn- numerical-summary [z data] (if (z/numerical? z data) (let [data (z/drop-missing z data) ps [0.0 0.10 0.25 0.50 0.75 0.90 1.0]] (merge {:is-numerical true} (when-not (empty? data) (zipmap (mapv #(format "p%03d" (int (* 100.0 (double %)))) ps) (z/quantiles (z/select-finite-values z data) ps))))) {:is-numerical false})) (defn- vector-summary [z data] (if (z/vector? z data) (let [data (z/drop-missing z data) ps [0.0 0.10 0.25 0.50 0.75 0.90 1.0]] (merge {:is-vector true} (when-not (empty? data) (zipmap (mapv #(format "p%03d" (int (* 100.0 (double %)))) ps) (z/quantiles (z/select-finite-values z data) ps))))) {:is-vector false})) (defn- attribute-summary [z data] (merge {:attribute (z/name z)} (distinct-missing-summary z data) (numerical-summary z data) (vector-summary z data))) ;;------------------------------------------------------------------------------ (defn- summary [options] (println (:type options) (z/count (:data options))) (when-not (z/empty? (:data options)) (let [data (:data options) attribute-map (:attributes options) options (dissoc options :data :attributes)] (z/pmap (fn [[k v]] (merge options (attribute-summary v data))) (sort-by key attribute-map))))) (defn- write-records [records ^java.io.File file] (let [header (sort-by name (into #{} (mapcat keys records)))] (with-open [w (z/print-writer file)] (.println w (s/join "\t" (mapv name header))) (doseq [record records] (.println w (s/join "\t" (mapv #(get record %) header)))))) (z/echo "wrote" (z/count records) "to" (z/pathname file))) ;;------------------------------------------------------------------------------ (defn- check [options] (assert (string? (:feature-set options)) (str "No :feature-set name given:\n" (z/pprint-map-str options))) (assert (and (instance? java.util.Map (:report-attributes options)) (not (z/empty? (:report-attributes options)))) (str "Invalid :report-attributes in:\n" (z/pprint-map-str options)))) ;;------------------------------------------------------------------------------ (defn report [options ^java.io.File f] (check options) (z/seconds (print-str "report") (let [records (concat (summary {:attributes (:report-attributes options) :data (:train-data options) :type "train"}) (summary {:attributes (:report-attributes options) :data (:test-data options) :type "test"}) (summary {:attributes (:report-attributes options) :data (:predict-data options) :type "predict"}))] (when-not (z/empty? records) (io/make-parents f) (write-records (z/sort-by #(vector (:attribute %) (:type %)) records) f))))) ;;------------------------------------------------------------------------------
93351
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<EMAIL> at <EMAIL>" :since "2016-11-28" :date "2017-11-20" :doc "Compute summary statistics for sanity checking." } taigabench.summary (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z])) ;;------------------------------------------------------------------------------ (defn- distinct-missing-summary [z data] (let [n (z/count data) not-missing (z/drop-missing z data) distinct (z/count (z/distinct z not-missing)) not-missing (z/count not-missing) missing-fraction (if (zero? n) 0.0 (- 1.0 (double (/ not-missing n))))] {:n n :not-missing not-missing :distinct distinct :missing-fraction missing-fraction})) (defn- numerical-summary [z data] (if (z/numerical? z data) (let [data (z/drop-missing z data) ps [0.0 0.10 0.25 0.50 0.75 0.90 1.0]] (merge {:is-numerical true} (when-not (empty? data) (zipmap (mapv #(format "p%03d" (int (* 100.0 (double %)))) ps) (z/quantiles (z/select-finite-values z data) ps))))) {:is-numerical false})) (defn- vector-summary [z data] (if (z/vector? z data) (let [data (z/drop-missing z data) ps [0.0 0.10 0.25 0.50 0.75 0.90 1.0]] (merge {:is-vector true} (when-not (empty? data) (zipmap (mapv #(format "p%03d" (int (* 100.0 (double %)))) ps) (z/quantiles (z/select-finite-values z data) ps))))) {:is-vector false})) (defn- attribute-summary [z data] (merge {:attribute (z/name z)} (distinct-missing-summary z data) (numerical-summary z data) (vector-summary z data))) ;;------------------------------------------------------------------------------ (defn- summary [options] (println (:type options) (z/count (:data options))) (when-not (z/empty? (:data options)) (let [data (:data options) attribute-map (:attributes options) options (dissoc options :data :attributes)] (z/pmap (fn [[k v]] (merge options (attribute-summary v data))) (sort-by key attribute-map))))) (defn- write-records [records ^java.io.File file] (let [header (sort-by name (into #{} (mapcat keys records)))] (with-open [w (z/print-writer file)] (.println w (s/join "\t" (mapv name header))) (doseq [record records] (.println w (s/join "\t" (mapv #(get record %) header)))))) (z/echo "wrote" (z/count records) "to" (z/pathname file))) ;;------------------------------------------------------------------------------ (defn- check [options] (assert (string? (:feature-set options)) (str "No :feature-set name given:\n" (z/pprint-map-str options))) (assert (and (instance? java.util.Map (:report-attributes options)) (not (z/empty? (:report-attributes options)))) (str "Invalid :report-attributes in:\n" (z/pprint-map-str options)))) ;;------------------------------------------------------------------------------ (defn report [options ^java.io.File f] (check options) (z/seconds (print-str "report") (let [records (concat (summary {:attributes (:report-attributes options) :data (:train-data options) :type "train"}) (summary {:attributes (:report-attributes options) :data (:test-data options) :type "test"}) (summary {:attributes (:report-attributes options) :data (:predict-data options) :type "predict"}))] (when-not (z/empty? records) (io/make-parents f) (write-records (z/sort-by #(vector (:attribute %) (:type %)) records) f))))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:EMAIL:<EMAIL>END_PI at PI:EMAIL:<EMAIL>END_PI" :since "2016-11-28" :date "2017-11-20" :doc "Compute summary statistics for sanity checking." } taigabench.summary (:require [clojure.string :as s] [clojure.java.io :as io] [zana.api :as z])) ;;------------------------------------------------------------------------------ (defn- distinct-missing-summary [z data] (let [n (z/count data) not-missing (z/drop-missing z data) distinct (z/count (z/distinct z not-missing)) not-missing (z/count not-missing) missing-fraction (if (zero? n) 0.0 (- 1.0 (double (/ not-missing n))))] {:n n :not-missing not-missing :distinct distinct :missing-fraction missing-fraction})) (defn- numerical-summary [z data] (if (z/numerical? z data) (let [data (z/drop-missing z data) ps [0.0 0.10 0.25 0.50 0.75 0.90 1.0]] (merge {:is-numerical true} (when-not (empty? data) (zipmap (mapv #(format "p%03d" (int (* 100.0 (double %)))) ps) (z/quantiles (z/select-finite-values z data) ps))))) {:is-numerical false})) (defn- vector-summary [z data] (if (z/vector? z data) (let [data (z/drop-missing z data) ps [0.0 0.10 0.25 0.50 0.75 0.90 1.0]] (merge {:is-vector true} (when-not (empty? data) (zipmap (mapv #(format "p%03d" (int (* 100.0 (double %)))) ps) (z/quantiles (z/select-finite-values z data) ps))))) {:is-vector false})) (defn- attribute-summary [z data] (merge {:attribute (z/name z)} (distinct-missing-summary z data) (numerical-summary z data) (vector-summary z data))) ;;------------------------------------------------------------------------------ (defn- summary [options] (println (:type options) (z/count (:data options))) (when-not (z/empty? (:data options)) (let [data (:data options) attribute-map (:attributes options) options (dissoc options :data :attributes)] (z/pmap (fn [[k v]] (merge options (attribute-summary v data))) (sort-by key attribute-map))))) (defn- write-records [records ^java.io.File file] (let [header (sort-by name (into #{} (mapcat keys records)))] (with-open [w (z/print-writer file)] (.println w (s/join "\t" (mapv name header))) (doseq [record records] (.println w (s/join "\t" (mapv #(get record %) header)))))) (z/echo "wrote" (z/count records) "to" (z/pathname file))) ;;------------------------------------------------------------------------------ (defn- check [options] (assert (string? (:feature-set options)) (str "No :feature-set name given:\n" (z/pprint-map-str options))) (assert (and (instance? java.util.Map (:report-attributes options)) (not (z/empty? (:report-attributes options)))) (str "Invalid :report-attributes in:\n" (z/pprint-map-str options)))) ;;------------------------------------------------------------------------------ (defn report [options ^java.io.File f] (check options) (z/seconds (print-str "report") (let [records (concat (summary {:attributes (:report-attributes options) :data (:train-data options) :type "train"}) (summary {:attributes (:report-attributes options) :data (:test-data options) :type "test"}) (summary {:attributes (:report-attributes options) :data (:predict-data options) :type "predict"}))] (when-not (z/empty? records) (io/make-parents f) (write-records (z/sort-by #(vector (:attribute %) (:type %)) records) f))))) ;;------------------------------------------------------------------------------
[ { "context": "web.xml\"\n (with-appengine (local-proxy :email \"test@example.com\" :admin true)\n (do\n (let [feed-count ", "end": 518, "score": 0.9999188184738159, "start": 502, "tag": "EMAIL", "value": "test@example.com" } ]
src/leiningen/print_database.clj
lhanson/Pillage-RSS
2
(ns leiningen.print-database (:require [clojure.string :as string]) (:use [pillage.feed-handling :only (get-syndfeed)] pillage.models [appengine.datastore :only (delete-entity save-entity)] appengine.environment [appengine.users :only (current-user)])) (defn print-database [] "A Leiningen task which lists the contents of the data store." (init-appengine "war") (with-configuration "war/WEB-INF/appengine-web.xml" (with-appengine (local-proxy :email "test@example.com" :admin true) (do (let [feed-count (count (find-pillagefeeds)) exclusion-count (count (find-exclusion-filters)) modification-count (count (find-modification-filters)) ] (println "Have" feed-count "feeds, " exclusion-count "exclusion filters, and" modification-count "modification filters"))))))
52346
(ns leiningen.print-database (:require [clojure.string :as string]) (:use [pillage.feed-handling :only (get-syndfeed)] pillage.models [appengine.datastore :only (delete-entity save-entity)] appengine.environment [appengine.users :only (current-user)])) (defn print-database [] "A Leiningen task which lists the contents of the data store." (init-appengine "war") (with-configuration "war/WEB-INF/appengine-web.xml" (with-appengine (local-proxy :email "<EMAIL>" :admin true) (do (let [feed-count (count (find-pillagefeeds)) exclusion-count (count (find-exclusion-filters)) modification-count (count (find-modification-filters)) ] (println "Have" feed-count "feeds, " exclusion-count "exclusion filters, and" modification-count "modification filters"))))))
true
(ns leiningen.print-database (:require [clojure.string :as string]) (:use [pillage.feed-handling :only (get-syndfeed)] pillage.models [appengine.datastore :only (delete-entity save-entity)] appengine.environment [appengine.users :only (current-user)])) (defn print-database [] "A Leiningen task which lists the contents of the data store." (init-appengine "war") (with-configuration "war/WEB-INF/appengine-web.xml" (with-appengine (local-proxy :email "PI:EMAIL:<EMAIL>END_PI" :admin true) (do (let [feed-count (count (find-pillagefeeds)) exclusion-count (count (find-exclusion-filters)) modification-count (count (find-modification-filters)) ] (println "Have" feed-count "feeds, " exclusion-count "exclusion filters, and" modification-count "modification filters"))))))
[ { "context": " (not-found {:success false :message \"I'm sorry Dave, there are no tokens here.\"}))))\n (GET \"/t", "end": 22235, "score": 0.8833443522453308, "start": 22231, "tag": "NAME", "value": "Dave" }, { "context": " (not-found {:success false :message \"I'm sorry Dave, there are no tags here.\"})))))\n (context \"/", "end": 23384, "score": 0.9965710639953613, "start": 23380, "tag": "NAME", "value": "Dave" } ]
src/artstor_group_service/core.clj
ithaka/artstor-group-service-os
0
(ns artstor-group-service.core (:require [clojure.spec :as spec] [schema.core :as s] [compojure.api.sweet :refer :all] [compojure.api.meta :refer [restructure-param]] [compojure.api.exception :as ex] [buddy.auth.accessrules :as baa] [ring.util.http-response :refer [bad-request]] [ring.middleware.cookies :as rcookie] [ring.logger :as ring-logger] [captains-common.core :as captains] [org.ithaka.clj-iacauth.ring.middleware :refer :all] [artstor-group-service.schema :as data] [artstor-group-service.repository :as repo] [artstor-group-service.service.metadata :as metadata] [artstor-group-service.auth :as auth] [artstor-group-service.user :as user] [artstor-group-service.util :as util :refer [not-found forbidden]] [artstor-group-service.logging :as grplog]) (:import (java.util UUID))) (defn access-error [req val] (forbidden (or val {:success false :message "Access denied"}))) (defn wrap-rule [handler rule] (-> handler (baa/wrap-access-rules {:rules [{:pattern #".*" :handler rule}] :on-error access-error}))) (defmethod restructure-param :auth-rules [_ rule acc] (update-in acc [:middleware] conj [wrap-rule rule])) (defmethod restructure-param :current-user [_ binding acc] (update-in acc [:letks] into [binding `(user/extract-user-or-ip ~'+compojure-api-request+)])) (def app (->> (api {:exceptions {:handlers {::ex/request-parsing (grplog/with-request-logging ex/request-parsing-handler) ::ex/request-validation (grplog/with-request-logging ex/request-validation-handler)}} :swagger {:ui "/" :spec "/swagger.json" :data {:info {:title "ANG Group Service API" :description "This service exposes CRUD methods for dealing with groups."} :tags [{:name "group" :description "Services for creating, updating, reading, and deleting groups"}]}}} (context "/api/v1/group" [] :tags ["group"] (GET "/" [] :auth-rules auth/can-perform-search? :return {:success s/Bool :total s/Int :groups [data/GroupSearch] :tags (s/maybe [{:key s/Str :doc_count s/Int}])} :header-params [{web-token :- (s/maybe s/Str) ""}] :query-params [{q :- s/Str nil} {tags :- [s/Str] []} {from :- s/Int 0} {size :- s/Int 24} {level :- (s/enum :all :public :institution :shared :private) :all}] :summary "Gets all Groups available for the currently logged in user" :current-user user :responses {200 {:schema {:success s/Bool :total s/Int :groups [data/GroupSearch] :tags (s/maybe [{:key s/Str :doc_count s/Int}])} :description "Search all groups and return matches"} 400 {:description "Invalid parameters supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (let [add-param {:tags tags :from from :size size :level level}] (captains/ok (repo/get-groups q (merge add-param {:profile-id (user :profile_id) :institution-ids (user :institution_ids)})) (grplog/build-search-event user (assoc add-param :query (if (nil? q) "" q)))))) (GET "/:group-id" [group-id] :auth-rules auth/can-read? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :query-params [{internal :- s/Bool false}] :summary "Returns a group object" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [found-group (repo/get-group group-id)] (let [deduped-group (repo/get-deduped-group found-group)] (captains/ok (auth/coerce-group-based-on-access-type deduped-group user) (grplog/build-group-event user deduped-group "artstor_read_group" true {:internal internal}))) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_read_group" false {:artstor-error "I couldn't find a group with that id." :internal internal})))) (POST "/" [] :auth-rules auth/logged-in? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :return data/Group :body [group data/NewGroup] :summary "Returns a freshly minted group object" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (if-let [errors (data/group-validator? group)] (bad-request errors) (let [newlygroup (repo/add! group user)] (captains/ok newlygroup (grplog/build-create-event user newlygroup))))) (POST "/:group-id/copy" [] :auth-rules auth/can-read? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [group-name {:name s/Str}] :summary "Returns a freshly minted group object copied from the provided group id" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "That's not a valid name"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "No group found to copy"} 500 {:description "Server Error handling the request"}} (if-let [errors (spec/explain-data ::data/name (group-name :name))] (bad-request errors) (if-let [new-group (repo/copy! group-id (group-name :name) user)] (captains/ok new-group (grplog/build-group-event user new-group "artstor_copy_group" true {:source_group_id group-id} )) (not-found {:success false :message "I couldn't find a group to copy."} (grplog/build-group-event user {:id group-id} "artstor_copy_group" false {:source_group_id group-id :artstor_error "I couldn't find a source group to copy."}))))) (GET "/:group-id/metadata" [group-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String] :query-params [{object_ids :- [s/Str] []} {legacy :- s/Bool true} {xml :- s/Bool false}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Gets the metadata for all the specified items the user has access too. (150 max) with group id" :responses {200 {:description "Find items by object_id and return metadata matches"} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if(repo/get-group group-id) (metadata/get-metadata group-id object_ids legacy xml (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (GET "/:group-id/secure/metadata/:object-id" [group-id object-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String object-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Accepts object-id in url and returns the metadata in legacy json format for the specified item." :responses {200 {:description "Find item by object_id and return legacy formatted metadata"} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if(repo/get-group group-id) (metadata/get-legacy-metadata group-id object-id (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (GET "/:group-id/items" [group-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String] :query-params [{object_ids :- [s/Str] []}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Gets the Items for all the specified items the user has access too. (150 max) with group id" :responses {200 {:description "Find items by object_id and return item details."} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [found-group (repo/get-group group-id)] (metadata/get-items group-id object_ids (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (PUT "/:group-id" [group-id] :auth-rules auth/can-write? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [group data/NewGroup] :summary "Updates a group object" :responses {200 {:schema data/Group :description "A lovely updated group object"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (repo/find-group-by-id group-id) (if (or (auth/can-change-group-access? user group-id) (empty? (group :access))) (if-let [errors (data/group-errors? group)] (bad-request errors) (captains/ok (auth/coerce-group-based-on-access-type (repo/update! group-id group) user) (grplog/build-group-event user (assoc group :id group-id) "artstor_update_group" true))) (forbidden {:success false :message "Insufficient Privileges"} (grplog/build-group-event user (assoc group :id group-id) "artstor_update_group" false {:artstor-error "Insufficient Privileges"}))) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_update_group" false {:artstor-error "I couldn't find a group with that id."})))) (PUT "/:group-id/admin/public" [group-id] :auth-rules auth/artstor-admin? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [public-flag {:public s/Bool}] :summary "For Artstor admin use only: Updates the group's public value." :responses {200 {:schema data/Group :description "Only updates public field. Other fields are ignored."} 400 {:description "Only send the value for public:"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (repo/find-group-by-id group-id) (captains/ok (auth/coerce-group-based-on-access-type (repo/update-public-flag! group-id public-flag) user) (grplog/build-group-event user {:id group-id} "artstor_update_group_public" true {:public_flag public-flag})) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_update_group_public" false {:public_flag public-flag :artstor-error "I couldn't find a group with that id."})))) (PUT "/items/delete" [] :auth-rules auth/logged-in? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :body [object_ids [s/Str]] :summary "Deletes objects from groups" :responses {200 {:description "Objects deleted from image groups"} 400 {:description "Invalid object-id(s) supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The groups associated with the supplied objects could not be found"} 500 {:description "Server Error handling the request"}} (if (empty? object_ids) (bad-request) (let [result (repo/get-groups-associated-with-object-ids object_ids)] (if (not (empty? result)) (let [data (into [] (flatten (map #(get-in result [%]) object_ids))) group-ids (map #(get % :group_id) data)] (captains/ok (repo/delete-groups-associated-with-object-ids object_ids group-ids) (grplog/build-delete-objects-event user result "artstor_delete_pc_objects_from_groups" {:object_ids (vec object_ids)}))) (not-found {:success true :message "Couldn't find any of the groups containing the object-id(s)"} (grplog/build-delete-objects-event user "" "artstor_delete_pc_objects_from_groups" {:artstor-error "I couldn't find groups associated with given objects"})))))) (DELETE "/:group-id" [group-id] :auth-rules auth/is-admin? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :return {:success s/Bool :message s/Str} :path-params [group-id :- String] :summary "Deletes a group" :responses {200 {:description "Group has been deleted"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [id (repo/delete! group-id)] (captains/ok {:success true :message (str "Your group (" id ") has been deleted.")} (grplog/build-group-event user {:id group-id} "artstor_delete_group" true)) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_delete_group" false {:artstor-error "I couldn't find a group with that id."})))) (POST "/:group-id/share" [group-id] :auth-rules auth/is-admin? :current-user user :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [token (s/maybe data/NewToken)] :summary "Creates a token for sharing the specified group" :responses {200 {:schema {:success s/Bool :token s/Str} :description "One hot and fresh token"} 400 {:description "Invalid data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (>= (repo/count-group-shares group-id) 1000) (bad-request {:success false :message "Cannot share to more than 1000 entities"}) (if-let [token (repo/generate-token (Long/parseLong (get user :profile_id)) group-id (get token :access_type 100) (get token :expiration_time))] (captains/ok {:success true :token (util/encode-uuid (UUID/fromString token))} {:group_id group-id}) (not-found {:success false :message "I couldn't find a group with that id."})))) (POST "/redeem/:token" [token] :auth-rules auth/logged-in? :current-user user :return data/Group :path-params [token :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Redeems a token for access to the specified group" :responses {200 {:schema {:success s/Bool :group data/Group} :description "A lovely group for you to use."} 400 {:description "Invalid token supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The token was not found or it expired."} 500 {:description "Server Error handling the request"}} (if-let [redeeming-group (repo/get-group-from-token (util/decode-uuid token))] (if (>= (repo/count-redeeming-group-access redeeming-group) 1000) (bad-request {:success false :message "Cannot share to more than 1000 entities"}) (if-let [group (repo/redeem-token (Long/parseLong (get user :profile_id)) (util/decode-uuid token))] (captains/ok {:success true :group (auth/coerce-group-based-on-access-type group user)} {:group_id (get group :id "")}) (not-found {:success false :message "That token has apparently gone stale. We're so sorry."}))) (not-found {:success false :message "That token has apparently gone stale. We're so sorry."}))) (DELETE "/expire/:token" [token] :auth-rules auth/logged-in? :current-user user :return data/Group :path-params [token :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Invalidates a token so it can no longer be used" :responses {200 {:schema data/RequestStatus :description "A boolean indicator of success"} 400 {:description "Invalid token supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The token was not found"} 500 {:description "Server Error handling the request"}} (let [res (repo/delete-token! (Long/parseLong (get user :profile_id)) (util/decode-uuid token))] (if (> res 0) (captains/ok {:success true :message "I tossed your token in the bin."}) (not-found {:success false :message "Your token has apparently gone missing. We're so sorry."})))) (GET "/:group-id/tokens" [group-id] :auth-rules auth/is-admin? :current-user user :return [{:success s/Bool :tokens [data/Token]}] :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Returns any tokens that are set on the group" :responses {200 {:schema {:success s/Bool :tokens [data/Token]} :description "A list of tokens on this group"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group was not found"} 500 {:description "Server Error handling the request"}} (let [tokens (repo/get-tokens (Long/parseLong (get user :profile_id)) group-id)] (if (seq tokens) (captains/ok {:success true :tokens (map #(assoc % :token (util/encode-uuid (UUID/fromString (% :token)))) tokens)} {:group_id group-id}) (not-found {:success false :message "I'm sorry Dave, there are no tokens here."})))) (GET "/tags/suggest" [] :auth-rules auth/logged-in? :current-user user :return [{:success s/Bool :tags [s/Str]}] :query-params [{q :- s/Str nil} {size :- s/Int nil}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Returns any tags that match the group search query" :responses {200 {:schema {:success s/Bool :tags [s/Str]} :description "A list of tags"} 400 {:description "Invalid query supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "no matches found"} 500 {:description "Server Error handling the request"}} (let [number-to-return (repo/get-valid-tag-count size) tags (repo/get-tags-that-start-with q number-to-return)] (if (seq tags) (captains/ok {:success true :tags tags}) (not-found {:success false :message "I'm sorry Dave, there are no tags here."}))))) (context "/internal/generate" [] :tags ["web-token"] (POST "/" [] :return [{:success s/Bool :tags [s/Str]}] :body [data data/ArtstorUser] :summary "Returns a web token" :responses {200 {:schema {:success s/Bool :token s/Str} :description "Generate a Web token"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (let [wt (artstor-group-service.auth/generate-web-token data)] (if (nil? wt) (bad-request) (captains/ok {:success true :token wt}))))) (ANY "/*" [] :responses {404 {:schema data/RequestStatus}} (not-found {:success false :message "My human masters didn't plan for this eventuality. Pity."}))) (auth/add-cors) (auth/add-empty-body-to-posts) (captains/wrap-web-logging {:event-type-func grplog/determine-event-type}) (user/wrap-user-or-ip) (with-auth {:exclude-paths [#"/index.html" #"/swagger.json" #".\.js" #".*.js" #"/images/.*" #"/lib/.*" #"/css/.*" #"/conf/.*" #"/internal/.*" #"/" #"/watchable"]}) (util/wrap-method-override) (ring-logger/wrap-with-logger) (rcookie/wrap-cookies)))
58310
(ns artstor-group-service.core (:require [clojure.spec :as spec] [schema.core :as s] [compojure.api.sweet :refer :all] [compojure.api.meta :refer [restructure-param]] [compojure.api.exception :as ex] [buddy.auth.accessrules :as baa] [ring.util.http-response :refer [bad-request]] [ring.middleware.cookies :as rcookie] [ring.logger :as ring-logger] [captains-common.core :as captains] [org.ithaka.clj-iacauth.ring.middleware :refer :all] [artstor-group-service.schema :as data] [artstor-group-service.repository :as repo] [artstor-group-service.service.metadata :as metadata] [artstor-group-service.auth :as auth] [artstor-group-service.user :as user] [artstor-group-service.util :as util :refer [not-found forbidden]] [artstor-group-service.logging :as grplog]) (:import (java.util UUID))) (defn access-error [req val] (forbidden (or val {:success false :message "Access denied"}))) (defn wrap-rule [handler rule] (-> handler (baa/wrap-access-rules {:rules [{:pattern #".*" :handler rule}] :on-error access-error}))) (defmethod restructure-param :auth-rules [_ rule acc] (update-in acc [:middleware] conj [wrap-rule rule])) (defmethod restructure-param :current-user [_ binding acc] (update-in acc [:letks] into [binding `(user/extract-user-or-ip ~'+compojure-api-request+)])) (def app (->> (api {:exceptions {:handlers {::ex/request-parsing (grplog/with-request-logging ex/request-parsing-handler) ::ex/request-validation (grplog/with-request-logging ex/request-validation-handler)}} :swagger {:ui "/" :spec "/swagger.json" :data {:info {:title "ANG Group Service API" :description "This service exposes CRUD methods for dealing with groups."} :tags [{:name "group" :description "Services for creating, updating, reading, and deleting groups"}]}}} (context "/api/v1/group" [] :tags ["group"] (GET "/" [] :auth-rules auth/can-perform-search? :return {:success s/Bool :total s/Int :groups [data/GroupSearch] :tags (s/maybe [{:key s/Str :doc_count s/Int}])} :header-params [{web-token :- (s/maybe s/Str) ""}] :query-params [{q :- s/Str nil} {tags :- [s/Str] []} {from :- s/Int 0} {size :- s/Int 24} {level :- (s/enum :all :public :institution :shared :private) :all}] :summary "Gets all Groups available for the currently logged in user" :current-user user :responses {200 {:schema {:success s/Bool :total s/Int :groups [data/GroupSearch] :tags (s/maybe [{:key s/Str :doc_count s/Int}])} :description "Search all groups and return matches"} 400 {:description "Invalid parameters supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (let [add-param {:tags tags :from from :size size :level level}] (captains/ok (repo/get-groups q (merge add-param {:profile-id (user :profile_id) :institution-ids (user :institution_ids)})) (grplog/build-search-event user (assoc add-param :query (if (nil? q) "" q)))))) (GET "/:group-id" [group-id] :auth-rules auth/can-read? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :query-params [{internal :- s/Bool false}] :summary "Returns a group object" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [found-group (repo/get-group group-id)] (let [deduped-group (repo/get-deduped-group found-group)] (captains/ok (auth/coerce-group-based-on-access-type deduped-group user) (grplog/build-group-event user deduped-group "artstor_read_group" true {:internal internal}))) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_read_group" false {:artstor-error "I couldn't find a group with that id." :internal internal})))) (POST "/" [] :auth-rules auth/logged-in? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :return data/Group :body [group data/NewGroup] :summary "Returns a freshly minted group object" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (if-let [errors (data/group-validator? group)] (bad-request errors) (let [newlygroup (repo/add! group user)] (captains/ok newlygroup (grplog/build-create-event user newlygroup))))) (POST "/:group-id/copy" [] :auth-rules auth/can-read? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [group-name {:name s/Str}] :summary "Returns a freshly minted group object copied from the provided group id" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "That's not a valid name"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "No group found to copy"} 500 {:description "Server Error handling the request"}} (if-let [errors (spec/explain-data ::data/name (group-name :name))] (bad-request errors) (if-let [new-group (repo/copy! group-id (group-name :name) user)] (captains/ok new-group (grplog/build-group-event user new-group "artstor_copy_group" true {:source_group_id group-id} )) (not-found {:success false :message "I couldn't find a group to copy."} (grplog/build-group-event user {:id group-id} "artstor_copy_group" false {:source_group_id group-id :artstor_error "I couldn't find a source group to copy."}))))) (GET "/:group-id/metadata" [group-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String] :query-params [{object_ids :- [s/Str] []} {legacy :- s/Bool true} {xml :- s/Bool false}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Gets the metadata for all the specified items the user has access too. (150 max) with group id" :responses {200 {:description "Find items by object_id and return metadata matches"} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if(repo/get-group group-id) (metadata/get-metadata group-id object_ids legacy xml (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (GET "/:group-id/secure/metadata/:object-id" [group-id object-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String object-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Accepts object-id in url and returns the metadata in legacy json format for the specified item." :responses {200 {:description "Find item by object_id and return legacy formatted metadata"} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if(repo/get-group group-id) (metadata/get-legacy-metadata group-id object-id (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (GET "/:group-id/items" [group-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String] :query-params [{object_ids :- [s/Str] []}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Gets the Items for all the specified items the user has access too. (150 max) with group id" :responses {200 {:description "Find items by object_id and return item details."} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [found-group (repo/get-group group-id)] (metadata/get-items group-id object_ids (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (PUT "/:group-id" [group-id] :auth-rules auth/can-write? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [group data/NewGroup] :summary "Updates a group object" :responses {200 {:schema data/Group :description "A lovely updated group object"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (repo/find-group-by-id group-id) (if (or (auth/can-change-group-access? user group-id) (empty? (group :access))) (if-let [errors (data/group-errors? group)] (bad-request errors) (captains/ok (auth/coerce-group-based-on-access-type (repo/update! group-id group) user) (grplog/build-group-event user (assoc group :id group-id) "artstor_update_group" true))) (forbidden {:success false :message "Insufficient Privileges"} (grplog/build-group-event user (assoc group :id group-id) "artstor_update_group" false {:artstor-error "Insufficient Privileges"}))) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_update_group" false {:artstor-error "I couldn't find a group with that id."})))) (PUT "/:group-id/admin/public" [group-id] :auth-rules auth/artstor-admin? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [public-flag {:public s/Bool}] :summary "For Artstor admin use only: Updates the group's public value." :responses {200 {:schema data/Group :description "Only updates public field. Other fields are ignored."} 400 {:description "Only send the value for public:"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (repo/find-group-by-id group-id) (captains/ok (auth/coerce-group-based-on-access-type (repo/update-public-flag! group-id public-flag) user) (grplog/build-group-event user {:id group-id} "artstor_update_group_public" true {:public_flag public-flag})) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_update_group_public" false {:public_flag public-flag :artstor-error "I couldn't find a group with that id."})))) (PUT "/items/delete" [] :auth-rules auth/logged-in? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :body [object_ids [s/Str]] :summary "Deletes objects from groups" :responses {200 {:description "Objects deleted from image groups"} 400 {:description "Invalid object-id(s) supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The groups associated with the supplied objects could not be found"} 500 {:description "Server Error handling the request"}} (if (empty? object_ids) (bad-request) (let [result (repo/get-groups-associated-with-object-ids object_ids)] (if (not (empty? result)) (let [data (into [] (flatten (map #(get-in result [%]) object_ids))) group-ids (map #(get % :group_id) data)] (captains/ok (repo/delete-groups-associated-with-object-ids object_ids group-ids) (grplog/build-delete-objects-event user result "artstor_delete_pc_objects_from_groups" {:object_ids (vec object_ids)}))) (not-found {:success true :message "Couldn't find any of the groups containing the object-id(s)"} (grplog/build-delete-objects-event user "" "artstor_delete_pc_objects_from_groups" {:artstor-error "I couldn't find groups associated with given objects"})))))) (DELETE "/:group-id" [group-id] :auth-rules auth/is-admin? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :return {:success s/Bool :message s/Str} :path-params [group-id :- String] :summary "Deletes a group" :responses {200 {:description "Group has been deleted"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [id (repo/delete! group-id)] (captains/ok {:success true :message (str "Your group (" id ") has been deleted.")} (grplog/build-group-event user {:id group-id} "artstor_delete_group" true)) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_delete_group" false {:artstor-error "I couldn't find a group with that id."})))) (POST "/:group-id/share" [group-id] :auth-rules auth/is-admin? :current-user user :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [token (s/maybe data/NewToken)] :summary "Creates a token for sharing the specified group" :responses {200 {:schema {:success s/Bool :token s/Str} :description "One hot and fresh token"} 400 {:description "Invalid data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (>= (repo/count-group-shares group-id) 1000) (bad-request {:success false :message "Cannot share to more than 1000 entities"}) (if-let [token (repo/generate-token (Long/parseLong (get user :profile_id)) group-id (get token :access_type 100) (get token :expiration_time))] (captains/ok {:success true :token (util/encode-uuid (UUID/fromString token))} {:group_id group-id}) (not-found {:success false :message "I couldn't find a group with that id."})))) (POST "/redeem/:token" [token] :auth-rules auth/logged-in? :current-user user :return data/Group :path-params [token :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Redeems a token for access to the specified group" :responses {200 {:schema {:success s/Bool :group data/Group} :description "A lovely group for you to use."} 400 {:description "Invalid token supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The token was not found or it expired."} 500 {:description "Server Error handling the request"}} (if-let [redeeming-group (repo/get-group-from-token (util/decode-uuid token))] (if (>= (repo/count-redeeming-group-access redeeming-group) 1000) (bad-request {:success false :message "Cannot share to more than 1000 entities"}) (if-let [group (repo/redeem-token (Long/parseLong (get user :profile_id)) (util/decode-uuid token))] (captains/ok {:success true :group (auth/coerce-group-based-on-access-type group user)} {:group_id (get group :id "")}) (not-found {:success false :message "That token has apparently gone stale. We're so sorry."}))) (not-found {:success false :message "That token has apparently gone stale. We're so sorry."}))) (DELETE "/expire/:token" [token] :auth-rules auth/logged-in? :current-user user :return data/Group :path-params [token :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Invalidates a token so it can no longer be used" :responses {200 {:schema data/RequestStatus :description "A boolean indicator of success"} 400 {:description "Invalid token supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The token was not found"} 500 {:description "Server Error handling the request"}} (let [res (repo/delete-token! (Long/parseLong (get user :profile_id)) (util/decode-uuid token))] (if (> res 0) (captains/ok {:success true :message "I tossed your token in the bin."}) (not-found {:success false :message "Your token has apparently gone missing. We're so sorry."})))) (GET "/:group-id/tokens" [group-id] :auth-rules auth/is-admin? :current-user user :return [{:success s/Bool :tokens [data/Token]}] :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Returns any tokens that are set on the group" :responses {200 {:schema {:success s/Bool :tokens [data/Token]} :description "A list of tokens on this group"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group was not found"} 500 {:description "Server Error handling the request"}} (let [tokens (repo/get-tokens (Long/parseLong (get user :profile_id)) group-id)] (if (seq tokens) (captains/ok {:success true :tokens (map #(assoc % :token (util/encode-uuid (UUID/fromString (% :token)))) tokens)} {:group_id group-id}) (not-found {:success false :message "I'm sorry <NAME>, there are no tokens here."})))) (GET "/tags/suggest" [] :auth-rules auth/logged-in? :current-user user :return [{:success s/Bool :tags [s/Str]}] :query-params [{q :- s/Str nil} {size :- s/Int nil}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Returns any tags that match the group search query" :responses {200 {:schema {:success s/Bool :tags [s/Str]} :description "A list of tags"} 400 {:description "Invalid query supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "no matches found"} 500 {:description "Server Error handling the request"}} (let [number-to-return (repo/get-valid-tag-count size) tags (repo/get-tags-that-start-with q number-to-return)] (if (seq tags) (captains/ok {:success true :tags tags}) (not-found {:success false :message "I'm sorry <NAME>, there are no tags here."}))))) (context "/internal/generate" [] :tags ["web-token"] (POST "/" [] :return [{:success s/Bool :tags [s/Str]}] :body [data data/ArtstorUser] :summary "Returns a web token" :responses {200 {:schema {:success s/Bool :token s/Str} :description "Generate a Web token"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (let [wt (artstor-group-service.auth/generate-web-token data)] (if (nil? wt) (bad-request) (captains/ok {:success true :token wt}))))) (ANY "/*" [] :responses {404 {:schema data/RequestStatus}} (not-found {:success false :message "My human masters didn't plan for this eventuality. Pity."}))) (auth/add-cors) (auth/add-empty-body-to-posts) (captains/wrap-web-logging {:event-type-func grplog/determine-event-type}) (user/wrap-user-or-ip) (with-auth {:exclude-paths [#"/index.html" #"/swagger.json" #".\.js" #".*.js" #"/images/.*" #"/lib/.*" #"/css/.*" #"/conf/.*" #"/internal/.*" #"/" #"/watchable"]}) (util/wrap-method-override) (ring-logger/wrap-with-logger) (rcookie/wrap-cookies)))
true
(ns artstor-group-service.core (:require [clojure.spec :as spec] [schema.core :as s] [compojure.api.sweet :refer :all] [compojure.api.meta :refer [restructure-param]] [compojure.api.exception :as ex] [buddy.auth.accessrules :as baa] [ring.util.http-response :refer [bad-request]] [ring.middleware.cookies :as rcookie] [ring.logger :as ring-logger] [captains-common.core :as captains] [org.ithaka.clj-iacauth.ring.middleware :refer :all] [artstor-group-service.schema :as data] [artstor-group-service.repository :as repo] [artstor-group-service.service.metadata :as metadata] [artstor-group-service.auth :as auth] [artstor-group-service.user :as user] [artstor-group-service.util :as util :refer [not-found forbidden]] [artstor-group-service.logging :as grplog]) (:import (java.util UUID))) (defn access-error [req val] (forbidden (or val {:success false :message "Access denied"}))) (defn wrap-rule [handler rule] (-> handler (baa/wrap-access-rules {:rules [{:pattern #".*" :handler rule}] :on-error access-error}))) (defmethod restructure-param :auth-rules [_ rule acc] (update-in acc [:middleware] conj [wrap-rule rule])) (defmethod restructure-param :current-user [_ binding acc] (update-in acc [:letks] into [binding `(user/extract-user-or-ip ~'+compojure-api-request+)])) (def app (->> (api {:exceptions {:handlers {::ex/request-parsing (grplog/with-request-logging ex/request-parsing-handler) ::ex/request-validation (grplog/with-request-logging ex/request-validation-handler)}} :swagger {:ui "/" :spec "/swagger.json" :data {:info {:title "ANG Group Service API" :description "This service exposes CRUD methods for dealing with groups."} :tags [{:name "group" :description "Services for creating, updating, reading, and deleting groups"}]}}} (context "/api/v1/group" [] :tags ["group"] (GET "/" [] :auth-rules auth/can-perform-search? :return {:success s/Bool :total s/Int :groups [data/GroupSearch] :tags (s/maybe [{:key s/Str :doc_count s/Int}])} :header-params [{web-token :- (s/maybe s/Str) ""}] :query-params [{q :- s/Str nil} {tags :- [s/Str] []} {from :- s/Int 0} {size :- s/Int 24} {level :- (s/enum :all :public :institution :shared :private) :all}] :summary "Gets all Groups available for the currently logged in user" :current-user user :responses {200 {:schema {:success s/Bool :total s/Int :groups [data/GroupSearch] :tags (s/maybe [{:key s/Str :doc_count s/Int}])} :description "Search all groups and return matches"} 400 {:description "Invalid parameters supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (let [add-param {:tags tags :from from :size size :level level}] (captains/ok (repo/get-groups q (merge add-param {:profile-id (user :profile_id) :institution-ids (user :institution_ids)})) (grplog/build-search-event user (assoc add-param :query (if (nil? q) "" q)))))) (GET "/:group-id" [group-id] :auth-rules auth/can-read? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :query-params [{internal :- s/Bool false}] :summary "Returns a group object" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [found-group (repo/get-group group-id)] (let [deduped-group (repo/get-deduped-group found-group)] (captains/ok (auth/coerce-group-based-on-access-type deduped-group user) (grplog/build-group-event user deduped-group "artstor_read_group" true {:internal internal}))) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_read_group" false {:artstor-error "I couldn't find a group with that id." :internal internal})))) (POST "/" [] :auth-rules auth/logged-in? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :return data/Group :body [group data/NewGroup] :summary "Returns a freshly minted group object" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (if-let [errors (data/group-validator? group)] (bad-request errors) (let [newlygroup (repo/add! group user)] (captains/ok newlygroup (grplog/build-create-event user newlygroup))))) (POST "/:group-id/copy" [] :auth-rules auth/can-read? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [group-name {:name s/Str}] :summary "Returns a freshly minted group object copied from the provided group id" :responses {200 {:schema data/Group :description "A lovely group object"} 400 {:description "That's not a valid name"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "No group found to copy"} 500 {:description "Server Error handling the request"}} (if-let [errors (spec/explain-data ::data/name (group-name :name))] (bad-request errors) (if-let [new-group (repo/copy! group-id (group-name :name) user)] (captains/ok new-group (grplog/build-group-event user new-group "artstor_copy_group" true {:source_group_id group-id} )) (not-found {:success false :message "I couldn't find a group to copy."} (grplog/build-group-event user {:id group-id} "artstor_copy_group" false {:source_group_id group-id :artstor_error "I couldn't find a source group to copy."}))))) (GET "/:group-id/metadata" [group-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String] :query-params [{object_ids :- [s/Str] []} {legacy :- s/Bool true} {xml :- s/Bool false}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Gets the metadata for all the specified items the user has access too. (150 max) with group id" :responses {200 {:description "Find items by object_id and return metadata matches"} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if(repo/get-group group-id) (metadata/get-metadata group-id object_ids legacy xml (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (GET "/:group-id/secure/metadata/:object-id" [group-id object-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String object-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Accepts object-id in url and returns the metadata in legacy json format for the specified item." :responses {200 {:description "Find item by object_id and return legacy formatted metadata"} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if(repo/get-group group-id) (metadata/get-legacy-metadata group-id object-id (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (GET "/:group-id/items" [group-id] :auth-rules auth/can-read? :current-user user :path-params [group-id :- String] :query-params [{object_ids :- [s/Str] []}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Gets the Items for all the specified items the user has access too. (150 max) with group id" :responses {200 {:description "Find items by object_id and return item details."} 400 {:description "Invalid item/group identifiers supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The item-id/group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [found-group (repo/get-group group-id)] (metadata/get-items group-id object_ids (str (first (:institution_ids user)))) (not-found {:success false :message "I couldn't find a group/item with that id."}))) (PUT "/:group-id" [group-id] :auth-rules auth/can-write? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [group data/NewGroup] :summary "Updates a group object" :responses {200 {:schema data/Group :description "A lovely updated group object"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (repo/find-group-by-id group-id) (if (or (auth/can-change-group-access? user group-id) (empty? (group :access))) (if-let [errors (data/group-errors? group)] (bad-request errors) (captains/ok (auth/coerce-group-based-on-access-type (repo/update! group-id group) user) (grplog/build-group-event user (assoc group :id group-id) "artstor_update_group" true))) (forbidden {:success false :message "Insufficient Privileges"} (grplog/build-group-event user (assoc group :id group-id) "artstor_update_group" false {:artstor-error "Insufficient Privileges"}))) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_update_group" false {:artstor-error "I couldn't find a group with that id."})))) (PUT "/:group-id/admin/public" [group-id] :auth-rules auth/artstor-admin? :current-user user :return data/Group :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [public-flag {:public s/Bool}] :summary "For Artstor admin use only: Updates the group's public value." :responses {200 {:schema data/Group :description "Only updates public field. Other fields are ignored."} 400 {:description "Only send the value for public:"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (repo/find-group-by-id group-id) (captains/ok (auth/coerce-group-based-on-access-type (repo/update-public-flag! group-id public-flag) user) (grplog/build-group-event user {:id group-id} "artstor_update_group_public" true {:public_flag public-flag})) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_update_group_public" false {:public_flag public-flag :artstor-error "I couldn't find a group with that id."})))) (PUT "/items/delete" [] :auth-rules auth/logged-in? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :body [object_ids [s/Str]] :summary "Deletes objects from groups" :responses {200 {:description "Objects deleted from image groups"} 400 {:description "Invalid object-id(s) supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The groups associated with the supplied objects could not be found"} 500 {:description "Server Error handling the request"}} (if (empty? object_ids) (bad-request) (let [result (repo/get-groups-associated-with-object-ids object_ids)] (if (not (empty? result)) (let [data (into [] (flatten (map #(get-in result [%]) object_ids))) group-ids (map #(get % :group_id) data)] (captains/ok (repo/delete-groups-associated-with-object-ids object_ids group-ids) (grplog/build-delete-objects-event user result "artstor_delete_pc_objects_from_groups" {:object_ids (vec object_ids)}))) (not-found {:success true :message "Couldn't find any of the groups containing the object-id(s)"} (grplog/build-delete-objects-event user "" "artstor_delete_pc_objects_from_groups" {:artstor-error "I couldn't find groups associated with given objects"})))))) (DELETE "/:group-id" [group-id] :auth-rules auth/is-admin? :current-user user :header-params [{web-token :- (s/maybe s/Str) ""}] :return {:success s/Bool :message s/Str} :path-params [group-id :- String] :summary "Deletes a group" :responses {200 {:description "Group has been deleted"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if-let [id (repo/delete! group-id)] (captains/ok {:success true :message (str "Your group (" id ") has been deleted.")} (grplog/build-group-event user {:id group-id} "artstor_delete_group" true)) (not-found {:success false :message "I couldn't find a group with that id."} (grplog/build-group-event user {:id group-id} "artstor_delete_group" false {:artstor-error "I couldn't find a group with that id."})))) (POST "/:group-id/share" [group-id] :auth-rules auth/is-admin? :current-user user :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :body [token (s/maybe data/NewToken)] :summary "Creates a token for sharing the specified group" :responses {200 {:schema {:success s/Bool :token s/Str} :description "One hot and fresh token"} 400 {:description "Invalid data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group-id supplied could not be found"} 500 {:description "Server Error handling the request"}} (if (>= (repo/count-group-shares group-id) 1000) (bad-request {:success false :message "Cannot share to more than 1000 entities"}) (if-let [token (repo/generate-token (Long/parseLong (get user :profile_id)) group-id (get token :access_type 100) (get token :expiration_time))] (captains/ok {:success true :token (util/encode-uuid (UUID/fromString token))} {:group_id group-id}) (not-found {:success false :message "I couldn't find a group with that id."})))) (POST "/redeem/:token" [token] :auth-rules auth/logged-in? :current-user user :return data/Group :path-params [token :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Redeems a token for access to the specified group" :responses {200 {:schema {:success s/Bool :group data/Group} :description "A lovely group for you to use."} 400 {:description "Invalid token supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The token was not found or it expired."} 500 {:description "Server Error handling the request"}} (if-let [redeeming-group (repo/get-group-from-token (util/decode-uuid token))] (if (>= (repo/count-redeeming-group-access redeeming-group) 1000) (bad-request {:success false :message "Cannot share to more than 1000 entities"}) (if-let [group (repo/redeem-token (Long/parseLong (get user :profile_id)) (util/decode-uuid token))] (captains/ok {:success true :group (auth/coerce-group-based-on-access-type group user)} {:group_id (get group :id "")}) (not-found {:success false :message "That token has apparently gone stale. We're so sorry."}))) (not-found {:success false :message "That token has apparently gone stale. We're so sorry."}))) (DELETE "/expire/:token" [token] :auth-rules auth/logged-in? :current-user user :return data/Group :path-params [token :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Invalidates a token so it can no longer be used" :responses {200 {:schema data/RequestStatus :description "A boolean indicator of success"} 400 {:description "Invalid token supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The token was not found"} 500 {:description "Server Error handling the request"}} (let [res (repo/delete-token! (Long/parseLong (get user :profile_id)) (util/decode-uuid token))] (if (> res 0) (captains/ok {:success true :message "I tossed your token in the bin."}) (not-found {:success false :message "Your token has apparently gone missing. We're so sorry."})))) (GET "/:group-id/tokens" [group-id] :auth-rules auth/is-admin? :current-user user :return [{:success s/Bool :tokens [data/Token]}] :path-params [group-id :- String] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Returns any tokens that are set on the group" :responses {200 {:schema {:success s/Bool :tokens [data/Token]} :description "A list of tokens on this group"} 400 {:description "Invalid group-id supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "The group was not found"} 500 {:description "Server Error handling the request"}} (let [tokens (repo/get-tokens (Long/parseLong (get user :profile_id)) group-id)] (if (seq tokens) (captains/ok {:success true :tokens (map #(assoc % :token (util/encode-uuid (UUID/fromString (% :token)))) tokens)} {:group_id group-id}) (not-found {:success false :message "I'm sorry PI:NAME:<NAME>END_PI, there are no tokens here."})))) (GET "/tags/suggest" [] :auth-rules auth/logged-in? :current-user user :return [{:success s/Bool :tags [s/Str]}] :query-params [{q :- s/Str nil} {size :- s/Int nil}] :header-params [{web-token :- (s/maybe s/Str) ""}] :summary "Returns any tags that match the group search query" :responses {200 {:schema {:success s/Bool :tags [s/Str]} :description "A list of tags"} 400 {:description "Invalid query supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 404 {:schema data/RequestStatus :description "no matches found"} 500 {:description "Server Error handling the request"}} (let [number-to-return (repo/get-valid-tag-count size) tags (repo/get-tags-that-start-with q number-to-return)] (if (seq tags) (captains/ok {:success true :tags tags}) (not-found {:success false :message "I'm sorry PI:NAME:<NAME>END_PI, there are no tags here."}))))) (context "/internal/generate" [] :tags ["web-token"] (POST "/" [] :return [{:success s/Bool :tags [s/Str]}] :body [data data/ArtstorUser] :summary "Returns a web token" :responses {200 {:schema {:success s/Bool :token s/Str} :description "Generate a Web token"} 400 {:description "Invalid form data supplied"} 401 {:description "Unauthorised"} 403 {:description "Access denied"} 500 {:description "Server Error handling the request"}} (let [wt (artstor-group-service.auth/generate-web-token data)] (if (nil? wt) (bad-request) (captains/ok {:success true :token wt}))))) (ANY "/*" [] :responses {404 {:schema data/RequestStatus}} (not-found {:success false :message "My human masters didn't plan for this eventuality. Pity."}))) (auth/add-cors) (auth/add-empty-body-to-posts) (captains/wrap-web-logging {:event-type-func grplog/determine-event-type}) (user/wrap-user-or-ip) (with-auth {:exclude-paths [#"/index.html" #"/swagger.json" #".\.js" #".*.js" #"/images/.*" #"/lib/.*" #"/css/.*" #"/conf/.*" #"/internal/.*" #"/" #"/watchable"]}) (util/wrap-method-override) (ring-logger/wrap-with-logger) (rcookie/wrap-cookies)))
[ { "context": ";; Copyright (c) Vital Labs, Inc. All rights reserved. The use and\n;; distri", "end": 27, "score": 0.9774565100669861, "start": 17, "tag": "NAME", "value": "Vital Labs" } ]
src/clojurecast/lang/cache.clj
VitalLabs/clojurecast
0
;; Copyright (c) Vital Labs, Inc. All rights reserved. The use and ;; distribution terms for this software are covered by the MIT ;; License (https://opensource.org/licenses/MIT) which can be found ;; in the file LICENSE at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be ;; bound by the terms of this license. You must not remove this notice, ;; or any other, from this software. (ns clojurecast.lang.cache (:require [clojure.core.cache :as cache] [clojurecast.lang.util :as util] [clojurecast.lang.interfaces])) (deftype Cache [])
56427
;; Copyright (c) <NAME>, Inc. All rights reserved. The use and ;; distribution terms for this software are covered by the MIT ;; License (https://opensource.org/licenses/MIT) which can be found ;; in the file LICENSE at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be ;; bound by the terms of this license. You must not remove this notice, ;; or any other, from this software. (ns clojurecast.lang.cache (:require [clojure.core.cache :as cache] [clojurecast.lang.util :as util] [clojurecast.lang.interfaces])) (deftype Cache [])
true
;; Copyright (c) PI:NAME:<NAME>END_PI, Inc. All rights reserved. The use and ;; distribution terms for this software are covered by the MIT ;; License (https://opensource.org/licenses/MIT) which can be found ;; in the file LICENSE at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be ;; bound by the terms of this license. You must not remove this notice, ;; or any other, from this software. (ns clojurecast.lang.cache (:require [clojure.core.cache :as cache] [clojurecast.lang.util :as util] [clojurecast.lang.interfaces])) (deftype Cache [])
[ { "context": "\n (spit (io/file src-dir \"ivan.txt\") \"Hey Ivan!\")\n\n (t/is (= cp-2\n (-", "end": 2048, "score": 0.7972273826599121, "start": 2044, "tag": "NAME", "value": "Ivan" }, { "context": "est-dir \"hello.txt\"))))\n\n (t/is (= \"Hey Ivan!\"\n (slurp (io/file dest-dir \"", "end": 2827, "score": 0.8778002262115479, "start": 2823, "tag": "NAME", "value": "Ivan" } ]
crux-s3/test/crux/s3/checkpoint_test.clj
deobald/crux
0
(ns crux.s3.checkpoint-test (:require [crux.s3.checkpoint :as s3c] [crux.s3-test :as s3t] [clojure.test :as t] [crux.fixtures :as fix] [crux.system :as sys] [clojure.java.io :as io] [crux.checkpoint :as cp] [crux.tx :as tx]) (:import (java.util UUID))) (t/use-fixtures :once s3t/with-s3-client) (t/deftest test-checkpoint-store (with-open [sys (-> (sys/prep-system {:store {:crux/module `s3c/->cp-store :configurator `s3t/->configurator :bucket s3t/test-s3-bucket :prefix (str "s3-cp-" (UUID/randomUUID))}}) (sys/start-system))] (fix/with-tmp-dir "s3-cp" [cp-dir] (let [{:keys [store]} sys src-dir (doto (io/file cp-dir "src") (.mkdirs)) cp-1 {::cp/cp-format ::foo-cp-format :tx {::tx/tx-id 1}} cp-2 {::cp/cp-format ::foo-cp-format :tx {::tx/tx-id 2}}] (t/testing "first checkpoint" (spit (io/file src-dir "hello.txt") "Hello world") (t/is (= cp-1 (-> (cp/upload-checkpoint store src-dir cp-1) (select-keys #{::cp/cp-format :tx})))) (t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format}))) (let [dest-dir (io/file cp-dir "dest") cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})] (t/is (= [cp-1] (->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format}) (map #(select-keys % #{::cp/cp-format :tx}))))) (cp/download-checkpoint store (first cps) dest-dir) (t/is (= "Hello world" (slurp (io/file dest-dir "hello.txt")))))) (t/testing "second checkpoint" (spit (io/file src-dir "ivan.txt") "Hey Ivan!") (t/is (= cp-2 (-> (cp/upload-checkpoint store src-dir cp-2) (select-keys #{::cp/cp-format :tx})))) (t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format}))) (let [dest-dir (io/file cp-dir "dest-2") cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})] (t/is (= [cp-2 cp-1] (->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format}) (map #(select-keys % #{::cp/cp-format :tx}))))) (cp/download-checkpoint store (first cps) dest-dir) (t/is (= "Hello world" (slurp (io/file dest-dir "hello.txt")))) (t/is (= "Hey Ivan!" (slurp (io/file dest-dir "ivan.txt"))))))))))
118748
(ns crux.s3.checkpoint-test (:require [crux.s3.checkpoint :as s3c] [crux.s3-test :as s3t] [clojure.test :as t] [crux.fixtures :as fix] [crux.system :as sys] [clojure.java.io :as io] [crux.checkpoint :as cp] [crux.tx :as tx]) (:import (java.util UUID))) (t/use-fixtures :once s3t/with-s3-client) (t/deftest test-checkpoint-store (with-open [sys (-> (sys/prep-system {:store {:crux/module `s3c/->cp-store :configurator `s3t/->configurator :bucket s3t/test-s3-bucket :prefix (str "s3-cp-" (UUID/randomUUID))}}) (sys/start-system))] (fix/with-tmp-dir "s3-cp" [cp-dir] (let [{:keys [store]} sys src-dir (doto (io/file cp-dir "src") (.mkdirs)) cp-1 {::cp/cp-format ::foo-cp-format :tx {::tx/tx-id 1}} cp-2 {::cp/cp-format ::foo-cp-format :tx {::tx/tx-id 2}}] (t/testing "first checkpoint" (spit (io/file src-dir "hello.txt") "Hello world") (t/is (= cp-1 (-> (cp/upload-checkpoint store src-dir cp-1) (select-keys #{::cp/cp-format :tx})))) (t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format}))) (let [dest-dir (io/file cp-dir "dest") cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})] (t/is (= [cp-1] (->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format}) (map #(select-keys % #{::cp/cp-format :tx}))))) (cp/download-checkpoint store (first cps) dest-dir) (t/is (= "Hello world" (slurp (io/file dest-dir "hello.txt")))))) (t/testing "second checkpoint" (spit (io/file src-dir "ivan.txt") "Hey <NAME>!") (t/is (= cp-2 (-> (cp/upload-checkpoint store src-dir cp-2) (select-keys #{::cp/cp-format :tx})))) (t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format}))) (let [dest-dir (io/file cp-dir "dest-2") cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})] (t/is (= [cp-2 cp-1] (->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format}) (map #(select-keys % #{::cp/cp-format :tx}))))) (cp/download-checkpoint store (first cps) dest-dir) (t/is (= "Hello world" (slurp (io/file dest-dir "hello.txt")))) (t/is (= "Hey <NAME>!" (slurp (io/file dest-dir "ivan.txt"))))))))))
true
(ns crux.s3.checkpoint-test (:require [crux.s3.checkpoint :as s3c] [crux.s3-test :as s3t] [clojure.test :as t] [crux.fixtures :as fix] [crux.system :as sys] [clojure.java.io :as io] [crux.checkpoint :as cp] [crux.tx :as tx]) (:import (java.util UUID))) (t/use-fixtures :once s3t/with-s3-client) (t/deftest test-checkpoint-store (with-open [sys (-> (sys/prep-system {:store {:crux/module `s3c/->cp-store :configurator `s3t/->configurator :bucket s3t/test-s3-bucket :prefix (str "s3-cp-" (UUID/randomUUID))}}) (sys/start-system))] (fix/with-tmp-dir "s3-cp" [cp-dir] (let [{:keys [store]} sys src-dir (doto (io/file cp-dir "src") (.mkdirs)) cp-1 {::cp/cp-format ::foo-cp-format :tx {::tx/tx-id 1}} cp-2 {::cp/cp-format ::foo-cp-format :tx {::tx/tx-id 2}}] (t/testing "first checkpoint" (spit (io/file src-dir "hello.txt") "Hello world") (t/is (= cp-1 (-> (cp/upload-checkpoint store src-dir cp-1) (select-keys #{::cp/cp-format :tx})))) (t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format}))) (let [dest-dir (io/file cp-dir "dest") cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})] (t/is (= [cp-1] (->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format}) (map #(select-keys % #{::cp/cp-format :tx}))))) (cp/download-checkpoint store (first cps) dest-dir) (t/is (= "Hello world" (slurp (io/file dest-dir "hello.txt")))))) (t/testing "second checkpoint" (spit (io/file src-dir "ivan.txt") "Hey PI:NAME:<NAME>END_PI!") (t/is (= cp-2 (-> (cp/upload-checkpoint store src-dir cp-2) (select-keys #{::cp/cp-format :tx})))) (t/is (empty? (cp/available-checkpoints store {::cp/cp-format ::bar-cp-format}))) (let [dest-dir (io/file cp-dir "dest-2") cps (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format})] (t/is (= [cp-2 cp-1] (->> (cp/available-checkpoints store {::cp/cp-format ::foo-cp-format}) (map #(select-keys % #{::cp/cp-format :tx}))))) (cp/download-checkpoint store (first cps) dest-dir) (t/is (= "Hello world" (slurp (io/file dest-dir "hello.txt")))) (t/is (= "Hey PI:NAME:<NAME>END_PI!" (slurp (io/file dest-dir "ivan.txt"))))))))))
[ { "context": "cute JRuby code.\"\n :url \"https://github.com/tobias/boot-jruby\"\n :scm {:url \"https://github.com", "end": 332, "score": 0.999504029750824, "start": 326, "tag": "USERNAME", "value": "tobias" }, { "context": "boot-jruby\"\n :scm {:url \"https://github.com/tobias/boot-jruby\"}\n :license {:name \"Apache Softw", "end": 389, "score": 0.999440610408783, "start": 383, "tag": "USERNAME", "value": "tobias" }, { "context": "0\"}}\n push {:gpg-sign true\n :gpg-user-id \"toby@tcrawley.org\"\n :repo \"clojars\"})\n\n(deftask build\n \"Bui", "end": 591, "score": 0.9999101161956787, "start": 574, "tag": "EMAIL", "value": "toby@tcrawley.org" } ]
build.boot
micha/boot-jruby
1
(set-env! :dependencies '[[org.clojure/clojure "1.6.0" :scope "provided"] [clj.rb "0.3.0"]] :resource-paths #{"src"}) (def +version+ "0.2.0") (task-options! pom {:project 'boot-jruby :version +version+ :description "Boot task to execute JRuby code." :url "https://github.com/tobias/boot-jruby" :scm {:url "https://github.com/tobias/boot-jruby"} :license {:name "Apache Software License - v 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"}} push {:gpg-sign true :gpg-user-id "toby@tcrawley.org" :repo "clojars"}) (deftask build "Build and install the artifact." [] (comp (pom) (jar) (install)))
50097
(set-env! :dependencies '[[org.clojure/clojure "1.6.0" :scope "provided"] [clj.rb "0.3.0"]] :resource-paths #{"src"}) (def +version+ "0.2.0") (task-options! pom {:project 'boot-jruby :version +version+ :description "Boot task to execute JRuby code." :url "https://github.com/tobias/boot-jruby" :scm {:url "https://github.com/tobias/boot-jruby"} :license {:name "Apache Software License - v 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"}} push {:gpg-sign true :gpg-user-id "<EMAIL>" :repo "clojars"}) (deftask build "Build and install the artifact." [] (comp (pom) (jar) (install)))
true
(set-env! :dependencies '[[org.clojure/clojure "1.6.0" :scope "provided"] [clj.rb "0.3.0"]] :resource-paths #{"src"}) (def +version+ "0.2.0") (task-options! pom {:project 'boot-jruby :version +version+ :description "Boot task to execute JRuby code." :url "https://github.com/tobias/boot-jruby" :scm {:url "https://github.com/tobias/boot-jruby"} :license {:name "Apache Software License - v 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0"}} push {:gpg-sign true :gpg-user-id "PI:EMAIL:<EMAIL>END_PI" :repo "clojars"}) (deftask build "Build and install the artifact." [] (comp (pom) (jar) (install)))
[ { "context": " [clojure.tools.namespace.dependency :as dep]\n [robert.hooke]\n [leiningen.test])\n (:import\n [java.io", "end": 217, "score": 0.7662705779075623, "start": 211, "tag": "USERNAME", "value": "robert" }, { "context": "re.tools.namespace.dependency :as dep]\n [robert.hooke]\n [leiningen.test])\n (:import\n [java.io File", "end": 223, "score": 0.7012754082679749, "start": 218, "tag": "NAME", "value": "hooke" } ]
src/leiningen/barrier.clj
TriforkSE/lein-barrier
1
(ns leiningen.barrier (:require [leiningen.core.main :as main] [clojure.tools.namespace.find :as ns-find] [clojure.tools.namespace.parse :as parse] [clojure.tools.namespace.dependency :as dep] [robert.hooke] [leiningen.test]) (:import [java.io File])) (def ^:dynamic *exit-after-barrier* true) (def ^:dynamic *ansi-colors-enabled* true) (def colors {:green "\033[32m" :red "\033[31m" :reset "\033[0m"}) (defn get-color [color] (when *ansi-colors-enabled* (get colors color))) (defn- get-all-ns-declarations [source-paths] (->> (map #(File. %) source-paths) (mapcat ns-find/find-ns-decls-in-dir) (map (juxt second parse/deps-from-ns-decl)))) (defn- add-deps [dep-graph depmap] (reduce (fn [ds [name dependencies]] (reduce (fn [g dep] (dep/depend g name dep)) ds dependencies)) dep-graph depmap)) (defn get-dep-graph [source-paths] (->> (get-all-ns-declarations source-paths) (into {}) (add-deps (dep/graph)))) (defn- unwind [m] (for [[k vs] m v vs] [k v])) (defn- check-constraints [deps constraints] (apply merge-with conj {:failed [] :passed []} (for [[x y] (unwind constraints)] (if (dep/depends? deps x y) {:failed [x y]} {:passed [x y]})))) (defn- dep-str [text x y c] (println (get-color c) text (str "[" x "] -> [" y "]") (get-color :reset))) (defn- handle-results [{failed :failed passed :passed}] (doseq [[x y] passed] (dep-str "Constraint Passed: " x y :green)) (doseq [[x y] failed] (dep-str "Constraint Violated: " x y :red)) (when *exit-after-barrier* (System/exit (count failed)))) (defn barrier "Check code barriers" [project & args] (let [source-paths (:source-paths project) barriers (:barriers project)] (-> (get-dep-graph source-paths) (check-constraints barriers) (handle-results))))
20851
(ns leiningen.barrier (:require [leiningen.core.main :as main] [clojure.tools.namespace.find :as ns-find] [clojure.tools.namespace.parse :as parse] [clojure.tools.namespace.dependency :as dep] [robert.<NAME>] [leiningen.test]) (:import [java.io File])) (def ^:dynamic *exit-after-barrier* true) (def ^:dynamic *ansi-colors-enabled* true) (def colors {:green "\033[32m" :red "\033[31m" :reset "\033[0m"}) (defn get-color [color] (when *ansi-colors-enabled* (get colors color))) (defn- get-all-ns-declarations [source-paths] (->> (map #(File. %) source-paths) (mapcat ns-find/find-ns-decls-in-dir) (map (juxt second parse/deps-from-ns-decl)))) (defn- add-deps [dep-graph depmap] (reduce (fn [ds [name dependencies]] (reduce (fn [g dep] (dep/depend g name dep)) ds dependencies)) dep-graph depmap)) (defn get-dep-graph [source-paths] (->> (get-all-ns-declarations source-paths) (into {}) (add-deps (dep/graph)))) (defn- unwind [m] (for [[k vs] m v vs] [k v])) (defn- check-constraints [deps constraints] (apply merge-with conj {:failed [] :passed []} (for [[x y] (unwind constraints)] (if (dep/depends? deps x y) {:failed [x y]} {:passed [x y]})))) (defn- dep-str [text x y c] (println (get-color c) text (str "[" x "] -> [" y "]") (get-color :reset))) (defn- handle-results [{failed :failed passed :passed}] (doseq [[x y] passed] (dep-str "Constraint Passed: " x y :green)) (doseq [[x y] failed] (dep-str "Constraint Violated: " x y :red)) (when *exit-after-barrier* (System/exit (count failed)))) (defn barrier "Check code barriers" [project & args] (let [source-paths (:source-paths project) barriers (:barriers project)] (-> (get-dep-graph source-paths) (check-constraints barriers) (handle-results))))
true
(ns leiningen.barrier (:require [leiningen.core.main :as main] [clojure.tools.namespace.find :as ns-find] [clojure.tools.namespace.parse :as parse] [clojure.tools.namespace.dependency :as dep] [robert.PI:NAME:<NAME>END_PI] [leiningen.test]) (:import [java.io File])) (def ^:dynamic *exit-after-barrier* true) (def ^:dynamic *ansi-colors-enabled* true) (def colors {:green "\033[32m" :red "\033[31m" :reset "\033[0m"}) (defn get-color [color] (when *ansi-colors-enabled* (get colors color))) (defn- get-all-ns-declarations [source-paths] (->> (map #(File. %) source-paths) (mapcat ns-find/find-ns-decls-in-dir) (map (juxt second parse/deps-from-ns-decl)))) (defn- add-deps [dep-graph depmap] (reduce (fn [ds [name dependencies]] (reduce (fn [g dep] (dep/depend g name dep)) ds dependencies)) dep-graph depmap)) (defn get-dep-graph [source-paths] (->> (get-all-ns-declarations source-paths) (into {}) (add-deps (dep/graph)))) (defn- unwind [m] (for [[k vs] m v vs] [k v])) (defn- check-constraints [deps constraints] (apply merge-with conj {:failed [] :passed []} (for [[x y] (unwind constraints)] (if (dep/depends? deps x y) {:failed [x y]} {:passed [x y]})))) (defn- dep-str [text x y c] (println (get-color c) text (str "[" x "] -> [" y "]") (get-color :reset))) (defn- handle-results [{failed :failed passed :passed}] (doseq [[x y] passed] (dep-str "Constraint Passed: " x y :green)) (doseq [[x y] failed] (dep-str "Constraint Violated: " x y :red)) (when *exit-after-barrier* (System/exit (count failed)))) (defn barrier "Check code barriers" [project & args] (let [source-paths (:source-paths project) barriers (:barriers project)] (-> (get-dep-graph source-paths) (check-constraints barriers) (handle-results))))
[ { "context": "\n (let [key (SecretKeySpec. (.getBytes secret) \"HmacSHA1\")\n mac (doto (Mac/getInstance \"HmacSHA1\")", "end": 369, "score": 0.9945522546768188, "start": 361, "tag": "KEY", "value": "HmacSHA1" } ]
src/exoscale/compute/api/hmac.clj
exoscale/clojure-exoscale
2
(ns exoscale.compute.api.hmac "HMAC-SHA1 signing" (:import javax.crypto.spec.SecretKeySpec javax.crypto.Mac java.util.Base64)) (defn sha1 "Given a secret, compute the base64 encoded representation of a payload's Hmac-Sha1" [^String secret ^String input] {:pre [(seq secret)]} (let [key (SecretKeySpec. (.getBytes secret) "HmacSHA1") mac (doto (Mac/getInstance "HmacSHA1") (.init key))] (some->> input (.getBytes) (.doFinal mac) (.encodeToString (Base64/getEncoder)))))
92136
(ns exoscale.compute.api.hmac "HMAC-SHA1 signing" (:import javax.crypto.spec.SecretKeySpec javax.crypto.Mac java.util.Base64)) (defn sha1 "Given a secret, compute the base64 encoded representation of a payload's Hmac-Sha1" [^String secret ^String input] {:pre [(seq secret)]} (let [key (SecretKeySpec. (.getBytes secret) "<KEY>") mac (doto (Mac/getInstance "HmacSHA1") (.init key))] (some->> input (.getBytes) (.doFinal mac) (.encodeToString (Base64/getEncoder)))))
true
(ns exoscale.compute.api.hmac "HMAC-SHA1 signing" (:import javax.crypto.spec.SecretKeySpec javax.crypto.Mac java.util.Base64)) (defn sha1 "Given a secret, compute the base64 encoded representation of a payload's Hmac-Sha1" [^String secret ^String input] {:pre [(seq secret)]} (let [key (SecretKeySpec. (.getBytes secret) "PI:KEY:<KEY>END_PI") mac (doto (Mac/getInstance "HmacSHA1") (.init key))] (some->> input (.getBytes) (.doFinal mac) (.encodeToString (Base64/getEncoder)))))
[ { "context": ")\n '{:find [e]\n :where [[e :name \"Pablo\"]]})\n;; end::query-valid-time[]\n)\n\n\n\n#_(comment\n;", "end": 1143, "score": 0.9987124800682068, "start": 1138, "tag": "NAME", "value": "Pablo" }, { "context": "{:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 100}\n #inst \"2018-05-18T0", "end": 1312, "score": 0.9995153546333313, "start": 1308, "tag": "NAME", "value": "Jeff" }, { "context": "{:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 1000}\n #inst \"2015-05-18T", "end": 1451, "score": 0.9997704029083252, "start": 1447, "tag": "NAME", "value": "Jeff" }, { "context": " {:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 100}}\n {:crux.tx/tx-time #inst", "end": 2692, "score": 0.9994210004806519, "start": 2688, "tag": "NAME", "value": "Jeff" }, { "context": " {:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 1000}}]\n;; end::history-with-d", "end": 3005, "score": 0.9992797374725342, "start": 3001, "tag": "NAME", "value": "Jeff" }, { "context": "\n(api/entity-history\n (api/db node)\n :ids.persons/Jeff\n :asc\n {:start {:crux.db/valid-time #inst \"2015-0", "end": 3396, "score": 0.7141898274421692, "start": 3392, "tag": "USERNAME", "value": "Jeff" } ]
docs/reference/modules/ROOT/examples/test/crux/docs/examples_test.clj
jonpither/crux
0
(ns crux.docs.examples-test (:require [clojure.java.io :as io] [crux.api :as crux])) ;; tag::require-ek[] (require '[crux.kafka.embedded :as ek]) ;; end::require-ek[] ;; tag::ek-example[] (defn start-embedded-kafka [kafka-port storage-dir] (ek/start-embedded-kafka {:crux.kafka.embedded/zookeeper-data-dir (io/file storage-dir "zk-data") :crux.kafka.embedded/kafka-log-dir (io/file storage-dir "kafka-log") :crux.kafka.embedded/kafka-port kafka-port})) ;; end::ek-example[] (defn stop-embedded-kafka [^java.io.Closeable embedded-kafka] ;; tag::ek-close[] (.close embedded-kafka) ;; end::ek-close[] ) ;; tag::start-http-client[] (defn start-http-client [port] (crux/new-api-client (str "http://localhost:" port))) ;; end::start-http-client[] (defn example-query-entity [node] ;; tag::query-entity[] (crux/entity (crux/db node) :dbpedia.resource/Pablo-Picasso) ;; end::query-entity[] ) (defn example-query-valid-time [node] ;; tag::query-valid-time[] (crux/q (crux/db node #inst "2018-05-19T09:20:27.966-00:00") '{:find [e] :where [[e :name "Pablo"]]}) ;; end::query-valid-time[] ) #_(comment ;; tag::history-full[] (api/submit-tx node [[:crux.tx/put {:crux.db/id :ids.persons/Jeff :person/name "Jeff" :person/wealth 100} #inst "2018-05-18T09:20:27.966"] [:crux.tx/put {:crux.db/id :ids.persons/Jeff :person/name "Jeff" :person/wealth 1000} #inst "2015-05-18T09:20:27.966"]]) ; yields {:crux.tx/tx-id 1555314836178, :crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"} ; Returning the history in descending order ; To return in ascending order, use :asc in place of :desc (api/entity-history (api/db node) :ids.persons/Jeff :desc) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817, :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash ; sha1 hash of document contents "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"} {:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"}] ;; end::history-full[] ;; tag::history-with-docs[] (api/entity-history (api/db node) :ids.persons/Jeff :desc {:with-docs? true}) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817, :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561" :crux.db/doc {:crux.db/id :ids.persons/Jeff :person/name "Jeff" :person/wealth 100}} {:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529" :crux.db/doc {:crux.db/id :ids.persons/Jeff :person/name "Jeff" :person/wealth 1000}}] ;; end::history-with-docs[] ;; tag::history-range[] ; Passing the additional 'opts' map with the start/end bounds. ; As we are returning results in :asc order, the :start map contains the earlier coordinates - ; If returning history range in descending order, we pass the later coordinates to the :start map (api/entity-history (api/db node) :ids.persons/Jeff :asc {:start {:crux.db/valid-time #inst "2015-05-18T09:20:27.966" ; valid-time-start :crux.tx/tx-time #inst "2015-05-18T09:20:27.966"} ; tx-time-start :end {:crux.db/valid-time #inst "2020-05-18T09:20:27.966" ; valid-time-end :crux.tx/tx-time #inst "2020-05-18T09:20:27.966"} ; tx-time-end }) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"} {:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817 :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}] ;; end::history-range[] )
61803
(ns crux.docs.examples-test (:require [clojure.java.io :as io] [crux.api :as crux])) ;; tag::require-ek[] (require '[crux.kafka.embedded :as ek]) ;; end::require-ek[] ;; tag::ek-example[] (defn start-embedded-kafka [kafka-port storage-dir] (ek/start-embedded-kafka {:crux.kafka.embedded/zookeeper-data-dir (io/file storage-dir "zk-data") :crux.kafka.embedded/kafka-log-dir (io/file storage-dir "kafka-log") :crux.kafka.embedded/kafka-port kafka-port})) ;; end::ek-example[] (defn stop-embedded-kafka [^java.io.Closeable embedded-kafka] ;; tag::ek-close[] (.close embedded-kafka) ;; end::ek-close[] ) ;; tag::start-http-client[] (defn start-http-client [port] (crux/new-api-client (str "http://localhost:" port))) ;; end::start-http-client[] (defn example-query-entity [node] ;; tag::query-entity[] (crux/entity (crux/db node) :dbpedia.resource/Pablo-Picasso) ;; end::query-entity[] ) (defn example-query-valid-time [node] ;; tag::query-valid-time[] (crux/q (crux/db node #inst "2018-05-19T09:20:27.966-00:00") '{:find [e] :where [[e :name "<NAME>"]]}) ;; end::query-valid-time[] ) #_(comment ;; tag::history-full[] (api/submit-tx node [[:crux.tx/put {:crux.db/id :ids.persons/Jeff :person/name "<NAME>" :person/wealth 100} #inst "2018-05-18T09:20:27.966"] [:crux.tx/put {:crux.db/id :ids.persons/Jeff :person/name "<NAME>" :person/wealth 1000} #inst "2015-05-18T09:20:27.966"]]) ; yields {:crux.tx/tx-id 1555314836178, :crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"} ; Returning the history in descending order ; To return in ascending order, use :asc in place of :desc (api/entity-history (api/db node) :ids.persons/Jeff :desc) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817, :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash ; sha1 hash of document contents "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"} {:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"}] ;; end::history-full[] ;; tag::history-with-docs[] (api/entity-history (api/db node) :ids.persons/Jeff :desc {:with-docs? true}) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817, :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561" :crux.db/doc {:crux.db/id :ids.persons/Jeff :person/name "<NAME>" :person/wealth 100}} {:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529" :crux.db/doc {:crux.db/id :ids.persons/Jeff :person/name "<NAME>" :person/wealth 1000}}] ;; end::history-with-docs[] ;; tag::history-range[] ; Passing the additional 'opts' map with the start/end bounds. ; As we are returning results in :asc order, the :start map contains the earlier coordinates - ; If returning history range in descending order, we pass the later coordinates to the :start map (api/entity-history (api/db node) :ids.persons/Jeff :asc {:start {:crux.db/valid-time #inst "2015-05-18T09:20:27.966" ; valid-time-start :crux.tx/tx-time #inst "2015-05-18T09:20:27.966"} ; tx-time-start :end {:crux.db/valid-time #inst "2020-05-18T09:20:27.966" ; valid-time-end :crux.tx/tx-time #inst "2020-05-18T09:20:27.966"} ; tx-time-end }) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"} {:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817 :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}] ;; end::history-range[] )
true
(ns crux.docs.examples-test (:require [clojure.java.io :as io] [crux.api :as crux])) ;; tag::require-ek[] (require '[crux.kafka.embedded :as ek]) ;; end::require-ek[] ;; tag::ek-example[] (defn start-embedded-kafka [kafka-port storage-dir] (ek/start-embedded-kafka {:crux.kafka.embedded/zookeeper-data-dir (io/file storage-dir "zk-data") :crux.kafka.embedded/kafka-log-dir (io/file storage-dir "kafka-log") :crux.kafka.embedded/kafka-port kafka-port})) ;; end::ek-example[] (defn stop-embedded-kafka [^java.io.Closeable embedded-kafka] ;; tag::ek-close[] (.close embedded-kafka) ;; end::ek-close[] ) ;; tag::start-http-client[] (defn start-http-client [port] (crux/new-api-client (str "http://localhost:" port))) ;; end::start-http-client[] (defn example-query-entity [node] ;; tag::query-entity[] (crux/entity (crux/db node) :dbpedia.resource/Pablo-Picasso) ;; end::query-entity[] ) (defn example-query-valid-time [node] ;; tag::query-valid-time[] (crux/q (crux/db node #inst "2018-05-19T09:20:27.966-00:00") '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]]}) ;; end::query-valid-time[] ) #_(comment ;; tag::history-full[] (api/submit-tx node [[:crux.tx/put {:crux.db/id :ids.persons/Jeff :person/name "PI:NAME:<NAME>END_PI" :person/wealth 100} #inst "2018-05-18T09:20:27.966"] [:crux.tx/put {:crux.db/id :ids.persons/Jeff :person/name "PI:NAME:<NAME>END_PI" :person/wealth 1000} #inst "2015-05-18T09:20:27.966"]]) ; yields {:crux.tx/tx-id 1555314836178, :crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"} ; Returning the history in descending order ; To return in ascending order, use :asc in place of :desc (api/entity-history (api/db node) :ids.persons/Jeff :desc) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817, :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash ; sha1 hash of document contents "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"} {:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"}] ;; end::history-full[] ;; tag::history-with-docs[] (api/entity-history (api/db node) :ids.persons/Jeff :desc {:with-docs? true}) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817, :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561" :crux.db/doc {:crux.db/id :ids.persons/Jeff :person/name "PI:NAME:<NAME>END_PI" :person/wealth 100}} {:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529" :crux.db/doc {:crux.db/id :ids.persons/Jeff :person/name "PI:NAME:<NAME>END_PI" :person/wealth 1000}}] ;; end::history-with-docs[] ;; tag::history-range[] ; Passing the additional 'opts' map with the start/end bounds. ; As we are returning results in :asc order, the :start map contains the earlier coordinates - ; If returning history range in descending order, we pass the later coordinates to the :start map (api/entity-history (api/db node) :ids.persons/Jeff :asc {:start {:crux.db/valid-time #inst "2015-05-18T09:20:27.966" ; valid-time-start :crux.tx/tx-time #inst "2015-05-18T09:20:27.966"} ; tx-time-start :end {:crux.db/valid-time #inst "2020-05-18T09:20:27.966" ; valid-time-end :crux.tx/tx-time #inst "2020-05-18T09:20:27.966"} ; tx-time-end }) ; yields [{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00", :crux.tx/tx-id 1555314836178, :crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00", :crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"} {:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00", :crux.tx/tx-id 1555314835817 :crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00", :crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}] ;; end::history-range[] )
[ { "context": "jks\"\n :key-password \"password\"}\n (let [response (http/get \"https://localho", "end": 1421, "score": 0.9985052347183228, "start": 1413, "tag": "PASSWORD", "value": "password" }, { "context": " (is (= (:query-string request-map) \"surname=jones&age=123\"))\n (is (= (:uri request-map) \"/", "end": 3910, "score": 0.8437456488609314, "start": 3905, "tag": "NAME", "value": "jones" }, { "context": "8\"))\n (is (= (:remote-addr request-map) \"127.0.0.1\"))\n (is (= (:scheme request-map) :http))", "end": 4270, "score": 0.9997556209564209, "start": 4261, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
ring-jetty-adapter/test/ring/adapter/test/jetty.clj
ryfow/ring
1
(ns ring.adapter.test.jetty (:use clojure.test ring.adapter.jetty) (:require [clj-http.client :as http]) (:import (org.eclipse.jetty.util.thread QueuedThreadPool) (org.eclipse.jetty.server Server Request) (org.eclipse.jetty.server.handler AbstractHandler))) (defn- hello-world [request] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello World"}) (defn- content-type-handler [content-type] (constantly {:status 200 :headers {"Content-Type" content-type} :body ""})) (defn- echo-handler [request] {:status 200 :headers {"request-map" (str (dissoc request :body))} :body (:body request)}) (defmacro with-server [app options & body] `(let [server# (run-jetty ~app ~(assoc options :join? false))] (try ~@body (finally (.stop server#))))) (deftest test-run-jetty (testing "HTTP server" (with-server hello-world {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (:status response) 200)) (is (.startsWith (get-in response [:headers "content-type"]) "text/plain")) (is (= (:body response) "Hello World"))))) (testing "HTTPS server" (with-server hello-world {:port 4347 :ssl-port 4348 :keystore "test/keystore.jks" :key-password "password"} (let [response (http/get "https://localhost:4348" {:insecure? true})] (is (= (:status response) 200)) (is (= (:body response) "Hello World"))))) (testing "configurator set to run last" (let [max-threads 20 new-handler (proxy [AbstractHandler] [] (handle [_ ^Request base-request request response])) threadPool (QueuedThreadPool. ({} :max-threads max-threads)) configurator (fn [server] (.setThreadPool server threadPool) (.setHandler server new-handler)) server (run-jetty hello-world {:join? false :port 4347 :configurator configurator})] (is (= (.getMaxThreads (.getThreadPool server)) max-threads)) (is (identical? new-handler (.getHandler server))) (is (= 1 (count (.getHandlers server)))) (.stop server))) (testing "setting daemon threads" (testing "default (daemon off)" (let [server (run-jetty hello-world {:port 4347 :join? false})] (is (not (.. server getThreadPool isDaemon))) (.stop server))) (testing "daemon on" (let [server (run-jetty hello-world {:port 4347 :join? false :daemon? true})] (is (.. server getThreadPool isDaemon)) (.stop server))) (testing "daemon off" (let [server (run-jetty hello-world {:port 4347 :join? false :daemon? false})] (is (not (.. server getThreadPool isDaemon))) (.stop server)))) (testing "default character encoding" (with-server (content-type-handler "text/plain") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (.contains (get-in response [:headers "content-type"]) "text/plain"))))) (testing "custom content-type" (with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (get-in response [:headers "content-type"]) "text/plain;charset=UTF-16;version=1"))))) (testing "request translation" (with-server echo-handler {:port 4347} (let [response (http/get "http://localhost:4347/foo/bar/baz?surname=jones&age=123" {:body "hello"})] (is (= (:status response) 200)) (is (= (:body response) "hello")) (let [request-map (read-string (get-in response [:headers "request-map"]))] (is (= (:query-string request-map) "surname=jones&age=123")) (is (= (:uri request-map) "/foo/bar/baz")) (is (= (:content-length request-map) 5)) (is (= (:character-encoding request-map) "UTF-8")) (is (= (:request-method request-map) :get)) (is (= (:content-type request-map) "text/plain; charset=UTF-8")) (is (= (:remote-addr request-map) "127.0.0.1")) (is (= (:scheme request-map) :http)) (is (= (:server-name request-map) "localhost")) (is (= (:server-port request-map) 4347)) (is (= (:ssl-client-cert request-map) nil)))))))
77415
(ns ring.adapter.test.jetty (:use clojure.test ring.adapter.jetty) (:require [clj-http.client :as http]) (:import (org.eclipse.jetty.util.thread QueuedThreadPool) (org.eclipse.jetty.server Server Request) (org.eclipse.jetty.server.handler AbstractHandler))) (defn- hello-world [request] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello World"}) (defn- content-type-handler [content-type] (constantly {:status 200 :headers {"Content-Type" content-type} :body ""})) (defn- echo-handler [request] {:status 200 :headers {"request-map" (str (dissoc request :body))} :body (:body request)}) (defmacro with-server [app options & body] `(let [server# (run-jetty ~app ~(assoc options :join? false))] (try ~@body (finally (.stop server#))))) (deftest test-run-jetty (testing "HTTP server" (with-server hello-world {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (:status response) 200)) (is (.startsWith (get-in response [:headers "content-type"]) "text/plain")) (is (= (:body response) "Hello World"))))) (testing "HTTPS server" (with-server hello-world {:port 4347 :ssl-port 4348 :keystore "test/keystore.jks" :key-password "<PASSWORD>"} (let [response (http/get "https://localhost:4348" {:insecure? true})] (is (= (:status response) 200)) (is (= (:body response) "Hello World"))))) (testing "configurator set to run last" (let [max-threads 20 new-handler (proxy [AbstractHandler] [] (handle [_ ^Request base-request request response])) threadPool (QueuedThreadPool. ({} :max-threads max-threads)) configurator (fn [server] (.setThreadPool server threadPool) (.setHandler server new-handler)) server (run-jetty hello-world {:join? false :port 4347 :configurator configurator})] (is (= (.getMaxThreads (.getThreadPool server)) max-threads)) (is (identical? new-handler (.getHandler server))) (is (= 1 (count (.getHandlers server)))) (.stop server))) (testing "setting daemon threads" (testing "default (daemon off)" (let [server (run-jetty hello-world {:port 4347 :join? false})] (is (not (.. server getThreadPool isDaemon))) (.stop server))) (testing "daemon on" (let [server (run-jetty hello-world {:port 4347 :join? false :daemon? true})] (is (.. server getThreadPool isDaemon)) (.stop server))) (testing "daemon off" (let [server (run-jetty hello-world {:port 4347 :join? false :daemon? false})] (is (not (.. server getThreadPool isDaemon))) (.stop server)))) (testing "default character encoding" (with-server (content-type-handler "text/plain") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (.contains (get-in response [:headers "content-type"]) "text/plain"))))) (testing "custom content-type" (with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (get-in response [:headers "content-type"]) "text/plain;charset=UTF-16;version=1"))))) (testing "request translation" (with-server echo-handler {:port 4347} (let [response (http/get "http://localhost:4347/foo/bar/baz?surname=jones&age=123" {:body "hello"})] (is (= (:status response) 200)) (is (= (:body response) "hello")) (let [request-map (read-string (get-in response [:headers "request-map"]))] (is (= (:query-string request-map) "surname=<NAME>&age=123")) (is (= (:uri request-map) "/foo/bar/baz")) (is (= (:content-length request-map) 5)) (is (= (:character-encoding request-map) "UTF-8")) (is (= (:request-method request-map) :get)) (is (= (:content-type request-map) "text/plain; charset=UTF-8")) (is (= (:remote-addr request-map) "127.0.0.1")) (is (= (:scheme request-map) :http)) (is (= (:server-name request-map) "localhost")) (is (= (:server-port request-map) 4347)) (is (= (:ssl-client-cert request-map) nil)))))))
true
(ns ring.adapter.test.jetty (:use clojure.test ring.adapter.jetty) (:require [clj-http.client :as http]) (:import (org.eclipse.jetty.util.thread QueuedThreadPool) (org.eclipse.jetty.server Server Request) (org.eclipse.jetty.server.handler AbstractHandler))) (defn- hello-world [request] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello World"}) (defn- content-type-handler [content-type] (constantly {:status 200 :headers {"Content-Type" content-type} :body ""})) (defn- echo-handler [request] {:status 200 :headers {"request-map" (str (dissoc request :body))} :body (:body request)}) (defmacro with-server [app options & body] `(let [server# (run-jetty ~app ~(assoc options :join? false))] (try ~@body (finally (.stop server#))))) (deftest test-run-jetty (testing "HTTP server" (with-server hello-world {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (:status response) 200)) (is (.startsWith (get-in response [:headers "content-type"]) "text/plain")) (is (= (:body response) "Hello World"))))) (testing "HTTPS server" (with-server hello-world {:port 4347 :ssl-port 4348 :keystore "test/keystore.jks" :key-password "PI:PASSWORD:<PASSWORD>END_PI"} (let [response (http/get "https://localhost:4348" {:insecure? true})] (is (= (:status response) 200)) (is (= (:body response) "Hello World"))))) (testing "configurator set to run last" (let [max-threads 20 new-handler (proxy [AbstractHandler] [] (handle [_ ^Request base-request request response])) threadPool (QueuedThreadPool. ({} :max-threads max-threads)) configurator (fn [server] (.setThreadPool server threadPool) (.setHandler server new-handler)) server (run-jetty hello-world {:join? false :port 4347 :configurator configurator})] (is (= (.getMaxThreads (.getThreadPool server)) max-threads)) (is (identical? new-handler (.getHandler server))) (is (= 1 (count (.getHandlers server)))) (.stop server))) (testing "setting daemon threads" (testing "default (daemon off)" (let [server (run-jetty hello-world {:port 4347 :join? false})] (is (not (.. server getThreadPool isDaemon))) (.stop server))) (testing "daemon on" (let [server (run-jetty hello-world {:port 4347 :join? false :daemon? true})] (is (.. server getThreadPool isDaemon)) (.stop server))) (testing "daemon off" (let [server (run-jetty hello-world {:port 4347 :join? false :daemon? false})] (is (not (.. server getThreadPool isDaemon))) (.stop server)))) (testing "default character encoding" (with-server (content-type-handler "text/plain") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (.contains (get-in response [:headers "content-type"]) "text/plain"))))) (testing "custom content-type" (with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (get-in response [:headers "content-type"]) "text/plain;charset=UTF-16;version=1"))))) (testing "request translation" (with-server echo-handler {:port 4347} (let [response (http/get "http://localhost:4347/foo/bar/baz?surname=jones&age=123" {:body "hello"})] (is (= (:status response) 200)) (is (= (:body response) "hello")) (let [request-map (read-string (get-in response [:headers "request-map"]))] (is (= (:query-string request-map) "surname=PI:NAME:<NAME>END_PI&age=123")) (is (= (:uri request-map) "/foo/bar/baz")) (is (= (:content-length request-map) 5)) (is (= (:character-encoding request-map) "UTF-8")) (is (= (:request-method request-map) :get)) (is (= (:content-type request-map) "text/plain; charset=UTF-8")) (is (= (:remote-addr request-map) "127.0.0.1")) (is (= (:scheme request-map) :http)) (is (= (:server-name request-map) "localhost")) (is (= (:server-port request-map) 4347)) (is (= (:ssl-client-cert request-map) nil)))))))
[ { "context": ";; Copyright 2014-2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 36, "score": 0.9998847842216492, "start": 23, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright 2014-2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 50, "score": 0.9999316334724426, "start": 38, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
test/buddy/core/codecs_tests.clj
shilder/buddy-core
121
;; Copyright 2014-2015 Andrey Antukh <niwi@niwi.nz> ;; ;; 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 buddy.core.codecs-tests (:require [clojure.test :refer :all] [buddy.core.codecs :as codecs :refer :all] [buddy.core.codecs.base64 :as b64] [buddy.core.bytes :as bytes] [buddy.core.keys :refer :all] [buddy.core.hash :as hash] [clojure.java.io :as io])) (deftest buddy-core-codecs (testing "Hex encode/decode 01" (let [some-bytes (str->bytes "FooBar") encoded (bytes->hex some-bytes) decoded (hex->bytes encoded) some-str (bytes->str decoded)] (is (bytes/equals? decoded, some-bytes)) (is (= some-str "FooBar")))) (testing "Hex encode/decode 02" (let [mybytes (into-array Byte/TYPE (range 10)) encoded (bytes->hex mybytes) decoded (hex->bytes encoded)] (is (bytes/equals? decoded mybytes)))) (testing "Safe base64 encode/decode" (let [output1 (b64/encode "foo" true) output2 (b64/decode output1)] (is (= (bytes->str output1) "Zm9v")) (is (= (bytes->str output2) "foo")))) (testing "Concat byte arrays" (let [array1 (into-array Byte/TYPE [1,2,3]) array2 (into-array Byte/TYPE [3,4,5])] (is (bytes/equals? (bytes/concat array1 array2) (into-array Byte/TYPE [1,2,3,3,4,5]))))))
9210
;; Copyright 2014-2015 <NAME> <<EMAIL>> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.core.codecs-tests (:require [clojure.test :refer :all] [buddy.core.codecs :as codecs :refer :all] [buddy.core.codecs.base64 :as b64] [buddy.core.bytes :as bytes] [buddy.core.keys :refer :all] [buddy.core.hash :as hash] [clojure.java.io :as io])) (deftest buddy-core-codecs (testing "Hex encode/decode 01" (let [some-bytes (str->bytes "FooBar") encoded (bytes->hex some-bytes) decoded (hex->bytes encoded) some-str (bytes->str decoded)] (is (bytes/equals? decoded, some-bytes)) (is (= some-str "FooBar")))) (testing "Hex encode/decode 02" (let [mybytes (into-array Byte/TYPE (range 10)) encoded (bytes->hex mybytes) decoded (hex->bytes encoded)] (is (bytes/equals? decoded mybytes)))) (testing "Safe base64 encode/decode" (let [output1 (b64/encode "foo" true) output2 (b64/decode output1)] (is (= (bytes->str output1) "Zm9v")) (is (= (bytes->str output2) "foo")))) (testing "Concat byte arrays" (let [array1 (into-array Byte/TYPE [1,2,3]) array2 (into-array Byte/TYPE [3,4,5])] (is (bytes/equals? (bytes/concat array1 array2) (into-array Byte/TYPE [1,2,3,3,4,5]))))))
true
;; Copyright 2014-2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.core.codecs-tests (:require [clojure.test :refer :all] [buddy.core.codecs :as codecs :refer :all] [buddy.core.codecs.base64 :as b64] [buddy.core.bytes :as bytes] [buddy.core.keys :refer :all] [buddy.core.hash :as hash] [clojure.java.io :as io])) (deftest buddy-core-codecs (testing "Hex encode/decode 01" (let [some-bytes (str->bytes "FooBar") encoded (bytes->hex some-bytes) decoded (hex->bytes encoded) some-str (bytes->str decoded)] (is (bytes/equals? decoded, some-bytes)) (is (= some-str "FooBar")))) (testing "Hex encode/decode 02" (let [mybytes (into-array Byte/TYPE (range 10)) encoded (bytes->hex mybytes) decoded (hex->bytes encoded)] (is (bytes/equals? decoded mybytes)))) (testing "Safe base64 encode/decode" (let [output1 (b64/encode "foo" true) output2 (b64/decode output1)] (is (= (bytes->str output1) "Zm9v")) (is (= (bytes->str output2) "foo")))) (testing "Concat byte arrays" (let [array1 (into-array Byte/TYPE [1,2,3]) array2 (into-array Byte/TYPE [3,4,5])] (is (bytes/equals? (bytes/concat array1 array2) (into-array Byte/TYPE [1,2,3,3,4,5]))))))
[ { "context": "on/world.json\"\n :region_key \"ISO_A2\"\n :region_name \"NAME\"\n ", "end": 1260, "score": 0.9937080144882202, "start": 1254, "tag": "KEY", "value": "ISO_A2" }, { "context": "rohibited.\")))\n\n(def ^:private invalid-hosts\n #{\"169.254.169.254\" ; internal metadata for AWS, OpenStack, and Azur", "end": 1673, "score": 0.9997130036354065, "start": 1658, "tag": "IP_ADDRESS", "value": "169.254.169.254" } ]
c#-metabase/src/metabase/api/geojson.clj
hanakhry/Crime_Admin
0
(ns metabase.api.geojson (:require [clojure.java.io :as io] [compojure.core :refer [GET]] [metabase.api.common :as api] [metabase.models.setting :as setting :refer [defsetting]] [metabase.util.i18n :as ui18n :refer [deferred-tru tru]] [metabase.util.schema :as su] [ring.util.codec :as rc] [ring.util.response :as rr] [schema.core :as s]) (:import java.net.URL org.apache.commons.io.input.ReaderInputStream)) (def ^:private CustomGeoJSON {s/Keyword {:name su/NonBlankString :url su/NonBlankString :region_key (s/maybe s/Str) :region_name (s/maybe s/Str) (s/optional-key :builtin) s/Bool}}) (def ^:private ^:const builtin-geojson {:us_states {:name "United States" :url "app/assets/geojson/us-states.json" :region_key "STATE" :region_name "NAME" :builtin true} :world_countries {:name "World" :url "app/assets/geojson/world.json" :region_key "ISO_A2" :region_name "NAME" :builtin true}}) (defn- invalid-location-msg [] (str (tru "Invalid GeoJSON file location: must either start with http:// or https:// or be a relative path to a file on the classpath.") " " (tru "URLs referring to hosts that supply internal hosting metadata are prohibited."))) (def ^:private invalid-hosts #{"169.254.169.254" ; internal metadata for AWS, OpenStack, and Azure "metadata.google.internal"}) ; internal metadata for GCP (defn- valid-host? [^URL url] (not (invalid-hosts (.getHost url)))) (defn- valid-protocol? [^URL url] (#{"http" "https"} (.getProtocol url))) (defn- valid-url? [url-string] (try (let [url (URL. url-string)] (and (valid-host? url) (valid-protocol? url))) (catch Throwable e (throw (ex-info (invalid-location-msg) {:status-code 400, :url url-string} e))))) (defn- valid-geojson-url? [geojson] (every? (fn [[_ {:keys [url]}]] (or (io/resource url) (valid-url? url))) geojson)) (defn- validate-geojson "Throws a 400 if the supplied `geojson` is poorly structured or has an illegal URL/path" [geojson] (try (s/validate CustomGeoJSON geojson) (catch Throwable e (throw (ex-info (tru "Invalid custom GeoJSON") {:status-code 400} e)))) (or (valid-geojson-url? geojson) (throw (ex-info (invalid-location-msg) {:status-code 400})))) (defsetting custom-geojson (deferred-tru "JSON containing information about custom GeoJSON files for use in map visualizations instead of the default US State or World GeoJSON.") :type :json :default {} :getter (fn [] (merge (setting/get-json :custom-geojson) builtin-geojson)) :setter (fn [new-value] (when new-value (validate-geojson new-value)) (setting/set-json! :custom-geojson new-value)) :visibility :public) (api/defendpoint-async GET "/:key" "Fetch a custom GeoJSON file as defined in the `custom-geojson` setting. (This just acts as a simple proxy for the file specified for `key`)." [{{:keys [key]} :params} respond raise] {key su/NonBlankString} (if-let [url (get-in (custom-geojson) [(keyword key) :url])] (try (with-open [reader (io/reader (or (io/resource url) url)) is (ReaderInputStream. reader)] (respond (-> (rr/response is) (rr/content-type "application/json")))) (catch Throwable e (raise (ex-info (tru "GeoJSON URL failed to load") {:status-code 400})))) (raise (ex-info (tru "Invalid custom GeoJSON key: {0}" key) {:status-code 400})))) (api/defendpoint-async GET "/" "Load a custom GeoJSON file based on a URL or file path provided as a query parameter. This behaves similarly to /api/geojson/:key but doesn't require the custom map to be saved to the DB first." [{{:keys [url]} :params} respond raise] {url su/NonBlankString} (let [decoded-url (rc/url-decode url)] (or (io/resource decoded-url) (valid-url? decoded-url)) (try (with-open [reader (io/reader (or (io/resource decoded-url) decoded-url)) is (ReaderInputStream. reader)] (respond (-> (rr/response is) (rr/content-type "application/json")))) (catch Throwable e (raise (ex-info (tru "GeoJSON URL failed to load") {:status-code 400})))))) (api/define-routes)
114768
(ns metabase.api.geojson (:require [clojure.java.io :as io] [compojure.core :refer [GET]] [metabase.api.common :as api] [metabase.models.setting :as setting :refer [defsetting]] [metabase.util.i18n :as ui18n :refer [deferred-tru tru]] [metabase.util.schema :as su] [ring.util.codec :as rc] [ring.util.response :as rr] [schema.core :as s]) (:import java.net.URL org.apache.commons.io.input.ReaderInputStream)) (def ^:private CustomGeoJSON {s/Keyword {:name su/NonBlankString :url su/NonBlankString :region_key (s/maybe s/Str) :region_name (s/maybe s/Str) (s/optional-key :builtin) s/Bool}}) (def ^:private ^:const builtin-geojson {:us_states {:name "United States" :url "app/assets/geojson/us-states.json" :region_key "STATE" :region_name "NAME" :builtin true} :world_countries {:name "World" :url "app/assets/geojson/world.json" :region_key "<KEY>" :region_name "NAME" :builtin true}}) (defn- invalid-location-msg [] (str (tru "Invalid GeoJSON file location: must either start with http:// or https:// or be a relative path to a file on the classpath.") " " (tru "URLs referring to hosts that supply internal hosting metadata are prohibited."))) (def ^:private invalid-hosts #{"169.254.169.254" ; internal metadata for AWS, OpenStack, and Azure "metadata.google.internal"}) ; internal metadata for GCP (defn- valid-host? [^URL url] (not (invalid-hosts (.getHost url)))) (defn- valid-protocol? [^URL url] (#{"http" "https"} (.getProtocol url))) (defn- valid-url? [url-string] (try (let [url (URL. url-string)] (and (valid-host? url) (valid-protocol? url))) (catch Throwable e (throw (ex-info (invalid-location-msg) {:status-code 400, :url url-string} e))))) (defn- valid-geojson-url? [geojson] (every? (fn [[_ {:keys [url]}]] (or (io/resource url) (valid-url? url))) geojson)) (defn- validate-geojson "Throws a 400 if the supplied `geojson` is poorly structured or has an illegal URL/path" [geojson] (try (s/validate CustomGeoJSON geojson) (catch Throwable e (throw (ex-info (tru "Invalid custom GeoJSON") {:status-code 400} e)))) (or (valid-geojson-url? geojson) (throw (ex-info (invalid-location-msg) {:status-code 400})))) (defsetting custom-geojson (deferred-tru "JSON containing information about custom GeoJSON files for use in map visualizations instead of the default US State or World GeoJSON.") :type :json :default {} :getter (fn [] (merge (setting/get-json :custom-geojson) builtin-geojson)) :setter (fn [new-value] (when new-value (validate-geojson new-value)) (setting/set-json! :custom-geojson new-value)) :visibility :public) (api/defendpoint-async GET "/:key" "Fetch a custom GeoJSON file as defined in the `custom-geojson` setting. (This just acts as a simple proxy for the file specified for `key`)." [{{:keys [key]} :params} respond raise] {key su/NonBlankString} (if-let [url (get-in (custom-geojson) [(keyword key) :url])] (try (with-open [reader (io/reader (or (io/resource url) url)) is (ReaderInputStream. reader)] (respond (-> (rr/response is) (rr/content-type "application/json")))) (catch Throwable e (raise (ex-info (tru "GeoJSON URL failed to load") {:status-code 400})))) (raise (ex-info (tru "Invalid custom GeoJSON key: {0}" key) {:status-code 400})))) (api/defendpoint-async GET "/" "Load a custom GeoJSON file based on a URL or file path provided as a query parameter. This behaves similarly to /api/geojson/:key but doesn't require the custom map to be saved to the DB first." [{{:keys [url]} :params} respond raise] {url su/NonBlankString} (let [decoded-url (rc/url-decode url)] (or (io/resource decoded-url) (valid-url? decoded-url)) (try (with-open [reader (io/reader (or (io/resource decoded-url) decoded-url)) is (ReaderInputStream. reader)] (respond (-> (rr/response is) (rr/content-type "application/json")))) (catch Throwable e (raise (ex-info (tru "GeoJSON URL failed to load") {:status-code 400})))))) (api/define-routes)
true
(ns metabase.api.geojson (:require [clojure.java.io :as io] [compojure.core :refer [GET]] [metabase.api.common :as api] [metabase.models.setting :as setting :refer [defsetting]] [metabase.util.i18n :as ui18n :refer [deferred-tru tru]] [metabase.util.schema :as su] [ring.util.codec :as rc] [ring.util.response :as rr] [schema.core :as s]) (:import java.net.URL org.apache.commons.io.input.ReaderInputStream)) (def ^:private CustomGeoJSON {s/Keyword {:name su/NonBlankString :url su/NonBlankString :region_key (s/maybe s/Str) :region_name (s/maybe s/Str) (s/optional-key :builtin) s/Bool}}) (def ^:private ^:const builtin-geojson {:us_states {:name "United States" :url "app/assets/geojson/us-states.json" :region_key "STATE" :region_name "NAME" :builtin true} :world_countries {:name "World" :url "app/assets/geojson/world.json" :region_key "PI:KEY:<KEY>END_PI" :region_name "NAME" :builtin true}}) (defn- invalid-location-msg [] (str (tru "Invalid GeoJSON file location: must either start with http:// or https:// or be a relative path to a file on the classpath.") " " (tru "URLs referring to hosts that supply internal hosting metadata are prohibited."))) (def ^:private invalid-hosts #{"169.254.169.254" ; internal metadata for AWS, OpenStack, and Azure "metadata.google.internal"}) ; internal metadata for GCP (defn- valid-host? [^URL url] (not (invalid-hosts (.getHost url)))) (defn- valid-protocol? [^URL url] (#{"http" "https"} (.getProtocol url))) (defn- valid-url? [url-string] (try (let [url (URL. url-string)] (and (valid-host? url) (valid-protocol? url))) (catch Throwable e (throw (ex-info (invalid-location-msg) {:status-code 400, :url url-string} e))))) (defn- valid-geojson-url? [geojson] (every? (fn [[_ {:keys [url]}]] (or (io/resource url) (valid-url? url))) geojson)) (defn- validate-geojson "Throws a 400 if the supplied `geojson` is poorly structured or has an illegal URL/path" [geojson] (try (s/validate CustomGeoJSON geojson) (catch Throwable e (throw (ex-info (tru "Invalid custom GeoJSON") {:status-code 400} e)))) (or (valid-geojson-url? geojson) (throw (ex-info (invalid-location-msg) {:status-code 400})))) (defsetting custom-geojson (deferred-tru "JSON containing information about custom GeoJSON files for use in map visualizations instead of the default US State or World GeoJSON.") :type :json :default {} :getter (fn [] (merge (setting/get-json :custom-geojson) builtin-geojson)) :setter (fn [new-value] (when new-value (validate-geojson new-value)) (setting/set-json! :custom-geojson new-value)) :visibility :public) (api/defendpoint-async GET "/:key" "Fetch a custom GeoJSON file as defined in the `custom-geojson` setting. (This just acts as a simple proxy for the file specified for `key`)." [{{:keys [key]} :params} respond raise] {key su/NonBlankString} (if-let [url (get-in (custom-geojson) [(keyword key) :url])] (try (with-open [reader (io/reader (or (io/resource url) url)) is (ReaderInputStream. reader)] (respond (-> (rr/response is) (rr/content-type "application/json")))) (catch Throwable e (raise (ex-info (tru "GeoJSON URL failed to load") {:status-code 400})))) (raise (ex-info (tru "Invalid custom GeoJSON key: {0}" key) {:status-code 400})))) (api/defendpoint-async GET "/" "Load a custom GeoJSON file based on a URL or file path provided as a query parameter. This behaves similarly to /api/geojson/:key but doesn't require the custom map to be saved to the DB first." [{{:keys [url]} :params} respond raise] {url su/NonBlankString} (let [decoded-url (rc/url-decode url)] (or (io/resource decoded-url) (valid-url? decoded-url)) (try (with-open [reader (io/reader (or (io/resource decoded-url) decoded-url)) is (ReaderInputStream. reader)] (respond (-> (rr/response is) (rr/content-type "application/json")))) (catch Throwable e (raise (ex-info (tru "GeoJSON URL failed to load") {:status-code 400})))))) (api/define-routes)
[ { "context": "(let [haystack [\"Zig\" \"Zag\" \"Wally\" \"Ronald\" \"Bush\" \"Krusty\" \"Charlie\" \"Bush\" \"Bozo\"", "end": 34, "score": 0.9995090961456299, "start": 29, "tag": "NAME", "value": "Wally" }, { "context": "(let [haystack [\"Zig\" \"Zag\" \"Wally\" \"Ronald\" \"Bush\" \"Krusty\" \"Charlie\" \"Bush\" \"Bozo\"]]\n (let", "end": 43, "score": 0.999530017375946, "start": 37, "tag": "NAME", "value": "Ronald" }, { "context": "(let [haystack [\"Zig\" \"Zag\" \"Wally\" \"Ronald\" \"Bush\" \"Krusty\" \"Charlie\" \"Bush\" \"Bozo\"]]\n (let [idx (", "end": 50, "score": 0.9482739567756653, "start": 46, "tag": "NAME", "value": "Bush" }, { "context": "t [haystack [\"Zig\" \"Zag\" \"Wally\" \"Ronald\" \"Bush\" \"Krusty\" \"Charlie\" \"Bush\" \"Bozo\"]]\n (let [idx (.indexOf ", "end": 59, "score": 0.9996330738067627, "start": 53, "tag": "NAME", "value": "Krusty" }, { "context": "ck [\"Zig\" \"Zag\" \"Wally\" \"Ronald\" \"Bush\" \"Krusty\" \"Charlie\" \"Bush\" \"Bozo\"]]\n (let [idx (.indexOf haystack \"", "end": 69, "score": 0.9996035099029541, "start": 62, "tag": "NAME", "value": "Charlie" } ]
Task/Search-a-list/Clojure/search-a-list.clj
LaudateCorpus1/RosettaCodeData
1
(let [haystack ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]] (let [idx (.indexOf haystack "Zig")] (if (neg? idx) (throw (Error. "item not found.")) idx)))
24411
(let [haystack ["Zig" "Zag" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "Bush" "Bozo"]] (let [idx (.indexOf haystack "Zig")] (if (neg? idx) (throw (Error. "item not found.")) idx)))
true
(let [haystack ["Zig" "Zag" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Bush" "Bozo"]] (let [idx (.indexOf haystack "Zig")] (if (neg? idx) (throw (Error. "item not found.")) idx)))
[ { "context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.99953693151474, "start": 21, "tag": "NAME", "value": "Peter Monks" } ]
src/tools_licenses/asf.clj
jellelicht/tools-licenses
0
; ; Copyright © 2021 Peter Monks ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns tools-licenses.asf "Logic related to the ASF's 3rd Party License Policy." (:require [clojure.string :as s] [tools-licenses.spdx :as spdx])) ; See https://www.apache.org/legal/resolved.html#category-a (def ^:private asf-cat-a ["Apache-1.1" "Apache-2.0" "PHP-3.01" "MX4J" ; Non-SPDX identifier in fallbacks "BSD-2-Clause" "BSD-3-Clause" "DOM4J" ; Non-SPDX identifier in fallbacks "PostgreSQL" ; "EDL-1.0" ; Legally equivalent to BSD-3-Clause according to SPDX, and detected as such "MIT" "ISC" "SMLNJ" ; "CUP" ; Legally equivalent to BSD-3-Clause according to ASF, and detected as such "ICU" "NCSA" "W3C" ; "W3C Community Contributor License Agreement" ; Not in SPDX; not yet supported "Xnet" "Zlib" "Libpng" ; "FSF autoconf license" ; Not in SPDX; not yet supported ; "DejaVu Fonts (Bitstream Vera/Arev licenses)" ; Not in SPDX; not yet supported "AFL-3.0" ; "Service+Component+Architecture+Specifications" ; Not in SPDX; not yet supported ; "OOXML XSD ECMA License" ; Not in SPDX; not yet supported "MS-PL" ; "Creative Commons Copyright-Only Dedication" ; Not in SPDX; not yet supported "PSF-2.0" ; "Python Imaging Library Software License" ; Not in SPDX; not yet supported "APAFML" "BSL-1.0" ; "License for CERN packages in COLT" ; Not in SPDX; not yet supported "WTFPL" ; "The Romantic WTF public license" ; Not in SPDX; not yet supported "Unicode-DFS-2015" "Unicode-DFS-2016" "ZPL-2.0" ; "ACE license" ; Not in SPDX; not yet supported; license text is no longer available online "UPL-1.0" ; "Open Grid Forum License" ; Not in SPDX; not yet supported ; "Google \"Additional IP Rights Grant (Patents)\" file" ; Not in SPDX; not yet supported "Unlicense" "HPND" "MulanPSL-2.0" ]) (def ^:private asf-cat-a-special ["OGL-UK-3.0" ; Note: provided it does not have a custom attribution notice, otherwise it becomes category-b "Public domain" ; Not in SPDX; see https://www.apache.org/legal/resolved.html#handling-public-domain-licensed-works ]) ; See https://www.apache.org/legal/resolved.html#category-b (def ^:private asf-cat-b ["CDDL-1.0" "CDDL-1.1" "CPL-1.0" "EPL-1.0" "EPL-2.0" "IPL-1.0" "MPL-1.0" "MPL-1.1" "MPL-2.0" "SPL-1.0" "OSL-3.0" "ErlPL-1.1" ; "UnRAR License (only for unarchiving)" ; Not in SPDX; not yet supported "OFL-1.0" "OFL-1.1" ; "Ubuntu Font License Version 1.0" ; Not in SPDX; not yet supported "IPA" "Ruby" ]) ; See https://www.apache.org/legal/resolved.html#category-x (def ^:private asf-cat-x [;"Binary Code License (BCL)" ; Not in SPDX; not yet supported ; "Intel Simplified Software License" ; Not in SPDX; not yet supported ; "JSR-275 License" ; Not in SPDX; not yet supported - TODO: ADD THIS TO FALLBACKS WITH A NON-SPDX ID ; "Microsoft Limited Public License" ; Not in SPDX; not yet supported ; "Amazon Software License (ASL)" ; Not in SPDX; not yet supported ; "Java SDK for Satori RTM license" ; Not in SPDX; not yet supported ; "Redis Source Available License (RSAL)" ; Not in SPDX; not yet supported ; "Booz Allen Public License" ; Not in SPDX; not yet supported ; "Confluent Community License Version 1.0" ; Not in SPDX; not yet supported ; "Any license including the Commons Clause License Condition v1.0" ; Not in SPDX; not yet supported ; "Creative Commons Non-Commercial variants" ; Handled via a special case ; "Sun Community Source License 3.0" ; Not in SPDX; not yet supported "GPL-1.0" "GPL-1.0-only" "GPL-2.0" "GPL-2.0+" "GPL-2.0-only" "GPL-2.0-or-later" "GPL-2.0-with-autoconf-exception" "GPL-2.0-with-bison-exception" "GPL-2.0-with-classpath-exception" "GPL-2.0-with-font-exception" "GPL-2.0-with-GCC-exception" "GPL-3.0" "GPL-3.0+" "GPL-3.0-only" "GPL-3.0-or-later" "GPL-3.0-with-autoconf-exception" "GPL-3.0-with-GCC-exception" "AGPL-1.0" ; Note this license is not related to the GNU AGPL "AGPL-1.0-only" ; Note this license is not related to the GNU AGPL "AGPL-1.0-or-later" ; Note this license is not related to the GNU AGPL "AGPL-3.0" "AGPL-3.0-only" "AGPL-3.0-or-later" "LGPL-2.0" "LGPL-2.0+" "LGPL-2.0-only" "LGPL-2.0-or-later" "LGPL-2.1" "LGPL-2.1+" "LGPL-2.1-only" "LGPL-2.1-or-later" "LGPL-3.0" "LGPL-3.0+" "LGPL-3.0-only" "LGPL-3.0-or-later" "QPL-1.0" "Sleepycat" "SSPL-1.0" "CPOL-1.02" "BSD-4-Clause" "BSD-4-Clause-Shortened" "BSD-4-Clause-UC" ; "Facebook BSD+Patents license" ; Not in SPDX; not yet supported "NPL-1.0" "NPL-1.1" ; "The Solipsistic Eclipse Public License" ; Not in SPDX; not yet supported ; "The \"Don't Be A Dick\" Public License" ; Not in SPDX; not yet supported "JSON" ]) ; Unless these licenses appear in cat A or B, these should be considered cat X (see https://www.apache.org/legal/resolved.html#criteria)) (def ^:private non-osi-approved (vec (map :license-id (filter :is-osi-approved spdx/license-list)))) (defn category "Returns the ASF 'category' for the given SPDX license id, which will be one of: :category-a - see https://www.apache.org/legal/resolved.html#category-a :category-a-special :category-b - see https://www.apache.org/legal/resolved.html#category-b :creative-commons - see https://www.apache.org/legal/resolved.html#cc-by (may be any category...) :category-x - see https://www.apache.org/legal/resolved.html#category-x :non-osi-approved - see https://www.apache.org/legal/resolved.html#criteria (effectively the same as :category-x) :uncategorised - the ASF category could not be determined for this license" [spdx-id] (if (seq (filter #(= spdx-id %) asf-cat-a)) :category-a (if (seq (filter #(= spdx-id %) asf-cat-a-special)) :category-a-special (if (seq (filter #(= spdx-id %) asf-cat-b)) :category-b (if (s/starts-with? spdx-id "CC-BY-") :creative-commons (if (seq (filter #(= spdx-id %) asf-cat-x)) :category-x (if (seq (filter #(= spdx-id %) non-osi-approved)) :non-osi-approved :uncategorised))))))) (def ^:private category-order {:category-a 0 :category-a-special 1 :category-b 2 :creative-commons 4 :category-x 5 :non-osi-approved 6 :uncategorised 7}) (def third-party-license-uri "https://www.apache.org/legal/resolved.html") (def category-info "Information on each category." {:category-a {:name "Category A" :url "https://www.apache.org/legal/resolved.html#category-a"} :category-a-special {:name "Category A (with caveats)" :url "https://www.apache.org/legal/resolved.html#category-a"} :category-b {:name "Category B" :url "https://www.apache.org/legal/resolved.html#category-b"} :creative-commons {:name "Creative Commons Licenses" :url "https://www.apache.org/legal/resolved.html#cc-by"} :category-x {:name "Category X" :url "https://www.apache.org/legal/resolved.html#category-x"} :non-osi-approved {:name "Non-OSI Approved Licenses" :url "https://www.apache.org/legal/resolved.html#criteria"} :uncategorised {:name "Uncategorised" :url "https://www.apache.org/legal/resolved.html#criteria"}}) (def category-compare "A comparator for ASF category keywords (see category fn for that list)." (comparator (fn [l r] (compare (get category-order l 99) (get category-order r 99))))) (def least-to-most-problematic-categories "A sequence of categories in least to most problematic." (sort-by category-order (keys category-order))) (defn least-problematic-category "Returns the least problematic category for the given sequence of SPDX license identifiers." [licenses] (first (sort-by category-order (map category licenses))))
52295
; ; Copyright © 2021 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns tools-licenses.asf "Logic related to the ASF's 3rd Party License Policy." (:require [clojure.string :as s] [tools-licenses.spdx :as spdx])) ; See https://www.apache.org/legal/resolved.html#category-a (def ^:private asf-cat-a ["Apache-1.1" "Apache-2.0" "PHP-3.01" "MX4J" ; Non-SPDX identifier in fallbacks "BSD-2-Clause" "BSD-3-Clause" "DOM4J" ; Non-SPDX identifier in fallbacks "PostgreSQL" ; "EDL-1.0" ; Legally equivalent to BSD-3-Clause according to SPDX, and detected as such "MIT" "ISC" "SMLNJ" ; "CUP" ; Legally equivalent to BSD-3-Clause according to ASF, and detected as such "ICU" "NCSA" "W3C" ; "W3C Community Contributor License Agreement" ; Not in SPDX; not yet supported "Xnet" "Zlib" "Libpng" ; "FSF autoconf license" ; Not in SPDX; not yet supported ; "DejaVu Fonts (Bitstream Vera/Arev licenses)" ; Not in SPDX; not yet supported "AFL-3.0" ; "Service+Component+Architecture+Specifications" ; Not in SPDX; not yet supported ; "OOXML XSD ECMA License" ; Not in SPDX; not yet supported "MS-PL" ; "Creative Commons Copyright-Only Dedication" ; Not in SPDX; not yet supported "PSF-2.0" ; "Python Imaging Library Software License" ; Not in SPDX; not yet supported "APAFML" "BSL-1.0" ; "License for CERN packages in COLT" ; Not in SPDX; not yet supported "WTFPL" ; "The Romantic WTF public license" ; Not in SPDX; not yet supported "Unicode-DFS-2015" "Unicode-DFS-2016" "ZPL-2.0" ; "ACE license" ; Not in SPDX; not yet supported; license text is no longer available online "UPL-1.0" ; "Open Grid Forum License" ; Not in SPDX; not yet supported ; "Google \"Additional IP Rights Grant (Patents)\" file" ; Not in SPDX; not yet supported "Unlicense" "HPND" "MulanPSL-2.0" ]) (def ^:private asf-cat-a-special ["OGL-UK-3.0" ; Note: provided it does not have a custom attribution notice, otherwise it becomes category-b "Public domain" ; Not in SPDX; see https://www.apache.org/legal/resolved.html#handling-public-domain-licensed-works ]) ; See https://www.apache.org/legal/resolved.html#category-b (def ^:private asf-cat-b ["CDDL-1.0" "CDDL-1.1" "CPL-1.0" "EPL-1.0" "EPL-2.0" "IPL-1.0" "MPL-1.0" "MPL-1.1" "MPL-2.0" "SPL-1.0" "OSL-3.0" "ErlPL-1.1" ; "UnRAR License (only for unarchiving)" ; Not in SPDX; not yet supported "OFL-1.0" "OFL-1.1" ; "Ubuntu Font License Version 1.0" ; Not in SPDX; not yet supported "IPA" "Ruby" ]) ; See https://www.apache.org/legal/resolved.html#category-x (def ^:private asf-cat-x [;"Binary Code License (BCL)" ; Not in SPDX; not yet supported ; "Intel Simplified Software License" ; Not in SPDX; not yet supported ; "JSR-275 License" ; Not in SPDX; not yet supported - TODO: ADD THIS TO FALLBACKS WITH A NON-SPDX ID ; "Microsoft Limited Public License" ; Not in SPDX; not yet supported ; "Amazon Software License (ASL)" ; Not in SPDX; not yet supported ; "Java SDK for Satori RTM license" ; Not in SPDX; not yet supported ; "Redis Source Available License (RSAL)" ; Not in SPDX; not yet supported ; "Booz Allen Public License" ; Not in SPDX; not yet supported ; "Confluent Community License Version 1.0" ; Not in SPDX; not yet supported ; "Any license including the Commons Clause License Condition v1.0" ; Not in SPDX; not yet supported ; "Creative Commons Non-Commercial variants" ; Handled via a special case ; "Sun Community Source License 3.0" ; Not in SPDX; not yet supported "GPL-1.0" "GPL-1.0-only" "GPL-2.0" "GPL-2.0+" "GPL-2.0-only" "GPL-2.0-or-later" "GPL-2.0-with-autoconf-exception" "GPL-2.0-with-bison-exception" "GPL-2.0-with-classpath-exception" "GPL-2.0-with-font-exception" "GPL-2.0-with-GCC-exception" "GPL-3.0" "GPL-3.0+" "GPL-3.0-only" "GPL-3.0-or-later" "GPL-3.0-with-autoconf-exception" "GPL-3.0-with-GCC-exception" "AGPL-1.0" ; Note this license is not related to the GNU AGPL "AGPL-1.0-only" ; Note this license is not related to the GNU AGPL "AGPL-1.0-or-later" ; Note this license is not related to the GNU AGPL "AGPL-3.0" "AGPL-3.0-only" "AGPL-3.0-or-later" "LGPL-2.0" "LGPL-2.0+" "LGPL-2.0-only" "LGPL-2.0-or-later" "LGPL-2.1" "LGPL-2.1+" "LGPL-2.1-only" "LGPL-2.1-or-later" "LGPL-3.0" "LGPL-3.0+" "LGPL-3.0-only" "LGPL-3.0-or-later" "QPL-1.0" "Sleepycat" "SSPL-1.0" "CPOL-1.02" "BSD-4-Clause" "BSD-4-Clause-Shortened" "BSD-4-Clause-UC" ; "Facebook BSD+Patents license" ; Not in SPDX; not yet supported "NPL-1.0" "NPL-1.1" ; "The Solipsistic Eclipse Public License" ; Not in SPDX; not yet supported ; "The \"Don't Be A Dick\" Public License" ; Not in SPDX; not yet supported "JSON" ]) ; Unless these licenses appear in cat A or B, these should be considered cat X (see https://www.apache.org/legal/resolved.html#criteria)) (def ^:private non-osi-approved (vec (map :license-id (filter :is-osi-approved spdx/license-list)))) (defn category "Returns the ASF 'category' for the given SPDX license id, which will be one of: :category-a - see https://www.apache.org/legal/resolved.html#category-a :category-a-special :category-b - see https://www.apache.org/legal/resolved.html#category-b :creative-commons - see https://www.apache.org/legal/resolved.html#cc-by (may be any category...) :category-x - see https://www.apache.org/legal/resolved.html#category-x :non-osi-approved - see https://www.apache.org/legal/resolved.html#criteria (effectively the same as :category-x) :uncategorised - the ASF category could not be determined for this license" [spdx-id] (if (seq (filter #(= spdx-id %) asf-cat-a)) :category-a (if (seq (filter #(= spdx-id %) asf-cat-a-special)) :category-a-special (if (seq (filter #(= spdx-id %) asf-cat-b)) :category-b (if (s/starts-with? spdx-id "CC-BY-") :creative-commons (if (seq (filter #(= spdx-id %) asf-cat-x)) :category-x (if (seq (filter #(= spdx-id %) non-osi-approved)) :non-osi-approved :uncategorised))))))) (def ^:private category-order {:category-a 0 :category-a-special 1 :category-b 2 :creative-commons 4 :category-x 5 :non-osi-approved 6 :uncategorised 7}) (def third-party-license-uri "https://www.apache.org/legal/resolved.html") (def category-info "Information on each category." {:category-a {:name "Category A" :url "https://www.apache.org/legal/resolved.html#category-a"} :category-a-special {:name "Category A (with caveats)" :url "https://www.apache.org/legal/resolved.html#category-a"} :category-b {:name "Category B" :url "https://www.apache.org/legal/resolved.html#category-b"} :creative-commons {:name "Creative Commons Licenses" :url "https://www.apache.org/legal/resolved.html#cc-by"} :category-x {:name "Category X" :url "https://www.apache.org/legal/resolved.html#category-x"} :non-osi-approved {:name "Non-OSI Approved Licenses" :url "https://www.apache.org/legal/resolved.html#criteria"} :uncategorised {:name "Uncategorised" :url "https://www.apache.org/legal/resolved.html#criteria"}}) (def category-compare "A comparator for ASF category keywords (see category fn for that list)." (comparator (fn [l r] (compare (get category-order l 99) (get category-order r 99))))) (def least-to-most-problematic-categories "A sequence of categories in least to most problematic." (sort-by category-order (keys category-order))) (defn least-problematic-category "Returns the least problematic category for the given sequence of SPDX license identifiers." [licenses] (first (sort-by category-order (map category licenses))))
true
; ; Copyright © 2021 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns tools-licenses.asf "Logic related to the ASF's 3rd Party License Policy." (:require [clojure.string :as s] [tools-licenses.spdx :as spdx])) ; See https://www.apache.org/legal/resolved.html#category-a (def ^:private asf-cat-a ["Apache-1.1" "Apache-2.0" "PHP-3.01" "MX4J" ; Non-SPDX identifier in fallbacks "BSD-2-Clause" "BSD-3-Clause" "DOM4J" ; Non-SPDX identifier in fallbacks "PostgreSQL" ; "EDL-1.0" ; Legally equivalent to BSD-3-Clause according to SPDX, and detected as such "MIT" "ISC" "SMLNJ" ; "CUP" ; Legally equivalent to BSD-3-Clause according to ASF, and detected as such "ICU" "NCSA" "W3C" ; "W3C Community Contributor License Agreement" ; Not in SPDX; not yet supported "Xnet" "Zlib" "Libpng" ; "FSF autoconf license" ; Not in SPDX; not yet supported ; "DejaVu Fonts (Bitstream Vera/Arev licenses)" ; Not in SPDX; not yet supported "AFL-3.0" ; "Service+Component+Architecture+Specifications" ; Not in SPDX; not yet supported ; "OOXML XSD ECMA License" ; Not in SPDX; not yet supported "MS-PL" ; "Creative Commons Copyright-Only Dedication" ; Not in SPDX; not yet supported "PSF-2.0" ; "Python Imaging Library Software License" ; Not in SPDX; not yet supported "APAFML" "BSL-1.0" ; "License for CERN packages in COLT" ; Not in SPDX; not yet supported "WTFPL" ; "The Romantic WTF public license" ; Not in SPDX; not yet supported "Unicode-DFS-2015" "Unicode-DFS-2016" "ZPL-2.0" ; "ACE license" ; Not in SPDX; not yet supported; license text is no longer available online "UPL-1.0" ; "Open Grid Forum License" ; Not in SPDX; not yet supported ; "Google \"Additional IP Rights Grant (Patents)\" file" ; Not in SPDX; not yet supported "Unlicense" "HPND" "MulanPSL-2.0" ]) (def ^:private asf-cat-a-special ["OGL-UK-3.0" ; Note: provided it does not have a custom attribution notice, otherwise it becomes category-b "Public domain" ; Not in SPDX; see https://www.apache.org/legal/resolved.html#handling-public-domain-licensed-works ]) ; See https://www.apache.org/legal/resolved.html#category-b (def ^:private asf-cat-b ["CDDL-1.0" "CDDL-1.1" "CPL-1.0" "EPL-1.0" "EPL-2.0" "IPL-1.0" "MPL-1.0" "MPL-1.1" "MPL-2.0" "SPL-1.0" "OSL-3.0" "ErlPL-1.1" ; "UnRAR License (only for unarchiving)" ; Not in SPDX; not yet supported "OFL-1.0" "OFL-1.1" ; "Ubuntu Font License Version 1.0" ; Not in SPDX; not yet supported "IPA" "Ruby" ]) ; See https://www.apache.org/legal/resolved.html#category-x (def ^:private asf-cat-x [;"Binary Code License (BCL)" ; Not in SPDX; not yet supported ; "Intel Simplified Software License" ; Not in SPDX; not yet supported ; "JSR-275 License" ; Not in SPDX; not yet supported - TODO: ADD THIS TO FALLBACKS WITH A NON-SPDX ID ; "Microsoft Limited Public License" ; Not in SPDX; not yet supported ; "Amazon Software License (ASL)" ; Not in SPDX; not yet supported ; "Java SDK for Satori RTM license" ; Not in SPDX; not yet supported ; "Redis Source Available License (RSAL)" ; Not in SPDX; not yet supported ; "Booz Allen Public License" ; Not in SPDX; not yet supported ; "Confluent Community License Version 1.0" ; Not in SPDX; not yet supported ; "Any license including the Commons Clause License Condition v1.0" ; Not in SPDX; not yet supported ; "Creative Commons Non-Commercial variants" ; Handled via a special case ; "Sun Community Source License 3.0" ; Not in SPDX; not yet supported "GPL-1.0" "GPL-1.0-only" "GPL-2.0" "GPL-2.0+" "GPL-2.0-only" "GPL-2.0-or-later" "GPL-2.0-with-autoconf-exception" "GPL-2.0-with-bison-exception" "GPL-2.0-with-classpath-exception" "GPL-2.0-with-font-exception" "GPL-2.0-with-GCC-exception" "GPL-3.0" "GPL-3.0+" "GPL-3.0-only" "GPL-3.0-or-later" "GPL-3.0-with-autoconf-exception" "GPL-3.0-with-GCC-exception" "AGPL-1.0" ; Note this license is not related to the GNU AGPL "AGPL-1.0-only" ; Note this license is not related to the GNU AGPL "AGPL-1.0-or-later" ; Note this license is not related to the GNU AGPL "AGPL-3.0" "AGPL-3.0-only" "AGPL-3.0-or-later" "LGPL-2.0" "LGPL-2.0+" "LGPL-2.0-only" "LGPL-2.0-or-later" "LGPL-2.1" "LGPL-2.1+" "LGPL-2.1-only" "LGPL-2.1-or-later" "LGPL-3.0" "LGPL-3.0+" "LGPL-3.0-only" "LGPL-3.0-or-later" "QPL-1.0" "Sleepycat" "SSPL-1.0" "CPOL-1.02" "BSD-4-Clause" "BSD-4-Clause-Shortened" "BSD-4-Clause-UC" ; "Facebook BSD+Patents license" ; Not in SPDX; not yet supported "NPL-1.0" "NPL-1.1" ; "The Solipsistic Eclipse Public License" ; Not in SPDX; not yet supported ; "The \"Don't Be A Dick\" Public License" ; Not in SPDX; not yet supported "JSON" ]) ; Unless these licenses appear in cat A or B, these should be considered cat X (see https://www.apache.org/legal/resolved.html#criteria)) (def ^:private non-osi-approved (vec (map :license-id (filter :is-osi-approved spdx/license-list)))) (defn category "Returns the ASF 'category' for the given SPDX license id, which will be one of: :category-a - see https://www.apache.org/legal/resolved.html#category-a :category-a-special :category-b - see https://www.apache.org/legal/resolved.html#category-b :creative-commons - see https://www.apache.org/legal/resolved.html#cc-by (may be any category...) :category-x - see https://www.apache.org/legal/resolved.html#category-x :non-osi-approved - see https://www.apache.org/legal/resolved.html#criteria (effectively the same as :category-x) :uncategorised - the ASF category could not be determined for this license" [spdx-id] (if (seq (filter #(= spdx-id %) asf-cat-a)) :category-a (if (seq (filter #(= spdx-id %) asf-cat-a-special)) :category-a-special (if (seq (filter #(= spdx-id %) asf-cat-b)) :category-b (if (s/starts-with? spdx-id "CC-BY-") :creative-commons (if (seq (filter #(= spdx-id %) asf-cat-x)) :category-x (if (seq (filter #(= spdx-id %) non-osi-approved)) :non-osi-approved :uncategorised))))))) (def ^:private category-order {:category-a 0 :category-a-special 1 :category-b 2 :creative-commons 4 :category-x 5 :non-osi-approved 6 :uncategorised 7}) (def third-party-license-uri "https://www.apache.org/legal/resolved.html") (def category-info "Information on each category." {:category-a {:name "Category A" :url "https://www.apache.org/legal/resolved.html#category-a"} :category-a-special {:name "Category A (with caveats)" :url "https://www.apache.org/legal/resolved.html#category-a"} :category-b {:name "Category B" :url "https://www.apache.org/legal/resolved.html#category-b"} :creative-commons {:name "Creative Commons Licenses" :url "https://www.apache.org/legal/resolved.html#cc-by"} :category-x {:name "Category X" :url "https://www.apache.org/legal/resolved.html#category-x"} :non-osi-approved {:name "Non-OSI Approved Licenses" :url "https://www.apache.org/legal/resolved.html#criteria"} :uncategorised {:name "Uncategorised" :url "https://www.apache.org/legal/resolved.html#criteria"}}) (def category-compare "A comparator for ASF category keywords (see category fn for that list)." (comparator (fn [l r] (compare (get category-order l 99) (get category-order r 99))))) (def least-to-most-problematic-categories "A sequence of categories in least to most problematic." (sort-by category-order (keys category-order))) (defn least-problematic-category "Returns the least problematic category for the given sequence of SPDX license identifiers." [licenses] (first (sort-by category-order (map category licenses))))
[ { "context": "\n(deftest test-match-based-on-regexp\n (let [key \"kubernetes\"\n regexp-name :compute-cluster-regex\n ", "end": 782, "score": 0.9540941715240479, "start": 772, "tag": "KEY", "value": "kubernetes" } ]
scheduler/test/cook/test/regexp_tools.clj
CGe0516/Cook
345
;; ;; 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 cook.test.regexp_tools (:require [clojure.test :refer :all] [cook.regexp-tools :as regexp-tools])) (deftest test-match-based-on-regexp (let [key "kubernetes" regexp-name :compute-cluster-regex match-list [{:compute-cluster-regex "^.*$", :tbf-config {:bucket-size 1}}]] (is (= {:bucket-size 1} (regexp-tools/match-based-on-regexp regexp-name :tbf-config match-list key))))) (deftest test-match-based-on-pool-name (testing "basics" (let [matchlist [{:pool-regex "^foo$" :field {:foo 1}} {:pool-regex ".*" :field {:bar 2}} {:pool-regex "^baz$" :field {:baz 3}}]] (is (= (regexp-tools/match-based-on-pool-name matchlist "foo" :field) {:foo 1})) (is (= (regexp-tools/match-based-on-pool-name matchlist "bar" :field) {:bar 2})) (is (= (regexp-tools/match-based-on-pool-name matchlist "baz" :field) {:bar 2}))) (is (= (regexp-tools/match-based-on-pool-name [] "foo" :field) nil))) (testing "defaulting" (is (= false (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field false}] "pool-name" :field :default-value "default"))) (is (= {} (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field {}}] "pool-name" :field :default-value "default"))) (is (= [] (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field []}] "pool-name" :field :default-value "default"))) (is (= "value" (regexp-tools/match-based-on-pool-name [{:pool-regex "^foo$" :field "value"}] "foo" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [{:pool-regex "^foo$" :field "value"}] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field nil}] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name nil "pool-name" :field :default-value "default")))))
27445
;; ;; 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 cook.test.regexp_tools (:require [clojure.test :refer :all] [cook.regexp-tools :as regexp-tools])) (deftest test-match-based-on-regexp (let [key "<KEY>" regexp-name :compute-cluster-regex match-list [{:compute-cluster-regex "^.*$", :tbf-config {:bucket-size 1}}]] (is (= {:bucket-size 1} (regexp-tools/match-based-on-regexp regexp-name :tbf-config match-list key))))) (deftest test-match-based-on-pool-name (testing "basics" (let [matchlist [{:pool-regex "^foo$" :field {:foo 1}} {:pool-regex ".*" :field {:bar 2}} {:pool-regex "^baz$" :field {:baz 3}}]] (is (= (regexp-tools/match-based-on-pool-name matchlist "foo" :field) {:foo 1})) (is (= (regexp-tools/match-based-on-pool-name matchlist "bar" :field) {:bar 2})) (is (= (regexp-tools/match-based-on-pool-name matchlist "baz" :field) {:bar 2}))) (is (= (regexp-tools/match-based-on-pool-name [] "foo" :field) nil))) (testing "defaulting" (is (= false (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field false}] "pool-name" :field :default-value "default"))) (is (= {} (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field {}}] "pool-name" :field :default-value "default"))) (is (= [] (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field []}] "pool-name" :field :default-value "default"))) (is (= "value" (regexp-tools/match-based-on-pool-name [{:pool-regex "^foo$" :field "value"}] "foo" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [{:pool-regex "^foo$" :field "value"}] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field nil}] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name nil "pool-name" :field :default-value "default")))))
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 cook.test.regexp_tools (:require [clojure.test :refer :all] [cook.regexp-tools :as regexp-tools])) (deftest test-match-based-on-regexp (let [key "PI:KEY:<KEY>END_PI" regexp-name :compute-cluster-regex match-list [{:compute-cluster-regex "^.*$", :tbf-config {:bucket-size 1}}]] (is (= {:bucket-size 1} (regexp-tools/match-based-on-regexp regexp-name :tbf-config match-list key))))) (deftest test-match-based-on-pool-name (testing "basics" (let [matchlist [{:pool-regex "^foo$" :field {:foo 1}} {:pool-regex ".*" :field {:bar 2}} {:pool-regex "^baz$" :field {:baz 3}}]] (is (= (regexp-tools/match-based-on-pool-name matchlist "foo" :field) {:foo 1})) (is (= (regexp-tools/match-based-on-pool-name matchlist "bar" :field) {:bar 2})) (is (= (regexp-tools/match-based-on-pool-name matchlist "baz" :field) {:bar 2}))) (is (= (regexp-tools/match-based-on-pool-name [] "foo" :field) nil))) (testing "defaulting" (is (= false (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field false}] "pool-name" :field :default-value "default"))) (is (= {} (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field {}}] "pool-name" :field :default-value "default"))) (is (= [] (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field []}] "pool-name" :field :default-value "default"))) (is (= "value" (regexp-tools/match-based-on-pool-name [{:pool-regex "^foo$" :field "value"}] "foo" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [{:pool-regex "^foo$" :field "value"}] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [{:pool-regex "^.*$" :field nil}] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name [] "pool-name" :field :default-value "default"))) (is (= "default" (regexp-tools/match-based-on-pool-name nil "pool-name" :field :default-value "default")))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998045563697815, "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.99981290102005, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/scene_selection.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.scene-selection (:require [clojure.set :as set] [dynamo.graph :as g] [editor.system :as system] [editor.background :as background] [editor.colors :as colors] [editor.camera :as c] [editor.core :as core] [editor.geom :as geom] [editor.gl :as gl] [editor.grid :as grid] [editor.input :as i] [editor.math :as math] [editor.types :as types] [editor.workspace :as workspace] [editor.gl.pass :as pass] [schema.core :as s] [service.log :as log]) (:import [com.defold.editor Start UIUtil] [com.jogamp.opengl.util GLPixelStorageModes] [com.jogamp.opengl.util.awt TextRenderer] [editor.types Camera AABB Region Rect] [java.awt Font] [java.awt.image BufferedImage DataBufferByte] [javafx.animation AnimationTimer] [javafx.application Platform] [javafx.beans.value ChangeListener] [javafx.collections FXCollections ObservableList] [javafx.embed.swing SwingFXUtils] [javafx.event ActionEvent EventHandler] [javafx.geometry BoundingBox] [javafx.scene Scene Node Parent] [javafx.scene.control Tab] [javafx.scene.image Image ImageView WritableImage PixelWriter] [javafx.scene.input MouseEvent] [javafx.scene.layout AnchorPane Pane] [java.lang Runnable Math] [java.nio IntBuffer ByteBuffer ByteOrder] [com.jogamp.opengl GL GL2 GL2GL3 GLContext GLProfile GLAutoDrawable GLOffscreenAutoDrawable GLDrawableFactory GLCapabilities] [com.jogamp.opengl.glu GLU] [javax.vecmath Point2i Point3d Quat4d Matrix4d Vector4d Matrix3d Vector3d])) (set! *warn-on-reflection* true) (defn render-selection-box [^GL2 gl render-args renderables count] (let [user-data (:user-data (first renderables)) start (:start user-data) current (:current user-data)] (when (and start current) (let [min-fn (fn [v1 v2] (map #(Math/min ^Double %1 ^Double %2) v1 v2)) max-fn (fn [v1 v2] (map #(Math/max ^Double %1 ^Double %2) v1 v2)) min-p (reduce min-fn [start current]) min-x (nth min-p 0) min-y (nth min-p 1) max-p (reduce max-fn [start current]) max-x (nth max-p 0) max-y (nth max-p 1) z 0.0 c (double-array (map #(/ % 255.0) [131 188 212]))] (.glColor3d gl (nth c 0) (nth c 1) (nth c 2)) (.glBegin gl GL2/GL_LINE_LOOP) (.glVertex3d gl min-x min-y z) (.glVertex3d gl min-x max-y z) (.glVertex3d gl max-x max-y z) (.glVertex3d gl max-x min-y z) (.glEnd gl) (.glBegin gl GL2/GL_QUADS) (.glColor4d gl (nth c 0) (nth c 1) (nth c 2) 0.2) (.glVertex3d gl min-x, min-y, z); (.glVertex3d gl min-x, max-y, z); (.glVertex3d gl max-x, max-y, z); (.glVertex3d gl max-x, min-y, z); (.glEnd gl))))) (defn- select [controller op-seq mode toggle?] (let [select-fn (g/node-value controller :select-fn) selection (g/node-value controller :picking-selection) mode-filter-fn (case mode :single (fn [selection] (if-let [sel (first selection)] [sel] [])) :multi identity) toggle-filter-fn (if toggle? (fn [selection] (let [selection-set (set selection) prev-selection (g/node-value controller :prev-selection) prev-selection-set (set prev-selection)] (into [] (concat (filter (complement selection-set) prev-selection) (filter (complement prev-selection-set) selection))))) identity) sel-filter-fn (comp toggle-filter-fn mode-filter-fn) selection (or (not-empty (sel-filter-fn selection)) (filter #(not (nil? %)) [(g/node-value controller :root-id)]))] (select-fn selection op-seq))) (def mac-toggle-modifiers #{:shift :meta}) (def other-toggle-modifiers #{:shift}) (def toggle-modifiers (if system/mac? mac-toggle-modifiers other-toggle-modifiers)) (def ^Integer min-pick-size 10) (defn distance [[x0 y0 z0] [x1 y1 z1]] (.distance (Point3d. x0 y0 z0) (Point3d. x1 y1 z1))) (defn handle-selection-input [self action user-data] (let [start (g/node-value self :start) current (g/node-value self :current) op-seq (g/node-value self :op-seq) mode (g/node-value self :mode) toggle? (g/node-value self :toggle?) cursor-pos [(:x action) (:y action) 0]] (case (:type action) :mouse-pressed (let [op-seq (gensym) toggle? (true? (some true? (map #(% action) toggle-modifiers))) mode :single] (g/transact (concat (g/set-property self :op-seq op-seq) (g/set-property self :start cursor-pos) (g/set-property self :current cursor-pos) (g/set-property self :mode mode) (g/set-property self :toggle? toggle?) (g/set-property self :prev-selection (g/node-value self :selection)))) (select self op-seq mode toggle?) nil) :mouse-released (do (g/transact (concat (g/set-property self :start nil) (g/set-property self :current nil) (g/set-property self :op-seq nil) (g/set-property self :mode nil) (g/set-property self :toggle? nil) (g/set-property self :prev-selection nil))) nil) :mouse-moved (if start (let [new-mode (if (and (= :single mode) (< min-pick-size (distance start cursor-pos))) :multi mode)] (g/transact (concat (when (not= new-mode mode) (g/set-property self :mode new-mode)) (g/set-property self :current cursor-pos))) (select self op-seq new-mode toggle?) nil) action) action))) (defn- imin [^Integer v1 ^Integer v2] (Math/min v1 v2)) (defn- imax [^Integer v1 ^Integer v2] (Math/max v1 v2)) (defn calc-picking-rect "Returns a rect where .x, .y is center of rect spanned by points [start current] and .width, .height the corresponding dimensions" [start current] (let [ps [start current] min-p (Point2i. (reduce imin (map first ps)) (reduce imin (map second ps))) max-p (Point2i. (reduce imax (map first ps)) (reduce imax (map second ps))) dims (doto (Point2i. max-p) (.sub min-p)) center (doto (Point2i. min-p) (.add (Point2i. (/ (.x dims) 2) (/ (.y dims) 2))))] (types/rect (.x center) (.y center) (Math/max (.x dims) min-pick-size) (Math/max (.y dims) min-pick-size)))) (g/deftype SelectionMode (s/enum :single :multi)) (g/defnode SelectionController (property select-fn Runnable) (property start types/Vec3) (property current types/Vec3) (property op-seq g/Any) (property mode SelectionMode) (property toggle? g/Bool) (property prev-selection g/Any) (input selection g/Any) (input picking-selection g/Any) (input root-id g/NodeID) (output picking-rect Rect :cached (g/fnk [start current] (calc-picking-rect start current))) (output renderable pass/RenderData :cached (g/fnk [start current] {pass/overlay [{:world-transform (Matrix4d. geom/Identity4d) :render-fn render-selection-box :user-data {:start start :current current}}]})) (output input-handler Runnable :cached (g/constantly handle-selection-input)))
93980
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 <NAME>, <NAME> ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.scene-selection (:require [clojure.set :as set] [dynamo.graph :as g] [editor.system :as system] [editor.background :as background] [editor.colors :as colors] [editor.camera :as c] [editor.core :as core] [editor.geom :as geom] [editor.gl :as gl] [editor.grid :as grid] [editor.input :as i] [editor.math :as math] [editor.types :as types] [editor.workspace :as workspace] [editor.gl.pass :as pass] [schema.core :as s] [service.log :as log]) (:import [com.defold.editor Start UIUtil] [com.jogamp.opengl.util GLPixelStorageModes] [com.jogamp.opengl.util.awt TextRenderer] [editor.types Camera AABB Region Rect] [java.awt Font] [java.awt.image BufferedImage DataBufferByte] [javafx.animation AnimationTimer] [javafx.application Platform] [javafx.beans.value ChangeListener] [javafx.collections FXCollections ObservableList] [javafx.embed.swing SwingFXUtils] [javafx.event ActionEvent EventHandler] [javafx.geometry BoundingBox] [javafx.scene Scene Node Parent] [javafx.scene.control Tab] [javafx.scene.image Image ImageView WritableImage PixelWriter] [javafx.scene.input MouseEvent] [javafx.scene.layout AnchorPane Pane] [java.lang Runnable Math] [java.nio IntBuffer ByteBuffer ByteOrder] [com.jogamp.opengl GL GL2 GL2GL3 GLContext GLProfile GLAutoDrawable GLOffscreenAutoDrawable GLDrawableFactory GLCapabilities] [com.jogamp.opengl.glu GLU] [javax.vecmath Point2i Point3d Quat4d Matrix4d Vector4d Matrix3d Vector3d])) (set! *warn-on-reflection* true) (defn render-selection-box [^GL2 gl render-args renderables count] (let [user-data (:user-data (first renderables)) start (:start user-data) current (:current user-data)] (when (and start current) (let [min-fn (fn [v1 v2] (map #(Math/min ^Double %1 ^Double %2) v1 v2)) max-fn (fn [v1 v2] (map #(Math/max ^Double %1 ^Double %2) v1 v2)) min-p (reduce min-fn [start current]) min-x (nth min-p 0) min-y (nth min-p 1) max-p (reduce max-fn [start current]) max-x (nth max-p 0) max-y (nth max-p 1) z 0.0 c (double-array (map #(/ % 255.0) [131 188 212]))] (.glColor3d gl (nth c 0) (nth c 1) (nth c 2)) (.glBegin gl GL2/GL_LINE_LOOP) (.glVertex3d gl min-x min-y z) (.glVertex3d gl min-x max-y z) (.glVertex3d gl max-x max-y z) (.glVertex3d gl max-x min-y z) (.glEnd gl) (.glBegin gl GL2/GL_QUADS) (.glColor4d gl (nth c 0) (nth c 1) (nth c 2) 0.2) (.glVertex3d gl min-x, min-y, z); (.glVertex3d gl min-x, max-y, z); (.glVertex3d gl max-x, max-y, z); (.glVertex3d gl max-x, min-y, z); (.glEnd gl))))) (defn- select [controller op-seq mode toggle?] (let [select-fn (g/node-value controller :select-fn) selection (g/node-value controller :picking-selection) mode-filter-fn (case mode :single (fn [selection] (if-let [sel (first selection)] [sel] [])) :multi identity) toggle-filter-fn (if toggle? (fn [selection] (let [selection-set (set selection) prev-selection (g/node-value controller :prev-selection) prev-selection-set (set prev-selection)] (into [] (concat (filter (complement selection-set) prev-selection) (filter (complement prev-selection-set) selection))))) identity) sel-filter-fn (comp toggle-filter-fn mode-filter-fn) selection (or (not-empty (sel-filter-fn selection)) (filter #(not (nil? %)) [(g/node-value controller :root-id)]))] (select-fn selection op-seq))) (def mac-toggle-modifiers #{:shift :meta}) (def other-toggle-modifiers #{:shift}) (def toggle-modifiers (if system/mac? mac-toggle-modifiers other-toggle-modifiers)) (def ^Integer min-pick-size 10) (defn distance [[x0 y0 z0] [x1 y1 z1]] (.distance (Point3d. x0 y0 z0) (Point3d. x1 y1 z1))) (defn handle-selection-input [self action user-data] (let [start (g/node-value self :start) current (g/node-value self :current) op-seq (g/node-value self :op-seq) mode (g/node-value self :mode) toggle? (g/node-value self :toggle?) cursor-pos [(:x action) (:y action) 0]] (case (:type action) :mouse-pressed (let [op-seq (gensym) toggle? (true? (some true? (map #(% action) toggle-modifiers))) mode :single] (g/transact (concat (g/set-property self :op-seq op-seq) (g/set-property self :start cursor-pos) (g/set-property self :current cursor-pos) (g/set-property self :mode mode) (g/set-property self :toggle? toggle?) (g/set-property self :prev-selection (g/node-value self :selection)))) (select self op-seq mode toggle?) nil) :mouse-released (do (g/transact (concat (g/set-property self :start nil) (g/set-property self :current nil) (g/set-property self :op-seq nil) (g/set-property self :mode nil) (g/set-property self :toggle? nil) (g/set-property self :prev-selection nil))) nil) :mouse-moved (if start (let [new-mode (if (and (= :single mode) (< min-pick-size (distance start cursor-pos))) :multi mode)] (g/transact (concat (when (not= new-mode mode) (g/set-property self :mode new-mode)) (g/set-property self :current cursor-pos))) (select self op-seq new-mode toggle?) nil) action) action))) (defn- imin [^Integer v1 ^Integer v2] (Math/min v1 v2)) (defn- imax [^Integer v1 ^Integer v2] (Math/max v1 v2)) (defn calc-picking-rect "Returns a rect where .x, .y is center of rect spanned by points [start current] and .width, .height the corresponding dimensions" [start current] (let [ps [start current] min-p (Point2i. (reduce imin (map first ps)) (reduce imin (map second ps))) max-p (Point2i. (reduce imax (map first ps)) (reduce imax (map second ps))) dims (doto (Point2i. max-p) (.sub min-p)) center (doto (Point2i. min-p) (.add (Point2i. (/ (.x dims) 2) (/ (.y dims) 2))))] (types/rect (.x center) (.y center) (Math/max (.x dims) min-pick-size) (Math/max (.y dims) min-pick-size)))) (g/deftype SelectionMode (s/enum :single :multi)) (g/defnode SelectionController (property select-fn Runnable) (property start types/Vec3) (property current types/Vec3) (property op-seq g/Any) (property mode SelectionMode) (property toggle? g/Bool) (property prev-selection g/Any) (input selection g/Any) (input picking-selection g/Any) (input root-id g/NodeID) (output picking-rect Rect :cached (g/fnk [start current] (calc-picking-rect start current))) (output renderable pass/RenderData :cached (g/fnk [start current] {pass/overlay [{:world-transform (Matrix4d. geom/Identity4d) :render-fn render-selection-box :user-data {:start start :current current}}]})) (output input-handler Runnable :cached (g/constantly handle-selection-input)))
true
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.scene-selection (:require [clojure.set :as set] [dynamo.graph :as g] [editor.system :as system] [editor.background :as background] [editor.colors :as colors] [editor.camera :as c] [editor.core :as core] [editor.geom :as geom] [editor.gl :as gl] [editor.grid :as grid] [editor.input :as i] [editor.math :as math] [editor.types :as types] [editor.workspace :as workspace] [editor.gl.pass :as pass] [schema.core :as s] [service.log :as log]) (:import [com.defold.editor Start UIUtil] [com.jogamp.opengl.util GLPixelStorageModes] [com.jogamp.opengl.util.awt TextRenderer] [editor.types Camera AABB Region Rect] [java.awt Font] [java.awt.image BufferedImage DataBufferByte] [javafx.animation AnimationTimer] [javafx.application Platform] [javafx.beans.value ChangeListener] [javafx.collections FXCollections ObservableList] [javafx.embed.swing SwingFXUtils] [javafx.event ActionEvent EventHandler] [javafx.geometry BoundingBox] [javafx.scene Scene Node Parent] [javafx.scene.control Tab] [javafx.scene.image Image ImageView WritableImage PixelWriter] [javafx.scene.input MouseEvent] [javafx.scene.layout AnchorPane Pane] [java.lang Runnable Math] [java.nio IntBuffer ByteBuffer ByteOrder] [com.jogamp.opengl GL GL2 GL2GL3 GLContext GLProfile GLAutoDrawable GLOffscreenAutoDrawable GLDrawableFactory GLCapabilities] [com.jogamp.opengl.glu GLU] [javax.vecmath Point2i Point3d Quat4d Matrix4d Vector4d Matrix3d Vector3d])) (set! *warn-on-reflection* true) (defn render-selection-box [^GL2 gl render-args renderables count] (let [user-data (:user-data (first renderables)) start (:start user-data) current (:current user-data)] (when (and start current) (let [min-fn (fn [v1 v2] (map #(Math/min ^Double %1 ^Double %2) v1 v2)) max-fn (fn [v1 v2] (map #(Math/max ^Double %1 ^Double %2) v1 v2)) min-p (reduce min-fn [start current]) min-x (nth min-p 0) min-y (nth min-p 1) max-p (reduce max-fn [start current]) max-x (nth max-p 0) max-y (nth max-p 1) z 0.0 c (double-array (map #(/ % 255.0) [131 188 212]))] (.glColor3d gl (nth c 0) (nth c 1) (nth c 2)) (.glBegin gl GL2/GL_LINE_LOOP) (.glVertex3d gl min-x min-y z) (.glVertex3d gl min-x max-y z) (.glVertex3d gl max-x max-y z) (.glVertex3d gl max-x min-y z) (.glEnd gl) (.glBegin gl GL2/GL_QUADS) (.glColor4d gl (nth c 0) (nth c 1) (nth c 2) 0.2) (.glVertex3d gl min-x, min-y, z); (.glVertex3d gl min-x, max-y, z); (.glVertex3d gl max-x, max-y, z); (.glVertex3d gl max-x, min-y, z); (.glEnd gl))))) (defn- select [controller op-seq mode toggle?] (let [select-fn (g/node-value controller :select-fn) selection (g/node-value controller :picking-selection) mode-filter-fn (case mode :single (fn [selection] (if-let [sel (first selection)] [sel] [])) :multi identity) toggle-filter-fn (if toggle? (fn [selection] (let [selection-set (set selection) prev-selection (g/node-value controller :prev-selection) prev-selection-set (set prev-selection)] (into [] (concat (filter (complement selection-set) prev-selection) (filter (complement prev-selection-set) selection))))) identity) sel-filter-fn (comp toggle-filter-fn mode-filter-fn) selection (or (not-empty (sel-filter-fn selection)) (filter #(not (nil? %)) [(g/node-value controller :root-id)]))] (select-fn selection op-seq))) (def mac-toggle-modifiers #{:shift :meta}) (def other-toggle-modifiers #{:shift}) (def toggle-modifiers (if system/mac? mac-toggle-modifiers other-toggle-modifiers)) (def ^Integer min-pick-size 10) (defn distance [[x0 y0 z0] [x1 y1 z1]] (.distance (Point3d. x0 y0 z0) (Point3d. x1 y1 z1))) (defn handle-selection-input [self action user-data] (let [start (g/node-value self :start) current (g/node-value self :current) op-seq (g/node-value self :op-seq) mode (g/node-value self :mode) toggle? (g/node-value self :toggle?) cursor-pos [(:x action) (:y action) 0]] (case (:type action) :mouse-pressed (let [op-seq (gensym) toggle? (true? (some true? (map #(% action) toggle-modifiers))) mode :single] (g/transact (concat (g/set-property self :op-seq op-seq) (g/set-property self :start cursor-pos) (g/set-property self :current cursor-pos) (g/set-property self :mode mode) (g/set-property self :toggle? toggle?) (g/set-property self :prev-selection (g/node-value self :selection)))) (select self op-seq mode toggle?) nil) :mouse-released (do (g/transact (concat (g/set-property self :start nil) (g/set-property self :current nil) (g/set-property self :op-seq nil) (g/set-property self :mode nil) (g/set-property self :toggle? nil) (g/set-property self :prev-selection nil))) nil) :mouse-moved (if start (let [new-mode (if (and (= :single mode) (< min-pick-size (distance start cursor-pos))) :multi mode)] (g/transact (concat (when (not= new-mode mode) (g/set-property self :mode new-mode)) (g/set-property self :current cursor-pos))) (select self op-seq new-mode toggle?) nil) action) action))) (defn- imin [^Integer v1 ^Integer v2] (Math/min v1 v2)) (defn- imax [^Integer v1 ^Integer v2] (Math/max v1 v2)) (defn calc-picking-rect "Returns a rect where .x, .y is center of rect spanned by points [start current] and .width, .height the corresponding dimensions" [start current] (let [ps [start current] min-p (Point2i. (reduce imin (map first ps)) (reduce imin (map second ps))) max-p (Point2i. (reduce imax (map first ps)) (reduce imax (map second ps))) dims (doto (Point2i. max-p) (.sub min-p)) center (doto (Point2i. min-p) (.add (Point2i. (/ (.x dims) 2) (/ (.y dims) 2))))] (types/rect (.x center) (.y center) (Math/max (.x dims) min-pick-size) (Math/max (.y dims) min-pick-size)))) (g/deftype SelectionMode (s/enum :single :multi)) (g/defnode SelectionController (property select-fn Runnable) (property start types/Vec3) (property current types/Vec3) (property op-seq g/Any) (property mode SelectionMode) (property toggle? g/Bool) (property prev-selection g/Any) (input selection g/Any) (input picking-selection g/Any) (input root-id g/NodeID) (output picking-rect Rect :cached (g/fnk [start current] (calc-picking-rect start current))) (output renderable pass/RenderData :cached (g/fnk [start current] {pass/overlay [{:world-transform (Matrix4d. geom/Identity4d) :render-fn render-selection-box :user-data {:start start :current current}}]})) (output input-handler Runnable :cached (g/constantly handle-selection-input)))
[ { "context": "sequence of non-whitespace words.\n(re-seq #\"\\w+\" \"mary had a little lamb\")\n\n; (apply str ...) can be use", "end": 173, "score": 0.8715393543243408, "start": 169, "tag": "NAME", "value": "mary" } ]
src/solutions/37_regex.clj
eliben/4clojure-solutions
1
(ns solutions.37-regex) ; re-seq provides a sequence of successive matches, so the following splits the ; string to a sequence of non-whitespace words. (re-seq #"\w+" "mary had a little lamb") ; (apply str ...) can be used to fuse the matches into a single string. (apply str (re-seq #"[A-Z]+" "bA1B3Ce "))
103825
(ns solutions.37-regex) ; re-seq provides a sequence of successive matches, so the following splits the ; string to a sequence of non-whitespace words. (re-seq #"\w+" "<NAME> had a little lamb") ; (apply str ...) can be used to fuse the matches into a single string. (apply str (re-seq #"[A-Z]+" "bA1B3Ce "))
true
(ns solutions.37-regex) ; re-seq provides a sequence of successive matches, so the following splits the ; string to a sequence of non-whitespace words. (re-seq #"\w+" "PI:NAME:<NAME>END_PI had a little lamb") ; (apply str ...) can be used to fuse the matches into a single string. (apply str (re-seq #"[A-Z]+" "bA1B3Ce "))
[ { "context": "retary/\") (:name x)))\n\n(def secretaryMap { \n\t:name fullname\n\t:occupation occupation\n\t:ministry ministry\n\t:fro", "end": 329, "score": 0.8900133371353149, "start": 321, "tag": "NAME", "value": "fullname" }, { "context": "\n(defmethod convert :secretary [x type]\n(let [[_ _ firstName lastName occupation ministry fromDate toDate note", "end": 640, "score": 0.8740923404693604, "start": 631, "tag": "NAME", "value": "firstName" }, { "context": "d convert :secretary [x type]\n(let [[_ _ firstName lastName occupation ministry fromDate toDate note] x]\n\t(->", "end": 649, "score": 0.9000309109687805, "start": 641, "tag": "NAME", "value": "lastName" } ]
src/clojsesame/integration/secretary.clj
hotlib/datanest2rdf
0
(ns clojsesame.integration.secretary (:require [clojsesame.vocabulary :refer :all] [clojsesame.sesame :refer :all])) (def secretaryInfo {:filename "dumps/statni_tajomnici-dump.csv" :type :secretary}) (defn- secretaryURI [x] (createURI (str basicNamespace "/secretary/") (:name x))) (def secretaryMap { :name fullname :occupation occupation :ministry ministry :fromDate fromDate :toDate toDate :note note}) (defrecord Secretary [name occupation ministry fromDate toDate note] SesameRepository (store [x] (storeRecord secretaryURI secretaryMap x))) (defmethod convert :secretary [x type] (let [[_ _ firstName lastName occupation ministry fromDate toDate note] x] (->Secretary (str firstName " " lastName) occupation ministry fromDate toDate note)))
120826
(ns clojsesame.integration.secretary (:require [clojsesame.vocabulary :refer :all] [clojsesame.sesame :refer :all])) (def secretaryInfo {:filename "dumps/statni_tajomnici-dump.csv" :type :secretary}) (defn- secretaryURI [x] (createURI (str basicNamespace "/secretary/") (:name x))) (def secretaryMap { :name <NAME> :occupation occupation :ministry ministry :fromDate fromDate :toDate toDate :note note}) (defrecord Secretary [name occupation ministry fromDate toDate note] SesameRepository (store [x] (storeRecord secretaryURI secretaryMap x))) (defmethod convert :secretary [x type] (let [[_ _ <NAME> <NAME> occupation ministry fromDate toDate note] x] (->Secretary (str firstName " " lastName) occupation ministry fromDate toDate note)))
true
(ns clojsesame.integration.secretary (:require [clojsesame.vocabulary :refer :all] [clojsesame.sesame :refer :all])) (def secretaryInfo {:filename "dumps/statni_tajomnici-dump.csv" :type :secretary}) (defn- secretaryURI [x] (createURI (str basicNamespace "/secretary/") (:name x))) (def secretaryMap { :name PI:NAME:<NAME>END_PI :occupation occupation :ministry ministry :fromDate fromDate :toDate toDate :note note}) (defrecord Secretary [name occupation ministry fromDate toDate note] SesameRepository (store [x] (storeRecord secretaryURI secretaryMap x))) (defmethod convert :secretary [x type] (let [[_ _ PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI occupation ministry fromDate toDate note] x] (->Secretary (str firstName " " lastName) occupation ministry fromDate toDate note)))
[ { "context": "tion\"\n :name \"Test Location\"\n :a", "end": 4599, "score": 0.684446394443512, "start": 4595, "tag": "NAME", "value": "Test" } ]
test/cljs/early_vote_site/early_vote_site_form/events_test.cljs
votinginfoproject/Metis
11
(ns early-vote-site.early-vote-site-form.events-test (:require [cljs.test :refer-macros [deftest is testing]] [clojure.string :as str] [early-vote-site.early-vote-site-form.events :as events])) (deftest form-update-test (testing "updates the form state for the given field" (let [db-before {:early-vote-site-form {:name "Hi"}} db-after {:early-vote-site-form {:name "Hi" :county-fips "01234"}}] (is (= db-after (events/form-update db-before [:early-vote-site-form/update :county-fips "01234"])))))) (deftest params-test (testing "pulls together form and merges state abbreviation" (let [db {:election-detail {:election {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}}] ;; note the transition from clojure style dashes to ;; json friendly underscores (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} (events/params (:early-vote-site-form db) db)))))) (deftest form-submit-test (testing "new early vote site" (let [db {:selected-election-id "fake-election-id" :election-detail {:election {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/form-submit {:db db} [:early-vote-site-form/save]) url (get-in fx [:http-xhrio :uri]) params (get-in fx [:http-xhrio :params]) method (get-in fx [:http-xhrio :method])] (is (= :post method)) (is (str/ends-with? url "/earlyvote/elections/fake-election-id/earlyvotesites")) (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} params)))) (testing "editing existing early vote site" (let [db {:selected-election-id "fake-election-id" :election-detail {:election {:state-fips "08"}} :early-vote-site-form {:id 123 :county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/form-submit {:db db} [:early-vote-site-form/save]) url (get-in fx [:http-xhrio :uri]) params (get-in fx [:http-xhrio :params]) method (get-in fx [:http-xhrio :method])] (is (= :put method)) (is (str/ends-with? url "/earlyvote/earlyvotesites/123")) (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} params))))) (deftest save-success-test (testing "save event" (let [db {:selected-election "fake-election-id" :election-detail {:detail {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/save-success {:db db} [])] (testing "cleared the form" (let [db-after (:db fx)] (is (= {:type "early_vote_site"} (:early-vote-site-form db-after))))) (testing "dispatches flash" (is (>= (.indexOf (:dispatch-n fx) [:flash/message "Early Vote Site saved"]) 0))) (testing "dispatches navigation to election-detail" (is (>= (.indexOf (:dispatch-n fx) [:navigate/election-detail]) 0))))))
39315
(ns early-vote-site.early-vote-site-form.events-test (:require [cljs.test :refer-macros [deftest is testing]] [clojure.string :as str] [early-vote-site.early-vote-site-form.events :as events])) (deftest form-update-test (testing "updates the form state for the given field" (let [db-before {:early-vote-site-form {:name "Hi"}} db-after {:early-vote-site-form {:name "Hi" :county-fips "01234"}}] (is (= db-after (events/form-update db-before [:early-vote-site-form/update :county-fips "01234"])))))) (deftest params-test (testing "pulls together form and merges state abbreviation" (let [db {:election-detail {:election {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}}] ;; note the transition from clojure style dashes to ;; json friendly underscores (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} (events/params (:early-vote-site-form db) db)))))) (deftest form-submit-test (testing "new early vote site" (let [db {:selected-election-id "fake-election-id" :election-detail {:election {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/form-submit {:db db} [:early-vote-site-form/save]) url (get-in fx [:http-xhrio :uri]) params (get-in fx [:http-xhrio :params]) method (get-in fx [:http-xhrio :method])] (is (= :post method)) (is (str/ends-with? url "/earlyvote/elections/fake-election-id/earlyvotesites")) (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} params)))) (testing "editing existing early vote site" (let [db {:selected-election-id "fake-election-id" :election-detail {:election {:state-fips "08"}} :early-vote-site-form {:id 123 :county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/form-submit {:db db} [:early-vote-site-form/save]) url (get-in fx [:http-xhrio :uri]) params (get-in fx [:http-xhrio :params]) method (get-in fx [:http-xhrio :method])] (is (= :put method)) (is (str/ends-with? url "/earlyvote/earlyvotesites/123")) (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} params))))) (deftest save-success-test (testing "save event" (let [db {:selected-election "fake-election-id" :election-detail {:detail {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "<NAME> Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/save-success {:db db} [])] (testing "cleared the form" (let [db-after (:db fx)] (is (= {:type "early_vote_site"} (:early-vote-site-form db-after))))) (testing "dispatches flash" (is (>= (.indexOf (:dispatch-n fx) [:flash/message "Early Vote Site saved"]) 0))) (testing "dispatches navigation to election-detail" (is (>= (.indexOf (:dispatch-n fx) [:navigate/election-detail]) 0))))))
true
(ns early-vote-site.early-vote-site-form.events-test (:require [cljs.test :refer-macros [deftest is testing]] [clojure.string :as str] [early-vote-site.early-vote-site-form.events :as events])) (deftest form-update-test (testing "updates the form state for the given field" (let [db-before {:early-vote-site-form {:name "Hi"}} db-after {:early-vote-site-form {:name "Hi" :county-fips "01234"}}] (is (= db-after (events/form-update db-before [:early-vote-site-form/update :county-fips "01234"])))))) (deftest params-test (testing "pulls together form and merges state abbreviation" (let [db {:election-detail {:election {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}}] ;; note the transition from clojure style dashes to ;; json friendly underscores (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} (events/params (:early-vote-site-form db) db)))))) (deftest form-submit-test (testing "new early vote site" (let [db {:selected-election-id "fake-election-id" :election-detail {:election {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/form-submit {:db db} [:early-vote-site-form/save]) url (get-in fx [:http-xhrio :uri]) params (get-in fx [:http-xhrio :params]) method (get-in fx [:http-xhrio :method])] (is (= :post method)) (is (str/ends-with? url "/earlyvote/elections/fake-election-id/earlyvotesites")) (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} params)))) (testing "editing existing early vote site" (let [db {:selected-election-id "fake-election-id" :election-detail {:election {:state-fips "08"}} :early-vote-site-form {:id 123 :county-fips "55555" :type "polling_location" :name "Test Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/form-submit {:db db} [:early-vote-site-form/save]) url (get-in fx [:http-xhrio :uri]) params (get-in fx [:http-xhrio :params]) method (get-in fx [:http-xhrio :method])] (is (= :put method)) (is (str/ends-with? url "/earlyvote/earlyvotesites/123")) (is (= {:county_fips "55555" :type "polling_location" :name "Test Location" :address_1 "123 Main St" :address_2 nil :address_3 nil :city "Steamboat Springs" :state "CO" :zip "80487" :directions nil :voter_services nil} params))))) (deftest save-success-test (testing "save event" (let [db {:selected-election "fake-election-id" :election-detail {:detail {:state-fips "08"}} :early-vote-site-form {:county-fips "55555" :type "polling_location" :name "PI:NAME:<NAME>END_PI Location" :address-1 "123 Main St" :city "Steamboat Springs" :zip "80487"}} fx (events/save-success {:db db} [])] (testing "cleared the form" (let [db-after (:db fx)] (is (= {:type "early_vote_site"} (:early-vote-site-form db-after))))) (testing "dispatches flash" (is (>= (.indexOf (:dispatch-n fx) [:flash/message "Early Vote Site saved"]) 0))) (testing "dispatches navigation to election-detail" (is (>= (.indexOf (:dispatch-n fx) [:navigate/election-detail]) 0))))))
[ { "context": "pired by factory_girl\"\n :url \"https://github.com/FundingCircle/factory-time\"\n :license {:name \"BSD 3-clause\"\n ", "end": 133, "score": 0.9995173811912537, "start": 120, "tag": "USERNAME", "value": "FundingCircle" }, { "context": ":env/clojars_user]\n :password [:gpg :env/clojars_password]}]\n [\"snaps", "end": 585, "score": 0.5460408329963684, "start": 582, "tag": "PASSWORD", "value": "gpg" }, { "context": "_user]\n :password [:gpg :env/clojars_password]}]\n [\"snapshots\"\n ", "end": 598, "score": 0.5219331979751587, "start": 594, "tag": "PASSWORD", "value": "jars" }, { "context": "]\n :password [:gpg :env/clojars_password]}]\n [\"snapshots\"\n ", "end": 607, "score": 0.5294207334518433, "start": 599, "tag": "PASSWORD", "value": "password" }, { "context": ":env/clojars_user]\n :password [:gpg :env/clojars_password]}]]\n :test-paths [\"spec\"])", "end": 820, "score": 0.6287750601768494, "start": 817, "tag": "PASSWORD", "value": "gpg" }, { "context": "jars_user]\n :password [:gpg :env/clojars_password]}]]\n :test-paths [\"spec\"])\n", "end": 842, "score": 0.7782015800476074, "start": 826, "tag": "PASSWORD", "value": "clojars_password" } ]
project.clj
FundingCircle/factory-time
13
(defproject factory-time "0.1.2" :description "A Clojure library inspired by factory_girl" :url "https://github.com/FundingCircle/factory-time" :license {:name "BSD 3-clause" :url "http://opensource.org/licenses/BSD-3-Clause"} :dependencies [[org.clojure/clojure "1.8.0"]] :profiles {:dev {:dependencies [[speclj "3.3.2"]]}} :plugins [[speclj "3.3.2"]] :repositories [["releases" {:url "https://clojars.org/repo" :sign-releases false :username [:gpg :env/clojars_user] :password [:gpg :env/clojars_password]}] ["snapshots" {:url "https://clojars.org/repo" :sign-releases false :username [:gpg :env/clojars_user] :password [:gpg :env/clojars_password]}]] :test-paths ["spec"])
21545
(defproject factory-time "0.1.2" :description "A Clojure library inspired by factory_girl" :url "https://github.com/FundingCircle/factory-time" :license {:name "BSD 3-clause" :url "http://opensource.org/licenses/BSD-3-Clause"} :dependencies [[org.clojure/clojure "1.8.0"]] :profiles {:dev {:dependencies [[speclj "3.3.2"]]}} :plugins [[speclj "3.3.2"]] :repositories [["releases" {:url "https://clojars.org/repo" :sign-releases false :username [:gpg :env/clojars_user] :password [:<PASSWORD> :env/clo<PASSWORD>_<PASSWORD>]}] ["snapshots" {:url "https://clojars.org/repo" :sign-releases false :username [:gpg :env/clojars_user] :password [:<PASSWORD> :env/<PASSWORD>]}]] :test-paths ["spec"])
true
(defproject factory-time "0.1.2" :description "A Clojure library inspired by factory_girl" :url "https://github.com/FundingCircle/factory-time" :license {:name "BSD 3-clause" :url "http://opensource.org/licenses/BSD-3-Clause"} :dependencies [[org.clojure/clojure "1.8.0"]] :profiles {:dev {:dependencies [[speclj "3.3.2"]]}} :plugins [[speclj "3.3.2"]] :repositories [["releases" {:url "https://clojars.org/repo" :sign-releases false :username [:gpg :env/clojars_user] :password [:PI:PASSWORD:<PASSWORD>END_PI :env/cloPI:PASSWORD:<PASSWORD>END_PI_PI:PASSWORD:<PASSWORD>END_PI]}] ["snapshots" {:url "https://clojars.org/repo" :sign-releases false :username [:gpg :env/clojars_user] :password [:PI:PASSWORD:<PASSWORD>END_PI :env/PI:PASSWORD:<PASSWORD>END_PI]}]] :test-paths ["spec"])
[ { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi", "end": 40, "score": 0.9998828768730164, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and", "end": 54, "score": 0.9999324679374695, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/clojure/catacumba/impl/executor.clj
source-c/catacumba
212
;; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns catacumba.impl.executor "A basic abstraction for executor services." (:require [promesa.core :as p]) (:import java.util.concurrent.ForkJoinPool java.util.concurrent.Executor java.util.concurrent.Executors java.util.concurrent.ThreadFactory)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The main abstraction definition. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol IExecutor (^:private -execute [_ task] "Execute a task in a executor.")) (defprotocol IExecutorService (^:private -submit [_ task] "Submit a task and return a promise.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-type Executor IExecutor (-execute [this task] (.execute this ^Runnable task)) IExecutorService (-submit [this task] (p/promise (fn [resolve reject] (-execute this #(try (resolve (task)) (catch Throwable e (reject e)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public Api ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:redef default (ForkJoinPool/commonPool)) (defn execute "Execute a task in a provided executor. A task is a plain clojure function or jvm Runnable instance." ([task] (-execute default task)) ([executor task] (-execute executor task))) (defn submit "Submit a task to be executed in a provided executor and return a promise that will be completed with the return value of a task. A task is a plain clojure function." ([task] (-submit default task)) ([executor task] (-submit executor task)))
43979
;; Copyright (c) 2015-2016 <NAME> <<EMAIL>> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns catacumba.impl.executor "A basic abstraction for executor services." (:require [promesa.core :as p]) (:import java.util.concurrent.ForkJoinPool java.util.concurrent.Executor java.util.concurrent.Executors java.util.concurrent.ThreadFactory)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The main abstraction definition. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol IExecutor (^:private -execute [_ task] "Execute a task in a executor.")) (defprotocol IExecutorService (^:private -submit [_ task] "Submit a task and return a promise.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-type Executor IExecutor (-execute [this task] (.execute this ^Runnable task)) IExecutorService (-submit [this task] (p/promise (fn [resolve reject] (-execute this #(try (resolve (task)) (catch Throwable e (reject e)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public Api ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:redef default (ForkJoinPool/commonPool)) (defn execute "Execute a task in a provided executor. A task is a plain clojure function or jvm Runnable instance." ([task] (-execute default task)) ([executor task] (-execute executor task))) (defn submit "Submit a task to be executed in a provided executor and return a promise that will be completed with the return value of a task. A task is a plain clojure function." ([task] (-submit default task)) ([executor task] (-submit executor task)))
true
;; Copyright (c) 2015-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; 1. Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; 2. Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (ns catacumba.impl.executor "A basic abstraction for executor services." (:require [promesa.core :as p]) (:import java.util.concurrent.ForkJoinPool java.util.concurrent.Executor java.util.concurrent.Executors java.util.concurrent.ThreadFactory)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The main abstraction definition. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol IExecutor (^:private -execute [_ task] "Execute a task in a executor.")) (defprotocol IExecutorService (^:private -submit [_ task] "Submit a task and return a promise.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (extend-type Executor IExecutor (-execute [this task] (.execute this ^Runnable task)) IExecutorService (-submit [this task] (p/promise (fn [resolve reject] (-execute this #(try (resolve (task)) (catch Throwable e (reject e)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public Api ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:redef default (ForkJoinPool/commonPool)) (defn execute "Execute a task in a provided executor. A task is a plain clojure function or jvm Runnable instance." ([task] (-execute default task)) ([executor task] (-execute executor task))) (defn submit "Submit a task to be executed in a provided executor and return a promise that will be completed with the return value of a task. A task is a plain clojure function." ([task] (-submit default task)) ([executor task] (-submit executor task)))
[ { "context": "t quantity])\n\n(def suppliers\n #{(Supplier. \"S1\" \"Smith\" 20 \"London\")\n (Supplier. \"S2\" \"Jones\" 10 \"Par", "end": 264, "score": 0.9996205568313599, "start": 259, "tag": "NAME", "value": "Smith" }, { "context": "r. \"S1\" \"Smith\" 20 \"London\")\n (Supplier. \"S2\" \"Jones\" 10 \"Paris\")\n (Supplier. \"S3\" \"Blake\" 30 \"Pari", "end": 305, "score": 0.9997663497924805, "start": 300, "tag": "NAME", "value": "Jones" }, { "context": "er. \"S2\" \"Jones\" 10 \"Paris\")\n (Supplier. \"S3\" \"Blake\" 30 \"Paris\")})\n\n(def parts\n #{(Part. \"P1\" \"Nut\" ", "end": 345, "score": 0.9995104670524597, "start": 340, "tag": "NAME", "value": "Blake" }, { "context": "id, :city :location})\n\n(set/select #(= (:name %) \"Smith\") suppliers)\n\n(filter #(= (:city %) \"Paris\") (set", "end": 699, "score": 0.998482346534729, "start": 694, "tag": "NAME", "value": "Smith" } ]
src/data/sets.cljc
priyatam/thinking-clojurescript
4
(ns data.sets (:require [clojure.set :as set])) (def a-set #{"one" "two"}) (defrecord Supplier [number name status city]) (defrecord Part [number name colour weight city]) (defrecord Shipment [supplier part quantity]) (def suppliers #{(Supplier. "S1" "Smith" 20 "London") (Supplier. "S2" "Jones" 10 "Paris") (Supplier. "S3" "Blake" 30 "Paris")}) (def parts #{(Part. "P1" "Nut" "Red" 12.0 "London") (Part. "P2" "Bolt" "Green" 17.0 "Paris") (Part. "P3" "Screw" "Blue" 17.0 "Oslo")}) (def shipments #{(Shipment. "S1" "P1" 300) (Shipment. "S2" "P2" 200) (Shipment. "S3" "P3" 400)}) (set/rename parts {:number :id, :city :location}) (set/select #(= (:name %) "Smith") suppliers) (filter #(= (:city %) "Paris") (set/project suppliers [:city])) (set/join parts shipments {:number :part}) (def res (set/project (set/join (set/select #(= (:city %) "Paris") suppliers) shipments {:number :supplier}) [:name]))
14653
(ns data.sets (:require [clojure.set :as set])) (def a-set #{"one" "two"}) (defrecord Supplier [number name status city]) (defrecord Part [number name colour weight city]) (defrecord Shipment [supplier part quantity]) (def suppliers #{(Supplier. "S1" "<NAME>" 20 "London") (Supplier. "S2" "<NAME>" 10 "Paris") (Supplier. "S3" "<NAME>" 30 "Paris")}) (def parts #{(Part. "P1" "Nut" "Red" 12.0 "London") (Part. "P2" "Bolt" "Green" 17.0 "Paris") (Part. "P3" "Screw" "Blue" 17.0 "Oslo")}) (def shipments #{(Shipment. "S1" "P1" 300) (Shipment. "S2" "P2" 200) (Shipment. "S3" "P3" 400)}) (set/rename parts {:number :id, :city :location}) (set/select #(= (:name %) "<NAME>") suppliers) (filter #(= (:city %) "Paris") (set/project suppliers [:city])) (set/join parts shipments {:number :part}) (def res (set/project (set/join (set/select #(= (:city %) "Paris") suppliers) shipments {:number :supplier}) [:name]))
true
(ns data.sets (:require [clojure.set :as set])) (def a-set #{"one" "two"}) (defrecord Supplier [number name status city]) (defrecord Part [number name colour weight city]) (defrecord Shipment [supplier part quantity]) (def suppliers #{(Supplier. "S1" "PI:NAME:<NAME>END_PI" 20 "London") (Supplier. "S2" "PI:NAME:<NAME>END_PI" 10 "Paris") (Supplier. "S3" "PI:NAME:<NAME>END_PI" 30 "Paris")}) (def parts #{(Part. "P1" "Nut" "Red" 12.0 "London") (Part. "P2" "Bolt" "Green" 17.0 "Paris") (Part. "P3" "Screw" "Blue" 17.0 "Oslo")}) (def shipments #{(Shipment. "S1" "P1" 300) (Shipment. "S2" "P2" 200) (Shipment. "S3" "P3" 400)}) (set/rename parts {:number :id, :city :location}) (set/select #(= (:name %) "PI:NAME:<NAME>END_PI") suppliers) (filter #(= (:city %) "Paris") (set/project suppliers [:city])) (set/join parts shipments {:number :part}) (def res (set/project (set/join (set/select #(= (:city %) "Paris") suppliers) shipments {:number :supplier}) [:name]))
[ { "context": " limitations under the License.\n;\n\n(ns ^{:author \"Hunter Hutchinson, hunter.hutchinson@gmail.com\"}\n com.palletops.jc", "end": 818, "score": 0.9998704791069031, "start": 801, "tag": "NAME", "value": "Hunter Hutchinson" }, { "context": " the License.\n;\n\n(ns ^{:author \"Hunter Hutchinson, hunter.hutchinson@gmail.com\"}\n com.palletops.jclouds.ec2.ami2\n \"A clojure b", "end": 847, "score": 0.9999180436134338, "start": 820, "tag": "EMAIL", "value": "hunter.hutchinson@gmail.com" } ]
src/com/palletops/jclouds/ec2/ami2.clj
pallet/clj-jclouds
5
; ; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns ^{:author "Hunter Hutchinson, hunter.hutchinson@gmail.com"} com.palletops.jclouds.ec2.ami2 "A clojure binding to the jclouds AMI service interface." (:use [com.palletops.jclouds.compute2 :only [location]]) (:import org.jclouds.aws.domain.Region org.jclouds.ec2.features.AMIApi org.jclouds.ec2.options.CreateImageOptions org.jclouds.compute.domain.NodeMetadata (org.jclouds.ec2.domain Volume Volume$Status Snapshot Snapshot$Status AvailabilityZoneInfo))) (defn ^org.jclouds.ec2.features.AMIApi ami-service "" [compute] (-> compute .getContext .getProviderSpecificContext .getApi .getAMIApi .get)) (defn get-region "Coerces the first parameter into a Region string; strings, keywords, and NodeMetadata instances are acceptable arguments. An optional second argument is returned if the first cannot be coerced into a region string. Returns nil otherwise." ([v] (get-region v nil)) ([v default-region] (cond (string? v) v (keyword? v) (name v) (instance? NodeMetadata v) (let [zone (location v)] ; no easier way to go from zone -> region? (if (> (.indexOf zone "-") -1) (subs zone 0 (-> zone count dec)) zone)) :else default-region))) (defn- as-string [v] (cond (string? v) v (keyword? v) (name v) :else v)) (defn- get-string [map key] (as-string (get map key))) (defn- as-int [v] (cond (number? v) (int v) (string? v) (Integer/parseInt v) :else (throw (IllegalArgumentException. (str "Don't know how to convert object of type " (class v) " to a string"))))) (defn create-image-in-region ([compute region name node-id description] (.createImageInRegion (ami-service compute) (get-region region) (as-string name) (as-string node-id) (into-array CreateImageOptions (when description [(.withDescription (CreateImageOptions.) description)])))))
89692
; ; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns ^{:author "<NAME>, <EMAIL>"} com.palletops.jclouds.ec2.ami2 "A clojure binding to the jclouds AMI service interface." (:use [com.palletops.jclouds.compute2 :only [location]]) (:import org.jclouds.aws.domain.Region org.jclouds.ec2.features.AMIApi org.jclouds.ec2.options.CreateImageOptions org.jclouds.compute.domain.NodeMetadata (org.jclouds.ec2.domain Volume Volume$Status Snapshot Snapshot$Status AvailabilityZoneInfo))) (defn ^org.jclouds.ec2.features.AMIApi ami-service "" [compute] (-> compute .getContext .getProviderSpecificContext .getApi .getAMIApi .get)) (defn get-region "Coerces the first parameter into a Region string; strings, keywords, and NodeMetadata instances are acceptable arguments. An optional second argument is returned if the first cannot be coerced into a region string. Returns nil otherwise." ([v] (get-region v nil)) ([v default-region] (cond (string? v) v (keyword? v) (name v) (instance? NodeMetadata v) (let [zone (location v)] ; no easier way to go from zone -> region? (if (> (.indexOf zone "-") -1) (subs zone 0 (-> zone count dec)) zone)) :else default-region))) (defn- as-string [v] (cond (string? v) v (keyword? v) (name v) :else v)) (defn- get-string [map key] (as-string (get map key))) (defn- as-int [v] (cond (number? v) (int v) (string? v) (Integer/parseInt v) :else (throw (IllegalArgumentException. (str "Don't know how to convert object of type " (class v) " to a string"))))) (defn create-image-in-region ([compute region name node-id description] (.createImageInRegion (ami-service compute) (get-region region) (as-string name) (as-string node-id) (into-array CreateImageOptions (when description [(.withDescription (CreateImageOptions.) description)])))))
true
; ; Licensed to the Apache Software Foundation (ASF) under one or more ; contributor license agreements. See the NOTICE file distributed with ; this work for additional information regarding copyright ownership. ; The ASF licenses this file to You under the Apache License, Version 2.0 ; (the "License"); you may not use this file except in compliance with ; the License. You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; (ns ^{:author "PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI"} com.palletops.jclouds.ec2.ami2 "A clojure binding to the jclouds AMI service interface." (:use [com.palletops.jclouds.compute2 :only [location]]) (:import org.jclouds.aws.domain.Region org.jclouds.ec2.features.AMIApi org.jclouds.ec2.options.CreateImageOptions org.jclouds.compute.domain.NodeMetadata (org.jclouds.ec2.domain Volume Volume$Status Snapshot Snapshot$Status AvailabilityZoneInfo))) (defn ^org.jclouds.ec2.features.AMIApi ami-service "" [compute] (-> compute .getContext .getProviderSpecificContext .getApi .getAMIApi .get)) (defn get-region "Coerces the first parameter into a Region string; strings, keywords, and NodeMetadata instances are acceptable arguments. An optional second argument is returned if the first cannot be coerced into a region string. Returns nil otherwise." ([v] (get-region v nil)) ([v default-region] (cond (string? v) v (keyword? v) (name v) (instance? NodeMetadata v) (let [zone (location v)] ; no easier way to go from zone -> region? (if (> (.indexOf zone "-") -1) (subs zone 0 (-> zone count dec)) zone)) :else default-region))) (defn- as-string [v] (cond (string? v) v (keyword? v) (name v) :else v)) (defn- get-string [map key] (as-string (get map key))) (defn- as-int [v] (cond (number? v) (int v) (string? v) (Integer/parseInt v) :else (throw (IllegalArgumentException. (str "Don't know how to convert object of type " (class v) " to a string"))))) (defn create-image-in-region ([compute region name node-id description] (.createImageInRegion (ami-service compute) (get-region region) (as-string name) (as-string node-id) (into-array CreateImageOptions (when description [(.withDescription (CreateImageOptions.) description)])))))
[ { "context": " [clojure.string :as s]))\n\n(def sendgrid-api-key \"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\")\n(def sendgrid-api-url \"https://api.sendgrid.com", "end": 601, "score": 0.9997792840003967, "start": 532, "tag": "KEY", "value": "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" }, { "context": "pi.sendgrid.com/v3/\")\n(def sendgrid-default-from \"info@vetd.com\")\n(def sendgrid-default-from-name \"Vetd Team\")\n(d", "end": 699, "score": 0.9999170303344727, "start": 686, "tag": "EMAIL", "value": "info@vetd.com" }, { "context": "))\n\n;;;; Example Usage\n#_(send-template-email\n \"chris@vetd.com\"\n {:subject \"Vetd Buying Platform\"\n :prehead", "end": 2123, "score": 0.9999274015426636, "start": 2109, "tag": "EMAIL", "value": "chris@vetd.com" }, { "context": " [:or\n [:like :u.email \"%@vetd.com\"]\n [:like :u.email \"temp@%\"]]]]]", "end": 5928, "score": 0.9990520477294922, "start": 5917, "tag": "EMAIL", "value": "\"%@vetd.com" } ]
src/clj/com/vetd/app/email_client.clj
jaydeesimon/vetd-app
98
(ns com.vetd.app.email-client (:require [com.vetd.app.common :as com] [com.vetd.app.util :as ut] [com.vetd.app.env :as env] [com.vetd.app.db :as db] [com.vetd.app.hasura :as ha] [com.vetd.app.links :as l] [taoensso.timbre :as log] [clj-http.client :as client] [clj-time.periodic :as t-per] [tick.core :as tick] [tick.alpha.api :as tcka] [clojure.string :as s])) (def sendgrid-api-key "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") (def sendgrid-api-url "https://api.sendgrid.com/v3/") (def sendgrid-default-from "info@vetd.com") (def sendgrid-default-from-name "Vetd Team") (def sendgrid-default-template-id "d-0942e461a64943018bd0d1d6cf711e21") ; "Simple" template (def common-opts {:as :json :content-type :json :coerce :always :throw-exceptions false :headers {"Authorization" (str "Bearer " sendgrid-api-key)}}) ;; NOTE when :success is true, :resp is nil. (defn- request [endpoint & [params headers]] (try (let [resp (-> (client/post (str sendgrid-api-url endpoint) (merge-with merge common-opts {:form-params params} {:headers headers})) :body)] {:success (not (seq (:errors resp))) :resp resp}) (catch Exception e (com/log-error e) {:success false :resp {:error {:message (.getMessage e)}}}))) (defn send-template-email [to data & [{:keys [from from-name template-id]}]] (request "mail/send" {:personalizations [{:to [{:email to}] :dynamic_template_data data}] :from {:email (or from sendgrid-default-from) :name (or from-name sendgrid-default-from-name)} :template_id (or template-id sendgrid-default-template-id)})) ;;;; Example Usage #_(send-template-email "chris@vetd.com" {:subject "Vetd Buying Platform" :preheader "You're going to want to see what's in this email" :main-content "Here is some example content."}) (defn- insert-unsubscribe [{:keys [user-id org-id etype]}] (let [[id idstr] (ut/mk-id&str)] (db/insert! :unsubscribes {:id id :idstr idstr :created (ut/now-ts) :updated (ut/now-ts) :deleted nil :user_id user-id :org_id org-id :etype etype}) id)) (defn unsubscribe "Unsubscribe a user from an email type." [{:keys [user-id org-id etype] :as args}] (insert-unsubscribe args)) (defn create-unsubscribe-link "Create a new unsubscribe link. Return the link url." [{:keys [user-id org-id etype] :as input}] (str l/base-url (l/create {:cmd :email-unsubscribe :input-data (select-keys input [:user-id :org-id :etype]) ;; a year from now :expires-action (+ (ut/now) (* 1000 60 60 24 365))}))) (defmethod l/action :email-unsubscribe [{:keys [input-data] :as link} _] (do (l/update-expires link "read" (+ (ut/now) (* 1000 60 5))) ; allow read for next 5 mins) {:unsubscribed? (boolean (unsubscribe input-data))})) ;;;; Auto Email (defonce scheduled-email-thread& (atom nil)) (defonce next-scheduled-event& (atom nil)) (def override-now& (atom nil)) (defn now- [] (or @override-now& (tick/now))) (defn monday? [x] (= (tick/day-of-week x) #time/day-of-week "MONDAY")) (defn nine-am-pdt? [x] (= (tick/hour x) 16)) (defn calc-next-due-ts [dt] (->> (tick/range (-> (tick/truncate dt :hours) (tick/+ (tick/new-duration 1 :hours))) (tick/+ dt (tick/new-period 8 :days)) (tick/new-duration 1 :hours)) (filter #(and (monday? %) (nine-am-pdt? %))) first)) (defn tick->ts [t] (tick/millis (tick/between (tick/epoch) t))) (defn ts->tick [msecs] (tcka/+ (tick/epoch) (tick/new-duration msecs :millis))) (defn insert-email-sent-log-entry [{:keys [etype org-id user-id data]}] (let [[id idstr] (ut/mk-id&str)] (-> (db/insert! :email_sent_log {:id id :idstr idstr :created (ut/now-ts) :updated (ut/now-ts) :etype (name etype) :org_id org-id :user_id user-id :data data}) first))) ;; TODO This will get trickier when we have multiple app server instances running again (defn select-next-email&recipient [max-ts] (-> {:select [[:%max.esl.created :max-created] [:m.id :membership-id] [:m.user_id :user-id] [:u.email :email] [:u.uname :uname] [:m.org_id :org-id] [:o.oname :oname]] :from [[:orgs :o]] :join [[:memberships :m] [:and [:= :m.deleted nil] [:= :m.org_id :o.id]] [:users :u] [:and [:= :u.id :user_id] [:= :u.deleted nil] ;; exclude users that were created less than 3 days ago [:< :u.created (->> (tick/new-period 3 :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)] [:like :u.email "%@%"] ;; primitive email address validation [:or ;; exclude test accounts, but let through real "Vetd" org [:= :m.org_id 2208512249632] [:not [:or [:like :u.email "%@vetd.com"] [:like :u.email "temp@%"]]]]]] :left-join [[:email_sent_log :esl] [:= :esl.user_id :m.user_id] [:unsubscribes :uns] [:and [:= :uns.user_id :u.id] [:= :uns.org_id :o.id] [:= :uns.etype "weekly-buyer-email"] [:= :uns.deleted nil]]] :where [:and [:= :o.deleted nil] [:= :o.buyer_qm true] [:= :uns.id nil]] :group-by [:m.id :m.user_id :m.org_id :o.oname :u.email :u.uname] :having [:or [:= :%max.esl.created nil] [:< :%max.esl.created (java.sql.Timestamp. max-ts)]] :limit 1} db/hs-query first)) (defn last-email-sent [etype] (-> {:select [[:%max.esl.created :max-created]] :from [[:email_sent_log :esl]] :where [:and [:= :esl.deleted nil] [:= :esl.etype etype]] :limit 1} db/hs-query first :max-created)) ;; days-forward should be less than 30/31 if using price-period of monthly (defn get-weekly-auto-email-data--product-renewals-soon [org-id price-period days-forward limit] (->> [[:stack-items {:_where {:_and (concat [{:status {:_eq "current"}} {:buyer_id {:_eq (str org-id)}} ;; {:renewal-reminder {:_eq true}} ;; include regardless of reminder checked {:price-period {:_eq price-period}} {:deleted {:_is_null true}}] (if (= price-period "monthly") (let [start-day (tick/day-of-month (now-)) end-day (->> (tick/new-period days-forward :days) (tick/+ (now-)) tick/day-of-month)] (if (> start-day end-day) ;; it wrapped around to next month [{:_or [{:renewal-day-of-month {:_gte start-day}} {:renewal-day-of-month {:_lte end-day}}]}] [{:renewal-day-of-month {:_gte start-day}} {:renewal-day-of-month {:_lte end-day}}])) [{:renewal-date {:_gte (str (tick/date (ut/now-ts)))}} {:renewal-date {:_lte (->> (tick/new-period days-forward :days) (tick/+ (now-)) tick/date str)}}]))} :_order_by {:renewal-date :asc} :_limit limit} [:price-amount :renewal-date :renewal-day-of-month [:product [:pname]]]]] ha/sync-query :stack-items (map (fn [{:keys [renewal-day-of-month] :as si}] (let [si-with-date (if (= price-period "monthly") (assoc si :renewal-date (str "on the " (ut/append-ordinal-suffix renewal-day-of-month))) (update-in si [:renewal-date] (comp str tick/date)))] (update-in si-with-date [:price-amount] #(some-> % ut/->dollars-str))))))) ;; active rounds are rounds that are "in-progress" (defn get-weekly-auto-email-data--active-rounds [org-id] (->> [[:rounds {:deleted nil :status "in-progress" :buyer-id org-id :_order_by {:created :desc}} [:id :idstr :title [:products [:id]]]]] ha/sync-query :rounds (map (fn [{:keys [products] :as round}] (assoc round :num-products (count products)))))) (defn get-weekly-auto-email-data--recent-preposals [org-id] (->> [[:form-docs {:ftype "preposal" :from-org-id org-id :_where {:_or [;; when Vetd requested the estimate on behalf of user (forwarded email) {:_and [{:created {:_gt (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. str)}} {:title {:_like "ADMIN %"}}]} ;; when the vendor created the estimate (preposal) {:doc-created {:_gt (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. str)}}]} :_order_by {:created :desc}} [:id :created :updated :doc-id :doc-created [:product [:pname]] [:from-org [:oname]] [:from-user [:id :uname]] [:to-org [:id :oname]]]]] ha/sync-query :form-docs (#(assoc {} :preposals (filter :doc-id %) :preposals-count (count (filter :doc-id %)) ;; Since we create preposals on behalf of the user ;; number of preposal requests with title beginning with "ADMIN " ;; is a proxy for the number of emails they forwarded to us. :num-emails-forwarded (count (filter (fn [form-doc] (> (->> form-doc :created .getTime) (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. .getTime))) %)))))) (defn get-weekly-auto-email-data--communities-num-new-discounts [group-id days-back] (->> {:select [[:%count.gd.id :count]] :from [[:group_discounts :gd]] :where [:and [:= :gd.deleted nil] [:= :gd.group_id group-id] [:> :gd.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]]} db/hs-query first :count)) (defn get-weekly-auto-email-data--communities-num-new-orgs [group-id days-back] (->> {:select [[:%count.gom.org_id :count]] :from [[:group_org_memberships :gom]] :where [:and [:= :gom.deleted nil] [:= :gom.group_id group-id] [:> :gom.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]]} db/hs-query first :count)) (defn get-weekly-auto-email-data--communities-num-new-stacks [group-id days-back] (-> {:select [[:%count.si.buyer_id :si-buyer-count]] :from [[:group_org_memberships :gom]] :join [[:stack_items :si] [:and [:= :si.buyer_id :gom.org_id] [:= :si.deleted nil]]] :where [:and [:= :gom.deleted nil] [:= :gom.group_id group-id]] :group-by [:si.buyer_id] :having [:> :%min.si.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]} db/hs-query count)) (defn get-weekly-auto-email-data--communities-recent-threads "For group-id, in the past days-back, the new threads that were created OR existing threads that gained a reply." [group-id days-back] (let [days-back-tick (->> (tick/new-period days-back :days) (tick/- (now-))) created-after-days-back? (comp (partial tick/< days-back-tick) tick/instant :created)] (->> [[:threads {:group-id (str group-id) :deleted nil :_limit 100 ;; hopefully enough to get all the old ones w/ recent replies :_order_by {:created :desc}} [:title :created [:messages {:deleted nil} [:created [:user [:uname]] [:org [:oname]]]]]]] ha/sync-query :threads (map #(identity {:title (-> % :title) :user-name (some-> % :messages first :user :uname) :org-name (some-> % :messages first :org :oname) :num-recent-replies (->> % :messages (drop 1) ;; the root message of the thread (filter created-after-days-back?) count) :created (-> % :created)})) (filter (some-fn (comp pos? :num-recent-replies) ;; has recent replies? ;; or thread itself was created recently? created-after-days-back?)) (map #(assoc % :num-recent-replies-string (let [num-recent-replies (:num-recent-replies %)] (cond (= 1 num-recent-replies) (str "(1 new reply)") (pos? num-recent-replies) (str "(" num-recent-replies " new replies)") :else "")))) (take 10)))) (defn get-weekly-auto-email-data--communities [group-id] (let [{:keys [gname]} (->> [[:groups {:id group-id} [:gname]]] ha/sync-query vals ffirst)] {:group-name gname :num-new-discounts (get-weekly-auto-email-data--communities-num-new-discounts group-id 7) :num-new-orgs (get-weekly-auto-email-data--communities-num-new-orgs group-id 7) :num-new-stacks (get-weekly-auto-email-data--communities-num-new-stacks group-id 7) :recent-threads (get-weekly-auto-email-data--communities-recent-threads group-id 7)})) (defn get-weekly-auto-email-data [user-id org-id oname uname] (let [group-ids (some->> [[:group-org-memberships {:org-id org-id} [:group-id]]] ha/sync-query vals first (map :group-id)) recent-preposals (get-weekly-auto-email-data--recent-preposals org-id) product-annual-renewals-soon (get-weekly-auto-email-data--product-renewals-soon org-id "annual" 30 15) product-monthly-renewals-soon (get-weekly-auto-email-data--product-renewals-soon org-id "monthly" 7 15) active-rounds (get-weekly-auto-email-data--active-rounds org-id)] {:base-url "https://app.vetd.com/" :unsubscribe-link (create-unsubscribe-link {:user-id user-id :org-id org-id :etype (name :weekly-buyer-email)}) ;; get just the First Name :user-name (str ;; nil -> "" (some->> (s/split (s/lower-case uname) #" ") (remove #{"mr." "mrs." "ms." "dr." "mr" "mrs" "ms" "dr"}) first s/capitalize)) :org-name oname :recent-preposals recent-preposals :product-annual-renewals-soon product-annual-renewals-soon :product-annual-renewals-soon-count (count product-annual-renewals-soon) :product-monthly-renewals-soon product-monthly-renewals-soon :product-monthly-renewals-soon-count (count product-monthly-renewals-soon) :active-rounds active-rounds :active-rounds-count (count active-rounds) :communities (map get-weekly-auto-email-data--communities group-ids)})) (defn do-scheduled-emailer [threshold-dt] (try (log/info (str "CALL do-scheduled-emailer " threshold-dt)) (let [threshold-ts (tick->ts threshold-dt)] (while (try (when-let [{:keys [email oname uname user-id org-id max-created]} (select-next-email&recipient threshold-ts)] (let [data (get-weekly-auto-email-data user-id org-id oname uname)] (send-template-email email data {:template-id "d-76e51dc96f2d4d7e8438bd6b407504f9"}) (insert-email-sent-log-entry {:etype :weekly-buyer-email :user-id user-id :org-id org-id :data data})) (Thread/sleep 1000) true) (catch Throwable e (com/log-error e) false)))) (catch Throwable e (com/log-error e) (Thread/sleep (* 1000 60 60))))) ;; this is not tested with multiple concurrent instances, but should be fine (defn start-scheduled-emailer-thread [] (when (and (not env/building?) ;; not while building env/prod? ;; only in prod (nil? @scheduled-email-thread&)) ;; we only need one thread (reset! scheduled-email-thread& (future (log/info "Starting scheduled-emailer") (reset! next-scheduled-event& ;; find the next send time based on email sent log (tick/instant (calc-next-due-ts (or (some-> (last-email-sent "weekly-buyer-email") tick/date-time) ;; if never sent, the -1 day allows it to possibly send today (if Monday) (tick/- (now-) (tick/new-period 1 :days)))))) (while (not @com/shutdown-signal) (let [event-time @next-scheduled-event&] (if (tick/> (now-) event-time) (do (reset! next-scheduled-event& (calc-next-due-ts (now-))) (#'do-scheduled-emailer (tick/- event-time (tick/new-period 6 :days)))) (Thread/sleep (* 1000 10))))) (log/info "Stopped scheduled-emailer"))))) (start-scheduled-emailer-thread) #_ (future-cancel @scheduled-email-thread&) #_ (reset! override-now& (tick/+ (tick/now) (tick/new-period 6 :days)))
2066
(ns com.vetd.app.email-client (:require [com.vetd.app.common :as com] [com.vetd.app.util :as ut] [com.vetd.app.env :as env] [com.vetd.app.db :as db] [com.vetd.app.hasura :as ha] [com.vetd.app.links :as l] [taoensso.timbre :as log] [clj-http.client :as client] [clj-time.periodic :as t-per] [tick.core :as tick] [tick.alpha.api :as tcka] [clojure.string :as s])) (def sendgrid-api-key "<KEY>") (def sendgrid-api-url "https://api.sendgrid.com/v3/") (def sendgrid-default-from "<EMAIL>") (def sendgrid-default-from-name "Vetd Team") (def sendgrid-default-template-id "d-0942e461a64943018bd0d1d6cf711e21") ; "Simple" template (def common-opts {:as :json :content-type :json :coerce :always :throw-exceptions false :headers {"Authorization" (str "Bearer " sendgrid-api-key)}}) ;; NOTE when :success is true, :resp is nil. (defn- request [endpoint & [params headers]] (try (let [resp (-> (client/post (str sendgrid-api-url endpoint) (merge-with merge common-opts {:form-params params} {:headers headers})) :body)] {:success (not (seq (:errors resp))) :resp resp}) (catch Exception e (com/log-error e) {:success false :resp {:error {:message (.getMessage e)}}}))) (defn send-template-email [to data & [{:keys [from from-name template-id]}]] (request "mail/send" {:personalizations [{:to [{:email to}] :dynamic_template_data data}] :from {:email (or from sendgrid-default-from) :name (or from-name sendgrid-default-from-name)} :template_id (or template-id sendgrid-default-template-id)})) ;;;; Example Usage #_(send-template-email "<EMAIL>" {:subject "Vetd Buying Platform" :preheader "You're going to want to see what's in this email" :main-content "Here is some example content."}) (defn- insert-unsubscribe [{:keys [user-id org-id etype]}] (let [[id idstr] (ut/mk-id&str)] (db/insert! :unsubscribes {:id id :idstr idstr :created (ut/now-ts) :updated (ut/now-ts) :deleted nil :user_id user-id :org_id org-id :etype etype}) id)) (defn unsubscribe "Unsubscribe a user from an email type." [{:keys [user-id org-id etype] :as args}] (insert-unsubscribe args)) (defn create-unsubscribe-link "Create a new unsubscribe link. Return the link url." [{:keys [user-id org-id etype] :as input}] (str l/base-url (l/create {:cmd :email-unsubscribe :input-data (select-keys input [:user-id :org-id :etype]) ;; a year from now :expires-action (+ (ut/now) (* 1000 60 60 24 365))}))) (defmethod l/action :email-unsubscribe [{:keys [input-data] :as link} _] (do (l/update-expires link "read" (+ (ut/now) (* 1000 60 5))) ; allow read for next 5 mins) {:unsubscribed? (boolean (unsubscribe input-data))})) ;;;; Auto Email (defonce scheduled-email-thread& (atom nil)) (defonce next-scheduled-event& (atom nil)) (def override-now& (atom nil)) (defn now- [] (or @override-now& (tick/now))) (defn monday? [x] (= (tick/day-of-week x) #time/day-of-week "MONDAY")) (defn nine-am-pdt? [x] (= (tick/hour x) 16)) (defn calc-next-due-ts [dt] (->> (tick/range (-> (tick/truncate dt :hours) (tick/+ (tick/new-duration 1 :hours))) (tick/+ dt (tick/new-period 8 :days)) (tick/new-duration 1 :hours)) (filter #(and (monday? %) (nine-am-pdt? %))) first)) (defn tick->ts [t] (tick/millis (tick/between (tick/epoch) t))) (defn ts->tick [msecs] (tcka/+ (tick/epoch) (tick/new-duration msecs :millis))) (defn insert-email-sent-log-entry [{:keys [etype org-id user-id data]}] (let [[id idstr] (ut/mk-id&str)] (-> (db/insert! :email_sent_log {:id id :idstr idstr :created (ut/now-ts) :updated (ut/now-ts) :etype (name etype) :org_id org-id :user_id user-id :data data}) first))) ;; TODO This will get trickier when we have multiple app server instances running again (defn select-next-email&recipient [max-ts] (-> {:select [[:%max.esl.created :max-created] [:m.id :membership-id] [:m.user_id :user-id] [:u.email :email] [:u.uname :uname] [:m.org_id :org-id] [:o.oname :oname]] :from [[:orgs :o]] :join [[:memberships :m] [:and [:= :m.deleted nil] [:= :m.org_id :o.id]] [:users :u] [:and [:= :u.id :user_id] [:= :u.deleted nil] ;; exclude users that were created less than 3 days ago [:< :u.created (->> (tick/new-period 3 :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)] [:like :u.email "%@%"] ;; primitive email address validation [:or ;; exclude test accounts, but let through real "Vetd" org [:= :m.org_id 2208512249632] [:not [:or [:like :u.email <EMAIL>"] [:like :u.email "temp@%"]]]]]] :left-join [[:email_sent_log :esl] [:= :esl.user_id :m.user_id] [:unsubscribes :uns] [:and [:= :uns.user_id :u.id] [:= :uns.org_id :o.id] [:= :uns.etype "weekly-buyer-email"] [:= :uns.deleted nil]]] :where [:and [:= :o.deleted nil] [:= :o.buyer_qm true] [:= :uns.id nil]] :group-by [:m.id :m.user_id :m.org_id :o.oname :u.email :u.uname] :having [:or [:= :%max.esl.created nil] [:< :%max.esl.created (java.sql.Timestamp. max-ts)]] :limit 1} db/hs-query first)) (defn last-email-sent [etype] (-> {:select [[:%max.esl.created :max-created]] :from [[:email_sent_log :esl]] :where [:and [:= :esl.deleted nil] [:= :esl.etype etype]] :limit 1} db/hs-query first :max-created)) ;; days-forward should be less than 30/31 if using price-period of monthly (defn get-weekly-auto-email-data--product-renewals-soon [org-id price-period days-forward limit] (->> [[:stack-items {:_where {:_and (concat [{:status {:_eq "current"}} {:buyer_id {:_eq (str org-id)}} ;; {:renewal-reminder {:_eq true}} ;; include regardless of reminder checked {:price-period {:_eq price-period}} {:deleted {:_is_null true}}] (if (= price-period "monthly") (let [start-day (tick/day-of-month (now-)) end-day (->> (tick/new-period days-forward :days) (tick/+ (now-)) tick/day-of-month)] (if (> start-day end-day) ;; it wrapped around to next month [{:_or [{:renewal-day-of-month {:_gte start-day}} {:renewal-day-of-month {:_lte end-day}}]}] [{:renewal-day-of-month {:_gte start-day}} {:renewal-day-of-month {:_lte end-day}}])) [{:renewal-date {:_gte (str (tick/date (ut/now-ts)))}} {:renewal-date {:_lte (->> (tick/new-period days-forward :days) (tick/+ (now-)) tick/date str)}}]))} :_order_by {:renewal-date :asc} :_limit limit} [:price-amount :renewal-date :renewal-day-of-month [:product [:pname]]]]] ha/sync-query :stack-items (map (fn [{:keys [renewal-day-of-month] :as si}] (let [si-with-date (if (= price-period "monthly") (assoc si :renewal-date (str "on the " (ut/append-ordinal-suffix renewal-day-of-month))) (update-in si [:renewal-date] (comp str tick/date)))] (update-in si-with-date [:price-amount] #(some-> % ut/->dollars-str))))))) ;; active rounds are rounds that are "in-progress" (defn get-weekly-auto-email-data--active-rounds [org-id] (->> [[:rounds {:deleted nil :status "in-progress" :buyer-id org-id :_order_by {:created :desc}} [:id :idstr :title [:products [:id]]]]] ha/sync-query :rounds (map (fn [{:keys [products] :as round}] (assoc round :num-products (count products)))))) (defn get-weekly-auto-email-data--recent-preposals [org-id] (->> [[:form-docs {:ftype "preposal" :from-org-id org-id :_where {:_or [;; when Vetd requested the estimate on behalf of user (forwarded email) {:_and [{:created {:_gt (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. str)}} {:title {:_like "ADMIN %"}}]} ;; when the vendor created the estimate (preposal) {:doc-created {:_gt (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. str)}}]} :_order_by {:created :desc}} [:id :created :updated :doc-id :doc-created [:product [:pname]] [:from-org [:oname]] [:from-user [:id :uname]] [:to-org [:id :oname]]]]] ha/sync-query :form-docs (#(assoc {} :preposals (filter :doc-id %) :preposals-count (count (filter :doc-id %)) ;; Since we create preposals on behalf of the user ;; number of preposal requests with title beginning with "ADMIN " ;; is a proxy for the number of emails they forwarded to us. :num-emails-forwarded (count (filter (fn [form-doc] (> (->> form-doc :created .getTime) (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. .getTime))) %)))))) (defn get-weekly-auto-email-data--communities-num-new-discounts [group-id days-back] (->> {:select [[:%count.gd.id :count]] :from [[:group_discounts :gd]] :where [:and [:= :gd.deleted nil] [:= :gd.group_id group-id] [:> :gd.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]]} db/hs-query first :count)) (defn get-weekly-auto-email-data--communities-num-new-orgs [group-id days-back] (->> {:select [[:%count.gom.org_id :count]] :from [[:group_org_memberships :gom]] :where [:and [:= :gom.deleted nil] [:= :gom.group_id group-id] [:> :gom.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]]} db/hs-query first :count)) (defn get-weekly-auto-email-data--communities-num-new-stacks [group-id days-back] (-> {:select [[:%count.si.buyer_id :si-buyer-count]] :from [[:group_org_memberships :gom]] :join [[:stack_items :si] [:and [:= :si.buyer_id :gom.org_id] [:= :si.deleted nil]]] :where [:and [:= :gom.deleted nil] [:= :gom.group_id group-id]] :group-by [:si.buyer_id] :having [:> :%min.si.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]} db/hs-query count)) (defn get-weekly-auto-email-data--communities-recent-threads "For group-id, in the past days-back, the new threads that were created OR existing threads that gained a reply." [group-id days-back] (let [days-back-tick (->> (tick/new-period days-back :days) (tick/- (now-))) created-after-days-back? (comp (partial tick/< days-back-tick) tick/instant :created)] (->> [[:threads {:group-id (str group-id) :deleted nil :_limit 100 ;; hopefully enough to get all the old ones w/ recent replies :_order_by {:created :desc}} [:title :created [:messages {:deleted nil} [:created [:user [:uname]] [:org [:oname]]]]]]] ha/sync-query :threads (map #(identity {:title (-> % :title) :user-name (some-> % :messages first :user :uname) :org-name (some-> % :messages first :org :oname) :num-recent-replies (->> % :messages (drop 1) ;; the root message of the thread (filter created-after-days-back?) count) :created (-> % :created)})) (filter (some-fn (comp pos? :num-recent-replies) ;; has recent replies? ;; or thread itself was created recently? created-after-days-back?)) (map #(assoc % :num-recent-replies-string (let [num-recent-replies (:num-recent-replies %)] (cond (= 1 num-recent-replies) (str "(1 new reply)") (pos? num-recent-replies) (str "(" num-recent-replies " new replies)") :else "")))) (take 10)))) (defn get-weekly-auto-email-data--communities [group-id] (let [{:keys [gname]} (->> [[:groups {:id group-id} [:gname]]] ha/sync-query vals ffirst)] {:group-name gname :num-new-discounts (get-weekly-auto-email-data--communities-num-new-discounts group-id 7) :num-new-orgs (get-weekly-auto-email-data--communities-num-new-orgs group-id 7) :num-new-stacks (get-weekly-auto-email-data--communities-num-new-stacks group-id 7) :recent-threads (get-weekly-auto-email-data--communities-recent-threads group-id 7)})) (defn get-weekly-auto-email-data [user-id org-id oname uname] (let [group-ids (some->> [[:group-org-memberships {:org-id org-id} [:group-id]]] ha/sync-query vals first (map :group-id)) recent-preposals (get-weekly-auto-email-data--recent-preposals org-id) product-annual-renewals-soon (get-weekly-auto-email-data--product-renewals-soon org-id "annual" 30 15) product-monthly-renewals-soon (get-weekly-auto-email-data--product-renewals-soon org-id "monthly" 7 15) active-rounds (get-weekly-auto-email-data--active-rounds org-id)] {:base-url "https://app.vetd.com/" :unsubscribe-link (create-unsubscribe-link {:user-id user-id :org-id org-id :etype (name :weekly-buyer-email)}) ;; get just the First Name :user-name (str ;; nil -> "" (some->> (s/split (s/lower-case uname) #" ") (remove #{"mr." "mrs." "ms." "dr." "mr" "mrs" "ms" "dr"}) first s/capitalize)) :org-name oname :recent-preposals recent-preposals :product-annual-renewals-soon product-annual-renewals-soon :product-annual-renewals-soon-count (count product-annual-renewals-soon) :product-monthly-renewals-soon product-monthly-renewals-soon :product-monthly-renewals-soon-count (count product-monthly-renewals-soon) :active-rounds active-rounds :active-rounds-count (count active-rounds) :communities (map get-weekly-auto-email-data--communities group-ids)})) (defn do-scheduled-emailer [threshold-dt] (try (log/info (str "CALL do-scheduled-emailer " threshold-dt)) (let [threshold-ts (tick->ts threshold-dt)] (while (try (when-let [{:keys [email oname uname user-id org-id max-created]} (select-next-email&recipient threshold-ts)] (let [data (get-weekly-auto-email-data user-id org-id oname uname)] (send-template-email email data {:template-id "d-76e51dc96f2d4d7e8438bd6b407504f9"}) (insert-email-sent-log-entry {:etype :weekly-buyer-email :user-id user-id :org-id org-id :data data})) (Thread/sleep 1000) true) (catch Throwable e (com/log-error e) false)))) (catch Throwable e (com/log-error e) (Thread/sleep (* 1000 60 60))))) ;; this is not tested with multiple concurrent instances, but should be fine (defn start-scheduled-emailer-thread [] (when (and (not env/building?) ;; not while building env/prod? ;; only in prod (nil? @scheduled-email-thread&)) ;; we only need one thread (reset! scheduled-email-thread& (future (log/info "Starting scheduled-emailer") (reset! next-scheduled-event& ;; find the next send time based on email sent log (tick/instant (calc-next-due-ts (or (some-> (last-email-sent "weekly-buyer-email") tick/date-time) ;; if never sent, the -1 day allows it to possibly send today (if Monday) (tick/- (now-) (tick/new-period 1 :days)))))) (while (not @com/shutdown-signal) (let [event-time @next-scheduled-event&] (if (tick/> (now-) event-time) (do (reset! next-scheduled-event& (calc-next-due-ts (now-))) (#'do-scheduled-emailer (tick/- event-time (tick/new-period 6 :days)))) (Thread/sleep (* 1000 10))))) (log/info "Stopped scheduled-emailer"))))) (start-scheduled-emailer-thread) #_ (future-cancel @scheduled-email-thread&) #_ (reset! override-now& (tick/+ (tick/now) (tick/new-period 6 :days)))
true
(ns com.vetd.app.email-client (:require [com.vetd.app.common :as com] [com.vetd.app.util :as ut] [com.vetd.app.env :as env] [com.vetd.app.db :as db] [com.vetd.app.hasura :as ha] [com.vetd.app.links :as l] [taoensso.timbre :as log] [clj-http.client :as client] [clj-time.periodic :as t-per] [tick.core :as tick] [tick.alpha.api :as tcka] [clojure.string :as s])) (def sendgrid-api-key "PI:KEY:<KEY>END_PI") (def sendgrid-api-url "https://api.sendgrid.com/v3/") (def sendgrid-default-from "PI:EMAIL:<EMAIL>END_PI") (def sendgrid-default-from-name "Vetd Team") (def sendgrid-default-template-id "d-0942e461a64943018bd0d1d6cf711e21") ; "Simple" template (def common-opts {:as :json :content-type :json :coerce :always :throw-exceptions false :headers {"Authorization" (str "Bearer " sendgrid-api-key)}}) ;; NOTE when :success is true, :resp is nil. (defn- request [endpoint & [params headers]] (try (let [resp (-> (client/post (str sendgrid-api-url endpoint) (merge-with merge common-opts {:form-params params} {:headers headers})) :body)] {:success (not (seq (:errors resp))) :resp resp}) (catch Exception e (com/log-error e) {:success false :resp {:error {:message (.getMessage e)}}}))) (defn send-template-email [to data & [{:keys [from from-name template-id]}]] (request "mail/send" {:personalizations [{:to [{:email to}] :dynamic_template_data data}] :from {:email (or from sendgrid-default-from) :name (or from-name sendgrid-default-from-name)} :template_id (or template-id sendgrid-default-template-id)})) ;;;; Example Usage #_(send-template-email "PI:EMAIL:<EMAIL>END_PI" {:subject "Vetd Buying Platform" :preheader "You're going to want to see what's in this email" :main-content "Here is some example content."}) (defn- insert-unsubscribe [{:keys [user-id org-id etype]}] (let [[id idstr] (ut/mk-id&str)] (db/insert! :unsubscribes {:id id :idstr idstr :created (ut/now-ts) :updated (ut/now-ts) :deleted nil :user_id user-id :org_id org-id :etype etype}) id)) (defn unsubscribe "Unsubscribe a user from an email type." [{:keys [user-id org-id etype] :as args}] (insert-unsubscribe args)) (defn create-unsubscribe-link "Create a new unsubscribe link. Return the link url." [{:keys [user-id org-id etype] :as input}] (str l/base-url (l/create {:cmd :email-unsubscribe :input-data (select-keys input [:user-id :org-id :etype]) ;; a year from now :expires-action (+ (ut/now) (* 1000 60 60 24 365))}))) (defmethod l/action :email-unsubscribe [{:keys [input-data] :as link} _] (do (l/update-expires link "read" (+ (ut/now) (* 1000 60 5))) ; allow read for next 5 mins) {:unsubscribed? (boolean (unsubscribe input-data))})) ;;;; Auto Email (defonce scheduled-email-thread& (atom nil)) (defonce next-scheduled-event& (atom nil)) (def override-now& (atom nil)) (defn now- [] (or @override-now& (tick/now))) (defn monday? [x] (= (tick/day-of-week x) #time/day-of-week "MONDAY")) (defn nine-am-pdt? [x] (= (tick/hour x) 16)) (defn calc-next-due-ts [dt] (->> (tick/range (-> (tick/truncate dt :hours) (tick/+ (tick/new-duration 1 :hours))) (tick/+ dt (tick/new-period 8 :days)) (tick/new-duration 1 :hours)) (filter #(and (monday? %) (nine-am-pdt? %))) first)) (defn tick->ts [t] (tick/millis (tick/between (tick/epoch) t))) (defn ts->tick [msecs] (tcka/+ (tick/epoch) (tick/new-duration msecs :millis))) (defn insert-email-sent-log-entry [{:keys [etype org-id user-id data]}] (let [[id idstr] (ut/mk-id&str)] (-> (db/insert! :email_sent_log {:id id :idstr idstr :created (ut/now-ts) :updated (ut/now-ts) :etype (name etype) :org_id org-id :user_id user-id :data data}) first))) ;; TODO This will get trickier when we have multiple app server instances running again (defn select-next-email&recipient [max-ts] (-> {:select [[:%max.esl.created :max-created] [:m.id :membership-id] [:m.user_id :user-id] [:u.email :email] [:u.uname :uname] [:m.org_id :org-id] [:o.oname :oname]] :from [[:orgs :o]] :join [[:memberships :m] [:and [:= :m.deleted nil] [:= :m.org_id :o.id]] [:users :u] [:and [:= :u.id :user_id] [:= :u.deleted nil] ;; exclude users that were created less than 3 days ago [:< :u.created (->> (tick/new-period 3 :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)] [:like :u.email "%@%"] ;; primitive email address validation [:or ;; exclude test accounts, but let through real "Vetd" org [:= :m.org_id 2208512249632] [:not [:or [:like :u.email PI:EMAIL:<EMAIL>END_PI"] [:like :u.email "temp@%"]]]]]] :left-join [[:email_sent_log :esl] [:= :esl.user_id :m.user_id] [:unsubscribes :uns] [:and [:= :uns.user_id :u.id] [:= :uns.org_id :o.id] [:= :uns.etype "weekly-buyer-email"] [:= :uns.deleted nil]]] :where [:and [:= :o.deleted nil] [:= :o.buyer_qm true] [:= :uns.id nil]] :group-by [:m.id :m.user_id :m.org_id :o.oname :u.email :u.uname] :having [:or [:= :%max.esl.created nil] [:< :%max.esl.created (java.sql.Timestamp. max-ts)]] :limit 1} db/hs-query first)) (defn last-email-sent [etype] (-> {:select [[:%max.esl.created :max-created]] :from [[:email_sent_log :esl]] :where [:and [:= :esl.deleted nil] [:= :esl.etype etype]] :limit 1} db/hs-query first :max-created)) ;; days-forward should be less than 30/31 if using price-period of monthly (defn get-weekly-auto-email-data--product-renewals-soon [org-id price-period days-forward limit] (->> [[:stack-items {:_where {:_and (concat [{:status {:_eq "current"}} {:buyer_id {:_eq (str org-id)}} ;; {:renewal-reminder {:_eq true}} ;; include regardless of reminder checked {:price-period {:_eq price-period}} {:deleted {:_is_null true}}] (if (= price-period "monthly") (let [start-day (tick/day-of-month (now-)) end-day (->> (tick/new-period days-forward :days) (tick/+ (now-)) tick/day-of-month)] (if (> start-day end-day) ;; it wrapped around to next month [{:_or [{:renewal-day-of-month {:_gte start-day}} {:renewal-day-of-month {:_lte end-day}}]}] [{:renewal-day-of-month {:_gte start-day}} {:renewal-day-of-month {:_lte end-day}}])) [{:renewal-date {:_gte (str (tick/date (ut/now-ts)))}} {:renewal-date {:_lte (->> (tick/new-period days-forward :days) (tick/+ (now-)) tick/date str)}}]))} :_order_by {:renewal-date :asc} :_limit limit} [:price-amount :renewal-date :renewal-day-of-month [:product [:pname]]]]] ha/sync-query :stack-items (map (fn [{:keys [renewal-day-of-month] :as si}] (let [si-with-date (if (= price-period "monthly") (assoc si :renewal-date (str "on the " (ut/append-ordinal-suffix renewal-day-of-month))) (update-in si [:renewal-date] (comp str tick/date)))] (update-in si-with-date [:price-amount] #(some-> % ut/->dollars-str))))))) ;; active rounds are rounds that are "in-progress" (defn get-weekly-auto-email-data--active-rounds [org-id] (->> [[:rounds {:deleted nil :status "in-progress" :buyer-id org-id :_order_by {:created :desc}} [:id :idstr :title [:products [:id]]]]] ha/sync-query :rounds (map (fn [{:keys [products] :as round}] (assoc round :num-products (count products)))))) (defn get-weekly-auto-email-data--recent-preposals [org-id] (->> [[:form-docs {:ftype "preposal" :from-org-id org-id :_where {:_or [;; when Vetd requested the estimate on behalf of user (forwarded email) {:_and [{:created {:_gt (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. str)}} {:title {:_like "ADMIN %"}}]} ;; when the vendor created the estimate (preposal) {:doc-created {:_gt (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. str)}}]} :_order_by {:created :desc}} [:id :created :updated :doc-id :doc-created [:product [:pname]] [:from-org [:oname]] [:from-user [:id :uname]] [:to-org [:id :oname]]]]] ha/sync-query :form-docs (#(assoc {} :preposals (filter :doc-id %) :preposals-count (count (filter :doc-id %)) ;; Since we create preposals on behalf of the user ;; number of preposal requests with title beginning with "ADMIN " ;; is a proxy for the number of emails they forwarded to us. :num-emails-forwarded (count (filter (fn [form-doc] (> (->> form-doc :created .getTime) (->> (tick/new-period 7 :days) (tick/- (now-)) tick->ts java.sql.Timestamp. .getTime))) %)))))) (defn get-weekly-auto-email-data--communities-num-new-discounts [group-id days-back] (->> {:select [[:%count.gd.id :count]] :from [[:group_discounts :gd]] :where [:and [:= :gd.deleted nil] [:= :gd.group_id group-id] [:> :gd.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]]} db/hs-query first :count)) (defn get-weekly-auto-email-data--communities-num-new-orgs [group-id days-back] (->> {:select [[:%count.gom.org_id :count]] :from [[:group_org_memberships :gom]] :where [:and [:= :gom.deleted nil] [:= :gom.group_id group-id] [:> :gom.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]]} db/hs-query first :count)) (defn get-weekly-auto-email-data--communities-num-new-stacks [group-id days-back] (-> {:select [[:%count.si.buyer_id :si-buyer-count]] :from [[:group_org_memberships :gom]] :join [[:stack_items :si] [:and [:= :si.buyer_id :gom.org_id] [:= :si.deleted nil]]] :where [:and [:= :gom.deleted nil] [:= :gom.group_id group-id]] :group-by [:si.buyer_id] :having [:> :%min.si.created (->> (tick/new-period days-back :days) (tick/- (now-)) tick->ts java.sql.Timestamp.)]} db/hs-query count)) (defn get-weekly-auto-email-data--communities-recent-threads "For group-id, in the past days-back, the new threads that were created OR existing threads that gained a reply." [group-id days-back] (let [days-back-tick (->> (tick/new-period days-back :days) (tick/- (now-))) created-after-days-back? (comp (partial tick/< days-back-tick) tick/instant :created)] (->> [[:threads {:group-id (str group-id) :deleted nil :_limit 100 ;; hopefully enough to get all the old ones w/ recent replies :_order_by {:created :desc}} [:title :created [:messages {:deleted nil} [:created [:user [:uname]] [:org [:oname]]]]]]] ha/sync-query :threads (map #(identity {:title (-> % :title) :user-name (some-> % :messages first :user :uname) :org-name (some-> % :messages first :org :oname) :num-recent-replies (->> % :messages (drop 1) ;; the root message of the thread (filter created-after-days-back?) count) :created (-> % :created)})) (filter (some-fn (comp pos? :num-recent-replies) ;; has recent replies? ;; or thread itself was created recently? created-after-days-back?)) (map #(assoc % :num-recent-replies-string (let [num-recent-replies (:num-recent-replies %)] (cond (= 1 num-recent-replies) (str "(1 new reply)") (pos? num-recent-replies) (str "(" num-recent-replies " new replies)") :else "")))) (take 10)))) (defn get-weekly-auto-email-data--communities [group-id] (let [{:keys [gname]} (->> [[:groups {:id group-id} [:gname]]] ha/sync-query vals ffirst)] {:group-name gname :num-new-discounts (get-weekly-auto-email-data--communities-num-new-discounts group-id 7) :num-new-orgs (get-weekly-auto-email-data--communities-num-new-orgs group-id 7) :num-new-stacks (get-weekly-auto-email-data--communities-num-new-stacks group-id 7) :recent-threads (get-weekly-auto-email-data--communities-recent-threads group-id 7)})) (defn get-weekly-auto-email-data [user-id org-id oname uname] (let [group-ids (some->> [[:group-org-memberships {:org-id org-id} [:group-id]]] ha/sync-query vals first (map :group-id)) recent-preposals (get-weekly-auto-email-data--recent-preposals org-id) product-annual-renewals-soon (get-weekly-auto-email-data--product-renewals-soon org-id "annual" 30 15) product-monthly-renewals-soon (get-weekly-auto-email-data--product-renewals-soon org-id "monthly" 7 15) active-rounds (get-weekly-auto-email-data--active-rounds org-id)] {:base-url "https://app.vetd.com/" :unsubscribe-link (create-unsubscribe-link {:user-id user-id :org-id org-id :etype (name :weekly-buyer-email)}) ;; get just the First Name :user-name (str ;; nil -> "" (some->> (s/split (s/lower-case uname) #" ") (remove #{"mr." "mrs." "ms." "dr." "mr" "mrs" "ms" "dr"}) first s/capitalize)) :org-name oname :recent-preposals recent-preposals :product-annual-renewals-soon product-annual-renewals-soon :product-annual-renewals-soon-count (count product-annual-renewals-soon) :product-monthly-renewals-soon product-monthly-renewals-soon :product-monthly-renewals-soon-count (count product-monthly-renewals-soon) :active-rounds active-rounds :active-rounds-count (count active-rounds) :communities (map get-weekly-auto-email-data--communities group-ids)})) (defn do-scheduled-emailer [threshold-dt] (try (log/info (str "CALL do-scheduled-emailer " threshold-dt)) (let [threshold-ts (tick->ts threshold-dt)] (while (try (when-let [{:keys [email oname uname user-id org-id max-created]} (select-next-email&recipient threshold-ts)] (let [data (get-weekly-auto-email-data user-id org-id oname uname)] (send-template-email email data {:template-id "d-76e51dc96f2d4d7e8438bd6b407504f9"}) (insert-email-sent-log-entry {:etype :weekly-buyer-email :user-id user-id :org-id org-id :data data})) (Thread/sleep 1000) true) (catch Throwable e (com/log-error e) false)))) (catch Throwable e (com/log-error e) (Thread/sleep (* 1000 60 60))))) ;; this is not tested with multiple concurrent instances, but should be fine (defn start-scheduled-emailer-thread [] (when (and (not env/building?) ;; not while building env/prod? ;; only in prod (nil? @scheduled-email-thread&)) ;; we only need one thread (reset! scheduled-email-thread& (future (log/info "Starting scheduled-emailer") (reset! next-scheduled-event& ;; find the next send time based on email sent log (tick/instant (calc-next-due-ts (or (some-> (last-email-sent "weekly-buyer-email") tick/date-time) ;; if never sent, the -1 day allows it to possibly send today (if Monday) (tick/- (now-) (tick/new-period 1 :days)))))) (while (not @com/shutdown-signal) (let [event-time @next-scheduled-event&] (if (tick/> (now-) event-time) (do (reset! next-scheduled-event& (calc-next-due-ts (now-))) (#'do-scheduled-emailer (tick/- event-time (tick/new-period 6 :days)))) (Thread/sleep (* 1000 10))))) (log/info "Stopped scheduled-emailer"))))) (start-scheduled-emailer-thread) #_ (future-cancel @scheduled-email-thread&) #_ (reset! override-now& (tick/+ (tick/now) (tick/new-period 6 :days)))
[ { "context": ";; Copyright (c) 2021 Thomas J. Otterson\n;; \n;; This software is released under the MIT Li", "end": 40, "score": 0.9996756315231323, "start": 22, "tag": "NAME", "value": "Thomas J. Otterson" } ]
src/barandis/euler/p9.clj
Barandis/euler-clojure
0
;; Copyright (c) 2021 Thomas J. Otterson ;; ;; This software is released under the MIT License. ;; https://opensource.org/licenses/MIT ;; Solves Project Euler problem 9: ;; ;; A Pythagorean triplet is a set of three natural numbers, a < b < c, for which ;; ;; a^2 + b^2 = c^2 ;; ;; For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. ;; ;; There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find ;; the product abc. ;; The method here is Euclid's formula, which still works great after all these ;; years. If m and n are coprime (have a GCD of 1) and m > n > 0, then ;; ;; a = m^2 - n^2 ;; b = 2mn ;; c = m^2 + n^2 ;; ;; are a Pythagorean triple. ;; ;; This formula produces only primitive triples like 3, 4, 5. Multiples of the ;; primitive triples (like 6, 8, 10) are also triples and must also be ;; generated. To do this, a constant k is multipled by each component to come up ;; with all of the other triples. k, m, and n are chosen so that triples above ;; the target value aren't generated, so no time is wasted checking them. ;; ;; This solution can be run using `clojure -X:p9`. It will default to the 1000 ;; target described in the problem. To run with another target, use `clojure ;; -X:p9 :target 150` or similar. (ns barandis.euler.p9) (defn- triples "Generates a sequence of all Pythagorean triples whose components add up to the target value. (This can also be regarded as the sides of Pythagorean triangles with the target perimeter.) An empty sequence will be returned if no Pythagorean triple's components add up to the target value." [target] (letfn [(gcd [x y] (if (zero? y) x (recur y (mod x y))))] (for [m (range 2 (Math/sqrt (/ target 2))) n (range (inc (mod m 2)) m 2) :when (= 1 (gcd m n)) :let [p (* 2 m (+ m n))] k (range 1 (inc (quot target p))) :let [m2 (* m m) n2 (* n n) a (* k (- m2 n2)) b (* 2 k m n) c (* k (+ m2 n2))] :when (= target (+ a b c))] [a b c]))) (defn solve "Displays the product of the components of the first Pythagorean triple whose components add up to (:target data). :target defaults to 1000, which makes the displayed value the solution to Project Euler problem 9." ([] (solve {})) ([data] (->> (get data :target 1000) triples first (reduce *) println time)))
119626
;; Copyright (c) 2021 <NAME> ;; ;; This software is released under the MIT License. ;; https://opensource.org/licenses/MIT ;; Solves Project Euler problem 9: ;; ;; A Pythagorean triplet is a set of three natural numbers, a < b < c, for which ;; ;; a^2 + b^2 = c^2 ;; ;; For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. ;; ;; There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find ;; the product abc. ;; The method here is Euclid's formula, which still works great after all these ;; years. If m and n are coprime (have a GCD of 1) and m > n > 0, then ;; ;; a = m^2 - n^2 ;; b = 2mn ;; c = m^2 + n^2 ;; ;; are a Pythagorean triple. ;; ;; This formula produces only primitive triples like 3, 4, 5. Multiples of the ;; primitive triples (like 6, 8, 10) are also triples and must also be ;; generated. To do this, a constant k is multipled by each component to come up ;; with all of the other triples. k, m, and n are chosen so that triples above ;; the target value aren't generated, so no time is wasted checking them. ;; ;; This solution can be run using `clojure -X:p9`. It will default to the 1000 ;; target described in the problem. To run with another target, use `clojure ;; -X:p9 :target 150` or similar. (ns barandis.euler.p9) (defn- triples "Generates a sequence of all Pythagorean triples whose components add up to the target value. (This can also be regarded as the sides of Pythagorean triangles with the target perimeter.) An empty sequence will be returned if no Pythagorean triple's components add up to the target value." [target] (letfn [(gcd [x y] (if (zero? y) x (recur y (mod x y))))] (for [m (range 2 (Math/sqrt (/ target 2))) n (range (inc (mod m 2)) m 2) :when (= 1 (gcd m n)) :let [p (* 2 m (+ m n))] k (range 1 (inc (quot target p))) :let [m2 (* m m) n2 (* n n) a (* k (- m2 n2)) b (* 2 k m n) c (* k (+ m2 n2))] :when (= target (+ a b c))] [a b c]))) (defn solve "Displays the product of the components of the first Pythagorean triple whose components add up to (:target data). :target defaults to 1000, which makes the displayed value the solution to Project Euler problem 9." ([] (solve {})) ([data] (->> (get data :target 1000) triples first (reduce *) println time)))
true
;; Copyright (c) 2021 PI:NAME:<NAME>END_PI ;; ;; This software is released under the MIT License. ;; https://opensource.org/licenses/MIT ;; Solves Project Euler problem 9: ;; ;; A Pythagorean triplet is a set of three natural numbers, a < b < c, for which ;; ;; a^2 + b^2 = c^2 ;; ;; For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. ;; ;; There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find ;; the product abc. ;; The method here is Euclid's formula, which still works great after all these ;; years. If m and n are coprime (have a GCD of 1) and m > n > 0, then ;; ;; a = m^2 - n^2 ;; b = 2mn ;; c = m^2 + n^2 ;; ;; are a Pythagorean triple. ;; ;; This formula produces only primitive triples like 3, 4, 5. Multiples of the ;; primitive triples (like 6, 8, 10) are also triples and must also be ;; generated. To do this, a constant k is multipled by each component to come up ;; with all of the other triples. k, m, and n are chosen so that triples above ;; the target value aren't generated, so no time is wasted checking them. ;; ;; This solution can be run using `clojure -X:p9`. It will default to the 1000 ;; target described in the problem. To run with another target, use `clojure ;; -X:p9 :target 150` or similar. (ns barandis.euler.p9) (defn- triples "Generates a sequence of all Pythagorean triples whose components add up to the target value. (This can also be regarded as the sides of Pythagorean triangles with the target perimeter.) An empty sequence will be returned if no Pythagorean triple's components add up to the target value." [target] (letfn [(gcd [x y] (if (zero? y) x (recur y (mod x y))))] (for [m (range 2 (Math/sqrt (/ target 2))) n (range (inc (mod m 2)) m 2) :when (= 1 (gcd m n)) :let [p (* 2 m (+ m n))] k (range 1 (inc (quot target p))) :let [m2 (* m m) n2 (* n n) a (* k (- m2 n2)) b (* 2 k m n) c (* k (+ m2 n2))] :when (= target (+ a b c))] [a b c]))) (defn solve "Displays the product of the components of the first Pythagorean triple whose components add up to (:target data). :target defaults to 1000, which makes the displayed value the solution to Project Euler problem 9." ([] (solve {})) ([data] (->> (get data :target 1000) triples first (reduce *) println time)))
[ { "context": "or state [:alert-success])\n diff-key-str {:referral_gallons \"Referral Gallons\"}\n diff-msg", "end": 6117, "score": 0.8078886270523071, "start": 6114, "tag": "KEY", "value": "ref" }, { "context": " [:alert-success])\n diff-key-str {:referral_gallons \"Referral Gallons\"}\n diff-msg-gen (", "end": 6122, "score": 0.5918751955032349, "start": 6122, "tag": "KEY", "value": "" }, { "context": "uccess])\n diff-key-str {:referral_gallons \"Referral Gallons\"}\n diff-msg-gen (fn [edit current] (diff-m", "end": 6148, "score": 0.9799823760986328, "start": 6132, "tag": "KEY", "value": "Referral Gallons" } ]
src/dashboard_cljs/users.cljs
Purple-Services/dashboard-cljs
6
(ns dashboard-cljs.users (:require [reagent.core :as r] [cljs.core.async :refer [put! sub chan]] [dashboard-cljs.cookies :as cookies] [dashboard-cljs.datastore :as datastore] [dashboard-cljs.forms :refer [entity-save retrieve-entity edit-on-success edit-on-error]] [dashboard-cljs.orders :refer [user-cross-link-on-click]] [dashboard-cljs.utils :refer [base-url unix-epoch->fmt unix-epoch->hrf markets json-string->clj pager-helper! integer->comma-sep-string parse-to-number? diff-message accessible-routes get-event-time now update-values select-toggle-key! subscription-id->name]] [dashboard-cljs.state :refer [users-state]] [dashboard-cljs.xhr :refer [retrieve-url xhrio-wrapper]] [dashboard-cljs.components :refer [DynamicTable RefreshButton KeyVal StarRating TablePager ConfirmationAlert FormGroup TextInput AlertSuccess SubmitDismissConfirmGroup TextAreaInput ViewHideButton TelephoneNumber Mailto GoogleMapLink Tab TabContent ProcessingIcon UserCrossLink ErrorComp]] [clojure.set :refer [subset?]] [clojure.string :as s])) (def push-selected-users (r/atom (set nil))) (def state users-state) (def user-search-results (r/cursor state [:search-results :users])) (datastore/sync-state! user-search-results (sub datastore/read-data-chan "user-search-results" (chan))) (defn update-user-count [] (retrieve-url (str base-url "users-count") "GET" {} (partial xhrio-wrapper (fn [response] (let [res (js->clj response :keywordize-keys true)] (reset! (r/cursor state [:users-count]) (integer->comma-sep-string (:total (first res))))))))) (defn update-members-count [saving?] (retrieve-url (str base-url "members-count") "GET" {} (partial xhrio-wrapper (fn [response] (let [res (js->clj response :keywordize-keys true)] (reset! (r/cursor state [:members-count]) (integer->comma-sep-string (:total (first res)))) (reset! saving? false)))))) (defonce users-count-result (update-user-count)) (defonce members-count-result (update-members-count (r/cursor state [:update-members-count-saving?]))) (defn displayed-user [user] (let [{:keys [referral_gallons]} user] (assoc user :referral_gallons (str referral_gallons) :referral-comment ""))) (defn user->server-req [user] (let [{:keys [referral_gallons]} user processed-ref-gallons (-> referral_gallons (clojure.string/replace #"," "") (js/Number))] (assoc user :referral_gallons (if (parse-to-number? processed-ref-gallons) processed-ref-gallons referral_gallons)))) (defn reset-edit-user! [edit-user current-user] (reset! edit-user (displayed-user @current-user))) (defn users-count-panel [state] (let [saving? (r/cursor state [:update-members-count-saving?]) refresh-fn (fn [saving?] (reset! saving? true) (update-user-count) (update-members-count saving?))] (fn [] [:div {:class "row"} [:div {:class "col-lg-12 col-xs -12"} [:div [:h3 {:style {:margin-top "0px"}} (str "Users (" @(r/cursor state [:users-count]) ") ") [:span {:style {:color "#5cb85c"}} (str "Members (" @(r/cursor state [:members-count]) ") ") [RefreshButton {:refresh-fn (fn [] (refresh-fn saving?)) :refreshing? saving?}]]]]]]))) (defn user-history-header "props { :sort-keyword ; r/atom, keyword :sort-reversed? ; r/atom, boolean }" [props] (fn [props] [:thead [:tr [:th {:style {:font-size "16px" :font-weight "normal"}} "Date"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Admin"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Adjustment"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Comment"]]])) (defn user-history-row [] (fn [user-log] [:tr ;; Date [:td (unix-epoch->fmt (:timestamp user-log) "M/D/YYYY h:mm A")] ;; Admin [:td (:admin_name user-log)] ;; Gallon adjustment [:td (str (:previous_value user-log) " -> " (:new_value user-log))] ;; comment [:td (:comment user-log)]])) (defn user-form "Form for editing a user" [user state] (let [edit-user (r/cursor state [:edit-user]) current-user (r/cursor state [:current-user]) retrieving? (r/cursor edit-user [:retrieving?]) editing? (r/cursor edit-user [:editing?]) confirming? (r/cursor state [:confirming-edit?]) errors (r/cursor edit-user [:errors]) referral-gallons (r/cursor edit-user [:referral_gallons]) comment (r/cursor edit-user [:referral_comment]) alert-success (r/cursor state [:alert-success]) diff-key-str {:referral_gallons "Referral Gallons"} diff-msg-gen (fn [edit current] (diff-message edit (displayed-user current) diff-key-str))] (fn [user] (let [default-card-info (if (empty? (:stripe_cards @edit-user)) nil (->> (:stripe_cards @edit-user) json-string->clj (filter #(= (:stripe_default_card @edit-user) (:id %))) first)) submit-on-click (fn [e] (.preventDefault e) (if @editing? (if (every? nil? (diff-msg-gen @edit-user @current-user)) ;; there isn't a diff message, no changes ;; do nothing (reset! editing? (not @editing?)) ;; there is a diff message, confirm changes (reset! confirming? true)) (do ;; get rid of alert-success (reset! alert-success "") (reset! editing? (not @editing?))))) dismiss-fn (fn [e] ;; reset any errors (reset! errors nil) ;; no longer editing (reset! editing? false) ;; reset current user (reset-edit-user! edit-user current-user) ;; reset confirming (reset! confirming? false))] [:form {:class "form-horizontal"} ;; email [KeyVal "ID" (:id @user)] [KeyVal "Email" [Mailto (:email @user)]] ;; phone number [KeyVal "Phone" [TelephoneNumber (:phone_number @user)]] ;; date started [KeyVal "Registered" (unix-epoch->fmt (:timestamp_created @user) "M/D/YYYY")] ;; last active (last ping) (when-not (nil? (:last_active @user)) [KeyVal "Last Active" (unix-epoch->fmt (:last_active @user) "M/D/YYYY")]) ;; default card (when (not (nil? default-card-info)) [KeyVal "Default Card" (str (:brand default-card-info) " " (:last4 default-card-info) " " (when (not (empty? (:exp_month default-card-info))) (:exp_month default-card-info) "/" (:exp_year default-card-info)))]) ;; referral code [KeyVal "Referral Code" (:referral_code @user)] ;; is this user a courier? [KeyVal "Courier" (if (:is_courier @user) "Yes" "No")] ;; Referral Gallons (if @editing? [:div [FormGroup {:label "Credit Gallons" :label-for "referral gallons" :errors (:referral_gallons @errors)} [TextInput {:value @referral-gallons :default-value @referral-gallons :on-change #(reset! referral-gallons (-> % (aget "target") (aget "value")))}]] [FormGroup {:label "Reason for Changing Credit Gallons" :label-for "referral gallons comment"} [TextAreaInput {:value @comment :rows 2 :cols 50 :on-change #(reset! comment (-> % (aget "target") (aget "value")))}]] [:br]] [KeyVal "Credit Gallons" (:referral_gallons @user)]) (when (subset? #{{:uri "/user" :method "PUT"}} @accessible-routes) [SubmitDismissConfirmGroup {:confirming? confirming? :editing? editing? :retrieving? retrieving? :submit-fn submit-on-click :dismiss-fn dismiss-fn}]) (when (subset? #{{:uri "/user" :method "PUT"}} @accessible-routes) (if (and @confirming? (not-every? nil? (diff-msg-gen @edit-user @current-user))) [ConfirmationAlert {:confirmation-message (fn [] [:div (str "Do you want to make the following changes to " (:name @current-user) "?") (map (fn [el] ^{:key el} [:h4 el]) (diff-msg-gen @edit-user @current-user))]) :cancel-on-click dismiss-fn :confirm-on-click (fn [_] (entity-save (user->server-req @edit-user) "user" "PUT" retrieving? (edit-on-success "user" edit-user current-user alert-success :aux-fn #(reset! confirming? false) :channel-topic "user-search-results" ) (edit-on-error edit-user :aux-fn #(reset! confirming? false)))) :retrieving? retrieving?}] (reset! confirming? false))) ;; success alert (when-not (empty? @alert-success) [AlertSuccess {:message @alert-success :dismiss #(reset! alert-success "")}])])))) (defn get-user-orders "Retrieve orders for user-id and insert them into the datastore" [user-id retrieving?] (reset! retrieving? true) (retrieve-url (str base-url "users/orders/" user-id) "GET" {} (partial xhrio-wrapper (fn [response] (let [orders (js->clj response :keywordize-keys true)] (reset! retrieving? false) (put! datastore/modify-data-chan {:topic "orders" :data orders})))))) (defn current-user-change! "Whenever the current user changes, do some work" [current-user] (when-not (nil? @current-user) (let [retrieving? (r/cursor state [:user-orders-retrieving?])] (get-user-orders (:id @current-user) retrieving?)))) (defn user-push-notification "A component for sending push notifications to users" [user] (let [default-state {:approved? false :confirming? false :retrieving? false :message (str) :alert-success (str) :alert-error (str)} state (r/atom default-state) approved? (r/cursor state [:approve?]) confirming? (r/cursor state [:confirming?]) retrieving? (r/cursor state [:retrieving?]) message (r/cursor state [:message]) alert-success (r/cursor state [:alert-success]) alert-error (r/cursor state [:alert-error]) confirm-on-click (fn [user e] (let [{:keys [id name]} user] (reset! retrieving? true) (retrieve-url (str base-url "send-push-to-user") "POST" (js/JSON.stringify (clj->js {:message @message :user-id id})) (partial xhrio-wrapper (fn [response] (reset! retrieving? false) (let [success? (:success (js->clj response :keywordize-keys true))] (when success? ;; confirm message was sent (reset! alert-success (str "Pushed the message '" @message "' to " name "!"))) (when (not success?) (reset! alert-error (str "Something went wrong." " Push notifications may or may" " not have been sent. Wait until" " sure before trying again.")))) (reset! confirming? false) (reset! message "")))))) confirmation-message (fn [username] (fn [] [:div "Are you sure you want to push the message '" [:span [:strong @message]] "' to " username "?" ]))] (r/create-class {:component-will-receive-props (fn [this] (reset! state default-state)) :reagent-render (fn [user] (let [] [:div {:class "panel panel-default"} [:div {:class "panel-body"} [:div [:h4 (str "Send Push Notification to " (:name user))]] (if @confirming? ;; confirmation [ConfirmationAlert {:cancel-on-click (fn [e] (reset! confirming? false) (reset! message "")) :confirm-on-click (partial confirm-on-click user) :confirmation-message (confirmation-message (:name user)) :retrieving? retrieving?}] ;; Message form [:form [:div {:class "form-group"} [:input {:type "text" :defaultValue "" :class "form-control" :placeholder "Message" :on-change (fn [e] (reset! message (-> e (aget "target") (aget "value"))) (reset! alert-error "") (reset! alert-success ""))}]] [:button {:type "submit" :class "btn btn-default" :on-click (fn [e] (.preventDefault e) (when (not (empty? @message)) (reset! confirming? true))) :disabled (s/blank? @message)} "Send Notification"]]) ;; alert message (when (not (empty? @alert-success)) [:div {:class "alert alert-success alert-dismissible"} [:button {:type "button" :class "close" :aria-label "Close"} [:i {:class "fa fa-times" :on-click #(reset! alert-success "")}]] [:strong @alert-success]]) ;; alert error (when (not (empty? @alert-error)) [:div {:class "alert alert-danger"} @alert-error])]]))}))) (defn UserNote "A component for displaying a user note" [{:keys [note current-user]}] (let [edit-note (r/atom {:retrieving? false :errors nil :comment nil}) retrieving? (r/atom false) editing-note? (r/atom false) alert-success (r/atom "") edit-comment (r/cursor edit-note [:comment]) aux-fn (fn [_] (reset! editing-note? (not @editing-note?)) (reset! retrieving? false)) cookie-admin-id (cookies/get-cookie "user-id")] (r/create-class {:component-did-mount (fn [this] (reset! edit-comment (:comment note))) :reagent-render (fn [{:keys [note current-user]}] (let [{:keys [admin_email admin_id timestamp comment]} note] [:div (when-not @editing-note? [:div [:h4 comment] [:h5 (str "- " admin_email) ", " (unix-epoch->fmt timestamp "M/D/YYYY h:mm a")]]) (when @editing-note? [:div [FormGroup {:label "Notes"} [TextAreaInput {:value @edit-comment :rows 2 :on-change #(reset! edit-comment (-> % (aget "target") (aget "value")))}]]]) (when (= admin_id cookie-admin-id) [:h5 (if-not @editing-note? [:a {:on-click (fn [e] (.preventDefault e) (reset! editing-note? true))} "Edit"] [:a {:on-click (fn [e] (.preventDefault e) (reset! editing-note? false) ;; check to see if the note changed (when (not= edit-comment (:comment note)) ;; the note changed, now replace the current ;; user's note comment with the new one (let [removed-note-admin-event-log (filter #(not= (:timestamp %) timestamp) (:admin_event_log @current-user)) new-admin-event-log (conj removed-note-admin-event-log (assoc note :comment @edit-comment))] ;;(.log js/console (clj->js new-admin-event-log)) (.log js/console (clj->js removed-note-admin-event-log)) ;; upload this to the server ;; (swap! current-user #(assoc % ;; :admin_event_log ;; new-admin-event-log)) (entity-save (clj->js {:id (:id @current-user) :user_note (assoc note :comment @edit-comment)}) "user" "PUT" retrieving? (edit-on-success "user" (r/atom {}) (r/atom {}) (r/atom {}) :channel-topic "user-search-results") #(.log js/console "some unknown error occured")) )) )} "Save"]) " | " [:a "Delete"]])]))}))) (defn courier-conversion "Convert a user to a courier" [user] (let [default-state {:confirming? false :editing? false :retrieving? false :alert-error ""} state (r/atom default-state) confirming? (r/cursor state [:confirming?]) editing? (r/cursor state [:editing?]) retrieving? (r/cursor state [:retrieving?]) alert-success (r/cursor users-state [:alert-success]) alert-error (r/cursor state [:alert-error]) confirm-on-click (fn [user e] (let [{:keys [id name]} user] (reset! retrieving? true) (retrieve-url (str base-url "users/convert-to-courier") "PUT" (js/JSON.stringify (clj->js {:user {:id id}})) (partial xhrio-wrapper (fn [response] (reset! retrieving? false) (let [response (js->clj response :keywordize-keys true) success? (:success response)] (when success? ;; confirm message was sent (reset! alert-success (str "Successfully converted '" name "' to a courier! You can " "now go to the Couriers tab and " "assign zones to this courier.")) (retrieve-entity "user" id (fn [user] (put! datastore/modify-data-chan {:topic "user-search-results" :data user}) (reset! (r/cursor users-state [:current-user]) (first user)) (datastore/sync-couriers!)))) (when (not success?) (reset! alert-error (str "Error: " (:message response))))) (reset! confirming? false)))))) confirmation-message (fn [username] (fn [] [:div "Are you sure you want to convert '" [:span [:strong username]] "' to a courier?" [:br] [:span [:strong " Warning: This can not be " "undone from the dashboard!"]] [:br] " Once converted, " "this account will not be able to place " "orders and will only be able to accept " "orders for delivery." [:br] " This action " "can only be reversed manually by an admin!"] ))] (r/create-class {:component-will-receive-props (fn [this] (reset! state default-state)) :reagent-render (fn [user] [:div (cond (not @confirming?) [:button {:type "button" :class "btn btn-default" :on-click (fn [e] (.preventDefault e) (reset! confirming? true) (reset! alert-success "") (reset! alert-error ""))} "Convert to Courier"] @confirming? [ConfirmationAlert {:cancel-on-click (fn [e] (reset! confirming? false)) :confirm-on-click (partial confirm-on-click user) :confirmation-message (confirmation-message (:name user)) :retrieving? retrieving?}]) ;; alert message (when (not (empty? @alert-success)) [AlertSuccess {:message @alert-success :dismiss #(reset! alert-success "")}]) ;; alert error (when (not (empty? @alert-error)) [ErrorComp {:error-message @alert-error :dismiss-fn #(reset! alert-error "")}])])}))) (defn user-panel "Display detailed and editable fields for an user. current-user is an r/atom" [current-user state] (let [sort-keyword (r/atom :target_time_start) sort-reversed? (r/atom false) current-page (r/cursor state [:user-orders-current-page]) page-size 5 edit-user (r/cursor state [:edit-user]) view-log? (r/cursor state [:view-log?]) toggle (r/atom {}) retrieving? (r/cursor state [:user-orders-retrieving?]) orders-view-toggle? (r/cursor toggle [:orders-view]) push-view-toggle? (r/cursor toggle [:push-view]) convert-courier-view? (r/cursor toggle [:convert-courier-view])] (fn [current-user] (let [sort-fn (if @sort-reversed? (partial sort-by @sort-keyword) (comp reverse (partial sort-by @sort-keyword))) orders ;; filter out the orders to only those assigned ;; to the user (->> @datastore/orders (filter (fn [order] (= (:id @current-user) (:user_id order))))) sorted-orders (->> orders sort-fn (partition-all page-size)) paginated-orders (pager-helper! sorted-orders current-page) most-recent-order (->> orders (sort-by :target_time_start) first) current-user-update @(r/track current-user-change! current-user) ;; admin-event-log (:admin_event_log @current-user) ;; user-notes (->> admin-event-log ;; (filter #(= (:action %) "user_notes")) ;; (sort-by :timestamp)) ] ;; edit-user should correspond to current-user (when-not (:editing? @edit-user) (reset! edit-user (assoc @edit-user :last_active (:target_time_start most-recent-order)))) ;; Make sure that orders view is not selected when a user has no orders (when (and (<= (count paginated-orders) 0) @orders-view-toggle?) (select-toggle-key! toggle :info-view)) ;; Make sure that push-view is not selected when a user has push ;; notifications turned off (when (and (s/blank? (:arn_endpoint @current-user)) @push-view-toggle?) (select-toggle-key! toggle :info-view)) ;; Make sure that courier conversion is not selected when a user ;; is already a courier (when (and (:is_courier @current-user) @convert-courier-view?) (select-toggle-key! toggle :info-view)) ;; If the user is not qualified to be a courier ;; reset the toggle key (when (and (or (> (:orders_count @current-user) 0) (:is_courier @current-user)) @convert-courier-view?) (select-toggle-key! toggle :info-view)) [:div {:class "panel-body"} ;; populate the current user with additional information [:div {:class "row"} [:div {:class "col-xs-12 col-lg-12"} [:div [:h3 (:name @current-user) (when-not (= 0 (:subscription_id @current-user)) [:span {:style {:color "#5cb85c" :font-size "0.7em !important"}} (str " " (subscription-id->name (:subscription_id @current-user)) " Plan")])]]]] [:div {:class "row"} [:div {:class "col-xs-12 col-lg-12"} ;; users info tab navigation [:ul {:class "nav nav-tabs"} [Tab {:default? true :toggle-key :info-view :toggle toggle} "Info"] (when (> (count paginated-orders) 0) [Tab {:default? false :toggle-key :orders-view :toggle toggle} (str "Orders (" (count orders) ")")]) (when (and (not (s/blank? (:arn_endpoint @current-user))) (subset? #{{:uri "/send-push-to-user" :method "POST"}} @accessible-routes)) [Tab {:default? false :toggle-key :push-view :toggle toggle} "Push Notification"]) (when (and (not (:is_courier @current-user )) (< (:orders_count @current-user) 1) (subset? #{{:uri "/users/convert-to-courier" :method "PUT"}} @accessible-routes)) [Tab {:default? false :toggle-key :convert-courier-view :toggle toggle} "Courier Conversion"])]]] ;; main display panel [:div {:class "tab-content"} [TabContent {:toggle (r/cursor toggle [:info-view])} [:div {:class "row"} [:div {:class "col-lg-3 col-xs-12"} [user-form current-user state]] ;; (when-not (empty? user-notes) ;; [:div {:class "col-lg-9 col-xs-12"} ;; (doall (map (fn [note] ;; ^{:key (:timestamp note)} ;; [UserNote {:note note ;; :current-user current-user}]) ;; user-notes))]) ]] [TabContent {:toggle (r/cursor toggle [:push-view])} [:div {:class "row"} [:div {:class "col-lg-6 col-xs-12"} [user-push-notification @current-user]]]] ;; below is for showing user logs, ;; implemented, but not used yet ;; [:br] ;; [ViewHideButton {:class "btn btn-sm btn-default" ;; :view-content "View Logs" ;; :hide-content "Hide Logs" ;; :on-click #(swap! view-log? not) ;; :view? view-log?}] ;; (when @view-log? ;; [:div {:class "table-responsive" ;; :style (if @view-log? ;; {} ;; {:display "none"})} ;; [StaticTable ;; {:table-header [user-history-header ;; {;;:sort-keyword sort-keyword-logs ;; ;;:sort-reversed? sort-reversed-logs? ;; }] ;; :table-row (user-history-row)} ;; (sort-by :timestamp (:admin_event_log @current-user))]]) [TabContent {:toggle (r/cursor toggle [:orders-view])} [:div {:class "row"} [:div {:class "col-lg-12 col-xs-12"} [:div {:style {:margin-top "1em"}} [RefreshButton {:refresh-fn (fn [refreshing?] (get-user-orders (:id @current-user) refreshing?)) :refreshing? retrieving?}]] ;; Table of orders for current user [:div {:class "table-responsive" :style (when-not (> (count paginated-orders) 0) {:display "none"})} [DynamicTable {:current-item (r/atom {}) :tr-props-fn (constantly true) :sort-keyword sort-keyword :sort-reversed? sort-reversed? :table-vecs [["Status" :status :status] ["Courier" :courier_name :courier_name] ["Placed" :target_time_start #(unix-epoch->hrf (:target_time_start %))] ["Deadline" :target_time_end (fn [order] [:span {:style (when-not (contains? #{"complete" "cancelled"} (:status order)) (when (< (- (:target_time_end order) (now)) (* 60 60)) {:color "#d9534f"}))} (unix-epoch->hrf (:target_time_end order)) (when (:tire_pressure_check order) ;; http://www.flaticon.com/free-icon/car-wheel_75660#term=wheel&page=1&position=34 [:img {:src (str base-url "/images/car-wheel.png") :alt "tire-check"}])])] ["Completed" (fn [order] (cond (contains? #{"cancelled"} (:status order)) "Cancelled" (contains? #{"complete"} (:status order)) (unix-epoch->hrf (get-event-time (:event_log order) "complete")) :else "In-Progress")) (fn [order] [:span (when (contains? #{"complete"} (:status order)) (let [completed-time (get-event-time (:event_log order) "complete")] [:span {:style (when (> completed-time (:target_time_end order)) {:color "#d9534f"})} (unix-epoch->hrf completed-time)])) (when (contains? #{"cancelled"} (:status order)) "Cancelled") (when-not (contains? #{"complete" "cancelled"} (:status order)) "In-Progress")])] ["Order Address" :address_street (fn [order] [GoogleMapLink (str (:address_street order) ", " (:address_zip order)) (:lat order) (:lng order)])] ["Courier Rating" :number_rating (fn [order] (let [number-rating (:number_rating order)] (when number-rating [StarRating number-rating])))]]} paginated-orders]] [:div {:style (when-not (> (count paginated-orders) 0) {:display "none"})} [TablePager {:total-pages (count sorted-orders) :current-page current-page}]]]]] [TabContent {:toggle (r/cursor toggle [:convert-courier-view])} [:div {:class "row"} [:div {:class "col-lg-12 col-xs-12"} [:div {:style {:margin-top "1em"}} [courier-conversion @current-user]]]]]]])))) (defn search-users-results-panel "Display a table of selectable users with an indivdual user panel for the selected user" [users state] (let [current-user (r/cursor state [:current-user]) edit-user (r/cursor state [:edit-user]) sort-keyword (r/atom :timestamp_created) sort-reversed? (r/atom false) current-page (r/atom 1) recent-search-term (r/cursor state [:recent-search-term]) page-size 5] (fn [users] (let [sort-fn (if @sort-reversed? (partial sort-by @sort-keyword) (comp reverse (partial sort-by @sort-keyword))) sorted-users (fn [] (->> users sort-fn (partition-all page-size))) paginated-users (fn [] (-> (sorted-users) (nth (- @current-page 1) '()))) table-pager-on-click (fn [] (let [first-user (first (paginated-users))] (reset! current-user first-user)))] (when (nil? @current-user) (table-pager-on-click)) (reset-edit-user! edit-user current-user) ;; set the edit-user values to match those of current-user [:div {:class "panel panel-default"} [user-panel current-user state] [:h4 "Users matching - \"" [:strong {:style {:white-space "pre"}} @recent-search-term] "\""] [:div {:class "panel" :style {:margin-top "15px"}} [:div {:class "table-responsive"} [DynamicTable {:current-item current-user :tr-props-fn (fn [user current-user] (let [user-orders (fn [user] (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))))] {:class (when (= (:id user) (:id @current-user)) "active") :on-click (fn [_] (reset! current-user user) (reset! (r/cursor state [:alert-success]) "") (when (<= (count (user-orders user)) 0) (select-toggle-key! (r/cursor state [:tab-content-toggle]) :info-view)) (reset! (r/cursor state [:user-orders-current-page]) 1))})) :sort-keyword sort-keyword :sort-reversed? sort-reversed? :table-vecs [["Name" :name (fn [user] [UserCrossLink {:on-click (fn [] (user-cross-link-on-click (:id user)))} [:span {:style (when-not (= 0 (:subscription_id user)) {:color "#5cb85c"})} (:name user)]])] ["Market" (fn [user] (-> (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))) first :zone (quot 50) markets)) (fn [user] (-> (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))) first :zone (quot 50) markets))] ["Orders" :orders_count :orders_count] ["Email" :email (fn [user] [Mailto (:email user)])] ["Phone" :phone_number (fn [user] [TelephoneNumber (:phone_number user)])] ["Card?" #(if (s/blank? (:stripe_default_card %)) "No" "Yes") #(if (s/blank? (:stripe_default_card %)) "No" "Yes")] ["Push?" #(if (s/blank? (:arn_endpoint %)) "No" "Yes") #(if (s/blank? (:arn_endpoint %)) "No" "Yes")] ["OS" :os :os] ["Version" :app_version :app_version] ["Joined" :timestamp_created #(unix-epoch->fmt (:timestamp_created %) "M/D/YYYY")]]} (paginated-users)]]] [TablePager {:total-pages (count (sorted-users)) :current-page current-page :on-click table-pager-on-click}]])))) (defn search-bar [state] (let [retrieving? (r/cursor state [:search-retrieving?]) search-results (r/cursor state [:search-results]) recent-search-term (r/cursor state [:recent-search-term]) search-term (r/cursor state [:search-term]) retrieve-results (fn [search-term] (retrieve-url (str base-url "search") "POST" (js/JSON.stringify (clj->js {:term search-term})) (partial xhrio-wrapper (fn [r] (let [response (js->clj r :keywordize-keys true)] (reset! retrieving? false) (reset! recent-search-term search-term) (reset! search-results response))))))] (fn [] [:div {:class "row"} [:div {:class "col-lg-6 col-xs-12"} [:form {:role "users-search"} [:div {:class "input-group"} [:input {:type "text" :class "form-control" :placeholder "Search Users" :on-change (fn [e] (reset! search-term (-> e (aget "target") (aget "value")))) :value @search-term}] [:div {:class "input-group-btn"} [:button {:class "btn btn-default" :type "submit" :on-click (fn [e] (.preventDefault e) (when-not (s/blank? @search-term) (reset! retrieving? true) (retrieve-results @search-term) (reset! (r/cursor state [:current-user]) nil) (reset! (r/cursor state [:current-order]) nil))) } [:i {:class "fa fa-search"}]]]]]]]))) (defn search-results "Display search results" [state] (fn [] (let [search-term (r/cursor state [:search-term]) retrieving? (r/cursor state [:search-retrieving?]) recent-search-term (r/cursor state [:recent-search-term]) search-results (r/cursor state [:search-results]) users-search-results (r/cursor search-results [:users])] [:div (when @retrieving? (.scrollTo js/window 0 0) [:h4 "Retrieving results for \"" [:strong {:style {:white-space "pre"}} @search-term] "\" " [ProcessingIcon]]) (when-not (nil? (and @search-term @recent-search-term)) [:div {:class "row" :id "search-results"} [:div {:class "col-lg-12 col-lg-12"} (when-not @retrieving? [:div (when (and (empty? @users-search-results) (not (s/blank? @recent-search-term)) (not @retrieving?)) [:div [:h4 "Your search - \"" [:strong {:style {:white-space "pre"}} @recent-search-term] \"" - did not match any users."]]) (when-not (empty? @users-search-results) [:div [search-users-results-panel @users-search-results state]])])]])]))) (defn cross-link-result "Retrieve and display user-id when clicked from an internal cross-link" [state] (fn [] (let [search-term (r/cursor state [:search-term]) recent-search-term (r/cursor state [:recent-search-term]) current-user (r/cursor state [:current-user]) retrieving? (r/cursor state [:cross-link-retrieving?]) ] [:div (when @retrieving? [:h4 "Retrieving user information " [:i {:class "fa fa-spinner fa-pulse" :style {:color "black"}}]]) (when (nil? (and @search-term @recent-search-term)) (when-not (nil? @current-user) [:div (when-not @retrieving? [user-panel current-user state])]))])))
112934
(ns dashboard-cljs.users (:require [reagent.core :as r] [cljs.core.async :refer [put! sub chan]] [dashboard-cljs.cookies :as cookies] [dashboard-cljs.datastore :as datastore] [dashboard-cljs.forms :refer [entity-save retrieve-entity edit-on-success edit-on-error]] [dashboard-cljs.orders :refer [user-cross-link-on-click]] [dashboard-cljs.utils :refer [base-url unix-epoch->fmt unix-epoch->hrf markets json-string->clj pager-helper! integer->comma-sep-string parse-to-number? diff-message accessible-routes get-event-time now update-values select-toggle-key! subscription-id->name]] [dashboard-cljs.state :refer [users-state]] [dashboard-cljs.xhr :refer [retrieve-url xhrio-wrapper]] [dashboard-cljs.components :refer [DynamicTable RefreshButton KeyVal StarRating TablePager ConfirmationAlert FormGroup TextInput AlertSuccess SubmitDismissConfirmGroup TextAreaInput ViewHideButton TelephoneNumber Mailto GoogleMapLink Tab TabContent ProcessingIcon UserCrossLink ErrorComp]] [clojure.set :refer [subset?]] [clojure.string :as s])) (def push-selected-users (r/atom (set nil))) (def state users-state) (def user-search-results (r/cursor state [:search-results :users])) (datastore/sync-state! user-search-results (sub datastore/read-data-chan "user-search-results" (chan))) (defn update-user-count [] (retrieve-url (str base-url "users-count") "GET" {} (partial xhrio-wrapper (fn [response] (let [res (js->clj response :keywordize-keys true)] (reset! (r/cursor state [:users-count]) (integer->comma-sep-string (:total (first res))))))))) (defn update-members-count [saving?] (retrieve-url (str base-url "members-count") "GET" {} (partial xhrio-wrapper (fn [response] (let [res (js->clj response :keywordize-keys true)] (reset! (r/cursor state [:members-count]) (integer->comma-sep-string (:total (first res)))) (reset! saving? false)))))) (defonce users-count-result (update-user-count)) (defonce members-count-result (update-members-count (r/cursor state [:update-members-count-saving?]))) (defn displayed-user [user] (let [{:keys [referral_gallons]} user] (assoc user :referral_gallons (str referral_gallons) :referral-comment ""))) (defn user->server-req [user] (let [{:keys [referral_gallons]} user processed-ref-gallons (-> referral_gallons (clojure.string/replace #"," "") (js/Number))] (assoc user :referral_gallons (if (parse-to-number? processed-ref-gallons) processed-ref-gallons referral_gallons)))) (defn reset-edit-user! [edit-user current-user] (reset! edit-user (displayed-user @current-user))) (defn users-count-panel [state] (let [saving? (r/cursor state [:update-members-count-saving?]) refresh-fn (fn [saving?] (reset! saving? true) (update-user-count) (update-members-count saving?))] (fn [] [:div {:class "row"} [:div {:class "col-lg-12 col-xs -12"} [:div [:h3 {:style {:margin-top "0px"}} (str "Users (" @(r/cursor state [:users-count]) ") ") [:span {:style {:color "#5cb85c"}} (str "Members (" @(r/cursor state [:members-count]) ") ") [RefreshButton {:refresh-fn (fn [] (refresh-fn saving?)) :refreshing? saving?}]]]]]]))) (defn user-history-header "props { :sort-keyword ; r/atom, keyword :sort-reversed? ; r/atom, boolean }" [props] (fn [props] [:thead [:tr [:th {:style {:font-size "16px" :font-weight "normal"}} "Date"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Admin"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Adjustment"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Comment"]]])) (defn user-history-row [] (fn [user-log] [:tr ;; Date [:td (unix-epoch->fmt (:timestamp user-log) "M/D/YYYY h:mm A")] ;; Admin [:td (:admin_name user-log)] ;; Gallon adjustment [:td (str (:previous_value user-log) " -> " (:new_value user-log))] ;; comment [:td (:comment user-log)]])) (defn user-form "Form for editing a user" [user state] (let [edit-user (r/cursor state [:edit-user]) current-user (r/cursor state [:current-user]) retrieving? (r/cursor edit-user [:retrieving?]) editing? (r/cursor edit-user [:editing?]) confirming? (r/cursor state [:confirming-edit?]) errors (r/cursor edit-user [:errors]) referral-gallons (r/cursor edit-user [:referral_gallons]) comment (r/cursor edit-user [:referral_comment]) alert-success (r/cursor state [:alert-success]) diff-key-str {:<KEY>erral<KEY>_gallons "<KEY>"} diff-msg-gen (fn [edit current] (diff-message edit (displayed-user current) diff-key-str))] (fn [user] (let [default-card-info (if (empty? (:stripe_cards @edit-user)) nil (->> (:stripe_cards @edit-user) json-string->clj (filter #(= (:stripe_default_card @edit-user) (:id %))) first)) submit-on-click (fn [e] (.preventDefault e) (if @editing? (if (every? nil? (diff-msg-gen @edit-user @current-user)) ;; there isn't a diff message, no changes ;; do nothing (reset! editing? (not @editing?)) ;; there is a diff message, confirm changes (reset! confirming? true)) (do ;; get rid of alert-success (reset! alert-success "") (reset! editing? (not @editing?))))) dismiss-fn (fn [e] ;; reset any errors (reset! errors nil) ;; no longer editing (reset! editing? false) ;; reset current user (reset-edit-user! edit-user current-user) ;; reset confirming (reset! confirming? false))] [:form {:class "form-horizontal"} ;; email [KeyVal "ID" (:id @user)] [KeyVal "Email" [Mailto (:email @user)]] ;; phone number [KeyVal "Phone" [TelephoneNumber (:phone_number @user)]] ;; date started [KeyVal "Registered" (unix-epoch->fmt (:timestamp_created @user) "M/D/YYYY")] ;; last active (last ping) (when-not (nil? (:last_active @user)) [KeyVal "Last Active" (unix-epoch->fmt (:last_active @user) "M/D/YYYY")]) ;; default card (when (not (nil? default-card-info)) [KeyVal "Default Card" (str (:brand default-card-info) " " (:last4 default-card-info) " " (when (not (empty? (:exp_month default-card-info))) (:exp_month default-card-info) "/" (:exp_year default-card-info)))]) ;; referral code [KeyVal "Referral Code" (:referral_code @user)] ;; is this user a courier? [KeyVal "Courier" (if (:is_courier @user) "Yes" "No")] ;; Referral Gallons (if @editing? [:div [FormGroup {:label "Credit Gallons" :label-for "referral gallons" :errors (:referral_gallons @errors)} [TextInput {:value @referral-gallons :default-value @referral-gallons :on-change #(reset! referral-gallons (-> % (aget "target") (aget "value")))}]] [FormGroup {:label "Reason for Changing Credit Gallons" :label-for "referral gallons comment"} [TextAreaInput {:value @comment :rows 2 :cols 50 :on-change #(reset! comment (-> % (aget "target") (aget "value")))}]] [:br]] [KeyVal "Credit Gallons" (:referral_gallons @user)]) (when (subset? #{{:uri "/user" :method "PUT"}} @accessible-routes) [SubmitDismissConfirmGroup {:confirming? confirming? :editing? editing? :retrieving? retrieving? :submit-fn submit-on-click :dismiss-fn dismiss-fn}]) (when (subset? #{{:uri "/user" :method "PUT"}} @accessible-routes) (if (and @confirming? (not-every? nil? (diff-msg-gen @edit-user @current-user))) [ConfirmationAlert {:confirmation-message (fn [] [:div (str "Do you want to make the following changes to " (:name @current-user) "?") (map (fn [el] ^{:key el} [:h4 el]) (diff-msg-gen @edit-user @current-user))]) :cancel-on-click dismiss-fn :confirm-on-click (fn [_] (entity-save (user->server-req @edit-user) "user" "PUT" retrieving? (edit-on-success "user" edit-user current-user alert-success :aux-fn #(reset! confirming? false) :channel-topic "user-search-results" ) (edit-on-error edit-user :aux-fn #(reset! confirming? false)))) :retrieving? retrieving?}] (reset! confirming? false))) ;; success alert (when-not (empty? @alert-success) [AlertSuccess {:message @alert-success :dismiss #(reset! alert-success "")}])])))) (defn get-user-orders "Retrieve orders for user-id and insert them into the datastore" [user-id retrieving?] (reset! retrieving? true) (retrieve-url (str base-url "users/orders/" user-id) "GET" {} (partial xhrio-wrapper (fn [response] (let [orders (js->clj response :keywordize-keys true)] (reset! retrieving? false) (put! datastore/modify-data-chan {:topic "orders" :data orders})))))) (defn current-user-change! "Whenever the current user changes, do some work" [current-user] (when-not (nil? @current-user) (let [retrieving? (r/cursor state [:user-orders-retrieving?])] (get-user-orders (:id @current-user) retrieving?)))) (defn user-push-notification "A component for sending push notifications to users" [user] (let [default-state {:approved? false :confirming? false :retrieving? false :message (str) :alert-success (str) :alert-error (str)} state (r/atom default-state) approved? (r/cursor state [:approve?]) confirming? (r/cursor state [:confirming?]) retrieving? (r/cursor state [:retrieving?]) message (r/cursor state [:message]) alert-success (r/cursor state [:alert-success]) alert-error (r/cursor state [:alert-error]) confirm-on-click (fn [user e] (let [{:keys [id name]} user] (reset! retrieving? true) (retrieve-url (str base-url "send-push-to-user") "POST" (js/JSON.stringify (clj->js {:message @message :user-id id})) (partial xhrio-wrapper (fn [response] (reset! retrieving? false) (let [success? (:success (js->clj response :keywordize-keys true))] (when success? ;; confirm message was sent (reset! alert-success (str "Pushed the message '" @message "' to " name "!"))) (when (not success?) (reset! alert-error (str "Something went wrong." " Push notifications may or may" " not have been sent. Wait until" " sure before trying again.")))) (reset! confirming? false) (reset! message "")))))) confirmation-message (fn [username] (fn [] [:div "Are you sure you want to push the message '" [:span [:strong @message]] "' to " username "?" ]))] (r/create-class {:component-will-receive-props (fn [this] (reset! state default-state)) :reagent-render (fn [user] (let [] [:div {:class "panel panel-default"} [:div {:class "panel-body"} [:div [:h4 (str "Send Push Notification to " (:name user))]] (if @confirming? ;; confirmation [ConfirmationAlert {:cancel-on-click (fn [e] (reset! confirming? false) (reset! message "")) :confirm-on-click (partial confirm-on-click user) :confirmation-message (confirmation-message (:name user)) :retrieving? retrieving?}] ;; Message form [:form [:div {:class "form-group"} [:input {:type "text" :defaultValue "" :class "form-control" :placeholder "Message" :on-change (fn [e] (reset! message (-> e (aget "target") (aget "value"))) (reset! alert-error "") (reset! alert-success ""))}]] [:button {:type "submit" :class "btn btn-default" :on-click (fn [e] (.preventDefault e) (when (not (empty? @message)) (reset! confirming? true))) :disabled (s/blank? @message)} "Send Notification"]]) ;; alert message (when (not (empty? @alert-success)) [:div {:class "alert alert-success alert-dismissible"} [:button {:type "button" :class "close" :aria-label "Close"} [:i {:class "fa fa-times" :on-click #(reset! alert-success "")}]] [:strong @alert-success]]) ;; alert error (when (not (empty? @alert-error)) [:div {:class "alert alert-danger"} @alert-error])]]))}))) (defn UserNote "A component for displaying a user note" [{:keys [note current-user]}] (let [edit-note (r/atom {:retrieving? false :errors nil :comment nil}) retrieving? (r/atom false) editing-note? (r/atom false) alert-success (r/atom "") edit-comment (r/cursor edit-note [:comment]) aux-fn (fn [_] (reset! editing-note? (not @editing-note?)) (reset! retrieving? false)) cookie-admin-id (cookies/get-cookie "user-id")] (r/create-class {:component-did-mount (fn [this] (reset! edit-comment (:comment note))) :reagent-render (fn [{:keys [note current-user]}] (let [{:keys [admin_email admin_id timestamp comment]} note] [:div (when-not @editing-note? [:div [:h4 comment] [:h5 (str "- " admin_email) ", " (unix-epoch->fmt timestamp "M/D/YYYY h:mm a")]]) (when @editing-note? [:div [FormGroup {:label "Notes"} [TextAreaInput {:value @edit-comment :rows 2 :on-change #(reset! edit-comment (-> % (aget "target") (aget "value")))}]]]) (when (= admin_id cookie-admin-id) [:h5 (if-not @editing-note? [:a {:on-click (fn [e] (.preventDefault e) (reset! editing-note? true))} "Edit"] [:a {:on-click (fn [e] (.preventDefault e) (reset! editing-note? false) ;; check to see if the note changed (when (not= edit-comment (:comment note)) ;; the note changed, now replace the current ;; user's note comment with the new one (let [removed-note-admin-event-log (filter #(not= (:timestamp %) timestamp) (:admin_event_log @current-user)) new-admin-event-log (conj removed-note-admin-event-log (assoc note :comment @edit-comment))] ;;(.log js/console (clj->js new-admin-event-log)) (.log js/console (clj->js removed-note-admin-event-log)) ;; upload this to the server ;; (swap! current-user #(assoc % ;; :admin_event_log ;; new-admin-event-log)) (entity-save (clj->js {:id (:id @current-user) :user_note (assoc note :comment @edit-comment)}) "user" "PUT" retrieving? (edit-on-success "user" (r/atom {}) (r/atom {}) (r/atom {}) :channel-topic "user-search-results") #(.log js/console "some unknown error occured")) )) )} "Save"]) " | " [:a "Delete"]])]))}))) (defn courier-conversion "Convert a user to a courier" [user] (let [default-state {:confirming? false :editing? false :retrieving? false :alert-error ""} state (r/atom default-state) confirming? (r/cursor state [:confirming?]) editing? (r/cursor state [:editing?]) retrieving? (r/cursor state [:retrieving?]) alert-success (r/cursor users-state [:alert-success]) alert-error (r/cursor state [:alert-error]) confirm-on-click (fn [user e] (let [{:keys [id name]} user] (reset! retrieving? true) (retrieve-url (str base-url "users/convert-to-courier") "PUT" (js/JSON.stringify (clj->js {:user {:id id}})) (partial xhrio-wrapper (fn [response] (reset! retrieving? false) (let [response (js->clj response :keywordize-keys true) success? (:success response)] (when success? ;; confirm message was sent (reset! alert-success (str "Successfully converted '" name "' to a courier! You can " "now go to the Couriers tab and " "assign zones to this courier.")) (retrieve-entity "user" id (fn [user] (put! datastore/modify-data-chan {:topic "user-search-results" :data user}) (reset! (r/cursor users-state [:current-user]) (first user)) (datastore/sync-couriers!)))) (when (not success?) (reset! alert-error (str "Error: " (:message response))))) (reset! confirming? false)))))) confirmation-message (fn [username] (fn [] [:div "Are you sure you want to convert '" [:span [:strong username]] "' to a courier?" [:br] [:span [:strong " Warning: This can not be " "undone from the dashboard!"]] [:br] " Once converted, " "this account will not be able to place " "orders and will only be able to accept " "orders for delivery." [:br] " This action " "can only be reversed manually by an admin!"] ))] (r/create-class {:component-will-receive-props (fn [this] (reset! state default-state)) :reagent-render (fn [user] [:div (cond (not @confirming?) [:button {:type "button" :class "btn btn-default" :on-click (fn [e] (.preventDefault e) (reset! confirming? true) (reset! alert-success "") (reset! alert-error ""))} "Convert to Courier"] @confirming? [ConfirmationAlert {:cancel-on-click (fn [e] (reset! confirming? false)) :confirm-on-click (partial confirm-on-click user) :confirmation-message (confirmation-message (:name user)) :retrieving? retrieving?}]) ;; alert message (when (not (empty? @alert-success)) [AlertSuccess {:message @alert-success :dismiss #(reset! alert-success "")}]) ;; alert error (when (not (empty? @alert-error)) [ErrorComp {:error-message @alert-error :dismiss-fn #(reset! alert-error "")}])])}))) (defn user-panel "Display detailed and editable fields for an user. current-user is an r/atom" [current-user state] (let [sort-keyword (r/atom :target_time_start) sort-reversed? (r/atom false) current-page (r/cursor state [:user-orders-current-page]) page-size 5 edit-user (r/cursor state [:edit-user]) view-log? (r/cursor state [:view-log?]) toggle (r/atom {}) retrieving? (r/cursor state [:user-orders-retrieving?]) orders-view-toggle? (r/cursor toggle [:orders-view]) push-view-toggle? (r/cursor toggle [:push-view]) convert-courier-view? (r/cursor toggle [:convert-courier-view])] (fn [current-user] (let [sort-fn (if @sort-reversed? (partial sort-by @sort-keyword) (comp reverse (partial sort-by @sort-keyword))) orders ;; filter out the orders to only those assigned ;; to the user (->> @datastore/orders (filter (fn [order] (= (:id @current-user) (:user_id order))))) sorted-orders (->> orders sort-fn (partition-all page-size)) paginated-orders (pager-helper! sorted-orders current-page) most-recent-order (->> orders (sort-by :target_time_start) first) current-user-update @(r/track current-user-change! current-user) ;; admin-event-log (:admin_event_log @current-user) ;; user-notes (->> admin-event-log ;; (filter #(= (:action %) "user_notes")) ;; (sort-by :timestamp)) ] ;; edit-user should correspond to current-user (when-not (:editing? @edit-user) (reset! edit-user (assoc @edit-user :last_active (:target_time_start most-recent-order)))) ;; Make sure that orders view is not selected when a user has no orders (when (and (<= (count paginated-orders) 0) @orders-view-toggle?) (select-toggle-key! toggle :info-view)) ;; Make sure that push-view is not selected when a user has push ;; notifications turned off (when (and (s/blank? (:arn_endpoint @current-user)) @push-view-toggle?) (select-toggle-key! toggle :info-view)) ;; Make sure that courier conversion is not selected when a user ;; is already a courier (when (and (:is_courier @current-user) @convert-courier-view?) (select-toggle-key! toggle :info-view)) ;; If the user is not qualified to be a courier ;; reset the toggle key (when (and (or (> (:orders_count @current-user) 0) (:is_courier @current-user)) @convert-courier-view?) (select-toggle-key! toggle :info-view)) [:div {:class "panel-body"} ;; populate the current user with additional information [:div {:class "row"} [:div {:class "col-xs-12 col-lg-12"} [:div [:h3 (:name @current-user) (when-not (= 0 (:subscription_id @current-user)) [:span {:style {:color "#5cb85c" :font-size "0.7em !important"}} (str " " (subscription-id->name (:subscription_id @current-user)) " Plan")])]]]] [:div {:class "row"} [:div {:class "col-xs-12 col-lg-12"} ;; users info tab navigation [:ul {:class "nav nav-tabs"} [Tab {:default? true :toggle-key :info-view :toggle toggle} "Info"] (when (> (count paginated-orders) 0) [Tab {:default? false :toggle-key :orders-view :toggle toggle} (str "Orders (" (count orders) ")")]) (when (and (not (s/blank? (:arn_endpoint @current-user))) (subset? #{{:uri "/send-push-to-user" :method "POST"}} @accessible-routes)) [Tab {:default? false :toggle-key :push-view :toggle toggle} "Push Notification"]) (when (and (not (:is_courier @current-user )) (< (:orders_count @current-user) 1) (subset? #{{:uri "/users/convert-to-courier" :method "PUT"}} @accessible-routes)) [Tab {:default? false :toggle-key :convert-courier-view :toggle toggle} "Courier Conversion"])]]] ;; main display panel [:div {:class "tab-content"} [TabContent {:toggle (r/cursor toggle [:info-view])} [:div {:class "row"} [:div {:class "col-lg-3 col-xs-12"} [user-form current-user state]] ;; (when-not (empty? user-notes) ;; [:div {:class "col-lg-9 col-xs-12"} ;; (doall (map (fn [note] ;; ^{:key (:timestamp note)} ;; [UserNote {:note note ;; :current-user current-user}]) ;; user-notes))]) ]] [TabContent {:toggle (r/cursor toggle [:push-view])} [:div {:class "row"} [:div {:class "col-lg-6 col-xs-12"} [user-push-notification @current-user]]]] ;; below is for showing user logs, ;; implemented, but not used yet ;; [:br] ;; [ViewHideButton {:class "btn btn-sm btn-default" ;; :view-content "View Logs" ;; :hide-content "Hide Logs" ;; :on-click #(swap! view-log? not) ;; :view? view-log?}] ;; (when @view-log? ;; [:div {:class "table-responsive" ;; :style (if @view-log? ;; {} ;; {:display "none"})} ;; [StaticTable ;; {:table-header [user-history-header ;; {;;:sort-keyword sort-keyword-logs ;; ;;:sort-reversed? sort-reversed-logs? ;; }] ;; :table-row (user-history-row)} ;; (sort-by :timestamp (:admin_event_log @current-user))]]) [TabContent {:toggle (r/cursor toggle [:orders-view])} [:div {:class "row"} [:div {:class "col-lg-12 col-xs-12"} [:div {:style {:margin-top "1em"}} [RefreshButton {:refresh-fn (fn [refreshing?] (get-user-orders (:id @current-user) refreshing?)) :refreshing? retrieving?}]] ;; Table of orders for current user [:div {:class "table-responsive" :style (when-not (> (count paginated-orders) 0) {:display "none"})} [DynamicTable {:current-item (r/atom {}) :tr-props-fn (constantly true) :sort-keyword sort-keyword :sort-reversed? sort-reversed? :table-vecs [["Status" :status :status] ["Courier" :courier_name :courier_name] ["Placed" :target_time_start #(unix-epoch->hrf (:target_time_start %))] ["Deadline" :target_time_end (fn [order] [:span {:style (when-not (contains? #{"complete" "cancelled"} (:status order)) (when (< (- (:target_time_end order) (now)) (* 60 60)) {:color "#d9534f"}))} (unix-epoch->hrf (:target_time_end order)) (when (:tire_pressure_check order) ;; http://www.flaticon.com/free-icon/car-wheel_75660#term=wheel&page=1&position=34 [:img {:src (str base-url "/images/car-wheel.png") :alt "tire-check"}])])] ["Completed" (fn [order] (cond (contains? #{"cancelled"} (:status order)) "Cancelled" (contains? #{"complete"} (:status order)) (unix-epoch->hrf (get-event-time (:event_log order) "complete")) :else "In-Progress")) (fn [order] [:span (when (contains? #{"complete"} (:status order)) (let [completed-time (get-event-time (:event_log order) "complete")] [:span {:style (when (> completed-time (:target_time_end order)) {:color "#d9534f"})} (unix-epoch->hrf completed-time)])) (when (contains? #{"cancelled"} (:status order)) "Cancelled") (when-not (contains? #{"complete" "cancelled"} (:status order)) "In-Progress")])] ["Order Address" :address_street (fn [order] [GoogleMapLink (str (:address_street order) ", " (:address_zip order)) (:lat order) (:lng order)])] ["Courier Rating" :number_rating (fn [order] (let [number-rating (:number_rating order)] (when number-rating [StarRating number-rating])))]]} paginated-orders]] [:div {:style (when-not (> (count paginated-orders) 0) {:display "none"})} [TablePager {:total-pages (count sorted-orders) :current-page current-page}]]]]] [TabContent {:toggle (r/cursor toggle [:convert-courier-view])} [:div {:class "row"} [:div {:class "col-lg-12 col-xs-12"} [:div {:style {:margin-top "1em"}} [courier-conversion @current-user]]]]]]])))) (defn search-users-results-panel "Display a table of selectable users with an indivdual user panel for the selected user" [users state] (let [current-user (r/cursor state [:current-user]) edit-user (r/cursor state [:edit-user]) sort-keyword (r/atom :timestamp_created) sort-reversed? (r/atom false) current-page (r/atom 1) recent-search-term (r/cursor state [:recent-search-term]) page-size 5] (fn [users] (let [sort-fn (if @sort-reversed? (partial sort-by @sort-keyword) (comp reverse (partial sort-by @sort-keyword))) sorted-users (fn [] (->> users sort-fn (partition-all page-size))) paginated-users (fn [] (-> (sorted-users) (nth (- @current-page 1) '()))) table-pager-on-click (fn [] (let [first-user (first (paginated-users))] (reset! current-user first-user)))] (when (nil? @current-user) (table-pager-on-click)) (reset-edit-user! edit-user current-user) ;; set the edit-user values to match those of current-user [:div {:class "panel panel-default"} [user-panel current-user state] [:h4 "Users matching - \"" [:strong {:style {:white-space "pre"}} @recent-search-term] "\""] [:div {:class "panel" :style {:margin-top "15px"}} [:div {:class "table-responsive"} [DynamicTable {:current-item current-user :tr-props-fn (fn [user current-user] (let [user-orders (fn [user] (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))))] {:class (when (= (:id user) (:id @current-user)) "active") :on-click (fn [_] (reset! current-user user) (reset! (r/cursor state [:alert-success]) "") (when (<= (count (user-orders user)) 0) (select-toggle-key! (r/cursor state [:tab-content-toggle]) :info-view)) (reset! (r/cursor state [:user-orders-current-page]) 1))})) :sort-keyword sort-keyword :sort-reversed? sort-reversed? :table-vecs [["Name" :name (fn [user] [UserCrossLink {:on-click (fn [] (user-cross-link-on-click (:id user)))} [:span {:style (when-not (= 0 (:subscription_id user)) {:color "#5cb85c"})} (:name user)]])] ["Market" (fn [user] (-> (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))) first :zone (quot 50) markets)) (fn [user] (-> (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))) first :zone (quot 50) markets))] ["Orders" :orders_count :orders_count] ["Email" :email (fn [user] [Mailto (:email user)])] ["Phone" :phone_number (fn [user] [TelephoneNumber (:phone_number user)])] ["Card?" #(if (s/blank? (:stripe_default_card %)) "No" "Yes") #(if (s/blank? (:stripe_default_card %)) "No" "Yes")] ["Push?" #(if (s/blank? (:arn_endpoint %)) "No" "Yes") #(if (s/blank? (:arn_endpoint %)) "No" "Yes")] ["OS" :os :os] ["Version" :app_version :app_version] ["Joined" :timestamp_created #(unix-epoch->fmt (:timestamp_created %) "M/D/YYYY")]]} (paginated-users)]]] [TablePager {:total-pages (count (sorted-users)) :current-page current-page :on-click table-pager-on-click}]])))) (defn search-bar [state] (let [retrieving? (r/cursor state [:search-retrieving?]) search-results (r/cursor state [:search-results]) recent-search-term (r/cursor state [:recent-search-term]) search-term (r/cursor state [:search-term]) retrieve-results (fn [search-term] (retrieve-url (str base-url "search") "POST" (js/JSON.stringify (clj->js {:term search-term})) (partial xhrio-wrapper (fn [r] (let [response (js->clj r :keywordize-keys true)] (reset! retrieving? false) (reset! recent-search-term search-term) (reset! search-results response))))))] (fn [] [:div {:class "row"} [:div {:class "col-lg-6 col-xs-12"} [:form {:role "users-search"} [:div {:class "input-group"} [:input {:type "text" :class "form-control" :placeholder "Search Users" :on-change (fn [e] (reset! search-term (-> e (aget "target") (aget "value")))) :value @search-term}] [:div {:class "input-group-btn"} [:button {:class "btn btn-default" :type "submit" :on-click (fn [e] (.preventDefault e) (when-not (s/blank? @search-term) (reset! retrieving? true) (retrieve-results @search-term) (reset! (r/cursor state [:current-user]) nil) (reset! (r/cursor state [:current-order]) nil))) } [:i {:class "fa fa-search"}]]]]]]]))) (defn search-results "Display search results" [state] (fn [] (let [search-term (r/cursor state [:search-term]) retrieving? (r/cursor state [:search-retrieving?]) recent-search-term (r/cursor state [:recent-search-term]) search-results (r/cursor state [:search-results]) users-search-results (r/cursor search-results [:users])] [:div (when @retrieving? (.scrollTo js/window 0 0) [:h4 "Retrieving results for \"" [:strong {:style {:white-space "pre"}} @search-term] "\" " [ProcessingIcon]]) (when-not (nil? (and @search-term @recent-search-term)) [:div {:class "row" :id "search-results"} [:div {:class "col-lg-12 col-lg-12"} (when-not @retrieving? [:div (when (and (empty? @users-search-results) (not (s/blank? @recent-search-term)) (not @retrieving?)) [:div [:h4 "Your search - \"" [:strong {:style {:white-space "pre"}} @recent-search-term] \"" - did not match any users."]]) (when-not (empty? @users-search-results) [:div [search-users-results-panel @users-search-results state]])])]])]))) (defn cross-link-result "Retrieve and display user-id when clicked from an internal cross-link" [state] (fn [] (let [search-term (r/cursor state [:search-term]) recent-search-term (r/cursor state [:recent-search-term]) current-user (r/cursor state [:current-user]) retrieving? (r/cursor state [:cross-link-retrieving?]) ] [:div (when @retrieving? [:h4 "Retrieving user information " [:i {:class "fa fa-spinner fa-pulse" :style {:color "black"}}]]) (when (nil? (and @search-term @recent-search-term)) (when-not (nil? @current-user) [:div (when-not @retrieving? [user-panel current-user state])]))])))
true
(ns dashboard-cljs.users (:require [reagent.core :as r] [cljs.core.async :refer [put! sub chan]] [dashboard-cljs.cookies :as cookies] [dashboard-cljs.datastore :as datastore] [dashboard-cljs.forms :refer [entity-save retrieve-entity edit-on-success edit-on-error]] [dashboard-cljs.orders :refer [user-cross-link-on-click]] [dashboard-cljs.utils :refer [base-url unix-epoch->fmt unix-epoch->hrf markets json-string->clj pager-helper! integer->comma-sep-string parse-to-number? diff-message accessible-routes get-event-time now update-values select-toggle-key! subscription-id->name]] [dashboard-cljs.state :refer [users-state]] [dashboard-cljs.xhr :refer [retrieve-url xhrio-wrapper]] [dashboard-cljs.components :refer [DynamicTable RefreshButton KeyVal StarRating TablePager ConfirmationAlert FormGroup TextInput AlertSuccess SubmitDismissConfirmGroup TextAreaInput ViewHideButton TelephoneNumber Mailto GoogleMapLink Tab TabContent ProcessingIcon UserCrossLink ErrorComp]] [clojure.set :refer [subset?]] [clojure.string :as s])) (def push-selected-users (r/atom (set nil))) (def state users-state) (def user-search-results (r/cursor state [:search-results :users])) (datastore/sync-state! user-search-results (sub datastore/read-data-chan "user-search-results" (chan))) (defn update-user-count [] (retrieve-url (str base-url "users-count") "GET" {} (partial xhrio-wrapper (fn [response] (let [res (js->clj response :keywordize-keys true)] (reset! (r/cursor state [:users-count]) (integer->comma-sep-string (:total (first res))))))))) (defn update-members-count [saving?] (retrieve-url (str base-url "members-count") "GET" {} (partial xhrio-wrapper (fn [response] (let [res (js->clj response :keywordize-keys true)] (reset! (r/cursor state [:members-count]) (integer->comma-sep-string (:total (first res)))) (reset! saving? false)))))) (defonce users-count-result (update-user-count)) (defonce members-count-result (update-members-count (r/cursor state [:update-members-count-saving?]))) (defn displayed-user [user] (let [{:keys [referral_gallons]} user] (assoc user :referral_gallons (str referral_gallons) :referral-comment ""))) (defn user->server-req [user] (let [{:keys [referral_gallons]} user processed-ref-gallons (-> referral_gallons (clojure.string/replace #"," "") (js/Number))] (assoc user :referral_gallons (if (parse-to-number? processed-ref-gallons) processed-ref-gallons referral_gallons)))) (defn reset-edit-user! [edit-user current-user] (reset! edit-user (displayed-user @current-user))) (defn users-count-panel [state] (let [saving? (r/cursor state [:update-members-count-saving?]) refresh-fn (fn [saving?] (reset! saving? true) (update-user-count) (update-members-count saving?))] (fn [] [:div {:class "row"} [:div {:class "col-lg-12 col-xs -12"} [:div [:h3 {:style {:margin-top "0px"}} (str "Users (" @(r/cursor state [:users-count]) ") ") [:span {:style {:color "#5cb85c"}} (str "Members (" @(r/cursor state [:members-count]) ") ") [RefreshButton {:refresh-fn (fn [] (refresh-fn saving?)) :refreshing? saving?}]]]]]]))) (defn user-history-header "props { :sort-keyword ; r/atom, keyword :sort-reversed? ; r/atom, boolean }" [props] (fn [props] [:thead [:tr [:th {:style {:font-size "16px" :font-weight "normal"}} "Date"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Admin"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Adjustment"] [:th {:style {:font-size "16px" :font-weight "normal"}} "Comment"]]])) (defn user-history-row [] (fn [user-log] [:tr ;; Date [:td (unix-epoch->fmt (:timestamp user-log) "M/D/YYYY h:mm A")] ;; Admin [:td (:admin_name user-log)] ;; Gallon adjustment [:td (str (:previous_value user-log) " -> " (:new_value user-log))] ;; comment [:td (:comment user-log)]])) (defn user-form "Form for editing a user" [user state] (let [edit-user (r/cursor state [:edit-user]) current-user (r/cursor state [:current-user]) retrieving? (r/cursor edit-user [:retrieving?]) editing? (r/cursor edit-user [:editing?]) confirming? (r/cursor state [:confirming-edit?]) errors (r/cursor edit-user [:errors]) referral-gallons (r/cursor edit-user [:referral_gallons]) comment (r/cursor edit-user [:referral_comment]) alert-success (r/cursor state [:alert-success]) diff-key-str {:PI:KEY:<KEY>END_PIerralPI:KEY:<KEY>END_PI_gallons "PI:KEY:<KEY>END_PI"} diff-msg-gen (fn [edit current] (diff-message edit (displayed-user current) diff-key-str))] (fn [user] (let [default-card-info (if (empty? (:stripe_cards @edit-user)) nil (->> (:stripe_cards @edit-user) json-string->clj (filter #(= (:stripe_default_card @edit-user) (:id %))) first)) submit-on-click (fn [e] (.preventDefault e) (if @editing? (if (every? nil? (diff-msg-gen @edit-user @current-user)) ;; there isn't a diff message, no changes ;; do nothing (reset! editing? (not @editing?)) ;; there is a diff message, confirm changes (reset! confirming? true)) (do ;; get rid of alert-success (reset! alert-success "") (reset! editing? (not @editing?))))) dismiss-fn (fn [e] ;; reset any errors (reset! errors nil) ;; no longer editing (reset! editing? false) ;; reset current user (reset-edit-user! edit-user current-user) ;; reset confirming (reset! confirming? false))] [:form {:class "form-horizontal"} ;; email [KeyVal "ID" (:id @user)] [KeyVal "Email" [Mailto (:email @user)]] ;; phone number [KeyVal "Phone" [TelephoneNumber (:phone_number @user)]] ;; date started [KeyVal "Registered" (unix-epoch->fmt (:timestamp_created @user) "M/D/YYYY")] ;; last active (last ping) (when-not (nil? (:last_active @user)) [KeyVal "Last Active" (unix-epoch->fmt (:last_active @user) "M/D/YYYY")]) ;; default card (when (not (nil? default-card-info)) [KeyVal "Default Card" (str (:brand default-card-info) " " (:last4 default-card-info) " " (when (not (empty? (:exp_month default-card-info))) (:exp_month default-card-info) "/" (:exp_year default-card-info)))]) ;; referral code [KeyVal "Referral Code" (:referral_code @user)] ;; is this user a courier? [KeyVal "Courier" (if (:is_courier @user) "Yes" "No")] ;; Referral Gallons (if @editing? [:div [FormGroup {:label "Credit Gallons" :label-for "referral gallons" :errors (:referral_gallons @errors)} [TextInput {:value @referral-gallons :default-value @referral-gallons :on-change #(reset! referral-gallons (-> % (aget "target") (aget "value")))}]] [FormGroup {:label "Reason for Changing Credit Gallons" :label-for "referral gallons comment"} [TextAreaInput {:value @comment :rows 2 :cols 50 :on-change #(reset! comment (-> % (aget "target") (aget "value")))}]] [:br]] [KeyVal "Credit Gallons" (:referral_gallons @user)]) (when (subset? #{{:uri "/user" :method "PUT"}} @accessible-routes) [SubmitDismissConfirmGroup {:confirming? confirming? :editing? editing? :retrieving? retrieving? :submit-fn submit-on-click :dismiss-fn dismiss-fn}]) (when (subset? #{{:uri "/user" :method "PUT"}} @accessible-routes) (if (and @confirming? (not-every? nil? (diff-msg-gen @edit-user @current-user))) [ConfirmationAlert {:confirmation-message (fn [] [:div (str "Do you want to make the following changes to " (:name @current-user) "?") (map (fn [el] ^{:key el} [:h4 el]) (diff-msg-gen @edit-user @current-user))]) :cancel-on-click dismiss-fn :confirm-on-click (fn [_] (entity-save (user->server-req @edit-user) "user" "PUT" retrieving? (edit-on-success "user" edit-user current-user alert-success :aux-fn #(reset! confirming? false) :channel-topic "user-search-results" ) (edit-on-error edit-user :aux-fn #(reset! confirming? false)))) :retrieving? retrieving?}] (reset! confirming? false))) ;; success alert (when-not (empty? @alert-success) [AlertSuccess {:message @alert-success :dismiss #(reset! alert-success "")}])])))) (defn get-user-orders "Retrieve orders for user-id and insert them into the datastore" [user-id retrieving?] (reset! retrieving? true) (retrieve-url (str base-url "users/orders/" user-id) "GET" {} (partial xhrio-wrapper (fn [response] (let [orders (js->clj response :keywordize-keys true)] (reset! retrieving? false) (put! datastore/modify-data-chan {:topic "orders" :data orders})))))) (defn current-user-change! "Whenever the current user changes, do some work" [current-user] (when-not (nil? @current-user) (let [retrieving? (r/cursor state [:user-orders-retrieving?])] (get-user-orders (:id @current-user) retrieving?)))) (defn user-push-notification "A component for sending push notifications to users" [user] (let [default-state {:approved? false :confirming? false :retrieving? false :message (str) :alert-success (str) :alert-error (str)} state (r/atom default-state) approved? (r/cursor state [:approve?]) confirming? (r/cursor state [:confirming?]) retrieving? (r/cursor state [:retrieving?]) message (r/cursor state [:message]) alert-success (r/cursor state [:alert-success]) alert-error (r/cursor state [:alert-error]) confirm-on-click (fn [user e] (let [{:keys [id name]} user] (reset! retrieving? true) (retrieve-url (str base-url "send-push-to-user") "POST" (js/JSON.stringify (clj->js {:message @message :user-id id})) (partial xhrio-wrapper (fn [response] (reset! retrieving? false) (let [success? (:success (js->clj response :keywordize-keys true))] (when success? ;; confirm message was sent (reset! alert-success (str "Pushed the message '" @message "' to " name "!"))) (when (not success?) (reset! alert-error (str "Something went wrong." " Push notifications may or may" " not have been sent. Wait until" " sure before trying again.")))) (reset! confirming? false) (reset! message "")))))) confirmation-message (fn [username] (fn [] [:div "Are you sure you want to push the message '" [:span [:strong @message]] "' to " username "?" ]))] (r/create-class {:component-will-receive-props (fn [this] (reset! state default-state)) :reagent-render (fn [user] (let [] [:div {:class "panel panel-default"} [:div {:class "panel-body"} [:div [:h4 (str "Send Push Notification to " (:name user))]] (if @confirming? ;; confirmation [ConfirmationAlert {:cancel-on-click (fn [e] (reset! confirming? false) (reset! message "")) :confirm-on-click (partial confirm-on-click user) :confirmation-message (confirmation-message (:name user)) :retrieving? retrieving?}] ;; Message form [:form [:div {:class "form-group"} [:input {:type "text" :defaultValue "" :class "form-control" :placeholder "Message" :on-change (fn [e] (reset! message (-> e (aget "target") (aget "value"))) (reset! alert-error "") (reset! alert-success ""))}]] [:button {:type "submit" :class "btn btn-default" :on-click (fn [e] (.preventDefault e) (when (not (empty? @message)) (reset! confirming? true))) :disabled (s/blank? @message)} "Send Notification"]]) ;; alert message (when (not (empty? @alert-success)) [:div {:class "alert alert-success alert-dismissible"} [:button {:type "button" :class "close" :aria-label "Close"} [:i {:class "fa fa-times" :on-click #(reset! alert-success "")}]] [:strong @alert-success]]) ;; alert error (when (not (empty? @alert-error)) [:div {:class "alert alert-danger"} @alert-error])]]))}))) (defn UserNote "A component for displaying a user note" [{:keys [note current-user]}] (let [edit-note (r/atom {:retrieving? false :errors nil :comment nil}) retrieving? (r/atom false) editing-note? (r/atom false) alert-success (r/atom "") edit-comment (r/cursor edit-note [:comment]) aux-fn (fn [_] (reset! editing-note? (not @editing-note?)) (reset! retrieving? false)) cookie-admin-id (cookies/get-cookie "user-id")] (r/create-class {:component-did-mount (fn [this] (reset! edit-comment (:comment note))) :reagent-render (fn [{:keys [note current-user]}] (let [{:keys [admin_email admin_id timestamp comment]} note] [:div (when-not @editing-note? [:div [:h4 comment] [:h5 (str "- " admin_email) ", " (unix-epoch->fmt timestamp "M/D/YYYY h:mm a")]]) (when @editing-note? [:div [FormGroup {:label "Notes"} [TextAreaInput {:value @edit-comment :rows 2 :on-change #(reset! edit-comment (-> % (aget "target") (aget "value")))}]]]) (when (= admin_id cookie-admin-id) [:h5 (if-not @editing-note? [:a {:on-click (fn [e] (.preventDefault e) (reset! editing-note? true))} "Edit"] [:a {:on-click (fn [e] (.preventDefault e) (reset! editing-note? false) ;; check to see if the note changed (when (not= edit-comment (:comment note)) ;; the note changed, now replace the current ;; user's note comment with the new one (let [removed-note-admin-event-log (filter #(not= (:timestamp %) timestamp) (:admin_event_log @current-user)) new-admin-event-log (conj removed-note-admin-event-log (assoc note :comment @edit-comment))] ;;(.log js/console (clj->js new-admin-event-log)) (.log js/console (clj->js removed-note-admin-event-log)) ;; upload this to the server ;; (swap! current-user #(assoc % ;; :admin_event_log ;; new-admin-event-log)) (entity-save (clj->js {:id (:id @current-user) :user_note (assoc note :comment @edit-comment)}) "user" "PUT" retrieving? (edit-on-success "user" (r/atom {}) (r/atom {}) (r/atom {}) :channel-topic "user-search-results") #(.log js/console "some unknown error occured")) )) )} "Save"]) " | " [:a "Delete"]])]))}))) (defn courier-conversion "Convert a user to a courier" [user] (let [default-state {:confirming? false :editing? false :retrieving? false :alert-error ""} state (r/atom default-state) confirming? (r/cursor state [:confirming?]) editing? (r/cursor state [:editing?]) retrieving? (r/cursor state [:retrieving?]) alert-success (r/cursor users-state [:alert-success]) alert-error (r/cursor state [:alert-error]) confirm-on-click (fn [user e] (let [{:keys [id name]} user] (reset! retrieving? true) (retrieve-url (str base-url "users/convert-to-courier") "PUT" (js/JSON.stringify (clj->js {:user {:id id}})) (partial xhrio-wrapper (fn [response] (reset! retrieving? false) (let [response (js->clj response :keywordize-keys true) success? (:success response)] (when success? ;; confirm message was sent (reset! alert-success (str "Successfully converted '" name "' to a courier! You can " "now go to the Couriers tab and " "assign zones to this courier.")) (retrieve-entity "user" id (fn [user] (put! datastore/modify-data-chan {:topic "user-search-results" :data user}) (reset! (r/cursor users-state [:current-user]) (first user)) (datastore/sync-couriers!)))) (when (not success?) (reset! alert-error (str "Error: " (:message response))))) (reset! confirming? false)))))) confirmation-message (fn [username] (fn [] [:div "Are you sure you want to convert '" [:span [:strong username]] "' to a courier?" [:br] [:span [:strong " Warning: This can not be " "undone from the dashboard!"]] [:br] " Once converted, " "this account will not be able to place " "orders and will only be able to accept " "orders for delivery." [:br] " This action " "can only be reversed manually by an admin!"] ))] (r/create-class {:component-will-receive-props (fn [this] (reset! state default-state)) :reagent-render (fn [user] [:div (cond (not @confirming?) [:button {:type "button" :class "btn btn-default" :on-click (fn [e] (.preventDefault e) (reset! confirming? true) (reset! alert-success "") (reset! alert-error ""))} "Convert to Courier"] @confirming? [ConfirmationAlert {:cancel-on-click (fn [e] (reset! confirming? false)) :confirm-on-click (partial confirm-on-click user) :confirmation-message (confirmation-message (:name user)) :retrieving? retrieving?}]) ;; alert message (when (not (empty? @alert-success)) [AlertSuccess {:message @alert-success :dismiss #(reset! alert-success "")}]) ;; alert error (when (not (empty? @alert-error)) [ErrorComp {:error-message @alert-error :dismiss-fn #(reset! alert-error "")}])])}))) (defn user-panel "Display detailed and editable fields for an user. current-user is an r/atom" [current-user state] (let [sort-keyword (r/atom :target_time_start) sort-reversed? (r/atom false) current-page (r/cursor state [:user-orders-current-page]) page-size 5 edit-user (r/cursor state [:edit-user]) view-log? (r/cursor state [:view-log?]) toggle (r/atom {}) retrieving? (r/cursor state [:user-orders-retrieving?]) orders-view-toggle? (r/cursor toggle [:orders-view]) push-view-toggle? (r/cursor toggle [:push-view]) convert-courier-view? (r/cursor toggle [:convert-courier-view])] (fn [current-user] (let [sort-fn (if @sort-reversed? (partial sort-by @sort-keyword) (comp reverse (partial sort-by @sort-keyword))) orders ;; filter out the orders to only those assigned ;; to the user (->> @datastore/orders (filter (fn [order] (= (:id @current-user) (:user_id order))))) sorted-orders (->> orders sort-fn (partition-all page-size)) paginated-orders (pager-helper! sorted-orders current-page) most-recent-order (->> orders (sort-by :target_time_start) first) current-user-update @(r/track current-user-change! current-user) ;; admin-event-log (:admin_event_log @current-user) ;; user-notes (->> admin-event-log ;; (filter #(= (:action %) "user_notes")) ;; (sort-by :timestamp)) ] ;; edit-user should correspond to current-user (when-not (:editing? @edit-user) (reset! edit-user (assoc @edit-user :last_active (:target_time_start most-recent-order)))) ;; Make sure that orders view is not selected when a user has no orders (when (and (<= (count paginated-orders) 0) @orders-view-toggle?) (select-toggle-key! toggle :info-view)) ;; Make sure that push-view is not selected when a user has push ;; notifications turned off (when (and (s/blank? (:arn_endpoint @current-user)) @push-view-toggle?) (select-toggle-key! toggle :info-view)) ;; Make sure that courier conversion is not selected when a user ;; is already a courier (when (and (:is_courier @current-user) @convert-courier-view?) (select-toggle-key! toggle :info-view)) ;; If the user is not qualified to be a courier ;; reset the toggle key (when (and (or (> (:orders_count @current-user) 0) (:is_courier @current-user)) @convert-courier-view?) (select-toggle-key! toggle :info-view)) [:div {:class "panel-body"} ;; populate the current user with additional information [:div {:class "row"} [:div {:class "col-xs-12 col-lg-12"} [:div [:h3 (:name @current-user) (when-not (= 0 (:subscription_id @current-user)) [:span {:style {:color "#5cb85c" :font-size "0.7em !important"}} (str " " (subscription-id->name (:subscription_id @current-user)) " Plan")])]]]] [:div {:class "row"} [:div {:class "col-xs-12 col-lg-12"} ;; users info tab navigation [:ul {:class "nav nav-tabs"} [Tab {:default? true :toggle-key :info-view :toggle toggle} "Info"] (when (> (count paginated-orders) 0) [Tab {:default? false :toggle-key :orders-view :toggle toggle} (str "Orders (" (count orders) ")")]) (when (and (not (s/blank? (:arn_endpoint @current-user))) (subset? #{{:uri "/send-push-to-user" :method "POST"}} @accessible-routes)) [Tab {:default? false :toggle-key :push-view :toggle toggle} "Push Notification"]) (when (and (not (:is_courier @current-user )) (< (:orders_count @current-user) 1) (subset? #{{:uri "/users/convert-to-courier" :method "PUT"}} @accessible-routes)) [Tab {:default? false :toggle-key :convert-courier-view :toggle toggle} "Courier Conversion"])]]] ;; main display panel [:div {:class "tab-content"} [TabContent {:toggle (r/cursor toggle [:info-view])} [:div {:class "row"} [:div {:class "col-lg-3 col-xs-12"} [user-form current-user state]] ;; (when-not (empty? user-notes) ;; [:div {:class "col-lg-9 col-xs-12"} ;; (doall (map (fn [note] ;; ^{:key (:timestamp note)} ;; [UserNote {:note note ;; :current-user current-user}]) ;; user-notes))]) ]] [TabContent {:toggle (r/cursor toggle [:push-view])} [:div {:class "row"} [:div {:class "col-lg-6 col-xs-12"} [user-push-notification @current-user]]]] ;; below is for showing user logs, ;; implemented, but not used yet ;; [:br] ;; [ViewHideButton {:class "btn btn-sm btn-default" ;; :view-content "View Logs" ;; :hide-content "Hide Logs" ;; :on-click #(swap! view-log? not) ;; :view? view-log?}] ;; (when @view-log? ;; [:div {:class "table-responsive" ;; :style (if @view-log? ;; {} ;; {:display "none"})} ;; [StaticTable ;; {:table-header [user-history-header ;; {;;:sort-keyword sort-keyword-logs ;; ;;:sort-reversed? sort-reversed-logs? ;; }] ;; :table-row (user-history-row)} ;; (sort-by :timestamp (:admin_event_log @current-user))]]) [TabContent {:toggle (r/cursor toggle [:orders-view])} [:div {:class "row"} [:div {:class "col-lg-12 col-xs-12"} [:div {:style {:margin-top "1em"}} [RefreshButton {:refresh-fn (fn [refreshing?] (get-user-orders (:id @current-user) refreshing?)) :refreshing? retrieving?}]] ;; Table of orders for current user [:div {:class "table-responsive" :style (when-not (> (count paginated-orders) 0) {:display "none"})} [DynamicTable {:current-item (r/atom {}) :tr-props-fn (constantly true) :sort-keyword sort-keyword :sort-reversed? sort-reversed? :table-vecs [["Status" :status :status] ["Courier" :courier_name :courier_name] ["Placed" :target_time_start #(unix-epoch->hrf (:target_time_start %))] ["Deadline" :target_time_end (fn [order] [:span {:style (when-not (contains? #{"complete" "cancelled"} (:status order)) (when (< (- (:target_time_end order) (now)) (* 60 60)) {:color "#d9534f"}))} (unix-epoch->hrf (:target_time_end order)) (when (:tire_pressure_check order) ;; http://www.flaticon.com/free-icon/car-wheel_75660#term=wheel&page=1&position=34 [:img {:src (str base-url "/images/car-wheel.png") :alt "tire-check"}])])] ["Completed" (fn [order] (cond (contains? #{"cancelled"} (:status order)) "Cancelled" (contains? #{"complete"} (:status order)) (unix-epoch->hrf (get-event-time (:event_log order) "complete")) :else "In-Progress")) (fn [order] [:span (when (contains? #{"complete"} (:status order)) (let [completed-time (get-event-time (:event_log order) "complete")] [:span {:style (when (> completed-time (:target_time_end order)) {:color "#d9534f"})} (unix-epoch->hrf completed-time)])) (when (contains? #{"cancelled"} (:status order)) "Cancelled") (when-not (contains? #{"complete" "cancelled"} (:status order)) "In-Progress")])] ["Order Address" :address_street (fn [order] [GoogleMapLink (str (:address_street order) ", " (:address_zip order)) (:lat order) (:lng order)])] ["Courier Rating" :number_rating (fn [order] (let [number-rating (:number_rating order)] (when number-rating [StarRating number-rating])))]]} paginated-orders]] [:div {:style (when-not (> (count paginated-orders) 0) {:display "none"})} [TablePager {:total-pages (count sorted-orders) :current-page current-page}]]]]] [TabContent {:toggle (r/cursor toggle [:convert-courier-view])} [:div {:class "row"} [:div {:class "col-lg-12 col-xs-12"} [:div {:style {:margin-top "1em"}} [courier-conversion @current-user]]]]]]])))) (defn search-users-results-panel "Display a table of selectable users with an indivdual user panel for the selected user" [users state] (let [current-user (r/cursor state [:current-user]) edit-user (r/cursor state [:edit-user]) sort-keyword (r/atom :timestamp_created) sort-reversed? (r/atom false) current-page (r/atom 1) recent-search-term (r/cursor state [:recent-search-term]) page-size 5] (fn [users] (let [sort-fn (if @sort-reversed? (partial sort-by @sort-keyword) (comp reverse (partial sort-by @sort-keyword))) sorted-users (fn [] (->> users sort-fn (partition-all page-size))) paginated-users (fn [] (-> (sorted-users) (nth (- @current-page 1) '()))) table-pager-on-click (fn [] (let [first-user (first (paginated-users))] (reset! current-user first-user)))] (when (nil? @current-user) (table-pager-on-click)) (reset-edit-user! edit-user current-user) ;; set the edit-user values to match those of current-user [:div {:class "panel panel-default"} [user-panel current-user state] [:h4 "Users matching - \"" [:strong {:style {:white-space "pre"}} @recent-search-term] "\""] [:div {:class "panel" :style {:margin-top "15px"}} [:div {:class "table-responsive"} [DynamicTable {:current-item current-user :tr-props-fn (fn [user current-user] (let [user-orders (fn [user] (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))))] {:class (when (= (:id user) (:id @current-user)) "active") :on-click (fn [_] (reset! current-user user) (reset! (r/cursor state [:alert-success]) "") (when (<= (count (user-orders user)) 0) (select-toggle-key! (r/cursor state [:tab-content-toggle]) :info-view)) (reset! (r/cursor state [:user-orders-current-page]) 1))})) :sort-keyword sort-keyword :sort-reversed? sort-reversed? :table-vecs [["Name" :name (fn [user] [UserCrossLink {:on-click (fn [] (user-cross-link-on-click (:id user)))} [:span {:style (when-not (= 0 (:subscription_id user)) {:color "#5cb85c"})} (:name user)]])] ["Market" (fn [user] (-> (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))) first :zone (quot 50) markets)) (fn [user] (-> (->> @datastore/orders (filter (fn [order] (= (:id user) (:user_id order))))) first :zone (quot 50) markets))] ["Orders" :orders_count :orders_count] ["Email" :email (fn [user] [Mailto (:email user)])] ["Phone" :phone_number (fn [user] [TelephoneNumber (:phone_number user)])] ["Card?" #(if (s/blank? (:stripe_default_card %)) "No" "Yes") #(if (s/blank? (:stripe_default_card %)) "No" "Yes")] ["Push?" #(if (s/blank? (:arn_endpoint %)) "No" "Yes") #(if (s/blank? (:arn_endpoint %)) "No" "Yes")] ["OS" :os :os] ["Version" :app_version :app_version] ["Joined" :timestamp_created #(unix-epoch->fmt (:timestamp_created %) "M/D/YYYY")]]} (paginated-users)]]] [TablePager {:total-pages (count (sorted-users)) :current-page current-page :on-click table-pager-on-click}]])))) (defn search-bar [state] (let [retrieving? (r/cursor state [:search-retrieving?]) search-results (r/cursor state [:search-results]) recent-search-term (r/cursor state [:recent-search-term]) search-term (r/cursor state [:search-term]) retrieve-results (fn [search-term] (retrieve-url (str base-url "search") "POST" (js/JSON.stringify (clj->js {:term search-term})) (partial xhrio-wrapper (fn [r] (let [response (js->clj r :keywordize-keys true)] (reset! retrieving? false) (reset! recent-search-term search-term) (reset! search-results response))))))] (fn [] [:div {:class "row"} [:div {:class "col-lg-6 col-xs-12"} [:form {:role "users-search"} [:div {:class "input-group"} [:input {:type "text" :class "form-control" :placeholder "Search Users" :on-change (fn [e] (reset! search-term (-> e (aget "target") (aget "value")))) :value @search-term}] [:div {:class "input-group-btn"} [:button {:class "btn btn-default" :type "submit" :on-click (fn [e] (.preventDefault e) (when-not (s/blank? @search-term) (reset! retrieving? true) (retrieve-results @search-term) (reset! (r/cursor state [:current-user]) nil) (reset! (r/cursor state [:current-order]) nil))) } [:i {:class "fa fa-search"}]]]]]]]))) (defn search-results "Display search results" [state] (fn [] (let [search-term (r/cursor state [:search-term]) retrieving? (r/cursor state [:search-retrieving?]) recent-search-term (r/cursor state [:recent-search-term]) search-results (r/cursor state [:search-results]) users-search-results (r/cursor search-results [:users])] [:div (when @retrieving? (.scrollTo js/window 0 0) [:h4 "Retrieving results for \"" [:strong {:style {:white-space "pre"}} @search-term] "\" " [ProcessingIcon]]) (when-not (nil? (and @search-term @recent-search-term)) [:div {:class "row" :id "search-results"} [:div {:class "col-lg-12 col-lg-12"} (when-not @retrieving? [:div (when (and (empty? @users-search-results) (not (s/blank? @recent-search-term)) (not @retrieving?)) [:div [:h4 "Your search - \"" [:strong {:style {:white-space "pre"}} @recent-search-term] \"" - did not match any users."]]) (when-not (empty? @users-search-results) [:div [search-users-results-panel @users-search-results state]])])]])]))) (defn cross-link-result "Retrieve and display user-id when clicked from an internal cross-link" [state] (fn [] (let [search-term (r/cursor state [:search-term]) recent-search-term (r/cursor state [:recent-search-term]) current-user (r/cursor state [:current-user]) retrieving? (r/cursor state [:cross-link-retrieving?]) ] [:div (when @retrieving? [:h4 "Retrieving user information " [:i {:class "fa fa-spinner fa-pulse" :style {:color "black"}}]]) (when (nil? (and @search-term @recent-search-term)) (when-not (nil? @current-user) [:div (when-not @retrieving? [user-panel current-user state])]))])))
[ { "context": "{ :doc \"Loading data into Riak\"\n :author \"Istvan Szukacs\" }\n riak-loader.core\n (:require \n [clojure.", "end": 674, "score": 0.9998978972434998, "start": 660, "tag": "NAME", "value": "Istvan Szukacs" } ]
src/riak_loader/core.clj
StreamBright/riak-loader
0
;; Copyright 2015 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 "Loading data into Riak" :author "Istvan Szukacs" } riak-loader.core (:require [clojure.java.io :as io ] [clojure.string :as cstr ] [clojure.tools.cli :as cli ] [clojure.tools.logging :as log ] [clojure.edn :as edn ] [cheshire.core :as ches ] [abracad.avro :as avro ] [clojure.core.async :refer [alts! chan go thread timeout >! >!! <! <!! go-loop] ] ) (:import [com.basho.riak.client.api RiakClient ] [com.basho.riak.client.core RiakNode$Builder RiakCluster$Builder ] [com.basho.riak.client.core.query Namespace Location RiakObject ] [com.basho.riak.client.api.commands.kv StoreValue StoreValue$Builder StoreValue$Option ] [com.basho.riak.client.api.cap Quorum ] [com.basho.riak.client.core.util BinaryValue ] [java.net InetSocketAddress ] [java.io File BufferedReader ] [clojure.lang PersistentArrayMap ] ) (:gen-class)) (defn read-file "Returns {:ok string } or {:error...}" ^PersistentArrayMap [^File file] (try (cond (.isFile file) {:ok (slurp file) } :else (throw (Exception. "Input is not a file"))) (catch Exception e {:error "Exception" :fn "read-file" :exception (.getMessage e) }))) (defn parse-edn-string "Returns {:ok {} } or {:error...}" ^PersistentArrayMap [^String s] (try {:ok (edn/read-string s)} (catch Exception e {:error "Exception" :fn "parse-config" :exception (.getMessage e)}))) (defn read-config "Reads the configuration file (app.edn) and returns the config as a hashmap" ^PersistentArrayMap [^String path] (let [ file-string (read-file (File. path)) ] (cond (contains? file-string :ok) ;if the file read is successful the content is sent to parse-edn-string ;that can return either and {:ok ...} or {:error ...} (parse-edn-string (file-string :ok)) :else ;keeping the original error and let it fall through file-string))) (defn exit ([^Long n] (log/info "init :: stop") (System/exit n)) ([^Long n ^String msg] (log/info msg) (log/info "init :: stop") (System/exit n))) ;; AVRO (defn lazy-avro "Returns a lazy sequence with the lines of an avro file" [^String file] (lazy-seq (avro/data-file-reader file))) ;; JSON (defn- lazy-helper "Processes a java.io.Reader lazily" [^BufferedReader reader] (lazy-seq (if-let [line (.readLine reader)] (cons line (lazy-helper reader)) (do (.close reader) nil)))) (defn lazy-json "Returns a lazy sequence with the lines of the file" [^String file] (lazy-helper (io/reader file))) ;; (defn riak-connect! "Connecting a Riak cluster" [host-port-list] (RiakClient/newClient (into-array (map #(InetSocketAddress. (first %) (Integer. (second %))) (map #(cstr/split % #":") host-port-list))))) (defn build-node-template "Budilgin Riak node template" [node-builder min-conn max-conn] (log/info (type node-builder)) (.withMaxConnections (.withMinConnections node-builder min-conn) max-conn)) (defn build-node "Building Riak node" [node-template host port] (.build (.withRemotePort (.withRemoteAddress node-template host) port))) (defn riak-connect2! "Connecting to a Riak cluster" [host-port-list] (let [ node-template (build-node-template (RiakNode$Builder.) 16 128) nodes (map #(build-node node-template (first %) (Integer. (second %))) (map #(cstr/split % #":") host-port-list)) cluster (.build (RiakCluster$Builder. nodes)) ] ;; return cluster)) (defn riak-store! "Storing a string in Riak" [riak-client riak-bucket riak-key riak-value] (let [ riak-object (RiakObject.) _ (.setValue (.setContentType riak-object "application/json") riak-value) store (.build (.withOption (.withLocation (StoreValue$Builder. riak-object) riak-key) StoreValue$Option/N_VAL (Integer. 1))) exx (.execute riak-client store) ] {:ok :ok})) (def blocking-producer >!!) (def blocking-consumer <!!) (def non-blocking-producer >!) (def non-blocking-consumer <!) (def cli-options ;; An option with a required argument [ ["-c" "--config CONFIG" "Config file name" :default "conf/app.edn"] ["-f" "--file FILE" "File to process" :default "/dev/null"] ["-t" "--type TYPE" "Upload type (patents, cpcs, entities..)" :default "patents"] ["-e" "--env ENV" "Environment (dev or prod)" :default "dev"] ["-s" "--serialization SER" "JSON or Avro" :default "json"] ["-h" "--help"] ]) (defn update-stats "Todo: add p50, p90, p99 with set atom" [counter result start-time] ;might not need do here, return {:ok :ok} (do (swap! counter inc) (cond (= (mod @counter 10000) 0) (do (let [ exec-time (with-precision 3 (/ (- (. System (nanoTime)) @start-time) 1000000000.0)) _ (reset! start-time (. System (nanoTime))) ] ;log stats (log/info (str " res: " result " count: " @counter " perf: " (int (/ 10000 exec-time)) " req/s" ))))))) (defn get-doc-key "Returns a Riak doc key string, example: xyz.json" [json-key doc] (let [json-keys (map #(get-in doc [ % ]) json-key)] (str (clojure.string/join "_" json-keys) ".json"))) (defn process-entry-avro "Takes an Avro entry and insert it to Riak as JSON" [entry json-key riak-client riak-bucket] ;;fixme (let [ doc-clj (ches/parse-string entry) doc-key (get-doc-key json-key doc-clj) riak-key (Location. riak-bucket doc-key) json-byte (.getBytes entry) riak-value (BinaryValue/unsafeCreate json-byte) _ (log/debug (str riak-client riak-bucket riak-key "riak-value")) ;returns {:ok ...} || {:err ...} could be checked _ (riak-store! riak-client riak-bucket riak-key riak-value)] {:ok :ok})) ;;fixme (defn process-entry-json "Takes a line (JSON string) and inserts it to Riak as JSON" [entry json-key riak-client riak-bucket] (let [ doc-clj (ches/parse-string entry) doc-key (get-doc-key json-key doc-clj) riak-key (Location. riak-bucket doc-key) json-byte (.getBytes entry) riak-value (BinaryValue/unsafeCreate json-byte) _ (log/debug (str riak-client riak-bucket riak-key "riak-value")) ;returns {:ok ...} || {:err ...} could be checked _ (riak-store! riak-client riak-bucket riak-key riak-value)] {:ok :ok})) (defn process-cli "Processing the cli arguments and options" [args cli-options] (let [ cli-options-parsed (cli/parse-opts args cli-options) {:keys [options arguments errors summary]} cli-options-parsed ] (cond (:help options) (exit 0) errors (exit 1) :else cli-options-parsed))) (defn process-config "Processing config with error handling" [file] ; Handle help and error conditions (let [config (read-config file)] (cond (or (empty? config) (:error config)) (exit 1 (str "Config cannot be read or parsed..." "\n" config)) :else config))) (defn process-serialization-option "Selecting serialization" [serialization input-file] (cond (= serialization :avro) {:seq (lazy-avro input-file) :proc process-entry-avro} (= serialization :json) {:seq (lazy-json input-file) :proc process-entry-json} :else (do (log/error (str "Unsupported serialization format: " serialization)) (exit 1)))) (defn -main [& args] (let [ ;; dealing with cli & config file cli-options-parsed (process-cli args cli-options) {:keys [options arguments errors summary]} cli-options-parsed config (process-config (:config options)) ;; wrapping out variables need for further execution env (keyword (:env options)) bucket-type (:type options) ;same as bucket-name _ (log/debug (str "bucket-type: " bucket-type)) bucket-name bucket-type json-key (get-in config [:ok :json-keys (keyword bucket-type)]) _ (log/debug (str "json-key: " json-key)) ;; On success it returns a lazy sequence that has the entries to be processed ;; and a matching processing function for that entry type serialization (keyword (:serialization options)) input-file (:file options) seq-and-proc (process-serialization-option serialization input-file) document-entries (:seq seq-and-proc) entry-processor (:proc seq-and-proc) riak-cluster (riak-connect2! (get-in config [:ok :env env :conn-string])) _ (.start riak-cluster) riak-client (RiakClient. riak-cluster) riak-bucket (Namespace. bucket-type bucket-name) stat-chan (chan) work-chan (chan) thread-count (get-in config [:ok :env env :thread-count]) thread-wait (get-in config [:ok :env env :thread-wait]) channel-timeout (get-in config [:ok :env env :channel-timeout]) counter (atom 0) start-time (atom (. System (nanoTime))) ] ;; TEST ;; (do (println "something") (exit 0)) ;; END TEST ;; creating N threads to insert data into Riak (dotimes [i thread-count] (thread (Thread/sleep thread-wait) (while true ;; this should be moves to a function and only the time measurement should be here ;; start ;; call into the function ;; stop (let [ entry (blocking-consumer work-chan) start (. System (nanoTime)) _ (entry-processor entry json-key riak-client riak-bucket) exec-time (with-precision 3 (/ (- (. System (nanoTime)) start) 1000000.0)) ] (blocking-producer stat-chan {:thread-name (.getName (Thread/currentThread)) :time exec-time}))))) ;; end of creating worker threads ;; start a thread that sends in json entries to the work-channel (thread (Thread/sleep 100) (doseq [entry document-entries] (blocking-producer work-chan entry))) ;; end of sending thread ;; main thread, blocks until timeout or all of the files are uploaded (while true (blocking-consumer (go (let [ [result source] (alts! [stat-chan (timeout channel-timeout)]) ] (if (= source stat-chan) (do ;(log/debug result) (update-stats counter result start-time)) ;else - timeout (do (log/info "Channel timed out. Stopping...") ;;shutdown riak (.shutdown riak-cluster) (exit 0))))))) ;;END ))
27527
;; Copyright 2015 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 "Loading data into Riak" :author "<NAME>" } riak-loader.core (:require [clojure.java.io :as io ] [clojure.string :as cstr ] [clojure.tools.cli :as cli ] [clojure.tools.logging :as log ] [clojure.edn :as edn ] [cheshire.core :as ches ] [abracad.avro :as avro ] [clojure.core.async :refer [alts! chan go thread timeout >! >!! <! <!! go-loop] ] ) (:import [com.basho.riak.client.api RiakClient ] [com.basho.riak.client.core RiakNode$Builder RiakCluster$Builder ] [com.basho.riak.client.core.query Namespace Location RiakObject ] [com.basho.riak.client.api.commands.kv StoreValue StoreValue$Builder StoreValue$Option ] [com.basho.riak.client.api.cap Quorum ] [com.basho.riak.client.core.util BinaryValue ] [java.net InetSocketAddress ] [java.io File BufferedReader ] [clojure.lang PersistentArrayMap ] ) (:gen-class)) (defn read-file "Returns {:ok string } or {:error...}" ^PersistentArrayMap [^File file] (try (cond (.isFile file) {:ok (slurp file) } :else (throw (Exception. "Input is not a file"))) (catch Exception e {:error "Exception" :fn "read-file" :exception (.getMessage e) }))) (defn parse-edn-string "Returns {:ok {} } or {:error...}" ^PersistentArrayMap [^String s] (try {:ok (edn/read-string s)} (catch Exception e {:error "Exception" :fn "parse-config" :exception (.getMessage e)}))) (defn read-config "Reads the configuration file (app.edn) and returns the config as a hashmap" ^PersistentArrayMap [^String path] (let [ file-string (read-file (File. path)) ] (cond (contains? file-string :ok) ;if the file read is successful the content is sent to parse-edn-string ;that can return either and {:ok ...} or {:error ...} (parse-edn-string (file-string :ok)) :else ;keeping the original error and let it fall through file-string))) (defn exit ([^Long n] (log/info "init :: stop") (System/exit n)) ([^Long n ^String msg] (log/info msg) (log/info "init :: stop") (System/exit n))) ;; AVRO (defn lazy-avro "Returns a lazy sequence with the lines of an avro file" [^String file] (lazy-seq (avro/data-file-reader file))) ;; JSON (defn- lazy-helper "Processes a java.io.Reader lazily" [^BufferedReader reader] (lazy-seq (if-let [line (.readLine reader)] (cons line (lazy-helper reader)) (do (.close reader) nil)))) (defn lazy-json "Returns a lazy sequence with the lines of the file" [^String file] (lazy-helper (io/reader file))) ;; (defn riak-connect! "Connecting a Riak cluster" [host-port-list] (RiakClient/newClient (into-array (map #(InetSocketAddress. (first %) (Integer. (second %))) (map #(cstr/split % #":") host-port-list))))) (defn build-node-template "Budilgin Riak node template" [node-builder min-conn max-conn] (log/info (type node-builder)) (.withMaxConnections (.withMinConnections node-builder min-conn) max-conn)) (defn build-node "Building Riak node" [node-template host port] (.build (.withRemotePort (.withRemoteAddress node-template host) port))) (defn riak-connect2! "Connecting to a Riak cluster" [host-port-list] (let [ node-template (build-node-template (RiakNode$Builder.) 16 128) nodes (map #(build-node node-template (first %) (Integer. (second %))) (map #(cstr/split % #":") host-port-list)) cluster (.build (RiakCluster$Builder. nodes)) ] ;; return cluster)) (defn riak-store! "Storing a string in Riak" [riak-client riak-bucket riak-key riak-value] (let [ riak-object (RiakObject.) _ (.setValue (.setContentType riak-object "application/json") riak-value) store (.build (.withOption (.withLocation (StoreValue$Builder. riak-object) riak-key) StoreValue$Option/N_VAL (Integer. 1))) exx (.execute riak-client store) ] {:ok :ok})) (def blocking-producer >!!) (def blocking-consumer <!!) (def non-blocking-producer >!) (def non-blocking-consumer <!) (def cli-options ;; An option with a required argument [ ["-c" "--config CONFIG" "Config file name" :default "conf/app.edn"] ["-f" "--file FILE" "File to process" :default "/dev/null"] ["-t" "--type TYPE" "Upload type (patents, cpcs, entities..)" :default "patents"] ["-e" "--env ENV" "Environment (dev or prod)" :default "dev"] ["-s" "--serialization SER" "JSON or Avro" :default "json"] ["-h" "--help"] ]) (defn update-stats "Todo: add p50, p90, p99 with set atom" [counter result start-time] ;might not need do here, return {:ok :ok} (do (swap! counter inc) (cond (= (mod @counter 10000) 0) (do (let [ exec-time (with-precision 3 (/ (- (. System (nanoTime)) @start-time) 1000000000.0)) _ (reset! start-time (. System (nanoTime))) ] ;log stats (log/info (str " res: " result " count: " @counter " perf: " (int (/ 10000 exec-time)) " req/s" ))))))) (defn get-doc-key "Returns a Riak doc key string, example: xyz.json" [json-key doc] (let [json-keys (map #(get-in doc [ % ]) json-key)] (str (clojure.string/join "_" json-keys) ".json"))) (defn process-entry-avro "Takes an Avro entry and insert it to Riak as JSON" [entry json-key riak-client riak-bucket] ;;fixme (let [ doc-clj (ches/parse-string entry) doc-key (get-doc-key json-key doc-clj) riak-key (Location. riak-bucket doc-key) json-byte (.getBytes entry) riak-value (BinaryValue/unsafeCreate json-byte) _ (log/debug (str riak-client riak-bucket riak-key "riak-value")) ;returns {:ok ...} || {:err ...} could be checked _ (riak-store! riak-client riak-bucket riak-key riak-value)] {:ok :ok})) ;;fixme (defn process-entry-json "Takes a line (JSON string) and inserts it to Riak as JSON" [entry json-key riak-client riak-bucket] (let [ doc-clj (ches/parse-string entry) doc-key (get-doc-key json-key doc-clj) riak-key (Location. riak-bucket doc-key) json-byte (.getBytes entry) riak-value (BinaryValue/unsafeCreate json-byte) _ (log/debug (str riak-client riak-bucket riak-key "riak-value")) ;returns {:ok ...} || {:err ...} could be checked _ (riak-store! riak-client riak-bucket riak-key riak-value)] {:ok :ok})) (defn process-cli "Processing the cli arguments and options" [args cli-options] (let [ cli-options-parsed (cli/parse-opts args cli-options) {:keys [options arguments errors summary]} cli-options-parsed ] (cond (:help options) (exit 0) errors (exit 1) :else cli-options-parsed))) (defn process-config "Processing config with error handling" [file] ; Handle help and error conditions (let [config (read-config file)] (cond (or (empty? config) (:error config)) (exit 1 (str "Config cannot be read or parsed..." "\n" config)) :else config))) (defn process-serialization-option "Selecting serialization" [serialization input-file] (cond (= serialization :avro) {:seq (lazy-avro input-file) :proc process-entry-avro} (= serialization :json) {:seq (lazy-json input-file) :proc process-entry-json} :else (do (log/error (str "Unsupported serialization format: " serialization)) (exit 1)))) (defn -main [& args] (let [ ;; dealing with cli & config file cli-options-parsed (process-cli args cli-options) {:keys [options arguments errors summary]} cli-options-parsed config (process-config (:config options)) ;; wrapping out variables need for further execution env (keyword (:env options)) bucket-type (:type options) ;same as bucket-name _ (log/debug (str "bucket-type: " bucket-type)) bucket-name bucket-type json-key (get-in config [:ok :json-keys (keyword bucket-type)]) _ (log/debug (str "json-key: " json-key)) ;; On success it returns a lazy sequence that has the entries to be processed ;; and a matching processing function for that entry type serialization (keyword (:serialization options)) input-file (:file options) seq-and-proc (process-serialization-option serialization input-file) document-entries (:seq seq-and-proc) entry-processor (:proc seq-and-proc) riak-cluster (riak-connect2! (get-in config [:ok :env env :conn-string])) _ (.start riak-cluster) riak-client (RiakClient. riak-cluster) riak-bucket (Namespace. bucket-type bucket-name) stat-chan (chan) work-chan (chan) thread-count (get-in config [:ok :env env :thread-count]) thread-wait (get-in config [:ok :env env :thread-wait]) channel-timeout (get-in config [:ok :env env :channel-timeout]) counter (atom 0) start-time (atom (. System (nanoTime))) ] ;; TEST ;; (do (println "something") (exit 0)) ;; END TEST ;; creating N threads to insert data into Riak (dotimes [i thread-count] (thread (Thread/sleep thread-wait) (while true ;; this should be moves to a function and only the time measurement should be here ;; start ;; call into the function ;; stop (let [ entry (blocking-consumer work-chan) start (. System (nanoTime)) _ (entry-processor entry json-key riak-client riak-bucket) exec-time (with-precision 3 (/ (- (. System (nanoTime)) start) 1000000.0)) ] (blocking-producer stat-chan {:thread-name (.getName (Thread/currentThread)) :time exec-time}))))) ;; end of creating worker threads ;; start a thread that sends in json entries to the work-channel (thread (Thread/sleep 100) (doseq [entry document-entries] (blocking-producer work-chan entry))) ;; end of sending thread ;; main thread, blocks until timeout or all of the files are uploaded (while true (blocking-consumer (go (let [ [result source] (alts! [stat-chan (timeout channel-timeout)]) ] (if (= source stat-chan) (do ;(log/debug result) (update-stats counter result start-time)) ;else - timeout (do (log/info "Channel timed out. Stopping...") ;;shutdown riak (.shutdown riak-cluster) (exit 0))))))) ;;END ))
true
;; Copyright 2015 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 "Loading data into Riak" :author "PI:NAME:<NAME>END_PI" } riak-loader.core (:require [clojure.java.io :as io ] [clojure.string :as cstr ] [clojure.tools.cli :as cli ] [clojure.tools.logging :as log ] [clojure.edn :as edn ] [cheshire.core :as ches ] [abracad.avro :as avro ] [clojure.core.async :refer [alts! chan go thread timeout >! >!! <! <!! go-loop] ] ) (:import [com.basho.riak.client.api RiakClient ] [com.basho.riak.client.core RiakNode$Builder RiakCluster$Builder ] [com.basho.riak.client.core.query Namespace Location RiakObject ] [com.basho.riak.client.api.commands.kv StoreValue StoreValue$Builder StoreValue$Option ] [com.basho.riak.client.api.cap Quorum ] [com.basho.riak.client.core.util BinaryValue ] [java.net InetSocketAddress ] [java.io File BufferedReader ] [clojure.lang PersistentArrayMap ] ) (:gen-class)) (defn read-file "Returns {:ok string } or {:error...}" ^PersistentArrayMap [^File file] (try (cond (.isFile file) {:ok (slurp file) } :else (throw (Exception. "Input is not a file"))) (catch Exception e {:error "Exception" :fn "read-file" :exception (.getMessage e) }))) (defn parse-edn-string "Returns {:ok {} } or {:error...}" ^PersistentArrayMap [^String s] (try {:ok (edn/read-string s)} (catch Exception e {:error "Exception" :fn "parse-config" :exception (.getMessage e)}))) (defn read-config "Reads the configuration file (app.edn) and returns the config as a hashmap" ^PersistentArrayMap [^String path] (let [ file-string (read-file (File. path)) ] (cond (contains? file-string :ok) ;if the file read is successful the content is sent to parse-edn-string ;that can return either and {:ok ...} or {:error ...} (parse-edn-string (file-string :ok)) :else ;keeping the original error and let it fall through file-string))) (defn exit ([^Long n] (log/info "init :: stop") (System/exit n)) ([^Long n ^String msg] (log/info msg) (log/info "init :: stop") (System/exit n))) ;; AVRO (defn lazy-avro "Returns a lazy sequence with the lines of an avro file" [^String file] (lazy-seq (avro/data-file-reader file))) ;; JSON (defn- lazy-helper "Processes a java.io.Reader lazily" [^BufferedReader reader] (lazy-seq (if-let [line (.readLine reader)] (cons line (lazy-helper reader)) (do (.close reader) nil)))) (defn lazy-json "Returns a lazy sequence with the lines of the file" [^String file] (lazy-helper (io/reader file))) ;; (defn riak-connect! "Connecting a Riak cluster" [host-port-list] (RiakClient/newClient (into-array (map #(InetSocketAddress. (first %) (Integer. (second %))) (map #(cstr/split % #":") host-port-list))))) (defn build-node-template "Budilgin Riak node template" [node-builder min-conn max-conn] (log/info (type node-builder)) (.withMaxConnections (.withMinConnections node-builder min-conn) max-conn)) (defn build-node "Building Riak node" [node-template host port] (.build (.withRemotePort (.withRemoteAddress node-template host) port))) (defn riak-connect2! "Connecting to a Riak cluster" [host-port-list] (let [ node-template (build-node-template (RiakNode$Builder.) 16 128) nodes (map #(build-node node-template (first %) (Integer. (second %))) (map #(cstr/split % #":") host-port-list)) cluster (.build (RiakCluster$Builder. nodes)) ] ;; return cluster)) (defn riak-store! "Storing a string in Riak" [riak-client riak-bucket riak-key riak-value] (let [ riak-object (RiakObject.) _ (.setValue (.setContentType riak-object "application/json") riak-value) store (.build (.withOption (.withLocation (StoreValue$Builder. riak-object) riak-key) StoreValue$Option/N_VAL (Integer. 1))) exx (.execute riak-client store) ] {:ok :ok})) (def blocking-producer >!!) (def blocking-consumer <!!) (def non-blocking-producer >!) (def non-blocking-consumer <!) (def cli-options ;; An option with a required argument [ ["-c" "--config CONFIG" "Config file name" :default "conf/app.edn"] ["-f" "--file FILE" "File to process" :default "/dev/null"] ["-t" "--type TYPE" "Upload type (patents, cpcs, entities..)" :default "patents"] ["-e" "--env ENV" "Environment (dev or prod)" :default "dev"] ["-s" "--serialization SER" "JSON or Avro" :default "json"] ["-h" "--help"] ]) (defn update-stats "Todo: add p50, p90, p99 with set atom" [counter result start-time] ;might not need do here, return {:ok :ok} (do (swap! counter inc) (cond (= (mod @counter 10000) 0) (do (let [ exec-time (with-precision 3 (/ (- (. System (nanoTime)) @start-time) 1000000000.0)) _ (reset! start-time (. System (nanoTime))) ] ;log stats (log/info (str " res: " result " count: " @counter " perf: " (int (/ 10000 exec-time)) " req/s" ))))))) (defn get-doc-key "Returns a Riak doc key string, example: xyz.json" [json-key doc] (let [json-keys (map #(get-in doc [ % ]) json-key)] (str (clojure.string/join "_" json-keys) ".json"))) (defn process-entry-avro "Takes an Avro entry and insert it to Riak as JSON" [entry json-key riak-client riak-bucket] ;;fixme (let [ doc-clj (ches/parse-string entry) doc-key (get-doc-key json-key doc-clj) riak-key (Location. riak-bucket doc-key) json-byte (.getBytes entry) riak-value (BinaryValue/unsafeCreate json-byte) _ (log/debug (str riak-client riak-bucket riak-key "riak-value")) ;returns {:ok ...} || {:err ...} could be checked _ (riak-store! riak-client riak-bucket riak-key riak-value)] {:ok :ok})) ;;fixme (defn process-entry-json "Takes a line (JSON string) and inserts it to Riak as JSON" [entry json-key riak-client riak-bucket] (let [ doc-clj (ches/parse-string entry) doc-key (get-doc-key json-key doc-clj) riak-key (Location. riak-bucket doc-key) json-byte (.getBytes entry) riak-value (BinaryValue/unsafeCreate json-byte) _ (log/debug (str riak-client riak-bucket riak-key "riak-value")) ;returns {:ok ...} || {:err ...} could be checked _ (riak-store! riak-client riak-bucket riak-key riak-value)] {:ok :ok})) (defn process-cli "Processing the cli arguments and options" [args cli-options] (let [ cli-options-parsed (cli/parse-opts args cli-options) {:keys [options arguments errors summary]} cli-options-parsed ] (cond (:help options) (exit 0) errors (exit 1) :else cli-options-parsed))) (defn process-config "Processing config with error handling" [file] ; Handle help and error conditions (let [config (read-config file)] (cond (or (empty? config) (:error config)) (exit 1 (str "Config cannot be read or parsed..." "\n" config)) :else config))) (defn process-serialization-option "Selecting serialization" [serialization input-file] (cond (= serialization :avro) {:seq (lazy-avro input-file) :proc process-entry-avro} (= serialization :json) {:seq (lazy-json input-file) :proc process-entry-json} :else (do (log/error (str "Unsupported serialization format: " serialization)) (exit 1)))) (defn -main [& args] (let [ ;; dealing with cli & config file cli-options-parsed (process-cli args cli-options) {:keys [options arguments errors summary]} cli-options-parsed config (process-config (:config options)) ;; wrapping out variables need for further execution env (keyword (:env options)) bucket-type (:type options) ;same as bucket-name _ (log/debug (str "bucket-type: " bucket-type)) bucket-name bucket-type json-key (get-in config [:ok :json-keys (keyword bucket-type)]) _ (log/debug (str "json-key: " json-key)) ;; On success it returns a lazy sequence that has the entries to be processed ;; and a matching processing function for that entry type serialization (keyword (:serialization options)) input-file (:file options) seq-and-proc (process-serialization-option serialization input-file) document-entries (:seq seq-and-proc) entry-processor (:proc seq-and-proc) riak-cluster (riak-connect2! (get-in config [:ok :env env :conn-string])) _ (.start riak-cluster) riak-client (RiakClient. riak-cluster) riak-bucket (Namespace. bucket-type bucket-name) stat-chan (chan) work-chan (chan) thread-count (get-in config [:ok :env env :thread-count]) thread-wait (get-in config [:ok :env env :thread-wait]) channel-timeout (get-in config [:ok :env env :channel-timeout]) counter (atom 0) start-time (atom (. System (nanoTime))) ] ;; TEST ;; (do (println "something") (exit 0)) ;; END TEST ;; creating N threads to insert data into Riak (dotimes [i thread-count] (thread (Thread/sleep thread-wait) (while true ;; this should be moves to a function and only the time measurement should be here ;; start ;; call into the function ;; stop (let [ entry (blocking-consumer work-chan) start (. System (nanoTime)) _ (entry-processor entry json-key riak-client riak-bucket) exec-time (with-precision 3 (/ (- (. System (nanoTime)) start) 1000000.0)) ] (blocking-producer stat-chan {:thread-name (.getName (Thread/currentThread)) :time exec-time}))))) ;; end of creating worker threads ;; start a thread that sends in json entries to the work-channel (thread (Thread/sleep 100) (doseq [entry document-entries] (blocking-producer work-chan entry))) ;; end of sending thread ;; main thread, blocks until timeout or all of the files are uploaded (while true (blocking-consumer (go (let [ [result source] (alts! [stat-chan (timeout channel-timeout)]) ] (if (= source stat-chan) (do ;(log/debug result) (update-stats counter result start-time)) ;else - timeout (do (log/info "Channel timed out. Stopping...") ;;shutdown riak (.shutdown riak-cluster) (exit 0))))))) ;;END ))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998080730438232, "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.9998129606246948, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/properties_view.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.properties-view (:require [clojure.string :as string] [dynamo.graph :as g] [editor.dialogs :as dialogs] [editor.ui :as ui] [editor.ui.fuzzy-combo-box :as fuzzy-combo-box] [editor.jfx :as jfx] [editor.types :as types] [editor.properties :as properties] [editor.workspace :as workspace] [editor.resource :as resource] [editor.math :as math] [editor.field-expression :as field-expression] [util.id-vec :as iv] [util.profiler :as profiler]) (:import [javafx.geometry Insets Point2D] [javafx.scene Node Parent] [javafx.scene.control Control Button CheckBox ColorPicker Label Slider TextField TextInputControl ToggleButton Tooltip TitledPane TextArea TreeItem Menu MenuItem MenuBar Tab ProgressBar] [javafx.scene.input MouseEvent] [javafx.scene.layout Pane AnchorPane GridPane HBox VBox Priority ColumnConstraints Region] [javafx.scene.paint Color] [javafx.util Duration] [editor.properties CurveSpread Curve])) (set! *warn-on-reflection* true) (def ^{:private true :const true} grid-hgap 4) (def ^{:private true :const true} grid-vgap 6) (def ^{:private true :const true} all-available 5000) (declare update-field-message) (defn- update-multi-text-fn [texts format-fn get-fns values message read-only?] (update-field-message texts message) (doseq [[^TextInputControl text get-fn] (map vector texts get-fns)] (doto text (ui/text! (format-fn (properties/unify-values (map get-fn values)))) (ui/editable! (not read-only?))) (if (ui/focus? text) (.selectAll text) (.home text)))) (defn- update-text-fn ([^TextInputControl text format-fn values message read-only?] (update-text-fn text format-fn identity values message read-only?)) ([^TextInputControl text format-fn get-fn values message read-only?] (update-multi-text-fn [text] format-fn [get-fn] values message read-only?))) (defn edit-type->type [edit-type] (or (some-> edit-type :type g/value-type-dispatch-value) (:type edit-type))) (defn- select-all-on-click! [^TextInputControl t] (doto t ;; Filter is necessary because the listener will be called after the text field has received focus, i.e. too late (.addEventFilter MouseEvent/MOUSE_PRESSED (ui/event-handler e (when (not (ui/focus? t)) (.deselect t) (ui/user-data! t ::selection-at-focus true)))) ;; Filter is necessary because the TextArea captures the event (.addEventFilter MouseEvent/MOUSE_RELEASED (ui/event-handler e (when (ui/user-data t ::selection-at-focus) (when (string/blank? (.getSelectedText t)) (.consume e) (ui/run-later (.selectAll t)))) (ui/user-data! t ::selection-at-focus nil))))) (defmulti customize! (fn [control update-fn] (class control))) (defmethod customize! TextField [^TextField t update-fn] (doto t (GridPane/setHgrow Priority/ALWAYS) (ui/on-action! update-fn) (ui/auto-commit! update-fn) (select-all-on-click!))) (defmethod customize! TextArea [^TextArea t update-fn] (doto t (GridPane/setHgrow Priority/ALWAYS) (ui/auto-commit! update-fn) (select-all-on-click!))) (defmulti create-property-control! (fn [edit-type _ property-fn] (edit-type->type edit-type))) (defmethod create-property-control! g/Str [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text str) update-fn (fn [_] (properties/set-values! (property-fn) (repeat (.getText text))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Int [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text field-expression/format-int) update-fn (fn [_] (if-let [v (field-expression/to-int (.getText text))] (let [property (property-fn)] (properties/set-values! property (repeat v)) (update-ui-fn (properties/values property) (properties/validation-message property) (properties/read-only? property)))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Num [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text field-expression/format-number) update-fn (fn [_] (if-let [v (field-expression/to-double (.getText text))] (properties/set-values! (property-fn) (repeat v)) (update-ui-fn (properties/values (property-fn)) (properties/validation-message (property-fn)) (properties/read-only? (property-fn)))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Bool [_ _ property-fn] (let [check (CheckBox.) update-ui-fn (fn [values message read-only?] (let [v (properties/unify-values values)] (if (nil? v) (.setIndeterminate check true) (doto check (.setIndeterminate false) (.setSelected v)))) (update-field-message [check] message) (ui/editable! check (not read-only?)))] (ui/on-action! check (fn [_] (properties/set-values! (property-fn) (repeat (.isSelected check))))) [check update-ui-fn])) (defn- create-grid-pane ^GridPane [ctrls] (let [box (doto (GridPane.) (ui/add-style! "property-component") (ui/children! ctrls))] (doall (map-indexed (fn [idx c] (GridPane/setConstraints c idx 0)) ctrls)) box)) (defn- create-multi-textfield! [labels property-fn] (let [text-fields (mapv (fn [_] (TextField.)) labels) box (doto (GridPane.) (.setHgap grid-hgap)) get-fns (map-indexed (fn [i _] #(nth % i)) text-fields) update-ui-fn (partial update-multi-text-fn text-fields field-expression/format-number get-fns)] (doseq [[t f] (map-indexed (fn [i t] [t (fn [_] (let [v (field-expression/to-double (.getText ^TextField t)) current-vals (properties/values (property-fn))] (if v (properties/set-values! (property-fn) (mapv #(assoc (vec %) i v) current-vals)) (update-ui-fn current-vals (properties/validation-message (property-fn)) (properties/read-only? (property-fn))))))]) text-fields)] (customize! t f)) (doall (map-indexed (fn [idx [^TextField t label]] (let [children (cond-> [] (seq label) (conj (doto (Label. label) (.setMinWidth Region/USE_PREF_SIZE))) true (conj t)) comp (doto (create-grid-pane children) (GridPane/setConstraints idx 0) (GridPane/setHgrow Priority/ALWAYS))] (ui/add-child! box comp))) (map vector text-fields labels))) [box update-ui-fn])) (defmethod create-property-control! types/Vec2 [edit-type _ property-fn] (let [{:keys [labels] :or {labels ["X" "Y"]}} edit-type] (create-multi-textfield! labels property-fn))) (defmethod create-property-control! types/Vec3 [edit-type _ property-fn] (let [{:keys [labels] :or {labels ["X" "Y" "Z"]}} edit-type] (create-multi-textfield! labels property-fn))) (defmethod create-property-control! types/Vec4 [_ _ property-fn] (create-multi-textfield! ["X" "Y" "Z" "W"] property-fn)) (defn- create-multi-keyed-textfield! [fields property-fn] (let [text-fields (mapv (fn [_] (TextField.)) fields) box (doto (GridPane.) (.setPrefWidth Double/MAX_VALUE)) get-fns (map (fn [f] (or (:get-fn f) #(get-in % (:path f)))) fields) update-ui-fn (partial update-multi-text-fn text-fields field-expression/format-number get-fns)] (doseq [[t f] (map (fn [f t] (let [set-fn (or (:set-fn f) (fn [e v] (assoc-in e (:path f) v)))] [t (fn [_] (let [v (field-expression/to-double (.getText ^TextField t)) current-vals (properties/values (property-fn))] (if v (properties/set-values! (property-fn) (mapv #(set-fn % v) current-vals)) (update-ui-fn current-vals (properties/validation-message (property-fn)) (properties/read-only? (property-fn))))))])) fields text-fields)] (customize! t f)) (doall (map-indexed (fn [idx [^TextField t f]] (let [children (cond-> [] (:label f) (conj (doto (Label. (:label f)) (.setMinWidth Region/USE_PREF_SIZE))) (:control f) (conj (doto ^Control (:control f) (.setMinWidth Region/USE_PREF_SIZE))) true (conj t)) ^GridPane comp (doto (create-grid-pane children) (GridPane/setConstraints idx 0) (GridPane/setHgrow Priority/ALWAYS))] (ui/add-child! box comp))) (map vector text-fields fields))) [box update-ui-fn])) (def ^:private ^:dynamic *programmatic-setting* nil) (defn- make-curve-toggler ^ToggleButton [property-fn] (let [^ToggleButton toggle-button (doto (ToggleButton. nil (jfx/get-image-view "icons/32/Icons_X_03_Bezier.png" 12.0)) (ui/add-styles! ["embedded-properties-button"]))] (doto toggle-button (ui/on-action! (fn [_] (let [selected (.isSelected toggle-button) vals (mapv (fn [curve] (let [v (-> curve properties/curve-vals first)] (assoc curve :points (iv/iv-vec (cond-> [v] selected (conj (assoc v 0 1.0))))))) (properties/values (property-fn)))] (properties/set-values! (property-fn) vals))))))) (defmethod create-property-control! CurveSpread [_ _ property-fn] (let [^ToggleButton toggle-button (make-curve-toggler property-fn) fields [{:get-fn (fn [c] (second (first (properties/curve-vals c)))) :set-fn (fn [c v] (properties/->curve-spread [[0.0 v 1.0 0.0]] (:spread c))) :control toggle-button} {:label "+/-" :path [:spread]}] [^HBox box update-ui-fn] (create-multi-keyed-textfield! fields property-fn) ^TextField text-field (some #(and (instance? TextField %) %) (.getChildren ^HBox (first (.getChildren box)))) update-ui-fn (fn [values message read-only?] (update-ui-fn values message read-only?) (let [curved? (boolean (< 1 (count (properties/curve-vals (first values)))))] (.setSelected toggle-button curved?) (ui/editable! toggle-button (some? (first values))) (ui/disable! text-field curved?)))] [box update-ui-fn])) (defmethod create-property-control! Curve [_ _ property-fn] (let [^ToggleButton toggle-button (make-curve-toggler property-fn) fields [{:get-fn (fn [c] (second (first (properties/curve-vals c)))) :set-fn (fn [c v] (properties/->curve [[0.0 v 1.0 0.0]])) :control toggle-button}] [^HBox box update-ui-fn] (create-multi-keyed-textfield! fields property-fn) ^TextField text-field (some #(and (instance? TextField %) %) (.getChildren ^HBox (first (.getChildren box)))) update-ui-fn (fn [values message read-only?] (update-ui-fn values message read-only?) (let [curved? (boolean (< 1 (count (properties/curve-vals (first values)))))] (.setSelected toggle-button curved?) (ui/editable! toggle-button (some? (first values))) (ui/disable! text-field curved?)))] [box update-ui-fn])) (defmethod create-property-control! types/Color [edit-type _ property-fn] (let [color-picker (doto (ColorPicker.) (.setPrefWidth Double/MAX_VALUE)) update-ui-fn (fn [values message read-only?] (let [v (properties/unify-values values)] (if (nil? v) (.setValue color-picker nil) (let [[r g b a] v] (.setValue color-picker (Color. r g b a))))) (update-field-message [color-picker] message) (ui/editable! color-picker (not read-only?)))] (ui/on-action! color-picker (fn [_] (let [^Color c (.getValue color-picker) v [(.getRed c) (.getGreen c) (.getBlue c) (.getOpacity c)] values (if (:ignore-alpha? edit-type) (map #(assoc %1 3 %2) (repeat v) (map last (properties/values (property-fn)))) (repeat v))] (properties/set-values! (property-fn) values)))) [color-picker update-ui-fn])) (defmethod create-property-control! :choicebox [{:keys [options]} _ property-fn] (let [combo-box (fuzzy-combo-box/make options) update-ui-fn (fn [values message read-only?] (binding [*programmatic-setting* true] (fuzzy-combo-box/set-value! combo-box (properties/unify-values values)) (update-field-message [combo-box] message) (ui/disable! combo-box read-only?))) listen-fn (fn [_old-val new-val] (when-not *programmatic-setting* (properties/set-values! (property-fn) (repeat new-val)) (ui/user-data! (ui/main-scene) ::ui/refresh-requested? true)))] (fuzzy-combo-box/observe! combo-box listen-fn) [combo-box update-ui-fn])) (defmethod create-property-control! resource/Resource [edit-type {:keys [workspace project]} property-fn] (let [box (GridPane.) browse-button (doto (Button. "\u2026") ; "..." (HORIZONTAL ELLIPSIS) (.setPrefWidth 26) (ui/add-style! "button-small")) open-button (doto (Button. "" (jfx/get-image-view "icons/32/Icons_S_14_linkarrow.png" 16)) (.setMaxWidth 26) (ui/add-style! "button-small")) text (TextField.) dialog-opts (if (:ext edit-type) {:ext (:ext edit-type)} {}) update-ui-fn (fn [values message read-only?] (update-text-fn text str (fn [v] (when v (resource/proj-path v))) values message read-only?) (let [val (properties/unify-values values)] (ui/editable! browse-button (not read-only?)) (ui/editable! open-button (and (resource/openable-resource? val) (resource/exists? val))))) commit-fn (fn [_] (let [path (ui/text text) resource (workspace/resolve-workspace-resource workspace path)] (properties/set-values! (property-fn) (repeat resource))))] (ui/add-style! box "composite-property-control-container") (ui/on-action! browse-button (fn [_] (when-let [resource (first (dialogs/make-resource-dialog workspace project dialog-opts))] (properties/set-values! (property-fn) (repeat resource))))) (ui/on-action! open-button (fn [_] (when-let [resource (-> (property-fn) properties/values properties/unify-values)] (ui/run-command open-button :open {:resources [resource]})))) (customize! text commit-fn) (ui/children! box [text browse-button open-button]) (GridPane/setConstraints text 0 0) (GridPane/setConstraints open-button 1 0) (GridPane/setConstraints browse-button 2 0) ; Merge the facing borders of the open and browse buttons. (GridPane/setMargin open-button (Insets. 0 -1 0 0)) (.setOnMousePressed open-button (ui/event-handler _ (.toFront open-button))) (.setOnMousePressed browse-button (ui/event-handler _ (.toFront browse-button))) (doto (.. box getColumnConstraints) (.add (doto (ColumnConstraints.) (.setPrefWidth all-available) (.setHgrow Priority/ALWAYS))) (.add (doto (ColumnConstraints.) (.setMinWidth ColumnConstraints/CONSTRAIN_TO_PREF) (.setHgrow Priority/NEVER))) (.add (doto (ColumnConstraints.) (.setMinWidth ColumnConstraints/CONSTRAIN_TO_PREF) (.setHgrow Priority/NEVER)))) [box update-ui-fn])) (defmethod create-property-control! :slider [edit-type context property-fn] (let [box (doto (GridPane.) (.setHgap grid-hgap)) [^TextField textfield tf-update-ui-fn] (create-property-control! {:type g/Num} context property-fn) min (:min edit-type 0.0) max (:max edit-type 1.0) val (:value edit-type max) precision (:precision edit-type) slider (Slider. min max val) update-ui-fn (fn [values message read-only?] (tf-update-ui-fn values message read-only?) (binding [*programmatic-setting* true] (if-let [v (properties/unify-values values)] (doto slider (.setDisable false) (.setValue v)) (.setDisable slider true)) (update-field-message [slider] message) (ui/editable! slider (not read-only?))))] (.setPrefColumnCount textfield (if precision (count (str precision)) 5)) (.addEventFilter slider MouseEvent/MOUSE_PRESSED (ui/event-handler event (ui/user-data! slider ::op-seq (gensym)))) (ui/observe (.valueProperty slider) (fn [observable old-val new-val] (when-not *programmatic-setting* (let [val (if precision (math/round-with-precision new-val precision) new-val)] (properties/set-values! (property-fn) (repeat val) (ui/user-data slider ::op-seq)))))) (ui/children! box [textfield slider]) (GridPane/setConstraints textfield 0 0) (GridPane/setConstraints slider 1 0) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setPercentWidth 20)))) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setPercentWidth 80)))) [box update-ui-fn])) (defmethod create-property-control! :multi-line-text [_ _ property-fn] (let [text (doto (TextArea.) (ui/add-style! "property") (.setMinHeight 68)) update-ui-fn (partial update-text-fn text str) update-fn #(properties/set-values! (property-fn) (repeat (.getText text)))] (ui/bind-key! text "Shortcut+Enter" update-fn) (customize! text (fn [_] (update-fn))) [text update-ui-fn])) (defmethod create-property-control! :default [_ _ _] (let [text (TextField.) wrapper (doto (HBox.) (.setPrefWidth Double/MAX_VALUE)) update-ui-fn (partial update-text-fn text str)] (HBox/setHgrow text Priority/ALWAYS) (ui/children! wrapper [text]) (.setDisable text true) [wrapper update-ui-fn])) (defn- node-screen-coords ^Point2D [^Node node ^Point2D offset] (let [scene (.getScene node) window (.getWindow scene) window-coords (Point2D. (.getX window) (.getY window)) scene-coords (Point2D. (.getX scene) (.getY scene)) node-coords (.localToScene node (.getX offset) (.getY offset))] (.add node-coords (.add scene-coords window-coords)))) (def ^:private severity-tooltip-style-map {:fatal "tooltip-error" :warning "tooltip-warning" :info "tooltip-info"}) (defn- show-message-tooltip [^Node control] (when-let [tip (ui/user-data control ::field-message)] ;; FIXME: Hack to position tooltip somewhat below control so .show doesn't immediately trigger an :exit. (let [tooltip (Tooltip. (:message tip)) control-bounds (.getLayoutBounds control) tooltip-coords (node-screen-coords control (Point2D. 0.0 (+ (.getHeight control-bounds) 11.0)))] (ui/add-style! tooltip (severity-tooltip-style-map (:severity tip))) (ui/user-data! control ::tooltip tooltip) (.show tooltip control (.getX tooltip-coords) (.getY tooltip-coords))))) (defn- hide-message-tooltip [control] (when-let [tooltip ^Tooltip (ui/user-data control ::tooltip)] (ui/user-data! control ::tooltip nil) (.hide tooltip))) (defn- update-message-tooltip [control] (when (ui/user-data control ::tooltip) (hide-message-tooltip control) (show-message-tooltip control))) (defn- install-tooltip-message [ctrl msg] (ui/user-data! ctrl ::field-message msg) (ui/on-mouse! ctrl (when msg (fn [verb e] (condp = verb :enter (show-message-tooltip ctrl) :exit (hide-message-tooltip ctrl) :move nil))))) (def ^:private severity-field-style-map {:fatal "field-error" :warning "field-warning" :info "field-info"}) (defn- update-field-message-style [ctrl msg] (if msg (ui/add-style! ctrl (severity-field-style-map (:severity msg))) (ui/remove-styles! ctrl (vals severity-field-style-map)))) (defn- update-field-message [ctrls msg] (doseq [ctrl ctrls] (install-tooltip-message ctrl msg) (update-field-message-style ctrl msg) (if msg (update-message-tooltip ctrl) (hide-message-tooltip ctrl)))) (defn- create-property-label [label key] (doto (Label. label) (.setTooltip (doto (Tooltip.) (.setText (format "Available as `%s` in editor scripts" (string/replace (name key) \- \_))) (.setHideDelay Duration/ZERO) (.setShowDuration (Duration/seconds 30)))) (ui/add-style! "property-label") (.setMinWidth Label/USE_PREF_SIZE) (.setMinHeight 28.0))) (defn- create-properties-row [context ^GridPane grid key property row property-fn] (let [^Label label (create-property-label (properties/label property) key) [^Node control update-ctrl-fn] (create-property-control! (:edit-type property) context (fn [] (property-fn key))) reset-btn (doto (Button. nil (jfx/get-image-view "icons/32/Icons_S_02_Reset.png")) (ui/add-styles! ["clear-button" "button-small"]) (ui/on-action! (fn [_] (properties/clear-override! (property-fn key)) (ui/suppress-auto-commit! control) (.requestFocus control)))) label-box (let [box (GridPane.)] (GridPane/setFillWidth label true) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setHgrow Priority/ALWAYS)))) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setHgrow Priority/NEVER)))) box) update-label-box (fn [overridden?] (if overridden? (do (ui/children! label-box [label reset-btn]) (GridPane/setConstraints label 0 0) (GridPane/setConstraints reset-btn 1 0)) (do (ui/children! label-box [label]) (GridPane/setConstraints label 0 0)))) update-ui-fn (fn [property] (let [overridden? (properties/overridden? property) f (if overridden? ui/add-style! ui/remove-style!)] (doseq [c [label control]] (f c "overridden")) (update-label-box overridden?) (update-ctrl-fn (properties/values property) (properties/validation-message property) (properties/read-only? property))))] (update-label-box (properties/overridden? property)) (GridPane/setConstraints label-box 0 row) (GridPane/setConstraints control 1 row) (.add (.getChildren grid) label-box) (.add (.getChildren grid) control) (GridPane/setFillWidth label-box true) (GridPane/setFillWidth control true) [key update-ui-fn])) (defn- create-properties [context grid properties property-fn] ; TODO - add multi-selection support for properties view (doall (map-indexed (fn [row [key property]] (create-properties-row context grid key property row property-fn)) properties))) (defn- make-grid [parent context properties property-fn] (let [grid (doto (GridPane.) (.setHgap grid-hgap) (.setVgap grid-vgap)) cc1 (doto (ColumnConstraints.) (.setHgrow Priority/NEVER)) cc2 (doto (ColumnConstraints.) (.setHgrow Priority/ALWAYS) (.setPrefWidth all-available))] (.. grid getColumnConstraints (add cc1)) (.. grid getColumnConstraints (add cc2)) (ui/add-child! parent grid) (ui/add-style! grid "form") (create-properties context grid properties property-fn))) (defn- create-category-label [label] (doto (Label. label) (ui/add-style! "property-category"))) (defn- make-pane! [parent context properties] (let [vbox (doto (VBox. (double 10.0)) (.setId "properties-view-pane") (.setPadding (Insets. 10 10 10 10)) (.setFillWidth true) (AnchorPane/setBottomAnchor 0.0) (AnchorPane/setLeftAnchor 0.0) (AnchorPane/setRightAnchor 0.0) (AnchorPane/setTopAnchor 0.0))] (let [property-fn (fn [key] (let [properties (:properties (ui/user-data vbox ::properties))] (get properties key))) display-order (:display-order properties) properties (:properties properties) generics [nil (mapv (fn [k] [k (get properties k)]) (filter (comp not properties/category?) display-order))] categories (mapv (fn [order] [(first order) (mapv (fn [k] [k (get properties k)]) (rest order))]) (filter properties/category? display-order)) update-fns (loop [sections (cons generics categories) result []] (if-let [[category properties] (first sections)] (let [update-fns (if (empty? properties) [] (do (when category (let [label (create-category-label category)] (ui/add-child! vbox label))) (make-grid vbox context properties property-fn)))] (recur (rest sections) (into result update-fns))) result))] ; NOTE: Note update-fns is a sequence of [[property-key update-ui-fn] ...] (ui/user-data! parent ::update-fns (into {} update-fns))) (ui/children! parent [vbox]) vbox)) (defn- refresh-pane! [^Parent parent properties] (let [pane (.lookup parent "#properties-view-pane") update-fns (ui/user-data parent ::update-fns) prev-properties (:properties (ui/user-data pane ::properties))] (ui/user-data! pane ::properties properties) (doseq [[key property] (:properties properties) ;; Only update the UI when the props actually differ ;; Differing :edit-type's would have recreated the UI so no need to compare them here :when (not= (dissoc property :edit-type) (dissoc (get prev-properties key) :edit-type))] (when-let [update-ui-fn (get update-fns key)] (update-ui-fn property))))) (def ^:private ephemeral-edit-type-fields [:from-type :to-type :set-fn]) (defn- edit-type->template [edit-type] (apply dissoc edit-type ephemeral-edit-type-fields)) (defn- properties->template [properties] (mapv (fn [[k v]] [k (edit-type->template (:edit-type v))]) (:properties properties))) (defn- update-pane! [parent context properties] ; NOTE: We cache the ui based on the ::template and ::properties user-data (profiler/profile "properties" "update-pane" (let [properties (properties/coalesce properties) template (properties->template properties) prev-template (ui/user-data parent ::template)] (when (not= template prev-template) (make-pane! parent context properties) (ui/user-data! parent ::template template)) (refresh-pane! parent properties)))) (g/defnode PropertiesView (property parent-view Parent) (property workspace g/Any) (property project g/Any) (input selected-node-properties g/Any) (output pane Pane :cached (g/fnk [parent-view workspace project selected-node-properties] (let [context {:workspace workspace :project project}] ;; Collecting the properties and then updating the view takes some time, but has no immediacy ;; This is effectively time-slicing it over two "frames" (or whenever JavaFX decides to run the second part) (ui/run-later (update-pane! parent-view context selected-node-properties)))))) (defn make-properties-view [workspace project app-view view-graph ^Node parent] (let [view-id (g/make-node! view-graph PropertiesView :parent-view parent :workspace workspace :project project) stage (.. parent getScene getWindow)] (g/connect! app-view :selected-node-properties view-id :selected-node-properties) view-id))
102901
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 <NAME>, <NAME> ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.properties-view (:require [clojure.string :as string] [dynamo.graph :as g] [editor.dialogs :as dialogs] [editor.ui :as ui] [editor.ui.fuzzy-combo-box :as fuzzy-combo-box] [editor.jfx :as jfx] [editor.types :as types] [editor.properties :as properties] [editor.workspace :as workspace] [editor.resource :as resource] [editor.math :as math] [editor.field-expression :as field-expression] [util.id-vec :as iv] [util.profiler :as profiler]) (:import [javafx.geometry Insets Point2D] [javafx.scene Node Parent] [javafx.scene.control Control Button CheckBox ColorPicker Label Slider TextField TextInputControl ToggleButton Tooltip TitledPane TextArea TreeItem Menu MenuItem MenuBar Tab ProgressBar] [javafx.scene.input MouseEvent] [javafx.scene.layout Pane AnchorPane GridPane HBox VBox Priority ColumnConstraints Region] [javafx.scene.paint Color] [javafx.util Duration] [editor.properties CurveSpread Curve])) (set! *warn-on-reflection* true) (def ^{:private true :const true} grid-hgap 4) (def ^{:private true :const true} grid-vgap 6) (def ^{:private true :const true} all-available 5000) (declare update-field-message) (defn- update-multi-text-fn [texts format-fn get-fns values message read-only?] (update-field-message texts message) (doseq [[^TextInputControl text get-fn] (map vector texts get-fns)] (doto text (ui/text! (format-fn (properties/unify-values (map get-fn values)))) (ui/editable! (not read-only?))) (if (ui/focus? text) (.selectAll text) (.home text)))) (defn- update-text-fn ([^TextInputControl text format-fn values message read-only?] (update-text-fn text format-fn identity values message read-only?)) ([^TextInputControl text format-fn get-fn values message read-only?] (update-multi-text-fn [text] format-fn [get-fn] values message read-only?))) (defn edit-type->type [edit-type] (or (some-> edit-type :type g/value-type-dispatch-value) (:type edit-type))) (defn- select-all-on-click! [^TextInputControl t] (doto t ;; Filter is necessary because the listener will be called after the text field has received focus, i.e. too late (.addEventFilter MouseEvent/MOUSE_PRESSED (ui/event-handler e (when (not (ui/focus? t)) (.deselect t) (ui/user-data! t ::selection-at-focus true)))) ;; Filter is necessary because the TextArea captures the event (.addEventFilter MouseEvent/MOUSE_RELEASED (ui/event-handler e (when (ui/user-data t ::selection-at-focus) (when (string/blank? (.getSelectedText t)) (.consume e) (ui/run-later (.selectAll t)))) (ui/user-data! t ::selection-at-focus nil))))) (defmulti customize! (fn [control update-fn] (class control))) (defmethod customize! TextField [^TextField t update-fn] (doto t (GridPane/setHgrow Priority/ALWAYS) (ui/on-action! update-fn) (ui/auto-commit! update-fn) (select-all-on-click!))) (defmethod customize! TextArea [^TextArea t update-fn] (doto t (GridPane/setHgrow Priority/ALWAYS) (ui/auto-commit! update-fn) (select-all-on-click!))) (defmulti create-property-control! (fn [edit-type _ property-fn] (edit-type->type edit-type))) (defmethod create-property-control! g/Str [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text str) update-fn (fn [_] (properties/set-values! (property-fn) (repeat (.getText text))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Int [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text field-expression/format-int) update-fn (fn [_] (if-let [v (field-expression/to-int (.getText text))] (let [property (property-fn)] (properties/set-values! property (repeat v)) (update-ui-fn (properties/values property) (properties/validation-message property) (properties/read-only? property)))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Num [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text field-expression/format-number) update-fn (fn [_] (if-let [v (field-expression/to-double (.getText text))] (properties/set-values! (property-fn) (repeat v)) (update-ui-fn (properties/values (property-fn)) (properties/validation-message (property-fn)) (properties/read-only? (property-fn)))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Bool [_ _ property-fn] (let [check (CheckBox.) update-ui-fn (fn [values message read-only?] (let [v (properties/unify-values values)] (if (nil? v) (.setIndeterminate check true) (doto check (.setIndeterminate false) (.setSelected v)))) (update-field-message [check] message) (ui/editable! check (not read-only?)))] (ui/on-action! check (fn [_] (properties/set-values! (property-fn) (repeat (.isSelected check))))) [check update-ui-fn])) (defn- create-grid-pane ^GridPane [ctrls] (let [box (doto (GridPane.) (ui/add-style! "property-component") (ui/children! ctrls))] (doall (map-indexed (fn [idx c] (GridPane/setConstraints c idx 0)) ctrls)) box)) (defn- create-multi-textfield! [labels property-fn] (let [text-fields (mapv (fn [_] (TextField.)) labels) box (doto (GridPane.) (.setHgap grid-hgap)) get-fns (map-indexed (fn [i _] #(nth % i)) text-fields) update-ui-fn (partial update-multi-text-fn text-fields field-expression/format-number get-fns)] (doseq [[t f] (map-indexed (fn [i t] [t (fn [_] (let [v (field-expression/to-double (.getText ^TextField t)) current-vals (properties/values (property-fn))] (if v (properties/set-values! (property-fn) (mapv #(assoc (vec %) i v) current-vals)) (update-ui-fn current-vals (properties/validation-message (property-fn)) (properties/read-only? (property-fn))))))]) text-fields)] (customize! t f)) (doall (map-indexed (fn [idx [^TextField t label]] (let [children (cond-> [] (seq label) (conj (doto (Label. label) (.setMinWidth Region/USE_PREF_SIZE))) true (conj t)) comp (doto (create-grid-pane children) (GridPane/setConstraints idx 0) (GridPane/setHgrow Priority/ALWAYS))] (ui/add-child! box comp))) (map vector text-fields labels))) [box update-ui-fn])) (defmethod create-property-control! types/Vec2 [edit-type _ property-fn] (let [{:keys [labels] :or {labels ["X" "Y"]}} edit-type] (create-multi-textfield! labels property-fn))) (defmethod create-property-control! types/Vec3 [edit-type _ property-fn] (let [{:keys [labels] :or {labels ["X" "Y" "Z"]}} edit-type] (create-multi-textfield! labels property-fn))) (defmethod create-property-control! types/Vec4 [_ _ property-fn] (create-multi-textfield! ["X" "Y" "Z" "W"] property-fn)) (defn- create-multi-keyed-textfield! [fields property-fn] (let [text-fields (mapv (fn [_] (TextField.)) fields) box (doto (GridPane.) (.setPrefWidth Double/MAX_VALUE)) get-fns (map (fn [f] (or (:get-fn f) #(get-in % (:path f)))) fields) update-ui-fn (partial update-multi-text-fn text-fields field-expression/format-number get-fns)] (doseq [[t f] (map (fn [f t] (let [set-fn (or (:set-fn f) (fn [e v] (assoc-in e (:path f) v)))] [t (fn [_] (let [v (field-expression/to-double (.getText ^TextField t)) current-vals (properties/values (property-fn))] (if v (properties/set-values! (property-fn) (mapv #(set-fn % v) current-vals)) (update-ui-fn current-vals (properties/validation-message (property-fn)) (properties/read-only? (property-fn))))))])) fields text-fields)] (customize! t f)) (doall (map-indexed (fn [idx [^TextField t f]] (let [children (cond-> [] (:label f) (conj (doto (Label. (:label f)) (.setMinWidth Region/USE_PREF_SIZE))) (:control f) (conj (doto ^Control (:control f) (.setMinWidth Region/USE_PREF_SIZE))) true (conj t)) ^GridPane comp (doto (create-grid-pane children) (GridPane/setConstraints idx 0) (GridPane/setHgrow Priority/ALWAYS))] (ui/add-child! box comp))) (map vector text-fields fields))) [box update-ui-fn])) (def ^:private ^:dynamic *programmatic-setting* nil) (defn- make-curve-toggler ^ToggleButton [property-fn] (let [^ToggleButton toggle-button (doto (ToggleButton. nil (jfx/get-image-view "icons/32/Icons_X_03_Bezier.png" 12.0)) (ui/add-styles! ["embedded-properties-button"]))] (doto toggle-button (ui/on-action! (fn [_] (let [selected (.isSelected toggle-button) vals (mapv (fn [curve] (let [v (-> curve properties/curve-vals first)] (assoc curve :points (iv/iv-vec (cond-> [v] selected (conj (assoc v 0 1.0))))))) (properties/values (property-fn)))] (properties/set-values! (property-fn) vals))))))) (defmethod create-property-control! CurveSpread [_ _ property-fn] (let [^ToggleButton toggle-button (make-curve-toggler property-fn) fields [{:get-fn (fn [c] (second (first (properties/curve-vals c)))) :set-fn (fn [c v] (properties/->curve-spread [[0.0 v 1.0 0.0]] (:spread c))) :control toggle-button} {:label "+/-" :path [:spread]}] [^HBox box update-ui-fn] (create-multi-keyed-textfield! fields property-fn) ^TextField text-field (some #(and (instance? TextField %) %) (.getChildren ^HBox (first (.getChildren box)))) update-ui-fn (fn [values message read-only?] (update-ui-fn values message read-only?) (let [curved? (boolean (< 1 (count (properties/curve-vals (first values)))))] (.setSelected toggle-button curved?) (ui/editable! toggle-button (some? (first values))) (ui/disable! text-field curved?)))] [box update-ui-fn])) (defmethod create-property-control! Curve [_ _ property-fn] (let [^ToggleButton toggle-button (make-curve-toggler property-fn) fields [{:get-fn (fn [c] (second (first (properties/curve-vals c)))) :set-fn (fn [c v] (properties/->curve [[0.0 v 1.0 0.0]])) :control toggle-button}] [^HBox box update-ui-fn] (create-multi-keyed-textfield! fields property-fn) ^TextField text-field (some #(and (instance? TextField %) %) (.getChildren ^HBox (first (.getChildren box)))) update-ui-fn (fn [values message read-only?] (update-ui-fn values message read-only?) (let [curved? (boolean (< 1 (count (properties/curve-vals (first values)))))] (.setSelected toggle-button curved?) (ui/editable! toggle-button (some? (first values))) (ui/disable! text-field curved?)))] [box update-ui-fn])) (defmethod create-property-control! types/Color [edit-type _ property-fn] (let [color-picker (doto (ColorPicker.) (.setPrefWidth Double/MAX_VALUE)) update-ui-fn (fn [values message read-only?] (let [v (properties/unify-values values)] (if (nil? v) (.setValue color-picker nil) (let [[r g b a] v] (.setValue color-picker (Color. r g b a))))) (update-field-message [color-picker] message) (ui/editable! color-picker (not read-only?)))] (ui/on-action! color-picker (fn [_] (let [^Color c (.getValue color-picker) v [(.getRed c) (.getGreen c) (.getBlue c) (.getOpacity c)] values (if (:ignore-alpha? edit-type) (map #(assoc %1 3 %2) (repeat v) (map last (properties/values (property-fn)))) (repeat v))] (properties/set-values! (property-fn) values)))) [color-picker update-ui-fn])) (defmethod create-property-control! :choicebox [{:keys [options]} _ property-fn] (let [combo-box (fuzzy-combo-box/make options) update-ui-fn (fn [values message read-only?] (binding [*programmatic-setting* true] (fuzzy-combo-box/set-value! combo-box (properties/unify-values values)) (update-field-message [combo-box] message) (ui/disable! combo-box read-only?))) listen-fn (fn [_old-val new-val] (when-not *programmatic-setting* (properties/set-values! (property-fn) (repeat new-val)) (ui/user-data! (ui/main-scene) ::ui/refresh-requested? true)))] (fuzzy-combo-box/observe! combo-box listen-fn) [combo-box update-ui-fn])) (defmethod create-property-control! resource/Resource [edit-type {:keys [workspace project]} property-fn] (let [box (GridPane.) browse-button (doto (Button. "\u2026") ; "..." (HORIZONTAL ELLIPSIS) (.setPrefWidth 26) (ui/add-style! "button-small")) open-button (doto (Button. "" (jfx/get-image-view "icons/32/Icons_S_14_linkarrow.png" 16)) (.setMaxWidth 26) (ui/add-style! "button-small")) text (TextField.) dialog-opts (if (:ext edit-type) {:ext (:ext edit-type)} {}) update-ui-fn (fn [values message read-only?] (update-text-fn text str (fn [v] (when v (resource/proj-path v))) values message read-only?) (let [val (properties/unify-values values)] (ui/editable! browse-button (not read-only?)) (ui/editable! open-button (and (resource/openable-resource? val) (resource/exists? val))))) commit-fn (fn [_] (let [path (ui/text text) resource (workspace/resolve-workspace-resource workspace path)] (properties/set-values! (property-fn) (repeat resource))))] (ui/add-style! box "composite-property-control-container") (ui/on-action! browse-button (fn [_] (when-let [resource (first (dialogs/make-resource-dialog workspace project dialog-opts))] (properties/set-values! (property-fn) (repeat resource))))) (ui/on-action! open-button (fn [_] (when-let [resource (-> (property-fn) properties/values properties/unify-values)] (ui/run-command open-button :open {:resources [resource]})))) (customize! text commit-fn) (ui/children! box [text browse-button open-button]) (GridPane/setConstraints text 0 0) (GridPane/setConstraints open-button 1 0) (GridPane/setConstraints browse-button 2 0) ; Merge the facing borders of the open and browse buttons. (GridPane/setMargin open-button (Insets. 0 -1 0 0)) (.setOnMousePressed open-button (ui/event-handler _ (.toFront open-button))) (.setOnMousePressed browse-button (ui/event-handler _ (.toFront browse-button))) (doto (.. box getColumnConstraints) (.add (doto (ColumnConstraints.) (.setPrefWidth all-available) (.setHgrow Priority/ALWAYS))) (.add (doto (ColumnConstraints.) (.setMinWidth ColumnConstraints/CONSTRAIN_TO_PREF) (.setHgrow Priority/NEVER))) (.add (doto (ColumnConstraints.) (.setMinWidth ColumnConstraints/CONSTRAIN_TO_PREF) (.setHgrow Priority/NEVER)))) [box update-ui-fn])) (defmethod create-property-control! :slider [edit-type context property-fn] (let [box (doto (GridPane.) (.setHgap grid-hgap)) [^TextField textfield tf-update-ui-fn] (create-property-control! {:type g/Num} context property-fn) min (:min edit-type 0.0) max (:max edit-type 1.0) val (:value edit-type max) precision (:precision edit-type) slider (Slider. min max val) update-ui-fn (fn [values message read-only?] (tf-update-ui-fn values message read-only?) (binding [*programmatic-setting* true] (if-let [v (properties/unify-values values)] (doto slider (.setDisable false) (.setValue v)) (.setDisable slider true)) (update-field-message [slider] message) (ui/editable! slider (not read-only?))))] (.setPrefColumnCount textfield (if precision (count (str precision)) 5)) (.addEventFilter slider MouseEvent/MOUSE_PRESSED (ui/event-handler event (ui/user-data! slider ::op-seq (gensym)))) (ui/observe (.valueProperty slider) (fn [observable old-val new-val] (when-not *programmatic-setting* (let [val (if precision (math/round-with-precision new-val precision) new-val)] (properties/set-values! (property-fn) (repeat val) (ui/user-data slider ::op-seq)))))) (ui/children! box [textfield slider]) (GridPane/setConstraints textfield 0 0) (GridPane/setConstraints slider 1 0) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setPercentWidth 20)))) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setPercentWidth 80)))) [box update-ui-fn])) (defmethod create-property-control! :multi-line-text [_ _ property-fn] (let [text (doto (TextArea.) (ui/add-style! "property") (.setMinHeight 68)) update-ui-fn (partial update-text-fn text str) update-fn #(properties/set-values! (property-fn) (repeat (.getText text)))] (ui/bind-key! text "Shortcut+Enter" update-fn) (customize! text (fn [_] (update-fn))) [text update-ui-fn])) (defmethod create-property-control! :default [_ _ _] (let [text (TextField.) wrapper (doto (HBox.) (.setPrefWidth Double/MAX_VALUE)) update-ui-fn (partial update-text-fn text str)] (HBox/setHgrow text Priority/ALWAYS) (ui/children! wrapper [text]) (.setDisable text true) [wrapper update-ui-fn])) (defn- node-screen-coords ^Point2D [^Node node ^Point2D offset] (let [scene (.getScene node) window (.getWindow scene) window-coords (Point2D. (.getX window) (.getY window)) scene-coords (Point2D. (.getX scene) (.getY scene)) node-coords (.localToScene node (.getX offset) (.getY offset))] (.add node-coords (.add scene-coords window-coords)))) (def ^:private severity-tooltip-style-map {:fatal "tooltip-error" :warning "tooltip-warning" :info "tooltip-info"}) (defn- show-message-tooltip [^Node control] (when-let [tip (ui/user-data control ::field-message)] ;; FIXME: Hack to position tooltip somewhat below control so .show doesn't immediately trigger an :exit. (let [tooltip (Tooltip. (:message tip)) control-bounds (.getLayoutBounds control) tooltip-coords (node-screen-coords control (Point2D. 0.0 (+ (.getHeight control-bounds) 11.0)))] (ui/add-style! tooltip (severity-tooltip-style-map (:severity tip))) (ui/user-data! control ::tooltip tooltip) (.show tooltip control (.getX tooltip-coords) (.getY tooltip-coords))))) (defn- hide-message-tooltip [control] (when-let [tooltip ^Tooltip (ui/user-data control ::tooltip)] (ui/user-data! control ::tooltip nil) (.hide tooltip))) (defn- update-message-tooltip [control] (when (ui/user-data control ::tooltip) (hide-message-tooltip control) (show-message-tooltip control))) (defn- install-tooltip-message [ctrl msg] (ui/user-data! ctrl ::field-message msg) (ui/on-mouse! ctrl (when msg (fn [verb e] (condp = verb :enter (show-message-tooltip ctrl) :exit (hide-message-tooltip ctrl) :move nil))))) (def ^:private severity-field-style-map {:fatal "field-error" :warning "field-warning" :info "field-info"}) (defn- update-field-message-style [ctrl msg] (if msg (ui/add-style! ctrl (severity-field-style-map (:severity msg))) (ui/remove-styles! ctrl (vals severity-field-style-map)))) (defn- update-field-message [ctrls msg] (doseq [ctrl ctrls] (install-tooltip-message ctrl msg) (update-field-message-style ctrl msg) (if msg (update-message-tooltip ctrl) (hide-message-tooltip ctrl)))) (defn- create-property-label [label key] (doto (Label. label) (.setTooltip (doto (Tooltip.) (.setText (format "Available as `%s` in editor scripts" (string/replace (name key) \- \_))) (.setHideDelay Duration/ZERO) (.setShowDuration (Duration/seconds 30)))) (ui/add-style! "property-label") (.setMinWidth Label/USE_PREF_SIZE) (.setMinHeight 28.0))) (defn- create-properties-row [context ^GridPane grid key property row property-fn] (let [^Label label (create-property-label (properties/label property) key) [^Node control update-ctrl-fn] (create-property-control! (:edit-type property) context (fn [] (property-fn key))) reset-btn (doto (Button. nil (jfx/get-image-view "icons/32/Icons_S_02_Reset.png")) (ui/add-styles! ["clear-button" "button-small"]) (ui/on-action! (fn [_] (properties/clear-override! (property-fn key)) (ui/suppress-auto-commit! control) (.requestFocus control)))) label-box (let [box (GridPane.)] (GridPane/setFillWidth label true) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setHgrow Priority/ALWAYS)))) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setHgrow Priority/NEVER)))) box) update-label-box (fn [overridden?] (if overridden? (do (ui/children! label-box [label reset-btn]) (GridPane/setConstraints label 0 0) (GridPane/setConstraints reset-btn 1 0)) (do (ui/children! label-box [label]) (GridPane/setConstraints label 0 0)))) update-ui-fn (fn [property] (let [overridden? (properties/overridden? property) f (if overridden? ui/add-style! ui/remove-style!)] (doseq [c [label control]] (f c "overridden")) (update-label-box overridden?) (update-ctrl-fn (properties/values property) (properties/validation-message property) (properties/read-only? property))))] (update-label-box (properties/overridden? property)) (GridPane/setConstraints label-box 0 row) (GridPane/setConstraints control 1 row) (.add (.getChildren grid) label-box) (.add (.getChildren grid) control) (GridPane/setFillWidth label-box true) (GridPane/setFillWidth control true) [key update-ui-fn])) (defn- create-properties [context grid properties property-fn] ; TODO - add multi-selection support for properties view (doall (map-indexed (fn [row [key property]] (create-properties-row context grid key property row property-fn)) properties))) (defn- make-grid [parent context properties property-fn] (let [grid (doto (GridPane.) (.setHgap grid-hgap) (.setVgap grid-vgap)) cc1 (doto (ColumnConstraints.) (.setHgrow Priority/NEVER)) cc2 (doto (ColumnConstraints.) (.setHgrow Priority/ALWAYS) (.setPrefWidth all-available))] (.. grid getColumnConstraints (add cc1)) (.. grid getColumnConstraints (add cc2)) (ui/add-child! parent grid) (ui/add-style! grid "form") (create-properties context grid properties property-fn))) (defn- create-category-label [label] (doto (Label. label) (ui/add-style! "property-category"))) (defn- make-pane! [parent context properties] (let [vbox (doto (VBox. (double 10.0)) (.setId "properties-view-pane") (.setPadding (Insets. 10 10 10 10)) (.setFillWidth true) (AnchorPane/setBottomAnchor 0.0) (AnchorPane/setLeftAnchor 0.0) (AnchorPane/setRightAnchor 0.0) (AnchorPane/setTopAnchor 0.0))] (let [property-fn (fn [key] (let [properties (:properties (ui/user-data vbox ::properties))] (get properties key))) display-order (:display-order properties) properties (:properties properties) generics [nil (mapv (fn [k] [k (get properties k)]) (filter (comp not properties/category?) display-order))] categories (mapv (fn [order] [(first order) (mapv (fn [k] [k (get properties k)]) (rest order))]) (filter properties/category? display-order)) update-fns (loop [sections (cons generics categories) result []] (if-let [[category properties] (first sections)] (let [update-fns (if (empty? properties) [] (do (when category (let [label (create-category-label category)] (ui/add-child! vbox label))) (make-grid vbox context properties property-fn)))] (recur (rest sections) (into result update-fns))) result))] ; NOTE: Note update-fns is a sequence of [[property-key update-ui-fn] ...] (ui/user-data! parent ::update-fns (into {} update-fns))) (ui/children! parent [vbox]) vbox)) (defn- refresh-pane! [^Parent parent properties] (let [pane (.lookup parent "#properties-view-pane") update-fns (ui/user-data parent ::update-fns) prev-properties (:properties (ui/user-data pane ::properties))] (ui/user-data! pane ::properties properties) (doseq [[key property] (:properties properties) ;; Only update the UI when the props actually differ ;; Differing :edit-type's would have recreated the UI so no need to compare them here :when (not= (dissoc property :edit-type) (dissoc (get prev-properties key) :edit-type))] (when-let [update-ui-fn (get update-fns key)] (update-ui-fn property))))) (def ^:private ephemeral-edit-type-fields [:from-type :to-type :set-fn]) (defn- edit-type->template [edit-type] (apply dissoc edit-type ephemeral-edit-type-fields)) (defn- properties->template [properties] (mapv (fn [[k v]] [k (edit-type->template (:edit-type v))]) (:properties properties))) (defn- update-pane! [parent context properties] ; NOTE: We cache the ui based on the ::template and ::properties user-data (profiler/profile "properties" "update-pane" (let [properties (properties/coalesce properties) template (properties->template properties) prev-template (ui/user-data parent ::template)] (when (not= template prev-template) (make-pane! parent context properties) (ui/user-data! parent ::template template)) (refresh-pane! parent properties)))) (g/defnode PropertiesView (property parent-view Parent) (property workspace g/Any) (property project g/Any) (input selected-node-properties g/Any) (output pane Pane :cached (g/fnk [parent-view workspace project selected-node-properties] (let [context {:workspace workspace :project project}] ;; Collecting the properties and then updating the view takes some time, but has no immediacy ;; This is effectively time-slicing it over two "frames" (or whenever JavaFX decides to run the second part) (ui/run-later (update-pane! parent-view context selected-node-properties)))))) (defn make-properties-view [workspace project app-view view-graph ^Node parent] (let [view-id (g/make-node! view-graph PropertiesView :parent-view parent :workspace workspace :project project) stage (.. parent getScene getWindow)] (g/connect! app-view :selected-node-properties view-id :selected-node-properties) view-id))
true
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.properties-view (:require [clojure.string :as string] [dynamo.graph :as g] [editor.dialogs :as dialogs] [editor.ui :as ui] [editor.ui.fuzzy-combo-box :as fuzzy-combo-box] [editor.jfx :as jfx] [editor.types :as types] [editor.properties :as properties] [editor.workspace :as workspace] [editor.resource :as resource] [editor.math :as math] [editor.field-expression :as field-expression] [util.id-vec :as iv] [util.profiler :as profiler]) (:import [javafx.geometry Insets Point2D] [javafx.scene Node Parent] [javafx.scene.control Control Button CheckBox ColorPicker Label Slider TextField TextInputControl ToggleButton Tooltip TitledPane TextArea TreeItem Menu MenuItem MenuBar Tab ProgressBar] [javafx.scene.input MouseEvent] [javafx.scene.layout Pane AnchorPane GridPane HBox VBox Priority ColumnConstraints Region] [javafx.scene.paint Color] [javafx.util Duration] [editor.properties CurveSpread Curve])) (set! *warn-on-reflection* true) (def ^{:private true :const true} grid-hgap 4) (def ^{:private true :const true} grid-vgap 6) (def ^{:private true :const true} all-available 5000) (declare update-field-message) (defn- update-multi-text-fn [texts format-fn get-fns values message read-only?] (update-field-message texts message) (doseq [[^TextInputControl text get-fn] (map vector texts get-fns)] (doto text (ui/text! (format-fn (properties/unify-values (map get-fn values)))) (ui/editable! (not read-only?))) (if (ui/focus? text) (.selectAll text) (.home text)))) (defn- update-text-fn ([^TextInputControl text format-fn values message read-only?] (update-text-fn text format-fn identity values message read-only?)) ([^TextInputControl text format-fn get-fn values message read-only?] (update-multi-text-fn [text] format-fn [get-fn] values message read-only?))) (defn edit-type->type [edit-type] (or (some-> edit-type :type g/value-type-dispatch-value) (:type edit-type))) (defn- select-all-on-click! [^TextInputControl t] (doto t ;; Filter is necessary because the listener will be called after the text field has received focus, i.e. too late (.addEventFilter MouseEvent/MOUSE_PRESSED (ui/event-handler e (when (not (ui/focus? t)) (.deselect t) (ui/user-data! t ::selection-at-focus true)))) ;; Filter is necessary because the TextArea captures the event (.addEventFilter MouseEvent/MOUSE_RELEASED (ui/event-handler e (when (ui/user-data t ::selection-at-focus) (when (string/blank? (.getSelectedText t)) (.consume e) (ui/run-later (.selectAll t)))) (ui/user-data! t ::selection-at-focus nil))))) (defmulti customize! (fn [control update-fn] (class control))) (defmethod customize! TextField [^TextField t update-fn] (doto t (GridPane/setHgrow Priority/ALWAYS) (ui/on-action! update-fn) (ui/auto-commit! update-fn) (select-all-on-click!))) (defmethod customize! TextArea [^TextArea t update-fn] (doto t (GridPane/setHgrow Priority/ALWAYS) (ui/auto-commit! update-fn) (select-all-on-click!))) (defmulti create-property-control! (fn [edit-type _ property-fn] (edit-type->type edit-type))) (defmethod create-property-control! g/Str [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text str) update-fn (fn [_] (properties/set-values! (property-fn) (repeat (.getText text))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Int [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text field-expression/format-int) update-fn (fn [_] (if-let [v (field-expression/to-int (.getText text))] (let [property (property-fn)] (properties/set-values! property (repeat v)) (update-ui-fn (properties/values property) (properties/validation-message property) (properties/read-only? property)))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Num [_ _ property-fn] (let [text (TextField.) update-ui-fn (partial update-text-fn text field-expression/format-number) update-fn (fn [_] (if-let [v (field-expression/to-double (.getText text))] (properties/set-values! (property-fn) (repeat v)) (update-ui-fn (properties/values (property-fn)) (properties/validation-message (property-fn)) (properties/read-only? (property-fn)))))] (customize! text update-fn) [text update-ui-fn])) (defmethod create-property-control! g/Bool [_ _ property-fn] (let [check (CheckBox.) update-ui-fn (fn [values message read-only?] (let [v (properties/unify-values values)] (if (nil? v) (.setIndeterminate check true) (doto check (.setIndeterminate false) (.setSelected v)))) (update-field-message [check] message) (ui/editable! check (not read-only?)))] (ui/on-action! check (fn [_] (properties/set-values! (property-fn) (repeat (.isSelected check))))) [check update-ui-fn])) (defn- create-grid-pane ^GridPane [ctrls] (let [box (doto (GridPane.) (ui/add-style! "property-component") (ui/children! ctrls))] (doall (map-indexed (fn [idx c] (GridPane/setConstraints c idx 0)) ctrls)) box)) (defn- create-multi-textfield! [labels property-fn] (let [text-fields (mapv (fn [_] (TextField.)) labels) box (doto (GridPane.) (.setHgap grid-hgap)) get-fns (map-indexed (fn [i _] #(nth % i)) text-fields) update-ui-fn (partial update-multi-text-fn text-fields field-expression/format-number get-fns)] (doseq [[t f] (map-indexed (fn [i t] [t (fn [_] (let [v (field-expression/to-double (.getText ^TextField t)) current-vals (properties/values (property-fn))] (if v (properties/set-values! (property-fn) (mapv #(assoc (vec %) i v) current-vals)) (update-ui-fn current-vals (properties/validation-message (property-fn)) (properties/read-only? (property-fn))))))]) text-fields)] (customize! t f)) (doall (map-indexed (fn [idx [^TextField t label]] (let [children (cond-> [] (seq label) (conj (doto (Label. label) (.setMinWidth Region/USE_PREF_SIZE))) true (conj t)) comp (doto (create-grid-pane children) (GridPane/setConstraints idx 0) (GridPane/setHgrow Priority/ALWAYS))] (ui/add-child! box comp))) (map vector text-fields labels))) [box update-ui-fn])) (defmethod create-property-control! types/Vec2 [edit-type _ property-fn] (let [{:keys [labels] :or {labels ["X" "Y"]}} edit-type] (create-multi-textfield! labels property-fn))) (defmethod create-property-control! types/Vec3 [edit-type _ property-fn] (let [{:keys [labels] :or {labels ["X" "Y" "Z"]}} edit-type] (create-multi-textfield! labels property-fn))) (defmethod create-property-control! types/Vec4 [_ _ property-fn] (create-multi-textfield! ["X" "Y" "Z" "W"] property-fn)) (defn- create-multi-keyed-textfield! [fields property-fn] (let [text-fields (mapv (fn [_] (TextField.)) fields) box (doto (GridPane.) (.setPrefWidth Double/MAX_VALUE)) get-fns (map (fn [f] (or (:get-fn f) #(get-in % (:path f)))) fields) update-ui-fn (partial update-multi-text-fn text-fields field-expression/format-number get-fns)] (doseq [[t f] (map (fn [f t] (let [set-fn (or (:set-fn f) (fn [e v] (assoc-in e (:path f) v)))] [t (fn [_] (let [v (field-expression/to-double (.getText ^TextField t)) current-vals (properties/values (property-fn))] (if v (properties/set-values! (property-fn) (mapv #(set-fn % v) current-vals)) (update-ui-fn current-vals (properties/validation-message (property-fn)) (properties/read-only? (property-fn))))))])) fields text-fields)] (customize! t f)) (doall (map-indexed (fn [idx [^TextField t f]] (let [children (cond-> [] (:label f) (conj (doto (Label. (:label f)) (.setMinWidth Region/USE_PREF_SIZE))) (:control f) (conj (doto ^Control (:control f) (.setMinWidth Region/USE_PREF_SIZE))) true (conj t)) ^GridPane comp (doto (create-grid-pane children) (GridPane/setConstraints idx 0) (GridPane/setHgrow Priority/ALWAYS))] (ui/add-child! box comp))) (map vector text-fields fields))) [box update-ui-fn])) (def ^:private ^:dynamic *programmatic-setting* nil) (defn- make-curve-toggler ^ToggleButton [property-fn] (let [^ToggleButton toggle-button (doto (ToggleButton. nil (jfx/get-image-view "icons/32/Icons_X_03_Bezier.png" 12.0)) (ui/add-styles! ["embedded-properties-button"]))] (doto toggle-button (ui/on-action! (fn [_] (let [selected (.isSelected toggle-button) vals (mapv (fn [curve] (let [v (-> curve properties/curve-vals first)] (assoc curve :points (iv/iv-vec (cond-> [v] selected (conj (assoc v 0 1.0))))))) (properties/values (property-fn)))] (properties/set-values! (property-fn) vals))))))) (defmethod create-property-control! CurveSpread [_ _ property-fn] (let [^ToggleButton toggle-button (make-curve-toggler property-fn) fields [{:get-fn (fn [c] (second (first (properties/curve-vals c)))) :set-fn (fn [c v] (properties/->curve-spread [[0.0 v 1.0 0.0]] (:spread c))) :control toggle-button} {:label "+/-" :path [:spread]}] [^HBox box update-ui-fn] (create-multi-keyed-textfield! fields property-fn) ^TextField text-field (some #(and (instance? TextField %) %) (.getChildren ^HBox (first (.getChildren box)))) update-ui-fn (fn [values message read-only?] (update-ui-fn values message read-only?) (let [curved? (boolean (< 1 (count (properties/curve-vals (first values)))))] (.setSelected toggle-button curved?) (ui/editable! toggle-button (some? (first values))) (ui/disable! text-field curved?)))] [box update-ui-fn])) (defmethod create-property-control! Curve [_ _ property-fn] (let [^ToggleButton toggle-button (make-curve-toggler property-fn) fields [{:get-fn (fn [c] (second (first (properties/curve-vals c)))) :set-fn (fn [c v] (properties/->curve [[0.0 v 1.0 0.0]])) :control toggle-button}] [^HBox box update-ui-fn] (create-multi-keyed-textfield! fields property-fn) ^TextField text-field (some #(and (instance? TextField %) %) (.getChildren ^HBox (first (.getChildren box)))) update-ui-fn (fn [values message read-only?] (update-ui-fn values message read-only?) (let [curved? (boolean (< 1 (count (properties/curve-vals (first values)))))] (.setSelected toggle-button curved?) (ui/editable! toggle-button (some? (first values))) (ui/disable! text-field curved?)))] [box update-ui-fn])) (defmethod create-property-control! types/Color [edit-type _ property-fn] (let [color-picker (doto (ColorPicker.) (.setPrefWidth Double/MAX_VALUE)) update-ui-fn (fn [values message read-only?] (let [v (properties/unify-values values)] (if (nil? v) (.setValue color-picker nil) (let [[r g b a] v] (.setValue color-picker (Color. r g b a))))) (update-field-message [color-picker] message) (ui/editable! color-picker (not read-only?)))] (ui/on-action! color-picker (fn [_] (let [^Color c (.getValue color-picker) v [(.getRed c) (.getGreen c) (.getBlue c) (.getOpacity c)] values (if (:ignore-alpha? edit-type) (map #(assoc %1 3 %2) (repeat v) (map last (properties/values (property-fn)))) (repeat v))] (properties/set-values! (property-fn) values)))) [color-picker update-ui-fn])) (defmethod create-property-control! :choicebox [{:keys [options]} _ property-fn] (let [combo-box (fuzzy-combo-box/make options) update-ui-fn (fn [values message read-only?] (binding [*programmatic-setting* true] (fuzzy-combo-box/set-value! combo-box (properties/unify-values values)) (update-field-message [combo-box] message) (ui/disable! combo-box read-only?))) listen-fn (fn [_old-val new-val] (when-not *programmatic-setting* (properties/set-values! (property-fn) (repeat new-val)) (ui/user-data! (ui/main-scene) ::ui/refresh-requested? true)))] (fuzzy-combo-box/observe! combo-box listen-fn) [combo-box update-ui-fn])) (defmethod create-property-control! resource/Resource [edit-type {:keys [workspace project]} property-fn] (let [box (GridPane.) browse-button (doto (Button. "\u2026") ; "..." (HORIZONTAL ELLIPSIS) (.setPrefWidth 26) (ui/add-style! "button-small")) open-button (doto (Button. "" (jfx/get-image-view "icons/32/Icons_S_14_linkarrow.png" 16)) (.setMaxWidth 26) (ui/add-style! "button-small")) text (TextField.) dialog-opts (if (:ext edit-type) {:ext (:ext edit-type)} {}) update-ui-fn (fn [values message read-only?] (update-text-fn text str (fn [v] (when v (resource/proj-path v))) values message read-only?) (let [val (properties/unify-values values)] (ui/editable! browse-button (not read-only?)) (ui/editable! open-button (and (resource/openable-resource? val) (resource/exists? val))))) commit-fn (fn [_] (let [path (ui/text text) resource (workspace/resolve-workspace-resource workspace path)] (properties/set-values! (property-fn) (repeat resource))))] (ui/add-style! box "composite-property-control-container") (ui/on-action! browse-button (fn [_] (when-let [resource (first (dialogs/make-resource-dialog workspace project dialog-opts))] (properties/set-values! (property-fn) (repeat resource))))) (ui/on-action! open-button (fn [_] (when-let [resource (-> (property-fn) properties/values properties/unify-values)] (ui/run-command open-button :open {:resources [resource]})))) (customize! text commit-fn) (ui/children! box [text browse-button open-button]) (GridPane/setConstraints text 0 0) (GridPane/setConstraints open-button 1 0) (GridPane/setConstraints browse-button 2 0) ; Merge the facing borders of the open and browse buttons. (GridPane/setMargin open-button (Insets. 0 -1 0 0)) (.setOnMousePressed open-button (ui/event-handler _ (.toFront open-button))) (.setOnMousePressed browse-button (ui/event-handler _ (.toFront browse-button))) (doto (.. box getColumnConstraints) (.add (doto (ColumnConstraints.) (.setPrefWidth all-available) (.setHgrow Priority/ALWAYS))) (.add (doto (ColumnConstraints.) (.setMinWidth ColumnConstraints/CONSTRAIN_TO_PREF) (.setHgrow Priority/NEVER))) (.add (doto (ColumnConstraints.) (.setMinWidth ColumnConstraints/CONSTRAIN_TO_PREF) (.setHgrow Priority/NEVER)))) [box update-ui-fn])) (defmethod create-property-control! :slider [edit-type context property-fn] (let [box (doto (GridPane.) (.setHgap grid-hgap)) [^TextField textfield tf-update-ui-fn] (create-property-control! {:type g/Num} context property-fn) min (:min edit-type 0.0) max (:max edit-type 1.0) val (:value edit-type max) precision (:precision edit-type) slider (Slider. min max val) update-ui-fn (fn [values message read-only?] (tf-update-ui-fn values message read-only?) (binding [*programmatic-setting* true] (if-let [v (properties/unify-values values)] (doto slider (.setDisable false) (.setValue v)) (.setDisable slider true)) (update-field-message [slider] message) (ui/editable! slider (not read-only?))))] (.setPrefColumnCount textfield (if precision (count (str precision)) 5)) (.addEventFilter slider MouseEvent/MOUSE_PRESSED (ui/event-handler event (ui/user-data! slider ::op-seq (gensym)))) (ui/observe (.valueProperty slider) (fn [observable old-val new-val] (when-not *programmatic-setting* (let [val (if precision (math/round-with-precision new-val precision) new-val)] (properties/set-values! (property-fn) (repeat val) (ui/user-data slider ::op-seq)))))) (ui/children! box [textfield slider]) (GridPane/setConstraints textfield 0 0) (GridPane/setConstraints slider 1 0) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setPercentWidth 20)))) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setPercentWidth 80)))) [box update-ui-fn])) (defmethod create-property-control! :multi-line-text [_ _ property-fn] (let [text (doto (TextArea.) (ui/add-style! "property") (.setMinHeight 68)) update-ui-fn (partial update-text-fn text str) update-fn #(properties/set-values! (property-fn) (repeat (.getText text)))] (ui/bind-key! text "Shortcut+Enter" update-fn) (customize! text (fn [_] (update-fn))) [text update-ui-fn])) (defmethod create-property-control! :default [_ _ _] (let [text (TextField.) wrapper (doto (HBox.) (.setPrefWidth Double/MAX_VALUE)) update-ui-fn (partial update-text-fn text str)] (HBox/setHgrow text Priority/ALWAYS) (ui/children! wrapper [text]) (.setDisable text true) [wrapper update-ui-fn])) (defn- node-screen-coords ^Point2D [^Node node ^Point2D offset] (let [scene (.getScene node) window (.getWindow scene) window-coords (Point2D. (.getX window) (.getY window)) scene-coords (Point2D. (.getX scene) (.getY scene)) node-coords (.localToScene node (.getX offset) (.getY offset))] (.add node-coords (.add scene-coords window-coords)))) (def ^:private severity-tooltip-style-map {:fatal "tooltip-error" :warning "tooltip-warning" :info "tooltip-info"}) (defn- show-message-tooltip [^Node control] (when-let [tip (ui/user-data control ::field-message)] ;; FIXME: Hack to position tooltip somewhat below control so .show doesn't immediately trigger an :exit. (let [tooltip (Tooltip. (:message tip)) control-bounds (.getLayoutBounds control) tooltip-coords (node-screen-coords control (Point2D. 0.0 (+ (.getHeight control-bounds) 11.0)))] (ui/add-style! tooltip (severity-tooltip-style-map (:severity tip))) (ui/user-data! control ::tooltip tooltip) (.show tooltip control (.getX tooltip-coords) (.getY tooltip-coords))))) (defn- hide-message-tooltip [control] (when-let [tooltip ^Tooltip (ui/user-data control ::tooltip)] (ui/user-data! control ::tooltip nil) (.hide tooltip))) (defn- update-message-tooltip [control] (when (ui/user-data control ::tooltip) (hide-message-tooltip control) (show-message-tooltip control))) (defn- install-tooltip-message [ctrl msg] (ui/user-data! ctrl ::field-message msg) (ui/on-mouse! ctrl (when msg (fn [verb e] (condp = verb :enter (show-message-tooltip ctrl) :exit (hide-message-tooltip ctrl) :move nil))))) (def ^:private severity-field-style-map {:fatal "field-error" :warning "field-warning" :info "field-info"}) (defn- update-field-message-style [ctrl msg] (if msg (ui/add-style! ctrl (severity-field-style-map (:severity msg))) (ui/remove-styles! ctrl (vals severity-field-style-map)))) (defn- update-field-message [ctrls msg] (doseq [ctrl ctrls] (install-tooltip-message ctrl msg) (update-field-message-style ctrl msg) (if msg (update-message-tooltip ctrl) (hide-message-tooltip ctrl)))) (defn- create-property-label [label key] (doto (Label. label) (.setTooltip (doto (Tooltip.) (.setText (format "Available as `%s` in editor scripts" (string/replace (name key) \- \_))) (.setHideDelay Duration/ZERO) (.setShowDuration (Duration/seconds 30)))) (ui/add-style! "property-label") (.setMinWidth Label/USE_PREF_SIZE) (.setMinHeight 28.0))) (defn- create-properties-row [context ^GridPane grid key property row property-fn] (let [^Label label (create-property-label (properties/label property) key) [^Node control update-ctrl-fn] (create-property-control! (:edit-type property) context (fn [] (property-fn key))) reset-btn (doto (Button. nil (jfx/get-image-view "icons/32/Icons_S_02_Reset.png")) (ui/add-styles! ["clear-button" "button-small"]) (ui/on-action! (fn [_] (properties/clear-override! (property-fn key)) (ui/suppress-auto-commit! control) (.requestFocus control)))) label-box (let [box (GridPane.)] (GridPane/setFillWidth label true) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setHgrow Priority/ALWAYS)))) (.. box getColumnConstraints (add (doto (ColumnConstraints.) (.setHgrow Priority/NEVER)))) box) update-label-box (fn [overridden?] (if overridden? (do (ui/children! label-box [label reset-btn]) (GridPane/setConstraints label 0 0) (GridPane/setConstraints reset-btn 1 0)) (do (ui/children! label-box [label]) (GridPane/setConstraints label 0 0)))) update-ui-fn (fn [property] (let [overridden? (properties/overridden? property) f (if overridden? ui/add-style! ui/remove-style!)] (doseq [c [label control]] (f c "overridden")) (update-label-box overridden?) (update-ctrl-fn (properties/values property) (properties/validation-message property) (properties/read-only? property))))] (update-label-box (properties/overridden? property)) (GridPane/setConstraints label-box 0 row) (GridPane/setConstraints control 1 row) (.add (.getChildren grid) label-box) (.add (.getChildren grid) control) (GridPane/setFillWidth label-box true) (GridPane/setFillWidth control true) [key update-ui-fn])) (defn- create-properties [context grid properties property-fn] ; TODO - add multi-selection support for properties view (doall (map-indexed (fn [row [key property]] (create-properties-row context grid key property row property-fn)) properties))) (defn- make-grid [parent context properties property-fn] (let [grid (doto (GridPane.) (.setHgap grid-hgap) (.setVgap grid-vgap)) cc1 (doto (ColumnConstraints.) (.setHgrow Priority/NEVER)) cc2 (doto (ColumnConstraints.) (.setHgrow Priority/ALWAYS) (.setPrefWidth all-available))] (.. grid getColumnConstraints (add cc1)) (.. grid getColumnConstraints (add cc2)) (ui/add-child! parent grid) (ui/add-style! grid "form") (create-properties context grid properties property-fn))) (defn- create-category-label [label] (doto (Label. label) (ui/add-style! "property-category"))) (defn- make-pane! [parent context properties] (let [vbox (doto (VBox. (double 10.0)) (.setId "properties-view-pane") (.setPadding (Insets. 10 10 10 10)) (.setFillWidth true) (AnchorPane/setBottomAnchor 0.0) (AnchorPane/setLeftAnchor 0.0) (AnchorPane/setRightAnchor 0.0) (AnchorPane/setTopAnchor 0.0))] (let [property-fn (fn [key] (let [properties (:properties (ui/user-data vbox ::properties))] (get properties key))) display-order (:display-order properties) properties (:properties properties) generics [nil (mapv (fn [k] [k (get properties k)]) (filter (comp not properties/category?) display-order))] categories (mapv (fn [order] [(first order) (mapv (fn [k] [k (get properties k)]) (rest order))]) (filter properties/category? display-order)) update-fns (loop [sections (cons generics categories) result []] (if-let [[category properties] (first sections)] (let [update-fns (if (empty? properties) [] (do (when category (let [label (create-category-label category)] (ui/add-child! vbox label))) (make-grid vbox context properties property-fn)))] (recur (rest sections) (into result update-fns))) result))] ; NOTE: Note update-fns is a sequence of [[property-key update-ui-fn] ...] (ui/user-data! parent ::update-fns (into {} update-fns))) (ui/children! parent [vbox]) vbox)) (defn- refresh-pane! [^Parent parent properties] (let [pane (.lookup parent "#properties-view-pane") update-fns (ui/user-data parent ::update-fns) prev-properties (:properties (ui/user-data pane ::properties))] (ui/user-data! pane ::properties properties) (doseq [[key property] (:properties properties) ;; Only update the UI when the props actually differ ;; Differing :edit-type's would have recreated the UI so no need to compare them here :when (not= (dissoc property :edit-type) (dissoc (get prev-properties key) :edit-type))] (when-let [update-ui-fn (get update-fns key)] (update-ui-fn property))))) (def ^:private ephemeral-edit-type-fields [:from-type :to-type :set-fn]) (defn- edit-type->template [edit-type] (apply dissoc edit-type ephemeral-edit-type-fields)) (defn- properties->template [properties] (mapv (fn [[k v]] [k (edit-type->template (:edit-type v))]) (:properties properties))) (defn- update-pane! [parent context properties] ; NOTE: We cache the ui based on the ::template and ::properties user-data (profiler/profile "properties" "update-pane" (let [properties (properties/coalesce properties) template (properties->template properties) prev-template (ui/user-data parent ::template)] (when (not= template prev-template) (make-pane! parent context properties) (ui/user-data! parent ::template template)) (refresh-pane! parent properties)))) (g/defnode PropertiesView (property parent-view Parent) (property workspace g/Any) (property project g/Any) (input selected-node-properties g/Any) (output pane Pane :cached (g/fnk [parent-view workspace project selected-node-properties] (let [context {:workspace workspace :project project}] ;; Collecting the properties and then updating the view takes some time, but has no immediacy ;; This is effectively time-slicing it over two "frames" (or whenever JavaFX decides to run the second part) (ui/run-later (update-pane! parent-view context selected-node-properties)))))) (defn make-properties-view [workspace project app-view view-graph ^Node parent] (let [view-id (g/make-node! view-graph PropertiesView :parent-view parent :workspace workspace :project project) stage (.. parent getScene getWindow)] (g/connect! app-view :selected-node-properties view-id :selected-node-properties) view-id))
[ { "context": "testing \"atom\"\n (let [resource (atom {:name \"Frank\"})\n handler (yada resource)\n ", "end": 1878, "score": 0.7850786447525024, "start": 1873, "tag": "NAME", "value": "Frank" } ]
test/yada/put_resource_test.clj
danielcompton/yada
0
;; Copyright © 2015, JUXT LTD. (ns yada.put-resource-test (:require [byte-streams :as b] [clojure.test :refer :all] [ring.mock.request :refer [request]] [clojure.java.io :as io] [manifold.stream :as s] [yada.test-util :refer [to-string]] [yada.handler :refer [handler]] [yada.resource :refer [resource]])) (defn add-headers [request m] (merge-with merge request {:headers m})) (deftest put-test (testing "string" (let [resource (atom "Bradley") h (handler resource) response @(h (request :get "/")) headers (:headers response)] (is (= 200 (:status response))) (is (= {"content-length" (str 7) "content-type" "text/plain;charset=utf-8"} (select-keys headers ["content-length" "content-type"]))) (is (= "Bradley" (to-string (:body response)))) (let [response @(h (-> (request :put "/" {:value "Chelsea"})))] (is (= 204 (:status response))) (is (= (contains? (set (keys (:headers response))) "content-type"))) (is (= (contains? (set (keys (:headers response))) "content-length"))) (is (nil? (:body response)))) (is (= @resource "Chelsea")) (let [response @(h (request :get "/"))] (is (= 200 (:status response))) (is (= {"content-length" (str 7) "content-type" "text/plain;charset=utf-8"} (select-keys (:headers response) ["content-length" "content-type"]))) (is (= "Chelsea" (to-string (:body response))))))) (testing "return response" (let [h (handler (resource {:methods {:put {:response (fn [ctx] (assoc (:response ctx) :body "BODY" :status 200))}}})) response @(h (request :put "/"))] (is (= "BODY" (b/to-string (:body response)))) (is (= 200 (:status response))))) #_(testing "atom" (let [resource (atom {:name "Frank"}) handler (yada resource) request (request :get "/") response @(handler request)] (given response :status := 200 :headers :> {"content-length" 16 "content-type" "application/edn"} :body :? string?) )))
44428
;; Copyright © 2015, JUXT LTD. (ns yada.put-resource-test (:require [byte-streams :as b] [clojure.test :refer :all] [ring.mock.request :refer [request]] [clojure.java.io :as io] [manifold.stream :as s] [yada.test-util :refer [to-string]] [yada.handler :refer [handler]] [yada.resource :refer [resource]])) (defn add-headers [request m] (merge-with merge request {:headers m})) (deftest put-test (testing "string" (let [resource (atom "Bradley") h (handler resource) response @(h (request :get "/")) headers (:headers response)] (is (= 200 (:status response))) (is (= {"content-length" (str 7) "content-type" "text/plain;charset=utf-8"} (select-keys headers ["content-length" "content-type"]))) (is (= "Bradley" (to-string (:body response)))) (let [response @(h (-> (request :put "/" {:value "Chelsea"})))] (is (= 204 (:status response))) (is (= (contains? (set (keys (:headers response))) "content-type"))) (is (= (contains? (set (keys (:headers response))) "content-length"))) (is (nil? (:body response)))) (is (= @resource "Chelsea")) (let [response @(h (request :get "/"))] (is (= 200 (:status response))) (is (= {"content-length" (str 7) "content-type" "text/plain;charset=utf-8"} (select-keys (:headers response) ["content-length" "content-type"]))) (is (= "Chelsea" (to-string (:body response))))))) (testing "return response" (let [h (handler (resource {:methods {:put {:response (fn [ctx] (assoc (:response ctx) :body "BODY" :status 200))}}})) response @(h (request :put "/"))] (is (= "BODY" (b/to-string (:body response)))) (is (= 200 (:status response))))) #_(testing "atom" (let [resource (atom {:name "<NAME>"}) handler (yada resource) request (request :get "/") response @(handler request)] (given response :status := 200 :headers :> {"content-length" 16 "content-type" "application/edn"} :body :? string?) )))
true
;; Copyright © 2015, JUXT LTD. (ns yada.put-resource-test (:require [byte-streams :as b] [clojure.test :refer :all] [ring.mock.request :refer [request]] [clojure.java.io :as io] [manifold.stream :as s] [yada.test-util :refer [to-string]] [yada.handler :refer [handler]] [yada.resource :refer [resource]])) (defn add-headers [request m] (merge-with merge request {:headers m})) (deftest put-test (testing "string" (let [resource (atom "Bradley") h (handler resource) response @(h (request :get "/")) headers (:headers response)] (is (= 200 (:status response))) (is (= {"content-length" (str 7) "content-type" "text/plain;charset=utf-8"} (select-keys headers ["content-length" "content-type"]))) (is (= "Bradley" (to-string (:body response)))) (let [response @(h (-> (request :put "/" {:value "Chelsea"})))] (is (= 204 (:status response))) (is (= (contains? (set (keys (:headers response))) "content-type"))) (is (= (contains? (set (keys (:headers response))) "content-length"))) (is (nil? (:body response)))) (is (= @resource "Chelsea")) (let [response @(h (request :get "/"))] (is (= 200 (:status response))) (is (= {"content-length" (str 7) "content-type" "text/plain;charset=utf-8"} (select-keys (:headers response) ["content-length" "content-type"]))) (is (= "Chelsea" (to-string (:body response))))))) (testing "return response" (let [h (handler (resource {:methods {:put {:response (fn [ctx] (assoc (:response ctx) :body "BODY" :status 200))}}})) response @(h (request :put "/"))] (is (= "BODY" (b/to-string (:body response)))) (is (= 200 (:status response))))) #_(testing "atom" (let [resource (atom {:name "PI:NAME:<NAME>END_PI"}) handler (yada resource) request (request :get "/") response @(handler request)] (given response :status := 200 :headers :> {"content-length" 16 "content-type" "application/edn"} :body :? string?) )))
[ { "context": " config {:marta-api-key (or (env :marta-api-key) \"475ad2ba-5928-4063-9d00-ae06fbb02f3c\")\n :marta-api-uri (or (env :marta-api", "end": 166, "score": 0.9997063279151917, "start": 130, "tag": "KEY", "value": "475ad2ba-5928-4063-9d00-ae06fbb02f3c" } ]
src/clojure/itg/clj_marta/common/config.clj
csmith-cb/clj-marta
1
(ns itg.clj-marta.common.config (:require [environ.core :refer [env]])) (def config {:marta-api-key (or (env :marta-api-key) "475ad2ba-5928-4063-9d00-ae06fbb02f3c") :marta-api-uri (or (env :marta-api-uri) "http://developer.itsmarta.com")})
121542
(ns itg.clj-marta.common.config (:require [environ.core :refer [env]])) (def config {:marta-api-key (or (env :marta-api-key) "<KEY>") :marta-api-uri (or (env :marta-api-uri) "http://developer.itsmarta.com")})
true
(ns itg.clj-marta.common.config (:require [environ.core :refer [env]])) (def config {:marta-api-key (or (env :marta-api-key) "PI:KEY:<KEY>END_PI") :marta-api-uri (or (env :marta-api-uri) "http://developer.itsmarta.com")})
[ { "context": "f drugs, clearances, and effects\"\n [{:drug-name \"Visomorpain\"\n :clearance \"IR\"\n :desc \"Little Black Frie", "end": 431, "score": 0.6694930195808411, "start": 420, "tag": "NAME", "value": "Visomorpain" }, { "context": "ulls pain and makes user happy.\"}\n {:drug-name \"Xanitrick\"\n :clearance \"IR\"\n :desc \"Wakey Wakey.\"\n ", "end": 545, "score": 0.9835927486419678, "start": 536, "tag": "NAME", "value": "Xanitrick" }, { "context": "R\"\n :desc \"Wakey Wakey.\"\n }\n {:drug-name \"Thiahexadrine\"\n :clearance \"IR\"\n :desc \"Focusol.\"\n }\n ", "end": 627, "score": 0.916317343711853, "start": 614, "tag": "NAME", "value": "Thiahexadrine" }, { "context": "e \"IR\"\n :desc \"Focusol.\"\n }\n {:drug-name \"Gelgernine\"\n :clearance \"R\"\n :desc \"Inner Happiness.\"\n", "end": 702, "score": 0.9494081735610962, "start": 692, "tag": "NAME", "value": "Gelgernine" }, { "context": " :desc \"Inner Happiness.\"\n }\n {:drug-name \"Sandallathon\"\n :clearance \"R\"\n :desc \"Sleepy-Sleepy.\"\n ", "end": 786, "score": 0.9306500554084778, "start": 774, "tag": "NAME", "value": "Sandallathon" }, { "context": "\n :desc \"Sleepy-Sleepy.\"\n }\n {:drug-name \"Pyroxidine\"\n :clearance \"R\"\n :desc \"Wide-Awake.\"\n }", "end": 866, "score": 0.8790504336357117, "start": 856, "tag": "NAME", "value": "Pyroxidine" }, { "context": "\"R\"\n :desc \"Wide-Awake.\"\n }\n {:drug-name \"Pyroxidine 2\"\n :clearance \"R\"\n :desc \"Wider Awak", "end": 937, "score": 0.5685996413230896, "start": 933, "tag": "NAME", "value": "Pyro" }, { "context": "R\"\n :desc \"Wider Awake.\"\n }\n {:drug-name \"Qualine\"\n :clearance \"R\"\n :desc \"E-Z-DUZ-IT.\"\n }", "end": 1020, "score": 0.9108015298843384, "start": 1013, "tag": "NAME", "value": "Qualine" }, { "context": "\"R\"\n :desc \"E-Z-DUZ-IT.\"\n }\n {:drug-name \"Persidax\"\n :clearance \"R\"\n :desc \"New You.\"\n }\n ", "end": 1095, "score": 0.9809484481811523, "start": 1087, "tag": "NAME", "value": "Persidax" }, { "context": "ce \"R\"\n :desc \"New You.\"\n }\n {:drug-name \"Clonoglazeron\"\n :clearance \"R\"\n :desc \"MelloWake.\"\n }\n", "end": 1172, "score": 0.9839810729026794, "start": 1159, "tag": "NAME", "value": "Clonoglazeron" }, { "context": " \"R\"\n :desc \"MelloWake.\"\n }\n {:drug-name \"Jargotan\"\n :clearance \"R\"\n :desc \"Scramble.\"\n }\n ", "end": 1246, "score": 0.9797771573066711, "start": 1238, "tag": "NAME", "value": "Jargotan" }, { "context": "e \"R\"\n :desc \"Scramble.\"\n }\n {:drug-name \"Smilase Tentrasildenafil\"\n :clearance \"R\"\n :desc \"Smilies.\"\n }\n ", "end": 1335, "score": 0.6768752336502075, "start": 1311, "tag": "NAME", "value": "Smilase Tentrasildenafil" } ]
src/hphelper/frontend/reference.cljs
lsenjov/hphelper
2
(ns hphelper.frontend.reference "Contains a component for giving players information" (:require [taoensso.timbre :as log] [reagent.core :as reagent :refer [atom]] [ajax.core :refer [GET POST] :as ajax] [hphelper.frontend.shared :refer [wrap-context add-button-size] :as shared] )) (def ^:private ref-drugs "A list of drugs, clearances, and effects" [{:drug-name "Visomorpain" :clearance "IR" :desc "Little Black Friend. Dulls pain and makes user happy."} {:drug-name "Xanitrick" :clearance "IR" :desc "Wakey Wakey." } {:drug-name "Thiahexadrine" :clearance "IR" :desc "Focusol." } {:drug-name "Gelgernine" :clearance "R" :desc "Inner Happiness." } {:drug-name "Sandallathon" :clearance "R" :desc "Sleepy-Sleepy." } {:drug-name "Pyroxidine" :clearance "R" :desc "Wide-Awake." } {:drug-name "Pyroxidine 2" :clearance "R" :desc "Wider Awake." } {:drug-name "Qualine" :clearance "R" :desc "E-Z-DUZ-IT." } {:drug-name "Persidax" :clearance "R" :desc "New You." } {:drug-name "Clonoglazeron" :clearance "R" :desc "MelloWake." } {:drug-name "Jargotan" :clearance "R" :desc "Scramble." } {:drug-name "Smilase Tentrasildenafil" :clearance "R" :desc "Smilies." } {:drug-name "Sodium Pentathol" :clearance "R" :desc "Filter Fighter." } {:drug-name "Zybenzaphrene" :clearance "O" :desc "Slumber Soft." } {:drug-name "Vulpazine" :clearance "O" :desc "Night Stalker." } {:drug-name "Calcium Carbonate" :clearance "O" :desc "Calm-n-Coat Antacid." } {:drug-name "Dioxromnurespa-butinol-3" :clearance "O" :desc "Sparkle Ultra." } {:drug-name "Asperquaint" :clearance "Y" :desc "Pep Pills." } {:drug-name "Erithermaboxadrine" :clearance "Y" :desc "Glow." } {:drug-name "Morlox" :clearance "Y" :desc "Furball." } {:drug-name "Telescopalamine" :clearance "G" :desc "Truth and Beauty. Self-finking pills." } {:drug-name "Necronomicil" :clearance "G" :desc "ReAnimator." } {:drug-name "Rolactin" :clearance "B" :desc "Happy Life." } {:drug-name "Thymoglandin" :clearance "B" :desc "Combat Quick." } {:drug-name "Oxyflucocillin" :clearance "B" :desc "Overdose Helper." } {:drug-name "Benetridin" :clearance "I" :desc "VideoLand." } {:drug-name "Diphenhydromegatoxine" :clearance "I" :desc "Regro." } {:drug-name "Dynomorphin" :clearance "U" :desc "" } {:drug-name "Hydropsionic Acid" :clearance "ILLEGAL" :desc "" } {:drug-name "Verasubsannine" :clearance "ILLEGAL" :desc "Believapills." } {:drug-name "Metamemopyroxide" :clearance "ILLEGAL" :desc "Friendly Fire." } ] ) (defn drugs-component "Component for rendering a list of drugs" [] (let [sort-atom (atom {:sort-key :drug-name})] (fn [] [:div [:div (shared/switcher-toolbar sort-atom [:sort-key] [[:drug-name "Name"] [:clearance "Clearance"] ] ) ] [:table {:class "table table-striped table-hover"} [:thead>tr [:th "Name"] [:th "Clearance"] [:th "Description"] ] [:tbody (->> ref-drugs ((case (:sort-key @sort-atom) :drug-name #(sort-by :drug-name %) :clearance #(sort-by (comp {"IR" 8 "R" 7 "O" 6 "Y" 5 "G" 4 "B" 3 "I" 2 "V" 1} :clearance) %) identity ) ) (map (fn [{:keys [drug-name clearance desc]}] [:tr [:td drug-name] [:td clearance] [:td desc]]) ) doall ) ] ] ] ) ) ) (defn specialties-component "Component for rendering specialties" [] (let [filter-atom (atom {:skills_parent nil})] (fn [] (let [specialties (shared/get-specialties)] [:div [:div (shared/switcher-toolbar filter-atom [:skills_parent] [[nil "No Filter"] ["M" "Management"] ["Su" "Subterfuge"]["V" "Violence"] ["H" "Hardware"] ["So" "Software"] ["W" "Wetware"] ["O" "Other"] ] ) ] [:table {:class "table table-striped table-hover"} [:thead>tr [:td "Name"] [:td "Parent Skill"] [:td "Description"] ] [:tbody (->> specialties ;; Filter skills (filter #(if (not (:skills_parent @filter-atom)) % (= (:skills_parent @filter-atom) (:skills_parent %)) ) ) ;; Sort Alphabetically (sort-by :skills_name) ;; Make it pretty (map (fn [{:keys [skills_name skills_desc skills_parent]}] ^{:key skills_name} [:tr [:td skills_name] [:td (shared/wrap-skill-initial skills_parent)] [:td skills_desc]])) doall ) ] ] "Filter: " (pr-str @filter-atom) ] ) ) ) ) (defn reference-component "Reference page for getting information" [] (let [page-atom (atom {:page nil})] (fn [] [:div [:div (shared/switcher-toolbar page-atom [:page] [[:specialties "Specialties"] [:drugs "Drugs"] ] ) ] (case (:page @page-atom) :skills "Not implemented" :specialties [specialties-component] :drugs [drugs-component] "Make a selection" ) ] ) ) )
3607
(ns hphelper.frontend.reference "Contains a component for giving players information" (:require [taoensso.timbre :as log] [reagent.core :as reagent :refer [atom]] [ajax.core :refer [GET POST] :as ajax] [hphelper.frontend.shared :refer [wrap-context add-button-size] :as shared] )) (def ^:private ref-drugs "A list of drugs, clearances, and effects" [{:drug-name "<NAME>" :clearance "IR" :desc "Little Black Friend. Dulls pain and makes user happy."} {:drug-name "<NAME>" :clearance "IR" :desc "Wakey Wakey." } {:drug-name "<NAME>" :clearance "IR" :desc "Focusol." } {:drug-name "<NAME>" :clearance "R" :desc "Inner Happiness." } {:drug-name "<NAME>" :clearance "R" :desc "Sleepy-Sleepy." } {:drug-name "<NAME>" :clearance "R" :desc "Wide-Awake." } {:drug-name "<NAME>xidine 2" :clearance "R" :desc "Wider Awake." } {:drug-name "<NAME>" :clearance "R" :desc "E-Z-DUZ-IT." } {:drug-name "<NAME>" :clearance "R" :desc "New You." } {:drug-name "<NAME>" :clearance "R" :desc "MelloWake." } {:drug-name "<NAME>" :clearance "R" :desc "Scramble." } {:drug-name "<NAME>" :clearance "R" :desc "Smilies." } {:drug-name "Sodium Pentathol" :clearance "R" :desc "Filter Fighter." } {:drug-name "Zybenzaphrene" :clearance "O" :desc "Slumber Soft." } {:drug-name "Vulpazine" :clearance "O" :desc "Night Stalker." } {:drug-name "Calcium Carbonate" :clearance "O" :desc "Calm-n-Coat Antacid." } {:drug-name "Dioxromnurespa-butinol-3" :clearance "O" :desc "Sparkle Ultra." } {:drug-name "Asperquaint" :clearance "Y" :desc "Pep Pills." } {:drug-name "Erithermaboxadrine" :clearance "Y" :desc "Glow." } {:drug-name "Morlox" :clearance "Y" :desc "Furball." } {:drug-name "Telescopalamine" :clearance "G" :desc "Truth and Beauty. Self-finking pills." } {:drug-name "Necronomicil" :clearance "G" :desc "ReAnimator." } {:drug-name "Rolactin" :clearance "B" :desc "Happy Life." } {:drug-name "Thymoglandin" :clearance "B" :desc "Combat Quick." } {:drug-name "Oxyflucocillin" :clearance "B" :desc "Overdose Helper." } {:drug-name "Benetridin" :clearance "I" :desc "VideoLand." } {:drug-name "Diphenhydromegatoxine" :clearance "I" :desc "Regro." } {:drug-name "Dynomorphin" :clearance "U" :desc "" } {:drug-name "Hydropsionic Acid" :clearance "ILLEGAL" :desc "" } {:drug-name "Verasubsannine" :clearance "ILLEGAL" :desc "Believapills." } {:drug-name "Metamemopyroxide" :clearance "ILLEGAL" :desc "Friendly Fire." } ] ) (defn drugs-component "Component for rendering a list of drugs" [] (let [sort-atom (atom {:sort-key :drug-name})] (fn [] [:div [:div (shared/switcher-toolbar sort-atom [:sort-key] [[:drug-name "Name"] [:clearance "Clearance"] ] ) ] [:table {:class "table table-striped table-hover"} [:thead>tr [:th "Name"] [:th "Clearance"] [:th "Description"] ] [:tbody (->> ref-drugs ((case (:sort-key @sort-atom) :drug-name #(sort-by :drug-name %) :clearance #(sort-by (comp {"IR" 8 "R" 7 "O" 6 "Y" 5 "G" 4 "B" 3 "I" 2 "V" 1} :clearance) %) identity ) ) (map (fn [{:keys [drug-name clearance desc]}] [:tr [:td drug-name] [:td clearance] [:td desc]]) ) doall ) ] ] ] ) ) ) (defn specialties-component "Component for rendering specialties" [] (let [filter-atom (atom {:skills_parent nil})] (fn [] (let [specialties (shared/get-specialties)] [:div [:div (shared/switcher-toolbar filter-atom [:skills_parent] [[nil "No Filter"] ["M" "Management"] ["Su" "Subterfuge"]["V" "Violence"] ["H" "Hardware"] ["So" "Software"] ["W" "Wetware"] ["O" "Other"] ] ) ] [:table {:class "table table-striped table-hover"} [:thead>tr [:td "Name"] [:td "Parent Skill"] [:td "Description"] ] [:tbody (->> specialties ;; Filter skills (filter #(if (not (:skills_parent @filter-atom)) % (= (:skills_parent @filter-atom) (:skills_parent %)) ) ) ;; Sort Alphabetically (sort-by :skills_name) ;; Make it pretty (map (fn [{:keys [skills_name skills_desc skills_parent]}] ^{:key skills_name} [:tr [:td skills_name] [:td (shared/wrap-skill-initial skills_parent)] [:td skills_desc]])) doall ) ] ] "Filter: " (pr-str @filter-atom) ] ) ) ) ) (defn reference-component "Reference page for getting information" [] (let [page-atom (atom {:page nil})] (fn [] [:div [:div (shared/switcher-toolbar page-atom [:page] [[:specialties "Specialties"] [:drugs "Drugs"] ] ) ] (case (:page @page-atom) :skills "Not implemented" :specialties [specialties-component] :drugs [drugs-component] "Make a selection" ) ] ) ) )
true
(ns hphelper.frontend.reference "Contains a component for giving players information" (:require [taoensso.timbre :as log] [reagent.core :as reagent :refer [atom]] [ajax.core :refer [GET POST] :as ajax] [hphelper.frontend.shared :refer [wrap-context add-button-size] :as shared] )) (def ^:private ref-drugs "A list of drugs, clearances, and effects" [{:drug-name "PI:NAME:<NAME>END_PI" :clearance "IR" :desc "Little Black Friend. Dulls pain and makes user happy."} {:drug-name "PI:NAME:<NAME>END_PI" :clearance "IR" :desc "Wakey Wakey." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "IR" :desc "Focusol." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "R" :desc "Inner Happiness." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "R" :desc "Sleepy-Sleepy." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "R" :desc "Wide-Awake." } {:drug-name "PI:NAME:<NAME>END_PIxidine 2" :clearance "R" :desc "Wider Awake." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "R" :desc "E-Z-DUZ-IT." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "R" :desc "New You." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "R" :desc "MelloWake." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "R" :desc "Scramble." } {:drug-name "PI:NAME:<NAME>END_PI" :clearance "R" :desc "Smilies." } {:drug-name "Sodium Pentathol" :clearance "R" :desc "Filter Fighter." } {:drug-name "Zybenzaphrene" :clearance "O" :desc "Slumber Soft." } {:drug-name "Vulpazine" :clearance "O" :desc "Night Stalker." } {:drug-name "Calcium Carbonate" :clearance "O" :desc "Calm-n-Coat Antacid." } {:drug-name "Dioxromnurespa-butinol-3" :clearance "O" :desc "Sparkle Ultra." } {:drug-name "Asperquaint" :clearance "Y" :desc "Pep Pills." } {:drug-name "Erithermaboxadrine" :clearance "Y" :desc "Glow." } {:drug-name "Morlox" :clearance "Y" :desc "Furball." } {:drug-name "Telescopalamine" :clearance "G" :desc "Truth and Beauty. Self-finking pills." } {:drug-name "Necronomicil" :clearance "G" :desc "ReAnimator." } {:drug-name "Rolactin" :clearance "B" :desc "Happy Life." } {:drug-name "Thymoglandin" :clearance "B" :desc "Combat Quick." } {:drug-name "Oxyflucocillin" :clearance "B" :desc "Overdose Helper." } {:drug-name "Benetridin" :clearance "I" :desc "VideoLand." } {:drug-name "Diphenhydromegatoxine" :clearance "I" :desc "Regro." } {:drug-name "Dynomorphin" :clearance "U" :desc "" } {:drug-name "Hydropsionic Acid" :clearance "ILLEGAL" :desc "" } {:drug-name "Verasubsannine" :clearance "ILLEGAL" :desc "Believapills." } {:drug-name "Metamemopyroxide" :clearance "ILLEGAL" :desc "Friendly Fire." } ] ) (defn drugs-component "Component for rendering a list of drugs" [] (let [sort-atom (atom {:sort-key :drug-name})] (fn [] [:div [:div (shared/switcher-toolbar sort-atom [:sort-key] [[:drug-name "Name"] [:clearance "Clearance"] ] ) ] [:table {:class "table table-striped table-hover"} [:thead>tr [:th "Name"] [:th "Clearance"] [:th "Description"] ] [:tbody (->> ref-drugs ((case (:sort-key @sort-atom) :drug-name #(sort-by :drug-name %) :clearance #(sort-by (comp {"IR" 8 "R" 7 "O" 6 "Y" 5 "G" 4 "B" 3 "I" 2 "V" 1} :clearance) %) identity ) ) (map (fn [{:keys [drug-name clearance desc]}] [:tr [:td drug-name] [:td clearance] [:td desc]]) ) doall ) ] ] ] ) ) ) (defn specialties-component "Component for rendering specialties" [] (let [filter-atom (atom {:skills_parent nil})] (fn [] (let [specialties (shared/get-specialties)] [:div [:div (shared/switcher-toolbar filter-atom [:skills_parent] [[nil "No Filter"] ["M" "Management"] ["Su" "Subterfuge"]["V" "Violence"] ["H" "Hardware"] ["So" "Software"] ["W" "Wetware"] ["O" "Other"] ] ) ] [:table {:class "table table-striped table-hover"} [:thead>tr [:td "Name"] [:td "Parent Skill"] [:td "Description"] ] [:tbody (->> specialties ;; Filter skills (filter #(if (not (:skills_parent @filter-atom)) % (= (:skills_parent @filter-atom) (:skills_parent %)) ) ) ;; Sort Alphabetically (sort-by :skills_name) ;; Make it pretty (map (fn [{:keys [skills_name skills_desc skills_parent]}] ^{:key skills_name} [:tr [:td skills_name] [:td (shared/wrap-skill-initial skills_parent)] [:td skills_desc]])) doall ) ] ] "Filter: " (pr-str @filter-atom) ] ) ) ) ) (defn reference-component "Reference page for getting information" [] (let [page-atom (atom {:page nil})] (fn [] [:div [:div (shared/switcher-toolbar page-atom [:page] [[:specialties "Specialties"] [:drugs "Drugs"] ] ) ] (case (:page @page-atom) :skills "Not implemented" :specialties [specialties-component] :drugs [drugs-component] "Make a selection" ) ] ) ) )
[ { "context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,", "end": 48, "score": 0.9998855590820312, "start": 36, "tag": "NAME", "value": "Ronen Narkis" }, { "context": "ment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Versio", "end": 57, "score": 0.5612590312957764, "start": 54, "tag": "EMAIL", "value": "isr" }, { "context": " \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version 2.", "end": 61, "score": 0.6432312726974487, "start": 58, "tag": "EMAIL", "value": "com" } ]
src/aws/validations.clj
celestial-ops/core
1
(comment re-core, Copyright 2012 Ronen Narkis, narkisr.com Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns aws.validations "AWS based validations" (:require [re-core.model :refer (check-validity)] [clojure.core.strint :refer (<<)] [subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])) (def machine-entity {:machine { :hostname #{:required :String} :domain #{:required :String} :user #{:required :String} :os #{:required :Keyword} }}) (def ebs-type #{"io1" "standard" "gp2"}) (validation :ebs-type (when-not-nil ebs-type (<< "EBS type must be either ~{ebs-type}"))) (validation :volume { :device #{:required :device} :size #{:required :Integer} :clear #{:required :Boolean} :volume-type #{:required :ebs-type} :iops #{:Integer} }) (validation :iops (fn [{:keys [volume-type iops]}] (when (and (= volume-type "io1") (nil? iops)) "iops required if io1 type is used"))) (validation :volume* (every-v #{:volume})) (validation :io-volume* (every-v #{:iops})) (validation :group* (every-v #{:String})) (def aws-entity {:aws { :instance-type #{:required :String} :key-name #{:required :String} :endpoint #{:required :String} :volumes #{:volume* :io-volume*} :security-groups #{:Vector :group*} :availability-zone #{:String} :ebs-optimized #{:Boolean} }}) (defmethod check-validity [:aws :entity] [aws] (validate! aws (combine machine-entity aws-entity) :error ::invalid-system)) (def aws-provider {:instance-type #{:required :String} :key-name #{:required :String} :placement {:availability-zone #{:String}} :security-groups #{:Vector :group*} :min-count #{:required :Integer} :max-count #{:required :Integer} :ebs-optimized #{:Boolean} }) (defn provider-validation [{:keys [aws] :as spec}] (validate! aws aws-provider :error ::invalid-aws))
88572
(comment re-core, Copyright 2012 <NAME>, nark<EMAIL>.<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 aws.validations "AWS based validations" (:require [re-core.model :refer (check-validity)] [clojure.core.strint :refer (<<)] [subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])) (def machine-entity {:machine { :hostname #{:required :String} :domain #{:required :String} :user #{:required :String} :os #{:required :Keyword} }}) (def ebs-type #{"io1" "standard" "gp2"}) (validation :ebs-type (when-not-nil ebs-type (<< "EBS type must be either ~{ebs-type}"))) (validation :volume { :device #{:required :device} :size #{:required :Integer} :clear #{:required :Boolean} :volume-type #{:required :ebs-type} :iops #{:Integer} }) (validation :iops (fn [{:keys [volume-type iops]}] (when (and (= volume-type "io1") (nil? iops)) "iops required if io1 type is used"))) (validation :volume* (every-v #{:volume})) (validation :io-volume* (every-v #{:iops})) (validation :group* (every-v #{:String})) (def aws-entity {:aws { :instance-type #{:required :String} :key-name #{:required :String} :endpoint #{:required :String} :volumes #{:volume* :io-volume*} :security-groups #{:Vector :group*} :availability-zone #{:String} :ebs-optimized #{:Boolean} }}) (defmethod check-validity [:aws :entity] [aws] (validate! aws (combine machine-entity aws-entity) :error ::invalid-system)) (def aws-provider {:instance-type #{:required :String} :key-name #{:required :String} :placement {:availability-zone #{:String}} :security-groups #{:Vector :group*} :min-count #{:required :Integer} :max-count #{:required :Integer} :ebs-optimized #{:Boolean} }) (defn provider-validation [{:keys [aws] :as spec}] (validate! aws aws-provider :error ::invalid-aws))
true
(comment re-core, Copyright 2012 PI:NAME:<NAME>END_PI, narkPI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns aws.validations "AWS based validations" (:require [re-core.model :refer (check-validity)] [clojure.core.strint :refer (<<)] [subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])) (def machine-entity {:machine { :hostname #{:required :String} :domain #{:required :String} :user #{:required :String} :os #{:required :Keyword} }}) (def ebs-type #{"io1" "standard" "gp2"}) (validation :ebs-type (when-not-nil ebs-type (<< "EBS type must be either ~{ebs-type}"))) (validation :volume { :device #{:required :device} :size #{:required :Integer} :clear #{:required :Boolean} :volume-type #{:required :ebs-type} :iops #{:Integer} }) (validation :iops (fn [{:keys [volume-type iops]}] (when (and (= volume-type "io1") (nil? iops)) "iops required if io1 type is used"))) (validation :volume* (every-v #{:volume})) (validation :io-volume* (every-v #{:iops})) (validation :group* (every-v #{:String})) (def aws-entity {:aws { :instance-type #{:required :String} :key-name #{:required :String} :endpoint #{:required :String} :volumes #{:volume* :io-volume*} :security-groups #{:Vector :group*} :availability-zone #{:String} :ebs-optimized #{:Boolean} }}) (defmethod check-validity [:aws :entity] [aws] (validate! aws (combine machine-entity aws-entity) :error ::invalid-system)) (def aws-provider {:instance-type #{:required :String} :key-name #{:required :String} :placement {:availability-zone #{:String}} :security-groups #{:Vector :group*} :min-count #{:required :Integer} :max-count #{:required :Integer} :ebs-optimized #{:Boolean} }) (defn provider-validation [{:keys [aws] :as spec}] (validate! aws aws-provider :error ::invalid-aws))
[ { "context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brow", "end": 25, "score": 0.9998517036437988, "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.999934196472168, "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.9997670650482178, "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.9999335408210754, "start": 79, "tag": "EMAIL", "value": "cb@opscode.com" } ]
config/software/ree.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. ;; (software "ree" :source "ruby-enterprise-1.8.7-2011.01" :steps [ {:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib" "LDFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include -R/opt/opscode/embedded/lib" "CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"} :command "./installer" :args ["-a" "/opt/opscode/embedded" "--dont-install-useful-gems" "--no-dev-docs"]} ]) ;; These gory bits are going on inside the installer above. Left for future understanding [cb] ;; ["bash" "-c" "cd ./source/distro/google-perftools-1.4 && ./configure --prefix=/opt/opscode/embedded --disable-dependency-tracking && make libtcmalloc_minimal.la"] ;; [ "mkdir" "-p" "/opt/opscode/embedded/lib"] ;; [ "bash" "-c" (str "cp -Rpf " (cond (is-os? "darwin") "./source/distro/google-perftools-1.4/.libs/libtcmalloc_minimal.*" ;; (is-os? "linux") "./source/distro/google-perftools-1.4/.libs/libtcmalloc_minimal.*") " /opt/opscode/embedded/lib")] ;; ["bash" "-c" "cd ./source && ./configure --prefix=/opt/opscode/embedded --enable-mbari-api CFLAGS='-g -O2' --with-opt-dir=/opt/opscode/embedded"] ;; ["bash" "-c" ;; (cond (is-os? "darwin") "cd ./source && make RPATH=/opt/opscode/embedded/lib PRELIBS=\"-Wl,-rpath,/opt/opscode/embedded/lib -L/opt/opscode/embedded/lib -lsystem_allocator -ltcmalloc_minimal\"" ;; (is-os? "linux") "cd ./source && make RPATH=/opt/opscode/embedded/lib PRELIBS=\"-Wl,-rpath,/opt/opscode/embedded/lib -L/opt/opscode/embedded/lib -ltcmalloc_minimal\"")] ;; [ "bash" "-c" "cd ./source && env RPATH=/opt/opscode/embedded/lib make install"]])
107171
;; ;; 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. ;; (software "ree" :source "ruby-enterprise-1.8.7-2011.01" :steps [ {:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib" "LDFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include -R/opt/opscode/embedded/lib" "CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"} :command "./installer" :args ["-a" "/opt/opscode/embedded" "--dont-install-useful-gems" "--no-dev-docs"]} ]) ;; These gory bits are going on inside the installer above. Left for future understanding [cb] ;; ["bash" "-c" "cd ./source/distro/google-perftools-1.4 && ./configure --prefix=/opt/opscode/embedded --disable-dependency-tracking && make libtcmalloc_minimal.la"] ;; [ "mkdir" "-p" "/opt/opscode/embedded/lib"] ;; [ "bash" "-c" (str "cp -Rpf " (cond (is-os? "darwin") "./source/distro/google-perftools-1.4/.libs/libtcmalloc_minimal.*" ;; (is-os? "linux") "./source/distro/google-perftools-1.4/.libs/libtcmalloc_minimal.*") " /opt/opscode/embedded/lib")] ;; ["bash" "-c" "cd ./source && ./configure --prefix=/opt/opscode/embedded --enable-mbari-api CFLAGS='-g -O2' --with-opt-dir=/opt/opscode/embedded"] ;; ["bash" "-c" ;; (cond (is-os? "darwin") "cd ./source && make RPATH=/opt/opscode/embedded/lib PRELIBS=\"-Wl,-rpath,/opt/opscode/embedded/lib -L/opt/opscode/embedded/lib -lsystem_allocator -ltcmalloc_minimal\"" ;; (is-os? "linux") "cd ./source && make RPATH=/opt/opscode/embedded/lib PRELIBS=\"-Wl,-rpath,/opt/opscode/embedded/lib -L/opt/opscode/embedded/lib -ltcmalloc_minimal\"")] ;; [ "bash" "-c" "cd ./source && env RPATH=/opt/opscode/embedded/lib make install"]])
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. ;; (software "ree" :source "ruby-enterprise-1.8.7-2011.01" :steps [ {:env {"LD_RUN_PATH" "/opt/opscode/embedded/lib" "LDFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include -R/opt/opscode/embedded/lib" "CFLAGS" "-L/opt/opscode/embedded/lib -I/opt/opscode/embedded/include"} :command "./installer" :args ["-a" "/opt/opscode/embedded" "--dont-install-useful-gems" "--no-dev-docs"]} ]) ;; These gory bits are going on inside the installer above. Left for future understanding [cb] ;; ["bash" "-c" "cd ./source/distro/google-perftools-1.4 && ./configure --prefix=/opt/opscode/embedded --disable-dependency-tracking && make libtcmalloc_minimal.la"] ;; [ "mkdir" "-p" "/opt/opscode/embedded/lib"] ;; [ "bash" "-c" (str "cp -Rpf " (cond (is-os? "darwin") "./source/distro/google-perftools-1.4/.libs/libtcmalloc_minimal.*" ;; (is-os? "linux") "./source/distro/google-perftools-1.4/.libs/libtcmalloc_minimal.*") " /opt/opscode/embedded/lib")] ;; ["bash" "-c" "cd ./source && ./configure --prefix=/opt/opscode/embedded --enable-mbari-api CFLAGS='-g -O2' --with-opt-dir=/opt/opscode/embedded"] ;; ["bash" "-c" ;; (cond (is-os? "darwin") "cd ./source && make RPATH=/opt/opscode/embedded/lib PRELIBS=\"-Wl,-rpath,/opt/opscode/embedded/lib -L/opt/opscode/embedded/lib -lsystem_allocator -ltcmalloc_minimal\"" ;; (is-os? "linux") "cd ./source && make RPATH=/opt/opscode/embedded/lib PRELIBS=\"-Wl,-rpath,/opt/opscode/embedded/lib -L/opt/opscode/embedded/lib -ltcmalloc_minimal\"")] ;; [ "bash" "-c" "cd ./source && env RPATH=/opt/opscode/embedded/lib make install"]])
[ { "context": "S3MMCZSAQBMJZHWYJSHLGU4B5O1BH\"\n :client-secret \"DPSNOMYFT2WETDZBIQTHAUW352C0CWJ5S2POQH1UHK2RZVES\"\n :callback {:domain \"http://localhost:300", "end": 899, "score": 0.9997133016586304, "start": 851, "tag": "KEY", "value": "DPSNOMYFT2WETDZBIQTHAUW352C0CWJ5S2POQH1UHK2RZVES" } ]
src/foursquare_1self/handler.clj
anildigital/foursquare-1self
0
(ns foursquare-1self.handler (:require [compojure.core :refer :all] [compojure.handler :as handler] [compojure.route :as route] [cemerick.friend :as friend] [clj-http.client :as client] [friend-oauth2.workflow :as oauth2] [friend-oauth2.util :refer [format-config-uri get-access-token-from-params]] [cheshire.core :as j] (cemerick.friend [workflows :as workflows] [credentials :as creds]))) (declare render-status-page) (declare render-checkins-page) (declare get-foursquare-checkins) (defn credential-fn [token] ;;lookup token in DB or whatever to fetch appropriate :roles {:identity token :roles #{::user}}) (def client-config {:client-id "DOWYGA5X3PVX3WXXDL0S3MMCZSAQBMJZHWYJSHLGU4B5O1BH" :client-secret "DPSNOMYFT2WETDZBIQTHAUW352C0CWJ5S2POQH1UHK2RZVES" :callback {:domain "http://localhost:3000" :path "/auth/callback"}}) (def uri-config {:authentication-uri {:url "https://foursquare.com/oauth2/authenticate" :query {:client_id (:client-id client-config) :response_type "code" :redirect_uri (format-config-uri client-config) :scope "email"}} :access-token-uri {:url "https://foursquare.com/oauth2/access_token" :query {:client_id (:client-id client-config) :client_secret (:client-secret client-config) :grant_type "authorization_code" :redirect_uri (format-config-uri client-config)}}}) (defroutes ring-app (GET "/" request "<a href=\"/repos\">My Github Repositories</a><br><a href=\"/status\">Status</a>") (GET "/status" request (render-status-page request)) (GET "/repos" request (friend/authorize #{::user} (render-checkins-page request))) (friend/logout (ANY "/logout" request (ring.util.response/redirect "/")))) (def app (handler/site (friend/authenticate ring-app {:allow-anon? true :workflows [(oauth2/workflow {:client-config client-config :uri-config uri-config :access-token-parsefn get-access-token-from-params :credential-fn credential-fn})]}))) (defn render-status-page [request] (let [count (:count (:session request) 0) session (assoc (:session request) :count (inc count))] (-> (ring.util.response/response (str "<p>We've hit the session page " (:count session) " times.</p><p>The current session: " session "</p>")) (assoc :session session)))) (defn render-checkins-page "Shows a list of the current users github repositories by calling the github api with the OAuth2 access token that the friend authentication has retrieved." [request] (let [authentications (get-in request [:session :cemerick.friend/identity :authentications]) access-token (:access_token (second (first authentications))) checkin-response (get-foursquare-checkins access-token)] (str (vec (map :name checkin-response))))) (defn get-foursquare-checkins "Github API call for the current authenticated users repository list." [access-token] (let [url (str "https://api.foursquare.com/v2/users/self/checkins?oauth_token=" access-token) response (client/get url {:accept :json}) repos (j/parse-string (:body response) true)] repos))
12262
(ns foursquare-1self.handler (:require [compojure.core :refer :all] [compojure.handler :as handler] [compojure.route :as route] [cemerick.friend :as friend] [clj-http.client :as client] [friend-oauth2.workflow :as oauth2] [friend-oauth2.util :refer [format-config-uri get-access-token-from-params]] [cheshire.core :as j] (cemerick.friend [workflows :as workflows] [credentials :as creds]))) (declare render-status-page) (declare render-checkins-page) (declare get-foursquare-checkins) (defn credential-fn [token] ;;lookup token in DB or whatever to fetch appropriate :roles {:identity token :roles #{::user}}) (def client-config {:client-id "DOWYGA5X3PVX3WXXDL0S3MMCZSAQBMJZHWYJSHLGU4B5O1BH" :client-secret "<KEY>" :callback {:domain "http://localhost:3000" :path "/auth/callback"}}) (def uri-config {:authentication-uri {:url "https://foursquare.com/oauth2/authenticate" :query {:client_id (:client-id client-config) :response_type "code" :redirect_uri (format-config-uri client-config) :scope "email"}} :access-token-uri {:url "https://foursquare.com/oauth2/access_token" :query {:client_id (:client-id client-config) :client_secret (:client-secret client-config) :grant_type "authorization_code" :redirect_uri (format-config-uri client-config)}}}) (defroutes ring-app (GET "/" request "<a href=\"/repos\">My Github Repositories</a><br><a href=\"/status\">Status</a>") (GET "/status" request (render-status-page request)) (GET "/repos" request (friend/authorize #{::user} (render-checkins-page request))) (friend/logout (ANY "/logout" request (ring.util.response/redirect "/")))) (def app (handler/site (friend/authenticate ring-app {:allow-anon? true :workflows [(oauth2/workflow {:client-config client-config :uri-config uri-config :access-token-parsefn get-access-token-from-params :credential-fn credential-fn})]}))) (defn render-status-page [request] (let [count (:count (:session request) 0) session (assoc (:session request) :count (inc count))] (-> (ring.util.response/response (str "<p>We've hit the session page " (:count session) " times.</p><p>The current session: " session "</p>")) (assoc :session session)))) (defn render-checkins-page "Shows a list of the current users github repositories by calling the github api with the OAuth2 access token that the friend authentication has retrieved." [request] (let [authentications (get-in request [:session :cemerick.friend/identity :authentications]) access-token (:access_token (second (first authentications))) checkin-response (get-foursquare-checkins access-token)] (str (vec (map :name checkin-response))))) (defn get-foursquare-checkins "Github API call for the current authenticated users repository list." [access-token] (let [url (str "https://api.foursquare.com/v2/users/self/checkins?oauth_token=" access-token) response (client/get url {:accept :json}) repos (j/parse-string (:body response) true)] repos))
true
(ns foursquare-1self.handler (:require [compojure.core :refer :all] [compojure.handler :as handler] [compojure.route :as route] [cemerick.friend :as friend] [clj-http.client :as client] [friend-oauth2.workflow :as oauth2] [friend-oauth2.util :refer [format-config-uri get-access-token-from-params]] [cheshire.core :as j] (cemerick.friend [workflows :as workflows] [credentials :as creds]))) (declare render-status-page) (declare render-checkins-page) (declare get-foursquare-checkins) (defn credential-fn [token] ;;lookup token in DB or whatever to fetch appropriate :roles {:identity token :roles #{::user}}) (def client-config {:client-id "DOWYGA5X3PVX3WXXDL0S3MMCZSAQBMJZHWYJSHLGU4B5O1BH" :client-secret "PI:KEY:<KEY>END_PI" :callback {:domain "http://localhost:3000" :path "/auth/callback"}}) (def uri-config {:authentication-uri {:url "https://foursquare.com/oauth2/authenticate" :query {:client_id (:client-id client-config) :response_type "code" :redirect_uri (format-config-uri client-config) :scope "email"}} :access-token-uri {:url "https://foursquare.com/oauth2/access_token" :query {:client_id (:client-id client-config) :client_secret (:client-secret client-config) :grant_type "authorization_code" :redirect_uri (format-config-uri client-config)}}}) (defroutes ring-app (GET "/" request "<a href=\"/repos\">My Github Repositories</a><br><a href=\"/status\">Status</a>") (GET "/status" request (render-status-page request)) (GET "/repos" request (friend/authorize #{::user} (render-checkins-page request))) (friend/logout (ANY "/logout" request (ring.util.response/redirect "/")))) (def app (handler/site (friend/authenticate ring-app {:allow-anon? true :workflows [(oauth2/workflow {:client-config client-config :uri-config uri-config :access-token-parsefn get-access-token-from-params :credential-fn credential-fn})]}))) (defn render-status-page [request] (let [count (:count (:session request) 0) session (assoc (:session request) :count (inc count))] (-> (ring.util.response/response (str "<p>We've hit the session page " (:count session) " times.</p><p>The current session: " session "</p>")) (assoc :session session)))) (defn render-checkins-page "Shows a list of the current users github repositories by calling the github api with the OAuth2 access token that the friend authentication has retrieved." [request] (let [authentications (get-in request [:session :cemerick.friend/identity :authentications]) access-token (:access_token (second (first authentications))) checkin-response (get-foursquare-checkins access-token)] (str (vec (map :name checkin-response))))) (defn get-foursquare-checkins "Github API call for the current authenticated users repository list." [access-token] (let [url (str "https://api.foursquare.com/v2/users/self/checkins?oauth_token=" access-token) response (client/get url {:accept :json}) repos (j/parse-string (:body response) true)] repos))
[ { "context": "(ns ^{:author \"Bruno Bonacci (@BrunoBonacci)\" :no-doc true}\n com.brunobonac", "end": 28, "score": 0.9998553991317749, "start": 15, "tag": "NAME", "value": "Bruno Bonacci" }, { "context": "(ns ^{:author \"Bruno Bonacci (@BrunoBonacci)\" :no-doc true}\n com.brunobonacci.oneconfig.ba", "end": 43, "score": 0.998731791973114, "start": 29, "tag": "USERNAME", "value": "(@BrunoBonacci" } ]
1config-core/src/com/brunobonacci/oneconfig/backends/file1.clj
obohrer/1config
1
(ns ^{:author "Bruno Bonacci (@BrunoBonacci)" :no-doc true} com.brunobonacci.oneconfig.backends.file1 (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [in-memory-config-backend TestStore data]] [com.brunobonacci.oneconfig.util :refer :all])) (deftype ReadOnlySingleFileConfigBackend [file type content] TestStore (data [_] {:file file :type type :content content}) IConfigClient (find [this {:keys [key env version] :as config-entry}] (assoc config-entry :value content :content-type type :change-num (System/currentTimeMillis))) IConfigBackend (load [_ {:keys [key env version change-num] :as config-entry}] (assoc config-entry :value content :content-type type :change-num (System/currentTimeMillis))) (save [_ config-entry] (throw (ex-info "Operation not permitted on this type of backend." {:type "ReadOnlySingleFileConfigBackend" :file file}))) (list [this filters] [{:env "*" :key "*" :version "*" :content-type type :change-num (System/currentTimeMillis) :backend :fix}])) (defn file1-config-backend [file] (let [type (or (filename->content-type (str file)) (throw (ex-info "Unrecognised configuration file format." {:type "ReadOnlySingleFileConfigBackend" :file file}))) content (or (read-config-file file) (throw (ex-info "Unable to load configuration file." {:type "ReadOnlySingleFileConfigBackend" :file file})))] (ReadOnlySingleFileConfigBackend. file type content))) (comment (def c (file1-config-backend "/tmp/test.txt")) (data c) (list c {:env "dev"}) (find c {:key "amazon_password" :version "2.2.2" :env "dev"}) )
15452
(ns ^{:author "<NAME> (@BrunoBonacci)" :no-doc true} com.brunobonacci.oneconfig.backends.file1 (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [in-memory-config-backend TestStore data]] [com.brunobonacci.oneconfig.util :refer :all])) (deftype ReadOnlySingleFileConfigBackend [file type content] TestStore (data [_] {:file file :type type :content content}) IConfigClient (find [this {:keys [key env version] :as config-entry}] (assoc config-entry :value content :content-type type :change-num (System/currentTimeMillis))) IConfigBackend (load [_ {:keys [key env version change-num] :as config-entry}] (assoc config-entry :value content :content-type type :change-num (System/currentTimeMillis))) (save [_ config-entry] (throw (ex-info "Operation not permitted on this type of backend." {:type "ReadOnlySingleFileConfigBackend" :file file}))) (list [this filters] [{:env "*" :key "*" :version "*" :content-type type :change-num (System/currentTimeMillis) :backend :fix}])) (defn file1-config-backend [file] (let [type (or (filename->content-type (str file)) (throw (ex-info "Unrecognised configuration file format." {:type "ReadOnlySingleFileConfigBackend" :file file}))) content (or (read-config-file file) (throw (ex-info "Unable to load configuration file." {:type "ReadOnlySingleFileConfigBackend" :file file})))] (ReadOnlySingleFileConfigBackend. file type content))) (comment (def c (file1-config-backend "/tmp/test.txt")) (data c) (list c {:env "dev"}) (find c {:key "amazon_password" :version "2.2.2" :env "dev"}) )
true
(ns ^{:author "PI:NAME:<NAME>END_PI (@BrunoBonacci)" :no-doc true} com.brunobonacci.oneconfig.backends.file1 (:refer-clojure :exclude [find load list]) (:require [com.brunobonacci.oneconfig.backend :refer :all] [com.brunobonacci.oneconfig.backends.in-memory :refer [in-memory-config-backend TestStore data]] [com.brunobonacci.oneconfig.util :refer :all])) (deftype ReadOnlySingleFileConfigBackend [file type content] TestStore (data [_] {:file file :type type :content content}) IConfigClient (find [this {:keys [key env version] :as config-entry}] (assoc config-entry :value content :content-type type :change-num (System/currentTimeMillis))) IConfigBackend (load [_ {:keys [key env version change-num] :as config-entry}] (assoc config-entry :value content :content-type type :change-num (System/currentTimeMillis))) (save [_ config-entry] (throw (ex-info "Operation not permitted on this type of backend." {:type "ReadOnlySingleFileConfigBackend" :file file}))) (list [this filters] [{:env "*" :key "*" :version "*" :content-type type :change-num (System/currentTimeMillis) :backend :fix}])) (defn file1-config-backend [file] (let [type (or (filename->content-type (str file)) (throw (ex-info "Unrecognised configuration file format." {:type "ReadOnlySingleFileConfigBackend" :file file}))) content (or (read-config-file file) (throw (ex-info "Unable to load configuration file." {:type "ReadOnlySingleFileConfigBackend" :file file})))] (ReadOnlySingleFileConfigBackend. file type content))) (comment (def c (file1-config-backend "/tmp/test.txt")) (data c) (list c {:env "dev"}) (find c {:key "amazon_password" :version "2.2.2" :env "dev"}) )
[ { "context": "ng and executions\n\n(def ac1\n {:no \"cl-a1\" :name \"john doe\" :type ::trading})\n \n(def ac2\n {:no \"cl-a2\" :na", "end": 91, "score": 0.9997312426567078, "start": 83, "tag": "NAME", "value": "john doe" }, { "context": "ype ::trading})\n \n(def ac2\n {:no \"cl-a2\" :name \"j p morgan\" :type ::trading})\n \n; sample executions\n; used ", "end": 155, "score": 0.9997745752334595, "start": 145, "tag": "NAME", "value": "j p morgan" } ]
data/train/clojure/8f0825565331524348835301f7befea56ec5bee3trade.clj
harshp8l/deep-learning-lang-detection
84
; sample accounts ; use for trading and executions (def ac1 {:no "cl-a1" :name "john doe" :type ::trading}) (def ac2 {:no "cl-a2" :name "j p morgan" :type ::trading}) ; sample executions ; used for generating client trade (def ex1 {:ref-no "er-123" :account ac1 :instrument "eq-123" :value 1000}) (defn trading? "Returns true if the account is a trading account" [account] (= (:type account) ::trading)) ; stub that generates dummy reference no ; currently it generates 100 unconditionally ; in real life it will be a detailed algorithm for generating reference numbers (defn generate-trade-ref-no "Generate reference no" [] 100) (defn allocate "Allocate execution to client account and generate client trade" [acc exe] (cond (nil? acc) (throw (IllegalArgumentException. "account cannot be nil")) (= (trading? acc) false) (throw (IllegalArgumentException. "must be a trading account")) :else {:ref-no (generate-trade-ref-no) :account acc :instrument (:instrument exe) :value (:value exe)})) ; a macro to abstract boilerplates (defmacro with-account [acc & body] `(cond (nil? ~acc) (throw (IllegalArgumentException. "account cannot be nil")) (= (trading? ~acc) false) (throw (IllegalArgumentException. "must be a trading account")) :else ~@body)) ; allocate function using macro with-account (defn allocatem "Allocate execution to client account and generate client trade" [acc exe] (with-account acc {:ref-no (generate-trade-ref-no) :account acc :instrument (:instrument exe) :value (:value exe)}))
113641
; sample accounts ; use for trading and executions (def ac1 {:no "cl-a1" :name "<NAME>" :type ::trading}) (def ac2 {:no "cl-a2" :name "<NAME>" :type ::trading}) ; sample executions ; used for generating client trade (def ex1 {:ref-no "er-123" :account ac1 :instrument "eq-123" :value 1000}) (defn trading? "Returns true if the account is a trading account" [account] (= (:type account) ::trading)) ; stub that generates dummy reference no ; currently it generates 100 unconditionally ; in real life it will be a detailed algorithm for generating reference numbers (defn generate-trade-ref-no "Generate reference no" [] 100) (defn allocate "Allocate execution to client account and generate client trade" [acc exe] (cond (nil? acc) (throw (IllegalArgumentException. "account cannot be nil")) (= (trading? acc) false) (throw (IllegalArgumentException. "must be a trading account")) :else {:ref-no (generate-trade-ref-no) :account acc :instrument (:instrument exe) :value (:value exe)})) ; a macro to abstract boilerplates (defmacro with-account [acc & body] `(cond (nil? ~acc) (throw (IllegalArgumentException. "account cannot be nil")) (= (trading? ~acc) false) (throw (IllegalArgumentException. "must be a trading account")) :else ~@body)) ; allocate function using macro with-account (defn allocatem "Allocate execution to client account and generate client trade" [acc exe] (with-account acc {:ref-no (generate-trade-ref-no) :account acc :instrument (:instrument exe) :value (:value exe)}))
true
; sample accounts ; use for trading and executions (def ac1 {:no "cl-a1" :name "PI:NAME:<NAME>END_PI" :type ::trading}) (def ac2 {:no "cl-a2" :name "PI:NAME:<NAME>END_PI" :type ::trading}) ; sample executions ; used for generating client trade (def ex1 {:ref-no "er-123" :account ac1 :instrument "eq-123" :value 1000}) (defn trading? "Returns true if the account is a trading account" [account] (= (:type account) ::trading)) ; stub that generates dummy reference no ; currently it generates 100 unconditionally ; in real life it will be a detailed algorithm for generating reference numbers (defn generate-trade-ref-no "Generate reference no" [] 100) (defn allocate "Allocate execution to client account and generate client trade" [acc exe] (cond (nil? acc) (throw (IllegalArgumentException. "account cannot be nil")) (= (trading? acc) false) (throw (IllegalArgumentException. "must be a trading account")) :else {:ref-no (generate-trade-ref-no) :account acc :instrument (:instrument exe) :value (:value exe)})) ; a macro to abstract boilerplates (defmacro with-account [acc & body] `(cond (nil? ~acc) (throw (IllegalArgumentException. "account cannot be nil")) (= (trading? ~acc) false) (throw (IllegalArgumentException. "must be a trading account")) :else ~@body)) ; allocate function using macro with-account (defn allocatem "Allocate execution to client account and generate client trade" [acc exe] (with-account acc {:ref-no (generate-trade-ref-no) :account acc :instrument (:instrument exe) :value (:value exe)}))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998714923858643, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "ps://github.com/trptcolin/reply/\"\n :author \"Chas Emerick\"}\n clojure.tools.nrepl.cmdline\n (:require [cloj", "end": 656, "score": 0.9998872876167297, "start": 644, "tag": "NAME", "value": "Chas Emerick" } ]
server/target/clojure/tools/nrepl/cmdline.clj
OctavioBR/healthcheck
0
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns #^{:doc "A proof-of-concept command-line client for nREPL. Please see e.g. reply for a proper command-line nREPL client @ https://github.com/trptcolin/reply/" :author "Chas Emerick"} clojure.tools.nrepl.cmdline (:require [clojure.tools.nrepl :as repl] [clojure.tools.nrepl.transport :as transport]) (:use (clojure.tools.nrepl [server :only (start-server)] [ack :only (send-ack)]))) (defn- ensure-newline [s] (if (= "\n" (last s)) s (str s \newline))) (def colored-output {:err #(binding [*out* *err*] (print "\033[31m") (print %) (print "\033[m") (flush)) :out print :value (fn [x] (print "\033[34m") (print x) (print "\033[m") (flush))}) (defn- run-repl ([port] (run-repl port nil)) ([port {:keys [prompt err out value] :or {prompt #(print (str % "=> ")) err println out println value println}}] (let [transport (repl/connect :host "localhost" :port port) client (repl/client-session (repl/client transport Long/MAX_VALUE)) ns (atom "user") {:keys [major minor incremental qualifier]} *clojure-version*] (println "network-repl") (println (str "Clojure " (clojure-version))) (loop [] (prompt @ns) (flush) (doseq [res (repl/message client {:op "eval" :code (pr-str (read))})] (when (:value res) (value (:value res))) (when (:out res) (out (:out res))) (when (:err res) (err (:err res))) (when (:ns res) (reset! ns (:ns res)))) (recur))))) (def #^{:private true} unary-options #{"--interactive" "--color"}) (defn- split-args [args] (loop [[arg & rem-args :as args] args options {}] (if-not (and arg (re-matches #"--.*" arg)) [options args] (if (unary-options arg) (recur rem-args (assoc options arg true)) (recur (rest rem-args) (assoc options arg (first rem-args))))))) (defn -main [& args] (let [[options args] (split-args args) server (start-server :port (Integer/parseInt (or (options "--port") "0"))) ssocket (:ss @server)] (when-let [ack-port (options "--ack")] (binding [*out* *err*] (println (format "ack'ing my port %d to other server running on port %s" (.getLocalPort ssocket) ack-port) (:status (send-ack (.getLocalPort ssocket) (Integer/parseInt ack-port)))))) (if (options "--interactive") (run-repl (.getLocalPort ssocket) (when (options "--color") colored-output)) ; need to hold process open with a non-daemon thread -- this should end up being super-temporary (Thread/sleep Long/MAX_VALUE))))
80827
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns #^{:doc "A proof-of-concept command-line client for nREPL. Please see e.g. reply for a proper command-line nREPL client @ https://github.com/trptcolin/reply/" :author "<NAME>"} clojure.tools.nrepl.cmdline (:require [clojure.tools.nrepl :as repl] [clojure.tools.nrepl.transport :as transport]) (:use (clojure.tools.nrepl [server :only (start-server)] [ack :only (send-ack)]))) (defn- ensure-newline [s] (if (= "\n" (last s)) s (str s \newline))) (def colored-output {:err #(binding [*out* *err*] (print "\033[31m") (print %) (print "\033[m") (flush)) :out print :value (fn [x] (print "\033[34m") (print x) (print "\033[m") (flush))}) (defn- run-repl ([port] (run-repl port nil)) ([port {:keys [prompt err out value] :or {prompt #(print (str % "=> ")) err println out println value println}}] (let [transport (repl/connect :host "localhost" :port port) client (repl/client-session (repl/client transport Long/MAX_VALUE)) ns (atom "user") {:keys [major minor incremental qualifier]} *clojure-version*] (println "network-repl") (println (str "Clojure " (clojure-version))) (loop [] (prompt @ns) (flush) (doseq [res (repl/message client {:op "eval" :code (pr-str (read))})] (when (:value res) (value (:value res))) (when (:out res) (out (:out res))) (when (:err res) (err (:err res))) (when (:ns res) (reset! ns (:ns res)))) (recur))))) (def #^{:private true} unary-options #{"--interactive" "--color"}) (defn- split-args [args] (loop [[arg & rem-args :as args] args options {}] (if-not (and arg (re-matches #"--.*" arg)) [options args] (if (unary-options arg) (recur rem-args (assoc options arg true)) (recur (rest rem-args) (assoc options arg (first rem-args))))))) (defn -main [& args] (let [[options args] (split-args args) server (start-server :port (Integer/parseInt (or (options "--port") "0"))) ssocket (:ss @server)] (when-let [ack-port (options "--ack")] (binding [*out* *err*] (println (format "ack'ing my port %d to other server running on port %s" (.getLocalPort ssocket) ack-port) (:status (send-ack (.getLocalPort ssocket) (Integer/parseInt ack-port)))))) (if (options "--interactive") (run-repl (.getLocalPort ssocket) (when (options "--color") colored-output)) ; need to hold process open with a non-daemon thread -- this should end up being super-temporary (Thread/sleep Long/MAX_VALUE))))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns #^{:doc "A proof-of-concept command-line client for nREPL. Please see e.g. reply for a proper command-line nREPL client @ https://github.com/trptcolin/reply/" :author "PI:NAME:<NAME>END_PI"} clojure.tools.nrepl.cmdline (:require [clojure.tools.nrepl :as repl] [clojure.tools.nrepl.transport :as transport]) (:use (clojure.tools.nrepl [server :only (start-server)] [ack :only (send-ack)]))) (defn- ensure-newline [s] (if (= "\n" (last s)) s (str s \newline))) (def colored-output {:err #(binding [*out* *err*] (print "\033[31m") (print %) (print "\033[m") (flush)) :out print :value (fn [x] (print "\033[34m") (print x) (print "\033[m") (flush))}) (defn- run-repl ([port] (run-repl port nil)) ([port {:keys [prompt err out value] :or {prompt #(print (str % "=> ")) err println out println value println}}] (let [transport (repl/connect :host "localhost" :port port) client (repl/client-session (repl/client transport Long/MAX_VALUE)) ns (atom "user") {:keys [major minor incremental qualifier]} *clojure-version*] (println "network-repl") (println (str "Clojure " (clojure-version))) (loop [] (prompt @ns) (flush) (doseq [res (repl/message client {:op "eval" :code (pr-str (read))})] (when (:value res) (value (:value res))) (when (:out res) (out (:out res))) (when (:err res) (err (:err res))) (when (:ns res) (reset! ns (:ns res)))) (recur))))) (def #^{:private true} unary-options #{"--interactive" "--color"}) (defn- split-args [args] (loop [[arg & rem-args :as args] args options {}] (if-not (and arg (re-matches #"--.*" arg)) [options args] (if (unary-options arg) (recur rem-args (assoc options arg true)) (recur (rest rem-args) (assoc options arg (first rem-args))))))) (defn -main [& args] (let [[options args] (split-args args) server (start-server :port (Integer/parseInt (or (options "--port") "0"))) ssocket (:ss @server)] (when-let [ack-port (options "--ack")] (binding [*out* *err*] (println (format "ack'ing my port %d to other server running on port %s" (.getLocalPort ssocket) ack-port) (:status (send-ack (.getLocalPort ssocket) (Integer/parseInt ack-port)))))) (if (options "--interactive") (run-repl (.getLocalPort ssocket) (when (options "--color") colored-output)) ; need to hold process open with a non-daemon thread -- this should end up being super-temporary (Thread/sleep Long/MAX_VALUE))))
[ { "context": "did: \" message))\n\n`(blarg# blarg#)\n\n`(let [name# \"Larry Potter\"] name#)\n\n\n(eval `(+ ~@(list 1 2 3)))\n\n(range 0 5", "end": 3059, "score": 0.9994469285011292, "start": 3047, "tag": "NAME", "value": "Larry Potter" }, { "context": "+ ~@alist)))\n\n(summation (range 0 12))\n\n(def var \"Salman\")\n\n\n(println `(first ~@var))\n\n(defmacro infix\n [", "end": 3204, "score": 0.9994292259216309, "start": 3198, "tag": "NAME", "value": "Salman" }, { "context": "adshot]\n true)\n\n(let [notify (delay (email-user \"and-my-axe@gmail.com\"))]\n (doseq [headshot gimli-headshots]\n (futu", "end": 5087, "score": 0.9998877644538879, "start": 5067, "tag": "EMAIL", "value": "and-my-axe@gmail.com" }, { "context": "l 0\n :percent-deteriorated 0}))\n\n@fred\n\n(let [zombie-state @fred]\n (if (>= (:percent-de", "end": 7667, "score": 0.9975389242172241, "start": 7663, "tag": "USERNAME", "value": "fred" }, { "context": "el increase-by}))\n\n(increase-cuddle-hunger-level @fred 10)\n\n(swap! fred increase-cuddle-hunger-level 10)", "end": 8141, "score": 0.9790576696395874, "start": 8137, "tag": "USERNAME", "value": "fred" }, { "context": "level 0\n :percent-deteriorated 0})\n\n@fred\n\n(defn shuffle-speed\n [zombie]\n (* (:cuddle-hun", "end": 8612, "score": 0.9958925247192383, "start": 8608, "tag": "USERNAME", "value": "fred" }, { "context": "q=word\"))\n\n(def ^:dynamic *notification-address* \"dobby@elf.org\")\n\n(= #{} (set nil))\n\n(= 3 (count #{1 2 3}))\n\n(= ", "end": 10922, "score": 0.9998400807380676, "start": 10909, "tag": "EMAIL", "value": "dobby@elf.org" }, { "context": "ame a) \" eats meat.\"))\n\n(def salman (atom {:name \"Salman\" :eater :carnivore}))\n(def shihab (atom {:name \"S", "end": 12013, "score": 0.9993048906326294, "start": 12007, "tag": "NAME", "value": "Salman" }, { "context": "n\" :eater :carnivore}))\n(def shihab (atom {:name \"Shihab\" :eater :herbivore}))\n\n(time (reset! shihab (asso", "end": 12068, "score": 0.9994022250175476, "start": 12062, "tag": "NAME", "value": "Shihab" }, { "context": " false))\n\n(carnivore? @shihab)\n\n@salman\n\n(ns koans.meditations.lazy-sequences)\n\n\"There ar", "end": 12290, "score": 0.8737180233001709, "start": 12284, "tag": "USERNAME", "value": "salman" }, { "context": "R nil}))\n\n(xconj nil 5)\n\n(def salman (ref {:name \"Salman\"}))\n\n(assoc @salman :age 10)\n\n(def the-world (ref", "end": 18042, "score": 0.9979961514472961, "start": 18036, "tag": "NAME", "value": "Salman" }, { "context": "ial + 20)))))\n\n(def bizarro-world (ref {}))\n\n(= [\"Real Jerry\" \"Bizarro Jerry\"\n (do\n (dosync\n ", "end": 19056, "score": 0.9934424757957458, "start": 19046, "tag": "NAME", "value": "Real Jerry" }, { "context": "\n\n(def bizarro-world (ref {}))\n\n(= [\"Real Jerry\" \"Bizarro Jerry\"\n (do\n (dosync\n (ref-set the-wor", "end": 19072, "score": 0.999286949634552, "start": 19059, "tag": "NAME", "value": "Bizarro Jerry" }, { "context": "-world {})\n (alter the-world assoc :jerry \"Real Jerry\")\n (alter bizarro-world assoc :jerry \"Biza", "end": 19178, "score": 0.9819948673248291, "start": 19168, "tag": "NAME", "value": "Real Jerry" }, { "context": "erry\")\n (alter bizarro-world assoc :jerry \"Bizarro Jerry\")))])\n\n(def atomic-clock (atom 0))\n\n\"Atoms are li", "end": 19237, "score": 0.998751163482666, "start": 19224, "tag": "NAME", "value": "Bizarro Jerry" } ]
clojure/ex4.clj
defunSM/code
0
(ns ex4.core) (defmacro backwards [form] (reverse form)) (backwards (" backwards" " am" "I" str)) (def addition-list (list + 1 2)) (eval addition-list) (eval (concat addition-list [10])) (eval (list 'def 'lucky-number (concat addition-list [10]))) lucky-number (str "To understand what recursion is," " you must first understand recursion") (list? (read-string "(+ 1 2)")) (conj (read-string "(+ 1 2)") :zagglewag) (#(+ 1 %) 3) (read-string "'(a b c)") (read-string "@var") (read-string "; ignore!\n(+ 1 2)") (eval (list (read-string "+") 1 2)) (eval (read-string "()")) (+ 1 2) (+ 1 (+ 2 3)) (if true 1 2) '(a b c) (read-string "(1 + 1)") (eval (let [infix (read-string "(1 + 1)")] (list (second infix) (first infix) (last infix)))) (defmacro ignore-last-operand [function-call] (butlast function-call)) (ignore-last-operand (+ 1 2 10)) (ignore-last-operand (+ 1 2 (println "Look at me!!!"))) (defmacro infix [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (1 + 2)) (defn read-resource [path] (read-string (slurp (clojure.java.io/resource path)))) (defn read-resource [path] (-> path clojure.java.io/resource slurp read-string)) (defmacro my-print [expression] (list 'let ['result expression] (list 'println 'result) 'result)) '(+ 1 ~(inc 1)) (defmacro code-critic [bad good] (list 'do (list 'println "Great squid of Madrid, this is bad code:" (list 'quote bad)) (list 'println "Sweet gorilla of Manila, this is good code:" (list 'quote good)))) (code-critic (1 + 1) (+ 1 1)) (defmacro code-critic [bad good] `(do (println "Great squid of Madrid, this is bad code:" (quote ~bad)) (println "Sweet gorilla of Manila, this is good code:" (quote ~good)))) (code-critic (1 + 1) (+ 1 1)) (defn criticize-code [criticism code] `(println ~criticism (quote ~code))) (defmacro code-critic [bad good] `(do ~(criticize-code "Cursed bacteria of Liberia this is bad code:" bad) ~(criticize-code "Sweet sacred boa of Western this is good code:" good))) (code-critic (1 + 1) (+ 1 1)) (defmacro code-critic [{:keys [good bad]}] `(do ~@(map #(apply criticize-code %) [["Sweet lion of Zion, this is bad code:" bad] ["Great cow of Moscow, this is good code:" good]]))) (code-critic (1 + 1) (+ 1 1)) (def message "Good Job!") (defmacro with-mischief [& stuff-to-do] (concat (list 'let ['message "oh, big deal!"]) stuff-to-do)) (with-mischief (println "Heres how I feel about that thing you did: " message)) (defmacro without-mischief [& stuff-to-do] (let [macro-message (gensym 'message)] `(let [~macro-message "Oh, big deal!"] ~@stuff-to-do (println "I still need to say " ~macro-message)))) (without-mischief (println "Heres how I feel about that thing you did: " message)) `(blarg# blarg#) `(let [name# "Larry Potter"] name#) (eval `(+ ~@(list 1 2 3))) (range 0 5) (defn summation [alist] (eval `(+ ~@alist))) (summation (range 0 12)) (def var "Salman") (println `(first ~@var)) (defmacro infix [something] (eval (list (second something) (first something) (last something)))) (infix (1 + 1)) (defmacro report [to-try] `(if ~to-try (println (quote ~to-try) "was successful:" ~to-try) (println (quote ~to-try) "was not successful:" ~to-try))) (defmacro report [to-try] `(let [result# ~to-try] (if result# (println (quote ~to-try) "was successful:" result#) (println (quote ~to-try) "was not successful:" result#)))) (report (do (Thread/sleep 1000) (+ 1 1))) (doseq [code ['(= 1 1) '(= 1 2)]] (report code)) (rand-int 2) (defmacro doseq-macro [macroname & args] `(do ~@(map (fn [arg] (list macroname arg)) args))) (doseq-macro report (= 1 1) (= 1 2)) (def order-detials-validations {:name ["Please enter a name" not-empty] :email ["Please enter an email address" not-empty]}) (future (Thread/sleep 4000) (println "I'll print after 4 seconds")) (let [result (future (println "This prints once") (+ 1 1))] (println "deref: " (deref result)) (println "@: " @result)) (let [result (future (Thread/sleep 3000) (+ 1 1))] (println "It will be at least 3 seconds before I print.") (println "The result will be: " @result)) (deref (future (Thread/sleep 1000) 0) 1000 5) (realized? (future (Thread/sleep 1000))) (let [f (future)] @f (realized? f)) (def jackson-5-delay (delay (let [message "Just call my name and I'll be there"] (println "First deref:" message) message))) (force jackson-5-delay) (println @jackson-5-delay) (def gimli-headshots ["serious.jpg" "fun.jpg" "playful.jpg"]) (defn email-user [email-address] (println "Sending headshot notification to" email-address)) (defn upload-document [headshot] true) (let [notify (delay (email-user "and-my-axe@gmail.com"))] (doseq [headshot gimli-headshots] (future (upload-document headshot) (force notify)))) (def my-promise (promise)) (deliver my-promise (+ 1 2)) @my-promise (def yak-butter-international {:store "Yak Butter International" :price 90 :smoothness 90}) (def better-than-nothing {:store "Butter than Nothing" :price 150 :smoothness 83}) (def baby-got-yak {:store "Baby Got Yak" :price 94 :smoothness 99}) (defn mock-api-call [result] (Thread/sleep 1000) result) (defn satisfactory? [butter] (and (<= (:price butter) 100) (>= (:smoothness butter) 97) butter)) (mock-api-call (if (satisfactory? baby-got-yak) (println "This is satisfactory.") (println "This is NOT satisfactory"))) (time (some (comp satisfactory? mock-api-call) [yak-butter-international better-than-nothing baby-got-yak])) (time (let [butter-promise (promise)] (doseq [butter [yak-butter-international better-than-nothing baby-got-yak]] (future (if-let [satisfactory-butter (satisfactory? (mock-api-call butter))] (deliver butter-promise satisfactory-butter)))) (println "And the winner is:" (:store @butter-promise)))) (let [ferengi-wisdom-promise (promise)] (future (println "here's some Ferengi wisdom:" @ferengi-wisdom-promise)) (Thread/sleep 1000) (deliver ferengi-wisdom-promise "Whisper your way to such success.")) (defmacro wait [timeout & body] `(do (Thread/sleep ~timeout) ~@body)) (time (wait 1000 (+ 1 1))) (let [saying3 (promise)] (future (deliver saying3 (wait 100 "Cheerio!"))) @(let [saying2 (promise)] (future (deliver saying2 (wait 400 "Pip pip!"))) @(let [saying1 (promise)] (future (deliver saying1 (wait 200 "'Ello, gov'n"))) (println @saying1) saying1) (println @saying2) saying2) (println @saying3) saying3) (time @(-> (enqueue saying (wait 200 "'Ello, gov'na!") (println @saying)) (enqueue saying (wait 400 "Pip ip!") (println @saying)) (enqueue saying (wait 100 "Cheerio!") (println @saying)))) (defmacro enqueue ([q concurrent-promise-name concurrent serialized] `(let [~concurrent-promise-name (promise)] (future (deliver ~concurrent-promise-name ~concurrent)) (deref ~q) ~serialized ~concurrent-promise-name)) ([concurrent-promise-name concurrent serialized] `(enqueue (future) ~concurrent-promise-name ~concurrent ~serialized))) (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 0})) @fred (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))))) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) (swap! fred increase-cuddle-hunger-level 10) (update-in {:a {:b 10}} [:a :b] inc) (swap! fred update-in [:cuddle-hunger-level] + 10) (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current State:" @num)) (-> (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current State:" @num))) (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) @fred (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to your courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) (swap! fred update-in [:cuddle-hunger-level] + 30) (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100)) (throw (IllegalStateException. "That's not mathy!"))) (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome [name] {:name name :socks #{}}) (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) (steal-sock sock-gnome dryer) (:socks @sock-gnome) (require 'clojure.xml) (parse) (use '[clojure.xml :only (parse)]) (parse (slurp "https://www.google.com/?gws_rd=ssl#q=word")) (def ^:dynamic *notification-address* "dobby@elf.org") (= #{} (set nil)) (= 3 (count #{1 2 3})) (= #{1 2 3 4 5} (set '(1 1 2 2 3 3 4 4 5 5))) (= #{1 2 3 4 5} (clojure.set/union #{1 2 3 4} #{2 3 5})) (= {:a :b} (hash-map :a :b)) (get {:a 1 :b 2} :b) (= ({:a 1 :b 2} :b) (get {:a 1 :b 2} :b)) (time ({:a 1 :b 2} :b)) (time (:b {:a 1 :b 2})) (time (assoc {:a 1 :b 2} :c 3)) (= 6 (#(* 3 %1 %2) 1 2)) (= 25 ((fn [x] (x 5)) (fn [n] (* n n)))) (let [x 5] (= :your-road (cond (= x 1) :false-road (= x 2) :falsey-road :else :your-road))) (if-not (zero? 1) true false) (defn explain-defcon [term] (case term :level-one :blue :level-two :red :level-three :green)) (explain-defcon :level-two) (map (fn [x] (* x x)) (vec (range 0 10))) (= "longest" (reduce (fn [a b] (if (< (count a) (count b)) b a)) ["which" "word" "is" "longest"])) (defmulti diet (fn [x] (:eater x))) (defmethod diet :herbivore [a] (str (:name a) " eats leafs.")) (defmethod diet :carnivore [a] (str (:name a) " eats meat.")) (def salman (atom {:name "Salman" :eater :carnivore})) (def shihab (atom {:name "Shihab" :eater :herbivore})) (time (reset! shihab (assoc @shihab :eater :herbivore))) (defn carnivore? [x] (if (= (:eater x) :carnivore) true false)) (carnivore? @shihab) @salman (ns koans.meditations.lazy-sequences) "There are many ways to generate a sequence" (= '(1 2 3 4) (range 1 5)) "The range starts at the beginning by default" (= '(0 1 2 3 4) (range 5)) "Only take what you need when the sequence is large" (= [0 1 2 3 4 5 6 7 8 9] (take 10 (range 100))) "Or limit results by dropping what you don't need" (= [95 96 97 98 99] (drop 95 (range 100))) "Iteration provides an infinite lazy sequence" (= (range 20) (take 20 (iterate inc 0))) "Repetition is key" (= [:a :a :a :a :a :a :a :a :a :a] (repeat 10 :a)) "Iteration can be used for repetition" (= (repeat 100 :foo) (take 100 (iterate (fn [x] x) :foo))) (repeat 100 :foo) "Sequence comprehensions can bind each element in turn to a symbol" (= '(0 1 2 3 4 5) (for [index (range 6)] index)) "They can easily emulate mapping" (= '(0 1 4 9 16 25) (map (fn [index] (* index index)) (range 6)) (for [index (range 6)] (* index index))) "And also filtering" (= '(1 3 5 7 9) (filter odd? (range 10)) (for [index (range 10) :when (odd? index)] index)) "Combinations of these transformations is trivial" (= '(1 9 25 49 81) (map (fn [index] (* index index)) (filter odd? (range 10))) (for [index (range 10) :when (odd? index)] (* index index))) "More complex transformations simply take multiple binding forms" (= [[:top :left] [:top :middle] [:top :right] [:middle :left] [:middle :middle] [:middle :right] [:bottom :left] [:bottom :middle] [:bottom :right]] (for [row [:top :middle :bottom] column [:left :middle :right]] [row column])) "One may know what they seek by knowing what they do not seek" (= [true false true] (let [not-a-symbol? (complement symbol?)] (map not-a-symbol? [:a 'b "c"]))) "Praise and 'complement' may help you separate the wheat from the chaff" (= [:wheat "wheat" 'wheat] (let [not-nil? (complement nil?)] (filter not-nil? [nil :wheat nil "wheat" nil 'wheat nil]))) "Partial functions allow procrastination" (= 20 (let [multiply-by-5 (partial * 5)] (multiply-by-5 4))) "Don't forget: first things first" (= [:a :b :c :d] (let [ab-adder (partial concat [:a :b])] (ab-adder [:c :d]))) (defn square [n] (* n n)) "Functions can join forces as one 'composed' function" (= 25 (let [inc-and-square (comp square inc)] (inc-and-square 4))) "Have a go on a double dec-er" (= 8 (let [double-dec (comp dec dec)] (double-dec 10))) "Be careful about the order in which you mix your functions" (= 99 (let [square-and-dec (comp dec square)] (square-and-dec 10))) #_(def koans '( "Recursion ends with a base case" (= true (is-even? 0)) "And starts by moving toward that base case" (= false (is-even? 1)) #_( "Having too many stack frames requires explicit tail calls with recur" (= false (is-even-bigint? 100003N))) "Reversing directions is easy when you have not gone far" (= '(1) (recursive-reverse [1])) "Yet it becomes more difficult the more steps you take" (= '(5 4 3 2 1) (recursive-reverse [1 2 3 4 5])) "Simple things may appear simple." (= 1 (factorial 1)) "They may require other simple steps." (= 2 (factorial 2)) "Sometimes a slightly bigger step is necessary" (= 6 (factorial 3)) "And eventually you must think harder" (= 24 (factorial 4)) #(_ "You can even deal with very large numbers" (< 1000000000000000000000000N (factorial 1000N)) "But what happens when the machine limits you?" (< 1000000000000000000000000N (factorial 100003N))))) (defn factorial [n] (loop [n n acc 1] (if (= 0 n) 1 (recur (dec n) (* n acc))))) (factorial 10) (defn is-even? [n] (if (= n 0) true (not (is-even? (dec n))))) (is-even? 2) (defn is-even-bigint? [n] (loop [n n acc true] (if (= n 0) acc (recur (dec n) (not acc))))) (defn recursive-reverse [coll] (loop [coll coll reversed ()] (if (= () coll) reversed (recur (rest coll) (cons (first coll) reversed))))) (clojure.string/join (concat "s" "a")) (defn strict-map1 [f coll] (loop [coll coll, acc nil] (if (empty? coll) (reverse acc) (recur (next coll) (cons (f (first coll)) acc))))) (strict-map1 - (range 5)) (defn strict-map2 [f coll] (loop [coll coll, acc []] (if (empty? coll) acc (recur (next coll) (conj acc (f (first coll))))))) (vector? (first {:width 10 :height 20 :depth 15})) (nth (vec {:width 10 :height 20 :depth 15}) 2) (doseq [[dimension amount] {:width 10 :height 20 :depth 15}] (println (str (name dimension) ":") amount "inches")) (def dice1 (range 5)) (range 5) (defmethod print-method clojure.lang.PersistentQueue [q, w] (print-method '<- w) (print-method (seq q) w) (print-method '-< w)) (def schedule (conj clojure.lang.PersistentQueue/EMPTY :wake-up :shower :brush-teeth)) (last schedule) (pop schedule) (def new (rest schedule)) (#{:a :b :c :d} :c) (#{:a :b :c :d} :e) (get #{:a 1 :b 2} :b) #{[] ()} (sorted-set [3 4] [1 2]) (def my-set (sorted-set :a :b)) (contains? #(1 2 3 4) 4) (clojure.set/difference #{1 2 3 4} #{3 4 5 6}) (defn xconj [t v] (cond (nil? t) {:val v :L nil :R nil})) (xconj nil 5) (def salman (ref {:name "Salman"})) (assoc @salman :age 10) (def the-world (ref "hello")) (def the-world (ref "hello")) (def bizarro-world (ref {})) (meditations "In the beginning, there was a word" (= __ (deref the-world)) "You can get the word more succinctly, but it's the same" (= __ @the-world) "You can be the change you wish to see in the world." "Alter where you need not replace" (= __ (let [exclamator (fn [x] (str x "!"))] (dosync (alter the-world exclamator) (alter the-world exclamator) (alter the-world exclamator)) @the-world)) "Don't forget to do your work in a transaction!" "Functions passed to alter may depend on the data in the ref" "Two worlds are better than one") (= "better" (do (dosync (ref-set the-world "better")) @the-world)) (= 0 (do (dosync (ref-set the-world 0)) @the-world)) (= 20 (do (dosync (alter the-world (partial + 20))))) (def bizarro-world (ref {})) (= ["Real Jerry" "Bizarro Jerry" (do (dosync (ref-set the-world {}) (alter the-world assoc :jerry "Real Jerry") (alter bizarro-world assoc :jerry "Bizarro Jerry")))]) (def atomic-clock (atom 0)) "Atoms are like refs" (= 0 @atomic-clock "You can change at the swap meet" (= 1 (do (swap! atomic-clock inc) @atomic-clock)) "Keep taxes out of this: swapping requires no transaction" (= 5 (do (swap! atomic-clock + 4) @atomic-clock)) "Any number of arguments might happen during a swap" (= 20 (do (swap! atomic-clock + 1 2 3 4 5) @atomic-clock)) "Atomic atoms are atomic" (= 20 (do (compare-and-set! atomic-clock 100 :fin) @atomic-clock)) "When your expectations are aligned with reality, things proceed that way" (= :fin (do (compare-and-set! atomic-clock 20 :fin) @atomic-clock))) "Wrap a quote around a list to suppress evaluation" (= (quote (1 2 3 4 5)) '(1 2 3 4 5)) "There is a shortcut too!" (= (quote (1 2 3 4 5)) '(1 2 3 4 5)) "You can quote symbols as well as lists... without evaluation!" (= __ (let [age 9] (quote age))) "You can use a literal list as a data collection without having Clojure try to call a function" (= (cons 1 (__ (2 3))) (list 1 2 3) (cons 1 [2 3])) "The quote affects all of its arguments, not just the top level" (= (list 1 __) '(1 (+ 2 3)) "Syntax-quote (`) acts similarly to the normal quote") (= (list 1 2 3) `(1 2 3) '(1 2 3) "Unquote (~) within a syntax-quoted expression lets you mark specific expressions as requiring evaluation") (= (list __ __) `(1 ~(+ 2 3)) '(1 5)) (defmacro hello [x] (str "Hello, " x)) (defmacro infix [form] (list (second form) (first form) (nth form 2))) (defn triangle [n] (/ (* n (+ n 1)) 2)) (println (triangle 10)) (map triangle (range 1 11)) (def tri-nums (map triangle (iterate inc 1))) (take 10 tri-nums) (take 10 (filter even? tri-nums)) (nth tri-nums 99) (take 2 (drop-while #(< % 10000) tri-nums)) (double (reduce + (take 1000 (map / tri-nums)))) (defn defer-expensive [cheap expensive] (if-let [good-enough (force cheap)] good-enough (force expensive))) (defer-expensive (delay :cheap) (delay (do (Thread/sleep 5000) :expensive))) (defer-expensive (delay nil) (delay (do (Thread/sleep 500) :expensive))) (defn atest [n] (if-let [something n] (println n) (println "False"))) (defn my-re-seq [re string] (let [matcher (re-matcher re string)] (loop [match (re-find matcher) result []] (if-not match result (recur (re-find match) (conj result match))))))
89321
(ns ex4.core) (defmacro backwards [form] (reverse form)) (backwards (" backwards" " am" "I" str)) (def addition-list (list + 1 2)) (eval addition-list) (eval (concat addition-list [10])) (eval (list 'def 'lucky-number (concat addition-list [10]))) lucky-number (str "To understand what recursion is," " you must first understand recursion") (list? (read-string "(+ 1 2)")) (conj (read-string "(+ 1 2)") :zagglewag) (#(+ 1 %) 3) (read-string "'(a b c)") (read-string "@var") (read-string "; ignore!\n(+ 1 2)") (eval (list (read-string "+") 1 2)) (eval (read-string "()")) (+ 1 2) (+ 1 (+ 2 3)) (if true 1 2) '(a b c) (read-string "(1 + 1)") (eval (let [infix (read-string "(1 + 1)")] (list (second infix) (first infix) (last infix)))) (defmacro ignore-last-operand [function-call] (butlast function-call)) (ignore-last-operand (+ 1 2 10)) (ignore-last-operand (+ 1 2 (println "Look at me!!!"))) (defmacro infix [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (1 + 2)) (defn read-resource [path] (read-string (slurp (clojure.java.io/resource path)))) (defn read-resource [path] (-> path clojure.java.io/resource slurp read-string)) (defmacro my-print [expression] (list 'let ['result expression] (list 'println 'result) 'result)) '(+ 1 ~(inc 1)) (defmacro code-critic [bad good] (list 'do (list 'println "Great squid of Madrid, this is bad code:" (list 'quote bad)) (list 'println "Sweet gorilla of Manila, this is good code:" (list 'quote good)))) (code-critic (1 + 1) (+ 1 1)) (defmacro code-critic [bad good] `(do (println "Great squid of Madrid, this is bad code:" (quote ~bad)) (println "Sweet gorilla of Manila, this is good code:" (quote ~good)))) (code-critic (1 + 1) (+ 1 1)) (defn criticize-code [criticism code] `(println ~criticism (quote ~code))) (defmacro code-critic [bad good] `(do ~(criticize-code "Cursed bacteria of Liberia this is bad code:" bad) ~(criticize-code "Sweet sacred boa of Western this is good code:" good))) (code-critic (1 + 1) (+ 1 1)) (defmacro code-critic [{:keys [good bad]}] `(do ~@(map #(apply criticize-code %) [["Sweet lion of Zion, this is bad code:" bad] ["Great cow of Moscow, this is good code:" good]]))) (code-critic (1 + 1) (+ 1 1)) (def message "Good Job!") (defmacro with-mischief [& stuff-to-do] (concat (list 'let ['message "oh, big deal!"]) stuff-to-do)) (with-mischief (println "Heres how I feel about that thing you did: " message)) (defmacro without-mischief [& stuff-to-do] (let [macro-message (gensym 'message)] `(let [~macro-message "Oh, big deal!"] ~@stuff-to-do (println "I still need to say " ~macro-message)))) (without-mischief (println "Heres how I feel about that thing you did: " message)) `(blarg# blarg#) `(let [name# "<NAME>"] name#) (eval `(+ ~@(list 1 2 3))) (range 0 5) (defn summation [alist] (eval `(+ ~@alist))) (summation (range 0 12)) (def var "<NAME>") (println `(first ~@var)) (defmacro infix [something] (eval (list (second something) (first something) (last something)))) (infix (1 + 1)) (defmacro report [to-try] `(if ~to-try (println (quote ~to-try) "was successful:" ~to-try) (println (quote ~to-try) "was not successful:" ~to-try))) (defmacro report [to-try] `(let [result# ~to-try] (if result# (println (quote ~to-try) "was successful:" result#) (println (quote ~to-try) "was not successful:" result#)))) (report (do (Thread/sleep 1000) (+ 1 1))) (doseq [code ['(= 1 1) '(= 1 2)]] (report code)) (rand-int 2) (defmacro doseq-macro [macroname & args] `(do ~@(map (fn [arg] (list macroname arg)) args))) (doseq-macro report (= 1 1) (= 1 2)) (def order-detials-validations {:name ["Please enter a name" not-empty] :email ["Please enter an email address" not-empty]}) (future (Thread/sleep 4000) (println "I'll print after 4 seconds")) (let [result (future (println "This prints once") (+ 1 1))] (println "deref: " (deref result)) (println "@: " @result)) (let [result (future (Thread/sleep 3000) (+ 1 1))] (println "It will be at least 3 seconds before I print.") (println "The result will be: " @result)) (deref (future (Thread/sleep 1000) 0) 1000 5) (realized? (future (Thread/sleep 1000))) (let [f (future)] @f (realized? f)) (def jackson-5-delay (delay (let [message "Just call my name and I'll be there"] (println "First deref:" message) message))) (force jackson-5-delay) (println @jackson-5-delay) (def gimli-headshots ["serious.jpg" "fun.jpg" "playful.jpg"]) (defn email-user [email-address] (println "Sending headshot notification to" email-address)) (defn upload-document [headshot] true) (let [notify (delay (email-user "<EMAIL>"))] (doseq [headshot gimli-headshots] (future (upload-document headshot) (force notify)))) (def my-promise (promise)) (deliver my-promise (+ 1 2)) @my-promise (def yak-butter-international {:store "Yak Butter International" :price 90 :smoothness 90}) (def better-than-nothing {:store "Butter than Nothing" :price 150 :smoothness 83}) (def baby-got-yak {:store "Baby Got Yak" :price 94 :smoothness 99}) (defn mock-api-call [result] (Thread/sleep 1000) result) (defn satisfactory? [butter] (and (<= (:price butter) 100) (>= (:smoothness butter) 97) butter)) (mock-api-call (if (satisfactory? baby-got-yak) (println "This is satisfactory.") (println "This is NOT satisfactory"))) (time (some (comp satisfactory? mock-api-call) [yak-butter-international better-than-nothing baby-got-yak])) (time (let [butter-promise (promise)] (doseq [butter [yak-butter-international better-than-nothing baby-got-yak]] (future (if-let [satisfactory-butter (satisfactory? (mock-api-call butter))] (deliver butter-promise satisfactory-butter)))) (println "And the winner is:" (:store @butter-promise)))) (let [ferengi-wisdom-promise (promise)] (future (println "here's some Ferengi wisdom:" @ferengi-wisdom-promise)) (Thread/sleep 1000) (deliver ferengi-wisdom-promise "Whisper your way to such success.")) (defmacro wait [timeout & body] `(do (Thread/sleep ~timeout) ~@body)) (time (wait 1000 (+ 1 1))) (let [saying3 (promise)] (future (deliver saying3 (wait 100 "Cheerio!"))) @(let [saying2 (promise)] (future (deliver saying2 (wait 400 "Pip pip!"))) @(let [saying1 (promise)] (future (deliver saying1 (wait 200 "'Ello, gov'n"))) (println @saying1) saying1) (println @saying2) saying2) (println @saying3) saying3) (time @(-> (enqueue saying (wait 200 "'Ello, gov'na!") (println @saying)) (enqueue saying (wait 400 "Pip ip!") (println @saying)) (enqueue saying (wait 100 "Cheerio!") (println @saying)))) (defmacro enqueue ([q concurrent-promise-name concurrent serialized] `(let [~concurrent-promise-name (promise)] (future (deliver ~concurrent-promise-name ~concurrent)) (deref ~q) ~serialized ~concurrent-promise-name)) ([concurrent-promise-name concurrent serialized] `(enqueue (future) ~concurrent-promise-name ~concurrent ~serialized))) (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 0})) @fred (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))))) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) (swap! fred increase-cuddle-hunger-level 10) (update-in {:a {:b 10}} [:a :b] inc) (swap! fred update-in [:cuddle-hunger-level] + 10) (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current State:" @num)) (-> (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current State:" @num))) (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) @fred (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to your courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) (swap! fred update-in [:cuddle-hunger-level] + 30) (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100)) (throw (IllegalStateException. "That's not mathy!"))) (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome [name] {:name name :socks #{}}) (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) (steal-sock sock-gnome dryer) (:socks @sock-gnome) (require 'clojure.xml) (parse) (use '[clojure.xml :only (parse)]) (parse (slurp "https://www.google.com/?gws_rd=ssl#q=word")) (def ^:dynamic *notification-address* "<EMAIL>") (= #{} (set nil)) (= 3 (count #{1 2 3})) (= #{1 2 3 4 5} (set '(1 1 2 2 3 3 4 4 5 5))) (= #{1 2 3 4 5} (clojure.set/union #{1 2 3 4} #{2 3 5})) (= {:a :b} (hash-map :a :b)) (get {:a 1 :b 2} :b) (= ({:a 1 :b 2} :b) (get {:a 1 :b 2} :b)) (time ({:a 1 :b 2} :b)) (time (:b {:a 1 :b 2})) (time (assoc {:a 1 :b 2} :c 3)) (= 6 (#(* 3 %1 %2) 1 2)) (= 25 ((fn [x] (x 5)) (fn [n] (* n n)))) (let [x 5] (= :your-road (cond (= x 1) :false-road (= x 2) :falsey-road :else :your-road))) (if-not (zero? 1) true false) (defn explain-defcon [term] (case term :level-one :blue :level-two :red :level-three :green)) (explain-defcon :level-two) (map (fn [x] (* x x)) (vec (range 0 10))) (= "longest" (reduce (fn [a b] (if (< (count a) (count b)) b a)) ["which" "word" "is" "longest"])) (defmulti diet (fn [x] (:eater x))) (defmethod diet :herbivore [a] (str (:name a) " eats leafs.")) (defmethod diet :carnivore [a] (str (:name a) " eats meat.")) (def salman (atom {:name "<NAME>" :eater :carnivore})) (def shihab (atom {:name "<NAME>" :eater :herbivore})) (time (reset! shihab (assoc @shihab :eater :herbivore))) (defn carnivore? [x] (if (= (:eater x) :carnivore) true false)) (carnivore? @shihab) @salman (ns koans.meditations.lazy-sequences) "There are many ways to generate a sequence" (= '(1 2 3 4) (range 1 5)) "The range starts at the beginning by default" (= '(0 1 2 3 4) (range 5)) "Only take what you need when the sequence is large" (= [0 1 2 3 4 5 6 7 8 9] (take 10 (range 100))) "Or limit results by dropping what you don't need" (= [95 96 97 98 99] (drop 95 (range 100))) "Iteration provides an infinite lazy sequence" (= (range 20) (take 20 (iterate inc 0))) "Repetition is key" (= [:a :a :a :a :a :a :a :a :a :a] (repeat 10 :a)) "Iteration can be used for repetition" (= (repeat 100 :foo) (take 100 (iterate (fn [x] x) :foo))) (repeat 100 :foo) "Sequence comprehensions can bind each element in turn to a symbol" (= '(0 1 2 3 4 5) (for [index (range 6)] index)) "They can easily emulate mapping" (= '(0 1 4 9 16 25) (map (fn [index] (* index index)) (range 6)) (for [index (range 6)] (* index index))) "And also filtering" (= '(1 3 5 7 9) (filter odd? (range 10)) (for [index (range 10) :when (odd? index)] index)) "Combinations of these transformations is trivial" (= '(1 9 25 49 81) (map (fn [index] (* index index)) (filter odd? (range 10))) (for [index (range 10) :when (odd? index)] (* index index))) "More complex transformations simply take multiple binding forms" (= [[:top :left] [:top :middle] [:top :right] [:middle :left] [:middle :middle] [:middle :right] [:bottom :left] [:bottom :middle] [:bottom :right]] (for [row [:top :middle :bottom] column [:left :middle :right]] [row column])) "One may know what they seek by knowing what they do not seek" (= [true false true] (let [not-a-symbol? (complement symbol?)] (map not-a-symbol? [:a 'b "c"]))) "Praise and 'complement' may help you separate the wheat from the chaff" (= [:wheat "wheat" 'wheat] (let [not-nil? (complement nil?)] (filter not-nil? [nil :wheat nil "wheat" nil 'wheat nil]))) "Partial functions allow procrastination" (= 20 (let [multiply-by-5 (partial * 5)] (multiply-by-5 4))) "Don't forget: first things first" (= [:a :b :c :d] (let [ab-adder (partial concat [:a :b])] (ab-adder [:c :d]))) (defn square [n] (* n n)) "Functions can join forces as one 'composed' function" (= 25 (let [inc-and-square (comp square inc)] (inc-and-square 4))) "Have a go on a double dec-er" (= 8 (let [double-dec (comp dec dec)] (double-dec 10))) "Be careful about the order in which you mix your functions" (= 99 (let [square-and-dec (comp dec square)] (square-and-dec 10))) #_(def koans '( "Recursion ends with a base case" (= true (is-even? 0)) "And starts by moving toward that base case" (= false (is-even? 1)) #_( "Having too many stack frames requires explicit tail calls with recur" (= false (is-even-bigint? 100003N))) "Reversing directions is easy when you have not gone far" (= '(1) (recursive-reverse [1])) "Yet it becomes more difficult the more steps you take" (= '(5 4 3 2 1) (recursive-reverse [1 2 3 4 5])) "Simple things may appear simple." (= 1 (factorial 1)) "They may require other simple steps." (= 2 (factorial 2)) "Sometimes a slightly bigger step is necessary" (= 6 (factorial 3)) "And eventually you must think harder" (= 24 (factorial 4)) #(_ "You can even deal with very large numbers" (< 1000000000000000000000000N (factorial 1000N)) "But what happens when the machine limits you?" (< 1000000000000000000000000N (factorial 100003N))))) (defn factorial [n] (loop [n n acc 1] (if (= 0 n) 1 (recur (dec n) (* n acc))))) (factorial 10) (defn is-even? [n] (if (= n 0) true (not (is-even? (dec n))))) (is-even? 2) (defn is-even-bigint? [n] (loop [n n acc true] (if (= n 0) acc (recur (dec n) (not acc))))) (defn recursive-reverse [coll] (loop [coll coll reversed ()] (if (= () coll) reversed (recur (rest coll) (cons (first coll) reversed))))) (clojure.string/join (concat "s" "a")) (defn strict-map1 [f coll] (loop [coll coll, acc nil] (if (empty? coll) (reverse acc) (recur (next coll) (cons (f (first coll)) acc))))) (strict-map1 - (range 5)) (defn strict-map2 [f coll] (loop [coll coll, acc []] (if (empty? coll) acc (recur (next coll) (conj acc (f (first coll))))))) (vector? (first {:width 10 :height 20 :depth 15})) (nth (vec {:width 10 :height 20 :depth 15}) 2) (doseq [[dimension amount] {:width 10 :height 20 :depth 15}] (println (str (name dimension) ":") amount "inches")) (def dice1 (range 5)) (range 5) (defmethod print-method clojure.lang.PersistentQueue [q, w] (print-method '<- w) (print-method (seq q) w) (print-method '-< w)) (def schedule (conj clojure.lang.PersistentQueue/EMPTY :wake-up :shower :brush-teeth)) (last schedule) (pop schedule) (def new (rest schedule)) (#{:a :b :c :d} :c) (#{:a :b :c :d} :e) (get #{:a 1 :b 2} :b) #{[] ()} (sorted-set [3 4] [1 2]) (def my-set (sorted-set :a :b)) (contains? #(1 2 3 4) 4) (clojure.set/difference #{1 2 3 4} #{3 4 5 6}) (defn xconj [t v] (cond (nil? t) {:val v :L nil :R nil})) (xconj nil 5) (def salman (ref {:name "<NAME>"})) (assoc @salman :age 10) (def the-world (ref "hello")) (def the-world (ref "hello")) (def bizarro-world (ref {})) (meditations "In the beginning, there was a word" (= __ (deref the-world)) "You can get the word more succinctly, but it's the same" (= __ @the-world) "You can be the change you wish to see in the world." "Alter where you need not replace" (= __ (let [exclamator (fn [x] (str x "!"))] (dosync (alter the-world exclamator) (alter the-world exclamator) (alter the-world exclamator)) @the-world)) "Don't forget to do your work in a transaction!" "Functions passed to alter may depend on the data in the ref" "Two worlds are better than one") (= "better" (do (dosync (ref-set the-world "better")) @the-world)) (= 0 (do (dosync (ref-set the-world 0)) @the-world)) (= 20 (do (dosync (alter the-world (partial + 20))))) (def bizarro-world (ref {})) (= ["<NAME>" "<NAME>" (do (dosync (ref-set the-world {}) (alter the-world assoc :jerry "<NAME>") (alter bizarro-world assoc :jerry "<NAME>")))]) (def atomic-clock (atom 0)) "Atoms are like refs" (= 0 @atomic-clock "You can change at the swap meet" (= 1 (do (swap! atomic-clock inc) @atomic-clock)) "Keep taxes out of this: swapping requires no transaction" (= 5 (do (swap! atomic-clock + 4) @atomic-clock)) "Any number of arguments might happen during a swap" (= 20 (do (swap! atomic-clock + 1 2 3 4 5) @atomic-clock)) "Atomic atoms are atomic" (= 20 (do (compare-and-set! atomic-clock 100 :fin) @atomic-clock)) "When your expectations are aligned with reality, things proceed that way" (= :fin (do (compare-and-set! atomic-clock 20 :fin) @atomic-clock))) "Wrap a quote around a list to suppress evaluation" (= (quote (1 2 3 4 5)) '(1 2 3 4 5)) "There is a shortcut too!" (= (quote (1 2 3 4 5)) '(1 2 3 4 5)) "You can quote symbols as well as lists... without evaluation!" (= __ (let [age 9] (quote age))) "You can use a literal list as a data collection without having Clojure try to call a function" (= (cons 1 (__ (2 3))) (list 1 2 3) (cons 1 [2 3])) "The quote affects all of its arguments, not just the top level" (= (list 1 __) '(1 (+ 2 3)) "Syntax-quote (`) acts similarly to the normal quote") (= (list 1 2 3) `(1 2 3) '(1 2 3) "Unquote (~) within a syntax-quoted expression lets you mark specific expressions as requiring evaluation") (= (list __ __) `(1 ~(+ 2 3)) '(1 5)) (defmacro hello [x] (str "Hello, " x)) (defmacro infix [form] (list (second form) (first form) (nth form 2))) (defn triangle [n] (/ (* n (+ n 1)) 2)) (println (triangle 10)) (map triangle (range 1 11)) (def tri-nums (map triangle (iterate inc 1))) (take 10 tri-nums) (take 10 (filter even? tri-nums)) (nth tri-nums 99) (take 2 (drop-while #(< % 10000) tri-nums)) (double (reduce + (take 1000 (map / tri-nums)))) (defn defer-expensive [cheap expensive] (if-let [good-enough (force cheap)] good-enough (force expensive))) (defer-expensive (delay :cheap) (delay (do (Thread/sleep 5000) :expensive))) (defer-expensive (delay nil) (delay (do (Thread/sleep 500) :expensive))) (defn atest [n] (if-let [something n] (println n) (println "False"))) (defn my-re-seq [re string] (let [matcher (re-matcher re string)] (loop [match (re-find matcher) result []] (if-not match result (recur (re-find match) (conj result match))))))
true
(ns ex4.core) (defmacro backwards [form] (reverse form)) (backwards (" backwards" " am" "I" str)) (def addition-list (list + 1 2)) (eval addition-list) (eval (concat addition-list [10])) (eval (list 'def 'lucky-number (concat addition-list [10]))) lucky-number (str "To understand what recursion is," " you must first understand recursion") (list? (read-string "(+ 1 2)")) (conj (read-string "(+ 1 2)") :zagglewag) (#(+ 1 %) 3) (read-string "'(a b c)") (read-string "@var") (read-string "; ignore!\n(+ 1 2)") (eval (list (read-string "+") 1 2)) (eval (read-string "()")) (+ 1 2) (+ 1 (+ 2 3)) (if true 1 2) '(a b c) (read-string "(1 + 1)") (eval (let [infix (read-string "(1 + 1)")] (list (second infix) (first infix) (last infix)))) (defmacro ignore-last-operand [function-call] (butlast function-call)) (ignore-last-operand (+ 1 2 10)) (ignore-last-operand (+ 1 2 (println "Look at me!!!"))) (defmacro infix [infixed] (list (second infixed) (first infixed) (last infixed))) (infix (1 + 2)) (defn read-resource [path] (read-string (slurp (clojure.java.io/resource path)))) (defn read-resource [path] (-> path clojure.java.io/resource slurp read-string)) (defmacro my-print [expression] (list 'let ['result expression] (list 'println 'result) 'result)) '(+ 1 ~(inc 1)) (defmacro code-critic [bad good] (list 'do (list 'println "Great squid of Madrid, this is bad code:" (list 'quote bad)) (list 'println "Sweet gorilla of Manila, this is good code:" (list 'quote good)))) (code-critic (1 + 1) (+ 1 1)) (defmacro code-critic [bad good] `(do (println "Great squid of Madrid, this is bad code:" (quote ~bad)) (println "Sweet gorilla of Manila, this is good code:" (quote ~good)))) (code-critic (1 + 1) (+ 1 1)) (defn criticize-code [criticism code] `(println ~criticism (quote ~code))) (defmacro code-critic [bad good] `(do ~(criticize-code "Cursed bacteria of Liberia this is bad code:" bad) ~(criticize-code "Sweet sacred boa of Western this is good code:" good))) (code-critic (1 + 1) (+ 1 1)) (defmacro code-critic [{:keys [good bad]}] `(do ~@(map #(apply criticize-code %) [["Sweet lion of Zion, this is bad code:" bad] ["Great cow of Moscow, this is good code:" good]]))) (code-critic (1 + 1) (+ 1 1)) (def message "Good Job!") (defmacro with-mischief [& stuff-to-do] (concat (list 'let ['message "oh, big deal!"]) stuff-to-do)) (with-mischief (println "Heres how I feel about that thing you did: " message)) (defmacro without-mischief [& stuff-to-do] (let [macro-message (gensym 'message)] `(let [~macro-message "Oh, big deal!"] ~@stuff-to-do (println "I still need to say " ~macro-message)))) (without-mischief (println "Heres how I feel about that thing you did: " message)) `(blarg# blarg#) `(let [name# "PI:NAME:<NAME>END_PI"] name#) (eval `(+ ~@(list 1 2 3))) (range 0 5) (defn summation [alist] (eval `(+ ~@alist))) (summation (range 0 12)) (def var "PI:NAME:<NAME>END_PI") (println `(first ~@var)) (defmacro infix [something] (eval (list (second something) (first something) (last something)))) (infix (1 + 1)) (defmacro report [to-try] `(if ~to-try (println (quote ~to-try) "was successful:" ~to-try) (println (quote ~to-try) "was not successful:" ~to-try))) (defmacro report [to-try] `(let [result# ~to-try] (if result# (println (quote ~to-try) "was successful:" result#) (println (quote ~to-try) "was not successful:" result#)))) (report (do (Thread/sleep 1000) (+ 1 1))) (doseq [code ['(= 1 1) '(= 1 2)]] (report code)) (rand-int 2) (defmacro doseq-macro [macroname & args] `(do ~@(map (fn [arg] (list macroname arg)) args))) (doseq-macro report (= 1 1) (= 1 2)) (def order-detials-validations {:name ["Please enter a name" not-empty] :email ["Please enter an email address" not-empty]}) (future (Thread/sleep 4000) (println "I'll print after 4 seconds")) (let [result (future (println "This prints once") (+ 1 1))] (println "deref: " (deref result)) (println "@: " @result)) (let [result (future (Thread/sleep 3000) (+ 1 1))] (println "It will be at least 3 seconds before I print.") (println "The result will be: " @result)) (deref (future (Thread/sleep 1000) 0) 1000 5) (realized? (future (Thread/sleep 1000))) (let [f (future)] @f (realized? f)) (def jackson-5-delay (delay (let [message "Just call my name and I'll be there"] (println "First deref:" message) message))) (force jackson-5-delay) (println @jackson-5-delay) (def gimli-headshots ["serious.jpg" "fun.jpg" "playful.jpg"]) (defn email-user [email-address] (println "Sending headshot notification to" email-address)) (defn upload-document [headshot] true) (let [notify (delay (email-user "PI:EMAIL:<EMAIL>END_PI"))] (doseq [headshot gimli-headshots] (future (upload-document headshot) (force notify)))) (def my-promise (promise)) (deliver my-promise (+ 1 2)) @my-promise (def yak-butter-international {:store "Yak Butter International" :price 90 :smoothness 90}) (def better-than-nothing {:store "Butter than Nothing" :price 150 :smoothness 83}) (def baby-got-yak {:store "Baby Got Yak" :price 94 :smoothness 99}) (defn mock-api-call [result] (Thread/sleep 1000) result) (defn satisfactory? [butter] (and (<= (:price butter) 100) (>= (:smoothness butter) 97) butter)) (mock-api-call (if (satisfactory? baby-got-yak) (println "This is satisfactory.") (println "This is NOT satisfactory"))) (time (some (comp satisfactory? mock-api-call) [yak-butter-international better-than-nothing baby-got-yak])) (time (let [butter-promise (promise)] (doseq [butter [yak-butter-international better-than-nothing baby-got-yak]] (future (if-let [satisfactory-butter (satisfactory? (mock-api-call butter))] (deliver butter-promise satisfactory-butter)))) (println "And the winner is:" (:store @butter-promise)))) (let [ferengi-wisdom-promise (promise)] (future (println "here's some Ferengi wisdom:" @ferengi-wisdom-promise)) (Thread/sleep 1000) (deliver ferengi-wisdom-promise "Whisper your way to such success.")) (defmacro wait [timeout & body] `(do (Thread/sleep ~timeout) ~@body)) (time (wait 1000 (+ 1 1))) (let [saying3 (promise)] (future (deliver saying3 (wait 100 "Cheerio!"))) @(let [saying2 (promise)] (future (deliver saying2 (wait 400 "Pip pip!"))) @(let [saying1 (promise)] (future (deliver saying1 (wait 200 "'Ello, gov'n"))) (println @saying1) saying1) (println @saying2) saying2) (println @saying3) saying3) (time @(-> (enqueue saying (wait 200 "'Ello, gov'na!") (println @saying)) (enqueue saying (wait 400 "Pip ip!") (println @saying)) (enqueue saying (wait 100 "Cheerio!") (println @saying)))) (defmacro enqueue ([q concurrent-promise-name concurrent serialized] `(let [~concurrent-promise-name (promise)] (future (deliver ~concurrent-promise-name ~concurrent)) (deref ~q) ~serialized ~concurrent-promise-name)) ([concurrent-promise-name concurrent serialized] `(enqueue (future) ~concurrent-promise-name ~concurrent ~serialized))) (def fred (atom {:cuddle-hunger-level 0 :percent-deteriorated 0})) @fred (let [zombie-state @fred] (if (>= (:percent-deteriorated zombie-state) 50) (future (println (:cuddle-hunger-level zombie-state))))) (swap! fred (fn [current-state] (merge-with + current-state {:cuddle-hunger-level 1 :percent-deteriorated 1}))) (defn increase-cuddle-hunger-level [zombie-state increase-by] (merge-with + zombie-state {:cuddle-hunger-level increase-by})) (increase-cuddle-hunger-level @fred 10) (swap! fred increase-cuddle-hunger-level 10) (update-in {:a {:b 10}} [:a :b] inc) (swap! fred update-in [:cuddle-hunger-level] + 10) (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current State:" @num)) (-> (let [num (atom 1) s1 @num] (swap! num inc) (println "State 1:" s1) (println "Current State:" @num))) (reset! fred {:cuddle-hunger-level 0 :percent-deteriorated 0}) @fred (defn shuffle-speed [zombie] (* (:cuddle-hunger-level zombie) (- 100 (:percent-deteriorated zombie)))) (defn shuffle-alert [key watched old-state new-state] (let [sph (shuffle-speed new-state)] (if (> sph 5000) (do (println "Run, you fool!") (println "The zombie's SPH is now " sph) (println "This message brought to your courtesy of " key)) (do (println "All's well with " key) (println "Cuddle hunger: " (:cuddle-hunger-level new-state)) (println "Percent deteriorated: " (:percent-deteriorated new-state)) (println "SPH: " sph))))) (reset! fred {:cuddle-hunger-level 22 :percent-deteriorated 2}) (add-watch fred :fred-shuffle-alert shuffle-alert) (swap! fred update-in [:percent-deteriorated] + 1) (swap! fred update-in [:cuddle-hunger-level] + 30) (defn percent-deteriorated-validator [{:keys [percent-deteriorated]}] (and (>= percent-deteriorated 0) (<= percent-deteriorated 100)) (throw (IllegalStateException. "That's not mathy!"))) (def bobby (atom {:cuddle-hunger-level 0 :percent-deteriorated 0} :validator percent-deteriorated-validator)) (swap! bobby update-in [:percent-deteriorated] + 200) (def sock-varieties #{"darned" "argyle" "wool" "horsehair" "mulleted" "passive-aggressive" "striped" "polka-dotted" "athletic" "business" "power" "invisible" "gollumed"}) (defn sock-count [sock-variety count] {:variety sock-variety :count count}) (defn generate-sock-gnome [name] {:name name :socks #{}}) (def sock-gnome (ref (generate-sock-gnome "Barumpharumph"))) (def dryer (ref {:name "LG 1337" :socks (set (map #(sock-count % 2) sock-varieties))})) (defn steal-sock [gnome dryer] (dosync (when-let [pair (some #(if (= (:count %) 2) %) (:socks @dryer))] (let [updated-count (sock-count (:variety pair) 1)] (alter gnome update-in [:socks] conj updated-count) (alter dryer update-in [:socks] disj pair) (alter dryer update-in [:socks] conj updated-count))))) (steal-sock sock-gnome dryer) (:socks @sock-gnome) (require 'clojure.xml) (parse) (use '[clojure.xml :only (parse)]) (parse (slurp "https://www.google.com/?gws_rd=ssl#q=word")) (def ^:dynamic *notification-address* "PI:EMAIL:<EMAIL>END_PI") (= #{} (set nil)) (= 3 (count #{1 2 3})) (= #{1 2 3 4 5} (set '(1 1 2 2 3 3 4 4 5 5))) (= #{1 2 3 4 5} (clojure.set/union #{1 2 3 4} #{2 3 5})) (= {:a :b} (hash-map :a :b)) (get {:a 1 :b 2} :b) (= ({:a 1 :b 2} :b) (get {:a 1 :b 2} :b)) (time ({:a 1 :b 2} :b)) (time (:b {:a 1 :b 2})) (time (assoc {:a 1 :b 2} :c 3)) (= 6 (#(* 3 %1 %2) 1 2)) (= 25 ((fn [x] (x 5)) (fn [n] (* n n)))) (let [x 5] (= :your-road (cond (= x 1) :false-road (= x 2) :falsey-road :else :your-road))) (if-not (zero? 1) true false) (defn explain-defcon [term] (case term :level-one :blue :level-two :red :level-three :green)) (explain-defcon :level-two) (map (fn [x] (* x x)) (vec (range 0 10))) (= "longest" (reduce (fn [a b] (if (< (count a) (count b)) b a)) ["which" "word" "is" "longest"])) (defmulti diet (fn [x] (:eater x))) (defmethod diet :herbivore [a] (str (:name a) " eats leafs.")) (defmethod diet :carnivore [a] (str (:name a) " eats meat.")) (def salman (atom {:name "PI:NAME:<NAME>END_PI" :eater :carnivore})) (def shihab (atom {:name "PI:NAME:<NAME>END_PI" :eater :herbivore})) (time (reset! shihab (assoc @shihab :eater :herbivore))) (defn carnivore? [x] (if (= (:eater x) :carnivore) true false)) (carnivore? @shihab) @salman (ns koans.meditations.lazy-sequences) "There are many ways to generate a sequence" (= '(1 2 3 4) (range 1 5)) "The range starts at the beginning by default" (= '(0 1 2 3 4) (range 5)) "Only take what you need when the sequence is large" (= [0 1 2 3 4 5 6 7 8 9] (take 10 (range 100))) "Or limit results by dropping what you don't need" (= [95 96 97 98 99] (drop 95 (range 100))) "Iteration provides an infinite lazy sequence" (= (range 20) (take 20 (iterate inc 0))) "Repetition is key" (= [:a :a :a :a :a :a :a :a :a :a] (repeat 10 :a)) "Iteration can be used for repetition" (= (repeat 100 :foo) (take 100 (iterate (fn [x] x) :foo))) (repeat 100 :foo) "Sequence comprehensions can bind each element in turn to a symbol" (= '(0 1 2 3 4 5) (for [index (range 6)] index)) "They can easily emulate mapping" (= '(0 1 4 9 16 25) (map (fn [index] (* index index)) (range 6)) (for [index (range 6)] (* index index))) "And also filtering" (= '(1 3 5 7 9) (filter odd? (range 10)) (for [index (range 10) :when (odd? index)] index)) "Combinations of these transformations is trivial" (= '(1 9 25 49 81) (map (fn [index] (* index index)) (filter odd? (range 10))) (for [index (range 10) :when (odd? index)] (* index index))) "More complex transformations simply take multiple binding forms" (= [[:top :left] [:top :middle] [:top :right] [:middle :left] [:middle :middle] [:middle :right] [:bottom :left] [:bottom :middle] [:bottom :right]] (for [row [:top :middle :bottom] column [:left :middle :right]] [row column])) "One may know what they seek by knowing what they do not seek" (= [true false true] (let [not-a-symbol? (complement symbol?)] (map not-a-symbol? [:a 'b "c"]))) "Praise and 'complement' may help you separate the wheat from the chaff" (= [:wheat "wheat" 'wheat] (let [not-nil? (complement nil?)] (filter not-nil? [nil :wheat nil "wheat" nil 'wheat nil]))) "Partial functions allow procrastination" (= 20 (let [multiply-by-5 (partial * 5)] (multiply-by-5 4))) "Don't forget: first things first" (= [:a :b :c :d] (let [ab-adder (partial concat [:a :b])] (ab-adder [:c :d]))) (defn square [n] (* n n)) "Functions can join forces as one 'composed' function" (= 25 (let [inc-and-square (comp square inc)] (inc-and-square 4))) "Have a go on a double dec-er" (= 8 (let [double-dec (comp dec dec)] (double-dec 10))) "Be careful about the order in which you mix your functions" (= 99 (let [square-and-dec (comp dec square)] (square-and-dec 10))) #_(def koans '( "Recursion ends with a base case" (= true (is-even? 0)) "And starts by moving toward that base case" (= false (is-even? 1)) #_( "Having too many stack frames requires explicit tail calls with recur" (= false (is-even-bigint? 100003N))) "Reversing directions is easy when you have not gone far" (= '(1) (recursive-reverse [1])) "Yet it becomes more difficult the more steps you take" (= '(5 4 3 2 1) (recursive-reverse [1 2 3 4 5])) "Simple things may appear simple." (= 1 (factorial 1)) "They may require other simple steps." (= 2 (factorial 2)) "Sometimes a slightly bigger step is necessary" (= 6 (factorial 3)) "And eventually you must think harder" (= 24 (factorial 4)) #(_ "You can even deal with very large numbers" (< 1000000000000000000000000N (factorial 1000N)) "But what happens when the machine limits you?" (< 1000000000000000000000000N (factorial 100003N))))) (defn factorial [n] (loop [n n acc 1] (if (= 0 n) 1 (recur (dec n) (* n acc))))) (factorial 10) (defn is-even? [n] (if (= n 0) true (not (is-even? (dec n))))) (is-even? 2) (defn is-even-bigint? [n] (loop [n n acc true] (if (= n 0) acc (recur (dec n) (not acc))))) (defn recursive-reverse [coll] (loop [coll coll reversed ()] (if (= () coll) reversed (recur (rest coll) (cons (first coll) reversed))))) (clojure.string/join (concat "s" "a")) (defn strict-map1 [f coll] (loop [coll coll, acc nil] (if (empty? coll) (reverse acc) (recur (next coll) (cons (f (first coll)) acc))))) (strict-map1 - (range 5)) (defn strict-map2 [f coll] (loop [coll coll, acc []] (if (empty? coll) acc (recur (next coll) (conj acc (f (first coll))))))) (vector? (first {:width 10 :height 20 :depth 15})) (nth (vec {:width 10 :height 20 :depth 15}) 2) (doseq [[dimension amount] {:width 10 :height 20 :depth 15}] (println (str (name dimension) ":") amount "inches")) (def dice1 (range 5)) (range 5) (defmethod print-method clojure.lang.PersistentQueue [q, w] (print-method '<- w) (print-method (seq q) w) (print-method '-< w)) (def schedule (conj clojure.lang.PersistentQueue/EMPTY :wake-up :shower :brush-teeth)) (last schedule) (pop schedule) (def new (rest schedule)) (#{:a :b :c :d} :c) (#{:a :b :c :d} :e) (get #{:a 1 :b 2} :b) #{[] ()} (sorted-set [3 4] [1 2]) (def my-set (sorted-set :a :b)) (contains? #(1 2 3 4) 4) (clojure.set/difference #{1 2 3 4} #{3 4 5 6}) (defn xconj [t v] (cond (nil? t) {:val v :L nil :R nil})) (xconj nil 5) (def salman (ref {:name "PI:NAME:<NAME>END_PI"})) (assoc @salman :age 10) (def the-world (ref "hello")) (def the-world (ref "hello")) (def bizarro-world (ref {})) (meditations "In the beginning, there was a word" (= __ (deref the-world)) "You can get the word more succinctly, but it's the same" (= __ @the-world) "You can be the change you wish to see in the world." "Alter where you need not replace" (= __ (let [exclamator (fn [x] (str x "!"))] (dosync (alter the-world exclamator) (alter the-world exclamator) (alter the-world exclamator)) @the-world)) "Don't forget to do your work in a transaction!" "Functions passed to alter may depend on the data in the ref" "Two worlds are better than one") (= "better" (do (dosync (ref-set the-world "better")) @the-world)) (= 0 (do (dosync (ref-set the-world 0)) @the-world)) (= 20 (do (dosync (alter the-world (partial + 20))))) (def bizarro-world (ref {})) (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" (do (dosync (ref-set the-world {}) (alter the-world assoc :jerry "PI:NAME:<NAME>END_PI") (alter bizarro-world assoc :jerry "PI:NAME:<NAME>END_PI")))]) (def atomic-clock (atom 0)) "Atoms are like refs" (= 0 @atomic-clock "You can change at the swap meet" (= 1 (do (swap! atomic-clock inc) @atomic-clock)) "Keep taxes out of this: swapping requires no transaction" (= 5 (do (swap! atomic-clock + 4) @atomic-clock)) "Any number of arguments might happen during a swap" (= 20 (do (swap! atomic-clock + 1 2 3 4 5) @atomic-clock)) "Atomic atoms are atomic" (= 20 (do (compare-and-set! atomic-clock 100 :fin) @atomic-clock)) "When your expectations are aligned with reality, things proceed that way" (= :fin (do (compare-and-set! atomic-clock 20 :fin) @atomic-clock))) "Wrap a quote around a list to suppress evaluation" (= (quote (1 2 3 4 5)) '(1 2 3 4 5)) "There is a shortcut too!" (= (quote (1 2 3 4 5)) '(1 2 3 4 5)) "You can quote symbols as well as lists... without evaluation!" (= __ (let [age 9] (quote age))) "You can use a literal list as a data collection without having Clojure try to call a function" (= (cons 1 (__ (2 3))) (list 1 2 3) (cons 1 [2 3])) "The quote affects all of its arguments, not just the top level" (= (list 1 __) '(1 (+ 2 3)) "Syntax-quote (`) acts similarly to the normal quote") (= (list 1 2 3) `(1 2 3) '(1 2 3) "Unquote (~) within a syntax-quoted expression lets you mark specific expressions as requiring evaluation") (= (list __ __) `(1 ~(+ 2 3)) '(1 5)) (defmacro hello [x] (str "Hello, " x)) (defmacro infix [form] (list (second form) (first form) (nth form 2))) (defn triangle [n] (/ (* n (+ n 1)) 2)) (println (triangle 10)) (map triangle (range 1 11)) (def tri-nums (map triangle (iterate inc 1))) (take 10 tri-nums) (take 10 (filter even? tri-nums)) (nth tri-nums 99) (take 2 (drop-while #(< % 10000) tri-nums)) (double (reduce + (take 1000 (map / tri-nums)))) (defn defer-expensive [cheap expensive] (if-let [good-enough (force cheap)] good-enough (force expensive))) (defer-expensive (delay :cheap) (delay (do (Thread/sleep 5000) :expensive))) (defer-expensive (delay nil) (delay (do (Thread/sleep 500) :expensive))) (defn atest [n] (if-let [something n] (println n) (println "False"))) (defn my-re-seq [re string] (let [matcher (re-matcher re string)] (loop [match (re-find matcher) result []] (if-not match result (recur (re-find match) (conj result match))))))
[ { "context": "bar\")\n(def LOGIN-CHALLENGE \"foobar2\")\n(def EMAIL \"foo@bar.com\")\n\n(deftest test-prepare-challenge\n (with-redefs", "end": 408, "score": 0.9998787641525269, "start": 397, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": "ENGE)))))\n\n(def register-payload\n {:attestation \"o2NmbXRmcGFja2VkZ2F0dFN0bXSiY2FsZyZjc2lnWEcwRQIgeOSXUhr3sMAO2WVq/fzmqAJn5RSf00y+2JHWSnrfBH4CIQDX9OvQGKb5q8Fj/SgJuiT2HwAcxtJ2q1FaWugkfiY32mhhdXRoRGF0YVjF09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk1FXo81/q3OAAI1vMYKZIsLJfHwVQMAQQEZBainwiWsYFxuJud3Nst81qcUmRq4jdLB/sOo2EJxZbDa4vF+xh31DS+XYCw9/6Csm75edLI9yIffVJaree8lpQECAyYgASFYIO7qcEAfShtfCKN8k1hJ0Vo1GtJ3toA0+agxwJcu24xzIlggEfYFr083E++o65vZ/I8hCZ3+Jpd1FdbaqAkCY1nvQuI=\"\n :client-data \"eyJjaGFsbGVuZ2UiOiJabTl2WW1GeSIs", "end": 1430, "score": 0.9991633296012878, "start": 1013, "tag": "KEY", "value": "o2NmbXRmcGFja2VkZ2F0dFN0bXSiY2FsZyZjc2lnWEcwRQIgeOSXUhr3sMAO2WVq/fzmqAJn5RSf00y+2JHWSnrfBH4CIQDX9OvQGKb5q8Fj/SgJuiT2HwAcxtJ2q1FaWugkfiY32mhhdXRoRGF0YVjF09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk1FXo81/q3OAAI1vMYKZIsLJfHwVQMAQQEZBainwiWsYFxuJud3Nst81qcUmRq4jdLB/sOo2EJxZbDa4vF+xh31DS+XYCw9/6Csm75edLI9yIffVJaree8lpQECAyYgASFYIO7qcEAfShtfCKN8k1hJ0Vo1GtJ3toA0+agxwJcu24xzIlggEfYFr083E++o65vZ/I8hCZ3+Jpd1FdbaqAkCY1nvQuI=\"" }, { "context": "5vZ/I8hCZ3+Jpd1FdbaqAkCY1nvQuI=\"\n :client-data \"eyJjaGFsbGVuZ2UiOiJabTl2WW1GeSIsIm9yaWdpbiI6Imh0dHBzOi8vZ3Jpc29uLm1lIiwidHlwZSI6IndlYmF1dGhuLmNyZWF0ZSJ9\"\n :challenge REGISTER-CHALLENGE})\n\n(deftest t", "end": 1552, "score": 0.999772846698761, "start": 1448, "tag": "KEY", "value": "eyJjaGFsbGVuZ2UiOiJabTl2WW1GeSIsIm9yaWdpbiI6Imh0dHBzOi8vZ3Jpc29uLm1lIiwidHlwZSI6IndlYmF1dGhuLmNyZWF0ZSJ9" }, { "context": ")))))\n\n(def login-payload\n {:credential-id \"ARkFqKfCJaxgXG4m53c2y3zWpxSZGriN0sH+w6jYQnFlsNri8X7GHfUNL5dgLD3/oKybvl50sj3Ih99Ulqt57yU=\"\n :user-handle \"Wm05dlFHSmhjaTVqYjIwPQ==\"", "end": 3191, "score": 0.9837015271186829, "start": 3102, "tag": "KEY", "value": "ARkFqKfCJaxgXG4m53c2y3zWpxSZGriN0sH+w6jYQnFlsNri8X7GHfUNL5dgLD3/oKybvl50sj3Ih99Ulqt57yU=\"" }, { "context": "Wm05dlFHSmhjaTVqYjIwPQ==\"\n :authenticator-data \"09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk0FXo82Tg==\"\n :", "end": 3274, "score": 0.889863133430481, "start": 3266, "tag": "KEY", "value": "09CVCOxd" }, { "context": "hjaTVqYjIwPQ==\"\n :authenticator-data \"09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk0FXo82Tg==\"\n :cli", "end": 3277, "score": 0.6360759139060974, "start": 3276, "tag": "KEY", "value": "x" }, { "context": "qYjIwPQ==\"\n :authenticator-data \"09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk0FXo82Tg==\"\n :client-data \"eyJjaGFsbGVu", "end": 3306, "score": 0.8587377667427063, "start": 3281, "tag": "KEY", "value": "5mFMLk7vvUH763HGL3Wl3siTn" }, { "context": "r-data \"09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk0FXo82Tg==\"\n :client-data \"eyJjaGFsbGVuZ2UiOiJabTl2W", "end": 3319, "score": 0.7831174731254578, "start": 3308, "tag": "KEY", "value": "0FXo82Tg==\"" }, { "context": "3HGL3Wl3siTnwk0FXo82Tg==\"\n :client-data \"eyJjaGFsbGVuZ2UiOiJabTl2WW1GeU1nIiwib3JpZ2luIjoiaHR0cHM6Ly9ncmlzb24ubWUiLCJ0eXBlIjoid2ViYXV0aG4uZ2V0In0=\"\n :signature \"MEUCIQCkfqWpAhi7CRO0exa2w", "end": 3449, "score": 0.9997295141220093, "start": 3344, "tag": "KEY", "value": "eyJjaGFsbGVuZ2UiOiJabTl2WW1GeU1nIiwib3JpZ2luIjoiaHR0cHM6Ly9ncmlzb24ubWUiLCJ0eXBlIjoid2ViYXV0aG4uZ2V0In0=\"" }, { "context": "nature \"MEUCIQCkfqWpAhi7CRO0exa2wenWgDaakqJq2uUKpDix4UrlcQIgFeDV8HEki7WSjRkz4j+MVLBjypqBD8hSm7gv+gI1roY=\"\n :challenge LOGIN-CHALLENGE})\n\n(deftes", "end": 3571, "score": 0.7785717248916626, "start": 3507, "tag": "KEY", "value": "qJq2uUKpDix4UrlcQIgFeDV8HEki7WSjRkz4j+MVLBjypqBD8hSm7gv+gI1roY=\"" } ]
test/cljwebauthn/core_test.clj
terop/cljwebauthn
0
(ns cljwebauthn.core-test (:require [clojure.test :refer :all] [cljwebauthn.core :refer :all] [cljwebauthn.b64 :as b64])) (def site-properties {:site-id "grison.me", :site-name "Stuff and Thoughts about IT Stuff", :protocol "https", :port 443, :host "grison.me"}) (def REGISTER-CHALLENGE "foobar") (def LOGIN-CHALLENGE "foobar2") (def EMAIL "foo@bar.com") (deftest test-prepare-challenge (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [prep (prepare-registration EMAIL site-properties)] (is (not (nil? prep))) (is (every? prep [:rp :user :cred :challenge])) (is (= {:rp {:id (:site-id site-properties) :name (:site-name site-properties)} :user {:id (b64/encode EMAIL)} :cred [{:type "public-key" :alg -7}] :challenge REGISTER-CHALLENGE} prep)) (is (contains? (:register @*challenges*) REGISTER-CHALLENGE))))) (def register-payload {:attestation "o2NmbXRmcGFja2VkZ2F0dFN0bXSiY2FsZyZjc2lnWEcwRQIgeOSXUhr3sMAO2WVq/fzmqAJn5RSf00y+2JHWSnrfBH4CIQDX9OvQGKb5q8Fj/SgJuiT2HwAcxtJ2q1FaWugkfiY32mhhdXRoRGF0YVjF09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk1FXo81/q3OAAI1vMYKZIsLJfHwVQMAQQEZBainwiWsYFxuJud3Nst81qcUmRq4jdLB/sOo2EJxZbDa4vF+xh31DS+XYCw9/6Csm75edLI9yIffVJaree8lpQECAyYgASFYIO7qcEAfShtfCKN8k1hJ0Vo1GtJ3toA0+agxwJcu24xzIlggEfYFr083E++o65vZ/I8hCZ3+Jpd1FdbaqAkCY1nvQuI=" :client-data "eyJjaGFsbGVuZ2UiOiJabTl2WW1GeSIsIm9yaWdpbiI6Imh0dHBzOi8vZ3Jpc29uLm1lIiwidHlwZSI6IndlYmF1dGhuLmNyZWF0ZSJ9" :challenge REGISTER-CHALLENGE}) (deftest test-register (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [auth (atom nil) _ (prepare-registration EMAIL site-properties) user (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user " user-id) (reset! auth authenticator))) auth-value @auth] (is (contains? (:register @*challenges*) REGISTER-CHALLENGE)) (is (= {:user-id EMAIL :challenge REGISTER-CHALLENGE} user)) (is (not (nil? auth-value)))))) (deftest test-prepare-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator)))] (with-redefs [generate-challenge (fn [] LOGIN-CHALLENGE)] (let [prep (prepare-login EMAIL (fn [user-id] [@auth]))] (is (contains? (:login @*challenges*) LOGIN-CHALLENGE)) (is (every? prep [:challenge :credentials])) (is (= LOGIN-CHALLENGE (:challenge prep))) (is (every? (-> prep :credentials first) [:type :id])))))))) (def login-payload {:credential-id "ARkFqKfCJaxgXG4m53c2y3zWpxSZGriN0sH+w6jYQnFlsNri8X7GHfUNL5dgLD3/oKybvl50sj3Ih99Ulqt57yU=" :user-handle "Wm05dlFHSmhjaTVqYjIwPQ==" :authenticator-data "09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk0FXo82Tg==" :client-data "eyJjaGFsbGVuZ2UiOiJabTl2WW1GeU1nIiwib3JpZ2luIjoiaHR0cHM6Ly9ncmlzb24ubWUiLCJ0eXBlIjoid2ViYXV0aG4uZ2V0In0=" :signature "MEUCIQCkfqWpAhi7CRO0exa2wenWgDaakqJq2uUKpDix4UrlcQIgFeDV8HEki7WSjRkz4j+MVLBjypqBD8hSm7gv+gI1roY=" :challenge LOGIN-CHALLENGE}) (deftest test-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator))) user (login-user login-payload site-properties (fn [user-id] [@auth]))] (is (every? user [:user-id :challenge])) (is (= LOGIN-CHALLENGE (:challenge user))) (is (= EMAIL (b64/decode (b64/decode (:user-id user)))))))))
65471
(ns cljwebauthn.core-test (:require [clojure.test :refer :all] [cljwebauthn.core :refer :all] [cljwebauthn.b64 :as b64])) (def site-properties {:site-id "grison.me", :site-name "Stuff and Thoughts about IT Stuff", :protocol "https", :port 443, :host "grison.me"}) (def REGISTER-CHALLENGE "foobar") (def LOGIN-CHALLENGE "foobar2") (def EMAIL "<EMAIL>") (deftest test-prepare-challenge (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [prep (prepare-registration EMAIL site-properties)] (is (not (nil? prep))) (is (every? prep [:rp :user :cred :challenge])) (is (= {:rp {:id (:site-id site-properties) :name (:site-name site-properties)} :user {:id (b64/encode EMAIL)} :cred [{:type "public-key" :alg -7}] :challenge REGISTER-CHALLENGE} prep)) (is (contains? (:register @*challenges*) REGISTER-CHALLENGE))))) (def register-payload {:attestation "<KEY> :client-data "<KEY>" :challenge REGISTER-CHALLENGE}) (deftest test-register (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [auth (atom nil) _ (prepare-registration EMAIL site-properties) user (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user " user-id) (reset! auth authenticator))) auth-value @auth] (is (contains? (:register @*challenges*) REGISTER-CHALLENGE)) (is (= {:user-id EMAIL :challenge REGISTER-CHALLENGE} user)) (is (not (nil? auth-value)))))) (deftest test-prepare-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator)))] (with-redefs [generate-challenge (fn [] LOGIN-CHALLENGE)] (let [prep (prepare-login EMAIL (fn [user-id] [@auth]))] (is (contains? (:login @*challenges*) LOGIN-CHALLENGE)) (is (every? prep [:challenge :credentials])) (is (= LOGIN-CHALLENGE (:challenge prep))) (is (every? (-> prep :credentials first) [:type :id])))))))) (def login-payload {:credential-id "<KEY> :user-handle "Wm05dlFHSmhjaTVqYjIwPQ==" :authenticator-data "<KEY>EG<KEY>TwSc<KEY>wk<KEY> :client-data "<KEY> :signature "MEUCIQCkfqWpAhi7CRO0exa2wenWgDaak<KEY> :challenge LOGIN-CHALLENGE}) (deftest test-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator))) user (login-user login-payload site-properties (fn [user-id] [@auth]))] (is (every? user [:user-id :challenge])) (is (= LOGIN-CHALLENGE (:challenge user))) (is (= EMAIL (b64/decode (b64/decode (:user-id user)))))))))
true
(ns cljwebauthn.core-test (:require [clojure.test :refer :all] [cljwebauthn.core :refer :all] [cljwebauthn.b64 :as b64])) (def site-properties {:site-id "grison.me", :site-name "Stuff and Thoughts about IT Stuff", :protocol "https", :port 443, :host "grison.me"}) (def REGISTER-CHALLENGE "foobar") (def LOGIN-CHALLENGE "foobar2") (def EMAIL "PI:EMAIL:<EMAIL>END_PI") (deftest test-prepare-challenge (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [prep (prepare-registration EMAIL site-properties)] (is (not (nil? prep))) (is (every? prep [:rp :user :cred :challenge])) (is (= {:rp {:id (:site-id site-properties) :name (:site-name site-properties)} :user {:id (b64/encode EMAIL)} :cred [{:type "public-key" :alg -7}] :challenge REGISTER-CHALLENGE} prep)) (is (contains? (:register @*challenges*) REGISTER-CHALLENGE))))) (def register-payload {:attestation "PI:KEY:<KEY>END_PI :client-data "PI:KEY:<KEY>END_PI" :challenge REGISTER-CHALLENGE}) (deftest test-register (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [auth (atom nil) _ (prepare-registration EMAIL site-properties) user (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user " user-id) (reset! auth authenticator))) auth-value @auth] (is (contains? (:register @*challenges*) REGISTER-CHALLENGE)) (is (= {:user-id EMAIL :challenge REGISTER-CHALLENGE} user)) (is (not (nil? auth-value)))))) (deftest test-prepare-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator)))] (with-redefs [generate-challenge (fn [] LOGIN-CHALLENGE)] (let [prep (prepare-login EMAIL (fn [user-id] [@auth]))] (is (contains? (:login @*challenges*) LOGIN-CHALLENGE)) (is (every? prep [:challenge :credentials])) (is (= LOGIN-CHALLENGE (:challenge prep))) (is (every? (-> prep :credentials first) [:type :id])))))))) (def login-payload {:credential-id "PI:KEY:<KEY>END_PI :user-handle "Wm05dlFHSmhjaTVqYjIwPQ==" :authenticator-data "PI:KEY:<KEY>END_PIEGPI:KEY:<KEY>END_PITwScPI:KEY:<KEY>END_PIwkPI:KEY:<KEY>END_PI :client-data "PI:KEY:<KEY>END_PI :signature "MEUCIQCkfqWpAhi7CRO0exa2wenWgDaakPI:KEY:<KEY>END_PI :challenge LOGIN-CHALLENGE}) (deftest test-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator))) user (login-user login-payload site-properties (fn [user-id] [@auth]))] (is (every? user [:user-id :challenge])) (is (= LOGIN-CHALLENGE (:challenge user))) (is (= EMAIL (b64/decode (b64/decode (:user-id user)))))))))
[ { "context": "))\n\n(deftest harvest-granules\n (let [format-key :echo10\n _ (dev-system-util/freeze-time! \"2010-01-", "end": 714, "score": 0.8482127785682678, "start": 708, "tag": "KEY", "value": "echo10" } ]
system-int-test/test/cmr/system_int_test/search/harvesting_test.clj
mschmele/Common-Metadata-Repository
0
(ns cmr.system-int-test.search.harvesting-test "Tests for using the scroll parameter to harvest metadata" (:require [clojure.test :refer :all] [cmr.common.util :as util :refer [are3]] [cmr.system-int-test.data2.collection :as data2-collection] [cmr.system-int-test.data2.core :as data2-core] [cmr.system-int-test.data2.granule :as data2-granule] [cmr.system-int-test.utils.dev-system-util :as dev-system-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (deftest harvest-granules (let [format-key :echo10 _ (dev-system-util/freeze-time! "2010-01-01T10:00:00Z") coll1-echo (data2-core/ingest "PROV1" (data2-collection/collection) {:format :echo10}) coll1-concept-id (:concept-id coll1-echo) _ (dev-system-util/freeze-time! "2012-01-01T10:00:00Z") coll2-echo (data2-core/ingest "PROV1" (data2-collection/collection) {:format :echo10}) coll2-concept-id (:concept-id coll2-echo) _ (dev-system-util/freeze-time! "2010-01-01T10:00:00Z") g1-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g1" :producer-gran-id "p1"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2011-01-01T10:00:00Z") g2-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g2" :producer-gran-id "p2"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2012-01-01T10:00:00Z") g3-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g3" :producer-gran-id "p3"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2013-01-01T10:00:00Z") g4-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g4" :producer-gran-id "p4"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2014-01-01T10:00:00Z") g5-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g5" :producer-gran-id "p5"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2015-01-01T10:00:00Z") g6-echo (data2-core/ingest "PROV1" (data2-granule/granule coll2-echo {:granule-ur "g6" :producer-gran-id "p6"}) {:format :echo10}) coll1-grans [g1-echo g2-echo g3-echo g4-echo g5-echo]] (index/wait-until-indexed) (testing "JSON format" (let [params {:collection_concept_id (:concept-id coll1-echo) :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule :json params options) scroll-id (:scroll-id response)] (testing "First search gets expected count and scroll-id" (is (= (count coll1-grans) (:hits response))) (is (not (nil? scroll-id)))))) (testing "Harvest by collection-concept-id" (let [params {:collection_concept_id (:concept-id coll1-echo) :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule format-key params options) scroll-id (:scroll-id response)] (testing "First search gets expected granules and scroll-id" (is (= (count coll1-grans) (:hits response))) (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [g1-echo g2-echo] response)) (testing "Second search gets next two granules" (data2-core/assert-metadata-results-match format-key [g3-echo g4-echo] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))) (testing "Third search gets last granule" (data2-core/assert-metadata-results-match format-key [g5-echo] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))) (testing "Subsequent search gets empty list" (data2-core/assert-metadata-results-match format-key [] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))))) (testing "Harvest granules by created-at" (let [params {:concept-id [coll1-concept-id coll2-concept-id] :created-at "2010-01-01T10:00:00Z,2014-02-01T10:00:00Z" :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule :echo10 params options) scroll-id (:scroll-id response)] (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [g1-echo g2-echo] response))) (testing "Harvest collections by created-at" (let [params {:created_at "2010-01-01T10:00:00Z,2011-01-01T10:00:00Z" :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :collection :echo10 params options) scroll-id (:scroll-id response)] (is (= 1 (:hits response))) (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [coll1-echo] response)))))
90019
(ns cmr.system-int-test.search.harvesting-test "Tests for using the scroll parameter to harvest metadata" (:require [clojure.test :refer :all] [cmr.common.util :as util :refer [are3]] [cmr.system-int-test.data2.collection :as data2-collection] [cmr.system-int-test.data2.core :as data2-core] [cmr.system-int-test.data2.granule :as data2-granule] [cmr.system-int-test.utils.dev-system-util :as dev-system-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (deftest harvest-granules (let [format-key :<KEY> _ (dev-system-util/freeze-time! "2010-01-01T10:00:00Z") coll1-echo (data2-core/ingest "PROV1" (data2-collection/collection) {:format :echo10}) coll1-concept-id (:concept-id coll1-echo) _ (dev-system-util/freeze-time! "2012-01-01T10:00:00Z") coll2-echo (data2-core/ingest "PROV1" (data2-collection/collection) {:format :echo10}) coll2-concept-id (:concept-id coll2-echo) _ (dev-system-util/freeze-time! "2010-01-01T10:00:00Z") g1-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g1" :producer-gran-id "p1"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2011-01-01T10:00:00Z") g2-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g2" :producer-gran-id "p2"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2012-01-01T10:00:00Z") g3-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g3" :producer-gran-id "p3"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2013-01-01T10:00:00Z") g4-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g4" :producer-gran-id "p4"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2014-01-01T10:00:00Z") g5-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g5" :producer-gran-id "p5"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2015-01-01T10:00:00Z") g6-echo (data2-core/ingest "PROV1" (data2-granule/granule coll2-echo {:granule-ur "g6" :producer-gran-id "p6"}) {:format :echo10}) coll1-grans [g1-echo g2-echo g3-echo g4-echo g5-echo]] (index/wait-until-indexed) (testing "JSON format" (let [params {:collection_concept_id (:concept-id coll1-echo) :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule :json params options) scroll-id (:scroll-id response)] (testing "First search gets expected count and scroll-id" (is (= (count coll1-grans) (:hits response))) (is (not (nil? scroll-id)))))) (testing "Harvest by collection-concept-id" (let [params {:collection_concept_id (:concept-id coll1-echo) :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule format-key params options) scroll-id (:scroll-id response)] (testing "First search gets expected granules and scroll-id" (is (= (count coll1-grans) (:hits response))) (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [g1-echo g2-echo] response)) (testing "Second search gets next two granules" (data2-core/assert-metadata-results-match format-key [g3-echo g4-echo] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))) (testing "Third search gets last granule" (data2-core/assert-metadata-results-match format-key [g5-echo] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))) (testing "Subsequent search gets empty list" (data2-core/assert-metadata-results-match format-key [] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))))) (testing "Harvest granules by created-at" (let [params {:concept-id [coll1-concept-id coll2-concept-id] :created-at "2010-01-01T10:00:00Z,2014-02-01T10:00:00Z" :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule :echo10 params options) scroll-id (:scroll-id response)] (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [g1-echo g2-echo] response))) (testing "Harvest collections by created-at" (let [params {:created_at "2010-01-01T10:00:00Z,2011-01-01T10:00:00Z" :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :collection :echo10 params options) scroll-id (:scroll-id response)] (is (= 1 (:hits response))) (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [coll1-echo] response)))))
true
(ns cmr.system-int-test.search.harvesting-test "Tests for using the scroll parameter to harvest metadata" (:require [clojure.test :refer :all] [cmr.common.util :as util :refer [are3]] [cmr.system-int-test.data2.collection :as data2-collection] [cmr.system-int-test.data2.core :as data2-core] [cmr.system-int-test.data2.granule :as data2-granule] [cmr.system-int-test.utils.dev-system-util :as dev-system-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"})) (deftest harvest-granules (let [format-key :PI:KEY:<KEY>END_PI _ (dev-system-util/freeze-time! "2010-01-01T10:00:00Z") coll1-echo (data2-core/ingest "PROV1" (data2-collection/collection) {:format :echo10}) coll1-concept-id (:concept-id coll1-echo) _ (dev-system-util/freeze-time! "2012-01-01T10:00:00Z") coll2-echo (data2-core/ingest "PROV1" (data2-collection/collection) {:format :echo10}) coll2-concept-id (:concept-id coll2-echo) _ (dev-system-util/freeze-time! "2010-01-01T10:00:00Z") g1-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g1" :producer-gran-id "p1"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2011-01-01T10:00:00Z") g2-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g2" :producer-gran-id "p2"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2012-01-01T10:00:00Z") g3-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g3" :producer-gran-id "p3"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2013-01-01T10:00:00Z") g4-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g4" :producer-gran-id "p4"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2014-01-01T10:00:00Z") g5-echo (data2-core/ingest "PROV1" (data2-granule/granule coll1-echo {:granule-ur "g5" :producer-gran-id "p5"}) {:format :echo10}) _ (dev-system-util/freeze-time! "2015-01-01T10:00:00Z") g6-echo (data2-core/ingest "PROV1" (data2-granule/granule coll2-echo {:granule-ur "g6" :producer-gran-id "p6"}) {:format :echo10}) coll1-grans [g1-echo g2-echo g3-echo g4-echo g5-echo]] (index/wait-until-indexed) (testing "JSON format" (let [params {:collection_concept_id (:concept-id coll1-echo) :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule :json params options) scroll-id (:scroll-id response)] (testing "First search gets expected count and scroll-id" (is (= (count coll1-grans) (:hits response))) (is (not (nil? scroll-id)))))) (testing "Harvest by collection-concept-id" (let [params {:collection_concept_id (:concept-id coll1-echo) :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule format-key params options) scroll-id (:scroll-id response)] (testing "First search gets expected granules and scroll-id" (is (= (count coll1-grans) (:hits response))) (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [g1-echo g2-echo] response)) (testing "Second search gets next two granules" (data2-core/assert-metadata-results-match format-key [g3-echo g4-echo] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))) (testing "Third search gets last granule" (data2-core/assert-metadata-results-match format-key [g5-echo] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))) (testing "Subsequent search gets empty list" (data2-core/assert-metadata-results-match format-key [] (search/find-metadata :granule format-key {:scroll true} {:headers {"CMR-Scroll-Id" scroll-id}}))))) (testing "Harvest granules by created-at" (let [params {:concept-id [coll1-concept-id coll2-concept-id] :created-at "2010-01-01T10:00:00Z,2014-02-01T10:00:00Z" :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :granule :echo10 params options) scroll-id (:scroll-id response)] (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [g1-echo g2-echo] response))) (testing "Harvest collections by created-at" (let [params {:created_at "2010-01-01T10:00:00Z,2011-01-01T10:00:00Z" :scroll true :page-size 2} options {:accept nil :url-extension "native"} response (search/find-metadata :collection :echo10 params options) scroll-id (:scroll-id response)] (is (= 1 (:hits response))) (is (not (nil? scroll-id))) (data2-core/assert-metadata-results-match format-key [coll1-echo] response)))))
[ { "context": ";\n; Copyright © 2020 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9995651841163635, "start": 21, "tag": "NAME", "value": "Peter Monks" }, { "context": "vacy policy is available here](https://github.com/pmonks/futbot/blob/main/PRIVACY.md).\")))\n\n(defn status-c", "end": 7569, "score": 0.9994314312934875, "start": 7563, "tag": "USERNAME", "value": "pmonks" } ]
src/futbot/chat.clj
pmonks/futbot
3
; ; Copyright © 2020 Peter Monks ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.chat (:require [clojure.string :as s] [clojure.instant :as inst] [clojure.tools.logging :as log] [java-time :as tm] [discljord.formatting :as df] [futbot.util :as u] [futbot.message-util :as mu] [futbot.config :as cfg] [futbot.source.ist :as ist] [futbot.blocklist :as blk])) (def prefix "!") (defn ist-command! "Generates a fake IST video title" [_ event-data] (let [channel-id (:channel-id event-data)] (if (or (mu/direct-message? event-data) ; Only respond if message was sent via DM or (some #{channel-id} (:ist-channel-ids cfg/config))) ; one of the allowed IST channels. (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "**" (ist/gen-title) "**") :footer {:text "Disclaimer: this is a generated fake" :icon_url "https://yt3.ggpht.com/ytc/AAUvwnjhzwc9yNfyfX8C1N820yMhaS27baWlSz2wqaRE=s176-c-k-c0x00ffffff-no-rj"})) (log/info (str "Ignoring " prefix "ist command in channel " channel-id))))) (defn move-command! "Moves a conversation to the specified channel" [args event-data] (when (not (mu/direct-message? event-data)) ; Only respond if the message was sent to a real channel in a server (i.e. not in a DM) (let [guild-id (:guild-id event-data) channel-id (:channel-id event-data) discord-message-channel (:discord-message-channel cfg/config)] (if (not (s/blank? args)) (if-let [target-channel-id (second (re-find df/channel-mention args))] (if (not= channel-id target-channel-id) (let [move-message-id (:id event-data) _ (mu/delete-message! discord-message-channel channel-id move-message-id) ; Don't delete the original message unless we've validated everything target-message-id (:id (mu/create-message! discord-message-channel target-channel-id :embed (assoc (mu/embed-template) :description (str "Continuing the conversation from " (mu/channel-link channel-id) "...")))) target-message-url (mu/message-url guild-id target-channel-id target-message-id) source-message-id (:id (mu/create-message! discord-message-channel channel-id :embed (assoc (mu/embed-template) :description (str "Let's continue this conversation in " (mu/channel-link target-channel-id) " ([link](" target-message-url ")).")))) source-message-url (mu/message-url guild-id channel-id source-message-id)] (mu/edit-message! discord-message-channel target-channel-id target-message-id :embed (assoc (mu/embed-template) :description (str "Continuing the conversation from " (mu/channel-link channel-id) " ([link](" source-message-url "))...")))) (log/info "Cannot move a conversation to the same channel.")) (log/warn "Could not find target channel in move command.")) (log/warn "move-command! arguments missing a target channel."))))) (defn epoch-command! "Displays the 'epoch seconds' value of the given date (in RFC-3339 format), or now if no value is provided." [args event-data] (let [channel-id (:channel-id event-data)] (try (let [d (if (s/blank? args) (java.util.Date.) (inst/read-instant-date args)) epoch (long (/ (.getTime ^java.util.Date d) 1000))] (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" epoch "`")))) (catch RuntimeException re (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (.getMessage re))))))) (defn dmath-command! "Displays the result of the given date math expression e.g. now + 1 day" [args event-data] (let [channel-id (:channel-id event-data)] (try (let [[b o v u] (s/split (s/lower-case (s/trim args)) #"\s+") base (if (= b "now") (.getEpochSecond (tm/instant)) (u/parse-int b)) op (case o "-" - "+" + nil) val (u/parse-int v) multiplier (case u ("m" "min" "mins" "minutes") 60 ("h" "hr" "hrs" "hours") (* 60 60) ("d" "day" "days") (* 60 60 24) ("w" "wk" "wks" "weeks") (* 60 60 24 7) 1)] ; Default to seconds (if base (if (and op val multiplier) ; Everything was provided - evaluate the expression (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" (op base (* val multiplier)) "`"))) (if-not (or op val) ; Only base was provided - display it (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" base "`"))) (throw (ex-info "Op, val or multiplier not provided" {})))) (throw (ex-info "Base not provided" {})))) (catch Exception _ (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "Unable to parse date math expression: `" args "`"))))))) (defn privacy-command! "Provides a link to the futbot privacy policy" [_ event-data] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :description "[futbot's privacy policy is available here](https://github.com/pmonks/futbot/blob/main/PRIVACY.md)."))) (defn status-command! "Provides technical status of futbot" [_ event-data] (let [now (tm/instant)] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :title "futbot Status" :fields [ {:name "Running for" :value (str (u/human-readable-date-diff cfg/boot-time now))} {:name "Built at" :value (str (tm/format :iso-instant cfg/built-at) (if cfg/git-url (str " from [" cfg/git-tag "](" cfg/git-url ")") ""))} ; Table of fields here {:name "Clojure" :value (str "v" (clojure-version)) :inline true} {:name "JVM" :value (str (System/getProperty "java.vm.vendor") " v" (System/getProperty "java.vm.version") " (" (System/getProperty "os.name") "/" (System/getProperty "os.arch") ")") :inline true} ; Force a newline (Discord is hardcoded to show 3 fields per line), by using Unicode zero width spaces (empty/blank strings won't work!) {:name "​" :value "​" :inline true} {:name "Heap memory in use" :value (u/human-readable-size (.getUsed (.getHeapMemoryUsage (java.lang.management.ManagementFactory/getMemoryMXBean)))) :inline true} {:name "Non-heap memory in use" :value (u/human-readable-size (.getUsed (.getNonHeapMemoryUsage (java.lang.management.ManagementFactory/getMemoryMXBean)))) :inline true} ])))) (defn gc-command! "Requests that the JVM perform a GC cycle." [_ event-data] (System/gc) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Garbage collection requested.")) (defn set-logging-command! "Sets the log level, optionally for the given logger (defaults to 'futbot')." [args event-data] (let [[level logger] (s/split args #"\s+")] (if level (do (cfg/set-log-level! level (if logger logger "futbot")) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content (str "Logging level " (s/upper-case level) " set" (if logger (str " for logger '" logger "'") " for logger 'futbot'") "."))) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Logging level not provided; must be one of: ERROR, WARN, INFO, DEBUG, TRACE")))) (defn debug-logging-command! "Enables debug logging, which turns on TRACE for 'discljord' and DEBUG for 'futbot'." [_ event-data] (cfg/set-log-level! "TRACE" "discljord") (cfg/set-log-level! "DEBUG" "futbot") (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Debug logging enabled (TRACE for 'discljord' and DEBUG for 'futbot').")) (defn reset-logging-command! "Resets all log levels to their configured defaults." [_ event-data] (cfg/reset-logging!) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Logging configuration reset.")) ; Table of "public" commands; those that can be used in any channel, group or DM (def global-command-dispatch-table {"move" #'move-command! "epoch" #'epoch-command! "dmath" #'dmath-command!}) (def memes-command-dispatch-table {"ist" #'ist-command!}) (def public-command-dispatch-table (into global-command-dispatch-table memes-command-dispatch-table)) (declare help-command!) ; Table of "private" commands; those that can only be used in a DM channel (def private-command-dispatch-table {"help" #'help-command! "privacy" #'privacy-command!}) (def secret-command-dispatch-table {"status" #'status-command! "gc" #'gc-command! "setlogging" #'set-logging-command! "debuglogging" #'debug-logging-command! "resetlogging" #'reset-logging-command!}) (defn help-command! "Displays this help message" [_ event-data] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :description (str "I understand the following command(s) in any channel or DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key global-command-dispatch-table))) "\n\nAnd the following command(s) in " (mu/channel-link "683853455038742610") " or a DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key memes-command-dispatch-table))) "\n\nAnd the following command(s) only in a DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key private-command-dispatch-table))))))) ; Responsive fns (defmulti handle-discord-event "Discord event handler" (fn [event-type _] event-type)) ; Default Discord event handler (noop) (defmethod handle-discord-event :default [_ _]) (defmethod handle-discord-event :message-create [_ event-data] ; Only respond to messages sent from a human (when (mu/human-message? event-data) (future ; Spin off the actual processing, so we don't clog the Discord event queue (try (when-not (blk/check-blocklist! event-data) ; First check if the given message violates the blocklist (let [content (s/triml (:content event-data))] (if (s/starts-with? content prefix) ; Parse the requested command and call it, if it exists (let [command-and-args (s/split content #"\s+" 2) command (s/lower-case (subs (s/trim (first command-and-args)) (count prefix))) args (second command-and-args)] (if-let [public-command-fn (get public-command-dispatch-table command)] (do (log/debug (str "Calling public command fn for '" command "' with args '" args "'.")) (public-command-fn args event-data)) (when (mu/direct-message? event-data) (if-let [private-command-fn (get private-command-dispatch-table command)] (do (log/debug (str "Calling private command fn for '" command "' with args '" args "'.")) (private-command-fn args event-data)) (if-let [secret-command-fn (get secret-command-dispatch-table command)] (do (log/debug (str "Calling secret command fn for '" command "' with args '" args "'.")) (secret-command-fn args event-data)) (help-command! nil event-data)))))) ; If the requested private command doesn't exist, provide help ; If any unrecognised message was sent to a DM channel, provide help (when-not (:guild-id event-data) (help-command! nil event-data))))) (catch Exception e (u/log-exception e)))))) (defmethod handle-discord-event :message-update [_ event-data] ; Only respond to messages sent from a human (when (mu/human-message? event-data) (future ; Spin off the actual processing, so we don't clog the Discord event queue (try (blk/check-blocklist! event-data) ; Check if the updated message violates the blocklist (catch Exception e (u/log-exception e))))))
66996
; ; Copyright © 2020 <NAME> ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.chat (:require [clojure.string :as s] [clojure.instant :as inst] [clojure.tools.logging :as log] [java-time :as tm] [discljord.formatting :as df] [futbot.util :as u] [futbot.message-util :as mu] [futbot.config :as cfg] [futbot.source.ist :as ist] [futbot.blocklist :as blk])) (def prefix "!") (defn ist-command! "Generates a fake IST video title" [_ event-data] (let [channel-id (:channel-id event-data)] (if (or (mu/direct-message? event-data) ; Only respond if message was sent via DM or (some #{channel-id} (:ist-channel-ids cfg/config))) ; one of the allowed IST channels. (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "**" (ist/gen-title) "**") :footer {:text "Disclaimer: this is a generated fake" :icon_url "https://yt3.ggpht.com/ytc/AAUvwnjhzwc9yNfyfX8C1N820yMhaS27baWlSz2wqaRE=s176-c-k-c0x00ffffff-no-rj"})) (log/info (str "Ignoring " prefix "ist command in channel " channel-id))))) (defn move-command! "Moves a conversation to the specified channel" [args event-data] (when (not (mu/direct-message? event-data)) ; Only respond if the message was sent to a real channel in a server (i.e. not in a DM) (let [guild-id (:guild-id event-data) channel-id (:channel-id event-data) discord-message-channel (:discord-message-channel cfg/config)] (if (not (s/blank? args)) (if-let [target-channel-id (second (re-find df/channel-mention args))] (if (not= channel-id target-channel-id) (let [move-message-id (:id event-data) _ (mu/delete-message! discord-message-channel channel-id move-message-id) ; Don't delete the original message unless we've validated everything target-message-id (:id (mu/create-message! discord-message-channel target-channel-id :embed (assoc (mu/embed-template) :description (str "Continuing the conversation from " (mu/channel-link channel-id) "...")))) target-message-url (mu/message-url guild-id target-channel-id target-message-id) source-message-id (:id (mu/create-message! discord-message-channel channel-id :embed (assoc (mu/embed-template) :description (str "Let's continue this conversation in " (mu/channel-link target-channel-id) " ([link](" target-message-url ")).")))) source-message-url (mu/message-url guild-id channel-id source-message-id)] (mu/edit-message! discord-message-channel target-channel-id target-message-id :embed (assoc (mu/embed-template) :description (str "Continuing the conversation from " (mu/channel-link channel-id) " ([link](" source-message-url "))...")))) (log/info "Cannot move a conversation to the same channel.")) (log/warn "Could not find target channel in move command.")) (log/warn "move-command! arguments missing a target channel."))))) (defn epoch-command! "Displays the 'epoch seconds' value of the given date (in RFC-3339 format), or now if no value is provided." [args event-data] (let [channel-id (:channel-id event-data)] (try (let [d (if (s/blank? args) (java.util.Date.) (inst/read-instant-date args)) epoch (long (/ (.getTime ^java.util.Date d) 1000))] (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" epoch "`")))) (catch RuntimeException re (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (.getMessage re))))))) (defn dmath-command! "Displays the result of the given date math expression e.g. now + 1 day" [args event-data] (let [channel-id (:channel-id event-data)] (try (let [[b o v u] (s/split (s/lower-case (s/trim args)) #"\s+") base (if (= b "now") (.getEpochSecond (tm/instant)) (u/parse-int b)) op (case o "-" - "+" + nil) val (u/parse-int v) multiplier (case u ("m" "min" "mins" "minutes") 60 ("h" "hr" "hrs" "hours") (* 60 60) ("d" "day" "days") (* 60 60 24) ("w" "wk" "wks" "weeks") (* 60 60 24 7) 1)] ; Default to seconds (if base (if (and op val multiplier) ; Everything was provided - evaluate the expression (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" (op base (* val multiplier)) "`"))) (if-not (or op val) ; Only base was provided - display it (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" base "`"))) (throw (ex-info "Op, val or multiplier not provided" {})))) (throw (ex-info "Base not provided" {})))) (catch Exception _ (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "Unable to parse date math expression: `" args "`"))))))) (defn privacy-command! "Provides a link to the futbot privacy policy" [_ event-data] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :description "[futbot's privacy policy is available here](https://github.com/pmonks/futbot/blob/main/PRIVACY.md)."))) (defn status-command! "Provides technical status of futbot" [_ event-data] (let [now (tm/instant)] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :title "futbot Status" :fields [ {:name "Running for" :value (str (u/human-readable-date-diff cfg/boot-time now))} {:name "Built at" :value (str (tm/format :iso-instant cfg/built-at) (if cfg/git-url (str " from [" cfg/git-tag "](" cfg/git-url ")") ""))} ; Table of fields here {:name "Clojure" :value (str "v" (clojure-version)) :inline true} {:name "JVM" :value (str (System/getProperty "java.vm.vendor") " v" (System/getProperty "java.vm.version") " (" (System/getProperty "os.name") "/" (System/getProperty "os.arch") ")") :inline true} ; Force a newline (Discord is hardcoded to show 3 fields per line), by using Unicode zero width spaces (empty/blank strings won't work!) {:name "​" :value "​" :inline true} {:name "Heap memory in use" :value (u/human-readable-size (.getUsed (.getHeapMemoryUsage (java.lang.management.ManagementFactory/getMemoryMXBean)))) :inline true} {:name "Non-heap memory in use" :value (u/human-readable-size (.getUsed (.getNonHeapMemoryUsage (java.lang.management.ManagementFactory/getMemoryMXBean)))) :inline true} ])))) (defn gc-command! "Requests that the JVM perform a GC cycle." [_ event-data] (System/gc) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Garbage collection requested.")) (defn set-logging-command! "Sets the log level, optionally for the given logger (defaults to 'futbot')." [args event-data] (let [[level logger] (s/split args #"\s+")] (if level (do (cfg/set-log-level! level (if logger logger "futbot")) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content (str "Logging level " (s/upper-case level) " set" (if logger (str " for logger '" logger "'") " for logger 'futbot'") "."))) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Logging level not provided; must be one of: ERROR, WARN, INFO, DEBUG, TRACE")))) (defn debug-logging-command! "Enables debug logging, which turns on TRACE for 'discljord' and DEBUG for 'futbot'." [_ event-data] (cfg/set-log-level! "TRACE" "discljord") (cfg/set-log-level! "DEBUG" "futbot") (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Debug logging enabled (TRACE for 'discljord' and DEBUG for 'futbot').")) (defn reset-logging-command! "Resets all log levels to their configured defaults." [_ event-data] (cfg/reset-logging!) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Logging configuration reset.")) ; Table of "public" commands; those that can be used in any channel, group or DM (def global-command-dispatch-table {"move" #'move-command! "epoch" #'epoch-command! "dmath" #'dmath-command!}) (def memes-command-dispatch-table {"ist" #'ist-command!}) (def public-command-dispatch-table (into global-command-dispatch-table memes-command-dispatch-table)) (declare help-command!) ; Table of "private" commands; those that can only be used in a DM channel (def private-command-dispatch-table {"help" #'help-command! "privacy" #'privacy-command!}) (def secret-command-dispatch-table {"status" #'status-command! "gc" #'gc-command! "setlogging" #'set-logging-command! "debuglogging" #'debug-logging-command! "resetlogging" #'reset-logging-command!}) (defn help-command! "Displays this help message" [_ event-data] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :description (str "I understand the following command(s) in any channel or DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key global-command-dispatch-table))) "\n\nAnd the following command(s) in " (mu/channel-link "683853455038742610") " or a DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key memes-command-dispatch-table))) "\n\nAnd the following command(s) only in a DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key private-command-dispatch-table))))))) ; Responsive fns (defmulti handle-discord-event "Discord event handler" (fn [event-type _] event-type)) ; Default Discord event handler (noop) (defmethod handle-discord-event :default [_ _]) (defmethod handle-discord-event :message-create [_ event-data] ; Only respond to messages sent from a human (when (mu/human-message? event-data) (future ; Spin off the actual processing, so we don't clog the Discord event queue (try (when-not (blk/check-blocklist! event-data) ; First check if the given message violates the blocklist (let [content (s/triml (:content event-data))] (if (s/starts-with? content prefix) ; Parse the requested command and call it, if it exists (let [command-and-args (s/split content #"\s+" 2) command (s/lower-case (subs (s/trim (first command-and-args)) (count prefix))) args (second command-and-args)] (if-let [public-command-fn (get public-command-dispatch-table command)] (do (log/debug (str "Calling public command fn for '" command "' with args '" args "'.")) (public-command-fn args event-data)) (when (mu/direct-message? event-data) (if-let [private-command-fn (get private-command-dispatch-table command)] (do (log/debug (str "Calling private command fn for '" command "' with args '" args "'.")) (private-command-fn args event-data)) (if-let [secret-command-fn (get secret-command-dispatch-table command)] (do (log/debug (str "Calling secret command fn for '" command "' with args '" args "'.")) (secret-command-fn args event-data)) (help-command! nil event-data)))))) ; If the requested private command doesn't exist, provide help ; If any unrecognised message was sent to a DM channel, provide help (when-not (:guild-id event-data) (help-command! nil event-data))))) (catch Exception e (u/log-exception e)))))) (defmethod handle-discord-event :message-update [_ event-data] ; Only respond to messages sent from a human (when (mu/human-message? event-data) (future ; Spin off the actual processing, so we don't clog the Discord event queue (try (blk/check-blocklist! event-data) ; Check if the updated message violates the blocklist (catch Exception e (u/log-exception e))))))
true
; ; Copyright © 2020 PI:NAME:<NAME>END_PI ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; (ns futbot.chat (:require [clojure.string :as s] [clojure.instant :as inst] [clojure.tools.logging :as log] [java-time :as tm] [discljord.formatting :as df] [futbot.util :as u] [futbot.message-util :as mu] [futbot.config :as cfg] [futbot.source.ist :as ist] [futbot.blocklist :as blk])) (def prefix "!") (defn ist-command! "Generates a fake IST video title" [_ event-data] (let [channel-id (:channel-id event-data)] (if (or (mu/direct-message? event-data) ; Only respond if message was sent via DM or (some #{channel-id} (:ist-channel-ids cfg/config))) ; one of the allowed IST channels. (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "**" (ist/gen-title) "**") :footer {:text "Disclaimer: this is a generated fake" :icon_url "https://yt3.ggpht.com/ytc/AAUvwnjhzwc9yNfyfX8C1N820yMhaS27baWlSz2wqaRE=s176-c-k-c0x00ffffff-no-rj"})) (log/info (str "Ignoring " prefix "ist command in channel " channel-id))))) (defn move-command! "Moves a conversation to the specified channel" [args event-data] (when (not (mu/direct-message? event-data)) ; Only respond if the message was sent to a real channel in a server (i.e. not in a DM) (let [guild-id (:guild-id event-data) channel-id (:channel-id event-data) discord-message-channel (:discord-message-channel cfg/config)] (if (not (s/blank? args)) (if-let [target-channel-id (second (re-find df/channel-mention args))] (if (not= channel-id target-channel-id) (let [move-message-id (:id event-data) _ (mu/delete-message! discord-message-channel channel-id move-message-id) ; Don't delete the original message unless we've validated everything target-message-id (:id (mu/create-message! discord-message-channel target-channel-id :embed (assoc (mu/embed-template) :description (str "Continuing the conversation from " (mu/channel-link channel-id) "...")))) target-message-url (mu/message-url guild-id target-channel-id target-message-id) source-message-id (:id (mu/create-message! discord-message-channel channel-id :embed (assoc (mu/embed-template) :description (str "Let's continue this conversation in " (mu/channel-link target-channel-id) " ([link](" target-message-url ")).")))) source-message-url (mu/message-url guild-id channel-id source-message-id)] (mu/edit-message! discord-message-channel target-channel-id target-message-id :embed (assoc (mu/embed-template) :description (str "Continuing the conversation from " (mu/channel-link channel-id) " ([link](" source-message-url "))...")))) (log/info "Cannot move a conversation to the same channel.")) (log/warn "Could not find target channel in move command.")) (log/warn "move-command! arguments missing a target channel."))))) (defn epoch-command! "Displays the 'epoch seconds' value of the given date (in RFC-3339 format), or now if no value is provided." [args event-data] (let [channel-id (:channel-id event-data)] (try (let [d (if (s/blank? args) (java.util.Date.) (inst/read-instant-date args)) epoch (long (/ (.getTime ^java.util.Date d) 1000))] (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" epoch "`")))) (catch RuntimeException re (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (.getMessage re))))))) (defn dmath-command! "Displays the result of the given date math expression e.g. now + 1 day" [args event-data] (let [channel-id (:channel-id event-data)] (try (let [[b o v u] (s/split (s/lower-case (s/trim args)) #"\s+") base (if (= b "now") (.getEpochSecond (tm/instant)) (u/parse-int b)) op (case o "-" - "+" + nil) val (u/parse-int v) multiplier (case u ("m" "min" "mins" "minutes") 60 ("h" "hr" "hrs" "hours") (* 60 60) ("d" "day" "days") (* 60 60 24) ("w" "wk" "wks" "weeks") (* 60 60 24 7) 1)] ; Default to seconds (if base (if (and op val multiplier) ; Everything was provided - evaluate the expression (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" (op base (* val multiplier)) "`"))) (if-not (or op val) ; Only base was provided - display it (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "`" base "`"))) (throw (ex-info "Op, val or multiplier not provided" {})))) (throw (ex-info "Base not provided" {})))) (catch Exception _ (mu/create-message! (:discord-message-channel cfg/config) channel-id :embed (assoc (mu/embed-template) :description (str "Unable to parse date math expression: `" args "`"))))))) (defn privacy-command! "Provides a link to the futbot privacy policy" [_ event-data] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :description "[futbot's privacy policy is available here](https://github.com/pmonks/futbot/blob/main/PRIVACY.md)."))) (defn status-command! "Provides technical status of futbot" [_ event-data] (let [now (tm/instant)] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :title "futbot Status" :fields [ {:name "Running for" :value (str (u/human-readable-date-diff cfg/boot-time now))} {:name "Built at" :value (str (tm/format :iso-instant cfg/built-at) (if cfg/git-url (str " from [" cfg/git-tag "](" cfg/git-url ")") ""))} ; Table of fields here {:name "Clojure" :value (str "v" (clojure-version)) :inline true} {:name "JVM" :value (str (System/getProperty "java.vm.vendor") " v" (System/getProperty "java.vm.version") " (" (System/getProperty "os.name") "/" (System/getProperty "os.arch") ")") :inline true} ; Force a newline (Discord is hardcoded to show 3 fields per line), by using Unicode zero width spaces (empty/blank strings won't work!) {:name "​" :value "​" :inline true} {:name "Heap memory in use" :value (u/human-readable-size (.getUsed (.getHeapMemoryUsage (java.lang.management.ManagementFactory/getMemoryMXBean)))) :inline true} {:name "Non-heap memory in use" :value (u/human-readable-size (.getUsed (.getNonHeapMemoryUsage (java.lang.management.ManagementFactory/getMemoryMXBean)))) :inline true} ])))) (defn gc-command! "Requests that the JVM perform a GC cycle." [_ event-data] (System/gc) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Garbage collection requested.")) (defn set-logging-command! "Sets the log level, optionally for the given logger (defaults to 'futbot')." [args event-data] (let [[level logger] (s/split args #"\s+")] (if level (do (cfg/set-log-level! level (if logger logger "futbot")) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content (str "Logging level " (s/upper-case level) " set" (if logger (str " for logger '" logger "'") " for logger 'futbot'") "."))) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Logging level not provided; must be one of: ERROR, WARN, INFO, DEBUG, TRACE")))) (defn debug-logging-command! "Enables debug logging, which turns on TRACE for 'discljord' and DEBUG for 'futbot'." [_ event-data] (cfg/set-log-level! "TRACE" "discljord") (cfg/set-log-level! "DEBUG" "futbot") (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Debug logging enabled (TRACE for 'discljord' and DEBUG for 'futbot').")) (defn reset-logging-command! "Resets all log levels to their configured defaults." [_ event-data] (cfg/reset-logging!) (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :content "Logging configuration reset.")) ; Table of "public" commands; those that can be used in any channel, group or DM (def global-command-dispatch-table {"move" #'move-command! "epoch" #'epoch-command! "dmath" #'dmath-command!}) (def memes-command-dispatch-table {"ist" #'ist-command!}) (def public-command-dispatch-table (into global-command-dispatch-table memes-command-dispatch-table)) (declare help-command!) ; Table of "private" commands; those that can only be used in a DM channel (def private-command-dispatch-table {"help" #'help-command! "privacy" #'privacy-command!}) (def secret-command-dispatch-table {"status" #'status-command! "gc" #'gc-command! "setlogging" #'set-logging-command! "debuglogging" #'debug-logging-command! "resetlogging" #'reset-logging-command!}) (defn help-command! "Displays this help message" [_ event-data] (mu/create-message! (:discord-message-channel cfg/config) (:channel-id event-data) :embed (assoc (mu/embed-template) :description (str "I understand the following command(s) in any channel or DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key global-command-dispatch-table))) "\n\nAnd the following command(s) in " (mu/channel-link "683853455038742610") " or a DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key memes-command-dispatch-table))) "\n\nAnd the following command(s) only in a DM:\n" (s/join "\n" (map #(str " • **`" prefix (key %) "`** - " (:doc (meta (val %)))) (sort-by key private-command-dispatch-table))))))) ; Responsive fns (defmulti handle-discord-event "Discord event handler" (fn [event-type _] event-type)) ; Default Discord event handler (noop) (defmethod handle-discord-event :default [_ _]) (defmethod handle-discord-event :message-create [_ event-data] ; Only respond to messages sent from a human (when (mu/human-message? event-data) (future ; Spin off the actual processing, so we don't clog the Discord event queue (try (when-not (blk/check-blocklist! event-data) ; First check if the given message violates the blocklist (let [content (s/triml (:content event-data))] (if (s/starts-with? content prefix) ; Parse the requested command and call it, if it exists (let [command-and-args (s/split content #"\s+" 2) command (s/lower-case (subs (s/trim (first command-and-args)) (count prefix))) args (second command-and-args)] (if-let [public-command-fn (get public-command-dispatch-table command)] (do (log/debug (str "Calling public command fn for '" command "' with args '" args "'.")) (public-command-fn args event-data)) (when (mu/direct-message? event-data) (if-let [private-command-fn (get private-command-dispatch-table command)] (do (log/debug (str "Calling private command fn for '" command "' with args '" args "'.")) (private-command-fn args event-data)) (if-let [secret-command-fn (get secret-command-dispatch-table command)] (do (log/debug (str "Calling secret command fn for '" command "' with args '" args "'.")) (secret-command-fn args event-data)) (help-command! nil event-data)))))) ; If the requested private command doesn't exist, provide help ; If any unrecognised message was sent to a DM channel, provide help (when-not (:guild-id event-data) (help-command! nil event-data))))) (catch Exception e (u/log-exception e)))))) (defmethod handle-discord-event :message-update [_ event-data] ; Only respond to messages sent from a human (when (mu/human-message? event-data) (future ; Spin off the actual processing, so we don't clog the Discord event queue (try (blk/check-blocklist! event-data) ; Check if the updated message violates the blocklist (catch Exception e (u/log-exception e))))))
[ { "context": ";; Copyright (c) 2015 <Diego Souza>\n\n;; Permission is hereby granted, free of charge", "end": 34, "score": 0.9998772740364075, "start": 23, "tag": "NAME", "value": "Diego Souza" } ]
src/storaged/src/leela/storaged/network/zhelpers.clj
locaweb/leela
22
;; Copyright (c) 2015 <Diego Souza> ;; 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 leela.storaged.network.zhelpers (:import [org.zeromq ZMQ ZMQ$Poller ZMQ$Socket ZMQ$PollItem] [java.util.concurrent.TimeUnit] [java.util.concurrent.ArrayBlockingQueue]) (:require [clojure.tools.logging :refer [info warn]])) (def empty-msg (byte-array 0)) (defn- run-recvmsg [state msg] (if-let [acc (:body state)] (assoc state :body (conj acc msg)) (if (or (nil? msg) (empty? msg)) (assoc state :body []) (if-let [acc (:peer state)] (assoc state :peer (conj acc msg)) (assoc state :peer [msg]))))) (defn- eval-recvmsg [state] (if-let [body (:body state)] (list (:peer state) body) (list [] (:peer state)))) (defn- make-pollitem [^ZMQ$Socket fh events] (let [^long flags (apply bit-or (conj events 0))] (ZMQ$PollItem. fh flags))) (defn- make-pollitems [watch] (let [events (map #(apply make-pollitem %) (partition 2 watch))] (into-array ZMQ$PollItem events))) (defn setup-socket ^ZMQ$Socket [^ZMQ$Socket fh] (.setLinger fh 0) (.setReconnectIVL fh 1000) (.setMaxMsgSize fh (* 10 1024 1024)) fh) (defn recvmsg [^ZMQ$Socket fh] (loop [state0 {}] (let [state1 (run-recvmsg state0 (.recv fh))] (if (.hasReceiveMore fh) (recur state1) (eval-recvmsg state1))))) (defn poll [timeout watch] (let [pollitems (make-pollitems watch)] (ZMQ/poll pollitems timeout) pollitems)) (defn- socket-send ([^ZMQ$Socket fh ^bytes msg] (.send fh msg 0)) ([^ZMQ$Socket fh ^bytes msg ^long flags] (.send fh msg flags))) (defn sendmsg [fh peer body] (doseq [msg peer] (socket-send fh msg ZMQ/SNDMORE)) (socket-send fh empty-msg ZMQ/SNDMORE) (loop [[x & xs] body] (if (empty? xs) (do (socket-send fh x)) (do (socket-send fh x ZMQ/SNDMORE) (recur xs)))))
111860
;; 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. (ns leela.storaged.network.zhelpers (:import [org.zeromq ZMQ ZMQ$Poller ZMQ$Socket ZMQ$PollItem] [java.util.concurrent.TimeUnit] [java.util.concurrent.ArrayBlockingQueue]) (:require [clojure.tools.logging :refer [info warn]])) (def empty-msg (byte-array 0)) (defn- run-recvmsg [state msg] (if-let [acc (:body state)] (assoc state :body (conj acc msg)) (if (or (nil? msg) (empty? msg)) (assoc state :body []) (if-let [acc (:peer state)] (assoc state :peer (conj acc msg)) (assoc state :peer [msg]))))) (defn- eval-recvmsg [state] (if-let [body (:body state)] (list (:peer state) body) (list [] (:peer state)))) (defn- make-pollitem [^ZMQ$Socket fh events] (let [^long flags (apply bit-or (conj events 0))] (ZMQ$PollItem. fh flags))) (defn- make-pollitems [watch] (let [events (map #(apply make-pollitem %) (partition 2 watch))] (into-array ZMQ$PollItem events))) (defn setup-socket ^ZMQ$Socket [^ZMQ$Socket fh] (.setLinger fh 0) (.setReconnectIVL fh 1000) (.setMaxMsgSize fh (* 10 1024 1024)) fh) (defn recvmsg [^ZMQ$Socket fh] (loop [state0 {}] (let [state1 (run-recvmsg state0 (.recv fh))] (if (.hasReceiveMore fh) (recur state1) (eval-recvmsg state1))))) (defn poll [timeout watch] (let [pollitems (make-pollitems watch)] (ZMQ/poll pollitems timeout) pollitems)) (defn- socket-send ([^ZMQ$Socket fh ^bytes msg] (.send fh msg 0)) ([^ZMQ$Socket fh ^bytes msg ^long flags] (.send fh msg flags))) (defn sendmsg [fh peer body] (doseq [msg peer] (socket-send fh msg ZMQ/SNDMORE)) (socket-send fh empty-msg ZMQ/SNDMORE) (loop [[x & xs] body] (if (empty? xs) (do (socket-send fh x)) (do (socket-send fh x ZMQ/SNDMORE) (recur xs)))))
true
;; 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. (ns leela.storaged.network.zhelpers (:import [org.zeromq ZMQ ZMQ$Poller ZMQ$Socket ZMQ$PollItem] [java.util.concurrent.TimeUnit] [java.util.concurrent.ArrayBlockingQueue]) (:require [clojure.tools.logging :refer [info warn]])) (def empty-msg (byte-array 0)) (defn- run-recvmsg [state msg] (if-let [acc (:body state)] (assoc state :body (conj acc msg)) (if (or (nil? msg) (empty? msg)) (assoc state :body []) (if-let [acc (:peer state)] (assoc state :peer (conj acc msg)) (assoc state :peer [msg]))))) (defn- eval-recvmsg [state] (if-let [body (:body state)] (list (:peer state) body) (list [] (:peer state)))) (defn- make-pollitem [^ZMQ$Socket fh events] (let [^long flags (apply bit-or (conj events 0))] (ZMQ$PollItem. fh flags))) (defn- make-pollitems [watch] (let [events (map #(apply make-pollitem %) (partition 2 watch))] (into-array ZMQ$PollItem events))) (defn setup-socket ^ZMQ$Socket [^ZMQ$Socket fh] (.setLinger fh 0) (.setReconnectIVL fh 1000) (.setMaxMsgSize fh (* 10 1024 1024)) fh) (defn recvmsg [^ZMQ$Socket fh] (loop [state0 {}] (let [state1 (run-recvmsg state0 (.recv fh))] (if (.hasReceiveMore fh) (recur state1) (eval-recvmsg state1))))) (defn poll [timeout watch] (let [pollitems (make-pollitems watch)] (ZMQ/poll pollitems timeout) pollitems)) (defn- socket-send ([^ZMQ$Socket fh ^bytes msg] (.send fh msg 0)) ([^ZMQ$Socket fh ^bytes msg ^long flags] (.send fh msg flags))) (defn sendmsg [fh peer body] (doseq [msg peer] (socket-send fh msg ZMQ/SNDMORE)) (socket-send fh empty-msg ZMQ/SNDMORE) (loop [[x & xs] body] (if (empty? xs) (do (socket-send fh x)) (do (socket-send fh x ZMQ/SNDMORE) (recur xs)))))
[ { "context": "oeu\" (.-length payload))\n (let [{pub-B :pub node-id :id sec-b :sec} (-> config :auth :herd-id) ;; FIX", "end": 1237, "score": 0.5092280507087708, "start": 1235, "tag": "KEY", "value": "id" } ]
src/herd_node/sp.cljs
herd1/herd
0
(ns herd-node.sp (:require [cljs.core :as cljs] [cljs.nodejs :as node] [cljs.core.async :refer [chan <! >! sub pub unsub close!] :as a] [herd-node.parse :as conv] [herd-node.dtls-comm :as dtls] [herd-node.conn-mgr :as conn] [herd-node.circ :as circ] [herd-node.path :as path] [herd-node.ntor :as hs] [herd-node.conns :as c] [herd-node.log :as log] [herd-node.dir :as dir] [herd-node.buf :as b]) (:require-macros [cljs.core.async.macros :as m :refer [go-loop go]])) (def to-cmd {0 :register-to-sp 1 :mk-secret 2 :ack-secret 3 :register-id-to-sp }) (def from-cmd (apply merge (for [k (keys to-cmd)] {(to-cmd k) k}))) ;; sent by mix: (defn send-client-sp-id [config socket client-index sp-id] "send a sp id & its client-index on the channel to a client" (circ/send-sp config socket (b/cat (-> :register-to-sp from-cmd b/new1) (b/new4 client-index) sp-id))) (defn mk-secret-from-create [config payload] (log/debug ":aoeu" (.-length payload)) (let [{pub-B :pub node-id :id sec-b :sec} (-> config :auth :herd-id) ;; FIXME: this is the current blocking bug. client-id (.readUInt32BE payload 0) hs-type (.readUInt16BE payload 4) len (.readUInt16BE payload 6) [shared-sec created] (hs/server-reply config {:pub-B pub-B :node-id node-id :sec-b sec-b} (.slice payload 8) (-> config :enc :key-len))] (assert (= hs-type 2) "unsupported handshake type") [client-id shared-sec created])) ;; sent by client: (defn send-mk-secret [config mix-socket client-id mix-auth] (let [[auth create] (hs/client-init config mix-auth)] (log/debug :FIXME :mk-secret (.-length create)) (circ/send-sp config mix-socket (b/cat (-> :mk-secret from-cmd b/new1) (b/new4 client-id) (b/new2 2) ;; type of hs (-> create .-length b/new2) create)) auth)) ;; init: (defn init [config] (let [[sp-ctrl sp-notify] (:sp-chans config) mix-answer (chan) config (merge config [sp-ctrl sp-notify]) process (fn [{cmd :cmd data :data socket :socket}] (let [cmd (if (number? cmd) (to-cmd cmd) cmd)] (log/info "Recvd" cmd) (condp = cmd ;;;; recvd by mix: :new-client (let [conns (c/get-all) sps (for [k (keys conns) :let [conn-data (conns k)] :when (= :super-peer (:role conn-data))] [k conn-data]) [sp-socket sp-data] (first sps) sp-id (-> sp-data :auth :srv-id) sp-clients (-> sp-data :client-secrets) sp-clients (or sp-clients {}) client-id (first (filter #(not (sp-clients %)) (range (:max-clients-per-channel config)))) client-ntor-id data] (when (not= 1 (count sps)) (log/error "wrong number of superpeers" sps)) (assert client-id "could not add client, channel full") (log/debug "Sending SP id" (b/hx sp-id) "to client" client-id) (c/update-data sp-socket [:client-secrets] (merge sp-clients {client-id {:secret nil :srv-id client-ntor-id}})) (c/update-data socket [:future-sp] sp-socket) (send-client-sp-id config socket client-id sp-id)) :mk-secret (let [[client-id shared-sec created] (mk-secret-from-create config data) on-destroy (-> socket c/get-data :on-destroy) sp-socket (-> socket c/get-data :future-sp) client-secrets (-> sp-socket c/get-data :client-secrets)] (c/update-data sp-socket [:client-secrets] (merge client-secrets {client-id {:secret shared-sec}})) (c/update-data socket [:on-destroy] (cons #(c/add-id sp-socket (:srv-id (client-secrets client-id))) on-destroy)) (dtls/send-node-secret {:index client-id} shared-sec) ;; send ack to client: (circ/send-sp config socket (b/cat (-> :ack-secret from-cmd b/new1) (-> created .-length b/new2) created))) ;;;; recvd by client: :register-to-sp (let [client-id (.readUInt32BE data 0) sp-id (.slice data 4)] (go (>! mix-answer [client-id sp-id]))) ;; :connect function is waiting for this. :ack-secret (go (>! mix-answer data)) ;; internal commands (not from the network) :connect (let [zone (-> config :geo-info :zone) net-info (dir/get-net-info) select-mixes #(->> net-info seq (map second) (filter %) shuffle) ;; FIXME make this a function mix (first (select-mixes #(and (= (:role %) :mix) (= (:zone %) zone)))) socket (conn/new :herd :client mix config {:connect identity})] ;; 1/ connect to mix, wait for client-id & sp-id (go (let [mix-socket (<! socket)] (circ/send-id config mix-socket) (log/debug :FIXME "sent id") (let [[client-id sp-id] (<! mix-answer) sp (first (select-mixes #(b/b= sp-id (-> % :auth :srv-id))))] (log/debug "Will connect to SP" (b/hx sp-id)) (assert sp "Could not find SP") ;; 2/ connect to SP: (let [socket (conn/new :herd :client sp config {:connect identity}) auth (send-mk-secret config mix-socket client-id (:auth mix)) payload (<! mix-answer) shared-sec (hs/client-finalise auth (.slice payload 2) (-> config :enc :key-len)) sp-socket (<! socket)] (circ/send-sp config sp-socket (b/cat (-> :register-id-to-sp from-cmd b/new1) (b/new4 client-id))) ;; 3/ create circuits: (dtls/send-role sp-socket :super-peer) (dtls/send-node-secret sp-socket shared-sec) (c/update-data sp-socket [:sp-auth] (:auth sp)) ;; FIXME: not sure if we'll keep this, but for now it'll do (c/update-data sp-socket [:auth] (-> mix-socket c/get-data :auth)) ;; FIXME: not sure if we'll keep this, but for now it'll do (c/add-id sp-socket (-> mix :auth :srv-id)) ;(circ/send-id config sp-socket) (path/init-pools config net-info (:geo-info config) 2 (c/get-data sp-socket)) (>! sp-notify [sp-socket mix])))))))))] (go-loop [msg (<! sp-ctrl)] (process msg) (recur (<! sp-ctrl))) (log/info "Superpeer signaling initialised")))
42138
(ns herd-node.sp (:require [cljs.core :as cljs] [cljs.nodejs :as node] [cljs.core.async :refer [chan <! >! sub pub unsub close!] :as a] [herd-node.parse :as conv] [herd-node.dtls-comm :as dtls] [herd-node.conn-mgr :as conn] [herd-node.circ :as circ] [herd-node.path :as path] [herd-node.ntor :as hs] [herd-node.conns :as c] [herd-node.log :as log] [herd-node.dir :as dir] [herd-node.buf :as b]) (:require-macros [cljs.core.async.macros :as m :refer [go-loop go]])) (def to-cmd {0 :register-to-sp 1 :mk-secret 2 :ack-secret 3 :register-id-to-sp }) (def from-cmd (apply merge (for [k (keys to-cmd)] {(to-cmd k) k}))) ;; sent by mix: (defn send-client-sp-id [config socket client-index sp-id] "send a sp id & its client-index on the channel to a client" (circ/send-sp config socket (b/cat (-> :register-to-sp from-cmd b/new1) (b/new4 client-index) sp-id))) (defn mk-secret-from-create [config payload] (log/debug ":aoeu" (.-length payload)) (let [{pub-B :pub node-<KEY> :id sec-b :sec} (-> config :auth :herd-id) ;; FIXME: this is the current blocking bug. client-id (.readUInt32BE payload 0) hs-type (.readUInt16BE payload 4) len (.readUInt16BE payload 6) [shared-sec created] (hs/server-reply config {:pub-B pub-B :node-id node-id :sec-b sec-b} (.slice payload 8) (-> config :enc :key-len))] (assert (= hs-type 2) "unsupported handshake type") [client-id shared-sec created])) ;; sent by client: (defn send-mk-secret [config mix-socket client-id mix-auth] (let [[auth create] (hs/client-init config mix-auth)] (log/debug :FIXME :mk-secret (.-length create)) (circ/send-sp config mix-socket (b/cat (-> :mk-secret from-cmd b/new1) (b/new4 client-id) (b/new2 2) ;; type of hs (-> create .-length b/new2) create)) auth)) ;; init: (defn init [config] (let [[sp-ctrl sp-notify] (:sp-chans config) mix-answer (chan) config (merge config [sp-ctrl sp-notify]) process (fn [{cmd :cmd data :data socket :socket}] (let [cmd (if (number? cmd) (to-cmd cmd) cmd)] (log/info "Recvd" cmd) (condp = cmd ;;;; recvd by mix: :new-client (let [conns (c/get-all) sps (for [k (keys conns) :let [conn-data (conns k)] :when (= :super-peer (:role conn-data))] [k conn-data]) [sp-socket sp-data] (first sps) sp-id (-> sp-data :auth :srv-id) sp-clients (-> sp-data :client-secrets) sp-clients (or sp-clients {}) client-id (first (filter #(not (sp-clients %)) (range (:max-clients-per-channel config)))) client-ntor-id data] (when (not= 1 (count sps)) (log/error "wrong number of superpeers" sps)) (assert client-id "could not add client, channel full") (log/debug "Sending SP id" (b/hx sp-id) "to client" client-id) (c/update-data sp-socket [:client-secrets] (merge sp-clients {client-id {:secret nil :srv-id client-ntor-id}})) (c/update-data socket [:future-sp] sp-socket) (send-client-sp-id config socket client-id sp-id)) :mk-secret (let [[client-id shared-sec created] (mk-secret-from-create config data) on-destroy (-> socket c/get-data :on-destroy) sp-socket (-> socket c/get-data :future-sp) client-secrets (-> sp-socket c/get-data :client-secrets)] (c/update-data sp-socket [:client-secrets] (merge client-secrets {client-id {:secret shared-sec}})) (c/update-data socket [:on-destroy] (cons #(c/add-id sp-socket (:srv-id (client-secrets client-id))) on-destroy)) (dtls/send-node-secret {:index client-id} shared-sec) ;; send ack to client: (circ/send-sp config socket (b/cat (-> :ack-secret from-cmd b/new1) (-> created .-length b/new2) created))) ;;;; recvd by client: :register-to-sp (let [client-id (.readUInt32BE data 0) sp-id (.slice data 4)] (go (>! mix-answer [client-id sp-id]))) ;; :connect function is waiting for this. :ack-secret (go (>! mix-answer data)) ;; internal commands (not from the network) :connect (let [zone (-> config :geo-info :zone) net-info (dir/get-net-info) select-mixes #(->> net-info seq (map second) (filter %) shuffle) ;; FIXME make this a function mix (first (select-mixes #(and (= (:role %) :mix) (= (:zone %) zone)))) socket (conn/new :herd :client mix config {:connect identity})] ;; 1/ connect to mix, wait for client-id & sp-id (go (let [mix-socket (<! socket)] (circ/send-id config mix-socket) (log/debug :FIXME "sent id") (let [[client-id sp-id] (<! mix-answer) sp (first (select-mixes #(b/b= sp-id (-> % :auth :srv-id))))] (log/debug "Will connect to SP" (b/hx sp-id)) (assert sp "Could not find SP") ;; 2/ connect to SP: (let [socket (conn/new :herd :client sp config {:connect identity}) auth (send-mk-secret config mix-socket client-id (:auth mix)) payload (<! mix-answer) shared-sec (hs/client-finalise auth (.slice payload 2) (-> config :enc :key-len)) sp-socket (<! socket)] (circ/send-sp config sp-socket (b/cat (-> :register-id-to-sp from-cmd b/new1) (b/new4 client-id))) ;; 3/ create circuits: (dtls/send-role sp-socket :super-peer) (dtls/send-node-secret sp-socket shared-sec) (c/update-data sp-socket [:sp-auth] (:auth sp)) ;; FIXME: not sure if we'll keep this, but for now it'll do (c/update-data sp-socket [:auth] (-> mix-socket c/get-data :auth)) ;; FIXME: not sure if we'll keep this, but for now it'll do (c/add-id sp-socket (-> mix :auth :srv-id)) ;(circ/send-id config sp-socket) (path/init-pools config net-info (:geo-info config) 2 (c/get-data sp-socket)) (>! sp-notify [sp-socket mix])))))))))] (go-loop [msg (<! sp-ctrl)] (process msg) (recur (<! sp-ctrl))) (log/info "Superpeer signaling initialised")))
true
(ns herd-node.sp (:require [cljs.core :as cljs] [cljs.nodejs :as node] [cljs.core.async :refer [chan <! >! sub pub unsub close!] :as a] [herd-node.parse :as conv] [herd-node.dtls-comm :as dtls] [herd-node.conn-mgr :as conn] [herd-node.circ :as circ] [herd-node.path :as path] [herd-node.ntor :as hs] [herd-node.conns :as c] [herd-node.log :as log] [herd-node.dir :as dir] [herd-node.buf :as b]) (:require-macros [cljs.core.async.macros :as m :refer [go-loop go]])) (def to-cmd {0 :register-to-sp 1 :mk-secret 2 :ack-secret 3 :register-id-to-sp }) (def from-cmd (apply merge (for [k (keys to-cmd)] {(to-cmd k) k}))) ;; sent by mix: (defn send-client-sp-id [config socket client-index sp-id] "send a sp id & its client-index on the channel to a client" (circ/send-sp config socket (b/cat (-> :register-to-sp from-cmd b/new1) (b/new4 client-index) sp-id))) (defn mk-secret-from-create [config payload] (log/debug ":aoeu" (.-length payload)) (let [{pub-B :pub node-PI:KEY:<KEY>END_PI :id sec-b :sec} (-> config :auth :herd-id) ;; FIXME: this is the current blocking bug. client-id (.readUInt32BE payload 0) hs-type (.readUInt16BE payload 4) len (.readUInt16BE payload 6) [shared-sec created] (hs/server-reply config {:pub-B pub-B :node-id node-id :sec-b sec-b} (.slice payload 8) (-> config :enc :key-len))] (assert (= hs-type 2) "unsupported handshake type") [client-id shared-sec created])) ;; sent by client: (defn send-mk-secret [config mix-socket client-id mix-auth] (let [[auth create] (hs/client-init config mix-auth)] (log/debug :FIXME :mk-secret (.-length create)) (circ/send-sp config mix-socket (b/cat (-> :mk-secret from-cmd b/new1) (b/new4 client-id) (b/new2 2) ;; type of hs (-> create .-length b/new2) create)) auth)) ;; init: (defn init [config] (let [[sp-ctrl sp-notify] (:sp-chans config) mix-answer (chan) config (merge config [sp-ctrl sp-notify]) process (fn [{cmd :cmd data :data socket :socket}] (let [cmd (if (number? cmd) (to-cmd cmd) cmd)] (log/info "Recvd" cmd) (condp = cmd ;;;; recvd by mix: :new-client (let [conns (c/get-all) sps (for [k (keys conns) :let [conn-data (conns k)] :when (= :super-peer (:role conn-data))] [k conn-data]) [sp-socket sp-data] (first sps) sp-id (-> sp-data :auth :srv-id) sp-clients (-> sp-data :client-secrets) sp-clients (or sp-clients {}) client-id (first (filter #(not (sp-clients %)) (range (:max-clients-per-channel config)))) client-ntor-id data] (when (not= 1 (count sps)) (log/error "wrong number of superpeers" sps)) (assert client-id "could not add client, channel full") (log/debug "Sending SP id" (b/hx sp-id) "to client" client-id) (c/update-data sp-socket [:client-secrets] (merge sp-clients {client-id {:secret nil :srv-id client-ntor-id}})) (c/update-data socket [:future-sp] sp-socket) (send-client-sp-id config socket client-id sp-id)) :mk-secret (let [[client-id shared-sec created] (mk-secret-from-create config data) on-destroy (-> socket c/get-data :on-destroy) sp-socket (-> socket c/get-data :future-sp) client-secrets (-> sp-socket c/get-data :client-secrets)] (c/update-data sp-socket [:client-secrets] (merge client-secrets {client-id {:secret shared-sec}})) (c/update-data socket [:on-destroy] (cons #(c/add-id sp-socket (:srv-id (client-secrets client-id))) on-destroy)) (dtls/send-node-secret {:index client-id} shared-sec) ;; send ack to client: (circ/send-sp config socket (b/cat (-> :ack-secret from-cmd b/new1) (-> created .-length b/new2) created))) ;;;; recvd by client: :register-to-sp (let [client-id (.readUInt32BE data 0) sp-id (.slice data 4)] (go (>! mix-answer [client-id sp-id]))) ;; :connect function is waiting for this. :ack-secret (go (>! mix-answer data)) ;; internal commands (not from the network) :connect (let [zone (-> config :geo-info :zone) net-info (dir/get-net-info) select-mixes #(->> net-info seq (map second) (filter %) shuffle) ;; FIXME make this a function mix (first (select-mixes #(and (= (:role %) :mix) (= (:zone %) zone)))) socket (conn/new :herd :client mix config {:connect identity})] ;; 1/ connect to mix, wait for client-id & sp-id (go (let [mix-socket (<! socket)] (circ/send-id config mix-socket) (log/debug :FIXME "sent id") (let [[client-id sp-id] (<! mix-answer) sp (first (select-mixes #(b/b= sp-id (-> % :auth :srv-id))))] (log/debug "Will connect to SP" (b/hx sp-id)) (assert sp "Could not find SP") ;; 2/ connect to SP: (let [socket (conn/new :herd :client sp config {:connect identity}) auth (send-mk-secret config mix-socket client-id (:auth mix)) payload (<! mix-answer) shared-sec (hs/client-finalise auth (.slice payload 2) (-> config :enc :key-len)) sp-socket (<! socket)] (circ/send-sp config sp-socket (b/cat (-> :register-id-to-sp from-cmd b/new1) (b/new4 client-id))) ;; 3/ create circuits: (dtls/send-role sp-socket :super-peer) (dtls/send-node-secret sp-socket shared-sec) (c/update-data sp-socket [:sp-auth] (:auth sp)) ;; FIXME: not sure if we'll keep this, but for now it'll do (c/update-data sp-socket [:auth] (-> mix-socket c/get-data :auth)) ;; FIXME: not sure if we'll keep this, but for now it'll do (c/add-id sp-socket (-> mix :auth :srv-id)) ;(circ/send-id config sp-socket) (path/init-pools config net-info (:geo-info config) 2 (c/get-data sp-socket)) (>! sp-notify [sp-socket mix])))))))))] (go-loop [msg (<! sp-ctrl)] (process msg) (recur (<! sp-ctrl))) (log/info "Superpeer signaling initialised")))
[ { "context": "p {} \"Created by <a href=\\\"http://tiltontec.com\\\">Kenneth Tilton</a>.\")\n (p {} \"Inspired by <a href=\\\"http:/", "end": 3255, "score": 0.9998714327812195, "start": 3241, "tag": "NAME", "value": "Kenneth Tilton" } ]
cljs/matrix/src/todo/matrix.cljs
kennytilton/ConnectJS
7
(ns todo.matrix (:require [cljs.pprint :as pp] [clojure.string :as str] [bide.core :as r] [tiltontec.util.core :refer [xor now]] [tiltontec.cell.base :refer [unbound ia-type *within-integrity*]] [tiltontec.cell.core :refer-macros [c? c?n c?once] :refer [c-in]] [tiltontec.model.core :refer [md-get md-reset! mxi-find mxu-find-class kid-values-kids] :as md] [tiltontec.tag.html :refer [io-clear-storage to-html mxa-find-tag dom-tag tag-dom mxa-find-type dom-has-class dom-ancestor-by-tag]] [tiltontec.tag.gen :refer-macros [ on-evt! section header h1 input footer p a span label ul li div button] :refer [dom-tag]] [todo.todo :refer [make-todo td-title td-completed td-upsert td-delete load-all td-id td-toggle-completed]])) (def matrix "Populated ny matrix-build! with the root of the application matrix." (atom nil)) (declare landing-page mx-todos mx-todo-items mx-find-matrix mx-todo-lookup event-to-mx mx-route) (defn matrix-build! [] (reset! matrix (md/make ::todoApp :route (c-in nil) :todos (c?once (todo.todo/todo-list me)) :dom (c?once (binding [md/*par* me] ;; todo macro-ize (landing-page)))))) (defn dom [] ;; API (md/md-get @matrix :dom)) ;;; --- routing ------------------------------- (def router (r/router [["/" :All] ["/active" :Active] ["/completed" :Completed]])) (defn on-navigate [route params query] (md-reset! @matrix :route (name route))) (defn start-router [] ;; (io-clear-storage) (r/start! router {:default :todo/all :on-navigate on-navigate})) ;;; --- the landing page ------------------------------- ; - subroutines serve to break up the page into manageable chunks (declare todo-list-item toggle-all dashboard-footer todo-entry) (defn landing-page [] [(section {:class "todoapp"} (header {:class "header"} (h1 {} "todos") (todo-entry)) (section {:class "main" :hidden (c? (zero? (count (mx-todo-items me)))) } (toggle-all) ;; Next we address the problem ReactJS handles by allowing ;; keys on items of a list of elements, namely how not to ;; regen all just because one comes or goes. (ul {:class "todo-list" :kid-values (c? (let [route (md-get (mx-find-matrix me) :route)] ;; todo figure out where they want filtering done (mx-todo-items me))) :kid-key #(md-get % :todo) :kid-factory todo-list-item} (kid-values-kids me cache))) (dashboard-footer)) ;; no need to hide everything behind a function.... (footer {:class "info"} (p {} "Double-click a todo to edit it.") (p {} "Created by <a href=\"http://tiltontec.com\">Kenneth Tilton</a>.") (p {} "Inspired by <a href=\"http://todomvc.com\">TodoMVC</a>."))]) ;; --- to-do Entry ------------------------- (defn todo-entry [] (input {:class "new-todo" :autofocus true :placeholder "What needs to be done?" :onkeypress (on-evt! todo.matrix/todo-process-on-enter)})) (defn todo-process-on-enter [e] (when (= (.-key e) "Enter") (let [raw (.-value (.-target e)) title (str/trim raw)] (if (= title "") (when (pos? (count raw)) (.alert js/window "A reminder to do nothing? We like it! But no.")) (md-reset! (mx-todos) :items-raw (conj (md-get (mx-todos) :items-raw) (make-todo {:title title})))) (set! (.-value (.-target e)) "")))) ;; -- toggle-all ------------------------------------- (defn toggle-all [] [(input {:id "toggle-all" :class "toggle-all" :input-type "checkbox" :action (c? (if (some (complement td-completed) (mx-todo-items me)) :complete :uncomplete)) :checked (c? (= (md-get me :action) :uncomplete))}) (label {:for "toggle-all" :onclick (on-evt! todo.matrix/td-completed-toggle-all)} "Mark all as complete")]) (defn td-completed-toggle-all [event] (let [input (mxu-find-class (event-to-mx event) "toggle-all") action (md-get input :action)] (doseq [td (mx-todo-items)] (md-reset! td :completed (when (= action :complete) (now)))))) ;; --- to-do list LI --------------------------------- (defn todo-list-item [me td] (li {:todo td :name :todo-li :class (c? (if (td-completed td) "completed" "")) :display (c? (let [route (mx-route me)] (cond (nil? route) unbound (or (= route "All") (xor (= route "Active") (md-get td :completed))) "block" :default "none")))} (div {:class "view"} (input {:class "toggle" :input-type "checkbox" :checked (c? (md-get td :completed)) :onclick (on-evt! todo.matrix/todo-toggle-completed (td-id td))}) (label {:ondblclick (on-evt! todo.matrix/todo-start-editing)} (td-title td)) (button {:class "destroy" :onclick (on-evt! todo.matrix/delete-by-key (td-id td))})) (input {:class "edit" :value (c?n (td-title td)) :onblur (on-evt! todo.matrix/todo-edit (td-id td)) :onkeydown (on-evt! todo.matrix/todo-edit (td-id td))}))) (defn delete-by-key [event id] ;; todo can we get this inline at leasT? (td-delete (mx-todo-lookup id))) (defn todo-toggle-completed [event id] (let [is (mx-todo-items) td (some (fn [td] (when (= id (td-id td)) td)) is)] (td-toggle-completed td))) (defn todo-start-editing [e] ;; I am tempted to make this more declarative, but leave as is ;; as an example of how MatrixJS allows straight JS coding (let [lbl (event-to-mx e) li (mxa-find-tag lbl "li") edt-dom (.item (.getElementsByClassName (tag-dom li) "edit") 0)] (.add (.-classList (tag-dom li)) "editing") (.focus edt-dom) ;; no one gets this right any more... (.setSelectionRange edt-dom 0 (.-length (.-value edt-dom))))) (defn todo-edit [e td-key] ;; this all might be done more declaratively (when-not *within-integrity* ;; todo is this still a problem? If so, handle better (let [edom (.-target e) title (str/trim (.-value edom)) td (mx-todo-lookup td-key (event-to-mx e)) li-dom (dom-ancestor-by-tag edom "li")] (cond (or (and (= (.-type e) "blur") (dom-has-class li-dom "editing")) (= (.-key e) "Enter")) (do (if (= title "") (td-delete td) (md-reset! td :title title)) (set! (.-value edom) title) ;; in case trimmed (.remove (.-classList li-dom) "editing")) (= (.-key e) "Escape") (do (set! (.-value edom) (td-title td)) (.remove (.-classList li-dom) "editing")))))) ;; --- dashboard ------------------------------------- (defn dashboard-footer [] (footer {:class "footer" :hidden (c? (zero? (count (mx-todo-items me))))} (span {:class "todo-count" :content (c? (pp/cl-format nil "<strong>~a</strong> item~:P remaining" (count (remove td-completed (mx-todo-items me)))))}) (ul {:class "filters"} (for [[label route] [["All", "#/"], ["Active","#/active"], ["Completed","#/completed"]]] (li {} (a {:href route :selector label :selected (c? (= (:selector @me) (mx-route me))) :class (c? (if (md-get me :selected) "selected" ""))} label)))) (button {:class "clear-completed" :hidden (c? (zero? (count (filter td-completed (mx-todo-items me))))) :onclick (on-evt! todo.matrix/clear-completed)} "Clear completed"))) (defn clear-completed [e] (doseq [td (filter td-completed (mx-todo-items))] (td-delete td))) ;; --- dependency-establishing accessors --------------------- (defn mx-route [mx] (md-get (mx-find-matrix mx) :route)) (defn mx-todos ([] (assert @matrix) (md-get @matrix :todos)) ([mx] (if (nil? mx) (mx-todos) (let [mtrx (mx-find-matrix mx)] (assert mtrx) (md-get mtrx :todos))))) (defn mx-todo-items ([] (mx-todo-items nil)) ([mx] (assert (mx-todos mx) "mti") (md-get (mx-todos mx) :items))) (defn mx-todo-lookup ([id] (mx-todo-lookup id nil)) ([id mx] (some (fn [td] (when (= id (td-id td)) td)) (mx-todo-items mx)))) (defn event-to-mx [e] (dom-tag (.-target e))) (defn mx-find-matrix [mx] (mxa-find-type mx ::todoApp))
65810
(ns todo.matrix (:require [cljs.pprint :as pp] [clojure.string :as str] [bide.core :as r] [tiltontec.util.core :refer [xor now]] [tiltontec.cell.base :refer [unbound ia-type *within-integrity*]] [tiltontec.cell.core :refer-macros [c? c?n c?once] :refer [c-in]] [tiltontec.model.core :refer [md-get md-reset! mxi-find mxu-find-class kid-values-kids] :as md] [tiltontec.tag.html :refer [io-clear-storage to-html mxa-find-tag dom-tag tag-dom mxa-find-type dom-has-class dom-ancestor-by-tag]] [tiltontec.tag.gen :refer-macros [ on-evt! section header h1 input footer p a span label ul li div button] :refer [dom-tag]] [todo.todo :refer [make-todo td-title td-completed td-upsert td-delete load-all td-id td-toggle-completed]])) (def matrix "Populated ny matrix-build! with the root of the application matrix." (atom nil)) (declare landing-page mx-todos mx-todo-items mx-find-matrix mx-todo-lookup event-to-mx mx-route) (defn matrix-build! [] (reset! matrix (md/make ::todoApp :route (c-in nil) :todos (c?once (todo.todo/todo-list me)) :dom (c?once (binding [md/*par* me] ;; todo macro-ize (landing-page)))))) (defn dom [] ;; API (md/md-get @matrix :dom)) ;;; --- routing ------------------------------- (def router (r/router [["/" :All] ["/active" :Active] ["/completed" :Completed]])) (defn on-navigate [route params query] (md-reset! @matrix :route (name route))) (defn start-router [] ;; (io-clear-storage) (r/start! router {:default :todo/all :on-navigate on-navigate})) ;;; --- the landing page ------------------------------- ; - subroutines serve to break up the page into manageable chunks (declare todo-list-item toggle-all dashboard-footer todo-entry) (defn landing-page [] [(section {:class "todoapp"} (header {:class "header"} (h1 {} "todos") (todo-entry)) (section {:class "main" :hidden (c? (zero? (count (mx-todo-items me)))) } (toggle-all) ;; Next we address the problem ReactJS handles by allowing ;; keys on items of a list of elements, namely how not to ;; regen all just because one comes or goes. (ul {:class "todo-list" :kid-values (c? (let [route (md-get (mx-find-matrix me) :route)] ;; todo figure out where they want filtering done (mx-todo-items me))) :kid-key #(md-get % :todo) :kid-factory todo-list-item} (kid-values-kids me cache))) (dashboard-footer)) ;; no need to hide everything behind a function.... (footer {:class "info"} (p {} "Double-click a todo to edit it.") (p {} "Created by <a href=\"http://tiltontec.com\"><NAME></a>.") (p {} "Inspired by <a href=\"http://todomvc.com\">TodoMVC</a>."))]) ;; --- to-do Entry ------------------------- (defn todo-entry [] (input {:class "new-todo" :autofocus true :placeholder "What needs to be done?" :onkeypress (on-evt! todo.matrix/todo-process-on-enter)})) (defn todo-process-on-enter [e] (when (= (.-key e) "Enter") (let [raw (.-value (.-target e)) title (str/trim raw)] (if (= title "") (when (pos? (count raw)) (.alert js/window "A reminder to do nothing? We like it! But no.")) (md-reset! (mx-todos) :items-raw (conj (md-get (mx-todos) :items-raw) (make-todo {:title title})))) (set! (.-value (.-target e)) "")))) ;; -- toggle-all ------------------------------------- (defn toggle-all [] [(input {:id "toggle-all" :class "toggle-all" :input-type "checkbox" :action (c? (if (some (complement td-completed) (mx-todo-items me)) :complete :uncomplete)) :checked (c? (= (md-get me :action) :uncomplete))}) (label {:for "toggle-all" :onclick (on-evt! todo.matrix/td-completed-toggle-all)} "Mark all as complete")]) (defn td-completed-toggle-all [event] (let [input (mxu-find-class (event-to-mx event) "toggle-all") action (md-get input :action)] (doseq [td (mx-todo-items)] (md-reset! td :completed (when (= action :complete) (now)))))) ;; --- to-do list LI --------------------------------- (defn todo-list-item [me td] (li {:todo td :name :todo-li :class (c? (if (td-completed td) "completed" "")) :display (c? (let [route (mx-route me)] (cond (nil? route) unbound (or (= route "All") (xor (= route "Active") (md-get td :completed))) "block" :default "none")))} (div {:class "view"} (input {:class "toggle" :input-type "checkbox" :checked (c? (md-get td :completed)) :onclick (on-evt! todo.matrix/todo-toggle-completed (td-id td))}) (label {:ondblclick (on-evt! todo.matrix/todo-start-editing)} (td-title td)) (button {:class "destroy" :onclick (on-evt! todo.matrix/delete-by-key (td-id td))})) (input {:class "edit" :value (c?n (td-title td)) :onblur (on-evt! todo.matrix/todo-edit (td-id td)) :onkeydown (on-evt! todo.matrix/todo-edit (td-id td))}))) (defn delete-by-key [event id] ;; todo can we get this inline at leasT? (td-delete (mx-todo-lookup id))) (defn todo-toggle-completed [event id] (let [is (mx-todo-items) td (some (fn [td] (when (= id (td-id td)) td)) is)] (td-toggle-completed td))) (defn todo-start-editing [e] ;; I am tempted to make this more declarative, but leave as is ;; as an example of how MatrixJS allows straight JS coding (let [lbl (event-to-mx e) li (mxa-find-tag lbl "li") edt-dom (.item (.getElementsByClassName (tag-dom li) "edit") 0)] (.add (.-classList (tag-dom li)) "editing") (.focus edt-dom) ;; no one gets this right any more... (.setSelectionRange edt-dom 0 (.-length (.-value edt-dom))))) (defn todo-edit [e td-key] ;; this all might be done more declaratively (when-not *within-integrity* ;; todo is this still a problem? If so, handle better (let [edom (.-target e) title (str/trim (.-value edom)) td (mx-todo-lookup td-key (event-to-mx e)) li-dom (dom-ancestor-by-tag edom "li")] (cond (or (and (= (.-type e) "blur") (dom-has-class li-dom "editing")) (= (.-key e) "Enter")) (do (if (= title "") (td-delete td) (md-reset! td :title title)) (set! (.-value edom) title) ;; in case trimmed (.remove (.-classList li-dom) "editing")) (= (.-key e) "Escape") (do (set! (.-value edom) (td-title td)) (.remove (.-classList li-dom) "editing")))))) ;; --- dashboard ------------------------------------- (defn dashboard-footer [] (footer {:class "footer" :hidden (c? (zero? (count (mx-todo-items me))))} (span {:class "todo-count" :content (c? (pp/cl-format nil "<strong>~a</strong> item~:P remaining" (count (remove td-completed (mx-todo-items me)))))}) (ul {:class "filters"} (for [[label route] [["All", "#/"], ["Active","#/active"], ["Completed","#/completed"]]] (li {} (a {:href route :selector label :selected (c? (= (:selector @me) (mx-route me))) :class (c? (if (md-get me :selected) "selected" ""))} label)))) (button {:class "clear-completed" :hidden (c? (zero? (count (filter td-completed (mx-todo-items me))))) :onclick (on-evt! todo.matrix/clear-completed)} "Clear completed"))) (defn clear-completed [e] (doseq [td (filter td-completed (mx-todo-items))] (td-delete td))) ;; --- dependency-establishing accessors --------------------- (defn mx-route [mx] (md-get (mx-find-matrix mx) :route)) (defn mx-todos ([] (assert @matrix) (md-get @matrix :todos)) ([mx] (if (nil? mx) (mx-todos) (let [mtrx (mx-find-matrix mx)] (assert mtrx) (md-get mtrx :todos))))) (defn mx-todo-items ([] (mx-todo-items nil)) ([mx] (assert (mx-todos mx) "mti") (md-get (mx-todos mx) :items))) (defn mx-todo-lookup ([id] (mx-todo-lookup id nil)) ([id mx] (some (fn [td] (when (= id (td-id td)) td)) (mx-todo-items mx)))) (defn event-to-mx [e] (dom-tag (.-target e))) (defn mx-find-matrix [mx] (mxa-find-type mx ::todoApp))
true
(ns todo.matrix (:require [cljs.pprint :as pp] [clojure.string :as str] [bide.core :as r] [tiltontec.util.core :refer [xor now]] [tiltontec.cell.base :refer [unbound ia-type *within-integrity*]] [tiltontec.cell.core :refer-macros [c? c?n c?once] :refer [c-in]] [tiltontec.model.core :refer [md-get md-reset! mxi-find mxu-find-class kid-values-kids] :as md] [tiltontec.tag.html :refer [io-clear-storage to-html mxa-find-tag dom-tag tag-dom mxa-find-type dom-has-class dom-ancestor-by-tag]] [tiltontec.tag.gen :refer-macros [ on-evt! section header h1 input footer p a span label ul li div button] :refer [dom-tag]] [todo.todo :refer [make-todo td-title td-completed td-upsert td-delete load-all td-id td-toggle-completed]])) (def matrix "Populated ny matrix-build! with the root of the application matrix." (atom nil)) (declare landing-page mx-todos mx-todo-items mx-find-matrix mx-todo-lookup event-to-mx mx-route) (defn matrix-build! [] (reset! matrix (md/make ::todoApp :route (c-in nil) :todos (c?once (todo.todo/todo-list me)) :dom (c?once (binding [md/*par* me] ;; todo macro-ize (landing-page)))))) (defn dom [] ;; API (md/md-get @matrix :dom)) ;;; --- routing ------------------------------- (def router (r/router [["/" :All] ["/active" :Active] ["/completed" :Completed]])) (defn on-navigate [route params query] (md-reset! @matrix :route (name route))) (defn start-router [] ;; (io-clear-storage) (r/start! router {:default :todo/all :on-navigate on-navigate})) ;;; --- the landing page ------------------------------- ; - subroutines serve to break up the page into manageable chunks (declare todo-list-item toggle-all dashboard-footer todo-entry) (defn landing-page [] [(section {:class "todoapp"} (header {:class "header"} (h1 {} "todos") (todo-entry)) (section {:class "main" :hidden (c? (zero? (count (mx-todo-items me)))) } (toggle-all) ;; Next we address the problem ReactJS handles by allowing ;; keys on items of a list of elements, namely how not to ;; regen all just because one comes or goes. (ul {:class "todo-list" :kid-values (c? (let [route (md-get (mx-find-matrix me) :route)] ;; todo figure out where they want filtering done (mx-todo-items me))) :kid-key #(md-get % :todo) :kid-factory todo-list-item} (kid-values-kids me cache))) (dashboard-footer)) ;; no need to hide everything behind a function.... (footer {:class "info"} (p {} "Double-click a todo to edit it.") (p {} "Created by <a href=\"http://tiltontec.com\">PI:NAME:<NAME>END_PI</a>.") (p {} "Inspired by <a href=\"http://todomvc.com\">TodoMVC</a>."))]) ;; --- to-do Entry ------------------------- (defn todo-entry [] (input {:class "new-todo" :autofocus true :placeholder "What needs to be done?" :onkeypress (on-evt! todo.matrix/todo-process-on-enter)})) (defn todo-process-on-enter [e] (when (= (.-key e) "Enter") (let [raw (.-value (.-target e)) title (str/trim raw)] (if (= title "") (when (pos? (count raw)) (.alert js/window "A reminder to do nothing? We like it! But no.")) (md-reset! (mx-todos) :items-raw (conj (md-get (mx-todos) :items-raw) (make-todo {:title title})))) (set! (.-value (.-target e)) "")))) ;; -- toggle-all ------------------------------------- (defn toggle-all [] [(input {:id "toggle-all" :class "toggle-all" :input-type "checkbox" :action (c? (if (some (complement td-completed) (mx-todo-items me)) :complete :uncomplete)) :checked (c? (= (md-get me :action) :uncomplete))}) (label {:for "toggle-all" :onclick (on-evt! todo.matrix/td-completed-toggle-all)} "Mark all as complete")]) (defn td-completed-toggle-all [event] (let [input (mxu-find-class (event-to-mx event) "toggle-all") action (md-get input :action)] (doseq [td (mx-todo-items)] (md-reset! td :completed (when (= action :complete) (now)))))) ;; --- to-do list LI --------------------------------- (defn todo-list-item [me td] (li {:todo td :name :todo-li :class (c? (if (td-completed td) "completed" "")) :display (c? (let [route (mx-route me)] (cond (nil? route) unbound (or (= route "All") (xor (= route "Active") (md-get td :completed))) "block" :default "none")))} (div {:class "view"} (input {:class "toggle" :input-type "checkbox" :checked (c? (md-get td :completed)) :onclick (on-evt! todo.matrix/todo-toggle-completed (td-id td))}) (label {:ondblclick (on-evt! todo.matrix/todo-start-editing)} (td-title td)) (button {:class "destroy" :onclick (on-evt! todo.matrix/delete-by-key (td-id td))})) (input {:class "edit" :value (c?n (td-title td)) :onblur (on-evt! todo.matrix/todo-edit (td-id td)) :onkeydown (on-evt! todo.matrix/todo-edit (td-id td))}))) (defn delete-by-key [event id] ;; todo can we get this inline at leasT? (td-delete (mx-todo-lookup id))) (defn todo-toggle-completed [event id] (let [is (mx-todo-items) td (some (fn [td] (when (= id (td-id td)) td)) is)] (td-toggle-completed td))) (defn todo-start-editing [e] ;; I am tempted to make this more declarative, but leave as is ;; as an example of how MatrixJS allows straight JS coding (let [lbl (event-to-mx e) li (mxa-find-tag lbl "li") edt-dom (.item (.getElementsByClassName (tag-dom li) "edit") 0)] (.add (.-classList (tag-dom li)) "editing") (.focus edt-dom) ;; no one gets this right any more... (.setSelectionRange edt-dom 0 (.-length (.-value edt-dom))))) (defn todo-edit [e td-key] ;; this all might be done more declaratively (when-not *within-integrity* ;; todo is this still a problem? If so, handle better (let [edom (.-target e) title (str/trim (.-value edom)) td (mx-todo-lookup td-key (event-to-mx e)) li-dom (dom-ancestor-by-tag edom "li")] (cond (or (and (= (.-type e) "blur") (dom-has-class li-dom "editing")) (= (.-key e) "Enter")) (do (if (= title "") (td-delete td) (md-reset! td :title title)) (set! (.-value edom) title) ;; in case trimmed (.remove (.-classList li-dom) "editing")) (= (.-key e) "Escape") (do (set! (.-value edom) (td-title td)) (.remove (.-classList li-dom) "editing")))))) ;; --- dashboard ------------------------------------- (defn dashboard-footer [] (footer {:class "footer" :hidden (c? (zero? (count (mx-todo-items me))))} (span {:class "todo-count" :content (c? (pp/cl-format nil "<strong>~a</strong> item~:P remaining" (count (remove td-completed (mx-todo-items me)))))}) (ul {:class "filters"} (for [[label route] [["All", "#/"], ["Active","#/active"], ["Completed","#/completed"]]] (li {} (a {:href route :selector label :selected (c? (= (:selector @me) (mx-route me))) :class (c? (if (md-get me :selected) "selected" ""))} label)))) (button {:class "clear-completed" :hidden (c? (zero? (count (filter td-completed (mx-todo-items me))))) :onclick (on-evt! todo.matrix/clear-completed)} "Clear completed"))) (defn clear-completed [e] (doseq [td (filter td-completed (mx-todo-items))] (td-delete td))) ;; --- dependency-establishing accessors --------------------- (defn mx-route [mx] (md-get (mx-find-matrix mx) :route)) (defn mx-todos ([] (assert @matrix) (md-get @matrix :todos)) ([mx] (if (nil? mx) (mx-todos) (let [mtrx (mx-find-matrix mx)] (assert mtrx) (md-get mtrx :todos))))) (defn mx-todo-items ([] (mx-todo-items nil)) ([mx] (assert (mx-todos mx) "mti") (md-get (mx-todos mx) :items))) (defn mx-todo-lookup ([id] (mx-todo-lookup id nil)) ([id mx] (some (fn [td] (when (= id (td-id td)) td)) (mx-todo-items mx)))) (defn event-to-mx [e] (dom-tag (.-target e))) (defn mx-find-matrix [mx] (mxa-find-type mx ::todoApp))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998133778572083, "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.9998233914375305, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/dynamo/integration/garbage_collection.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 dynamo.integration.garbage-collection "Garbage disposal of nodes on the dynamo graph level" (:require [clojure.test :refer :all] [dynamo.graph :as g] [support.test-support :refer [with-clean-system tx-nodes]])) (g/defnode EmptyNode) (defn gnodes [world] (-> (g/graph world) :nodes vals)) (deftest test-deleting-nodes (testing "adding one node and deleting it" (with-clean-system (let [[node] (tx-nodes (g/make-node world EmptyNode))] (is (= 1 (count (gnodes world)))) (g/transact (g/delete-node node)) (is (= 0 (count (gnodes world))))))) (testing "adding twos node and deleting one" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world) ))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world))))))) (testing "adding twos node and deleting one, then adding it back" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world)))) (g/transact (g/make-node world EmptyNode)) (is (= 2 (count (gnodes world))))))) (testing "adding twos node and deleting one, then adding it back and deleting it" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world)))) (let [[node3] (tx-nodes (g/make-node world EmptyNode))] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node3)) (is (= 1 (count (gnodes world)))))))) (testing "adding 100 nodes, then deleting 50" (with-clean-system (let [nodes (g/tx-nodes-added (g/transact (repeatedly 100 #(g/make-node world EmptyNode))) )] (is (= 100 (count (gnodes world)))) (g/transact (mapv #(g/delete-node %) (take 50 nodes))) (is (= 50 (count (gnodes world))))))))
55118
;; 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 dynamo.integration.garbage-collection "Garbage disposal of nodes on the dynamo graph level" (:require [clojure.test :refer :all] [dynamo.graph :as g] [support.test-support :refer [with-clean-system tx-nodes]])) (g/defnode EmptyNode) (defn gnodes [world] (-> (g/graph world) :nodes vals)) (deftest test-deleting-nodes (testing "adding one node and deleting it" (with-clean-system (let [[node] (tx-nodes (g/make-node world EmptyNode))] (is (= 1 (count (gnodes world)))) (g/transact (g/delete-node node)) (is (= 0 (count (gnodes world))))))) (testing "adding twos node and deleting one" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world) ))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world))))))) (testing "adding twos node and deleting one, then adding it back" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world)))) (g/transact (g/make-node world EmptyNode)) (is (= 2 (count (gnodes world))))))) (testing "adding twos node and deleting one, then adding it back and deleting it" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world)))) (let [[node3] (tx-nodes (g/make-node world EmptyNode))] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node3)) (is (= 1 (count (gnodes world)))))))) (testing "adding 100 nodes, then deleting 50" (with-clean-system (let [nodes (g/tx-nodes-added (g/transact (repeatedly 100 #(g/make-node world EmptyNode))) )] (is (= 100 (count (gnodes world)))) (g/transact (mapv #(g/delete-node %) (take 50 nodes))) (is (= 50 (count (gnodes world))))))))
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 dynamo.integration.garbage-collection "Garbage disposal of nodes on the dynamo graph level" (:require [clojure.test :refer :all] [dynamo.graph :as g] [support.test-support :refer [with-clean-system tx-nodes]])) (g/defnode EmptyNode) (defn gnodes [world] (-> (g/graph world) :nodes vals)) (deftest test-deleting-nodes (testing "adding one node and deleting it" (with-clean-system (let [[node] (tx-nodes (g/make-node world EmptyNode))] (is (= 1 (count (gnodes world)))) (g/transact (g/delete-node node)) (is (= 0 (count (gnodes world))))))) (testing "adding twos node and deleting one" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world) ))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world))))))) (testing "adding twos node and deleting one, then adding it back" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world)))) (g/transact (g/make-node world EmptyNode)) (is (= 2 (count (gnodes world))))))) (testing "adding twos node and deleting one, then adding it back and deleting it" (with-clean-system (let [[node1 node2] (tx-nodes (g/make-node world EmptyNode) (g/make-node world EmptyNode)) graph-nodes (-> (g/graph world) :nodes vals)] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node1)) (is (= 1 (count (gnodes world)))) (let [[node3] (tx-nodes (g/make-node world EmptyNode))] (is (= 2 (count (gnodes world)))) (g/transact (g/delete-node node3)) (is (= 1 (count (gnodes world)))))))) (testing "adding 100 nodes, then deleting 50" (with-clean-system (let [nodes (g/tx-nodes-added (g/transact (repeatedly 100 #(g/make-node world EmptyNode))) )] (is (= 100 (count (gnodes world)))) (g/transact (mapv #(g/delete-node %) (take 50 nodes))) (is (= 50 (count (gnodes world))))))))
[ { "context": "ensource.org/licenses/MIT\"}\n :signing {:gpg-key \"9DD8C3E9\"}\n :source-paths [\"src/main\"]\n :resource-paths ", "end": 198, "score": 0.9993780255317688, "start": 190, "tag": "KEY", "value": "9DD8C3E9" } ]
project.clj
tav10102/cljs-vanilla-react-example
0
(defproject cljs-vanilla-react-example "0.0.1" :description "React & ClojureScript " :license {:name "MIT" :url "https://opensource.org/licenses/MIT"} :signing {:gpg-key "9DD8C3E9"} :source-paths ["src/main"] :resource-paths ["resources"] :plugins [[lein-ancient "0.6.15"] [lein-shell "0.5.0"]] :profiles {:clj {:dependencies [[org.clojure/clojure "1.10.1"]]} :cljs {:dependencies [[thheller/shadow-cljs "2.11.7"]]}} :aliases {"watch" ["shell" "./node_modules/.bin/shadow-cljs" "watch" "app"]})
68769
(defproject cljs-vanilla-react-example "0.0.1" :description "React & ClojureScript " :license {:name "MIT" :url "https://opensource.org/licenses/MIT"} :signing {:gpg-key "<KEY>"} :source-paths ["src/main"] :resource-paths ["resources"] :plugins [[lein-ancient "0.6.15"] [lein-shell "0.5.0"]] :profiles {:clj {:dependencies [[org.clojure/clojure "1.10.1"]]} :cljs {:dependencies [[thheller/shadow-cljs "2.11.7"]]}} :aliases {"watch" ["shell" "./node_modules/.bin/shadow-cljs" "watch" "app"]})
true
(defproject cljs-vanilla-react-example "0.0.1" :description "React & ClojureScript " :license {:name "MIT" :url "https://opensource.org/licenses/MIT"} :signing {:gpg-key "PI:KEY:<KEY>END_PI"} :source-paths ["src/main"] :resource-paths ["resources"] :plugins [[lein-ancient "0.6.15"] [lein-shell "0.5.0"]] :profiles {:clj {:dependencies [[org.clojure/clojure "1.10.1"]]} :cljs {:dependencies [[thheller/shadow-cljs "2.11.7"]]}} :aliases {"watch" ["shell" "./node_modules/.bin/shadow-cljs" "watch" "app"]})
[ { "context": "(ns ^{:author \"Janos Erdos\"}\n erdos.match\n \"Small library for generating p", "end": 26, "score": 0.9998841285705566, "start": 15, "tag": "NAME", "value": "Janos Erdos" } ]
src/erdos/match.clj
erdos/erdos.match
3
(ns ^{:author "Janos Erdos"} erdos.match "Small library for generating pattern matching code." (:require [clojure.walk]) (:gen-class)) (defn- reverse-series "Reverse list of opcodes and change :?= to := or :==" [series] (:res (reduce (fn [acc [code & args]] (if (= code :?=) (if (contains? (:syms acc) (first args)) (assoc acc :res (cons `[:== ~@args] (:res acc))) (assoc acc, :res (cons `[:= ~@args] (:res acc)) :syms (conj (:syms acc) (first args)))) (assoc acc :res (cons `[~code ~@args] (:res acc))))) {:res nil, :syms #{}} series))) ;; opcode constructors (defn- guard-pred [f & args] `[:guard (~f ~@args)]) (defn- guard= [& ops] (apply guard-pred '= ops)) (defn- let?= [sym val] (assert (symbol? sym)) [:?= sym val]) (defn- let= [sym val] (assert (symbol? sym)) [:= sym val]) (def -match nil) (defmulti -match (fn [pat rsn] (type pat))) ;; scalar types (doseq [t [String Number Boolean nil clojure.lang.Keyword Character]] (defmethod -match t [pat rsn] [(guard= pat rsn)])) (def symbol-prefix-guards {"str" string? "sym" symbol? "kwd" keyword? "int" integer? "num" number? "flo" float? "cha" char? "vec" vector? "map" map? "set" set? "seq" seq? "coll" coll?}) ;; symbol (defmethod -match clojure.lang.Symbol [pat rsn] (cond (= '_ pat) , [] (= \? (-> pat str first)) , (let [g0 (if-let [t (-> pat meta :tag)] (guard-pred 'instance? t rsn)) g1 (if-let [g (-> pat meta :guard)] (guard-pred g rsn))] (if-let [ns (.getNamespace ^clojure.lang.Symbol pat)] (if-let [g2 (get symbol-prefix-guards (subs ns 1))] (if (= "_" (name pat)) [(guard-pred g2 rsn) g0 g1] [(guard-pred g2 rsn) g0 g1 (let?= (symbol (str "?" (name pat))) rsn)]) (->> ns (str "No guard for symbol prefix: ") (new IllegalArgumentException) (throw))) [g0 g1 (let?= pat rsn)])) :otherwise , [(guard= `'~pat rsn)])) ;; map (defmethod -match clojure.lang.IPersistentMap [pat rsn] (let [l2 (gensym "m")] (cons (guard-pred 'map? rsn) (mapcat (fn [[k v]] (list* (guard-pred 'contains? rsn k) (let= l2 `(get ~rsn ~k)) (-match v l2))) (seq pat))))) ;; lists. (defn handle-vec-itm [rsn l2 i k] (if-not (= k '_) (list* (let= l2 `(nth ~rsn ~i)) (-match k l2)))) (defn handle-vec [pat rsn] (let [l2 (gensym "v")] (if (= '& (last (butlast pat))) (do (assert (symbol? (last pat)) "Vararg name must be a symbol.") (conj (mapcat (partial handle-vec-itm rsn l2) (range), (-> pat butlast butlast)) (let?= (last pat) `(nthrest ~rsn ~(-> pat count dec dec))) (guard-pred '>= `(count ~rsn) (-> pat count dec dec)))) (conj (mapcat (partial handle-vec-itm rsn l2) (range), (seq pat)) (guard= `(count ~rsn) (count pat)))))) (defn handle-seq-itm [tmp seq-sym itm-sym p] (concat [(guard-pred 'seq seq-sym) (let= itm-sym `(first ~seq-sym))] (if (and (symbol? p) (-> p meta :when)) [(let= tmp `( ~(-> p meta :when) ~itm-sym)) (if (not= p '_) (let?= p `(if ~tmp ~itm-sym))) (let= seq-sym `(if ~tmp (next ~seq-sym) ~seq-sym))] (concat (-match p itm-sym) [(let= seq-sym `(next ~seq-sym))])))) (defn handle-seq "Creates code for sequential traversal." [pat rsn] (let [seq-sym (gensym "seq") ende? (= '& (last (butlast pat))) ps (mapcat (partial handle-seq-itm (gensym "tmp") seq-sym (gensym "itm")) (if ende? (butlast (butlast pat)) pat))] (list* (let= seq-sym `(seq ~rsn)) (if ende? (concat ps [(let?= (last pat) seq-sym)]) (concat ps [(guard-pred 'nil? seq-sym)]))))) (defmethod -match clojure.lang.ISeq [pat rsn] (cond (= (first pat) 'clojure.core/unquote) ,,,[(guard= (-> pat second eval) rsn)] (= (first pat) 'clojure.core/deref) ,,,[(guard= (second pat) rsn)] :else ,,,(list* (guard-pred 'seq? rsn) (handle-seq pat rsn)))) ;; vector (defmethod -match clojure.lang.IPersistentVector [pat rsn] (list* (guard-pred 'vector? rsn) (handle-vec pat rsn))) ;; (-match '(?a ?b ?c d) 'jano) (defn- make-series "Analyze pattern object and produce a list of opcodes." [pat root-sym] (letfn [] (-match pat root-sym))) ;; process generated op code. (defmulti ^:private opcode (fn [op & _] (first op))) (defmethod opcode := [[_ n v] & body] `(let [~n ~v] ~@body)) (defmethod opcode :== ([[_ n v] then] `(if (= ~n ~v) ~then)) ([[_ n v] then else] `(if (= ~n ~v) ~then ~else))) (defmethod opcode :guard ([[_ e] then] `(if ~e ~then)) ([[_ e] then else] `(if ~e ~then ~else))) (defmethod opcode nil ([_ then] then)) (defn- compile-series "Compile ser list of opcodes to clj code." [ser body] (reduce (fn [acc op] (opcode op acc)) body, (reverse-series ser))) (defn- merge-sexp "Join expressions by merging similiar outer if-else branches." [a b] (or (if (empty? a) b) (if (empty? b) a) (when (and (= 'if (first a) (first b)) (= (second a) (second b))) (assert (nil? (get a 3))) (assert (nil? (get b 3))) `(if ~(second a) ~(merge-sexp (nth a 2) (nth b 2)))) (when (= 'clojure.core/or (first a) (first b)) `(or ~@(concat (rest a) (rest b)))) (when (= 'clojure.core/or (first a)) `(or ~@(rest a) ~b)) (when (= 'clojure.core/or (first b)) `(or ~a ~@(rest b))) `(or ~a ~b))) (defn- match0-pattern "Returns the generated code for the clauses" [value & clauses] (assert (-> clauses count even?)) (let [vsym (gensym "MC") cls (partition 2 clauses) ;; [pattern action]* cls (map (fn [[p c]] [(make-series p vsym) c]) cls) ;; [pcode action]* cls (map (fn [[p c]] (compile-series p [c])) cls)] `(first (let [~vsym ~value] ~(reduce merge-sexp cls))))) (defmacro match0 [value & clauses] (apply match0-pattern value clauses)) (defn- simplify-sexp-item "Simplify a sexp, eg.: merge (if) forms, etc." [sexp] (match0 sexp (or & ?ops) `(or ~@(mapcat #(match0 %, (clojure.core/or & ?xs) ?xs, (or & ?xs) ?xs, ?x [?x]) ?ops)) (if (= ?a ?x1) ?a1 (if (= ?a ?x2) ?a2 ?a3)) `(case ~?a, ~?x1 ~?a1, ~?x2 ~?a2, ~?a3) (if (= ?a ?x1) ?a1 (clojure.core/case ?a & ?as)) `(case ~?a, ~?x1 ~?a1, ~@?as) (clojure.core/let [?k ?v] (clojure.core/let [& ?as] ?body)) `(let [~?k ~?v ~@?as] ~?body) ?else ?else)) (defn simplify-sexp "Recursively simplify sexp." [sexp] (clojure.walk/postwalk simplify-sexp-item sexp)) (defn match-pattern "Produce clj code for pattern matching" [expr & clauses] (simplify-sexp (apply match0-pattern expr clauses))) (defmacro match-pattern* "Macro form of match-pattern fn" [expr & clauses] `'~(apply match-pattern expr clauses)) (defmacro match "Use this macro for patterns matching." [expr & clauses] (apply match-pattern expr clauses)) (defmacro match! "Like (match) but throws an IllegalArgumentException when no pattern could be matched." [val & cases] `(match ~val ~@cases ?_else (-> "No pattern is matched" throw IllegalArgumentException.))) (defmacro defmatcher [name] `(def ~name (with-meta (constantly nil) {:doc "Automatically generated matcher fn." :matches ()}))) (defmacro addmatch [name clause & body] (let [body (if (next body) `(do ~@body) (first body))] `(let [m# (-> ~name meta :matches (conj '~body '~clause)) f# (list 'fn '[x#] (concat '(match x#) m#))] (alter-var-root (var ~name) (constantly (with-meta (eval f#) (assoc (meta ~name) :matches m#))))))) (defmacro matchfn "Returns a function for a given pattern." [& opts] (match opts (^{:when symbol?} ?name & ?opts) (do (assert (every? seq? ?opts) (str "not seq: " ?opts)) `(fn* [a#] (match a# ~@(mapcat (fn [[p & body]] [p `(do ~@body)]) ?opts))))))< (defmacro matchfn! "Like (matchfn) but throws an exception when pattern is not matched." [& opts] (let [err `(-> "No pattern could be matched in (matchfn!)" IllegalArgumentException. throw)] (match opts (^{:guard symbol?} ?name & ?opts) `(matchfn ~?name ~@?opts ?else# ~err) (& ?opts) `(matchfn ~@?opts ?else# ~err)))) :OK
94251
(ns ^{:author "<NAME>"} erdos.match "Small library for generating pattern matching code." (:require [clojure.walk]) (:gen-class)) (defn- reverse-series "Reverse list of opcodes and change :?= to := or :==" [series] (:res (reduce (fn [acc [code & args]] (if (= code :?=) (if (contains? (:syms acc) (first args)) (assoc acc :res (cons `[:== ~@args] (:res acc))) (assoc acc, :res (cons `[:= ~@args] (:res acc)) :syms (conj (:syms acc) (first args)))) (assoc acc :res (cons `[~code ~@args] (:res acc))))) {:res nil, :syms #{}} series))) ;; opcode constructors (defn- guard-pred [f & args] `[:guard (~f ~@args)]) (defn- guard= [& ops] (apply guard-pred '= ops)) (defn- let?= [sym val] (assert (symbol? sym)) [:?= sym val]) (defn- let= [sym val] (assert (symbol? sym)) [:= sym val]) (def -match nil) (defmulti -match (fn [pat rsn] (type pat))) ;; scalar types (doseq [t [String Number Boolean nil clojure.lang.Keyword Character]] (defmethod -match t [pat rsn] [(guard= pat rsn)])) (def symbol-prefix-guards {"str" string? "sym" symbol? "kwd" keyword? "int" integer? "num" number? "flo" float? "cha" char? "vec" vector? "map" map? "set" set? "seq" seq? "coll" coll?}) ;; symbol (defmethod -match clojure.lang.Symbol [pat rsn] (cond (= '_ pat) , [] (= \? (-> pat str first)) , (let [g0 (if-let [t (-> pat meta :tag)] (guard-pred 'instance? t rsn)) g1 (if-let [g (-> pat meta :guard)] (guard-pred g rsn))] (if-let [ns (.getNamespace ^clojure.lang.Symbol pat)] (if-let [g2 (get symbol-prefix-guards (subs ns 1))] (if (= "_" (name pat)) [(guard-pred g2 rsn) g0 g1] [(guard-pred g2 rsn) g0 g1 (let?= (symbol (str "?" (name pat))) rsn)]) (->> ns (str "No guard for symbol prefix: ") (new IllegalArgumentException) (throw))) [g0 g1 (let?= pat rsn)])) :otherwise , [(guard= `'~pat rsn)])) ;; map (defmethod -match clojure.lang.IPersistentMap [pat rsn] (let [l2 (gensym "m")] (cons (guard-pred 'map? rsn) (mapcat (fn [[k v]] (list* (guard-pred 'contains? rsn k) (let= l2 `(get ~rsn ~k)) (-match v l2))) (seq pat))))) ;; lists. (defn handle-vec-itm [rsn l2 i k] (if-not (= k '_) (list* (let= l2 `(nth ~rsn ~i)) (-match k l2)))) (defn handle-vec [pat rsn] (let [l2 (gensym "v")] (if (= '& (last (butlast pat))) (do (assert (symbol? (last pat)) "Vararg name must be a symbol.") (conj (mapcat (partial handle-vec-itm rsn l2) (range), (-> pat butlast butlast)) (let?= (last pat) `(nthrest ~rsn ~(-> pat count dec dec))) (guard-pred '>= `(count ~rsn) (-> pat count dec dec)))) (conj (mapcat (partial handle-vec-itm rsn l2) (range), (seq pat)) (guard= `(count ~rsn) (count pat)))))) (defn handle-seq-itm [tmp seq-sym itm-sym p] (concat [(guard-pred 'seq seq-sym) (let= itm-sym `(first ~seq-sym))] (if (and (symbol? p) (-> p meta :when)) [(let= tmp `( ~(-> p meta :when) ~itm-sym)) (if (not= p '_) (let?= p `(if ~tmp ~itm-sym))) (let= seq-sym `(if ~tmp (next ~seq-sym) ~seq-sym))] (concat (-match p itm-sym) [(let= seq-sym `(next ~seq-sym))])))) (defn handle-seq "Creates code for sequential traversal." [pat rsn] (let [seq-sym (gensym "seq") ende? (= '& (last (butlast pat))) ps (mapcat (partial handle-seq-itm (gensym "tmp") seq-sym (gensym "itm")) (if ende? (butlast (butlast pat)) pat))] (list* (let= seq-sym `(seq ~rsn)) (if ende? (concat ps [(let?= (last pat) seq-sym)]) (concat ps [(guard-pred 'nil? seq-sym)]))))) (defmethod -match clojure.lang.ISeq [pat rsn] (cond (= (first pat) 'clojure.core/unquote) ,,,[(guard= (-> pat second eval) rsn)] (= (first pat) 'clojure.core/deref) ,,,[(guard= (second pat) rsn)] :else ,,,(list* (guard-pred 'seq? rsn) (handle-seq pat rsn)))) ;; vector (defmethod -match clojure.lang.IPersistentVector [pat rsn] (list* (guard-pred 'vector? rsn) (handle-vec pat rsn))) ;; (-match '(?a ?b ?c d) 'jano) (defn- make-series "Analyze pattern object and produce a list of opcodes." [pat root-sym] (letfn [] (-match pat root-sym))) ;; process generated op code. (defmulti ^:private opcode (fn [op & _] (first op))) (defmethod opcode := [[_ n v] & body] `(let [~n ~v] ~@body)) (defmethod opcode :== ([[_ n v] then] `(if (= ~n ~v) ~then)) ([[_ n v] then else] `(if (= ~n ~v) ~then ~else))) (defmethod opcode :guard ([[_ e] then] `(if ~e ~then)) ([[_ e] then else] `(if ~e ~then ~else))) (defmethod opcode nil ([_ then] then)) (defn- compile-series "Compile ser list of opcodes to clj code." [ser body] (reduce (fn [acc op] (opcode op acc)) body, (reverse-series ser))) (defn- merge-sexp "Join expressions by merging similiar outer if-else branches." [a b] (or (if (empty? a) b) (if (empty? b) a) (when (and (= 'if (first a) (first b)) (= (second a) (second b))) (assert (nil? (get a 3))) (assert (nil? (get b 3))) `(if ~(second a) ~(merge-sexp (nth a 2) (nth b 2)))) (when (= 'clojure.core/or (first a) (first b)) `(or ~@(concat (rest a) (rest b)))) (when (= 'clojure.core/or (first a)) `(or ~@(rest a) ~b)) (when (= 'clojure.core/or (first b)) `(or ~a ~@(rest b))) `(or ~a ~b))) (defn- match0-pattern "Returns the generated code for the clauses" [value & clauses] (assert (-> clauses count even?)) (let [vsym (gensym "MC") cls (partition 2 clauses) ;; [pattern action]* cls (map (fn [[p c]] [(make-series p vsym) c]) cls) ;; [pcode action]* cls (map (fn [[p c]] (compile-series p [c])) cls)] `(first (let [~vsym ~value] ~(reduce merge-sexp cls))))) (defmacro match0 [value & clauses] (apply match0-pattern value clauses)) (defn- simplify-sexp-item "Simplify a sexp, eg.: merge (if) forms, etc." [sexp] (match0 sexp (or & ?ops) `(or ~@(mapcat #(match0 %, (clojure.core/or & ?xs) ?xs, (or & ?xs) ?xs, ?x [?x]) ?ops)) (if (= ?a ?x1) ?a1 (if (= ?a ?x2) ?a2 ?a3)) `(case ~?a, ~?x1 ~?a1, ~?x2 ~?a2, ~?a3) (if (= ?a ?x1) ?a1 (clojure.core/case ?a & ?as)) `(case ~?a, ~?x1 ~?a1, ~@?as) (clojure.core/let [?k ?v] (clojure.core/let [& ?as] ?body)) `(let [~?k ~?v ~@?as] ~?body) ?else ?else)) (defn simplify-sexp "Recursively simplify sexp." [sexp] (clojure.walk/postwalk simplify-sexp-item sexp)) (defn match-pattern "Produce clj code for pattern matching" [expr & clauses] (simplify-sexp (apply match0-pattern expr clauses))) (defmacro match-pattern* "Macro form of match-pattern fn" [expr & clauses] `'~(apply match-pattern expr clauses)) (defmacro match "Use this macro for patterns matching." [expr & clauses] (apply match-pattern expr clauses)) (defmacro match! "Like (match) but throws an IllegalArgumentException when no pattern could be matched." [val & cases] `(match ~val ~@cases ?_else (-> "No pattern is matched" throw IllegalArgumentException.))) (defmacro defmatcher [name] `(def ~name (with-meta (constantly nil) {:doc "Automatically generated matcher fn." :matches ()}))) (defmacro addmatch [name clause & body] (let [body (if (next body) `(do ~@body) (first body))] `(let [m# (-> ~name meta :matches (conj '~body '~clause)) f# (list 'fn '[x#] (concat '(match x#) m#))] (alter-var-root (var ~name) (constantly (with-meta (eval f#) (assoc (meta ~name) :matches m#))))))) (defmacro matchfn "Returns a function for a given pattern." [& opts] (match opts (^{:when symbol?} ?name & ?opts) (do (assert (every? seq? ?opts) (str "not seq: " ?opts)) `(fn* [a#] (match a# ~@(mapcat (fn [[p & body]] [p `(do ~@body)]) ?opts))))))< (defmacro matchfn! "Like (matchfn) but throws an exception when pattern is not matched." [& opts] (let [err `(-> "No pattern could be matched in (matchfn!)" IllegalArgumentException. throw)] (match opts (^{:guard symbol?} ?name & ?opts) `(matchfn ~?name ~@?opts ?else# ~err) (& ?opts) `(matchfn ~@?opts ?else# ~err)))) :OK
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} erdos.match "Small library for generating pattern matching code." (:require [clojure.walk]) (:gen-class)) (defn- reverse-series "Reverse list of opcodes and change :?= to := or :==" [series] (:res (reduce (fn [acc [code & args]] (if (= code :?=) (if (contains? (:syms acc) (first args)) (assoc acc :res (cons `[:== ~@args] (:res acc))) (assoc acc, :res (cons `[:= ~@args] (:res acc)) :syms (conj (:syms acc) (first args)))) (assoc acc :res (cons `[~code ~@args] (:res acc))))) {:res nil, :syms #{}} series))) ;; opcode constructors (defn- guard-pred [f & args] `[:guard (~f ~@args)]) (defn- guard= [& ops] (apply guard-pred '= ops)) (defn- let?= [sym val] (assert (symbol? sym)) [:?= sym val]) (defn- let= [sym val] (assert (symbol? sym)) [:= sym val]) (def -match nil) (defmulti -match (fn [pat rsn] (type pat))) ;; scalar types (doseq [t [String Number Boolean nil clojure.lang.Keyword Character]] (defmethod -match t [pat rsn] [(guard= pat rsn)])) (def symbol-prefix-guards {"str" string? "sym" symbol? "kwd" keyword? "int" integer? "num" number? "flo" float? "cha" char? "vec" vector? "map" map? "set" set? "seq" seq? "coll" coll?}) ;; symbol (defmethod -match clojure.lang.Symbol [pat rsn] (cond (= '_ pat) , [] (= \? (-> pat str first)) , (let [g0 (if-let [t (-> pat meta :tag)] (guard-pred 'instance? t rsn)) g1 (if-let [g (-> pat meta :guard)] (guard-pred g rsn))] (if-let [ns (.getNamespace ^clojure.lang.Symbol pat)] (if-let [g2 (get symbol-prefix-guards (subs ns 1))] (if (= "_" (name pat)) [(guard-pred g2 rsn) g0 g1] [(guard-pred g2 rsn) g0 g1 (let?= (symbol (str "?" (name pat))) rsn)]) (->> ns (str "No guard for symbol prefix: ") (new IllegalArgumentException) (throw))) [g0 g1 (let?= pat rsn)])) :otherwise , [(guard= `'~pat rsn)])) ;; map (defmethod -match clojure.lang.IPersistentMap [pat rsn] (let [l2 (gensym "m")] (cons (guard-pred 'map? rsn) (mapcat (fn [[k v]] (list* (guard-pred 'contains? rsn k) (let= l2 `(get ~rsn ~k)) (-match v l2))) (seq pat))))) ;; lists. (defn handle-vec-itm [rsn l2 i k] (if-not (= k '_) (list* (let= l2 `(nth ~rsn ~i)) (-match k l2)))) (defn handle-vec [pat rsn] (let [l2 (gensym "v")] (if (= '& (last (butlast pat))) (do (assert (symbol? (last pat)) "Vararg name must be a symbol.") (conj (mapcat (partial handle-vec-itm rsn l2) (range), (-> pat butlast butlast)) (let?= (last pat) `(nthrest ~rsn ~(-> pat count dec dec))) (guard-pred '>= `(count ~rsn) (-> pat count dec dec)))) (conj (mapcat (partial handle-vec-itm rsn l2) (range), (seq pat)) (guard= `(count ~rsn) (count pat)))))) (defn handle-seq-itm [tmp seq-sym itm-sym p] (concat [(guard-pred 'seq seq-sym) (let= itm-sym `(first ~seq-sym))] (if (and (symbol? p) (-> p meta :when)) [(let= tmp `( ~(-> p meta :when) ~itm-sym)) (if (not= p '_) (let?= p `(if ~tmp ~itm-sym))) (let= seq-sym `(if ~tmp (next ~seq-sym) ~seq-sym))] (concat (-match p itm-sym) [(let= seq-sym `(next ~seq-sym))])))) (defn handle-seq "Creates code for sequential traversal." [pat rsn] (let [seq-sym (gensym "seq") ende? (= '& (last (butlast pat))) ps (mapcat (partial handle-seq-itm (gensym "tmp") seq-sym (gensym "itm")) (if ende? (butlast (butlast pat)) pat))] (list* (let= seq-sym `(seq ~rsn)) (if ende? (concat ps [(let?= (last pat) seq-sym)]) (concat ps [(guard-pred 'nil? seq-sym)]))))) (defmethod -match clojure.lang.ISeq [pat rsn] (cond (= (first pat) 'clojure.core/unquote) ,,,[(guard= (-> pat second eval) rsn)] (= (first pat) 'clojure.core/deref) ,,,[(guard= (second pat) rsn)] :else ,,,(list* (guard-pred 'seq? rsn) (handle-seq pat rsn)))) ;; vector (defmethod -match clojure.lang.IPersistentVector [pat rsn] (list* (guard-pred 'vector? rsn) (handle-vec pat rsn))) ;; (-match '(?a ?b ?c d) 'jano) (defn- make-series "Analyze pattern object and produce a list of opcodes." [pat root-sym] (letfn [] (-match pat root-sym))) ;; process generated op code. (defmulti ^:private opcode (fn [op & _] (first op))) (defmethod opcode := [[_ n v] & body] `(let [~n ~v] ~@body)) (defmethod opcode :== ([[_ n v] then] `(if (= ~n ~v) ~then)) ([[_ n v] then else] `(if (= ~n ~v) ~then ~else))) (defmethod opcode :guard ([[_ e] then] `(if ~e ~then)) ([[_ e] then else] `(if ~e ~then ~else))) (defmethod opcode nil ([_ then] then)) (defn- compile-series "Compile ser list of opcodes to clj code." [ser body] (reduce (fn [acc op] (opcode op acc)) body, (reverse-series ser))) (defn- merge-sexp "Join expressions by merging similiar outer if-else branches." [a b] (or (if (empty? a) b) (if (empty? b) a) (when (and (= 'if (first a) (first b)) (= (second a) (second b))) (assert (nil? (get a 3))) (assert (nil? (get b 3))) `(if ~(second a) ~(merge-sexp (nth a 2) (nth b 2)))) (when (= 'clojure.core/or (first a) (first b)) `(or ~@(concat (rest a) (rest b)))) (when (= 'clojure.core/or (first a)) `(or ~@(rest a) ~b)) (when (= 'clojure.core/or (first b)) `(or ~a ~@(rest b))) `(or ~a ~b))) (defn- match0-pattern "Returns the generated code for the clauses" [value & clauses] (assert (-> clauses count even?)) (let [vsym (gensym "MC") cls (partition 2 clauses) ;; [pattern action]* cls (map (fn [[p c]] [(make-series p vsym) c]) cls) ;; [pcode action]* cls (map (fn [[p c]] (compile-series p [c])) cls)] `(first (let [~vsym ~value] ~(reduce merge-sexp cls))))) (defmacro match0 [value & clauses] (apply match0-pattern value clauses)) (defn- simplify-sexp-item "Simplify a sexp, eg.: merge (if) forms, etc." [sexp] (match0 sexp (or & ?ops) `(or ~@(mapcat #(match0 %, (clojure.core/or & ?xs) ?xs, (or & ?xs) ?xs, ?x [?x]) ?ops)) (if (= ?a ?x1) ?a1 (if (= ?a ?x2) ?a2 ?a3)) `(case ~?a, ~?x1 ~?a1, ~?x2 ~?a2, ~?a3) (if (= ?a ?x1) ?a1 (clojure.core/case ?a & ?as)) `(case ~?a, ~?x1 ~?a1, ~@?as) (clojure.core/let [?k ?v] (clojure.core/let [& ?as] ?body)) `(let [~?k ~?v ~@?as] ~?body) ?else ?else)) (defn simplify-sexp "Recursively simplify sexp." [sexp] (clojure.walk/postwalk simplify-sexp-item sexp)) (defn match-pattern "Produce clj code for pattern matching" [expr & clauses] (simplify-sexp (apply match0-pattern expr clauses))) (defmacro match-pattern* "Macro form of match-pattern fn" [expr & clauses] `'~(apply match-pattern expr clauses)) (defmacro match "Use this macro for patterns matching." [expr & clauses] (apply match-pattern expr clauses)) (defmacro match! "Like (match) but throws an IllegalArgumentException when no pattern could be matched." [val & cases] `(match ~val ~@cases ?_else (-> "No pattern is matched" throw IllegalArgumentException.))) (defmacro defmatcher [name] `(def ~name (with-meta (constantly nil) {:doc "Automatically generated matcher fn." :matches ()}))) (defmacro addmatch [name clause & body] (let [body (if (next body) `(do ~@body) (first body))] `(let [m# (-> ~name meta :matches (conj '~body '~clause)) f# (list 'fn '[x#] (concat '(match x#) m#))] (alter-var-root (var ~name) (constantly (with-meta (eval f#) (assoc (meta ~name) :matches m#))))))) (defmacro matchfn "Returns a function for a given pattern." [& opts] (match opts (^{:when symbol?} ?name & ?opts) (do (assert (every? seq? ?opts) (str "not seq: " ?opts)) `(fn* [a#] (match a# ~@(mapcat (fn [[p & body]] [p `(do ~@body)]) ?opts))))))< (defmacro matchfn! "Like (matchfn) but throws an exception when pattern is not matched." [& opts] (let [err `(-> "No pattern could be matched in (matchfn!)" IllegalArgumentException. throw)] (match opts (^{:guard symbol?} ?name & ?opts) `(matchfn ~?name ~@?opts ?else# ~err) (& ?opts) `(matchfn ~@?opts ?else# ~err)))) :OK
[ { "context": "(ns ^{:doc \"Search button.\"\n :author \"Eric Weinstein <eric.q.weinstein@gmail.com>\"}\n cityshelf.compon", "end": 57, "score": 0.9998879432678223, "start": 43, "tag": "NAME", "value": "Eric Weinstein" }, { "context": "c \"Search button.\"\n :author \"Eric Weinstein <eric.q.weinstein@gmail.com>\"}\n cityshelf.components.search-button\n (:requi", "end": 85, "score": 0.999926745891571, "start": 59, "tag": "EMAIL", "value": "eric.q.weinstein@gmail.com" } ]
src/cityshelf/components/search_button.cljs
ericqweinstein/cityshelf
0
(ns ^{:doc "Search button." :author "Eric Weinstein <eric.q.weinstein@gmail.com>"} cityshelf.components.search-button (:require [cityshelf.session :as session])) (declare switch-class) (defn search-button "Creates a search button." [query] [:button {:on-click query :class "cs-search-btn activated"} [:i {:class (switch-class)}]]) (defn- switch-class "Triggers the spinner when searching." [] (if (session/get! :searching) "fa fa-circle-o-notch fa-spin fa-lg" "fa fa-search fa-lg"))
60807
(ns ^{:doc "Search button." :author "<NAME> <<EMAIL>>"} cityshelf.components.search-button (:require [cityshelf.session :as session])) (declare switch-class) (defn search-button "Creates a search button." [query] [:button {:on-click query :class "cs-search-btn activated"} [:i {:class (switch-class)}]]) (defn- switch-class "Triggers the spinner when searching." [] (if (session/get! :searching) "fa fa-circle-o-notch fa-spin fa-lg" "fa fa-search fa-lg"))
true
(ns ^{:doc "Search button." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"} cityshelf.components.search-button (:require [cityshelf.session :as session])) (declare switch-class) (defn search-button "Creates a search button." [query] [:button {:on-click query :class "cs-search-btn activated"} [:i {:class (switch-class)}]]) (defn- switch-class "Triggers the spinner when searching." [] (if (session/get! :searching) "fa fa-circle-o-notch fa-spin fa-lg" "fa fa-search fa-lg"))
[ { "context": "ard representation as an integer, based on Kevin Suffecool's specs:\n\n +--------+--------+--------+--", "end": 866, "score": 0.5216154456138611, "start": 863, "tag": "NAME", "value": "uff" } ]
src/poker_hand_evaluator/core.clj
tomasmacia/tp-clojure-tdl
1
(ns poker-hand-evaluator.core (:use [poker-hand-evaluator.lookup-tables]) (:use [clojure.math.combinatorics]) (:use [clojure.set])) (def suit-details "Available suits and the respective bit pattern to be used in the card format" {"♠" 0x1000, "♥" 0x2000, "♦" 0x4000, "♣" 0x8000}) (def face-details "Available face values, including their assigned prime and their rank to be used in the card format" {"2" {:prime 2, :index 0} "3" {:prime 3, :index 1} "4" {:prime 5, :index 2} "5" {:prime 7, :index 3} "6" {:prime 11, :index 4} "7" {:prime 13, :index 5} "8" {:prime 17, :index 6} "9" {:prime 19, :index 7} "T" {:prime 23, :index 8} "J" {:prime 29, :index 9} "Q" {:prime 31, :index 10} "K" {:prime 37, :index 11} "A" {:prime 41, :index 12}}) (defn- card-value "Card representation as an integer, based on Kevin Suffecool's specs: +--------+--------+--------+--------+ |xxxbbbbb|bbbbbbbb|cdhsrrrr|xxpppppp| +--------+--------+--------+--------+ p = prime number of rank (deuce=2,trey=3,four=5,five=7,...,ace=41) r = rank of card (deuce=0,trey=1,four=2,five=3,...,ace=12) cdhs = suit of card b = bit turned on depending on rank of card" [face suit] (let [details (face-details face) prime (details :prime) face-value (details :index) suit-value (suit-details suit)] (bit-or prime (bit-shift-left face-value 8) suit-value (bit-shift-left 1 (+ 16 face-value))) ) ) (defn- generate-deck "creates map: card name -> card value" [] (let [deck {}] (into {} (for [face (keys face-details) suit (keys suit-details)] [(str face suit) (card-value face suit)])) ) ) (def deck "The default deck to be used by the evaluator" (generate-deck)) (defn- calculate-hand-index "The hand index is calculated using: (c1 OR c2 OR c3 OR c4 OR c5) >> 16 This value can be used later to find values in lookup tables." [cards] (bit-shift-right (apply bit-or cards) 16) ) (defn- flush-hand "The following expression is used to check if the hand is a flush: c1 AND c2 AND c3 AND c4 AND c5 AND 0xF000 If the expression returns a non-zero value, then we have a flush and can use the lookup table for flushes to resolve the hand rank." [hand-index card-values] (and (not= (bit-and (apply bit-and card-values) 0xF000) 0) (flush-to-rank hand-index) )) (defn- unique-card-hand "Straights or High Card hands are resolved using a specific lookup table to resolve hand with 5 unique cards. This lookup will return a hand rank only for straights and high cards (0 for any other hand)." [hand-index] (let [hand-rank (unique5-to-rank hand-index)] (and (not= hand-rank 0) hand-rank) ) ) (defn- other-hands "Other hands are all non-flush and non-unique5. We first calculate the prime product of all cards: q = (c1 AND 0xFF) * (c2 AND 0xFF) * ... * (c5 AND 0xFF) Because the range of q is huge (48-100M+), we use 2 lookup tables: we search the index of q on the first and then use this index on the second to find the actual hand rank." [card-values] (let [q (reduce * (map #(bit-and % 0xFF) card-values)) q-index (java.util.Collections/binarySearch prime-product-to-combination q)] (or (combination-to-rank q-index) false) )) (defn- calculate-hand-rank "Uses the following strategies to find the hand rank, in order: 1. bit masking + lookup table for flush hands 2. bit masking + lookup table for hands with 5 unique cards 3. prime multiplying + 2 lookup tables for the remaining hands " [hand] (let [card-values (map deck hand) hand-index (calculate-hand-index card-values)] (or (flush-hand hand-index, card-values) (unique-card-hand hand-index) (other-hands card-values) ) ) ) (def ranks "Poker ranks and their respective maximum rank" {7462 :HighCard 6185 :OnePair 3325 :TwoPairs 2467 :ThreeOfAKind 1609 :Straight 1599 :Flush 322 :FullHouse 166 :FourOfAKind 10 :StraightFlush}) (defn- resolve-rank-name "Resolves the name of a given rank" [hand-rank] (ranks (+ hand-rank (first (filter #(>= % 0) (sort (map #(- % hand-rank) (keys ranks))))))) ) (defn- evaluate-hand "Evaluates a 5-card poker hand, returning a map including its name and rank" [& hand] (let [hand-rank (calculate-hand-rank hand) rank-name (resolve-rank-name hand-rank)] {:cards hand :rank hand-rank :hand rank-name}) ) (defn- highest-rank "Finds the highest rank for a list of evaluated hands" [evaluated-hands] (first (sort #(< (%1 :rank) (%2 :rank)) evaluated-hands)) ) (defn- evaluate-all-combinations "Evaluates all possible 5-card combinations for a hand" [hand] (map #(apply evaluate-hand %) (combinations hand 5)) ) ;; (def replacements ;; {#"S" "♠" ;; #"H" "♥" ;; #"D" "♦" ;; #"C" "♣" ;; }) (defn- replace-symbols "Replace different symbols" ;; TODO: revisar [hand-rank] (clojure.string/replace (clojure.string/replace (clojure.string/replace (clojure.string/replace hand-rank "S" "♠") "D" "♦") "C" "♣") "H" "♥") ) (defn- normalize-symbols "Transform symbols into common symbols" [hand] (map replace-symbols (map clojure.string/upper-case hand)) ) (defn evaluate "Evaluates a poker hand. If it contains more than 5 cards, it returns the best hand possible" [& hand] (highest-rank (evaluate-all-combinations (normalize-symbols hand))) ) ;Con threading-macros (defn- replace-symbols* [hand-rank] (-> hand-rank (clojure.string/replace "S" "♠") (clojure.string/replace "D" "♦") (clojure.string/replace "C" "♣") (clojure.string/replace "H" "♥")) ) (defn- highest-rank* [evaluated-hands] (->> evaluated-hands (sort #(< (%1 :rank) (%2 :rank))) first) ) (defn- normalize-symbols* [hand] (map replace-symbols* (map clojure.string/upper-case hand)) ) (defn evaluate* "Evaluates a poker hand. If it contains more than 5 cards, it returns the best hand possible" [& hand] (highest-rank* (evaluate-all-combinations (normalize-symbols* hand))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Hasta aca el proyecto existente, nuevas funcionalidades abajo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn evaluate-all "Evalua una lista de manos de 5 o mas cartas" [& hands] ) (defn sort-hand-draw "Devuelve las manos en orden (mejor - peor)" [cards] ;; (first (sort-by :rank (map #(apply evaluate %) '(("Th" "Jh" "Qh" "Kh" "9h") ("Tc" "Jc" "Qc" "Kc" "Ac"))))) (sort-by :rank (map #(apply evaluate %) cards)) ) (defn best-hand-draw "Devuelve la mejor mano que contenga las cartas provistas" [cards] ;; (first (sort-by :rank (map #(apply evaluate %) '(("Th" "Jh" "Qh" "Kh" "9h") ("Tc" "Jc" "Qc" "Kc" "Ac"))))) (first (sort-hand-draw cards)) ) (defn complete-best-hand "Devuelve la mejor mano posible con las cartas pasadas como parámetro" [& uncompleted-hand] (let [result (future (let [norm-uncompleted-hand (normalize-symbols uncompleted-hand) mazo (keys deck)] (Thread/sleep 5000) (best-hand-draw (filter #(= (count (set %)) 5) (map #(conj norm-uncompleted-hand %) mazo))) ))] (if (not (realized? result)) (println "Procesando resultado...") (println "Ya terminó.")) @result) ) (defmulti complete-best-hand-multi (fn [& uncompleted-hand] [(let [result (count uncompleted-hand)] result)])) (defmethod complete-best-hand-multi [1] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [2] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [3] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [4] [& uncompleted-hand] (let [norm-uncompleted-hand (normalize-symbols uncompleted-hand) mazo (keys deck)] (best-hand-draw (filter #(= (count (set %)) 5) (map #(conj norm-uncompleted-hand %) mazo))) ) ) (defmethod complete-best-hand-multi :default [& uncompleted-hand] "Para completar la mano deben pasarse 4 cartas") (defn random-cards "Devuelve una secuencia de n cartas aleatorias sin repetir" [n cards] (take n (shuffle cards))) (def mazo (keys deck)) (defn random-game "Devuelve la mano posible con las n cartas aleatorias pasadas" [n cards] (apply evaluate (random-cards n cards))) (defn texas-game "Devuelve la mejor mano posible con las cartas aleatorias pasadas" [cards] (let [x (random-cards 7 cards) y (partition-all 5 x) mesa (first y) jugador (second y)] (println "Mesa:" mesa) (println "Jugador:" jugador) (apply evaluate x)) ) (defmacro texas-game* [cards] `(let [x# (random-cards 7 ~cards) y# (partition-all 5 x#) mesa# (first y#) jugador# (second y#)] (println "Mesa:" mesa#) (println "Jugador:" jugador#) (apply evaluate x#)) ) (def mazo-ref (ref (shuffle mazo))) (defn main "Simula un juego" [] (def hand-ref (ref #{})) (dosync (alter hand-ref (fn [hand] (set (take 5 @mazo-ref)))) (alter mazo-ref (fn [mazo] (let [cards @hand-ref] (filter #(not (contains? cards %)) mazo))) )) (println "Your cards:" (deref hand-ref)) (println (apply evaluate (deref hand-ref))) (println "\nDraw phase. Enter your cards to discard (empty if none):") (let [c (filter #(not (empty? %)) (clojure.string/split (read-line) #" "))] (println "\nChanging:" c) (dosync (alter hand-ref (fn [hand] (filter #(not (contains? (set c) %)) (union hand (set (take (count c) @mazo-ref)))))) (alter mazo-ref (fn [m] (shuffle mazo) ))) ) (println "\n\nShowdown:" (deref hand-ref)) (println (apply evaluate (deref hand-ref))) )
88798
(ns poker-hand-evaluator.core (:use [poker-hand-evaluator.lookup-tables]) (:use [clojure.math.combinatorics]) (:use [clojure.set])) (def suit-details "Available suits and the respective bit pattern to be used in the card format" {"♠" 0x1000, "♥" 0x2000, "♦" 0x4000, "♣" 0x8000}) (def face-details "Available face values, including their assigned prime and their rank to be used in the card format" {"2" {:prime 2, :index 0} "3" {:prime 3, :index 1} "4" {:prime 5, :index 2} "5" {:prime 7, :index 3} "6" {:prime 11, :index 4} "7" {:prime 13, :index 5} "8" {:prime 17, :index 6} "9" {:prime 19, :index 7} "T" {:prime 23, :index 8} "J" {:prime 29, :index 9} "Q" {:prime 31, :index 10} "K" {:prime 37, :index 11} "A" {:prime 41, :index 12}}) (defn- card-value "Card representation as an integer, based on Kevin S<NAME>ecool's specs: +--------+--------+--------+--------+ |xxxbbbbb|bbbbbbbb|cdhsrrrr|xxpppppp| +--------+--------+--------+--------+ p = prime number of rank (deuce=2,trey=3,four=5,five=7,...,ace=41) r = rank of card (deuce=0,trey=1,four=2,five=3,...,ace=12) cdhs = suit of card b = bit turned on depending on rank of card" [face suit] (let [details (face-details face) prime (details :prime) face-value (details :index) suit-value (suit-details suit)] (bit-or prime (bit-shift-left face-value 8) suit-value (bit-shift-left 1 (+ 16 face-value))) ) ) (defn- generate-deck "creates map: card name -> card value" [] (let [deck {}] (into {} (for [face (keys face-details) suit (keys suit-details)] [(str face suit) (card-value face suit)])) ) ) (def deck "The default deck to be used by the evaluator" (generate-deck)) (defn- calculate-hand-index "The hand index is calculated using: (c1 OR c2 OR c3 OR c4 OR c5) >> 16 This value can be used later to find values in lookup tables." [cards] (bit-shift-right (apply bit-or cards) 16) ) (defn- flush-hand "The following expression is used to check if the hand is a flush: c1 AND c2 AND c3 AND c4 AND c5 AND 0xF000 If the expression returns a non-zero value, then we have a flush and can use the lookup table for flushes to resolve the hand rank." [hand-index card-values] (and (not= (bit-and (apply bit-and card-values) 0xF000) 0) (flush-to-rank hand-index) )) (defn- unique-card-hand "Straights or High Card hands are resolved using a specific lookup table to resolve hand with 5 unique cards. This lookup will return a hand rank only for straights and high cards (0 for any other hand)." [hand-index] (let [hand-rank (unique5-to-rank hand-index)] (and (not= hand-rank 0) hand-rank) ) ) (defn- other-hands "Other hands are all non-flush and non-unique5. We first calculate the prime product of all cards: q = (c1 AND 0xFF) * (c2 AND 0xFF) * ... * (c5 AND 0xFF) Because the range of q is huge (48-100M+), we use 2 lookup tables: we search the index of q on the first and then use this index on the second to find the actual hand rank." [card-values] (let [q (reduce * (map #(bit-and % 0xFF) card-values)) q-index (java.util.Collections/binarySearch prime-product-to-combination q)] (or (combination-to-rank q-index) false) )) (defn- calculate-hand-rank "Uses the following strategies to find the hand rank, in order: 1. bit masking + lookup table for flush hands 2. bit masking + lookup table for hands with 5 unique cards 3. prime multiplying + 2 lookup tables for the remaining hands " [hand] (let [card-values (map deck hand) hand-index (calculate-hand-index card-values)] (or (flush-hand hand-index, card-values) (unique-card-hand hand-index) (other-hands card-values) ) ) ) (def ranks "Poker ranks and their respective maximum rank" {7462 :HighCard 6185 :OnePair 3325 :TwoPairs 2467 :ThreeOfAKind 1609 :Straight 1599 :Flush 322 :FullHouse 166 :FourOfAKind 10 :StraightFlush}) (defn- resolve-rank-name "Resolves the name of a given rank" [hand-rank] (ranks (+ hand-rank (first (filter #(>= % 0) (sort (map #(- % hand-rank) (keys ranks))))))) ) (defn- evaluate-hand "Evaluates a 5-card poker hand, returning a map including its name and rank" [& hand] (let [hand-rank (calculate-hand-rank hand) rank-name (resolve-rank-name hand-rank)] {:cards hand :rank hand-rank :hand rank-name}) ) (defn- highest-rank "Finds the highest rank for a list of evaluated hands" [evaluated-hands] (first (sort #(< (%1 :rank) (%2 :rank)) evaluated-hands)) ) (defn- evaluate-all-combinations "Evaluates all possible 5-card combinations for a hand" [hand] (map #(apply evaluate-hand %) (combinations hand 5)) ) ;; (def replacements ;; {#"S" "♠" ;; #"H" "♥" ;; #"D" "♦" ;; #"C" "♣" ;; }) (defn- replace-symbols "Replace different symbols" ;; TODO: revisar [hand-rank] (clojure.string/replace (clojure.string/replace (clojure.string/replace (clojure.string/replace hand-rank "S" "♠") "D" "♦") "C" "♣") "H" "♥") ) (defn- normalize-symbols "Transform symbols into common symbols" [hand] (map replace-symbols (map clojure.string/upper-case hand)) ) (defn evaluate "Evaluates a poker hand. If it contains more than 5 cards, it returns the best hand possible" [& hand] (highest-rank (evaluate-all-combinations (normalize-symbols hand))) ) ;Con threading-macros (defn- replace-symbols* [hand-rank] (-> hand-rank (clojure.string/replace "S" "♠") (clojure.string/replace "D" "♦") (clojure.string/replace "C" "♣") (clojure.string/replace "H" "♥")) ) (defn- highest-rank* [evaluated-hands] (->> evaluated-hands (sort #(< (%1 :rank) (%2 :rank))) first) ) (defn- normalize-symbols* [hand] (map replace-symbols* (map clojure.string/upper-case hand)) ) (defn evaluate* "Evaluates a poker hand. If it contains more than 5 cards, it returns the best hand possible" [& hand] (highest-rank* (evaluate-all-combinations (normalize-symbols* hand))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Hasta aca el proyecto existente, nuevas funcionalidades abajo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn evaluate-all "Evalua una lista de manos de 5 o mas cartas" [& hands] ) (defn sort-hand-draw "Devuelve las manos en orden (mejor - peor)" [cards] ;; (first (sort-by :rank (map #(apply evaluate %) '(("Th" "Jh" "Qh" "Kh" "9h") ("Tc" "Jc" "Qc" "Kc" "Ac"))))) (sort-by :rank (map #(apply evaluate %) cards)) ) (defn best-hand-draw "Devuelve la mejor mano que contenga las cartas provistas" [cards] ;; (first (sort-by :rank (map #(apply evaluate %) '(("Th" "Jh" "Qh" "Kh" "9h") ("Tc" "Jc" "Qc" "Kc" "Ac"))))) (first (sort-hand-draw cards)) ) (defn complete-best-hand "Devuelve la mejor mano posible con las cartas pasadas como parámetro" [& uncompleted-hand] (let [result (future (let [norm-uncompleted-hand (normalize-symbols uncompleted-hand) mazo (keys deck)] (Thread/sleep 5000) (best-hand-draw (filter #(= (count (set %)) 5) (map #(conj norm-uncompleted-hand %) mazo))) ))] (if (not (realized? result)) (println "Procesando resultado...") (println "Ya terminó.")) @result) ) (defmulti complete-best-hand-multi (fn [& uncompleted-hand] [(let [result (count uncompleted-hand)] result)])) (defmethod complete-best-hand-multi [1] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [2] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [3] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [4] [& uncompleted-hand] (let [norm-uncompleted-hand (normalize-symbols uncompleted-hand) mazo (keys deck)] (best-hand-draw (filter #(= (count (set %)) 5) (map #(conj norm-uncompleted-hand %) mazo))) ) ) (defmethod complete-best-hand-multi :default [& uncompleted-hand] "Para completar la mano deben pasarse 4 cartas") (defn random-cards "Devuelve una secuencia de n cartas aleatorias sin repetir" [n cards] (take n (shuffle cards))) (def mazo (keys deck)) (defn random-game "Devuelve la mano posible con las n cartas aleatorias pasadas" [n cards] (apply evaluate (random-cards n cards))) (defn texas-game "Devuelve la mejor mano posible con las cartas aleatorias pasadas" [cards] (let [x (random-cards 7 cards) y (partition-all 5 x) mesa (first y) jugador (second y)] (println "Mesa:" mesa) (println "Jugador:" jugador) (apply evaluate x)) ) (defmacro texas-game* [cards] `(let [x# (random-cards 7 ~cards) y# (partition-all 5 x#) mesa# (first y#) jugador# (second y#)] (println "Mesa:" mesa#) (println "Jugador:" jugador#) (apply evaluate x#)) ) (def mazo-ref (ref (shuffle mazo))) (defn main "Simula un juego" [] (def hand-ref (ref #{})) (dosync (alter hand-ref (fn [hand] (set (take 5 @mazo-ref)))) (alter mazo-ref (fn [mazo] (let [cards @hand-ref] (filter #(not (contains? cards %)) mazo))) )) (println "Your cards:" (deref hand-ref)) (println (apply evaluate (deref hand-ref))) (println "\nDraw phase. Enter your cards to discard (empty if none):") (let [c (filter #(not (empty? %)) (clojure.string/split (read-line) #" "))] (println "\nChanging:" c) (dosync (alter hand-ref (fn [hand] (filter #(not (contains? (set c) %)) (union hand (set (take (count c) @mazo-ref)))))) (alter mazo-ref (fn [m] (shuffle mazo) ))) ) (println "\n\nShowdown:" (deref hand-ref)) (println (apply evaluate (deref hand-ref))) )
true
(ns poker-hand-evaluator.core (:use [poker-hand-evaluator.lookup-tables]) (:use [clojure.math.combinatorics]) (:use [clojure.set])) (def suit-details "Available suits and the respective bit pattern to be used in the card format" {"♠" 0x1000, "♥" 0x2000, "♦" 0x4000, "♣" 0x8000}) (def face-details "Available face values, including their assigned prime and their rank to be used in the card format" {"2" {:prime 2, :index 0} "3" {:prime 3, :index 1} "4" {:prime 5, :index 2} "5" {:prime 7, :index 3} "6" {:prime 11, :index 4} "7" {:prime 13, :index 5} "8" {:prime 17, :index 6} "9" {:prime 19, :index 7} "T" {:prime 23, :index 8} "J" {:prime 29, :index 9} "Q" {:prime 31, :index 10} "K" {:prime 37, :index 11} "A" {:prime 41, :index 12}}) (defn- card-value "Card representation as an integer, based on Kevin SPI:NAME:<NAME>END_PIecool's specs: +--------+--------+--------+--------+ |xxxbbbbb|bbbbbbbb|cdhsrrrr|xxpppppp| +--------+--------+--------+--------+ p = prime number of rank (deuce=2,trey=3,four=5,five=7,...,ace=41) r = rank of card (deuce=0,trey=1,four=2,five=3,...,ace=12) cdhs = suit of card b = bit turned on depending on rank of card" [face suit] (let [details (face-details face) prime (details :prime) face-value (details :index) suit-value (suit-details suit)] (bit-or prime (bit-shift-left face-value 8) suit-value (bit-shift-left 1 (+ 16 face-value))) ) ) (defn- generate-deck "creates map: card name -> card value" [] (let [deck {}] (into {} (for [face (keys face-details) suit (keys suit-details)] [(str face suit) (card-value face suit)])) ) ) (def deck "The default deck to be used by the evaluator" (generate-deck)) (defn- calculate-hand-index "The hand index is calculated using: (c1 OR c2 OR c3 OR c4 OR c5) >> 16 This value can be used later to find values in lookup tables." [cards] (bit-shift-right (apply bit-or cards) 16) ) (defn- flush-hand "The following expression is used to check if the hand is a flush: c1 AND c2 AND c3 AND c4 AND c5 AND 0xF000 If the expression returns a non-zero value, then we have a flush and can use the lookup table for flushes to resolve the hand rank." [hand-index card-values] (and (not= (bit-and (apply bit-and card-values) 0xF000) 0) (flush-to-rank hand-index) )) (defn- unique-card-hand "Straights or High Card hands are resolved using a specific lookup table to resolve hand with 5 unique cards. This lookup will return a hand rank only for straights and high cards (0 for any other hand)." [hand-index] (let [hand-rank (unique5-to-rank hand-index)] (and (not= hand-rank 0) hand-rank) ) ) (defn- other-hands "Other hands are all non-flush and non-unique5. We first calculate the prime product of all cards: q = (c1 AND 0xFF) * (c2 AND 0xFF) * ... * (c5 AND 0xFF) Because the range of q is huge (48-100M+), we use 2 lookup tables: we search the index of q on the first and then use this index on the second to find the actual hand rank." [card-values] (let [q (reduce * (map #(bit-and % 0xFF) card-values)) q-index (java.util.Collections/binarySearch prime-product-to-combination q)] (or (combination-to-rank q-index) false) )) (defn- calculate-hand-rank "Uses the following strategies to find the hand rank, in order: 1. bit masking + lookup table for flush hands 2. bit masking + lookup table for hands with 5 unique cards 3. prime multiplying + 2 lookup tables for the remaining hands " [hand] (let [card-values (map deck hand) hand-index (calculate-hand-index card-values)] (or (flush-hand hand-index, card-values) (unique-card-hand hand-index) (other-hands card-values) ) ) ) (def ranks "Poker ranks and their respective maximum rank" {7462 :HighCard 6185 :OnePair 3325 :TwoPairs 2467 :ThreeOfAKind 1609 :Straight 1599 :Flush 322 :FullHouse 166 :FourOfAKind 10 :StraightFlush}) (defn- resolve-rank-name "Resolves the name of a given rank" [hand-rank] (ranks (+ hand-rank (first (filter #(>= % 0) (sort (map #(- % hand-rank) (keys ranks))))))) ) (defn- evaluate-hand "Evaluates a 5-card poker hand, returning a map including its name and rank" [& hand] (let [hand-rank (calculate-hand-rank hand) rank-name (resolve-rank-name hand-rank)] {:cards hand :rank hand-rank :hand rank-name}) ) (defn- highest-rank "Finds the highest rank for a list of evaluated hands" [evaluated-hands] (first (sort #(< (%1 :rank) (%2 :rank)) evaluated-hands)) ) (defn- evaluate-all-combinations "Evaluates all possible 5-card combinations for a hand" [hand] (map #(apply evaluate-hand %) (combinations hand 5)) ) ;; (def replacements ;; {#"S" "♠" ;; #"H" "♥" ;; #"D" "♦" ;; #"C" "♣" ;; }) (defn- replace-symbols "Replace different symbols" ;; TODO: revisar [hand-rank] (clojure.string/replace (clojure.string/replace (clojure.string/replace (clojure.string/replace hand-rank "S" "♠") "D" "♦") "C" "♣") "H" "♥") ) (defn- normalize-symbols "Transform symbols into common symbols" [hand] (map replace-symbols (map clojure.string/upper-case hand)) ) (defn evaluate "Evaluates a poker hand. If it contains more than 5 cards, it returns the best hand possible" [& hand] (highest-rank (evaluate-all-combinations (normalize-symbols hand))) ) ;Con threading-macros (defn- replace-symbols* [hand-rank] (-> hand-rank (clojure.string/replace "S" "♠") (clojure.string/replace "D" "♦") (clojure.string/replace "C" "♣") (clojure.string/replace "H" "♥")) ) (defn- highest-rank* [evaluated-hands] (->> evaluated-hands (sort #(< (%1 :rank) (%2 :rank))) first) ) (defn- normalize-symbols* [hand] (map replace-symbols* (map clojure.string/upper-case hand)) ) (defn evaluate* "Evaluates a poker hand. If it contains more than 5 cards, it returns the best hand possible" [& hand] (highest-rank* (evaluate-all-combinations (normalize-symbols* hand))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Hasta aca el proyecto existente, nuevas funcionalidades abajo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn evaluate-all "Evalua una lista de manos de 5 o mas cartas" [& hands] ) (defn sort-hand-draw "Devuelve las manos en orden (mejor - peor)" [cards] ;; (first (sort-by :rank (map #(apply evaluate %) '(("Th" "Jh" "Qh" "Kh" "9h") ("Tc" "Jc" "Qc" "Kc" "Ac"))))) (sort-by :rank (map #(apply evaluate %) cards)) ) (defn best-hand-draw "Devuelve la mejor mano que contenga las cartas provistas" [cards] ;; (first (sort-by :rank (map #(apply evaluate %) '(("Th" "Jh" "Qh" "Kh" "9h") ("Tc" "Jc" "Qc" "Kc" "Ac"))))) (first (sort-hand-draw cards)) ) (defn complete-best-hand "Devuelve la mejor mano posible con las cartas pasadas como parámetro" [& uncompleted-hand] (let [result (future (let [norm-uncompleted-hand (normalize-symbols uncompleted-hand) mazo (keys deck)] (Thread/sleep 5000) (best-hand-draw (filter #(= (count (set %)) 5) (map #(conj norm-uncompleted-hand %) mazo))) ))] (if (not (realized? result)) (println "Procesando resultado...") (println "Ya terminó.")) @result) ) (defmulti complete-best-hand-multi (fn [& uncompleted-hand] [(let [result (count uncompleted-hand)] result)])) (defmethod complete-best-hand-multi [1] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [2] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [3] [& uncompleted-hand] "funcionalidad proximamente disponible") (defmethod complete-best-hand-multi [4] [& uncompleted-hand] (let [norm-uncompleted-hand (normalize-symbols uncompleted-hand) mazo (keys deck)] (best-hand-draw (filter #(= (count (set %)) 5) (map #(conj norm-uncompleted-hand %) mazo))) ) ) (defmethod complete-best-hand-multi :default [& uncompleted-hand] "Para completar la mano deben pasarse 4 cartas") (defn random-cards "Devuelve una secuencia de n cartas aleatorias sin repetir" [n cards] (take n (shuffle cards))) (def mazo (keys deck)) (defn random-game "Devuelve la mano posible con las n cartas aleatorias pasadas" [n cards] (apply evaluate (random-cards n cards))) (defn texas-game "Devuelve la mejor mano posible con las cartas aleatorias pasadas" [cards] (let [x (random-cards 7 cards) y (partition-all 5 x) mesa (first y) jugador (second y)] (println "Mesa:" mesa) (println "Jugador:" jugador) (apply evaluate x)) ) (defmacro texas-game* [cards] `(let [x# (random-cards 7 ~cards) y# (partition-all 5 x#) mesa# (first y#) jugador# (second y#)] (println "Mesa:" mesa#) (println "Jugador:" jugador#) (apply evaluate x#)) ) (def mazo-ref (ref (shuffle mazo))) (defn main "Simula un juego" [] (def hand-ref (ref #{})) (dosync (alter hand-ref (fn [hand] (set (take 5 @mazo-ref)))) (alter mazo-ref (fn [mazo] (let [cards @hand-ref] (filter #(not (contains? cards %)) mazo))) )) (println "Your cards:" (deref hand-ref)) (println (apply evaluate (deref hand-ref))) (println "\nDraw phase. Enter your cards to discard (empty if none):") (let [c (filter #(not (empty? %)) (clojure.string/split (read-line) #" "))] (println "\nChanging:" c) (dosync (alter hand-ref (fn [hand] (filter #(not (contains? (set c) %)) (union hand (set (take (count c) @mazo-ref)))))) (alter mazo-ref (fn [m] (shuffle mazo) ))) ) (println "\n\nShowdown:" (deref hand-ref)) (println (apply evaluate (deref hand-ref))) )
[ { "context": "nation\"])\n (default-challenger [\"Fall Guy\" \"Kati Jones\"]))\n (take-credits state :contest", "end": 19062, "score": 0.6949031352996826, "start": 19059, "tag": "NAME", "value": "Guy" }, { "context": "])\n (default-challenger [\"Fall Guy\" \"Kati Jones\"]))\n (take-credits state :contestant)\n (pla", "end": 19075, "score": 0.9872035384178162, "start": 19065, "tag": "NAME", "value": "Kati Jones" }, { "context": "ontestant)\n (play-from-hand state :challenger \"Kati Jones\")\n (play-from-hand state :challenger \"Fall Guy", "end": 19166, "score": 0.9316030740737915, "start": 19156, "tag": "NAME", "value": "Kati Jones" }, { "context": "radicle state 0)]\n (prompt-select :contestant kati)\n (is (empty? (:prompt (get-challenger)))", "end": 19381, "score": 0.9761947989463806, "start": 19380, "tag": "NAME", "value": "k" }, { "context": "dicle state 0)]\n (prompt-select :contestant kati)\n (is (empty? (:prompt (get-challenger))) \"F", "end": 19384, "score": 0.5238483548164368, "start": 19381, "tag": "NAME", "value": "ati" }, { "context": " (is (= 1 (count (:discard (get-challenger)))) \"Kati Jones discarded\"))))\n\n(deftest chronos-project\n ;; Chr", "end": 19531, "score": 0.9574300050735474, "start": 19521, "tag": "NAME", "value": "Kati Jones" }, { "context": "2 points\")\n (play-from-hand state :contestant \"Merger\" \"New party\")\n (take-credits state :contestant", "end": 69929, "score": 0.9254210591316223, "start": 69923, "tag": "NAME", "value": "Merger" }, { "context": "\"City Surveillance\"\n \"Jackson Howard\" \"Museum of History\" \"Advanced Assembly Lines\"])\n", "end": 98436, "score": 0.9996392726898193, "start": 98422, "tag": "NAME", "value": "Jackson Howard" }, { "context": "isement\"))\n (is (core/has-subtype? (find-card \"Jackson Howard\" (:hand (get-contestant))) \"Advertisement\"))\n ", "end": 99200, "score": 0.9844239950180054, "start": 99186, "tag": "NAME", "value": "Jackson Howard" }, { "context": "isement\"))\n (is (core/has-subtype? (find-card \"Jackson Howard\" (:hand (get-contestant))) \"Executive\"))\n (is ", "end": 99299, "score": 0.9926706552505493, "start": 99285, "tag": "NAME", "value": "Jackson Howard" }, { "context": "t\")))\n (is (not (core/has-subtype? (find-card \"Jackson Howard\" (:hand (get-contestant))) \"Advertisement\")))\n ", "end": 100114, "score": 0.988492488861084, "start": 100100, "tag": "NAME", "value": "Jackson Howard" }, { "context": "sement\")))\n (is (core/has-subtype? (find-card \"Jackson Howard\" (:hand (get-contestant))) \"Executive\"))\n (is ", "end": 100214, "score": 0.9905484318733215, "start": 100200, "tag": "NAME", "value": "Jackson Howard" }, { "context": "eek\" \"Hedge Fund\"\n \"Jackson Howard\" \"Gutenberg\"])\n (default-challenge", "end": 100758, "score": 0.9998953342437744, "start": 100744, "tag": "NAME", "value": "Jackson Howard" }, { "context": "\n \"Jackson Howard\" \"Gutenberg\"])\n (default-challenger [\"Self-mod", "end": 100770, "score": 0.9939302802085876, "start": 100761, "tag": "NAME", "value": "Gutenberg" }, { "context": "eek\" \"Hedge Fund\"\n \"Jackson Howard\" \"Gutenberg\"])\n (default-challenge", "end": 102180, "score": 0.9998956918716431, "start": 102166, "tag": "NAME", "value": "Jackson Howard" }, { "context": "\n \"Jackson Howard\" \"Gutenberg\"])\n (default-challenger [\"Self-mod", "end": 102192, "score": 0.9557161331176758, "start": 102183, "tag": "NAME", "value": "Gutenberg" }, { "context": " \"Chiyashi\"])\n (make-deck \"Reina Roja: Freedom Fighter\" []))\n (starting-hand sta", "end": 103982, "score": 0.6043739914894104, "start": 103979, "tag": "NAME", "value": "ina" } ]
test/clj/game_test/cards/agendas.clj
SylvanSign/cardnum
0
(ns game-test.cards.agendas (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (use-fixtures :once load-all-cards (partial reset-card-defs "agendas")) (deftest ^{:card-title "15-minutes"} fifteen-minutes ;; 15 Minutes - check if it works correctly from both sides (do-game (new-game (default-contestant ["15 Minutes"]) (default-challenger)) (play-from-hand state :contestant "15 Minutes" "New party") (take-credits state :contestant) ;; use 15 minutes to take it away from challenger (run-empty-locale state "Locale 1") (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (= 1 (:agenda-point (get-challenger)))) (is (= 1 (count (:scored (get-challenger))))) (let [fifm (first (:scored (get-challenger)))] (is (= 3 (:click (get-contestant)))) (is (= 1 (count (:abilities (refresh fifm))))) (card-ability state :contestant (refresh fifm) 0) (is (zero? (:agenda-point (get-challenger)))) (is (zero? (count (:scored (get-challenger)))))) (is (= "15 Minutes" (:title (first (:deck (get-contestant)))))) ;; TODO: could also check for deck shuffle (is (= 2 (:click (get-contestant)))) ;; use 15 minutes to take it away from contestant (hey, maybe some obscure case happens where contestant would want that) (core/click-draw state :contestant 1) (play-from-hand state :contestant "15 Minutes" "New party") (take-credits state :challenger) (score-agenda state :contestant (get-content state :party2 0)) (is (= 1 (:agenda-point (get-contestant)))) (is (= 1 (count (:scored (get-contestant))))) (let [fifm (first (:scored (get-contestant)))] (is (= 1 (count (:abilities (refresh fifm))))) (card-ability state :contestant (refresh fifm) 0) (is (zero? (:agenda-point (get-contestant)))) (is (zero? (count (:scored (get-contestant)))))) (is (= "15 Minutes" (:title (first (:deck (get-contestant)))))))) (deftest accelerated-beta-test ;; Accelerated Beta Test (do-game (new-game (default-contestant ["Accelerated Beta Test" "Enigma" (qty "Hedge Fund" 2)]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Accelerated Beta Test"]) (play-and-score state "Accelerated Beta Test") (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Enigma" (get-in @state [:contestant :play-area]))) (prompt-choice :contestant "HQ") (is (some? (get-character state :hq 0))) (is (= 2 (count (:discard (get-contestant))))) (core/move state :contestant (find-card "Accelerated Beta Test" (:scored (get-contestant))) :hand) (core/move state :contestant (find-card "Hedge Fund" (:discard (get-contestant))) :deck) (core/move state :contestant (find-card "Hedge Fund" (:discard (get-contestant))) :deck) (play-and-score state "Accelerated Beta Test") (prompt-choice :contestant "Yes") (prompt-choice :contestant "I have no regrets") (is (= 2 (count (:discard (get-contestant))))))) (deftest advanced-concept-hopper ;; Advanced Concept Hopper (do-game (new-game (default-contestant ["Advanced Concept Hopper" (qty "Hedge Fund" 4)]) (default-challenger)) (starting-hand state :contestant ["Advanced Concept Hopper"]) (play-and-score state "Advanced Concept Hopper") (take-credits state :contestant) (testing "Contestant draws 1 card, only once per turn" (let [cards (count (:hand (get-contestant)))] (is (= cards (count (:hand (get-contestant)))) (str "Contestant should have " cards " cards in hand")) (run-on state :archives) (prompt-choice :contestant "Draw 1 card") (is (= (inc cards) (count (:hand (get-contestant)))) (str "Contestant should have " (inc cards) " card in hand")) (run-successful state) (run-on state :archives) (is (empty (:prompt (get-contestant))) "No prompt as it's once per turn"))) (take-credits state :challenger) (take-credits state :contestant) (testing "Contestant gains 1 credit, only once per turn" (let [credits (:credit (get-contestant))] (is (= credits (:credit (get-contestant))) (str "Contestant should have " credits " credits")) (run-on state :archives) (prompt-choice :contestant "Gain 1 [Credits]") (is (= (inc credits) (:credit (get-contestant))) (str "Contestant should have " (inc credits) " credits")) (run-successful state) (run-on state :archives) (is (empty (:prompt (get-contestant))) "No prompt as it's once per turn"))))) (deftest ancestral-imager ;; Ancestral Imager (do-game (new-game (default-contestant [(qty "Ancestral Imager" 3)]) (default-challenger)) (play-and-score state "Ancestral Imager") (take-credits state :contestant) (let [grip (count (:hand (get-challenger)))] (is (= grip (count (:hand (get-challenger)))) (str "Challenger has " grip " cards in hand")) (run-on state :hq) (run-jack-out state) (is (= (dec grip) (count (:hand (get-challenger)))) "Challenger took 1 net damage")))) (deftest ar-enhanced-security ;; AR-Enhanced Security (do-game (new-game (default-contestant ["AR-Enhanced Security" (qty "NGO Front" 3)]) (default-challenger)) (testing "set up" (core/gain state :contestant :click 10 :credit 10) (core/gain state :challenger :credit 10) (dotimes [_ 3] (play-from-hand state :contestant "NGO Front" "New party")) (take-credits state :contestant)) (testing "don't take a tag from discarding normally" (run-on state :party1) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 1 (count (:discard (get-contestant)))) "discarded") (is (zero? (:tag (get-challenger))) "Challenger took 0 tags") (take-credits state :challenger) (play-and-score state "AR-Enhanced Security") (take-credits state :contestant)) (testing "gain a tag from first discard" (run-on state :party2) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 2 (count (:discard (get-contestant)))) "discarded") (is (= 1 (:tag (get-challenger))) "Challenger took 1 tag")) (testing "don't gain a tag from second discard" (run-on state :party3) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 3 (count (:discard (get-contestant)))) "discarded") (is (= 1 (:tag (get-challenger))) "Challenger took 0 tags")))) (deftest armed-intimidation ;; Armed Intimidation (do-game (new-game (default-contestant [(qty "Armed Intimidation" 2)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 2)])) (play-and-score state "Armed Intimidation") (prompt-choice :challenger "Take 2 tags") (is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from Armed Intimidation tag choice") (play-and-score state "Armed Intimidation") (is (= 5 (count (:hand (get-challenger)))) "Challenger has 5 cards before Armed Intimidation meat damage") (prompt-choice :challenger "Suffer 5 meat damage") (is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards after Armed Intimidation meat damage"))) (deftest armored-locales ;; Armored Locales (do-game (new-game (default-contestant ["Armored Locales"]) (default-challenger)) (play-and-score state "Armored Locales") (let [as-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh as-scored) :agenda)) "Should start with 1 agenda counters") (take-credits state :contestant) (run-on state "HQ") (card-ability state :contestant as-scored 0) (is (last-log-contains? state "make the Challenger discard") "Should only write to log")))) (deftest astroscript-pilot-resource ;; AstroScript token placement (do-game (new-game (default-contestant [(qty "AstroScript Pilot Resource" 3) (qty "Character Wall" 2)]) (default-challenger)) (core/gain state :contestant :click 3) (letfn [(try-place [from to] (card-ability state :contestant (refresh from) 0) (prompt-select :contestant (refresh to))) (should-not-place [from to msg] (try-place from to) (prompt-choice :contestant "Done") (is (= 1 (get-counters (refresh from) :agenda)) (str (:title from)" token was not used on " (:title to) msg)) (is (zero? (get-counters (refresh to) :advancement)) (str "Advancement token not placed on " (:title to) msg))) (should-place [from to msg] (try-place from to) (is (zero? (get-counters (refresh from) :agenda)) (str (:title from) " token was used on " (:title to) msg)) (is (= 1 (get-counters (refresh to) :advancement)) (str "Advancement token placed on " (:title to) msg)))] (play-and-score state "AstroScript Pilot Resource") (play-from-hand state :contestant "AstroScript Pilot Resource" "New party") (let [scored-astro (get-scored state :contestant 0) placed-astro (get-content state :party2 0) hand-astro (find-card "AstroScript Pilot Resource" (:hand get-contestant))] (should-not-place scored-astro hand-astro " in hand") (should-place scored-astro placed-astro " that is placed") (advance state placed-astro 2) (core/score state :contestant {:card (refresh placed-astro)})) (play-from-hand state :contestant "Character Wall" "HQ") (let [no-token-astro (get-scored state :contestant 0) token-astro (get-scored state :contestant 1) hand-character-wall (find-card "Character Wall" (:hand get-contestant)) placed-character-wall (get-character state :hq 0)] (should-not-place token-astro no-token-astro " that is scored") (should-not-place token-astro hand-character-wall " in hand") (should-place token-astro placed-character-wall " that is placed"))))) (deftest award-bait ;; Award Bait (do-game (new-game (default-contestant [(qty "Award Bait" 2) "Character Wall"]) (default-challenger)) (core/move state :contestant (find-card "Award Bait" (:hand (get-contestant))) :deck) (play-from-hand state :contestant "Character Wall" "HQ") (let [iw (get-character state :hq 0)] (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (play-from-hand state :contestant "Award Bait" "New party") (take-credits state :contestant) (run-on state :party1) (run-successful state) (prompt-choice :contestant "2") (prompt-select :contestant (refresh iw)) (prompt-choice :challenger "Steal") (is (= 2 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 advancement tokens") (run-on state :rd) (run-successful state) (prompt-choice :challenger "Access") (prompt-choice :contestant "2") (prompt-select :contestant (refresh iw)) (prompt-choice :challenger "Steal") (is (= 4 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 advancement tokens")))) (deftest bacterial-resourceming ;; Bacterial Resourceming (testing "Scoring should not cause a run to exist for challenger." (do-game (new-game (default-contestant ["Bacterial Resourceming" "Hedge Fund"]) (default-challenger)) (starting-hand state :contestant ["Bacterial Resourceming"]) (play-and-score state "Bacterial Resourceming") (prompt-choice :contestant "Yes") (prompt-choice :contestant "Done") (prompt-choice :contestant "Done") (prompt-card :contestant (first (:deck (get-contestant)))) (prompt-choice :contestant "Done") (is (empty (:prompt (get-contestant))) "Bacterial Resourceming prompts finished") (is (not (:run @state)) "No run is active"))) (testing "Removing all cards from R&D should not freeze for challenger, nor give an extra access." (do-game (new-game (default-contestant [(qty "Bacterial Resourceming" 8)]) (default-challenger) {:start-as :challenger}) (starting-hand state :contestant []) (run-empty-locale state :rd) (prompt-choice :challenger "Steal") (prompt-choice :contestant "Yes") ;; Move all 7 cards to discard (doseq [_ (range 7) ;; Get the first card listed in the prompt choice ;; TODO make this function :let [card (-> @state (get-in [:contestant :prompt]) first (get-in [:choices 0]))]] (prompt-card :contestant card)) (prompt-choice :contestant "Done") ; Finished with discarding (prompt-choice :contestant "Done") ; Finished with move-to-hq (no cards to move) ;; Run and prompts should be over now (is (empty (:prompt (get-contestant))) "Bacterial Resourceming prompts finished") (is (empty (:prompt (get-challenger))) "Bacterial Resourceming prompts finished") (is (not (:run @state)))))) (deftest better-citizen-resource ;; Better Citizen Resource (testing "Basic test" (do-game (new-game (default-contestant ["Better Citizen Resource"]) (default-challenger [(qty "The Maker's Eye" 2) (qty "Wyrm" 2)])) (play-and-score state "Better Citizen Resource") (take-credits state :contestant) (core/gain state :challenger :credit 10) (is (zero? (:tag (get-challenger))) "Challenger starts with 0 tags") (play-from-hand state :challenger "The Maker's Eye") (prompt-choice :contestant "Yes") (is (= 1 (:tag (get-challenger))) "Challenger takes 1 tag for playing a Run event") (run-successful state) (play-from-hand state :challenger "Wyrm") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (= 1 (:tag (get-challenger))) "Challenger doesn't gain a tag from placing an characterbreaker after playing a Run event") (take-credits state :challenger) (take-credits state :contestant) (play-from-hand state :challenger "Wyrm") (prompt-choice :contestant "Yes") (is (= 2 (:tag (get-challenger))) "Challenger gains 1 tag for placing an Icebreaker") (play-from-hand state :challenger "The Maker's Eye") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (= 2 (:tag (get-challenger))) "Challenger doesn't gain a tag from playing a Run event after placing an Icebreaker") (run-successful state))) (testing "Should only trigger on Run events. #3619" (do-game (new-game (default-contestant ["Better Citizen Resource"]) (default-challenger ["Mining Accident"])) (play-and-score state "Better Citizen Resource") (take-credits state :contestant) (run-empty-locale state "HQ") (play-from-hand state :challenger "Mining Accident") (prompt-choice-partial :contestant "Pay") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (zero? (:tag (get-challenger))) "Challenger should not gain a tag from playing a non-Run event")))) (deftest bifrost-array ;; Bifrost Array (do-game (new-game (default-contestant ["Bifrost Array" "Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity") (let [ht-scored (get-scored state :contestant 0)] (play-and-score state "Bifrost Array") (prompt-choice :contestant "Yes") (prompt-select :contestant (refresh ht-scored)) (is (= 19 (:credit (get-contestant))) "Should gain 7 credits from 12 to 19") (is (= 2 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity")))) (deftest brain-rewiring ;; Brain Rewiring (do-game (new-game (default-contestant ["Brain Rewiring"]) (default-challenger)) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-and-score state "Brain Rewiring") (prompt-choice :contestant "Yes") (prompt-choice :contestant 2) (is (= 1 (count (:hand (get-challenger))))))) (deftest braintrust ;; Braintrust (do-game (new-game (default-contestant ["Braintrust" "Ichi 1.0"]) (default-challenger)) (play-from-hand state :contestant "Braintrust" "New party") (let [bt (get-content state :party1 0)] (core/add-prop state :contestant bt :advance-counter 7) (core/score state :contestant {:card (refresh bt)}) (let [scored-bt (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh scored-bt) :agenda)) "Scored w/ 4 over-advancements; 2 agenda counters") (play-from-hand state :contestant "Ichi 1.0" "HQ") (core/reveal state :contestant (get-character state :hq 0)) (is (= 2 (:credit (get-contestant))) "2c discount to reveal Ichi"))))) (deftest breaking-news ;; Breaking News (do-game (new-game (default-contestant [(qty "Breaking News" 3)]) (default-challenger)) (play-and-score state "Breaking News") (is (= 2 (get-in @state [:challenger :tag])) "Challenger receives 2 tags from Breaking News") (take-credits state :contestant) (is (zero? (get-in @state [:challenger :tag]))) "Two tags removed at the end of the turn")) (deftest cfc-excavation-contract ;; CFC Excavation Contract (dotimes [n 5] (do-game (new-game (default-contestant ["CFC Excavation Contract" (qty "Eli 1.0" n)]) (default-challenger)) (core/gain state :contestant :click 10 :credit 10) (is (= 15 (:credit (get-contestant))) "Should start with 5 credits") (dotimes [_ n] (play-from-hand state :contestant "Eli 1.0" "New party") (core/reveal state :contestant (get-character state (keyword (str "party" (:rid @state))) 0))) (let [credit (:credit (get-contestant))] (play-and-score state "CFC Excavation Contract") (is (= (+ credit (* 2 n)) (:credit (get-contestant))) (str "Should now have with " (+ credit (* 2 n)) " credits")))))) (deftest character-assassination ;; Character Assassination (do-game (new-game (default-contestant ["Character Assassination"]) (default-challenger ["Fall Guy" "Kati Jones"])) (take-credits state :contestant) (play-from-hand state :challenger "Kati Jones") (play-from-hand state :challenger "Fall Guy") (take-credits state :challenger) (play-and-score state "Character Assassination") (let [kati (get-radicle state 0)] (prompt-select :contestant kati) (is (empty? (:prompt (get-challenger))) "Fall Guy prevention didn't occur") (is (= 1 (count (:discard (get-challenger)))) "Kati Jones discarded")))) (deftest chronos-project ;; Chronos Project (do-game (new-game (default-contestant ["Chronos Project"]) (default-challenger)) (dotimes [_ 3] (core/move state :challenger (find-card "Sure Gamble" (:hand (get-challenger))) :discard)) (is (= 3 (count (:discard (get-challenger)))) "Challenger should have 3 cards in heap") (play-and-score state "Chronos Project") (is (zero? (count (:discard (get-challenger)))) "Challenger should have 0 cards in heap"))) (deftest city-works-project ;; City Works Project (do-game (new-game (default-contestant ["City Works Project"]) (default-challenger [(qty "Sure Gamble" 4)])) (play-from-hand state :contestant "City Works Project" "New party") (let [cwp (get-content state :party1 0)] (core/advance state :contestant {:card (refresh cwp)}) (core/advance state :contestant {:card (refresh cwp)})) (take-credits state :contestant) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (= 4 (count (:discard (get-challenger)))) "Challenger paid 4 meat damage"))) (deftest clone-retirement ;; Clone Retirement (do-game (new-game (default-contestant [(qty "Clone Retirement" 2) "Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant)))) (is (= 1 (:bad-publicity (get-contestant)))) (play-and-score state "Clone Retirement") (is (zero? (:bad-publicity (get-contestant)))) (play-from-hand state :contestant "Clone Retirement" "New party") (take-credits state :contestant) (run-on state "Locale 3") (run-successful state) (prompt-choice :challenger "Steal") (is (= 1 (:bad-publicity (get-contestant)))))) (deftest contestantorate-sales-team ;; Contestantorate Sales Team (do-game (new-game (default-contestant [(qty "Contestantorate Sales Team" 2)]) (default-challenger)) (is (= 5 (:credit (get-contestant)))) (play-and-score state "Contestantorate Sales Team") (let [scored-cst (get-scored state :contestant 0)] (core/end-turn state :contestant nil) (core/start-turn state :challenger nil) (is (= 6 (:credit (get-contestant))) "Increments at challenger's start of turn") (is (= 9 (get-counters (refresh scored-cst) :credit))) (core/end-turn state :challenger nil) (core/start-turn state :contestant nil) (is (= 7 (:credit (get-contestant))) "Increments at contestant's start of turn") (is (= 8 (get-counters (refresh scored-cst) :credit)))))) (deftest contestantorate-war ;; Contestantorate War (do-game (new-game (default-contestant [(qty "Contestantorate War" 2)]) (default-challenger)) (is (= 5 (:credit (get-contestant)))) (play-and-score state "Contestantorate War") (is (zero? (:credit (get-contestant))) "Lost all credits") (core/gain state :contestant :credit 7) (play-and-score state "Contestantorate War") (is (= 14 (:credit (get-contestant))) "Had 7 credits when scoring, gained another 7"))) (deftest crisis-management ;; Crisis Management (do-game (new-game (default-contestant ["Crisis Management"]) (default-challenger)) (play-and-score state "Crisis Management") (take-credits state :contestant) (take-credits state :challenger) (is (= 3 (count (:hand (get-challenger)))) "No damage done, Challenger not tagged") (take-credits state :contestant) (core/gain state :challenger :tag 1) (take-credits state :challenger) (is (= 2 (count (:hand (get-challenger)))) "Crisis Management dealt 1 meat damage"))) (deftest dedicated-neural-net ;; Dedicated Neural Net (do-game (new-game (default-contestant ["Dedicated Neural Net" (qty "Scorched Earth" 2) "Hedge Fund" "Caprcharacter Nisei"]) (default-challenger ["HQ Interface"])) (play-from-hand state :contestant "Caprcharacter Nisei" "HQ") (play-and-score state "Dedicated Neural Net") (take-credits state :contestant) (run-empty-locale state :hq) (prompt-choice :challenger "0") (prompt-choice :contestant "1") (is (-> @state :run :run-effect :replace-access) "Replace-access tiggered") (prompt-select :contestant (find-card "Hedge Fund" (:hand (get-contestant)))) (prompt-choice :challenger "Card from hand") (is (accessing state "Hedge Fund") "Challenger accessing Hedge Fund") (prompt-choice :challenger "No action") ;; test for #2376 (prompt-choice :challenger "Unrevealed region in HQ") (is (accessing state "Caprcharacter Nisei") "Challenger accessing Caprcharacter") (prompt-choice :challenger "No") (is (not (:run @state)) "Run completed") (run-empty-locale state :hq) (prompt-choice :challenger "No action") (take-credits state :challenger) (take-credits state :contestant) (play-from-hand state :challenger "HQ Interface") (run-empty-locale state :hq) (prompt-choice :challenger "0") (prompt-choice :contestant "1") (is (= 2 (-> (get-contestant) :selected first :max)) "Contestant chooses 2 cards for Challenger to access"))) (deftest degree-mill ;; Degree Mill (testing "Basic behavior" (do-game (new-game (default-contestant [(qty "Degree Mill" 2)]) (default-challenger ["Character Analyzer" "All-nighter" "Hunting Grounds"])) (play-from-hand state :contestant "Degree Mill" "New party") (take-credits state :contestant) (is (= 0 (count (:deck (get-challenger)))) "Challenger starts with empty deck") (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "No action") (is (= 0 (:agenda-point (get-challenger))) "Challenger stole Degree Mill with no placed cards") (play-from-hand state :challenger "Character Analyzer") (play-from-hand state :challenger "All-nighter") (let [ia (get-radicle state 0) an (get-radicle state 1)] (run-on state "Locale 1") (run-successful state) (prompt-choice-partial :challenger "Pay") (prompt-select :challenger ia) (prompt-select :challenger an) (is (= 3 (:agenda-point (get-challenger))) "Challenger failed to steal Degree Mill") (is (empty? (get-in @state [:challenger :rig :radicle])) "Degree Mill didn't remove placed cards") (is (= 2 (count (:deck (get-challenger)))) "Degree Mill didn't put cards back in deck")) (take-credits state :challenger) ;; Checking if facedowns work as well (play-from-hand state :contestant "Degree Mill" "New party") (take-credits state :contestant) (play-from-hand state :challenger "Hunting Grounds") (let [hg (get-radicle state 0)] (run-on state "Locale 2") (run-successful state) (prompt-choice :challenger "No action") (is (= 3 (:agenda-point (get-challenger))) "Challenger stole Degree Mill with single card") (card-ability state :challenger hg 1) (is (= 2 (count (get-in (get-challenger) [:rig :facedown]))) "Hunting Ground did not place cards facedown") (is (empty? (:deck (get-challenger))) "Hunting Grounds did not remove cards from deck") (let [fd1 (get-challenger-facedown state 0) fd2 (get-challenger-facedown state 1)] (run-on state "Locale 2") (run-successful state) (prompt-choice-partial :challenger "Pay") (prompt-select :challenger fd1) (prompt-select :challenger fd2) (is (= 6 (:agenda-point (get-challenger))) "Challenger failed to steal Degree Mill with facedown cards") (is (empty? (get-in (get-challenger) [:rig :facedown])) "Degree Mill didn't remove facedown cards") (is (= 2 (count (:deck (get-challenger)))) "Degree Mill didn't put cards back in deck"))))) (testing "Multiple steal costs" (do-game (new-game (default-contestant [(qty "Degree Mill" 1) (qty "Strongbox" 1)]) (default-challenger [(qty "Character Analyzer" 3) (qty "All-nighter" 3)])) (play-from-hand state :contestant "Degree Mill" "New party") (play-from-hand state :contestant "Strongbox" "Locale 1") (let [dm (get-content state :party1 0) sb (get-content state :party1 1)] (core/reveal state :contestant sb) (take-credits state :contestant) (play-from-hand state :challenger "Character Analyzer") (play-from-hand state :challenger "All-nighter") (run-empty-locale state :party1) (prompt-select :challenger (refresh dm)) (prompt-choice-partial :challenger "Pay") (is (= 1 (:click (get-challenger))) "Challenger should start with 1 remaining click") (prompt-choice-partial :challenger "Click") (is (zero? (:click (get-challenger))) "Challenger should have spent a click") (is (= 2 (count (get-in @state [:challenger :rig :radicle]))) "Challenger starts with 2 radicles") (prompt-choice-partial :challenger "shuffling") (prompt-select :challenger (get-radicle state 1)) (prompt-select :challenger (get-radicle state 0)) (is (empty? (get-radicle state)) "Degree Mill removed placed cards") (is (not-empty (get-scored state :challenger)) "Challenger stole an agenda"))))) (deftest director-haas'-pet-project ;; Director Haas' Pet Project (do-game (new-game (default-contestant ["Director Haas' Pet Project" "Adonis Campaign" "Strongbox" "Eli 1.0" (qty "Hedge Fund" 5)]) (default-challenger)) (starting-hand state :contestant ["Director Haas' Pet Project" "Adonis Campaign" "Strongbox"]) (core/move state :contestant (find-card "Eli 1.0" (:deck (get-contestant))) :discard) (play-and-score state "Director Haas' Pet Project") (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Adonis Campaign" (:hand (get-contestant)))) (prompt-select :contestant (find-card "Strongbox" (:hand (get-contestant)))) (prompt-select :contestant (find-card "Eli 1.0" (:discard (get-contestant)))))) (deftest domestic-sleepers ;; Domestic Sleepers (do-game (new-game (default-contestant ["Domestic Sleepers"]) (default-challenger)) (play-and-score state "Domestic Sleepers") (core/gain state :contestant :click 3) (let [ds_scored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh ds_scored) :agenda)) "Should start with 0 agenda counters") (is (zero? (:agenda-point (get-contestant))) "Should provide 0 agenda points initially") (card-ability state :contestant ds_scored 0) (is (= 1 (get-counters (refresh ds_scored) :agenda)) "Should gain 1 agenda counter") (is (= 1 (:agenda-point (get-contestant))) "Should provide 1 agenda point after ability use")))) (deftest eden-fragment ;; Test that Eden Fragment ignores the place cost of the first character (do-game (new-game (default-contestant [(qty "Eden Fragment" 3) (qty "Character Wall" 3)]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (play-and-score state "Eden Fragment") (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Character Wall" "HQ") (is (some? (get-character state :hq 1)) "Contestant has two character placed on HQ") (is (= 6 (:credit (get-contestant))) "Contestant does not pay for placing the first Character of the turn") (play-from-hand state :contestant "Character Wall" "HQ") (is (some? (get-character state :hq 2)) "Contestant has three character placed on HQ") (is (= 4 (:credit (get-contestant))) "Contestant pays for placing the second Character of the turn"))) (deftest efficiency-committee ;; Efficiency Committee (do-game (new-game (default-contestant [(qty "Efficiency Committee" 3) (qty "Shipment from SanSan" 2) "Character Wall"]) (default-challenger)) (core/gain state :contestant :click 4) (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Character Wall" "HQ") (let [ec1 (get-content state :party1 0) ec2 (get-content state :party2 0) ec3 (get-content state :party3 0) iw (get-character state :hq 0)] (score-agenda state :contestant ec1) (let [ec1_scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh ec1_scored) :agenda))) (is (= 2 (:agenda-point (get-contestant)))) ;; use token (is (= 3 (:click (get-contestant)))) (card-ability state :contestant ec1_scored 0) (is (= 4 (:click (get-contestant)))) ;; try to advance Character Wall (advance state iw) (is (= 4 (:click (get-contestant)))) (is (zero? (get-counters (refresh iw) :advancement))) ;; try to advance Efficiency Committee (advance state ec2) (is (= 4 (:click (get-contestant)))) (is (zero? (get-counters (refresh ec2) :advancement))) ;; advance with Shipment from SanSan (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ec2) (is (= 2 (get-counters (refresh ec2) :advancement))) (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ec2) (is (= 4 (get-counters (refresh ec2) :advancement))) (core/score state :contestant {:card (refresh ec2)}) (is (= 4 (:agenda-point (get-contestant)))) (take-credits state :contestant) (take-credits state :challenger) ;; can advance again (advance state iw) (is (= 1 (get-counters (refresh iw) :advancement))) (advance state ec3) (is (= 1 (get-counters (refresh ec3) :advancement))))))) (deftest elective-region ;; Elective Region (do-game (new-game (default-contestant ["Elective Region"]) (default-challenger)) (play-and-score state "Elective Region") (let [eu-scored (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh eu-scored) :agenda)) "Should start with 2 agenda counters") (take-credits state :contestant) (take-credits state :challenger) (is (= 3 (:click (get-contestant))) "Should start with 4 clicks") (card-ability state :contestant eu-scored 0) (card-ability state :contestant eu-scored 0) (is (= 4 (:click (get-contestant))) "Should gain 2 clicks, not 3") (is (= 1 (get-counters (refresh eu-scored) :agenda)) "Should still have 1 agenda counter")))) (deftest encrypted-portals ;; Encrypted Portals (do-game (new-game (default-contestant ["Encrypted Portals" "Lotus Field"]) (default-challenger)) (play-from-hand state :contestant "Lotus Field" "HQ") (let [lf (get-character state :hq 0)] (core/reveal state :contestant lf) (is (= 4 (:current-strength (refresh lf))) "Should start with base strength of 4") (is (zero? (:credit (get-contestant))) "Should have 0 credits after reveal") (play-and-score state "Encrypted Portals") (is (= 5 (:current-strength (refresh lf))) "Should gain 1 strength from 4 to 5") (is (= 1 (:credit (get-contestant))) "Should gain 1 credit for revealed code gate")))) (deftest escalate-vitriol ;; Escalate Vitriol (do-game (new-game (default-contestant ["Escalate Vitriol"]) (default-challenger)) (core/lose state :contestant :credit 5) (play-and-score state "Escalate Vitriol") (let [ev-scored (get-scored state :contestant 0)] (dotimes [tag 10] (is (zero? (:tag (get-challenger))) "Should start with 0 tags") (is (zero? (:credit (get-contestant))) "Should start with 0 credits") (core/gain state :challenger :tag tag) (card-ability state :contestant ev-scored 0) (is (= tag (:credit (get-contestant))) (str "Should gain " tag " credits")) (take-credits state :contestant) (take-credits state :challenger) (core/lose state :contestant :credit (:credit (get-contestant))) (core/lose state :challenger :tag tag))))) (deftest executive-retreat ;; Executive Retreat (do-game (new-game (default-contestant ["Executive Retreat" (qty "Hedge Fund" 5)]) (default-challenger)) (starting-hand state :contestant ["Executive Retreat" "Hedge Fund"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should start with 1 card in HQ") (play-and-score state "Executive Retreat") (is (zero? (count (:hand (get-contestant)))) "Contestant should have 0 cards in HQ after shuffling HQ back into R&D") (let [er-scored (get-scored state :contestant 0)] (card-ability state :contestant er-scored 0) (is (= 5 (count (:hand (get-contestant)))) "Contestant should have 5 cards in hand") (is (zero? (get-counters (refresh er-scored) :agenda)) "Executive Retreat should have 0 agenda counters"))) (testing "Overdraw" (do-game (new-game (default-contestant ["Executive Retreat" (qty "Hedge Fund" 4)]) (default-challenger)) (starting-hand state :contestant ["Executive Retreat" "Hedge Fund"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should start with 1 card in HQ") (play-and-score state "Executive Retreat") (is (zero? (count (:hand (get-contestant)))) "Contestant should have 0 cards in HQ after shuffling HQ back into R&D") (let [er-scored (get-scored state :contestant 0)] (card-ability state :contestant er-scored 0) (is (= 4 (count (:hand (get-contestant)))) "Contestant should have 5 cards in hand") (is (zero? (get-counters (refresh er-scored) :agenda)) "Executive Retreat should have 0 agenda counters") (is (= :challenger (:winner @state)) "Challenger wins") (is (= "Decked" (:reason @state)) "Win condition reports decked"))))) (deftest explode-a-palooza ;; Explode-a-palooza (testing "Basic test" (do-game (new-game (default-contestant ["Explode-a-palooza"]) (default-challenger)) (play-from-hand state :contestant "Explode-a-palooza" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Access") (prompt-choice :challenger "Steal") (prompt-choice :contestant "Yes") (is (= 12 (:credit (get-contestant))) "Gained 5 credits"))) (testing "Interaction with The Turning Wheel. Issue #1717." (do-game (new-game (default-contestant [(qty "Explode-a-palooza" 3)]) (default-challenger ["The Turning Wheel"])) (starting-hand state :contestant ["Explode-a-palooza" "Explode-a-palooza"]) (play-from-hand state :contestant "Explode-a-palooza" "New party") (take-credits state :contestant) (play-from-hand state :challenger "The Turning Wheel") (run-empty-locale state :party1) (prompt-choice :challenger "Access") (prompt-choice :contestant "Yes") (prompt-choice :challenger "Steal") (let [ttw (get-radicle state 0)] (is (zero? (get-counters (refresh ttw) :power)) "TTW did not gain counters") (is (= 1 (count (:scored (get-challenger)))) "Challenger stole Explodapalooza") (is (= 12 (:credit (get-contestant))) "Gained 5 credits") (run-empty-locale state :rd) (prompt-choice :challenger "Access") (prompt-choice :contestant "Yes") (prompt-choice :challenger "Steal") (is (zero? (get-counters (refresh ttw) :power)) "TTW did not gain counters") (is (= 2 (count (:scored (get-challenger)))) "Challenger stole Explodapalooza") (is (= 17 (:credit (get-contestant))) "Gained 5 credits"))))) (deftest false-lead ;; False Lead (do-game (new-game (default-contestant ["False Lead"]) (default-challenger)) (play-and-score state "False Lead") (is (= 1 (count (:scored (get-contestant)))) "Contestant should have 1 agenda point") (take-credits state :contestant) (is (= 4 (:click (get-challenger))) "Challenger should start turn with 4 clicks") (card-ability state :contestant (get-scored state :contestant 0) 0) (is (= 2 (:click (get-challenger))) "Challenger should lose 2 clicks from False Lead"))) (deftest fetal-ai ;; Fetal AI (testing "basic test" (do-game (new-game (default-contestant [(qty "Fetal AI" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3) (qty "Quality Time" 3)])) (play-from-hand state :contestant "Fetal AI" "New party") (take-credits state :contestant 2) (run-empty-locale state "Locale 1") (prompt-choice-partial :challenger "Pay") (is (= 3 (count (:hand (get-challenger)))) "Challenger took 2 net damage from Fetal AI") (is (= 3 (:credit (get-challenger))) "Challenger paid 2cr to steal Fetal AI") (is (= 1 (count (:scored (get-challenger)))) "Challenger stole Fetal AI")) (testing "can't afford to steal" (do-game (new-game (default-contestant [(qty "Fetal AI" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3) (qty "Quality Time" 3)])) (play-from-hand state :contestant "Fetal AI" "New party") (take-credits state :contestant 2) (core/lose state :challenger :credit 5) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (= 3 (count (:hand (get-challenger)))) "Challenger took 2 net damage from Fetal AI") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Fetal AI"))))) (deftest firmware-updates ;; Firmware Updates (do-game (new-game (default-contestant ["Firmware Updates" "Character Wall"]) (default-challenger)) (play-and-score state "Firmware Updates") (play-from-hand state :contestant "Character Wall" "HQ") (let [fu (get-scored state :contestant 0) iw (get-character state :hq 0)] (is (= 3 (get-counters (refresh fu) :agenda)) "Firmware Updates should start with 3 agenda counters") (core/reveal state :contestant iw) (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (card-ability state :contestant fu 0) (prompt-select :contestant (refresh iw)) (is (= 2 (get-counters (refresh fu) :agenda)) "Firmware Updates should now have 2 agenda counters") (is (= 1 (get-counters (refresh iw) :advancement)) "Character Wall should have 1 advancement token")))) (deftest geothermal-fracking ;; Geothermal Fracking (testing "basic test" (do-game (new-game (default-contestant ["Geothermal Fracking"]) (default-challenger)) (play-and-score state "Geothermal Fracking") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (is (zero? (:bad-publicity (get-contestant))) "Should start with 0 bad publicity") (let [gf-scored (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh gf-scored) :agenda)) "Should start with 2 agenda counters") (card-ability state :contestant gf-scored 0) (is (= 1 (:click (get-contestant))) "Should have 1 click left") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity")))) (testing "prevented bad publicity shouldn't block credit gain" (do-game (new-game (default-contestant ["Geothermal Fracking" "Broadcast Square"]) (default-challenger)) (play-and-score state "Geothermal Fracking") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (is (zero? (:bad-publicity (get-contestant))) "Should start with 0 bad publicity") (play-from-hand state :contestant "Broadcast Square" "New party") (let [gf-scored (get-scored state :contestant 0) bs (get-content state :party2 0)] (core/reveal state :contestant bs) (is (= 2 (get-counters (refresh gf-scored) :agenda)) "Should start with 2 agenda counters") (card-ability state :contestant gf-scored 0) (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (zero? (:click (get-contestant))) "Should have 0 click left") (is (= 10 (:credit (get-contestant))) "Should gain 7 credits from 3 to 10") (is (zero? (:bad-publicity (get-contestant))) "Should gain 0 bad publicity from prevention"))))) (deftest genetic-resequencing ;; Genetic Resequencing (do-game (new-game (default-contestant ["Genetic Resequencing" (qty "Braintrust" 2)]) (default-challenger)) (play-from-hand state :contestant "Braintrust" "New party") (play-from-hand state :contestant "Braintrust" "New party") (play-from-hand state :contestant "Genetic Resequencing" "New party") (let [bt1 (get-content state :party1 0) bt2 (get-content state :party2 0) gr (get-content state :party3 0)] (score-agenda state :contestant bt1) (let [btscored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh btscored) :agenda)) "No agenda counters on scored Braintrust") (score-agenda state :contestant gr) (prompt-select :contestant bt2) (is (zero? (get-counters (refresh bt2) :agenda)) "No agenda counters on placed Braintrust; not a valid target") (prompt-select :contestant btscored) (is (= 1 (get-counters (refresh btscored) :agenda)) "1 agenda counter placed on scored Braintrust"))))) (deftest gila-hands-arcology ;; Gila Hands Arcology (do-game (new-game (default-contestant ["Gila Hands Arcology"]) (default-challenger)) (play-and-score state "Gila Hands Arcology") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (core/gain state :contestant :click 2) (let [gha-scored (get-scored state :contestant 0)] (card-ability state :contestant gha-scored 0) (is (= 2 (:click (get-contestant))) "Should spend 2 clicks on Gila Hands") (is (= 8 (:credit (get-contestant))) "Should gain 3 credits from 5 to 8") (card-ability state :contestant gha-scored 0) (is (zero? (:click (get-contestant))) "Should spend 2 clicks on Gila Hands") (is (= 11 (:credit (get-contestant))) "Should gain 3 credits from 8 to 11")))) (deftest glenn-station ;; Glenn Station (do-game (new-game (default-contestant ["Glenn Station" "Character Wall"]) (default-challenger)) (play-and-score state "Glenn Station") (let [gs-scored (get-scored state :contestant 0)] (card-ability state :contestant gs-scored 0) (prompt-card :contestant (find-card "Character Wall" (:hand (get-contestant)))) (is (= 1 (count (:hosted (refresh gs-scored))))) (card-ability state :contestant gs-scored 1) (prompt-card :contestant (find-card "Character Wall" (:hosted (refresh gs-scored)))) (is (zero? (count (:hosted (refresh gs-scored)))))))) (deftest global-food-initiative ;; Global Food Initiative (do-game (new-game (default-contestant [(qty "Global Food Initiative" 2)]) (default-challenger)) (testing "Contestant scores" (is (zero? (:agenda-point (get-challenger))) "Challenger should start with 0 agenda points") (is (zero? (:agenda-point (get-contestant))) "Contestant should start with 0 agenda points") (play-and-score state "Global Food Initiative") (is (= 3 (:agenda-point (get-contestant))) "Contestant should gain 3 agenda points")) (testing "Challenger steals" (play-from-hand state :contestant "Global Food Initiative" "New party") (take-credits state :contestant) (run-on state :party2) (run-successful state) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should gain 2 agenda points, not 3")))) (deftest government-contracts ;; Government Contracts (do-game (new-game (default-contestant ["Government Contracts"]) (default-challenger)) (play-and-score state "Government Contracts") (is (= 2 (:click (get-contestant)))) (card-ability state :contestant (get-scored state :contestant 0) 0) (is (zero? (:click (get-contestant))) "Spent 2 clicks") (is (= 9 (:credit (get-contestant))) "Gained 4 credits"))) (deftest government-takeover ;; Government Takeover (do-game (new-game (default-contestant ["Government Takeover"]) (default-challenger)) (play-and-score state "Government Takeover") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (let [gt-scored (get-scored state :contestant 0)] (card-ability state :contestant gt-scored 0) (is (= 8 (:credit (get-contestant))) "Should gain 3 credits from 5 to 8")))) (deftest graft ;; Graft (letfn [(graft-test [[number-of-picks deck-size]] (let [cards ["Character Wall" "Fire Wall" "Orion"]] (do-game (new-game (default-contestant ["Graft" "Character Wall" "Fire Wall" "Orion"]) (default-challenger)) (starting-hand state :contestant ["Graft"]) (play-and-score state "Graft") (dotimes [current-pick number-of-picks] (prompt-card :contestant (find-card (nth cards current-pick) (:deck (get-contestant))))) (is (= number-of-picks (count (:hand (get-contestant))))) (is (= deck-size (count (:deck (get-contestant))))))))] (doall (map graft-test [[0 3] [1 2] [2 1] [3 0]])))) (deftest hades-fragment ;; Hades Fragment (do-game (new-game (default-contestant ["Hades Fragment" (qty "Hedge Fund" 2)]) (default-challenger)) (starting-hand state :contestant ["Hades Fragment"]) (play-and-score state "Hades Fragment") (take-credits state :contestant) (take-credits state :challenger) (is (= 1 (count (:hand (get-contestant)))) "Contestant should have no opportunity to use Hades Shard") (core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :discard) (take-credits state :contestant) (take-credits state :challenger) (let [hf-scored (get-scored state :contestant 0)] (card-ability state :contestant hf-scored 0) (prompt-select :contestant (find-card "Hedge Fund" (:discard (get-contestant)))) (is (= 2 (count (:deck (get-contestant)))) "R&D should have 2 cards in it after Hades Fragment use")))) (deftest helium-3-deposit ;; Helium-3 Deposit (do-game (new-game (default-contestant ["Helium-3 Deposit" "Chief Slee" "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Chief Slee" "New party") (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (let [cs (get-content state :party1 0) iw (get-character state :hq 0)] (is (zero? (get-counters (refresh cs) :power)) "Chief Slee should start with 0 power counters") (core/reveal state :contestant iw) (run-on state "HQ") (card-ability state :contestant cs 0) (is (= 1 (get-counters (refresh cs) :power)) "Chief Slee should gain 1 power counter") (take-credits state :challenger) (play-and-score state "Helium-3 Deposit") (prompt-choice :contestant "2") (prompt-select :contestant cs) (is (= 3 (get-counters (refresh cs) :power)) "Chief Slee should gain 2 power counters from 1 to 3")))) (deftest high-risk-investment ;; High-Risk Investment (do-game (new-game (default-contestant ["High-Risk Investment"]) (default-challenger)) (play-and-score state "High-Risk Investment") (let [hri-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh hri-scored) :agenda)) "Has 1 agenda counter") (take-credits state :contestant) (is (= 7 (:credit (get-contestant)))) (take-credits state :challenger) (is (= 9 (:credit (get-challenger)))) (card-ability state :contestant hri-scored 0) (is (= 16 (:credit (get-contestant))) "Gained 9 credits") (is (= 2 (:click (get-contestant))) "Spent 1 click") (is (zero? (get-counters (refresh hri-scored) :agenda)) "Spent agenda counter")))) (deftest hollywood-renovation ;; Hollywood Renovation (do-game (new-game (default-contestant ["Hollywood Renovation" "Character Wall"]) (default-challenger)) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "Character Wall" "HQ") (play-from-hand state :contestant "Hollywood Renovation" "New party") (let [hr (get-content state :party1 0) iw (get-character state :hq 0)] (is (zero? (get-counters (refresh hr) :advancement)) "Hollywood Renovation should start with 0 advancement tokens") (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (dotimes [n 5] (advance state (refresh hr)) (prompt-select :contestant (refresh iw))) (is (= 5 (get-counters (refresh hr) :advancement)) "Hollywood Renovation should gain 5 advancement tokens") (is (= 5 (get-counters (refresh iw) :advancement)) "Character Wall should gain 5 advancement tokens") (advance state (refresh hr)) (prompt-select :contestant (refresh iw)) (is (= 6 (get-counters (refresh hr) :advancement)) "Hollywood Renovation should gain 1 from 5 to 6 advancement tokens") (is (= 7 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 from 5 to 7 advancement tokens")))) (deftest hostile-takeover ;; Hostile Takeover (do-game (new-game (default-contestant ["Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Gain 7 credits") (is (= 1 (:bad-publicity (get-contestant))) "Take 1 bad publicity"))) (deftest house-of-knives ;; House of Knives (do-game (new-game (default-contestant ["House of Knives"]) (default-challenger)) (play-and-score state "House of Knives") (let [hok-scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh hok-scored) :agenda)) "House of Knives should start with 3 counters") (take-credits state :contestant) (run-empty-locale state "R&D") (run-phase-43 state) (card-ability state :contestant hok-scored 0) (is (= 1 (count (:discard (get-challenger)))) "Challenger should pay 1 net damage") (run-empty-locale state "R&D") (run-phase-43 state) (card-ability state :contestant hok-scored 0) (card-ability state :contestant hok-scored 0) (is (= 2 (count (:discard (get-challenger)))) "Challenger should pay 1 net damage")))) (deftest ikawah-project ;; Ikawah Project (testing "Basic test" (do-game (new-game (default-contestant ["Ikawah Project"]) (default-challenger)) (play-from-hand state :contestant "Ikawah Project" "New party") (testing "No credits" (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click 3) (run-empty-locale state :party1) (prompt-choice :challenger "No action") (is (zero? (:credit (get-challenger))) "Challenger couldn't afford to steal, so no credits spent") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Ikawah Project")) (testing "No clicks" (take-credits state :challenger) (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click 3) (run-empty-locale state :party1) (prompt-choice :challenger "No action") (is (zero? (:click (get-challenger))) "Challenger couldn't afford to steal, so no clicks spent") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Ikawah Project")) (testing "Enough of both" (take-credits state :challenger) (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click (:click (get-challenger))) (core/gain state :challenger :credit 5 :click 4) (is (= 5 (:credit (get-challenger))) "Challenger should be reset to 5 credits") (is (= 4 (:click (get-challenger))) "Challenger should be reset to 4 clicks") (run-empty-locale state :party1) (prompt-choice-partial :challenger "Pay") (prompt-choice :challenger "[Click]") (prompt-choice :challenger "2 [Credits]") (is (= 2 (:click (get-challenger))) "Challenger should lose 1 click to steal") (is (= 3 (:credit (get-challenger))) "Challenger should lose 2 credits to steal") (is (= 3 (:agenda-point (get-challenger)))) (is (= 1 (count (:scored (get-challenger)))) "Challenger should steal Ikawah Project")))) (testing "Not stealing" ;; do not reveal when the Challenger does not steal from R&D (do-game (new-game (default-contestant [(qty "Ikawah Project" 2)]) (default-challenger)) (take-credits state :contestant) (starting-hand state :contestant ["Ikawah Project"]) (run-empty-locale state "R&D") (prompt-choice :challenger "No action") (is (not (last-log-contains? state "Ikawah Project")) "Ikawah Project should not be mentioned") (run-empty-locale state "HQ") (prompt-choice :challenger "No action") (is (last-log-contains? state "Ikawah Project") "Ikawah Project should be mentioned")))) (deftest illicit-sales ;; Illicit Sales (letfn [(illicit-sales-test [[starting-bp answer credits-gained]] (testing (str "starting with " starting-bp " and answering " answer " and gaining " credits-gained) (do-game (new-game (default-contestant ["Illicit Sales"]) (default-challenger)) (let [credits (:credit (get-contestant))] (core/gain state :contestant :bad-publicity starting-bp) (play-and-score state "Illicit Sales") (prompt-choice :contestant answer) (is (= (:credit (get-contestant)) (+ credits credits-gained)))))))] (doall (map illicit-sales-test [[0 "No" 0] [0 "Yes" 3] [1 "No" 3] [1 "Yes" 6] [2 "No" 6] [2 "Yes" 9] [3 "No" 9] [3 "Yes" 12]])))) (deftest improved-protein-source ;; Improved Protein Source (do-game (new-game (default-contestant [(qty "Improved Protein Source" 2)]) (default-challenger)) (is (= 5 (:credit (get-challenger))) "Challenger starts with 5 credits") (play-and-score state "Improved Protein Source") (is (= 9 (:credit (get-challenger))) "Challenger should gain 4 credits from Contestant scoring") (play-from-hand state :contestant "Improved Protein Source" "New party") (take-credits state :contestant) (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (is (= 13 (:credit (get-challenger))) "Challenger should gain 4 credits from Contestant scoring"))) (deftest improved-tracers ;; Improved Tracers (do-game (new-game (default-contestant ["Improved Tracers" "News Hound"]) (default-challenger)) (play-from-hand state :contestant "News Hound" "HQ") (let [nh (get-character state :hq 0)] (core/reveal state :contestant nh) (is (= 4 (:current-strength (refresh nh))) "Should start with base strength of 4") (is (= 3 (:credit (get-contestant))) "Should have 2 credits after reveal") (play-and-score state "Improved Tracers") (is (= 5 (:current-strength (refresh nh))) "Should gain 1 strength from 4 to 5") (take-credits state :contestant) (run-on state "HQ") (run-phase-43 state) (card-subroutine state :contestant nh 0) (is (= 1 (get-in @state [:bonus :trace])) "Should gain 1 bonus trace strength") (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 1 (:tag (get-challenger))))))) (deftest labyrinthine-locales ;; Labyrinthine Locales (do-game (new-game (default-contestant [(qty "Labyrinthine Locales" 2)]) (default-challenger)) (play-and-score state "Labyrinthine Locales") (play-and-score state "Labyrinthine Locales") (take-credits state :contestant) (let [ls1 (get-scored state :contestant 0) ls2 (get-scored state :contestant 1)] (is (= 2 (get-counters (refresh ls1) :power))) (is (= 2 (get-counters (refresh ls2) :power))) (testing "Don't use token" (run-on state "HQ") (run-jack-out state) (is (:run @state) "Jack out prevent prompt") (prompt-choice :contestant "Done") (is (not (:run @state)) "Contestant does not prevent the jack out, run ends")) (testing "Use token" (run-on state "HQ") (run-jack-out state) (card-ability state :contestant ls1 0) (card-ability state :contestant ls2 0) (card-ability state :contestant ls1 0) (prompt-choice :contestant "Done") (is (:run @state) "Jack out prevented, run is still ongoing") (is (true? (get-in @state [:run :cannot-jack-out])) "Cannot jack out flag is in effect") (run-successful state) (is (not (:run @state)))) (testing "one Labyrinthine is empty but the other still has one token, ensure prompt still occurs" (is (zero? (get-counters (refresh ls1) :power))) (is (= 1 (get-counters (refresh ls2) :power))) (run-on state "HQ") (run-jack-out state) (is (:run @state)) (card-ability state :contestant ls2 0) (prompt-choice :contestant "Done") (is (true? (get-in @state [:run :cannot-jack-out]))) (run-successful state) (is (not (:run @state)))) (testing "No more tokens" (run-on state "HQ") (run-jack-out state) (is (not (:run @state)) "No jack out prevent prompt"))))) (deftest lcharacternse-acquisition ;; Lcharacternse Acquisition (do-game (new-game (default-contestant [(qty "Lcharacternse Acquisition" 4) "Adonis Campaign" "Eve Campaign" "Strongbox" "Contestantorate Troubleshooter"]) (default-challenger)) (testing "Set up" (starting-hand state :contestant ["Lcharacternse Acquisition" "Lcharacternse Acquisition" "Lcharacternse Acquisition" "Lcharacternse Acquisition" "Adonis Campaign" "Strongbox"]) (core/move state :contestant (find-card "Eve Campaign" (:deck (get-contestant))) :discard) (core/move state :contestant (find-card "Contestantorate Troubleshooter" (:deck (get-contestant))) :discard) (core/gain state :contestant :click 4)) (testing "Site & HQ" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Adonis Campaign" (:hand (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party2 0)))) (testing "Region & HQ" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Strongbox" (:hand (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party4 0)))) (testing "Site & Archives" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Eve Campaign" (:discard (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party6 0)))) (testing "Region & Archives" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Contestantorate Troubleshooter" (:discard (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party8 0)))))) (deftest mandatory-seed-replacement ;; Mandatory Seed Replacement (do-game (new-game (default-contestant ["Mandatory Seed Replacement" "Character Wall" "Fire Wall" "Kakugo" "Chum" "RSVP" "Sensei"]) (default-challenger)) (core/click-draw state :contestant 2) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "Character Wall" "Archives") (play-from-hand state :contestant "Fire Wall" "R&D") (play-from-hand state :contestant "Kakugo" "HQ") (play-from-hand state :contestant "Chum" "Archives") (play-from-hand state :contestant "RSVP" "R&D") (play-from-hand state :contestant "Sensei" "HQ") (let [iw (get-character state :archives 0) fw (get-character state :rd 0) kk (get-character state :hq 0) ch (get-character state :archives 1) rs (get-character state :rd 1) sn (get-character state :hq 1)] (core/reveal state :contestant iw) (core/reveal state :contestant fw) (core/reveal state :contestant kk) (core/reveal state :contestant ch) (core/reveal state :contestant rs) (core/reveal state :contestant sn) (play-and-score state "Mandatory Seed Replacement") (prompt-select :contestant (refresh iw)) (prompt-select :contestant (refresh fw)) (prompt-select :contestant (refresh kk)) (prompt-select :contestant (refresh ch)) (prompt-select :contestant (refresh rs)) (prompt-select :contestant (refresh sn))))) (deftest mandatory-regions ;; Mandatory Regions (testing "Gain an additional click" (do-game (new-game (default-contestant ["Mandatory Regions" "Melange Mining Contestant."]) (default-challenger)) (play-and-score state "Mandatory Regions") (is (= 2 (:agenda-point (get-contestant)))) (play-from-hand state :contestant "Melange Mining Contestant." "New party") (let [mmc (get-content state :party2 0)] (core/reveal state :contestant mmc) (take-credits state :contestant) (take-credits state :challenger) (is (= 4 (:click (get-contestant)))) (card-ability state :contestant mmc 0) (is (= 1 (:click (get-contestant))))))) (testing "Lose additional click if sacrifcharacterd" (do-game (new-game (default-contestant ["Mandatory Regions" "Archer"]) (default-challenger)) (play-and-score state "Mandatory Regions") (is (= 2 (:agenda-point (get-contestant)))) (play-from-hand state :contestant "Archer" "HQ") (take-credits state :contestant) (take-credits state :challenger) (let [arc (get-character state :hq 0) mu (get-scored state :contestant 0)] (is (= 4 (:click (get-contestant))) "Contestant should start turn with 4 clicks") (core/reveal state :contestant arc) (prompt-select :contestant (refresh mu)) (is (= 3 (:click (get-contestant))) "Contestant should lose 1 click on agenda sacrifcharacter"))))) (deftest market-research ;; Market Research (do-game (new-game (default-contestant [(qty "Market Research" 2)]) (default-challenger)) (testing "Challenger is not tagged" (play-and-score state "Market Research") (is (= 2 (:agenda-point (get-contestant))) "Only 4 advancements: scored for standard 2 points")) (testing "Challenger is tagged" (core/gain state :challenger :tag 1) (play-and-score state "Market Research") (is (= 5 (:agenda-point (get-contestant))) "5 advancements: scored for 3 points")))) (deftest medical-breakthrough ;; Medical Breakthrough (do-game (new-game (default-contestant [(qty "Medical Breakthrough" 3) (qty "Hedge Fund" 3)]) (default-challenger)) (play-from-hand state :contestant "Medical Breakthrough" "New party") (play-from-hand state :contestant "Medical Breakthrough" "New party") (play-from-hand state :contestant "Hedge Fund") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (take-credits state :challenger) (let [mb2 (get-content state :party2 0)] (advance state mb2 3) (core/score state :contestant {:card (refresh mb2)}) (is (= 2 (:agenda-point (get-contestant))) "Only needed 3 advancements to score")) (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Medical Breakthrough" "New party") (let [mb3 (get-content state :party3 0)] (advance state mb3 2) (core/score state :contestant {:card (refresh mb3)}) (is (= 4 (:agenda-point (get-contestant))) "Only needed 2 advancements to score")))) (deftest merger ;; Merger (do-game (new-game (default-contestant [(qty "Merger" 2)]) (default-challenger)) (play-and-score state "Merger") (is (= 2 (:agenda-point (get-contestant))) "Contestant should score 2 points") (play-from-hand state :contestant "Merger" "New party") (take-credits state :contestant) (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (is (= 3 (:agenda-point (get-challenger))) "Challenger should score 3 points"))) (deftest meteor-mining ;; Meteor Mining (testing "when Meteor Mining is stolen" (do-game (new-game (default-contestant ["Meteor Mining"]) (default-challenger)) (play-from-hand state :contestant "Meteor Mining" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should score 2 points"))) (testing "when Meteor Mining is scored" (letfn [(meteor-mining-test [[tags num-choices pick creds dmg]] (do-game (new-game (default-contestant ["Meteor Mining"]) (default-challenger [(qty "Sure Gamble" 7)])) (starting-hand state :challenger (repeat 7 "Sure Gamble")) (let [credits (:credit (get-contestant)) grip (count (:hand (get-challenger)))] (core/gain state :challenger :tag tags) (play-and-score state "Meteor Mining") (is (= num-choices (count (:choices (first (get-in @state [:contestant :prompt])))))) (prompt-choice :contestant pick) (is (= (+ credits creds) (:credit (get-contestant))) (str "Contestant should have " (+ credits creds) " credits")) (is (= (- grip dmg) (count (:hand (get-challenger)))) (str "Challenger should have " (- grip dmg) " cards in hand")))))] (doall (map meteor-mining-test [[0 2 "No action" 0 0] [0 2 "Gain 7 [Credits]" 7 0] [1 2 "No action" 0 0] [1 2 "Gain 7 [Credits]" 7 0] [2 3 "No action" 0 0] [2 3 "Gain 7 [Credits]" 7 0] [2 3 "Do 7 meat damage" 0 7] [3 3 "No action" 0 0] [3 3 "Gain 7 [Credits]" 7 0] [3 3 "Do 7 meat damage" 0 7]]))))) (deftest napd-contract ;; NAPD Contract (testing "basic test" (do-game (new-game (default-contestant ["NAPD Contract"]) (default-challenger)) (play-from-hand state :contestant "NAPD Contract" "New party") (let [napd (get-content state :party1 0)] (advance state napd 2) (take-credits state :contestant) (core/lose state :challenger :credit 2) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal NAPD Contract") (is (= 3 (:credit (get-challenger))) "Challenger couldn't afford to steal, so no credits spent") (take-credits state :challenger) (core/gain state :contestant :bad-publicity 1) (advance state napd 2) (core/score state :contestant {:card (refresh napd)}) (is (some? (get-content state :party1 0)) "Contestant can't score with 4 advancements because of BP") (advance state napd) (core/score state :contestant {:card (refresh napd)}) (is (= 2 (:agenda-point (get-contestant))) "Scored NAPD for 2 points after 5 advancements")))) (testing "scoring requirement increases with bad publicity from Contestantorate Scandal" (do-game (new-game (default-contestant ["NAPD Contract"]) (default-challenger ["Contestantorate Scandal"])) (play-from-hand state :contestant "NAPD Contract" "New party") (let [napd (get-content state :party1 0)] (advance state napd 2) (take-credits state :contestant) (play-from-hand state :challenger "Contestantorate Scandal") (take-credits state :challenger) (advance state napd 2) (core/score state :contestant {:card (refresh napd)}) (is (some? (get-content state :party1 0)) "Contestant can't score with 4 advancements because of BP") (advance state napd) (core/score state :contestant {:card (refresh napd)}) (is (= 2 (:agenda-point (get-contestant))) "Scored NAPD for 2 points after 5 advancements"))))) (deftest net-quarantine ;; Net Quarantine (do-game (new-game (default-contestant ["Net Quarantine"]) (default-challenger)) (core/gain state :challenger :link 1) (core/gain state :contestant :click 3) (play-and-score state "Net Quarantine") (is (= 5 (:credit (get-contestant))) "Contestant has 5 credits") (is (= 1 (:link (get-challenger))) "Challenger has 1 link") (core/init-trace state :contestant {:title "/trace command" :side :contestant} {:base 1}) (prompt-choice :contestant 0) (is (zero? (:link (get-challenger))) "Challenger has 0 link") (prompt-choice :challenger 3) (is (= 1 (:link (get-challenger))) "Challenger has 1 link again") (is (= 6 (:credit (get-contestant))) "Contestant gained a credit from NQ") ; second trace of turn - no link reduction (core/init-trace state :contestant {:title "/trace command" :side :contestant} {:base 1}) (prompt-choice :contestant 0) (is (= 1 (:link (get-challenger))) "Challenger has 1 link") (prompt-choice :challenger 2) (is (= 7 (:credit (get-contestant))) "Contestant gained a credit from NQ"))) (deftest new-construction ;; New Construction (do-game (new-game (default-contestant ["New Construction" (qty "Commercial Bankers Group" 10)]) (default-challenger)) (starting-hand state :contestant (vec (cons "New Construction" (repeat 10 "Commercial Bankers Group")))) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "New Construction" "New party") (let [nc (get-content state :party1 0)] (is (zero? (get-counters (refresh nc) :advancement))) (dotimes [n 4] (advance state (refresh nc)) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Commercial Bankers Group" (:hand (get-contestant))))) (is (= 4 (get-counters (refresh nc) :advancement))) (is (not= :this-turn (:revealed (get-content state :party5 0)))) (let [credits (:credit (get-contestant))] (advance state (refresh nc)) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Commercial Bankers Group" (:hand (get-contestant)))) (is (= 5 (get-counters (refresh nc) :advancement))) (is (= :this-turn (:revealed (get-content state :party6 0)))) (is (= (dec credits) (:credit (get-contestant)))))))) (deftest next-wave-2 ;; NEXT Wave 2 (do-game (new-game (default-contestant [(qty "NEXT Wave 2" 2) "NEXT Bronze"]) (default-challenger)) (is (zero? (:brain-damage (get-challenger))) "Challenger should start with 0 brain damage") (play-from-hand state :contestant "NEXT Bronze" "HQ") (let [nxbr (get-character state :hq 0)] (core/reveal state :contestant nxbr)) (play-and-score state "NEXT Wave 2") (prompt-choice :contestant "No") (is (zero? (:brain-damage (get-challenger))) "Challenger should stay at 0 brain damage") (play-and-score state "NEXT Wave 2") (prompt-choice :contestant "Yes") (is (= 1 (:brain-damage (get-challenger))) "Challenger should gain 1 brain damage"))) (deftest nisei-mk-ii ;; Nisei MK II - Remove hosted counter to ETR, check this works in 4.3 (do-game (new-game (default-contestant ["Nisei MK II"]) (default-challenger)) (play-and-score state "Nisei MK II") (let [scored-nisei (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh scored-nisei) :agenda)) "Scored Nisei has one counter") (take-credits state :contestant) (run-on state "HQ") (run-phase-43 state) (card-ability state :contestant (refresh scored-nisei) 0) (prompt-choice :contestant "Done") ; close 4.3 contestant (is (not (:run @state)) "Run ended by using Nisei counter") (is (zero? (get-counters (refresh scored-nisei) :agenda)) "Scored Nisei has no counters")))) (deftest oaktown-renovation ;; Oaktown Renovation (do-game (new-game (default-contestant ["Oaktown Renovation" "Shipment from SanSan"]) (default-challenger)) (core/gain state :contestant :click 3) (play-from-hand state :contestant "Oaktown Renovation" "New party") (let [oak (get-content state :party1 0)] (is (:revealed (refresh oak)) "Oaktown placed face up") (advance state oak) (is (= 6 (:credit (get-contestant))) "Spent 1 credit to advance, gained 2 credits from Oaktown") (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant oak) (is (= 3 (get-counters (refresh oak) :advancement))) (is (= 6 (:credit (get-contestant))) "No credits gained due to advancements being placed") (advance state oak) (is (= 7 (:credit (get-contestant))) "Spent 1 credit to advance, gained 2 credits from Oaktown") (advance state oak) (is (= 5 (get-counters (refresh oak) :advancement))) (is (= 9 (:credit (get-contestant))) "Spent 1 credit to advance, gained 3 credits from Oaktown")))) (deftest obokata-protocol ;; Obotaka Protocol (do-game (new-game (make-deck "Cardnum: Personal Evolution" [(qty "Obokata Protocol" 10)]) (default-challenger [(qty "Sure Gamble" 4)])) (play-from-hand state :contestant "Obokata Protocol" "New party") (take-credits state :contestant) (core/gain state :challenger :agenda-point 6) (run-empty-locale state "Locale 1") (prompt-choice-partial :challenger "Pay") (is (= 4 (count (:discard (get-challenger)))) "Challenger paid 4 net damage") (is (= :challenger (:winner @state)) "Challenger wins") (is (= "Agenda" (:reason @state)) "Win condition reports agenda points") (is (last-log-contains? state "wins the game") "PE did not fire"))) (deftest paper-trail ;; Paper Trail (do-game (new-game (default-contestant ["Paper Trail"]) (default-challenger ["Aeneas Informant" "Bank Job" "Rosetta 2.0" "Magnum Opus" "Astrolabe"])) (take-credits state :contestant) (core/gain state :challenger :click 10 :credit 10) (play-from-hand state :challenger "Aeneas Informant") (play-from-hand state :challenger "Bank Job") (play-from-hand state :challenger "Rosetta 2.0") (play-from-hand state :challenger "Magnum Opus") (play-from-hand state :challenger "Astrolabe") (take-credits state :challenger) (play-and-score state "Paper Trail") (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 2 (count (:discard (get-challenger))))) (is (some? (get-radicle state 0))) (is (= 1 (count (get-radicle state)))) (is (some? (get-resource state 0))) (is (some? (get-hazard state 0))))) (deftest personality-profiles ;; Personality Profiles (testing "basic test" (do-game (new-game (default-contestant ["Personality Profiles"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" (qty "Patron" 2)])) (starting-hand state :challenger ["Self-modifying Code" "Clone Chip" "Patron" "Patron"]) (play-and-score state "Personality Profiles") (take-credits state :contestant) (play-from-hand state :challenger "Self-modifying Code") (play-from-hand state :challenger "Clone Chip") (let [smc (get-resource state 0)] (card-ability state :challenger smc 0) (prompt-card :challenger (find-card "Corroder" (:deck (get-challenger)))) (is (= 2 (count (:discard (get-challenger)))))) (let [chip (get-hazard state 0)] (card-ability state :challenger chip 0) (prompt-select :challenger (find-card "Self-modifying Code" (:discard (get-challenger)))) (is (second-last-log-contains? state "Patron") "Personality Profiles discarded card name is in log") (is (= 3 (count (:discard (get-challenger)))))))) (testing "Ensure effects still fire with an empty hand, #1840" (do-game (new-game (default-contestant ["Personality Profiles"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder"])) (starting-hand state :challenger ["Self-modifying Code" "Clone Chip"]) (play-and-score state "Personality Profiles") (take-credits state :contestant) (play-from-hand state :challenger "Self-modifying Code") (play-from-hand state :challenger "Clone Chip") (let [smc (get-resource state 0)] (card-ability state :challenger smc 0) (prompt-card :challenger (find-card "Corroder" (:deck (get-challenger))))) (let [cor (get-resource state 0)] (is (some? cor)) (is (= (:title cor) "Corroder")) (is (= "Self-modifying Code" (:title (first (:discard (get-challenger))))))) (let [chip (get-hazard state 0)] (card-ability state :challenger chip 0) (prompt-select :challenger (find-card "Self-modifying Code" (:discard (get-challenger))))) (let [smc (get-resource state 1)] (is (some? smc)) (is (= (:title smc) "Self-modifying Code")) (is (= "Clone Chip" (:title (first (:discard (get-challenger)))))))))) (deftest philotic-entanglement ;; Philotic Entanglement (do-game (new-game (default-contestant ["Philotic Entanglement" (qty "House of Knives" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Cache" 2)])) (play-from-hand state :contestant "House of Knives" "New party") (play-from-hand state :contestant "House of Knives" "New party") (play-from-hand state :contestant "House of Knives" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (run-empty-locale state :party3) (prompt-choice :challenger "Steal") (is (= 3 (count (:scored (get-challenger))))) (take-credits state :challenger) (play-and-score state "Philotic Entanglement") (is (= 2 (:agenda-point (get-contestant)))) (is (= 3 (count (:discard (get-challenger)))) "Dealt 3 net damage upon scoring"))) (deftest posted-bounty ;; Posted Bounty (testing "Forfeiting takes 1 bad publicity" (do-game (new-game (default-contestant ["Posted Bounty"]) (default-challenger)) (play-and-score state "Posted Bounty") (prompt-choice :contestant "Yes") (is (zero? (:agenda-point (get-contestant))) "Forfeiting Posted Bounty nullifies agenda points") (is (= 1 (:bad-publicity (get-contestant))) "Forfeiting takes 1 bad publicity") (is (= 1 (:tag (get-challenger))) "Challenger receives 1 tag forfeiting Posted Bounty"))) (testing "Choosing not to forfeit scores normally" (do-game (new-game (default-contestant ["Posted Bounty"]) (default-challenger)) (play-and-score state "Posted Bounty") (prompt-choice :contestant "No") (is (= 1 (:agenda-point (get-contestant)))) (is (zero? (:bad-publicity (get-contestant)))) (is (zero? (:tag (get-challenger))))))) (deftest priority-requisition ;; Priority Requisition (do-game (new-game (default-contestant ["Priority Requisition" "Archer"]) (default-challenger)) (play-from-hand state :contestant "Archer" "HQ") (let [arc (get-character state :hq 0)] (play-and-score state "Priority Requisition") (prompt-select :contestant arc) (is (:revealed (refresh arc)))))) (deftest private-security-force ;; Private Security Force (do-game (new-game (default-contestant [(qty "Private Security Force" 10)]) (default-challenger)) (core/gain state :challenger :tag 1) (play-and-score state "Private Security Force") (let [psf-scored (get-scored state :contestant 0)] (card-ability state :contestant psf-scored 0) (is (= 1 (count (:discard (get-challenger))))) (take-credits state :challenger) (dotimes [n 3] (card-ability state :contestant psf-scored 0)) (is (= 3 (count (:discard (get-challenger))))) (is (= :contestant (:winner @state)) "Contestant wins") (is (= "Flatline" (:reason @state)) "Win condition reports flatline")))) (deftest profiteering ;; Profiteering (do-game (new-game (default-contestant ["Profiteering"]) (default-challenger)) (play-and-score state "Profiteering") (prompt-choice :contestant "3") (is (= 1 (:agenda-point (get-contestant)))) (is (= 3 (:bad-publicity (get-contestant))) "Took 3 bad publicity") (is (= 20 (:credit (get-contestant))) "Gained 15 credits"))) (deftest project-ares ;; Project Ares (do-game (new-game (default-contestant [(qty "Project Ares" 2)]) (default-challenger ["Clone Chip"])) (take-credits state :contestant) (play-from-hand state :challenger "Clone Chip") (take-credits state :challenger) (play-and-score state "Project Ares") (is (empty? (get-in @state [:challenger :prompt])) "No prompt for Challenger if scored with 4 advancement tokens") (core/gain state :contestant :click 5) (play-from-hand state :contestant "Project Ares" "New party") (let [ares (get-content state :party2 0)] (advance state ares 6) (is (= 6 (get-counters (refresh ares) :advancement))) (core/score state :contestant {:card (refresh ares)}) (is (prompt-is-card? :challenger ares) "Challenger has Ares prompt to discard placed cards")) (prompt-select :challenger (find-card "Clone Chip" (:hazard (:rig (get-challenger))))) (is (empty? (get-in @state [:challenger :prompt])) "Challenger must discard 2 cards but only has 1 card in rig, prompt ended") (is (= 1 (count (:discard (get-challenger))))) (is (= 1 (:bad-publicity (get-contestant)))))) (deftest project-atlas ;; Project Atlas (testing "basic test" (do-game (new-game (default-challenger ["Project Atlas" "Beanstalk Royalties"]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Project Atlas"]) (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party1 0)] (advance state atlas 4) (is (= 4 (get-counters (refresh atlas) :advancement)) "Atlas should have 4 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant)))) (is (zero? (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 0 agenda counters") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand")))) (testing "test with Titan" (do-game (new-game (make-deck "Titan Transnational: Investing In Your Future" [(qty "Project Atlas" 2) "Beanstalk Royalties" "Hedge Fund"]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Project Atlas" "Project Atlas"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party1 0)] (advance state atlas 3) (is (= 3 (get-counters (refresh atlas) :advancement)) "Atlas should have 3 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant)))) (is (zero? (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 0 agenda counters") (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 card in hand")) ;; Should gain 2 counters (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party2 0)] (advance state atlas 4) (is (= 4 (get-counters (refresh atlas) :advancement)) "Atlas should have 4 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 1)] (is (= 2 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 2 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Hedge Fund" (:deck (get-contestant)))) (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counters") (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 cards in hand"))))) (deftest project-beale ;; Project Beale (do-game (new-game (default-contestant [(qty "Project Beale" 2)]) (default-challenger)) (core/gain state :contestant :click 8 :credit 8) (play-from-hand state :contestant "Project Beale" "New party") (let [pb1 (get-content state :party1 0)] (advance state pb1 4) (core/score state :contestant {:card (refresh pb1)}) (is (= 2 (:agenda-point (get-contestant))) "Only 4 advancements: scored for standard 2 points") (play-from-hand state :contestant "Project Beale" "New party")) (let [pb2 (get-content state :party2 0)] (advance state pb2 5) (core/score state :contestant {:card (refresh pb2)}) (is (= 5 (:agenda-point (get-contestant))) "5 advancements: scored for 3 points")))) (deftest project-kusanagi ;; Project Kusanagi (do-game (new-game (default-contestant [(qty "Project Kusanagi" 2) "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (core/gain state :contestant :click 10 :credit 10) (testing "Should gain 0 counters" (play-and-score state "Project Kusanagi") (let [pk-scored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh pk-scored) :agenda)) "Kusanagi should start with 0 agenda counters"))) (testing "Should gain 1 counter" (play-from-hand state :contestant "Project Kusanagi" "New party") (let [pk (get-content state :party2 0)] (advance state pk 3) (is (= 3 (get-counters (refresh pk) :advancement)) "Kusanagi should have 3 advancement tokens") (core/score state :contestant {:card (refresh pk)})) (let [pk-scored (get-scored state :contestant 1)] (is (= 1 (get-counters (refresh pk-scored) :agenda)) "Kusanagi should have 1 agenda counter") (run-empty-locale state :hq) (card-ability state :contestant pk-scored 0) (is (last-log-contains? state "Do 1 net damage")) (is (zero? (get-counters (refresh pk-scored) :agenda)) "Kusanagi should have 0 agenda counters"))))) (deftest project-vitruvius ;; Project Vitruvius (do-game (new-game (default-contestant ["Project Vitruvius" "Hedge Fund"]) (default-challenger)) ;; Set up (core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :discard) (is (= 1 (count (:discard (get-contestant)))) "Contestant should have 1 cards in hand") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Vitruvius" "New party") (let [vit (get-content state :party1 0)] (advance state vit 4) (is (= 4 (get-counters (refresh vit) :advancement)) "Vitruvius should have 4 advancement tokens") (core/score state :contestant {:card (refresh vit)})) (let [vit-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh vit-scored) :agenda)) "Vitruvius should have 1 agenda counter") (card-ability state :contestant vit-scored 0) (prompt-select :contestant (find-card "Hedge Fund" (:discard (get-contestant)))) (is (zero? (get-counters (refresh vit-scored) :agenda)) "Vitruvius should have 0 agenda counters") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand")))) (deftest project-wotan ;; Project Wotan - Only checks if agenda counter is spent (do-game (new-game (default-contestant ["Project Wotan" "Eli 1.0" (qty "Hedge Fund" 3)]) (default-challenger)) (starting-hand state :contestant ["Project Wotan" "Eli 1.0"]) (play-from-hand state :contestant "Eli 1.0" "HQ") (let [eli (get-character state :hq 0)] (core/reveal state :contestant eli)) (play-and-score state "Project Wotan") (take-credits state :contestant) (let [wot-scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh wot-scored) :agenda)) "Wotan should start with 3 agenda counters") (run-on state "HQ") (card-ability state :contestant wot-scored 0) (is (= 2 (get-counters (refresh wot-scored) :agenda))) "Wotan should only have 2 agenda counters"))) (deftest puppet-master ;; Puppet Master - game progresses if no valid targets. Issue #1661. (do-game (new-game (default-contestant ["Puppet Master"]) (default-challenger)) (play-and-score state "Puppet Master") (take-credits state :contestant) (run-empty-locale state :archives) (prompt-choice :contestant "Done") (is (empty? (:prompt (get-challenger))) "Challenger's waiting prompt resolved"))) (deftest quantum-predictive-model ;; Quantum Predictive Model (do-game (new-game (default-contestant [(qty "Quantum Predictive Model" 4)]) (default-challenger)) (testing "Set up" (starting-hand state :contestant ["Quantum Predictive Model" "Quantum Predictive Model"]) (play-from-hand state :contestant "Quantum Predictive Model" "New party") (play-from-hand state :contestant "Quantum Predictive Model" "New party") (take-credits state :contestant)) (testing "Access placed with no tag" (run-on state :party1) (run-successful state) (prompt-choice :challenger "Steal") (is (= 1 (:agenda-point (get-challenger))) "Challenger should steal")) (testing "Access R&D with no tag" (run-on state :rd) (run-successful state) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should steal")) (core/gain state :challenger :tag 1) (testing "Access intalled with tag" (run-on state :party2) (run-successful state) (prompt-choice :challenger "No action") ;; this is now a prompt that QPM was added to Contestant score area (is (= 2 (:agenda-point (get-challenger))) "Challenger should not steal") (is (= 1 (:agenda-point (get-contestant))) "Contestant should score")) (testing "Access R&D with tag" (run-on state :rd) (run-successful state) (prompt-choice :challenger "No action") (is (= 2 (:agenda-point (get-challenger))) "Challenger should not steal") (is (= 2 (:agenda-point (get-contestant))) "Contestant should score")) (is (zero? (count (:deck (get-contestant))))))) (deftest rebranding-team ;; Rebranding Team (do-game (new-game (default-contestant ["Rebranding Team" "Launch Campaign" "City Surveillance" "Jackson Howard" "Museum of History" "Advanced Assembly Lines"]) (default-challenger)) (play-and-score state "Rebranding Team") (core/click-draw state :challenger 1) (is (core/has-subtype? (find-card "Advanced Assembly Lines" (:hand (get-contestant))) "Advertisement")) ; #2608 part 2 - retain Advertisement always (discard-from-hand state :contestant "Advanced Assembly Lines") (is (core/has-subtype? (find-card "Advanced Assembly Lines" (:discard (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "Launch Campaign" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "City Surveillance" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "Jackson Howard" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "Jackson Howard" (:hand (get-contestant))) "Executive")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Alliance")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Ritzy")) (core/move state :contestant (find-card "Rebranding Team" (:scored (get-contestant))) :deck) (is (core/has-subtype? (find-card "Launch Campaign" (:hand (get-contestant))) "Advertisement")) (is (not (core/has-subtype? (find-card "Advanced Assembly Lines" (:discard (get-contestant))) "Advertisement"))) (is (not (core/has-subtype? (find-card "City Surveillance" (:hand (get-contestant))) "Advertisement"))) (is (not (core/has-subtype? (find-card "Jackson Howard" (:hand (get-contestant))) "Advertisement"))) (is (core/has-subtype? (find-card "Jackson Howard" (:hand (get-contestant))) "Executive")) (is (not (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Advertisement"))) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Alliance")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Ritzy")))) (deftest reeducation ;; Reeducation (testing "Simple test" (do-game (new-game (default-contestant ["Reeducation" "Sweeps Week" "Hedge Fund" "Jackson Howard" "Gutenberg"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" "Sure Gamble" "Desperado"])) (starting-hand state :contestant ["Reeducation" "Sweeps Week"]) (starting-hand state :challenger ["Self-modifying Code"]) (play-and-score state "Reeducation") (is (prompt-is-type? :challenger :waiting) "Challenger has wait prompt") (is (= 1 (count (get-in @state [:contestant :hand])))) (is (= 1 (count (get-in @state [:challenger :hand])))) (prompt-card :contestant (find-card "Sweeps Week" (:hand (get-contestant)))) ; put Sweeps Week at bottom of R&D (prompt-choice :contestant "Done") ; finished selecting cards (prompt-choice :contestant "Done") ; contestant prompt for Done/Start Over (is (= "Sweeps Week" (:title (last (:deck (get-contestant)))))) (is (= "Self-modifying Code" (:title (last (:deck (get-challenger)))))) (is (= 1 (count (get-in @state [:contestant :hand])))) (is (zero? (count (get-in @state [:challenger :hand])))))) (testing "Extra cards" ;; If Contestant is adding more cards in HQ than Challenger has in their Grip, Challenger ;; is not 'able' to resolve the effect and doesn't have to add to bottom of Stack (do-game (new-game (default-contestant ["Reeducation" "Sweeps Week" "Hedge Fund" "Jackson Howard" "Gutenberg"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" "Sure Gamble" "Desperado"])) (starting-hand state :contestant ["Reeducation" "Sweeps Week" "Hedge Fund"]) (starting-hand state :challenger ["Self-modifying Code"]) (play-and-score state "Reeducation") (is (prompt-is-type? :challenger :waiting) "Challenger has wait prompt") (is (= 2 (count (:hand (get-contestant))))) (is (= 1 (count (:hand (get-challenger))))) (prompt-card :contestant (find-card "Sweeps Week" (:hand (get-contestant)))) (prompt-card :contestant (find-card "Hedge Fund" (:hand (get-contestant)))) ; this is the bottom card of R&D (prompt-choice :contestant "Done") ; finished selecting cards (prompt-choice :contestant "Done") ; contestant prompt for Done/Start Over (is (= "Hedge Fund" (:title (last (:deck (get-contestant)))))) (is (= "Sweeps Week" (:title (last (butlast (:deck (get-contestant))))))) (is (= "Self-modifying Code" (:title (first (:hand (get-challenger)))))) (is (= 2 (count (:hand (get-contestant))))) (is (= 1 (count (:hand (get-challenger)))))))) (deftest party-data-farm ;; Party Data Farm (do-game (new-game (default-contestant ["Party Data Farm"]) (default-challenger)) (is (= 5 (get-hand-size :contestant))) (play-and-score state "Party Data Farm") (is (= 7 (get-hand-size :contestant))))) (deftest party-enforcement ;; Party Enforcement - Search R&D for a piece of character and place it on a party at no reveal cost (do-game (new-game (default-contestant [(qty "Party Enforcement" 2) "Archer" "Chiyashi"]) (make-deck "Reina Roja: Freedom Fighter" [])) (starting-hand state :contestant ["Party Enforcement" "Party Enforcement"]) (is (= 2 (count (:deck (get-contestant))))) (play-and-score state "Party Enforcement") (let [N (:credit (get-contestant))] (prompt-choice :contestant "Yes") (prompt-choice :contestant (find-card "Chiyashi" (:deck (get-contestant)))) (prompt-choice :contestant "New party") (is (core/revealed? (get-character state :party2 0)) "Chiyashi was placed revealed") (is (= N (:credit (get-contestant))) "Revealing Chiyashi was free")) (play-and-score state "Party Enforcement") (let [N (:credit (get-contestant))] (prompt-choice :contestant "Yes") (prompt-card :contestant (find-card "Archer" (:deck (get-contestant)))) (prompt-choice :contestant "Locale 2") (is (= (dec N) (:credit (get-contestant))) "Placing Archer cost a credit") (is (not-empty (:prompt (get-contestant))) "Contestant prompted to forfeit an agenda for Archer") (is (= (dec N) (:credit (get-contestant))) "Revealing Archer didn't cost any credits")))) (deftest research-grant ;; Research Grant (testing "Basic test" (do-game (new-game (default-contestant [(qty "Research Grant" 2)]) (default-challenger)) (play-from-hand state :contestant "Research Grant" "New party") (play-and-score state "Research Grant") (prompt-select :contestant (get-content state :party1 0)) (is (= 2 (count (:scored (get-contestant)))) "2 copies of Research Grant scored"))) (testing "vs Leela" ;; Issue #3069 (do-game (new-game (default-contestant [(qty "Research Grant" 2) (qty "Character Wall" 2)]) (make-deck "Leela Patel: Trained Pragmatist" ["Sure Gamble"])) (core/gain state :contestant :click 1) (play-from-hand state :contestant "Character Wall" "HQ") (play-from-hand state :contestant "Character Wall" "R&D") (play-from-hand state :contestant "Research Grant" "New party") (play-and-score state "Research Grant") (prompt-select :contestant (get-content state :party1 0)) (is (= 2 (count (:scored (get-contestant)))) "2 copies of Research Grant scored") (prompt-select :challenger (get-character state :hq 0)) (prompt-select :challenger (get-character state :rd 0)) (is (empty? (:effect-completed @state)) "All score and Leela effects resolved")))) (deftest restructured-datapool ;; Restructured Datapool (do-game (new-game (default-contestant ["Restructured Datapool"]) (default-challenger)) (is (zero? (:tag (get-challenger))) "Challenger should start with no tags") (play-and-score state "Restructured Datapool") (let [rd-scored (get-scored state :contestant 0)] (card-ability state :contestant rd-scored 0) (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 1 (:tag (get-challenger))) "Challenger should gain a tag from Restructured Datapool ability")))) (deftest self-destruct-chips ;; Self-Destruct Chips (do-game (new-game (default-contestant ["Self-Destruct Chips"]) (default-challenger)) (is (= 5 (get-hand-size :challenger)) "Challenger's hand size starts at 5") (play-and-score state "Self-Destruct Chips") (is (= 4 (get-hand-size :challenger)) "By scoring Self-Destruct Chips, Challenger's hand size is reduced by 1"))) (deftest sensor-net-activation ;; Sensor Net Activation (do-game (new-game (default-contestant [(qty "Sensor Net Activation" 2) "Enforcer 1.0" "Ash 2X3ZB9CY"]) (default-challenger)) (play-from-hand state :contestant "Enforcer 1.0" "HQ") (play-and-score state "Sensor Net Activation") (let [sna-scored (get-scored state :contestant 0) enf (get-character state :hq 0)] (is (= 1 (get-counters (refresh sna-scored) :agenda)) "Should start with 1 agenda counter") (is (not (:revealed (refresh enf))) "Enforcer 1.0 should start hidden") (card-ability state :contestant (refresh sna-scored) 0) (prompt-select :contestant enf) (is (:revealed (refresh enf)) "Enforcer 1.0 should be revealed") (is (= 1 (count (:scored (get-contestant)))) "Enforcer 1.0 should be revealed without forfeiting agenda") (take-credits state :contestant) (is (not (:revealed (refresh enf))) "Enforcer 1.0 should be hidden")) (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Ash 2X3ZB9CY" "New party") (play-and-score state "Sensor Net Activation") (let [sna-scored (get-scored state :contestant 1) ash (get-content state :party2 0)] (is (= 1 (get-counters (refresh sna-scored) :agenda)) "Should start with 1 agenda counter") (is (not (:revealed (refresh ash))) "Ash should start hidden") (card-ability state :contestant (refresh sna-scored) 0) (prompt-select :contestant ash) (is (:revealed (refresh ash)) "Ash should be revealed") (take-credits state :contestant) (is (not (:revealed (refresh ash))) "Ash should be hidden")))) (deftest sentinel-defense-resource ;; Sentinel Defense Resource - Doesn't fire if brain damage is prevented (do-game (new-game (default-contestant ["Sentinel Defense Resource" "Viktor 1.0"]) (default-challenger ["Feedback Filter" (qty "Sure Gamble" 3)])) (play-and-score state "Sentinel Defense Resource") (play-from-hand state :contestant "Viktor 1.0" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Feedback Filter") (let [viktor (get-character state :hq 0) ff (get-hazard state 0)] (run-on state "HQ") (core/reveal state :contestant viktor) (card-subroutine state :contestant viktor 0) (prompt-choice :challenger "Done") ;; Don't prevent the brain damage (is (= 1 (count (:discard (get-challenger))))) (is (= 1 (:brain-damage (get-challenger)))) (prompt-choice :challenger "Done") ;; So we take the net, but don't prevent it either (is (= 2 (count (:discard (get-challenger))))) (card-subroutine state :contestant viktor 0) (card-ability state :challenger ff 1) ;; Prevent the brain damage this time (prompt-choice :challenger "Done") (is (= 3 (count (:discard (get-challenger)))) "Feedback filter discarded, didn't take another net damage") (is (= 1 (:brain-damage (get-challenger))))))) (deftest show-of-force ;; Show of Force (do-game (new-game (default-contestant ["Show of Force"]) (default-challenger)) (is (= 3 (count (:hand (get-challenger)))) "Challenger should start with 3 cards in hand") (play-and-score state "Show of Force") (is (= 1 (count (:hand (get-challenger)))) "Challenger should have 1 card in hand") (is (= 2 (count (:discard (get-challenger)))) "Challenger should have discarded 2 cards"))) (deftest ssl-endorsement ;; SSL Endorsement (testing "gain credits when in contestant score area before turn begins" (do-game (new-game (default-contestant ["SSL Endorsement"]) (default-challenger)) (play-and-score state "SSL Endorsement") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 5 (:credit (get-contestant))) "Contestant starts with 5 credits") (prompt-choice :contestant "Yes") (is (= 8 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 8 (:credit (get-contestant))) "Contestant starts with 8 credits") (prompt-choice :contestant "No") (is (= 8 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 8 (:credit (get-contestant))) "Contestant starts with 8 credits") (prompt-choice :contestant "Yes") (is (= 11 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 11 (:credit (get-contestant))) "Contestant starts with 11 credits") (prompt-choice :contestant "Yes") (is (= 14 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money"))) (testing "gain credits when in challenger score area before turn begins" (do-game (new-game (default-contestant ["SSL Endorsement"]) (default-challenger)) (play-from-hand state :contestant "SSL Endorsement" "New party") (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 7 (:credit (get-contestant))) "Contestant starts with 7 credits") (prompt-choice :contestant "Yes") (is (= 10 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits") (prompt-choice :contestant "No") (is (= 10 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits") (prompt-choice :contestant "Yes") (is (= 13 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 13 (:credit (get-contestant))) "Contestant starts with 13 credits") (prompt-choice :contestant "Yes") (is (= 16 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money"))) (testing "register event when agenda swapped with Turntable" ;; Regression test for #3114 (do-game (new-game (default-contestant ["SSL Endorsement" "Breaking News"]) (default-challenger ["Turntable"])) (play-from-hand state :contestant "Breaking News" "New party") (play-and-score state "SSL Endorsement") (take-credits state :contestant) (play-from-hand state :challenger "Turntable") (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (prompt-choice :challenger "Yes") (prompt-select :challenger (find-card "SSL Endorsement" (:scored (get-contestant)))) ;; Swap BN with SSL (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 6 (:credit (get-contestant))) "Contestant starts with 7 credits") (prompt-choice :contestant "Yes") (is (= 9 (:credit (get-contestant))) "Contestant gains 3 credits from Turntable'd SSL Endorsement"))) (testing "don't double register event when agenda is swapped" (do-game (new-game (default-contestant ["SSL Endorsement" "Breaking News" "Exchange of Information"]) (default-challenger)) (play-from-hand state :contestant "SSL Endorsement" "New party") (play-and-score state "Breaking News") (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 6 (:credit (get-contestant))) "Contestant starts with 6 credits") (prompt-choice :contestant "Yes") (is (= 9 (:credit (get-contestant))) "Contestant gains 3 credits") (core/gain state :challenger :tag 1) (play-from-hand state :contestant "Exchange of Information") (prompt-select :contestant (find-card "SSL Endorsement" (:scored (get-challenger)))) (prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant)))) (take-credits state :challenger) (is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits") (prompt-choice :contestant "No") (is (empty? (:prompt (get-contestant))) "Not double prompted for credits") (is (= 9 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits") (prompt-choice :contestant "Yes") (is (= 12 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 12 (:credit (get-contestant))) "Contestant starts with 12 credits") (prompt-choice :contestant "Yes") (is (= 15 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money")))) (deftest standoff ;; Standoff (testing "Challenger declines first" (do-game (new-game (default-contestant ["Standoff" "Character Wall" "News Team"]) (default-challenger ["Cache"])) (starting-hand state :contestant ["Standoff" "Character Wall"]) (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Cache") (take-credits state :challenger) (play-and-score state "Standoff") (starting-hand state :contestant []) (is (zero? (-> (get-challenger) :discard count)) "Challenger should have no cards in Heap") (prompt-select :challenger (get-resource state 0)) (is (= 1 (-> (get-challenger) :discard count)) "Challenger should now have 1 card in Heap") (is (zero? (-> (get-contestant) :discard count)) "Contestant should have no cards in Archives") (prompt-select :contestant (get-character state :hq 0)) (is (= 1 (-> (get-contestant) :discard count)) "Contestant should now have 1 card in Archives") (is (zero? (-> (get-contestant) :hand count)) "Contestant should have no cards in hand") (let [credits (:credit (get-contestant))] (prompt-choice :challenger "Done") (is (= (+ credits 5) (:credit (get-contestant))) "Contestant should gain 5 credits from Challenger declining to discard an placed card") (is (= 1 (-> (get-contestant) :hand count)) "Contestant should draw a card from Challenger declining to discard an placed card")))) (testing "Contestant declines first" (do-game (new-game (default-contestant ["Standoff" "Character Wall" "News Team"]) (default-challenger ["Cache" "Cache"])) (starting-hand state :contestant ["Standoff" "Character Wall"]) (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Cache") (play-from-hand state :challenger "Cache") (take-credits state :challenger) (play-and-score state "Standoff") (starting-hand state :contestant []) (is (zero? (-> (get-challenger) :discard count)) "Challenger should have no cards in Heap") (prompt-select :challenger (get-resource state 0)) (is (= 1 (-> (get-challenger) :discard count)) "Challenger should now have 1 card in Heap") (is (zero? (-> (get-contestant) :discard count)) "Contestant should have no cards in Archives") (prompt-select :contestant (get-character state :hq 0)) (is (= 1 (-> (get-contestant) :discard count)) "Contestant should now have 1 card in Archives") (is (zero? (-> (get-contestant) :hand count)) "Contestant should have no cards in hand") (prompt-select :challenger (get-resource state 0)) (is (= 2 (-> (get-challenger) :discard count)) "Challenger should now have 2 cards in Heap") (let [credits (:credit (get-contestant))] (prompt-choice :contestant "Done") (is (= credits (:credit (get-contestant))) "Contestant should gain no credits from declining to discard an placed card") (is (zero? (-> (get-contestant) :hand count)) "Contestant should draw no cards from declining to discard an placed card"))))) (deftest successful-field-test ;; Successful Field Test (do-game (new-game (default-contestant ["Successful Field Test" (qty "Character Wall" 10)]) (default-challenger)) (starting-hand state :contestant (vec (cons "Successful Field Test" (repeat 10 "Character Wall")))) (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (play-and-score state "Successful Field Test") (dotimes [n 10] (prompt-select :contestant (find-card "Character Wall" (:hand (get-contestant)))) (prompt-choice :contestant "HQ")) (is (= 5 (:credit (get-contestant))) "Should still have 5 credits") (is (some? (get-character state :hq 9))))) (deftest superior-cyberwalls ;; Superior Cyberwalls (do-game (new-game (default-contestant ["Superior Cyberwalls" "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (let [iw (get-character state :hq 0)] (core/reveal state :contestant iw) (is (= 1 (:current-strength (refresh iw))) "Should start with base strength of 1") (is (= 4 (:credit (get-contestant))) "Should have 4 credits after reveal") (play-and-score state "Superior Cyberwalls") (is (= 2 (:current-strength (refresh iw))) "Should gain 1 strength from 1 to 2") (is (= 5 (:credit (get-contestant))) "Should gain 1 credit for revealed barrier")))) (deftest tgtbt ;; TGTBT - Give the Challenger 1 tag when they access ;; OHG still not working... (do-game (new-game (default-contestant [(qty "TGTBT" 2) "Old Hollywood Grid"]) (default-challenger)) (play-from-hand state :contestant "TGTBT" "New party") (play-from-hand state :contestant "Old Hollywood Grid" "Locale 1") (play-from-hand state :contestant "TGTBT" "New party") (take-credits state :contestant) (let [tg1 (get-content state :party1 0) ohg (get-content state :party1 1)] (run-on state "Locale 1") (core/reveal state :contestant ohg) (run-successful state) (prompt-select :challenger tg1) ;; Accesses TGTBT but can't steal (is (= 1 (:tag (get-challenger))) "Challenger took 1 tag from accessing without stealing") (prompt-choice :challenger "No action") (prompt-select :challenger ohg)) (prompt-choice :challenger "Yes") ;; Discards OHG (run-empty-locale state "Locale 2") ;; Accesses TGTBT and can steal (prompt-choice :challenger "Steal") (is (= 2 (:tag (get-challenger))) "Challenger took 1 tag from accessing and stealing"))) (deftest the-cleaners ;; The Cleaners (testing "Basic test" (do-game (new-game (default-contestant ["The Cleaners" "Scorched Earth"]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3)])) (play-and-score state "The Cleaners") (core/gain state :challenger :tag 1) (play-from-hand state :contestant "Scorched Earth") (is (zero? (count (:hand (get-challenger)))) "5 damage dealt to Challenger"))) (testing "No bonus damage when challenger 'suffers' damage, ie Cybernetics" (do-game (new-game (default-contestant ["The Cleaners"]) (default-challenger [(qty "Respirocytes" 3)])) (play-and-score state "The Cleaners") (take-credits state :contestant) (play-from-hand state :challenger "Respirocytes") (is (= 1 (count (:hand (get-challenger)))) "Only 1 damage dealt to Challenger from Cybernetics")))) (deftest the-future-is-now ;; The Future is Now (testing "With at least one card in deck" (do-game (new-game (default-contestant ["The Future is Now" "Character Wall"]) (default-challenger)) (starting-hand state :contestant ["The Future is Now"]) (is (= 1 (count (:hand (get-contestant))))) (is (= 1 (count (:deck (get-contestant))))) (play-and-score state "The Future is Now") (prompt-card :contestant (find-card "Character Wall" (:deck (get-contestant)))) (is (= 1 (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant))))))) (testing "With an empty deck" (do-game (new-game (default-contestant ["The Future is Now"]) (default-challenger)) (is (= 1 (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant))))) (play-and-score state "The Future is Now") (is (empty? (:prompt (get-contestant))) "Ability shouldn't fire if deck is empty") (is (zero? (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant)))))))) (deftest the-future-perfect ;; The Future Perfect (do-game (new-game (default-contestant [(qty "The Future Perfect" 2)]) (default-challenger)) (play-from-hand state :contestant "The Future Perfect" "New party") (take-credits state :contestant) (testing "No steal on not-equal Psi game" (run-empty-locale state "HQ") (prompt-choice :contestant "1 [Credits]") (prompt-choice :challenger "0 [Credits]") ;; Cannot steal prompt (prompt-choice :challenger "No action") (is (zero? (:agenda-point (get-challenger))) "Challenger did not steal TFP")) (testing "Successful steal on equal Psi game" (run-empty-locale state "HQ") (prompt-choice :contestant "1 [Credits]") (prompt-choice :challenger "1 [Credits]") (prompt-choice :challenger "Steal") (is (= 3 (:agenda-point (get-challenger))) "Challenger stole TFP")) (testing "No Psi game and successful steal when placed" (run-empty-locale state "Locale 1") (prompt-choice :challenger "Steal") (is (= 6 (:agenda-point (get-challenger))) "Challenger stole TFP - no Psi game on placed TFP")))) (deftest underway-renovation ;; Underway Renovation (do-game (new-game (default-contestant ["Underway Renovation" "Shipment from SanSan"]) (default-challenger)) (core/gain state :contestant :click 2) (starting-hand state :challenger []) (play-from-hand state :contestant "Underway Renovation" "New party") (let [ur (get-content state :party1 0)] (advance state ur) (is (last-log-contains? state "Sure Gamble") "Underway Renovation discarded card name is in log") ; check for #2370 (is (not (last-log-contains? state "Sure Gamble, Sure Gamble")) "Underway Renovation discarded card name is in log") (is (= 1 (count (:discard (get-challenger)))) "1 card milled from Challenger Stack") (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ur) (is (= 3 (get-counters (refresh ur) :advancement))) (is (= 1 (count (:discard (get-challenger)))) "No Challenger mills; advancements were placed") (advance state ur) (is (= 4 (get-counters (refresh ur) :advancement))) (is (last-log-contains? state "Sure Gamble, Sure Gamble") "Underway Renovation discarded card name is in log") (is (= 3 (count (:discard (get-challenger)))) "2 cards milled from Challenger Stack; 4+ advancements")))) (deftest unorthodox-predictions ;; Unorthodox Predictions (do-game (new-game (default-contestant ["Unorthodox Predictions"]) (default-challenger)) (play-and-score state "Unorthodox Predictions") (prompt-choice :contestant "Barrier") (is (last-log-contains? state "Barrier")))) (deftest utopia-fragment ;; Utopia Fragment (do-game (new-game (default-contestant ["Utopia Fragment" "Hostile Takeover"]) (default-challenger)) (play-and-score state "Utopia Fragment") (play-from-hand state :contestant "Hostile Takeover" "New party") (advance state (get-content state :party2 0)) (take-credits state :contestant) (run-on state :party2) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 1 (:agenda-point (get-challenger)))) (is (= 3 (:credit (get-challenger)))))) (deftest vanity-project ;; Vanity Project (do-game (new-game (default-contestant ["Vanity Project"]) (default-challenger)) (play-and-score state "Vanity Project") (is (= 4 (:agenda-point (get-contestant)))))) (deftest veterans-resource ;; Veterans Resource (testing "Veterans Resource basic test" (do-game (new-game (default-contestant [(qty "Hostile Takeover" 2) "Veterans Resource"]) (default-challenger)) (play-and-score state "Hostile Takeover") (play-and-score state "Hostile Takeover") (is (= 19 (:credit (get-contestant))) "Should gain 14 credits from 5 to 19") (is (= 2 (:bad-publicity (get-contestant))) "Should gain 2 bad publicity") (play-and-score state "Veterans Resource") (is (zero? (:bad-publicity (get-contestant))) "Should lose 2 bad publicity"))) (testing "Removes _up to 2_ bad publicity" (do-game (new-game (default-contestant ["Hostile Takeover" "Veterans Resource"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity") (play-and-score state "Veterans Resource") (is (zero? (:bad-publicity (get-contestant))) "Should lose 1 bad publicity")))) (deftest viral-weaponization ;; Viral Weaponization - at the end of turn scored, do 1 net damage for each card in grip (testing "Score on contestant turn" (do-game (new-game (default-contestant [(qty "Viral Weaponization" 2)]) (default-challenger [(qty "Sure Gamble" 3)])) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-and-score state "Viral Weaponization") (is (= 2 (count (:hand (get-challenger)))) "Challenger doesn't take damage when scored") (take-credits state :contestant) (is (zero? (count (:hand (get-challenger)))) "Challenger takes damage at end of turn") (core/click-draw state :challenger 1) (take-credits state :challenger) (take-credits state :contestant) (is (= 1 (count (:hand (get-challenger)))) "Challenger doesn't take damage in future turns") (play-from-hand state :challenger "Sure Gamble") (take-credits state :challenger) (is (zero? (count (:hand (get-challenger)))) "Challenger's hand is empty") (play-and-score state "Viral Weaponization") (take-credits state :contestant) (is (zero? (count (:hand (get-challenger)))) "Challenger's hand is empty"))) (testing "Score on challengers turn" (do-game (new-game (default-contestant ["Viral Weaponization" "Plan B"]) (default-challenger [(qty "Sure Gamble" 3)])) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-from-hand state :contestant "Plan B" "New party") (core/add-prop state :contestant (get-content state :party1 0) :advance-counter 4) (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Viral Weaponization" (:hand (get-contestant)))) (prompt-choice-partial :challenger "No") (is (= 2 (count (:hand (get-challenger)))) "Challenger doesn't take damage when scored") (take-credits state :challenger) (is (zero? (count (:hand (get-challenger)))) "Challenger takes damage at end of turn")))) (deftest voting-machine-initiative ;; Voting Machine Initiative (testing "Voting Machine Initiative" (do-game (new-game (default-contestant ["Voting Machine Initiative"]) (default-challenger)) (letfn [(vmi-test [vmi choice counter] (let [diff (if (= "Yes" choice) 1 0)] (is (= counter (get-counters (refresh vmi) :agenda))) (is (= 4 (:click (get-challenger)))) (prompt-choice :contestant choice) (is (= (- 4 diff) (:click (get-challenger)))) (is (= (- counter diff) (get-counters (refresh vmi) :agenda))) (take-credits state :challenger) (take-credits state :contestant)))] (play-and-score state "Voting Machine Initiative") (take-credits state :contestant) (let [vmi-scored (get-scored state :contestant 0)] (vmi-test vmi-scored "Yes" 3) (vmi-test vmi-scored "No" 2) (vmi-test vmi-scored "Yes" 2) (vmi-test vmi-scored "Yes" 1) (is (empty (:prompt (get-contestant))) "No prompt as there are no agenda counters left")))))) (deftest vulcan-coverup ;; Vulcan Coverup (do-game (new-game (default-contestant [(qty "Vulcan Coverup" 2)]) (default-challenger)) (play-from-hand state :contestant "Vulcan Coverup" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (is (= 1 (:bad-publicity (get-contestant))) "Took 1 bad pub from stolen agenda") (take-credits state :challenger) (play-and-score state "Vulcan Coverup") (is (= 2 (count (:discard (get-challenger)))) "Did 2 meat damage upon scoring"))) (deftest water-monopoly ;; Water Monopoly (do-game (new-game (default-contestant ["Water Monopoly"]) (default-challenger ["Fan Site" "Levy Advanced Research Lab"])) (play-and-score state "Water Monopoly") (take-credits state :contestant) (is (= 5 (:credit (get-challenger))) "Challenger should start with 5 credits") (play-from-hand state :challenger "Fan Site") (is (= 5 (:credit (get-challenger))) "Shouldn't lose any credits") (play-from-hand state :challenger "Levy Advanced Research Lab") (is (zero? (:credit (get-challenger))) "Should cost an extra credit to play")))
93986
(ns game-test.cards.agendas (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (use-fixtures :once load-all-cards (partial reset-card-defs "agendas")) (deftest ^{:card-title "15-minutes"} fifteen-minutes ;; 15 Minutes - check if it works correctly from both sides (do-game (new-game (default-contestant ["15 Minutes"]) (default-challenger)) (play-from-hand state :contestant "15 Minutes" "New party") (take-credits state :contestant) ;; use 15 minutes to take it away from challenger (run-empty-locale state "Locale 1") (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (= 1 (:agenda-point (get-challenger)))) (is (= 1 (count (:scored (get-challenger))))) (let [fifm (first (:scored (get-challenger)))] (is (= 3 (:click (get-contestant)))) (is (= 1 (count (:abilities (refresh fifm))))) (card-ability state :contestant (refresh fifm) 0) (is (zero? (:agenda-point (get-challenger)))) (is (zero? (count (:scored (get-challenger)))))) (is (= "15 Minutes" (:title (first (:deck (get-contestant)))))) ;; TODO: could also check for deck shuffle (is (= 2 (:click (get-contestant)))) ;; use 15 minutes to take it away from contestant (hey, maybe some obscure case happens where contestant would want that) (core/click-draw state :contestant 1) (play-from-hand state :contestant "15 Minutes" "New party") (take-credits state :challenger) (score-agenda state :contestant (get-content state :party2 0)) (is (= 1 (:agenda-point (get-contestant)))) (is (= 1 (count (:scored (get-contestant))))) (let [fifm (first (:scored (get-contestant)))] (is (= 1 (count (:abilities (refresh fifm))))) (card-ability state :contestant (refresh fifm) 0) (is (zero? (:agenda-point (get-contestant)))) (is (zero? (count (:scored (get-contestant)))))) (is (= "15 Minutes" (:title (first (:deck (get-contestant)))))))) (deftest accelerated-beta-test ;; Accelerated Beta Test (do-game (new-game (default-contestant ["Accelerated Beta Test" "Enigma" (qty "Hedge Fund" 2)]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Accelerated Beta Test"]) (play-and-score state "Accelerated Beta Test") (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Enigma" (get-in @state [:contestant :play-area]))) (prompt-choice :contestant "HQ") (is (some? (get-character state :hq 0))) (is (= 2 (count (:discard (get-contestant))))) (core/move state :contestant (find-card "Accelerated Beta Test" (:scored (get-contestant))) :hand) (core/move state :contestant (find-card "Hedge Fund" (:discard (get-contestant))) :deck) (core/move state :contestant (find-card "Hedge Fund" (:discard (get-contestant))) :deck) (play-and-score state "Accelerated Beta Test") (prompt-choice :contestant "Yes") (prompt-choice :contestant "I have no regrets") (is (= 2 (count (:discard (get-contestant))))))) (deftest advanced-concept-hopper ;; Advanced Concept Hopper (do-game (new-game (default-contestant ["Advanced Concept Hopper" (qty "Hedge Fund" 4)]) (default-challenger)) (starting-hand state :contestant ["Advanced Concept Hopper"]) (play-and-score state "Advanced Concept Hopper") (take-credits state :contestant) (testing "Contestant draws 1 card, only once per turn" (let [cards (count (:hand (get-contestant)))] (is (= cards (count (:hand (get-contestant)))) (str "Contestant should have " cards " cards in hand")) (run-on state :archives) (prompt-choice :contestant "Draw 1 card") (is (= (inc cards) (count (:hand (get-contestant)))) (str "Contestant should have " (inc cards) " card in hand")) (run-successful state) (run-on state :archives) (is (empty (:prompt (get-contestant))) "No prompt as it's once per turn"))) (take-credits state :challenger) (take-credits state :contestant) (testing "Contestant gains 1 credit, only once per turn" (let [credits (:credit (get-contestant))] (is (= credits (:credit (get-contestant))) (str "Contestant should have " credits " credits")) (run-on state :archives) (prompt-choice :contestant "Gain 1 [Credits]") (is (= (inc credits) (:credit (get-contestant))) (str "Contestant should have " (inc credits) " credits")) (run-successful state) (run-on state :archives) (is (empty (:prompt (get-contestant))) "No prompt as it's once per turn"))))) (deftest ancestral-imager ;; Ancestral Imager (do-game (new-game (default-contestant [(qty "Ancestral Imager" 3)]) (default-challenger)) (play-and-score state "Ancestral Imager") (take-credits state :contestant) (let [grip (count (:hand (get-challenger)))] (is (= grip (count (:hand (get-challenger)))) (str "Challenger has " grip " cards in hand")) (run-on state :hq) (run-jack-out state) (is (= (dec grip) (count (:hand (get-challenger)))) "Challenger took 1 net damage")))) (deftest ar-enhanced-security ;; AR-Enhanced Security (do-game (new-game (default-contestant ["AR-Enhanced Security" (qty "NGO Front" 3)]) (default-challenger)) (testing "set up" (core/gain state :contestant :click 10 :credit 10) (core/gain state :challenger :credit 10) (dotimes [_ 3] (play-from-hand state :contestant "NGO Front" "New party")) (take-credits state :contestant)) (testing "don't take a tag from discarding normally" (run-on state :party1) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 1 (count (:discard (get-contestant)))) "discarded") (is (zero? (:tag (get-challenger))) "Challenger took 0 tags") (take-credits state :challenger) (play-and-score state "AR-Enhanced Security") (take-credits state :contestant)) (testing "gain a tag from first discard" (run-on state :party2) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 2 (count (:discard (get-contestant)))) "discarded") (is (= 1 (:tag (get-challenger))) "Challenger took 1 tag")) (testing "don't gain a tag from second discard" (run-on state :party3) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 3 (count (:discard (get-contestant)))) "discarded") (is (= 1 (:tag (get-challenger))) "Challenger took 0 tags")))) (deftest armed-intimidation ;; Armed Intimidation (do-game (new-game (default-contestant [(qty "Armed Intimidation" 2)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 2)])) (play-and-score state "Armed Intimidation") (prompt-choice :challenger "Take 2 tags") (is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from Armed Intimidation tag choice") (play-and-score state "Armed Intimidation") (is (= 5 (count (:hand (get-challenger)))) "Challenger has 5 cards before Armed Intimidation meat damage") (prompt-choice :challenger "Suffer 5 meat damage") (is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards after Armed Intimidation meat damage"))) (deftest armored-locales ;; Armored Locales (do-game (new-game (default-contestant ["Armored Locales"]) (default-challenger)) (play-and-score state "Armored Locales") (let [as-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh as-scored) :agenda)) "Should start with 1 agenda counters") (take-credits state :contestant) (run-on state "HQ") (card-ability state :contestant as-scored 0) (is (last-log-contains? state "make the Challenger discard") "Should only write to log")))) (deftest astroscript-pilot-resource ;; AstroScript token placement (do-game (new-game (default-contestant [(qty "AstroScript Pilot Resource" 3) (qty "Character Wall" 2)]) (default-challenger)) (core/gain state :contestant :click 3) (letfn [(try-place [from to] (card-ability state :contestant (refresh from) 0) (prompt-select :contestant (refresh to))) (should-not-place [from to msg] (try-place from to) (prompt-choice :contestant "Done") (is (= 1 (get-counters (refresh from) :agenda)) (str (:title from)" token was not used on " (:title to) msg)) (is (zero? (get-counters (refresh to) :advancement)) (str "Advancement token not placed on " (:title to) msg))) (should-place [from to msg] (try-place from to) (is (zero? (get-counters (refresh from) :agenda)) (str (:title from) " token was used on " (:title to) msg)) (is (= 1 (get-counters (refresh to) :advancement)) (str "Advancement token placed on " (:title to) msg)))] (play-and-score state "AstroScript Pilot Resource") (play-from-hand state :contestant "AstroScript Pilot Resource" "New party") (let [scored-astro (get-scored state :contestant 0) placed-astro (get-content state :party2 0) hand-astro (find-card "AstroScript Pilot Resource" (:hand get-contestant))] (should-not-place scored-astro hand-astro " in hand") (should-place scored-astro placed-astro " that is placed") (advance state placed-astro 2) (core/score state :contestant {:card (refresh placed-astro)})) (play-from-hand state :contestant "Character Wall" "HQ") (let [no-token-astro (get-scored state :contestant 0) token-astro (get-scored state :contestant 1) hand-character-wall (find-card "Character Wall" (:hand get-contestant)) placed-character-wall (get-character state :hq 0)] (should-not-place token-astro no-token-astro " that is scored") (should-not-place token-astro hand-character-wall " in hand") (should-place token-astro placed-character-wall " that is placed"))))) (deftest award-bait ;; Award Bait (do-game (new-game (default-contestant [(qty "Award Bait" 2) "Character Wall"]) (default-challenger)) (core/move state :contestant (find-card "Award Bait" (:hand (get-contestant))) :deck) (play-from-hand state :contestant "Character Wall" "HQ") (let [iw (get-character state :hq 0)] (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (play-from-hand state :contestant "Award Bait" "New party") (take-credits state :contestant) (run-on state :party1) (run-successful state) (prompt-choice :contestant "2") (prompt-select :contestant (refresh iw)) (prompt-choice :challenger "Steal") (is (= 2 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 advancement tokens") (run-on state :rd) (run-successful state) (prompt-choice :challenger "Access") (prompt-choice :contestant "2") (prompt-select :contestant (refresh iw)) (prompt-choice :challenger "Steal") (is (= 4 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 advancement tokens")))) (deftest bacterial-resourceming ;; Bacterial Resourceming (testing "Scoring should not cause a run to exist for challenger." (do-game (new-game (default-contestant ["Bacterial Resourceming" "Hedge Fund"]) (default-challenger)) (starting-hand state :contestant ["Bacterial Resourceming"]) (play-and-score state "Bacterial Resourceming") (prompt-choice :contestant "Yes") (prompt-choice :contestant "Done") (prompt-choice :contestant "Done") (prompt-card :contestant (first (:deck (get-contestant)))) (prompt-choice :contestant "Done") (is (empty (:prompt (get-contestant))) "Bacterial Resourceming prompts finished") (is (not (:run @state)) "No run is active"))) (testing "Removing all cards from R&D should not freeze for challenger, nor give an extra access." (do-game (new-game (default-contestant [(qty "Bacterial Resourceming" 8)]) (default-challenger) {:start-as :challenger}) (starting-hand state :contestant []) (run-empty-locale state :rd) (prompt-choice :challenger "Steal") (prompt-choice :contestant "Yes") ;; Move all 7 cards to discard (doseq [_ (range 7) ;; Get the first card listed in the prompt choice ;; TODO make this function :let [card (-> @state (get-in [:contestant :prompt]) first (get-in [:choices 0]))]] (prompt-card :contestant card)) (prompt-choice :contestant "Done") ; Finished with discarding (prompt-choice :contestant "Done") ; Finished with move-to-hq (no cards to move) ;; Run and prompts should be over now (is (empty (:prompt (get-contestant))) "Bacterial Resourceming prompts finished") (is (empty (:prompt (get-challenger))) "Bacterial Resourceming prompts finished") (is (not (:run @state)))))) (deftest better-citizen-resource ;; Better Citizen Resource (testing "Basic test" (do-game (new-game (default-contestant ["Better Citizen Resource"]) (default-challenger [(qty "The Maker's Eye" 2) (qty "Wyrm" 2)])) (play-and-score state "Better Citizen Resource") (take-credits state :contestant) (core/gain state :challenger :credit 10) (is (zero? (:tag (get-challenger))) "Challenger starts with 0 tags") (play-from-hand state :challenger "The Maker's Eye") (prompt-choice :contestant "Yes") (is (= 1 (:tag (get-challenger))) "Challenger takes 1 tag for playing a Run event") (run-successful state) (play-from-hand state :challenger "Wyrm") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (= 1 (:tag (get-challenger))) "Challenger doesn't gain a tag from placing an characterbreaker after playing a Run event") (take-credits state :challenger) (take-credits state :contestant) (play-from-hand state :challenger "Wyrm") (prompt-choice :contestant "Yes") (is (= 2 (:tag (get-challenger))) "Challenger gains 1 tag for placing an Icebreaker") (play-from-hand state :challenger "The Maker's Eye") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (= 2 (:tag (get-challenger))) "Challenger doesn't gain a tag from playing a Run event after placing an Icebreaker") (run-successful state))) (testing "Should only trigger on Run events. #3619" (do-game (new-game (default-contestant ["Better Citizen Resource"]) (default-challenger ["Mining Accident"])) (play-and-score state "Better Citizen Resource") (take-credits state :contestant) (run-empty-locale state "HQ") (play-from-hand state :challenger "Mining Accident") (prompt-choice-partial :contestant "Pay") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (zero? (:tag (get-challenger))) "Challenger should not gain a tag from playing a non-Run event")))) (deftest bifrost-array ;; Bifrost Array (do-game (new-game (default-contestant ["Bifrost Array" "Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity") (let [ht-scored (get-scored state :contestant 0)] (play-and-score state "Bifrost Array") (prompt-choice :contestant "Yes") (prompt-select :contestant (refresh ht-scored)) (is (= 19 (:credit (get-contestant))) "Should gain 7 credits from 12 to 19") (is (= 2 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity")))) (deftest brain-rewiring ;; Brain Rewiring (do-game (new-game (default-contestant ["Brain Rewiring"]) (default-challenger)) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-and-score state "Brain Rewiring") (prompt-choice :contestant "Yes") (prompt-choice :contestant 2) (is (= 1 (count (:hand (get-challenger))))))) (deftest braintrust ;; Braintrust (do-game (new-game (default-contestant ["Braintrust" "Ichi 1.0"]) (default-challenger)) (play-from-hand state :contestant "Braintrust" "New party") (let [bt (get-content state :party1 0)] (core/add-prop state :contestant bt :advance-counter 7) (core/score state :contestant {:card (refresh bt)}) (let [scored-bt (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh scored-bt) :agenda)) "Scored w/ 4 over-advancements; 2 agenda counters") (play-from-hand state :contestant "Ichi 1.0" "HQ") (core/reveal state :contestant (get-character state :hq 0)) (is (= 2 (:credit (get-contestant))) "2c discount to reveal Ichi"))))) (deftest breaking-news ;; Breaking News (do-game (new-game (default-contestant [(qty "Breaking News" 3)]) (default-challenger)) (play-and-score state "Breaking News") (is (= 2 (get-in @state [:challenger :tag])) "Challenger receives 2 tags from Breaking News") (take-credits state :contestant) (is (zero? (get-in @state [:challenger :tag]))) "Two tags removed at the end of the turn")) (deftest cfc-excavation-contract ;; CFC Excavation Contract (dotimes [n 5] (do-game (new-game (default-contestant ["CFC Excavation Contract" (qty "Eli 1.0" n)]) (default-challenger)) (core/gain state :contestant :click 10 :credit 10) (is (= 15 (:credit (get-contestant))) "Should start with 5 credits") (dotimes [_ n] (play-from-hand state :contestant "Eli 1.0" "New party") (core/reveal state :contestant (get-character state (keyword (str "party" (:rid @state))) 0))) (let [credit (:credit (get-contestant))] (play-and-score state "CFC Excavation Contract") (is (= (+ credit (* 2 n)) (:credit (get-contestant))) (str "Should now have with " (+ credit (* 2 n)) " credits")))))) (deftest character-assassination ;; Character Assassination (do-game (new-game (default-contestant ["Character Assassination"]) (default-challenger ["Fall <NAME>" "<NAME>"])) (take-credits state :contestant) (play-from-hand state :challenger "<NAME>") (play-from-hand state :challenger "Fall Guy") (take-credits state :challenger) (play-and-score state "Character Assassination") (let [kati (get-radicle state 0)] (prompt-select :contestant <NAME> <NAME>) (is (empty? (:prompt (get-challenger))) "Fall Guy prevention didn't occur") (is (= 1 (count (:discard (get-challenger)))) "<NAME> discarded")))) (deftest chronos-project ;; Chronos Project (do-game (new-game (default-contestant ["Chronos Project"]) (default-challenger)) (dotimes [_ 3] (core/move state :challenger (find-card "Sure Gamble" (:hand (get-challenger))) :discard)) (is (= 3 (count (:discard (get-challenger)))) "Challenger should have 3 cards in heap") (play-and-score state "Chronos Project") (is (zero? (count (:discard (get-challenger)))) "Challenger should have 0 cards in heap"))) (deftest city-works-project ;; City Works Project (do-game (new-game (default-contestant ["City Works Project"]) (default-challenger [(qty "Sure Gamble" 4)])) (play-from-hand state :contestant "City Works Project" "New party") (let [cwp (get-content state :party1 0)] (core/advance state :contestant {:card (refresh cwp)}) (core/advance state :contestant {:card (refresh cwp)})) (take-credits state :contestant) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (= 4 (count (:discard (get-challenger)))) "Challenger paid 4 meat damage"))) (deftest clone-retirement ;; Clone Retirement (do-game (new-game (default-contestant [(qty "Clone Retirement" 2) "Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant)))) (is (= 1 (:bad-publicity (get-contestant)))) (play-and-score state "Clone Retirement") (is (zero? (:bad-publicity (get-contestant)))) (play-from-hand state :contestant "Clone Retirement" "New party") (take-credits state :contestant) (run-on state "Locale 3") (run-successful state) (prompt-choice :challenger "Steal") (is (= 1 (:bad-publicity (get-contestant)))))) (deftest contestantorate-sales-team ;; Contestantorate Sales Team (do-game (new-game (default-contestant [(qty "Contestantorate Sales Team" 2)]) (default-challenger)) (is (= 5 (:credit (get-contestant)))) (play-and-score state "Contestantorate Sales Team") (let [scored-cst (get-scored state :contestant 0)] (core/end-turn state :contestant nil) (core/start-turn state :challenger nil) (is (= 6 (:credit (get-contestant))) "Increments at challenger's start of turn") (is (= 9 (get-counters (refresh scored-cst) :credit))) (core/end-turn state :challenger nil) (core/start-turn state :contestant nil) (is (= 7 (:credit (get-contestant))) "Increments at contestant's start of turn") (is (= 8 (get-counters (refresh scored-cst) :credit)))))) (deftest contestantorate-war ;; Contestantorate War (do-game (new-game (default-contestant [(qty "Contestantorate War" 2)]) (default-challenger)) (is (= 5 (:credit (get-contestant)))) (play-and-score state "Contestantorate War") (is (zero? (:credit (get-contestant))) "Lost all credits") (core/gain state :contestant :credit 7) (play-and-score state "Contestantorate War") (is (= 14 (:credit (get-contestant))) "Had 7 credits when scoring, gained another 7"))) (deftest crisis-management ;; Crisis Management (do-game (new-game (default-contestant ["Crisis Management"]) (default-challenger)) (play-and-score state "Crisis Management") (take-credits state :contestant) (take-credits state :challenger) (is (= 3 (count (:hand (get-challenger)))) "No damage done, Challenger not tagged") (take-credits state :contestant) (core/gain state :challenger :tag 1) (take-credits state :challenger) (is (= 2 (count (:hand (get-challenger)))) "Crisis Management dealt 1 meat damage"))) (deftest dedicated-neural-net ;; Dedicated Neural Net (do-game (new-game (default-contestant ["Dedicated Neural Net" (qty "Scorched Earth" 2) "Hedge Fund" "Caprcharacter Nisei"]) (default-challenger ["HQ Interface"])) (play-from-hand state :contestant "Caprcharacter Nisei" "HQ") (play-and-score state "Dedicated Neural Net") (take-credits state :contestant) (run-empty-locale state :hq) (prompt-choice :challenger "0") (prompt-choice :contestant "1") (is (-> @state :run :run-effect :replace-access) "Replace-access tiggered") (prompt-select :contestant (find-card "Hedge Fund" (:hand (get-contestant)))) (prompt-choice :challenger "Card from hand") (is (accessing state "Hedge Fund") "Challenger accessing Hedge Fund") (prompt-choice :challenger "No action") ;; test for #2376 (prompt-choice :challenger "Unrevealed region in HQ") (is (accessing state "Caprcharacter Nisei") "Challenger accessing Caprcharacter") (prompt-choice :challenger "No") (is (not (:run @state)) "Run completed") (run-empty-locale state :hq) (prompt-choice :challenger "No action") (take-credits state :challenger) (take-credits state :contestant) (play-from-hand state :challenger "HQ Interface") (run-empty-locale state :hq) (prompt-choice :challenger "0") (prompt-choice :contestant "1") (is (= 2 (-> (get-contestant) :selected first :max)) "Contestant chooses 2 cards for Challenger to access"))) (deftest degree-mill ;; Degree Mill (testing "Basic behavior" (do-game (new-game (default-contestant [(qty "Degree Mill" 2)]) (default-challenger ["Character Analyzer" "All-nighter" "Hunting Grounds"])) (play-from-hand state :contestant "Degree Mill" "New party") (take-credits state :contestant) (is (= 0 (count (:deck (get-challenger)))) "Challenger starts with empty deck") (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "No action") (is (= 0 (:agenda-point (get-challenger))) "Challenger stole Degree Mill with no placed cards") (play-from-hand state :challenger "Character Analyzer") (play-from-hand state :challenger "All-nighter") (let [ia (get-radicle state 0) an (get-radicle state 1)] (run-on state "Locale 1") (run-successful state) (prompt-choice-partial :challenger "Pay") (prompt-select :challenger ia) (prompt-select :challenger an) (is (= 3 (:agenda-point (get-challenger))) "Challenger failed to steal Degree Mill") (is (empty? (get-in @state [:challenger :rig :radicle])) "Degree Mill didn't remove placed cards") (is (= 2 (count (:deck (get-challenger)))) "Degree Mill didn't put cards back in deck")) (take-credits state :challenger) ;; Checking if facedowns work as well (play-from-hand state :contestant "Degree Mill" "New party") (take-credits state :contestant) (play-from-hand state :challenger "Hunting Grounds") (let [hg (get-radicle state 0)] (run-on state "Locale 2") (run-successful state) (prompt-choice :challenger "No action") (is (= 3 (:agenda-point (get-challenger))) "Challenger stole Degree Mill with single card") (card-ability state :challenger hg 1) (is (= 2 (count (get-in (get-challenger) [:rig :facedown]))) "Hunting Ground did not place cards facedown") (is (empty? (:deck (get-challenger))) "Hunting Grounds did not remove cards from deck") (let [fd1 (get-challenger-facedown state 0) fd2 (get-challenger-facedown state 1)] (run-on state "Locale 2") (run-successful state) (prompt-choice-partial :challenger "Pay") (prompt-select :challenger fd1) (prompt-select :challenger fd2) (is (= 6 (:agenda-point (get-challenger))) "Challenger failed to steal Degree Mill with facedown cards") (is (empty? (get-in (get-challenger) [:rig :facedown])) "Degree Mill didn't remove facedown cards") (is (= 2 (count (:deck (get-challenger)))) "Degree Mill didn't put cards back in deck"))))) (testing "Multiple steal costs" (do-game (new-game (default-contestant [(qty "Degree Mill" 1) (qty "Strongbox" 1)]) (default-challenger [(qty "Character Analyzer" 3) (qty "All-nighter" 3)])) (play-from-hand state :contestant "Degree Mill" "New party") (play-from-hand state :contestant "Strongbox" "Locale 1") (let [dm (get-content state :party1 0) sb (get-content state :party1 1)] (core/reveal state :contestant sb) (take-credits state :contestant) (play-from-hand state :challenger "Character Analyzer") (play-from-hand state :challenger "All-nighter") (run-empty-locale state :party1) (prompt-select :challenger (refresh dm)) (prompt-choice-partial :challenger "Pay") (is (= 1 (:click (get-challenger))) "Challenger should start with 1 remaining click") (prompt-choice-partial :challenger "Click") (is (zero? (:click (get-challenger))) "Challenger should have spent a click") (is (= 2 (count (get-in @state [:challenger :rig :radicle]))) "Challenger starts with 2 radicles") (prompt-choice-partial :challenger "shuffling") (prompt-select :challenger (get-radicle state 1)) (prompt-select :challenger (get-radicle state 0)) (is (empty? (get-radicle state)) "Degree Mill removed placed cards") (is (not-empty (get-scored state :challenger)) "Challenger stole an agenda"))))) (deftest director-haas'-pet-project ;; Director Haas' Pet Project (do-game (new-game (default-contestant ["Director Haas' Pet Project" "Adonis Campaign" "Strongbox" "Eli 1.0" (qty "Hedge Fund" 5)]) (default-challenger)) (starting-hand state :contestant ["Director Haas' Pet Project" "Adonis Campaign" "Strongbox"]) (core/move state :contestant (find-card "Eli 1.0" (:deck (get-contestant))) :discard) (play-and-score state "Director Haas' Pet Project") (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Adonis Campaign" (:hand (get-contestant)))) (prompt-select :contestant (find-card "Strongbox" (:hand (get-contestant)))) (prompt-select :contestant (find-card "Eli 1.0" (:discard (get-contestant)))))) (deftest domestic-sleepers ;; Domestic Sleepers (do-game (new-game (default-contestant ["Domestic Sleepers"]) (default-challenger)) (play-and-score state "Domestic Sleepers") (core/gain state :contestant :click 3) (let [ds_scored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh ds_scored) :agenda)) "Should start with 0 agenda counters") (is (zero? (:agenda-point (get-contestant))) "Should provide 0 agenda points initially") (card-ability state :contestant ds_scored 0) (is (= 1 (get-counters (refresh ds_scored) :agenda)) "Should gain 1 agenda counter") (is (= 1 (:agenda-point (get-contestant))) "Should provide 1 agenda point after ability use")))) (deftest eden-fragment ;; Test that Eden Fragment ignores the place cost of the first character (do-game (new-game (default-contestant [(qty "Eden Fragment" 3) (qty "Character Wall" 3)]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (play-and-score state "Eden Fragment") (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Character Wall" "HQ") (is (some? (get-character state :hq 1)) "Contestant has two character placed on HQ") (is (= 6 (:credit (get-contestant))) "Contestant does not pay for placing the first Character of the turn") (play-from-hand state :contestant "Character Wall" "HQ") (is (some? (get-character state :hq 2)) "Contestant has three character placed on HQ") (is (= 4 (:credit (get-contestant))) "Contestant pays for placing the second Character of the turn"))) (deftest efficiency-committee ;; Efficiency Committee (do-game (new-game (default-contestant [(qty "Efficiency Committee" 3) (qty "Shipment from SanSan" 2) "Character Wall"]) (default-challenger)) (core/gain state :contestant :click 4) (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Character Wall" "HQ") (let [ec1 (get-content state :party1 0) ec2 (get-content state :party2 0) ec3 (get-content state :party3 0) iw (get-character state :hq 0)] (score-agenda state :contestant ec1) (let [ec1_scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh ec1_scored) :agenda))) (is (= 2 (:agenda-point (get-contestant)))) ;; use token (is (= 3 (:click (get-contestant)))) (card-ability state :contestant ec1_scored 0) (is (= 4 (:click (get-contestant)))) ;; try to advance Character Wall (advance state iw) (is (= 4 (:click (get-contestant)))) (is (zero? (get-counters (refresh iw) :advancement))) ;; try to advance Efficiency Committee (advance state ec2) (is (= 4 (:click (get-contestant)))) (is (zero? (get-counters (refresh ec2) :advancement))) ;; advance with Shipment from SanSan (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ec2) (is (= 2 (get-counters (refresh ec2) :advancement))) (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ec2) (is (= 4 (get-counters (refresh ec2) :advancement))) (core/score state :contestant {:card (refresh ec2)}) (is (= 4 (:agenda-point (get-contestant)))) (take-credits state :contestant) (take-credits state :challenger) ;; can advance again (advance state iw) (is (= 1 (get-counters (refresh iw) :advancement))) (advance state ec3) (is (= 1 (get-counters (refresh ec3) :advancement))))))) (deftest elective-region ;; Elective Region (do-game (new-game (default-contestant ["Elective Region"]) (default-challenger)) (play-and-score state "Elective Region") (let [eu-scored (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh eu-scored) :agenda)) "Should start with 2 agenda counters") (take-credits state :contestant) (take-credits state :challenger) (is (= 3 (:click (get-contestant))) "Should start with 4 clicks") (card-ability state :contestant eu-scored 0) (card-ability state :contestant eu-scored 0) (is (= 4 (:click (get-contestant))) "Should gain 2 clicks, not 3") (is (= 1 (get-counters (refresh eu-scored) :agenda)) "Should still have 1 agenda counter")))) (deftest encrypted-portals ;; Encrypted Portals (do-game (new-game (default-contestant ["Encrypted Portals" "Lotus Field"]) (default-challenger)) (play-from-hand state :contestant "Lotus Field" "HQ") (let [lf (get-character state :hq 0)] (core/reveal state :contestant lf) (is (= 4 (:current-strength (refresh lf))) "Should start with base strength of 4") (is (zero? (:credit (get-contestant))) "Should have 0 credits after reveal") (play-and-score state "Encrypted Portals") (is (= 5 (:current-strength (refresh lf))) "Should gain 1 strength from 4 to 5") (is (= 1 (:credit (get-contestant))) "Should gain 1 credit for revealed code gate")))) (deftest escalate-vitriol ;; Escalate Vitriol (do-game (new-game (default-contestant ["Escalate Vitriol"]) (default-challenger)) (core/lose state :contestant :credit 5) (play-and-score state "Escalate Vitriol") (let [ev-scored (get-scored state :contestant 0)] (dotimes [tag 10] (is (zero? (:tag (get-challenger))) "Should start with 0 tags") (is (zero? (:credit (get-contestant))) "Should start with 0 credits") (core/gain state :challenger :tag tag) (card-ability state :contestant ev-scored 0) (is (= tag (:credit (get-contestant))) (str "Should gain " tag " credits")) (take-credits state :contestant) (take-credits state :challenger) (core/lose state :contestant :credit (:credit (get-contestant))) (core/lose state :challenger :tag tag))))) (deftest executive-retreat ;; Executive Retreat (do-game (new-game (default-contestant ["Executive Retreat" (qty "Hedge Fund" 5)]) (default-challenger)) (starting-hand state :contestant ["Executive Retreat" "Hedge Fund"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should start with 1 card in HQ") (play-and-score state "Executive Retreat") (is (zero? (count (:hand (get-contestant)))) "Contestant should have 0 cards in HQ after shuffling HQ back into R&D") (let [er-scored (get-scored state :contestant 0)] (card-ability state :contestant er-scored 0) (is (= 5 (count (:hand (get-contestant)))) "Contestant should have 5 cards in hand") (is (zero? (get-counters (refresh er-scored) :agenda)) "Executive Retreat should have 0 agenda counters"))) (testing "Overdraw" (do-game (new-game (default-contestant ["Executive Retreat" (qty "Hedge Fund" 4)]) (default-challenger)) (starting-hand state :contestant ["Executive Retreat" "Hedge Fund"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should start with 1 card in HQ") (play-and-score state "Executive Retreat") (is (zero? (count (:hand (get-contestant)))) "Contestant should have 0 cards in HQ after shuffling HQ back into R&D") (let [er-scored (get-scored state :contestant 0)] (card-ability state :contestant er-scored 0) (is (= 4 (count (:hand (get-contestant)))) "Contestant should have 5 cards in hand") (is (zero? (get-counters (refresh er-scored) :agenda)) "Executive Retreat should have 0 agenda counters") (is (= :challenger (:winner @state)) "Challenger wins") (is (= "Decked" (:reason @state)) "Win condition reports decked"))))) (deftest explode-a-palooza ;; Explode-a-palooza (testing "Basic test" (do-game (new-game (default-contestant ["Explode-a-palooza"]) (default-challenger)) (play-from-hand state :contestant "Explode-a-palooza" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Access") (prompt-choice :challenger "Steal") (prompt-choice :contestant "Yes") (is (= 12 (:credit (get-contestant))) "Gained 5 credits"))) (testing "Interaction with The Turning Wheel. Issue #1717." (do-game (new-game (default-contestant [(qty "Explode-a-palooza" 3)]) (default-challenger ["The Turning Wheel"])) (starting-hand state :contestant ["Explode-a-palooza" "Explode-a-palooza"]) (play-from-hand state :contestant "Explode-a-palooza" "New party") (take-credits state :contestant) (play-from-hand state :challenger "The Turning Wheel") (run-empty-locale state :party1) (prompt-choice :challenger "Access") (prompt-choice :contestant "Yes") (prompt-choice :challenger "Steal") (let [ttw (get-radicle state 0)] (is (zero? (get-counters (refresh ttw) :power)) "TTW did not gain counters") (is (= 1 (count (:scored (get-challenger)))) "Challenger stole Explodapalooza") (is (= 12 (:credit (get-contestant))) "Gained 5 credits") (run-empty-locale state :rd) (prompt-choice :challenger "Access") (prompt-choice :contestant "Yes") (prompt-choice :challenger "Steal") (is (zero? (get-counters (refresh ttw) :power)) "TTW did not gain counters") (is (= 2 (count (:scored (get-challenger)))) "Challenger stole Explodapalooza") (is (= 17 (:credit (get-contestant))) "Gained 5 credits"))))) (deftest false-lead ;; False Lead (do-game (new-game (default-contestant ["False Lead"]) (default-challenger)) (play-and-score state "False Lead") (is (= 1 (count (:scored (get-contestant)))) "Contestant should have 1 agenda point") (take-credits state :contestant) (is (= 4 (:click (get-challenger))) "Challenger should start turn with 4 clicks") (card-ability state :contestant (get-scored state :contestant 0) 0) (is (= 2 (:click (get-challenger))) "Challenger should lose 2 clicks from False Lead"))) (deftest fetal-ai ;; Fetal AI (testing "basic test" (do-game (new-game (default-contestant [(qty "Fetal AI" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3) (qty "Quality Time" 3)])) (play-from-hand state :contestant "Fetal AI" "New party") (take-credits state :contestant 2) (run-empty-locale state "Locale 1") (prompt-choice-partial :challenger "Pay") (is (= 3 (count (:hand (get-challenger)))) "Challenger took 2 net damage from Fetal AI") (is (= 3 (:credit (get-challenger))) "Challenger paid 2cr to steal Fetal AI") (is (= 1 (count (:scored (get-challenger)))) "Challenger stole Fetal AI")) (testing "can't afford to steal" (do-game (new-game (default-contestant [(qty "Fetal AI" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3) (qty "Quality Time" 3)])) (play-from-hand state :contestant "Fetal AI" "New party") (take-credits state :contestant 2) (core/lose state :challenger :credit 5) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (= 3 (count (:hand (get-challenger)))) "Challenger took 2 net damage from Fetal AI") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Fetal AI"))))) (deftest firmware-updates ;; Firmware Updates (do-game (new-game (default-contestant ["Firmware Updates" "Character Wall"]) (default-challenger)) (play-and-score state "Firmware Updates") (play-from-hand state :contestant "Character Wall" "HQ") (let [fu (get-scored state :contestant 0) iw (get-character state :hq 0)] (is (= 3 (get-counters (refresh fu) :agenda)) "Firmware Updates should start with 3 agenda counters") (core/reveal state :contestant iw) (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (card-ability state :contestant fu 0) (prompt-select :contestant (refresh iw)) (is (= 2 (get-counters (refresh fu) :agenda)) "Firmware Updates should now have 2 agenda counters") (is (= 1 (get-counters (refresh iw) :advancement)) "Character Wall should have 1 advancement token")))) (deftest geothermal-fracking ;; Geothermal Fracking (testing "basic test" (do-game (new-game (default-contestant ["Geothermal Fracking"]) (default-challenger)) (play-and-score state "Geothermal Fracking") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (is (zero? (:bad-publicity (get-contestant))) "Should start with 0 bad publicity") (let [gf-scored (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh gf-scored) :agenda)) "Should start with 2 agenda counters") (card-ability state :contestant gf-scored 0) (is (= 1 (:click (get-contestant))) "Should have 1 click left") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity")))) (testing "prevented bad publicity shouldn't block credit gain" (do-game (new-game (default-contestant ["Geothermal Fracking" "Broadcast Square"]) (default-challenger)) (play-and-score state "Geothermal Fracking") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (is (zero? (:bad-publicity (get-contestant))) "Should start with 0 bad publicity") (play-from-hand state :contestant "Broadcast Square" "New party") (let [gf-scored (get-scored state :contestant 0) bs (get-content state :party2 0)] (core/reveal state :contestant bs) (is (= 2 (get-counters (refresh gf-scored) :agenda)) "Should start with 2 agenda counters") (card-ability state :contestant gf-scored 0) (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (zero? (:click (get-contestant))) "Should have 0 click left") (is (= 10 (:credit (get-contestant))) "Should gain 7 credits from 3 to 10") (is (zero? (:bad-publicity (get-contestant))) "Should gain 0 bad publicity from prevention"))))) (deftest genetic-resequencing ;; Genetic Resequencing (do-game (new-game (default-contestant ["Genetic Resequencing" (qty "Braintrust" 2)]) (default-challenger)) (play-from-hand state :contestant "Braintrust" "New party") (play-from-hand state :contestant "Braintrust" "New party") (play-from-hand state :contestant "Genetic Resequencing" "New party") (let [bt1 (get-content state :party1 0) bt2 (get-content state :party2 0) gr (get-content state :party3 0)] (score-agenda state :contestant bt1) (let [btscored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh btscored) :agenda)) "No agenda counters on scored Braintrust") (score-agenda state :contestant gr) (prompt-select :contestant bt2) (is (zero? (get-counters (refresh bt2) :agenda)) "No agenda counters on placed Braintrust; not a valid target") (prompt-select :contestant btscored) (is (= 1 (get-counters (refresh btscored) :agenda)) "1 agenda counter placed on scored Braintrust"))))) (deftest gila-hands-arcology ;; Gila Hands Arcology (do-game (new-game (default-contestant ["Gila Hands Arcology"]) (default-challenger)) (play-and-score state "Gila Hands Arcology") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (core/gain state :contestant :click 2) (let [gha-scored (get-scored state :contestant 0)] (card-ability state :contestant gha-scored 0) (is (= 2 (:click (get-contestant))) "Should spend 2 clicks on Gila Hands") (is (= 8 (:credit (get-contestant))) "Should gain 3 credits from 5 to 8") (card-ability state :contestant gha-scored 0) (is (zero? (:click (get-contestant))) "Should spend 2 clicks on Gila Hands") (is (= 11 (:credit (get-contestant))) "Should gain 3 credits from 8 to 11")))) (deftest glenn-station ;; Glenn Station (do-game (new-game (default-contestant ["Glenn Station" "Character Wall"]) (default-challenger)) (play-and-score state "Glenn Station") (let [gs-scored (get-scored state :contestant 0)] (card-ability state :contestant gs-scored 0) (prompt-card :contestant (find-card "Character Wall" (:hand (get-contestant)))) (is (= 1 (count (:hosted (refresh gs-scored))))) (card-ability state :contestant gs-scored 1) (prompt-card :contestant (find-card "Character Wall" (:hosted (refresh gs-scored)))) (is (zero? (count (:hosted (refresh gs-scored)))))))) (deftest global-food-initiative ;; Global Food Initiative (do-game (new-game (default-contestant [(qty "Global Food Initiative" 2)]) (default-challenger)) (testing "Contestant scores" (is (zero? (:agenda-point (get-challenger))) "Challenger should start with 0 agenda points") (is (zero? (:agenda-point (get-contestant))) "Contestant should start with 0 agenda points") (play-and-score state "Global Food Initiative") (is (= 3 (:agenda-point (get-contestant))) "Contestant should gain 3 agenda points")) (testing "Challenger steals" (play-from-hand state :contestant "Global Food Initiative" "New party") (take-credits state :contestant) (run-on state :party2) (run-successful state) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should gain 2 agenda points, not 3")))) (deftest government-contracts ;; Government Contracts (do-game (new-game (default-contestant ["Government Contracts"]) (default-challenger)) (play-and-score state "Government Contracts") (is (= 2 (:click (get-contestant)))) (card-ability state :contestant (get-scored state :contestant 0) 0) (is (zero? (:click (get-contestant))) "Spent 2 clicks") (is (= 9 (:credit (get-contestant))) "Gained 4 credits"))) (deftest government-takeover ;; Government Takeover (do-game (new-game (default-contestant ["Government Takeover"]) (default-challenger)) (play-and-score state "Government Takeover") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (let [gt-scored (get-scored state :contestant 0)] (card-ability state :contestant gt-scored 0) (is (= 8 (:credit (get-contestant))) "Should gain 3 credits from 5 to 8")))) (deftest graft ;; Graft (letfn [(graft-test [[number-of-picks deck-size]] (let [cards ["Character Wall" "Fire Wall" "Orion"]] (do-game (new-game (default-contestant ["Graft" "Character Wall" "Fire Wall" "Orion"]) (default-challenger)) (starting-hand state :contestant ["Graft"]) (play-and-score state "Graft") (dotimes [current-pick number-of-picks] (prompt-card :contestant (find-card (nth cards current-pick) (:deck (get-contestant))))) (is (= number-of-picks (count (:hand (get-contestant))))) (is (= deck-size (count (:deck (get-contestant))))))))] (doall (map graft-test [[0 3] [1 2] [2 1] [3 0]])))) (deftest hades-fragment ;; Hades Fragment (do-game (new-game (default-contestant ["Hades Fragment" (qty "Hedge Fund" 2)]) (default-challenger)) (starting-hand state :contestant ["Hades Fragment"]) (play-and-score state "Hades Fragment") (take-credits state :contestant) (take-credits state :challenger) (is (= 1 (count (:hand (get-contestant)))) "Contestant should have no opportunity to use Hades Shard") (core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :discard) (take-credits state :contestant) (take-credits state :challenger) (let [hf-scored (get-scored state :contestant 0)] (card-ability state :contestant hf-scored 0) (prompt-select :contestant (find-card "Hedge Fund" (:discard (get-contestant)))) (is (= 2 (count (:deck (get-contestant)))) "R&D should have 2 cards in it after Hades Fragment use")))) (deftest helium-3-deposit ;; Helium-3 Deposit (do-game (new-game (default-contestant ["Helium-3 Deposit" "Chief Slee" "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Chief Slee" "New party") (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (let [cs (get-content state :party1 0) iw (get-character state :hq 0)] (is (zero? (get-counters (refresh cs) :power)) "Chief Slee should start with 0 power counters") (core/reveal state :contestant iw) (run-on state "HQ") (card-ability state :contestant cs 0) (is (= 1 (get-counters (refresh cs) :power)) "Chief Slee should gain 1 power counter") (take-credits state :challenger) (play-and-score state "Helium-3 Deposit") (prompt-choice :contestant "2") (prompt-select :contestant cs) (is (= 3 (get-counters (refresh cs) :power)) "Chief Slee should gain 2 power counters from 1 to 3")))) (deftest high-risk-investment ;; High-Risk Investment (do-game (new-game (default-contestant ["High-Risk Investment"]) (default-challenger)) (play-and-score state "High-Risk Investment") (let [hri-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh hri-scored) :agenda)) "Has 1 agenda counter") (take-credits state :contestant) (is (= 7 (:credit (get-contestant)))) (take-credits state :challenger) (is (= 9 (:credit (get-challenger)))) (card-ability state :contestant hri-scored 0) (is (= 16 (:credit (get-contestant))) "Gained 9 credits") (is (= 2 (:click (get-contestant))) "Spent 1 click") (is (zero? (get-counters (refresh hri-scored) :agenda)) "Spent agenda counter")))) (deftest hollywood-renovation ;; Hollywood Renovation (do-game (new-game (default-contestant ["Hollywood Renovation" "Character Wall"]) (default-challenger)) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "Character Wall" "HQ") (play-from-hand state :contestant "Hollywood Renovation" "New party") (let [hr (get-content state :party1 0) iw (get-character state :hq 0)] (is (zero? (get-counters (refresh hr) :advancement)) "Hollywood Renovation should start with 0 advancement tokens") (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (dotimes [n 5] (advance state (refresh hr)) (prompt-select :contestant (refresh iw))) (is (= 5 (get-counters (refresh hr) :advancement)) "Hollywood Renovation should gain 5 advancement tokens") (is (= 5 (get-counters (refresh iw) :advancement)) "Character Wall should gain 5 advancement tokens") (advance state (refresh hr)) (prompt-select :contestant (refresh iw)) (is (= 6 (get-counters (refresh hr) :advancement)) "Hollywood Renovation should gain 1 from 5 to 6 advancement tokens") (is (= 7 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 from 5 to 7 advancement tokens")))) (deftest hostile-takeover ;; Hostile Takeover (do-game (new-game (default-contestant ["Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Gain 7 credits") (is (= 1 (:bad-publicity (get-contestant))) "Take 1 bad publicity"))) (deftest house-of-knives ;; House of Knives (do-game (new-game (default-contestant ["House of Knives"]) (default-challenger)) (play-and-score state "House of Knives") (let [hok-scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh hok-scored) :agenda)) "House of Knives should start with 3 counters") (take-credits state :contestant) (run-empty-locale state "R&D") (run-phase-43 state) (card-ability state :contestant hok-scored 0) (is (= 1 (count (:discard (get-challenger)))) "Challenger should pay 1 net damage") (run-empty-locale state "R&D") (run-phase-43 state) (card-ability state :contestant hok-scored 0) (card-ability state :contestant hok-scored 0) (is (= 2 (count (:discard (get-challenger)))) "Challenger should pay 1 net damage")))) (deftest ikawah-project ;; Ikawah Project (testing "Basic test" (do-game (new-game (default-contestant ["Ikawah Project"]) (default-challenger)) (play-from-hand state :contestant "Ikawah Project" "New party") (testing "No credits" (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click 3) (run-empty-locale state :party1) (prompt-choice :challenger "No action") (is (zero? (:credit (get-challenger))) "Challenger couldn't afford to steal, so no credits spent") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Ikawah Project")) (testing "No clicks" (take-credits state :challenger) (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click 3) (run-empty-locale state :party1) (prompt-choice :challenger "No action") (is (zero? (:click (get-challenger))) "Challenger couldn't afford to steal, so no clicks spent") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Ikawah Project")) (testing "Enough of both" (take-credits state :challenger) (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click (:click (get-challenger))) (core/gain state :challenger :credit 5 :click 4) (is (= 5 (:credit (get-challenger))) "Challenger should be reset to 5 credits") (is (= 4 (:click (get-challenger))) "Challenger should be reset to 4 clicks") (run-empty-locale state :party1) (prompt-choice-partial :challenger "Pay") (prompt-choice :challenger "[Click]") (prompt-choice :challenger "2 [Credits]") (is (= 2 (:click (get-challenger))) "Challenger should lose 1 click to steal") (is (= 3 (:credit (get-challenger))) "Challenger should lose 2 credits to steal") (is (= 3 (:agenda-point (get-challenger)))) (is (= 1 (count (:scored (get-challenger)))) "Challenger should steal Ikawah Project")))) (testing "Not stealing" ;; do not reveal when the Challenger does not steal from R&D (do-game (new-game (default-contestant [(qty "Ikawah Project" 2)]) (default-challenger)) (take-credits state :contestant) (starting-hand state :contestant ["Ikawah Project"]) (run-empty-locale state "R&D") (prompt-choice :challenger "No action") (is (not (last-log-contains? state "Ikawah Project")) "Ikawah Project should not be mentioned") (run-empty-locale state "HQ") (prompt-choice :challenger "No action") (is (last-log-contains? state "Ikawah Project") "Ikawah Project should be mentioned")))) (deftest illicit-sales ;; Illicit Sales (letfn [(illicit-sales-test [[starting-bp answer credits-gained]] (testing (str "starting with " starting-bp " and answering " answer " and gaining " credits-gained) (do-game (new-game (default-contestant ["Illicit Sales"]) (default-challenger)) (let [credits (:credit (get-contestant))] (core/gain state :contestant :bad-publicity starting-bp) (play-and-score state "Illicit Sales") (prompt-choice :contestant answer) (is (= (:credit (get-contestant)) (+ credits credits-gained)))))))] (doall (map illicit-sales-test [[0 "No" 0] [0 "Yes" 3] [1 "No" 3] [1 "Yes" 6] [2 "No" 6] [2 "Yes" 9] [3 "No" 9] [3 "Yes" 12]])))) (deftest improved-protein-source ;; Improved Protein Source (do-game (new-game (default-contestant [(qty "Improved Protein Source" 2)]) (default-challenger)) (is (= 5 (:credit (get-challenger))) "Challenger starts with 5 credits") (play-and-score state "Improved Protein Source") (is (= 9 (:credit (get-challenger))) "Challenger should gain 4 credits from Contestant scoring") (play-from-hand state :contestant "Improved Protein Source" "New party") (take-credits state :contestant) (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (is (= 13 (:credit (get-challenger))) "Challenger should gain 4 credits from Contestant scoring"))) (deftest improved-tracers ;; Improved Tracers (do-game (new-game (default-contestant ["Improved Tracers" "News Hound"]) (default-challenger)) (play-from-hand state :contestant "News Hound" "HQ") (let [nh (get-character state :hq 0)] (core/reveal state :contestant nh) (is (= 4 (:current-strength (refresh nh))) "Should start with base strength of 4") (is (= 3 (:credit (get-contestant))) "Should have 2 credits after reveal") (play-and-score state "Improved Tracers") (is (= 5 (:current-strength (refresh nh))) "Should gain 1 strength from 4 to 5") (take-credits state :contestant) (run-on state "HQ") (run-phase-43 state) (card-subroutine state :contestant nh 0) (is (= 1 (get-in @state [:bonus :trace])) "Should gain 1 bonus trace strength") (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 1 (:tag (get-challenger))))))) (deftest labyrinthine-locales ;; Labyrinthine Locales (do-game (new-game (default-contestant [(qty "Labyrinthine Locales" 2)]) (default-challenger)) (play-and-score state "Labyrinthine Locales") (play-and-score state "Labyrinthine Locales") (take-credits state :contestant) (let [ls1 (get-scored state :contestant 0) ls2 (get-scored state :contestant 1)] (is (= 2 (get-counters (refresh ls1) :power))) (is (= 2 (get-counters (refresh ls2) :power))) (testing "Don't use token" (run-on state "HQ") (run-jack-out state) (is (:run @state) "Jack out prevent prompt") (prompt-choice :contestant "Done") (is (not (:run @state)) "Contestant does not prevent the jack out, run ends")) (testing "Use token" (run-on state "HQ") (run-jack-out state) (card-ability state :contestant ls1 0) (card-ability state :contestant ls2 0) (card-ability state :contestant ls1 0) (prompt-choice :contestant "Done") (is (:run @state) "Jack out prevented, run is still ongoing") (is (true? (get-in @state [:run :cannot-jack-out])) "Cannot jack out flag is in effect") (run-successful state) (is (not (:run @state)))) (testing "one Labyrinthine is empty but the other still has one token, ensure prompt still occurs" (is (zero? (get-counters (refresh ls1) :power))) (is (= 1 (get-counters (refresh ls2) :power))) (run-on state "HQ") (run-jack-out state) (is (:run @state)) (card-ability state :contestant ls2 0) (prompt-choice :contestant "Done") (is (true? (get-in @state [:run :cannot-jack-out]))) (run-successful state) (is (not (:run @state)))) (testing "No more tokens" (run-on state "HQ") (run-jack-out state) (is (not (:run @state)) "No jack out prevent prompt"))))) (deftest lcharacternse-acquisition ;; Lcharacternse Acquisition (do-game (new-game (default-contestant [(qty "Lcharacternse Acquisition" 4) "Adonis Campaign" "Eve Campaign" "Strongbox" "Contestantorate Troubleshooter"]) (default-challenger)) (testing "Set up" (starting-hand state :contestant ["Lcharacternse Acquisition" "Lcharacternse Acquisition" "Lcharacternse Acquisition" "Lcharacternse Acquisition" "Adonis Campaign" "Strongbox"]) (core/move state :contestant (find-card "Eve Campaign" (:deck (get-contestant))) :discard) (core/move state :contestant (find-card "Contestantorate Troubleshooter" (:deck (get-contestant))) :discard) (core/gain state :contestant :click 4)) (testing "Site & HQ" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Adonis Campaign" (:hand (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party2 0)))) (testing "Region & HQ" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Strongbox" (:hand (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party4 0)))) (testing "Site & Archives" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Eve Campaign" (:discard (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party6 0)))) (testing "Region & Archives" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Contestantorate Troubleshooter" (:discard (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party8 0)))))) (deftest mandatory-seed-replacement ;; Mandatory Seed Replacement (do-game (new-game (default-contestant ["Mandatory Seed Replacement" "Character Wall" "Fire Wall" "Kakugo" "Chum" "RSVP" "Sensei"]) (default-challenger)) (core/click-draw state :contestant 2) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "Character Wall" "Archives") (play-from-hand state :contestant "Fire Wall" "R&D") (play-from-hand state :contestant "Kakugo" "HQ") (play-from-hand state :contestant "Chum" "Archives") (play-from-hand state :contestant "RSVP" "R&D") (play-from-hand state :contestant "Sensei" "HQ") (let [iw (get-character state :archives 0) fw (get-character state :rd 0) kk (get-character state :hq 0) ch (get-character state :archives 1) rs (get-character state :rd 1) sn (get-character state :hq 1)] (core/reveal state :contestant iw) (core/reveal state :contestant fw) (core/reveal state :contestant kk) (core/reveal state :contestant ch) (core/reveal state :contestant rs) (core/reveal state :contestant sn) (play-and-score state "Mandatory Seed Replacement") (prompt-select :contestant (refresh iw)) (prompt-select :contestant (refresh fw)) (prompt-select :contestant (refresh kk)) (prompt-select :contestant (refresh ch)) (prompt-select :contestant (refresh rs)) (prompt-select :contestant (refresh sn))))) (deftest mandatory-regions ;; Mandatory Regions (testing "Gain an additional click" (do-game (new-game (default-contestant ["Mandatory Regions" "Melange Mining Contestant."]) (default-challenger)) (play-and-score state "Mandatory Regions") (is (= 2 (:agenda-point (get-contestant)))) (play-from-hand state :contestant "Melange Mining Contestant." "New party") (let [mmc (get-content state :party2 0)] (core/reveal state :contestant mmc) (take-credits state :contestant) (take-credits state :challenger) (is (= 4 (:click (get-contestant)))) (card-ability state :contestant mmc 0) (is (= 1 (:click (get-contestant))))))) (testing "Lose additional click if sacrifcharacterd" (do-game (new-game (default-contestant ["Mandatory Regions" "Archer"]) (default-challenger)) (play-and-score state "Mandatory Regions") (is (= 2 (:agenda-point (get-contestant)))) (play-from-hand state :contestant "Archer" "HQ") (take-credits state :contestant) (take-credits state :challenger) (let [arc (get-character state :hq 0) mu (get-scored state :contestant 0)] (is (= 4 (:click (get-contestant))) "Contestant should start turn with 4 clicks") (core/reveal state :contestant arc) (prompt-select :contestant (refresh mu)) (is (= 3 (:click (get-contestant))) "Contestant should lose 1 click on agenda sacrifcharacter"))))) (deftest market-research ;; Market Research (do-game (new-game (default-contestant [(qty "Market Research" 2)]) (default-challenger)) (testing "Challenger is not tagged" (play-and-score state "Market Research") (is (= 2 (:agenda-point (get-contestant))) "Only 4 advancements: scored for standard 2 points")) (testing "Challenger is tagged" (core/gain state :challenger :tag 1) (play-and-score state "Market Research") (is (= 5 (:agenda-point (get-contestant))) "5 advancements: scored for 3 points")))) (deftest medical-breakthrough ;; Medical Breakthrough (do-game (new-game (default-contestant [(qty "Medical Breakthrough" 3) (qty "Hedge Fund" 3)]) (default-challenger)) (play-from-hand state :contestant "Medical Breakthrough" "New party") (play-from-hand state :contestant "Medical Breakthrough" "New party") (play-from-hand state :contestant "Hedge Fund") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (take-credits state :challenger) (let [mb2 (get-content state :party2 0)] (advance state mb2 3) (core/score state :contestant {:card (refresh mb2)}) (is (= 2 (:agenda-point (get-contestant))) "Only needed 3 advancements to score")) (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Medical Breakthrough" "New party") (let [mb3 (get-content state :party3 0)] (advance state mb3 2) (core/score state :contestant {:card (refresh mb3)}) (is (= 4 (:agenda-point (get-contestant))) "Only needed 2 advancements to score")))) (deftest merger ;; Merger (do-game (new-game (default-contestant [(qty "Merger" 2)]) (default-challenger)) (play-and-score state "Merger") (is (= 2 (:agenda-point (get-contestant))) "Contestant should score 2 points") (play-from-hand state :contestant "<NAME>" "New party") (take-credits state :contestant) (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (is (= 3 (:agenda-point (get-challenger))) "Challenger should score 3 points"))) (deftest meteor-mining ;; Meteor Mining (testing "when Meteor Mining is stolen" (do-game (new-game (default-contestant ["Meteor Mining"]) (default-challenger)) (play-from-hand state :contestant "Meteor Mining" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should score 2 points"))) (testing "when Meteor Mining is scored" (letfn [(meteor-mining-test [[tags num-choices pick creds dmg]] (do-game (new-game (default-contestant ["Meteor Mining"]) (default-challenger [(qty "Sure Gamble" 7)])) (starting-hand state :challenger (repeat 7 "Sure Gamble")) (let [credits (:credit (get-contestant)) grip (count (:hand (get-challenger)))] (core/gain state :challenger :tag tags) (play-and-score state "Meteor Mining") (is (= num-choices (count (:choices (first (get-in @state [:contestant :prompt])))))) (prompt-choice :contestant pick) (is (= (+ credits creds) (:credit (get-contestant))) (str "Contestant should have " (+ credits creds) " credits")) (is (= (- grip dmg) (count (:hand (get-challenger)))) (str "Challenger should have " (- grip dmg) " cards in hand")))))] (doall (map meteor-mining-test [[0 2 "No action" 0 0] [0 2 "Gain 7 [Credits]" 7 0] [1 2 "No action" 0 0] [1 2 "Gain 7 [Credits]" 7 0] [2 3 "No action" 0 0] [2 3 "Gain 7 [Credits]" 7 0] [2 3 "Do 7 meat damage" 0 7] [3 3 "No action" 0 0] [3 3 "Gain 7 [Credits]" 7 0] [3 3 "Do 7 meat damage" 0 7]]))))) (deftest napd-contract ;; NAPD Contract (testing "basic test" (do-game (new-game (default-contestant ["NAPD Contract"]) (default-challenger)) (play-from-hand state :contestant "NAPD Contract" "New party") (let [napd (get-content state :party1 0)] (advance state napd 2) (take-credits state :contestant) (core/lose state :challenger :credit 2) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal NAPD Contract") (is (= 3 (:credit (get-challenger))) "Challenger couldn't afford to steal, so no credits spent") (take-credits state :challenger) (core/gain state :contestant :bad-publicity 1) (advance state napd 2) (core/score state :contestant {:card (refresh napd)}) (is (some? (get-content state :party1 0)) "Contestant can't score with 4 advancements because of BP") (advance state napd) (core/score state :contestant {:card (refresh napd)}) (is (= 2 (:agenda-point (get-contestant))) "Scored NAPD for 2 points after 5 advancements")))) (testing "scoring requirement increases with bad publicity from Contestantorate Scandal" (do-game (new-game (default-contestant ["NAPD Contract"]) (default-challenger ["Contestantorate Scandal"])) (play-from-hand state :contestant "NAPD Contract" "New party") (let [napd (get-content state :party1 0)] (advance state napd 2) (take-credits state :contestant) (play-from-hand state :challenger "Contestantorate Scandal") (take-credits state :challenger) (advance state napd 2) (core/score state :contestant {:card (refresh napd)}) (is (some? (get-content state :party1 0)) "Contestant can't score with 4 advancements because of BP") (advance state napd) (core/score state :contestant {:card (refresh napd)}) (is (= 2 (:agenda-point (get-contestant))) "Scored NAPD for 2 points after 5 advancements"))))) (deftest net-quarantine ;; Net Quarantine (do-game (new-game (default-contestant ["Net Quarantine"]) (default-challenger)) (core/gain state :challenger :link 1) (core/gain state :contestant :click 3) (play-and-score state "Net Quarantine") (is (= 5 (:credit (get-contestant))) "Contestant has 5 credits") (is (= 1 (:link (get-challenger))) "Challenger has 1 link") (core/init-trace state :contestant {:title "/trace command" :side :contestant} {:base 1}) (prompt-choice :contestant 0) (is (zero? (:link (get-challenger))) "Challenger has 0 link") (prompt-choice :challenger 3) (is (= 1 (:link (get-challenger))) "Challenger has 1 link again") (is (= 6 (:credit (get-contestant))) "Contestant gained a credit from NQ") ; second trace of turn - no link reduction (core/init-trace state :contestant {:title "/trace command" :side :contestant} {:base 1}) (prompt-choice :contestant 0) (is (= 1 (:link (get-challenger))) "Challenger has 1 link") (prompt-choice :challenger 2) (is (= 7 (:credit (get-contestant))) "Contestant gained a credit from NQ"))) (deftest new-construction ;; New Construction (do-game (new-game (default-contestant ["New Construction" (qty "Commercial Bankers Group" 10)]) (default-challenger)) (starting-hand state :contestant (vec (cons "New Construction" (repeat 10 "Commercial Bankers Group")))) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "New Construction" "New party") (let [nc (get-content state :party1 0)] (is (zero? (get-counters (refresh nc) :advancement))) (dotimes [n 4] (advance state (refresh nc)) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Commercial Bankers Group" (:hand (get-contestant))))) (is (= 4 (get-counters (refresh nc) :advancement))) (is (not= :this-turn (:revealed (get-content state :party5 0)))) (let [credits (:credit (get-contestant))] (advance state (refresh nc)) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Commercial Bankers Group" (:hand (get-contestant)))) (is (= 5 (get-counters (refresh nc) :advancement))) (is (= :this-turn (:revealed (get-content state :party6 0)))) (is (= (dec credits) (:credit (get-contestant)))))))) (deftest next-wave-2 ;; NEXT Wave 2 (do-game (new-game (default-contestant [(qty "NEXT Wave 2" 2) "NEXT Bronze"]) (default-challenger)) (is (zero? (:brain-damage (get-challenger))) "Challenger should start with 0 brain damage") (play-from-hand state :contestant "NEXT Bronze" "HQ") (let [nxbr (get-character state :hq 0)] (core/reveal state :contestant nxbr)) (play-and-score state "NEXT Wave 2") (prompt-choice :contestant "No") (is (zero? (:brain-damage (get-challenger))) "Challenger should stay at 0 brain damage") (play-and-score state "NEXT Wave 2") (prompt-choice :contestant "Yes") (is (= 1 (:brain-damage (get-challenger))) "Challenger should gain 1 brain damage"))) (deftest nisei-mk-ii ;; Nisei MK II - Remove hosted counter to ETR, check this works in 4.3 (do-game (new-game (default-contestant ["Nisei MK II"]) (default-challenger)) (play-and-score state "Nisei MK II") (let [scored-nisei (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh scored-nisei) :agenda)) "Scored Nisei has one counter") (take-credits state :contestant) (run-on state "HQ") (run-phase-43 state) (card-ability state :contestant (refresh scored-nisei) 0) (prompt-choice :contestant "Done") ; close 4.3 contestant (is (not (:run @state)) "Run ended by using Nisei counter") (is (zero? (get-counters (refresh scored-nisei) :agenda)) "Scored Nisei has no counters")))) (deftest oaktown-renovation ;; Oaktown Renovation (do-game (new-game (default-contestant ["Oaktown Renovation" "Shipment from SanSan"]) (default-challenger)) (core/gain state :contestant :click 3) (play-from-hand state :contestant "Oaktown Renovation" "New party") (let [oak (get-content state :party1 0)] (is (:revealed (refresh oak)) "Oaktown placed face up") (advance state oak) (is (= 6 (:credit (get-contestant))) "Spent 1 credit to advance, gained 2 credits from Oaktown") (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant oak) (is (= 3 (get-counters (refresh oak) :advancement))) (is (= 6 (:credit (get-contestant))) "No credits gained due to advancements being placed") (advance state oak) (is (= 7 (:credit (get-contestant))) "Spent 1 credit to advance, gained 2 credits from Oaktown") (advance state oak) (is (= 5 (get-counters (refresh oak) :advancement))) (is (= 9 (:credit (get-contestant))) "Spent 1 credit to advance, gained 3 credits from Oaktown")))) (deftest obokata-protocol ;; Obotaka Protocol (do-game (new-game (make-deck "Cardnum: Personal Evolution" [(qty "Obokata Protocol" 10)]) (default-challenger [(qty "Sure Gamble" 4)])) (play-from-hand state :contestant "Obokata Protocol" "New party") (take-credits state :contestant) (core/gain state :challenger :agenda-point 6) (run-empty-locale state "Locale 1") (prompt-choice-partial :challenger "Pay") (is (= 4 (count (:discard (get-challenger)))) "Challenger paid 4 net damage") (is (= :challenger (:winner @state)) "Challenger wins") (is (= "Agenda" (:reason @state)) "Win condition reports agenda points") (is (last-log-contains? state "wins the game") "PE did not fire"))) (deftest paper-trail ;; Paper Trail (do-game (new-game (default-contestant ["Paper Trail"]) (default-challenger ["Aeneas Informant" "Bank Job" "Rosetta 2.0" "Magnum Opus" "Astrolabe"])) (take-credits state :contestant) (core/gain state :challenger :click 10 :credit 10) (play-from-hand state :challenger "Aeneas Informant") (play-from-hand state :challenger "Bank Job") (play-from-hand state :challenger "Rosetta 2.0") (play-from-hand state :challenger "Magnum Opus") (play-from-hand state :challenger "Astrolabe") (take-credits state :challenger) (play-and-score state "Paper Trail") (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 2 (count (:discard (get-challenger))))) (is (some? (get-radicle state 0))) (is (= 1 (count (get-radicle state)))) (is (some? (get-resource state 0))) (is (some? (get-hazard state 0))))) (deftest personality-profiles ;; Personality Profiles (testing "basic test" (do-game (new-game (default-contestant ["Personality Profiles"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" (qty "Patron" 2)])) (starting-hand state :challenger ["Self-modifying Code" "Clone Chip" "Patron" "Patron"]) (play-and-score state "Personality Profiles") (take-credits state :contestant) (play-from-hand state :challenger "Self-modifying Code") (play-from-hand state :challenger "Clone Chip") (let [smc (get-resource state 0)] (card-ability state :challenger smc 0) (prompt-card :challenger (find-card "Corroder" (:deck (get-challenger)))) (is (= 2 (count (:discard (get-challenger)))))) (let [chip (get-hazard state 0)] (card-ability state :challenger chip 0) (prompt-select :challenger (find-card "Self-modifying Code" (:discard (get-challenger)))) (is (second-last-log-contains? state "Patron") "Personality Profiles discarded card name is in log") (is (= 3 (count (:discard (get-challenger)))))))) (testing "Ensure effects still fire with an empty hand, #1840" (do-game (new-game (default-contestant ["Personality Profiles"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder"])) (starting-hand state :challenger ["Self-modifying Code" "Clone Chip"]) (play-and-score state "Personality Profiles") (take-credits state :contestant) (play-from-hand state :challenger "Self-modifying Code") (play-from-hand state :challenger "Clone Chip") (let [smc (get-resource state 0)] (card-ability state :challenger smc 0) (prompt-card :challenger (find-card "Corroder" (:deck (get-challenger))))) (let [cor (get-resource state 0)] (is (some? cor)) (is (= (:title cor) "Corroder")) (is (= "Self-modifying Code" (:title (first (:discard (get-challenger))))))) (let [chip (get-hazard state 0)] (card-ability state :challenger chip 0) (prompt-select :challenger (find-card "Self-modifying Code" (:discard (get-challenger))))) (let [smc (get-resource state 1)] (is (some? smc)) (is (= (:title smc) "Self-modifying Code")) (is (= "Clone Chip" (:title (first (:discard (get-challenger)))))))))) (deftest philotic-entanglement ;; Philotic Entanglement (do-game (new-game (default-contestant ["Philotic Entanglement" (qty "House of Knives" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Cache" 2)])) (play-from-hand state :contestant "House of Knives" "New party") (play-from-hand state :contestant "House of Knives" "New party") (play-from-hand state :contestant "House of Knives" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (run-empty-locale state :party3) (prompt-choice :challenger "Steal") (is (= 3 (count (:scored (get-challenger))))) (take-credits state :challenger) (play-and-score state "Philotic Entanglement") (is (= 2 (:agenda-point (get-contestant)))) (is (= 3 (count (:discard (get-challenger)))) "Dealt 3 net damage upon scoring"))) (deftest posted-bounty ;; Posted Bounty (testing "Forfeiting takes 1 bad publicity" (do-game (new-game (default-contestant ["Posted Bounty"]) (default-challenger)) (play-and-score state "Posted Bounty") (prompt-choice :contestant "Yes") (is (zero? (:agenda-point (get-contestant))) "Forfeiting Posted Bounty nullifies agenda points") (is (= 1 (:bad-publicity (get-contestant))) "Forfeiting takes 1 bad publicity") (is (= 1 (:tag (get-challenger))) "Challenger receives 1 tag forfeiting Posted Bounty"))) (testing "Choosing not to forfeit scores normally" (do-game (new-game (default-contestant ["Posted Bounty"]) (default-challenger)) (play-and-score state "Posted Bounty") (prompt-choice :contestant "No") (is (= 1 (:agenda-point (get-contestant)))) (is (zero? (:bad-publicity (get-contestant)))) (is (zero? (:tag (get-challenger))))))) (deftest priority-requisition ;; Priority Requisition (do-game (new-game (default-contestant ["Priority Requisition" "Archer"]) (default-challenger)) (play-from-hand state :contestant "Archer" "HQ") (let [arc (get-character state :hq 0)] (play-and-score state "Priority Requisition") (prompt-select :contestant arc) (is (:revealed (refresh arc)))))) (deftest private-security-force ;; Private Security Force (do-game (new-game (default-contestant [(qty "Private Security Force" 10)]) (default-challenger)) (core/gain state :challenger :tag 1) (play-and-score state "Private Security Force") (let [psf-scored (get-scored state :contestant 0)] (card-ability state :contestant psf-scored 0) (is (= 1 (count (:discard (get-challenger))))) (take-credits state :challenger) (dotimes [n 3] (card-ability state :contestant psf-scored 0)) (is (= 3 (count (:discard (get-challenger))))) (is (= :contestant (:winner @state)) "Contestant wins") (is (= "Flatline" (:reason @state)) "Win condition reports flatline")))) (deftest profiteering ;; Profiteering (do-game (new-game (default-contestant ["Profiteering"]) (default-challenger)) (play-and-score state "Profiteering") (prompt-choice :contestant "3") (is (= 1 (:agenda-point (get-contestant)))) (is (= 3 (:bad-publicity (get-contestant))) "Took 3 bad publicity") (is (= 20 (:credit (get-contestant))) "Gained 15 credits"))) (deftest project-ares ;; Project Ares (do-game (new-game (default-contestant [(qty "Project Ares" 2)]) (default-challenger ["Clone Chip"])) (take-credits state :contestant) (play-from-hand state :challenger "Clone Chip") (take-credits state :challenger) (play-and-score state "Project Ares") (is (empty? (get-in @state [:challenger :prompt])) "No prompt for Challenger if scored with 4 advancement tokens") (core/gain state :contestant :click 5) (play-from-hand state :contestant "Project Ares" "New party") (let [ares (get-content state :party2 0)] (advance state ares 6) (is (= 6 (get-counters (refresh ares) :advancement))) (core/score state :contestant {:card (refresh ares)}) (is (prompt-is-card? :challenger ares) "Challenger has Ares prompt to discard placed cards")) (prompt-select :challenger (find-card "Clone Chip" (:hazard (:rig (get-challenger))))) (is (empty? (get-in @state [:challenger :prompt])) "Challenger must discard 2 cards but only has 1 card in rig, prompt ended") (is (= 1 (count (:discard (get-challenger))))) (is (= 1 (:bad-publicity (get-contestant)))))) (deftest project-atlas ;; Project Atlas (testing "basic test" (do-game (new-game (default-challenger ["Project Atlas" "Beanstalk Royalties"]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Project Atlas"]) (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party1 0)] (advance state atlas 4) (is (= 4 (get-counters (refresh atlas) :advancement)) "Atlas should have 4 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant)))) (is (zero? (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 0 agenda counters") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand")))) (testing "test with Titan" (do-game (new-game (make-deck "Titan Transnational: Investing In Your Future" [(qty "Project Atlas" 2) "Beanstalk Royalties" "Hedge Fund"]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Project Atlas" "Project Atlas"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party1 0)] (advance state atlas 3) (is (= 3 (get-counters (refresh atlas) :advancement)) "Atlas should have 3 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant)))) (is (zero? (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 0 agenda counters") (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 card in hand")) ;; Should gain 2 counters (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party2 0)] (advance state atlas 4) (is (= 4 (get-counters (refresh atlas) :advancement)) "Atlas should have 4 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 1)] (is (= 2 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 2 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Hedge Fund" (:deck (get-contestant)))) (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counters") (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 cards in hand"))))) (deftest project-beale ;; Project Beale (do-game (new-game (default-contestant [(qty "Project Beale" 2)]) (default-challenger)) (core/gain state :contestant :click 8 :credit 8) (play-from-hand state :contestant "Project Beale" "New party") (let [pb1 (get-content state :party1 0)] (advance state pb1 4) (core/score state :contestant {:card (refresh pb1)}) (is (= 2 (:agenda-point (get-contestant))) "Only 4 advancements: scored for standard 2 points") (play-from-hand state :contestant "Project Beale" "New party")) (let [pb2 (get-content state :party2 0)] (advance state pb2 5) (core/score state :contestant {:card (refresh pb2)}) (is (= 5 (:agenda-point (get-contestant))) "5 advancements: scored for 3 points")))) (deftest project-kusanagi ;; Project Kusanagi (do-game (new-game (default-contestant [(qty "Project Kusanagi" 2) "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (core/gain state :contestant :click 10 :credit 10) (testing "Should gain 0 counters" (play-and-score state "Project Kusanagi") (let [pk-scored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh pk-scored) :agenda)) "Kusanagi should start with 0 agenda counters"))) (testing "Should gain 1 counter" (play-from-hand state :contestant "Project Kusanagi" "New party") (let [pk (get-content state :party2 0)] (advance state pk 3) (is (= 3 (get-counters (refresh pk) :advancement)) "Kusanagi should have 3 advancement tokens") (core/score state :contestant {:card (refresh pk)})) (let [pk-scored (get-scored state :contestant 1)] (is (= 1 (get-counters (refresh pk-scored) :agenda)) "Kusanagi should have 1 agenda counter") (run-empty-locale state :hq) (card-ability state :contestant pk-scored 0) (is (last-log-contains? state "Do 1 net damage")) (is (zero? (get-counters (refresh pk-scored) :agenda)) "Kusanagi should have 0 agenda counters"))))) (deftest project-vitruvius ;; Project Vitruvius (do-game (new-game (default-contestant ["Project Vitruvius" "Hedge Fund"]) (default-challenger)) ;; Set up (core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :discard) (is (= 1 (count (:discard (get-contestant)))) "Contestant should have 1 cards in hand") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Vitruvius" "New party") (let [vit (get-content state :party1 0)] (advance state vit 4) (is (= 4 (get-counters (refresh vit) :advancement)) "Vitruvius should have 4 advancement tokens") (core/score state :contestant {:card (refresh vit)})) (let [vit-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh vit-scored) :agenda)) "Vitruvius should have 1 agenda counter") (card-ability state :contestant vit-scored 0) (prompt-select :contestant (find-card "Hedge Fund" (:discard (get-contestant)))) (is (zero? (get-counters (refresh vit-scored) :agenda)) "Vitruvius should have 0 agenda counters") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand")))) (deftest project-wotan ;; Project Wotan - Only checks if agenda counter is spent (do-game (new-game (default-contestant ["Project Wotan" "Eli 1.0" (qty "Hedge Fund" 3)]) (default-challenger)) (starting-hand state :contestant ["Project Wotan" "Eli 1.0"]) (play-from-hand state :contestant "Eli 1.0" "HQ") (let [eli (get-character state :hq 0)] (core/reveal state :contestant eli)) (play-and-score state "Project Wotan") (take-credits state :contestant) (let [wot-scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh wot-scored) :agenda)) "Wotan should start with 3 agenda counters") (run-on state "HQ") (card-ability state :contestant wot-scored 0) (is (= 2 (get-counters (refresh wot-scored) :agenda))) "Wotan should only have 2 agenda counters"))) (deftest puppet-master ;; Puppet Master - game progresses if no valid targets. Issue #1661. (do-game (new-game (default-contestant ["Puppet Master"]) (default-challenger)) (play-and-score state "Puppet Master") (take-credits state :contestant) (run-empty-locale state :archives) (prompt-choice :contestant "Done") (is (empty? (:prompt (get-challenger))) "Challenger's waiting prompt resolved"))) (deftest quantum-predictive-model ;; Quantum Predictive Model (do-game (new-game (default-contestant [(qty "Quantum Predictive Model" 4)]) (default-challenger)) (testing "Set up" (starting-hand state :contestant ["Quantum Predictive Model" "Quantum Predictive Model"]) (play-from-hand state :contestant "Quantum Predictive Model" "New party") (play-from-hand state :contestant "Quantum Predictive Model" "New party") (take-credits state :contestant)) (testing "Access placed with no tag" (run-on state :party1) (run-successful state) (prompt-choice :challenger "Steal") (is (= 1 (:agenda-point (get-challenger))) "Challenger should steal")) (testing "Access R&D with no tag" (run-on state :rd) (run-successful state) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should steal")) (core/gain state :challenger :tag 1) (testing "Access intalled with tag" (run-on state :party2) (run-successful state) (prompt-choice :challenger "No action") ;; this is now a prompt that QPM was added to Contestant score area (is (= 2 (:agenda-point (get-challenger))) "Challenger should not steal") (is (= 1 (:agenda-point (get-contestant))) "Contestant should score")) (testing "Access R&D with tag" (run-on state :rd) (run-successful state) (prompt-choice :challenger "No action") (is (= 2 (:agenda-point (get-challenger))) "Challenger should not steal") (is (= 2 (:agenda-point (get-contestant))) "Contestant should score")) (is (zero? (count (:deck (get-contestant))))))) (deftest rebranding-team ;; Rebranding Team (do-game (new-game (default-contestant ["Rebranding Team" "Launch Campaign" "City Surveillance" "<NAME>" "Museum of History" "Advanced Assembly Lines"]) (default-challenger)) (play-and-score state "Rebranding Team") (core/click-draw state :challenger 1) (is (core/has-subtype? (find-card "Advanced Assembly Lines" (:hand (get-contestant))) "Advertisement")) ; #2608 part 2 - retain Advertisement always (discard-from-hand state :contestant "Advanced Assembly Lines") (is (core/has-subtype? (find-card "Advanced Assembly Lines" (:discard (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "Launch Campaign" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "City Surveillance" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "<NAME>" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "<NAME>" (:hand (get-contestant))) "Executive")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Alliance")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Ritzy")) (core/move state :contestant (find-card "Rebranding Team" (:scored (get-contestant))) :deck) (is (core/has-subtype? (find-card "Launch Campaign" (:hand (get-contestant))) "Advertisement")) (is (not (core/has-subtype? (find-card "Advanced Assembly Lines" (:discard (get-contestant))) "Advertisement"))) (is (not (core/has-subtype? (find-card "City Surveillance" (:hand (get-contestant))) "Advertisement"))) (is (not (core/has-subtype? (find-card "<NAME>" (:hand (get-contestant))) "Advertisement"))) (is (core/has-subtype? (find-card "<NAME>" (:hand (get-contestant))) "Executive")) (is (not (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Advertisement"))) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Alliance")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Ritzy")))) (deftest reeducation ;; Reeducation (testing "Simple test" (do-game (new-game (default-contestant ["Reeducation" "Sweeps Week" "Hedge Fund" "<NAME>" "<NAME>"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" "Sure Gamble" "Desperado"])) (starting-hand state :contestant ["Reeducation" "Sweeps Week"]) (starting-hand state :challenger ["Self-modifying Code"]) (play-and-score state "Reeducation") (is (prompt-is-type? :challenger :waiting) "Challenger has wait prompt") (is (= 1 (count (get-in @state [:contestant :hand])))) (is (= 1 (count (get-in @state [:challenger :hand])))) (prompt-card :contestant (find-card "Sweeps Week" (:hand (get-contestant)))) ; put Sweeps Week at bottom of R&D (prompt-choice :contestant "Done") ; finished selecting cards (prompt-choice :contestant "Done") ; contestant prompt for Done/Start Over (is (= "Sweeps Week" (:title (last (:deck (get-contestant)))))) (is (= "Self-modifying Code" (:title (last (:deck (get-challenger)))))) (is (= 1 (count (get-in @state [:contestant :hand])))) (is (zero? (count (get-in @state [:challenger :hand])))))) (testing "Extra cards" ;; If Contestant is adding more cards in HQ than Challenger has in their Grip, Challenger ;; is not 'able' to resolve the effect and doesn't have to add to bottom of Stack (do-game (new-game (default-contestant ["Reeducation" "Sweeps Week" "Hedge Fund" "<NAME>" "<NAME>"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" "Sure Gamble" "Desperado"])) (starting-hand state :contestant ["Reeducation" "Sweeps Week" "Hedge Fund"]) (starting-hand state :challenger ["Self-modifying Code"]) (play-and-score state "Reeducation") (is (prompt-is-type? :challenger :waiting) "Challenger has wait prompt") (is (= 2 (count (:hand (get-contestant))))) (is (= 1 (count (:hand (get-challenger))))) (prompt-card :contestant (find-card "Sweeps Week" (:hand (get-contestant)))) (prompt-card :contestant (find-card "Hedge Fund" (:hand (get-contestant)))) ; this is the bottom card of R&D (prompt-choice :contestant "Done") ; finished selecting cards (prompt-choice :contestant "Done") ; contestant prompt for Done/Start Over (is (= "Hedge Fund" (:title (last (:deck (get-contestant)))))) (is (= "Sweeps Week" (:title (last (butlast (:deck (get-contestant))))))) (is (= "Self-modifying Code" (:title (first (:hand (get-challenger)))))) (is (= 2 (count (:hand (get-contestant))))) (is (= 1 (count (:hand (get-challenger)))))))) (deftest party-data-farm ;; Party Data Farm (do-game (new-game (default-contestant ["Party Data Farm"]) (default-challenger)) (is (= 5 (get-hand-size :contestant))) (play-and-score state "Party Data Farm") (is (= 7 (get-hand-size :contestant))))) (deftest party-enforcement ;; Party Enforcement - Search R&D for a piece of character and place it on a party at no reveal cost (do-game (new-game (default-contestant [(qty "Party Enforcement" 2) "Archer" "Chiyashi"]) (make-deck "Re<NAME> Roja: Freedom Fighter" [])) (starting-hand state :contestant ["Party Enforcement" "Party Enforcement"]) (is (= 2 (count (:deck (get-contestant))))) (play-and-score state "Party Enforcement") (let [N (:credit (get-contestant))] (prompt-choice :contestant "Yes") (prompt-choice :contestant (find-card "Chiyashi" (:deck (get-contestant)))) (prompt-choice :contestant "New party") (is (core/revealed? (get-character state :party2 0)) "Chiyashi was placed revealed") (is (= N (:credit (get-contestant))) "Revealing Chiyashi was free")) (play-and-score state "Party Enforcement") (let [N (:credit (get-contestant))] (prompt-choice :contestant "Yes") (prompt-card :contestant (find-card "Archer" (:deck (get-contestant)))) (prompt-choice :contestant "Locale 2") (is (= (dec N) (:credit (get-contestant))) "Placing Archer cost a credit") (is (not-empty (:prompt (get-contestant))) "Contestant prompted to forfeit an agenda for Archer") (is (= (dec N) (:credit (get-contestant))) "Revealing Archer didn't cost any credits")))) (deftest research-grant ;; Research Grant (testing "Basic test" (do-game (new-game (default-contestant [(qty "Research Grant" 2)]) (default-challenger)) (play-from-hand state :contestant "Research Grant" "New party") (play-and-score state "Research Grant") (prompt-select :contestant (get-content state :party1 0)) (is (= 2 (count (:scored (get-contestant)))) "2 copies of Research Grant scored"))) (testing "vs Leela" ;; Issue #3069 (do-game (new-game (default-contestant [(qty "Research Grant" 2) (qty "Character Wall" 2)]) (make-deck "Leela Patel: Trained Pragmatist" ["Sure Gamble"])) (core/gain state :contestant :click 1) (play-from-hand state :contestant "Character Wall" "HQ") (play-from-hand state :contestant "Character Wall" "R&D") (play-from-hand state :contestant "Research Grant" "New party") (play-and-score state "Research Grant") (prompt-select :contestant (get-content state :party1 0)) (is (= 2 (count (:scored (get-contestant)))) "2 copies of Research Grant scored") (prompt-select :challenger (get-character state :hq 0)) (prompt-select :challenger (get-character state :rd 0)) (is (empty? (:effect-completed @state)) "All score and Leela effects resolved")))) (deftest restructured-datapool ;; Restructured Datapool (do-game (new-game (default-contestant ["Restructured Datapool"]) (default-challenger)) (is (zero? (:tag (get-challenger))) "Challenger should start with no tags") (play-and-score state "Restructured Datapool") (let [rd-scored (get-scored state :contestant 0)] (card-ability state :contestant rd-scored 0) (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 1 (:tag (get-challenger))) "Challenger should gain a tag from Restructured Datapool ability")))) (deftest self-destruct-chips ;; Self-Destruct Chips (do-game (new-game (default-contestant ["Self-Destruct Chips"]) (default-challenger)) (is (= 5 (get-hand-size :challenger)) "Challenger's hand size starts at 5") (play-and-score state "Self-Destruct Chips") (is (= 4 (get-hand-size :challenger)) "By scoring Self-Destruct Chips, Challenger's hand size is reduced by 1"))) (deftest sensor-net-activation ;; Sensor Net Activation (do-game (new-game (default-contestant [(qty "Sensor Net Activation" 2) "Enforcer 1.0" "Ash 2X3ZB9CY"]) (default-challenger)) (play-from-hand state :contestant "Enforcer 1.0" "HQ") (play-and-score state "Sensor Net Activation") (let [sna-scored (get-scored state :contestant 0) enf (get-character state :hq 0)] (is (= 1 (get-counters (refresh sna-scored) :agenda)) "Should start with 1 agenda counter") (is (not (:revealed (refresh enf))) "Enforcer 1.0 should start hidden") (card-ability state :contestant (refresh sna-scored) 0) (prompt-select :contestant enf) (is (:revealed (refresh enf)) "Enforcer 1.0 should be revealed") (is (= 1 (count (:scored (get-contestant)))) "Enforcer 1.0 should be revealed without forfeiting agenda") (take-credits state :contestant) (is (not (:revealed (refresh enf))) "Enforcer 1.0 should be hidden")) (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Ash 2X3ZB9CY" "New party") (play-and-score state "Sensor Net Activation") (let [sna-scored (get-scored state :contestant 1) ash (get-content state :party2 0)] (is (= 1 (get-counters (refresh sna-scored) :agenda)) "Should start with 1 agenda counter") (is (not (:revealed (refresh ash))) "Ash should start hidden") (card-ability state :contestant (refresh sna-scored) 0) (prompt-select :contestant ash) (is (:revealed (refresh ash)) "Ash should be revealed") (take-credits state :contestant) (is (not (:revealed (refresh ash))) "Ash should be hidden")))) (deftest sentinel-defense-resource ;; Sentinel Defense Resource - Doesn't fire if brain damage is prevented (do-game (new-game (default-contestant ["Sentinel Defense Resource" "Viktor 1.0"]) (default-challenger ["Feedback Filter" (qty "Sure Gamble" 3)])) (play-and-score state "Sentinel Defense Resource") (play-from-hand state :contestant "Viktor 1.0" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Feedback Filter") (let [viktor (get-character state :hq 0) ff (get-hazard state 0)] (run-on state "HQ") (core/reveal state :contestant viktor) (card-subroutine state :contestant viktor 0) (prompt-choice :challenger "Done") ;; Don't prevent the brain damage (is (= 1 (count (:discard (get-challenger))))) (is (= 1 (:brain-damage (get-challenger)))) (prompt-choice :challenger "Done") ;; So we take the net, but don't prevent it either (is (= 2 (count (:discard (get-challenger))))) (card-subroutine state :contestant viktor 0) (card-ability state :challenger ff 1) ;; Prevent the brain damage this time (prompt-choice :challenger "Done") (is (= 3 (count (:discard (get-challenger)))) "Feedback filter discarded, didn't take another net damage") (is (= 1 (:brain-damage (get-challenger))))))) (deftest show-of-force ;; Show of Force (do-game (new-game (default-contestant ["Show of Force"]) (default-challenger)) (is (= 3 (count (:hand (get-challenger)))) "Challenger should start with 3 cards in hand") (play-and-score state "Show of Force") (is (= 1 (count (:hand (get-challenger)))) "Challenger should have 1 card in hand") (is (= 2 (count (:discard (get-challenger)))) "Challenger should have discarded 2 cards"))) (deftest ssl-endorsement ;; SSL Endorsement (testing "gain credits when in contestant score area before turn begins" (do-game (new-game (default-contestant ["SSL Endorsement"]) (default-challenger)) (play-and-score state "SSL Endorsement") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 5 (:credit (get-contestant))) "Contestant starts with 5 credits") (prompt-choice :contestant "Yes") (is (= 8 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 8 (:credit (get-contestant))) "Contestant starts with 8 credits") (prompt-choice :contestant "No") (is (= 8 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 8 (:credit (get-contestant))) "Contestant starts with 8 credits") (prompt-choice :contestant "Yes") (is (= 11 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 11 (:credit (get-contestant))) "Contestant starts with 11 credits") (prompt-choice :contestant "Yes") (is (= 14 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money"))) (testing "gain credits when in challenger score area before turn begins" (do-game (new-game (default-contestant ["SSL Endorsement"]) (default-challenger)) (play-from-hand state :contestant "SSL Endorsement" "New party") (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 7 (:credit (get-contestant))) "Contestant starts with 7 credits") (prompt-choice :contestant "Yes") (is (= 10 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits") (prompt-choice :contestant "No") (is (= 10 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits") (prompt-choice :contestant "Yes") (is (= 13 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 13 (:credit (get-contestant))) "Contestant starts with 13 credits") (prompt-choice :contestant "Yes") (is (= 16 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money"))) (testing "register event when agenda swapped with Turntable" ;; Regression test for #3114 (do-game (new-game (default-contestant ["SSL Endorsement" "Breaking News"]) (default-challenger ["Turntable"])) (play-from-hand state :contestant "Breaking News" "New party") (play-and-score state "SSL Endorsement") (take-credits state :contestant) (play-from-hand state :challenger "Turntable") (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (prompt-choice :challenger "Yes") (prompt-select :challenger (find-card "SSL Endorsement" (:scored (get-contestant)))) ;; Swap BN with SSL (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 6 (:credit (get-contestant))) "Contestant starts with 7 credits") (prompt-choice :contestant "Yes") (is (= 9 (:credit (get-contestant))) "Contestant gains 3 credits from Turntable'd SSL Endorsement"))) (testing "don't double register event when agenda is swapped" (do-game (new-game (default-contestant ["SSL Endorsement" "Breaking News" "Exchange of Information"]) (default-challenger)) (play-from-hand state :contestant "SSL Endorsement" "New party") (play-and-score state "Breaking News") (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 6 (:credit (get-contestant))) "Contestant starts with 6 credits") (prompt-choice :contestant "Yes") (is (= 9 (:credit (get-contestant))) "Contestant gains 3 credits") (core/gain state :challenger :tag 1) (play-from-hand state :contestant "Exchange of Information") (prompt-select :contestant (find-card "SSL Endorsement" (:scored (get-challenger)))) (prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant)))) (take-credits state :challenger) (is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits") (prompt-choice :contestant "No") (is (empty? (:prompt (get-contestant))) "Not double prompted for credits") (is (= 9 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits") (prompt-choice :contestant "Yes") (is (= 12 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 12 (:credit (get-contestant))) "Contestant starts with 12 credits") (prompt-choice :contestant "Yes") (is (= 15 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money")))) (deftest standoff ;; Standoff (testing "Challenger declines first" (do-game (new-game (default-contestant ["Standoff" "Character Wall" "News Team"]) (default-challenger ["Cache"])) (starting-hand state :contestant ["Standoff" "Character Wall"]) (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Cache") (take-credits state :challenger) (play-and-score state "Standoff") (starting-hand state :contestant []) (is (zero? (-> (get-challenger) :discard count)) "Challenger should have no cards in Heap") (prompt-select :challenger (get-resource state 0)) (is (= 1 (-> (get-challenger) :discard count)) "Challenger should now have 1 card in Heap") (is (zero? (-> (get-contestant) :discard count)) "Contestant should have no cards in Archives") (prompt-select :contestant (get-character state :hq 0)) (is (= 1 (-> (get-contestant) :discard count)) "Contestant should now have 1 card in Archives") (is (zero? (-> (get-contestant) :hand count)) "Contestant should have no cards in hand") (let [credits (:credit (get-contestant))] (prompt-choice :challenger "Done") (is (= (+ credits 5) (:credit (get-contestant))) "Contestant should gain 5 credits from Challenger declining to discard an placed card") (is (= 1 (-> (get-contestant) :hand count)) "Contestant should draw a card from Challenger declining to discard an placed card")))) (testing "Contestant declines first" (do-game (new-game (default-contestant ["Standoff" "Character Wall" "News Team"]) (default-challenger ["Cache" "Cache"])) (starting-hand state :contestant ["Standoff" "Character Wall"]) (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Cache") (play-from-hand state :challenger "Cache") (take-credits state :challenger) (play-and-score state "Standoff") (starting-hand state :contestant []) (is (zero? (-> (get-challenger) :discard count)) "Challenger should have no cards in Heap") (prompt-select :challenger (get-resource state 0)) (is (= 1 (-> (get-challenger) :discard count)) "Challenger should now have 1 card in Heap") (is (zero? (-> (get-contestant) :discard count)) "Contestant should have no cards in Archives") (prompt-select :contestant (get-character state :hq 0)) (is (= 1 (-> (get-contestant) :discard count)) "Contestant should now have 1 card in Archives") (is (zero? (-> (get-contestant) :hand count)) "Contestant should have no cards in hand") (prompt-select :challenger (get-resource state 0)) (is (= 2 (-> (get-challenger) :discard count)) "Challenger should now have 2 cards in Heap") (let [credits (:credit (get-contestant))] (prompt-choice :contestant "Done") (is (= credits (:credit (get-contestant))) "Contestant should gain no credits from declining to discard an placed card") (is (zero? (-> (get-contestant) :hand count)) "Contestant should draw no cards from declining to discard an placed card"))))) (deftest successful-field-test ;; Successful Field Test (do-game (new-game (default-contestant ["Successful Field Test" (qty "Character Wall" 10)]) (default-challenger)) (starting-hand state :contestant (vec (cons "Successful Field Test" (repeat 10 "Character Wall")))) (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (play-and-score state "Successful Field Test") (dotimes [n 10] (prompt-select :contestant (find-card "Character Wall" (:hand (get-contestant)))) (prompt-choice :contestant "HQ")) (is (= 5 (:credit (get-contestant))) "Should still have 5 credits") (is (some? (get-character state :hq 9))))) (deftest superior-cyberwalls ;; Superior Cyberwalls (do-game (new-game (default-contestant ["Superior Cyberwalls" "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (let [iw (get-character state :hq 0)] (core/reveal state :contestant iw) (is (= 1 (:current-strength (refresh iw))) "Should start with base strength of 1") (is (= 4 (:credit (get-contestant))) "Should have 4 credits after reveal") (play-and-score state "Superior Cyberwalls") (is (= 2 (:current-strength (refresh iw))) "Should gain 1 strength from 1 to 2") (is (= 5 (:credit (get-contestant))) "Should gain 1 credit for revealed barrier")))) (deftest tgtbt ;; TGTBT - Give the Challenger 1 tag when they access ;; OHG still not working... (do-game (new-game (default-contestant [(qty "TGTBT" 2) "Old Hollywood Grid"]) (default-challenger)) (play-from-hand state :contestant "TGTBT" "New party") (play-from-hand state :contestant "Old Hollywood Grid" "Locale 1") (play-from-hand state :contestant "TGTBT" "New party") (take-credits state :contestant) (let [tg1 (get-content state :party1 0) ohg (get-content state :party1 1)] (run-on state "Locale 1") (core/reveal state :contestant ohg) (run-successful state) (prompt-select :challenger tg1) ;; Accesses TGTBT but can't steal (is (= 1 (:tag (get-challenger))) "Challenger took 1 tag from accessing without stealing") (prompt-choice :challenger "No action") (prompt-select :challenger ohg)) (prompt-choice :challenger "Yes") ;; Discards OHG (run-empty-locale state "Locale 2") ;; Accesses TGTBT and can steal (prompt-choice :challenger "Steal") (is (= 2 (:tag (get-challenger))) "Challenger took 1 tag from accessing and stealing"))) (deftest the-cleaners ;; The Cleaners (testing "Basic test" (do-game (new-game (default-contestant ["The Cleaners" "Scorched Earth"]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3)])) (play-and-score state "The Cleaners") (core/gain state :challenger :tag 1) (play-from-hand state :contestant "Scorched Earth") (is (zero? (count (:hand (get-challenger)))) "5 damage dealt to Challenger"))) (testing "No bonus damage when challenger 'suffers' damage, ie Cybernetics" (do-game (new-game (default-contestant ["The Cleaners"]) (default-challenger [(qty "Respirocytes" 3)])) (play-and-score state "The Cleaners") (take-credits state :contestant) (play-from-hand state :challenger "Respirocytes") (is (= 1 (count (:hand (get-challenger)))) "Only 1 damage dealt to Challenger from Cybernetics")))) (deftest the-future-is-now ;; The Future is Now (testing "With at least one card in deck" (do-game (new-game (default-contestant ["The Future is Now" "Character Wall"]) (default-challenger)) (starting-hand state :contestant ["The Future is Now"]) (is (= 1 (count (:hand (get-contestant))))) (is (= 1 (count (:deck (get-contestant))))) (play-and-score state "The Future is Now") (prompt-card :contestant (find-card "Character Wall" (:deck (get-contestant)))) (is (= 1 (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant))))))) (testing "With an empty deck" (do-game (new-game (default-contestant ["The Future is Now"]) (default-challenger)) (is (= 1 (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant))))) (play-and-score state "The Future is Now") (is (empty? (:prompt (get-contestant))) "Ability shouldn't fire if deck is empty") (is (zero? (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant)))))))) (deftest the-future-perfect ;; The Future Perfect (do-game (new-game (default-contestant [(qty "The Future Perfect" 2)]) (default-challenger)) (play-from-hand state :contestant "The Future Perfect" "New party") (take-credits state :contestant) (testing "No steal on not-equal Psi game" (run-empty-locale state "HQ") (prompt-choice :contestant "1 [Credits]") (prompt-choice :challenger "0 [Credits]") ;; Cannot steal prompt (prompt-choice :challenger "No action") (is (zero? (:agenda-point (get-challenger))) "Challenger did not steal TFP")) (testing "Successful steal on equal Psi game" (run-empty-locale state "HQ") (prompt-choice :contestant "1 [Credits]") (prompt-choice :challenger "1 [Credits]") (prompt-choice :challenger "Steal") (is (= 3 (:agenda-point (get-challenger))) "Challenger stole TFP")) (testing "No Psi game and successful steal when placed" (run-empty-locale state "Locale 1") (prompt-choice :challenger "Steal") (is (= 6 (:agenda-point (get-challenger))) "Challenger stole TFP - no Psi game on placed TFP")))) (deftest underway-renovation ;; Underway Renovation (do-game (new-game (default-contestant ["Underway Renovation" "Shipment from SanSan"]) (default-challenger)) (core/gain state :contestant :click 2) (starting-hand state :challenger []) (play-from-hand state :contestant "Underway Renovation" "New party") (let [ur (get-content state :party1 0)] (advance state ur) (is (last-log-contains? state "Sure Gamble") "Underway Renovation discarded card name is in log") ; check for #2370 (is (not (last-log-contains? state "Sure Gamble, Sure Gamble")) "Underway Renovation discarded card name is in log") (is (= 1 (count (:discard (get-challenger)))) "1 card milled from Challenger Stack") (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ur) (is (= 3 (get-counters (refresh ur) :advancement))) (is (= 1 (count (:discard (get-challenger)))) "No Challenger mills; advancements were placed") (advance state ur) (is (= 4 (get-counters (refresh ur) :advancement))) (is (last-log-contains? state "Sure Gamble, Sure Gamble") "Underway Renovation discarded card name is in log") (is (= 3 (count (:discard (get-challenger)))) "2 cards milled from Challenger Stack; 4+ advancements")))) (deftest unorthodox-predictions ;; Unorthodox Predictions (do-game (new-game (default-contestant ["Unorthodox Predictions"]) (default-challenger)) (play-and-score state "Unorthodox Predictions") (prompt-choice :contestant "Barrier") (is (last-log-contains? state "Barrier")))) (deftest utopia-fragment ;; Utopia Fragment (do-game (new-game (default-contestant ["Utopia Fragment" "Hostile Takeover"]) (default-challenger)) (play-and-score state "Utopia Fragment") (play-from-hand state :contestant "Hostile Takeover" "New party") (advance state (get-content state :party2 0)) (take-credits state :contestant) (run-on state :party2) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 1 (:agenda-point (get-challenger)))) (is (= 3 (:credit (get-challenger)))))) (deftest vanity-project ;; Vanity Project (do-game (new-game (default-contestant ["Vanity Project"]) (default-challenger)) (play-and-score state "Vanity Project") (is (= 4 (:agenda-point (get-contestant)))))) (deftest veterans-resource ;; Veterans Resource (testing "Veterans Resource basic test" (do-game (new-game (default-contestant [(qty "Hostile Takeover" 2) "Veterans Resource"]) (default-challenger)) (play-and-score state "Hostile Takeover") (play-and-score state "Hostile Takeover") (is (= 19 (:credit (get-contestant))) "Should gain 14 credits from 5 to 19") (is (= 2 (:bad-publicity (get-contestant))) "Should gain 2 bad publicity") (play-and-score state "Veterans Resource") (is (zero? (:bad-publicity (get-contestant))) "Should lose 2 bad publicity"))) (testing "Removes _up to 2_ bad publicity" (do-game (new-game (default-contestant ["Hostile Takeover" "Veterans Resource"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity") (play-and-score state "Veterans Resource") (is (zero? (:bad-publicity (get-contestant))) "Should lose 1 bad publicity")))) (deftest viral-weaponization ;; Viral Weaponization - at the end of turn scored, do 1 net damage for each card in grip (testing "Score on contestant turn" (do-game (new-game (default-contestant [(qty "Viral Weaponization" 2)]) (default-challenger [(qty "Sure Gamble" 3)])) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-and-score state "Viral Weaponization") (is (= 2 (count (:hand (get-challenger)))) "Challenger doesn't take damage when scored") (take-credits state :contestant) (is (zero? (count (:hand (get-challenger)))) "Challenger takes damage at end of turn") (core/click-draw state :challenger 1) (take-credits state :challenger) (take-credits state :contestant) (is (= 1 (count (:hand (get-challenger)))) "Challenger doesn't take damage in future turns") (play-from-hand state :challenger "Sure Gamble") (take-credits state :challenger) (is (zero? (count (:hand (get-challenger)))) "Challenger's hand is empty") (play-and-score state "Viral Weaponization") (take-credits state :contestant) (is (zero? (count (:hand (get-challenger)))) "Challenger's hand is empty"))) (testing "Score on challengers turn" (do-game (new-game (default-contestant ["Viral Weaponization" "Plan B"]) (default-challenger [(qty "Sure Gamble" 3)])) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-from-hand state :contestant "Plan B" "New party") (core/add-prop state :contestant (get-content state :party1 0) :advance-counter 4) (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Viral Weaponization" (:hand (get-contestant)))) (prompt-choice-partial :challenger "No") (is (= 2 (count (:hand (get-challenger)))) "Challenger doesn't take damage when scored") (take-credits state :challenger) (is (zero? (count (:hand (get-challenger)))) "Challenger takes damage at end of turn")))) (deftest voting-machine-initiative ;; Voting Machine Initiative (testing "Voting Machine Initiative" (do-game (new-game (default-contestant ["Voting Machine Initiative"]) (default-challenger)) (letfn [(vmi-test [vmi choice counter] (let [diff (if (= "Yes" choice) 1 0)] (is (= counter (get-counters (refresh vmi) :agenda))) (is (= 4 (:click (get-challenger)))) (prompt-choice :contestant choice) (is (= (- 4 diff) (:click (get-challenger)))) (is (= (- counter diff) (get-counters (refresh vmi) :agenda))) (take-credits state :challenger) (take-credits state :contestant)))] (play-and-score state "Voting Machine Initiative") (take-credits state :contestant) (let [vmi-scored (get-scored state :contestant 0)] (vmi-test vmi-scored "Yes" 3) (vmi-test vmi-scored "No" 2) (vmi-test vmi-scored "Yes" 2) (vmi-test vmi-scored "Yes" 1) (is (empty (:prompt (get-contestant))) "No prompt as there are no agenda counters left")))))) (deftest vulcan-coverup ;; Vulcan Coverup (do-game (new-game (default-contestant [(qty "Vulcan Coverup" 2)]) (default-challenger)) (play-from-hand state :contestant "Vulcan Coverup" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (is (= 1 (:bad-publicity (get-contestant))) "Took 1 bad pub from stolen agenda") (take-credits state :challenger) (play-and-score state "Vulcan Coverup") (is (= 2 (count (:discard (get-challenger)))) "Did 2 meat damage upon scoring"))) (deftest water-monopoly ;; Water Monopoly (do-game (new-game (default-contestant ["Water Monopoly"]) (default-challenger ["Fan Site" "Levy Advanced Research Lab"])) (play-and-score state "Water Monopoly") (take-credits state :contestant) (is (= 5 (:credit (get-challenger))) "Challenger should start with 5 credits") (play-from-hand state :challenger "Fan Site") (is (= 5 (:credit (get-challenger))) "Shouldn't lose any credits") (play-from-hand state :challenger "Levy Advanced Research Lab") (is (zero? (:credit (get-challenger))) "Should cost an extra credit to play")))
true
(ns game-test.cards.agendas (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (use-fixtures :once load-all-cards (partial reset-card-defs "agendas")) (deftest ^{:card-title "15-minutes"} fifteen-minutes ;; 15 Minutes - check if it works correctly from both sides (do-game (new-game (default-contestant ["15 Minutes"]) (default-challenger)) (play-from-hand state :contestant "15 Minutes" "New party") (take-credits state :contestant) ;; use 15 minutes to take it away from challenger (run-empty-locale state "Locale 1") (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (= 1 (:agenda-point (get-challenger)))) (is (= 1 (count (:scored (get-challenger))))) (let [fifm (first (:scored (get-challenger)))] (is (= 3 (:click (get-contestant)))) (is (= 1 (count (:abilities (refresh fifm))))) (card-ability state :contestant (refresh fifm) 0) (is (zero? (:agenda-point (get-challenger)))) (is (zero? (count (:scored (get-challenger)))))) (is (= "15 Minutes" (:title (first (:deck (get-contestant)))))) ;; TODO: could also check for deck shuffle (is (= 2 (:click (get-contestant)))) ;; use 15 minutes to take it away from contestant (hey, maybe some obscure case happens where contestant would want that) (core/click-draw state :contestant 1) (play-from-hand state :contestant "15 Minutes" "New party") (take-credits state :challenger) (score-agenda state :contestant (get-content state :party2 0)) (is (= 1 (:agenda-point (get-contestant)))) (is (= 1 (count (:scored (get-contestant))))) (let [fifm (first (:scored (get-contestant)))] (is (= 1 (count (:abilities (refresh fifm))))) (card-ability state :contestant (refresh fifm) 0) (is (zero? (:agenda-point (get-contestant)))) (is (zero? (count (:scored (get-contestant)))))) (is (= "15 Minutes" (:title (first (:deck (get-contestant)))))))) (deftest accelerated-beta-test ;; Accelerated Beta Test (do-game (new-game (default-contestant ["Accelerated Beta Test" "Enigma" (qty "Hedge Fund" 2)]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Accelerated Beta Test"]) (play-and-score state "Accelerated Beta Test") (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Enigma" (get-in @state [:contestant :play-area]))) (prompt-choice :contestant "HQ") (is (some? (get-character state :hq 0))) (is (= 2 (count (:discard (get-contestant))))) (core/move state :contestant (find-card "Accelerated Beta Test" (:scored (get-contestant))) :hand) (core/move state :contestant (find-card "Hedge Fund" (:discard (get-contestant))) :deck) (core/move state :contestant (find-card "Hedge Fund" (:discard (get-contestant))) :deck) (play-and-score state "Accelerated Beta Test") (prompt-choice :contestant "Yes") (prompt-choice :contestant "I have no regrets") (is (= 2 (count (:discard (get-contestant))))))) (deftest advanced-concept-hopper ;; Advanced Concept Hopper (do-game (new-game (default-contestant ["Advanced Concept Hopper" (qty "Hedge Fund" 4)]) (default-challenger)) (starting-hand state :contestant ["Advanced Concept Hopper"]) (play-and-score state "Advanced Concept Hopper") (take-credits state :contestant) (testing "Contestant draws 1 card, only once per turn" (let [cards (count (:hand (get-contestant)))] (is (= cards (count (:hand (get-contestant)))) (str "Contestant should have " cards " cards in hand")) (run-on state :archives) (prompt-choice :contestant "Draw 1 card") (is (= (inc cards) (count (:hand (get-contestant)))) (str "Contestant should have " (inc cards) " card in hand")) (run-successful state) (run-on state :archives) (is (empty (:prompt (get-contestant))) "No prompt as it's once per turn"))) (take-credits state :challenger) (take-credits state :contestant) (testing "Contestant gains 1 credit, only once per turn" (let [credits (:credit (get-contestant))] (is (= credits (:credit (get-contestant))) (str "Contestant should have " credits " credits")) (run-on state :archives) (prompt-choice :contestant "Gain 1 [Credits]") (is (= (inc credits) (:credit (get-contestant))) (str "Contestant should have " (inc credits) " credits")) (run-successful state) (run-on state :archives) (is (empty (:prompt (get-contestant))) "No prompt as it's once per turn"))))) (deftest ancestral-imager ;; Ancestral Imager (do-game (new-game (default-contestant [(qty "Ancestral Imager" 3)]) (default-challenger)) (play-and-score state "Ancestral Imager") (take-credits state :contestant) (let [grip (count (:hand (get-challenger)))] (is (= grip (count (:hand (get-challenger)))) (str "Challenger has " grip " cards in hand")) (run-on state :hq) (run-jack-out state) (is (= (dec grip) (count (:hand (get-challenger)))) "Challenger took 1 net damage")))) (deftest ar-enhanced-security ;; AR-Enhanced Security (do-game (new-game (default-contestant ["AR-Enhanced Security" (qty "NGO Front" 3)]) (default-challenger)) (testing "set up" (core/gain state :contestant :click 10 :credit 10) (core/gain state :challenger :credit 10) (dotimes [_ 3] (play-from-hand state :contestant "NGO Front" "New party")) (take-credits state :contestant)) (testing "don't take a tag from discarding normally" (run-on state :party1) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 1 (count (:discard (get-contestant)))) "discarded") (is (zero? (:tag (get-challenger))) "Challenger took 0 tags") (take-credits state :challenger) (play-and-score state "AR-Enhanced Security") (take-credits state :contestant)) (testing "gain a tag from first discard" (run-on state :party2) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 2 (count (:discard (get-contestant)))) "discarded") (is (= 1 (:tag (get-challenger))) "Challenger took 1 tag")) (testing "don't gain a tag from second discard" (run-on state :party3) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 3 (count (:discard (get-contestant)))) "discarded") (is (= 1 (:tag (get-challenger))) "Challenger took 0 tags")))) (deftest armed-intimidation ;; Armed Intimidation (do-game (new-game (default-contestant [(qty "Armed Intimidation" 2)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 2)])) (play-and-score state "Armed Intimidation") (prompt-choice :challenger "Take 2 tags") (is (= 2 (:tag (get-challenger))) "Challenger took 2 tags from Armed Intimidation tag choice") (play-and-score state "Armed Intimidation") (is (= 5 (count (:hand (get-challenger)))) "Challenger has 5 cards before Armed Intimidation meat damage") (prompt-choice :challenger "Suffer 5 meat damage") (is (zero? (count (:hand (get-challenger)))) "Challenger has 0 cards after Armed Intimidation meat damage"))) (deftest armored-locales ;; Armored Locales (do-game (new-game (default-contestant ["Armored Locales"]) (default-challenger)) (play-and-score state "Armored Locales") (let [as-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh as-scored) :agenda)) "Should start with 1 agenda counters") (take-credits state :contestant) (run-on state "HQ") (card-ability state :contestant as-scored 0) (is (last-log-contains? state "make the Challenger discard") "Should only write to log")))) (deftest astroscript-pilot-resource ;; AstroScript token placement (do-game (new-game (default-contestant [(qty "AstroScript Pilot Resource" 3) (qty "Character Wall" 2)]) (default-challenger)) (core/gain state :contestant :click 3) (letfn [(try-place [from to] (card-ability state :contestant (refresh from) 0) (prompt-select :contestant (refresh to))) (should-not-place [from to msg] (try-place from to) (prompt-choice :contestant "Done") (is (= 1 (get-counters (refresh from) :agenda)) (str (:title from)" token was not used on " (:title to) msg)) (is (zero? (get-counters (refresh to) :advancement)) (str "Advancement token not placed on " (:title to) msg))) (should-place [from to msg] (try-place from to) (is (zero? (get-counters (refresh from) :agenda)) (str (:title from) " token was used on " (:title to) msg)) (is (= 1 (get-counters (refresh to) :advancement)) (str "Advancement token placed on " (:title to) msg)))] (play-and-score state "AstroScript Pilot Resource") (play-from-hand state :contestant "AstroScript Pilot Resource" "New party") (let [scored-astro (get-scored state :contestant 0) placed-astro (get-content state :party2 0) hand-astro (find-card "AstroScript Pilot Resource" (:hand get-contestant))] (should-not-place scored-astro hand-astro " in hand") (should-place scored-astro placed-astro " that is placed") (advance state placed-astro 2) (core/score state :contestant {:card (refresh placed-astro)})) (play-from-hand state :contestant "Character Wall" "HQ") (let [no-token-astro (get-scored state :contestant 0) token-astro (get-scored state :contestant 1) hand-character-wall (find-card "Character Wall" (:hand get-contestant)) placed-character-wall (get-character state :hq 0)] (should-not-place token-astro no-token-astro " that is scored") (should-not-place token-astro hand-character-wall " in hand") (should-place token-astro placed-character-wall " that is placed"))))) (deftest award-bait ;; Award Bait (do-game (new-game (default-contestant [(qty "Award Bait" 2) "Character Wall"]) (default-challenger)) (core/move state :contestant (find-card "Award Bait" (:hand (get-contestant))) :deck) (play-from-hand state :contestant "Character Wall" "HQ") (let [iw (get-character state :hq 0)] (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (play-from-hand state :contestant "Award Bait" "New party") (take-credits state :contestant) (run-on state :party1) (run-successful state) (prompt-choice :contestant "2") (prompt-select :contestant (refresh iw)) (prompt-choice :challenger "Steal") (is (= 2 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 advancement tokens") (run-on state :rd) (run-successful state) (prompt-choice :challenger "Access") (prompt-choice :contestant "2") (prompt-select :contestant (refresh iw)) (prompt-choice :challenger "Steal") (is (= 4 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 advancement tokens")))) (deftest bacterial-resourceming ;; Bacterial Resourceming (testing "Scoring should not cause a run to exist for challenger." (do-game (new-game (default-contestant ["Bacterial Resourceming" "Hedge Fund"]) (default-challenger)) (starting-hand state :contestant ["Bacterial Resourceming"]) (play-and-score state "Bacterial Resourceming") (prompt-choice :contestant "Yes") (prompt-choice :contestant "Done") (prompt-choice :contestant "Done") (prompt-card :contestant (first (:deck (get-contestant)))) (prompt-choice :contestant "Done") (is (empty (:prompt (get-contestant))) "Bacterial Resourceming prompts finished") (is (not (:run @state)) "No run is active"))) (testing "Removing all cards from R&D should not freeze for challenger, nor give an extra access." (do-game (new-game (default-contestant [(qty "Bacterial Resourceming" 8)]) (default-challenger) {:start-as :challenger}) (starting-hand state :contestant []) (run-empty-locale state :rd) (prompt-choice :challenger "Steal") (prompt-choice :contestant "Yes") ;; Move all 7 cards to discard (doseq [_ (range 7) ;; Get the first card listed in the prompt choice ;; TODO make this function :let [card (-> @state (get-in [:contestant :prompt]) first (get-in [:choices 0]))]] (prompt-card :contestant card)) (prompt-choice :contestant "Done") ; Finished with discarding (prompt-choice :contestant "Done") ; Finished with move-to-hq (no cards to move) ;; Run and prompts should be over now (is (empty (:prompt (get-contestant))) "Bacterial Resourceming prompts finished") (is (empty (:prompt (get-challenger))) "Bacterial Resourceming prompts finished") (is (not (:run @state)))))) (deftest better-citizen-resource ;; Better Citizen Resource (testing "Basic test" (do-game (new-game (default-contestant ["Better Citizen Resource"]) (default-challenger [(qty "The Maker's Eye" 2) (qty "Wyrm" 2)])) (play-and-score state "Better Citizen Resource") (take-credits state :contestant) (core/gain state :challenger :credit 10) (is (zero? (:tag (get-challenger))) "Challenger starts with 0 tags") (play-from-hand state :challenger "The Maker's Eye") (prompt-choice :contestant "Yes") (is (= 1 (:tag (get-challenger))) "Challenger takes 1 tag for playing a Run event") (run-successful state) (play-from-hand state :challenger "Wyrm") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (= 1 (:tag (get-challenger))) "Challenger doesn't gain a tag from placing an characterbreaker after playing a Run event") (take-credits state :challenger) (take-credits state :contestant) (play-from-hand state :challenger "Wyrm") (prompt-choice :contestant "Yes") (is (= 2 (:tag (get-challenger))) "Challenger gains 1 tag for placing an Icebreaker") (play-from-hand state :challenger "The Maker's Eye") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (= 2 (:tag (get-challenger))) "Challenger doesn't gain a tag from playing a Run event after placing an Icebreaker") (run-successful state))) (testing "Should only trigger on Run events. #3619" (do-game (new-game (default-contestant ["Better Citizen Resource"]) (default-challenger ["Mining Accident"])) (play-and-score state "Better Citizen Resource") (take-credits state :contestant) (run-empty-locale state "HQ") (play-from-hand state :challenger "Mining Accident") (prompt-choice-partial :contestant "Pay") (is (empty? (-> (get-contestant) :prompt)) "Contestant shouldn't get a prompt to use Better Citizen Resource") (is (zero? (:tag (get-challenger))) "Challenger should not gain a tag from playing a non-Run event")))) (deftest bifrost-array ;; Bifrost Array (do-game (new-game (default-contestant ["Bifrost Array" "Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity") (let [ht-scored (get-scored state :contestant 0)] (play-and-score state "Bifrost Array") (prompt-choice :contestant "Yes") (prompt-select :contestant (refresh ht-scored)) (is (= 19 (:credit (get-contestant))) "Should gain 7 credits from 12 to 19") (is (= 2 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity")))) (deftest brain-rewiring ;; Brain Rewiring (do-game (new-game (default-contestant ["Brain Rewiring"]) (default-challenger)) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-and-score state "Brain Rewiring") (prompt-choice :contestant "Yes") (prompt-choice :contestant 2) (is (= 1 (count (:hand (get-challenger))))))) (deftest braintrust ;; Braintrust (do-game (new-game (default-contestant ["Braintrust" "Ichi 1.0"]) (default-challenger)) (play-from-hand state :contestant "Braintrust" "New party") (let [bt (get-content state :party1 0)] (core/add-prop state :contestant bt :advance-counter 7) (core/score state :contestant {:card (refresh bt)}) (let [scored-bt (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh scored-bt) :agenda)) "Scored w/ 4 over-advancements; 2 agenda counters") (play-from-hand state :contestant "Ichi 1.0" "HQ") (core/reveal state :contestant (get-character state :hq 0)) (is (= 2 (:credit (get-contestant))) "2c discount to reveal Ichi"))))) (deftest breaking-news ;; Breaking News (do-game (new-game (default-contestant [(qty "Breaking News" 3)]) (default-challenger)) (play-and-score state "Breaking News") (is (= 2 (get-in @state [:challenger :tag])) "Challenger receives 2 tags from Breaking News") (take-credits state :contestant) (is (zero? (get-in @state [:challenger :tag]))) "Two tags removed at the end of the turn")) (deftest cfc-excavation-contract ;; CFC Excavation Contract (dotimes [n 5] (do-game (new-game (default-contestant ["CFC Excavation Contract" (qty "Eli 1.0" n)]) (default-challenger)) (core/gain state :contestant :click 10 :credit 10) (is (= 15 (:credit (get-contestant))) "Should start with 5 credits") (dotimes [_ n] (play-from-hand state :contestant "Eli 1.0" "New party") (core/reveal state :contestant (get-character state (keyword (str "party" (:rid @state))) 0))) (let [credit (:credit (get-contestant))] (play-and-score state "CFC Excavation Contract") (is (= (+ credit (* 2 n)) (:credit (get-contestant))) (str "Should now have with " (+ credit (* 2 n)) " credits")))))) (deftest character-assassination ;; Character Assassination (do-game (new-game (default-contestant ["Character Assassination"]) (default-challenger ["Fall PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"])) (take-credits state :contestant) (play-from-hand state :challenger "PI:NAME:<NAME>END_PI") (play-from-hand state :challenger "Fall Guy") (take-credits state :challenger) (play-and-score state "Character Assassination") (let [kati (get-radicle state 0)] (prompt-select :contestant PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI) (is (empty? (:prompt (get-challenger))) "Fall Guy prevention didn't occur") (is (= 1 (count (:discard (get-challenger)))) "PI:NAME:<NAME>END_PI discarded")))) (deftest chronos-project ;; Chronos Project (do-game (new-game (default-contestant ["Chronos Project"]) (default-challenger)) (dotimes [_ 3] (core/move state :challenger (find-card "Sure Gamble" (:hand (get-challenger))) :discard)) (is (= 3 (count (:discard (get-challenger)))) "Challenger should have 3 cards in heap") (play-and-score state "Chronos Project") (is (zero? (count (:discard (get-challenger)))) "Challenger should have 0 cards in heap"))) (deftest city-works-project ;; City Works Project (do-game (new-game (default-contestant ["City Works Project"]) (default-challenger [(qty "Sure Gamble" 4)])) (play-from-hand state :contestant "City Works Project" "New party") (let [cwp (get-content state :party1 0)] (core/advance state :contestant {:card (refresh cwp)}) (core/advance state :contestant {:card (refresh cwp)})) (take-credits state :contestant) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (= 4 (count (:discard (get-challenger)))) "Challenger paid 4 meat damage"))) (deftest clone-retirement ;; Clone Retirement (do-game (new-game (default-contestant [(qty "Clone Retirement" 2) "Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant)))) (is (= 1 (:bad-publicity (get-contestant)))) (play-and-score state "Clone Retirement") (is (zero? (:bad-publicity (get-contestant)))) (play-from-hand state :contestant "Clone Retirement" "New party") (take-credits state :contestant) (run-on state "Locale 3") (run-successful state) (prompt-choice :challenger "Steal") (is (= 1 (:bad-publicity (get-contestant)))))) (deftest contestantorate-sales-team ;; Contestantorate Sales Team (do-game (new-game (default-contestant [(qty "Contestantorate Sales Team" 2)]) (default-challenger)) (is (= 5 (:credit (get-contestant)))) (play-and-score state "Contestantorate Sales Team") (let [scored-cst (get-scored state :contestant 0)] (core/end-turn state :contestant nil) (core/start-turn state :challenger nil) (is (= 6 (:credit (get-contestant))) "Increments at challenger's start of turn") (is (= 9 (get-counters (refresh scored-cst) :credit))) (core/end-turn state :challenger nil) (core/start-turn state :contestant nil) (is (= 7 (:credit (get-contestant))) "Increments at contestant's start of turn") (is (= 8 (get-counters (refresh scored-cst) :credit)))))) (deftest contestantorate-war ;; Contestantorate War (do-game (new-game (default-contestant [(qty "Contestantorate War" 2)]) (default-challenger)) (is (= 5 (:credit (get-contestant)))) (play-and-score state "Contestantorate War") (is (zero? (:credit (get-contestant))) "Lost all credits") (core/gain state :contestant :credit 7) (play-and-score state "Contestantorate War") (is (= 14 (:credit (get-contestant))) "Had 7 credits when scoring, gained another 7"))) (deftest crisis-management ;; Crisis Management (do-game (new-game (default-contestant ["Crisis Management"]) (default-challenger)) (play-and-score state "Crisis Management") (take-credits state :contestant) (take-credits state :challenger) (is (= 3 (count (:hand (get-challenger)))) "No damage done, Challenger not tagged") (take-credits state :contestant) (core/gain state :challenger :tag 1) (take-credits state :challenger) (is (= 2 (count (:hand (get-challenger)))) "Crisis Management dealt 1 meat damage"))) (deftest dedicated-neural-net ;; Dedicated Neural Net (do-game (new-game (default-contestant ["Dedicated Neural Net" (qty "Scorched Earth" 2) "Hedge Fund" "Caprcharacter Nisei"]) (default-challenger ["HQ Interface"])) (play-from-hand state :contestant "Caprcharacter Nisei" "HQ") (play-and-score state "Dedicated Neural Net") (take-credits state :contestant) (run-empty-locale state :hq) (prompt-choice :challenger "0") (prompt-choice :contestant "1") (is (-> @state :run :run-effect :replace-access) "Replace-access tiggered") (prompt-select :contestant (find-card "Hedge Fund" (:hand (get-contestant)))) (prompt-choice :challenger "Card from hand") (is (accessing state "Hedge Fund") "Challenger accessing Hedge Fund") (prompt-choice :challenger "No action") ;; test for #2376 (prompt-choice :challenger "Unrevealed region in HQ") (is (accessing state "Caprcharacter Nisei") "Challenger accessing Caprcharacter") (prompt-choice :challenger "No") (is (not (:run @state)) "Run completed") (run-empty-locale state :hq) (prompt-choice :challenger "No action") (take-credits state :challenger) (take-credits state :contestant) (play-from-hand state :challenger "HQ Interface") (run-empty-locale state :hq) (prompt-choice :challenger "0") (prompt-choice :contestant "1") (is (= 2 (-> (get-contestant) :selected first :max)) "Contestant chooses 2 cards for Challenger to access"))) (deftest degree-mill ;; Degree Mill (testing "Basic behavior" (do-game (new-game (default-contestant [(qty "Degree Mill" 2)]) (default-challenger ["Character Analyzer" "All-nighter" "Hunting Grounds"])) (play-from-hand state :contestant "Degree Mill" "New party") (take-credits state :contestant) (is (= 0 (count (:deck (get-challenger)))) "Challenger starts with empty deck") (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "No action") (is (= 0 (:agenda-point (get-challenger))) "Challenger stole Degree Mill with no placed cards") (play-from-hand state :challenger "Character Analyzer") (play-from-hand state :challenger "All-nighter") (let [ia (get-radicle state 0) an (get-radicle state 1)] (run-on state "Locale 1") (run-successful state) (prompt-choice-partial :challenger "Pay") (prompt-select :challenger ia) (prompt-select :challenger an) (is (= 3 (:agenda-point (get-challenger))) "Challenger failed to steal Degree Mill") (is (empty? (get-in @state [:challenger :rig :radicle])) "Degree Mill didn't remove placed cards") (is (= 2 (count (:deck (get-challenger)))) "Degree Mill didn't put cards back in deck")) (take-credits state :challenger) ;; Checking if facedowns work as well (play-from-hand state :contestant "Degree Mill" "New party") (take-credits state :contestant) (play-from-hand state :challenger "Hunting Grounds") (let [hg (get-radicle state 0)] (run-on state "Locale 2") (run-successful state) (prompt-choice :challenger "No action") (is (= 3 (:agenda-point (get-challenger))) "Challenger stole Degree Mill with single card") (card-ability state :challenger hg 1) (is (= 2 (count (get-in (get-challenger) [:rig :facedown]))) "Hunting Ground did not place cards facedown") (is (empty? (:deck (get-challenger))) "Hunting Grounds did not remove cards from deck") (let [fd1 (get-challenger-facedown state 0) fd2 (get-challenger-facedown state 1)] (run-on state "Locale 2") (run-successful state) (prompt-choice-partial :challenger "Pay") (prompt-select :challenger fd1) (prompt-select :challenger fd2) (is (= 6 (:agenda-point (get-challenger))) "Challenger failed to steal Degree Mill with facedown cards") (is (empty? (get-in (get-challenger) [:rig :facedown])) "Degree Mill didn't remove facedown cards") (is (= 2 (count (:deck (get-challenger)))) "Degree Mill didn't put cards back in deck"))))) (testing "Multiple steal costs" (do-game (new-game (default-contestant [(qty "Degree Mill" 1) (qty "Strongbox" 1)]) (default-challenger [(qty "Character Analyzer" 3) (qty "All-nighter" 3)])) (play-from-hand state :contestant "Degree Mill" "New party") (play-from-hand state :contestant "Strongbox" "Locale 1") (let [dm (get-content state :party1 0) sb (get-content state :party1 1)] (core/reveal state :contestant sb) (take-credits state :contestant) (play-from-hand state :challenger "Character Analyzer") (play-from-hand state :challenger "All-nighter") (run-empty-locale state :party1) (prompt-select :challenger (refresh dm)) (prompt-choice-partial :challenger "Pay") (is (= 1 (:click (get-challenger))) "Challenger should start with 1 remaining click") (prompt-choice-partial :challenger "Click") (is (zero? (:click (get-challenger))) "Challenger should have spent a click") (is (= 2 (count (get-in @state [:challenger :rig :radicle]))) "Challenger starts with 2 radicles") (prompt-choice-partial :challenger "shuffling") (prompt-select :challenger (get-radicle state 1)) (prompt-select :challenger (get-radicle state 0)) (is (empty? (get-radicle state)) "Degree Mill removed placed cards") (is (not-empty (get-scored state :challenger)) "Challenger stole an agenda"))))) (deftest director-haas'-pet-project ;; Director Haas' Pet Project (do-game (new-game (default-contestant ["Director Haas' Pet Project" "Adonis Campaign" "Strongbox" "Eli 1.0" (qty "Hedge Fund" 5)]) (default-challenger)) (starting-hand state :contestant ["Director Haas' Pet Project" "Adonis Campaign" "Strongbox"]) (core/move state :contestant (find-card "Eli 1.0" (:deck (get-contestant))) :discard) (play-and-score state "Director Haas' Pet Project") (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Adonis Campaign" (:hand (get-contestant)))) (prompt-select :contestant (find-card "Strongbox" (:hand (get-contestant)))) (prompt-select :contestant (find-card "Eli 1.0" (:discard (get-contestant)))))) (deftest domestic-sleepers ;; Domestic Sleepers (do-game (new-game (default-contestant ["Domestic Sleepers"]) (default-challenger)) (play-and-score state "Domestic Sleepers") (core/gain state :contestant :click 3) (let [ds_scored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh ds_scored) :agenda)) "Should start with 0 agenda counters") (is (zero? (:agenda-point (get-contestant))) "Should provide 0 agenda points initially") (card-ability state :contestant ds_scored 0) (is (= 1 (get-counters (refresh ds_scored) :agenda)) "Should gain 1 agenda counter") (is (= 1 (:agenda-point (get-contestant))) "Should provide 1 agenda point after ability use")))) (deftest eden-fragment ;; Test that Eden Fragment ignores the place cost of the first character (do-game (new-game (default-contestant [(qty "Eden Fragment" 3) (qty "Character Wall" 3)]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (play-and-score state "Eden Fragment") (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Character Wall" "HQ") (is (some? (get-character state :hq 1)) "Contestant has two character placed on HQ") (is (= 6 (:credit (get-contestant))) "Contestant does not pay for placing the first Character of the turn") (play-from-hand state :contestant "Character Wall" "HQ") (is (some? (get-character state :hq 2)) "Contestant has three character placed on HQ") (is (= 4 (:credit (get-contestant))) "Contestant pays for placing the second Character of the turn"))) (deftest efficiency-committee ;; Efficiency Committee (do-game (new-game (default-contestant [(qty "Efficiency Committee" 3) (qty "Shipment from SanSan" 2) "Character Wall"]) (default-challenger)) (core/gain state :contestant :click 4) (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Efficiency Committee" "New party") (play-from-hand state :contestant "Character Wall" "HQ") (let [ec1 (get-content state :party1 0) ec2 (get-content state :party2 0) ec3 (get-content state :party3 0) iw (get-character state :hq 0)] (score-agenda state :contestant ec1) (let [ec1_scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh ec1_scored) :agenda))) (is (= 2 (:agenda-point (get-contestant)))) ;; use token (is (= 3 (:click (get-contestant)))) (card-ability state :contestant ec1_scored 0) (is (= 4 (:click (get-contestant)))) ;; try to advance Character Wall (advance state iw) (is (= 4 (:click (get-contestant)))) (is (zero? (get-counters (refresh iw) :advancement))) ;; try to advance Efficiency Committee (advance state ec2) (is (= 4 (:click (get-contestant)))) (is (zero? (get-counters (refresh ec2) :advancement))) ;; advance with Shipment from SanSan (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ec2) (is (= 2 (get-counters (refresh ec2) :advancement))) (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ec2) (is (= 4 (get-counters (refresh ec2) :advancement))) (core/score state :contestant {:card (refresh ec2)}) (is (= 4 (:agenda-point (get-contestant)))) (take-credits state :contestant) (take-credits state :challenger) ;; can advance again (advance state iw) (is (= 1 (get-counters (refresh iw) :advancement))) (advance state ec3) (is (= 1 (get-counters (refresh ec3) :advancement))))))) (deftest elective-region ;; Elective Region (do-game (new-game (default-contestant ["Elective Region"]) (default-challenger)) (play-and-score state "Elective Region") (let [eu-scored (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh eu-scored) :agenda)) "Should start with 2 agenda counters") (take-credits state :contestant) (take-credits state :challenger) (is (= 3 (:click (get-contestant))) "Should start with 4 clicks") (card-ability state :contestant eu-scored 0) (card-ability state :contestant eu-scored 0) (is (= 4 (:click (get-contestant))) "Should gain 2 clicks, not 3") (is (= 1 (get-counters (refresh eu-scored) :agenda)) "Should still have 1 agenda counter")))) (deftest encrypted-portals ;; Encrypted Portals (do-game (new-game (default-contestant ["Encrypted Portals" "Lotus Field"]) (default-challenger)) (play-from-hand state :contestant "Lotus Field" "HQ") (let [lf (get-character state :hq 0)] (core/reveal state :contestant lf) (is (= 4 (:current-strength (refresh lf))) "Should start with base strength of 4") (is (zero? (:credit (get-contestant))) "Should have 0 credits after reveal") (play-and-score state "Encrypted Portals") (is (= 5 (:current-strength (refresh lf))) "Should gain 1 strength from 4 to 5") (is (= 1 (:credit (get-contestant))) "Should gain 1 credit for revealed code gate")))) (deftest escalate-vitriol ;; Escalate Vitriol (do-game (new-game (default-contestant ["Escalate Vitriol"]) (default-challenger)) (core/lose state :contestant :credit 5) (play-and-score state "Escalate Vitriol") (let [ev-scored (get-scored state :contestant 0)] (dotimes [tag 10] (is (zero? (:tag (get-challenger))) "Should start with 0 tags") (is (zero? (:credit (get-contestant))) "Should start with 0 credits") (core/gain state :challenger :tag tag) (card-ability state :contestant ev-scored 0) (is (= tag (:credit (get-contestant))) (str "Should gain " tag " credits")) (take-credits state :contestant) (take-credits state :challenger) (core/lose state :contestant :credit (:credit (get-contestant))) (core/lose state :challenger :tag tag))))) (deftest executive-retreat ;; Executive Retreat (do-game (new-game (default-contestant ["Executive Retreat" (qty "Hedge Fund" 5)]) (default-challenger)) (starting-hand state :contestant ["Executive Retreat" "Hedge Fund"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should start with 1 card in HQ") (play-and-score state "Executive Retreat") (is (zero? (count (:hand (get-contestant)))) "Contestant should have 0 cards in HQ after shuffling HQ back into R&D") (let [er-scored (get-scored state :contestant 0)] (card-ability state :contestant er-scored 0) (is (= 5 (count (:hand (get-contestant)))) "Contestant should have 5 cards in hand") (is (zero? (get-counters (refresh er-scored) :agenda)) "Executive Retreat should have 0 agenda counters"))) (testing "Overdraw" (do-game (new-game (default-contestant ["Executive Retreat" (qty "Hedge Fund" 4)]) (default-challenger)) (starting-hand state :contestant ["Executive Retreat" "Hedge Fund"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should start with 1 card in HQ") (play-and-score state "Executive Retreat") (is (zero? (count (:hand (get-contestant)))) "Contestant should have 0 cards in HQ after shuffling HQ back into R&D") (let [er-scored (get-scored state :contestant 0)] (card-ability state :contestant er-scored 0) (is (= 4 (count (:hand (get-contestant)))) "Contestant should have 5 cards in hand") (is (zero? (get-counters (refresh er-scored) :agenda)) "Executive Retreat should have 0 agenda counters") (is (= :challenger (:winner @state)) "Challenger wins") (is (= "Decked" (:reason @state)) "Win condition reports decked"))))) (deftest explode-a-palooza ;; Explode-a-palooza (testing "Basic test" (do-game (new-game (default-contestant ["Explode-a-palooza"]) (default-challenger)) (play-from-hand state :contestant "Explode-a-palooza" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Access") (prompt-choice :challenger "Steal") (prompt-choice :contestant "Yes") (is (= 12 (:credit (get-contestant))) "Gained 5 credits"))) (testing "Interaction with The Turning Wheel. Issue #1717." (do-game (new-game (default-contestant [(qty "Explode-a-palooza" 3)]) (default-challenger ["The Turning Wheel"])) (starting-hand state :contestant ["Explode-a-palooza" "Explode-a-palooza"]) (play-from-hand state :contestant "Explode-a-palooza" "New party") (take-credits state :contestant) (play-from-hand state :challenger "The Turning Wheel") (run-empty-locale state :party1) (prompt-choice :challenger "Access") (prompt-choice :contestant "Yes") (prompt-choice :challenger "Steal") (let [ttw (get-radicle state 0)] (is (zero? (get-counters (refresh ttw) :power)) "TTW did not gain counters") (is (= 1 (count (:scored (get-challenger)))) "Challenger stole Explodapalooza") (is (= 12 (:credit (get-contestant))) "Gained 5 credits") (run-empty-locale state :rd) (prompt-choice :challenger "Access") (prompt-choice :contestant "Yes") (prompt-choice :challenger "Steal") (is (zero? (get-counters (refresh ttw) :power)) "TTW did not gain counters") (is (= 2 (count (:scored (get-challenger)))) "Challenger stole Explodapalooza") (is (= 17 (:credit (get-contestant))) "Gained 5 credits"))))) (deftest false-lead ;; False Lead (do-game (new-game (default-contestant ["False Lead"]) (default-challenger)) (play-and-score state "False Lead") (is (= 1 (count (:scored (get-contestant)))) "Contestant should have 1 agenda point") (take-credits state :contestant) (is (= 4 (:click (get-challenger))) "Challenger should start turn with 4 clicks") (card-ability state :contestant (get-scored state :contestant 0) 0) (is (= 2 (:click (get-challenger))) "Challenger should lose 2 clicks from False Lead"))) (deftest fetal-ai ;; Fetal AI (testing "basic test" (do-game (new-game (default-contestant [(qty "Fetal AI" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3) (qty "Quality Time" 3)])) (play-from-hand state :contestant "Fetal AI" "New party") (take-credits state :contestant 2) (run-empty-locale state "Locale 1") (prompt-choice-partial :challenger "Pay") (is (= 3 (count (:hand (get-challenger)))) "Challenger took 2 net damage from Fetal AI") (is (= 3 (:credit (get-challenger))) "Challenger paid 2cr to steal Fetal AI") (is (= 1 (count (:scored (get-challenger)))) "Challenger stole Fetal AI")) (testing "can't afford to steal" (do-game (new-game (default-contestant [(qty "Fetal AI" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3) (qty "Quality Time" 3)])) (play-from-hand state :contestant "Fetal AI" "New party") (take-credits state :contestant 2) (core/lose state :challenger :credit 5) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (= 3 (count (:hand (get-challenger)))) "Challenger took 2 net damage from Fetal AI") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Fetal AI"))))) (deftest firmware-updates ;; Firmware Updates (do-game (new-game (default-contestant ["Firmware Updates" "Character Wall"]) (default-challenger)) (play-and-score state "Firmware Updates") (play-from-hand state :contestant "Character Wall" "HQ") (let [fu (get-scored state :contestant 0) iw (get-character state :hq 0)] (is (= 3 (get-counters (refresh fu) :agenda)) "Firmware Updates should start with 3 agenda counters") (core/reveal state :contestant iw) (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (card-ability state :contestant fu 0) (prompt-select :contestant (refresh iw)) (is (= 2 (get-counters (refresh fu) :agenda)) "Firmware Updates should now have 2 agenda counters") (is (= 1 (get-counters (refresh iw) :advancement)) "Character Wall should have 1 advancement token")))) (deftest geothermal-fracking ;; Geothermal Fracking (testing "basic test" (do-game (new-game (default-contestant ["Geothermal Fracking"]) (default-challenger)) (play-and-score state "Geothermal Fracking") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (is (zero? (:bad-publicity (get-contestant))) "Should start with 0 bad publicity") (let [gf-scored (get-scored state :contestant 0)] (is (= 2 (get-counters (refresh gf-scored) :agenda)) "Should start with 2 agenda counters") (card-ability state :contestant gf-scored 0) (is (= 1 (:click (get-contestant))) "Should have 1 click left") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity")))) (testing "prevented bad publicity shouldn't block credit gain" (do-game (new-game (default-contestant ["Geothermal Fracking" "Broadcast Square"]) (default-challenger)) (play-and-score state "Geothermal Fracking") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (is (zero? (:bad-publicity (get-contestant))) "Should start with 0 bad publicity") (play-from-hand state :contestant "Broadcast Square" "New party") (let [gf-scored (get-scored state :contestant 0) bs (get-content state :party2 0)] (core/reveal state :contestant bs) (is (= 2 (get-counters (refresh gf-scored) :agenda)) "Should start with 2 agenda counters") (card-ability state :contestant gf-scored 0) (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (zero? (:click (get-contestant))) "Should have 0 click left") (is (= 10 (:credit (get-contestant))) "Should gain 7 credits from 3 to 10") (is (zero? (:bad-publicity (get-contestant))) "Should gain 0 bad publicity from prevention"))))) (deftest genetic-resequencing ;; Genetic Resequencing (do-game (new-game (default-contestant ["Genetic Resequencing" (qty "Braintrust" 2)]) (default-challenger)) (play-from-hand state :contestant "Braintrust" "New party") (play-from-hand state :contestant "Braintrust" "New party") (play-from-hand state :contestant "Genetic Resequencing" "New party") (let [bt1 (get-content state :party1 0) bt2 (get-content state :party2 0) gr (get-content state :party3 0)] (score-agenda state :contestant bt1) (let [btscored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh btscored) :agenda)) "No agenda counters on scored Braintrust") (score-agenda state :contestant gr) (prompt-select :contestant bt2) (is (zero? (get-counters (refresh bt2) :agenda)) "No agenda counters on placed Braintrust; not a valid target") (prompt-select :contestant btscored) (is (= 1 (get-counters (refresh btscored) :agenda)) "1 agenda counter placed on scored Braintrust"))))) (deftest gila-hands-arcology ;; Gila Hands Arcology (do-game (new-game (default-contestant ["Gila Hands Arcology"]) (default-challenger)) (play-and-score state "Gila Hands Arcology") (is (= 2 (:click (get-contestant))) "Should have 2 clicks left") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (core/gain state :contestant :click 2) (let [gha-scored (get-scored state :contestant 0)] (card-ability state :contestant gha-scored 0) (is (= 2 (:click (get-contestant))) "Should spend 2 clicks on Gila Hands") (is (= 8 (:credit (get-contestant))) "Should gain 3 credits from 5 to 8") (card-ability state :contestant gha-scored 0) (is (zero? (:click (get-contestant))) "Should spend 2 clicks on Gila Hands") (is (= 11 (:credit (get-contestant))) "Should gain 3 credits from 8 to 11")))) (deftest glenn-station ;; Glenn Station (do-game (new-game (default-contestant ["Glenn Station" "Character Wall"]) (default-challenger)) (play-and-score state "Glenn Station") (let [gs-scored (get-scored state :contestant 0)] (card-ability state :contestant gs-scored 0) (prompt-card :contestant (find-card "Character Wall" (:hand (get-contestant)))) (is (= 1 (count (:hosted (refresh gs-scored))))) (card-ability state :contestant gs-scored 1) (prompt-card :contestant (find-card "Character Wall" (:hosted (refresh gs-scored)))) (is (zero? (count (:hosted (refresh gs-scored)))))))) (deftest global-food-initiative ;; Global Food Initiative (do-game (new-game (default-contestant [(qty "Global Food Initiative" 2)]) (default-challenger)) (testing "Contestant scores" (is (zero? (:agenda-point (get-challenger))) "Challenger should start with 0 agenda points") (is (zero? (:agenda-point (get-contestant))) "Contestant should start with 0 agenda points") (play-and-score state "Global Food Initiative") (is (= 3 (:agenda-point (get-contestant))) "Contestant should gain 3 agenda points")) (testing "Challenger steals" (play-from-hand state :contestant "Global Food Initiative" "New party") (take-credits state :contestant) (run-on state :party2) (run-successful state) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should gain 2 agenda points, not 3")))) (deftest government-contracts ;; Government Contracts (do-game (new-game (default-contestant ["Government Contracts"]) (default-challenger)) (play-and-score state "Government Contracts") (is (= 2 (:click (get-contestant)))) (card-ability state :contestant (get-scored state :contestant 0) 0) (is (zero? (:click (get-contestant))) "Spent 2 clicks") (is (= 9 (:credit (get-contestant))) "Gained 4 credits"))) (deftest government-takeover ;; Government Takeover (do-game (new-game (default-contestant ["Government Takeover"]) (default-challenger)) (play-and-score state "Government Takeover") (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (let [gt-scored (get-scored state :contestant 0)] (card-ability state :contestant gt-scored 0) (is (= 8 (:credit (get-contestant))) "Should gain 3 credits from 5 to 8")))) (deftest graft ;; Graft (letfn [(graft-test [[number-of-picks deck-size]] (let [cards ["Character Wall" "Fire Wall" "Orion"]] (do-game (new-game (default-contestant ["Graft" "Character Wall" "Fire Wall" "Orion"]) (default-challenger)) (starting-hand state :contestant ["Graft"]) (play-and-score state "Graft") (dotimes [current-pick number-of-picks] (prompt-card :contestant (find-card (nth cards current-pick) (:deck (get-contestant))))) (is (= number-of-picks (count (:hand (get-contestant))))) (is (= deck-size (count (:deck (get-contestant))))))))] (doall (map graft-test [[0 3] [1 2] [2 1] [3 0]])))) (deftest hades-fragment ;; Hades Fragment (do-game (new-game (default-contestant ["Hades Fragment" (qty "Hedge Fund" 2)]) (default-challenger)) (starting-hand state :contestant ["Hades Fragment"]) (play-and-score state "Hades Fragment") (take-credits state :contestant) (take-credits state :challenger) (is (= 1 (count (:hand (get-contestant)))) "Contestant should have no opportunity to use Hades Shard") (core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :discard) (take-credits state :contestant) (take-credits state :challenger) (let [hf-scored (get-scored state :contestant 0)] (card-ability state :contestant hf-scored 0) (prompt-select :contestant (find-card "Hedge Fund" (:discard (get-contestant)))) (is (= 2 (count (:deck (get-contestant)))) "R&D should have 2 cards in it after Hades Fragment use")))) (deftest helium-3-deposit ;; Helium-3 Deposit (do-game (new-game (default-contestant ["Helium-3 Deposit" "Chief Slee" "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Chief Slee" "New party") (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (let [cs (get-content state :party1 0) iw (get-character state :hq 0)] (is (zero? (get-counters (refresh cs) :power)) "Chief Slee should start with 0 power counters") (core/reveal state :contestant iw) (run-on state "HQ") (card-ability state :contestant cs 0) (is (= 1 (get-counters (refresh cs) :power)) "Chief Slee should gain 1 power counter") (take-credits state :challenger) (play-and-score state "Helium-3 Deposit") (prompt-choice :contestant "2") (prompt-select :contestant cs) (is (= 3 (get-counters (refresh cs) :power)) "Chief Slee should gain 2 power counters from 1 to 3")))) (deftest high-risk-investment ;; High-Risk Investment (do-game (new-game (default-contestant ["High-Risk Investment"]) (default-challenger)) (play-and-score state "High-Risk Investment") (let [hri-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh hri-scored) :agenda)) "Has 1 agenda counter") (take-credits state :contestant) (is (= 7 (:credit (get-contestant)))) (take-credits state :challenger) (is (= 9 (:credit (get-challenger)))) (card-ability state :contestant hri-scored 0) (is (= 16 (:credit (get-contestant))) "Gained 9 credits") (is (= 2 (:click (get-contestant))) "Spent 1 click") (is (zero? (get-counters (refresh hri-scored) :agenda)) "Spent agenda counter")))) (deftest hollywood-renovation ;; Hollywood Renovation (do-game (new-game (default-contestant ["Hollywood Renovation" "Character Wall"]) (default-challenger)) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "Character Wall" "HQ") (play-from-hand state :contestant "Hollywood Renovation" "New party") (let [hr (get-content state :party1 0) iw (get-character state :hq 0)] (is (zero? (get-counters (refresh hr) :advancement)) "Hollywood Renovation should start with 0 advancement tokens") (is (zero? (get-counters (refresh iw) :advancement)) "Character Wall should start with 0 advancement tokens") (dotimes [n 5] (advance state (refresh hr)) (prompt-select :contestant (refresh iw))) (is (= 5 (get-counters (refresh hr) :advancement)) "Hollywood Renovation should gain 5 advancement tokens") (is (= 5 (get-counters (refresh iw) :advancement)) "Character Wall should gain 5 advancement tokens") (advance state (refresh hr)) (prompt-select :contestant (refresh iw)) (is (= 6 (get-counters (refresh hr) :advancement)) "Hollywood Renovation should gain 1 from 5 to 6 advancement tokens") (is (= 7 (get-counters (refresh iw) :advancement)) "Character Wall should gain 2 from 5 to 7 advancement tokens")))) (deftest hostile-takeover ;; Hostile Takeover (do-game (new-game (default-contestant ["Hostile Takeover"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Gain 7 credits") (is (= 1 (:bad-publicity (get-contestant))) "Take 1 bad publicity"))) (deftest house-of-knives ;; House of Knives (do-game (new-game (default-contestant ["House of Knives"]) (default-challenger)) (play-and-score state "House of Knives") (let [hok-scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh hok-scored) :agenda)) "House of Knives should start with 3 counters") (take-credits state :contestant) (run-empty-locale state "R&D") (run-phase-43 state) (card-ability state :contestant hok-scored 0) (is (= 1 (count (:discard (get-challenger)))) "Challenger should pay 1 net damage") (run-empty-locale state "R&D") (run-phase-43 state) (card-ability state :contestant hok-scored 0) (card-ability state :contestant hok-scored 0) (is (= 2 (count (:discard (get-challenger)))) "Challenger should pay 1 net damage")))) (deftest ikawah-project ;; Ikawah Project (testing "Basic test" (do-game (new-game (default-contestant ["Ikawah Project"]) (default-challenger)) (play-from-hand state :contestant "Ikawah Project" "New party") (testing "No credits" (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click 3) (run-empty-locale state :party1) (prompt-choice :challenger "No action") (is (zero? (:credit (get-challenger))) "Challenger couldn't afford to steal, so no credits spent") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Ikawah Project")) (testing "No clicks" (take-credits state :challenger) (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click 3) (run-empty-locale state :party1) (prompt-choice :challenger "No action") (is (zero? (:click (get-challenger))) "Challenger couldn't afford to steal, so no clicks spent") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal Ikawah Project")) (testing "Enough of both" (take-credits state :challenger) (take-credits state :contestant) (core/lose state :challenger :credit (:credit (get-challenger)) :click (:click (get-challenger))) (core/gain state :challenger :credit 5 :click 4) (is (= 5 (:credit (get-challenger))) "Challenger should be reset to 5 credits") (is (= 4 (:click (get-challenger))) "Challenger should be reset to 4 clicks") (run-empty-locale state :party1) (prompt-choice-partial :challenger "Pay") (prompt-choice :challenger "[Click]") (prompt-choice :challenger "2 [Credits]") (is (= 2 (:click (get-challenger))) "Challenger should lose 1 click to steal") (is (= 3 (:credit (get-challenger))) "Challenger should lose 2 credits to steal") (is (= 3 (:agenda-point (get-challenger)))) (is (= 1 (count (:scored (get-challenger)))) "Challenger should steal Ikawah Project")))) (testing "Not stealing" ;; do not reveal when the Challenger does not steal from R&D (do-game (new-game (default-contestant [(qty "Ikawah Project" 2)]) (default-challenger)) (take-credits state :contestant) (starting-hand state :contestant ["Ikawah Project"]) (run-empty-locale state "R&D") (prompt-choice :challenger "No action") (is (not (last-log-contains? state "Ikawah Project")) "Ikawah Project should not be mentioned") (run-empty-locale state "HQ") (prompt-choice :challenger "No action") (is (last-log-contains? state "Ikawah Project") "Ikawah Project should be mentioned")))) (deftest illicit-sales ;; Illicit Sales (letfn [(illicit-sales-test [[starting-bp answer credits-gained]] (testing (str "starting with " starting-bp " and answering " answer " and gaining " credits-gained) (do-game (new-game (default-contestant ["Illicit Sales"]) (default-challenger)) (let [credits (:credit (get-contestant))] (core/gain state :contestant :bad-publicity starting-bp) (play-and-score state "Illicit Sales") (prompt-choice :contestant answer) (is (= (:credit (get-contestant)) (+ credits credits-gained)))))))] (doall (map illicit-sales-test [[0 "No" 0] [0 "Yes" 3] [1 "No" 3] [1 "Yes" 6] [2 "No" 6] [2 "Yes" 9] [3 "No" 9] [3 "Yes" 12]])))) (deftest improved-protein-source ;; Improved Protein Source (do-game (new-game (default-contestant [(qty "Improved Protein Source" 2)]) (default-challenger)) (is (= 5 (:credit (get-challenger))) "Challenger starts with 5 credits") (play-and-score state "Improved Protein Source") (is (= 9 (:credit (get-challenger))) "Challenger should gain 4 credits from Contestant scoring") (play-from-hand state :contestant "Improved Protein Source" "New party") (take-credits state :contestant) (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (is (= 13 (:credit (get-challenger))) "Challenger should gain 4 credits from Contestant scoring"))) (deftest improved-tracers ;; Improved Tracers (do-game (new-game (default-contestant ["Improved Tracers" "News Hound"]) (default-challenger)) (play-from-hand state :contestant "News Hound" "HQ") (let [nh (get-character state :hq 0)] (core/reveal state :contestant nh) (is (= 4 (:current-strength (refresh nh))) "Should start with base strength of 4") (is (= 3 (:credit (get-contestant))) "Should have 2 credits after reveal") (play-and-score state "Improved Tracers") (is (= 5 (:current-strength (refresh nh))) "Should gain 1 strength from 4 to 5") (take-credits state :contestant) (run-on state "HQ") (run-phase-43 state) (card-subroutine state :contestant nh 0) (is (= 1 (get-in @state [:bonus :trace])) "Should gain 1 bonus trace strength") (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 1 (:tag (get-challenger))))))) (deftest labyrinthine-locales ;; Labyrinthine Locales (do-game (new-game (default-contestant [(qty "Labyrinthine Locales" 2)]) (default-challenger)) (play-and-score state "Labyrinthine Locales") (play-and-score state "Labyrinthine Locales") (take-credits state :contestant) (let [ls1 (get-scored state :contestant 0) ls2 (get-scored state :contestant 1)] (is (= 2 (get-counters (refresh ls1) :power))) (is (= 2 (get-counters (refresh ls2) :power))) (testing "Don't use token" (run-on state "HQ") (run-jack-out state) (is (:run @state) "Jack out prevent prompt") (prompt-choice :contestant "Done") (is (not (:run @state)) "Contestant does not prevent the jack out, run ends")) (testing "Use token" (run-on state "HQ") (run-jack-out state) (card-ability state :contestant ls1 0) (card-ability state :contestant ls2 0) (card-ability state :contestant ls1 0) (prompt-choice :contestant "Done") (is (:run @state) "Jack out prevented, run is still ongoing") (is (true? (get-in @state [:run :cannot-jack-out])) "Cannot jack out flag is in effect") (run-successful state) (is (not (:run @state)))) (testing "one Labyrinthine is empty but the other still has one token, ensure prompt still occurs" (is (zero? (get-counters (refresh ls1) :power))) (is (= 1 (get-counters (refresh ls2) :power))) (run-on state "HQ") (run-jack-out state) (is (:run @state)) (card-ability state :contestant ls2 0) (prompt-choice :contestant "Done") (is (true? (get-in @state [:run :cannot-jack-out]))) (run-successful state) (is (not (:run @state)))) (testing "No more tokens" (run-on state "HQ") (run-jack-out state) (is (not (:run @state)) "No jack out prevent prompt"))))) (deftest lcharacternse-acquisition ;; Lcharacternse Acquisition (do-game (new-game (default-contestant [(qty "Lcharacternse Acquisition" 4) "Adonis Campaign" "Eve Campaign" "Strongbox" "Contestantorate Troubleshooter"]) (default-challenger)) (testing "Set up" (starting-hand state :contestant ["Lcharacternse Acquisition" "Lcharacternse Acquisition" "Lcharacternse Acquisition" "Lcharacternse Acquisition" "Adonis Campaign" "Strongbox"]) (core/move state :contestant (find-card "Eve Campaign" (:deck (get-contestant))) :discard) (core/move state :contestant (find-card "Contestantorate Troubleshooter" (:deck (get-contestant))) :discard) (core/gain state :contestant :click 4)) (testing "Site & HQ" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Adonis Campaign" (:hand (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party2 0)))) (testing "Region & HQ" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Strongbox" (:hand (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party4 0)))) (testing "Site & Archives" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Eve Campaign" (:discard (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party6 0)))) (testing "Region & Archives" (play-and-score state "Lcharacternse Acquisition") (prompt-select :contestant (find-card "Contestantorate Troubleshooter" (:discard (get-contestant)))) (prompt-choice :contestant "New party") (is (some? (get-content state :party8 0)))))) (deftest mandatory-seed-replacement ;; Mandatory Seed Replacement (do-game (new-game (default-contestant ["Mandatory Seed Replacement" "Character Wall" "Fire Wall" "Kakugo" "Chum" "RSVP" "Sensei"]) (default-challenger)) (core/click-draw state :contestant 2) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "Character Wall" "Archives") (play-from-hand state :contestant "Fire Wall" "R&D") (play-from-hand state :contestant "Kakugo" "HQ") (play-from-hand state :contestant "Chum" "Archives") (play-from-hand state :contestant "RSVP" "R&D") (play-from-hand state :contestant "Sensei" "HQ") (let [iw (get-character state :archives 0) fw (get-character state :rd 0) kk (get-character state :hq 0) ch (get-character state :archives 1) rs (get-character state :rd 1) sn (get-character state :hq 1)] (core/reveal state :contestant iw) (core/reveal state :contestant fw) (core/reveal state :contestant kk) (core/reveal state :contestant ch) (core/reveal state :contestant rs) (core/reveal state :contestant sn) (play-and-score state "Mandatory Seed Replacement") (prompt-select :contestant (refresh iw)) (prompt-select :contestant (refresh fw)) (prompt-select :contestant (refresh kk)) (prompt-select :contestant (refresh ch)) (prompt-select :contestant (refresh rs)) (prompt-select :contestant (refresh sn))))) (deftest mandatory-regions ;; Mandatory Regions (testing "Gain an additional click" (do-game (new-game (default-contestant ["Mandatory Regions" "Melange Mining Contestant."]) (default-challenger)) (play-and-score state "Mandatory Regions") (is (= 2 (:agenda-point (get-contestant)))) (play-from-hand state :contestant "Melange Mining Contestant." "New party") (let [mmc (get-content state :party2 0)] (core/reveal state :contestant mmc) (take-credits state :contestant) (take-credits state :challenger) (is (= 4 (:click (get-contestant)))) (card-ability state :contestant mmc 0) (is (= 1 (:click (get-contestant))))))) (testing "Lose additional click if sacrifcharacterd" (do-game (new-game (default-contestant ["Mandatory Regions" "Archer"]) (default-challenger)) (play-and-score state "Mandatory Regions") (is (= 2 (:agenda-point (get-contestant)))) (play-from-hand state :contestant "Archer" "HQ") (take-credits state :contestant) (take-credits state :challenger) (let [arc (get-character state :hq 0) mu (get-scored state :contestant 0)] (is (= 4 (:click (get-contestant))) "Contestant should start turn with 4 clicks") (core/reveal state :contestant arc) (prompt-select :contestant (refresh mu)) (is (= 3 (:click (get-contestant))) "Contestant should lose 1 click on agenda sacrifcharacter"))))) (deftest market-research ;; Market Research (do-game (new-game (default-contestant [(qty "Market Research" 2)]) (default-challenger)) (testing "Challenger is not tagged" (play-and-score state "Market Research") (is (= 2 (:agenda-point (get-contestant))) "Only 4 advancements: scored for standard 2 points")) (testing "Challenger is tagged" (core/gain state :challenger :tag 1) (play-and-score state "Market Research") (is (= 5 (:agenda-point (get-contestant))) "5 advancements: scored for 3 points")))) (deftest medical-breakthrough ;; Medical Breakthrough (do-game (new-game (default-contestant [(qty "Medical Breakthrough" 3) (qty "Hedge Fund" 3)]) (default-challenger)) (play-from-hand state :contestant "Medical Breakthrough" "New party") (play-from-hand state :contestant "Medical Breakthrough" "New party") (play-from-hand state :contestant "Hedge Fund") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (take-credits state :challenger) (let [mb2 (get-content state :party2 0)] (advance state mb2 3) (core/score state :contestant {:card (refresh mb2)}) (is (= 2 (:agenda-point (get-contestant))) "Only needed 3 advancements to score")) (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Medical Breakthrough" "New party") (let [mb3 (get-content state :party3 0)] (advance state mb3 2) (core/score state :contestant {:card (refresh mb3)}) (is (= 4 (:agenda-point (get-contestant))) "Only needed 2 advancements to score")))) (deftest merger ;; Merger (do-game (new-game (default-contestant [(qty "Merger" 2)]) (default-challenger)) (play-and-score state "Merger") (is (= 2 (:agenda-point (get-contestant))) "Contestant should score 2 points") (play-from-hand state :contestant "PI:NAME:<NAME>END_PI" "New party") (take-credits state :contestant) (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (is (= 3 (:agenda-point (get-challenger))) "Challenger should score 3 points"))) (deftest meteor-mining ;; Meteor Mining (testing "when Meteor Mining is stolen" (do-game (new-game (default-contestant ["Meteor Mining"]) (default-challenger)) (play-from-hand state :contestant "Meteor Mining" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should score 2 points"))) (testing "when Meteor Mining is scored" (letfn [(meteor-mining-test [[tags num-choices pick creds dmg]] (do-game (new-game (default-contestant ["Meteor Mining"]) (default-challenger [(qty "Sure Gamble" 7)])) (starting-hand state :challenger (repeat 7 "Sure Gamble")) (let [credits (:credit (get-contestant)) grip (count (:hand (get-challenger)))] (core/gain state :challenger :tag tags) (play-and-score state "Meteor Mining") (is (= num-choices (count (:choices (first (get-in @state [:contestant :prompt])))))) (prompt-choice :contestant pick) (is (= (+ credits creds) (:credit (get-contestant))) (str "Contestant should have " (+ credits creds) " credits")) (is (= (- grip dmg) (count (:hand (get-challenger)))) (str "Challenger should have " (- grip dmg) " cards in hand")))))] (doall (map meteor-mining-test [[0 2 "No action" 0 0] [0 2 "Gain 7 [Credits]" 7 0] [1 2 "No action" 0 0] [1 2 "Gain 7 [Credits]" 7 0] [2 3 "No action" 0 0] [2 3 "Gain 7 [Credits]" 7 0] [2 3 "Do 7 meat damage" 0 7] [3 3 "No action" 0 0] [3 3 "Gain 7 [Credits]" 7 0] [3 3 "Do 7 meat damage" 0 7]]))))) (deftest napd-contract ;; NAPD Contract (testing "basic test" (do-game (new-game (default-contestant ["NAPD Contract"]) (default-challenger)) (play-from-hand state :contestant "NAPD Contract" "New party") (let [napd (get-content state :party1 0)] (advance state napd 2) (take-credits state :contestant) (core/lose state :challenger :credit 2) (run-empty-locale state "Locale 1") (prompt-choice :challenger "Yes") (is (zero? (count (:scored (get-challenger)))) "Challenger could not steal NAPD Contract") (is (= 3 (:credit (get-challenger))) "Challenger couldn't afford to steal, so no credits spent") (take-credits state :challenger) (core/gain state :contestant :bad-publicity 1) (advance state napd 2) (core/score state :contestant {:card (refresh napd)}) (is (some? (get-content state :party1 0)) "Contestant can't score with 4 advancements because of BP") (advance state napd) (core/score state :contestant {:card (refresh napd)}) (is (= 2 (:agenda-point (get-contestant))) "Scored NAPD for 2 points after 5 advancements")))) (testing "scoring requirement increases with bad publicity from Contestantorate Scandal" (do-game (new-game (default-contestant ["NAPD Contract"]) (default-challenger ["Contestantorate Scandal"])) (play-from-hand state :contestant "NAPD Contract" "New party") (let [napd (get-content state :party1 0)] (advance state napd 2) (take-credits state :contestant) (play-from-hand state :challenger "Contestantorate Scandal") (take-credits state :challenger) (advance state napd 2) (core/score state :contestant {:card (refresh napd)}) (is (some? (get-content state :party1 0)) "Contestant can't score with 4 advancements because of BP") (advance state napd) (core/score state :contestant {:card (refresh napd)}) (is (= 2 (:agenda-point (get-contestant))) "Scored NAPD for 2 points after 5 advancements"))))) (deftest net-quarantine ;; Net Quarantine (do-game (new-game (default-contestant ["Net Quarantine"]) (default-challenger)) (core/gain state :challenger :link 1) (core/gain state :contestant :click 3) (play-and-score state "Net Quarantine") (is (= 5 (:credit (get-contestant))) "Contestant has 5 credits") (is (= 1 (:link (get-challenger))) "Challenger has 1 link") (core/init-trace state :contestant {:title "/trace command" :side :contestant} {:base 1}) (prompt-choice :contestant 0) (is (zero? (:link (get-challenger))) "Challenger has 0 link") (prompt-choice :challenger 3) (is (= 1 (:link (get-challenger))) "Challenger has 1 link again") (is (= 6 (:credit (get-contestant))) "Contestant gained a credit from NQ") ; second trace of turn - no link reduction (core/init-trace state :contestant {:title "/trace command" :side :contestant} {:base 1}) (prompt-choice :contestant 0) (is (= 1 (:link (get-challenger))) "Challenger has 1 link") (prompt-choice :challenger 2) (is (= 7 (:credit (get-contestant))) "Contestant gained a credit from NQ"))) (deftest new-construction ;; New Construction (do-game (new-game (default-contestant ["New Construction" (qty "Commercial Bankers Group" 10)]) (default-challenger)) (starting-hand state :contestant (vec (cons "New Construction" (repeat 10 "Commercial Bankers Group")))) (core/gain state :contestant :click 10 :credit 10) (play-from-hand state :contestant "New Construction" "New party") (let [nc (get-content state :party1 0)] (is (zero? (get-counters (refresh nc) :advancement))) (dotimes [n 4] (advance state (refresh nc)) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Commercial Bankers Group" (:hand (get-contestant))))) (is (= 4 (get-counters (refresh nc) :advancement))) (is (not= :this-turn (:revealed (get-content state :party5 0)))) (let [credits (:credit (get-contestant))] (advance state (refresh nc)) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Commercial Bankers Group" (:hand (get-contestant)))) (is (= 5 (get-counters (refresh nc) :advancement))) (is (= :this-turn (:revealed (get-content state :party6 0)))) (is (= (dec credits) (:credit (get-contestant)))))))) (deftest next-wave-2 ;; NEXT Wave 2 (do-game (new-game (default-contestant [(qty "NEXT Wave 2" 2) "NEXT Bronze"]) (default-challenger)) (is (zero? (:brain-damage (get-challenger))) "Challenger should start with 0 brain damage") (play-from-hand state :contestant "NEXT Bronze" "HQ") (let [nxbr (get-character state :hq 0)] (core/reveal state :contestant nxbr)) (play-and-score state "NEXT Wave 2") (prompt-choice :contestant "No") (is (zero? (:brain-damage (get-challenger))) "Challenger should stay at 0 brain damage") (play-and-score state "NEXT Wave 2") (prompt-choice :contestant "Yes") (is (= 1 (:brain-damage (get-challenger))) "Challenger should gain 1 brain damage"))) (deftest nisei-mk-ii ;; Nisei MK II - Remove hosted counter to ETR, check this works in 4.3 (do-game (new-game (default-contestant ["Nisei MK II"]) (default-challenger)) (play-and-score state "Nisei MK II") (let [scored-nisei (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh scored-nisei) :agenda)) "Scored Nisei has one counter") (take-credits state :contestant) (run-on state "HQ") (run-phase-43 state) (card-ability state :contestant (refresh scored-nisei) 0) (prompt-choice :contestant "Done") ; close 4.3 contestant (is (not (:run @state)) "Run ended by using Nisei counter") (is (zero? (get-counters (refresh scored-nisei) :agenda)) "Scored Nisei has no counters")))) (deftest oaktown-renovation ;; Oaktown Renovation (do-game (new-game (default-contestant ["Oaktown Renovation" "Shipment from SanSan"]) (default-challenger)) (core/gain state :contestant :click 3) (play-from-hand state :contestant "Oaktown Renovation" "New party") (let [oak (get-content state :party1 0)] (is (:revealed (refresh oak)) "Oaktown placed face up") (advance state oak) (is (= 6 (:credit (get-contestant))) "Spent 1 credit to advance, gained 2 credits from Oaktown") (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant oak) (is (= 3 (get-counters (refresh oak) :advancement))) (is (= 6 (:credit (get-contestant))) "No credits gained due to advancements being placed") (advance state oak) (is (= 7 (:credit (get-contestant))) "Spent 1 credit to advance, gained 2 credits from Oaktown") (advance state oak) (is (= 5 (get-counters (refresh oak) :advancement))) (is (= 9 (:credit (get-contestant))) "Spent 1 credit to advance, gained 3 credits from Oaktown")))) (deftest obokata-protocol ;; Obotaka Protocol (do-game (new-game (make-deck "Cardnum: Personal Evolution" [(qty "Obokata Protocol" 10)]) (default-challenger [(qty "Sure Gamble" 4)])) (play-from-hand state :contestant "Obokata Protocol" "New party") (take-credits state :contestant) (core/gain state :challenger :agenda-point 6) (run-empty-locale state "Locale 1") (prompt-choice-partial :challenger "Pay") (is (= 4 (count (:discard (get-challenger)))) "Challenger paid 4 net damage") (is (= :challenger (:winner @state)) "Challenger wins") (is (= "Agenda" (:reason @state)) "Win condition reports agenda points") (is (last-log-contains? state "wins the game") "PE did not fire"))) (deftest paper-trail ;; Paper Trail (do-game (new-game (default-contestant ["Paper Trail"]) (default-challenger ["Aeneas Informant" "Bank Job" "Rosetta 2.0" "Magnum Opus" "Astrolabe"])) (take-credits state :contestant) (core/gain state :challenger :click 10 :credit 10) (play-from-hand state :challenger "Aeneas Informant") (play-from-hand state :challenger "Bank Job") (play-from-hand state :challenger "Rosetta 2.0") (play-from-hand state :challenger "Magnum Opus") (play-from-hand state :challenger "Astrolabe") (take-credits state :challenger) (play-and-score state "Paper Trail") (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 2 (count (:discard (get-challenger))))) (is (some? (get-radicle state 0))) (is (= 1 (count (get-radicle state)))) (is (some? (get-resource state 0))) (is (some? (get-hazard state 0))))) (deftest personality-profiles ;; Personality Profiles (testing "basic test" (do-game (new-game (default-contestant ["Personality Profiles"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" (qty "Patron" 2)])) (starting-hand state :challenger ["Self-modifying Code" "Clone Chip" "Patron" "Patron"]) (play-and-score state "Personality Profiles") (take-credits state :contestant) (play-from-hand state :challenger "Self-modifying Code") (play-from-hand state :challenger "Clone Chip") (let [smc (get-resource state 0)] (card-ability state :challenger smc 0) (prompt-card :challenger (find-card "Corroder" (:deck (get-challenger)))) (is (= 2 (count (:discard (get-challenger)))))) (let [chip (get-hazard state 0)] (card-ability state :challenger chip 0) (prompt-select :challenger (find-card "Self-modifying Code" (:discard (get-challenger)))) (is (second-last-log-contains? state "Patron") "Personality Profiles discarded card name is in log") (is (= 3 (count (:discard (get-challenger)))))))) (testing "Ensure effects still fire with an empty hand, #1840" (do-game (new-game (default-contestant ["Personality Profiles"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder"])) (starting-hand state :challenger ["Self-modifying Code" "Clone Chip"]) (play-and-score state "Personality Profiles") (take-credits state :contestant) (play-from-hand state :challenger "Self-modifying Code") (play-from-hand state :challenger "Clone Chip") (let [smc (get-resource state 0)] (card-ability state :challenger smc 0) (prompt-card :challenger (find-card "Corroder" (:deck (get-challenger))))) (let [cor (get-resource state 0)] (is (some? cor)) (is (= (:title cor) "Corroder")) (is (= "Self-modifying Code" (:title (first (:discard (get-challenger))))))) (let [chip (get-hazard state 0)] (card-ability state :challenger chip 0) (prompt-select :challenger (find-card "Self-modifying Code" (:discard (get-challenger))))) (let [smc (get-resource state 1)] (is (some? smc)) (is (= (:title smc) "Self-modifying Code")) (is (= "Clone Chip" (:title (first (:discard (get-challenger)))))))))) (deftest philotic-entanglement ;; Philotic Entanglement (do-game (new-game (default-contestant ["Philotic Entanglement" (qty "House of Knives" 3)]) (default-challenger [(qty "Sure Gamble" 3) (qty "Cache" 2)])) (play-from-hand state :contestant "House of Knives" "New party") (play-from-hand state :contestant "House of Knives" "New party") (play-from-hand state :contestant "House of Knives" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (run-empty-locale state :party2) (prompt-choice :challenger "Steal") (run-empty-locale state :party3) (prompt-choice :challenger "Steal") (is (= 3 (count (:scored (get-challenger))))) (take-credits state :challenger) (play-and-score state "Philotic Entanglement") (is (= 2 (:agenda-point (get-contestant)))) (is (= 3 (count (:discard (get-challenger)))) "Dealt 3 net damage upon scoring"))) (deftest posted-bounty ;; Posted Bounty (testing "Forfeiting takes 1 bad publicity" (do-game (new-game (default-contestant ["Posted Bounty"]) (default-challenger)) (play-and-score state "Posted Bounty") (prompt-choice :contestant "Yes") (is (zero? (:agenda-point (get-contestant))) "Forfeiting Posted Bounty nullifies agenda points") (is (= 1 (:bad-publicity (get-contestant))) "Forfeiting takes 1 bad publicity") (is (= 1 (:tag (get-challenger))) "Challenger receives 1 tag forfeiting Posted Bounty"))) (testing "Choosing not to forfeit scores normally" (do-game (new-game (default-contestant ["Posted Bounty"]) (default-challenger)) (play-and-score state "Posted Bounty") (prompt-choice :contestant "No") (is (= 1 (:agenda-point (get-contestant)))) (is (zero? (:bad-publicity (get-contestant)))) (is (zero? (:tag (get-challenger))))))) (deftest priority-requisition ;; Priority Requisition (do-game (new-game (default-contestant ["Priority Requisition" "Archer"]) (default-challenger)) (play-from-hand state :contestant "Archer" "HQ") (let [arc (get-character state :hq 0)] (play-and-score state "Priority Requisition") (prompt-select :contestant arc) (is (:revealed (refresh arc)))))) (deftest private-security-force ;; Private Security Force (do-game (new-game (default-contestant [(qty "Private Security Force" 10)]) (default-challenger)) (core/gain state :challenger :tag 1) (play-and-score state "Private Security Force") (let [psf-scored (get-scored state :contestant 0)] (card-ability state :contestant psf-scored 0) (is (= 1 (count (:discard (get-challenger))))) (take-credits state :challenger) (dotimes [n 3] (card-ability state :contestant psf-scored 0)) (is (= 3 (count (:discard (get-challenger))))) (is (= :contestant (:winner @state)) "Contestant wins") (is (= "Flatline" (:reason @state)) "Win condition reports flatline")))) (deftest profiteering ;; Profiteering (do-game (new-game (default-contestant ["Profiteering"]) (default-challenger)) (play-and-score state "Profiteering") (prompt-choice :contestant "3") (is (= 1 (:agenda-point (get-contestant)))) (is (= 3 (:bad-publicity (get-contestant))) "Took 3 bad publicity") (is (= 20 (:credit (get-contestant))) "Gained 15 credits"))) (deftest project-ares ;; Project Ares (do-game (new-game (default-contestant [(qty "Project Ares" 2)]) (default-challenger ["Clone Chip"])) (take-credits state :contestant) (play-from-hand state :challenger "Clone Chip") (take-credits state :challenger) (play-and-score state "Project Ares") (is (empty? (get-in @state [:challenger :prompt])) "No prompt for Challenger if scored with 4 advancement tokens") (core/gain state :contestant :click 5) (play-from-hand state :contestant "Project Ares" "New party") (let [ares (get-content state :party2 0)] (advance state ares 6) (is (= 6 (get-counters (refresh ares) :advancement))) (core/score state :contestant {:card (refresh ares)}) (is (prompt-is-card? :challenger ares) "Challenger has Ares prompt to discard placed cards")) (prompt-select :challenger (find-card "Clone Chip" (:hazard (:rig (get-challenger))))) (is (empty? (get-in @state [:challenger :prompt])) "Challenger must discard 2 cards but only has 1 card in rig, prompt ended") (is (= 1 (count (:discard (get-challenger))))) (is (= 1 (:bad-publicity (get-contestant)))))) (deftest project-atlas ;; Project Atlas (testing "basic test" (do-game (new-game (default-challenger ["Project Atlas" "Beanstalk Royalties"]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Project Atlas"]) (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party1 0)] (advance state atlas 4) (is (= 4 (get-counters (refresh atlas) :advancement)) "Atlas should have 4 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant)))) (is (zero? (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 0 agenda counters") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand")))) (testing "test with Titan" (do-game (new-game (make-deck "Titan Transnational: Investing In Your Future" [(qty "Project Atlas" 2) "Beanstalk Royalties" "Hedge Fund"]) (default-challenger)) ;; Set up (starting-hand state :contestant ["Project Atlas" "Project Atlas"]) (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party1 0)] (advance state atlas 3) (is (= 3 (get-counters (refresh atlas) :advancement)) "Atlas should have 3 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Beanstalk Royalties" (:deck (get-contestant)))) (is (zero? (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 0 agenda counters") (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 card in hand")) ;; Should gain 2 counters (play-from-hand state :contestant "Project Atlas" "New party") (let [atlas (get-content state :party2 0)] (advance state atlas 4) (is (= 4 (get-counters (refresh atlas) :advancement)) "Atlas should have 4 advancement tokens") (core/score state :contestant {:card (refresh atlas)})) (let [atlas-scored (get-scored state :contestant 1)] (is (= 2 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 2 agenda counter") (card-ability state :contestant atlas-scored 0) (prompt-card :contestant (find-card "Hedge Fund" (:deck (get-contestant)))) (is (= 1 (get-counters (refresh atlas-scored) :agenda)) "Atlas should have 1 agenda counters") (is (= 2 (count (:hand (get-contestant)))) "Contestant should have 2 cards in hand"))))) (deftest project-beale ;; Project Beale (do-game (new-game (default-contestant [(qty "Project Beale" 2)]) (default-challenger)) (core/gain state :contestant :click 8 :credit 8) (play-from-hand state :contestant "Project Beale" "New party") (let [pb1 (get-content state :party1 0)] (advance state pb1 4) (core/score state :contestant {:card (refresh pb1)}) (is (= 2 (:agenda-point (get-contestant))) "Only 4 advancements: scored for standard 2 points") (play-from-hand state :contestant "Project Beale" "New party")) (let [pb2 (get-content state :party2 0)] (advance state pb2 5) (core/score state :contestant {:card (refresh pb2)}) (is (= 5 (:agenda-point (get-contestant))) "5 advancements: scored for 3 points")))) (deftest project-kusanagi ;; Project Kusanagi (do-game (new-game (default-contestant [(qty "Project Kusanagi" 2) "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (core/gain state :contestant :click 10 :credit 10) (testing "Should gain 0 counters" (play-and-score state "Project Kusanagi") (let [pk-scored (get-scored state :contestant 0)] (is (zero? (get-counters (refresh pk-scored) :agenda)) "Kusanagi should start with 0 agenda counters"))) (testing "Should gain 1 counter" (play-from-hand state :contestant "Project Kusanagi" "New party") (let [pk (get-content state :party2 0)] (advance state pk 3) (is (= 3 (get-counters (refresh pk) :advancement)) "Kusanagi should have 3 advancement tokens") (core/score state :contestant {:card (refresh pk)})) (let [pk-scored (get-scored state :contestant 1)] (is (= 1 (get-counters (refresh pk-scored) :agenda)) "Kusanagi should have 1 agenda counter") (run-empty-locale state :hq) (card-ability state :contestant pk-scored 0) (is (last-log-contains? state "Do 1 net damage")) (is (zero? (get-counters (refresh pk-scored) :agenda)) "Kusanagi should have 0 agenda counters"))))) (deftest project-vitruvius ;; Project Vitruvius (do-game (new-game (default-contestant ["Project Vitruvius" "Hedge Fund"]) (default-challenger)) ;; Set up (core/move state :contestant (find-card "Hedge Fund" (:hand (get-contestant))) :discard) (is (= 1 (count (:discard (get-contestant)))) "Contestant should have 1 cards in hand") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand") (core/gain state :contestant :click 10 :credit 10) ;; Should gain 1 counter (play-from-hand state :contestant "Project Vitruvius" "New party") (let [vit (get-content state :party1 0)] (advance state vit 4) (is (= 4 (get-counters (refresh vit) :advancement)) "Vitruvius should have 4 advancement tokens") (core/score state :contestant {:card (refresh vit)})) (let [vit-scored (get-scored state :contestant 0)] (is (= 1 (get-counters (refresh vit-scored) :agenda)) "Vitruvius should have 1 agenda counter") (card-ability state :contestant vit-scored 0) (prompt-select :contestant (find-card "Hedge Fund" (:discard (get-contestant)))) (is (zero? (get-counters (refresh vit-scored) :agenda)) "Vitruvius should have 0 agenda counters") (is (= 1 (count (:hand (get-contestant)))) "Contestant should have 1 cards in hand")))) (deftest project-wotan ;; Project Wotan - Only checks if agenda counter is spent (do-game (new-game (default-contestant ["Project Wotan" "Eli 1.0" (qty "Hedge Fund" 3)]) (default-challenger)) (starting-hand state :contestant ["Project Wotan" "Eli 1.0"]) (play-from-hand state :contestant "Eli 1.0" "HQ") (let [eli (get-character state :hq 0)] (core/reveal state :contestant eli)) (play-and-score state "Project Wotan") (take-credits state :contestant) (let [wot-scored (get-scored state :contestant 0)] (is (= 3 (get-counters (refresh wot-scored) :agenda)) "Wotan should start with 3 agenda counters") (run-on state "HQ") (card-ability state :contestant wot-scored 0) (is (= 2 (get-counters (refresh wot-scored) :agenda))) "Wotan should only have 2 agenda counters"))) (deftest puppet-master ;; Puppet Master - game progresses if no valid targets. Issue #1661. (do-game (new-game (default-contestant ["Puppet Master"]) (default-challenger)) (play-and-score state "Puppet Master") (take-credits state :contestant) (run-empty-locale state :archives) (prompt-choice :contestant "Done") (is (empty? (:prompt (get-challenger))) "Challenger's waiting prompt resolved"))) (deftest quantum-predictive-model ;; Quantum Predictive Model (do-game (new-game (default-contestant [(qty "Quantum Predictive Model" 4)]) (default-challenger)) (testing "Set up" (starting-hand state :contestant ["Quantum Predictive Model" "Quantum Predictive Model"]) (play-from-hand state :contestant "Quantum Predictive Model" "New party") (play-from-hand state :contestant "Quantum Predictive Model" "New party") (take-credits state :contestant)) (testing "Access placed with no tag" (run-on state :party1) (run-successful state) (prompt-choice :challenger "Steal") (is (= 1 (:agenda-point (get-challenger))) "Challenger should steal")) (testing "Access R&D with no tag" (run-on state :rd) (run-successful state) (prompt-choice :challenger "Steal") (is (= 2 (:agenda-point (get-challenger))) "Challenger should steal")) (core/gain state :challenger :tag 1) (testing "Access intalled with tag" (run-on state :party2) (run-successful state) (prompt-choice :challenger "No action") ;; this is now a prompt that QPM was added to Contestant score area (is (= 2 (:agenda-point (get-challenger))) "Challenger should not steal") (is (= 1 (:agenda-point (get-contestant))) "Contestant should score")) (testing "Access R&D with tag" (run-on state :rd) (run-successful state) (prompt-choice :challenger "No action") (is (= 2 (:agenda-point (get-challenger))) "Challenger should not steal") (is (= 2 (:agenda-point (get-contestant))) "Contestant should score")) (is (zero? (count (:deck (get-contestant))))))) (deftest rebranding-team ;; Rebranding Team (do-game (new-game (default-contestant ["Rebranding Team" "Launch Campaign" "City Surveillance" "PI:NAME:<NAME>END_PI" "Museum of History" "Advanced Assembly Lines"]) (default-challenger)) (play-and-score state "Rebranding Team") (core/click-draw state :challenger 1) (is (core/has-subtype? (find-card "Advanced Assembly Lines" (:hand (get-contestant))) "Advertisement")) ; #2608 part 2 - retain Advertisement always (discard-from-hand state :contestant "Advanced Assembly Lines") (is (core/has-subtype? (find-card "Advanced Assembly Lines" (:discard (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "Launch Campaign" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "City Surveillance" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "PI:NAME:<NAME>END_PI" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "PI:NAME:<NAME>END_PI" (:hand (get-contestant))) "Executive")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Advertisement")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Alliance")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Ritzy")) (core/move state :contestant (find-card "Rebranding Team" (:scored (get-contestant))) :deck) (is (core/has-subtype? (find-card "Launch Campaign" (:hand (get-contestant))) "Advertisement")) (is (not (core/has-subtype? (find-card "Advanced Assembly Lines" (:discard (get-contestant))) "Advertisement"))) (is (not (core/has-subtype? (find-card "City Surveillance" (:hand (get-contestant))) "Advertisement"))) (is (not (core/has-subtype? (find-card "PI:NAME:<NAME>END_PI" (:hand (get-contestant))) "Advertisement"))) (is (core/has-subtype? (find-card "PI:NAME:<NAME>END_PI" (:hand (get-contestant))) "Executive")) (is (not (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Advertisement"))) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Alliance")) (is (core/has-subtype? (find-card "Museum of History" (:hand (get-contestant))) "Ritzy")))) (deftest reeducation ;; Reeducation (testing "Simple test" (do-game (new-game (default-contestant ["Reeducation" "Sweeps Week" "Hedge Fund" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" "Sure Gamble" "Desperado"])) (starting-hand state :contestant ["Reeducation" "Sweeps Week"]) (starting-hand state :challenger ["Self-modifying Code"]) (play-and-score state "Reeducation") (is (prompt-is-type? :challenger :waiting) "Challenger has wait prompt") (is (= 1 (count (get-in @state [:contestant :hand])))) (is (= 1 (count (get-in @state [:challenger :hand])))) (prompt-card :contestant (find-card "Sweeps Week" (:hand (get-contestant)))) ; put Sweeps Week at bottom of R&D (prompt-choice :contestant "Done") ; finished selecting cards (prompt-choice :contestant "Done") ; contestant prompt for Done/Start Over (is (= "Sweeps Week" (:title (last (:deck (get-contestant)))))) (is (= "Self-modifying Code" (:title (last (:deck (get-challenger)))))) (is (= 1 (count (get-in @state [:contestant :hand])))) (is (zero? (count (get-in @state [:challenger :hand])))))) (testing "Extra cards" ;; If Contestant is adding more cards in HQ than Challenger has in their Grip, Challenger ;; is not 'able' to resolve the effect and doesn't have to add to bottom of Stack (do-game (new-game (default-contestant ["Reeducation" "Sweeps Week" "Hedge Fund" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) (default-challenger ["Self-modifying Code" "Clone Chip" "Corroder" "Sure Gamble" "Desperado"])) (starting-hand state :contestant ["Reeducation" "Sweeps Week" "Hedge Fund"]) (starting-hand state :challenger ["Self-modifying Code"]) (play-and-score state "Reeducation") (is (prompt-is-type? :challenger :waiting) "Challenger has wait prompt") (is (= 2 (count (:hand (get-contestant))))) (is (= 1 (count (:hand (get-challenger))))) (prompt-card :contestant (find-card "Sweeps Week" (:hand (get-contestant)))) (prompt-card :contestant (find-card "Hedge Fund" (:hand (get-contestant)))) ; this is the bottom card of R&D (prompt-choice :contestant "Done") ; finished selecting cards (prompt-choice :contestant "Done") ; contestant prompt for Done/Start Over (is (= "Hedge Fund" (:title (last (:deck (get-contestant)))))) (is (= "Sweeps Week" (:title (last (butlast (:deck (get-contestant))))))) (is (= "Self-modifying Code" (:title (first (:hand (get-challenger)))))) (is (= 2 (count (:hand (get-contestant))))) (is (= 1 (count (:hand (get-challenger)))))))) (deftest party-data-farm ;; Party Data Farm (do-game (new-game (default-contestant ["Party Data Farm"]) (default-challenger)) (is (= 5 (get-hand-size :contestant))) (play-and-score state "Party Data Farm") (is (= 7 (get-hand-size :contestant))))) (deftest party-enforcement ;; Party Enforcement - Search R&D for a piece of character and place it on a party at no reveal cost (do-game (new-game (default-contestant [(qty "Party Enforcement" 2) "Archer" "Chiyashi"]) (make-deck "RePI:NAME:<NAME>END_PI Roja: Freedom Fighter" [])) (starting-hand state :contestant ["Party Enforcement" "Party Enforcement"]) (is (= 2 (count (:deck (get-contestant))))) (play-and-score state "Party Enforcement") (let [N (:credit (get-contestant))] (prompt-choice :contestant "Yes") (prompt-choice :contestant (find-card "Chiyashi" (:deck (get-contestant)))) (prompt-choice :contestant "New party") (is (core/revealed? (get-character state :party2 0)) "Chiyashi was placed revealed") (is (= N (:credit (get-contestant))) "Revealing Chiyashi was free")) (play-and-score state "Party Enforcement") (let [N (:credit (get-contestant))] (prompt-choice :contestant "Yes") (prompt-card :contestant (find-card "Archer" (:deck (get-contestant)))) (prompt-choice :contestant "Locale 2") (is (= (dec N) (:credit (get-contestant))) "Placing Archer cost a credit") (is (not-empty (:prompt (get-contestant))) "Contestant prompted to forfeit an agenda for Archer") (is (= (dec N) (:credit (get-contestant))) "Revealing Archer didn't cost any credits")))) (deftest research-grant ;; Research Grant (testing "Basic test" (do-game (new-game (default-contestant [(qty "Research Grant" 2)]) (default-challenger)) (play-from-hand state :contestant "Research Grant" "New party") (play-and-score state "Research Grant") (prompt-select :contestant (get-content state :party1 0)) (is (= 2 (count (:scored (get-contestant)))) "2 copies of Research Grant scored"))) (testing "vs Leela" ;; Issue #3069 (do-game (new-game (default-contestant [(qty "Research Grant" 2) (qty "Character Wall" 2)]) (make-deck "Leela Patel: Trained Pragmatist" ["Sure Gamble"])) (core/gain state :contestant :click 1) (play-from-hand state :contestant "Character Wall" "HQ") (play-from-hand state :contestant "Character Wall" "R&D") (play-from-hand state :contestant "Research Grant" "New party") (play-and-score state "Research Grant") (prompt-select :contestant (get-content state :party1 0)) (is (= 2 (count (:scored (get-contestant)))) "2 copies of Research Grant scored") (prompt-select :challenger (get-character state :hq 0)) (prompt-select :challenger (get-character state :rd 0)) (is (empty? (:effect-completed @state)) "All score and Leela effects resolved")))) (deftest restructured-datapool ;; Restructured Datapool (do-game (new-game (default-contestant ["Restructured Datapool"]) (default-challenger)) (is (zero? (:tag (get-challenger))) "Challenger should start with no tags") (play-and-score state "Restructured Datapool") (let [rd-scored (get-scored state :contestant 0)] (card-ability state :contestant rd-scored 0) (prompt-choice :contestant 0) (prompt-choice :challenger 0) (is (= 1 (:tag (get-challenger))) "Challenger should gain a tag from Restructured Datapool ability")))) (deftest self-destruct-chips ;; Self-Destruct Chips (do-game (new-game (default-contestant ["Self-Destruct Chips"]) (default-challenger)) (is (= 5 (get-hand-size :challenger)) "Challenger's hand size starts at 5") (play-and-score state "Self-Destruct Chips") (is (= 4 (get-hand-size :challenger)) "By scoring Self-Destruct Chips, Challenger's hand size is reduced by 1"))) (deftest sensor-net-activation ;; Sensor Net Activation (do-game (new-game (default-contestant [(qty "Sensor Net Activation" 2) "Enforcer 1.0" "Ash 2X3ZB9CY"]) (default-challenger)) (play-from-hand state :contestant "Enforcer 1.0" "HQ") (play-and-score state "Sensor Net Activation") (let [sna-scored (get-scored state :contestant 0) enf (get-character state :hq 0)] (is (= 1 (get-counters (refresh sna-scored) :agenda)) "Should start with 1 agenda counter") (is (not (:revealed (refresh enf))) "Enforcer 1.0 should start hidden") (card-ability state :contestant (refresh sna-scored) 0) (prompt-select :contestant enf) (is (:revealed (refresh enf)) "Enforcer 1.0 should be revealed") (is (= 1 (count (:scored (get-contestant)))) "Enforcer 1.0 should be revealed without forfeiting agenda") (take-credits state :contestant) (is (not (:revealed (refresh enf))) "Enforcer 1.0 should be hidden")) (take-credits state :contestant) (take-credits state :challenger) (play-from-hand state :contestant "Ash 2X3ZB9CY" "New party") (play-and-score state "Sensor Net Activation") (let [sna-scored (get-scored state :contestant 1) ash (get-content state :party2 0)] (is (= 1 (get-counters (refresh sna-scored) :agenda)) "Should start with 1 agenda counter") (is (not (:revealed (refresh ash))) "Ash should start hidden") (card-ability state :contestant (refresh sna-scored) 0) (prompt-select :contestant ash) (is (:revealed (refresh ash)) "Ash should be revealed") (take-credits state :contestant) (is (not (:revealed (refresh ash))) "Ash should be hidden")))) (deftest sentinel-defense-resource ;; Sentinel Defense Resource - Doesn't fire if brain damage is prevented (do-game (new-game (default-contestant ["Sentinel Defense Resource" "Viktor 1.0"]) (default-challenger ["Feedback Filter" (qty "Sure Gamble" 3)])) (play-and-score state "Sentinel Defense Resource") (play-from-hand state :contestant "Viktor 1.0" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Feedback Filter") (let [viktor (get-character state :hq 0) ff (get-hazard state 0)] (run-on state "HQ") (core/reveal state :contestant viktor) (card-subroutine state :contestant viktor 0) (prompt-choice :challenger "Done") ;; Don't prevent the brain damage (is (= 1 (count (:discard (get-challenger))))) (is (= 1 (:brain-damage (get-challenger)))) (prompt-choice :challenger "Done") ;; So we take the net, but don't prevent it either (is (= 2 (count (:discard (get-challenger))))) (card-subroutine state :contestant viktor 0) (card-ability state :challenger ff 1) ;; Prevent the brain damage this time (prompt-choice :challenger "Done") (is (= 3 (count (:discard (get-challenger)))) "Feedback filter discarded, didn't take another net damage") (is (= 1 (:brain-damage (get-challenger))))))) (deftest show-of-force ;; Show of Force (do-game (new-game (default-contestant ["Show of Force"]) (default-challenger)) (is (= 3 (count (:hand (get-challenger)))) "Challenger should start with 3 cards in hand") (play-and-score state "Show of Force") (is (= 1 (count (:hand (get-challenger)))) "Challenger should have 1 card in hand") (is (= 2 (count (:discard (get-challenger)))) "Challenger should have discarded 2 cards"))) (deftest ssl-endorsement ;; SSL Endorsement (testing "gain credits when in contestant score area before turn begins" (do-game (new-game (default-contestant ["SSL Endorsement"]) (default-challenger)) (play-and-score state "SSL Endorsement") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 5 (:credit (get-contestant))) "Contestant starts with 5 credits") (prompt-choice :contestant "Yes") (is (= 8 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 8 (:credit (get-contestant))) "Contestant starts with 8 credits") (prompt-choice :contestant "No") (is (= 8 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 8 (:credit (get-contestant))) "Contestant starts with 8 credits") (prompt-choice :contestant "Yes") (is (= 11 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 11 (:credit (get-contestant))) "Contestant starts with 11 credits") (prompt-choice :contestant "Yes") (is (= 14 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money"))) (testing "gain credits when in challenger score area before turn begins" (do-game (new-game (default-contestant ["SSL Endorsement"]) (default-challenger)) (play-from-hand state :contestant "SSL Endorsement" "New party") (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 7 (:credit (get-contestant))) "Contestant starts with 7 credits") (prompt-choice :contestant "Yes") (is (= 10 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits") (prompt-choice :contestant "No") (is (= 10 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 10 (:credit (get-contestant))) "Contestant starts with 10 credits") (prompt-choice :contestant "Yes") (is (= 13 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 13 (:credit (get-contestant))) "Contestant starts with 13 credits") (prompt-choice :contestant "Yes") (is (= 16 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money"))) (testing "register event when agenda swapped with Turntable" ;; Regression test for #3114 (do-game (new-game (default-contestant ["SSL Endorsement" "Breaking News"]) (default-challenger ["Turntable"])) (play-from-hand state :contestant "Breaking News" "New party") (play-and-score state "SSL Endorsement") (take-credits state :contestant) (play-from-hand state :challenger "Turntable") (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (prompt-choice :challenger "Yes") (prompt-select :challenger (find-card "SSL Endorsement" (:scored (get-contestant)))) ;; Swap BN with SSL (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 6 (:credit (get-contestant))) "Contestant starts with 7 credits") (prompt-choice :contestant "Yes") (is (= 9 (:credit (get-contestant))) "Contestant gains 3 credits from Turntable'd SSL Endorsement"))) (testing "don't double register event when agenda is swapped" (do-game (new-game (default-contestant ["SSL Endorsement" "Breaking News" "Exchange of Information"]) (default-challenger)) (play-from-hand state :contestant "SSL Endorsement" "New party") (play-and-score state "Breaking News") (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :challenger "Steal") (take-credits state :challenger) (is (not-empty (:prompt (get-contestant))) "Contestant prompted to take credits") (is (= 6 (:credit (get-contestant))) "Contestant starts with 6 credits") (prompt-choice :contestant "Yes") (is (= 9 (:credit (get-contestant))) "Contestant gains 3 credits") (core/gain state :challenger :tag 1) (play-from-hand state :contestant "Exchange of Information") (prompt-select :contestant (find-card "SSL Endorsement" (:scored (get-challenger)))) (prompt-select :contestant (find-card "Breaking News" (:scored (get-contestant)))) (take-credits state :challenger) (is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits") (prompt-choice :contestant "No") (is (empty? (:prompt (get-contestant))) "Not double prompted for credits") (is (= 9 (:credit (get-contestant))) "Contestant doesn't gain 3 credits") (take-credits state :challenger) (is (= 9 (:credit (get-contestant))) "Contestant starts with 9 credits") (prompt-choice :contestant "Yes") (is (= 12 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (= 12 (:credit (get-contestant))) "Contestant starts with 12 credits") (prompt-choice :contestant "Yes") (is (= 15 (:credit (get-contestant))) "Contestant gains 3 credits") (take-credits state :challenger) (is (empty? (:prompt (get-contestant))) "Not prompted when out of money")))) (deftest standoff ;; Standoff (testing "Challenger declines first" (do-game (new-game (default-contestant ["Standoff" "Character Wall" "News Team"]) (default-challenger ["Cache"])) (starting-hand state :contestant ["Standoff" "Character Wall"]) (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Cache") (take-credits state :challenger) (play-and-score state "Standoff") (starting-hand state :contestant []) (is (zero? (-> (get-challenger) :discard count)) "Challenger should have no cards in Heap") (prompt-select :challenger (get-resource state 0)) (is (= 1 (-> (get-challenger) :discard count)) "Challenger should now have 1 card in Heap") (is (zero? (-> (get-contestant) :discard count)) "Contestant should have no cards in Archives") (prompt-select :contestant (get-character state :hq 0)) (is (= 1 (-> (get-contestant) :discard count)) "Contestant should now have 1 card in Archives") (is (zero? (-> (get-contestant) :hand count)) "Contestant should have no cards in hand") (let [credits (:credit (get-contestant))] (prompt-choice :challenger "Done") (is (= (+ credits 5) (:credit (get-contestant))) "Contestant should gain 5 credits from Challenger declining to discard an placed card") (is (= 1 (-> (get-contestant) :hand count)) "Contestant should draw a card from Challenger declining to discard an placed card")))) (testing "Contestant declines first" (do-game (new-game (default-contestant ["Standoff" "Character Wall" "News Team"]) (default-challenger ["Cache" "Cache"])) (starting-hand state :contestant ["Standoff" "Character Wall"]) (play-from-hand state :contestant "Character Wall" "HQ") (take-credits state :contestant) (play-from-hand state :challenger "Cache") (play-from-hand state :challenger "Cache") (take-credits state :challenger) (play-and-score state "Standoff") (starting-hand state :contestant []) (is (zero? (-> (get-challenger) :discard count)) "Challenger should have no cards in Heap") (prompt-select :challenger (get-resource state 0)) (is (= 1 (-> (get-challenger) :discard count)) "Challenger should now have 1 card in Heap") (is (zero? (-> (get-contestant) :discard count)) "Contestant should have no cards in Archives") (prompt-select :contestant (get-character state :hq 0)) (is (= 1 (-> (get-contestant) :discard count)) "Contestant should now have 1 card in Archives") (is (zero? (-> (get-contestant) :hand count)) "Contestant should have no cards in hand") (prompt-select :challenger (get-resource state 0)) (is (= 2 (-> (get-challenger) :discard count)) "Challenger should now have 2 cards in Heap") (let [credits (:credit (get-contestant))] (prompt-choice :contestant "Done") (is (= credits (:credit (get-contestant))) "Contestant should gain no credits from declining to discard an placed card") (is (zero? (-> (get-contestant) :hand count)) "Contestant should draw no cards from declining to discard an placed card"))))) (deftest successful-field-test ;; Successful Field Test (do-game (new-game (default-contestant ["Successful Field Test" (qty "Character Wall" 10)]) (default-challenger)) (starting-hand state :contestant (vec (cons "Successful Field Test" (repeat 10 "Character Wall")))) (is (= 5 (:credit (get-contestant))) "Should start with 5 credits") (play-and-score state "Successful Field Test") (dotimes [n 10] (prompt-select :contestant (find-card "Character Wall" (:hand (get-contestant)))) (prompt-choice :contestant "HQ")) (is (= 5 (:credit (get-contestant))) "Should still have 5 credits") (is (some? (get-character state :hq 9))))) (deftest superior-cyberwalls ;; Superior Cyberwalls (do-game (new-game (default-contestant ["Superior Cyberwalls" "Character Wall"]) (default-challenger)) (play-from-hand state :contestant "Character Wall" "HQ") (let [iw (get-character state :hq 0)] (core/reveal state :contestant iw) (is (= 1 (:current-strength (refresh iw))) "Should start with base strength of 1") (is (= 4 (:credit (get-contestant))) "Should have 4 credits after reveal") (play-and-score state "Superior Cyberwalls") (is (= 2 (:current-strength (refresh iw))) "Should gain 1 strength from 1 to 2") (is (= 5 (:credit (get-contestant))) "Should gain 1 credit for revealed barrier")))) (deftest tgtbt ;; TGTBT - Give the Challenger 1 tag when they access ;; OHG still not working... (do-game (new-game (default-contestant [(qty "TGTBT" 2) "Old Hollywood Grid"]) (default-challenger)) (play-from-hand state :contestant "TGTBT" "New party") (play-from-hand state :contestant "Old Hollywood Grid" "Locale 1") (play-from-hand state :contestant "TGTBT" "New party") (take-credits state :contestant) (let [tg1 (get-content state :party1 0) ohg (get-content state :party1 1)] (run-on state "Locale 1") (core/reveal state :contestant ohg) (run-successful state) (prompt-select :challenger tg1) ;; Accesses TGTBT but can't steal (is (= 1 (:tag (get-challenger))) "Challenger took 1 tag from accessing without stealing") (prompt-choice :challenger "No action") (prompt-select :challenger ohg)) (prompt-choice :challenger "Yes") ;; Discards OHG (run-empty-locale state "Locale 2") ;; Accesses TGTBT and can steal (prompt-choice :challenger "Steal") (is (= 2 (:tag (get-challenger))) "Challenger took 1 tag from accessing and stealing"))) (deftest the-cleaners ;; The Cleaners (testing "Basic test" (do-game (new-game (default-contestant ["The Cleaners" "Scorched Earth"]) (default-challenger [(qty "Sure Gamble" 3) (qty "Diesel" 3)])) (play-and-score state "The Cleaners") (core/gain state :challenger :tag 1) (play-from-hand state :contestant "Scorched Earth") (is (zero? (count (:hand (get-challenger)))) "5 damage dealt to Challenger"))) (testing "No bonus damage when challenger 'suffers' damage, ie Cybernetics" (do-game (new-game (default-contestant ["The Cleaners"]) (default-challenger [(qty "Respirocytes" 3)])) (play-and-score state "The Cleaners") (take-credits state :contestant) (play-from-hand state :challenger "Respirocytes") (is (= 1 (count (:hand (get-challenger)))) "Only 1 damage dealt to Challenger from Cybernetics")))) (deftest the-future-is-now ;; The Future is Now (testing "With at least one card in deck" (do-game (new-game (default-contestant ["The Future is Now" "Character Wall"]) (default-challenger)) (starting-hand state :contestant ["The Future is Now"]) (is (= 1 (count (:hand (get-contestant))))) (is (= 1 (count (:deck (get-contestant))))) (play-and-score state "The Future is Now") (prompt-card :contestant (find-card "Character Wall" (:deck (get-contestant)))) (is (= 1 (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant))))))) (testing "With an empty deck" (do-game (new-game (default-contestant ["The Future is Now"]) (default-challenger)) (is (= 1 (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant))))) (play-and-score state "The Future is Now") (is (empty? (:prompt (get-contestant))) "Ability shouldn't fire if deck is empty") (is (zero? (count (:hand (get-contestant))))) (is (zero? (count (:deck (get-contestant)))))))) (deftest the-future-perfect ;; The Future Perfect (do-game (new-game (default-contestant [(qty "The Future Perfect" 2)]) (default-challenger)) (play-from-hand state :contestant "The Future Perfect" "New party") (take-credits state :contestant) (testing "No steal on not-equal Psi game" (run-empty-locale state "HQ") (prompt-choice :contestant "1 [Credits]") (prompt-choice :challenger "0 [Credits]") ;; Cannot steal prompt (prompt-choice :challenger "No action") (is (zero? (:agenda-point (get-challenger))) "Challenger did not steal TFP")) (testing "Successful steal on equal Psi game" (run-empty-locale state "HQ") (prompt-choice :contestant "1 [Credits]") (prompt-choice :challenger "1 [Credits]") (prompt-choice :challenger "Steal") (is (= 3 (:agenda-point (get-challenger))) "Challenger stole TFP")) (testing "No Psi game and successful steal when placed" (run-empty-locale state "Locale 1") (prompt-choice :challenger "Steal") (is (= 6 (:agenda-point (get-challenger))) "Challenger stole TFP - no Psi game on placed TFP")))) (deftest underway-renovation ;; Underway Renovation (do-game (new-game (default-contestant ["Underway Renovation" "Shipment from SanSan"]) (default-challenger)) (core/gain state :contestant :click 2) (starting-hand state :challenger []) (play-from-hand state :contestant "Underway Renovation" "New party") (let [ur (get-content state :party1 0)] (advance state ur) (is (last-log-contains? state "Sure Gamble") "Underway Renovation discarded card name is in log") ; check for #2370 (is (not (last-log-contains? state "Sure Gamble, Sure Gamble")) "Underway Renovation discarded card name is in log") (is (= 1 (count (:discard (get-challenger)))) "1 card milled from Challenger Stack") (play-from-hand state :contestant "Shipment from SanSan") (prompt-choice :contestant "2") (prompt-select :contestant ur) (is (= 3 (get-counters (refresh ur) :advancement))) (is (= 1 (count (:discard (get-challenger)))) "No Challenger mills; advancements were placed") (advance state ur) (is (= 4 (get-counters (refresh ur) :advancement))) (is (last-log-contains? state "Sure Gamble, Sure Gamble") "Underway Renovation discarded card name is in log") (is (= 3 (count (:discard (get-challenger)))) "2 cards milled from Challenger Stack; 4+ advancements")))) (deftest unorthodox-predictions ;; Unorthodox Predictions (do-game (new-game (default-contestant ["Unorthodox Predictions"]) (default-challenger)) (play-and-score state "Unorthodox Predictions") (prompt-choice :contestant "Barrier") (is (last-log-contains? state "Barrier")))) (deftest utopia-fragment ;; Utopia Fragment (do-game (new-game (default-contestant ["Utopia Fragment" "Hostile Takeover"]) (default-challenger)) (play-and-score state "Utopia Fragment") (play-from-hand state :contestant "Hostile Takeover" "New party") (advance state (get-content state :party2 0)) (take-credits state :contestant) (run-on state :party2) (run-successful state) (prompt-choice-partial :challenger "Pay") (is (= 1 (:agenda-point (get-challenger)))) (is (= 3 (:credit (get-challenger)))))) (deftest vanity-project ;; Vanity Project (do-game (new-game (default-contestant ["Vanity Project"]) (default-challenger)) (play-and-score state "Vanity Project") (is (= 4 (:agenda-point (get-contestant)))))) (deftest veterans-resource ;; Veterans Resource (testing "Veterans Resource basic test" (do-game (new-game (default-contestant [(qty "Hostile Takeover" 2) "Veterans Resource"]) (default-challenger)) (play-and-score state "Hostile Takeover") (play-and-score state "Hostile Takeover") (is (= 19 (:credit (get-contestant))) "Should gain 14 credits from 5 to 19") (is (= 2 (:bad-publicity (get-contestant))) "Should gain 2 bad publicity") (play-and-score state "Veterans Resource") (is (zero? (:bad-publicity (get-contestant))) "Should lose 2 bad publicity"))) (testing "Removes _up to 2_ bad publicity" (do-game (new-game (default-contestant ["Hostile Takeover" "Veterans Resource"]) (default-challenger)) (play-and-score state "Hostile Takeover") (is (= 12 (:credit (get-contestant))) "Should gain 7 credits from 5 to 12") (is (= 1 (:bad-publicity (get-contestant))) "Should gain 1 bad publicity") (play-and-score state "Veterans Resource") (is (zero? (:bad-publicity (get-contestant))) "Should lose 1 bad publicity")))) (deftest viral-weaponization ;; Viral Weaponization - at the end of turn scored, do 1 net damage for each card in grip (testing "Score on contestant turn" (do-game (new-game (default-contestant [(qty "Viral Weaponization" 2)]) (default-challenger [(qty "Sure Gamble" 3)])) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-and-score state "Viral Weaponization") (is (= 2 (count (:hand (get-challenger)))) "Challenger doesn't take damage when scored") (take-credits state :contestant) (is (zero? (count (:hand (get-challenger)))) "Challenger takes damage at end of turn") (core/click-draw state :challenger 1) (take-credits state :challenger) (take-credits state :contestant) (is (= 1 (count (:hand (get-challenger)))) "Challenger doesn't take damage in future turns") (play-from-hand state :challenger "Sure Gamble") (take-credits state :challenger) (is (zero? (count (:hand (get-challenger)))) "Challenger's hand is empty") (play-and-score state "Viral Weaponization") (take-credits state :contestant) (is (zero? (count (:hand (get-challenger)))) "Challenger's hand is empty"))) (testing "Score on challengers turn" (do-game (new-game (default-contestant ["Viral Weaponization" "Plan B"]) (default-challenger [(qty "Sure Gamble" 3)])) (starting-hand state :challenger ["Sure Gamble" "Sure Gamble"]) (play-from-hand state :contestant "Plan B" "New party") (core/add-prop state :contestant (get-content state :party1 0) :advance-counter 4) (take-credits state :contestant) (run-on state "Locale 1") (run-successful state) (prompt-choice :contestant "Yes") (prompt-select :contestant (find-card "Viral Weaponization" (:hand (get-contestant)))) (prompt-choice-partial :challenger "No") (is (= 2 (count (:hand (get-challenger)))) "Challenger doesn't take damage when scored") (take-credits state :challenger) (is (zero? (count (:hand (get-challenger)))) "Challenger takes damage at end of turn")))) (deftest voting-machine-initiative ;; Voting Machine Initiative (testing "Voting Machine Initiative" (do-game (new-game (default-contestant ["Voting Machine Initiative"]) (default-challenger)) (letfn [(vmi-test [vmi choice counter] (let [diff (if (= "Yes" choice) 1 0)] (is (= counter (get-counters (refresh vmi) :agenda))) (is (= 4 (:click (get-challenger)))) (prompt-choice :contestant choice) (is (= (- 4 diff) (:click (get-challenger)))) (is (= (- counter diff) (get-counters (refresh vmi) :agenda))) (take-credits state :challenger) (take-credits state :contestant)))] (play-and-score state "Voting Machine Initiative") (take-credits state :contestant) (let [vmi-scored (get-scored state :contestant 0)] (vmi-test vmi-scored "Yes" 3) (vmi-test vmi-scored "No" 2) (vmi-test vmi-scored "Yes" 2) (vmi-test vmi-scored "Yes" 1) (is (empty (:prompt (get-contestant))) "No prompt as there are no agenda counters left")))))) (deftest vulcan-coverup ;; Vulcan Coverup (do-game (new-game (default-contestant [(qty "Vulcan Coverup" 2)]) (default-challenger)) (play-from-hand state :contestant "Vulcan Coverup" "New party") (take-credits state :contestant) (run-empty-locale state :party1) (prompt-choice :challenger "Steal") (is (= 1 (:bad-publicity (get-contestant))) "Took 1 bad pub from stolen agenda") (take-credits state :challenger) (play-and-score state "Vulcan Coverup") (is (= 2 (count (:discard (get-challenger)))) "Did 2 meat damage upon scoring"))) (deftest water-monopoly ;; Water Monopoly (do-game (new-game (default-contestant ["Water Monopoly"]) (default-challenger ["Fan Site" "Levy Advanced Research Lab"])) (play-and-score state "Water Monopoly") (take-credits state :contestant) (is (= 5 (:credit (get-challenger))) "Challenger should start with 5 credits") (play-from-hand state :challenger "Fan Site") (is (= 5 (:credit (get-challenger))) "Shouldn't lose any credits") (play-from-hand state :challenger "Levy Advanced Research Lab") (is (zero? (:credit (get-challenger))) "Should cost an extra credit to play")))
[ { "context": " (:remote-addr req)\n \"81.43.193.199\") ;; Default IP, Spain\n ip (if (= ip \"127.", "end": 5110, "score": 0.9997122883796692, "start": 5097, "tag": "IP_ADDRESS", "value": "81.43.193.199" }, { "context": ".199\") ;; Default IP, Spain\n ip (if (= ip \"127.0.0.1\")\n \"81.43.193.199\"\n ip)\n ", "end": 5165, "score": 0.9992536902427673, "start": 5156, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "n\n ip (if (= ip \"127.0.0.1\")\n \"81.43.193.199\"\n ip)\n ;; ip \"5.28.16.121\"\n ", "end": 5195, "score": 0.9995526075363159, "start": 5182, "tag": "IP_ADDRESS", "value": "81.43.193.199" }, { "context": " \"81.43.193.199\"\n ip)\n ;; ip \"5.28.16.121\"\n tax-rate (ip->tax-rate ip)\n custo", "end": 5240, "score": 0.9077176451683044, "start": 5229, "tag": "IP_ADDRESS", "value": "5.28.16.121" } ]
src/instant_website/stripe.clj
instantwebsite/core-api
0
(ns instant-website.stripe (:require [clojure.pprint :refer [pprint] :rename {pprint pp}] [clojure.tools.logging :refer [log]] [clojure.core.memoize :refer [fifo]] ;; [org.httpkit.client :as http] [cheshire.core :refer [parse-string generate-string]] [paraman.core :refer [convert]] [iapetos.collector.fn :as fn] ;; [instant-website.config :refer [config]] [instant-website.metrics :as metrics])) (def stripe-url "https://api.stripe.com/v1") (def stripe-secret-key (:stripe-sk config)) (def available-plans [:free :pro]) (def free-plan :free) (def pro-plan :free) (defn create-url [path] (str (:frontend-host config) path)) (def urls {:checkout {:cancel-url (create-url "/pricing/cancel") :success-url (create-url "/pricing/success")} :portal {:return-url (create-url "/profile")}}) (def pro-price-id (:stripe-pro-price-id config)) ;; TODO should not create customer if already exists, throw exception ;; or reuse existing customer (defn create-customer! [user-id email] (log :debug (format "creating stripe customer for user %s with email %s" user-id email)) (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :form-params {:email email :metadata {:user-id user-id}}}] (-> @(http/post (str stripe-url "/customers") opts) :body (parse-string true)))) (defn checkout-session-params [tax-rate-id customer-id] ;; TODO ugly shortcut, fix proper. Only diff is the tax_rates (if (nil? tax-rate-id) (convert {:cancel_url (-> urls :checkout :cancel-url) :success_url (-> urls :checkout :success-url) :mode "subscription" :allow_promotion_codes true :customer customer-id :line_items [{:price (:stripe-pro-price-id config) :quantity 1}] :payment_method_types ["card"]}) (convert {:cancel_url (-> urls :checkout :cancel-url) :success_url (-> urls :checkout :success-url) :mode "subscription" :allow_promotion_codes true :customer customer-id :line_items [{:price (:stripe-pro-price-id config) :quantity 1 :tax_rates [tax-rate-id]}] :payment_method_types ["card"]}))) (def ipinfo-token (:ipinfo-token config)) (defn ip->country [ip] (-> @(http/get (str "http://ipinfo.io/" ip) {:insecure? true ;; TODO somehow, cert not valid for ipinfo... :user-agent "Instant-Website" :headers {"Accept" "application/json" "Authorization" (str "Bearer " ipinfo-token)}}) :body (parse-string true) :country)) (defn -stripe-tax-rates ([] (-stripe-tax-rates nil [])) ([last-id collected] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)}} starting-after (if last-id (str "&starting_after=" last-id) nil) res @(http/get (str stripe-url (if starting-after (str "/tax_rates?active=true&limit=1000" starting-after) "/tax_rates?active=true&limit=1000")) opts) body (:body res) parsed (parse-string body true) has-more? (:has_more parsed)] (if has-more? (-stripe-tax-rates (-> parsed :data last :id) (concat collected (:data parsed))) (concat collected (:data parsed)))))) (def stripe-tax-rates (fifo -stripe-tax-rates)) (defn ip->tax-rate [ip] (let [country-code (ip->country ip) tax-rate (some #(when (= (:jurisdiction %) country-code) %) (stripe-tax-rates))] tax-rate)) (defn stripe-create-checkout-session [ip-address customer-id] (let [params (checkout-session-params (-> ip-address ip->tax-rate :id) customer-id) opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :body params}] (println "[stripe-create-checkout-session]") (pp params) (-> @(http/post (str stripe-url "/checkout/sessions") opts) :body (parse-string true)))) (defn stripe-create-portal-session [customer-id] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :body (convert {:customer customer-id :return_url (-> urls :portal :return-url)})}] (-> @(http/post (str stripe-url "/billing_portal/sessions") opts) :body (parse-string true)))) (defn handle-create-session [req] (log :info "[handle-create-session]") (log :info (dissoc req :crux)) (let [ip (or (get-in req [:headers ":CF-Connecting-IP"]) (:remote-addr req) "81.43.193.199") ;; Default IP, Spain ip (if (= ip "127.0.0.1") "81.43.193.199" ip) ;; ip "5.28.16.121" tax-rate (ip->tax-rate ip) customer-id (-> req :identity :user :user/stripe-id)] {:status 201 :body (stripe-create-checkout-session ip customer-id)})) (fn/instrument! metrics/registry #'handle-create-session) (defn handle-create-portal-session [req] (let [customer-id (-> req :identity :user :user/stripe-id)] {:status 201 :body (stripe-create-portal-session customer-id)})) (fn/instrument! metrics/registry #'handle-create-portal-session) (defn stripe-events [] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :query-params {:limit 100}}] (-> @(http/get (str stripe-url "/events") opts) :body (parse-string true) :data)))
64691
(ns instant-website.stripe (:require [clojure.pprint :refer [pprint] :rename {pprint pp}] [clojure.tools.logging :refer [log]] [clojure.core.memoize :refer [fifo]] ;; [org.httpkit.client :as http] [cheshire.core :refer [parse-string generate-string]] [paraman.core :refer [convert]] [iapetos.collector.fn :as fn] ;; [instant-website.config :refer [config]] [instant-website.metrics :as metrics])) (def stripe-url "https://api.stripe.com/v1") (def stripe-secret-key (:stripe-sk config)) (def available-plans [:free :pro]) (def free-plan :free) (def pro-plan :free) (defn create-url [path] (str (:frontend-host config) path)) (def urls {:checkout {:cancel-url (create-url "/pricing/cancel") :success-url (create-url "/pricing/success")} :portal {:return-url (create-url "/profile")}}) (def pro-price-id (:stripe-pro-price-id config)) ;; TODO should not create customer if already exists, throw exception ;; or reuse existing customer (defn create-customer! [user-id email] (log :debug (format "creating stripe customer for user %s with email %s" user-id email)) (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :form-params {:email email :metadata {:user-id user-id}}}] (-> @(http/post (str stripe-url "/customers") opts) :body (parse-string true)))) (defn checkout-session-params [tax-rate-id customer-id] ;; TODO ugly shortcut, fix proper. Only diff is the tax_rates (if (nil? tax-rate-id) (convert {:cancel_url (-> urls :checkout :cancel-url) :success_url (-> urls :checkout :success-url) :mode "subscription" :allow_promotion_codes true :customer customer-id :line_items [{:price (:stripe-pro-price-id config) :quantity 1}] :payment_method_types ["card"]}) (convert {:cancel_url (-> urls :checkout :cancel-url) :success_url (-> urls :checkout :success-url) :mode "subscription" :allow_promotion_codes true :customer customer-id :line_items [{:price (:stripe-pro-price-id config) :quantity 1 :tax_rates [tax-rate-id]}] :payment_method_types ["card"]}))) (def ipinfo-token (:ipinfo-token config)) (defn ip->country [ip] (-> @(http/get (str "http://ipinfo.io/" ip) {:insecure? true ;; TODO somehow, cert not valid for ipinfo... :user-agent "Instant-Website" :headers {"Accept" "application/json" "Authorization" (str "Bearer " ipinfo-token)}}) :body (parse-string true) :country)) (defn -stripe-tax-rates ([] (-stripe-tax-rates nil [])) ([last-id collected] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)}} starting-after (if last-id (str "&starting_after=" last-id) nil) res @(http/get (str stripe-url (if starting-after (str "/tax_rates?active=true&limit=1000" starting-after) "/tax_rates?active=true&limit=1000")) opts) body (:body res) parsed (parse-string body true) has-more? (:has_more parsed)] (if has-more? (-stripe-tax-rates (-> parsed :data last :id) (concat collected (:data parsed))) (concat collected (:data parsed)))))) (def stripe-tax-rates (fifo -stripe-tax-rates)) (defn ip->tax-rate [ip] (let [country-code (ip->country ip) tax-rate (some #(when (= (:jurisdiction %) country-code) %) (stripe-tax-rates))] tax-rate)) (defn stripe-create-checkout-session [ip-address customer-id] (let [params (checkout-session-params (-> ip-address ip->tax-rate :id) customer-id) opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :body params}] (println "[stripe-create-checkout-session]") (pp params) (-> @(http/post (str stripe-url "/checkout/sessions") opts) :body (parse-string true)))) (defn stripe-create-portal-session [customer-id] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :body (convert {:customer customer-id :return_url (-> urls :portal :return-url)})}] (-> @(http/post (str stripe-url "/billing_portal/sessions") opts) :body (parse-string true)))) (defn handle-create-session [req] (log :info "[handle-create-session]") (log :info (dissoc req :crux)) (let [ip (or (get-in req [:headers ":CF-Connecting-IP"]) (:remote-addr req) "192.168.3.11") ;; Default IP, Spain ip (if (= ip "127.0.0.1") "192.168.3.11" ip) ;; ip "172.16.17.32" tax-rate (ip->tax-rate ip) customer-id (-> req :identity :user :user/stripe-id)] {:status 201 :body (stripe-create-checkout-session ip customer-id)})) (fn/instrument! metrics/registry #'handle-create-session) (defn handle-create-portal-session [req] (let [customer-id (-> req :identity :user :user/stripe-id)] {:status 201 :body (stripe-create-portal-session customer-id)})) (fn/instrument! metrics/registry #'handle-create-portal-session) (defn stripe-events [] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :query-params {:limit 100}}] (-> @(http/get (str stripe-url "/events") opts) :body (parse-string true) :data)))
true
(ns instant-website.stripe (:require [clojure.pprint :refer [pprint] :rename {pprint pp}] [clojure.tools.logging :refer [log]] [clojure.core.memoize :refer [fifo]] ;; [org.httpkit.client :as http] [cheshire.core :refer [parse-string generate-string]] [paraman.core :refer [convert]] [iapetos.collector.fn :as fn] ;; [instant-website.config :refer [config]] [instant-website.metrics :as metrics])) (def stripe-url "https://api.stripe.com/v1") (def stripe-secret-key (:stripe-sk config)) (def available-plans [:free :pro]) (def free-plan :free) (def pro-plan :free) (defn create-url [path] (str (:frontend-host config) path)) (def urls {:checkout {:cancel-url (create-url "/pricing/cancel") :success-url (create-url "/pricing/success")} :portal {:return-url (create-url "/profile")}}) (def pro-price-id (:stripe-pro-price-id config)) ;; TODO should not create customer if already exists, throw exception ;; or reuse existing customer (defn create-customer! [user-id email] (log :debug (format "creating stripe customer for user %s with email %s" user-id email)) (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :form-params {:email email :metadata {:user-id user-id}}}] (-> @(http/post (str stripe-url "/customers") opts) :body (parse-string true)))) (defn checkout-session-params [tax-rate-id customer-id] ;; TODO ugly shortcut, fix proper. Only diff is the tax_rates (if (nil? tax-rate-id) (convert {:cancel_url (-> urls :checkout :cancel-url) :success_url (-> urls :checkout :success-url) :mode "subscription" :allow_promotion_codes true :customer customer-id :line_items [{:price (:stripe-pro-price-id config) :quantity 1}] :payment_method_types ["card"]}) (convert {:cancel_url (-> urls :checkout :cancel-url) :success_url (-> urls :checkout :success-url) :mode "subscription" :allow_promotion_codes true :customer customer-id :line_items [{:price (:stripe-pro-price-id config) :quantity 1 :tax_rates [tax-rate-id]}] :payment_method_types ["card"]}))) (def ipinfo-token (:ipinfo-token config)) (defn ip->country [ip] (-> @(http/get (str "http://ipinfo.io/" ip) {:insecure? true ;; TODO somehow, cert not valid for ipinfo... :user-agent "Instant-Website" :headers {"Accept" "application/json" "Authorization" (str "Bearer " ipinfo-token)}}) :body (parse-string true) :country)) (defn -stripe-tax-rates ([] (-stripe-tax-rates nil [])) ([last-id collected] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)}} starting-after (if last-id (str "&starting_after=" last-id) nil) res @(http/get (str stripe-url (if starting-after (str "/tax_rates?active=true&limit=1000" starting-after) "/tax_rates?active=true&limit=1000")) opts) body (:body res) parsed (parse-string body true) has-more? (:has_more parsed)] (if has-more? (-stripe-tax-rates (-> parsed :data last :id) (concat collected (:data parsed))) (concat collected (:data parsed)))))) (def stripe-tax-rates (fifo -stripe-tax-rates)) (defn ip->tax-rate [ip] (let [country-code (ip->country ip) tax-rate (some #(when (= (:jurisdiction %) country-code) %) (stripe-tax-rates))] tax-rate)) (defn stripe-create-checkout-session [ip-address customer-id] (let [params (checkout-session-params (-> ip-address ip->tax-rate :id) customer-id) opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :body params}] (println "[stripe-create-checkout-session]") (pp params) (-> @(http/post (str stripe-url "/checkout/sessions") opts) :body (parse-string true)))) (defn stripe-create-portal-session [customer-id] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :body (convert {:customer customer-id :return_url (-> urls :portal :return-url)})}] (-> @(http/post (str stripe-url "/billing_portal/sessions") opts) :body (parse-string true)))) (defn handle-create-session [req] (log :info "[handle-create-session]") (log :info (dissoc req :crux)) (let [ip (or (get-in req [:headers ":CF-Connecting-IP"]) (:remote-addr req) "PI:IP_ADDRESS:192.168.3.11END_PI") ;; Default IP, Spain ip (if (= ip "127.0.0.1") "PI:IP_ADDRESS:192.168.3.11END_PI" ip) ;; ip "PI:IP_ADDRESS:172.16.17.32END_PI" tax-rate (ip->tax-rate ip) customer-id (-> req :identity :user :user/stripe-id)] {:status 201 :body (stripe-create-checkout-session ip customer-id)})) (fn/instrument! metrics/registry #'handle-create-session) (defn handle-create-portal-session [req] (let [customer-id (-> req :identity :user :user/stripe-id)] {:status 201 :body (stripe-create-portal-session customer-id)})) (fn/instrument! metrics/registry #'handle-create-portal-session) (defn stripe-events [] (let [opts {:headers {"Authorization" (str "Bearer " stripe-secret-key)} :query-params {:limit 100}}] (-> @(http/get (str stripe-url "/events") opts) :body (parse-string true) :data)))
[ { "context": "\n username \"guest\"\n password \"guest\"}}]\n (logging/info \"using rabbitmq api-endpoi", "end": 3063, "score": 0.9992074370384216, "start": 3058, "tag": "PASSWORD", "value": "guest" } ]
src/brainbot/nozzle/sys.clj
binarymind/es-nozzle
1
(ns brainbot.nozzle.sys "system map creation and a bit of iniconfig utils" (:require [brainbot.nozzle.worker :as worker] [brainbot.nozzle.rmqstate :as rmqstate] [brainbot.nozzle.misc :as misc] [brainbot.nozzle.inihelper :as inihelper] [brainbot.nozzle.async-helper :as async-helper] [brainbot.nozzle.meta-runner :as meta-runner]) (:require [clojure.tools.logging :as logging] [clj-logging-config.log4j :as log-config]) (:require [langohr.http :as rmqapi] [langohr.basic :as lb] [langohr.core :as rmq] [langohr.channel :as lch]) (:import [java.util.concurrent Executors])) (defn valid-name? "check if s is a valid-name, i.e. a non-empty sequence of the characters a-zA-Z0-9 - and _" [s] (boolean (re-matches #"^[-a-zA-Z0-9_]+$" s))) (defn- bool-from-config [s] (contains? #{"yes" "on" "1"} s)) (defn- parse-main-section* [iniconfig] {:rmq-settings (inihelper/rmq-settings-from-config iniconfig) :filesystems (misc/trimmed-lines-from-string (get-in iniconfig [inihelper/main-section-name "filesystems"])) :rmq-prefix (get-in iniconfig [inihelper/main-section-name "rmq-prefix"] inihelper/main-section-name) :generate-thumbnails? (bool-from-config (get-in iniconfig [inihelper/main-section-name "generate-thumbnails"] "no")) :es-url (or (get-in iniconfig [inihelper/main-section-name "es-url"]) "http://localhost:9200")}) (defn- inidie "call misc/die, put the section name and iniconfig source in front of the error message" [iniconfig section msg] (misc/die (format "while parsing section %s in %s: %s" section (-> iniconfig meta :source) msg))) (defn- make-die-fn "return fn wrapping misc/die, put the section name and iniconfig source in front of the error message" [iniconfig section] (partial inidie iniconfig section)) (defn- validate-filesystems "validate filesystem names. call die with an error message, if validation fails" [filesystems die] (doseq [fs filesystems] (when-not (valid-name? fs) (die (format "the filesystem name %s is not valid" (pr-str fs)))))) (defn- validate-main-section "validate main section" [{:keys [rmq-prefix filesystems]} die] (when-not (valid-name? rmq-prefix) (die (format "rmq-prefix value %s is not valid" (pr-str rmq-prefix)))) (validate-filesystems filesystems die)) (defn- parse-main-section "parse nozzle's main section. the result will be stored as :config inside the system map" [iniconfig] (let [res (parse-main-section* iniconfig) die (make-die-fn iniconfig inihelper/main-section-name)] (validate-main-section res die) res)) (defn http-connect! "initialize langohr.http by calling its connect! method" ([] (http-connect! {})) ([{:keys [api-endpoint username password] :or {api-endpoint "http://localhost:55672" username "guest" password "guest"}}] (logging/info "using rabbitmq api-endpoint" api-endpoint "as user" username) (rmqapi/connect! api-endpoint username password))) (defn make-system "create a system map. the system map is where we store our configuration data and some state. the system map contains the followings keys: :iniconfig the ini configuration :command-sections command sections as passed on the command line :config parsed values from the main section :thread-pool the thread pool which should be used by workers :name->obj an atom, mapping section names as specified in the ini config to the objects which we created." [iniconfig command-sections] (let [config (parse-main-section iniconfig)] (http-connect! config) ;; need to set this up for rmqstate/start-looping-qwatcher {:iniconfig iniconfig :command-sections command-sections :looping-qwatcher (rmqstate/start-looping-qwatcher (-> config :rmq-settings :vhost)) :config config :name->obj (atom {}) :thread-pool (Executors/newFixedThreadPool 256)})) (def ^{:doc "the system map currently running. only use this for development"} current-system nil) (defn run-system "start running the system by starting a meta-runner with the command-sections" [{:keys [iniconfig command-sections looping-qwatcher] :as system}] (alter-var-root #'current-system (constantly system)) (worker/start (meta-runner/make-meta-runner system command-sections)) (async-helper/looping-start looping-qwatcher)) (defn- get-filesystems-for-section* "get filesystems specified in section and validate them. no fallback" [system section-name] (let [filesystems (misc/trimmed-lines-from-string (get-in system [:iniconfig section-name "filesystems"])) die (make-die-fn (:iniconfig system) section-name)] (validate-filesystems filesystems die) filesystems)) (defn get-filesystems-for-section "get the list of filesystem names specified in the given section or as a fallback in the main section" [system section-name] (or (get-filesystems-for-section* system section-name) (get-in system [:config :filesystems]) (inidie (:iniconfig system) section-name "no filesystems defined")))
105293
(ns brainbot.nozzle.sys "system map creation and a bit of iniconfig utils" (:require [brainbot.nozzle.worker :as worker] [brainbot.nozzle.rmqstate :as rmqstate] [brainbot.nozzle.misc :as misc] [brainbot.nozzle.inihelper :as inihelper] [brainbot.nozzle.async-helper :as async-helper] [brainbot.nozzle.meta-runner :as meta-runner]) (:require [clojure.tools.logging :as logging] [clj-logging-config.log4j :as log-config]) (:require [langohr.http :as rmqapi] [langohr.basic :as lb] [langohr.core :as rmq] [langohr.channel :as lch]) (:import [java.util.concurrent Executors])) (defn valid-name? "check if s is a valid-name, i.e. a non-empty sequence of the characters a-zA-Z0-9 - and _" [s] (boolean (re-matches #"^[-a-zA-Z0-9_]+$" s))) (defn- bool-from-config [s] (contains? #{"yes" "on" "1"} s)) (defn- parse-main-section* [iniconfig] {:rmq-settings (inihelper/rmq-settings-from-config iniconfig) :filesystems (misc/trimmed-lines-from-string (get-in iniconfig [inihelper/main-section-name "filesystems"])) :rmq-prefix (get-in iniconfig [inihelper/main-section-name "rmq-prefix"] inihelper/main-section-name) :generate-thumbnails? (bool-from-config (get-in iniconfig [inihelper/main-section-name "generate-thumbnails"] "no")) :es-url (or (get-in iniconfig [inihelper/main-section-name "es-url"]) "http://localhost:9200")}) (defn- inidie "call misc/die, put the section name and iniconfig source in front of the error message" [iniconfig section msg] (misc/die (format "while parsing section %s in %s: %s" section (-> iniconfig meta :source) msg))) (defn- make-die-fn "return fn wrapping misc/die, put the section name and iniconfig source in front of the error message" [iniconfig section] (partial inidie iniconfig section)) (defn- validate-filesystems "validate filesystem names. call die with an error message, if validation fails" [filesystems die] (doseq [fs filesystems] (when-not (valid-name? fs) (die (format "the filesystem name %s is not valid" (pr-str fs)))))) (defn- validate-main-section "validate main section" [{:keys [rmq-prefix filesystems]} die] (when-not (valid-name? rmq-prefix) (die (format "rmq-prefix value %s is not valid" (pr-str rmq-prefix)))) (validate-filesystems filesystems die)) (defn- parse-main-section "parse nozzle's main section. the result will be stored as :config inside the system map" [iniconfig] (let [res (parse-main-section* iniconfig) die (make-die-fn iniconfig inihelper/main-section-name)] (validate-main-section res die) res)) (defn http-connect! "initialize langohr.http by calling its connect! method" ([] (http-connect! {})) ([{:keys [api-endpoint username password] :or {api-endpoint "http://localhost:55672" username "guest" password "<PASSWORD>"}}] (logging/info "using rabbitmq api-endpoint" api-endpoint "as user" username) (rmqapi/connect! api-endpoint username password))) (defn make-system "create a system map. the system map is where we store our configuration data and some state. the system map contains the followings keys: :iniconfig the ini configuration :command-sections command sections as passed on the command line :config parsed values from the main section :thread-pool the thread pool which should be used by workers :name->obj an atom, mapping section names as specified in the ini config to the objects which we created." [iniconfig command-sections] (let [config (parse-main-section iniconfig)] (http-connect! config) ;; need to set this up for rmqstate/start-looping-qwatcher {:iniconfig iniconfig :command-sections command-sections :looping-qwatcher (rmqstate/start-looping-qwatcher (-> config :rmq-settings :vhost)) :config config :name->obj (atom {}) :thread-pool (Executors/newFixedThreadPool 256)})) (def ^{:doc "the system map currently running. only use this for development"} current-system nil) (defn run-system "start running the system by starting a meta-runner with the command-sections" [{:keys [iniconfig command-sections looping-qwatcher] :as system}] (alter-var-root #'current-system (constantly system)) (worker/start (meta-runner/make-meta-runner system command-sections)) (async-helper/looping-start looping-qwatcher)) (defn- get-filesystems-for-section* "get filesystems specified in section and validate them. no fallback" [system section-name] (let [filesystems (misc/trimmed-lines-from-string (get-in system [:iniconfig section-name "filesystems"])) die (make-die-fn (:iniconfig system) section-name)] (validate-filesystems filesystems die) filesystems)) (defn get-filesystems-for-section "get the list of filesystem names specified in the given section or as a fallback in the main section" [system section-name] (or (get-filesystems-for-section* system section-name) (get-in system [:config :filesystems]) (inidie (:iniconfig system) section-name "no filesystems defined")))
true
(ns brainbot.nozzle.sys "system map creation and a bit of iniconfig utils" (:require [brainbot.nozzle.worker :as worker] [brainbot.nozzle.rmqstate :as rmqstate] [brainbot.nozzle.misc :as misc] [brainbot.nozzle.inihelper :as inihelper] [brainbot.nozzle.async-helper :as async-helper] [brainbot.nozzle.meta-runner :as meta-runner]) (:require [clojure.tools.logging :as logging] [clj-logging-config.log4j :as log-config]) (:require [langohr.http :as rmqapi] [langohr.basic :as lb] [langohr.core :as rmq] [langohr.channel :as lch]) (:import [java.util.concurrent Executors])) (defn valid-name? "check if s is a valid-name, i.e. a non-empty sequence of the characters a-zA-Z0-9 - and _" [s] (boolean (re-matches #"^[-a-zA-Z0-9_]+$" s))) (defn- bool-from-config [s] (contains? #{"yes" "on" "1"} s)) (defn- parse-main-section* [iniconfig] {:rmq-settings (inihelper/rmq-settings-from-config iniconfig) :filesystems (misc/trimmed-lines-from-string (get-in iniconfig [inihelper/main-section-name "filesystems"])) :rmq-prefix (get-in iniconfig [inihelper/main-section-name "rmq-prefix"] inihelper/main-section-name) :generate-thumbnails? (bool-from-config (get-in iniconfig [inihelper/main-section-name "generate-thumbnails"] "no")) :es-url (or (get-in iniconfig [inihelper/main-section-name "es-url"]) "http://localhost:9200")}) (defn- inidie "call misc/die, put the section name and iniconfig source in front of the error message" [iniconfig section msg] (misc/die (format "while parsing section %s in %s: %s" section (-> iniconfig meta :source) msg))) (defn- make-die-fn "return fn wrapping misc/die, put the section name and iniconfig source in front of the error message" [iniconfig section] (partial inidie iniconfig section)) (defn- validate-filesystems "validate filesystem names. call die with an error message, if validation fails" [filesystems die] (doseq [fs filesystems] (when-not (valid-name? fs) (die (format "the filesystem name %s is not valid" (pr-str fs)))))) (defn- validate-main-section "validate main section" [{:keys [rmq-prefix filesystems]} die] (when-not (valid-name? rmq-prefix) (die (format "rmq-prefix value %s is not valid" (pr-str rmq-prefix)))) (validate-filesystems filesystems die)) (defn- parse-main-section "parse nozzle's main section. the result will be stored as :config inside the system map" [iniconfig] (let [res (parse-main-section* iniconfig) die (make-die-fn iniconfig inihelper/main-section-name)] (validate-main-section res die) res)) (defn http-connect! "initialize langohr.http by calling its connect! method" ([] (http-connect! {})) ([{:keys [api-endpoint username password] :or {api-endpoint "http://localhost:55672" username "guest" password "PI:PASSWORD:<PASSWORD>END_PI"}}] (logging/info "using rabbitmq api-endpoint" api-endpoint "as user" username) (rmqapi/connect! api-endpoint username password))) (defn make-system "create a system map. the system map is where we store our configuration data and some state. the system map contains the followings keys: :iniconfig the ini configuration :command-sections command sections as passed on the command line :config parsed values from the main section :thread-pool the thread pool which should be used by workers :name->obj an atom, mapping section names as specified in the ini config to the objects which we created." [iniconfig command-sections] (let [config (parse-main-section iniconfig)] (http-connect! config) ;; need to set this up for rmqstate/start-looping-qwatcher {:iniconfig iniconfig :command-sections command-sections :looping-qwatcher (rmqstate/start-looping-qwatcher (-> config :rmq-settings :vhost)) :config config :name->obj (atom {}) :thread-pool (Executors/newFixedThreadPool 256)})) (def ^{:doc "the system map currently running. only use this for development"} current-system nil) (defn run-system "start running the system by starting a meta-runner with the command-sections" [{:keys [iniconfig command-sections looping-qwatcher] :as system}] (alter-var-root #'current-system (constantly system)) (worker/start (meta-runner/make-meta-runner system command-sections)) (async-helper/looping-start looping-qwatcher)) (defn- get-filesystems-for-section* "get filesystems specified in section and validate them. no fallback" [system section-name] (let [filesystems (misc/trimmed-lines-from-string (get-in system [:iniconfig section-name "filesystems"])) die (make-die-fn (:iniconfig system) section-name)] (validate-filesystems filesystems die) filesystems)) (defn get-filesystems-for-section "get the list of filesystem names specified in the given section or as a fallback in the main section" [system section-name] (or (get-filesystems-for-section* system section-name) (get-in system [:config :filesystems]) (inidie (:iniconfig system) section-name "no filesystems defined")))
[ { "context": "ext-field {:required true :size 32 :class \"fld\"} \"username\")]]\n\n [:tr\n [:td {:class \"lbl\"} (f/label", "end": 843, "score": 0.9991322159767151, "start": 835, "tag": "USERNAME", "value": "username" }, { "context": "ord-field {:required true :size 32 :class \"fld\"} \"password\")]]\n\n [:tr [:td {:style \"text-align:center\" :", "end": 1012, "score": 0.9942229986190796, "start": 1004, "tag": "PASSWORD", "value": "password" } ]
src/certo/views/login.clj
bmds-researchsoftware/certo
1
(ns certo.views.login (:require [clojure.string :as str] [hiccup.core :as h] [hiccup.form :as f] [ring.util.anti-forgery :as af] [certo.views.common :as common])) (defn login [title] (common/page title [:br] [:br] [:div {:class "ct"} (common/format-title title)] (f/form-to {:id "login-form"} [:post "login"] (af/anti-forgery-field) [:table {:class "login"} [:tr [:td {:class "lnk" :style "text-align:left;" } [:a {:href "/"} "Home"]] [:td {:class "lnk" :style "text-align:right"} [:a {:href "/help.html"} "Help"]]] [:tr [:th {:style "text-align:center" :colspan "2"} (str/capitalize "Login")]] [:tr [:td {:class "lbl"} (f/label name "Username:")] [:td {:class "fld"} (f/text-field {:required true :size 32 :class "fld"} "username")]] [:tr [:td {:class "lbl"} (f/label name "Password:")] [:td {:class "fld"} (f/password-field {:required true :size 32 :class "fld"} "password")]] [:tr [:td {:style "text-align:center" :colspan "2"} (f/submit-button {:form "login-form"} "Login")]]])))
101114
(ns certo.views.login (:require [clojure.string :as str] [hiccup.core :as h] [hiccup.form :as f] [ring.util.anti-forgery :as af] [certo.views.common :as common])) (defn login [title] (common/page title [:br] [:br] [:div {:class "ct"} (common/format-title title)] (f/form-to {:id "login-form"} [:post "login"] (af/anti-forgery-field) [:table {:class "login"} [:tr [:td {:class "lnk" :style "text-align:left;" } [:a {:href "/"} "Home"]] [:td {:class "lnk" :style "text-align:right"} [:a {:href "/help.html"} "Help"]]] [:tr [:th {:style "text-align:center" :colspan "2"} (str/capitalize "Login")]] [:tr [:td {:class "lbl"} (f/label name "Username:")] [:td {:class "fld"} (f/text-field {:required true :size 32 :class "fld"} "username")]] [:tr [:td {:class "lbl"} (f/label name "Password:")] [:td {:class "fld"} (f/password-field {:required true :size 32 :class "fld"} "<PASSWORD>")]] [:tr [:td {:style "text-align:center" :colspan "2"} (f/submit-button {:form "login-form"} "Login")]]])))
true
(ns certo.views.login (:require [clojure.string :as str] [hiccup.core :as h] [hiccup.form :as f] [ring.util.anti-forgery :as af] [certo.views.common :as common])) (defn login [title] (common/page title [:br] [:br] [:div {:class "ct"} (common/format-title title)] (f/form-to {:id "login-form"} [:post "login"] (af/anti-forgery-field) [:table {:class "login"} [:tr [:td {:class "lnk" :style "text-align:left;" } [:a {:href "/"} "Home"]] [:td {:class "lnk" :style "text-align:right"} [:a {:href "/help.html"} "Help"]]] [:tr [:th {:style "text-align:center" :colspan "2"} (str/capitalize "Login")]] [:tr [:td {:class "lbl"} (f/label name "Username:")] [:td {:class "fld"} (f/text-field {:required true :size 32 :class "fld"} "username")]] [:tr [:td {:class "lbl"} (f/label name "Password:")] [:td {:class "fld"} (f/password-field {:required true :size 32 :class "fld"} "PI:PASSWORD:<PASSWORD>END_PI")]] [:tr [:td {:style "text-align:center" :colspan "2"} (f/submit-button {:form "login-form"} "Login")]]])))
[ { "context": ";; Copyright (c) Andrew A. Raines\n;;\n;; Permission is hereby granted, free of charg", "end": 33, "score": 0.9998772740364075, "start": 17, "tag": "NAME", "value": "Andrew A. Raines" } ]
src/postal/sendmail.clj
poenneby/postal
371
;; Copyright (c) Andrew A. Raines ;; ;; 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 postal.sendmail (:use [postal.message :only [message->str sender recipients]])) (def sendmails ["/usr/lib/sendmail" "/usr/sbin/sendmail" "/usr/bin/sendmail" "/usr/local/lib/sendmail" "/usr/local/sbin/sendmail" "/usr/local/bin/sendmail" "/usr/sbin/msmtp"]) (def errors {0 [:SUCCESS "message sent"] 64 [:EX_USAGE "command line usage error"] 65 [:EX_DATAERR "data format error"] 66 [:EX_NOINPUT "cannot open input"] 67 [:EX_NOUSER "addressee unknown"] 68 [:EX_NOHOST "host name unknown"] 69 [:EX_UNAVAILABLE "service unavailable"] 70 [:EX_SOFTWARE "internal software error"] 71 [:EX_OSERR "system error (no fork?)"] 72 [:EX_OSFILE "critical OS file missing"] 73 [:EX_CANTCREAT "can't create (user) output file"] 74 [:EX_IOERR "input/output error"] 75 [:EX_TEMPFAIL "temp failure; user is invited to retry"] 76 [:EX_PROTOCOL "remote error in protocol"] 77 [:EX_NOPERM "permission denied"] 78 [:EX_CONFIG "configuration error"]}) (defn error [code] (let [[e message] (errors code)] {:code code :error e :message message})) (defn find-sendmail [] (if-let [SENDMAIL (System/getenv "SENDMAIL")] SENDMAIL (first (filter #(.isFile (java.io.File. ^String %)) sendmails)))) (defn sanitize [^String text] (.replaceAll text "\r\n" (System/getProperty "line.separator"))) (defn sendmail-send ([msg] (sendmail-send msg (find-sendmail))) ([msg sendmail] (let [mail (sanitize (message->str msg)) cmd (concat [sendmail "-f" (sender msg)] (recipients msg)) pb (ProcessBuilder. ^java.util.List cmd) p (.start pb) smtp (java.io.PrintStream. (.getOutputStream p))] (.print smtp mail) (.close smtp) (.waitFor p) (error (.exitValue p)))))
47722
;; Copyright (c) <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 postal.sendmail (:use [postal.message :only [message->str sender recipients]])) (def sendmails ["/usr/lib/sendmail" "/usr/sbin/sendmail" "/usr/bin/sendmail" "/usr/local/lib/sendmail" "/usr/local/sbin/sendmail" "/usr/local/bin/sendmail" "/usr/sbin/msmtp"]) (def errors {0 [:SUCCESS "message sent"] 64 [:EX_USAGE "command line usage error"] 65 [:EX_DATAERR "data format error"] 66 [:EX_NOINPUT "cannot open input"] 67 [:EX_NOUSER "addressee unknown"] 68 [:EX_NOHOST "host name unknown"] 69 [:EX_UNAVAILABLE "service unavailable"] 70 [:EX_SOFTWARE "internal software error"] 71 [:EX_OSERR "system error (no fork?)"] 72 [:EX_OSFILE "critical OS file missing"] 73 [:EX_CANTCREAT "can't create (user) output file"] 74 [:EX_IOERR "input/output error"] 75 [:EX_TEMPFAIL "temp failure; user is invited to retry"] 76 [:EX_PROTOCOL "remote error in protocol"] 77 [:EX_NOPERM "permission denied"] 78 [:EX_CONFIG "configuration error"]}) (defn error [code] (let [[e message] (errors code)] {:code code :error e :message message})) (defn find-sendmail [] (if-let [SENDMAIL (System/getenv "SENDMAIL")] SENDMAIL (first (filter #(.isFile (java.io.File. ^String %)) sendmails)))) (defn sanitize [^String text] (.replaceAll text "\r\n" (System/getProperty "line.separator"))) (defn sendmail-send ([msg] (sendmail-send msg (find-sendmail))) ([msg sendmail] (let [mail (sanitize (message->str msg)) cmd (concat [sendmail "-f" (sender msg)] (recipients msg)) pb (ProcessBuilder. ^java.util.List cmd) p (.start pb) smtp (java.io.PrintStream. (.getOutputStream p))] (.print smtp mail) (.close smtp) (.waitFor p) (error (.exitValue p)))))
true
;; Copyright (c) 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 postal.sendmail (:use [postal.message :only [message->str sender recipients]])) (def sendmails ["/usr/lib/sendmail" "/usr/sbin/sendmail" "/usr/bin/sendmail" "/usr/local/lib/sendmail" "/usr/local/sbin/sendmail" "/usr/local/bin/sendmail" "/usr/sbin/msmtp"]) (def errors {0 [:SUCCESS "message sent"] 64 [:EX_USAGE "command line usage error"] 65 [:EX_DATAERR "data format error"] 66 [:EX_NOINPUT "cannot open input"] 67 [:EX_NOUSER "addressee unknown"] 68 [:EX_NOHOST "host name unknown"] 69 [:EX_UNAVAILABLE "service unavailable"] 70 [:EX_SOFTWARE "internal software error"] 71 [:EX_OSERR "system error (no fork?)"] 72 [:EX_OSFILE "critical OS file missing"] 73 [:EX_CANTCREAT "can't create (user) output file"] 74 [:EX_IOERR "input/output error"] 75 [:EX_TEMPFAIL "temp failure; user is invited to retry"] 76 [:EX_PROTOCOL "remote error in protocol"] 77 [:EX_NOPERM "permission denied"] 78 [:EX_CONFIG "configuration error"]}) (defn error [code] (let [[e message] (errors code)] {:code code :error e :message message})) (defn find-sendmail [] (if-let [SENDMAIL (System/getenv "SENDMAIL")] SENDMAIL (first (filter #(.isFile (java.io.File. ^String %)) sendmails)))) (defn sanitize [^String text] (.replaceAll text "\r\n" (System/getProperty "line.separator"))) (defn sendmail-send ([msg] (sendmail-send msg (find-sendmail))) ([msg sendmail] (let [mail (sanitize (message->str msg)) cmd (concat [sendmail "-f" (sender msg)] (recipients msg)) pb (ProcessBuilder. ^java.util.List cmd) p (.start pb) smtp (java.io.PrintStream. (.getOutputStream p))] (.print smtp mail) (.close smtp) (.waitFor p) (error (.exitValue p)))))
[ { "context": "minal :new))\n(def police (send-to Police :new \"Biggles\"))\n(send-to criminal :taunt police)\n\n(load-file \"", "end": 1457, "score": 0.7619592547416687, "start": 1453, "tag": "NAME", "value": "gles" } ]
func-prog/fp-oo/test/solutions/ts_message_class.clj
tannerwelsh/code-training
0
(ns solutions.ts-message-class (:use midje.sweet)) (load-file "sources/consolidation.clj") (load-file "solutions/pieces/message-class-1.clj") (load-file "test/solutions/ruby-complete.clj") (load-file "sources/message-class-exercises.clj") (fact (let [snooper (send-to Snooper :new)] (send-to snooper :snoop "an arg") => [:snoop 'Snooper ["an arg"] snooper])) (load-file "solutions/pieces/message-class-2.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [snooper (send-to SubSnooper :new)] (activate-method (send-to snooper :snoop "an arg")) => [:snoop 'Snooper ["an arg"] snooper] (send-to snooper :fail-dramatically) => (throws Error) (send-to snooper :to-string) => "Look! {:__left_symbol__ SubSnooper}")) (load-file "solutions/pieces/message-class-3.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [snooper (send-to Snooper :new)] (send-to snooper :snoop "an arg") => [:snoop 'Snooper ["an arg"] snooper])) (fact (let [snooper (send-to SubSnooper :new)] (activate-method (send-to snooper :snoop "an arg")) => [:snoop 'Snooper ["an arg"] snooper] (send-to snooper :fail-dramatically) => (throws Error) (send-to snooper :to-string) => "Look! {:__left_symbol__ SubSnooper}")) (load-file "solutions/pieces/message-class-4.clj") (load-file "test/solutions/ruby-complete.clj") (def criminal (send-to Criminal :new)) (def police (send-to Police :new "Biggles")) (send-to criminal :taunt police) (load-file "solutions/pieces/message-class-5.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [traceful (send-to (send-to Bottom :new "one") :chained-message 1) one (send-to Bottom :new "one") two (send-to Bottom :new "two") trace (send-to traceful :trace)] (nth trace 0) => {:target one, :name :chained-message, :args [1] :holder-name 'Bottom, :super-count 0} (nth trace 1) => {:target two, :name :secondary-message, :args [10] :holder-name 'Bottom, :super-count 0} (nth trace 2) => {:target two, :name :secondary-message, :args [10] :holder-name 'Middle, :super-count 1} (nth trace 3) => {:target two, :name :secondary-message, :args [100] :holder-name 'Top, :super-count 2} (nth trace 4) => {:target two, :name :tertiary-message, :args [1000] :holder-name 'Middle, :super-count 0} (nth trace 5) => {:target two, :name :tertiary-message, :args [10000] :holder-name 'Top, :super-count 1} ;; Just check that this doesn't blow up. (friendly-trace trace)))
70643
(ns solutions.ts-message-class (:use midje.sweet)) (load-file "sources/consolidation.clj") (load-file "solutions/pieces/message-class-1.clj") (load-file "test/solutions/ruby-complete.clj") (load-file "sources/message-class-exercises.clj") (fact (let [snooper (send-to Snooper :new)] (send-to snooper :snoop "an arg") => [:snoop 'Snooper ["an arg"] snooper])) (load-file "solutions/pieces/message-class-2.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [snooper (send-to SubSnooper :new)] (activate-method (send-to snooper :snoop "an arg")) => [:snoop 'Snooper ["an arg"] snooper] (send-to snooper :fail-dramatically) => (throws Error) (send-to snooper :to-string) => "Look! {:__left_symbol__ SubSnooper}")) (load-file "solutions/pieces/message-class-3.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [snooper (send-to Snooper :new)] (send-to snooper :snoop "an arg") => [:snoop 'Snooper ["an arg"] snooper])) (fact (let [snooper (send-to SubSnooper :new)] (activate-method (send-to snooper :snoop "an arg")) => [:snoop 'Snooper ["an arg"] snooper] (send-to snooper :fail-dramatically) => (throws Error) (send-to snooper :to-string) => "Look! {:__left_symbol__ SubSnooper}")) (load-file "solutions/pieces/message-class-4.clj") (load-file "test/solutions/ruby-complete.clj") (def criminal (send-to Criminal :new)) (def police (send-to Police :new "Big<NAME>")) (send-to criminal :taunt police) (load-file "solutions/pieces/message-class-5.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [traceful (send-to (send-to Bottom :new "one") :chained-message 1) one (send-to Bottom :new "one") two (send-to Bottom :new "two") trace (send-to traceful :trace)] (nth trace 0) => {:target one, :name :chained-message, :args [1] :holder-name 'Bottom, :super-count 0} (nth trace 1) => {:target two, :name :secondary-message, :args [10] :holder-name 'Bottom, :super-count 0} (nth trace 2) => {:target two, :name :secondary-message, :args [10] :holder-name 'Middle, :super-count 1} (nth trace 3) => {:target two, :name :secondary-message, :args [100] :holder-name 'Top, :super-count 2} (nth trace 4) => {:target two, :name :tertiary-message, :args [1000] :holder-name 'Middle, :super-count 0} (nth trace 5) => {:target two, :name :tertiary-message, :args [10000] :holder-name 'Top, :super-count 1} ;; Just check that this doesn't blow up. (friendly-trace trace)))
true
(ns solutions.ts-message-class (:use midje.sweet)) (load-file "sources/consolidation.clj") (load-file "solutions/pieces/message-class-1.clj") (load-file "test/solutions/ruby-complete.clj") (load-file "sources/message-class-exercises.clj") (fact (let [snooper (send-to Snooper :new)] (send-to snooper :snoop "an arg") => [:snoop 'Snooper ["an arg"] snooper])) (load-file "solutions/pieces/message-class-2.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [snooper (send-to SubSnooper :new)] (activate-method (send-to snooper :snoop "an arg")) => [:snoop 'Snooper ["an arg"] snooper] (send-to snooper :fail-dramatically) => (throws Error) (send-to snooper :to-string) => "Look! {:__left_symbol__ SubSnooper}")) (load-file "solutions/pieces/message-class-3.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [snooper (send-to Snooper :new)] (send-to snooper :snoop "an arg") => [:snoop 'Snooper ["an arg"] snooper])) (fact (let [snooper (send-to SubSnooper :new)] (activate-method (send-to snooper :snoop "an arg")) => [:snoop 'Snooper ["an arg"] snooper] (send-to snooper :fail-dramatically) => (throws Error) (send-to snooper :to-string) => "Look! {:__left_symbol__ SubSnooper}")) (load-file "solutions/pieces/message-class-4.clj") (load-file "test/solutions/ruby-complete.clj") (def criminal (send-to Criminal :new)) (def police (send-to Police :new "BigPI:NAME:<NAME>END_PI")) (send-to criminal :taunt police) (load-file "solutions/pieces/message-class-5.clj") (load-file "test/solutions/ruby-complete.clj") (fact (let [traceful (send-to (send-to Bottom :new "one") :chained-message 1) one (send-to Bottom :new "one") two (send-to Bottom :new "two") trace (send-to traceful :trace)] (nth trace 0) => {:target one, :name :chained-message, :args [1] :holder-name 'Bottom, :super-count 0} (nth trace 1) => {:target two, :name :secondary-message, :args [10] :holder-name 'Bottom, :super-count 0} (nth trace 2) => {:target two, :name :secondary-message, :args [10] :holder-name 'Middle, :super-count 1} (nth trace 3) => {:target two, :name :secondary-message, :args [100] :holder-name 'Top, :super-count 2} (nth trace 4) => {:target two, :name :tertiary-message, :args [1000] :holder-name 'Middle, :super-count 0} (nth trace 5) => {:target two, :name :tertiary-message, :args [10000] :holder-name 'Top, :super-count 1} ;; Just check that this doesn't blow up. (friendly-trace trace)))
[ { "context": "ltiValued true\n :termVectors true}\n\n {:name \"director\",\n :type \"text_lowcased\",\n :indexed true,\n ", "end": 9060, "score": 0.620918869972229, "start": 9052, "tag": "NAME", "value": "director" }, { "context": " :stored true\n :termVectors true}\n\n {:name \"producers\",\n :type \"text_lowcased\",\n :indexed t", "end": 9164, "score": 0.5319293737411499, "start": 9161, "tag": "USERNAME", "value": "pro" } ]
src/clj/corona_demo/data.clj
Stylitics/corona-demo
3
(ns corona-demo.data (:require [clojure.data.json :as json] [corona-demo.utils :as utils])) ;;; Movies (def data-dir (str (System/getProperty "user.dir") "/resources/solr/tmdb/data/")) (def csv-dir (str data-dir "csv/")) (def movies-file "tmdb_5000_movies.csv") (def credits-file "tmdb_5000_credits.csv") (def links-file "links.csv") (def ratings-file "ratings.csv") (def users-file "users.csv") (def movies-fields-val-fns {:genres (utils/mapv-json-vals "name") :keywords (utils/mapv-json-vals "name") :spoken_languages (utils/mapv-json-vals "iso_639_1") :production_companies (utils/mapv-json-vals "name") :production_countries (utils/mapv-json-vals "iso_3166_1")}) (def movies* (utils/read-csv (str csv-dir movies-file) {:key-fn keyword :val-fns movies-fields-val-fns})) (defonce links (utils/read-csv (str csv-dir links-file) {:key-fn keyword :val-fns {:movieId #(Long/parseLong %)}})) #_(take 10 links) (def credits-raw-maps (utils/read-csv (str csv-dir credits-file) {:key-fn keyword})) (defn parse-credit-raw-map [{:keys [movie_id cast crew] :as row}] (let [crew-data (json/read-str crew)] {:db_id (:movie_id row) :cast ((utils/mapv-json-vals "name") cast) :director (-> (filter #(= "Director" (get % "job")) crew-data) first (get "name")) :producers (->> crew-data (filter #(= "Producer" (get % "job"))) (mapv #(get % "name")))})) (defonce credits (map parse-credit-raw-map credits-raw-maps)) (defn tmdb_id->credits [db_id] (-> (first (filter #(= db_id (:movie_id %)) credits)) (dissoc :db_id))) (defn tmdb_id->movie-lens-id [db_id] (:movieId (first (filter #(= db_id (:tmdbId %)) links)))) (defonce movies (mapv (fn [{:keys [db_id] :as m}] (-> m (assoc :movie_lens_id (tmdb_id->movie-lens-id db_id)) (merge (tmdb_id->credits db_id)))) movies*)) #_(count movies) #_(first movies) #_(count (filter :movie_lens_id movies)) #_(db_id->movieId "862") (defn read-ratings [] (utils/read-csv (str csv-dir ratings-file) {:key-fn keyword :val-fns {:userId (fn [id] (Long/parseLong id)) :movieId (fn [id] (Long/parseLong id)) :rating (fn [f] (Float/parseFloat f))}})) (defonce ratings (read-ratings)) #_(first ratings) (defn make-rated-movies-ids-set [ratings] (set (map :movieId ratings))) (def rated-movie-ids (make-rated-movies-ids-set ratings)) (def rated-movies (filter #(contains? rated-movie-ids (:movie_lens_id %)) movies)) #_(count rated-movies) (defn read-users "Parse user records from 'users-csv-resource-name' resource (.csv format)" [] (let [parse-num (fn [v] (Float/parseFloat v)) db-fields [:userId :gender :age :occupation :zip] users-fields-fns {:userId (fn [id] (Long/parseLong id)) :gender (fn [g] (case g "F" 0.0 "M" 1.0)) :age (fn [v] (when-not (= v "1") (Float/parseFloat v))) :occupation (fn [v] (Float/parseFloat v))} entries (utils/read-csv (str csv-dir users-file) {:key-fn keyword :val-fns users-fields-fns})] (filter :age entries))) #_(take 3 (read-users)) #_(count (read-users)) (def schema-type-text_en_splitting "A text field with defaults appropriate for English, plus aggressive word-splitting and autophrase features enabled. This field is just like text_en, except it adds WordDelimiterGraphFilter to enable splitting and matching of words on case-change, alpha numeric boundaries, and non-alphanumeric chars. This means certain compound word cases will work, for example query \"wi fi\" will match document \"WiFi\" or \"wi-fi\". " {:name "text_en_splitting" :class "solr.TextField" :positionIncrementGap "100" :autoGeneratePhraseQueries "true" :indexAnalyzer {:tokenizer {:class "solr.WhitespaceTokenizerFactory"} :filters [ ;; Removes stop words {:class "solr.StopFilterFactory" :words "lang/stopwords_en.txt" ;added :ignoreCase "true"} ;; Splits and matches words on case-change, ;; alpha numeric boundaries, and ;; non-alphanumeric chars ;; 'wi fi' = 'WiFi' = 'wi-fi' {:class "solr.WordDelimiterGraphFilterFactory" :generateWordParts "1" :generateNumberParts "1" :catenateWords "1" :catenateNumbers "1" :catenateAll "0" :splitOnCaseChange "1"} ;; Lowercases content {:class "solr.LowerCaseFilterFactory"} ;; Protects some words from being stemmed {:class "solr.KeywordMarkerFilterFactory" :protected "protwords.txt"} ;; Applies the Porter Stemming Algorithm for English ;; "jump" "jumping" "jumped" => "jump" "jump" "jump" {:class "solr.PorterStemFilterFactory"} ;; Needed for synonyms {:class "solr.FlattenGraphFilterFactory"}]} :queryAnalyzer {:type "query" :tokenizer {:class "solr.WhitespaceTokenizerFactory"} :filters [ ;; Adds up in synonyms at query time {:class "solr.SynonymGraphFilterFactory" :synonyms "synonyms.txt" ;added :ignoreCase "true" :expand "true"} {:class "solr.StopFilterFactory" :words "lang/stopwords_en.txt" ;added :ignoreCase "true"} {:class "solr.WordDelimiterGraphFilterFactory" :generateWordParts "1" :generateNumberParts "1" :catenateWords "1" :catenateNumbers "1" :catenateAll "0" :splitOnCaseChange "1"} {:class "solr.LowerCaseFilterFactory"} {:class "solr.KeywordMarkerFilterFactory" :protected "protwords.txt" ;added } {:class "solr.PorterStemFilterFactory"} ]}}) (def basic-fields "You can find your basic schema types here: resources/solr/tmdb/conf/managedschema" [{:name "_text_", :type "text_en_splitting", :multiValued true, :indexed true, :stored false} {:name "_version_", ; version of document, query per version :type "plong", :indexed true, :stored true} {:name "db_id", :type "string", :multiValued false, :indexed true, :required true, :stored true}]) (def content-fields [{:name "tagline", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "overview", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "genres", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "title", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "keywords", :type "text_en_splitting", :indexed true, :stored true :multiValued true :termVectors true} {:name "original_title", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "production_companies", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "production_countries", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "spoken_languages", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "original_language", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "status", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "homepage", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "cast", :type "text_lowcased", :indexed true, :stored true :multiValued true :termVectors true} {:name "director", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "producers", :type "text_lowcased", :indexed true, :stored true :multiValued true :termVectors true}]) (def number-fields [{:name "release_date", :type "pdate", :indexed true, :stored true} {:name "budget", :type "plong", :indexed true, :stored true} {:name "revenue", :type "plong", :indexed true, :stored true} {:name "vote_count", :type "plongs"} {:name "popularity", :type "pfloat", :indexed true, :stored true} {:name "runtime", :type "pfloat", :indexed true, :stored true} {:name "vote_average", :type "pfloat", :indexed true, :stored true}])
88826
(ns corona-demo.data (:require [clojure.data.json :as json] [corona-demo.utils :as utils])) ;;; Movies (def data-dir (str (System/getProperty "user.dir") "/resources/solr/tmdb/data/")) (def csv-dir (str data-dir "csv/")) (def movies-file "tmdb_5000_movies.csv") (def credits-file "tmdb_5000_credits.csv") (def links-file "links.csv") (def ratings-file "ratings.csv") (def users-file "users.csv") (def movies-fields-val-fns {:genres (utils/mapv-json-vals "name") :keywords (utils/mapv-json-vals "name") :spoken_languages (utils/mapv-json-vals "iso_639_1") :production_companies (utils/mapv-json-vals "name") :production_countries (utils/mapv-json-vals "iso_3166_1")}) (def movies* (utils/read-csv (str csv-dir movies-file) {:key-fn keyword :val-fns movies-fields-val-fns})) (defonce links (utils/read-csv (str csv-dir links-file) {:key-fn keyword :val-fns {:movieId #(Long/parseLong %)}})) #_(take 10 links) (def credits-raw-maps (utils/read-csv (str csv-dir credits-file) {:key-fn keyword})) (defn parse-credit-raw-map [{:keys [movie_id cast crew] :as row}] (let [crew-data (json/read-str crew)] {:db_id (:movie_id row) :cast ((utils/mapv-json-vals "name") cast) :director (-> (filter #(= "Director" (get % "job")) crew-data) first (get "name")) :producers (->> crew-data (filter #(= "Producer" (get % "job"))) (mapv #(get % "name")))})) (defonce credits (map parse-credit-raw-map credits-raw-maps)) (defn tmdb_id->credits [db_id] (-> (first (filter #(= db_id (:movie_id %)) credits)) (dissoc :db_id))) (defn tmdb_id->movie-lens-id [db_id] (:movieId (first (filter #(= db_id (:tmdbId %)) links)))) (defonce movies (mapv (fn [{:keys [db_id] :as m}] (-> m (assoc :movie_lens_id (tmdb_id->movie-lens-id db_id)) (merge (tmdb_id->credits db_id)))) movies*)) #_(count movies) #_(first movies) #_(count (filter :movie_lens_id movies)) #_(db_id->movieId "862") (defn read-ratings [] (utils/read-csv (str csv-dir ratings-file) {:key-fn keyword :val-fns {:userId (fn [id] (Long/parseLong id)) :movieId (fn [id] (Long/parseLong id)) :rating (fn [f] (Float/parseFloat f))}})) (defonce ratings (read-ratings)) #_(first ratings) (defn make-rated-movies-ids-set [ratings] (set (map :movieId ratings))) (def rated-movie-ids (make-rated-movies-ids-set ratings)) (def rated-movies (filter #(contains? rated-movie-ids (:movie_lens_id %)) movies)) #_(count rated-movies) (defn read-users "Parse user records from 'users-csv-resource-name' resource (.csv format)" [] (let [parse-num (fn [v] (Float/parseFloat v)) db-fields [:userId :gender :age :occupation :zip] users-fields-fns {:userId (fn [id] (Long/parseLong id)) :gender (fn [g] (case g "F" 0.0 "M" 1.0)) :age (fn [v] (when-not (= v "1") (Float/parseFloat v))) :occupation (fn [v] (Float/parseFloat v))} entries (utils/read-csv (str csv-dir users-file) {:key-fn keyword :val-fns users-fields-fns})] (filter :age entries))) #_(take 3 (read-users)) #_(count (read-users)) (def schema-type-text_en_splitting "A text field with defaults appropriate for English, plus aggressive word-splitting and autophrase features enabled. This field is just like text_en, except it adds WordDelimiterGraphFilter to enable splitting and matching of words on case-change, alpha numeric boundaries, and non-alphanumeric chars. This means certain compound word cases will work, for example query \"wi fi\" will match document \"WiFi\" or \"wi-fi\". " {:name "text_en_splitting" :class "solr.TextField" :positionIncrementGap "100" :autoGeneratePhraseQueries "true" :indexAnalyzer {:tokenizer {:class "solr.WhitespaceTokenizerFactory"} :filters [ ;; Removes stop words {:class "solr.StopFilterFactory" :words "lang/stopwords_en.txt" ;added :ignoreCase "true"} ;; Splits and matches words on case-change, ;; alpha numeric boundaries, and ;; non-alphanumeric chars ;; 'wi fi' = 'WiFi' = 'wi-fi' {:class "solr.WordDelimiterGraphFilterFactory" :generateWordParts "1" :generateNumberParts "1" :catenateWords "1" :catenateNumbers "1" :catenateAll "0" :splitOnCaseChange "1"} ;; Lowercases content {:class "solr.LowerCaseFilterFactory"} ;; Protects some words from being stemmed {:class "solr.KeywordMarkerFilterFactory" :protected "protwords.txt"} ;; Applies the Porter Stemming Algorithm for English ;; "jump" "jumping" "jumped" => "jump" "jump" "jump" {:class "solr.PorterStemFilterFactory"} ;; Needed for synonyms {:class "solr.FlattenGraphFilterFactory"}]} :queryAnalyzer {:type "query" :tokenizer {:class "solr.WhitespaceTokenizerFactory"} :filters [ ;; Adds up in synonyms at query time {:class "solr.SynonymGraphFilterFactory" :synonyms "synonyms.txt" ;added :ignoreCase "true" :expand "true"} {:class "solr.StopFilterFactory" :words "lang/stopwords_en.txt" ;added :ignoreCase "true"} {:class "solr.WordDelimiterGraphFilterFactory" :generateWordParts "1" :generateNumberParts "1" :catenateWords "1" :catenateNumbers "1" :catenateAll "0" :splitOnCaseChange "1"} {:class "solr.LowerCaseFilterFactory"} {:class "solr.KeywordMarkerFilterFactory" :protected "protwords.txt" ;added } {:class "solr.PorterStemFilterFactory"} ]}}) (def basic-fields "You can find your basic schema types here: resources/solr/tmdb/conf/managedschema" [{:name "_text_", :type "text_en_splitting", :multiValued true, :indexed true, :stored false} {:name "_version_", ; version of document, query per version :type "plong", :indexed true, :stored true} {:name "db_id", :type "string", :multiValued false, :indexed true, :required true, :stored true}]) (def content-fields [{:name "tagline", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "overview", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "genres", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "title", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "keywords", :type "text_en_splitting", :indexed true, :stored true :multiValued true :termVectors true} {:name "original_title", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "production_companies", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "production_countries", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "spoken_languages", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "original_language", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "status", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "homepage", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "cast", :type "text_lowcased", :indexed true, :stored true :multiValued true :termVectors true} {:name "<NAME>", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "producers", :type "text_lowcased", :indexed true, :stored true :multiValued true :termVectors true}]) (def number-fields [{:name "release_date", :type "pdate", :indexed true, :stored true} {:name "budget", :type "plong", :indexed true, :stored true} {:name "revenue", :type "plong", :indexed true, :stored true} {:name "vote_count", :type "plongs"} {:name "popularity", :type "pfloat", :indexed true, :stored true} {:name "runtime", :type "pfloat", :indexed true, :stored true} {:name "vote_average", :type "pfloat", :indexed true, :stored true}])
true
(ns corona-demo.data (:require [clojure.data.json :as json] [corona-demo.utils :as utils])) ;;; Movies (def data-dir (str (System/getProperty "user.dir") "/resources/solr/tmdb/data/")) (def csv-dir (str data-dir "csv/")) (def movies-file "tmdb_5000_movies.csv") (def credits-file "tmdb_5000_credits.csv") (def links-file "links.csv") (def ratings-file "ratings.csv") (def users-file "users.csv") (def movies-fields-val-fns {:genres (utils/mapv-json-vals "name") :keywords (utils/mapv-json-vals "name") :spoken_languages (utils/mapv-json-vals "iso_639_1") :production_companies (utils/mapv-json-vals "name") :production_countries (utils/mapv-json-vals "iso_3166_1")}) (def movies* (utils/read-csv (str csv-dir movies-file) {:key-fn keyword :val-fns movies-fields-val-fns})) (defonce links (utils/read-csv (str csv-dir links-file) {:key-fn keyword :val-fns {:movieId #(Long/parseLong %)}})) #_(take 10 links) (def credits-raw-maps (utils/read-csv (str csv-dir credits-file) {:key-fn keyword})) (defn parse-credit-raw-map [{:keys [movie_id cast crew] :as row}] (let [crew-data (json/read-str crew)] {:db_id (:movie_id row) :cast ((utils/mapv-json-vals "name") cast) :director (-> (filter #(= "Director" (get % "job")) crew-data) first (get "name")) :producers (->> crew-data (filter #(= "Producer" (get % "job"))) (mapv #(get % "name")))})) (defonce credits (map parse-credit-raw-map credits-raw-maps)) (defn tmdb_id->credits [db_id] (-> (first (filter #(= db_id (:movie_id %)) credits)) (dissoc :db_id))) (defn tmdb_id->movie-lens-id [db_id] (:movieId (first (filter #(= db_id (:tmdbId %)) links)))) (defonce movies (mapv (fn [{:keys [db_id] :as m}] (-> m (assoc :movie_lens_id (tmdb_id->movie-lens-id db_id)) (merge (tmdb_id->credits db_id)))) movies*)) #_(count movies) #_(first movies) #_(count (filter :movie_lens_id movies)) #_(db_id->movieId "862") (defn read-ratings [] (utils/read-csv (str csv-dir ratings-file) {:key-fn keyword :val-fns {:userId (fn [id] (Long/parseLong id)) :movieId (fn [id] (Long/parseLong id)) :rating (fn [f] (Float/parseFloat f))}})) (defonce ratings (read-ratings)) #_(first ratings) (defn make-rated-movies-ids-set [ratings] (set (map :movieId ratings))) (def rated-movie-ids (make-rated-movies-ids-set ratings)) (def rated-movies (filter #(contains? rated-movie-ids (:movie_lens_id %)) movies)) #_(count rated-movies) (defn read-users "Parse user records from 'users-csv-resource-name' resource (.csv format)" [] (let [parse-num (fn [v] (Float/parseFloat v)) db-fields [:userId :gender :age :occupation :zip] users-fields-fns {:userId (fn [id] (Long/parseLong id)) :gender (fn [g] (case g "F" 0.0 "M" 1.0)) :age (fn [v] (when-not (= v "1") (Float/parseFloat v))) :occupation (fn [v] (Float/parseFloat v))} entries (utils/read-csv (str csv-dir users-file) {:key-fn keyword :val-fns users-fields-fns})] (filter :age entries))) #_(take 3 (read-users)) #_(count (read-users)) (def schema-type-text_en_splitting "A text field with defaults appropriate for English, plus aggressive word-splitting and autophrase features enabled. This field is just like text_en, except it adds WordDelimiterGraphFilter to enable splitting and matching of words on case-change, alpha numeric boundaries, and non-alphanumeric chars. This means certain compound word cases will work, for example query \"wi fi\" will match document \"WiFi\" or \"wi-fi\". " {:name "text_en_splitting" :class "solr.TextField" :positionIncrementGap "100" :autoGeneratePhraseQueries "true" :indexAnalyzer {:tokenizer {:class "solr.WhitespaceTokenizerFactory"} :filters [ ;; Removes stop words {:class "solr.StopFilterFactory" :words "lang/stopwords_en.txt" ;added :ignoreCase "true"} ;; Splits and matches words on case-change, ;; alpha numeric boundaries, and ;; non-alphanumeric chars ;; 'wi fi' = 'WiFi' = 'wi-fi' {:class "solr.WordDelimiterGraphFilterFactory" :generateWordParts "1" :generateNumberParts "1" :catenateWords "1" :catenateNumbers "1" :catenateAll "0" :splitOnCaseChange "1"} ;; Lowercases content {:class "solr.LowerCaseFilterFactory"} ;; Protects some words from being stemmed {:class "solr.KeywordMarkerFilterFactory" :protected "protwords.txt"} ;; Applies the Porter Stemming Algorithm for English ;; "jump" "jumping" "jumped" => "jump" "jump" "jump" {:class "solr.PorterStemFilterFactory"} ;; Needed for synonyms {:class "solr.FlattenGraphFilterFactory"}]} :queryAnalyzer {:type "query" :tokenizer {:class "solr.WhitespaceTokenizerFactory"} :filters [ ;; Adds up in synonyms at query time {:class "solr.SynonymGraphFilterFactory" :synonyms "synonyms.txt" ;added :ignoreCase "true" :expand "true"} {:class "solr.StopFilterFactory" :words "lang/stopwords_en.txt" ;added :ignoreCase "true"} {:class "solr.WordDelimiterGraphFilterFactory" :generateWordParts "1" :generateNumberParts "1" :catenateWords "1" :catenateNumbers "1" :catenateAll "0" :splitOnCaseChange "1"} {:class "solr.LowerCaseFilterFactory"} {:class "solr.KeywordMarkerFilterFactory" :protected "protwords.txt" ;added } {:class "solr.PorterStemFilterFactory"} ]}}) (def basic-fields "You can find your basic schema types here: resources/solr/tmdb/conf/managedschema" [{:name "_text_", :type "text_en_splitting", :multiValued true, :indexed true, :stored false} {:name "_version_", ; version of document, query per version :type "plong", :indexed true, :stored true} {:name "db_id", :type "string", :multiValued false, :indexed true, :required true, :stored true}]) (def content-fields [{:name "tagline", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "overview", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "genres", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "title", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "keywords", :type "text_en_splitting", :indexed true, :stored true :multiValued true :termVectors true} {:name "original_title", :type "text_en_splitting", :indexed true, :stored true :termVectors true} {:name "production_companies", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "production_countries", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "spoken_languages", :type "text_lowcased", :multiValued true, :indexed true, :stored true :termVectors true} {:name "original_language", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "status", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "homepage", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "cast", :type "text_lowcased", :indexed true, :stored true :multiValued true :termVectors true} {:name "PI:NAME:<NAME>END_PI", :type "text_lowcased", :indexed true, :stored true :termVectors true} {:name "producers", :type "text_lowcased", :indexed true, :stored true :multiValued true :termVectors true}]) (def number-fields [{:name "release_date", :type "pdate", :indexed true, :stored true} {:name "budget", :type "plong", :indexed true, :stored true} {:name "revenue", :type "plong", :indexed true, :stored true} {:name "vote_count", :type "plongs"} {:name "popularity", :type "pfloat", :indexed true, :stored true} {:name "runtime", :type "pfloat", :indexed true, :stored true} {:name "vote_average", :type "pfloat", :indexed true, :stored true}])
[ { "context": ";\n; Copyright 2019 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 30, "score": 0.9996452331542969, "start": 19, "tag": "NAME", "value": "Peter Monks" } ]
repl-init.clj
pmonks/clojars-dependencies
0
; ; Copyright 2019 Peter Monks ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; ; SPDX-License-Identifier: Apache-2.0 ; ; This script is intended to be used to initialise a clj REPL set up for easy experimentation with this project. ; ; Use: ; ; clojure -i repl-init.clj -r ; ; Note: do NOT use `clj` to run this script, or you will see strange output behaviour ; (require '[clojure.pprint :as pp :refer [pprint]]) (require '[clojure.string :as s]) (require '[clojure.java.io :as io]) (require '[clojure.xml :as xml]) (require '[clojure.zip :as zip]) (require '[clojure.data.zip.xml :as zip-xml]) (require '[version-clj.core :as ver]) (require '[loom.graph :as g]) (require '[loom.alg :as galg]) (require '[loom.io :as gio]) (require '[clojars-dependencies.core :as cd] :reload-all) (require '[spinner.core :as spin]) (def prevent-sync false) (def poms-directory "./poms") (def clojars-poms-directory "./poms/clojars") ; REPL state setup... (if prevent-sync (println "ℹ️ Skipping sync") (do (io/make-parents clojars-poms-directory) (print "ℹ️ Syncing POMs from Clojars... ") (if (spin/spin! (fn [] (cd/sync-clojars-poms! clojars-poms-directory))) ; This may take a long time... (println "\nℹ️ Done - updated POMs synced") (println "\nℹ️ Done - no changes")))) (print "ℹ️ Parsing POMs... ") (def parsed-poms (cd/parse-pom-files poms-directory)) ; Should use a spinner here, but the JVM's idiotic "illegal reflection" warning seems to screw up jansi (println "\nℹ️ Parsed" (count parsed-poms) "POMs") (def latest-versions-only (cd/latest-project-versions parsed-poms)) (println "ℹ️ Found" (count latest-versions-only) "unique projects") (def dependencies (cd/dependencies latest-versions-only)) (println "ℹ️ Found" (count dependencies) "unique dependencies amongst latest versions") ; Experiments go here... (def inverted-dependencies (group-by second dependencies)) ; This isn't correct... (def sample-library "version-clj/version-clj") (def consumers (seq (sort (map first (get inverted-dependencies sample-library))))) (println "ℹ️ Consumers of" (str sample-library ":\n") (if consumers (doall (map (partial println "* ") consumers)) "- none -")) ;(println "ℹ️ Top 25 most depended-upon projects:\n *" (s/join "\n * " (take 25 (map first (sort-by #(count (val %)) > inverted-dependencies))))) ; Build a Loom graph ;(def g (apply g/digraph dependencies)) ;(println "ℹ️ Dependencies are a DAG?" (galg/dag? g)) ;(def g (apply g/digraph edges)) ;(graphio/view g) ; Warning: this takes a *VERY* long time on a data set of this size...
120868
; ; Copyright 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. ; ; SPDX-License-Identifier: Apache-2.0 ; ; This script is intended to be used to initialise a clj REPL set up for easy experimentation with this project. ; ; Use: ; ; clojure -i repl-init.clj -r ; ; Note: do NOT use `clj` to run this script, or you will see strange output behaviour ; (require '[clojure.pprint :as pp :refer [pprint]]) (require '[clojure.string :as s]) (require '[clojure.java.io :as io]) (require '[clojure.xml :as xml]) (require '[clojure.zip :as zip]) (require '[clojure.data.zip.xml :as zip-xml]) (require '[version-clj.core :as ver]) (require '[loom.graph :as g]) (require '[loom.alg :as galg]) (require '[loom.io :as gio]) (require '[clojars-dependencies.core :as cd] :reload-all) (require '[spinner.core :as spin]) (def prevent-sync false) (def poms-directory "./poms") (def clojars-poms-directory "./poms/clojars") ; REPL state setup... (if prevent-sync (println "ℹ️ Skipping sync") (do (io/make-parents clojars-poms-directory) (print "ℹ️ Syncing POMs from Clojars... ") (if (spin/spin! (fn [] (cd/sync-clojars-poms! clojars-poms-directory))) ; This may take a long time... (println "\nℹ️ Done - updated POMs synced") (println "\nℹ️ Done - no changes")))) (print "ℹ️ Parsing POMs... ") (def parsed-poms (cd/parse-pom-files poms-directory)) ; Should use a spinner here, but the JVM's idiotic "illegal reflection" warning seems to screw up jansi (println "\nℹ️ Parsed" (count parsed-poms) "POMs") (def latest-versions-only (cd/latest-project-versions parsed-poms)) (println "ℹ️ Found" (count latest-versions-only) "unique projects") (def dependencies (cd/dependencies latest-versions-only)) (println "ℹ️ Found" (count dependencies) "unique dependencies amongst latest versions") ; Experiments go here... (def inverted-dependencies (group-by second dependencies)) ; This isn't correct... (def sample-library "version-clj/version-clj") (def consumers (seq (sort (map first (get inverted-dependencies sample-library))))) (println "ℹ️ Consumers of" (str sample-library ":\n") (if consumers (doall (map (partial println "* ") consumers)) "- none -")) ;(println "ℹ️ Top 25 most depended-upon projects:\n *" (s/join "\n * " (take 25 (map first (sort-by #(count (val %)) > inverted-dependencies))))) ; Build a Loom graph ;(def g (apply g/digraph dependencies)) ;(println "ℹ️ Dependencies are a DAG?" (galg/dag? g)) ;(def g (apply g/digraph edges)) ;(graphio/view g) ; Warning: this takes a *VERY* long time on a data set of this size...
true
; ; Copyright 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. ; ; SPDX-License-Identifier: Apache-2.0 ; ; This script is intended to be used to initialise a clj REPL set up for easy experimentation with this project. ; ; Use: ; ; clojure -i repl-init.clj -r ; ; Note: do NOT use `clj` to run this script, or you will see strange output behaviour ; (require '[clojure.pprint :as pp :refer [pprint]]) (require '[clojure.string :as s]) (require '[clojure.java.io :as io]) (require '[clojure.xml :as xml]) (require '[clojure.zip :as zip]) (require '[clojure.data.zip.xml :as zip-xml]) (require '[version-clj.core :as ver]) (require '[loom.graph :as g]) (require '[loom.alg :as galg]) (require '[loom.io :as gio]) (require '[clojars-dependencies.core :as cd] :reload-all) (require '[spinner.core :as spin]) (def prevent-sync false) (def poms-directory "./poms") (def clojars-poms-directory "./poms/clojars") ; REPL state setup... (if prevent-sync (println "ℹ️ Skipping sync") (do (io/make-parents clojars-poms-directory) (print "ℹ️ Syncing POMs from Clojars... ") (if (spin/spin! (fn [] (cd/sync-clojars-poms! clojars-poms-directory))) ; This may take a long time... (println "\nℹ️ Done - updated POMs synced") (println "\nℹ️ Done - no changes")))) (print "ℹ️ Parsing POMs... ") (def parsed-poms (cd/parse-pom-files poms-directory)) ; Should use a spinner here, but the JVM's idiotic "illegal reflection" warning seems to screw up jansi (println "\nℹ️ Parsed" (count parsed-poms) "POMs") (def latest-versions-only (cd/latest-project-versions parsed-poms)) (println "ℹ️ Found" (count latest-versions-only) "unique projects") (def dependencies (cd/dependencies latest-versions-only)) (println "ℹ️ Found" (count dependencies) "unique dependencies amongst latest versions") ; Experiments go here... (def inverted-dependencies (group-by second dependencies)) ; This isn't correct... (def sample-library "version-clj/version-clj") (def consumers (seq (sort (map first (get inverted-dependencies sample-library))))) (println "ℹ️ Consumers of" (str sample-library ":\n") (if consumers (doall (map (partial println "* ") consumers)) "- none -")) ;(println "ℹ️ Top 25 most depended-upon projects:\n *" (s/join "\n * " (take 25 (map first (sort-by #(count (val %)) > inverted-dependencies))))) ; Build a Loom graph ;(def g (apply g/digraph dependencies)) ;(println "ℹ️ Dependencies are a DAG?" (galg/dag? g)) ;(def g (apply g/digraph edges)) ;(graphio/view g) ; Warning: this takes a *VERY* long time on a data set of this size...
[ { "context": ";; Copyright 2014 Rich Hickey. All Rights Reserved.\n;;\n;; Licensed under the Ap", "end": 30, "score": 0.999795138835907, "start": 19, "tag": "NAME", "value": "Rich Hickey" } ]
src/Transit/sellars/transit/alpha.clj
jeremyrsellars/transit-csharp
0
;; Copyright 2014 Rich Hickey. All Rights Reserved. ;; ;; 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 sellars.transit.alpha "An implementation of the transit-format for Clojure built on top of the transit-cljr library." (:refer-clojure :exclude [read]) (:require [clojure.string :as str]) (:import [Sellars.Transit.Alpha IWriteHandler IReadHandler IListReadHandler IDictionaryReadHandler IDefaultReadHandler IReader IWriter IListReader TransitFactory+Format IDictionaryReader] [Sellars.Transit.Cljr.Alpha TransitFactory] [Sellars.Transit.Spi.Alpha IReaderSpi] [System.IO Stream])) (defprotocol HandlerMapProvider (handler-map [this])) (deftype HandlerMapContainer [m] HandlerMapProvider (handler-map [this] m)) ;; writing (set! *warn-on-reflection* true) (defn- transit-format "Converts a keyword to a TransitFactory+Format value." [kw] (Enum/Parse TransitFactory+Format (str/replace (name kw) #"^.|-." #(-> % (str/upper-case) (str/replace #"-" ""))) true)) (defn tagged-value "Creates a TaggedValue object." [tag rep] (TransitFactory/TaggedValue tag rep)) (defn nsed-name "Convert a keyword or symbol to a string in namespace/name format." [^clojure.lang.Named kw-or-sym] (if-let [ns (.getNamespace kw-or-sym)] (str ns "/" (.getName kw-or-sym)) (.getName kw-or-sym))) (defn- fn-or-val [f] (if (fn? f) f (constantly f))) (defn write-handler "Creates a transit IWriteHandler whose tag, rep, stringRep, and verboseWriteHandler methods invoke the provided fns. If a non-fn is passed as an argument, implemented handler method returns the value unaltered." ([tag-fn rep-fn] (write-handler tag-fn rep-fn nil nil)) ([tag-fn rep-fn str-rep-fn] (write-handler tag-fn rep-fn str-rep-fn nil)) ([tag-fn rep-fn str-rep-fn verbose-handler-fn] (let [tag-fn (fn-or-val tag-fn) rep-fn (fn-or-val rep-fn) str-rep-fn (fn-or-val str-rep-fn) verbose-handler-fn (fn-or-val verbose-handler-fn)] (reify IWriteHandler (Tag [_ o] (tag-fn o)) (Representation [_ o] (rep-fn o)) (StringRepresentation [_ o] (when str-rep-fn (str-rep-fn o))) (GetVerboseHandler [_] (when verbose-handler-fn (verbose-handler-fn))))))) (deftype WithMeta [value meta]) (def default-write-handlers "Returns a map of default WriteHandlers for Clojure types. Java types are handled by the default WriteHandlers provided by the transit-java library." {sellars.transit.alpha.WithMeta (reify IWriteHandler (Tag [_ _] "with-meta") (Representation [_ o] (TransitFactory/TaggedValue "array" [(.-value ^sellars.transit.alpha.WithMeta o) (.-meta ^sellars.transit.alpha.WithMeta o)])) (StringRepresentation [_ _] nil) (GetVerboseHandler [_] nil))}) (deftype Writer [^IWriter w]) (defn writer "Creates a writer over the provided destination `out` using the specified format, one of: :msgpack, :json or :json-verbose. An optional opts map may be passed. Supported options are: :handlers - a map of types to IWriteHandler instances, they are merged with the default-handlers and then with the default handlers provided by transit-java. :default-handler - a default IWriteHandler to use if NO handler is found for a type. If no default is specified, an error will be thrown for an unknown type. :transform - a function of one argument that will transform values before they are written." ([out type] (writer out type {})) ([^Stream out type {:keys [handlers default-handler transform]}] (if (#{:json :json-verbose :msgpack} type) (let [handler-map (if (instance? HandlerMapContainer handlers) (handler-map handlers) (merge default-write-handlers handlers))] (Writer. (TransitFactory/Writer (transit-format type) out handler-map default-handler (when transform (condp instance? transform |System.Func`2[System.Object,System.Object]| transform clojure.lang.IFn (sys-func [Object Object] [x] (transform x)) (throw (ex-info (str "Invalid transform. Must be Func<object,object> or fn. " (class transform)) {:transform transform}))))))) (throw (ex-info "Type must be :json, :json-verbose, or :msgpack" {:type type}))))) (defn write "Writes a value to a transit writer." [^Writer writer o] (.Write (.w writer) o)) ; is there a way to type-hint a generic interface? ;; reading (defn read-handler "Creates a transit ReadHandler whose FromRepresentation method invokes the provided fn." [from-rep] (reify IReadHandler (FromRepresentation [_ o] (from-rep o)))) (defn- custom-default-read-handler "Returns an IDefaultReadHandler. fn-or-IDefaultReadHandler may be a fn like (fn default-read-handler [tag rep]rep) If fn-or-IDefaultReadHandler is already an IDefaultReadHandler, returns fn-or-IDefaultReadHandler. " [fn-or-IDefaultReadHandler] (if (instance? IDefaultReadHandler fn-or-IDefaultReadHandler) fn-or-IDefaultReadHandler (reify IDefaultReadHandler (FromRepresentation [_ tag representation] (fn-or-IDefaultReadHandler tag representation))))) (defn read-map-handler "Creates a Transit MapReadHandler whose FromRepresentation and DictionaryReader methods invoke the provided fns." [from-rep map-reader] (reify IDictionaryReadHandler (FromRepresentation [_ o] (from-rep o)) (DictionaryReader [_] (map-reader)))) (defn read-array-handler "Creates a Transit IListReadHandler whose FromRepresentation and ListReader methods invoke the provided fns." [from-rep array-reader] (reify IListReadHandler (FromRepresentation [_ o] (from-rep o)) (ListReader [_] (array-reader)))) (def default-read-handlers "Returns a map of default ReadHandlers for Clojure types. Java types are handled by the default ReadHandlers provided by the transit-java library." {"with-meta" (reify IReadHandler (FromRepresentation [_ o] (with-meta (nth o 0) (nth o 1))))}) (defn transient-map-builder "Creates a MapBuilder that makes Clojure- compatible maps." [] (reify IDictionaryReader (Init [_] (transient {})) #_(Init [_ ^int size] (transient {})) (Add [_ m k v] (assoc! m k v)) (Complete [_ m] (persistent! m)))) (defn map-builder "Creates a MapBuilder that makes Clojure- compatible maps." [] (reify IDictionaryReader (Init [_] (transient [])) #_(Init [_ ^int size] (transient [])) (Add [_ l k v] (conj! (conj! l k) v)) (Complete [_ l] (apply hash-map (persistent! l))))) (defn list-builder "Creates an ArrayBuilder that makes Clojure- compatible lists." [] (reify IListReader (Init [_] (transient [])) #_(Init [_ ^int size] (transient [])) (Add [_ v item] (conj! v item)) (Complete [_ v] (persistent! v)))) (deftype Reader [r]) (defn reader "Creates a reader over the provided source `in` using the specified format, one of: :msgpack, :json or :json-verbose. An optional opts map may be passed. Supported options are: :handlers - a map of tags to ReadHandler instances, they are merged with the Clojure default-read-handlers and then with the default ReadHandlers provided by transit-java. :default-handler - an instance of DefaultReadHandler, used to process transit encoded values for which there is no other ReadHandler; if :default-handler is not specified, non-readable values are returned as TaggedValues." ([in type] (reader in type {})) ([^Stream in type {:keys [handlers default-handler]}] (if (#{:json :json-verbose :msgpack} type) (let [handler-map (if (instance? HandlerMapContainer handlers) (handler-map handlers) (merge default-read-handlers handlers)) reader (TransitFactory/Reader (transit-format type) in handler-map (when default-handler (custom-default-read-handler default-handler)))] (Reader. (.SetBuilders ^IReaderSpi reader (map-builder) (list-builder)))) (throw (ex-info "Type must be :json, :json-verbose or :msgpack" {:type type}))))) (defn read "Reads a value from a reader. Throws a RuntimeException when the reader's Stream is empty." [^Reader reader] (.Read ^IReader (.r reader))) (defn record-write-handler "Creates a IWriteHandler for a record type" [^Type type] (reify IWriteHandler (Tag [_ _] (.get_FullName type)) (Representation [_ rec] (tagged-value "map" rec)) (StringRepresentation [_ _] nil) (GetVerboseHandler [_] nil))) (defn record-write-handlers "Creates a map of record types to IWriteHandlers" [& types] (reduce (fn [h t] (assoc h t (record-write-handler t))) {} types)) (defn record-read-handler "Creates a ReadHandler for a record type" [^Type type] (let [type-name (map #(str/replace % "_" "-") (str/split (.get_FullName type) #"\.")) map-ctor (-> (str (str/join "." (butlast type-name)) "/map->" (last type-name)) symbol resolve)] (reify IReadHandler (FromRepresentation [_ m] (map-ctor m))))) (defn record-read-handlers "Creates a map of record type tags to ReadHandlers" [& types] (reduce (fn [d ^Type t] (assoc d (.get_FullName t) (record-read-handler t))) {} types)) (defn read-handler-map "Returns a HandlerMapContainer containing a ReadHandlerMap containing all the default handlers for Clojure and Java and any custom handlers that you supply, letting you store the return value and pass it to multiple invocations of reader. This can be more efficient than repeatedly handing the same raw map of tags -> custom handlers to reader." [custom-handlers] (HandlerMapContainer. (TransitFactory/ReadHandlerMap (merge default-read-handlers custom-handlers)))) (defn write-handler-map "Returns a HandlerMapContainer containing a WriteHandlerMap containing all the default handlers for Clojure and Java and any custom handlers that you supply, letting you store the return value and pass it to multiple invocations of writer. This can be more efficient than repeatedly handing the same raw map of types -> custom handlers to writer." [custom-handlers] (HandlerMapContainer. (TransitFactory/WriteHandlerMap (merge default-write-handlers custom-handlers)))) (defn write-meta "For :transform. Will write any metadata present on the value." [x] (if (instance? clojure.lang.IObj x) (if-let [m (meta x)] (WithMeta. (with-meta x nil) m) x) x)) (comment (require 'sellars.transit) (in-ns 'sellars.transit) (import [java.io File ByteArrayStream ByteArrayStream StreamWriter]) (def out (ByteArrayStream. 2000)) (def w (writer out :json)) (def w (writer out :json-verbose)) (def w (writer out :msgpack)) (def w (writer out :msgpack {:transform write-meta})) (def w (writer out :json {:transform write-meta})) (write w "foo") (write w 10) (write w [1 2 3]) (write w (with-meta [1 2 3] {:foo 'bar})) (String. (.toByteArray out)) (write w {:a-key 1 :b-key 2}) (write w {"a" "1" "b" "2"}) (write w {:a-key [1 2]}) (write w #{1 2}) (write w [{:a-key 1} {:a-key 2}]) (write w [#{1 2} #{1 2}]) (write w (int-array (range 10))) (write w {[:a :b] 2}) (write w [123N]) (write w 1/3) (write w {false 10 [] 20}) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json)) (def r (reader in :msgpack)) (def x (read r)) (meta x) (type (read r)) ;; extensibility (defrecord Point [x y]) (defrecord Circle [c r]) (def ext-write-handlers {Point (write-handler "point" (fn [p] [(.x p) (.y p)])) Circle (write-handler "circle" (fn [c] [(.c c) (.r c)]))}) (def ext-read-handlers {"point" (read-handler (fn [[x y]] (prn "making a point") (Point. x y))) "circle" (read-handler (fn [[c r]] (prn "making a circle") (Circle. c r)))}) (def ext-write-handlers (record-write-handlers Point Circle)) (def ext-read-handlers (record-read-handlers Point Circle)) (def out (ByteArrayStream. 2000)) (def w (writer out :json {:handlers ext-write-handlers})) (write w (Point. 10 20)) (write w (Circle. (Point. 10 20) 30)) (write w [(Point. 10 20) (Point. 20 40) (Point. 0 0)]) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json {:handlers ext-read-handlers})) (read r) ;; write and read handler maps (def custom-write-handler-map (write-handler-map ext-write-handlers)) (def custom-read-handler-map (read-handler-map ext-read-handlers)) (def out (ByteArrayStream. 2000)) (def w (writer out :json {:handlers custom-write-handler-map})) (write w (Point. 10 20)) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json {:handlers custom-read-handler-map})) (read r))
74708
;; Copyright 2014 <NAME>. All Rights Reserved. ;; ;; 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 sellars.transit.alpha "An implementation of the transit-format for Clojure built on top of the transit-cljr library." (:refer-clojure :exclude [read]) (:require [clojure.string :as str]) (:import [Sellars.Transit.Alpha IWriteHandler IReadHandler IListReadHandler IDictionaryReadHandler IDefaultReadHandler IReader IWriter IListReader TransitFactory+Format IDictionaryReader] [Sellars.Transit.Cljr.Alpha TransitFactory] [Sellars.Transit.Spi.Alpha IReaderSpi] [System.IO Stream])) (defprotocol HandlerMapProvider (handler-map [this])) (deftype HandlerMapContainer [m] HandlerMapProvider (handler-map [this] m)) ;; writing (set! *warn-on-reflection* true) (defn- transit-format "Converts a keyword to a TransitFactory+Format value." [kw] (Enum/Parse TransitFactory+Format (str/replace (name kw) #"^.|-." #(-> % (str/upper-case) (str/replace #"-" ""))) true)) (defn tagged-value "Creates a TaggedValue object." [tag rep] (TransitFactory/TaggedValue tag rep)) (defn nsed-name "Convert a keyword or symbol to a string in namespace/name format." [^clojure.lang.Named kw-or-sym] (if-let [ns (.getNamespace kw-or-sym)] (str ns "/" (.getName kw-or-sym)) (.getName kw-or-sym))) (defn- fn-or-val [f] (if (fn? f) f (constantly f))) (defn write-handler "Creates a transit IWriteHandler whose tag, rep, stringRep, and verboseWriteHandler methods invoke the provided fns. If a non-fn is passed as an argument, implemented handler method returns the value unaltered." ([tag-fn rep-fn] (write-handler tag-fn rep-fn nil nil)) ([tag-fn rep-fn str-rep-fn] (write-handler tag-fn rep-fn str-rep-fn nil)) ([tag-fn rep-fn str-rep-fn verbose-handler-fn] (let [tag-fn (fn-or-val tag-fn) rep-fn (fn-or-val rep-fn) str-rep-fn (fn-or-val str-rep-fn) verbose-handler-fn (fn-or-val verbose-handler-fn)] (reify IWriteHandler (Tag [_ o] (tag-fn o)) (Representation [_ o] (rep-fn o)) (StringRepresentation [_ o] (when str-rep-fn (str-rep-fn o))) (GetVerboseHandler [_] (when verbose-handler-fn (verbose-handler-fn))))))) (deftype WithMeta [value meta]) (def default-write-handlers "Returns a map of default WriteHandlers for Clojure types. Java types are handled by the default WriteHandlers provided by the transit-java library." {sellars.transit.alpha.WithMeta (reify IWriteHandler (Tag [_ _] "with-meta") (Representation [_ o] (TransitFactory/TaggedValue "array" [(.-value ^sellars.transit.alpha.WithMeta o) (.-meta ^sellars.transit.alpha.WithMeta o)])) (StringRepresentation [_ _] nil) (GetVerboseHandler [_] nil))}) (deftype Writer [^IWriter w]) (defn writer "Creates a writer over the provided destination `out` using the specified format, one of: :msgpack, :json or :json-verbose. An optional opts map may be passed. Supported options are: :handlers - a map of types to IWriteHandler instances, they are merged with the default-handlers and then with the default handlers provided by transit-java. :default-handler - a default IWriteHandler to use if NO handler is found for a type. If no default is specified, an error will be thrown for an unknown type. :transform - a function of one argument that will transform values before they are written." ([out type] (writer out type {})) ([^Stream out type {:keys [handlers default-handler transform]}] (if (#{:json :json-verbose :msgpack} type) (let [handler-map (if (instance? HandlerMapContainer handlers) (handler-map handlers) (merge default-write-handlers handlers))] (Writer. (TransitFactory/Writer (transit-format type) out handler-map default-handler (when transform (condp instance? transform |System.Func`2[System.Object,System.Object]| transform clojure.lang.IFn (sys-func [Object Object] [x] (transform x)) (throw (ex-info (str "Invalid transform. Must be Func<object,object> or fn. " (class transform)) {:transform transform}))))))) (throw (ex-info "Type must be :json, :json-verbose, or :msgpack" {:type type}))))) (defn write "Writes a value to a transit writer." [^Writer writer o] (.Write (.w writer) o)) ; is there a way to type-hint a generic interface? ;; reading (defn read-handler "Creates a transit ReadHandler whose FromRepresentation method invokes the provided fn." [from-rep] (reify IReadHandler (FromRepresentation [_ o] (from-rep o)))) (defn- custom-default-read-handler "Returns an IDefaultReadHandler. fn-or-IDefaultReadHandler may be a fn like (fn default-read-handler [tag rep]rep) If fn-or-IDefaultReadHandler is already an IDefaultReadHandler, returns fn-or-IDefaultReadHandler. " [fn-or-IDefaultReadHandler] (if (instance? IDefaultReadHandler fn-or-IDefaultReadHandler) fn-or-IDefaultReadHandler (reify IDefaultReadHandler (FromRepresentation [_ tag representation] (fn-or-IDefaultReadHandler tag representation))))) (defn read-map-handler "Creates a Transit MapReadHandler whose FromRepresentation and DictionaryReader methods invoke the provided fns." [from-rep map-reader] (reify IDictionaryReadHandler (FromRepresentation [_ o] (from-rep o)) (DictionaryReader [_] (map-reader)))) (defn read-array-handler "Creates a Transit IListReadHandler whose FromRepresentation and ListReader methods invoke the provided fns." [from-rep array-reader] (reify IListReadHandler (FromRepresentation [_ o] (from-rep o)) (ListReader [_] (array-reader)))) (def default-read-handlers "Returns a map of default ReadHandlers for Clojure types. Java types are handled by the default ReadHandlers provided by the transit-java library." {"with-meta" (reify IReadHandler (FromRepresentation [_ o] (with-meta (nth o 0) (nth o 1))))}) (defn transient-map-builder "Creates a MapBuilder that makes Clojure- compatible maps." [] (reify IDictionaryReader (Init [_] (transient {})) #_(Init [_ ^int size] (transient {})) (Add [_ m k v] (assoc! m k v)) (Complete [_ m] (persistent! m)))) (defn map-builder "Creates a MapBuilder that makes Clojure- compatible maps." [] (reify IDictionaryReader (Init [_] (transient [])) #_(Init [_ ^int size] (transient [])) (Add [_ l k v] (conj! (conj! l k) v)) (Complete [_ l] (apply hash-map (persistent! l))))) (defn list-builder "Creates an ArrayBuilder that makes Clojure- compatible lists." [] (reify IListReader (Init [_] (transient [])) #_(Init [_ ^int size] (transient [])) (Add [_ v item] (conj! v item)) (Complete [_ v] (persistent! v)))) (deftype Reader [r]) (defn reader "Creates a reader over the provided source `in` using the specified format, one of: :msgpack, :json or :json-verbose. An optional opts map may be passed. Supported options are: :handlers - a map of tags to ReadHandler instances, they are merged with the Clojure default-read-handlers and then with the default ReadHandlers provided by transit-java. :default-handler - an instance of DefaultReadHandler, used to process transit encoded values for which there is no other ReadHandler; if :default-handler is not specified, non-readable values are returned as TaggedValues." ([in type] (reader in type {})) ([^Stream in type {:keys [handlers default-handler]}] (if (#{:json :json-verbose :msgpack} type) (let [handler-map (if (instance? HandlerMapContainer handlers) (handler-map handlers) (merge default-read-handlers handlers)) reader (TransitFactory/Reader (transit-format type) in handler-map (when default-handler (custom-default-read-handler default-handler)))] (Reader. (.SetBuilders ^IReaderSpi reader (map-builder) (list-builder)))) (throw (ex-info "Type must be :json, :json-verbose or :msgpack" {:type type}))))) (defn read "Reads a value from a reader. Throws a RuntimeException when the reader's Stream is empty." [^Reader reader] (.Read ^IReader (.r reader))) (defn record-write-handler "Creates a IWriteHandler for a record type" [^Type type] (reify IWriteHandler (Tag [_ _] (.get_FullName type)) (Representation [_ rec] (tagged-value "map" rec)) (StringRepresentation [_ _] nil) (GetVerboseHandler [_] nil))) (defn record-write-handlers "Creates a map of record types to IWriteHandlers" [& types] (reduce (fn [h t] (assoc h t (record-write-handler t))) {} types)) (defn record-read-handler "Creates a ReadHandler for a record type" [^Type type] (let [type-name (map #(str/replace % "_" "-") (str/split (.get_FullName type) #"\.")) map-ctor (-> (str (str/join "." (butlast type-name)) "/map->" (last type-name)) symbol resolve)] (reify IReadHandler (FromRepresentation [_ m] (map-ctor m))))) (defn record-read-handlers "Creates a map of record type tags to ReadHandlers" [& types] (reduce (fn [d ^Type t] (assoc d (.get_FullName t) (record-read-handler t))) {} types)) (defn read-handler-map "Returns a HandlerMapContainer containing a ReadHandlerMap containing all the default handlers for Clojure and Java and any custom handlers that you supply, letting you store the return value and pass it to multiple invocations of reader. This can be more efficient than repeatedly handing the same raw map of tags -> custom handlers to reader." [custom-handlers] (HandlerMapContainer. (TransitFactory/ReadHandlerMap (merge default-read-handlers custom-handlers)))) (defn write-handler-map "Returns a HandlerMapContainer containing a WriteHandlerMap containing all the default handlers for Clojure and Java and any custom handlers that you supply, letting you store the return value and pass it to multiple invocations of writer. This can be more efficient than repeatedly handing the same raw map of types -> custom handlers to writer." [custom-handlers] (HandlerMapContainer. (TransitFactory/WriteHandlerMap (merge default-write-handlers custom-handlers)))) (defn write-meta "For :transform. Will write any metadata present on the value." [x] (if (instance? clojure.lang.IObj x) (if-let [m (meta x)] (WithMeta. (with-meta x nil) m) x) x)) (comment (require 'sellars.transit) (in-ns 'sellars.transit) (import [java.io File ByteArrayStream ByteArrayStream StreamWriter]) (def out (ByteArrayStream. 2000)) (def w (writer out :json)) (def w (writer out :json-verbose)) (def w (writer out :msgpack)) (def w (writer out :msgpack {:transform write-meta})) (def w (writer out :json {:transform write-meta})) (write w "foo") (write w 10) (write w [1 2 3]) (write w (with-meta [1 2 3] {:foo 'bar})) (String. (.toByteArray out)) (write w {:a-key 1 :b-key 2}) (write w {"a" "1" "b" "2"}) (write w {:a-key [1 2]}) (write w #{1 2}) (write w [{:a-key 1} {:a-key 2}]) (write w [#{1 2} #{1 2}]) (write w (int-array (range 10))) (write w {[:a :b] 2}) (write w [123N]) (write w 1/3) (write w {false 10 [] 20}) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json)) (def r (reader in :msgpack)) (def x (read r)) (meta x) (type (read r)) ;; extensibility (defrecord Point [x y]) (defrecord Circle [c r]) (def ext-write-handlers {Point (write-handler "point" (fn [p] [(.x p) (.y p)])) Circle (write-handler "circle" (fn [c] [(.c c) (.r c)]))}) (def ext-read-handlers {"point" (read-handler (fn [[x y]] (prn "making a point") (Point. x y))) "circle" (read-handler (fn [[c r]] (prn "making a circle") (Circle. c r)))}) (def ext-write-handlers (record-write-handlers Point Circle)) (def ext-read-handlers (record-read-handlers Point Circle)) (def out (ByteArrayStream. 2000)) (def w (writer out :json {:handlers ext-write-handlers})) (write w (Point. 10 20)) (write w (Circle. (Point. 10 20) 30)) (write w [(Point. 10 20) (Point. 20 40) (Point. 0 0)]) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json {:handlers ext-read-handlers})) (read r) ;; write and read handler maps (def custom-write-handler-map (write-handler-map ext-write-handlers)) (def custom-read-handler-map (read-handler-map ext-read-handlers)) (def out (ByteArrayStream. 2000)) (def w (writer out :json {:handlers custom-write-handler-map})) (write w (Point. 10 20)) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json {:handlers custom-read-handler-map})) (read r))
true
;; Copyright 2014 PI:NAME:<NAME>END_PI. All Rights Reserved. ;; ;; 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 sellars.transit.alpha "An implementation of the transit-format for Clojure built on top of the transit-cljr library." (:refer-clojure :exclude [read]) (:require [clojure.string :as str]) (:import [Sellars.Transit.Alpha IWriteHandler IReadHandler IListReadHandler IDictionaryReadHandler IDefaultReadHandler IReader IWriter IListReader TransitFactory+Format IDictionaryReader] [Sellars.Transit.Cljr.Alpha TransitFactory] [Sellars.Transit.Spi.Alpha IReaderSpi] [System.IO Stream])) (defprotocol HandlerMapProvider (handler-map [this])) (deftype HandlerMapContainer [m] HandlerMapProvider (handler-map [this] m)) ;; writing (set! *warn-on-reflection* true) (defn- transit-format "Converts a keyword to a TransitFactory+Format value." [kw] (Enum/Parse TransitFactory+Format (str/replace (name kw) #"^.|-." #(-> % (str/upper-case) (str/replace #"-" ""))) true)) (defn tagged-value "Creates a TaggedValue object." [tag rep] (TransitFactory/TaggedValue tag rep)) (defn nsed-name "Convert a keyword or symbol to a string in namespace/name format." [^clojure.lang.Named kw-or-sym] (if-let [ns (.getNamespace kw-or-sym)] (str ns "/" (.getName kw-or-sym)) (.getName kw-or-sym))) (defn- fn-or-val [f] (if (fn? f) f (constantly f))) (defn write-handler "Creates a transit IWriteHandler whose tag, rep, stringRep, and verboseWriteHandler methods invoke the provided fns. If a non-fn is passed as an argument, implemented handler method returns the value unaltered." ([tag-fn rep-fn] (write-handler tag-fn rep-fn nil nil)) ([tag-fn rep-fn str-rep-fn] (write-handler tag-fn rep-fn str-rep-fn nil)) ([tag-fn rep-fn str-rep-fn verbose-handler-fn] (let [tag-fn (fn-or-val tag-fn) rep-fn (fn-or-val rep-fn) str-rep-fn (fn-or-val str-rep-fn) verbose-handler-fn (fn-or-val verbose-handler-fn)] (reify IWriteHandler (Tag [_ o] (tag-fn o)) (Representation [_ o] (rep-fn o)) (StringRepresentation [_ o] (when str-rep-fn (str-rep-fn o))) (GetVerboseHandler [_] (when verbose-handler-fn (verbose-handler-fn))))))) (deftype WithMeta [value meta]) (def default-write-handlers "Returns a map of default WriteHandlers for Clojure types. Java types are handled by the default WriteHandlers provided by the transit-java library." {sellars.transit.alpha.WithMeta (reify IWriteHandler (Tag [_ _] "with-meta") (Representation [_ o] (TransitFactory/TaggedValue "array" [(.-value ^sellars.transit.alpha.WithMeta o) (.-meta ^sellars.transit.alpha.WithMeta o)])) (StringRepresentation [_ _] nil) (GetVerboseHandler [_] nil))}) (deftype Writer [^IWriter w]) (defn writer "Creates a writer over the provided destination `out` using the specified format, one of: :msgpack, :json or :json-verbose. An optional opts map may be passed. Supported options are: :handlers - a map of types to IWriteHandler instances, they are merged with the default-handlers and then with the default handlers provided by transit-java. :default-handler - a default IWriteHandler to use if NO handler is found for a type. If no default is specified, an error will be thrown for an unknown type. :transform - a function of one argument that will transform values before they are written." ([out type] (writer out type {})) ([^Stream out type {:keys [handlers default-handler transform]}] (if (#{:json :json-verbose :msgpack} type) (let [handler-map (if (instance? HandlerMapContainer handlers) (handler-map handlers) (merge default-write-handlers handlers))] (Writer. (TransitFactory/Writer (transit-format type) out handler-map default-handler (when transform (condp instance? transform |System.Func`2[System.Object,System.Object]| transform clojure.lang.IFn (sys-func [Object Object] [x] (transform x)) (throw (ex-info (str "Invalid transform. Must be Func<object,object> or fn. " (class transform)) {:transform transform}))))))) (throw (ex-info "Type must be :json, :json-verbose, or :msgpack" {:type type}))))) (defn write "Writes a value to a transit writer." [^Writer writer o] (.Write (.w writer) o)) ; is there a way to type-hint a generic interface? ;; reading (defn read-handler "Creates a transit ReadHandler whose FromRepresentation method invokes the provided fn." [from-rep] (reify IReadHandler (FromRepresentation [_ o] (from-rep o)))) (defn- custom-default-read-handler "Returns an IDefaultReadHandler. fn-or-IDefaultReadHandler may be a fn like (fn default-read-handler [tag rep]rep) If fn-or-IDefaultReadHandler is already an IDefaultReadHandler, returns fn-or-IDefaultReadHandler. " [fn-or-IDefaultReadHandler] (if (instance? IDefaultReadHandler fn-or-IDefaultReadHandler) fn-or-IDefaultReadHandler (reify IDefaultReadHandler (FromRepresentation [_ tag representation] (fn-or-IDefaultReadHandler tag representation))))) (defn read-map-handler "Creates a Transit MapReadHandler whose FromRepresentation and DictionaryReader methods invoke the provided fns." [from-rep map-reader] (reify IDictionaryReadHandler (FromRepresentation [_ o] (from-rep o)) (DictionaryReader [_] (map-reader)))) (defn read-array-handler "Creates a Transit IListReadHandler whose FromRepresentation and ListReader methods invoke the provided fns." [from-rep array-reader] (reify IListReadHandler (FromRepresentation [_ o] (from-rep o)) (ListReader [_] (array-reader)))) (def default-read-handlers "Returns a map of default ReadHandlers for Clojure types. Java types are handled by the default ReadHandlers provided by the transit-java library." {"with-meta" (reify IReadHandler (FromRepresentation [_ o] (with-meta (nth o 0) (nth o 1))))}) (defn transient-map-builder "Creates a MapBuilder that makes Clojure- compatible maps." [] (reify IDictionaryReader (Init [_] (transient {})) #_(Init [_ ^int size] (transient {})) (Add [_ m k v] (assoc! m k v)) (Complete [_ m] (persistent! m)))) (defn map-builder "Creates a MapBuilder that makes Clojure- compatible maps." [] (reify IDictionaryReader (Init [_] (transient [])) #_(Init [_ ^int size] (transient [])) (Add [_ l k v] (conj! (conj! l k) v)) (Complete [_ l] (apply hash-map (persistent! l))))) (defn list-builder "Creates an ArrayBuilder that makes Clojure- compatible lists." [] (reify IListReader (Init [_] (transient [])) #_(Init [_ ^int size] (transient [])) (Add [_ v item] (conj! v item)) (Complete [_ v] (persistent! v)))) (deftype Reader [r]) (defn reader "Creates a reader over the provided source `in` using the specified format, one of: :msgpack, :json or :json-verbose. An optional opts map may be passed. Supported options are: :handlers - a map of tags to ReadHandler instances, they are merged with the Clojure default-read-handlers and then with the default ReadHandlers provided by transit-java. :default-handler - an instance of DefaultReadHandler, used to process transit encoded values for which there is no other ReadHandler; if :default-handler is not specified, non-readable values are returned as TaggedValues." ([in type] (reader in type {})) ([^Stream in type {:keys [handlers default-handler]}] (if (#{:json :json-verbose :msgpack} type) (let [handler-map (if (instance? HandlerMapContainer handlers) (handler-map handlers) (merge default-read-handlers handlers)) reader (TransitFactory/Reader (transit-format type) in handler-map (when default-handler (custom-default-read-handler default-handler)))] (Reader. (.SetBuilders ^IReaderSpi reader (map-builder) (list-builder)))) (throw (ex-info "Type must be :json, :json-verbose or :msgpack" {:type type}))))) (defn read "Reads a value from a reader. Throws a RuntimeException when the reader's Stream is empty." [^Reader reader] (.Read ^IReader (.r reader))) (defn record-write-handler "Creates a IWriteHandler for a record type" [^Type type] (reify IWriteHandler (Tag [_ _] (.get_FullName type)) (Representation [_ rec] (tagged-value "map" rec)) (StringRepresentation [_ _] nil) (GetVerboseHandler [_] nil))) (defn record-write-handlers "Creates a map of record types to IWriteHandlers" [& types] (reduce (fn [h t] (assoc h t (record-write-handler t))) {} types)) (defn record-read-handler "Creates a ReadHandler for a record type" [^Type type] (let [type-name (map #(str/replace % "_" "-") (str/split (.get_FullName type) #"\.")) map-ctor (-> (str (str/join "." (butlast type-name)) "/map->" (last type-name)) symbol resolve)] (reify IReadHandler (FromRepresentation [_ m] (map-ctor m))))) (defn record-read-handlers "Creates a map of record type tags to ReadHandlers" [& types] (reduce (fn [d ^Type t] (assoc d (.get_FullName t) (record-read-handler t))) {} types)) (defn read-handler-map "Returns a HandlerMapContainer containing a ReadHandlerMap containing all the default handlers for Clojure and Java and any custom handlers that you supply, letting you store the return value and pass it to multiple invocations of reader. This can be more efficient than repeatedly handing the same raw map of tags -> custom handlers to reader." [custom-handlers] (HandlerMapContainer. (TransitFactory/ReadHandlerMap (merge default-read-handlers custom-handlers)))) (defn write-handler-map "Returns a HandlerMapContainer containing a WriteHandlerMap containing all the default handlers for Clojure and Java and any custom handlers that you supply, letting you store the return value and pass it to multiple invocations of writer. This can be more efficient than repeatedly handing the same raw map of types -> custom handlers to writer." [custom-handlers] (HandlerMapContainer. (TransitFactory/WriteHandlerMap (merge default-write-handlers custom-handlers)))) (defn write-meta "For :transform. Will write any metadata present on the value." [x] (if (instance? clojure.lang.IObj x) (if-let [m (meta x)] (WithMeta. (with-meta x nil) m) x) x)) (comment (require 'sellars.transit) (in-ns 'sellars.transit) (import [java.io File ByteArrayStream ByteArrayStream StreamWriter]) (def out (ByteArrayStream. 2000)) (def w (writer out :json)) (def w (writer out :json-verbose)) (def w (writer out :msgpack)) (def w (writer out :msgpack {:transform write-meta})) (def w (writer out :json {:transform write-meta})) (write w "foo") (write w 10) (write w [1 2 3]) (write w (with-meta [1 2 3] {:foo 'bar})) (String. (.toByteArray out)) (write w {:a-key 1 :b-key 2}) (write w {"a" "1" "b" "2"}) (write w {:a-key [1 2]}) (write w #{1 2}) (write w [{:a-key 1} {:a-key 2}]) (write w [#{1 2} #{1 2}]) (write w (int-array (range 10))) (write w {[:a :b] 2}) (write w [123N]) (write w 1/3) (write w {false 10 [] 20}) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json)) (def r (reader in :msgpack)) (def x (read r)) (meta x) (type (read r)) ;; extensibility (defrecord Point [x y]) (defrecord Circle [c r]) (def ext-write-handlers {Point (write-handler "point" (fn [p] [(.x p) (.y p)])) Circle (write-handler "circle" (fn [c] [(.c c) (.r c)]))}) (def ext-read-handlers {"point" (read-handler (fn [[x y]] (prn "making a point") (Point. x y))) "circle" (read-handler (fn [[c r]] (prn "making a circle") (Circle. c r)))}) (def ext-write-handlers (record-write-handlers Point Circle)) (def ext-read-handlers (record-read-handlers Point Circle)) (def out (ByteArrayStream. 2000)) (def w (writer out :json {:handlers ext-write-handlers})) (write w (Point. 10 20)) (write w (Circle. (Point. 10 20) 30)) (write w [(Point. 10 20) (Point. 20 40) (Point. 0 0)]) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json {:handlers ext-read-handlers})) (read r) ;; write and read handler maps (def custom-write-handler-map (write-handler-map ext-write-handlers)) (def custom-read-handler-map (read-handler-map ext-read-handlers)) (def out (ByteArrayStream. 2000)) (def w (writer out :json {:handlers custom-write-handler-map})) (write w (Point. 10 20)) (def in (ByteArrayStream. (.toByteArray out))) (def r (reader in :json {:handlers custom-read-handler-map})) (read r))
[ { "context": ";; Copyright 2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 31, "score": 0.9998859167098999, "start": 18, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright 2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 45, "score": 0.9999318718910217, "start": 33, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/continuo/postgresql/transaction.clj
niwinz/continuo
1
;; Copyright 2015 Andrey Antukh <niwi@niwi.nz> ;; ;; 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 continuo.postgresql.transaction (:require [clojure.edn :as edn] [cuerdas.core :as str] [suricatta.core :as sc] [taoensso.nippy :as nippy] [continuo.postgresql.attributes :as attrs] [continuo.impl :as impl] [continuo.util.template :as tmpl] [continuo.util.codecs :as codecs] [continuo.util.uuid :as uuid] [continuo.executor :as exec])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private ^:dynamic *max-retries* 1024) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Locks ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hold-exclusive-lock ([conn] (hold-exclusive-lock conn "txlog")) ([conn tablename] (as-> (format "LOCK TABLE %s IN ACCESS EXCLUSIVE MODE" tablename) sql (sc/execute conn sql)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Transactions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- current-attr-value "Get the current attribute value in the database. It returns `nil` in case of the attr does not has value." [conn [_ eid attr val]] (let [table (attrs/normalize-attrname attr "user") tmpl (str "SELECT * FROM {{table}} " " WHERE eid=?") eid (impl/-resolve-eid eid) sql (tmpl/render-string tmpl {:table table})] (sc/fetch-one conn [sql eid]))) (defmulti -apply-fact (fn [_ _ [type]] type)) (defmethod -apply-fact :db/add [conn txid [type eid attr val :as fact]] (let [table (attrs/normalize-attrname attr "user") eid (impl/-resolve-eid eid) current-value (current-attr-value conn fact)] (if current-value (do (when (not= current-value val) (let [tmpl (str "UPDATE {{table}} " " SET modified_at=current_timestamp, " " content=?, txid=?" " WHERE eid=?") sql (tmpl/render-string tmpl {:table table})] (sc/execute conn [sql val txid eid]))) eid) (let [tmpl (str "INSERT INTO {{table}} " " (eid, txid, modified_at, content)" " VALUES (?,?,current_timestamp,?)") sql1 (tmpl/render-string tmpl {:table table}) sql2 "INSERT INTO entity_attrs (eid, attr) VALUES (?, ?)"] (sc/execute conn [sql1 eid txid val]) (sc/execute conn [sql2 eid (pr-str attr)]) eid)))) (defmethod -apply-fact :db/retract [conn txid [type eid attr val]] (let [table (attrs/normalize-attrname attr "user") tmpl "DELETE FROM {{table}} WHERE eid = ? AND content = ?" sql (tmpl/render-string tmpl {:table table}) eid (impl/-resolve-eid eid) sqlv [sql eid val]] (when (pos? (sc/execute conn sqlv)) (let [sql (str "DELETE FROM entity_attrs" " WHERE eid=? AND attr=?")] (sc/execute conn [sql eid (pr-str attr)]))) nil)) (defn -apply-tx [conn txid facts] (let [sql (str "INSERT INTO txlog (id, facts, created_at) " " VALUES (?,?,current_timestamp)") facts (mapv #(update % 1 impl/-resolve-eid) facts) data (codecs/data->bytes facts)] (sc/execute conn [sql txid data]))) (defn get-next-txid "Get a next transaction identifier." [conn] (uuid/host-uuid)) (defn- run-transaction "Given an connection and seq of operation objects, execute them in serie." [conn facts] (sc/atomic conn (binding [impl/*eid-map* (volatile! {})] (let [txid (get-next-txid conn)] (-apply-tx conn txid facts) (let [ids (mapv #(-apply-fact conn txid %) facts)] (set (filterv identity ids))))))) (defn- is-serialization-failure? [error] (let [cause (.getCause error)] (and (instance? org.postgresql.util.PSQLException cause) (= (.getSQLState cause) "40001")))) (defn- try-transact [tx facts] (with-open [conn (impl/-get-connection tx)] (try [::ok (run-transaction conn facts)] (catch Exception e (if (is-serialization-failure? e) [::repeat e] [::error e]))))) (defn transact [tx facts] (let [tx-name (gensym "tx-") max-retries *max-retries*] (exec/submit #(loop [current-try 1] ;; (locking #'is-serialization-failure? ;; (println (format "Running a transaction %s, try %s of %s" ;; tx-name current-try (inc retries)))) (let [[state value] (try-transact tx facts)] (if (identical? state ::repeat) (if (<= current-try max-retries) (recur (inc current-try)) (throw value)) (if (identical? state ::error) (throw value) value))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Entity Retrieval ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- get-attributes [conn eid] (let [sql (str "SELECT attr FROM entity_attrs" " WHERE eid = ?")] (mapv (fn [record] (edn/read-string (:attr record))) (sc/fetch conn [sql eid])))) (defn- make-query-sql [attr] (let [table (attrs/normalize-attrname attr "user") tmpl (str "(SELECT eid, content FROM {{table}}" " WHERE eid=?)")] (tmpl/render-string tmpl {:table table}))) (defn columns-sql [attrs] (reduce (fn [acc [index attr]] (let [field (str "t" index ".content AS f" index)] (str acc ", " field))) "t0.eid" (map-indexed vector attrs))) (defn join-sql [attrs] (let [attrs (map-indexed vector attrs) [index attr] (first attrs) table (attrs/normalize-attrname attr "user") alias (str "t" index) tmpl (str "{{table}} AS {{alias}}") initial (tmpl/render-string tmpl {:table table :alias alias})] (reduce (fn [acc [index attr]] (let [table (attrs/normalize-attrname attr "user") alias (str "t" index) prevalias (str "t" (dec index)) tmpl (str " INNER JOIN {{table}} AS {{alias}}" " ON ({{prevalias}}.eid = {{alias}}.eid)")] (str acc (tmpl/render-string tmpl {:table table :alias alias :prevalias prevalias})))) initial (rest attrs)))) (defn get-entity [conn eid] (let [eid (impl/-resolve-eid eid) attrs (get-attributes conn eid) columns-sql (columns-sql attrs) join-sql (join-sql attrs) sqltmpl "SELECT {{columns}} FROM {{join}} WHERE t0.eid=?" sql (tmpl/render-string sqltmpl {:columns columns-sql :join join-sql}) result (sc/fetch-one conn [sql eid] {:format :row})] (loop [attrs attrs values (rest result) result {:eid eid}] (let [attr (first attrs) value (first values)] (if attr (recur (rest attrs) (rest values) (assoc result attr value)) result))))) (defn entity [tx eid] (exec/submit #(let [conn (impl/-get-connection tx)] (get-entity conn eid))))
85321
;; Copyright 2015 <NAME> <<EMAIL>> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns continuo.postgresql.transaction (:require [clojure.edn :as edn] [cuerdas.core :as str] [suricatta.core :as sc] [taoensso.nippy :as nippy] [continuo.postgresql.attributes :as attrs] [continuo.impl :as impl] [continuo.util.template :as tmpl] [continuo.util.codecs :as codecs] [continuo.util.uuid :as uuid] [continuo.executor :as exec])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private ^:dynamic *max-retries* 1024) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Locks ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hold-exclusive-lock ([conn] (hold-exclusive-lock conn "txlog")) ([conn tablename] (as-> (format "LOCK TABLE %s IN ACCESS EXCLUSIVE MODE" tablename) sql (sc/execute conn sql)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Transactions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- current-attr-value "Get the current attribute value in the database. It returns `nil` in case of the attr does not has value." [conn [_ eid attr val]] (let [table (attrs/normalize-attrname attr "user") tmpl (str "SELECT * FROM {{table}} " " WHERE eid=?") eid (impl/-resolve-eid eid) sql (tmpl/render-string tmpl {:table table})] (sc/fetch-one conn [sql eid]))) (defmulti -apply-fact (fn [_ _ [type]] type)) (defmethod -apply-fact :db/add [conn txid [type eid attr val :as fact]] (let [table (attrs/normalize-attrname attr "user") eid (impl/-resolve-eid eid) current-value (current-attr-value conn fact)] (if current-value (do (when (not= current-value val) (let [tmpl (str "UPDATE {{table}} " " SET modified_at=current_timestamp, " " content=?, txid=?" " WHERE eid=?") sql (tmpl/render-string tmpl {:table table})] (sc/execute conn [sql val txid eid]))) eid) (let [tmpl (str "INSERT INTO {{table}} " " (eid, txid, modified_at, content)" " VALUES (?,?,current_timestamp,?)") sql1 (tmpl/render-string tmpl {:table table}) sql2 "INSERT INTO entity_attrs (eid, attr) VALUES (?, ?)"] (sc/execute conn [sql1 eid txid val]) (sc/execute conn [sql2 eid (pr-str attr)]) eid)))) (defmethod -apply-fact :db/retract [conn txid [type eid attr val]] (let [table (attrs/normalize-attrname attr "user") tmpl "DELETE FROM {{table}} WHERE eid = ? AND content = ?" sql (tmpl/render-string tmpl {:table table}) eid (impl/-resolve-eid eid) sqlv [sql eid val]] (when (pos? (sc/execute conn sqlv)) (let [sql (str "DELETE FROM entity_attrs" " WHERE eid=? AND attr=?")] (sc/execute conn [sql eid (pr-str attr)]))) nil)) (defn -apply-tx [conn txid facts] (let [sql (str "INSERT INTO txlog (id, facts, created_at) " " VALUES (?,?,current_timestamp)") facts (mapv #(update % 1 impl/-resolve-eid) facts) data (codecs/data->bytes facts)] (sc/execute conn [sql txid data]))) (defn get-next-txid "Get a next transaction identifier." [conn] (uuid/host-uuid)) (defn- run-transaction "Given an connection and seq of operation objects, execute them in serie." [conn facts] (sc/atomic conn (binding [impl/*eid-map* (volatile! {})] (let [txid (get-next-txid conn)] (-apply-tx conn txid facts) (let [ids (mapv #(-apply-fact conn txid %) facts)] (set (filterv identity ids))))))) (defn- is-serialization-failure? [error] (let [cause (.getCause error)] (and (instance? org.postgresql.util.PSQLException cause) (= (.getSQLState cause) "40001")))) (defn- try-transact [tx facts] (with-open [conn (impl/-get-connection tx)] (try [::ok (run-transaction conn facts)] (catch Exception e (if (is-serialization-failure? e) [::repeat e] [::error e]))))) (defn transact [tx facts] (let [tx-name (gensym "tx-") max-retries *max-retries*] (exec/submit #(loop [current-try 1] ;; (locking #'is-serialization-failure? ;; (println (format "Running a transaction %s, try %s of %s" ;; tx-name current-try (inc retries)))) (let [[state value] (try-transact tx facts)] (if (identical? state ::repeat) (if (<= current-try max-retries) (recur (inc current-try)) (throw value)) (if (identical? state ::error) (throw value) value))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Entity Retrieval ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- get-attributes [conn eid] (let [sql (str "SELECT attr FROM entity_attrs" " WHERE eid = ?")] (mapv (fn [record] (edn/read-string (:attr record))) (sc/fetch conn [sql eid])))) (defn- make-query-sql [attr] (let [table (attrs/normalize-attrname attr "user") tmpl (str "(SELECT eid, content FROM {{table}}" " WHERE eid=?)")] (tmpl/render-string tmpl {:table table}))) (defn columns-sql [attrs] (reduce (fn [acc [index attr]] (let [field (str "t" index ".content AS f" index)] (str acc ", " field))) "t0.eid" (map-indexed vector attrs))) (defn join-sql [attrs] (let [attrs (map-indexed vector attrs) [index attr] (first attrs) table (attrs/normalize-attrname attr "user") alias (str "t" index) tmpl (str "{{table}} AS {{alias}}") initial (tmpl/render-string tmpl {:table table :alias alias})] (reduce (fn [acc [index attr]] (let [table (attrs/normalize-attrname attr "user") alias (str "t" index) prevalias (str "t" (dec index)) tmpl (str " INNER JOIN {{table}} AS {{alias}}" " ON ({{prevalias}}.eid = {{alias}}.eid)")] (str acc (tmpl/render-string tmpl {:table table :alias alias :prevalias prevalias})))) initial (rest attrs)))) (defn get-entity [conn eid] (let [eid (impl/-resolve-eid eid) attrs (get-attributes conn eid) columns-sql (columns-sql attrs) join-sql (join-sql attrs) sqltmpl "SELECT {{columns}} FROM {{join}} WHERE t0.eid=?" sql (tmpl/render-string sqltmpl {:columns columns-sql :join join-sql}) result (sc/fetch-one conn [sql eid] {:format :row})] (loop [attrs attrs values (rest result) result {:eid eid}] (let [attr (first attrs) value (first values)] (if attr (recur (rest attrs) (rest values) (assoc result attr value)) result))))) (defn entity [tx eid] (exec/submit #(let [conn (impl/-get-connection tx)] (get-entity conn eid))))
true
;; Copyright 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns continuo.postgresql.transaction (:require [clojure.edn :as edn] [cuerdas.core :as str] [suricatta.core :as sc] [taoensso.nippy :as nippy] [continuo.postgresql.attributes :as attrs] [continuo.impl :as impl] [continuo.util.template :as tmpl] [continuo.util.codecs :as codecs] [continuo.util.uuid :as uuid] [continuo.executor :as exec])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:private ^:dynamic *max-retries* 1024) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Locks ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn hold-exclusive-lock ([conn] (hold-exclusive-lock conn "txlog")) ([conn tablename] (as-> (format "LOCK TABLE %s IN ACCESS EXCLUSIVE MODE" tablename) sql (sc/execute conn sql)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Transactions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- current-attr-value "Get the current attribute value in the database. It returns `nil` in case of the attr does not has value." [conn [_ eid attr val]] (let [table (attrs/normalize-attrname attr "user") tmpl (str "SELECT * FROM {{table}} " " WHERE eid=?") eid (impl/-resolve-eid eid) sql (tmpl/render-string tmpl {:table table})] (sc/fetch-one conn [sql eid]))) (defmulti -apply-fact (fn [_ _ [type]] type)) (defmethod -apply-fact :db/add [conn txid [type eid attr val :as fact]] (let [table (attrs/normalize-attrname attr "user") eid (impl/-resolve-eid eid) current-value (current-attr-value conn fact)] (if current-value (do (when (not= current-value val) (let [tmpl (str "UPDATE {{table}} " " SET modified_at=current_timestamp, " " content=?, txid=?" " WHERE eid=?") sql (tmpl/render-string tmpl {:table table})] (sc/execute conn [sql val txid eid]))) eid) (let [tmpl (str "INSERT INTO {{table}} " " (eid, txid, modified_at, content)" " VALUES (?,?,current_timestamp,?)") sql1 (tmpl/render-string tmpl {:table table}) sql2 "INSERT INTO entity_attrs (eid, attr) VALUES (?, ?)"] (sc/execute conn [sql1 eid txid val]) (sc/execute conn [sql2 eid (pr-str attr)]) eid)))) (defmethod -apply-fact :db/retract [conn txid [type eid attr val]] (let [table (attrs/normalize-attrname attr "user") tmpl "DELETE FROM {{table}} WHERE eid = ? AND content = ?" sql (tmpl/render-string tmpl {:table table}) eid (impl/-resolve-eid eid) sqlv [sql eid val]] (when (pos? (sc/execute conn sqlv)) (let [sql (str "DELETE FROM entity_attrs" " WHERE eid=? AND attr=?")] (sc/execute conn [sql eid (pr-str attr)]))) nil)) (defn -apply-tx [conn txid facts] (let [sql (str "INSERT INTO txlog (id, facts, created_at) " " VALUES (?,?,current_timestamp)") facts (mapv #(update % 1 impl/-resolve-eid) facts) data (codecs/data->bytes facts)] (sc/execute conn [sql txid data]))) (defn get-next-txid "Get a next transaction identifier." [conn] (uuid/host-uuid)) (defn- run-transaction "Given an connection and seq of operation objects, execute them in serie." [conn facts] (sc/atomic conn (binding [impl/*eid-map* (volatile! {})] (let [txid (get-next-txid conn)] (-apply-tx conn txid facts) (let [ids (mapv #(-apply-fact conn txid %) facts)] (set (filterv identity ids))))))) (defn- is-serialization-failure? [error] (let [cause (.getCause error)] (and (instance? org.postgresql.util.PSQLException cause) (= (.getSQLState cause) "40001")))) (defn- try-transact [tx facts] (with-open [conn (impl/-get-connection tx)] (try [::ok (run-transaction conn facts)] (catch Exception e (if (is-serialization-failure? e) [::repeat e] [::error e]))))) (defn transact [tx facts] (let [tx-name (gensym "tx-") max-retries *max-retries*] (exec/submit #(loop [current-try 1] ;; (locking #'is-serialization-failure? ;; (println (format "Running a transaction %s, try %s of %s" ;; tx-name current-try (inc retries)))) (let [[state value] (try-transact tx facts)] (if (identical? state ::repeat) (if (<= current-try max-retries) (recur (inc current-try)) (throw value)) (if (identical? state ::error) (throw value) value))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Entity Retrieval ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- get-attributes [conn eid] (let [sql (str "SELECT attr FROM entity_attrs" " WHERE eid = ?")] (mapv (fn [record] (edn/read-string (:attr record))) (sc/fetch conn [sql eid])))) (defn- make-query-sql [attr] (let [table (attrs/normalize-attrname attr "user") tmpl (str "(SELECT eid, content FROM {{table}}" " WHERE eid=?)")] (tmpl/render-string tmpl {:table table}))) (defn columns-sql [attrs] (reduce (fn [acc [index attr]] (let [field (str "t" index ".content AS f" index)] (str acc ", " field))) "t0.eid" (map-indexed vector attrs))) (defn join-sql [attrs] (let [attrs (map-indexed vector attrs) [index attr] (first attrs) table (attrs/normalize-attrname attr "user") alias (str "t" index) tmpl (str "{{table}} AS {{alias}}") initial (tmpl/render-string tmpl {:table table :alias alias})] (reduce (fn [acc [index attr]] (let [table (attrs/normalize-attrname attr "user") alias (str "t" index) prevalias (str "t" (dec index)) tmpl (str " INNER JOIN {{table}} AS {{alias}}" " ON ({{prevalias}}.eid = {{alias}}.eid)")] (str acc (tmpl/render-string tmpl {:table table :alias alias :prevalias prevalias})))) initial (rest attrs)))) (defn get-entity [conn eid] (let [eid (impl/-resolve-eid eid) attrs (get-attributes conn eid) columns-sql (columns-sql attrs) join-sql (join-sql attrs) sqltmpl "SELECT {{columns}} FROM {{join}} WHERE t0.eid=?" sql (tmpl/render-string sqltmpl {:columns columns-sql :join join-sql}) result (sc/fetch-one conn [sql eid] {:format :row})] (loop [attrs attrs values (rest result) result {:eid eid}] (let [attr (first attrs) value (first values)] (if attr (recur (rest attrs) (rest values) (assoc result attr value)) result))))) (defn entity [tx eid] (exec/submit #(let [conn (impl/-get-connection tx)] (get-entity conn eid))))