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": "d \"tag\" :name \"extensible effect\"}\n {:lastName \"Peyton Jones\" :uuid \"f4ecaa79-5740-432e-82b4-519ba3e750e2\" :ki", "end": 406, "score": 0.9998796582221985, "start": 394, "tag": "NAME", "value": "Peyton Jones" }, { "context": "32e-82b4-519ba3e750e2\" :kind \"author\" :firstName \"Simon\"}\n {:lastName \"Kmett\" :uuid \"dedadd6d-8042-41d2", "end": 485, "score": 0.9992715120315552, "start": 480, "tag": "NAME", "value": "Simon" }, { "context": ":kind \"author\" :firstName \"Simon\"}\n {:lastName \"Kmett\" :uuid \"dedadd6d-8042-41d2-a4b5-21f43a36bf8f\" :ki", "end": 508, "score": 0.9998302459716797, "start": 503, "tag": "NAME", "value": "Kmett" }, { "context": "1d2-a4b5-21f43a36bf8f\" :kind \"author\" :firstName \"Edward\"}])\n\n(def search-result\n [{:uuid \"e1c02dec-2746-", "end": 588, "score": 0.9998217821121216, "start": 582, "tag": "NAME", "value": "Edward" }, { "context": "om/watch?v=re96UgMk6GQ\"\n :authors [{:lastName \"Peyton Jones\"\n\t :uuid \"f4ecaa79-5740-432e-82b4-519ba3e75", "end": 755, "score": 0.9998642802238464, "start": 743, "tag": "NAME", "value": "Peyton Jones" }, { "context": "-5740-432e-82b4-519ba3e750e2\"\n\t :firstName \"Simon\"}\n\t {:lastName \"Peyton Jones\"\n\t :uuid ", "end": 835, "score": 0.9993317127227783, "start": 830, "tag": "NAME", "value": "Simon" }, { "context": "2\"\n\t :firstName \"Simon\"}\n\t {:lastName \"Peyton Jones\"\n\t :uuid \"f4ecaa79-5740-432e-82b4-519ba3e75", "end": 869, "score": 0.9998753666877747, "start": 857, "tag": "NAME", "value": "Peyton Jones" }, { "context": "-5740-432e-82b4-519ba3e750e2\"\n\t :firstName \"Simon\"}]\n :title \"Escape from the ivory tower: the H", "end": 949, "score": 0.9988340139389038, "start": 944, "tag": "NAME", "value": "Simon" }, { "context": "\"\n :type \"Video\"\n :description \"In this talk Simon discusses Haskell’s birth and evolution, includin", "end": 1069, "score": 0.5052412152290344, "start": 1064, "tag": "NAME", "value": "Simon" }, { "context": "om/watch?v=6COvD8oynmI\"\n :authors [{:lastName \"Peyton Jones\"\n\t :uuid \"f4ecaa79-5740-432e-82b4-519ba3e75", "end": 1406, "score": 0.9998618364334106, "start": 1394, "tag": "NAME", "value": "Peyton Jones" }, { "context": "-5740-432e-82b4-519ba3e750e2\"\n\t :firstName \"Simon\"}]\n :title \"Adventure with Types in Haskell\"\n ", "end": 1486, "score": 0.9992437958717346, "start": 1481, "tag": "NAME", "value": "Simon" }, { "context": "om/watch?v=6COvD8oynmI\"\n :authors [{:lastName \"Peyton Jones\"\n\t :uuid \"f4ecaa79-5740-432e-82b4-519ba3e75", "end": 1813, "score": 0.9998685717582703, "start": 1801, "tag": "NAME", "value": "Peyton Jones" }, { "context": "-5740-432e-82b4-519ba3e750e2\"\n\t :firstName \"Simon\"}]\n :title \"Adventure with Types in Haskell\"\n ", "end": 1893, "score": 0.991616427898407, "start": 1888, "tag": "NAME", "value": "Simon" }, { "context": "om/watch?v=6COvD8oynmI\"\n :authors [{:lastName \"Peyton Jones\"\n\t :uuid \"f4ecaa79-5740-432e-82b4-519ba3e75", "end": 2220, "score": 0.999856173992157, "start": 2208, "tag": "NAME", "value": "Peyton Jones" }, { "context": "-5740-432e-82b4-519ba3e750e2\"\n\t :firstName \"Simon\"}]\n :title \"Adventure with Types in Haskell\"\n ", "end": 2300, "score": 0.9961860179901123, "start": 2295, "tag": "NAME", "value": "Simon" }, { "context": "om/watch?v=6COvD8oynmI\"\n :authors [{:lastName \"Peyton Jones\"\n\t :uuid \"f4ecaa79-5740-432e-82b4-519ba3e75", "end": 2626, "score": 0.9998701214790344, "start": 2614, "tag": "NAME", "value": "Peyton Jones" }, { "context": "-5740-432e-82b4-519ba3e750e2\"\n\t :firstName \"Simon\"}]\n :title \"Adventure with Types in Haskell\"\n ", "end": 2706, "score": 0.9998066425323486, "start": 2701, "tag": "NAME", "value": "Simon" }, { "context": "om/watch?v=6COvD8oynmI\"\n :authors [{:lastName \"Peyton Jones\"\n\t :uuid \"f4ecaa79-5740-432e-82b4-519ba3e75", "end": 3033, "score": 0.9998729825019836, "start": 3021, "tag": "NAME", "value": "Peyton Jones" }, { "context": "-5740-432e-82b4-519ba3e750e2\"\n\t :firstName \"Simon\"}]\n :title \"Adventure with Types in Haskell\"\n ", "end": 3113, "score": 0.9996318817138672, "start": 3108, "tag": "NAME", "value": "Simon" }, { "context": "1-953b-4870-aa60-46db2b661275\" :author/firstName \"Simon\" :author/lastName \"Peyton Jones\"\n :author/fullNam", "end": 3526, "score": 0.9996147155761719, "start": 3521, "tag": "NAME", "value": "Simon" }, { "context": "1275\" :author/firstName \"Simon\" :author/lastName \"Peyton Jones\"\n :author/fullName \"Simon Peyton Jones\"} {:db/id ", "end": 3558, "score": 0.9998835325241089, "start": 3546, "tag": "NAME", "value": "Peyton Jones" }, { "context": "author/lastName \"Peyton Jones\"\n :author/fullName \"Simon Peyton Jones\"} {:db/id \"Video\"\n :item-type :Video} {:item/uuid", "end": 3597, "score": 0.9998816251754761, "start": 3579, "tag": "NAME", "value": "Simon Peyton Jones" }, { "context": ":00:00.000-00:00\"\n :item/description \"In this talk Simon discusses Haskell’s birth and evolution\n includin", "end": 3987, "score": 0.9163271188735962, "start": 3982, "tag": "NAME", "value": "Simon" }, { "context": "-8c85-45b2-9e86-685af4b9be39\"\n :author/firstName \"Jasper\"\n :author/lastName \"Van der Jeugt\"\n :author/fullN", "end": 4851, "score": 0.9998691082000732, "start": 4845, "tag": "NAME", "value": "Jasper" }, { "context": "9\"\n :author/firstName \"Jasper\"\n :author/lastName \"Van der Jeugt\"\n :author/fullName \"Jasper Van der Jeugt\"} {:db/i", "end": 4885, "score": 0.9998774528503418, "start": 4872, "tag": "NAME", "value": "Van der Jeugt" }, { "context": "uthor/lastName \"Van der Jeugt\"\n :author/fullName \"Jasper Van der Jeugt\"} {:db/id \"Tutorial\"\n :item-type :Tutorial} {:ite", "end": 4926, "score": 0.9998763799667358, "start": 4906, "tag": "NAME", "value": "Jasper Van der Jeugt" }, { "context": "-6817-4899-b1cb-912940308596\"\n :author/firstName \"Joe\"\n :author/lastName \"Nelson\"\n :author/fullName \"Jo", "end": 5706, "score": 0.9998763799667358, "start": 5703, "tag": "NAME", "value": "Joe" }, { "context": "8596\"\n :author/firstName \"Joe\"\n :author/lastName \"Nelson\"\n :author/fullName \"Joe Nelson\"} {:item/uuid \"c2e", "end": 5733, "score": 0.9998854994773865, "start": 5727, "tag": "NAME", "value": "Nelson" }, { "context": "oe\"\n :author/lastName \"Nelson\"\n :author/fullName \"Joe Nelson\"} {:item/uuid \"c2e53ed0-06ab-45d8-a1e5-ef63ad1cfa", "end": 5764, "score": 0.9998704195022583, "start": 5754, "tag": "NAME", "value": "Joe Nelson" }, { "context": "-a0c8-46fe-b21f-07be119985cb\"\n :author/firstName \"Gabriel\"\n :author/lastName \"Gonzales\"\n :author/fullName \"", "end": 6643, "score": 0.999853789806366, "start": 6636, "tag": "NAME", "value": "Gabriel" }, { "context": "\"\n :author/firstName \"Gabriel\"\n :author/lastName \"Gonzales\"\n :author/fullName \"Gabriel Gonzales\"} {:item/uui", "end": 6672, "score": 0.999875009059906, "start": 6664, "tag": "NAME", "value": "Gonzales" }, { "context": "\"\n :author/lastName \"Gonzales\"\n :author/fullName \"Gabriel Gonzales\"} {:item/uuid \"00600f4f-3e9d-494a-a221-94981318e5", "end": 6709, "score": 0.9998804926872253, "start": 6693, "tag": "NAME", "value": "Gabriel Gonzales" }, { "context": "-395f-4b69-8597-6a37afb73c58\"\n :author/firstName \"Artyom\"\n :author/lastName \"Kazak\"\n :author/fullName \"Art", "end": 7139, "score": 0.9998686909675598, "start": 7133, "tag": "NAME", "value": "Artyom" }, { "context": "8\"\n :author/firstName \"Artyom\"\n :author/lastName \"Kazak\"\n :author/fullName \"Artyom Kazak\"} {:item/uuid \"b", "end": 7165, "score": 0.9998589158058167, "start": 7160, "tag": "NAME", "value": "Kazak" }, { "context": "yom\"\n :author/lastName \"Kazak\"\n :author/fullName \"Artyom Kazak\"} {:item/uuid \"b839544e-ca98-442e-90e4-52b5e999f3", "end": 7198, "score": 0.9998822808265686, "start": 7186, "tag": "NAME", "value": "Artyom Kazak" }, { "context": "-9509-42cc-b78f-4948403ead77\"\n :author/firstName \"Aditya\"\n :author/lastName \"Bhargava\"\n :author/fullName \"", "end": 9051, "score": 0.9998671412467957, "start": 9045, "tag": "NAME", "value": "Aditya" }, { "context": "7\"\n :author/firstName \"Aditya\"\n :author/lastName \"Bhargava\"\n :author/fullName \"Aditya Bhargava\"} {:db/id \"Ar", "end": 9080, "score": 0.9998846054077148, "start": 9072, "tag": "NAME", "value": "Bhargava" }, { "context": "\"\n :author/lastName \"Bhargava\"\n :author/fullName \"Aditya Bhargava\"} {:db/id \"Article\"\n :item-type :Article} {:item/", "end": 9116, "score": 0.9998637437820435, "start": 9101, "tag": "NAME", "value": "Aditya Bhargava" } ]
frontend/src/haskell_bazaar_frontend/stubs.cljs
Chouffe/haskell-bazaar
23
(ns haskell-bazaar-frontend.stubs) (def keywords [{:kind "tag" :name "type class"} {:kind "tag" :name "functor"} {:kind "tag" :name "applicative"} {:kind "tag" :name "monad"} {:kind "tag" :name "category theory"} {:kind "tag" :name "type inference"} {:kind "tag" :name "free monad"} {:kind "tag" :name "effect"} {:kind "tag" :name "extensible effect"} {:lastName "Peyton Jones" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :kind "author" :firstName "Simon"} {:lastName "Kmett" :uuid "dedadd6d-8042-41d2-a4b5-21f43a36bf8f" :kind "author" :firstName "Edward"}]) (def search-result [{:uuid "e1c02dec-2746-4a9c-a591-95c970f57ce6" :url "https://www.youtube.com/watch?v=re96UgMk6GQ" :authors [{:lastName "Peyton Jones" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "Simon"} {:lastName "Peyton Jones" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "Simon"}] :title "Escape from the ivory tower: the Haskell journey" :type "Video" :description "In this talk Simon discusses Haskell’s birth and evolution, including some of the research and engineering challenges he faced in design and implementation." :tags [{:name "monad"} {:name "type class"}]} {:uuid "2dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "Peyton Jones" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "Simon"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "3dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "Peyton Jones" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "Simon"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "4dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "Peyton Jones" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "Simon"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "fdab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "Peyton Jones" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "Simon"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "5dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "Peyton Jones" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "Simon"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]}]) (def ds-facts [{:db/id "monad" :tag/name "monad"} {:db/id "type class" :tag/name "type class"} {:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275" :author/uuid "ed6cc7d1-953b-4870-aa60-46db2b661275" :author/firstName "Simon" :author/lastName "Peyton Jones" :author/fullName "Simon Peyton Jones"} {:db/id "Video" :item-type :Video} {:item/uuid "30bd0a31-6622-4a4f-8fdf-ea9790353ff2" :item/authors [{:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"} {:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"}] :item/title "Escape from the ivory tower: the Haskell journey" :item/type {:db/id "Video"} :item/created-at #inst "2017-03-01T00:00:00.000-00:00" :item/description "In this talk Simon discusses Haskell’s birth and evolution including some of the research and engineering challenges he faced in design and implementation." :item/tags [{:db/id "monad"} {:db/id "type class"}]} {:db/id "type inference" :tag/name "type inference"} {:item/uuid "d4764fe6-862c-4943-841b-0998ccaa9966" :item/authors [{:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"}] :item/title "Adventure with Types in Haskell" :item/type {:db/id "Video"} :item/created-at #inst "2013-07-01T00:00:00.000-00:00" :item/description "Recorded at Oregon Programming Languages Summer School 2013" :item/tags [{:db/id "type inference"}]} {:db/id "dependency injection" :tag/name "dependency injection"} {:db/id "design pattern" :tag/name "design pattern"} {:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39" :author/uuid "be27fae0-8c85-45b2-9e86-685af4b9be39" :author/firstName "Jasper" :author/lastName "Van der Jeugt" :author/fullName "Jasper Van der Jeugt"} {:db/id "Tutorial" :item-type :Tutorial} {:item/uuid "f6af8441-5764-49da-b1a7-f13f4c1d14af" :item/authors [{:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39"} {:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39"}] :item/title "Haskell Design Patterns: The Handle Pattern" :item/type {:db/id "Tutorial"} :item/created-at #inst "2018-03-08T00:00:00.000-00:00" :item/description "A neat and simple way to build services in Haskell" :item/tags [{:db/id "dependency injection"} {:db/id "design pattern"}]} {:db/id "property based testing" :tag/name "property based testing"} {:db/id "testing" :tag/name "testing"} {:db/id "quickcheck" :tag/name "quickcheck"} {:db/id "0e612a56-6817-4899-b1cb-912940308596" :author/uuid "0e612a56-6817-4899-b1cb-912940308596" :author/firstName "Joe" :author/lastName "Nelson" :author/fullName "Joe Nelson"} {:item/uuid "c2e53ed0-06ab-45d8-a1e5-ef63ad1cfa9e" :item/authors [{:db/id "0e612a56-6817-4899-b1cb-912940308596"} {:db/id "0e612a56-6817-4899-b1cb-912940308596"} {:db/id "0e612a56-6817-4899-b1cb-912940308596"}] :item/title "The Design and Use of QuickCheck" :item/type {:db/id "Tutorial"} :item/created-at #inst "2017-01-14T00:00:00.000-00:00" :item/description "QuickCheck is the grandfather of property-based testing libraries. Despite being imitated in over thirty languages the original implementation remains pre-eminent due to the type system and consistent logic of the Haskell language in which it is written." :item/tags [{:db/id "property based testing"} {:db/id "testing"} {:db/id "quickcheck"}]} {:db/id "lens" :tag/name "lens"} {:db/id "df5c3cd7-a0c8-46fe-b21f-07be119985cb" :author/uuid "df5c3cd7-a0c8-46fe-b21f-07be119985cb" :author/firstName "Gabriel" :author/lastName "Gonzales" :author/fullName "Gabriel Gonzales"} {:item/uuid "00600f4f-3e9d-494a-a221-94981318e5aa" :item/authors [{:db/id "df5c3cd7-a0c8-46fe-b21f-07be119985cb"}] :item/title "Lenses" :item/type {:db/id "Tutorial"} :item/created-at #inst "2012-01-28T00:00:00.000-00:00" :item/description "Lens tour and tutorial" :item/tags [{:db/id "lens"}]} {:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58" :author/uuid "b13d3c75-395f-4b69-8597-6a37afb73c58" :author/firstName "Artyom" :author/lastName "Kazak" :author/fullName "Artyom Kazak"} {:item/uuid "b839544e-ca98-442e-90e4-52b5e999f3d2" :item/authors [{:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"}] :item/title "Lens Over Tea #1" :item/type {:db/id "Tutorial"} :item/created-at #inst "2016-01-01T00:00:00.000-00:00" :item/description "lenses 101 traversals 101 and some implementation details" :item/tags [{:db/id "lens"}]} {:db/id "traversal" :tag/name "traversal"} {:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5" :author/uuid "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5" :author/firstName "Haskell" :author/lastName "WikiBook" :author/fullName "Haskell WikiBook"} {:db/id "Book" :item-type :Book} {:item/uuid "612d20a2-e5ec-4e78-aca9-9e5e3e87b430" :item/authors [{:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5"} {:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5"}] :item/title "Lenses and functional references" :item/type {:db/id "Book"} :item/created-at #inst "2018-06-19T00:00:00.000-00:00" :item/description "This chapter is about functional references. By \"references\" we mean they point at parts of values allowing us to access and modify them. By \"functional\" we mean they do so in a way that provides the flexibility and composability we came to expect from functions. We will study functional references as implemented by the powerful lens library. lens is named after lenses a particularly well known kind of functional reference. Beyond being very interesting from a conceptual point of view lenses and other functional references allow for several convenient and increasingly common idioms put into use by a number of useful libraries." :item/tags [{:db/id "traversal"} {:db/id "lens"}]} {:db/id "applicative" :tag/name "applicative"} {:db/id "functor" :tag/name "functor"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77" :author/uuid "fdbaf717-9509-42cc-b78f-4948403ead77" :author/firstName "Aditya" :author/lastName "Bhargava" :author/fullName "Aditya Bhargava"} {:db/id "Article" :item-type :Article} {:item/uuid "32bc182c-352c-431b-8bfe-71c9a5c3c6d0" :item/authors [{:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"}] :item/title "Functors Applicatives And Monads In Pictures" :item/type {:db/id "Article"} :item/created-at #inst "2013-04-17T00:00:00.000-00:00" :item/description "Visualize functors applicative and monads with pictures" :item/tags [{:db/id "monad"} {:db/id "applicative"} {:db/id "functor"}]} {:db/id "aeson" :tag/name "aeson"} {:db/id "json" :tag/name "json"} {:item/uuid "0dc0b65d-8690-41e7-afae-39089aab5e61" :item/authors [{:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"} {:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"}] :item/title "Aeson: the tutorial" :item/type {:db/id "Tutorial"} :item/created-at #inst "2016-01-01T00:00:00.000-00:00" :item/description "Aeson is the most widely used library for parsing JSON (in Haskell of course I'm not talking about the whole world). It's also hopelessly magical for people who try to learn it by looking at provided examples and existing tutorials don't help that much so I wrote my own. It's supposed to be the most comprehensive Aeson tutorial on the web; if there's anything missing from it send me an email! (So far the only thing I haven't covered is using lenses with Aeson but this is coming soon.)" :item/tags [{:db/id "aeson"} {:db/id "json"}]}])
54829
(ns haskell-bazaar-frontend.stubs) (def keywords [{:kind "tag" :name "type class"} {:kind "tag" :name "functor"} {:kind "tag" :name "applicative"} {:kind "tag" :name "monad"} {:kind "tag" :name "category theory"} {:kind "tag" :name "type inference"} {:kind "tag" :name "free monad"} {:kind "tag" :name "effect"} {:kind "tag" :name "extensible effect"} {:lastName "<NAME>" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :kind "author" :firstName "<NAME>"} {:lastName "<NAME>" :uuid "dedadd6d-8042-41d2-a4b5-21f43a36bf8f" :kind "author" :firstName "<NAME>"}]) (def search-result [{:uuid "e1c02dec-2746-4a9c-a591-95c970f57ce6" :url "https://www.youtube.com/watch?v=re96UgMk6GQ" :authors [{:lastName "<NAME>" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "<NAME>"} {:lastName "<NAME>" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "<NAME>"}] :title "Escape from the ivory tower: the Haskell journey" :type "Video" :description "In this talk <NAME> discusses Haskell’s birth and evolution, including some of the research and engineering challenges he faced in design and implementation." :tags [{:name "monad"} {:name "type class"}]} {:uuid "2dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "<NAME>" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "<NAME>"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "3dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "<NAME>" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "<NAME>"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "4dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "<NAME>" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "<NAME>"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "fdab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "<NAME>" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "<NAME>"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "5dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "<NAME>" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "<NAME>"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]}]) (def ds-facts [{:db/id "monad" :tag/name "monad"} {:db/id "type class" :tag/name "type class"} {:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275" :author/uuid "ed6cc7d1-953b-4870-aa60-46db2b661275" :author/firstName "<NAME>" :author/lastName "<NAME>" :author/fullName "<NAME>"} {:db/id "Video" :item-type :Video} {:item/uuid "30bd0a31-6622-4a4f-8fdf-ea9790353ff2" :item/authors [{:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"} {:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"}] :item/title "Escape from the ivory tower: the Haskell journey" :item/type {:db/id "Video"} :item/created-at #inst "2017-03-01T00:00:00.000-00:00" :item/description "In this talk <NAME> discusses Haskell’s birth and evolution including some of the research and engineering challenges he faced in design and implementation." :item/tags [{:db/id "monad"} {:db/id "type class"}]} {:db/id "type inference" :tag/name "type inference"} {:item/uuid "d4764fe6-862c-4943-841b-0998ccaa9966" :item/authors [{:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"}] :item/title "Adventure with Types in Haskell" :item/type {:db/id "Video"} :item/created-at #inst "2013-07-01T00:00:00.000-00:00" :item/description "Recorded at Oregon Programming Languages Summer School 2013" :item/tags [{:db/id "type inference"}]} {:db/id "dependency injection" :tag/name "dependency injection"} {:db/id "design pattern" :tag/name "design pattern"} {:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39" :author/uuid "be27fae0-8c85-45b2-9e86-685af4b9be39" :author/firstName "<NAME>" :author/lastName "<NAME>" :author/fullName "<NAME>"} {:db/id "Tutorial" :item-type :Tutorial} {:item/uuid "f6af8441-5764-49da-b1a7-f13f4c1d14af" :item/authors [{:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39"} {:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39"}] :item/title "Haskell Design Patterns: The Handle Pattern" :item/type {:db/id "Tutorial"} :item/created-at #inst "2018-03-08T00:00:00.000-00:00" :item/description "A neat and simple way to build services in Haskell" :item/tags [{:db/id "dependency injection"} {:db/id "design pattern"}]} {:db/id "property based testing" :tag/name "property based testing"} {:db/id "testing" :tag/name "testing"} {:db/id "quickcheck" :tag/name "quickcheck"} {:db/id "0e612a56-6817-4899-b1cb-912940308596" :author/uuid "0e612a56-6817-4899-b1cb-912940308596" :author/firstName "<NAME>" :author/lastName "<NAME>" :author/fullName "<NAME>"} {:item/uuid "c2e53ed0-06ab-45d8-a1e5-ef63ad1cfa9e" :item/authors [{:db/id "0e612a56-6817-4899-b1cb-912940308596"} {:db/id "0e612a56-6817-4899-b1cb-912940308596"} {:db/id "0e612a56-6817-4899-b1cb-912940308596"}] :item/title "The Design and Use of QuickCheck" :item/type {:db/id "Tutorial"} :item/created-at #inst "2017-01-14T00:00:00.000-00:00" :item/description "QuickCheck is the grandfather of property-based testing libraries. Despite being imitated in over thirty languages the original implementation remains pre-eminent due to the type system and consistent logic of the Haskell language in which it is written." :item/tags [{:db/id "property based testing"} {:db/id "testing"} {:db/id "quickcheck"}]} {:db/id "lens" :tag/name "lens"} {:db/id "df5c3cd7-a0c8-46fe-b21f-07be119985cb" :author/uuid "df5c3cd7-a0c8-46fe-b21f-07be119985cb" :author/firstName "<NAME>" :author/lastName "<NAME>" :author/fullName "<NAME>"} {:item/uuid "00600f4f-3e9d-494a-a221-94981318e5aa" :item/authors [{:db/id "df5c3cd7-a0c8-46fe-b21f-07be119985cb"}] :item/title "Lenses" :item/type {:db/id "Tutorial"} :item/created-at #inst "2012-01-28T00:00:00.000-00:00" :item/description "Lens tour and tutorial" :item/tags [{:db/id "lens"}]} {:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58" :author/uuid "b13d3c75-395f-4b69-8597-6a37afb73c58" :author/firstName "<NAME>" :author/lastName "<NAME>" :author/fullName "<NAME>"} {:item/uuid "b839544e-ca98-442e-90e4-52b5e999f3d2" :item/authors [{:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"}] :item/title "Lens Over Tea #1" :item/type {:db/id "Tutorial"} :item/created-at #inst "2016-01-01T00:00:00.000-00:00" :item/description "lenses 101 traversals 101 and some implementation details" :item/tags [{:db/id "lens"}]} {:db/id "traversal" :tag/name "traversal"} {:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5" :author/uuid "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5" :author/firstName "Haskell" :author/lastName "WikiBook" :author/fullName "Haskell WikiBook"} {:db/id "Book" :item-type :Book} {:item/uuid "612d20a2-e5ec-4e78-aca9-9e5e3e87b430" :item/authors [{:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5"} {:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5"}] :item/title "Lenses and functional references" :item/type {:db/id "Book"} :item/created-at #inst "2018-06-19T00:00:00.000-00:00" :item/description "This chapter is about functional references. By \"references\" we mean they point at parts of values allowing us to access and modify them. By \"functional\" we mean they do so in a way that provides the flexibility and composability we came to expect from functions. We will study functional references as implemented by the powerful lens library. lens is named after lenses a particularly well known kind of functional reference. Beyond being very interesting from a conceptual point of view lenses and other functional references allow for several convenient and increasingly common idioms put into use by a number of useful libraries." :item/tags [{:db/id "traversal"} {:db/id "lens"}]} {:db/id "applicative" :tag/name "applicative"} {:db/id "functor" :tag/name "functor"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77" :author/uuid "fdbaf717-9509-42cc-b78f-4948403ead77" :author/firstName "<NAME>" :author/lastName "<NAME>" :author/fullName "<NAME>"} {:db/id "Article" :item-type :Article} {:item/uuid "32bc182c-352c-431b-8bfe-71c9a5c3c6d0" :item/authors [{:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"}] :item/title "Functors Applicatives And Monads In Pictures" :item/type {:db/id "Article"} :item/created-at #inst "2013-04-17T00:00:00.000-00:00" :item/description "Visualize functors applicative and monads with pictures" :item/tags [{:db/id "monad"} {:db/id "applicative"} {:db/id "functor"}]} {:db/id "aeson" :tag/name "aeson"} {:db/id "json" :tag/name "json"} {:item/uuid "0dc0b65d-8690-41e7-afae-39089aab5e61" :item/authors [{:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"} {:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"}] :item/title "Aeson: the tutorial" :item/type {:db/id "Tutorial"} :item/created-at #inst "2016-01-01T00:00:00.000-00:00" :item/description "Aeson is the most widely used library for parsing JSON (in Haskell of course I'm not talking about the whole world). It's also hopelessly magical for people who try to learn it by looking at provided examples and existing tutorials don't help that much so I wrote my own. It's supposed to be the most comprehensive Aeson tutorial on the web; if there's anything missing from it send me an email! (So far the only thing I haven't covered is using lenses with Aeson but this is coming soon.)" :item/tags [{:db/id "aeson"} {:db/id "json"}]}])
true
(ns haskell-bazaar-frontend.stubs) (def keywords [{:kind "tag" :name "type class"} {:kind "tag" :name "functor"} {:kind "tag" :name "applicative"} {:kind "tag" :name "monad"} {:kind "tag" :name "category theory"} {:kind "tag" :name "type inference"} {:kind "tag" :name "free monad"} {:kind "tag" :name "effect"} {:kind "tag" :name "extensible effect"} {:lastName "PI:NAME:<NAME>END_PI" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :kind "author" :firstName "PI:NAME:<NAME>END_PI"} {:lastName "PI:NAME:<NAME>END_PI" :uuid "dedadd6d-8042-41d2-a4b5-21f43a36bf8f" :kind "author" :firstName "PI:NAME:<NAME>END_PI"}]) (def search-result [{:uuid "e1c02dec-2746-4a9c-a591-95c970f57ce6" :url "https://www.youtube.com/watch?v=re96UgMk6GQ" :authors [{:lastName "PI:NAME:<NAME>END_PI" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "PI:NAME:<NAME>END_PI"} {:lastName "PI:NAME:<NAME>END_PI" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "PI:NAME:<NAME>END_PI"}] :title "Escape from the ivory tower: the Haskell journey" :type "Video" :description "In this talk PI:NAME:<NAME>END_PI discusses Haskell’s birth and evolution, including some of the research and engineering challenges he faced in design and implementation." :tags [{:name "monad"} {:name "type class"}]} {:uuid "2dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "PI:NAME:<NAME>END_PI" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "PI:NAME:<NAME>END_PI"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "3dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "PI:NAME:<NAME>END_PI" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "PI:NAME:<NAME>END_PI"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "4dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "PI:NAME:<NAME>END_PI" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "PI:NAME:<NAME>END_PI"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "fdab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "PI:NAME:<NAME>END_PI" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "PI:NAME:<NAME>END_PI"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]} {:uuid "5dab10af-04cb-4112-bc3d-ea877d737e7c" :url "https://www.youtube.com/watch?v=6COvD8oynmI" :authors [{:lastName "PI:NAME:<NAME>END_PI" :uuid "f4ecaa79-5740-432e-82b4-519ba3e750e2" :firstName "PI:NAME:<NAME>END_PI"}] :title "Adventure with Types in Haskell" :type "Video" :description "Recorded at Oregon Programming Languages Summer School 2013" :tags [{:name "type inference"}]}]) (def ds-facts [{:db/id "monad" :tag/name "monad"} {:db/id "type class" :tag/name "type class"} {:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275" :author/uuid "ed6cc7d1-953b-4870-aa60-46db2b661275" :author/firstName "PI:NAME:<NAME>END_PI" :author/lastName "PI:NAME:<NAME>END_PI" :author/fullName "PI:NAME:<NAME>END_PI"} {:db/id "Video" :item-type :Video} {:item/uuid "30bd0a31-6622-4a4f-8fdf-ea9790353ff2" :item/authors [{:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"} {:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"}] :item/title "Escape from the ivory tower: the Haskell journey" :item/type {:db/id "Video"} :item/created-at #inst "2017-03-01T00:00:00.000-00:00" :item/description "In this talk PI:NAME:<NAME>END_PI discusses Haskell’s birth and evolution including some of the research and engineering challenges he faced in design and implementation." :item/tags [{:db/id "monad"} {:db/id "type class"}]} {:db/id "type inference" :tag/name "type inference"} {:item/uuid "d4764fe6-862c-4943-841b-0998ccaa9966" :item/authors [{:db/id "ed6cc7d1-953b-4870-aa60-46db2b661275"}] :item/title "Adventure with Types in Haskell" :item/type {:db/id "Video"} :item/created-at #inst "2013-07-01T00:00:00.000-00:00" :item/description "Recorded at Oregon Programming Languages Summer School 2013" :item/tags [{:db/id "type inference"}]} {:db/id "dependency injection" :tag/name "dependency injection"} {:db/id "design pattern" :tag/name "design pattern"} {:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39" :author/uuid "be27fae0-8c85-45b2-9e86-685af4b9be39" :author/firstName "PI:NAME:<NAME>END_PI" :author/lastName "PI:NAME:<NAME>END_PI" :author/fullName "PI:NAME:<NAME>END_PI"} {:db/id "Tutorial" :item-type :Tutorial} {:item/uuid "f6af8441-5764-49da-b1a7-f13f4c1d14af" :item/authors [{:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39"} {:db/id "be27fae0-8c85-45b2-9e86-685af4b9be39"}] :item/title "Haskell Design Patterns: The Handle Pattern" :item/type {:db/id "Tutorial"} :item/created-at #inst "2018-03-08T00:00:00.000-00:00" :item/description "A neat and simple way to build services in Haskell" :item/tags [{:db/id "dependency injection"} {:db/id "design pattern"}]} {:db/id "property based testing" :tag/name "property based testing"} {:db/id "testing" :tag/name "testing"} {:db/id "quickcheck" :tag/name "quickcheck"} {:db/id "0e612a56-6817-4899-b1cb-912940308596" :author/uuid "0e612a56-6817-4899-b1cb-912940308596" :author/firstName "PI:NAME:<NAME>END_PI" :author/lastName "PI:NAME:<NAME>END_PI" :author/fullName "PI:NAME:<NAME>END_PI"} {:item/uuid "c2e53ed0-06ab-45d8-a1e5-ef63ad1cfa9e" :item/authors [{:db/id "0e612a56-6817-4899-b1cb-912940308596"} {:db/id "0e612a56-6817-4899-b1cb-912940308596"} {:db/id "0e612a56-6817-4899-b1cb-912940308596"}] :item/title "The Design and Use of QuickCheck" :item/type {:db/id "Tutorial"} :item/created-at #inst "2017-01-14T00:00:00.000-00:00" :item/description "QuickCheck is the grandfather of property-based testing libraries. Despite being imitated in over thirty languages the original implementation remains pre-eminent due to the type system and consistent logic of the Haskell language in which it is written." :item/tags [{:db/id "property based testing"} {:db/id "testing"} {:db/id "quickcheck"}]} {:db/id "lens" :tag/name "lens"} {:db/id "df5c3cd7-a0c8-46fe-b21f-07be119985cb" :author/uuid "df5c3cd7-a0c8-46fe-b21f-07be119985cb" :author/firstName "PI:NAME:<NAME>END_PI" :author/lastName "PI:NAME:<NAME>END_PI" :author/fullName "PI:NAME:<NAME>END_PI"} {:item/uuid "00600f4f-3e9d-494a-a221-94981318e5aa" :item/authors [{:db/id "df5c3cd7-a0c8-46fe-b21f-07be119985cb"}] :item/title "Lenses" :item/type {:db/id "Tutorial"} :item/created-at #inst "2012-01-28T00:00:00.000-00:00" :item/description "Lens tour and tutorial" :item/tags [{:db/id "lens"}]} {:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58" :author/uuid "b13d3c75-395f-4b69-8597-6a37afb73c58" :author/firstName "PI:NAME:<NAME>END_PI" :author/lastName "PI:NAME:<NAME>END_PI" :author/fullName "PI:NAME:<NAME>END_PI"} {:item/uuid "b839544e-ca98-442e-90e4-52b5e999f3d2" :item/authors [{:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"}] :item/title "Lens Over Tea #1" :item/type {:db/id "Tutorial"} :item/created-at #inst "2016-01-01T00:00:00.000-00:00" :item/description "lenses 101 traversals 101 and some implementation details" :item/tags [{:db/id "lens"}]} {:db/id "traversal" :tag/name "traversal"} {:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5" :author/uuid "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5" :author/firstName "Haskell" :author/lastName "WikiBook" :author/fullName "Haskell WikiBook"} {:db/id "Book" :item-type :Book} {:item/uuid "612d20a2-e5ec-4e78-aca9-9e5e3e87b430" :item/authors [{:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5"} {:db/id "7613d49f-0fb4-4d92-a048-a4e0fa6a46c5"}] :item/title "Lenses and functional references" :item/type {:db/id "Book"} :item/created-at #inst "2018-06-19T00:00:00.000-00:00" :item/description "This chapter is about functional references. By \"references\" we mean they point at parts of values allowing us to access and modify them. By \"functional\" we mean they do so in a way that provides the flexibility and composability we came to expect from functions. We will study functional references as implemented by the powerful lens library. lens is named after lenses a particularly well known kind of functional reference. Beyond being very interesting from a conceptual point of view lenses and other functional references allow for several convenient and increasingly common idioms put into use by a number of useful libraries." :item/tags [{:db/id "traversal"} {:db/id "lens"}]} {:db/id "applicative" :tag/name "applicative"} {:db/id "functor" :tag/name "functor"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77" :author/uuid "fdbaf717-9509-42cc-b78f-4948403ead77" :author/firstName "PI:NAME:<NAME>END_PI" :author/lastName "PI:NAME:<NAME>END_PI" :author/fullName "PI:NAME:<NAME>END_PI"} {:db/id "Article" :item-type :Article} {:item/uuid "32bc182c-352c-431b-8bfe-71c9a5c3c6d0" :item/authors [{:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"} {:db/id "fdbaf717-9509-42cc-b78f-4948403ead77"}] :item/title "Functors Applicatives And Monads In Pictures" :item/type {:db/id "Article"} :item/created-at #inst "2013-04-17T00:00:00.000-00:00" :item/description "Visualize functors applicative and monads with pictures" :item/tags [{:db/id "monad"} {:db/id "applicative"} {:db/id "functor"}]} {:db/id "aeson" :tag/name "aeson"} {:db/id "json" :tag/name "json"} {:item/uuid "0dc0b65d-8690-41e7-afae-39089aab5e61" :item/authors [{:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"} {:db/id "b13d3c75-395f-4b69-8597-6a37afb73c58"}] :item/title "Aeson: the tutorial" :item/type {:db/id "Tutorial"} :item/created-at #inst "2016-01-01T00:00:00.000-00:00" :item/description "Aeson is the most widely used library for parsing JSON (in Haskell of course I'm not talking about the whole world). It's also hopelessly magical for people who try to learn it by looking at provided examples and existing tutorials don't help that much so I wrote my own. It's supposed to be the most comprehensive Aeson tutorial on the web; if there's anything missing from it send me an email! (So far the only thing I haven't covered is using lenses with Aeson but this is coming soon.)" :item/tags [{:db/id "aeson"} {:db/id "json"}]}])
[ { "context": "(ns cljnode.core\r\n #^{:authors [\"Maxim Molchanov <elzor.job@gmail.com>\",\r\n \"Duncan", "end": 51, "score": 0.9998540878295898, "start": 36, "tag": "NAME", "value": "Maxim Molchanov" }, { "context": " cljnode.core\r\n #^{:authors [\"Maxim Molchanov <elzor.job@gmail.com>\",\r\n \"Duncan McGreggor <oubiwann@", "end": 72, "score": 0.999932050704956, "start": 53, "tag": "EMAIL", "value": "elzor.job@gmail.com" }, { "context": "chanov <elzor.job@gmail.com>\",\r\n \"Duncan McGreggor <oubiwann@gmail.com>\"],\r\n :doc \"Node run po", "end": 111, "score": 0.999880313873291, "start": 95, "tag": "NAME", "value": "Duncan McGreggor" }, { "context": "gmail.com>\",\r\n \"Duncan McGreggor <oubiwann@gmail.com>\"],\r\n :doc \"Node run point\"}\r\n (:require", "end": 131, "score": 0.9999290704727173, "start": 113, "tag": "EMAIL", "value": "oubiwann@gmail.com" } ]
src/clj/cljnode/core.clj
J3T4R0/duplet-public
0
(ns cljnode.core #^{:authors ["Maxim Molchanov <elzor.job@gmail.com>", "Duncan McGreggor <oubiwann@gmail.com>"], :doc "Node run point"} (:require [clojure.tools.logging :as log] [cljnode.server :as cljnode]) (:gen-class)) (defn -main [& args] (log/info "Starting Clojure node ...") (cljnode/server (System/getProperty "node") (System/getProperty "mbox") (System/getProperty "cookie") (read-string (System/getProperty "epmd_port"))) (log/info "Stopping Clojure node ..."))
65100
(ns cljnode.core #^{:authors ["<NAME> <<EMAIL>>", "<NAME> <<EMAIL>>"], :doc "Node run point"} (:require [clojure.tools.logging :as log] [cljnode.server :as cljnode]) (:gen-class)) (defn -main [& args] (log/info "Starting Clojure node ...") (cljnode/server (System/getProperty "node") (System/getProperty "mbox") (System/getProperty "cookie") (read-string (System/getProperty "epmd_port"))) (log/info "Stopping Clojure node ..."))
true
(ns cljnode.core #^{:authors ["PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>", "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"], :doc "Node run point"} (:require [clojure.tools.logging :as log] [cljnode.server :as cljnode]) (:gen-class)) (defn -main [& args] (log/info "Starting Clojure node ...") (cljnode/server (System/getProperty "node") (System/getProperty "mbox") (System/getProperty "cookie") (read-string (System/getProperty "epmd_port"))) (log/info "Stopping Clojure node ..."))
[ { "context": "tils]))\n\n(t/deftest sort-like\n (t/is (= [{:name :pierre :points 10}\n {:name :ana :points 20}\n ", "end": 244, "score": 0.9966349601745605, "start": 238, "tag": "NAME", "value": "pierre" }, { "context": " {:name :ana :points 20}\n {:name :lola :points 5}]\n (sut/sort-like [{:name :pi", "end": 317, "score": 0.9295340776443481, "start": 313, "tag": "NAME", "value": "lola" }, { "context": "la :points 5}]\n (sut/sort-like [{:name :pierre}\n {:name :ana}\n ", "end": 371, "score": 0.9970064163208008, "start": 365, "tag": "NAME", "value": "pierre" }, { "context": "na :points 20}\n {:name :lola :points 5}\n {:name :pie", "end": 577, "score": 0.9152825474739075, "start": 573, "tag": "NAME", "value": "lola" }, { "context": "ola :points 5}\n {:name :pierre :points 10}]))))\n\n(t/deftest group-interleave\n (", "end": 630, "score": 0.9937222599983215, "start": 624, "tag": "NAME", "value": "pierre" } ]
test/capacity/utils_test.cljc
pierrel/capacity-planner
0
(ns capacity.utils-test (:require [capacity.utils :as sut] #?(:clj [clojure.test :as t] :cljs [cljs.test :as t :include-macros true])) (:use [capacity.test-utils])) (t/deftest sort-like (t/is (= [{:name :pierre :points 10} {:name :ana :points 20} {:name :lola :points 5}] (sut/sort-like [{:name :pierre} {:name :ana} {:name :lola}] :name [{:name :ana :points 20} {:name :lola :points 5} {:name :pierre :points 10}])))) (t/deftest group-interleave (are-equal sut/group-interleave [[1 2 3] [:a :b :c] ["a" "b" "c"]] [[1 :a "a"] [2 :b "b"] [3 :c "c"]] [(range) [:a :b :c :d]] [[0 :a] [1 :b] [2 :c] [3 :d]])) (t/deftest insert (are-equal sut/insert [1 2 '(1 2 3 4)] '(1 2 1 3 4) ['(3 4 5) 2 '(1 2 6 7)] '(1 2 (3 4 5) 6 7))) (t/deftest remove-from (are-equal sut/remove-from [[1 2 3 4] [0 1]] '(3 4) ['() '()] '() ['(0 1 2) [2]] '(0 1))) (t/deftest with-lookup (sut/with-lookup [l [:a :b :c]] (t/is (= true (get l :a))) (t/is (= false (get l :z false)))))
37409
(ns capacity.utils-test (:require [capacity.utils :as sut] #?(:clj [clojure.test :as t] :cljs [cljs.test :as t :include-macros true])) (:use [capacity.test-utils])) (t/deftest sort-like (t/is (= [{:name :<NAME> :points 10} {:name :ana :points 20} {:name :<NAME> :points 5}] (sut/sort-like [{:name :<NAME>} {:name :ana} {:name :lola}] :name [{:name :ana :points 20} {:name :<NAME> :points 5} {:name :<NAME> :points 10}])))) (t/deftest group-interleave (are-equal sut/group-interleave [[1 2 3] [:a :b :c] ["a" "b" "c"]] [[1 :a "a"] [2 :b "b"] [3 :c "c"]] [(range) [:a :b :c :d]] [[0 :a] [1 :b] [2 :c] [3 :d]])) (t/deftest insert (are-equal sut/insert [1 2 '(1 2 3 4)] '(1 2 1 3 4) ['(3 4 5) 2 '(1 2 6 7)] '(1 2 (3 4 5) 6 7))) (t/deftest remove-from (are-equal sut/remove-from [[1 2 3 4] [0 1]] '(3 4) ['() '()] '() ['(0 1 2) [2]] '(0 1))) (t/deftest with-lookup (sut/with-lookup [l [:a :b :c]] (t/is (= true (get l :a))) (t/is (= false (get l :z false)))))
true
(ns capacity.utils-test (:require [capacity.utils :as sut] #?(:clj [clojure.test :as t] :cljs [cljs.test :as t :include-macros true])) (:use [capacity.test-utils])) (t/deftest sort-like (t/is (= [{:name :PI:NAME:<NAME>END_PI :points 10} {:name :ana :points 20} {:name :PI:NAME:<NAME>END_PI :points 5}] (sut/sort-like [{:name :PI:NAME:<NAME>END_PI} {:name :ana} {:name :lola}] :name [{:name :ana :points 20} {:name :PI:NAME:<NAME>END_PI :points 5} {:name :PI:NAME:<NAME>END_PI :points 10}])))) (t/deftest group-interleave (are-equal sut/group-interleave [[1 2 3] [:a :b :c] ["a" "b" "c"]] [[1 :a "a"] [2 :b "b"] [3 :c "c"]] [(range) [:a :b :c :d]] [[0 :a] [1 :b] [2 :c] [3 :d]])) (t/deftest insert (are-equal sut/insert [1 2 '(1 2 3 4)] '(1 2 1 3 4) ['(3 4 5) 2 '(1 2 6 7)] '(1 2 (3 4 5) 6 7))) (t/deftest remove-from (are-equal sut/remove-from [[1 2 3 4] [0 1]] '(3 4) ['() '()] '() ['(0 1 2) [2]] '(0 1))) (t/deftest with-lookup (sut/with-lookup [l [:a :b :c]] (t/is (= true (get l :a))) (t/is (= false (get l :z false)))))
[ { "context": " (navigator/delete :user {:id \"thomas\"}))\n status (navigator/status result", "end": 1871, "score": 0.6471121907234192, "start": 1865, "tag": "USERNAME", "value": "thomas" }, { "context": "ces\n :users (create-user \"fred\")\n :users (create-user", "end": 2411, "score": 0.6776763200759888, "start": 2410, "tag": "USERNAME", "value": "f" }, { "context": "es\n :users (create-user \"fred\")\n :users (create-user \"s", "end": 2414, "score": 0.6498139500617981, "start": 2411, "tag": "NAME", "value": "red" }, { "context": "d\")\n :users (create-user \"sue\")\n :users (create-user \"m", "end": 2466, "score": 0.94675612449646, "start": 2463, "tag": "USERNAME", "value": "sue" }, { "context": "e\")\n :users (create-user \"mary\"))\n (json/resource->json))}", "end": 2519, "score": 0.8905042409896851, "start": 2515, "tag": "USERNAME", "value": "mary" }, { "context": ")]\n\n (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-prop", "end": 2868, "score": 0.9996218681335449, "start": 2864, "tag": "NAME", "value": "Fred" }, { "context": " (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property %", "end": 2874, "score": 0.9995702505111694, "start": 2871, "tag": "NAME", "value": "Sue" }, { "context": "is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property % :name)", "end": 2881, "score": 0.9997955560684204, "start": 2877, "tag": "NAME", "value": "Mary" }, { "context": "ces\n :users (create-user \"fred\")\n :users (create-user", "end": 3709, "score": 0.5066914558410645, "start": 3708, "tag": "USERNAME", "value": "f" }, { "context": "es\n :users (create-user \"fred\")\n :users (create-user \"s", "end": 3712, "score": 0.68425053358078, "start": 3709, "tag": "NAME", "value": "red" }, { "context": "d\")\n :users (create-user \"sue\")\n :users (create-user \"m", "end": 3764, "score": 0.9688169956207275, "start": 3761, "tag": "USERNAME", "value": "sue" }, { "context": "e\")\n :users (create-user \"mary\"))\n (json/resource->json))}", "end": 3817, "score": 0.922254204750061, "start": 3813, "tag": "USERNAME", "value": "mary" }, { "context": ")]\n\n (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-prop", "end": 4180, "score": 0.9998401403427124, "start": 4176, "tag": "NAME", "value": "Fred" }, { "context": " (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property %", "end": 4186, "score": 0.9995728731155396, "start": 4183, "tag": "NAME", "value": "Sue" }, { "context": "is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property % :name)", "end": 4193, "score": 0.9998290538787842, "start": 4189, "tag": "NAME", "value": "Mary" }, { "context": "ces\n :users (create-user \"fred\")\n :users (create-user \"s", "end": 4808, "score": 0.7839003801345825, "start": 4804, "tag": "NAME", "value": "fred" }, { "context": "d\")\n :users (create-user \"sue\"))\n (json/resource->json))}", "end": 4860, "score": 0.965316116809845, "start": 4857, "tag": "USERNAME", "value": "sue" }, { "context": ")]\n\n (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\"]\n (map #(hal/get-property % ", "end": 5282, "score": 0.999815821647644, "start": 5278, "tag": "NAME", "value": "Fred" }, { "context": " (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\"]\n (map #(hal/get-property % :name)", "end": 5288, "score": 0.9996731877326965, "start": 5285, "tag": "NAME", "value": "Sue" }, { "context": "ces\n :users (create-user \"fred\")\n :users (create-user \"s", "end": 5892, "score": 0.8184108734130859, "start": 5888, "tag": "NAME", "value": "fred" }, { "context": "d\")\n :users (create-user \"sue\")\n :users (create-user \"m", "end": 5944, "score": 0.985625147819519, "start": 5941, "tag": "USERNAME", "value": "sue" }, { "context": "e\")\n :users (create-user \"mary\"))\n (json/resource->json))}", "end": 5997, "score": 0.8778902292251587, "start": 5993, "tag": "NAME", "value": "mary" }, { "context": ")]\n\n (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-prop", "end": 6376, "score": 0.9997409582138062, "start": 6372, "tag": "NAME", "value": "Fred" }, { "context": " (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property %", "end": 6382, "score": 0.996471643447876, "start": 6379, "tag": "NAME", "value": "Sue" }, { "context": "is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property % :name)", "end": 6389, "score": 0.99944007396698, "start": 6385, "tag": "NAME", "value": "Mary" }, { "context": " (create-url base-url \"/users\")\n {:name \"Thomas\"}\n \"/users/thomas\")\n (stubs/on-ge", "end": 6723, "score": 0.9924207925796509, "start": 6717, "tag": "NAME", "value": "Thomas" }, { "context": "s/on-get\n (create-url base-url \"/users/thomas\")\n {:status 200\n :body (-> (", "end": 6820, "score": 0.5991120338439941, "start": 6816, "tag": "NAME", "value": "omas" }, { "context": ")\n (hal/add-property :name \"Thomas\")\n (json/resource->json))})", "end": 6958, "score": 0.9802731871604919, "start": 6952, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/post :users {:name \"Thomas\"}))\n status (navigator/status result)\n", "end": 7123, "score": 0.9951666593551636, "start": 7117, "tag": "NAME", "value": "Thomas" }, { "context": "lt)]\n\n (is (= 200 status))\n (is (= \"Thomas\" (hal/get-property new-user :name))))))\n\n (testi", "end": 7274, "score": 0.9075623750686646, "start": 7268, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/delete :user {:id \"thomas\"}))\n status (navigator/status resu", "end": 7738, "score": 0.9586436152458191, "start": 7736, "tag": "NAME", "value": "th" }, { "context": " (navigator/delete :user {:id \"thomas\"}))\n status (navigator/status result)]", "end": 7742, "score": 0.9755409359931946, "start": 7738, "tag": "NAME", "value": "omas" }, { "context": "rl base-url \"/users/thomas\")\n {:surname \"Svensson\"}\n \"/users/thomas\")\n (stubs/on-ge", "end": 8150, "score": 0.9981462359428406, "start": 8142, "tag": "NAME", "value": "Svensson" }, { "context": ")\n (hal/add-property :name \"Thomas\")\n (hal/add-property :surna", "end": 8385, "score": 0.9991532564163208, "start": 8379, "tag": "NAME", "value": "Thomas" }, { "context": " (hal/add-property :surname \"Svensson\")\n (json/resource->json))})", "end": 8447, "score": 0.9995603561401367, "start": 8439, "tag": "NAME", "value": "Svensson" }, { "context": " (navigator/patch :user {:id \"thomas\"} {:surname \"Svensson\"}))\n status (nav", "end": 8610, "score": 0.7763441801071167, "start": 8604, "tag": "NAME", "value": "thomas" }, { "context": " (navigator/patch :user {:id \"thomas\"} {:surname \"Svensson\"}))\n status (navigator/status result)\n", "end": 8632, "score": 0.9997389912605286, "start": 8624, "tag": "NAME", "value": "Svensson" }, { "context": "lt)]\n\n (is (= 200 status))\n (is (= \"Thomas\" (hal/get-property new-user :name)))\n (is ", "end": 8783, "score": 0.9991552829742432, "start": 8777, "tag": "NAME", "value": "Thomas" }, { "context": "al/get-property new-user :name)))\n (is (= \"Svensson\" (hal/get-property new-user :surname))))))\n\n (te", "end": 8845, "score": 0.9996944069862366, "start": 8837, "tag": "NAME", "value": "Svensson" }, { "context": " (create-url base-url \"/users\")\n {:name \"Thomas\"}\n \"/users/thomas\")\n (stubs/on-ge", "end": 9204, "score": 0.9862936735153198, "start": 9198, "tag": "NAME", "value": "Thomas" }, { "context": "rs\")\n {:name \"Thomas\"}\n \"/users/thomas\")\n (stubs/on-get\n (create-url", "end": 9227, "score": 0.8421838879585266, "start": 9225, "tag": "USERNAME", "value": "th" }, { "context": "\")\n {:name \"Thomas\"}\n \"/users/thomas\")\n (stubs/on-get\n (create-url bas", "end": 9231, "score": 0.7229945659637451, "start": 9227, "tag": "NAME", "value": "omas" }, { "context": "ubs/on-get\n (create-url base-url \"/users/thomas\")\n {:status 200\n :body (", "end": 9297, "score": 0.6538341045379639, "start": 9295, "tag": "NAME", "value": "th" }, { "context": "s/on-get\n (create-url base-url \"/users/thomas\")\n {:status 200\n :body (-> (", "end": 9301, "score": 0.9759624600410461, "start": 9297, "tag": "NAME", "value": "omas" }, { "context": " (hal/add-link :self \"/users/thomas\")\n (hal/add-property :name ", "end": 9426, "score": 0.9677268266677856, "start": 9422, "tag": "NAME", "value": "omas" }, { "context": ")\n (hal/add-property :name \"Thomas\")\n (json/resource->json))})", "end": 9483, "score": 0.9951887130737305, "start": 9477, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/post :users {:name \"Thomas\"}))\n status (navigator/status result)\n", "end": 9648, "score": 0.949081301689148, "start": 9642, "tag": "NAME", "value": "Thomas" }, { "context": "lt)]\n\n (is (= 200 status))\n (is (= \"Thomas\" (hal/get-property new-user :name))))))\n\n (testi", "end": 9799, "score": 0.9966239929199219, "start": 9793, "tag": "NAME", "value": "Thomas" }, { "context": "\n (create-url base-url \"/users\") {:name \"thomas\"}\n {:status 204}))\n (let [result (-", "end": 10132, "score": 0.8507084846496582, "start": 10126, "tag": "NAME", "value": "thomas" }, { "context": " (navigator/delete :users {:name \"thomas\"}))\n status (navigator/status resu", "end": 10272, "score": 0.9956718683242798, "start": 10270, "tag": "NAME", "value": "th" }, { "context": " (navigator/delete :users {:name \"thomas\"}))\n status (navigator/status result)]", "end": 10276, "score": 0.7732699513435364, "start": 10272, "tag": "NAME", "value": "omas" }, { "context": "t-redirect\n (create-url base-url \"/users/thomas/items\")\n {:name \"Sponge\"}\n ", "end": 10680, "score": 0.726041316986084, "start": 10678, "tag": "NAME", "value": "th" }, { "context": "redirect\n (create-url base-url \"/users/thomas/items\")\n {:name \"Sponge\"}\n \"/us", "end": 10684, "score": 0.8378206491470337, "start": 10680, "tag": "NAME", "value": "omas" }, { "context": "base-url \"/users/thomas/items\")\n {:name \"Sponge\"}\n \"/users/thomas/items/1\")\n (stu", "end": 10717, "score": 0.8337264060974121, "start": 10711, "tag": "NAME", "value": "Sponge" }, { "context": "ms\")\n {:name \"Sponge\"}\n \"/users/thomas/items/1\")\n (stubs/on-get\n (cr", "end": 10740, "score": 0.43571579456329346, "start": 10738, "tag": "NAME", "value": "th" }, { "context": "\")\n {:name \"Sponge\"}\n \"/users/thomas/items/1\")\n (stubs/on-get\n (create", "end": 10744, "score": 0.5182442665100098, "start": 10740, "tag": "NAME", "value": "omas" }, { "context": "ubs/on-get\n (create-url base-url \"/users/thomas/items/1\")\n {:status 200\n :", "end": 10818, "score": 0.5971518754959106, "start": 10816, "tag": "NAME", "value": "th" }, { "context": "s/on-get\n (create-url base-url \"/users/thomas/items/1\")\n {:status 200\n :body", "end": 10822, "score": 0.5672265291213989, "start": 10818, "tag": "NAME", "value": "omas" }, { "context": "\n :body (-> (hal/new-resource \"/users/thomas/items/1\")\n (hal/add-pro", "end": 10907, "score": 0.6124192476272583, "start": 10905, "tag": "NAME", "value": "th" }, { "context": " :body (-> (hal/new-resource \"/users/thomas/items/1\")\n (hal/add-propert", "end": 10911, "score": 0.5659016370773315, "start": 10907, "tag": "NAME", "value": "omas" }, { "context": " (navigator/post :useritems {:id \"thomas\"} {:name \"Sponge\"}))\n status (navi", "end": 11139, "score": 0.9388297200202942, "start": 11137, "tag": "NAME", "value": "th" }, { "context": " (navigator/post :useritems {:id \"thomas\"} {:name \"Sponge\"}))\n status (navigato", "end": 11143, "score": 0.4518710970878601, "start": 11139, "tag": "NAME", "value": "omas" }, { "context": "(navigator/post :useritems {:id \"thomas\"} {:name \"Sponge\"}))\n status (navigator/status result)\n", "end": 11160, "score": 0.8628010749816895, "start": 11154, "tag": "NAME", "value": "Sponge" }, { "context": " (create-url base-url \"/users\")\n {:name \"Thomas\"}\n {:status 400}))\n (let [status (-", "end": 11678, "score": 0.7764608860015869, "start": 11672, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/post :users {:name \"Thomas\"})\n (navigator/status))]\n ", "end": 11820, "score": 0.9345115423202515, "start": 11814, "tag": "NAME", "value": "Thomas" }, { "context": " (create-url base-url \"/users\")\n {:name \"Thomas\"}\n \"/users/thomas\"))\n (let [result ", "end": 12235, "score": 0.9728517532348633, "start": 12229, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/post :users {:name \"Thomas\"}))\n status (navigator/status result)]", "end": 12405, "score": 0.8822368383407593, "start": 12399, "tag": "NAME", "value": "Thomas" }, { "context": " (is (= 201 status))\n\n (is (= \"/users/thomas\"\n (navigator/get-header result ", "end": 12511, "score": 0.6346193552017212, "start": 12509, "tag": "USERNAME", "value": "th" }, { "context": " (create-url base-url \"/users\")\n {:name \"Thomas\"}\n \"/users/thomas\")\n (stubs/on-ge", "end": 12882, "score": 0.9974700212478638, "start": 12876, "tag": "NAME", "value": "Thomas" }, { "context": "rs\")\n {:name \"Thomas\"}\n \"/users/thomas\")\n (stubs/on-get\n (create-url bas", "end": 12909, "score": 0.8639366626739502, "start": 12903, "tag": "USERNAME", "value": "thomas" }, { "context": "ubs/on-get\n (create-url base-url \"/users/thomas\")\n {:status 200\n :body (", "end": 12975, "score": 0.6997644305229187, "start": 12973, "tag": "USERNAME", "value": "th" }, { "context": "s/on-get\n (create-url base-url \"/users/thomas\")\n {:status 200\n :body (-> (", "end": 12979, "score": 0.6342854499816895, "start": 12975, "tag": "NAME", "value": "omas" }, { "context": "\n :body (-> (hal/new-resource \"/users/thomas\")\n (hal/add-property :n", "end": 13056, "score": 0.5190649032592773, "start": 13054, "tag": "USERNAME", "value": "th" }, { "context": " :body (-> (hal/new-resource \"/users/thomas\")\n (hal/add-property :name ", "end": 13060, "score": 0.43408405780792236, "start": 13056, "tag": "NAME", "value": "omas" }, { "context": ")\n (hal/add-property :name \"Thomas\")\n (json/resource->json))})", "end": 13117, "score": 0.9910480976104736, "start": 13111, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/post :users {:name \"Thomas\"})\n (navigator/follow-redir", "end": 13308, "score": 0.99717116355896, "start": 13302, "tag": "NAME", "value": "Thomas" }, { "context": "lt)]\n\n (is (= 200 status))\n (is (= \"Thomas\" (hal/get-property new-user :name))))))\n\n (testi", "end": 13510, "score": 0.996071994304657, "start": 13504, "tag": "NAME", "value": "Thomas" }, { "context": " (create-url base-url \"/users\")\n {:name \"Thomas\"}\n {:status 201\n :headers {}}", "end": 13840, "score": 0.9929376840591431, "start": 13834, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/post :users {:name \"Thomas\"})\n (navigator/follow-redir", "end": 14078, "score": 0.995336651802063, "start": 14072, "tag": "NAME", "value": "Thomas" }, { "context": "ubs/on-put\n (create-url base-url \"/users/thomas\")\n {:name \"Thomas\"}\n {:stat", "end": 14408, "score": 0.40885522961616516, "start": 14406, "tag": "USERNAME", "value": "th" }, { "context": "e-url base-url \"/users/thomas\")\n {:name \"Thomas\"}\n {:status 200\n :body (-> (", "end": 14439, "score": 0.9841246604919434, "start": 14433, "tag": "NAME", "value": "Thomas" }, { "context": ")\n (hal/add-property :name \"Thomas\")\n (json/resource->json))})", "end": 14577, "score": 0.8449461460113525, "start": 14571, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/put :user {:id \"thomas\"} {:name \"Thomas\"}))\n status (navigato", "end": 14738, "score": 0.9474691152572632, "start": 14732, "tag": "NAME", "value": "thomas" }, { "context": " (navigator/put :user {:id \"thomas\"} {:name \"Thomas\"}))\n status (navigator/status result)\n", "end": 14755, "score": 0.9970899224281311, "start": 14749, "tag": "NAME", "value": "Thomas" }, { "context": "lt)]\n\n (is (= 200 status))\n (is (= \"Thomas\" (hal/get-property user :name))))))\n\n (testing \"", "end": 14902, "score": 0.9925029277801514, "start": 14896, "tag": "NAME", "value": "Thomas" }, { "context": "t-redirect\n (create-url base-url \"/users/thomas\")\n {:name \"Thomas\"}\n \"/user", "end": 15247, "score": 0.48824477195739746, "start": 15245, "tag": "USERNAME", "value": "th" }, { "context": "redirect\n (create-url base-url \"/users/thomas\")\n {:name \"Thomas\"}\n \"/users/th", "end": 15251, "score": 0.7445555329322815, "start": 15247, "tag": "NAME", "value": "omas" }, { "context": "e-url base-url \"/users/thomas\")\n {:name \"Thomas\"}\n \"/users/thomas\")\n (stubs/on-ge", "end": 15278, "score": 0.9951846599578857, "start": 15272, "tag": "NAME", "value": "Thomas" }, { "context": "\")\n {:name \"Thomas\"}\n \"/users/thomas\")\n (stubs/on-get\n (create-url bas", "end": 15305, "score": 0.4350690543651581, "start": 15301, "tag": "NAME", "value": "omas" }, { "context": "ubs/on-get\n (create-url base-url \"/users/thomas\")\n {:status 200\n :body (", "end": 15371, "score": 0.37034106254577637, "start": 15369, "tag": "NAME", "value": "th" }, { "context": "s/on-get\n (create-url base-url \"/users/thomas\")\n {:status 200\n :body (-> (", "end": 15375, "score": 0.7395898699760437, "start": 15371, "tag": "NAME", "value": "omas" }, { "context": " :body (-> (hal/new-resource \"/users/thomas\")\n (hal/add-property :name ", "end": 15456, "score": 0.7664724588394165, "start": 15452, "tag": "NAME", "value": "omas" }, { "context": ")\n (hal/add-property :name \"Thomas\")\n (json/resource->json))})", "end": 15513, "score": 0.9381202459335327, "start": 15507, "tag": "NAME", "value": "Thomas" }, { "context": " (navigator/put :user {:id \"thomas\"} {:name \"Thomas\"}))\n status (navigato", "end": 15674, "score": 0.9175035953521729, "start": 15668, "tag": "NAME", "value": "thomas" }, { "context": " (navigator/put :user {:id \"thomas\"} {:name \"Thomas\"}))\n status (navigator/status result)\n", "end": 15691, "score": 0.9957505464553833, "start": 15685, "tag": "NAME", "value": "Thomas" }, { "context": "lt)]\n\n (is (= 200 status))\n (is (= \"Thomas\" (hal/get-property user :name))))))\n\n (testing \"", "end": 15838, "score": 0.9232239127159119, "start": 15832, "tag": "NAME", "value": "Thomas" }, { "context": "bs/on-head\n (create-url base-url \"/users/thomas\")\n {:status 200}))\n (let [resul", "end": 16147, "score": 0.41816428303718567, "start": 16145, "tag": "NAME", "value": "th" }, { "context": "/on-head\n (create-url base-url \"/users/thomas\")\n {:status 200}))\n (let [result (-", "end": 16151, "score": 0.7303027510643005, "start": 16147, "tag": "NAME", "value": "omas" }, { "context": " (navigator/head :user {:id \"thomas\"}))\n status (navigator/status resu", "end": 16286, "score": 0.9058369994163513, "start": 16284, "tag": "NAME", "value": "th" }, { "context": " (navigator/head :user {:id \"thomas\"}))\n status (navigator/status result)]", "end": 16290, "score": 0.4455491006374359, "start": 16286, "tag": "NAME", "value": "omas" }, { "context": " (navigator/delete :user {:id \"thomas\"}))\n status (navigator/status re", "end": 17126, "score": 0.9007644653320312, "start": 17124, "tag": "NAME", "value": "th" }, { "context": " (navigator/delete :user {:id \"thomas\"}))\n status (navigator/status result", "end": 17130, "score": 0.6764199733734131, "start": 17126, "tag": "USERNAME", "value": "omas" }, { "context": "ource-location\" resource-url}\n {:name \"Thomas\"}\n {:status 201}))\n (let [r", "end": 17720, "score": 0.9996955990791321, "start": 17718, "tag": "NAME", "value": "Th" }, { "context": "rce-location\" resource-url}\n {:name \"Thomas\"}\n {:status 201}))\n (let [resul", "end": 17724, "score": 0.6716799139976501, "start": 17720, "tag": "NAME", "value": "omas" }, { "context": " (navigator/post :users {:name \"Thomas\"}))\n status (navigator/status re", "end": 17977, "score": 0.9996926784515381, "start": 17975, "tag": "NAME", "value": "Th" }, { "context": " (navigator/post :users {:name \"Thomas\"}))\n status (navigator/status result", "end": 17981, "score": 0.7242211699485779, "start": 17977, "tag": "NAME", "value": "omas" }, { "context": "rces\n :users [(create-user \"fred\")\n (create-user \"su", "end": 18360, "score": 0.9943740367889404, "start": 18356, "tag": "NAME", "value": "fred" }, { "context": "ed\")\n (create-user \"sue\")\n (create-user \"ma", "end": 18411, "score": 0.9948897361755371, "start": 18408, "tag": "NAME", "value": "sue" }, { "context": "ue\")\n (create-user \"mary\")])\n (json/resource->json))})", "end": 18463, "score": 0.9993263483047485, "start": 18459, "tag": "NAME", "value": "mary" }, { "context": ")]\n\n (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-prop", "end": 19002, "score": 0.9998329877853394, "start": 18998, "tag": "NAME", "value": "Fred" }, { "context": " (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property %", "end": 19008, "score": 0.999779462814331, "start": 19005, "tag": "NAME", "value": "Sue" }, { "context": "is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property % :name)", "end": 19015, "score": 0.9997783303260803, "start": 19011, "tag": "NAME", "value": "Mary" }, { "context": "rces\n :users [(create-user \"fred\")\n (create-user \"su", "end": 19404, "score": 0.9996437430381775, "start": 19400, "tag": "NAME", "value": "fred" }, { "context": "ed\")\n (create-user \"sue\")\n (create-user \"ma", "end": 19455, "score": 0.9989727735519409, "start": 19452, "tag": "NAME", "value": "sue" }, { "context": "ue\")\n (create-user \"mary\")])\n (json/resource->json))})", "end": 19507, "score": 0.99973464012146, "start": 19503, "tag": "NAME", "value": "mary" }, { "context": ")]\n\n (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-prop", "end": 20065, "score": 0.9998419880867004, "start": 20061, "tag": "NAME", "value": "Fred" }, { "context": " (is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property %", "end": 20071, "score": 0.9997893571853638, "start": 20068, "tag": "NAME", "value": "Sue" }, { "context": "is (= 200 status))\n\n (is (= [\"Fred\" \"Sue\" \"Mary\"]\n (map #(hal/get-property % :name)", "end": 20078, "score": 0.9997718930244446, "start": 20074, "tag": "NAME", "value": "Mary" } ]
test/halboy/navigator_test.clj
bamdadd/halboy
0
(ns halboy.navigator-test (:use org.httpkit.fake) (:require [clojure.test :refer :all] [clojure.string :refer [capitalize]] [halboy.navigator :as navigator] [halboy.resource :as hal] [halboy.json :as json] [halboy.support.api :as stubs] [halboy.resource :as hal]) (:import [java.net URL])) (def base-url "https://service.example.com") (defn- create-url [base-url resource] (-> (URL. base-url) (URL. resource) (.toString))) (defn- create-user [name] (-> (hal/new-resource) (hal/add-link :self {:href (create-url base-url (format "/users/%s" name))}) (hal/add-property :name (capitalize name)))) (deftest halboy-navigator (testing "should be able to retrieve the settings" (with-fake-http (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (let [options (-> (navigator/discover base-url) (navigator/settings))] (is (true? (:follow-redirects options))) (is (empty? (:headers options))) (is (not (nil? (:client options))))))) (testing "should be able to pass options to the HTTP client" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete-with-headers resource-url {"Content-Type" "application/json" "Accept" "application/hal+json" "My-Header" "some-value"} {:status 204})) (let [result (-> (navigator/discover base-url {:http {:headers {"My-Header" "some-value"}}}) (navigator/delete :user {:id "thomas"})) status (navigator/status result)] (is (= 204 status)))))) (testing "should be able to navigate through links in an API" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "fred") :users (create-user "sue") :users (create-user "mary")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["Fred" "Sue" "Mary"] (map #(hal/get-property % :name) users)))))) (testing "should throw an error when trying to get a link which does not exist" (with-fake-http (stubs/on-discover base-url) (is (thrown? clojure.lang.ExceptionInfo (-> (navigator/discover base-url) (navigator/get :users)))))) (testing "should be able to navigate through links with query params" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-get (create-url base-url "/users") {:admin "true"} {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "fred") :users (create-user "sue") :users (create-user "mary")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users {:admin true})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["Fred" "Sue" "Mary"] (map #(hal/get-property % :name) users)))))) (testing "should be able to navigate through links with multiple query params" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin,owner}" :templated true}) (stubs/on-get (create-url base-url "/users") {:admin "true" :owner "false"} {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "fred") :users (create-user "sue")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users {:admin true :owner false})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["Fred" "Sue"] (map #(hal/get-property % :name) users)))))) (testing "should be able to navigate with a mixture of template and query params" (with-fake-http (concat (stubs/on-discover base-url :friends {:href "/users/{id}/friends{?mutual}" :templated true}) (stubs/on-get (create-url base-url "/users/thomas/friends") {:mutual "true"} {:status 200 :body (-> (hal/new-resource "/users/thomas/friends") (hal/add-resources :users (create-user "fred") :users (create-user "sue") :users (create-user "mary")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :friends {:id "thomas" :mutual true})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["Fred" "Sue" "Mary"] (map #(hal/get-property % :name) users)))))) (testing "should be able to create resources in an API" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-redirect (create-url base-url "/users") {:name "Thomas"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thomas") {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "Thomas") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :users {:name "Thomas"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "Thomas" (hal/get-property new-user :name)))))) (testing "should be able to remove resources in an API" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete (create-url base-url "/users/thomas") {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/delete :user {:id "thomas"})) status (navigator/status result)] (is (= 204 status))))) (testing "should be able to update resources in an API" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-patch-redirect (create-url base-url "/users/thomas") {:surname "Svensson"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thomas") {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "Thomas") (hal/add-property :surname "Svensson") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/patch :user {:id "thomas"} {:surname "Svensson"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "Thomas" (hal/get-property new-user :name))) (is (= "Svensson" (hal/get-property new-user :surname)))))) (testing "should handle query params on post" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?first,second}" :templated true}) (stubs/on-post-redirect (create-url base-url "/users") {:name "Thomas"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thomas") {:status 200 :body (-> (hal/new-resource) (hal/add-link :self "/users/thomas") (hal/add-property :name "Thomas") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :users {:name "Thomas"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "Thomas" (hal/get-property new-user :name)))))) (testing "should handle query params on delete" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?name}" :templated true}) (stubs/on-delete (create-url base-url "/users") {:name "thomas"} {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/delete :users {:name "thomas"})) status (navigator/status result)] (is (= 204 status))))) (testing "should be able to use template params when creating resources" (with-fake-http (concat (stubs/on-discover base-url :useritems {:href "/users/{id}/items" :templated true}) (stubs/on-post-redirect (create-url base-url "/users/thomas/items") {:name "Sponge"} "/users/thomas/items/1") (stubs/on-get (create-url base-url "/users/thomas/items/1") {:status 200 :body (-> (hal/new-resource "/users/thomas/items/1") (hal/add-property :name "Sponge") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :useritems {:id "thomas"} {:name "Sponge"})) status (navigator/status result) new-item (navigator/resource result)] (is (= 200 status)) (is (= "Sponge" (hal/get-property new-item :name)))))) (testing "should not follow location headers when the status is not 201" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-post (create-url base-url "/users") {:name "Thomas"} {:status 400})) (let [status (-> (navigator/discover base-url) (navigator/post :users {:name "Thomas"}) (navigator/status))] (is (= 400 status))))) (testing "should not follow location headers when the options say not to" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-post-redirect (create-url base-url "/users") {:name "Thomas"} "/users/thomas")) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "Thomas"})) status (navigator/status result)] (is (= 201 status)) (is (= "/users/thomas" (navigator/get-header result :location)))))) (testing "should be able to continue the conversation even if we do not follow redirects" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-redirect (create-url base-url "/users") {:name "Thomas"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thomas") {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "Thomas") (json/resource->json))})) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "Thomas"}) (navigator/follow-redirect)) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "Thomas" (hal/get-property new-user :name)))))) (testing "should throw when trying to follow a redirect without a location header" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post (create-url base-url "/users") {:name "Thomas"} {:status 201 :headers {}})) (is (thrown? clojure.lang.ExceptionInfo (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "Thomas"}) (navigator/follow-redirect)))))) (testing "should be able to put to a resource" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-put (create-url base-url "/users/thomas") {:name "Thomas"} {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "Thomas") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/put :user {:id "thomas"} {:name "Thomas"})) status (navigator/status result) user (navigator/resource result)] (is (= 200 status)) (is (= "Thomas" (hal/get-property user :name)))))) (testing "should follow redirects when putting to a resource returns a 201" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-put-redirect (create-url base-url "/users/thomas") {:name "Thomas"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thomas") {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "Thomas") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/put :user {:id "thomas"} {:name "Thomas"})) status (navigator/status result) user (navigator/resource result)] (is (= 200 status)) (is (= "Thomas" (hal/get-property user :name)))))) (testing "should be able to head to a resource" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-head (create-url base-url "/users/thomas") {:status 200})) (let [result (-> (navigator/discover base-url) (navigator/head :user {:id "thomas"})) status (navigator/status result)] (is (= 200 status))))) (testing "should be able to set header for delete" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete-with-headers resource-url {"Content-Type" "application/json" "Accept" "application/hal+json" "X-resource-location" resource-url} {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/set-header "X-resource-location" resource-url) (navigator/delete :user {:id "thomas"})) status (navigator/status result)] (is (= 204 status)))))) (testing "should be able to set header for post" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-with-headers (create-url base-url "/users") {"Content-Type" "application/json" "Accept" "application/hal+json" "X-resource-location" resource-url} {:name "Thomas"} {:status 201})) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/set-header "X-resource-location" resource-url) (navigator/post :users {:name "Thomas"})) status (navigator/status result)] (is (= 201 status)))))) (testing "should be able to resume conversations" (with-fake-http (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users [(create-user "fred") (create-user "sue") (create-user "mary")]) (json/resource->json))}) (let [resource (-> (hal/new-resource base-url) (hal/add-link :users {:href "/users{?admin}" :templated true})) result (-> (navigator/resume resource) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["Fred" "Sue" "Mary"] (map #(hal/get-property % :name) users)))))) (testing "should be able to hint at the location when the self link is not absolute" (with-fake-http (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users [(create-user "fred") (create-user "sue") (create-user "mary")]) (json/resource->json))}) (let [resource (-> (hal/new-resource "/") (hal/add-link :users {:href "/users{?admin}" :templated true})) result (-> (navigator/resume resource {:resume-from base-url}) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["Fred" "Sue" "Mary"] (map #(hal/get-property % :name) users)))))) (testing "should throw an error when trying to resume a conversation with a resource that lacks a self link" (is (thrown? clojure.lang.ExceptionInfo (navigator/resume (hal/new-resource))))) (testing "should throw an error when trying to resume a conversation with a resource with a relative self link, and no :resume-from option" (is (thrown? clojure.lang.ExceptionInfo (navigator/resume (-> (hal/new-resource) (hal/add-href :self "/users")))))))
32087
(ns halboy.navigator-test (:use org.httpkit.fake) (:require [clojure.test :refer :all] [clojure.string :refer [capitalize]] [halboy.navigator :as navigator] [halboy.resource :as hal] [halboy.json :as json] [halboy.support.api :as stubs] [halboy.resource :as hal]) (:import [java.net URL])) (def base-url "https://service.example.com") (defn- create-url [base-url resource] (-> (URL. base-url) (URL. resource) (.toString))) (defn- create-user [name] (-> (hal/new-resource) (hal/add-link :self {:href (create-url base-url (format "/users/%s" name))}) (hal/add-property :name (capitalize name)))) (deftest halboy-navigator (testing "should be able to retrieve the settings" (with-fake-http (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (let [options (-> (navigator/discover base-url) (navigator/settings))] (is (true? (:follow-redirects options))) (is (empty? (:headers options))) (is (not (nil? (:client options))))))) (testing "should be able to pass options to the HTTP client" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete-with-headers resource-url {"Content-Type" "application/json" "Accept" "application/hal+json" "My-Header" "some-value"} {:status 204})) (let [result (-> (navigator/discover base-url {:http {:headers {"My-Header" "some-value"}}}) (navigator/delete :user {:id "thomas"})) status (navigator/status result)] (is (= 204 status)))))) (testing "should be able to navigate through links in an API" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "f<NAME>") :users (create-user "sue") :users (create-user "mary")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["<NAME>" "<NAME>" "<NAME>"] (map #(hal/get-property % :name) users)))))) (testing "should throw an error when trying to get a link which does not exist" (with-fake-http (stubs/on-discover base-url) (is (thrown? clojure.lang.ExceptionInfo (-> (navigator/discover base-url) (navigator/get :users)))))) (testing "should be able to navigate through links with query params" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-get (create-url base-url "/users") {:admin "true"} {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "f<NAME>") :users (create-user "sue") :users (create-user "mary")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users {:admin true})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["<NAME>" "<NAME>" "<NAME>"] (map #(hal/get-property % :name) users)))))) (testing "should be able to navigate through links with multiple query params" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin,owner}" :templated true}) (stubs/on-get (create-url base-url "/users") {:admin "true" :owner "false"} {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "<NAME>") :users (create-user "sue")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users {:admin true :owner false})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["<NAME>" "<NAME>"] (map #(hal/get-property % :name) users)))))) (testing "should be able to navigate with a mixture of template and query params" (with-fake-http (concat (stubs/on-discover base-url :friends {:href "/users/{id}/friends{?mutual}" :templated true}) (stubs/on-get (create-url base-url "/users/thomas/friends") {:mutual "true"} {:status 200 :body (-> (hal/new-resource "/users/thomas/friends") (hal/add-resources :users (create-user "<NAME>") :users (create-user "sue") :users (create-user "<NAME>")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :friends {:id "thomas" :mutual true})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["<NAME>" "<NAME>" "<NAME>"] (map #(hal/get-property % :name) users)))))) (testing "should be able to create resources in an API" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-redirect (create-url base-url "/users") {:name "<NAME>"} "/users/thomas") (stubs/on-get (create-url base-url "/users/th<NAME>") {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "<NAME>") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :users {:name "<NAME>"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "<NAME>" (hal/get-property new-user :name)))))) (testing "should be able to remove resources in an API" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete (create-url base-url "/users/thomas") {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/delete :user {:id "<NAME> <NAME>"})) status (navigator/status result)] (is (= 204 status))))) (testing "should be able to update resources in an API" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-patch-redirect (create-url base-url "/users/thomas") {:surname "<NAME>"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thomas") {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "<NAME>") (hal/add-property :surname "<NAME>") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/patch :user {:id "<NAME>"} {:surname "<NAME>"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "<NAME>" (hal/get-property new-user :name))) (is (= "<NAME>" (hal/get-property new-user :surname)))))) (testing "should handle query params on post" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?first,second}" :templated true}) (stubs/on-post-redirect (create-url base-url "/users") {:name "<NAME>"} "/users/th<NAME>") (stubs/on-get (create-url base-url "/users/<NAME> <NAME>") {:status 200 :body (-> (hal/new-resource) (hal/add-link :self "/users/th<NAME>") (hal/add-property :name "<NAME>") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :users {:name "<NAME>"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "<NAME>" (hal/get-property new-user :name)))))) (testing "should handle query params on delete" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?name}" :templated true}) (stubs/on-delete (create-url base-url "/users") {:name "<NAME>"} {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/delete :users {:name "<NAME> <NAME>"})) status (navigator/status result)] (is (= 204 status))))) (testing "should be able to use template params when creating resources" (with-fake-http (concat (stubs/on-discover base-url :useritems {:href "/users/{id}/items" :templated true}) (stubs/on-post-redirect (create-url base-url "/users/<NAME> <NAME>/items") {:name "<NAME>"} "/users/<NAME> <NAME>/items/1") (stubs/on-get (create-url base-url "/users/<NAME> <NAME>/items/1") {:status 200 :body (-> (hal/new-resource "/users/<NAME> <NAME>/items/1") (hal/add-property :name "Sponge") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :useritems {:id "<NAME> <NAME>"} {:name "<NAME>"})) status (navigator/status result) new-item (navigator/resource result)] (is (= 200 status)) (is (= "Sponge" (hal/get-property new-item :name)))))) (testing "should not follow location headers when the status is not 201" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-post (create-url base-url "/users") {:name "<NAME>"} {:status 400})) (let [status (-> (navigator/discover base-url) (navigator/post :users {:name "<NAME>"}) (navigator/status))] (is (= 400 status))))) (testing "should not follow location headers when the options say not to" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-post-redirect (create-url base-url "/users") {:name "<NAME>"} "/users/thomas")) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "<NAME>"})) status (navigator/status result)] (is (= 201 status)) (is (= "/users/thomas" (navigator/get-header result :location)))))) (testing "should be able to continue the conversation even if we do not follow redirects" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-redirect (create-url base-url "/users") {:name "<NAME>"} "/users/thomas") (stubs/on-get (create-url base-url "/users/th<NAME>") {:status 200 :body (-> (hal/new-resource "/users/th<NAME>") (hal/add-property :name "<NAME>") (json/resource->json))})) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "<NAME>"}) (navigator/follow-redirect)) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "<NAME>" (hal/get-property new-user :name)))))) (testing "should throw when trying to follow a redirect without a location header" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post (create-url base-url "/users") {:name "<NAME>"} {:status 201 :headers {}})) (is (thrown? clojure.lang.ExceptionInfo (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "<NAME>"}) (navigator/follow-redirect)))))) (testing "should be able to put to a resource" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-put (create-url base-url "/users/thomas") {:name "<NAME>"} {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "<NAME>") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/put :user {:id "<NAME>"} {:name "<NAME>"})) status (navigator/status result) user (navigator/resource result)] (is (= 200 status)) (is (= "<NAME>" (hal/get-property user :name)))))) (testing "should follow redirects when putting to a resource returns a 201" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-put-redirect (create-url base-url "/users/th<NAME>") {:name "<NAME>"} "/users/th<NAME>") (stubs/on-get (create-url base-url "/users/<NAME> <NAME>") {:status 200 :body (-> (hal/new-resource "/users/th<NAME>") (hal/add-property :name "<NAME>") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/put :user {:id "<NAME>"} {:name "<NAME>"})) status (navigator/status result) user (navigator/resource result)] (is (= 200 status)) (is (= "<NAME>" (hal/get-property user :name)))))) (testing "should be able to head to a resource" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-head (create-url base-url "/users/<NAME> <NAME>") {:status 200})) (let [result (-> (navigator/discover base-url) (navigator/head :user {:id "<NAME> <NAME>"})) status (navigator/status result)] (is (= 200 status))))) (testing "should be able to set header for delete" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete-with-headers resource-url {"Content-Type" "application/json" "Accept" "application/hal+json" "X-resource-location" resource-url} {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/set-header "X-resource-location" resource-url) (navigator/delete :user {:id "<NAME>omas"})) status (navigator/status result)] (is (= 204 status)))))) (testing "should be able to set header for post" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-with-headers (create-url base-url "/users") {"Content-Type" "application/json" "Accept" "application/hal+json" "X-resource-location" resource-url} {:name "<NAME> <NAME>"} {:status 201})) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/set-header "X-resource-location" resource-url) (navigator/post :users {:name "<NAME> <NAME>"})) status (navigator/status result)] (is (= 201 status)))))) (testing "should be able to resume conversations" (with-fake-http (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users [(create-user "<NAME>") (create-user "<NAME>") (create-user "<NAME>")]) (json/resource->json))}) (let [resource (-> (hal/new-resource base-url) (hal/add-link :users {:href "/users{?admin}" :templated true})) result (-> (navigator/resume resource) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["<NAME>" "<NAME>" "<NAME>"] (map #(hal/get-property % :name) users)))))) (testing "should be able to hint at the location when the self link is not absolute" (with-fake-http (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users [(create-user "<NAME>") (create-user "<NAME>") (create-user "<NAME>")]) (json/resource->json))}) (let [resource (-> (hal/new-resource "/") (hal/add-link :users {:href "/users{?admin}" :templated true})) result (-> (navigator/resume resource {:resume-from base-url}) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["<NAME>" "<NAME>" "<NAME>"] (map #(hal/get-property % :name) users)))))) (testing "should throw an error when trying to resume a conversation with a resource that lacks a self link" (is (thrown? clojure.lang.ExceptionInfo (navigator/resume (hal/new-resource))))) (testing "should throw an error when trying to resume a conversation with a resource with a relative self link, and no :resume-from option" (is (thrown? clojure.lang.ExceptionInfo (navigator/resume (-> (hal/new-resource) (hal/add-href :self "/users")))))))
true
(ns halboy.navigator-test (:use org.httpkit.fake) (:require [clojure.test :refer :all] [clojure.string :refer [capitalize]] [halboy.navigator :as navigator] [halboy.resource :as hal] [halboy.json :as json] [halboy.support.api :as stubs] [halboy.resource :as hal]) (:import [java.net URL])) (def base-url "https://service.example.com") (defn- create-url [base-url resource] (-> (URL. base-url) (URL. resource) (.toString))) (defn- create-user [name] (-> (hal/new-resource) (hal/add-link :self {:href (create-url base-url (format "/users/%s" name))}) (hal/add-property :name (capitalize name)))) (deftest halboy-navigator (testing "should be able to retrieve the settings" (with-fake-http (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (let [options (-> (navigator/discover base-url) (navigator/settings))] (is (true? (:follow-redirects options))) (is (empty? (:headers options))) (is (not (nil? (:client options))))))) (testing "should be able to pass options to the HTTP client" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete-with-headers resource-url {"Content-Type" "application/json" "Accept" "application/hal+json" "My-Header" "some-value"} {:status 204})) (let [result (-> (navigator/discover base-url {:http {:headers {"My-Header" "some-value"}}}) (navigator/delete :user {:id "thomas"})) status (navigator/status result)] (is (= 204 status)))))) (testing "should be able to navigate through links in an API" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "fPI:NAME:<NAME>END_PI") :users (create-user "sue") :users (create-user "mary")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] (map #(hal/get-property % :name) users)))))) (testing "should throw an error when trying to get a link which does not exist" (with-fake-http (stubs/on-discover base-url) (is (thrown? clojure.lang.ExceptionInfo (-> (navigator/discover base-url) (navigator/get :users)))))) (testing "should be able to navigate through links with query params" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-get (create-url base-url "/users") {:admin "true"} {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "fPI:NAME:<NAME>END_PI") :users (create-user "sue") :users (create-user "mary")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users {:admin true})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] (map #(hal/get-property % :name) users)))))) (testing "should be able to navigate through links with multiple query params" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin,owner}" :templated true}) (stubs/on-get (create-url base-url "/users") {:admin "true" :owner "false"} {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users (create-user "PI:NAME:<NAME>END_PI") :users (create-user "sue")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :users {:admin true :owner false})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] (map #(hal/get-property % :name) users)))))) (testing "should be able to navigate with a mixture of template and query params" (with-fake-http (concat (stubs/on-discover base-url :friends {:href "/users/{id}/friends{?mutual}" :templated true}) (stubs/on-get (create-url base-url "/users/thomas/friends") {:mutual "true"} {:status 200 :body (-> (hal/new-resource "/users/thomas/friends") (hal/add-resources :users (create-user "PI:NAME:<NAME>END_PI") :users (create-user "sue") :users (create-user "PI:NAME:<NAME>END_PI")) (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/get :friends {:id "thomas" :mutual true})) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] (map #(hal/get-property % :name) users)))))) (testing "should be able to create resources in an API" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-redirect (create-url base-url "/users") {:name "PI:NAME:<NAME>END_PI"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thPI:NAME:<NAME>END_PI") {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "PI:NAME:<NAME>END_PI") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :users {:name "PI:NAME:<NAME>END_PI"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "PI:NAME:<NAME>END_PI" (hal/get-property new-user :name)))))) (testing "should be able to remove resources in an API" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete (create-url base-url "/users/thomas") {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/delete :user {:id "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"})) status (navigator/status result)] (is (= 204 status))))) (testing "should be able to update resources in an API" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-patch-redirect (create-url base-url "/users/thomas") {:surname "PI:NAME:<NAME>END_PI"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thomas") {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "PI:NAME:<NAME>END_PI") (hal/add-property :surname "PI:NAME:<NAME>END_PI") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/patch :user {:id "PI:NAME:<NAME>END_PI"} {:surname "PI:NAME:<NAME>END_PI"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "PI:NAME:<NAME>END_PI" (hal/get-property new-user :name))) (is (= "PI:NAME:<NAME>END_PI" (hal/get-property new-user :surname)))))) (testing "should handle query params on post" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?first,second}" :templated true}) (stubs/on-post-redirect (create-url base-url "/users") {:name "PI:NAME:<NAME>END_PI"} "/users/thPI:NAME:<NAME>END_PI") (stubs/on-get (create-url base-url "/users/PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI") {:status 200 :body (-> (hal/new-resource) (hal/add-link :self "/users/thPI:NAME:<NAME>END_PI") (hal/add-property :name "PI:NAME:<NAME>END_PI") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :users {:name "PI:NAME:<NAME>END_PI"})) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "PI:NAME:<NAME>END_PI" (hal/get-property new-user :name)))))) (testing "should handle query params on delete" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?name}" :templated true}) (stubs/on-delete (create-url base-url "/users") {:name "PI:NAME:<NAME>END_PI"} {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/delete :users {:name "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"})) status (navigator/status result)] (is (= 204 status))))) (testing "should be able to use template params when creating resources" (with-fake-http (concat (stubs/on-discover base-url :useritems {:href "/users/{id}/items" :templated true}) (stubs/on-post-redirect (create-url base-url "/users/PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI/items") {:name "PI:NAME:<NAME>END_PI"} "/users/PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI/items/1") (stubs/on-get (create-url base-url "/users/PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI/items/1") {:status 200 :body (-> (hal/new-resource "/users/PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI/items/1") (hal/add-property :name "Sponge") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/post :useritems {:id "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"})) status (navigator/status result) new-item (navigator/resource result)] (is (= 200 status)) (is (= "Sponge" (hal/get-property new-item :name)))))) (testing "should not follow location headers when the status is not 201" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-post (create-url base-url "/users") {:name "PI:NAME:<NAME>END_PI"} {:status 400})) (let [status (-> (navigator/discover base-url) (navigator/post :users {:name "PI:NAME:<NAME>END_PI"}) (navigator/status))] (is (= 400 status))))) (testing "should not follow location headers when the options say not to" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users{?admin}" :templated true}) (stubs/on-post-redirect (create-url base-url "/users") {:name "PI:NAME:<NAME>END_PI"} "/users/thomas")) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "PI:NAME:<NAME>END_PI"})) status (navigator/status result)] (is (= 201 status)) (is (= "/users/thomas" (navigator/get-header result :location)))))) (testing "should be able to continue the conversation even if we do not follow redirects" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-redirect (create-url base-url "/users") {:name "PI:NAME:<NAME>END_PI"} "/users/thomas") (stubs/on-get (create-url base-url "/users/thPI:NAME:<NAME>END_PI") {:status 200 :body (-> (hal/new-resource "/users/thPI:NAME:<NAME>END_PI") (hal/add-property :name "PI:NAME:<NAME>END_PI") (json/resource->json))})) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "PI:NAME:<NAME>END_PI"}) (navigator/follow-redirect)) status (navigator/status result) new-user (navigator/resource result)] (is (= 200 status)) (is (= "PI:NAME:<NAME>END_PI" (hal/get-property new-user :name)))))) (testing "should throw when trying to follow a redirect without a location header" (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post (create-url base-url "/users") {:name "PI:NAME:<NAME>END_PI"} {:status 201 :headers {}})) (is (thrown? clojure.lang.ExceptionInfo (-> (navigator/discover base-url {:follow-redirects false}) (navigator/post :users {:name "PI:NAME:<NAME>END_PI"}) (navigator/follow-redirect)))))) (testing "should be able to put to a resource" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-put (create-url base-url "/users/thomas") {:name "PI:NAME:<NAME>END_PI"} {:status 200 :body (-> (hal/new-resource "/users/thomas") (hal/add-property :name "PI:NAME:<NAME>END_PI") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/put :user {:id "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"})) status (navigator/status result) user (navigator/resource result)] (is (= 200 status)) (is (= "PI:NAME:<NAME>END_PI" (hal/get-property user :name)))))) (testing "should follow redirects when putting to a resource returns a 201" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-put-redirect (create-url base-url "/users/thPI:NAME:<NAME>END_PI") {:name "PI:NAME:<NAME>END_PI"} "/users/thPI:NAME:<NAME>END_PI") (stubs/on-get (create-url base-url "/users/PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI") {:status 200 :body (-> (hal/new-resource "/users/thPI:NAME:<NAME>END_PI") (hal/add-property :name "PI:NAME:<NAME>END_PI") (json/resource->json))})) (let [result (-> (navigator/discover base-url) (navigator/put :user {:id "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"})) status (navigator/status result) user (navigator/resource result)] (is (= 200 status)) (is (= "PI:NAME:<NAME>END_PI" (hal/get-property user :name)))))) (testing "should be able to head to a resource" (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-head (create-url base-url "/users/PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI") {:status 200})) (let [result (-> (navigator/discover base-url) (navigator/head :user {:id "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"})) status (navigator/status result)] (is (= 200 status))))) (testing "should be able to set header for delete" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :user {:href "/users/{id}" :templated true}) (stubs/on-delete-with-headers resource-url {"Content-Type" "application/json" "Accept" "application/hal+json" "X-resource-location" resource-url} {:status 204})) (let [result (-> (navigator/discover base-url) (navigator/set-header "X-resource-location" resource-url) (navigator/delete :user {:id "PI:NAME:<NAME>END_PIomas"})) status (navigator/status result)] (is (= 204 status)))))) (testing "should be able to set header for post" (let [resource-url (create-url base-url "/users/thomas")] (with-fake-http (concat (stubs/on-discover base-url :users {:href "/users"}) (stubs/on-post-with-headers (create-url base-url "/users") {"Content-Type" "application/json" "Accept" "application/hal+json" "X-resource-location" resource-url} {:name "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"} {:status 201})) (let [result (-> (navigator/discover base-url {:follow-redirects false}) (navigator/set-header "X-resource-location" resource-url) (navigator/post :users {:name "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"})) status (navigator/status result)] (is (= 201 status)))))) (testing "should be able to resume conversations" (with-fake-http (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users [(create-user "PI:NAME:<NAME>END_PI") (create-user "PI:NAME:<NAME>END_PI") (create-user "PI:NAME:<NAME>END_PI")]) (json/resource->json))}) (let [resource (-> (hal/new-resource base-url) (hal/add-link :users {:href "/users{?admin}" :templated true})) result (-> (navigator/resume resource) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] (map #(hal/get-property % :name) users)))))) (testing "should be able to hint at the location when the self link is not absolute" (with-fake-http (stubs/on-get (create-url base-url "/users") {:status 200 :body (-> (hal/new-resource "/users") (hal/add-resources :users [(create-user "PI:NAME:<NAME>END_PI") (create-user "PI:NAME:<NAME>END_PI") (create-user "PI:NAME:<NAME>END_PI")]) (json/resource->json))}) (let [resource (-> (hal/new-resource "/") (hal/add-link :users {:href "/users{?admin}" :templated true})) result (-> (navigator/resume resource {:resume-from base-url}) (navigator/get :users)) status (navigator/status result) users (-> (navigator/resource result) (hal/get-resource :users))] (is (= 200 status)) (is (= ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] (map #(hal/get-property % :name) users)))))) (testing "should throw an error when trying to resume a conversation with a resource that lacks a self link" (is (thrown? clojure.lang.ExceptionInfo (navigator/resume (hal/new-resource))))) (testing "should throw an error when trying to resume a conversation with a resource with a relative self link, and no :resume-from option" (is (thrown? clojure.lang.ExceptionInfo (navigator/resume (-> (hal/new-resource) (hal/add-href :self "/users")))))))
[ { "context": "solution actual] (some #{solution} actual)\n \"HUMOR\" (sut/simple-solve \"AIELDNTPYG\" \".....\" [\"\" \"RO\" ", "end": 2769, "score": 0.9507694244384766, "start": 2764, "tag": "NAME", "value": "HUMOR" }, { "context": "\"AIELDNTPYG\" \".....\" [\"\" \"RO\" \"\" \"UM\" \"\"])\n \"ULCER\" (sut/simple-solve \"AIDONTS\" \"...E.\" [\"R\" \"RU\" \"L", "end": 2844, "score": 0.9640712738037109, "start": 2839, "tag": "NAME", "value": "ULCER" }, { "context": " \"AIDONTS\" \"...E.\" [\"R\" \"RU\" \"L\" \"U\" \"L\"])\n \"CYNIC\" (sut/simple-solve \"ARELDOUTPGMKOS\" \".YN..\" [\"\" \"", "end": 2918, "score": 0.8183146715164185, "start": 2913, "tag": "NAME", "value": "CYNIC" }, { "context": "RELDOUTPGMKOS\" \".YN..\" [\"\" \"I\" \"I\" \"\" \"\"])\n \"AROMA\" (sut/simple-solve \"ETYUIPDGLN\" \"AR.M.\" [\"\" \"O\" \"", "end": 2995, "score": 0.9316971898078918, "start": 2990, "tag": "NAME", "value": "AROMA" } ]
test/core_logic_wordle/core_test.clj
mjul/core-logic-wordle
0
(ns core-logic-wordle.core-test (:require [clojure.test :refer :all] [clojure.core.logic :as l] [core-logic-wordle.core :as sut])) (deftest specific-solve-test (testing "specific-solve will return at least one five-letter word" (let [actual (sut/specific-solve)] (is (every? string? actual)) (is (every? #(= 5 (count %)) actual)) (is (some #{"HUMOR"} actual) "HUMOR is the known solution")))) (deftest knowno-test (testing "known binding" (testing "when the value is known (non-nil), knowno must bind the value" (let [actual (l/run* [q] (l/fresh [a] (sut/knowno a "A") (l/== q a)))] (is (= ["A"] actual)))) (testing "when the value is unknown known (nil), knowno must not bind the value" (let [actual (l/run* [q] (l/fresh [a] (sut/knowno a nil) ;; this can only succeed if a is not ground by the above (l/== a :not-known) (l/== q a)))] (is (= [:not-known] actual)))))) (deftest simple-solve-test (testing "test solving a specific problem" (testing "sanity checks inputs" (testing "non-letters may not be in known list" (is (thrown? AssertionError (sut/simple-solve "A" "A...." ["" "" "" "" ""])))) (testing "non-letters may not be in not-in-this-position list" (is (thrown? AssertionError (sut/simple-solve "A" "....." ["" "A" "" "" ""]))))) (testing "where every letter and position is known" (testing "and nothing else is known" (let [actual (sut/simple-solve "" "THINK" ["" "" "" "" ""])] (is (= 1 (count actual))) (is (= "THINK" (first actual))))) (testing "and compatible not-in-this-positions are known" (let [actual (sut/simple-solve "" "THINK" ["HI" "IN" "NK" "KT" "TH"])] (is (= 1 (count actual))) (is (= ["THINK"] actual))))) (testing "where some letters and positions are known" (testing "and compatible not-in-this-positions are known" (testing "and has single solution" (let [actual (sut/simple-solve "" "TH.NK" ["HI" "IN" "NK" "KT" "TH"])] (is (= 1 (count actual))) (is (= ["THINK"] actual)))) (testing "and has multiple solutions" (let [actual (sut/simple-solve "BCDEFGJLMOPQRSUVWXYZ" "TH.NK" ["" "" "" "" ""])] (is (= #{"THTNK" "THHNK" "THINK" "THNNK" "THKNK" "THANK"} (set actual)))))))) (testing "actual Wordle problems can be solved" (are [solution actual] (some #{solution} actual) "HUMOR" (sut/simple-solve "AIELDNTPYG" "....." ["" "RO" "" "UM" ""]) "ULCER" (sut/simple-solve "AIDONTS" "...E." ["R" "RU" "L" "U" "L"]) "CYNIC" (sut/simple-solve "ARELDOUTPGMKOS" ".YN.." ["" "I" "I" "" ""]) "AROMA" (sut/simple-solve "ETYUIPDGLN" "AR.M." ["" "O" "" "" ""]) "DODGE" (sut/simple-solve "RTYUIPASLCNM" "DO..E" ["" "" "GO" "E" ""]) "OTHER" (sut/simple-solve "UIADLN" "...E." ["" "RO" "" "" "T"]) "BLOKE" (sut/simple-solve "RTYUIPASDHCNM" ".LO.E" ["" "O" "" "E" "L"]) "CHOKE" (sut/simple-solve "RTUIADLNSP" "..O.E" ["" "OC" "" "E" ""]) "SWEET" (sut/simple-solve "RYUIOPADGHLCBN" "...ET" ["E" "E" "S" "" ""]) )))
87433
(ns core-logic-wordle.core-test (:require [clojure.test :refer :all] [clojure.core.logic :as l] [core-logic-wordle.core :as sut])) (deftest specific-solve-test (testing "specific-solve will return at least one five-letter word" (let [actual (sut/specific-solve)] (is (every? string? actual)) (is (every? #(= 5 (count %)) actual)) (is (some #{"HUMOR"} actual) "HUMOR is the known solution")))) (deftest knowno-test (testing "known binding" (testing "when the value is known (non-nil), knowno must bind the value" (let [actual (l/run* [q] (l/fresh [a] (sut/knowno a "A") (l/== q a)))] (is (= ["A"] actual)))) (testing "when the value is unknown known (nil), knowno must not bind the value" (let [actual (l/run* [q] (l/fresh [a] (sut/knowno a nil) ;; this can only succeed if a is not ground by the above (l/== a :not-known) (l/== q a)))] (is (= [:not-known] actual)))))) (deftest simple-solve-test (testing "test solving a specific problem" (testing "sanity checks inputs" (testing "non-letters may not be in known list" (is (thrown? AssertionError (sut/simple-solve "A" "A...." ["" "" "" "" ""])))) (testing "non-letters may not be in not-in-this-position list" (is (thrown? AssertionError (sut/simple-solve "A" "....." ["" "A" "" "" ""]))))) (testing "where every letter and position is known" (testing "and nothing else is known" (let [actual (sut/simple-solve "" "THINK" ["" "" "" "" ""])] (is (= 1 (count actual))) (is (= "THINK" (first actual))))) (testing "and compatible not-in-this-positions are known" (let [actual (sut/simple-solve "" "THINK" ["HI" "IN" "NK" "KT" "TH"])] (is (= 1 (count actual))) (is (= ["THINK"] actual))))) (testing "where some letters and positions are known" (testing "and compatible not-in-this-positions are known" (testing "and has single solution" (let [actual (sut/simple-solve "" "TH.NK" ["HI" "IN" "NK" "KT" "TH"])] (is (= 1 (count actual))) (is (= ["THINK"] actual)))) (testing "and has multiple solutions" (let [actual (sut/simple-solve "BCDEFGJLMOPQRSUVWXYZ" "TH.NK" ["" "" "" "" ""])] (is (= #{"THTNK" "THHNK" "THINK" "THNNK" "THKNK" "THANK"} (set actual)))))))) (testing "actual Wordle problems can be solved" (are [solution actual] (some #{solution} actual) "<NAME>" (sut/simple-solve "AIELDNTPYG" "....." ["" "RO" "" "UM" ""]) "<NAME>" (sut/simple-solve "AIDONTS" "...E." ["R" "RU" "L" "U" "L"]) "<NAME>" (sut/simple-solve "ARELDOUTPGMKOS" ".YN.." ["" "I" "I" "" ""]) "<NAME>" (sut/simple-solve "ETYUIPDGLN" "AR.M." ["" "O" "" "" ""]) "DODGE" (sut/simple-solve "RTYUIPASLCNM" "DO..E" ["" "" "GO" "E" ""]) "OTHER" (sut/simple-solve "UIADLN" "...E." ["" "RO" "" "" "T"]) "BLOKE" (sut/simple-solve "RTYUIPASDHCNM" ".LO.E" ["" "O" "" "E" "L"]) "CHOKE" (sut/simple-solve "RTUIADLNSP" "..O.E" ["" "OC" "" "E" ""]) "SWEET" (sut/simple-solve "RYUIOPADGHLCBN" "...ET" ["E" "E" "S" "" ""]) )))
true
(ns core-logic-wordle.core-test (:require [clojure.test :refer :all] [clojure.core.logic :as l] [core-logic-wordle.core :as sut])) (deftest specific-solve-test (testing "specific-solve will return at least one five-letter word" (let [actual (sut/specific-solve)] (is (every? string? actual)) (is (every? #(= 5 (count %)) actual)) (is (some #{"HUMOR"} actual) "HUMOR is the known solution")))) (deftest knowno-test (testing "known binding" (testing "when the value is known (non-nil), knowno must bind the value" (let [actual (l/run* [q] (l/fresh [a] (sut/knowno a "A") (l/== q a)))] (is (= ["A"] actual)))) (testing "when the value is unknown known (nil), knowno must not bind the value" (let [actual (l/run* [q] (l/fresh [a] (sut/knowno a nil) ;; this can only succeed if a is not ground by the above (l/== a :not-known) (l/== q a)))] (is (= [:not-known] actual)))))) (deftest simple-solve-test (testing "test solving a specific problem" (testing "sanity checks inputs" (testing "non-letters may not be in known list" (is (thrown? AssertionError (sut/simple-solve "A" "A...." ["" "" "" "" ""])))) (testing "non-letters may not be in not-in-this-position list" (is (thrown? AssertionError (sut/simple-solve "A" "....." ["" "A" "" "" ""]))))) (testing "where every letter and position is known" (testing "and nothing else is known" (let [actual (sut/simple-solve "" "THINK" ["" "" "" "" ""])] (is (= 1 (count actual))) (is (= "THINK" (first actual))))) (testing "and compatible not-in-this-positions are known" (let [actual (sut/simple-solve "" "THINK" ["HI" "IN" "NK" "KT" "TH"])] (is (= 1 (count actual))) (is (= ["THINK"] actual))))) (testing "where some letters and positions are known" (testing "and compatible not-in-this-positions are known" (testing "and has single solution" (let [actual (sut/simple-solve "" "TH.NK" ["HI" "IN" "NK" "KT" "TH"])] (is (= 1 (count actual))) (is (= ["THINK"] actual)))) (testing "and has multiple solutions" (let [actual (sut/simple-solve "BCDEFGJLMOPQRSUVWXYZ" "TH.NK" ["" "" "" "" ""])] (is (= #{"THTNK" "THHNK" "THINK" "THNNK" "THKNK" "THANK"} (set actual)))))))) (testing "actual Wordle problems can be solved" (are [solution actual] (some #{solution} actual) "PI:NAME:<NAME>END_PI" (sut/simple-solve "AIELDNTPYG" "....." ["" "RO" "" "UM" ""]) "PI:NAME:<NAME>END_PI" (sut/simple-solve "AIDONTS" "...E." ["R" "RU" "L" "U" "L"]) "PI:NAME:<NAME>END_PI" (sut/simple-solve "ARELDOUTPGMKOS" ".YN.." ["" "I" "I" "" ""]) "PI:NAME:<NAME>END_PI" (sut/simple-solve "ETYUIPDGLN" "AR.M." ["" "O" "" "" ""]) "DODGE" (sut/simple-solve "RTYUIPASLCNM" "DO..E" ["" "" "GO" "E" ""]) "OTHER" (sut/simple-solve "UIADLN" "...E." ["" "RO" "" "" "T"]) "BLOKE" (sut/simple-solve "RTYUIPASDHCNM" ".LO.E" ["" "O" "" "E" "L"]) "CHOKE" (sut/simple-solve "RTUIADLNSP" "..O.E" ["" "OC" "" "E" ""]) "SWEET" (sut/simple-solve "RYUIOPADGHLCBN" "...ET" ["E" "E" "S" "" ""]) )))
[ { "context": "[:attributes attribute]))\n\n\n(def record\n {:name \"Matija\"\n :attributes {:age 23 :weight 75 :height 180 :", "end": 654, "score": 0.9989116191864014, "start": 648, "tag": "NAME", "value": "Matija" }, { "context": " (merge m part)))\n\n(println (my-assoc-in {:name \"Matija\"} [:attributes :age] 23))\n(println (my-assoc-in {", "end": 925, "score": 0.9988932609558105, "start": 919, "tag": "NAME", "value": "Matija" }, { "context": "tributes :age] 23))\n(println (my-assoc-in {:name \"matija\"} [:age] 23))\n\n(println ((comp :age :attributes) ", "end": 988, "score": 0.9984312653541565, "start": 982, "tag": "NAME", "value": "matija" } ]
fonclojure/src/com/matija/chapter5.clj
matija94/show-me-the-code
1
(ns com.matija.chapter5) (defn sum ([vals] (sum vals 0)) ([vals accumulator] (if (empty? vals) accumulator (sum (rest vals) (+ (first vals) accumulator))))) (println (sum [1 2 3 4 5])) (println ((comp inc * ) 2 3)) (defn two-comp [f g] (fn [& args] (f (apply g args)))) (println ((two-comp inc *) 2 3)) (defn my-comp [f & funs] (fn [& args] (if (empty? funs) (apply f args) (f (apply (apply my-comp funs) args))))) (println ((my-comp #(* % 3) inc *) 2 3)) (println (apply * [2 3])) (defn attr [record attribute] (get-in record [:attributes attribute])) (def record {:name "Matija" :attributes {:age 23 :weight 75 :height 180 :shape "good"}}) (defn my-assoc-in [m [k & ks] v] (let [part (if (empty? ks) (assoc m k v) (assoc {} k (my-assoc-in {} ks v)))] (merge m part))) (println (my-assoc-in {:name "Matija"} [:attributes :age] 23)) (println (my-assoc-in {:name "matija"} [:age] 23)) (println ((comp :age :attributes) record)) (println (attr record :age)) (defn my-update-in [m [k & ks] f & args] (if (empty? ks) (assoc m k (apply f (get m k) args)) (assoc m k (apply my-update-in (get m k) ks f args)))) (println (my-update-in record [:attributes :shape] str " very")) (def lucky-number (concat '(+ 1 2) [10])) (println (eval lucky-number)) (eval (eval (read-string "(list println \"matija\" \"interstellar\")")))
119473
(ns com.matija.chapter5) (defn sum ([vals] (sum vals 0)) ([vals accumulator] (if (empty? vals) accumulator (sum (rest vals) (+ (first vals) accumulator))))) (println (sum [1 2 3 4 5])) (println ((comp inc * ) 2 3)) (defn two-comp [f g] (fn [& args] (f (apply g args)))) (println ((two-comp inc *) 2 3)) (defn my-comp [f & funs] (fn [& args] (if (empty? funs) (apply f args) (f (apply (apply my-comp funs) args))))) (println ((my-comp #(* % 3) inc *) 2 3)) (println (apply * [2 3])) (defn attr [record attribute] (get-in record [:attributes attribute])) (def record {:name "<NAME>" :attributes {:age 23 :weight 75 :height 180 :shape "good"}}) (defn my-assoc-in [m [k & ks] v] (let [part (if (empty? ks) (assoc m k v) (assoc {} k (my-assoc-in {} ks v)))] (merge m part))) (println (my-assoc-in {:name "<NAME>"} [:attributes :age] 23)) (println (my-assoc-in {:name "<NAME>"} [:age] 23)) (println ((comp :age :attributes) record)) (println (attr record :age)) (defn my-update-in [m [k & ks] f & args] (if (empty? ks) (assoc m k (apply f (get m k) args)) (assoc m k (apply my-update-in (get m k) ks f args)))) (println (my-update-in record [:attributes :shape] str " very")) (def lucky-number (concat '(+ 1 2) [10])) (println (eval lucky-number)) (eval (eval (read-string "(list println \"matija\" \"interstellar\")")))
true
(ns com.matija.chapter5) (defn sum ([vals] (sum vals 0)) ([vals accumulator] (if (empty? vals) accumulator (sum (rest vals) (+ (first vals) accumulator))))) (println (sum [1 2 3 4 5])) (println ((comp inc * ) 2 3)) (defn two-comp [f g] (fn [& args] (f (apply g args)))) (println ((two-comp inc *) 2 3)) (defn my-comp [f & funs] (fn [& args] (if (empty? funs) (apply f args) (f (apply (apply my-comp funs) args))))) (println ((my-comp #(* % 3) inc *) 2 3)) (println (apply * [2 3])) (defn attr [record attribute] (get-in record [:attributes attribute])) (def record {:name "PI:NAME:<NAME>END_PI" :attributes {:age 23 :weight 75 :height 180 :shape "good"}}) (defn my-assoc-in [m [k & ks] v] (let [part (if (empty? ks) (assoc m k v) (assoc {} k (my-assoc-in {} ks v)))] (merge m part))) (println (my-assoc-in {:name "PI:NAME:<NAME>END_PI"} [:attributes :age] 23)) (println (my-assoc-in {:name "PI:NAME:<NAME>END_PI"} [:age] 23)) (println ((comp :age :attributes) record)) (println (attr record :age)) (defn my-update-in [m [k & ks] f & args] (if (empty? ks) (assoc m k (apply f (get m k) args)) (assoc m k (apply my-update-in (get m k) ks f args)))) (println (my-update-in record [:attributes :shape] str " very")) (def lucky-number (concat '(+ 1 2) [10])) (println (eval lucky-number)) (eval (eval (read-string "(list println \"matija\" \"interstellar\")")))
[ { "context": " 12.34)\n - `:name` [string]: payer name. ex: \\\"Iron Bank S.A.\\\"\n - `:tax-id` [string]: payer tax ID (CPF or CN", "end": 625, "score": 0.9830968976020813, "start": 612, "tag": "NAME", "value": "Iron Bank S.A" }, { "context": "ap]\n (let [{\n amount \"amount\"\n name \"name\"\n tax-id \"tax-id\"\n due \"due\"\n expi", "end": 3748, "score": 0.7996777296066284, "start": 3744, "tag": "NAME", "value": "name" }, { "context": "34)\n - name [string]: payer full name. ex: \\\"Anthony Edward Stark\\\"\n - tax-id [string]: payer tax ID (CPF or C", "end": 15284, "score": 0.9998693466186523, "start": 15264, "tag": "NAME", "value": "Anthony Edward Stark" } ]
src/starkbank/invoice.clj
starkbank/sdk-clojure
5
(ns starkbank.invoice "When you initialize an Invoice map, the entity will not be automatically sent to the Stark Bank API. The 'create' function sends the maps to the Stark Bank API and returns the list of created maps. To create scheduled Invoices, which will display the discount, interest, etc. on the final users banking interface, use dates instead of datetimes on the \"due\" and \"discounts\" fields. ## Parameters (required): - `:amount` [integer]: Invoice value in cents. Minimum amount = 0 (any value will be accepted). ex: 1234 (= R$ 12.34) - `:name` [string]: payer name. ex: \"Iron Bank S.A.\" - `:tax-id` [string]: payer tax ID (CPF or CNPJ) with or without formatting. ex: \"01234567890\" or \"20.018.183/0001-80\" ## Parameters (optional): - `:due` [string, default now + 2 days]: Invoice due date in ISO format. ex: \"2020-11-27T01:24:01.665-00:00\" - `:expiration` [integer, default 5097600 (59 days)]: time interval in seconds between due date and expiration date. ex 123456789 - `:fine` [float, default 2.0]: Invoice fine for overdue payment in %. ex: 2.5 - `:interest` [float, default 1.0]: Invoice monthly interest for overdue payment in %. ex: 5.2 - `:discounts` [list of maps, default nil]: list of maps with :percentage (float) and :due (string) pairs - `:tags` [list of strings, default nil]: list of strings for tagging - `:descriptions` [list of maps, default nil]: list of maps with :key (string) and :value (string) pairs ## Attributes (return-only): - `:fee` [integer, default nil]: fee charged by this Invoice. ex: 65 (= R$ 0.65) - `:pdf` [string, default nil]: public Invoice PDF URL. ex: \"https://invoice.starkbank.com/pdf/d454fa4e524441c1b0c1a729457ed9d8\" - `:link` [string, default nil]: public Invoice webpage URL. ex: \"https://my-workspace.sandbox.starkbank.com/invoicelink/d454fa4e524441c1b0c1a729457ed9d8\" - `:nominal-amount` [integer, default nil]: Invoice emission value in cents (will change if invoice is updated, but not if it's paid). ex: 400000 - `:fine-amount` [integer, default nil]: Invoice fine value calculated over nominal-amount. ex: 20000 - `:interest-amount` [integer, default nil]: Invoice interest value calculated over nominal-amount. ex: 10000 - `:discount-amount` [integer, default nil]: Invoice discount value calculated over nominal-amount. ex: 3000 - `:transaction-ids` [list of strings]: ledger transaction ids linked to this invoice (if there are more than one, all but first are reversals). ex: [\"19827356981273\"] - `:id` [string, default nil]: unique id returned when the Invoice is created. ex: \"5656565656565656\" - `:brcode` [string, default nil]: BR Code for the Invoice payment. ex: \"00020101021226800014br.gov.bcb.pix2558invoice.starkbank.com/f5333103-3279-4db2-8389-5efe335ba93d5204000053039865802BR5913Arya Stark6009Sao Paulo6220051656565656565656566304A9A0\" - `:status` [string, default nil]: current Invoice status. ex: \"registered\" or \"paid\" - `:created` [string, default nil]: creation datetime for the Invoice. ex: \"2020-03-26T19:32:35.418698+00:00\" - `:updated` [string, default nil]: latest update datetime for the Invoice. ex: \"2020-03-26T19:32:35.418698+00:00\"" (:refer-clojure :exclude [get set update]) (:import [com.starkbank Invoice]) (:use [starkbank.user] [clojure.walk])) (defn- clojure-descriptions-to-java ([clojure-map] (let [{ key "key" value "value" } (stringify-keys clojure-map)] (java.util.HashMap. { "key" key "value" value } )))) (defn- clojure-to-java ([clojure-map] (let [{ amount "amount" name "name" tax-id "tax-id" due "due" expiration "expiration" fine "fine" interest "interest" discounts "discounts" tags "tags" descriptions "descriptions" } (stringify-keys clojure-map)] (defn- apply-java-hashmap [x] (java.util.HashMap. x)) (Invoice. (java.util.HashMap. { "amount" (if (nil? amount) nil (Long. amount)) "name" name "taxId" tax-id "due" due "expiration" (if (nil? expiration) nil (Long. expiration)) "fine" (if (nil? fine) nil (double fine)) "interest" (if (nil? interest) nil (double interest)) "discounts" (if (nil? discounts) nil (java.util.ArrayList. (map apply-java-hashmap discounts))) "tags" (if (nil? tags) nil (into-array String tags)) "descriptions" (if (nil? descriptions) nil (java.util.ArrayList. (map clojure-descriptions-to-java descriptions))) } ))))) (defn- java-to-clojure ([java-object] (defn- java-description-to-map [description] (if (nil? (.key description)) {:key (.value description)} { :key (.key description) :value (.value description)})) (defn- java-discount-to-map [discount] { :percentage (.percentage discount) :due (.due discount)}) { :id (.id java-object) :amount (.amount java-object) :name (.name java-object) :tax-id (.taxId java-object) :due (.due java-object) :expiration (.expiration java-object) :fine (.fine java-object) :interest (.interest java-object) :tags (into [] (.tags java-object)) :descriptions (into [] (keywordize-keys (map java-description-to-map (.descriptions java-object)))) :discounts (into [] (keywordize-keys (map java-discount-to-map (.discounts java-object)))) :fee (.fee java-object) :pdf (.pdf java-object) :link (.link java-object) :nominal-amount (.nominalAmount java-object) :fine-amount (.fineAmount java-object) :interest-amount (.interestAmount java-object) :discount-amount (.discountAmount java-object) :transaction-ids (into [] (.transactionIds java-object)) :brcode (.brcode java-object) :status (.status java-object) :created (.created java-object) :updated (.updated java-object) })) (defn- java-payment-to-clojure ([java-object] (defn- java-description-to-map [description] (if (nil? (.key description)) {:key (.value description)} {:key (.key description) :value (.value description)})) { :amount (.amount java-object) :name (.name java-object) :tax-id (.taxId java-object) :bank-code (.bankCode java-object) :branch-code (.branchCode java-object) :account-number (.accountNumber java-object) :account-type (.accountType java-object) :end-to-end-id (.endToEndId java-object) :method (.method java-object) })) (defn- clojure-query-to-java ([clojure-map] (let [{ limit "limit" after "after" before "before" status "status" tags "tags" ids "ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "status" status "tags" (if (nil? tags) nil (into-array String tags)) "ids" (if (nil? ids) nil (into-array String ids)) } )))) (defn- clojure-page-to-java ([clojure-map] (let [{ cursor "cursor" limit "limit" after "after" before "before" status "status" tags "tags" ids "ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "cursor" cursor "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "status" status "tags" (if (nil? tags) nil (into-array String tags)) "ids" (if (nil? ids) nil (into-array String ids)) } )))) (defn- clojure-update-to-java ([clojure-map] (let [{ status "status" amount "amount" due "due" expiration "expiration" } (stringify-keys clojure-map)] (java.util.HashMap. { "status" status "amount" (if (nil? amount) nil (Long. amount)) "due" due "expiration" (if (nil? expiration) nil (Long. expiration)) })))) (defn create "Send a list of Invoice maps for creation in the Stark Bank API ## Parameters (required): - `invoices` [list of Invoice maps]: list of Invoice maps to be created in the API ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - list of Invoice maps with updated attributes" ([invoices] (def java-invoices (map clojure-to-java invoices)) (def created-java-invoices (Invoice/create java-invoices)) (map java-to-clojure created-java-invoices)) ([invoices, user] (def java-invoices (map clojure-to-java invoices)) (def created-java-invoices (Invoice/create java-invoices (#'starkbank.user/get-java-user user))) (map java-to-clojure created-java-invoices))) (defn query "Receive a stream of Invoice maps previously created in the Stark Bank API. Use this function instead of page if you want to stream the objects without worrying about cursors and pagination. ## Options: - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:status` [string, default nil]: filter for status of retrieved maps. ex: \"created\", \"paid\", \"canceled\" or \"overdue\" - `:tags` [list of strings, default nil]: tags to filter retrieved maps. ex: [\"tony\", \"stark\"] - `:ids` [list of strings, default nil]: list of ids to filter retrieved maps. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - stream of Invoice maps with updated attributes" ([] (map java-to-clojure (Invoice/query))) ([params] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice/query java-params))) ([params, user] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice/query java-params (#'starkbank.user/get-java-user user))))) (defn page "Receive a list of up to 100 Invoice maps previously created in the Stark Bank API and the cursor to the next page. Use this function instead of query if you want to manually page your requests. ## Options: - `:cursor` [string, default nil]: cursor returned on the previous page function call - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:status` [string, default nil]: filter for status of retrieved maps. ex: \"created\", \"paid\", \"canceled\" or \"overdue\" - `:tags` [list of strings, default nil]: tags to filter retrieved maps. ex: [\"tony\", \"stark\"] - `:ids` [list of strings, default nil]: list of ids to filter retrieved maps. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - map with :invoices and :cursor: - `:invoices`: list of invoice maps with updated attributes - `:cursor`: cursor string to retrieve the next page of invoices" ([] (def invoice-page (Invoice/page)) (def cursor (.cursor invoice-page)) (def invoices (map java-to-clojure (.invoices invoice-page))) {:invoices invoices, :cursor cursor}) ([params] (def java-params (clojure-page-to-java params)) (def invoice-page (Invoice/page java-params)) {:invoices (map java-to-clojure (.invoices invoice-page)), :cursor (.cursor invoice-page)}) ([params, user] (def java-params (clojure-page-to-java params)) (def invoice-page (Invoice/page java-params (#'starkbank.user/get-java-user user))) {:invoices (map java-to-clojure (.invoices invoice-page)), :cursor (.cursor invoice-page)})) (defn get "Receive a single Invoice map previously created in the Stark Bank API by passing its id ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice map with updated attributes" ([id] (java-to-clojure (Invoice/get id))) ([id, user] (java-to-clojure (Invoice/get id (#'starkbank.user/get-java-user user))))) (defn pdf "Receive a single Invoice pdf file generated in the Stark Bank API by passing its id. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice pdf file content" ([id] (clojure.java.io/input-stream (Invoice/pdf id))) ([id, user] (clojure.java.io/input-stream (Invoice/pdf id (#'starkbank.user/get-java-user user))))) (defn qrcode "Receive a single Invoice QRCode in png format generated in the Stark Bank API by the invoice ID. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice QR Code png blob" ([id] (Invoice/qrcode id)) ([id, user] (Invoice/qrcode id (#'starkbank.user/get-java-user user)))) (defn payment "Receive the invoice.payment sub-resource associated with a paid invoice. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice payment information: - amount [integer]: amount in cents that was paid. ex: 1234 (= R$ 12.34) - name [string]: payer full name. ex: \"Anthony Edward Stark\" - tax-id [string]: payer tax ID (CPF or CNPJ). ex: \"20.018.183/0001-80\" - bank-code [string]: code of the payer bank institution in Brazil. ex: \"20018183\" - branch-code [string]: payer bank account branch. ex: \"1357-9\" - account-number [string]: payer bank account number. ex: \"876543-2\" - account-type [string]: payer bank account type. ex: \"checking\", \"savings\", \"salary\" or \"payment\" - end-to-end-id [string]: central bank's unique transaction ID. ex: \"E79457883202101262140HHX553UPqeq\" - method [string]: payment method that was used. ex: \"pix\"" ([id] (java-payment-to-clojure (Invoice/payment id))) ([id, user] (java-payment-to-clojure (Invoice/payment id (#'starkbank.user/get-java-user user))))) (defn update "Update an Invoice by passing id. ## Parameters (required): - `:id` [list of strings]: Invoice unique ids. ex: \"5656565656565656\" ## Parameters (optional): - `:status` [string, default nil]: If the Invoice hasn't been paid yet, you may cancel it by passing \"canceled\" in the status - `:amount` [integer, default nil]: If the Invoice hasn't been paid yet, you may update its amount by passing the desired amount integer - `:due` [string, default today + 2 days]: Invoice due date in UTC ISO format. ex: \"2020-11-25T17:59:26.249976+00:00\" - `:expiration` [DateInterval or integer, default nil]: time interval in seconds between due date and expiration date. ex 123456789 - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - target Invoice with updated attributes" ([id, params] (java-to-clojure (Invoice/update id (clojure-update-to-java params)))) ([id, params, user] (java-to-clojure (Invoice/update id (clojure-update-to-java params) (#'starkbank.user/get-java-user user))))) (ns starkbank.invoice.log "Every time an Invoice entity is updated, a corresponding Invoice.Log is generated for the entity. This log is never generated by the user, but it can be retrieved to check additional information on the Invoice. ## Attributes: - `:id` [string]: unique id returned when the log is created. ex: \"5656565656565656\" - `:invoice` [Invoice]: Invoice entity to which the log refers to. - `:errors` [list of strings]: list of errors linked to this Invoice event - `:type` [string]: type of the Invoice event which triggered the log creation. ex: \"registered\" or \"paid\" - `:created` [string]: creation datetime for the log. ex: \"2020-03-26T19:32:35.418698+00:00\"" (:refer-clojure :exclude [get set]) (:import [com.starkbank Invoice$Log]) (:require [starkbank.invoice :as invoice]) (:use [starkbank.user] [clojure.walk])) (defn- java-to-clojure ([java-object] { :id (.id java-object) :created (.created java-object) :errors (into [] (.errors java-object)) :type (.type java-object) :invoice (#'invoice/java-to-clojure (.invoice java-object)) })) (defn- clojure-query-to-java ([clojure-map] (let [{ limit "limit" after "after" before "before" types "types" invoice-ids "invoice-ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "types" (if (nil? types) nil (into-array String types)) "invoiceIds" (if (nil? invoice-ids) nil (into-array String invoice-ids)) } )))) (defn- clojure-page-to-java ([clojure-map] (let [{ cursor "cursor" limit "limit" after "after" before "before" types "types" invoice-ids "invoice-ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "cursor" cursor "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "types" (if (nil? types) nil (into-array String types)) "invoiceIds" (if (nil? invoice-ids) nil (into-array String invoice-ids)) } )))) (defn get "Receive a single Log map previously created by the Stark Bank API by passing its id ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Log map with updated attributes" ([id] (java-to-clojure (Invoice$Log/get id))) ([id, user] (java-to-clojure (Invoice$Log/get id (#'starkbank.user/get-java-user user))))) (defn query "Receive a stream of Log maps previously created in the Stark Bank API. Use this function instead of page if you want to stream the objects without worrying about cursors and pagination. ## Options: - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:types` [list of strings, default nil]: filter for log event types. ex: \"paid\" or \"registered\" - `:invoice-ids` [list of strings, default nil]: list of Invoice ids to filter logs. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - stream of Log maps with updated attributes" ([] (map java-to-clojure (Invoice$Log/query))) ([params] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice$Log/query java-params))) ([params, user] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice$Log/query java-params (#'starkbank.user/get-java-user user))))) (defn page "Receive a list of up to 100 Invoice.Log maps previously created in the Stark Bank API and the cursor to the next page. Use this function instead of query if you want to manually page your requests. ## Options: - `:cursor` [string, default nil]: cursor returned on the previous page function call - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:types` [list of strings, default nil]: filter for log event types. ex: \"paid\" or \"registered\" - `:invoice-ids` [list of strings, default nil]: list of Invoice ids to filter logs. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - map with :logs and :cursor: - `:logs`: list of log maps with updated attributes - `:cursor`: cursor string to retrieve the next page of logs" ([] (def log-page (Invoice$Log/page)) (def cursor (.cursor log-page)) (def logs (map java-to-clojure (.logs log-page))) {:logs logs, :cursor cursor}) ([params] (def java-params (clojure-page-to-java params)) (def log-page (Invoice$Log/page java-params)) {:logs (map java-to-clojure (.logs log-page)), :cursor (.cursor log-page)}) ([params, user] (def java-params (clojure-page-to-java params)) (def log-page (Invoice$Log/page java-params (#'starkbank.user/get-java-user user))) {:logs (map java-to-clojure (.logs log-page)), :cursor (.cursor log-page)})) (defn pdf "Receive a single Invoice pdf file generated in the Stark Bank API by passing its id. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice pdf file content" ([id] (clojure.java.io/input-stream (Invoice$Log/pdf id))) ([id, user] (clojure.java.io/input-stream (Invoice$Log/pdf id (#'starkbank.user/get-java-user user)))))
82822
(ns starkbank.invoice "When you initialize an Invoice map, the entity will not be automatically sent to the Stark Bank API. The 'create' function sends the maps to the Stark Bank API and returns the list of created maps. To create scheduled Invoices, which will display the discount, interest, etc. on the final users banking interface, use dates instead of datetimes on the \"due\" and \"discounts\" fields. ## Parameters (required): - `:amount` [integer]: Invoice value in cents. Minimum amount = 0 (any value will be accepted). ex: 1234 (= R$ 12.34) - `:name` [string]: payer name. ex: \"<NAME>.\" - `:tax-id` [string]: payer tax ID (CPF or CNPJ) with or without formatting. ex: \"01234567890\" or \"20.018.183/0001-80\" ## Parameters (optional): - `:due` [string, default now + 2 days]: Invoice due date in ISO format. ex: \"2020-11-27T01:24:01.665-00:00\" - `:expiration` [integer, default 5097600 (59 days)]: time interval in seconds between due date and expiration date. ex 123456789 - `:fine` [float, default 2.0]: Invoice fine for overdue payment in %. ex: 2.5 - `:interest` [float, default 1.0]: Invoice monthly interest for overdue payment in %. ex: 5.2 - `:discounts` [list of maps, default nil]: list of maps with :percentage (float) and :due (string) pairs - `:tags` [list of strings, default nil]: list of strings for tagging - `:descriptions` [list of maps, default nil]: list of maps with :key (string) and :value (string) pairs ## Attributes (return-only): - `:fee` [integer, default nil]: fee charged by this Invoice. ex: 65 (= R$ 0.65) - `:pdf` [string, default nil]: public Invoice PDF URL. ex: \"https://invoice.starkbank.com/pdf/d454fa4e524441c1b0c1a729457ed9d8\" - `:link` [string, default nil]: public Invoice webpage URL. ex: \"https://my-workspace.sandbox.starkbank.com/invoicelink/d454fa4e524441c1b0c1a729457ed9d8\" - `:nominal-amount` [integer, default nil]: Invoice emission value in cents (will change if invoice is updated, but not if it's paid). ex: 400000 - `:fine-amount` [integer, default nil]: Invoice fine value calculated over nominal-amount. ex: 20000 - `:interest-amount` [integer, default nil]: Invoice interest value calculated over nominal-amount. ex: 10000 - `:discount-amount` [integer, default nil]: Invoice discount value calculated over nominal-amount. ex: 3000 - `:transaction-ids` [list of strings]: ledger transaction ids linked to this invoice (if there are more than one, all but first are reversals). ex: [\"19827356981273\"] - `:id` [string, default nil]: unique id returned when the Invoice is created. ex: \"5656565656565656\" - `:brcode` [string, default nil]: BR Code for the Invoice payment. ex: \"00020101021226800014br.gov.bcb.pix2558invoice.starkbank.com/f5333103-3279-4db2-8389-5efe335ba93d5204000053039865802BR5913Arya Stark6009Sao Paulo6220051656565656565656566304A9A0\" - `:status` [string, default nil]: current Invoice status. ex: \"registered\" or \"paid\" - `:created` [string, default nil]: creation datetime for the Invoice. ex: \"2020-03-26T19:32:35.418698+00:00\" - `:updated` [string, default nil]: latest update datetime for the Invoice. ex: \"2020-03-26T19:32:35.418698+00:00\"" (:refer-clojure :exclude [get set update]) (:import [com.starkbank Invoice]) (:use [starkbank.user] [clojure.walk])) (defn- clojure-descriptions-to-java ([clojure-map] (let [{ key "key" value "value" } (stringify-keys clojure-map)] (java.util.HashMap. { "key" key "value" value } )))) (defn- clojure-to-java ([clojure-map] (let [{ amount "amount" name "<NAME>" tax-id "tax-id" due "due" expiration "expiration" fine "fine" interest "interest" discounts "discounts" tags "tags" descriptions "descriptions" } (stringify-keys clojure-map)] (defn- apply-java-hashmap [x] (java.util.HashMap. x)) (Invoice. (java.util.HashMap. { "amount" (if (nil? amount) nil (Long. amount)) "name" name "taxId" tax-id "due" due "expiration" (if (nil? expiration) nil (Long. expiration)) "fine" (if (nil? fine) nil (double fine)) "interest" (if (nil? interest) nil (double interest)) "discounts" (if (nil? discounts) nil (java.util.ArrayList. (map apply-java-hashmap discounts))) "tags" (if (nil? tags) nil (into-array String tags)) "descriptions" (if (nil? descriptions) nil (java.util.ArrayList. (map clojure-descriptions-to-java descriptions))) } ))))) (defn- java-to-clojure ([java-object] (defn- java-description-to-map [description] (if (nil? (.key description)) {:key (.value description)} { :key (.key description) :value (.value description)})) (defn- java-discount-to-map [discount] { :percentage (.percentage discount) :due (.due discount)}) { :id (.id java-object) :amount (.amount java-object) :name (.name java-object) :tax-id (.taxId java-object) :due (.due java-object) :expiration (.expiration java-object) :fine (.fine java-object) :interest (.interest java-object) :tags (into [] (.tags java-object)) :descriptions (into [] (keywordize-keys (map java-description-to-map (.descriptions java-object)))) :discounts (into [] (keywordize-keys (map java-discount-to-map (.discounts java-object)))) :fee (.fee java-object) :pdf (.pdf java-object) :link (.link java-object) :nominal-amount (.nominalAmount java-object) :fine-amount (.fineAmount java-object) :interest-amount (.interestAmount java-object) :discount-amount (.discountAmount java-object) :transaction-ids (into [] (.transactionIds java-object)) :brcode (.brcode java-object) :status (.status java-object) :created (.created java-object) :updated (.updated java-object) })) (defn- java-payment-to-clojure ([java-object] (defn- java-description-to-map [description] (if (nil? (.key description)) {:key (.value description)} {:key (.key description) :value (.value description)})) { :amount (.amount java-object) :name (.name java-object) :tax-id (.taxId java-object) :bank-code (.bankCode java-object) :branch-code (.branchCode java-object) :account-number (.accountNumber java-object) :account-type (.accountType java-object) :end-to-end-id (.endToEndId java-object) :method (.method java-object) })) (defn- clojure-query-to-java ([clojure-map] (let [{ limit "limit" after "after" before "before" status "status" tags "tags" ids "ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "status" status "tags" (if (nil? tags) nil (into-array String tags)) "ids" (if (nil? ids) nil (into-array String ids)) } )))) (defn- clojure-page-to-java ([clojure-map] (let [{ cursor "cursor" limit "limit" after "after" before "before" status "status" tags "tags" ids "ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "cursor" cursor "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "status" status "tags" (if (nil? tags) nil (into-array String tags)) "ids" (if (nil? ids) nil (into-array String ids)) } )))) (defn- clojure-update-to-java ([clojure-map] (let [{ status "status" amount "amount" due "due" expiration "expiration" } (stringify-keys clojure-map)] (java.util.HashMap. { "status" status "amount" (if (nil? amount) nil (Long. amount)) "due" due "expiration" (if (nil? expiration) nil (Long. expiration)) })))) (defn create "Send a list of Invoice maps for creation in the Stark Bank API ## Parameters (required): - `invoices` [list of Invoice maps]: list of Invoice maps to be created in the API ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - list of Invoice maps with updated attributes" ([invoices] (def java-invoices (map clojure-to-java invoices)) (def created-java-invoices (Invoice/create java-invoices)) (map java-to-clojure created-java-invoices)) ([invoices, user] (def java-invoices (map clojure-to-java invoices)) (def created-java-invoices (Invoice/create java-invoices (#'starkbank.user/get-java-user user))) (map java-to-clojure created-java-invoices))) (defn query "Receive a stream of Invoice maps previously created in the Stark Bank API. Use this function instead of page if you want to stream the objects without worrying about cursors and pagination. ## Options: - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:status` [string, default nil]: filter for status of retrieved maps. ex: \"created\", \"paid\", \"canceled\" or \"overdue\" - `:tags` [list of strings, default nil]: tags to filter retrieved maps. ex: [\"tony\", \"stark\"] - `:ids` [list of strings, default nil]: list of ids to filter retrieved maps. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - stream of Invoice maps with updated attributes" ([] (map java-to-clojure (Invoice/query))) ([params] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice/query java-params))) ([params, user] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice/query java-params (#'starkbank.user/get-java-user user))))) (defn page "Receive a list of up to 100 Invoice maps previously created in the Stark Bank API and the cursor to the next page. Use this function instead of query if you want to manually page your requests. ## Options: - `:cursor` [string, default nil]: cursor returned on the previous page function call - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:status` [string, default nil]: filter for status of retrieved maps. ex: \"created\", \"paid\", \"canceled\" or \"overdue\" - `:tags` [list of strings, default nil]: tags to filter retrieved maps. ex: [\"tony\", \"stark\"] - `:ids` [list of strings, default nil]: list of ids to filter retrieved maps. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - map with :invoices and :cursor: - `:invoices`: list of invoice maps with updated attributes - `:cursor`: cursor string to retrieve the next page of invoices" ([] (def invoice-page (Invoice/page)) (def cursor (.cursor invoice-page)) (def invoices (map java-to-clojure (.invoices invoice-page))) {:invoices invoices, :cursor cursor}) ([params] (def java-params (clojure-page-to-java params)) (def invoice-page (Invoice/page java-params)) {:invoices (map java-to-clojure (.invoices invoice-page)), :cursor (.cursor invoice-page)}) ([params, user] (def java-params (clojure-page-to-java params)) (def invoice-page (Invoice/page java-params (#'starkbank.user/get-java-user user))) {:invoices (map java-to-clojure (.invoices invoice-page)), :cursor (.cursor invoice-page)})) (defn get "Receive a single Invoice map previously created in the Stark Bank API by passing its id ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice map with updated attributes" ([id] (java-to-clojure (Invoice/get id))) ([id, user] (java-to-clojure (Invoice/get id (#'starkbank.user/get-java-user user))))) (defn pdf "Receive a single Invoice pdf file generated in the Stark Bank API by passing its id. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice pdf file content" ([id] (clojure.java.io/input-stream (Invoice/pdf id))) ([id, user] (clojure.java.io/input-stream (Invoice/pdf id (#'starkbank.user/get-java-user user))))) (defn qrcode "Receive a single Invoice QRCode in png format generated in the Stark Bank API by the invoice ID. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice QR Code png blob" ([id] (Invoice/qrcode id)) ([id, user] (Invoice/qrcode id (#'starkbank.user/get-java-user user)))) (defn payment "Receive the invoice.payment sub-resource associated with a paid invoice. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice payment information: - amount [integer]: amount in cents that was paid. ex: 1234 (= R$ 12.34) - name [string]: payer full name. ex: \"<NAME>\" - tax-id [string]: payer tax ID (CPF or CNPJ). ex: \"20.018.183/0001-80\" - bank-code [string]: code of the payer bank institution in Brazil. ex: \"20018183\" - branch-code [string]: payer bank account branch. ex: \"1357-9\" - account-number [string]: payer bank account number. ex: \"876543-2\" - account-type [string]: payer bank account type. ex: \"checking\", \"savings\", \"salary\" or \"payment\" - end-to-end-id [string]: central bank's unique transaction ID. ex: \"E79457883202101262140HHX553UPqeq\" - method [string]: payment method that was used. ex: \"pix\"" ([id] (java-payment-to-clojure (Invoice/payment id))) ([id, user] (java-payment-to-clojure (Invoice/payment id (#'starkbank.user/get-java-user user))))) (defn update "Update an Invoice by passing id. ## Parameters (required): - `:id` [list of strings]: Invoice unique ids. ex: \"5656565656565656\" ## Parameters (optional): - `:status` [string, default nil]: If the Invoice hasn't been paid yet, you may cancel it by passing \"canceled\" in the status - `:amount` [integer, default nil]: If the Invoice hasn't been paid yet, you may update its amount by passing the desired amount integer - `:due` [string, default today + 2 days]: Invoice due date in UTC ISO format. ex: \"2020-11-25T17:59:26.249976+00:00\" - `:expiration` [DateInterval or integer, default nil]: time interval in seconds between due date and expiration date. ex 123456789 - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - target Invoice with updated attributes" ([id, params] (java-to-clojure (Invoice/update id (clojure-update-to-java params)))) ([id, params, user] (java-to-clojure (Invoice/update id (clojure-update-to-java params) (#'starkbank.user/get-java-user user))))) (ns starkbank.invoice.log "Every time an Invoice entity is updated, a corresponding Invoice.Log is generated for the entity. This log is never generated by the user, but it can be retrieved to check additional information on the Invoice. ## Attributes: - `:id` [string]: unique id returned when the log is created. ex: \"5656565656565656\" - `:invoice` [Invoice]: Invoice entity to which the log refers to. - `:errors` [list of strings]: list of errors linked to this Invoice event - `:type` [string]: type of the Invoice event which triggered the log creation. ex: \"registered\" or \"paid\" - `:created` [string]: creation datetime for the log. ex: \"2020-03-26T19:32:35.418698+00:00\"" (:refer-clojure :exclude [get set]) (:import [com.starkbank Invoice$Log]) (:require [starkbank.invoice :as invoice]) (:use [starkbank.user] [clojure.walk])) (defn- java-to-clojure ([java-object] { :id (.id java-object) :created (.created java-object) :errors (into [] (.errors java-object)) :type (.type java-object) :invoice (#'invoice/java-to-clojure (.invoice java-object)) })) (defn- clojure-query-to-java ([clojure-map] (let [{ limit "limit" after "after" before "before" types "types" invoice-ids "invoice-ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "types" (if (nil? types) nil (into-array String types)) "invoiceIds" (if (nil? invoice-ids) nil (into-array String invoice-ids)) } )))) (defn- clojure-page-to-java ([clojure-map] (let [{ cursor "cursor" limit "limit" after "after" before "before" types "types" invoice-ids "invoice-ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "cursor" cursor "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "types" (if (nil? types) nil (into-array String types)) "invoiceIds" (if (nil? invoice-ids) nil (into-array String invoice-ids)) } )))) (defn get "Receive a single Log map previously created by the Stark Bank API by passing its id ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Log map with updated attributes" ([id] (java-to-clojure (Invoice$Log/get id))) ([id, user] (java-to-clojure (Invoice$Log/get id (#'starkbank.user/get-java-user user))))) (defn query "Receive a stream of Log maps previously created in the Stark Bank API. Use this function instead of page if you want to stream the objects without worrying about cursors and pagination. ## Options: - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:types` [list of strings, default nil]: filter for log event types. ex: \"paid\" or \"registered\" - `:invoice-ids` [list of strings, default nil]: list of Invoice ids to filter logs. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - stream of Log maps with updated attributes" ([] (map java-to-clojure (Invoice$Log/query))) ([params] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice$Log/query java-params))) ([params, user] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice$Log/query java-params (#'starkbank.user/get-java-user user))))) (defn page "Receive a list of up to 100 Invoice.Log maps previously created in the Stark Bank API and the cursor to the next page. Use this function instead of query if you want to manually page your requests. ## Options: - `:cursor` [string, default nil]: cursor returned on the previous page function call - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:types` [list of strings, default nil]: filter for log event types. ex: \"paid\" or \"registered\" - `:invoice-ids` [list of strings, default nil]: list of Invoice ids to filter logs. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - map with :logs and :cursor: - `:logs`: list of log maps with updated attributes - `:cursor`: cursor string to retrieve the next page of logs" ([] (def log-page (Invoice$Log/page)) (def cursor (.cursor log-page)) (def logs (map java-to-clojure (.logs log-page))) {:logs logs, :cursor cursor}) ([params] (def java-params (clojure-page-to-java params)) (def log-page (Invoice$Log/page java-params)) {:logs (map java-to-clojure (.logs log-page)), :cursor (.cursor log-page)}) ([params, user] (def java-params (clojure-page-to-java params)) (def log-page (Invoice$Log/page java-params (#'starkbank.user/get-java-user user))) {:logs (map java-to-clojure (.logs log-page)), :cursor (.cursor log-page)})) (defn pdf "Receive a single Invoice pdf file generated in the Stark Bank API by passing its id. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice pdf file content" ([id] (clojure.java.io/input-stream (Invoice$Log/pdf id))) ([id, user] (clojure.java.io/input-stream (Invoice$Log/pdf id (#'starkbank.user/get-java-user user)))))
true
(ns starkbank.invoice "When you initialize an Invoice map, the entity will not be automatically sent to the Stark Bank API. The 'create' function sends the maps to the Stark Bank API and returns the list of created maps. To create scheduled Invoices, which will display the discount, interest, etc. on the final users banking interface, use dates instead of datetimes on the \"due\" and \"discounts\" fields. ## Parameters (required): - `:amount` [integer]: Invoice value in cents. Minimum amount = 0 (any value will be accepted). ex: 1234 (= R$ 12.34) - `:name` [string]: payer name. ex: \"PI:NAME:<NAME>END_PI.\" - `:tax-id` [string]: payer tax ID (CPF or CNPJ) with or without formatting. ex: \"01234567890\" or \"20.018.183/0001-80\" ## Parameters (optional): - `:due` [string, default now + 2 days]: Invoice due date in ISO format. ex: \"2020-11-27T01:24:01.665-00:00\" - `:expiration` [integer, default 5097600 (59 days)]: time interval in seconds between due date and expiration date. ex 123456789 - `:fine` [float, default 2.0]: Invoice fine for overdue payment in %. ex: 2.5 - `:interest` [float, default 1.0]: Invoice monthly interest for overdue payment in %. ex: 5.2 - `:discounts` [list of maps, default nil]: list of maps with :percentage (float) and :due (string) pairs - `:tags` [list of strings, default nil]: list of strings for tagging - `:descriptions` [list of maps, default nil]: list of maps with :key (string) and :value (string) pairs ## Attributes (return-only): - `:fee` [integer, default nil]: fee charged by this Invoice. ex: 65 (= R$ 0.65) - `:pdf` [string, default nil]: public Invoice PDF URL. ex: \"https://invoice.starkbank.com/pdf/d454fa4e524441c1b0c1a729457ed9d8\" - `:link` [string, default nil]: public Invoice webpage URL. ex: \"https://my-workspace.sandbox.starkbank.com/invoicelink/d454fa4e524441c1b0c1a729457ed9d8\" - `:nominal-amount` [integer, default nil]: Invoice emission value in cents (will change if invoice is updated, but not if it's paid). ex: 400000 - `:fine-amount` [integer, default nil]: Invoice fine value calculated over nominal-amount. ex: 20000 - `:interest-amount` [integer, default nil]: Invoice interest value calculated over nominal-amount. ex: 10000 - `:discount-amount` [integer, default nil]: Invoice discount value calculated over nominal-amount. ex: 3000 - `:transaction-ids` [list of strings]: ledger transaction ids linked to this invoice (if there are more than one, all but first are reversals). ex: [\"19827356981273\"] - `:id` [string, default nil]: unique id returned when the Invoice is created. ex: \"5656565656565656\" - `:brcode` [string, default nil]: BR Code for the Invoice payment. ex: \"00020101021226800014br.gov.bcb.pix2558invoice.starkbank.com/f5333103-3279-4db2-8389-5efe335ba93d5204000053039865802BR5913Arya Stark6009Sao Paulo6220051656565656565656566304A9A0\" - `:status` [string, default nil]: current Invoice status. ex: \"registered\" or \"paid\" - `:created` [string, default nil]: creation datetime for the Invoice. ex: \"2020-03-26T19:32:35.418698+00:00\" - `:updated` [string, default nil]: latest update datetime for the Invoice. ex: \"2020-03-26T19:32:35.418698+00:00\"" (:refer-clojure :exclude [get set update]) (:import [com.starkbank Invoice]) (:use [starkbank.user] [clojure.walk])) (defn- clojure-descriptions-to-java ([clojure-map] (let [{ key "key" value "value" } (stringify-keys clojure-map)] (java.util.HashMap. { "key" key "value" value } )))) (defn- clojure-to-java ([clojure-map] (let [{ amount "amount" name "PI:NAME:<NAME>END_PI" tax-id "tax-id" due "due" expiration "expiration" fine "fine" interest "interest" discounts "discounts" tags "tags" descriptions "descriptions" } (stringify-keys clojure-map)] (defn- apply-java-hashmap [x] (java.util.HashMap. x)) (Invoice. (java.util.HashMap. { "amount" (if (nil? amount) nil (Long. amount)) "name" name "taxId" tax-id "due" due "expiration" (if (nil? expiration) nil (Long. expiration)) "fine" (if (nil? fine) nil (double fine)) "interest" (if (nil? interest) nil (double interest)) "discounts" (if (nil? discounts) nil (java.util.ArrayList. (map apply-java-hashmap discounts))) "tags" (if (nil? tags) nil (into-array String tags)) "descriptions" (if (nil? descriptions) nil (java.util.ArrayList. (map clojure-descriptions-to-java descriptions))) } ))))) (defn- java-to-clojure ([java-object] (defn- java-description-to-map [description] (if (nil? (.key description)) {:key (.value description)} { :key (.key description) :value (.value description)})) (defn- java-discount-to-map [discount] { :percentage (.percentage discount) :due (.due discount)}) { :id (.id java-object) :amount (.amount java-object) :name (.name java-object) :tax-id (.taxId java-object) :due (.due java-object) :expiration (.expiration java-object) :fine (.fine java-object) :interest (.interest java-object) :tags (into [] (.tags java-object)) :descriptions (into [] (keywordize-keys (map java-description-to-map (.descriptions java-object)))) :discounts (into [] (keywordize-keys (map java-discount-to-map (.discounts java-object)))) :fee (.fee java-object) :pdf (.pdf java-object) :link (.link java-object) :nominal-amount (.nominalAmount java-object) :fine-amount (.fineAmount java-object) :interest-amount (.interestAmount java-object) :discount-amount (.discountAmount java-object) :transaction-ids (into [] (.transactionIds java-object)) :brcode (.brcode java-object) :status (.status java-object) :created (.created java-object) :updated (.updated java-object) })) (defn- java-payment-to-clojure ([java-object] (defn- java-description-to-map [description] (if (nil? (.key description)) {:key (.value description)} {:key (.key description) :value (.value description)})) { :amount (.amount java-object) :name (.name java-object) :tax-id (.taxId java-object) :bank-code (.bankCode java-object) :branch-code (.branchCode java-object) :account-number (.accountNumber java-object) :account-type (.accountType java-object) :end-to-end-id (.endToEndId java-object) :method (.method java-object) })) (defn- clojure-query-to-java ([clojure-map] (let [{ limit "limit" after "after" before "before" status "status" tags "tags" ids "ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "status" status "tags" (if (nil? tags) nil (into-array String tags)) "ids" (if (nil? ids) nil (into-array String ids)) } )))) (defn- clojure-page-to-java ([clojure-map] (let [{ cursor "cursor" limit "limit" after "after" before "before" status "status" tags "tags" ids "ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "cursor" cursor "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "status" status "tags" (if (nil? tags) nil (into-array String tags)) "ids" (if (nil? ids) nil (into-array String ids)) } )))) (defn- clojure-update-to-java ([clojure-map] (let [{ status "status" amount "amount" due "due" expiration "expiration" } (stringify-keys clojure-map)] (java.util.HashMap. { "status" status "amount" (if (nil? amount) nil (Long. amount)) "due" due "expiration" (if (nil? expiration) nil (Long. expiration)) })))) (defn create "Send a list of Invoice maps for creation in the Stark Bank API ## Parameters (required): - `invoices` [list of Invoice maps]: list of Invoice maps to be created in the API ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - list of Invoice maps with updated attributes" ([invoices] (def java-invoices (map clojure-to-java invoices)) (def created-java-invoices (Invoice/create java-invoices)) (map java-to-clojure created-java-invoices)) ([invoices, user] (def java-invoices (map clojure-to-java invoices)) (def created-java-invoices (Invoice/create java-invoices (#'starkbank.user/get-java-user user))) (map java-to-clojure created-java-invoices))) (defn query "Receive a stream of Invoice maps previously created in the Stark Bank API. Use this function instead of page if you want to stream the objects without worrying about cursors and pagination. ## Options: - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:status` [string, default nil]: filter for status of retrieved maps. ex: \"created\", \"paid\", \"canceled\" or \"overdue\" - `:tags` [list of strings, default nil]: tags to filter retrieved maps. ex: [\"tony\", \"stark\"] - `:ids` [list of strings, default nil]: list of ids to filter retrieved maps. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - stream of Invoice maps with updated attributes" ([] (map java-to-clojure (Invoice/query))) ([params] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice/query java-params))) ([params, user] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice/query java-params (#'starkbank.user/get-java-user user))))) (defn page "Receive a list of up to 100 Invoice maps previously created in the Stark Bank API and the cursor to the next page. Use this function instead of query if you want to manually page your requests. ## Options: - `:cursor` [string, default nil]: cursor returned on the previous page function call - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:status` [string, default nil]: filter for status of retrieved maps. ex: \"created\", \"paid\", \"canceled\" or \"overdue\" - `:tags` [list of strings, default nil]: tags to filter retrieved maps. ex: [\"tony\", \"stark\"] - `:ids` [list of strings, default nil]: list of ids to filter retrieved maps. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - map with :invoices and :cursor: - `:invoices`: list of invoice maps with updated attributes - `:cursor`: cursor string to retrieve the next page of invoices" ([] (def invoice-page (Invoice/page)) (def cursor (.cursor invoice-page)) (def invoices (map java-to-clojure (.invoices invoice-page))) {:invoices invoices, :cursor cursor}) ([params] (def java-params (clojure-page-to-java params)) (def invoice-page (Invoice/page java-params)) {:invoices (map java-to-clojure (.invoices invoice-page)), :cursor (.cursor invoice-page)}) ([params, user] (def java-params (clojure-page-to-java params)) (def invoice-page (Invoice/page java-params (#'starkbank.user/get-java-user user))) {:invoices (map java-to-clojure (.invoices invoice-page)), :cursor (.cursor invoice-page)})) (defn get "Receive a single Invoice map previously created in the Stark Bank API by passing its id ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice map with updated attributes" ([id] (java-to-clojure (Invoice/get id))) ([id, user] (java-to-clojure (Invoice/get id (#'starkbank.user/get-java-user user))))) (defn pdf "Receive a single Invoice pdf file generated in the Stark Bank API by passing its id. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice pdf file content" ([id] (clojure.java.io/input-stream (Invoice/pdf id))) ([id, user] (clojure.java.io/input-stream (Invoice/pdf id (#'starkbank.user/get-java-user user))))) (defn qrcode "Receive a single Invoice QRCode in png format generated in the Stark Bank API by the invoice ID. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice QR Code png blob" ([id] (Invoice/qrcode id)) ([id, user] (Invoice/qrcode id (#'starkbank.user/get-java-user user)))) (defn payment "Receive the invoice.payment sub-resource associated with a paid invoice. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice payment information: - amount [integer]: amount in cents that was paid. ex: 1234 (= R$ 12.34) - name [string]: payer full name. ex: \"PI:NAME:<NAME>END_PI\" - tax-id [string]: payer tax ID (CPF or CNPJ). ex: \"20.018.183/0001-80\" - bank-code [string]: code of the payer bank institution in Brazil. ex: \"20018183\" - branch-code [string]: payer bank account branch. ex: \"1357-9\" - account-number [string]: payer bank account number. ex: \"876543-2\" - account-type [string]: payer bank account type. ex: \"checking\", \"savings\", \"salary\" or \"payment\" - end-to-end-id [string]: central bank's unique transaction ID. ex: \"E79457883202101262140HHX553UPqeq\" - method [string]: payment method that was used. ex: \"pix\"" ([id] (java-payment-to-clojure (Invoice/payment id))) ([id, user] (java-payment-to-clojure (Invoice/payment id (#'starkbank.user/get-java-user user))))) (defn update "Update an Invoice by passing id. ## Parameters (required): - `:id` [list of strings]: Invoice unique ids. ex: \"5656565656565656\" ## Parameters (optional): - `:status` [string, default nil]: If the Invoice hasn't been paid yet, you may cancel it by passing \"canceled\" in the status - `:amount` [integer, default nil]: If the Invoice hasn't been paid yet, you may update its amount by passing the desired amount integer - `:due` [string, default today + 2 days]: Invoice due date in UTC ISO format. ex: \"2020-11-25T17:59:26.249976+00:00\" - `:expiration` [DateInterval or integer, default nil]: time interval in seconds between due date and expiration date. ex 123456789 - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - target Invoice with updated attributes" ([id, params] (java-to-clojure (Invoice/update id (clojure-update-to-java params)))) ([id, params, user] (java-to-clojure (Invoice/update id (clojure-update-to-java params) (#'starkbank.user/get-java-user user))))) (ns starkbank.invoice.log "Every time an Invoice entity is updated, a corresponding Invoice.Log is generated for the entity. This log is never generated by the user, but it can be retrieved to check additional information on the Invoice. ## Attributes: - `:id` [string]: unique id returned when the log is created. ex: \"5656565656565656\" - `:invoice` [Invoice]: Invoice entity to which the log refers to. - `:errors` [list of strings]: list of errors linked to this Invoice event - `:type` [string]: type of the Invoice event which triggered the log creation. ex: \"registered\" or \"paid\" - `:created` [string]: creation datetime for the log. ex: \"2020-03-26T19:32:35.418698+00:00\"" (:refer-clojure :exclude [get set]) (:import [com.starkbank Invoice$Log]) (:require [starkbank.invoice :as invoice]) (:use [starkbank.user] [clojure.walk])) (defn- java-to-clojure ([java-object] { :id (.id java-object) :created (.created java-object) :errors (into [] (.errors java-object)) :type (.type java-object) :invoice (#'invoice/java-to-clojure (.invoice java-object)) })) (defn- clojure-query-to-java ([clojure-map] (let [{ limit "limit" after "after" before "before" types "types" invoice-ids "invoice-ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "types" (if (nil? types) nil (into-array String types)) "invoiceIds" (if (nil? invoice-ids) nil (into-array String invoice-ids)) } )))) (defn- clojure-page-to-java ([clojure-map] (let [{ cursor "cursor" limit "limit" after "after" before "before" types "types" invoice-ids "invoice-ids" } (stringify-keys clojure-map)] (java.util.HashMap. { "cursor" cursor "limit" (if (nil? limit) nil (Integer. limit)) "after" after "before" before "types" (if (nil? types) nil (into-array String types)) "invoiceIds" (if (nil? invoice-ids) nil (into-array String invoice-ids)) } )))) (defn get "Receive a single Log map previously created by the Stark Bank API by passing its id ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Log map with updated attributes" ([id] (java-to-clojure (Invoice$Log/get id))) ([id, user] (java-to-clojure (Invoice$Log/get id (#'starkbank.user/get-java-user user))))) (defn query "Receive a stream of Log maps previously created in the Stark Bank API. Use this function instead of page if you want to stream the objects without worrying about cursors and pagination. ## Options: - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:types` [list of strings, default nil]: filter for log event types. ex: \"paid\" or \"registered\" - `:invoice-ids` [list of strings, default nil]: list of Invoice ids to filter logs. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - stream of Log maps with updated attributes" ([] (map java-to-clojure (Invoice$Log/query))) ([params] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice$Log/query java-params))) ([params, user] (def java-params (clojure-query-to-java params)) (map java-to-clojure (Invoice$Log/query java-params (#'starkbank.user/get-java-user user))))) (defn page "Receive a list of up to 100 Invoice.Log maps previously created in the Stark Bank API and the cursor to the next page. Use this function instead of query if you want to manually page your requests. ## Options: - `:cursor` [string, default nil]: cursor returned on the previous page function call - `:limit` [integer, default nil]: maximum number of maps to be retrieved. Unlimited if nil. ex: 35 - `:after` [string, default nil]: date filter for maps created only after specified date. ex: \"2020-3-10\" - `:before` [string, default nil]: date filter for maps created only before specified date. ex: \"2020-3-10\" - `:types` [list of strings, default nil]: filter for log event types. ex: \"paid\" or \"registered\" - `:invoice-ids` [list of strings, default nil]: list of Invoice ids to filter logs. ex: [\"5656565656565656\", \"4545454545454545\"] - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - map with :logs and :cursor: - `:logs`: list of log maps with updated attributes - `:cursor`: cursor string to retrieve the next page of logs" ([] (def log-page (Invoice$Log/page)) (def cursor (.cursor log-page)) (def logs (map java-to-clojure (.logs log-page))) {:logs logs, :cursor cursor}) ([params] (def java-params (clojure-page-to-java params)) (def log-page (Invoice$Log/page java-params)) {:logs (map java-to-clojure (.logs log-page)), :cursor (.cursor log-page)}) ([params, user] (def java-params (clojure-page-to-java params)) (def log-page (Invoice$Log/page java-params (#'starkbank.user/get-java-user user))) {:logs (map java-to-clojure (.logs log-page)), :cursor (.cursor log-page)})) (defn pdf "Receive a single Invoice pdf file generated in the Stark Bank API by passing its id. ## Parameters (required): - `:id` [string]: map unique id. ex: \"5656565656565656\" ## Options: - `:user` [Project or Organization, default nil]: Project or Organization map returned from starkbank.user/project or starkbank.user/organization. Only necessary if starkbank.settings/user has not been set. ## Return: - Invoice pdf file content" ([id] (clojure.java.io/input-stream (Invoice$Log/pdf id))) ([id, user] (clojure.java.io/input-stream (Invoice$Log/pdf id (#'starkbank.user/get-java-user user)))))
[ { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 40, "score": 0.9998821020126343, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 54, "score": 0.9999303817749023, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/buddy/sign/util.clj
greut/buddy-sign
105
;; Copyright (c) 2015-2016 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.sign.util (:require [buddy.core.codecs :as codecs]) (:import java.lang.reflect.Method clojure.lang.Reflector)) (defprotocol IKeyProvider (resolve-key [key header] "Resolve a key")) (defprotocol ITimestamp "Default protocol for convert any type to unix timestamp." (to-timestamp [obj] "Covert to timestamp")) ;; Default impl for the key provider (extend-protocol IKeyProvider (Class/forName "[B") (resolve-key [key header] key) String (resolve-key [key header] key) clojure.lang.IFn (resolve-key [key header] (key header)) java.security.Key (resolve-key [key header] key)) (extend-protocol ITimestamp java.util.Date (to-timestamp [obj] (-> (.getTime ^java.util.Date obj) (quot 1000))) java.lang.Long (to-timestamp [obj] obj)) ;; apply Joda-Time extensions. DateTime and Instant implement ReadableInstant so this works for both (when-let [klass (try (Class/forName "org.joda.time.ReadableInstant") (catch ClassNotFoundException _))] (let [[^Method method] (Reflector/getMethods klass 0 "getMillis" false)] (extend klass ITimestamp {:to-timestamp (fn [this] (-> (.invoke method this (make-array Object 0)) (quot 1000)))}))) ;; apply Java 8 extensions (when-let [klass (try (Class/forName "java.time.Instant") (catch ClassNotFoundException _))] (let [[^Method method] (Reflector/getMethods klass 0 "getEpochSecond" false)] (extend klass ITimestamp {:to-timestamp (fn [this] (.invoke method this (make-array Object 0)))}))) (defn now "Get a current timestamp in seconds." [] (quot (System/currentTimeMillis) 1000)) (def ^:deprecated timestamp "Alias to `now`." now) (defmacro defalias [name orig] `(do (alter-meta! (if (.hasRoot (var ~orig)) (def ~name (.getRawRoot (var ~orig))) (def ~name)) #(conj (dissoc % :macro) (apply dissoc (meta (var ~orig)) (remove #{:macro} (keys %))))) (var ~name)))
18655
;; Copyright (c) 2015-2016 <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.sign.util (:require [buddy.core.codecs :as codecs]) (:import java.lang.reflect.Method clojure.lang.Reflector)) (defprotocol IKeyProvider (resolve-key [key header] "Resolve a key")) (defprotocol ITimestamp "Default protocol for convert any type to unix timestamp." (to-timestamp [obj] "Covert to timestamp")) ;; Default impl for the key provider (extend-protocol IKeyProvider (Class/forName "[B") (resolve-key [key header] key) String (resolve-key [key header] key) clojure.lang.IFn (resolve-key [key header] (key header)) java.security.Key (resolve-key [key header] key)) (extend-protocol ITimestamp java.util.Date (to-timestamp [obj] (-> (.getTime ^java.util.Date obj) (quot 1000))) java.lang.Long (to-timestamp [obj] obj)) ;; apply Joda-Time extensions. DateTime and Instant implement ReadableInstant so this works for both (when-let [klass (try (Class/forName "org.joda.time.ReadableInstant") (catch ClassNotFoundException _))] (let [[^Method method] (Reflector/getMethods klass 0 "getMillis" false)] (extend klass ITimestamp {:to-timestamp (fn [this] (-> (.invoke method this (make-array Object 0)) (quot 1000)))}))) ;; apply Java 8 extensions (when-let [klass (try (Class/forName "java.time.Instant") (catch ClassNotFoundException _))] (let [[^Method method] (Reflector/getMethods klass 0 "getEpochSecond" false)] (extend klass ITimestamp {:to-timestamp (fn [this] (.invoke method this (make-array Object 0)))}))) (defn now "Get a current timestamp in seconds." [] (quot (System/currentTimeMillis) 1000)) (def ^:deprecated timestamp "Alias to `now`." now) (defmacro defalias [name orig] `(do (alter-meta! (if (.hasRoot (var ~orig)) (def ~name (.getRawRoot (var ~orig))) (def ~name)) #(conj (dissoc % :macro) (apply dissoc (meta (var ~orig)) (remove #{:macro} (keys %))))) (var ~name)))
true
;; Copyright (c) 2015-2016 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.sign.util (:require [buddy.core.codecs :as codecs]) (:import java.lang.reflect.Method clojure.lang.Reflector)) (defprotocol IKeyProvider (resolve-key [key header] "Resolve a key")) (defprotocol ITimestamp "Default protocol for convert any type to unix timestamp." (to-timestamp [obj] "Covert to timestamp")) ;; Default impl for the key provider (extend-protocol IKeyProvider (Class/forName "[B") (resolve-key [key header] key) String (resolve-key [key header] key) clojure.lang.IFn (resolve-key [key header] (key header)) java.security.Key (resolve-key [key header] key)) (extend-protocol ITimestamp java.util.Date (to-timestamp [obj] (-> (.getTime ^java.util.Date obj) (quot 1000))) java.lang.Long (to-timestamp [obj] obj)) ;; apply Joda-Time extensions. DateTime and Instant implement ReadableInstant so this works for both (when-let [klass (try (Class/forName "org.joda.time.ReadableInstant") (catch ClassNotFoundException _))] (let [[^Method method] (Reflector/getMethods klass 0 "getMillis" false)] (extend klass ITimestamp {:to-timestamp (fn [this] (-> (.invoke method this (make-array Object 0)) (quot 1000)))}))) ;; apply Java 8 extensions (when-let [klass (try (Class/forName "java.time.Instant") (catch ClassNotFoundException _))] (let [[^Method method] (Reflector/getMethods klass 0 "getEpochSecond" false)] (extend klass ITimestamp {:to-timestamp (fn [this] (.invoke method this (make-array Object 0)))}))) (defn now "Get a current timestamp in seconds." [] (quot (System/currentTimeMillis) 1000)) (def ^:deprecated timestamp "Alias to `now`." now) (defmacro defalias [name orig] `(do (alter-meta! (if (.hasRoot (var ~orig)) (def ~name (.getRawRoot (var ~orig))) (def ~name)) #(conj (dissoc % :macro) (apply dissoc (meta (var ~orig)) (remove #{:macro} (keys %))))) (var ~name)))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998642802238464, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "tice, or any other, from this software.\n\n; Author: Stuart Halloway\n\n\n(ns clojure.test-clojure.main\n (:use clojure.t", "end": 489, "score": 0.9998854398727417, "start": 474, "tag": "NAME", "value": "Stuart Halloway" } ]
Chapter 07 Code/niko/clojure/test/clojure/test_clojure/main.clj
PacktPublishing/Clojure-Programming-Cookbook
14
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: Stuart Halloway (ns clojure.test-clojure.main (:use clojure.test [clojure.test-helper :only [platform-newlines]]) (:require [clojure.main :as main])) (deftest eval-opt (testing "evals and prints forms" (is (= (platform-newlines "2\n4\n") (with-out-str (#'clojure.main/eval-opt "(+ 1 1) (+ 2 2)"))))) (testing "skips printing nils" (is (= (platform-newlines ":a\n:c\n") (with-out-str (#'clojure.main/eval-opt ":a nil :c"))))) (testing "does not block access to *in* (#299)" (with-in-str "(+ 1 1)" (is (= (platform-newlines "(+ 1 1)\n") (with-out-str (#'clojure.main/eval-opt "(read)"))))))) (defmacro with-err-str "Evaluates exprs in a context in which *err* is bound to a fresh StringWriter. Returns the string created by any nested printing calls." [& body] `(let [s# (new java.io.StringWriter) p# (new java.io.PrintWriter s#)] (binding [*err* p#] ~@body (str s#)))) (defn run-repl-and-return-err "Run repl, swallowing stdout and returing stderr." [in-str] (with-err-str (with-out-str (with-in-str in-str (main/repl))))) ;argh - test fragility, please fix #_(deftest repl-exception-safety (testing "catches and prints exception on bad equals" (is (re-matches #"java\.lang\.NullPointerException\r?\n" (run-repl-and-return-err "(proxy [Object] [] (equals [o] (.toString nil)))")))))
118476
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: <NAME> (ns clojure.test-clojure.main (:use clojure.test [clojure.test-helper :only [platform-newlines]]) (:require [clojure.main :as main])) (deftest eval-opt (testing "evals and prints forms" (is (= (platform-newlines "2\n4\n") (with-out-str (#'clojure.main/eval-opt "(+ 1 1) (+ 2 2)"))))) (testing "skips printing nils" (is (= (platform-newlines ":a\n:c\n") (with-out-str (#'clojure.main/eval-opt ":a nil :c"))))) (testing "does not block access to *in* (#299)" (with-in-str "(+ 1 1)" (is (= (platform-newlines "(+ 1 1)\n") (with-out-str (#'clojure.main/eval-opt "(read)"))))))) (defmacro with-err-str "Evaluates exprs in a context in which *err* is bound to a fresh StringWriter. Returns the string created by any nested printing calls." [& body] `(let [s# (new java.io.StringWriter) p# (new java.io.PrintWriter s#)] (binding [*err* p#] ~@body (str s#)))) (defn run-repl-and-return-err "Run repl, swallowing stdout and returing stderr." [in-str] (with-err-str (with-out-str (with-in-str in-str (main/repl))))) ;argh - test fragility, please fix #_(deftest repl-exception-safety (testing "catches and prints exception on bad equals" (is (re-matches #"java\.lang\.NullPointerException\r?\n" (run-repl-and-return-err "(proxy [Object] [] (equals [o] (.toString nil)))")))))
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. ; Author: PI:NAME:<NAME>END_PI (ns clojure.test-clojure.main (:use clojure.test [clojure.test-helper :only [platform-newlines]]) (:require [clojure.main :as main])) (deftest eval-opt (testing "evals and prints forms" (is (= (platform-newlines "2\n4\n") (with-out-str (#'clojure.main/eval-opt "(+ 1 1) (+ 2 2)"))))) (testing "skips printing nils" (is (= (platform-newlines ":a\n:c\n") (with-out-str (#'clojure.main/eval-opt ":a nil :c"))))) (testing "does not block access to *in* (#299)" (with-in-str "(+ 1 1)" (is (= (platform-newlines "(+ 1 1)\n") (with-out-str (#'clojure.main/eval-opt "(read)"))))))) (defmacro with-err-str "Evaluates exprs in a context in which *err* is bound to a fresh StringWriter. Returns the string created by any nested printing calls." [& body] `(let [s# (new java.io.StringWriter) p# (new java.io.PrintWriter s#)] (binding [*err* p#] ~@body (str s#)))) (defn run-repl-and-return-err "Run repl, swallowing stdout and returing stderr." [in-str] (with-err-str (with-out-str (with-in-str in-str (main/repl))))) ;argh - test fragility, please fix #_(deftest repl-exception-safety (testing "catches and prints exception on bad equals" (is (re-matches #"java\.lang\.NullPointerException\r?\n" (run-repl-and-return-err "(proxy [Object] [] (equals [o] (.toString nil)))")))))
[ { "context": "{:auth {:repository-auth {#\"clojars\" {:username \"broad\"\n :password ", "end": 54, "score": 0.9976660013198853, "start": 49, "tag": "USERNAME", "value": "broad" }, { "context": "\n :password :env/clojars_password}}}}\n", "end": 125, "score": 0.8244444727897644, "start": 105, "tag": "PASSWORD", "value": "env/clojars_password" } ]
.lein/profiles.clj
broadinstitute/react-cljs-nav
2
{:auth {:repository-auth {#"clojars" {:username "broad" :password :env/clojars_password}}}}
87719
{:auth {:repository-auth {#"clojars" {:username "broad" :password :<PASSWORD>}}}}
true
{:auth {:repository-auth {#"clojars" {:username "broad" :password :PI:PASSWORD:<PASSWORD>END_PI}}}}
[ { "context": "gresql\"\n :username \"covid\"\n :password \"covidp", "end": 1550, "score": 0.9904398322105408, "start": 1545, "tag": "USERNAME", "value": "covid" }, { "context": "\"covid\"\n :password \"covidpwd\"\n :database-name \"altrun", "end": 1602, "score": 0.9994345903396606, "start": 1594, "tag": "PASSWORD", "value": "covidpwd" } ]
src/coronavirus_scrapper_api/components/database.clj
giovanialtelino/coronavirus-api
2
(ns coronavirus-scrapper-api.components.database (:require [com.stuartsierra.component :as component] [hikari-cp.core :as hikari])) (def datasource-prod { :auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "corona" :adapter "postgresql" :username (System/getenv "DATABASE_USR") :password (System/getenv "DATABASE_PWD") :database-name "postgres" :server-name "localhost" :port-number 5432 :register-mbeans false}) (def datasource-dev { :auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "corona" :adapter "postgresql" :username "covid" :password "covidpwd" :database-name "altrunox" :server-name "localhost" :port-number 5432 :register-mbeans false}) (defn datasource [ds] (hikari/make-datasource ds)) (defrecord DatabaseComponent [config] component/Lifecycle (start [this] (if (= :prod (:env config)) (assoc this :database {:datasource (datasource datasource-prod)}) (assoc this :database {:datasource (datasource datasource-dev)}))) (stop [this] (assoc this :database nil)) Object (toString [_] "<Database>")) (defn new-database [] (map->DatabaseComponent {}))
27382
(ns coronavirus-scrapper-api.components.database (:require [com.stuartsierra.component :as component] [hikari-cp.core :as hikari])) (def datasource-prod { :auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "corona" :adapter "postgresql" :username (System/getenv "DATABASE_USR") :password (System/getenv "DATABASE_PWD") :database-name "postgres" :server-name "localhost" :port-number 5432 :register-mbeans false}) (def datasource-dev { :auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "corona" :adapter "postgresql" :username "covid" :password "<PASSWORD>" :database-name "altrunox" :server-name "localhost" :port-number 5432 :register-mbeans false}) (defn datasource [ds] (hikari/make-datasource ds)) (defrecord DatabaseComponent [config] component/Lifecycle (start [this] (if (= :prod (:env config)) (assoc this :database {:datasource (datasource datasource-prod)}) (assoc this :database {:datasource (datasource datasource-dev)}))) (stop [this] (assoc this :database nil)) Object (toString [_] "<Database>")) (defn new-database [] (map->DatabaseComponent {}))
true
(ns coronavirus-scrapper-api.components.database (:require [com.stuartsierra.component :as component] [hikari-cp.core :as hikari])) (def datasource-prod { :auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "corona" :adapter "postgresql" :username (System/getenv "DATABASE_USR") :password (System/getenv "DATABASE_PWD") :database-name "postgres" :server-name "localhost" :port-number 5432 :register-mbeans false}) (def datasource-dev { :auto-commit true :read-only false :connection-timeout 30000 :validation-timeout 5000 :idle-timeout 600000 :max-lifetime 1800000 :minimum-idle 10 :maximum-pool-size 10 :pool-name "corona" :adapter "postgresql" :username "covid" :password "PI:PASSWORD:<PASSWORD>END_PI" :database-name "altrunox" :server-name "localhost" :port-number 5432 :register-mbeans false}) (defn datasource [ds] (hikari/make-datasource ds)) (defrecord DatabaseComponent [config] component/Lifecycle (start [this] (if (= :prod (:env config)) (assoc this :database {:datasource (datasource datasource-prod)}) (assoc this :database {:datasource (datasource datasource-dev)}))) (stop [this] (assoc this :database nil)) Object (toString [_] "<Database>")) (defn new-database [] (map->DatabaseComponent {}))
[ { "context": " \"basePath\")\n inheriting-key? #{\"parameters\" \"consumes\" \"produces\" \"schemes\" \"security\"}]\n (->>\n ; create request-key / swagger-", "end": 5635, "score": 0.8045244812965393, "start": 5594, "tag": "KEY", "value": "\"consumes\" \"produces\" \"schemes\" \"security" } ]
src/io/sarnowski/swagger1st/mapper.clj
ethercrow/swagger1st
0
(ns io.sarnowski.swagger1st.mapper (:require [ring.util.response :as r] [flatland.ordered.map :refer [ordered-map]] [clojure.walk :as walk] [clojure.string :as string] [clojure.tools.logging :as log] [io.sarnowski.swagger1st.util.api :as api]) (:import (clojure.lang IObj))) (defn get-definition "Resolves a $ref reference to its content." [r d] (let [path (rest (string/split r #"/"))] (get-in d path))) (defn conj-not-nil [coll v] (if (nil? v) coll (conj coll v))) (defn postwalk-with-path "like postwalk, but f is called with two arguments: current element and accumulated path. Accumulated path is constructed by conj'ing non-nil results of calling path-step-fn on every form." [f path path-step-fn form] (let [new-path (conj-not-nil path (path-step-fn form))] (walk/walk #(postwalk-with-path f new-path path-step-fn %) identity (f form new-path)))) (defn with-meta-if-applicable "Sets meta if obj can hold it." [obj m] (if (instance? IObj obj) (with-meta obj m) obj)) (defn denormalize-refs* "Searches for $ref objects and replaces those with their target, also remembering the source in ::from metadata. Does not resolve the same ref under one parent." [definition] (let [check-ref (fn [element path] (let [r (get element "$ref")] (if (and r (not (contains? path r))) (with-meta-if-applicable (get-definition r definition) {::from r}) element)))] (postwalk-with-path (fn [element path] (if (map? element) (check-ref element path) element)) #{} #(-> % meta ::from) definition))) (defn denormalize-refs "Iteratively resolves refs until the result no longer changes. Protected from circular refs by denormalize-refs* implementation." [definition] (loop [d definition] (let [new-d (denormalize-refs* d)] (if (= new-d d) new-d (recur new-d))))) (defn inherit-map "Merges a map from parent to definition, overwriting keys with definition." [definition parent-definition map-name] (let [m (get definition map-name) pm (get parent-definition map-name) merged (merge pm m)] (assoc definition map-name merged))) (defn inherit-list "Denormalizes a collection, using the parent or replacing it with definition." [definition parent-definition col-name] (assoc definition col-name (if-let [col (get definition col-name)] col (get parent-definition col-name)))) (defn conj-if-not "Conjoins x to col if test-fn doesn't find an existing entry in col." [test-fn col x & xs] (let [col (if (empty? (filter (fn [y] (test-fn x y)) col)) (conj col x) col)] (if xs (recur test-fn col (first xs) (next xs)) col))) (defn inherit-list-elements "Denormalizes a collection, replacing entries that are equal." [definition parent-definition col-name if-not-fn] (assoc definition col-name (let [pd (get parent-definition col-name) d (get definition col-name)] (remove nil? (conj-if-not if-not-fn d (first pd) (next pd)))))) (defn keys-equal? "Compares two maps if both have the same given keys." [x y ks] (every? (fn [k] (= (get x k) (get y k))) ks)) (defn inherit-mimetypes "Inherit 'consumes' and 'produces' mimetypes if not defined." [definition parent-definition] (-> definition (inherit-list parent-definition "consumes") (inherit-list parent-definition "produces") (inherit-list parent-definition "security"))) (defn inherit-path-spec "Denormalizes inheritance of parameters etc. from the path to operation." [definition parent-definition] (-> definition (inherit-mimetypes parent-definition) (inherit-list-elements parent-definition "parameters" (fn [x y] (keys-equal? x y ["name" "in"]))) (inherit-map parent-definition "responses") (inherit-list parent-definition "security"))) (defn split-path "Splits a / separated path into its segments." [path] (let [split (fn [^String s] (.split s "/"))] (-> path split rest))) (defn variable-to-keyword "Replaces a variable path segment (like /{username}/) with the variable name as keyword (like :username)." [seg] (if-let [variable-name (second (re-matches #"\{(.*)\}" seg))] ; use keywords for variable names (keyword variable-name) ; no variable found, return original segment seg)) (defn create-request-tuple "Generates easier to digest request tuples from operations and paths." [operation operation-definition path path-definition] (let [keyword-path (->> path split-path (map variable-to-keyword)) definition (inherit-path-spec operation-definition path-definition)] [[operation keyword-path] definition])) (defn join-base-path "Joins the defined path with the global base path. Base paths are expected to start with a / and not end with a /." [path base-path] (if (and base-path (not= base-path "/")) (str base-path path) path)) (defn extract-requests "Extracts request-key->operation-definition from a swagger definition." [definition] (let [base-path (get definition "basePath") inheriting-key? #{"parameters" "consumes" "produces" "schemes" "security"}] (->> ; create request-key / swagger-request tuples (for [[path path-definition] (get definition "paths")] (when-not (inheriting-key? path) (let [path (join-base-path path base-path) path-definition (inherit-mimetypes path-definition definition)] (for [[operation operation-definition] path-definition] (when-not (inheriting-key? operation) (create-request-tuple operation operation-definition path path-definition)))))) ; streamline tuples and bring into a map (apply concat) (remove nil?) (into {})))) (defn flatten-allOf "Replace occurrence of allOf with the merged maps which are defined for allOf. While the spec allows to create schema which contradict each other (http://spacetelescope.github.io/understanding-json-schema/reference/combining.html#allof) the implementation uses only the last definition of a given property" [definition] (letfn [(con [f l] (cond (every? map? [f l]) (merge f l) (every? seq? [f l]) (concat f l) :else l)) (allOf-flat [d] (reduce-kv (fn [a k v] (if (= "allOf" k) (apply (partial merge-with con) (cons a v)) (assoc a k v))) (ordered-map) d)) (visit [n] (if (and (map? n) (contains? n "allOf")) (allOf-flat n) n))] (walk/prewalk visit definition))) (defn create-requests "Creates a map of 'request-key' -> 'swagger-definition' entries. The request-key can be used to efficiently lookup requests. The swagger-definition contains denormalized information about the request specification (all refs and inheritance is denormalized)." [definition] (-> definition denormalize-refs flatten-allOf extract-requests)) (defn path-machtes? "Matches a template path with a real path. Paths are provided as collections of their segments. If the template has a keyword value, it is a dynamic segment." [path-template path-real] (when (= (count path-template) (count path-real)) (let [pairs (map vector path-template path-real) pair-matches? (fn [[t r]] (or (keyword? t) (= t r)))] (every? pair-matches? pairs)))) (defn request-matches? "Checks if the given request matches a defined swagger-request." [[operation path-template] request] (and (= operation (-> request :request-method name)) (path-machtes? path-template (-> request :uri split-path)))) (defn lookup-request "Creates a function that can do efficient lookups of requests." [requests request] (->> requests (filter (fn [[template _]] (request-matches? template request))) ; if we have multiple matches then its not well defined, just choose the first first)) (defn setup [{:keys [definition] :as context}] (log/debug "definition:" definition) (let [requests (create-requests definition)] (log/debug "requests:" requests) (assoc context :requests requests))) (defn correlate [{:keys [requests]} next-handler request] (let [[key swagger-request] (lookup-request requests request)] (if (nil? swagger-request) (api/error 404 (str (.toUpperCase (-> request :request-method name)) " " (-> request :uri) " not found.")) (let [request (-> request (assoc-in [:swagger :request] swagger-request) (assoc-in [:swagger :key] key))] (log/debug "request" key "->" swagger-request) (next-handler request)))))
110930
(ns io.sarnowski.swagger1st.mapper (:require [ring.util.response :as r] [flatland.ordered.map :refer [ordered-map]] [clojure.walk :as walk] [clojure.string :as string] [clojure.tools.logging :as log] [io.sarnowski.swagger1st.util.api :as api]) (:import (clojure.lang IObj))) (defn get-definition "Resolves a $ref reference to its content." [r d] (let [path (rest (string/split r #"/"))] (get-in d path))) (defn conj-not-nil [coll v] (if (nil? v) coll (conj coll v))) (defn postwalk-with-path "like postwalk, but f is called with two arguments: current element and accumulated path. Accumulated path is constructed by conj'ing non-nil results of calling path-step-fn on every form." [f path path-step-fn form] (let [new-path (conj-not-nil path (path-step-fn form))] (walk/walk #(postwalk-with-path f new-path path-step-fn %) identity (f form new-path)))) (defn with-meta-if-applicable "Sets meta if obj can hold it." [obj m] (if (instance? IObj obj) (with-meta obj m) obj)) (defn denormalize-refs* "Searches for $ref objects and replaces those with their target, also remembering the source in ::from metadata. Does not resolve the same ref under one parent." [definition] (let [check-ref (fn [element path] (let [r (get element "$ref")] (if (and r (not (contains? path r))) (with-meta-if-applicable (get-definition r definition) {::from r}) element)))] (postwalk-with-path (fn [element path] (if (map? element) (check-ref element path) element)) #{} #(-> % meta ::from) definition))) (defn denormalize-refs "Iteratively resolves refs until the result no longer changes. Protected from circular refs by denormalize-refs* implementation." [definition] (loop [d definition] (let [new-d (denormalize-refs* d)] (if (= new-d d) new-d (recur new-d))))) (defn inherit-map "Merges a map from parent to definition, overwriting keys with definition." [definition parent-definition map-name] (let [m (get definition map-name) pm (get parent-definition map-name) merged (merge pm m)] (assoc definition map-name merged))) (defn inherit-list "Denormalizes a collection, using the parent or replacing it with definition." [definition parent-definition col-name] (assoc definition col-name (if-let [col (get definition col-name)] col (get parent-definition col-name)))) (defn conj-if-not "Conjoins x to col if test-fn doesn't find an existing entry in col." [test-fn col x & xs] (let [col (if (empty? (filter (fn [y] (test-fn x y)) col)) (conj col x) col)] (if xs (recur test-fn col (first xs) (next xs)) col))) (defn inherit-list-elements "Denormalizes a collection, replacing entries that are equal." [definition parent-definition col-name if-not-fn] (assoc definition col-name (let [pd (get parent-definition col-name) d (get definition col-name)] (remove nil? (conj-if-not if-not-fn d (first pd) (next pd)))))) (defn keys-equal? "Compares two maps if both have the same given keys." [x y ks] (every? (fn [k] (= (get x k) (get y k))) ks)) (defn inherit-mimetypes "Inherit 'consumes' and 'produces' mimetypes if not defined." [definition parent-definition] (-> definition (inherit-list parent-definition "consumes") (inherit-list parent-definition "produces") (inherit-list parent-definition "security"))) (defn inherit-path-spec "Denormalizes inheritance of parameters etc. from the path to operation." [definition parent-definition] (-> definition (inherit-mimetypes parent-definition) (inherit-list-elements parent-definition "parameters" (fn [x y] (keys-equal? x y ["name" "in"]))) (inherit-map parent-definition "responses") (inherit-list parent-definition "security"))) (defn split-path "Splits a / separated path into its segments." [path] (let [split (fn [^String s] (.split s "/"))] (-> path split rest))) (defn variable-to-keyword "Replaces a variable path segment (like /{username}/) with the variable name as keyword (like :username)." [seg] (if-let [variable-name (second (re-matches #"\{(.*)\}" seg))] ; use keywords for variable names (keyword variable-name) ; no variable found, return original segment seg)) (defn create-request-tuple "Generates easier to digest request tuples from operations and paths." [operation operation-definition path path-definition] (let [keyword-path (->> path split-path (map variable-to-keyword)) definition (inherit-path-spec operation-definition path-definition)] [[operation keyword-path] definition])) (defn join-base-path "Joins the defined path with the global base path. Base paths are expected to start with a / and not end with a /." [path base-path] (if (and base-path (not= base-path "/")) (str base-path path) path)) (defn extract-requests "Extracts request-key->operation-definition from a swagger definition." [definition] (let [base-path (get definition "basePath") inheriting-key? #{"parameters" <KEY>"}] (->> ; create request-key / swagger-request tuples (for [[path path-definition] (get definition "paths")] (when-not (inheriting-key? path) (let [path (join-base-path path base-path) path-definition (inherit-mimetypes path-definition definition)] (for [[operation operation-definition] path-definition] (when-not (inheriting-key? operation) (create-request-tuple operation operation-definition path path-definition)))))) ; streamline tuples and bring into a map (apply concat) (remove nil?) (into {})))) (defn flatten-allOf "Replace occurrence of allOf with the merged maps which are defined for allOf. While the spec allows to create schema which contradict each other (http://spacetelescope.github.io/understanding-json-schema/reference/combining.html#allof) the implementation uses only the last definition of a given property" [definition] (letfn [(con [f l] (cond (every? map? [f l]) (merge f l) (every? seq? [f l]) (concat f l) :else l)) (allOf-flat [d] (reduce-kv (fn [a k v] (if (= "allOf" k) (apply (partial merge-with con) (cons a v)) (assoc a k v))) (ordered-map) d)) (visit [n] (if (and (map? n) (contains? n "allOf")) (allOf-flat n) n))] (walk/prewalk visit definition))) (defn create-requests "Creates a map of 'request-key' -> 'swagger-definition' entries. The request-key can be used to efficiently lookup requests. The swagger-definition contains denormalized information about the request specification (all refs and inheritance is denormalized)." [definition] (-> definition denormalize-refs flatten-allOf extract-requests)) (defn path-machtes? "Matches a template path with a real path. Paths are provided as collections of their segments. If the template has a keyword value, it is a dynamic segment." [path-template path-real] (when (= (count path-template) (count path-real)) (let [pairs (map vector path-template path-real) pair-matches? (fn [[t r]] (or (keyword? t) (= t r)))] (every? pair-matches? pairs)))) (defn request-matches? "Checks if the given request matches a defined swagger-request." [[operation path-template] request] (and (= operation (-> request :request-method name)) (path-machtes? path-template (-> request :uri split-path)))) (defn lookup-request "Creates a function that can do efficient lookups of requests." [requests request] (->> requests (filter (fn [[template _]] (request-matches? template request))) ; if we have multiple matches then its not well defined, just choose the first first)) (defn setup [{:keys [definition] :as context}] (log/debug "definition:" definition) (let [requests (create-requests definition)] (log/debug "requests:" requests) (assoc context :requests requests))) (defn correlate [{:keys [requests]} next-handler request] (let [[key swagger-request] (lookup-request requests request)] (if (nil? swagger-request) (api/error 404 (str (.toUpperCase (-> request :request-method name)) " " (-> request :uri) " not found.")) (let [request (-> request (assoc-in [:swagger :request] swagger-request) (assoc-in [:swagger :key] key))] (log/debug "request" key "->" swagger-request) (next-handler request)))))
true
(ns io.sarnowski.swagger1st.mapper (:require [ring.util.response :as r] [flatland.ordered.map :refer [ordered-map]] [clojure.walk :as walk] [clojure.string :as string] [clojure.tools.logging :as log] [io.sarnowski.swagger1st.util.api :as api]) (:import (clojure.lang IObj))) (defn get-definition "Resolves a $ref reference to its content." [r d] (let [path (rest (string/split r #"/"))] (get-in d path))) (defn conj-not-nil [coll v] (if (nil? v) coll (conj coll v))) (defn postwalk-with-path "like postwalk, but f is called with two arguments: current element and accumulated path. Accumulated path is constructed by conj'ing non-nil results of calling path-step-fn on every form." [f path path-step-fn form] (let [new-path (conj-not-nil path (path-step-fn form))] (walk/walk #(postwalk-with-path f new-path path-step-fn %) identity (f form new-path)))) (defn with-meta-if-applicable "Sets meta if obj can hold it." [obj m] (if (instance? IObj obj) (with-meta obj m) obj)) (defn denormalize-refs* "Searches for $ref objects and replaces those with their target, also remembering the source in ::from metadata. Does not resolve the same ref under one parent." [definition] (let [check-ref (fn [element path] (let [r (get element "$ref")] (if (and r (not (contains? path r))) (with-meta-if-applicable (get-definition r definition) {::from r}) element)))] (postwalk-with-path (fn [element path] (if (map? element) (check-ref element path) element)) #{} #(-> % meta ::from) definition))) (defn denormalize-refs "Iteratively resolves refs until the result no longer changes. Protected from circular refs by denormalize-refs* implementation." [definition] (loop [d definition] (let [new-d (denormalize-refs* d)] (if (= new-d d) new-d (recur new-d))))) (defn inherit-map "Merges a map from parent to definition, overwriting keys with definition." [definition parent-definition map-name] (let [m (get definition map-name) pm (get parent-definition map-name) merged (merge pm m)] (assoc definition map-name merged))) (defn inherit-list "Denormalizes a collection, using the parent or replacing it with definition." [definition parent-definition col-name] (assoc definition col-name (if-let [col (get definition col-name)] col (get parent-definition col-name)))) (defn conj-if-not "Conjoins x to col if test-fn doesn't find an existing entry in col." [test-fn col x & xs] (let [col (if (empty? (filter (fn [y] (test-fn x y)) col)) (conj col x) col)] (if xs (recur test-fn col (first xs) (next xs)) col))) (defn inherit-list-elements "Denormalizes a collection, replacing entries that are equal." [definition parent-definition col-name if-not-fn] (assoc definition col-name (let [pd (get parent-definition col-name) d (get definition col-name)] (remove nil? (conj-if-not if-not-fn d (first pd) (next pd)))))) (defn keys-equal? "Compares two maps if both have the same given keys." [x y ks] (every? (fn [k] (= (get x k) (get y k))) ks)) (defn inherit-mimetypes "Inherit 'consumes' and 'produces' mimetypes if not defined." [definition parent-definition] (-> definition (inherit-list parent-definition "consumes") (inherit-list parent-definition "produces") (inherit-list parent-definition "security"))) (defn inherit-path-spec "Denormalizes inheritance of parameters etc. from the path to operation." [definition parent-definition] (-> definition (inherit-mimetypes parent-definition) (inherit-list-elements parent-definition "parameters" (fn [x y] (keys-equal? x y ["name" "in"]))) (inherit-map parent-definition "responses") (inherit-list parent-definition "security"))) (defn split-path "Splits a / separated path into its segments." [path] (let [split (fn [^String s] (.split s "/"))] (-> path split rest))) (defn variable-to-keyword "Replaces a variable path segment (like /{username}/) with the variable name as keyword (like :username)." [seg] (if-let [variable-name (second (re-matches #"\{(.*)\}" seg))] ; use keywords for variable names (keyword variable-name) ; no variable found, return original segment seg)) (defn create-request-tuple "Generates easier to digest request tuples from operations and paths." [operation operation-definition path path-definition] (let [keyword-path (->> path split-path (map variable-to-keyword)) definition (inherit-path-spec operation-definition path-definition)] [[operation keyword-path] definition])) (defn join-base-path "Joins the defined path with the global base path. Base paths are expected to start with a / and not end with a /." [path base-path] (if (and base-path (not= base-path "/")) (str base-path path) path)) (defn extract-requests "Extracts request-key->operation-definition from a swagger definition." [definition] (let [base-path (get definition "basePath") inheriting-key? #{"parameters" PI:KEY:<KEY>END_PI"}] (->> ; create request-key / swagger-request tuples (for [[path path-definition] (get definition "paths")] (when-not (inheriting-key? path) (let [path (join-base-path path base-path) path-definition (inherit-mimetypes path-definition definition)] (for [[operation operation-definition] path-definition] (when-not (inheriting-key? operation) (create-request-tuple operation operation-definition path path-definition)))))) ; streamline tuples and bring into a map (apply concat) (remove nil?) (into {})))) (defn flatten-allOf "Replace occurrence of allOf with the merged maps which are defined for allOf. While the spec allows to create schema which contradict each other (http://spacetelescope.github.io/understanding-json-schema/reference/combining.html#allof) the implementation uses only the last definition of a given property" [definition] (letfn [(con [f l] (cond (every? map? [f l]) (merge f l) (every? seq? [f l]) (concat f l) :else l)) (allOf-flat [d] (reduce-kv (fn [a k v] (if (= "allOf" k) (apply (partial merge-with con) (cons a v)) (assoc a k v))) (ordered-map) d)) (visit [n] (if (and (map? n) (contains? n "allOf")) (allOf-flat n) n))] (walk/prewalk visit definition))) (defn create-requests "Creates a map of 'request-key' -> 'swagger-definition' entries. The request-key can be used to efficiently lookup requests. The swagger-definition contains denormalized information about the request specification (all refs and inheritance is denormalized)." [definition] (-> definition denormalize-refs flatten-allOf extract-requests)) (defn path-machtes? "Matches a template path with a real path. Paths are provided as collections of their segments. If the template has a keyword value, it is a dynamic segment." [path-template path-real] (when (= (count path-template) (count path-real)) (let [pairs (map vector path-template path-real) pair-matches? (fn [[t r]] (or (keyword? t) (= t r)))] (every? pair-matches? pairs)))) (defn request-matches? "Checks if the given request matches a defined swagger-request." [[operation path-template] request] (and (= operation (-> request :request-method name)) (path-machtes? path-template (-> request :uri split-path)))) (defn lookup-request "Creates a function that can do efficient lookups of requests." [requests request] (->> requests (filter (fn [[template _]] (request-matches? template request))) ; if we have multiple matches then its not well defined, just choose the first first)) (defn setup [{:keys [definition] :as context}] (log/debug "definition:" definition) (let [requests (create-requests definition)] (log/debug "requests:" requests) (assoc context :requests requests))) (defn correlate [{:keys [requests]} next-handler request] (let [[key swagger-request] (lookup-request requests request)] (if (nil? swagger-request) (api/error 404 (str (.toUpperCase (-> request :request-method name)) " " (-> request :uri) " not found.")) (let [request (-> request (assoc-in [:swagger :request] swagger-request) (assoc-in [:swagger :key] key))] (log/debug "request" key "->" swagger-request) (next-handler request)))))
[ { "context": "t end))))\n\n\n(defn select-keys-in-order\n \"Thanks [Jay Fields](http://blog.jayfields.com/2011/01/clojure-select", "end": 19563, "score": 0.7637946605682373, "start": 19553, "tag": "NAME", "value": "Jay Fields" }, { "context": " keyseq)))\n\n(defn select-vals-in-order\n \"Thanks [Jay Fields](http://blog.jayfields.com/2011/01/clojure-select", "end": 19791, "score": 0.8224325180053711, "start": 19781, "tag": "NAME", "value": "Jay Fields" } ]
resources/public/cljs-out/dev/gadjett/collections.cljc
23trastos/REPLiCA
0
(ns gadjett.collections (:require [clojure.set :refer [union]] [clojure.walk :refer [postwalk]] [clojure.string :refer [blank? join split-lines]] [clojure.zip :as zip])) (def infinity #?(:cljs js/Infinity :clj Double/POSITIVE_INFINITY)) (defn abs "Absolute value of a number ~~~klipse (map abs (range -5 5)) ~~~ " [x] (max x (- x))) (defn- scale [x y] (if (or (zero? x) (zero? y)) 1 (abs x))) (defn almost= ([x y] (almost= x y 0.00001)) ([x y epsilon] (or (= x y) (<= (abs (- x y)) (* (scale x y) epsilon))))) (defn- =set [a b] (= (into #{} a) (into #{} b))) (defn =without-keys? "Compare two maps exclusing some keys ~~~klipse (=without-keys? {:a 1 :b 2 :c 3} {:a 1 :b 5} #{:b :c}) ~~~ " [obj-a obj-b keys-list] (apply = (map #(apply dissoc % keys-list) [obj-a obj-b]))) (defn vec->map "Converts a 2d vec to a hash-map. ~~~klipse (vec->map [[:a 1] [:b 2]]) ~~~ " [vec] (into {} vec)) (defn map-2d-vec "Maps the values of a `2D` vector where each element of the vector is a key-value pair. `f` is a `1-ary` function that receives the key. ~~~klipse (map-2d-vec inc [[:a 1] [:b 2]]) ~~~ " [f m] (map (fn[[k id]] [k (f id)]) m)) (defn map-2d-vec-kv "Maps the values of a `2D` vector where each element of the vector is a key-value pair. `fk` is a `1-ary` function that receives the key. `fv` is a `1-ary` function that receives the value. ~~~klipse (map-2d-vec-kv name inc [[:a 1] [:b 2]]) ~~~ " [fk fv m] (map (fn[[k id]] [(fk k) (fv id)]) m)) (defn map-object "Returns a map with the same keys as `m` and with the values transformed by `f`. `f` is a `1-ary` function that receives the key. ~~~klipse (map-object inc {:a 1 :b 2 :c 3}) ~~~ " [f m] (vec->map (map-2d-vec f m))) (defn map-object-with-key "Returns a map with the same keys as `m` and with the values transformed by `f`. `f` must be a `2-ary` function that receives the key and the value as arguments. ~~~klipse (map-object-with-key list {:a 1 :b 2 :c 3}) ~~~ " [f m] (into {} (map (fn [[a b]] [a (f a b)]) m))) (defn map-object-kv "Returns a map with the keys mapped by `fk` and the values mapped by `fv`. ~~~klipse (map-object-kv name inc {:a 1 :b 2 :c 3}) ~~~ " [fk fv m] (vec->map (map-2d-vec-kv fk fv m))) (defn map-reverse-hierarchy "Turns a hash map inside out. See: [here](http://stackoverflow.com/a/23653784/813665) ~~~klipse (map-reverse-hierarchy {:monday {:banana 2 :apple 3} :tuesday {:banana 5 :orange 2}}) ~~~ " [m] (or (apply merge-with conj (for [[k1 v1] m [k2 v2] v1] {k2 {k1 v2}})) {})) (defn mean "Calculates the mean (a.k.a average) of a sequence of numbers. ~~~klipse (mean [1 2 10 -1 12.3]) ~~~ " [x] (if (empty? x) 0 (/ (apply + x) (count x)))) (defn sequence->map "Converts a sequence into a map where the keys are the indexes of the elements in the sequence. ~~~klipse (sequence->map [10 20 30]) ~~~ " [s] (zipmap (range (count s)) s)) (defn sequence-of-maps->map "Converts a sequence of maps into a map where: - the keys are extracted from the maps using `key-fn` - the vals extracted from the maps using `val-fn` ~~~klipse (sequence-of-maps->map [{:key :price :value 19} {:key :quantity :value 100}] :key :value) ~~~ " [coll key-fn val-fn] (reduce (fn [res m] (assoc res (key-fn m) (val-fn m))) {} coll)) (defn- range-with-end ([end] [end (range end)]) ([start end] [end (range start end)]) ([start end steps] [end (range start end steps)])) (defn range-till-end "Like `range` but including the `end`. ~~~klipse (range-till-end 10) ~~~ ~~~klipse (range-till-end 10 18) ~~~ ~~~klipse (range-till-end 10 100 5) ~~~ " [& args] (let [[end lis] (apply range-with-end args)] (concat lis [end]))) (defn append-cyclic "Appends an element to a list popping out the first element. ~~~klipse (-> (repeat 3 nil) (append-cyclic 1) (append-cyclic 2) (append-cyclic 3) (append-cyclic 4)) ~~~ " [lst a] (if (seq lst) (concat (rest lst) [a]) lst)) (defn assoc-cyclic "Assoc a key-value pair to a map popping out an element of the map. If the key already exists, no element is popped out. If `n` is supplied, no elmement is popped out if the map has less than `n` entries. ~~~klipse (-> {:a 1 :b 2 :c 3} (assoc-cyclic :d 4) (assoc-cyclic :e 5) (assoc-cyclic :f 6) (assoc-cyclic :g 7)) ~~~ " ([coll k v] (if (contains? coll k) (assoc coll k v) (into {} (append-cyclic coll [k v])))) ([coll k v n] (if (< (count coll) n) (assoc coll k v) (assoc-cyclic coll k v)))) (defn max-and-min "Returns a couple of the `max` and the `min` of a sequence. ~~~klipse (max-and-min (range 5)) ~~~ " [x] (if (empty? x) [0 0] ((juxt #(apply max %) #(apply min %)) x))) (defn compactize-map "Removes entries with `nil` values. ~~~klipse (compactize-map {:a 1 :b nil :c 3}) ~~~ " [m] (into {} (remove (comp nil? second) m))) ;; http://stackoverflow.com/a/34221816/813665 (defn compactize-map-recursive "Remove from a map the entries whose values are `nil`. If all the values of a nested map are `nil` the entrie is removed. ~~~klipse (compactize-map-recursive {:x 1 :z {:a nil} :a {:b nil :c 2 :d {:e nil :f 2}}}) ~~~ " [m] (let [f (fn [x] (if (map? x) (let [kvs (filter (comp not nil? second) x)] (if (empty? kvs) nil (into {} kvs))) x))] (postwalk f m))) (defn filter-map "Run a function on the values of a map and keep only the (key, value) pairs for which the function returns true ~~~klipse (filter-map even? {:a 1 :b 2 :c 3}) ~~~ " [f m] (into {} (filter (comp f val) m))) (defn nearest-of-ss "Returns the nearest number to `x` of a sorted set ~~~klipse (nearest-of-ss (apply sorted-set (range 5)) 1.2) ~~~ " [ss x] (let [greater (first (subseq ss >= x)) smaller (first (rsubseq ss <= x))] (apply min-key #(abs (- % x)) (remove nil? [greater smaller])))) (defn nearest-of-seq "Maps each element of `b` to its nearest element in `a`. If `a` is empty, returns `b`. ~~~klipse (nearest-of-seq (range 5) [1.2 3.4 4]) ~~~ " [a b] (if (empty? a) b (map (partial nearest-of-ss (apply sorted-set a)) b))) (defn map-to-object "Returns a map whose keys are the elements of `lst` and values are mapped by `f`. ~~~klipse (map-to-object inc (range 5)) ~~~ " [f lst] (zipmap lst (map f lst))) (defn mapify " Takes a seq, and returns a map where the keys are the result of applying f to the elements in the seq. The result of f should be unique for each element in the seq, otherwise you will loose some data. If it is not unique, consider using [group-by](https://clojuredocs.org/clojure.core/group-by). ~~~klipse (mapify inc (range 5) ) ~~~ " [f s] (zipmap (map f s) s)) (defn map-with-index "Maps a sequence to a sequence of maps with index and value ~~~klipse (map-with-index [10 20 30] :idx :val) ~~~ " [s idx-key val-key] (map-indexed (fn [i v] {idx-key i val-key v}) s)) (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. `keys` is a sequence of keys. Any empty maps that result will not be present in the new structure. See [assoc-in](https://clojuredocs.org/clojure.core/assoc-in) ~~~klipse (dissoc-in {:a 1 :b 2} [:b]) ~~~ ~~~klipse (dissoc-in {:a {:b 2 :B 3} :c 3} [:a :b]) ~~~ ~~~klipse (dissoc-in {:a {:b 2} :c 3} [:a :b]) ~~~ " [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) (defn positions "Receives a collection of lengths and returns a list of start and end positions. Options: * `max-val`: (default `infinity`) - max value for `end` * `first-val`: (default 0) - first value of `start` ~~~klipse (positions '(10 10 20) :first-val 100 :max-val 137) ~~~ " [coll-of-lengths & {:keys [max-val first-val] :or {max-val infinity first-val 0}}] (let [end-pos (rest (reductions + first-val coll-of-lengths)) start-pos (concat [first-val] end-pos)] (map #(list (min max-val %1) (min max-val %2)) start-pos end-pos))) (defn split-by-predicate "Splits a collection to items where the separator is a repetition of at least n elements that satisfy `pred`. Inspired by: [this question](http://stackoverflow.com/a/23555616/813665). ~~~klipse (split-by-predicate (shuffle (range 30)) even? 2) ~~~ " [coll pred n] (let [part (partition-by pred coll) ppart (partition-by (fn [x] (and (>= (count x) n) (every? pred x))) part)] (map #(apply concat %) ppart))) (defn split-by-predicate-positions " Optimized version of `split-by-predicate` where we assume that the data is from a signal that we can sample. Instead of checking each element, we check 1 over `n` elements. We return the positions where the data splits. ~~~klipse (let [data (map Math/sin (range 0 6.28 0.001))] (split-by-predicate-positions data #(<= -0.01 % 0.01) 2 10)) ~~~ The following assertion holds: ~~~clojure (= (split-by-predicate coll pred n) (map #(apply subsequence data %) (split-by-predicate-positions coll pred n 1))) ~~~ Here is an example: ~~~klipse (let [data (map Math/sin (range 0 6.28 0.01))] (= (split-by-predicate data #(<= -0.01 % 0.01) 2) (map #(apply subsequence data %) (split-by-predicate-positions data #(<= -0.01 % 0.01) 2 1)))) ~~~ " [coll pred n d] (let [lengths (map #(* d %) (map count (split-by-predicate (take-nth d coll) pred (/ n d)))) pos (positions lengths :max-val (count coll))] pos)) (defn submap? "Checks if `m1` is a submap of `m2`. Map `m1` is a submap of `m2` if all key/value pairs in `m1` exist in `m2`. ~~~klipse (submap? {:a 1} {:a 1 :b 2}) ~~~ ~~~klipse (submap? {:a 1} {:a 1 :b 2 :c nil}) ~~~ " [m1 m2] (= m1 (select-keys m2 (keys m1)))) (defn subsequence " Returns a lazy subsequence of `coll`, starting at `start, ending at `end` (not included). ~~~klipse (subsequence (range) 10 20) ~~~ " [coll start end] (->> (drop start coll) (take (- end start)))) (defn index-of "Returns the index of an element in a sequence or `-1` if not present. ~~~klipse (index-of (range 100) 18) ~~~ " [s element] (or (ffirst (filter #(= (second %) element) (map-indexed #(vector %1 %2) s))) -1)) (defn- flatten-keys* [a ks m] (if (map? m) (if (seq m) (reduce into (map (fn [[k v]] (flatten-keys* a (conj ks k) v)) (seq m))) {}) (assoc a ks m))) (defn flatten-keys " Flatten the keys of a nested map. Thanks to [Jay Fields](http://blog.jayfields.com/2010/09/clojure-flatten-keys.html) ~~~klipse (flatten-keys {:a {:b 1} :c {:d 2 :e 4 :f {:g 8}}}) ~~~ " [m] (flatten-keys* {} [] m)) (defn unflatten-keys " Unflattend the keys of a map that has been `flatten-keys`ed. ~~~klipse (unflatten-keys {[:a :b] 1, [:c :d] 2, [:c :e] 4, [:c :f :g] 8}) ~~~ " [m] (reduce-kv (fn [a b c] (assoc-in a b c)) {} m)) (defn take-from-map "Creates a map with n leaves which are nested values of m. The following assertion holds: ~~~clojure (>= n (count (flatten-keys (take-from-map n m))))))) ~~~ ~~~klipse (take-from-map 3 {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}}) ~~~ " [n m] (->> m flatten-keys (take n) (into {}) unflatten-keys)) (defn- deep-merge* [& maps] (let [f (fn [old new] (if (and (map? old) (map? new)) (merge-with deep-merge* old new) new))] (if (every? map? maps) (apply merge-with f maps) (last maps)))) (defn deep-merge " Deep merges maps. ~~~klipse (deep-merge {} {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}} {:a {:b 1}, :c {:e 4, :d 2000, :f {:g 9000}}}) ~~~ " [& maps] (let [maps (filter identity maps)] (assert (every? map? maps)) (apply merge-with deep-merge* maps))) (defn- deep-merge-with* [g & maps] (let [f (fn [old new] (if (and (map? old) (map? new)) (merge-with (partial deep-merge-with* g) old new) (g old new)))] (if (every? map? maps) (apply merge-with f maps) (apply g maps)))) (defn deep-merge-with "Like merge-with but deep. ~~~klipse (deep-merge-with concat {:x {:b [1] :a [1]}} {:x {:a [3 4]}}) ~~~ " [g & maps] (let [maps (filter identity maps)] (assert (every? map? maps)) (apply merge-with (partial deep-merge-with* g) maps))) (defn branches-and-leaves "Returns all branches and leaves off a nested map object. ~~~klipse (branches-and-leaves {:a {:b 1 :c {:d 2}} :e 3}) ~~~ " [m] (as-> (tree-seq coll? #(if (map? %) (vals %) %) m) $ (group-by coll? $) (assoc $ true (or (get $ true) [])) (assoc $ false (or (get $ false) [])) (clojure.set/rename-keys $ {true :branches false :leaves}))) (defn filter-branches "Filters branches of a (nested) map `m` according to a predicate `m`. ~~~klipse (filter-branches {:x {:id 19 :b 1 :c {:id 2}} :e 3} :id) ~~~ " [m p] (->> (branches-and-leaves m) :branches (filter p))) (defn out-of-bound? "Checks if index `idx` is in range of vector `v`. More efficient than `(get v idx)` ~~~klipse (map #(out-of-bound? [1 2 3] %) [-1 0 1 2 3 4]) ~~~ " [v idx] (or (<= (count v) idx) (> 0 idx))) (defn partition-between "Splits a collection between two items according to predicate `pred` - which means split the sequence on breaking point. See: [here](http://stackoverflow.com/questions/23207490/partition-a-seq-by-a-windowing-predicate-in-clojure) For instance, split each time the series stop being ascending: ~~~klipse (partition-between > [1 2 4 9 8 7 6 5 1 2 4 5 11]) ~~~ " [pred coll] (let [switch (reductions not= true (map pred coll (rest coll)))] (map (partial map first) (partition-by second (map list coll switch))))) (defn collify "Ensure `s` is a collection: if `s` is a collection returns it; otherwise returns (s) ~~~klipse (collify 1) ~~~ ~~~klipse (collify [1 2 3]) ~~~ " [s] (if (coll? s) s (list s))) (defn edn-zip "A zipper for `edn`. ~~~klipse (edn-zip {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}}) ~~~ " [root] (zip/zipper #(or (vector? %) (map? %) (seq? %)) (fn [node] (cond (vector? node) (vec node) (map? node) (vec node) (seq? node) (seq node))) (fn [node children] (-> (cond (vector? node) (vec children) (map? node) (into {} children) (seq? node) children) (with-meta (meta node)))) root)) (defn- loc-my-replace [smap loc] (if-let [[_ [replacement & values]] (find smap (zip/node loc))] (as-> loc $ (zip/replace $ replacement) (reduce (fn [agg v] (zip/insert-right agg v)) $ (reverse values))) loc)) (defn my-replace "Recursively transforms `form` by replacing keys in `smap` with their values, spliced. The values in `smap` must be sequences. Like clojure.walk/prewalk-replace but supports list in values. ~~~klipse (my-replace '{go (go gadjett)} '(go (<! (timeout 100)) (go (<! timeout 0)))) ~~~ " [smap form] {:pre [(every? seq? (vals smap))]} (loop [loc (edn-zip form)] (if (zip/end? loc) (zip/root loc) (recur (zip/next (loc-my-replace smap loc)))))) (defn- comment? [s] (re-matches #"\s*;.*" s)) (defn remove-ending-comments "Removes comment lines from the end. ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\"aa\", \" \", \"bb\" \"; this comment should not appear\"])] (remove-ending-comments lines)) ~~~ " [s] (->> s split-lines reverse (drop-while comment?) reverse (join "\n"))) (defn fix-blank-lines "Removes blank lines from the begining and from the end (not from the middle) ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\" \", \"aa\", \" \", \"bb\", \" \t \"])] (fix-blank-lines lines)) ~~~ " [s] (->> s split-lines (drop-while blank?) reverse (drop-while blank?) reverse (join "\n"))) (defn remove-blank-lines "Removes blank lines. ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\" \", \"aa\", \" \", \"bb\", \" \t \"])] (remove-blank-lines lines)) ~~~ " [s] (->> s split-lines (remove blank?) (join "\n"))) #?(:cljs (defn compact " (clojurescript only) Compacts an expression by taking only the first `max-elements-in-coll` from collections and first `max-chars-in-str` from strings. Functions are displayed as \"lambda()\". It works recursively. It is useful for logging and reporting. Default settings: - `max-elements-in-coll` 10 - `max-chars-in-str` 20 ~~~klipse (compact {:infinite-list (range) :long-str \"a very very very very long string - too long to be true\" :long-map (zipmap (range 100) (range 100)) :function #(+ 1 2)}) ~~~ " [x & {:keys [max-elements-in-coll max-chars-in-str] :or {max-elements-in-coll 10 max-chars-in-str 20} :as args}] (cond (= x true) x (= x false) x (nil? x) x (keyword? x) x (number? x) x (string? x) (subs x 0 max-chars-in-str) (map? x) (take-from-map max-elements-in-coll (map-object #(compact % args) x)) (seqable? x) (take max-elements-in-coll (map #(compact % args) x)) (array? x) (str "***[" (type x) "]***") (= js/Function (type x)) "lambda()" (instance? js/Object x) (str "***[" (subs (str (type x)) 0 15) "]***") :else (str "***[" (type x) "]***"))) ) (defn map-nested-vals "Map the values of a nested map. ~~~klipse (map-nested-vals first {:a [1 2 3] :b {:c [4 5 6]}}) ~~~ " [f m] (->> m flatten-keys (map-object f) unflatten-keys)) (defn join-them "Join a sequence of collections `colls` according to function equality. `fns` - a sequence of functions `colls` - a sequence of collections ~~~klipse (let [a [{:id 1 :price 19} {:id 2 :price 3}] b [{:guid 1 :quantity 13}]] (join-them [:id :guid] [a b])) ~~~ " [fns colls] (->> (map mapify fns colls) (apply deep-merge) vals)) (comment (subs "a" 1)) (defn substr "Like clojure.core/subs but prevents some exceptions when the `start` or `end` are out of bound. ~~~klipse (subs \"\" -2) ~~~ " ([s start] (subs s (max 0 (min start (count s))))) ([s start end] (let [start (max 0 (min start (count s))) end (min (count s) end)] (subs s start end)))) (defn select-keys-in-order "Thanks [Jay Fields](http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html)" [m keyseq] (map m keyseq)) (defn select-vals [map keyseq] (vals (select-keys map keyseq))) (defn select-vals-in-order "Thanks [Jay Fields](http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html)" [map ks] (reduce #(conj %1 (map %2)) [] ks))
10089
(ns gadjett.collections (:require [clojure.set :refer [union]] [clojure.walk :refer [postwalk]] [clojure.string :refer [blank? join split-lines]] [clojure.zip :as zip])) (def infinity #?(:cljs js/Infinity :clj Double/POSITIVE_INFINITY)) (defn abs "Absolute value of a number ~~~klipse (map abs (range -5 5)) ~~~ " [x] (max x (- x))) (defn- scale [x y] (if (or (zero? x) (zero? y)) 1 (abs x))) (defn almost= ([x y] (almost= x y 0.00001)) ([x y epsilon] (or (= x y) (<= (abs (- x y)) (* (scale x y) epsilon))))) (defn- =set [a b] (= (into #{} a) (into #{} b))) (defn =without-keys? "Compare two maps exclusing some keys ~~~klipse (=without-keys? {:a 1 :b 2 :c 3} {:a 1 :b 5} #{:b :c}) ~~~ " [obj-a obj-b keys-list] (apply = (map #(apply dissoc % keys-list) [obj-a obj-b]))) (defn vec->map "Converts a 2d vec to a hash-map. ~~~klipse (vec->map [[:a 1] [:b 2]]) ~~~ " [vec] (into {} vec)) (defn map-2d-vec "Maps the values of a `2D` vector where each element of the vector is a key-value pair. `f` is a `1-ary` function that receives the key. ~~~klipse (map-2d-vec inc [[:a 1] [:b 2]]) ~~~ " [f m] (map (fn[[k id]] [k (f id)]) m)) (defn map-2d-vec-kv "Maps the values of a `2D` vector where each element of the vector is a key-value pair. `fk` is a `1-ary` function that receives the key. `fv` is a `1-ary` function that receives the value. ~~~klipse (map-2d-vec-kv name inc [[:a 1] [:b 2]]) ~~~ " [fk fv m] (map (fn[[k id]] [(fk k) (fv id)]) m)) (defn map-object "Returns a map with the same keys as `m` and with the values transformed by `f`. `f` is a `1-ary` function that receives the key. ~~~klipse (map-object inc {:a 1 :b 2 :c 3}) ~~~ " [f m] (vec->map (map-2d-vec f m))) (defn map-object-with-key "Returns a map with the same keys as `m` and with the values transformed by `f`. `f` must be a `2-ary` function that receives the key and the value as arguments. ~~~klipse (map-object-with-key list {:a 1 :b 2 :c 3}) ~~~ " [f m] (into {} (map (fn [[a b]] [a (f a b)]) m))) (defn map-object-kv "Returns a map with the keys mapped by `fk` and the values mapped by `fv`. ~~~klipse (map-object-kv name inc {:a 1 :b 2 :c 3}) ~~~ " [fk fv m] (vec->map (map-2d-vec-kv fk fv m))) (defn map-reverse-hierarchy "Turns a hash map inside out. See: [here](http://stackoverflow.com/a/23653784/813665) ~~~klipse (map-reverse-hierarchy {:monday {:banana 2 :apple 3} :tuesday {:banana 5 :orange 2}}) ~~~ " [m] (or (apply merge-with conj (for [[k1 v1] m [k2 v2] v1] {k2 {k1 v2}})) {})) (defn mean "Calculates the mean (a.k.a average) of a sequence of numbers. ~~~klipse (mean [1 2 10 -1 12.3]) ~~~ " [x] (if (empty? x) 0 (/ (apply + x) (count x)))) (defn sequence->map "Converts a sequence into a map where the keys are the indexes of the elements in the sequence. ~~~klipse (sequence->map [10 20 30]) ~~~ " [s] (zipmap (range (count s)) s)) (defn sequence-of-maps->map "Converts a sequence of maps into a map where: - the keys are extracted from the maps using `key-fn` - the vals extracted from the maps using `val-fn` ~~~klipse (sequence-of-maps->map [{:key :price :value 19} {:key :quantity :value 100}] :key :value) ~~~ " [coll key-fn val-fn] (reduce (fn [res m] (assoc res (key-fn m) (val-fn m))) {} coll)) (defn- range-with-end ([end] [end (range end)]) ([start end] [end (range start end)]) ([start end steps] [end (range start end steps)])) (defn range-till-end "Like `range` but including the `end`. ~~~klipse (range-till-end 10) ~~~ ~~~klipse (range-till-end 10 18) ~~~ ~~~klipse (range-till-end 10 100 5) ~~~ " [& args] (let [[end lis] (apply range-with-end args)] (concat lis [end]))) (defn append-cyclic "Appends an element to a list popping out the first element. ~~~klipse (-> (repeat 3 nil) (append-cyclic 1) (append-cyclic 2) (append-cyclic 3) (append-cyclic 4)) ~~~ " [lst a] (if (seq lst) (concat (rest lst) [a]) lst)) (defn assoc-cyclic "Assoc a key-value pair to a map popping out an element of the map. If the key already exists, no element is popped out. If `n` is supplied, no elmement is popped out if the map has less than `n` entries. ~~~klipse (-> {:a 1 :b 2 :c 3} (assoc-cyclic :d 4) (assoc-cyclic :e 5) (assoc-cyclic :f 6) (assoc-cyclic :g 7)) ~~~ " ([coll k v] (if (contains? coll k) (assoc coll k v) (into {} (append-cyclic coll [k v])))) ([coll k v n] (if (< (count coll) n) (assoc coll k v) (assoc-cyclic coll k v)))) (defn max-and-min "Returns a couple of the `max` and the `min` of a sequence. ~~~klipse (max-and-min (range 5)) ~~~ " [x] (if (empty? x) [0 0] ((juxt #(apply max %) #(apply min %)) x))) (defn compactize-map "Removes entries with `nil` values. ~~~klipse (compactize-map {:a 1 :b nil :c 3}) ~~~ " [m] (into {} (remove (comp nil? second) m))) ;; http://stackoverflow.com/a/34221816/813665 (defn compactize-map-recursive "Remove from a map the entries whose values are `nil`. If all the values of a nested map are `nil` the entrie is removed. ~~~klipse (compactize-map-recursive {:x 1 :z {:a nil} :a {:b nil :c 2 :d {:e nil :f 2}}}) ~~~ " [m] (let [f (fn [x] (if (map? x) (let [kvs (filter (comp not nil? second) x)] (if (empty? kvs) nil (into {} kvs))) x))] (postwalk f m))) (defn filter-map "Run a function on the values of a map and keep only the (key, value) pairs for which the function returns true ~~~klipse (filter-map even? {:a 1 :b 2 :c 3}) ~~~ " [f m] (into {} (filter (comp f val) m))) (defn nearest-of-ss "Returns the nearest number to `x` of a sorted set ~~~klipse (nearest-of-ss (apply sorted-set (range 5)) 1.2) ~~~ " [ss x] (let [greater (first (subseq ss >= x)) smaller (first (rsubseq ss <= x))] (apply min-key #(abs (- % x)) (remove nil? [greater smaller])))) (defn nearest-of-seq "Maps each element of `b` to its nearest element in `a`. If `a` is empty, returns `b`. ~~~klipse (nearest-of-seq (range 5) [1.2 3.4 4]) ~~~ " [a b] (if (empty? a) b (map (partial nearest-of-ss (apply sorted-set a)) b))) (defn map-to-object "Returns a map whose keys are the elements of `lst` and values are mapped by `f`. ~~~klipse (map-to-object inc (range 5)) ~~~ " [f lst] (zipmap lst (map f lst))) (defn mapify " Takes a seq, and returns a map where the keys are the result of applying f to the elements in the seq. The result of f should be unique for each element in the seq, otherwise you will loose some data. If it is not unique, consider using [group-by](https://clojuredocs.org/clojure.core/group-by). ~~~klipse (mapify inc (range 5) ) ~~~ " [f s] (zipmap (map f s) s)) (defn map-with-index "Maps a sequence to a sequence of maps with index and value ~~~klipse (map-with-index [10 20 30] :idx :val) ~~~ " [s idx-key val-key] (map-indexed (fn [i v] {idx-key i val-key v}) s)) (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. `keys` is a sequence of keys. Any empty maps that result will not be present in the new structure. See [assoc-in](https://clojuredocs.org/clojure.core/assoc-in) ~~~klipse (dissoc-in {:a 1 :b 2} [:b]) ~~~ ~~~klipse (dissoc-in {:a {:b 2 :B 3} :c 3} [:a :b]) ~~~ ~~~klipse (dissoc-in {:a {:b 2} :c 3} [:a :b]) ~~~ " [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) (defn positions "Receives a collection of lengths and returns a list of start and end positions. Options: * `max-val`: (default `infinity`) - max value for `end` * `first-val`: (default 0) - first value of `start` ~~~klipse (positions '(10 10 20) :first-val 100 :max-val 137) ~~~ " [coll-of-lengths & {:keys [max-val first-val] :or {max-val infinity first-val 0}}] (let [end-pos (rest (reductions + first-val coll-of-lengths)) start-pos (concat [first-val] end-pos)] (map #(list (min max-val %1) (min max-val %2)) start-pos end-pos))) (defn split-by-predicate "Splits a collection to items where the separator is a repetition of at least n elements that satisfy `pred`. Inspired by: [this question](http://stackoverflow.com/a/23555616/813665). ~~~klipse (split-by-predicate (shuffle (range 30)) even? 2) ~~~ " [coll pred n] (let [part (partition-by pred coll) ppart (partition-by (fn [x] (and (>= (count x) n) (every? pred x))) part)] (map #(apply concat %) ppart))) (defn split-by-predicate-positions " Optimized version of `split-by-predicate` where we assume that the data is from a signal that we can sample. Instead of checking each element, we check 1 over `n` elements. We return the positions where the data splits. ~~~klipse (let [data (map Math/sin (range 0 6.28 0.001))] (split-by-predicate-positions data #(<= -0.01 % 0.01) 2 10)) ~~~ The following assertion holds: ~~~clojure (= (split-by-predicate coll pred n) (map #(apply subsequence data %) (split-by-predicate-positions coll pred n 1))) ~~~ Here is an example: ~~~klipse (let [data (map Math/sin (range 0 6.28 0.01))] (= (split-by-predicate data #(<= -0.01 % 0.01) 2) (map #(apply subsequence data %) (split-by-predicate-positions data #(<= -0.01 % 0.01) 2 1)))) ~~~ " [coll pred n d] (let [lengths (map #(* d %) (map count (split-by-predicate (take-nth d coll) pred (/ n d)))) pos (positions lengths :max-val (count coll))] pos)) (defn submap? "Checks if `m1` is a submap of `m2`. Map `m1` is a submap of `m2` if all key/value pairs in `m1` exist in `m2`. ~~~klipse (submap? {:a 1} {:a 1 :b 2}) ~~~ ~~~klipse (submap? {:a 1} {:a 1 :b 2 :c nil}) ~~~ " [m1 m2] (= m1 (select-keys m2 (keys m1)))) (defn subsequence " Returns a lazy subsequence of `coll`, starting at `start, ending at `end` (not included). ~~~klipse (subsequence (range) 10 20) ~~~ " [coll start end] (->> (drop start coll) (take (- end start)))) (defn index-of "Returns the index of an element in a sequence or `-1` if not present. ~~~klipse (index-of (range 100) 18) ~~~ " [s element] (or (ffirst (filter #(= (second %) element) (map-indexed #(vector %1 %2) s))) -1)) (defn- flatten-keys* [a ks m] (if (map? m) (if (seq m) (reduce into (map (fn [[k v]] (flatten-keys* a (conj ks k) v)) (seq m))) {}) (assoc a ks m))) (defn flatten-keys " Flatten the keys of a nested map. Thanks to [Jay Fields](http://blog.jayfields.com/2010/09/clojure-flatten-keys.html) ~~~klipse (flatten-keys {:a {:b 1} :c {:d 2 :e 4 :f {:g 8}}}) ~~~ " [m] (flatten-keys* {} [] m)) (defn unflatten-keys " Unflattend the keys of a map that has been `flatten-keys`ed. ~~~klipse (unflatten-keys {[:a :b] 1, [:c :d] 2, [:c :e] 4, [:c :f :g] 8}) ~~~ " [m] (reduce-kv (fn [a b c] (assoc-in a b c)) {} m)) (defn take-from-map "Creates a map with n leaves which are nested values of m. The following assertion holds: ~~~clojure (>= n (count (flatten-keys (take-from-map n m))))))) ~~~ ~~~klipse (take-from-map 3 {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}}) ~~~ " [n m] (->> m flatten-keys (take n) (into {}) unflatten-keys)) (defn- deep-merge* [& maps] (let [f (fn [old new] (if (and (map? old) (map? new)) (merge-with deep-merge* old new) new))] (if (every? map? maps) (apply merge-with f maps) (last maps)))) (defn deep-merge " Deep merges maps. ~~~klipse (deep-merge {} {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}} {:a {:b 1}, :c {:e 4, :d 2000, :f {:g 9000}}}) ~~~ " [& maps] (let [maps (filter identity maps)] (assert (every? map? maps)) (apply merge-with deep-merge* maps))) (defn- deep-merge-with* [g & maps] (let [f (fn [old new] (if (and (map? old) (map? new)) (merge-with (partial deep-merge-with* g) old new) (g old new)))] (if (every? map? maps) (apply merge-with f maps) (apply g maps)))) (defn deep-merge-with "Like merge-with but deep. ~~~klipse (deep-merge-with concat {:x {:b [1] :a [1]}} {:x {:a [3 4]}}) ~~~ " [g & maps] (let [maps (filter identity maps)] (assert (every? map? maps)) (apply merge-with (partial deep-merge-with* g) maps))) (defn branches-and-leaves "Returns all branches and leaves off a nested map object. ~~~klipse (branches-and-leaves {:a {:b 1 :c {:d 2}} :e 3}) ~~~ " [m] (as-> (tree-seq coll? #(if (map? %) (vals %) %) m) $ (group-by coll? $) (assoc $ true (or (get $ true) [])) (assoc $ false (or (get $ false) [])) (clojure.set/rename-keys $ {true :branches false :leaves}))) (defn filter-branches "Filters branches of a (nested) map `m` according to a predicate `m`. ~~~klipse (filter-branches {:x {:id 19 :b 1 :c {:id 2}} :e 3} :id) ~~~ " [m p] (->> (branches-and-leaves m) :branches (filter p))) (defn out-of-bound? "Checks if index `idx` is in range of vector `v`. More efficient than `(get v idx)` ~~~klipse (map #(out-of-bound? [1 2 3] %) [-1 0 1 2 3 4]) ~~~ " [v idx] (or (<= (count v) idx) (> 0 idx))) (defn partition-between "Splits a collection between two items according to predicate `pred` - which means split the sequence on breaking point. See: [here](http://stackoverflow.com/questions/23207490/partition-a-seq-by-a-windowing-predicate-in-clojure) For instance, split each time the series stop being ascending: ~~~klipse (partition-between > [1 2 4 9 8 7 6 5 1 2 4 5 11]) ~~~ " [pred coll] (let [switch (reductions not= true (map pred coll (rest coll)))] (map (partial map first) (partition-by second (map list coll switch))))) (defn collify "Ensure `s` is a collection: if `s` is a collection returns it; otherwise returns (s) ~~~klipse (collify 1) ~~~ ~~~klipse (collify [1 2 3]) ~~~ " [s] (if (coll? s) s (list s))) (defn edn-zip "A zipper for `edn`. ~~~klipse (edn-zip {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}}) ~~~ " [root] (zip/zipper #(or (vector? %) (map? %) (seq? %)) (fn [node] (cond (vector? node) (vec node) (map? node) (vec node) (seq? node) (seq node))) (fn [node children] (-> (cond (vector? node) (vec children) (map? node) (into {} children) (seq? node) children) (with-meta (meta node)))) root)) (defn- loc-my-replace [smap loc] (if-let [[_ [replacement & values]] (find smap (zip/node loc))] (as-> loc $ (zip/replace $ replacement) (reduce (fn [agg v] (zip/insert-right agg v)) $ (reverse values))) loc)) (defn my-replace "Recursively transforms `form` by replacing keys in `smap` with their values, spliced. The values in `smap` must be sequences. Like clojure.walk/prewalk-replace but supports list in values. ~~~klipse (my-replace '{go (go gadjett)} '(go (<! (timeout 100)) (go (<! timeout 0)))) ~~~ " [smap form] {:pre [(every? seq? (vals smap))]} (loop [loc (edn-zip form)] (if (zip/end? loc) (zip/root loc) (recur (zip/next (loc-my-replace smap loc)))))) (defn- comment? [s] (re-matches #"\s*;.*" s)) (defn remove-ending-comments "Removes comment lines from the end. ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\"aa\", \" \", \"bb\" \"; this comment should not appear\"])] (remove-ending-comments lines)) ~~~ " [s] (->> s split-lines reverse (drop-while comment?) reverse (join "\n"))) (defn fix-blank-lines "Removes blank lines from the begining and from the end (not from the middle) ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\" \", \"aa\", \" \", \"bb\", \" \t \"])] (fix-blank-lines lines)) ~~~ " [s] (->> s split-lines (drop-while blank?) reverse (drop-while blank?) reverse (join "\n"))) (defn remove-blank-lines "Removes blank lines. ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\" \", \"aa\", \" \", \"bb\", \" \t \"])] (remove-blank-lines lines)) ~~~ " [s] (->> s split-lines (remove blank?) (join "\n"))) #?(:cljs (defn compact " (clojurescript only) Compacts an expression by taking only the first `max-elements-in-coll` from collections and first `max-chars-in-str` from strings. Functions are displayed as \"lambda()\". It works recursively. It is useful for logging and reporting. Default settings: - `max-elements-in-coll` 10 - `max-chars-in-str` 20 ~~~klipse (compact {:infinite-list (range) :long-str \"a very very very very long string - too long to be true\" :long-map (zipmap (range 100) (range 100)) :function #(+ 1 2)}) ~~~ " [x & {:keys [max-elements-in-coll max-chars-in-str] :or {max-elements-in-coll 10 max-chars-in-str 20} :as args}] (cond (= x true) x (= x false) x (nil? x) x (keyword? x) x (number? x) x (string? x) (subs x 0 max-chars-in-str) (map? x) (take-from-map max-elements-in-coll (map-object #(compact % args) x)) (seqable? x) (take max-elements-in-coll (map #(compact % args) x)) (array? x) (str "***[" (type x) "]***") (= js/Function (type x)) "lambda()" (instance? js/Object x) (str "***[" (subs (str (type x)) 0 15) "]***") :else (str "***[" (type x) "]***"))) ) (defn map-nested-vals "Map the values of a nested map. ~~~klipse (map-nested-vals first {:a [1 2 3] :b {:c [4 5 6]}}) ~~~ " [f m] (->> m flatten-keys (map-object f) unflatten-keys)) (defn join-them "Join a sequence of collections `colls` according to function equality. `fns` - a sequence of functions `colls` - a sequence of collections ~~~klipse (let [a [{:id 1 :price 19} {:id 2 :price 3}] b [{:guid 1 :quantity 13}]] (join-them [:id :guid] [a b])) ~~~ " [fns colls] (->> (map mapify fns colls) (apply deep-merge) vals)) (comment (subs "a" 1)) (defn substr "Like clojure.core/subs but prevents some exceptions when the `start` or `end` are out of bound. ~~~klipse (subs \"\" -2) ~~~ " ([s start] (subs s (max 0 (min start (count s))))) ([s start end] (let [start (max 0 (min start (count s))) end (min (count s) end)] (subs s start end)))) (defn select-keys-in-order "Thanks [<NAME>](http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html)" [m keyseq] (map m keyseq)) (defn select-vals [map keyseq] (vals (select-keys map keyseq))) (defn select-vals-in-order "Thanks [<NAME>](http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html)" [map ks] (reduce #(conj %1 (map %2)) [] ks))
true
(ns gadjett.collections (:require [clojure.set :refer [union]] [clojure.walk :refer [postwalk]] [clojure.string :refer [blank? join split-lines]] [clojure.zip :as zip])) (def infinity #?(:cljs js/Infinity :clj Double/POSITIVE_INFINITY)) (defn abs "Absolute value of a number ~~~klipse (map abs (range -5 5)) ~~~ " [x] (max x (- x))) (defn- scale [x y] (if (or (zero? x) (zero? y)) 1 (abs x))) (defn almost= ([x y] (almost= x y 0.00001)) ([x y epsilon] (or (= x y) (<= (abs (- x y)) (* (scale x y) epsilon))))) (defn- =set [a b] (= (into #{} a) (into #{} b))) (defn =without-keys? "Compare two maps exclusing some keys ~~~klipse (=without-keys? {:a 1 :b 2 :c 3} {:a 1 :b 5} #{:b :c}) ~~~ " [obj-a obj-b keys-list] (apply = (map #(apply dissoc % keys-list) [obj-a obj-b]))) (defn vec->map "Converts a 2d vec to a hash-map. ~~~klipse (vec->map [[:a 1] [:b 2]]) ~~~ " [vec] (into {} vec)) (defn map-2d-vec "Maps the values of a `2D` vector where each element of the vector is a key-value pair. `f` is a `1-ary` function that receives the key. ~~~klipse (map-2d-vec inc [[:a 1] [:b 2]]) ~~~ " [f m] (map (fn[[k id]] [k (f id)]) m)) (defn map-2d-vec-kv "Maps the values of a `2D` vector where each element of the vector is a key-value pair. `fk` is a `1-ary` function that receives the key. `fv` is a `1-ary` function that receives the value. ~~~klipse (map-2d-vec-kv name inc [[:a 1] [:b 2]]) ~~~ " [fk fv m] (map (fn[[k id]] [(fk k) (fv id)]) m)) (defn map-object "Returns a map with the same keys as `m` and with the values transformed by `f`. `f` is a `1-ary` function that receives the key. ~~~klipse (map-object inc {:a 1 :b 2 :c 3}) ~~~ " [f m] (vec->map (map-2d-vec f m))) (defn map-object-with-key "Returns a map with the same keys as `m` and with the values transformed by `f`. `f` must be a `2-ary` function that receives the key and the value as arguments. ~~~klipse (map-object-with-key list {:a 1 :b 2 :c 3}) ~~~ " [f m] (into {} (map (fn [[a b]] [a (f a b)]) m))) (defn map-object-kv "Returns a map with the keys mapped by `fk` and the values mapped by `fv`. ~~~klipse (map-object-kv name inc {:a 1 :b 2 :c 3}) ~~~ " [fk fv m] (vec->map (map-2d-vec-kv fk fv m))) (defn map-reverse-hierarchy "Turns a hash map inside out. See: [here](http://stackoverflow.com/a/23653784/813665) ~~~klipse (map-reverse-hierarchy {:monday {:banana 2 :apple 3} :tuesday {:banana 5 :orange 2}}) ~~~ " [m] (or (apply merge-with conj (for [[k1 v1] m [k2 v2] v1] {k2 {k1 v2}})) {})) (defn mean "Calculates the mean (a.k.a average) of a sequence of numbers. ~~~klipse (mean [1 2 10 -1 12.3]) ~~~ " [x] (if (empty? x) 0 (/ (apply + x) (count x)))) (defn sequence->map "Converts a sequence into a map where the keys are the indexes of the elements in the sequence. ~~~klipse (sequence->map [10 20 30]) ~~~ " [s] (zipmap (range (count s)) s)) (defn sequence-of-maps->map "Converts a sequence of maps into a map where: - the keys are extracted from the maps using `key-fn` - the vals extracted from the maps using `val-fn` ~~~klipse (sequence-of-maps->map [{:key :price :value 19} {:key :quantity :value 100}] :key :value) ~~~ " [coll key-fn val-fn] (reduce (fn [res m] (assoc res (key-fn m) (val-fn m))) {} coll)) (defn- range-with-end ([end] [end (range end)]) ([start end] [end (range start end)]) ([start end steps] [end (range start end steps)])) (defn range-till-end "Like `range` but including the `end`. ~~~klipse (range-till-end 10) ~~~ ~~~klipse (range-till-end 10 18) ~~~ ~~~klipse (range-till-end 10 100 5) ~~~ " [& args] (let [[end lis] (apply range-with-end args)] (concat lis [end]))) (defn append-cyclic "Appends an element to a list popping out the first element. ~~~klipse (-> (repeat 3 nil) (append-cyclic 1) (append-cyclic 2) (append-cyclic 3) (append-cyclic 4)) ~~~ " [lst a] (if (seq lst) (concat (rest lst) [a]) lst)) (defn assoc-cyclic "Assoc a key-value pair to a map popping out an element of the map. If the key already exists, no element is popped out. If `n` is supplied, no elmement is popped out if the map has less than `n` entries. ~~~klipse (-> {:a 1 :b 2 :c 3} (assoc-cyclic :d 4) (assoc-cyclic :e 5) (assoc-cyclic :f 6) (assoc-cyclic :g 7)) ~~~ " ([coll k v] (if (contains? coll k) (assoc coll k v) (into {} (append-cyclic coll [k v])))) ([coll k v n] (if (< (count coll) n) (assoc coll k v) (assoc-cyclic coll k v)))) (defn max-and-min "Returns a couple of the `max` and the `min` of a sequence. ~~~klipse (max-and-min (range 5)) ~~~ " [x] (if (empty? x) [0 0] ((juxt #(apply max %) #(apply min %)) x))) (defn compactize-map "Removes entries with `nil` values. ~~~klipse (compactize-map {:a 1 :b nil :c 3}) ~~~ " [m] (into {} (remove (comp nil? second) m))) ;; http://stackoverflow.com/a/34221816/813665 (defn compactize-map-recursive "Remove from a map the entries whose values are `nil`. If all the values of a nested map are `nil` the entrie is removed. ~~~klipse (compactize-map-recursive {:x 1 :z {:a nil} :a {:b nil :c 2 :d {:e nil :f 2}}}) ~~~ " [m] (let [f (fn [x] (if (map? x) (let [kvs (filter (comp not nil? second) x)] (if (empty? kvs) nil (into {} kvs))) x))] (postwalk f m))) (defn filter-map "Run a function on the values of a map and keep only the (key, value) pairs for which the function returns true ~~~klipse (filter-map even? {:a 1 :b 2 :c 3}) ~~~ " [f m] (into {} (filter (comp f val) m))) (defn nearest-of-ss "Returns the nearest number to `x` of a sorted set ~~~klipse (nearest-of-ss (apply sorted-set (range 5)) 1.2) ~~~ " [ss x] (let [greater (first (subseq ss >= x)) smaller (first (rsubseq ss <= x))] (apply min-key #(abs (- % x)) (remove nil? [greater smaller])))) (defn nearest-of-seq "Maps each element of `b` to its nearest element in `a`. If `a` is empty, returns `b`. ~~~klipse (nearest-of-seq (range 5) [1.2 3.4 4]) ~~~ " [a b] (if (empty? a) b (map (partial nearest-of-ss (apply sorted-set a)) b))) (defn map-to-object "Returns a map whose keys are the elements of `lst` and values are mapped by `f`. ~~~klipse (map-to-object inc (range 5)) ~~~ " [f lst] (zipmap lst (map f lst))) (defn mapify " Takes a seq, and returns a map where the keys are the result of applying f to the elements in the seq. The result of f should be unique for each element in the seq, otherwise you will loose some data. If it is not unique, consider using [group-by](https://clojuredocs.org/clojure.core/group-by). ~~~klipse (mapify inc (range 5) ) ~~~ " [f s] (zipmap (map f s) s)) (defn map-with-index "Maps a sequence to a sequence of maps with index and value ~~~klipse (map-with-index [10 20 30] :idx :val) ~~~ " [s idx-key val-key] (map-indexed (fn [i v] {idx-key i val-key v}) s)) (defn dissoc-in "Dissociates an entry from a nested associative structure returning a new nested structure. `keys` is a sequence of keys. Any empty maps that result will not be present in the new structure. See [assoc-in](https://clojuredocs.org/clojure.core/assoc-in) ~~~klipse (dissoc-in {:a 1 :b 2} [:b]) ~~~ ~~~klipse (dissoc-in {:a {:b 2 :B 3} :c 3} [:a :b]) ~~~ ~~~klipse (dissoc-in {:a {:b 2} :c 3} [:a :b]) ~~~ " [m [k & ks :as keys]] (if ks (if-let [nextmap (get m k)] (let [newmap (dissoc-in nextmap ks)] (if (seq newmap) (assoc m k newmap) (dissoc m k))) m) (dissoc m k))) (defn positions "Receives a collection of lengths and returns a list of start and end positions. Options: * `max-val`: (default `infinity`) - max value for `end` * `first-val`: (default 0) - first value of `start` ~~~klipse (positions '(10 10 20) :first-val 100 :max-val 137) ~~~ " [coll-of-lengths & {:keys [max-val first-val] :or {max-val infinity first-val 0}}] (let [end-pos (rest (reductions + first-val coll-of-lengths)) start-pos (concat [first-val] end-pos)] (map #(list (min max-val %1) (min max-val %2)) start-pos end-pos))) (defn split-by-predicate "Splits a collection to items where the separator is a repetition of at least n elements that satisfy `pred`. Inspired by: [this question](http://stackoverflow.com/a/23555616/813665). ~~~klipse (split-by-predicate (shuffle (range 30)) even? 2) ~~~ " [coll pred n] (let [part (partition-by pred coll) ppart (partition-by (fn [x] (and (>= (count x) n) (every? pred x))) part)] (map #(apply concat %) ppart))) (defn split-by-predicate-positions " Optimized version of `split-by-predicate` where we assume that the data is from a signal that we can sample. Instead of checking each element, we check 1 over `n` elements. We return the positions where the data splits. ~~~klipse (let [data (map Math/sin (range 0 6.28 0.001))] (split-by-predicate-positions data #(<= -0.01 % 0.01) 2 10)) ~~~ The following assertion holds: ~~~clojure (= (split-by-predicate coll pred n) (map #(apply subsequence data %) (split-by-predicate-positions coll pred n 1))) ~~~ Here is an example: ~~~klipse (let [data (map Math/sin (range 0 6.28 0.01))] (= (split-by-predicate data #(<= -0.01 % 0.01) 2) (map #(apply subsequence data %) (split-by-predicate-positions data #(<= -0.01 % 0.01) 2 1)))) ~~~ " [coll pred n d] (let [lengths (map #(* d %) (map count (split-by-predicate (take-nth d coll) pred (/ n d)))) pos (positions lengths :max-val (count coll))] pos)) (defn submap? "Checks if `m1` is a submap of `m2`. Map `m1` is a submap of `m2` if all key/value pairs in `m1` exist in `m2`. ~~~klipse (submap? {:a 1} {:a 1 :b 2}) ~~~ ~~~klipse (submap? {:a 1} {:a 1 :b 2 :c nil}) ~~~ " [m1 m2] (= m1 (select-keys m2 (keys m1)))) (defn subsequence " Returns a lazy subsequence of `coll`, starting at `start, ending at `end` (not included). ~~~klipse (subsequence (range) 10 20) ~~~ " [coll start end] (->> (drop start coll) (take (- end start)))) (defn index-of "Returns the index of an element in a sequence or `-1` if not present. ~~~klipse (index-of (range 100) 18) ~~~ " [s element] (or (ffirst (filter #(= (second %) element) (map-indexed #(vector %1 %2) s))) -1)) (defn- flatten-keys* [a ks m] (if (map? m) (if (seq m) (reduce into (map (fn [[k v]] (flatten-keys* a (conj ks k) v)) (seq m))) {}) (assoc a ks m))) (defn flatten-keys " Flatten the keys of a nested map. Thanks to [Jay Fields](http://blog.jayfields.com/2010/09/clojure-flatten-keys.html) ~~~klipse (flatten-keys {:a {:b 1} :c {:d 2 :e 4 :f {:g 8}}}) ~~~ " [m] (flatten-keys* {} [] m)) (defn unflatten-keys " Unflattend the keys of a map that has been `flatten-keys`ed. ~~~klipse (unflatten-keys {[:a :b] 1, [:c :d] 2, [:c :e] 4, [:c :f :g] 8}) ~~~ " [m] (reduce-kv (fn [a b c] (assoc-in a b c)) {} m)) (defn take-from-map "Creates a map with n leaves which are nested values of m. The following assertion holds: ~~~clojure (>= n (count (flatten-keys (take-from-map n m))))))) ~~~ ~~~klipse (take-from-map 3 {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}}) ~~~ " [n m] (->> m flatten-keys (take n) (into {}) unflatten-keys)) (defn- deep-merge* [& maps] (let [f (fn [old new] (if (and (map? old) (map? new)) (merge-with deep-merge* old new) new))] (if (every? map? maps) (apply merge-with f maps) (last maps)))) (defn deep-merge " Deep merges maps. ~~~klipse (deep-merge {} {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}} {:a {:b 1}, :c {:e 4, :d 2000, :f {:g 9000}}}) ~~~ " [& maps] (let [maps (filter identity maps)] (assert (every? map? maps)) (apply merge-with deep-merge* maps))) (defn- deep-merge-with* [g & maps] (let [f (fn [old new] (if (and (map? old) (map? new)) (merge-with (partial deep-merge-with* g) old new) (g old new)))] (if (every? map? maps) (apply merge-with f maps) (apply g maps)))) (defn deep-merge-with "Like merge-with but deep. ~~~klipse (deep-merge-with concat {:x {:b [1] :a [1]}} {:x {:a [3 4]}}) ~~~ " [g & maps] (let [maps (filter identity maps)] (assert (every? map? maps)) (apply merge-with (partial deep-merge-with* g) maps))) (defn branches-and-leaves "Returns all branches and leaves off a nested map object. ~~~klipse (branches-and-leaves {:a {:b 1 :c {:d 2}} :e 3}) ~~~ " [m] (as-> (tree-seq coll? #(if (map? %) (vals %) %) m) $ (group-by coll? $) (assoc $ true (or (get $ true) [])) (assoc $ false (or (get $ false) [])) (clojure.set/rename-keys $ {true :branches false :leaves}))) (defn filter-branches "Filters branches of a (nested) map `m` according to a predicate `m`. ~~~klipse (filter-branches {:x {:id 19 :b 1 :c {:id 2}} :e 3} :id) ~~~ " [m p] (->> (branches-and-leaves m) :branches (filter p))) (defn out-of-bound? "Checks if index `idx` is in range of vector `v`. More efficient than `(get v idx)` ~~~klipse (map #(out-of-bound? [1 2 3] %) [-1 0 1 2 3 4]) ~~~ " [v idx] (or (<= (count v) idx) (> 0 idx))) (defn partition-between "Splits a collection between two items according to predicate `pred` - which means split the sequence on breaking point. See: [here](http://stackoverflow.com/questions/23207490/partition-a-seq-by-a-windowing-predicate-in-clojure) For instance, split each time the series stop being ascending: ~~~klipse (partition-between > [1 2 4 9 8 7 6 5 1 2 4 5 11]) ~~~ " [pred coll] (let [switch (reductions not= true (map pred coll (rest coll)))] (map (partial map first) (partition-by second (map list coll switch))))) (defn collify "Ensure `s` is a collection: if `s` is a collection returns it; otherwise returns (s) ~~~klipse (collify 1) ~~~ ~~~klipse (collify [1 2 3]) ~~~ " [s] (if (coll? s) s (list s))) (defn edn-zip "A zipper for `edn`. ~~~klipse (edn-zip {:a {:b 1}, :c {:e 4, :d 2, :f {:g 8}}}) ~~~ " [root] (zip/zipper #(or (vector? %) (map? %) (seq? %)) (fn [node] (cond (vector? node) (vec node) (map? node) (vec node) (seq? node) (seq node))) (fn [node children] (-> (cond (vector? node) (vec children) (map? node) (into {} children) (seq? node) children) (with-meta (meta node)))) root)) (defn- loc-my-replace [smap loc] (if-let [[_ [replacement & values]] (find smap (zip/node loc))] (as-> loc $ (zip/replace $ replacement) (reduce (fn [agg v] (zip/insert-right agg v)) $ (reverse values))) loc)) (defn my-replace "Recursively transforms `form` by replacing keys in `smap` with their values, spliced. The values in `smap` must be sequences. Like clojure.walk/prewalk-replace but supports list in values. ~~~klipse (my-replace '{go (go gadjett)} '(go (<! (timeout 100)) (go (<! timeout 0)))) ~~~ " [smap form] {:pre [(every? seq? (vals smap))]} (loop [loc (edn-zip form)] (if (zip/end? loc) (zip/root loc) (recur (zip/next (loc-my-replace smap loc)))))) (defn- comment? [s] (re-matches #"\s*;.*" s)) (defn remove-ending-comments "Removes comment lines from the end. ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\"aa\", \" \", \"bb\" \"; this comment should not appear\"])] (remove-ending-comments lines)) ~~~ " [s] (->> s split-lines reverse (drop-while comment?) reverse (join "\n"))) (defn fix-blank-lines "Removes blank lines from the begining and from the end (not from the middle) ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\" \", \"aa\", \" \", \"bb\", \" \t \"])] (fix-blank-lines lines)) ~~~ " [s] (->> s split-lines (drop-while blank?) reverse (drop-while blank?) reverse (join "\n"))) (defn remove-blank-lines "Removes blank lines. ~~~klipse ; we use (char 10) for end-of-line due to technical issues with string manipulation with `codox` (let [lines (clojure.string/join (char 10) [\" \", \"aa\", \" \", \"bb\", \" \t \"])] (remove-blank-lines lines)) ~~~ " [s] (->> s split-lines (remove blank?) (join "\n"))) #?(:cljs (defn compact " (clojurescript only) Compacts an expression by taking only the first `max-elements-in-coll` from collections and first `max-chars-in-str` from strings. Functions are displayed as \"lambda()\". It works recursively. It is useful for logging and reporting. Default settings: - `max-elements-in-coll` 10 - `max-chars-in-str` 20 ~~~klipse (compact {:infinite-list (range) :long-str \"a very very very very long string - too long to be true\" :long-map (zipmap (range 100) (range 100)) :function #(+ 1 2)}) ~~~ " [x & {:keys [max-elements-in-coll max-chars-in-str] :or {max-elements-in-coll 10 max-chars-in-str 20} :as args}] (cond (= x true) x (= x false) x (nil? x) x (keyword? x) x (number? x) x (string? x) (subs x 0 max-chars-in-str) (map? x) (take-from-map max-elements-in-coll (map-object #(compact % args) x)) (seqable? x) (take max-elements-in-coll (map #(compact % args) x)) (array? x) (str "***[" (type x) "]***") (= js/Function (type x)) "lambda()" (instance? js/Object x) (str "***[" (subs (str (type x)) 0 15) "]***") :else (str "***[" (type x) "]***"))) ) (defn map-nested-vals "Map the values of a nested map. ~~~klipse (map-nested-vals first {:a [1 2 3] :b {:c [4 5 6]}}) ~~~ " [f m] (->> m flatten-keys (map-object f) unflatten-keys)) (defn join-them "Join a sequence of collections `colls` according to function equality. `fns` - a sequence of functions `colls` - a sequence of collections ~~~klipse (let [a [{:id 1 :price 19} {:id 2 :price 3}] b [{:guid 1 :quantity 13}]] (join-them [:id :guid] [a b])) ~~~ " [fns colls] (->> (map mapify fns colls) (apply deep-merge) vals)) (comment (subs "a" 1)) (defn substr "Like clojure.core/subs but prevents some exceptions when the `start` or `end` are out of bound. ~~~klipse (subs \"\" -2) ~~~ " ([s start] (subs s (max 0 (min start (count s))))) ([s start end] (let [start (max 0 (min start (count s))) end (min (count s) end)] (subs s start end)))) (defn select-keys-in-order "Thanks [PI:NAME:<NAME>END_PI](http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html)" [m keyseq] (map m keyseq)) (defn select-vals [map keyseq] (vals (select-keys map keyseq))) (defn select-vals-in-order "Thanks [PI:NAME:<NAME>END_PI](http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html)" [map ks] (reduce #(conj %1 (map %2)) [] ks))
[ { "context": "\n (with-redefs [config-nuvla/*stripe-api-key* \"123\"\n a/is-admin? ", "end": 1049, "score": 0.9238130450248718, "start": 1046, "tag": "KEY", "value": "123" }, { "context": "(with-redefs [config-nuvla/*stripe-api-key* \"123\"\n a/is-admin? ", "end": 1262, "score": 0.926826536655426, "start": 1259, "tag": "KEY", "value": "123" }, { "context": "(with-redefs [config-nuvla/*stripe-api-key* \"123\"\n a/is-admin? ", "end": 1568, "score": 0.9447224736213684, "start": 1565, "tag": "KEY", "value": "123" }, { "context": "(with-redefs [config-nuvla/*stripe-api-key* \"123\"\n a/is-admin? ", "end": 1873, "score": 0.9022027850151062, "start": 1870, "tag": "KEY", "value": "123" } ]
code/test/sixsq/nuvla/server/resources/nuvlabox/utils_test.clj
nuvla/server
0
(ns sixsq.nuvla.server.resources.nuvlabox.utils-test (:require [clojure.test :refer [deftest is testing]] [sixsq.nuvla.auth.acl-resource :as a] [sixsq.nuvla.pricing.payment :as payment] [sixsq.nuvla.server.resources.configuration-nuvla :as config-nuvla] [sixsq.nuvla.server.resources.nuvlabox.utils :as t])) (deftest check-short-nb-id (is (nil? (t/short-nb-id nil))) (is (= "abc" (t/short-nb-id "nuvlabox/abc-def-ghi-jkl")))) (deftest check-has-pull-support? (is (false? (t/has-pull-support? {:capabilities []}))) (is (false? (t/has-pull-support? {}))) (is (false? (t/has-pull-support? {:capabilities ["ANYTHING"]}))) (is (t/has-pull-support? {:capabilities ["ANYTHING" "NUVLA_JOB_PULL"]}))) (deftest throw-when-payment-required (testing "stripe is disabled" (with-redefs [config-nuvla/*stripe-api-key* nil a/is-admin? (constantly false)] (is (= (t/throw-when-payment-required {}) {})))) (testing "is admin" (with-redefs [config-nuvla/*stripe-api-key* "123" a/is-admin? (constantly true)] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer is active" (with-redefs [config-nuvla/*stripe-api-key* "123" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "active"})] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer is trialing" (with-redefs [config-nuvla/*stripe-api-key* "123" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "trialing"})] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer past_due" (with-redefs [config-nuvla/*stripe-api-key* "123" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "past_due"})] (is (= (t/throw-when-payment-required {}) {})))))
49819
(ns sixsq.nuvla.server.resources.nuvlabox.utils-test (:require [clojure.test :refer [deftest is testing]] [sixsq.nuvla.auth.acl-resource :as a] [sixsq.nuvla.pricing.payment :as payment] [sixsq.nuvla.server.resources.configuration-nuvla :as config-nuvla] [sixsq.nuvla.server.resources.nuvlabox.utils :as t])) (deftest check-short-nb-id (is (nil? (t/short-nb-id nil))) (is (= "abc" (t/short-nb-id "nuvlabox/abc-def-ghi-jkl")))) (deftest check-has-pull-support? (is (false? (t/has-pull-support? {:capabilities []}))) (is (false? (t/has-pull-support? {}))) (is (false? (t/has-pull-support? {:capabilities ["ANYTHING"]}))) (is (t/has-pull-support? {:capabilities ["ANYTHING" "NUVLA_JOB_PULL"]}))) (deftest throw-when-payment-required (testing "stripe is disabled" (with-redefs [config-nuvla/*stripe-api-key* nil a/is-admin? (constantly false)] (is (= (t/throw-when-payment-required {}) {})))) (testing "is admin" (with-redefs [config-nuvla/*stripe-api-key* "<KEY>" a/is-admin? (constantly true)] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer is active" (with-redefs [config-nuvla/*stripe-api-key* "<KEY>" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "active"})] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer is trialing" (with-redefs [config-nuvla/*stripe-api-key* "<KEY>" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "trialing"})] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer past_due" (with-redefs [config-nuvla/*stripe-api-key* "<KEY>" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "past_due"})] (is (= (t/throw-when-payment-required {}) {})))))
true
(ns sixsq.nuvla.server.resources.nuvlabox.utils-test (:require [clojure.test :refer [deftest is testing]] [sixsq.nuvla.auth.acl-resource :as a] [sixsq.nuvla.pricing.payment :as payment] [sixsq.nuvla.server.resources.configuration-nuvla :as config-nuvla] [sixsq.nuvla.server.resources.nuvlabox.utils :as t])) (deftest check-short-nb-id (is (nil? (t/short-nb-id nil))) (is (= "abc" (t/short-nb-id "nuvlabox/abc-def-ghi-jkl")))) (deftest check-has-pull-support? (is (false? (t/has-pull-support? {:capabilities []}))) (is (false? (t/has-pull-support? {}))) (is (false? (t/has-pull-support? {:capabilities ["ANYTHING"]}))) (is (t/has-pull-support? {:capabilities ["ANYTHING" "NUVLA_JOB_PULL"]}))) (deftest throw-when-payment-required (testing "stripe is disabled" (with-redefs [config-nuvla/*stripe-api-key* nil a/is-admin? (constantly false)] (is (= (t/throw-when-payment-required {}) {})))) (testing "is admin" (with-redefs [config-nuvla/*stripe-api-key* "PI:KEY:<KEY>END_PI" a/is-admin? (constantly true)] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer is active" (with-redefs [config-nuvla/*stripe-api-key* "PI:KEY:<KEY>END_PI" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "active"})] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer is trialing" (with-redefs [config-nuvla/*stripe-api-key* "PI:KEY:<KEY>END_PI" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "trialing"})] (is (= (t/throw-when-payment-required {}) {})))) (testing "customer past_due" (with-redefs [config-nuvla/*stripe-api-key* "PI:KEY:<KEY>END_PI" a/is-admin? (constantly false) payment/active-claim->subscription (constantly {:status "past_due"})] (is (= (t/throw-when-payment-required {}) {})))))
[ { "context": ";;; SYNTH.CLJ\n;;; Mark Burger, August - October 2015\n;;;\n;;; To use, simply (lo", "end": 29, "score": 0.9998605251312256, "start": 18, "tag": "NAME", "value": "Mark Burger" }, { "context": ";;; SYNTH.CLJ\n;;; Mark Burger, August - October 2015\n;;;\n;;; To use, simply (load-file ", "end": 37, "score": 0.9391738772392273, "start": 31, "tag": "NAME", "value": "August" } ]
data/train/clojure/1569e5c6e602cf6b65b697c3987481d6038365a2Synth.clj
harshp8l/deep-learning-lang-detection
84
;;; SYNTH.CLJ ;;; Mark Burger, August - October 2015 ;;; ;;; To use, simply (load-file "../path/to/Synth.clj") ;;; ;;; API EXPLANATION-- ;;; ;;; (synth-init) ;;; Defines global variables and opens the synthesizer ;;; ;;; (channel <number>) ;;; returns a channel of the specified number, usually 0 through 15. ;;; Each channel can have its own instrument and notes. ;;; ;;; (change-instrument <channel> <instrument number>) ;;; Changes the instrument playing on the channel. For instrument numbers, ;;; use print-instruments. This assumes a default bank. By default in ;;; testing, instrument numbers go from 0 - 128. ;;; ;;; (change-instrument-with-bank <channel> <bank> <instrument number>) ;;; Sometimes, you'll need the entire range of instruments. That's ;;; accessible here. Bank/Program numbers are available from ;;; print-instruments. ;;; ;;; (print-instruments) ;;; Prints the number of an instrument beside its human-readable name. ;;; Most implementations only allow elements 1 through 127 of this list ;;; to get loaded into the synthesizer. ;;; ;;; (play-note <channel> <note> <intensity> <duration>) ;;; Play the selected note (see below) on the specified channel (use ;;; the channel function to retrieve a channel) for an intensity (0 - 255) ;;; over a certain (<duration>) number of milliseconds. ;;; ;;; (play-notes <channel> <music>) ;;; Play the array of music on a channel. <music> is a list of arrays, where ;;; each element of the array is four elements-- a note, its intensity, ;;; its duration (milliseconds), and the number of milliseconds to wait ;;; before playing the next note. ;;; ;;; (start-beat <function> <wait> <identifier>) ;;; Calls the <function>-- usually an (fn...) with some play-note or ;;; play-notes calls in it== every <wait> milliseconds. The identifier ;;; is a string that's used for turning on/off this beat timer sequence. ;;; Note that using this implementation, a beat can happen across multiple ;;; channels. ;;; ;;; (stop-beat <identifier>) ;;; A beat generated with (start-beat ...) with a provided identifier can ;;; be stopped with this function using the same identifier. ;;; ;;; (synth-shutdown) ;;; Stops any running beats and closes the synthesizer. ;;; ;;; ;;; THE NOTES-- ;;; ;;; Basically, MIDI notes begin at zero. Each increment in the number resembles ;;; moving right one key (including black keys) across a piano / synthesizer. ;;; ;;; 60 is C4 ;;; 61 - C4 # ;;; 62 - D4 ;;; 63 - D4 # ;;; 64 - E4 ;;; 65 - F4 ;;; 66 - F4 # ;;; 67 - G4 ;;; 68 - G4 # ;;; 69 - A4 ;;; 70 - A4 # ;;; 71 - B4 ;;; 72 - C5 ;;; ... etc ... ;;; ;;; Information is pretty easily findable with an image search, i.e. ;;; https://www.google.com/search?tbm=isch&q=midi+numbers ;;; (import '(javax.sound.midi MidiSystem) '(java.util HashMap) ) (def synth (MidiSystem/getSynthesizer)) (def instruments (.getAvailableInstruments synth)) (def beat-array (new HashMap)) (defn synth-init[] (.open synth) "Boom!" ) ; num, for most implementations should be 0 through 15. (defn channel[num] (nth (.getChannels synth) num) ) (defn change-instrument [chan instrument] (.programChange chan instrument) ) (defn change-instrument-with-bank [chan bank instrument] (.programChange chan bank instrument) ) (defn print-instruments[] (dotimes [i (count instruments)] (println (nth instruments i)) ) ) ; See what instruments are loaded with -- ; (map (fn [a] (.getName a)) instruments) ; (.loadInstrument synth (nth instruments 3)) (defn play-note[channel note intensity duration] (.start (new Thread (fn [] (.noteOn channel note intensity) (Thread/sleep duration) (.noteOff channel note) ))) ) ; Music is (list ; [note1 intensity1 duration1 pauseAfter1] ; [note2 intensity2 duration2 pauseAfter2] ... ) (defn play-notes [channel music] (dotimes [n (count music)] (let [q (nth music n)] (play-note channel (nth q 0) (nth q 1) (nth q 2)) (Thread/sleep (nth q 3)) ) ) ) (defn start-beat[f millis id] (.start (new Thread (fn [] (.put beat-array id true) (while (not (nil? (.get beat-array id))) (eval (list f)) (Thread/sleep millis) )))) ) (defn stop-beat[id] (.put beat-array id nil) ) (defn synth-shutdown[] (map (fn [k] (stop-beat k)) (.keySet beat-array)) (.close synth) )
30577
;;; SYNTH.CLJ ;;; <NAME>, <NAME> - October 2015 ;;; ;;; To use, simply (load-file "../path/to/Synth.clj") ;;; ;;; API EXPLANATION-- ;;; ;;; (synth-init) ;;; Defines global variables and opens the synthesizer ;;; ;;; (channel <number>) ;;; returns a channel of the specified number, usually 0 through 15. ;;; Each channel can have its own instrument and notes. ;;; ;;; (change-instrument <channel> <instrument number>) ;;; Changes the instrument playing on the channel. For instrument numbers, ;;; use print-instruments. This assumes a default bank. By default in ;;; testing, instrument numbers go from 0 - 128. ;;; ;;; (change-instrument-with-bank <channel> <bank> <instrument number>) ;;; Sometimes, you'll need the entire range of instruments. That's ;;; accessible here. Bank/Program numbers are available from ;;; print-instruments. ;;; ;;; (print-instruments) ;;; Prints the number of an instrument beside its human-readable name. ;;; Most implementations only allow elements 1 through 127 of this list ;;; to get loaded into the synthesizer. ;;; ;;; (play-note <channel> <note> <intensity> <duration>) ;;; Play the selected note (see below) on the specified channel (use ;;; the channel function to retrieve a channel) for an intensity (0 - 255) ;;; over a certain (<duration>) number of milliseconds. ;;; ;;; (play-notes <channel> <music>) ;;; Play the array of music on a channel. <music> is a list of arrays, where ;;; each element of the array is four elements-- a note, its intensity, ;;; its duration (milliseconds), and the number of milliseconds to wait ;;; before playing the next note. ;;; ;;; (start-beat <function> <wait> <identifier>) ;;; Calls the <function>-- usually an (fn...) with some play-note or ;;; play-notes calls in it== every <wait> milliseconds. The identifier ;;; is a string that's used for turning on/off this beat timer sequence. ;;; Note that using this implementation, a beat can happen across multiple ;;; channels. ;;; ;;; (stop-beat <identifier>) ;;; A beat generated with (start-beat ...) with a provided identifier can ;;; be stopped with this function using the same identifier. ;;; ;;; (synth-shutdown) ;;; Stops any running beats and closes the synthesizer. ;;; ;;; ;;; THE NOTES-- ;;; ;;; Basically, MIDI notes begin at zero. Each increment in the number resembles ;;; moving right one key (including black keys) across a piano / synthesizer. ;;; ;;; 60 is C4 ;;; 61 - C4 # ;;; 62 - D4 ;;; 63 - D4 # ;;; 64 - E4 ;;; 65 - F4 ;;; 66 - F4 # ;;; 67 - G4 ;;; 68 - G4 # ;;; 69 - A4 ;;; 70 - A4 # ;;; 71 - B4 ;;; 72 - C5 ;;; ... etc ... ;;; ;;; Information is pretty easily findable with an image search, i.e. ;;; https://www.google.com/search?tbm=isch&q=midi+numbers ;;; (import '(javax.sound.midi MidiSystem) '(java.util HashMap) ) (def synth (MidiSystem/getSynthesizer)) (def instruments (.getAvailableInstruments synth)) (def beat-array (new HashMap)) (defn synth-init[] (.open synth) "Boom!" ) ; num, for most implementations should be 0 through 15. (defn channel[num] (nth (.getChannels synth) num) ) (defn change-instrument [chan instrument] (.programChange chan instrument) ) (defn change-instrument-with-bank [chan bank instrument] (.programChange chan bank instrument) ) (defn print-instruments[] (dotimes [i (count instruments)] (println (nth instruments i)) ) ) ; See what instruments are loaded with -- ; (map (fn [a] (.getName a)) instruments) ; (.loadInstrument synth (nth instruments 3)) (defn play-note[channel note intensity duration] (.start (new Thread (fn [] (.noteOn channel note intensity) (Thread/sleep duration) (.noteOff channel note) ))) ) ; Music is (list ; [note1 intensity1 duration1 pauseAfter1] ; [note2 intensity2 duration2 pauseAfter2] ... ) (defn play-notes [channel music] (dotimes [n (count music)] (let [q (nth music n)] (play-note channel (nth q 0) (nth q 1) (nth q 2)) (Thread/sleep (nth q 3)) ) ) ) (defn start-beat[f millis id] (.start (new Thread (fn [] (.put beat-array id true) (while (not (nil? (.get beat-array id))) (eval (list f)) (Thread/sleep millis) )))) ) (defn stop-beat[id] (.put beat-array id nil) ) (defn synth-shutdown[] (map (fn [k] (stop-beat k)) (.keySet beat-array)) (.close synth) )
true
;;; SYNTH.CLJ ;;; PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI - October 2015 ;;; ;;; To use, simply (load-file "../path/to/Synth.clj") ;;; ;;; API EXPLANATION-- ;;; ;;; (synth-init) ;;; Defines global variables and opens the synthesizer ;;; ;;; (channel <number>) ;;; returns a channel of the specified number, usually 0 through 15. ;;; Each channel can have its own instrument and notes. ;;; ;;; (change-instrument <channel> <instrument number>) ;;; Changes the instrument playing on the channel. For instrument numbers, ;;; use print-instruments. This assumes a default bank. By default in ;;; testing, instrument numbers go from 0 - 128. ;;; ;;; (change-instrument-with-bank <channel> <bank> <instrument number>) ;;; Sometimes, you'll need the entire range of instruments. That's ;;; accessible here. Bank/Program numbers are available from ;;; print-instruments. ;;; ;;; (print-instruments) ;;; Prints the number of an instrument beside its human-readable name. ;;; Most implementations only allow elements 1 through 127 of this list ;;; to get loaded into the synthesizer. ;;; ;;; (play-note <channel> <note> <intensity> <duration>) ;;; Play the selected note (see below) on the specified channel (use ;;; the channel function to retrieve a channel) for an intensity (0 - 255) ;;; over a certain (<duration>) number of milliseconds. ;;; ;;; (play-notes <channel> <music>) ;;; Play the array of music on a channel. <music> is a list of arrays, where ;;; each element of the array is four elements-- a note, its intensity, ;;; its duration (milliseconds), and the number of milliseconds to wait ;;; before playing the next note. ;;; ;;; (start-beat <function> <wait> <identifier>) ;;; Calls the <function>-- usually an (fn...) with some play-note or ;;; play-notes calls in it== every <wait> milliseconds. The identifier ;;; is a string that's used for turning on/off this beat timer sequence. ;;; Note that using this implementation, a beat can happen across multiple ;;; channels. ;;; ;;; (stop-beat <identifier>) ;;; A beat generated with (start-beat ...) with a provided identifier can ;;; be stopped with this function using the same identifier. ;;; ;;; (synth-shutdown) ;;; Stops any running beats and closes the synthesizer. ;;; ;;; ;;; THE NOTES-- ;;; ;;; Basically, MIDI notes begin at zero. Each increment in the number resembles ;;; moving right one key (including black keys) across a piano / synthesizer. ;;; ;;; 60 is C4 ;;; 61 - C4 # ;;; 62 - D4 ;;; 63 - D4 # ;;; 64 - E4 ;;; 65 - F4 ;;; 66 - F4 # ;;; 67 - G4 ;;; 68 - G4 # ;;; 69 - A4 ;;; 70 - A4 # ;;; 71 - B4 ;;; 72 - C5 ;;; ... etc ... ;;; ;;; Information is pretty easily findable with an image search, i.e. ;;; https://www.google.com/search?tbm=isch&q=midi+numbers ;;; (import '(javax.sound.midi MidiSystem) '(java.util HashMap) ) (def synth (MidiSystem/getSynthesizer)) (def instruments (.getAvailableInstruments synth)) (def beat-array (new HashMap)) (defn synth-init[] (.open synth) "Boom!" ) ; num, for most implementations should be 0 through 15. (defn channel[num] (nth (.getChannels synth) num) ) (defn change-instrument [chan instrument] (.programChange chan instrument) ) (defn change-instrument-with-bank [chan bank instrument] (.programChange chan bank instrument) ) (defn print-instruments[] (dotimes [i (count instruments)] (println (nth instruments i)) ) ) ; See what instruments are loaded with -- ; (map (fn [a] (.getName a)) instruments) ; (.loadInstrument synth (nth instruments 3)) (defn play-note[channel note intensity duration] (.start (new Thread (fn [] (.noteOn channel note intensity) (Thread/sleep duration) (.noteOff channel note) ))) ) ; Music is (list ; [note1 intensity1 duration1 pauseAfter1] ; [note2 intensity2 duration2 pauseAfter2] ... ) (defn play-notes [channel music] (dotimes [n (count music)] (let [q (nth music n)] (play-note channel (nth q 0) (nth q 1) (nth q 2)) (Thread/sleep (nth q 3)) ) ) ) (defn start-beat[f millis id] (.start (new Thread (fn [] (.put beat-array id true) (while (not (nil? (.get beat-array id))) (eval (list f)) (Thread/sleep millis) )))) ) (defn stop-beat[id] (.put beat-array id nil) ) (defn synth-shutdown[] (map (fn [k] (stop-beat k)) (.keySet beat-array)) (.close synth) )
[ { "context": "is is a test\" \"Das is ein test\",\n \"|Hi, {name}\" \"Hallo, {name}\",\n \"|N: {n, number} ({m, date, long})\"\n ", "end": 226, "score": 0.975603461265564, "start": 221, "tag": "NAME", "value": "Hallo" } ]
src/devguide/app/i18n/de.cljs
goodbobk/untangled
1
(ns app.i18n.de (:require untangled.i18n) (:import goog.module.ModuleManager)) ;; This file was generated by untangled's i18n leiningen plugin. (def translations {"|This is a test" "Das is ein test", "|Hi, {name}" "Hallo, {name}", "|N: {n, number} ({m, date, long})" "N: {n, number} ({m, date, long})"}) (swap! untangled.i18n/*loaded-translations* (fn [x] (assoc x "de" translations))) (try (-> goog.module.ModuleManager .getInstance (.setLoaded "de")) (catch js/Object e))
43864
(ns app.i18n.de (:require untangled.i18n) (:import goog.module.ModuleManager)) ;; This file was generated by untangled's i18n leiningen plugin. (def translations {"|This is a test" "Das is ein test", "|Hi, {name}" "<NAME>, {name}", "|N: {n, number} ({m, date, long})" "N: {n, number} ({m, date, long})"}) (swap! untangled.i18n/*loaded-translations* (fn [x] (assoc x "de" translations))) (try (-> goog.module.ModuleManager .getInstance (.setLoaded "de")) (catch js/Object e))
true
(ns app.i18n.de (:require untangled.i18n) (:import goog.module.ModuleManager)) ;; This file was generated by untangled's i18n leiningen plugin. (def translations {"|This is a test" "Das is ein test", "|Hi, {name}" "PI:NAME:<NAME>END_PI, {name}", "|N: {n, number} ({m, date, long})" "N: {n, number} ({m, date, long})"}) (swap! untangled.i18n/*loaded-translations* (fn [x] (assoc x "de" translations))) (try (-> goog.module.ModuleManager .getInstance (.setLoaded "de")) (catch js/Object e))
[ { "context": "urpose: general utilitis\n;;;; Author: mikel evins\n;;;; Copyright: Copyright 2009 by mikel evins", "end": 236, "score": 0.9998786449432373, "start": 225, "tag": "NAME", "value": "mikel evins" }, { "context": " mikel evins\n;;;; Copyright: Copyright 2009 by mikel evins, all rights reserved\n;;;; License: Licensed", "end": 286, "score": 0.9998680949211121, "start": 275, "tag": "NAME", "value": "mikel evins" } ]
0.2.1/clj/build/classes/xg/categories/utils.clj
mikelevins/categories
5
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: utils.clj ;;;; Project: Categories ;;;; Purpose: general utilitis ;;;; Author: mikel evins ;;;; Copyright: Copyright 2009 by mikel evins, all rights reserved ;;;; License: Licensed under the Apache License, version 2.0 ;;;; See the accompanying file "License" for more information ;;;; ;;;; *********************************************************************** (ns xg.categories.utils) (defn str-or-nil [x] (if (nil? x) "nil" (str x))) (defn error [msg & args] (throw (Exception. (apply (partial format msg) (map str-or-nil args))))) (defn plist->map [plist] (loop [pl plist acc {}] (if (empty? pl) acc (let [k (first pl) more (rest pl)] (if (contains? acc k) (error "Duplicate key in property-list: %s" k) (if (empty? more) (error "Malformed property-list: %s" plist) (let [v (first more) remainder (rest more)] (recur remainder (merge acc {k v}))))))))) (defn member [item seq](some (fn [s] (= item s)) seq))
101356
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: utils.clj ;;;; Project: Categories ;;;; Purpose: general utilitis ;;;; Author: <NAME> ;;;; Copyright: Copyright 2009 by <NAME>, all rights reserved ;;;; License: Licensed under the Apache License, version 2.0 ;;;; See the accompanying file "License" for more information ;;;; ;;;; *********************************************************************** (ns xg.categories.utils) (defn str-or-nil [x] (if (nil? x) "nil" (str x))) (defn error [msg & args] (throw (Exception. (apply (partial format msg) (map str-or-nil args))))) (defn plist->map [plist] (loop [pl plist acc {}] (if (empty? pl) acc (let [k (first pl) more (rest pl)] (if (contains? acc k) (error "Duplicate key in property-list: %s" k) (if (empty? more) (error "Malformed property-list: %s" plist) (let [v (first more) remainder (rest more)] (recur remainder (merge acc {k v}))))))))) (defn member [item seq](some (fn [s] (= item s)) seq))
true
;;;; *********************************************************************** ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: utils.clj ;;;; Project: Categories ;;;; Purpose: general utilitis ;;;; Author: PI:NAME:<NAME>END_PI ;;;; Copyright: Copyright 2009 by PI:NAME:<NAME>END_PI, all rights reserved ;;;; License: Licensed under the Apache License, version 2.0 ;;;; See the accompanying file "License" for more information ;;;; ;;;; *********************************************************************** (ns xg.categories.utils) (defn str-or-nil [x] (if (nil? x) "nil" (str x))) (defn error [msg & args] (throw (Exception. (apply (partial format msg) (map str-or-nil args))))) (defn plist->map [plist] (loop [pl plist acc {}] (if (empty? pl) acc (let [k (first pl) more (rest pl)] (if (contains? acc k) (error "Duplicate key in property-list: %s" k) (if (empty? more) (error "Malformed property-list: %s" plist) (let [v (first more) remainder (rest more)] (recur remainder (merge acc {k v}))))))))) (defn member [item seq](some (fn [s] (= item s)) seq))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-07-06\"\n :doc \"Profile spikes fu", "end": 105, "score": 0.999871551990509, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/scripts/clojure/taiga/scripts/profile/spikes.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-07-06" :doc "Profile spikes function probability forest example." } taiga.scripts.profile.spikes (:require [clojure.test :as test] [taiga.test.classify.spikes.majority-vote-probability] [taiga.test.classify.spikes.positive-fraction-probability])) ;;------------------------------------------------------------------------------ (test/run-tests 'taiga.test.classify.spikes.majority-vote-probability) (test/run-tests 'taiga.test.classify.spikes.positive-fraction-probability) ;;------------------------------------------------------------------------------
36649
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-07-06" :doc "Profile spikes function probability forest example." } taiga.scripts.profile.spikes (:require [clojure.test :as test] [taiga.test.classify.spikes.majority-vote-probability] [taiga.test.classify.spikes.positive-fraction-probability])) ;;------------------------------------------------------------------------------ (test/run-tests 'taiga.test.classify.spikes.majority-vote-probability) (test/run-tests 'taiga.test.classify.spikes.positive-fraction-probability) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-07-06" :doc "Profile spikes function probability forest example." } taiga.scripts.profile.spikes (:require [clojure.test :as test] [taiga.test.classify.spikes.majority-vote-probability] [taiga.test.classify.spikes.positive-fraction-probability])) ;;------------------------------------------------------------------------------ (test/run-tests 'taiga.test.classify.spikes.majority-vote-probability) (test/run-tests 'taiga.test.classify.spikes.positive-fraction-probability) ;;------------------------------------------------------------------------------
[ { "context": " 2008\n :produced-by \"Jim Morris\",\n :production-company \"Pixar Animat", "end": 406, "score": 0.9998927712440491, "start": 396, "tag": "NAME", "value": "Jim Morris" }, { "context": "uces a NEW map\n (println (assoc walle :editor \"Stephen Schaffer\"))\n (println walle)\n\n ; the dissoc function", "end": 1369, "score": 0.9995752573013306, "start": 1353, "tag": "NAME", "value": "Stephen Schaffer" }, { "context": "emo\"\n :produced-by \"Graham Walters\"\n :year 2003", "end": 1630, "score": 0.9998863339424133, "start": 1616, "tag": "NAME", "value": "Graham Walters" }, { "context": "ing\"\n :produced-by \"Don Hahn\"\n :year 1994", "end": 2020, "score": 0.9998772740364075, "start": 2012, "tag": "NAME", "value": "Don Hahn" } ]
Clojure/maps/src/maps/core.clj
rithsuon/LecturesHW
3
(ns maps.core (:gen-class)) (defn -main [& args] ; a map is a dictionary: a data structure that associates a key with a value. ; {} creates a map; adjacent values in the map declare a key-value pair. (let [walle {:title "WALL-E", ; the commas are optional but can aid readability. :year 2008 :produced-by "Jim Morris", :production-company "Pixar Animation Studios", :budget 180000000, :earnings 521300000, :running-time 98}] ; a : in front of an identifier creates a "keyword". think of these as strings for now. (println walle) ; we can retrieve a value from a map using the get function ; (get *map* *key*) (println (get walle :title)) ; println is like println, except it prints formatted in the same way the value ; would be formatted in code, so strings print with surrounding "" ; keywords are like strings, but can be used as a function as well. ; (:keyword *map*) is the same as (get *map* :keyword) (println (:produced-by walle)) ; the assoc function can associate a new key into a map, or override an old one. ; maps are immutable, however... so this operation produces a NEW map (println (assoc walle :editor "Stephen Schaffer")) (println walle) ; the dissoc function can likewise remove a key. (println (dissoc walle :year)) (let [disney (list walle {:title "Finding Nemo" :produced-by "Graham Walters" :year 2003 :production-company "Pixar Animation Studios" :budget 94000000 :earnings 936700000 :running-time 100} {:title "The Lion King" :produced-by "Don Hahn" :year 1994 :production-company "Walt Disney Feature Animation" :budget 45000000 :earnings 987500000 :running-time 88})] ; we can use map, filter, and reduce with maps (println (filter #(>= (:running-time %) 90) disney)) ; all movies that ran at least 90 minutes (println (map :title disney)) ; remember, keywords are functions. (println (map #(get % :title) disney)) (println (map #(double (/ (:earnings %) (:budget %))) disney)) ; earnings to budget ratios (println (reduce + 0 (map :earnings disney))) ; sum of all earnings ; other useful things ; (sort-by *key-fn* comp coll) ; sorts the collection by comparing the result of (key-fn item) for each item ; in the collection. Uses comp to decide the ordering (<, >). (println (sort-by :budget < disney)) ; sort the films by budget, decreasing order ; challenge: return only the titles of the movies, sorted in decreasing order by earnings (println (map :title (sort-by :earning > disney))) ; challenge: return only the titles of PIXAR movies, sorted in increasing order by budget (println (map :title (sort-by :budget < (filter #(= "Pixar Animation Studios" (:production-company %)) disney)))) ) ) )
105109
(ns maps.core (:gen-class)) (defn -main [& args] ; a map is a dictionary: a data structure that associates a key with a value. ; {} creates a map; adjacent values in the map declare a key-value pair. (let [walle {:title "WALL-E", ; the commas are optional but can aid readability. :year 2008 :produced-by "<NAME>", :production-company "Pixar Animation Studios", :budget 180000000, :earnings 521300000, :running-time 98}] ; a : in front of an identifier creates a "keyword". think of these as strings for now. (println walle) ; we can retrieve a value from a map using the get function ; (get *map* *key*) (println (get walle :title)) ; println is like println, except it prints formatted in the same way the value ; would be formatted in code, so strings print with surrounding "" ; keywords are like strings, but can be used as a function as well. ; (:keyword *map*) is the same as (get *map* :keyword) (println (:produced-by walle)) ; the assoc function can associate a new key into a map, or override an old one. ; maps are immutable, however... so this operation produces a NEW map (println (assoc walle :editor "<NAME>")) (println walle) ; the dissoc function can likewise remove a key. (println (dissoc walle :year)) (let [disney (list walle {:title "Finding Nemo" :produced-by "<NAME>" :year 2003 :production-company "Pixar Animation Studios" :budget 94000000 :earnings 936700000 :running-time 100} {:title "The Lion King" :produced-by "<NAME>" :year 1994 :production-company "Walt Disney Feature Animation" :budget 45000000 :earnings 987500000 :running-time 88})] ; we can use map, filter, and reduce with maps (println (filter #(>= (:running-time %) 90) disney)) ; all movies that ran at least 90 minutes (println (map :title disney)) ; remember, keywords are functions. (println (map #(get % :title) disney)) (println (map #(double (/ (:earnings %) (:budget %))) disney)) ; earnings to budget ratios (println (reduce + 0 (map :earnings disney))) ; sum of all earnings ; other useful things ; (sort-by *key-fn* comp coll) ; sorts the collection by comparing the result of (key-fn item) for each item ; in the collection. Uses comp to decide the ordering (<, >). (println (sort-by :budget < disney)) ; sort the films by budget, decreasing order ; challenge: return only the titles of the movies, sorted in decreasing order by earnings (println (map :title (sort-by :earning > disney))) ; challenge: return only the titles of PIXAR movies, sorted in increasing order by budget (println (map :title (sort-by :budget < (filter #(= "Pixar Animation Studios" (:production-company %)) disney)))) ) ) )
true
(ns maps.core (:gen-class)) (defn -main [& args] ; a map is a dictionary: a data structure that associates a key with a value. ; {} creates a map; adjacent values in the map declare a key-value pair. (let [walle {:title "WALL-E", ; the commas are optional but can aid readability. :year 2008 :produced-by "PI:NAME:<NAME>END_PI", :production-company "Pixar Animation Studios", :budget 180000000, :earnings 521300000, :running-time 98}] ; a : in front of an identifier creates a "keyword". think of these as strings for now. (println walle) ; we can retrieve a value from a map using the get function ; (get *map* *key*) (println (get walle :title)) ; println is like println, except it prints formatted in the same way the value ; would be formatted in code, so strings print with surrounding "" ; keywords are like strings, but can be used as a function as well. ; (:keyword *map*) is the same as (get *map* :keyword) (println (:produced-by walle)) ; the assoc function can associate a new key into a map, or override an old one. ; maps are immutable, however... so this operation produces a NEW map (println (assoc walle :editor "PI:NAME:<NAME>END_PI")) (println walle) ; the dissoc function can likewise remove a key. (println (dissoc walle :year)) (let [disney (list walle {:title "Finding Nemo" :produced-by "PI:NAME:<NAME>END_PI" :year 2003 :production-company "Pixar Animation Studios" :budget 94000000 :earnings 936700000 :running-time 100} {:title "The Lion King" :produced-by "PI:NAME:<NAME>END_PI" :year 1994 :production-company "Walt Disney Feature Animation" :budget 45000000 :earnings 987500000 :running-time 88})] ; we can use map, filter, and reduce with maps (println (filter #(>= (:running-time %) 90) disney)) ; all movies that ran at least 90 minutes (println (map :title disney)) ; remember, keywords are functions. (println (map #(get % :title) disney)) (println (map #(double (/ (:earnings %) (:budget %))) disney)) ; earnings to budget ratios (println (reduce + 0 (map :earnings disney))) ; sum of all earnings ; other useful things ; (sort-by *key-fn* comp coll) ; sorts the collection by comparing the result of (key-fn item) for each item ; in the collection. Uses comp to decide the ordering (<, >). (println (sort-by :budget < disney)) ; sort the films by budget, decreasing order ; challenge: return only the titles of the movies, sorted in decreasing order by earnings (println (map :title (sort-by :earning > disney))) ; challenge: return only the titles of PIXAR movies, sorted in increasing order by budget (println (map :title (sort-by :budget < (filter #(= "Pixar Animation Studios" (:production-company %)) disney)))) ) ) )
[ { "context": " https://adventofcode.com/2020/day/5\n;; author: Vitor SRG (vitorssrg@gmail.com)\n;; date: 2021-01-02\n;;", "end": 225, "score": 0.9998776912689209, "start": 216, "tag": "NAME", "value": "Vitor SRG" }, { "context": "entofcode.com/2020/day/5\n;; author: Vitor SRG (vitorssrg@gmail.com)\n;; date: 2021-01-02\n;; execution: $ bash ./", "end": 246, "score": 0.999930202960968, "start": 227, "tag": "EMAIL", "value": "vitorssrg@gmail.com" } ]
aoc2020/d05/main.clj
vitorsrg/advent-of-code
0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; domain: Advent of Code 2020 ;; challenge: Day 5: Binary Boarding ;; url: https://adventofcode.com/2020/day/5 ;; author: Vitor SRG (vitorssrg@gmail.com) ;; date: 2021-01-02 ;; execution: $ bash ./aoc2020/run.sh d05 < [INPUT_FILE] ;; example: ;; $ bash ./aoc2020/run.sh d05 < ./aoc2020/d05/input.txt ;; part 1 864 ;; part 2 739 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns d05.main) (defn replace-several [content & replacements] (let [replacement-list (partition 2 replacements)] (reduce #(apply clojure.string/replace %1 %2) content replacement-list))) (defn parse-seat [seat-code] (let [[seat-code row-code col-code] (re-find #"([FB]{7})([LR]{3})" seat-code) row-bincode (replace-several row-code "F" "0" "B" "1") col-bincode (replace-several col-code "L" "0" "R" "1") row-number (Integer/parseInt row-bincode 2) col-number (Integer/parseInt col-bincode 2) seat-id (+ (* row-number 8) col-number)] {:seat-code seat-code, ;; :row-code row-code, ;; :col-code col-code, ;; :row-bincode row-bincode, ;; :col-bincode col-bincode, :row-number row-number, :col-number col-number, :seat-id seat-id})) (defn -main [& args] (let [seats (->> *in* (slurp) (clojure.string/split-lines) (map parse-seat) (vec))] ;; (run! println (map parse-seat ["BFFFBBFRRR" "FFFBBBFRRR" "BBFFBBFRLL"])) ;; part 1 (let [max-seat-id (apply max (map :seat-id seats))] (println "part 1" max-seat-id)) ;; part 2 (let [seat-ids-sorted (vec (sort (map :seat-id seats))) missing-seat-id (first (for [i (range (- (count seat-ids-sorted) 1)) :let [seat-id (seat-ids-sorted i) next-seat-id (seat-ids-sorted (+ i 1))] :when (= next-seat-id (+ seat-id 2))] (+ seat-id 1)))] (println "part 2" missing-seat-id))))
109222
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; domain: Advent of Code 2020 ;; challenge: Day 5: Binary Boarding ;; url: https://adventofcode.com/2020/day/5 ;; author: <NAME> (<EMAIL>) ;; date: 2021-01-02 ;; execution: $ bash ./aoc2020/run.sh d05 < [INPUT_FILE] ;; example: ;; $ bash ./aoc2020/run.sh d05 < ./aoc2020/d05/input.txt ;; part 1 864 ;; part 2 739 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns d05.main) (defn replace-several [content & replacements] (let [replacement-list (partition 2 replacements)] (reduce #(apply clojure.string/replace %1 %2) content replacement-list))) (defn parse-seat [seat-code] (let [[seat-code row-code col-code] (re-find #"([FB]{7})([LR]{3})" seat-code) row-bincode (replace-several row-code "F" "0" "B" "1") col-bincode (replace-several col-code "L" "0" "R" "1") row-number (Integer/parseInt row-bincode 2) col-number (Integer/parseInt col-bincode 2) seat-id (+ (* row-number 8) col-number)] {:seat-code seat-code, ;; :row-code row-code, ;; :col-code col-code, ;; :row-bincode row-bincode, ;; :col-bincode col-bincode, :row-number row-number, :col-number col-number, :seat-id seat-id})) (defn -main [& args] (let [seats (->> *in* (slurp) (clojure.string/split-lines) (map parse-seat) (vec))] ;; (run! println (map parse-seat ["BFFFBBFRRR" "FFFBBBFRRR" "BBFFBBFRLL"])) ;; part 1 (let [max-seat-id (apply max (map :seat-id seats))] (println "part 1" max-seat-id)) ;; part 2 (let [seat-ids-sorted (vec (sort (map :seat-id seats))) missing-seat-id (first (for [i (range (- (count seat-ids-sorted) 1)) :let [seat-id (seat-ids-sorted i) next-seat-id (seat-ids-sorted (+ i 1))] :when (= next-seat-id (+ seat-id 2))] (+ seat-id 1)))] (println "part 2" missing-seat-id))))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; domain: Advent of Code 2020 ;; challenge: Day 5: Binary Boarding ;; url: https://adventofcode.com/2020/day/5 ;; author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ;; date: 2021-01-02 ;; execution: $ bash ./aoc2020/run.sh d05 < [INPUT_FILE] ;; example: ;; $ bash ./aoc2020/run.sh d05 < ./aoc2020/d05/input.txt ;; part 1 864 ;; part 2 739 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns d05.main) (defn replace-several [content & replacements] (let [replacement-list (partition 2 replacements)] (reduce #(apply clojure.string/replace %1 %2) content replacement-list))) (defn parse-seat [seat-code] (let [[seat-code row-code col-code] (re-find #"([FB]{7})([LR]{3})" seat-code) row-bincode (replace-several row-code "F" "0" "B" "1") col-bincode (replace-several col-code "L" "0" "R" "1") row-number (Integer/parseInt row-bincode 2) col-number (Integer/parseInt col-bincode 2) seat-id (+ (* row-number 8) col-number)] {:seat-code seat-code, ;; :row-code row-code, ;; :col-code col-code, ;; :row-bincode row-bincode, ;; :col-bincode col-bincode, :row-number row-number, :col-number col-number, :seat-id seat-id})) (defn -main [& args] (let [seats (->> *in* (slurp) (clojure.string/split-lines) (map parse-seat) (vec))] ;; (run! println (map parse-seat ["BFFFBBFRRR" "FFFBBBFRRR" "BBFFBBFRLL"])) ;; part 1 (let [max-seat-id (apply max (map :seat-id seats))] (println "part 1" max-seat-id)) ;; part 2 (let [seat-ids-sorted (vec (sort (map :seat-id seats))) missing-seat-id (first (for [i (range (- (count seat-ids-sorted) 1)) :let [seat-id (seat-ids-sorted i) next-seat-id (seat-ids-sorted (+ i 1))] :when (= next-seat-id (+ seat-id 2))] (+ seat-id 1)))] (println "part 2" missing-seat-id))))
[ { "context": " user interface.\n;; Copyright 2011-2013, Vixu.com, F.M. (Filip) de Waard <fmw@vixu.com>.\n;;\n;; Licensed under the Apache L", "end": 125, "score": 0.9865292906761169, "start": 104, "tag": "NAME", "value": "F.M. (Filip) de Waard" }, { "context": "right 2011-2013, Vixu.com, F.M. (Filip) de Waard <fmw@vixu.com>.\n;;\n;; Licensed under the Apache License, Versio", "end": 139, "score": 0.9999334216117859, "start": 127, "tag": "EMAIL", "value": "fmw@vixu.com" } ]
src/cljs/src/ui.cljs
fmw/vix
22
;; cljs/src/ui.cljs: utility functions related to the user interface. ;; Copyright 2011-2013, Vixu.com, F.M. (Filip) de Waard <fmw@vixu.com>. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns vix.ui (:use-macros [vix.crossover.macros :only [get-snippets]]) (:use [domina.css :only [sel]] [domina.xpath :only [xpath]]) (:require [vix.util :as util] [domina :as domina] [clojure.string :as string] [goog.dom :as dom] [goog.dom.forms :as forms] [goog.dom.classes :as classes] [goog.ui.Dialog :as goog.ui.Dialog] [goog.ui.Dialog.ButtonSet :as goog.ui.Dialog.ButtonSet] [goog.ui.Dialog.EventType :as goog.ui.Dialog.EventType] [goog.ui.DatePicker :as DatePicker] [goog.ui.DatePicker.Events :as DatePickerEvents] [goog.events :as events] [goog.fx.DragDrop :as goog.fx.DragDrop] [goog.fx.DragDropGroup :as goog.fx.DragDropGroup] ;; [goog.fx.dom :as fx-dom] ;; [goog.fx.Animation :as Animation] ;; [goog.fx.Animation.EventType :as transition-event] ;; [goog.Timer :as timer] )) (def snippets "Map with the HTML snippets generated by the get-snippets macro, e.g. {:feed/:add-feed-button \"<button ...>\" ...}." (get-snippets)) (defn clear-page! "Removes all child-nodes of the div#main-page node, effectively clearing the page." [] (domina/destroy-children! (xpath "//div[@id='main-page']"))) (defn- execute-show! "Performs the action grunt work for the show! fn, apart from clearing the page, see its docstring for more information." [& all-actions] (loop [actions (flatten all-actions)] (when (not-empty actions) (let [{:keys [parent snippet transformations children] :as action} (first actions)] (domina/append! (xpath (or parent "//div[@id='main-page']")) (snippets snippet)) (doall ;; execute transformations (map (fn [{:keys [selector text attrs remove-attr add-class remove-class value checked]}] (let [node (xpath selector)] (when text (domina/set-text! node text)) (when attrs (domina/set-attrs! node attrs)) (when remove-attr (domina/remove-attr! node remove-attr)) (when add-class (domina/add-class! node add-class)) (when remove-class (domina/remove-class! node remove-class)) (when value (domina/set-value! node value)) (when (not (nil? checked)) (if checked (domina/set-attr! (domina/single-node node) :checked "checked") (domina/remove-attr! (domina/single-node node) :checked))))) transformations)) (when (not-empty children) (apply execute-show! children)) (recur (rest actions)))))) (defn show! "Clears the page and executes the provided actions. Accepts any number of arguments, each being an action map. Every action should at least contain a :snippet key that is mapped to a HTML string to insert. The action may contain a :parent key, that maps to a string containing an xpath selector for a parent element to place the newly created element in. Without a :parent value, the div#main-page element is used as a parent element by default. The action may also contain a :transformations key that maps to a sequence of transformations to perform after the snippet is added to the DOM. Each transformation is a map with a :selector key mapped to a string with an xpath selector for the node to transform, as well as a :text, :attrs, :remove-attr :value or :checked key (or multiple) containing the new text content for the node, an attribute map, a keyword of an attribute to remove, form field value or boolean respectively. The action map may also contain an optional :children key, which maps to a sequence of actions that will be recursively executed after the current action is added to the DOM and its transformations are completed (i.e. with nesting). See the views/feed and views/editor namespaces for example usage." [& all-actions] (clear-page!) (apply execute-show! all-actions)) (defn set-form-value [el-id-or-obj value] (let [el (util/get-element el-id-or-obj)] (forms/setValue el value))) (defn get-form-value [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (forms/getValue el))) (defn is-checked? "Accepts a checkbox element or element ID and returns true if checked." [el-id-or-obj] (= "on" (get-form-value el-id-or-obj))) (defn get-form-value-by-name [form-el-id-or-obj name] (let [form (util/get-element form-el-id-or-obj)] (forms/getValueByName form name))) (defn get-form-values "Returns a map containing the values for all form elements within the given form-el. Keys are element names converted to keywords. Values are either strings or a vector of strings if the form element has multiple values." [form-el] (let [form-data (forms/getFormDataMap (util/get-element form-el))] (zipmap (map keyword (. form-data (getKeys))) (map (fn [value] (if (> (count value) 1) (vec value) (first value))) (. form-data (getValues)))))) (defn button-to-obj [button] (util/map-to-obj {:key (name button) :caption (if (= button :ok) "OK" (string/capitalize (name button)))})) (defn button-set [& buttons] (let [button-set (new goog.ui.Dialog.ButtonSet)] (doseq [button buttons] (doto button-set (.addButton (button-to-obj button) (= button (first buttons)) (= button :cancel)))) button-set)) (defn display-dialog! "Displays a goog.ui.Dialog with given title and the HTML content from the provided content string. When the dialog is closed the dialog is removed and the provided callback function is called with the dialog result (:ok or :cancel) as the first argument and a map with the form data from the provided form-el HTML form node as the second argument." ([title content form-el options callback] (display-dialog! title content form-el options callback :ok :cancel)) ([title content form-el {:keys [modal? auto-close?]} callback & buttons] (let [dialog (new goog.ui.Dialog)] (events/listen dialog goog.ui.Dialog.EventType/SELECT (fn [evt] (. evt (preventDefault)) (. evt (stopPropagation)) (let [button (keyword (.-key evt))] (callback button (when form-el (get-form-values form-el))) (when (or auto-close? (= :cancel button)) (remove-dialog!))))) (doto dialog (.setModal modal?) (.setTitle title) (.setContent content) (.setButtonSet (apply button-set buttons)) (.setVisible true))))) (defn remove-dialog! "Removes any goog.ui.Dialog elements from the DOM." [] (domina/destroy! (domina/by-class "modal-dialog")) (domina/destroy! (domina/by-class "modal-dialog-bg"))) (defn display-datepicker "Displays a date picker in a dialog and passes a goog.date.Date object (or nil if no date is selected) to the success-handler function if the user confirms the selection. If the include-time? argument is true two arguments are added to the success-handler fn: hour and minute (both strings)." [success-handler include-time?] (let [dp (goog.ui.DatePicker.)] (display-dialog "Pick a date" (str (:ui/date-widget snippets) (when include-time? (:ui/datepicker-time-row snippets))) (fn [evt] (when (= "ok" (.-key evt)) (let [date-obj (. dp (getDate))] (success-handler {:date-object date-obj :date-string (.toIsoString date-obj true) :hour (get-form-value "hour") :minute (get-form-value "minute")})) (. dp (dispose))) (remove-dialog))) (.decorate dp (dom/getElement "date-widget")))) (defn add-or-remove-errors "Displays or removes error, using status-el and active-el, based on the provided validation-result (either :pass or a map with its :error key mapped to the particular error and its :message key to the human-readable error message that is to be displayed in status-el." [status-el active-el validation-result] (if (= validation-result :pass) (remove-error status-el active-el) (display-error status-el (:message validation-result) active-el))) (defn display-error "Adds the class 'error' to the provided status-el, sets its text content to the given message and also adds the 'error' class to the other-elements provided as optional further arguments. Returns nil." [status-el message & other-elements] (doseq [el other-elements] (domina/add-class! el "error")) (doto status-el (domina/remove-class! "status-ok") (domina/remove-class! "hide") (domina/add-class! "status-error") (domina/add-class! "error") (domina/set-text! message)) nil) (defn remove-error "Removes the classes 'error' and 'status-error' from the given status-el, sets the text content of the status-el to an empty string and removes the 'error' class from any other-elements provided as optional further arguments. Returns nil." [status-el & other-elements] (doseq [el other-elements] (domina/remove-class! el "error")) (doto status-el (domina/remove-class! "status-error") (domina/remove-class! "error") (domina/set-text! "")) nil) (defn enable-element [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (doto el (classes/remove "disabled") (.removeAttribute "disabled")))) (defn disable-element [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (doto el (classes/add "disabled") (.setAttribute "disabled" "disabled")))) (defn trigger-on-class [class trigger-on f] ;; converting to vector to avoid issues with doseq and arrays (doseq [el (cljs.core.Vector/fromArray (dom/getElementsByClass class))] (events/listen el trigger-on f))) (defn remove-class-from-elements [class elements] (doseq [el elements] (classes/remove el class))) (defn not-fixed? [el] (not (classes/has el "fixed"))) (def active-el (atom nil)) (defn get-draggable-item "Returns the actual draggable item starting from a (possibly nested) event target element and going up the tree recursively (up to 5 times). The event's target object refers to the element that was clicked on, which might be a nested node (e.g. a span or a element inside the li node that is the intended draggable item)." [el] (loop [current-el el times-called 0] (if (and (= (.-tagName current-el) "LI") (.hasAttribute current-el "draggable")) (cond (= (.-draggable current-el) false) (if (classes/has current-el "drop-on-grandparent") (util/get-parent (util/get-parent current-el)) nil) (= (.-draggable current-el) true) current-el) (if (<= times-called 5) (recur (util/get-parent current-el) (inc times-called)) nil)))) (defn node-contains? "Checks if the element passed as the first argument contains the element passed at the second argument." [x y] (when (and x y) (dom/contains x y))) (defn can-add-to-nested-ul? [el-dragged el-dropped-on] (not (or (node-contains? el-dragged el-dropped-on) (node-contains? el-dropped-on el-dragged)))) (defn get-item-details-el [el] (first (util/get-children-by-class el "item-details"))) (defn remove-highlight-from-add-link-elements [elements] (doseq [add-link-el elements] (when (classes/has add-link-el "highlight-add-link-el") (classes/remove add-link-el "highlight-add-link-el") (set! (.-textContent add-link-el) (. (.-textContent add-link-el) (substr 2)))))) (defn clean-drop-data "Removes META elements from provided html string and returns innerHTML string. This is necessary because some versions of Chrome append a meta tag to the drop data." [html] (let [unclean-dummy-el (dom/createElement "div") clean-dummy-el (dom/createElement "div")] (set! (.-innerHTML unclean-dummy-el) html) (doseq [non-meta-child (filter #(not (= (.-tagName %) "META")) (util/get-children unclean-dummy-el))] (dom/appendChild clean-dummy-el non-meta-child)) (.-innerHTML clean-dummy-el))) (defn to-sortable-tree [parent-el after-drop-fn] (let [top-level-drop-zone-el (dom/getElement "menu-top-level-drop-zone") li-elements (filter not-fixed? (util/get-children-by-tag parent-el "li")) add-link-elements (util/get-elements-by-tag-and-class "a" "add-item-to-nested-menu")] ;; required to make the top-level-drop-zone a valid drop target (. top-level-drop-zone-el (addEventListener "dragover" (fn [e] (. e (stopPropagation)) (. e (preventDefault))))) (. top-level-drop-zone-el (addEventListener "drop" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (dom/appendChild parent-el @active-el)))) (doseq [el li-elements] ;; not using Google's events/listen because it strips .dataTransfer (. el (addEventListener "dragstart" (fn [e] (when-let [dragged-el (get-draggable-item (.-target e))] (reset! active-el dragged-el) (classes/add dragged-el "dragging") (comment (set! (.effectAllowed (.-dataTransfer e)) "move")) (. (.-dataTransfer e) (setData "text/html" (.-innerHTML dragged-el))) ;; show the top level drop zone (if relevant) (when-not (= (util/get-parent dragged-el) parent-el) (classes/remove top-level-drop-zone-el "invisible")) ;; highlight add link buttons that can be dropped on (doseq [add-link-el add-link-elements] (when-not (or (classes/has add-link-el "highlight-add-link-el") (node-contains? dragged-el add-link-el) (util/is-sibling? dragged-el (util/get-parent add-link-el))) (classes/add add-link-el "highlight-add-link-el") (set! (.-textContent add-link-el) (str "\u21fe " (.-textContent add-link-el))))))))) ;; required to make the node a valid drop target (. el (addEventListener "dragover" (fn [e] (. e (stopPropagation)) (. e (preventDefault))))) (. el (addEventListener "drop" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (remove-highlight-from-add-link-elements add-link-elements) (when-let [drop-target (get-draggable-item (.-target e))] (cond ;; when dropped on an add-item node of a nested ul (classes/has (.-target e) "add-item-to-nested-menu") (when (can-add-to-nested-ul? @active-el drop-target) (dom/insertSiblingBefore @active-el (util/get-parent (.-target e)))) :default ;; when dropped on another node (when-not (= @active-el drop-target) (let [drop-data (clean-drop-data (. (.-dataTransfer e) (getData "text/html")))] (if ;; when dropped on an ancestor or descendant node (or (node-contains? drop-target @active-el) (node-contains? @active-el drop-target)) (let [dt-item-details-el (get-item-details-el drop-target) data-dummy-el (dom/createElement "div")] (do ;; use dummy el to access the item-details ;; child node of the dragged element (set! (.-innerHTML data-dummy-el) drop-data) (set! (.-innerHTML (get-item-details-el @active-el)) (.-innerHTML dt-item-details-el)) (set! (.-innerHTML dt-item-details-el) (.-innerHTML (first (util/get-children data-dummy-el)))))) ;; when dropped on an unrelated node (do (set! (.-innerHTML @active-el) (.-innerHTML drop-target)) (set! (.-innerHTML drop-target) drop-data))))))) (after-drop-fn)))) (. el (addEventListener "dragend" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (classes/remove @active-el "dragging") (classes/add top-level-drop-zone-el "invisible") (remove-highlight-from-add-link-elements add-link-elements))))))) ; TODO: this function is still a work-in-progress (comment (defn fx! ([fx-obj element duration] (fx! fx-obj element duration {:begin nil :end nil})) ([fx-obj element duration event-handlers] (let [begin-fn (:begin event-handlers) end-fn (:end event-handlers) animation (fx-obj. element duration)] (when (fn? begin-fn) (events/listen animation transition-event/BEGIN begin-fn)) (when (fn? end-fn) (events/listen animation transition-event/END #((do (end-fn) (. animation (destroy)))))) (. animation (play))))) (def fade-in! (partial fx! fx-dom/FadeInAndShow true)) (def fade-out! (partial fx! fx-dom/FadeOutAndHide true))) (comment ; TODO: implement a nice animation for displaying status messages (defn remove-slug-error [status-el slug-el] (let [end-fn (fn [] ; make sure we don't remove new errors that ; popped up after the start of the animation (when (classes/has slug-el "error") (swap! fade-out-animation-active false) (classes/remove status-el "status-error") (classes/remove status-el "error") (dom/setTextContent status-el " ")))] (when (classes/has slug-el "error") (fade-out! status-el 1000 {:begin-fn nil :end-fn end-fn}) (classes/remove slug-el "error")))))
68038
;; cljs/src/ui.cljs: utility functions related to the user interface. ;; Copyright 2011-2013, Vixu.com, <NAME> <<EMAIL>>. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns vix.ui (:use-macros [vix.crossover.macros :only [get-snippets]]) (:use [domina.css :only [sel]] [domina.xpath :only [xpath]]) (:require [vix.util :as util] [domina :as domina] [clojure.string :as string] [goog.dom :as dom] [goog.dom.forms :as forms] [goog.dom.classes :as classes] [goog.ui.Dialog :as goog.ui.Dialog] [goog.ui.Dialog.ButtonSet :as goog.ui.Dialog.ButtonSet] [goog.ui.Dialog.EventType :as goog.ui.Dialog.EventType] [goog.ui.DatePicker :as DatePicker] [goog.ui.DatePicker.Events :as DatePickerEvents] [goog.events :as events] [goog.fx.DragDrop :as goog.fx.DragDrop] [goog.fx.DragDropGroup :as goog.fx.DragDropGroup] ;; [goog.fx.dom :as fx-dom] ;; [goog.fx.Animation :as Animation] ;; [goog.fx.Animation.EventType :as transition-event] ;; [goog.Timer :as timer] )) (def snippets "Map with the HTML snippets generated by the get-snippets macro, e.g. {:feed/:add-feed-button \"<button ...>\" ...}." (get-snippets)) (defn clear-page! "Removes all child-nodes of the div#main-page node, effectively clearing the page." [] (domina/destroy-children! (xpath "//div[@id='main-page']"))) (defn- execute-show! "Performs the action grunt work for the show! fn, apart from clearing the page, see its docstring for more information." [& all-actions] (loop [actions (flatten all-actions)] (when (not-empty actions) (let [{:keys [parent snippet transformations children] :as action} (first actions)] (domina/append! (xpath (or parent "//div[@id='main-page']")) (snippets snippet)) (doall ;; execute transformations (map (fn [{:keys [selector text attrs remove-attr add-class remove-class value checked]}] (let [node (xpath selector)] (when text (domina/set-text! node text)) (when attrs (domina/set-attrs! node attrs)) (when remove-attr (domina/remove-attr! node remove-attr)) (when add-class (domina/add-class! node add-class)) (when remove-class (domina/remove-class! node remove-class)) (when value (domina/set-value! node value)) (when (not (nil? checked)) (if checked (domina/set-attr! (domina/single-node node) :checked "checked") (domina/remove-attr! (domina/single-node node) :checked))))) transformations)) (when (not-empty children) (apply execute-show! children)) (recur (rest actions)))))) (defn show! "Clears the page and executes the provided actions. Accepts any number of arguments, each being an action map. Every action should at least contain a :snippet key that is mapped to a HTML string to insert. The action may contain a :parent key, that maps to a string containing an xpath selector for a parent element to place the newly created element in. Without a :parent value, the div#main-page element is used as a parent element by default. The action may also contain a :transformations key that maps to a sequence of transformations to perform after the snippet is added to the DOM. Each transformation is a map with a :selector key mapped to a string with an xpath selector for the node to transform, as well as a :text, :attrs, :remove-attr :value or :checked key (or multiple) containing the new text content for the node, an attribute map, a keyword of an attribute to remove, form field value or boolean respectively. The action map may also contain an optional :children key, which maps to a sequence of actions that will be recursively executed after the current action is added to the DOM and its transformations are completed (i.e. with nesting). See the views/feed and views/editor namespaces for example usage." [& all-actions] (clear-page!) (apply execute-show! all-actions)) (defn set-form-value [el-id-or-obj value] (let [el (util/get-element el-id-or-obj)] (forms/setValue el value))) (defn get-form-value [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (forms/getValue el))) (defn is-checked? "Accepts a checkbox element or element ID and returns true if checked." [el-id-or-obj] (= "on" (get-form-value el-id-or-obj))) (defn get-form-value-by-name [form-el-id-or-obj name] (let [form (util/get-element form-el-id-or-obj)] (forms/getValueByName form name))) (defn get-form-values "Returns a map containing the values for all form elements within the given form-el. Keys are element names converted to keywords. Values are either strings or a vector of strings if the form element has multiple values." [form-el] (let [form-data (forms/getFormDataMap (util/get-element form-el))] (zipmap (map keyword (. form-data (getKeys))) (map (fn [value] (if (> (count value) 1) (vec value) (first value))) (. form-data (getValues)))))) (defn button-to-obj [button] (util/map-to-obj {:key (name button) :caption (if (= button :ok) "OK" (string/capitalize (name button)))})) (defn button-set [& buttons] (let [button-set (new goog.ui.Dialog.ButtonSet)] (doseq [button buttons] (doto button-set (.addButton (button-to-obj button) (= button (first buttons)) (= button :cancel)))) button-set)) (defn display-dialog! "Displays a goog.ui.Dialog with given title and the HTML content from the provided content string. When the dialog is closed the dialog is removed and the provided callback function is called with the dialog result (:ok or :cancel) as the first argument and a map with the form data from the provided form-el HTML form node as the second argument." ([title content form-el options callback] (display-dialog! title content form-el options callback :ok :cancel)) ([title content form-el {:keys [modal? auto-close?]} callback & buttons] (let [dialog (new goog.ui.Dialog)] (events/listen dialog goog.ui.Dialog.EventType/SELECT (fn [evt] (. evt (preventDefault)) (. evt (stopPropagation)) (let [button (keyword (.-key evt))] (callback button (when form-el (get-form-values form-el))) (when (or auto-close? (= :cancel button)) (remove-dialog!))))) (doto dialog (.setModal modal?) (.setTitle title) (.setContent content) (.setButtonSet (apply button-set buttons)) (.setVisible true))))) (defn remove-dialog! "Removes any goog.ui.Dialog elements from the DOM." [] (domina/destroy! (domina/by-class "modal-dialog")) (domina/destroy! (domina/by-class "modal-dialog-bg"))) (defn display-datepicker "Displays a date picker in a dialog and passes a goog.date.Date object (or nil if no date is selected) to the success-handler function if the user confirms the selection. If the include-time? argument is true two arguments are added to the success-handler fn: hour and minute (both strings)." [success-handler include-time?] (let [dp (goog.ui.DatePicker.)] (display-dialog "Pick a date" (str (:ui/date-widget snippets) (when include-time? (:ui/datepicker-time-row snippets))) (fn [evt] (when (= "ok" (.-key evt)) (let [date-obj (. dp (getDate))] (success-handler {:date-object date-obj :date-string (.toIsoString date-obj true) :hour (get-form-value "hour") :minute (get-form-value "minute")})) (. dp (dispose))) (remove-dialog))) (.decorate dp (dom/getElement "date-widget")))) (defn add-or-remove-errors "Displays or removes error, using status-el and active-el, based on the provided validation-result (either :pass or a map with its :error key mapped to the particular error and its :message key to the human-readable error message that is to be displayed in status-el." [status-el active-el validation-result] (if (= validation-result :pass) (remove-error status-el active-el) (display-error status-el (:message validation-result) active-el))) (defn display-error "Adds the class 'error' to the provided status-el, sets its text content to the given message and also adds the 'error' class to the other-elements provided as optional further arguments. Returns nil." [status-el message & other-elements] (doseq [el other-elements] (domina/add-class! el "error")) (doto status-el (domina/remove-class! "status-ok") (domina/remove-class! "hide") (domina/add-class! "status-error") (domina/add-class! "error") (domina/set-text! message)) nil) (defn remove-error "Removes the classes 'error' and 'status-error' from the given status-el, sets the text content of the status-el to an empty string and removes the 'error' class from any other-elements provided as optional further arguments. Returns nil." [status-el & other-elements] (doseq [el other-elements] (domina/remove-class! el "error")) (doto status-el (domina/remove-class! "status-error") (domina/remove-class! "error") (domina/set-text! "")) nil) (defn enable-element [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (doto el (classes/remove "disabled") (.removeAttribute "disabled")))) (defn disable-element [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (doto el (classes/add "disabled") (.setAttribute "disabled" "disabled")))) (defn trigger-on-class [class trigger-on f] ;; converting to vector to avoid issues with doseq and arrays (doseq [el (cljs.core.Vector/fromArray (dom/getElementsByClass class))] (events/listen el trigger-on f))) (defn remove-class-from-elements [class elements] (doseq [el elements] (classes/remove el class))) (defn not-fixed? [el] (not (classes/has el "fixed"))) (def active-el (atom nil)) (defn get-draggable-item "Returns the actual draggable item starting from a (possibly nested) event target element and going up the tree recursively (up to 5 times). The event's target object refers to the element that was clicked on, which might be a nested node (e.g. a span or a element inside the li node that is the intended draggable item)." [el] (loop [current-el el times-called 0] (if (and (= (.-tagName current-el) "LI") (.hasAttribute current-el "draggable")) (cond (= (.-draggable current-el) false) (if (classes/has current-el "drop-on-grandparent") (util/get-parent (util/get-parent current-el)) nil) (= (.-draggable current-el) true) current-el) (if (<= times-called 5) (recur (util/get-parent current-el) (inc times-called)) nil)))) (defn node-contains? "Checks if the element passed as the first argument contains the element passed at the second argument." [x y] (when (and x y) (dom/contains x y))) (defn can-add-to-nested-ul? [el-dragged el-dropped-on] (not (or (node-contains? el-dragged el-dropped-on) (node-contains? el-dropped-on el-dragged)))) (defn get-item-details-el [el] (first (util/get-children-by-class el "item-details"))) (defn remove-highlight-from-add-link-elements [elements] (doseq [add-link-el elements] (when (classes/has add-link-el "highlight-add-link-el") (classes/remove add-link-el "highlight-add-link-el") (set! (.-textContent add-link-el) (. (.-textContent add-link-el) (substr 2)))))) (defn clean-drop-data "Removes META elements from provided html string and returns innerHTML string. This is necessary because some versions of Chrome append a meta tag to the drop data." [html] (let [unclean-dummy-el (dom/createElement "div") clean-dummy-el (dom/createElement "div")] (set! (.-innerHTML unclean-dummy-el) html) (doseq [non-meta-child (filter #(not (= (.-tagName %) "META")) (util/get-children unclean-dummy-el))] (dom/appendChild clean-dummy-el non-meta-child)) (.-innerHTML clean-dummy-el))) (defn to-sortable-tree [parent-el after-drop-fn] (let [top-level-drop-zone-el (dom/getElement "menu-top-level-drop-zone") li-elements (filter not-fixed? (util/get-children-by-tag parent-el "li")) add-link-elements (util/get-elements-by-tag-and-class "a" "add-item-to-nested-menu")] ;; required to make the top-level-drop-zone a valid drop target (. top-level-drop-zone-el (addEventListener "dragover" (fn [e] (. e (stopPropagation)) (. e (preventDefault))))) (. top-level-drop-zone-el (addEventListener "drop" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (dom/appendChild parent-el @active-el)))) (doseq [el li-elements] ;; not using Google's events/listen because it strips .dataTransfer (. el (addEventListener "dragstart" (fn [e] (when-let [dragged-el (get-draggable-item (.-target e))] (reset! active-el dragged-el) (classes/add dragged-el "dragging") (comment (set! (.effectAllowed (.-dataTransfer e)) "move")) (. (.-dataTransfer e) (setData "text/html" (.-innerHTML dragged-el))) ;; show the top level drop zone (if relevant) (when-not (= (util/get-parent dragged-el) parent-el) (classes/remove top-level-drop-zone-el "invisible")) ;; highlight add link buttons that can be dropped on (doseq [add-link-el add-link-elements] (when-not (or (classes/has add-link-el "highlight-add-link-el") (node-contains? dragged-el add-link-el) (util/is-sibling? dragged-el (util/get-parent add-link-el))) (classes/add add-link-el "highlight-add-link-el") (set! (.-textContent add-link-el) (str "\u21fe " (.-textContent add-link-el))))))))) ;; required to make the node a valid drop target (. el (addEventListener "dragover" (fn [e] (. e (stopPropagation)) (. e (preventDefault))))) (. el (addEventListener "drop" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (remove-highlight-from-add-link-elements add-link-elements) (when-let [drop-target (get-draggable-item (.-target e))] (cond ;; when dropped on an add-item node of a nested ul (classes/has (.-target e) "add-item-to-nested-menu") (when (can-add-to-nested-ul? @active-el drop-target) (dom/insertSiblingBefore @active-el (util/get-parent (.-target e)))) :default ;; when dropped on another node (when-not (= @active-el drop-target) (let [drop-data (clean-drop-data (. (.-dataTransfer e) (getData "text/html")))] (if ;; when dropped on an ancestor or descendant node (or (node-contains? drop-target @active-el) (node-contains? @active-el drop-target)) (let [dt-item-details-el (get-item-details-el drop-target) data-dummy-el (dom/createElement "div")] (do ;; use dummy el to access the item-details ;; child node of the dragged element (set! (.-innerHTML data-dummy-el) drop-data) (set! (.-innerHTML (get-item-details-el @active-el)) (.-innerHTML dt-item-details-el)) (set! (.-innerHTML dt-item-details-el) (.-innerHTML (first (util/get-children data-dummy-el)))))) ;; when dropped on an unrelated node (do (set! (.-innerHTML @active-el) (.-innerHTML drop-target)) (set! (.-innerHTML drop-target) drop-data))))))) (after-drop-fn)))) (. el (addEventListener "dragend" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (classes/remove @active-el "dragging") (classes/add top-level-drop-zone-el "invisible") (remove-highlight-from-add-link-elements add-link-elements))))))) ; TODO: this function is still a work-in-progress (comment (defn fx! ([fx-obj element duration] (fx! fx-obj element duration {:begin nil :end nil})) ([fx-obj element duration event-handlers] (let [begin-fn (:begin event-handlers) end-fn (:end event-handlers) animation (fx-obj. element duration)] (when (fn? begin-fn) (events/listen animation transition-event/BEGIN begin-fn)) (when (fn? end-fn) (events/listen animation transition-event/END #((do (end-fn) (. animation (destroy)))))) (. animation (play))))) (def fade-in! (partial fx! fx-dom/FadeInAndShow true)) (def fade-out! (partial fx! fx-dom/FadeOutAndHide true))) (comment ; TODO: implement a nice animation for displaying status messages (defn remove-slug-error [status-el slug-el] (let [end-fn (fn [] ; make sure we don't remove new errors that ; popped up after the start of the animation (when (classes/has slug-el "error") (swap! fade-out-animation-active false) (classes/remove status-el "status-error") (classes/remove status-el "error") (dom/setTextContent status-el " ")))] (when (classes/has slug-el "error") (fade-out! status-el 1000 {:begin-fn nil :end-fn end-fn}) (classes/remove slug-el "error")))))
true
;; cljs/src/ui.cljs: utility functions related to the user interface. ;; Copyright 2011-2013, Vixu.com, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns vix.ui (:use-macros [vix.crossover.macros :only [get-snippets]]) (:use [domina.css :only [sel]] [domina.xpath :only [xpath]]) (:require [vix.util :as util] [domina :as domina] [clojure.string :as string] [goog.dom :as dom] [goog.dom.forms :as forms] [goog.dom.classes :as classes] [goog.ui.Dialog :as goog.ui.Dialog] [goog.ui.Dialog.ButtonSet :as goog.ui.Dialog.ButtonSet] [goog.ui.Dialog.EventType :as goog.ui.Dialog.EventType] [goog.ui.DatePicker :as DatePicker] [goog.ui.DatePicker.Events :as DatePickerEvents] [goog.events :as events] [goog.fx.DragDrop :as goog.fx.DragDrop] [goog.fx.DragDropGroup :as goog.fx.DragDropGroup] ;; [goog.fx.dom :as fx-dom] ;; [goog.fx.Animation :as Animation] ;; [goog.fx.Animation.EventType :as transition-event] ;; [goog.Timer :as timer] )) (def snippets "Map with the HTML snippets generated by the get-snippets macro, e.g. {:feed/:add-feed-button \"<button ...>\" ...}." (get-snippets)) (defn clear-page! "Removes all child-nodes of the div#main-page node, effectively clearing the page." [] (domina/destroy-children! (xpath "//div[@id='main-page']"))) (defn- execute-show! "Performs the action grunt work for the show! fn, apart from clearing the page, see its docstring for more information." [& all-actions] (loop [actions (flatten all-actions)] (when (not-empty actions) (let [{:keys [parent snippet transformations children] :as action} (first actions)] (domina/append! (xpath (or parent "//div[@id='main-page']")) (snippets snippet)) (doall ;; execute transformations (map (fn [{:keys [selector text attrs remove-attr add-class remove-class value checked]}] (let [node (xpath selector)] (when text (domina/set-text! node text)) (when attrs (domina/set-attrs! node attrs)) (when remove-attr (domina/remove-attr! node remove-attr)) (when add-class (domina/add-class! node add-class)) (when remove-class (domina/remove-class! node remove-class)) (when value (domina/set-value! node value)) (when (not (nil? checked)) (if checked (domina/set-attr! (domina/single-node node) :checked "checked") (domina/remove-attr! (domina/single-node node) :checked))))) transformations)) (when (not-empty children) (apply execute-show! children)) (recur (rest actions)))))) (defn show! "Clears the page and executes the provided actions. Accepts any number of arguments, each being an action map. Every action should at least contain a :snippet key that is mapped to a HTML string to insert. The action may contain a :parent key, that maps to a string containing an xpath selector for a parent element to place the newly created element in. Without a :parent value, the div#main-page element is used as a parent element by default. The action may also contain a :transformations key that maps to a sequence of transformations to perform after the snippet is added to the DOM. Each transformation is a map with a :selector key mapped to a string with an xpath selector for the node to transform, as well as a :text, :attrs, :remove-attr :value or :checked key (or multiple) containing the new text content for the node, an attribute map, a keyword of an attribute to remove, form field value or boolean respectively. The action map may also contain an optional :children key, which maps to a sequence of actions that will be recursively executed after the current action is added to the DOM and its transformations are completed (i.e. with nesting). See the views/feed and views/editor namespaces for example usage." [& all-actions] (clear-page!) (apply execute-show! all-actions)) (defn set-form-value [el-id-or-obj value] (let [el (util/get-element el-id-or-obj)] (forms/setValue el value))) (defn get-form-value [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (forms/getValue el))) (defn is-checked? "Accepts a checkbox element or element ID and returns true if checked." [el-id-or-obj] (= "on" (get-form-value el-id-or-obj))) (defn get-form-value-by-name [form-el-id-or-obj name] (let [form (util/get-element form-el-id-or-obj)] (forms/getValueByName form name))) (defn get-form-values "Returns a map containing the values for all form elements within the given form-el. Keys are element names converted to keywords. Values are either strings or a vector of strings if the form element has multiple values." [form-el] (let [form-data (forms/getFormDataMap (util/get-element form-el))] (zipmap (map keyword (. form-data (getKeys))) (map (fn [value] (if (> (count value) 1) (vec value) (first value))) (. form-data (getValues)))))) (defn button-to-obj [button] (util/map-to-obj {:key (name button) :caption (if (= button :ok) "OK" (string/capitalize (name button)))})) (defn button-set [& buttons] (let [button-set (new goog.ui.Dialog.ButtonSet)] (doseq [button buttons] (doto button-set (.addButton (button-to-obj button) (= button (first buttons)) (= button :cancel)))) button-set)) (defn display-dialog! "Displays a goog.ui.Dialog with given title and the HTML content from the provided content string. When the dialog is closed the dialog is removed and the provided callback function is called with the dialog result (:ok or :cancel) as the first argument and a map with the form data from the provided form-el HTML form node as the second argument." ([title content form-el options callback] (display-dialog! title content form-el options callback :ok :cancel)) ([title content form-el {:keys [modal? auto-close?]} callback & buttons] (let [dialog (new goog.ui.Dialog)] (events/listen dialog goog.ui.Dialog.EventType/SELECT (fn [evt] (. evt (preventDefault)) (. evt (stopPropagation)) (let [button (keyword (.-key evt))] (callback button (when form-el (get-form-values form-el))) (when (or auto-close? (= :cancel button)) (remove-dialog!))))) (doto dialog (.setModal modal?) (.setTitle title) (.setContent content) (.setButtonSet (apply button-set buttons)) (.setVisible true))))) (defn remove-dialog! "Removes any goog.ui.Dialog elements from the DOM." [] (domina/destroy! (domina/by-class "modal-dialog")) (domina/destroy! (domina/by-class "modal-dialog-bg"))) (defn display-datepicker "Displays a date picker in a dialog and passes a goog.date.Date object (or nil if no date is selected) to the success-handler function if the user confirms the selection. If the include-time? argument is true two arguments are added to the success-handler fn: hour and minute (both strings)." [success-handler include-time?] (let [dp (goog.ui.DatePicker.)] (display-dialog "Pick a date" (str (:ui/date-widget snippets) (when include-time? (:ui/datepicker-time-row snippets))) (fn [evt] (when (= "ok" (.-key evt)) (let [date-obj (. dp (getDate))] (success-handler {:date-object date-obj :date-string (.toIsoString date-obj true) :hour (get-form-value "hour") :minute (get-form-value "minute")})) (. dp (dispose))) (remove-dialog))) (.decorate dp (dom/getElement "date-widget")))) (defn add-or-remove-errors "Displays or removes error, using status-el and active-el, based on the provided validation-result (either :pass or a map with its :error key mapped to the particular error and its :message key to the human-readable error message that is to be displayed in status-el." [status-el active-el validation-result] (if (= validation-result :pass) (remove-error status-el active-el) (display-error status-el (:message validation-result) active-el))) (defn display-error "Adds the class 'error' to the provided status-el, sets its text content to the given message and also adds the 'error' class to the other-elements provided as optional further arguments. Returns nil." [status-el message & other-elements] (doseq [el other-elements] (domina/add-class! el "error")) (doto status-el (domina/remove-class! "status-ok") (domina/remove-class! "hide") (domina/add-class! "status-error") (domina/add-class! "error") (domina/set-text! message)) nil) (defn remove-error "Removes the classes 'error' and 'status-error' from the given status-el, sets the text content of the status-el to an empty string and removes the 'error' class from any other-elements provided as optional further arguments. Returns nil." [status-el & other-elements] (doseq [el other-elements] (domina/remove-class! el "error")) (doto status-el (domina/remove-class! "status-error") (domina/remove-class! "error") (domina/set-text! "")) nil) (defn enable-element [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (doto el (classes/remove "disabled") (.removeAttribute "disabled")))) (defn disable-element [el-id-or-obj] (let [el (util/get-element el-id-or-obj)] (doto el (classes/add "disabled") (.setAttribute "disabled" "disabled")))) (defn trigger-on-class [class trigger-on f] ;; converting to vector to avoid issues with doseq and arrays (doseq [el (cljs.core.Vector/fromArray (dom/getElementsByClass class))] (events/listen el trigger-on f))) (defn remove-class-from-elements [class elements] (doseq [el elements] (classes/remove el class))) (defn not-fixed? [el] (not (classes/has el "fixed"))) (def active-el (atom nil)) (defn get-draggable-item "Returns the actual draggable item starting from a (possibly nested) event target element and going up the tree recursively (up to 5 times). The event's target object refers to the element that was clicked on, which might be a nested node (e.g. a span or a element inside the li node that is the intended draggable item)." [el] (loop [current-el el times-called 0] (if (and (= (.-tagName current-el) "LI") (.hasAttribute current-el "draggable")) (cond (= (.-draggable current-el) false) (if (classes/has current-el "drop-on-grandparent") (util/get-parent (util/get-parent current-el)) nil) (= (.-draggable current-el) true) current-el) (if (<= times-called 5) (recur (util/get-parent current-el) (inc times-called)) nil)))) (defn node-contains? "Checks if the element passed as the first argument contains the element passed at the second argument." [x y] (when (and x y) (dom/contains x y))) (defn can-add-to-nested-ul? [el-dragged el-dropped-on] (not (or (node-contains? el-dragged el-dropped-on) (node-contains? el-dropped-on el-dragged)))) (defn get-item-details-el [el] (first (util/get-children-by-class el "item-details"))) (defn remove-highlight-from-add-link-elements [elements] (doseq [add-link-el elements] (when (classes/has add-link-el "highlight-add-link-el") (classes/remove add-link-el "highlight-add-link-el") (set! (.-textContent add-link-el) (. (.-textContent add-link-el) (substr 2)))))) (defn clean-drop-data "Removes META elements from provided html string and returns innerHTML string. This is necessary because some versions of Chrome append a meta tag to the drop data." [html] (let [unclean-dummy-el (dom/createElement "div") clean-dummy-el (dom/createElement "div")] (set! (.-innerHTML unclean-dummy-el) html) (doseq [non-meta-child (filter #(not (= (.-tagName %) "META")) (util/get-children unclean-dummy-el))] (dom/appendChild clean-dummy-el non-meta-child)) (.-innerHTML clean-dummy-el))) (defn to-sortable-tree [parent-el after-drop-fn] (let [top-level-drop-zone-el (dom/getElement "menu-top-level-drop-zone") li-elements (filter not-fixed? (util/get-children-by-tag parent-el "li")) add-link-elements (util/get-elements-by-tag-and-class "a" "add-item-to-nested-menu")] ;; required to make the top-level-drop-zone a valid drop target (. top-level-drop-zone-el (addEventListener "dragover" (fn [e] (. e (stopPropagation)) (. e (preventDefault))))) (. top-level-drop-zone-el (addEventListener "drop" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (dom/appendChild parent-el @active-el)))) (doseq [el li-elements] ;; not using Google's events/listen because it strips .dataTransfer (. el (addEventListener "dragstart" (fn [e] (when-let [dragged-el (get-draggable-item (.-target e))] (reset! active-el dragged-el) (classes/add dragged-el "dragging") (comment (set! (.effectAllowed (.-dataTransfer e)) "move")) (. (.-dataTransfer e) (setData "text/html" (.-innerHTML dragged-el))) ;; show the top level drop zone (if relevant) (when-not (= (util/get-parent dragged-el) parent-el) (classes/remove top-level-drop-zone-el "invisible")) ;; highlight add link buttons that can be dropped on (doseq [add-link-el add-link-elements] (when-not (or (classes/has add-link-el "highlight-add-link-el") (node-contains? dragged-el add-link-el) (util/is-sibling? dragged-el (util/get-parent add-link-el))) (classes/add add-link-el "highlight-add-link-el") (set! (.-textContent add-link-el) (str "\u21fe " (.-textContent add-link-el))))))))) ;; required to make the node a valid drop target (. el (addEventListener "dragover" (fn [e] (. e (stopPropagation)) (. e (preventDefault))))) (. el (addEventListener "drop" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (remove-highlight-from-add-link-elements add-link-elements) (when-let [drop-target (get-draggable-item (.-target e))] (cond ;; when dropped on an add-item node of a nested ul (classes/has (.-target e) "add-item-to-nested-menu") (when (can-add-to-nested-ul? @active-el drop-target) (dom/insertSiblingBefore @active-el (util/get-parent (.-target e)))) :default ;; when dropped on another node (when-not (= @active-el drop-target) (let [drop-data (clean-drop-data (. (.-dataTransfer e) (getData "text/html")))] (if ;; when dropped on an ancestor or descendant node (or (node-contains? drop-target @active-el) (node-contains? @active-el drop-target)) (let [dt-item-details-el (get-item-details-el drop-target) data-dummy-el (dom/createElement "div")] (do ;; use dummy el to access the item-details ;; child node of the dragged element (set! (.-innerHTML data-dummy-el) drop-data) (set! (.-innerHTML (get-item-details-el @active-el)) (.-innerHTML dt-item-details-el)) (set! (.-innerHTML dt-item-details-el) (.-innerHTML (first (util/get-children data-dummy-el)))))) ;; when dropped on an unrelated node (do (set! (.-innerHTML @active-el) (.-innerHTML drop-target)) (set! (.-innerHTML drop-target) drop-data))))))) (after-drop-fn)))) (. el (addEventListener "dragend" (fn [e] (. e (stopPropagation)) (. e (preventDefault)) (classes/remove @active-el "dragging") (classes/add top-level-drop-zone-el "invisible") (remove-highlight-from-add-link-elements add-link-elements))))))) ; TODO: this function is still a work-in-progress (comment (defn fx! ([fx-obj element duration] (fx! fx-obj element duration {:begin nil :end nil})) ([fx-obj element duration event-handlers] (let [begin-fn (:begin event-handlers) end-fn (:end event-handlers) animation (fx-obj. element duration)] (when (fn? begin-fn) (events/listen animation transition-event/BEGIN begin-fn)) (when (fn? end-fn) (events/listen animation transition-event/END #((do (end-fn) (. animation (destroy)))))) (. animation (play))))) (def fade-in! (partial fx! fx-dom/FadeInAndShow true)) (def fade-out! (partial fx! fx-dom/FadeOutAndHide true))) (comment ; TODO: implement a nice animation for displaying status messages (defn remove-slug-error [status-el slug-el] (let [end-fn (fn [] ; make sure we don't remove new errors that ; popped up after the start of the animation (when (classes/has slug-el "error") (swap! fade-out-animation-active false) (classes/remove status-el "status-error") (classes/remove status-el "error") (dom/setTextContent status-el " ")))] (when (classes/has slug-el "error") (fade-out! status-el 1000 {:begin-fn nil :end-fn end-fn}) (classes/remove slug-el "error")))))
[ { "context": " [name names]\n (let [extensions [{:oid \"2.5.29.17\"\n :value {:dns-name [n", "end": 1037, "score": 0.999719500541687, "start": 1028, "tag": "IP_ADDRESS", "value": "2.5.29.17" } ]
test/utils/puppetlabs/pcp/testutils/certs.clj
rileynewton/pcp-broker
6
(ns puppetlabs.pcp.testutils.certs (:require [me.raynes.fs :as fs] [puppetlabs.ssl-utils.core :as ssl-utils] [puppetlabs.ssl-utils.simple :as ssl-simple])) (def cert-serial-num (atom 0)) (defn save-pems [ssl-dir cert] (let [pub-key-dir (fs/file ssl-dir "public_keys") priv-key-dir (fs/file ssl-dir "private_keys") cert-dir (fs/file ssl-dir "certs")] (fs/mkdirs pub-key-dir) (fs/mkdirs priv-key-dir) (fs/mkdirs cert-dir) (ssl-utils/key->pem! (:public-key cert) (fs/file pub-key-dir (str (:certname cert) ".pem"))) (ssl-utils/key->pem! (:private-key cert) (fs/file priv-key-dir (str (:certname cert) ".pem"))) (ssl-utils/cert->pem! (:cert cert) (fs/file cert-dir (str (:certname cert) ".pem"))) (println "saved pems for" (:certname cert)))) (defn gen-pcp-certs [ssl-dir names] (let [cacert (ssl-simple/gen-self-signed-cert "ca" (swap! cert-serial-num inc))] (save-pems ssl-dir cacert) (doseq [name names] (let [extensions [{:oid "2.5.29.17" :value {:dns-name [name "localhost"]} :critical false}] cert (ssl-simple/gen-cert name cacert (swap! cert-serial-num inc) {:extensions extensions})] (save-pems ssl-dir cert))) (let [crl (ssl-simple/gen-crl cacert)] (fs/mkdirs (fs/file ssl-dir "ca")) (fs/copy (fs/file ssl-dir "certs/ca.pem") (fs/file ssl-dir "ca/ca_crt.pem")) (ssl-utils/crl->pem! crl (fs/file ssl-dir "ca" "ca_crl.pem"))))) (defn -main [& args] (let [certs (rest (drop-while (fn [s] (not (= s "--"))) args))] (gen-pcp-certs "./test-resources/ssl" certs)))
110387
(ns puppetlabs.pcp.testutils.certs (:require [me.raynes.fs :as fs] [puppetlabs.ssl-utils.core :as ssl-utils] [puppetlabs.ssl-utils.simple :as ssl-simple])) (def cert-serial-num (atom 0)) (defn save-pems [ssl-dir cert] (let [pub-key-dir (fs/file ssl-dir "public_keys") priv-key-dir (fs/file ssl-dir "private_keys") cert-dir (fs/file ssl-dir "certs")] (fs/mkdirs pub-key-dir) (fs/mkdirs priv-key-dir) (fs/mkdirs cert-dir) (ssl-utils/key->pem! (:public-key cert) (fs/file pub-key-dir (str (:certname cert) ".pem"))) (ssl-utils/key->pem! (:private-key cert) (fs/file priv-key-dir (str (:certname cert) ".pem"))) (ssl-utils/cert->pem! (:cert cert) (fs/file cert-dir (str (:certname cert) ".pem"))) (println "saved pems for" (:certname cert)))) (defn gen-pcp-certs [ssl-dir names] (let [cacert (ssl-simple/gen-self-signed-cert "ca" (swap! cert-serial-num inc))] (save-pems ssl-dir cacert) (doseq [name names] (let [extensions [{:oid "172.16.31.10" :value {:dns-name [name "localhost"]} :critical false}] cert (ssl-simple/gen-cert name cacert (swap! cert-serial-num inc) {:extensions extensions})] (save-pems ssl-dir cert))) (let [crl (ssl-simple/gen-crl cacert)] (fs/mkdirs (fs/file ssl-dir "ca")) (fs/copy (fs/file ssl-dir "certs/ca.pem") (fs/file ssl-dir "ca/ca_crt.pem")) (ssl-utils/crl->pem! crl (fs/file ssl-dir "ca" "ca_crl.pem"))))) (defn -main [& args] (let [certs (rest (drop-while (fn [s] (not (= s "--"))) args))] (gen-pcp-certs "./test-resources/ssl" certs)))
true
(ns puppetlabs.pcp.testutils.certs (:require [me.raynes.fs :as fs] [puppetlabs.ssl-utils.core :as ssl-utils] [puppetlabs.ssl-utils.simple :as ssl-simple])) (def cert-serial-num (atom 0)) (defn save-pems [ssl-dir cert] (let [pub-key-dir (fs/file ssl-dir "public_keys") priv-key-dir (fs/file ssl-dir "private_keys") cert-dir (fs/file ssl-dir "certs")] (fs/mkdirs pub-key-dir) (fs/mkdirs priv-key-dir) (fs/mkdirs cert-dir) (ssl-utils/key->pem! (:public-key cert) (fs/file pub-key-dir (str (:certname cert) ".pem"))) (ssl-utils/key->pem! (:private-key cert) (fs/file priv-key-dir (str (:certname cert) ".pem"))) (ssl-utils/cert->pem! (:cert cert) (fs/file cert-dir (str (:certname cert) ".pem"))) (println "saved pems for" (:certname cert)))) (defn gen-pcp-certs [ssl-dir names] (let [cacert (ssl-simple/gen-self-signed-cert "ca" (swap! cert-serial-num inc))] (save-pems ssl-dir cacert) (doseq [name names] (let [extensions [{:oid "PI:IP_ADDRESS:172.16.31.10END_PI" :value {:dns-name [name "localhost"]} :critical false}] cert (ssl-simple/gen-cert name cacert (swap! cert-serial-num inc) {:extensions extensions})] (save-pems ssl-dir cert))) (let [crl (ssl-simple/gen-crl cacert)] (fs/mkdirs (fs/file ssl-dir "ca")) (fs/copy (fs/file ssl-dir "certs/ca.pem") (fs/file ssl-dir "ca/ca_crt.pem")) (ssl-utils/crl->pem! crl (fs/file ssl-dir "ca" "ca_crl.pem"))))) (defn -main [& args] (let [certs (rest (drop-while (fn [s] (not (= s "--"))) args))] (gen-pcp-certs "./test-resources/ssl" certs)))
[ { "context": "ernal:6443\\\"\n {:basic-auth {:username \\\"admin\\\"\n :password \\\"1234\\\"}})\"", "end": 1360, "score": 0.9142035841941833, "start": 1355, "tag": "USERNAME", "value": "admin" }, { "context": "me \\\"admin\\\"\n :password \\\"1234\\\"}})\"\n [host opts]\n (let [interceptors (concat ", "end": 1404, "score": 0.9992579817771912, "start": 1400, "tag": "PASSWORD", "value": "1234" } ]
src/kubernetes_api/core.clj
deas/k8s-api
87
(ns kubernetes-api.core (:require [kubernetes-api.extensions.custom-resource-definition :as crd] [kubernetes-api.interceptors.auth :as interceptors.auth] [kubernetes-api.interceptors.raise :as interceptors.raise] [kubernetes-api.internals.client :as internals.client] [kubernetes-api.internals.martian :as internals.martian] [kubernetes-api.misc :as misc] [kubernetes-api.swagger :as swagger] [martian.core :as martian] [martian.httpkit :as martian-httpkit] martian.swagger)) (defn client "Creates a Kubernetes Client compliant with martian api and its helpers host - a string url to the kubernetes cluster Options: [Authentication] :basic-auth - a map with plain text username/password :token - oauth token string without Bearer prefix :token-fn - a single-argument function that receives this opts and returns a token :client-cert/:ca-cert/:client-key - string filepath indicating certificates and key files to configure client cert. :insecure? - ignore self-signed server certificates [Custom] :interceptors - additional interceptors to the martian's client Example: (client \"https://kubernetes.docker.internal:6443\" {:basic-auth {:username \"admin\" :password \"1234\"}})" [host opts] (let [interceptors (concat [(interceptors.raise/new opts) (interceptors.auth/new opts)] (:interceptors opts) martian-httpkit/default-interceptors) k8s (internals.client/pascal-case-routes (martian/bootstrap-swagger host (or (swagger/from-api host opts) (swagger/read)) {:interceptors interceptors}))] (assoc k8s ::api-group-list (internals.martian/response-for k8s :GetApiVersions) ::core-api-versions (internals.martian/response-for k8s :GetCoreApiVersions)))) (defn invoke "Invoke a action on kubernetes api Parameters: :kind - a keyword identifing a kubernetes entity :action - each entity can have different subset of action. Examples: :create :update :patch :list :get :delete :deletecollection :request - to check what is this use kubernetes-api.core/info function Example: (invoke k8s {:kind :Deployment :action :create :request {:namespace \"default\" :body {:apiVersion \"v1\", ...}})" [k8s {:keys [request] :as params}] (if-let [action (internals.client/find-preferred-route k8s (dissoc params :request))] (internals.martian/response-for k8s action (or request {})) (throw (ex-info "Could not find action" {:search (dissoc params :request)})))) (defn extend-client "Extend a Kubernetes Client to support CustomResourceDefinitions Example: (extend-client k8s {:api \"tekton.dev\" :version \"v1alpha1\"})" [k8s {:keys [api version] :as extension-api}] (let [api-resources (internals.martian/response-for k8s :GetArbitraryApiResources {:api api :version version}) crds (internals.martian/response-for k8s :ListApiextensionsV1beta1CustomResourceDefinition)] (internals.client/pascal-case-routes (update k8s :handlers #(concat % (martian.swagger/swagger->handlers (crd/swagger-from extension-api api-resources crds))))))) (defn explore "Return a data structure with all actions performable on Kubernetes API, organized per kind and per action Examples: (explore k8s) => [[:Deployment [:get \"some description\"] ...] [:Service [:create \"other description\"] ...]] (explore k8s :Deployment) => [:Deployment [:create \"description\"] ...]" ([{:keys [handlers] :as k8s}] (->> (filter (partial internals.client/preffered-version? k8s) handlers) (group-by internals.client/kind) (map (fn [[kind handlers]] (vec (cons (keyword kind) (mapv (juxt internals.client/action :summary) handlers))))) (sort-by (comp str first)) vec)) ([k8s kind] (->> (explore k8s) (misc/find-first #(= kind (first %))) vec))) (defn request "Returns the map that is passed to org.httpkit.client/request function. Used mostly for debugging. For customizing this, use the :interceptors option while creating an client" [k8s {:keys [request] :as params}] (if-let [action (internals.client/find-preferred-route k8s (dissoc params :request))] (martian/request-for k8s action (or request {})) (throw (ex-info "Could not find action" {:search (dissoc params :request)})))) (defn info "Returns everything on a specific action, including request and response schemas" [k8s params] (martian/explore k8s (internals.client/find-preferred-route k8s (dissoc params :request))))
84577
(ns kubernetes-api.core (:require [kubernetes-api.extensions.custom-resource-definition :as crd] [kubernetes-api.interceptors.auth :as interceptors.auth] [kubernetes-api.interceptors.raise :as interceptors.raise] [kubernetes-api.internals.client :as internals.client] [kubernetes-api.internals.martian :as internals.martian] [kubernetes-api.misc :as misc] [kubernetes-api.swagger :as swagger] [martian.core :as martian] [martian.httpkit :as martian-httpkit] martian.swagger)) (defn client "Creates a Kubernetes Client compliant with martian api and its helpers host - a string url to the kubernetes cluster Options: [Authentication] :basic-auth - a map with plain text username/password :token - oauth token string without Bearer prefix :token-fn - a single-argument function that receives this opts and returns a token :client-cert/:ca-cert/:client-key - string filepath indicating certificates and key files to configure client cert. :insecure? - ignore self-signed server certificates [Custom] :interceptors - additional interceptors to the martian's client Example: (client \"https://kubernetes.docker.internal:6443\" {:basic-auth {:username \"admin\" :password \"<PASSWORD>\"}})" [host opts] (let [interceptors (concat [(interceptors.raise/new opts) (interceptors.auth/new opts)] (:interceptors opts) martian-httpkit/default-interceptors) k8s (internals.client/pascal-case-routes (martian/bootstrap-swagger host (or (swagger/from-api host opts) (swagger/read)) {:interceptors interceptors}))] (assoc k8s ::api-group-list (internals.martian/response-for k8s :GetApiVersions) ::core-api-versions (internals.martian/response-for k8s :GetCoreApiVersions)))) (defn invoke "Invoke a action on kubernetes api Parameters: :kind - a keyword identifing a kubernetes entity :action - each entity can have different subset of action. Examples: :create :update :patch :list :get :delete :deletecollection :request - to check what is this use kubernetes-api.core/info function Example: (invoke k8s {:kind :Deployment :action :create :request {:namespace \"default\" :body {:apiVersion \"v1\", ...}})" [k8s {:keys [request] :as params}] (if-let [action (internals.client/find-preferred-route k8s (dissoc params :request))] (internals.martian/response-for k8s action (or request {})) (throw (ex-info "Could not find action" {:search (dissoc params :request)})))) (defn extend-client "Extend a Kubernetes Client to support CustomResourceDefinitions Example: (extend-client k8s {:api \"tekton.dev\" :version \"v1alpha1\"})" [k8s {:keys [api version] :as extension-api}] (let [api-resources (internals.martian/response-for k8s :GetArbitraryApiResources {:api api :version version}) crds (internals.martian/response-for k8s :ListApiextensionsV1beta1CustomResourceDefinition)] (internals.client/pascal-case-routes (update k8s :handlers #(concat % (martian.swagger/swagger->handlers (crd/swagger-from extension-api api-resources crds))))))) (defn explore "Return a data structure with all actions performable on Kubernetes API, organized per kind and per action Examples: (explore k8s) => [[:Deployment [:get \"some description\"] ...] [:Service [:create \"other description\"] ...]] (explore k8s :Deployment) => [:Deployment [:create \"description\"] ...]" ([{:keys [handlers] :as k8s}] (->> (filter (partial internals.client/preffered-version? k8s) handlers) (group-by internals.client/kind) (map (fn [[kind handlers]] (vec (cons (keyword kind) (mapv (juxt internals.client/action :summary) handlers))))) (sort-by (comp str first)) vec)) ([k8s kind] (->> (explore k8s) (misc/find-first #(= kind (first %))) vec))) (defn request "Returns the map that is passed to org.httpkit.client/request function. Used mostly for debugging. For customizing this, use the :interceptors option while creating an client" [k8s {:keys [request] :as params}] (if-let [action (internals.client/find-preferred-route k8s (dissoc params :request))] (martian/request-for k8s action (or request {})) (throw (ex-info "Could not find action" {:search (dissoc params :request)})))) (defn info "Returns everything on a specific action, including request and response schemas" [k8s params] (martian/explore k8s (internals.client/find-preferred-route k8s (dissoc params :request))))
true
(ns kubernetes-api.core (:require [kubernetes-api.extensions.custom-resource-definition :as crd] [kubernetes-api.interceptors.auth :as interceptors.auth] [kubernetes-api.interceptors.raise :as interceptors.raise] [kubernetes-api.internals.client :as internals.client] [kubernetes-api.internals.martian :as internals.martian] [kubernetes-api.misc :as misc] [kubernetes-api.swagger :as swagger] [martian.core :as martian] [martian.httpkit :as martian-httpkit] martian.swagger)) (defn client "Creates a Kubernetes Client compliant with martian api and its helpers host - a string url to the kubernetes cluster Options: [Authentication] :basic-auth - a map with plain text username/password :token - oauth token string without Bearer prefix :token-fn - a single-argument function that receives this opts and returns a token :client-cert/:ca-cert/:client-key - string filepath indicating certificates and key files to configure client cert. :insecure? - ignore self-signed server certificates [Custom] :interceptors - additional interceptors to the martian's client Example: (client \"https://kubernetes.docker.internal:6443\" {:basic-auth {:username \"admin\" :password \"PI:PASSWORD:<PASSWORD>END_PI\"}})" [host opts] (let [interceptors (concat [(interceptors.raise/new opts) (interceptors.auth/new opts)] (:interceptors opts) martian-httpkit/default-interceptors) k8s (internals.client/pascal-case-routes (martian/bootstrap-swagger host (or (swagger/from-api host opts) (swagger/read)) {:interceptors interceptors}))] (assoc k8s ::api-group-list (internals.martian/response-for k8s :GetApiVersions) ::core-api-versions (internals.martian/response-for k8s :GetCoreApiVersions)))) (defn invoke "Invoke a action on kubernetes api Parameters: :kind - a keyword identifing a kubernetes entity :action - each entity can have different subset of action. Examples: :create :update :patch :list :get :delete :deletecollection :request - to check what is this use kubernetes-api.core/info function Example: (invoke k8s {:kind :Deployment :action :create :request {:namespace \"default\" :body {:apiVersion \"v1\", ...}})" [k8s {:keys [request] :as params}] (if-let [action (internals.client/find-preferred-route k8s (dissoc params :request))] (internals.martian/response-for k8s action (or request {})) (throw (ex-info "Could not find action" {:search (dissoc params :request)})))) (defn extend-client "Extend a Kubernetes Client to support CustomResourceDefinitions Example: (extend-client k8s {:api \"tekton.dev\" :version \"v1alpha1\"})" [k8s {:keys [api version] :as extension-api}] (let [api-resources (internals.martian/response-for k8s :GetArbitraryApiResources {:api api :version version}) crds (internals.martian/response-for k8s :ListApiextensionsV1beta1CustomResourceDefinition)] (internals.client/pascal-case-routes (update k8s :handlers #(concat % (martian.swagger/swagger->handlers (crd/swagger-from extension-api api-resources crds))))))) (defn explore "Return a data structure with all actions performable on Kubernetes API, organized per kind and per action Examples: (explore k8s) => [[:Deployment [:get \"some description\"] ...] [:Service [:create \"other description\"] ...]] (explore k8s :Deployment) => [:Deployment [:create \"description\"] ...]" ([{:keys [handlers] :as k8s}] (->> (filter (partial internals.client/preffered-version? k8s) handlers) (group-by internals.client/kind) (map (fn [[kind handlers]] (vec (cons (keyword kind) (mapv (juxt internals.client/action :summary) handlers))))) (sort-by (comp str first)) vec)) ([k8s kind] (->> (explore k8s) (misc/find-first #(= kind (first %))) vec))) (defn request "Returns the map that is passed to org.httpkit.client/request function. Used mostly for debugging. For customizing this, use the :interceptors option while creating an client" [k8s {:keys [request] :as params}] (if-let [action (internals.client/find-preferred-route k8s (dissoc params :request))] (martian/request-for k8s action (or request {})) (throw (ex-info "Could not find action" {:search (dissoc params :request)})))) (defn info "Returns everything on a specific action, including request and response schemas" [k8s params] (martian/explore k8s (internals.client/find-preferred-route k8s (dissoc params :request))))
[ { "context": "et! !viewers {})\n\n;; heavily inspired by code from Thomas Heller in shadow-cljs, see\n;; https://github.com/thhelle", "end": 35186, "score": 0.9950361251831055, "start": 35173, "tag": "NAME", "value": "Thomas Heller" }, { "context": " Heller in shadow-cljs, see\n;; https://github.com/thheller/shadow-cljs/blob/1708acb21bcdae244b50293d17633ce3", "end": 35237, "score": 0.9961894154548645, "start": 35229, "tag": "USERNAME", "value": "thheller" }, { "context": "(->Form '(fn [name] (html [:<> \"Hello \" name]))) \"James\"))\n#_(apply-viewers (with-viewers [{:pred (consta", "end": 39056, "score": 0.9995536208152771, "start": 39051, "tag": "NAME", "value": "James" }, { "context": "h-viewer '(fn [name] (html [:<> \"Hello \" name])) \"James\")))\n\n(defn desc->values\n \"Takes a `description` ", "end": 47501, "score": 0.9367284178733826, "start": 47496, "tag": "NAME", "value": "James" }, { "context": "-viewer :table (normalize-table-data (repeat 60 [\"Adelie\" \"Biscoe\" 50 30 200 5000 :female])))))\n\n(defn pat", "end": 48249, "score": 0.9991273283958435, "start": 48243, "tag": "NAME", "value": "Adelie" }, { "context": "table (normalize-table-data (repeat 60 [\"Adelie\" \"Biscoe\" 50 30 200 5000 :female])))))\n\n(defn path-to-valu", "end": 48258, "score": 0.9987855553627014, "start": 48252, "tag": "NAME", "value": "Biscoe" } ]
src/nextjournal/clerk/viewer.cljc
nextjournal/clerk
598
(ns nextjournal.clerk.viewer (:require [clojure.string :as str] [clojure.pprint :as pprint] [clojure.datafy :as datafy] [clojure.set :as set] [clojure.walk :as w] #?@(:clj [[clojure.repl :refer [demunge]] [nextjournal.clerk.config :as config] [nextjournal.clerk.hashing :as hashing]] :cljs [[reagent.ratom :as ratom]]) [nextjournal.markdown :as md] [nextjournal.markdown.transform :as md.transform] [lambdaisland.uri.normalize :as uri.normalize]) #?(:clj (:import (clojure.lang IDeref) (java.lang Throwable) (java.awt.image BufferedImage) (javax.imageio ImageIO) (java.util Base64)))) (defrecord ViewerEval [form]) (defrecord ViewerFn [form #?(:cljs f)] #?@(:cljs [IFn (-invoke [this x] ((:f this) x)) (-invoke [this x y] ((:f this) x y))])) (defn viewer-fn? [x] (instance? ViewerFn x)) (defn ->viewer-fn [form] (map->ViewerFn {:form form #?@(:cljs [:f (eval form)])})) (defn ->viewer-eval [form] (map->ViewerEval {:form form})) #?(:clj (defmethod print-method ViewerFn [v ^java.io.Writer w] (.write w (str "#viewer-fn " (pr-str `~(:form v)))))) #?(:clj (defmethod print-method ViewerEval [v ^java.io.Writer w] (.write w (str "#viewer-eval " (pr-str `~(:form v)))))) #_(binding [*data-readers* {'viewer-fn ->viewer-fn}] (read-string (pr-str (->viewer-fn '(fn [x] x))))) #_(binding [*data-readers* {'viewer-fn ->viewer-fn}] (read-string (pr-str (->viewer-fn 'number?)))) (comment (def num? (form->fn+form 'number?)) (num? 42) (:form num?) (pr-str num?)) (defn wrapped-value? "Tests if `x` is a map containing a `:nextjournal/value`." [x] (and (map? x) ;; can throw for `sorted-map` (try (contains? x :nextjournal/value) (catch #?(:clj Exception :cljs js/Error) _e false)))) (defn ensure-wrapped "Ensures `x` is wrapped in a map under a `:nextjournal/value` key." ([x] (if (wrapped-value? x) x {:nextjournal/value x})) ([x v] (-> x ensure-wrapped (assoc :nextjournal/viewer v)))) #_(ensure-wrapped 123) #_(ensure-wrapped {:nextjournal/value 456}) (defn ->value "Takes `x` and returns the `:nextjournal/value` from it, or otherwise `x` unmodified." [x] (if (wrapped-value? x) (:nextjournal/value x) x)) #_(->value (with-viewer :code '(+ 1 2 3))) #_(->value 123) (defn ->viewer "Returns the `:nextjournal/viewer` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/viewer x))) #_(->viewer (with-viewer :code '(+ 1 2 3))) #_(->viewer "123") (defn ->viewers "Returns the `:nextjournal/viewers` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/viewers x))) (defn width "Returns the `:nextjournal/width` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/width x))) (defn normalize-viewer-opts [opts] (when-not (map? opts) (throw (ex-info "normalize-viewer-opts not passed `map?` opts" {:opts opts}))) (set/rename-keys opts {:nextjournal.clerk/viewer :nextjournal/viewer :nextjournal.clerk/viewers :nextjournal/viewers :nextjournal.clerk/opts :nextjournal/opts :nextjournal.clerk/width :nextjournal/width})) (defn normalize-viewer [viewer] (cond (keyword? viewer) viewer (map? viewer) viewer (or (symbol? viewer) (seq? viewer) #?(:cljs (fn? viewer))) {:render-fn viewer} #?@(:clj [(fn? viewer) {:transform-fn viewer}]) :else (throw (ex-info "cannot normalize viewer" {:viewer viewer})))) #_(normalize-viewer '#(v/html [:h3 "Hello " % "!"])) #_(normalize-viewer :latex) #_(normalize-viewer {:render-fn '#(v/html [:h3 "Hello " % "!"]) :transform-fn identity}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; public api (defn with-viewer "Wraps the given value `x` and associates it with the given `viewer`. Takes an optional second `viewer-opts` arg." ([viewer x] (with-viewer viewer nil x)) ([viewer viewer-opts x] (merge (when viewer-opts (normalize-viewer-opts viewer-opts)) (-> x ensure-wrapped (assoc :nextjournal/viewer (normalize-viewer viewer)))))) ;; TODO: Think of a better name (defn with-viewer-extracting-opts [viewer & opts+items] (cond (and (map? (first opts+items)) (not (wrapped-value? (first opts+items)))) (with-viewer viewer (first opts+items) (rest opts+items)) (and (sequential? (first opts+items)) (= 1 (count opts+items))) (apply (partial with-viewer viewer) opts+items) :else (with-viewer viewer opts+items))) #_(with-viewer :latex "x^2") #_(with-viewer '#(v/html [:h3 "Hello " % "!"]) "x^2") (defn with-viewers "Binds viewers to types, eg {:boolean view-fn}" [viewers x] (-> x ensure-wrapped (assoc :nextjournal/viewers viewers))) #_(->> "x^2" (with-viewer :latex) (with-viewers [{:name :latex :render-fn :mathjax}])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; table viewer normalization (defn rpad-vec [v length padding] (vec (take length (concat v (repeat padding))))) (def missing-pred :nextjournal/missing) (defn normalize-seq-of-seq [s] (let [max-count (count (apply max-key count s))] {:rows (mapv #(rpad-vec (->value %) max-count missing-pred) s)})) (defn normalize-seq-of-map [s] (let [ks (->> s (mapcat keys) distinct vec)] {:head ks :rows (mapv (fn [m] (mapv #(get m % missing-pred) ks)) s)})) (defn normalize-map-of-seq [m] (let [ks (-> m keys vec) m* (if (seq? (get m (first ks))) (reduce (fn [acc [k s]] (assoc acc k (vec s))) {} m) m)] {:head ks :rows (->> (range (count (val (apply max-key (comp count val) m*)))) (mapv (fn [i] (mapv #(get-in m* [% i] missing-pred) ks))))})) (defn normalize-seq-to-vec [{:keys [head rows]}] (cond-> {:rows (vec rows)} head (assoc :head (vec head)))) (defn use-headers [s] (let [{:as table :keys [rows]} (normalize-seq-of-seq s)] (-> table (assoc :head (first rows)) (update :rows rest)))) (defn normalize-table-data [data] (cond (and (map? data) (-> data :rows sequential?)) (normalize-seq-to-vec data) (and (map? data) (sequential? (first (vals data)))) (normalize-map-of-seq data) (and (sequential? data) (map? (first data))) (normalize-seq-of-map data) (and (sequential? data) (sequential? (first data))) (normalize-seq-of-seq data) :else nil)) (defn demunge-ex-data [ex-data] (update ex-data :trace (fn [traces] (mapv #(update % 0 (comp demunge pr-str)) traces)))) #_(demunge-ex-data (datafy/datafy (ex-info "foo" {:bar :baz}))) (declare present present* !viewers apply-viewers apply-viewers* ensure-wrapped-with-viewers process-viewer process-wrapped-value default-viewers find-named-viewer) (defn inspect-fn [] #?(:clj (->viewer-eval 'v/inspect) :cljs (eval 'v/inspect))) (defn when-wrapped [f] #(cond-> % (wrapped-value? %) f)) (defn inspect-wrapped-value [wrapped-value] [(inspect-fn) (-> wrapped-value apply-viewers process-wrapped-value)]) #_(w/postwalk (when-wrapped inspect-wrapped-value) [1 2 {:a [3 (with-viewer :latex "\\alpha")]} 4]) (defn mark-presented [wrapped-value] (assoc wrapped-value :nextjournal/presented? true)) (defn mark-preserve-keys [wrapped-value] (assoc wrapped-value :nextjournal/preserve-keys? true)) (defn fetch-all [_opts _xs] (throw (ex-info "`fetch-all` is deprecated, please use a `:transform-fn` with `mark-presented` instead." {}))) (defn get-safe ([key] #(get-safe % key)) ([map key] (when (map? map) (try (get map key) ;; can throw for e.g. sorted-map (catch #?(:clj Exception :cljs js/Error) _e nil))))) (def var-from-def? (get-safe :nextjournal.clerk/var-from-def)) (def datafied? (get-safe :nextjournal.clerk/datafied)) (defn with-md-viewer [wrapped-value] (let [{:as node :keys [type]} (->value wrapped-value)] (when-not type (throw (ex-info "no type given for with-md-viewer" {:wrapped-value wrapped-value}))) (with-viewer (keyword "nextjournal.markdown" (name type)) wrapped-value))) (defn into-markup [markup] (fn [{:as wrapped-value :nextjournal/keys [viewers]}] (-> (with-viewer {:name :html- :render-fn 'v/html} wrapped-value) mark-presented (update :nextjournal/value (fn [{:as node :keys [text content]}] (into (cond-> markup (fn? markup) (apply [node])) (cond text [text] content (mapv #(-> (with-md-viewer %) (assoc :nextjournal/viewers viewers) (apply-viewers) (as-> w (if (= :html- (:name (->viewer w))) (->value w) [(inspect-fn) (process-wrapped-value w)]))) content)))))))) #?(:clj (defn ->edn [x] (binding [*print-namespace-maps* false] (pr-str x)))) #_(->edn {:nextjournal/value :foo}) #?(:clj (defn base64-encode-value [{:as result :nextjournal/keys [content-type]}] (update result :nextjournal/value (fn [data] (str "data:" content-type ";base64, " (.encodeToString (Base64/getEncoder) data)))))) (defn apply-viewer-unwrapping-var-from-def [{:as result :nextjournal/keys [value viewer]}] (if viewer (let [{:keys [transform-fn]} (and (map? viewer) viewer) value (if (and (not transform-fn) (get value :nextjournal.clerk/var-from-def)) (-> value :nextjournal.clerk/var-from-def deref) value)] (assoc result :nextjournal/value (if (or (var? viewer) (fn? viewer)) (viewer value) {:nextjournal/value value :nextjournal/viewer (normalize-viewer viewer)}))) result)) #_(apply-viewer-unwrapping-var-from-def {:nextjournal/value [:h1 "hi"] :nextjournal/viewer :html}) #_(apply-viewer-unwrapping-var-from-def {:nextjournal/value [:h1 "hi"] :nextjournal/viewer (resolve 'nextjournal.clerk/html)}) #?(:clj (defn extract-blobs [lazy-load? blob-id presentd-result] (w/postwalk #(cond-> % (and (get % :nextjournal/content-type) lazy-load?) (assoc :nextjournal/value {:blob-id blob-id :path (:path %)}) (and (get % :nextjournal/content-type) (not lazy-load?)) base64-encode-value) presentd-result))) (defn get-default-viewers [] (:default @!viewers default-viewers)) (defn get-viewers ([scope] (get-viewers scope nil)) ([scope value] (or (when value (->viewers value)) (when scope (@!viewers scope)) (get-default-viewers)))) #_(get-viewers nil nil) #?(:clj (defn ->result [{:keys [inline-results?]} {:as result :nextjournal/keys [value blob-id viewers]}] (let [lazy-load? (and (not inline-results?) blob-id) presentd-result (extract-blobs lazy-load? blob-id (present (ensure-wrapped-with-viewers (or viewers (get-viewers *ns*)) value))) opts-from-form-meta (select-keys result [:nextjournal/width :nextjournal/opts])] (merge {:nextjournal/viewer :clerk/result :nextjournal/value (cond-> (try {:nextjournal/edn (->edn (merge presentd-result opts-from-form-meta))} (catch Throwable _e {:nextjournal/string (pr-str value)})) (-> presentd-result ->viewer :name) (assoc :nextjournal/viewer (select-keys (->viewer presentd-result) [:name])) lazy-load? (assoc :nextjournal/fetch-opts {:blob-id blob-id} :nextjournal/hash (hashing/->hash-str [blob-id presentd-result opts-from-form-meta])))} (dissoc presentd-result :nextjournal/value :nextjournal/viewer :nextjournal/viewers) ;; TODO: consider dropping this. Still needed by notebook-viewer fn to read :nextjournal/width option on result blocks opts-from-form-meta)))) (defn result-hidden? [result] (= :hide-result (-> result ->value ->viewer))) (defn ->display [{:as code-cell :keys [result ns?]}] (let [{:nextjournal.clerk/keys [visibility]} result result? (and (contains? code-cell :result) (not (result-hidden? result)) (not (contains? visibility :hide-ns)) (not (and ns? (contains? visibility :hide)))) fold? (and (not (contains? visibility :hide-ns)) (or (contains? visibility :fold) (contains? visibility :fold-ns))) code? (or fold? (contains? visibility :show))] {:result? result? :fold? fold? :code? code?})) #_(->display {:result {:nextjournal.clerk/visibility #{:fold :hide-ns}}}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold-ns}}}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold}} :ns? true}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide} :nextjournal/value {:nextjournal/viewer :hide-result}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide}} :ns? true}) #?(:clj (defn with-block-viewer [doc {:as cell :keys [type]}] (case type :markdown [(with-viewer :markdown (:doc cell))] :code (let [{:as cell :keys [result]} (update cell :result apply-viewer-unwrapping-var-from-def) {:as display-opts :keys [code? result?]} (->display cell)] (cond-> [] code? (conj (with-viewer :clerk/code-block ;; TODO: display analysis could be merged into cell earlier (-> cell (merge display-opts) (dissoc :result)))) result? (conj (->result doc result))))))) (defn update-viewers [viewers select-fn->update-fn] (reduce (fn [viewers [pred update-fn]] (mapv (fn [viewer] (cond-> viewer (pred viewer) update-fn)) viewers)) viewers select-fn->update-fn)) #_(update-viewers default-viewers {:fetch-opts #(dissoc % :fetch-opts)}) (defn add-viewers ([added-viewers] (add-viewers (get-default-viewers) added-viewers)) ([viewers added-viewers] (into (vec added-viewers) viewers))) (def table-missing-viewer {:pred #{:nextjournal/missing} :render-fn '(fn [x] (v/html [:<>]))}) (def table-markup-viewer {:name :table/markup :render-fn '(fn [head+body opts] (v/html (into [:table.text-xs.sans-serif.text-gray-900.dark:text-white.not-prose] (v/inspect-children opts) head+body)))}) (def table-head-viewer {:name :table/head :render-fn '(fn [header-row {:as opts :keys [path number-col?]}] (v/html [:thead.border-b.border-gray-300.dark:border-slate-700 (into [:tr] (map-indexed (fn [i {:as header-cell :nextjournal/keys [value]}] (let [title (when (or (string? value) (keyword? value) (symbol? value)) value)] [:th.relative.pl-6.pr-2.py-1.align-bottom.font-medium (cond-> {:class (when (number-col? i) "text-right")} title (assoc :title title)) [:div.flex.items-center (v/inspect opts header-cell)]]))) header-row)]))}) (def table-body-viewer {:name :table/body :fetch-opts {:n 20} :render-fn '(fn [rows opts] (v/html (into [:tbody] (map-indexed (fn [idx row] (v/inspect (update opts :path conj idx) row))) rows)))}) (def table-row-viewer {:name :table/row :render-fn '(fn [row {:as opts :keys [path number-col?]}] (v/html (into [:tr.hover:bg-gray-200.dark:hover:bg-slate-700 {:class (if (even? (peek path)) "bg-black/5 dark:bg-gray-800" "bg-white dark:bg-gray-900")}] (map-indexed (fn [idx cell] [:td.pl-6.pr-2.py-1 (when (number-col? idx) {:class "text-right"}) (v/inspect opts cell)])) row)))}) (defn update-table-viewers [viewers] (-> viewers (update-viewers {(comp #{string?} :pred) #(assoc % :render-fn (quote v/string-viewer)) (comp #{number?} :pred) #(assoc % :render-fn '(fn [x] (v/html [:span.tabular-nums (if (js/Number.isNaN x) "NaN" (str x))]))) (comp #{:elision} :name) #(assoc % :render-fn '(fn [{:as fetch-opts :keys [total offset unbounded?]} {:keys [num-cols]}] (v/html [v/consume-view-context :fetch-fn (fn [fetch-fn] [:tr.border-t.dark:border-slate-700 [:td.text-center.py-1 {:col-span num-cols :class (if (fn? fetch-fn) "bg-indigo-50 hover:bg-indigo-100 dark:bg-gray-800 dark:hover:bg-slate-700 cursor-pointer" "text-gray-400 text-slate-500") :on-click (fn [_] (when (fn? fetch-fn) (fetch-fn fetch-opts)))} (- total offset) (when unbounded? "+") (if (fn? fetch-fn) " more…" " more elided")]])])))}) (add-viewers [table-missing-viewer table-markup-viewer table-head-viewer table-body-viewer table-row-viewer]))) #?(:clj (def utc-date-format ;; from `clojure.instant/thread-local-utc-date-format` (doto (java.text.SimpleDateFormat. "yyyy-MM-dd'T'HH:mm:ss.SSS-00:00") (.setTimeZone (java.util.TimeZone/getTimeZone "GMT"))))) #?(:clj (defn datafy-scope [scope] (cond (instance? clojure.lang.Namespace scope) {:namespace (-> scope str keyword)} (keyword? scope) scope :else (throw (ex-info (str "Unsupported scope " scope) {:scope scope}))))) #_(datafy-scope *ns*) #_(datafy-scope #'datafy-scope) (defn update-val [f & args] (fn [wrapped-value] (apply update wrapped-value :nextjournal/value f args))) #_((update-val + 1) {:nextjournal/value 41}) (def markdown-viewers [{:name :nextjournal.markdown/doc :transform-fn (into-markup [:div.viewer-markdown])} ;; blocks {:name :nextjournal.markdown/heading :transform-fn (into-markup (fn [{:as node :keys [heading-level]}] [(str "h" heading-level) {:id (uri.normalize/normalize-fragment (md.transform/->text node))}]))} {:name :nextjournal.markdown/image :transform-fn #(with-viewer :html [:img.inline (-> % ->value :attrs)])} {:name :nextjournal.markdown/blockquote :transform-fn (into-markup [:blockquote])} {:name :nextjournal.markdown/paragraph :transform-fn (into-markup [:p])} {:name :nextjournal.markdown/plain :transform-fn (into-markup [:<>])} {:name :nextjournal.markdown/ruler :transform-fn (into-markup [:hr])} {:name :nextjournal.markdown/code :transform-fn (fn [wrapped-value] (with-viewer :html [:div.viewer-code (with-viewer :code (md.transform/->text (->value wrapped-value)))]))} ;; marks {:name :nextjournal.markdown/em :transform-fn (into-markup [:em])} {:name :nextjournal.markdown/strong :transform-fn (into-markup [:strong])} {:name :nextjournal.markdown/monospace :transform-fn (into-markup [:code])} {:name :nextjournal.markdown/strikethrough :transform-fn (into-markup [:s])} {:name :nextjournal.markdown/link :transform-fn (into-markup #(vector :a (:attrs %)))} {:name :nextjournal.markdown/internal-link :transform-fn (into-markup #(vector :a {:href (str "#" (:text %))}))} {:name :nextjournal.markdown/hashtag :transform-fn (into-markup #(vector :a {:href (str "#" (:text %))}))} ;; inlines {:name :nextjournal.markdown/text :transform-fn (into-markup [:span])} {:name :nextjournal.markdown/softbreak :transform-fn (fn [_] (with-viewer :html [:span " "]))} #?(:clj {:name :nextjournal.markdown/inline :transform-fn (comp eval read-string md.transform/->text)}) ;; formulas {:name :nextjournal.markdown/formula :transform-fn (comp :text ->value) :render-fn '(fn [tex] (v/katex-viewer tex {:inline? true}))} {:name :nextjournal.markdown/block-formula :transform-fn (comp :text ->value) :render-fn 'v/katex-viewer} ;; lists {:name :nextjournal.markdown/bullet-list :transform-fn (into-markup [:ul])} {:name :nextjournal.markdown/numbered-list :transform-fn (into-markup [:ol])} {:name :nextjournal.markdown/todo-list :transform-fn (into-markup [:ul.contains-task-list])} {:name :nextjournal.markdown/list-item :transform-fn (into-markup [:li])} {:name :nextjournal.markdown/todo-item :transform-fn (into-markup (fn [{:keys [attrs]}] [:li [:input {:type "checkbox" :default-checked (:checked attrs)}]]))} ;; tables {:name :nextjournal.markdown/table :transform-fn (into-markup [:table])} {:name :nextjournal.markdown/table-head :transform-fn (into-markup [:thead])} {:name :nextjournal.markdown/table-body :transform-fn (into-markup [:tbody])} {:name :nextjournal.markdown/table-row :transform-fn (into-markup [:tr])} {:name :nextjournal.markdown/table-header :transform-fn (into-markup #(vector :th {:style (md.transform/table-alignment (:attrs %))}))} {:name :nextjournal.markdown/table-data :transform-fn (into-markup #(vector :td {:style (md.transform/table-alignment (:attrs %))}))} ;; ToC via [[TOC]] placeholder ignored {:name :nextjournal.markdown/toc :transform-fn (into-markup [:div.toc])} ;; sidenotes {:name :nextjournal.markdown/sidenote :transform-fn (into-markup (fn [{:keys [attrs]}] [:span.sidenote [:sup {:style {:margin-right "3px"}} (-> attrs :ref inc)]]))} {:name :nextjournal.markdown/sidenote-ref :transform-fn (into-markup [:sup.sidenote-ref])}]) (def char-viewer {:pred char? :render-fn '(fn [c] (v/html [:span.cmt-string.inspected-value "\\" c]))}) (def string-viewer {:pred string? :render-fn (quote v/quoted-string-viewer) :fetch-opts {:n 80}}) (def number-viewer {:pred number? :render-fn (quote v/number-viewer)}) (def number-hex-viewer {:name :number-hex :render-fn '(fn [num] (v/number-viewer (str "0x" (.toString (js/Number. num) 16))))}) (def symbol-viewer {:pred symbol? :render-fn '(fn [x] (v/html [:span.cmt-keyword.inspected-value (str x)]))}) (def keyword-viewer {:pred keyword? :render-fn '(fn [x] (v/html [:span.cmt-atom.inspected-value (str x)]))}) (def nil-viewer {:pred nil? :render-fn '(fn [_] (v/html [:span.cmt-default.inspected-value "nil"]))}) (def boolean-viewer {:pred boolean? :render-fn '(fn [x] (v/html [:span.cmt-bool.inspected-value (str x)]))}) (def map-entry-viewer {:pred map-entry? :name :map-entry :render-fn '(fn [xs opts] (v/html (into [:<>] (comp (v/inspect-children opts) (interpose " ")) xs))) :fetch-opts {:n 2}}) (def var-from-def-viewer {:pred var-from-def? :transform-fn (update-val (comp deref :nextjournal.clerk/var-from-def))}) (def read+inspect-viewer {:name :read+inspect :render-fn '(fn [x] (try (v/html [v/inspect-paginated (v/read-string x)]) (catch js/Error _e (v/unreadable-edn-viewer x))))}) (def vector-viewer {:pred vector? :render-fn 'v/coll-viewer :opening-paren "[" :closing-paren "]" :fetch-opts {:n 20}}) (def set-viewer {:pred set? :render-fn 'v/coll-viewer :opening-paren "#{" :closing-paren "}" :fetch-opts {:n 20}}) (def sequential-viewer {:pred sequential? :render-fn 'v/coll-viewer :opening-paren "(" :closing-paren ")" :fetch-opts {:n 20}}) (def map-viewer {:pred map? :name :map :render-fn 'v/map-viewer :opening-paren "{" :closing-paren "}" :fetch-opts {:n 10}}) (def var-viewer {:pred var? :transform-fn (comp symbol ->value) :render-fn '(fn [x] (v/html [:span.inspected-value [:span.cmt-meta "#'" (str x)]]))}) (def throwable-viewer {:pred (fn [e] (instance? #?(:clj Throwable :cljs js/Error) e)) :name :error :render-fn (quote v/throwable-viewer) :transform-fn (comp mark-presented (update-val (comp demunge-ex-data datafy/datafy)))}) (def buffered-image-viewer #?(:clj {:pred #(instance? BufferedImage %) :transform-fn (fn [{image :nextjournal/value}] (let [stream (java.io.ByteArrayOutputStream.) w (.getWidth image) h (.getHeight image) r (float (/ w h))] (ImageIO/write image "png" stream) (-> {:nextjournal/value (.toByteArray stream) :nextjournal/content-type "image/png" :nextjournal/width (if (and (< 2 r) (< 900 w)) :full :wide)} mark-presented))) :render-fn '(fn [blob] (v/html [:figure.flex.flex-col.items-center.not-prose [:img {:src (v/url-for blob)}]]))})) (def ideref-viewer {:pred #(instance? IDeref %) :transform-fn (fn [wrapped-value] (with-viewer :tagged-value {:tag "object" :value (let [r (->value wrapped-value)] (vector (type r) #?(:clj (with-viewer :number-hex (System/identityHashCode r))) (if-let [deref-as-map (resolve 'clojure.core/deref-as-map)] (deref-as-map r) r)))}))}) (def regex-viewer {:pred #?(:clj (partial instance? java.util.regex.Pattern) :cljs regexp?) :transform-fn (fn [wrapped-value] (with-viewer :tagged-value {:tag "" :value (let [regex (->value wrapped-value)] #?(:clj (.pattern regex) :cljs (.-source regex)))}))}) (def fallback-viewer {:pred (constantly :true) :transform-fn (update-val #(with-viewer :read+inspect (pr-str %)))}) (def elision-viewer {:name :elision :render-fn (quote v/elision-viewer) :transform-fn mark-presented}) (def katex-viewer {:name :latex :render-fn (quote v/katex-viewer) :transform-fn mark-presented}) (def mathjax-viewer {:name :mathjax :render-fn (quote v/mathjax-viewer) :transform-fn mark-presented}) (def html-viewer {:name :html :render-fn (quote v/html) :transform-fn (comp mark-presented (update-val (partial w/postwalk (when-wrapped inspect-wrapped-value))))}) (def plotly-viewer {:name :plotly :render-fn (quote v/plotly-viewer) :transform-fn mark-presented}) (def vega-lite-viewer {:name :vega-lite :render-fn (quote v/vega-lite-viewer) :transform-fn mark-presented}) (def markdown-viewer {:name :markdown :transform-fn (fn [wrapped-value] (-> wrapped-value mark-presented (update :nextjournal/value #(cond->> % (string? %) md/parse)) (update :nextjournal/viewers add-viewers markdown-viewers) (with-md-viewer)))}) (def code-viewer {:name :code :render-fn (quote v/code-viewer) :transform-fn (comp mark-presented (update-val (fn [v] (if (string? v) v (str/trim (with-out-str (pprint/pprint v)))))))}) (def code-folded-viewer {:name :code-folded :render-fn (quote v/foldable-code-viewer) :transform-fn (comp mark-presented (update-val (fn [v] (if (string? v) v (with-out-str (pprint/pprint v))))))}) (def reagent-viewer {:name :reagent :render-fn (quote v/reagent-viewer) :transform-fn mark-presented}) (def row-viewer {:name :row :render-fn '(fn [items opts] (let [item-count (count items)] (v/html (into [:div {:class "md:flex md:flex-row md:gap-4 not-prose" :style opts}] (map (fn [item] [:div.flex.items-center.justify-center.flex-auto (v/inspect opts item)])) items))))}) (def col-viewer {:name :col :render-fn '(fn [items opts] (v/html (into [:div {:class "md:flex md:flex-col md:gap-4 clerk-grid not-prose" :style opts}] (map (fn [item] [:div.flex.items-center.justify-center (v/inspect opts item)])) items)))}) (def table-viewer {:name :table :transform-fn (fn [wrapped-value] (if-let [{:keys [head rows]} (normalize-table-data (->value wrapped-value))] (-> wrapped-value (assoc :nextjournal/viewer :table/markup) (update :nextjournal/width #(or % :wide)) (update :nextjournal/viewers update-table-viewers) (assoc :nextjournal/opts {:num-cols (-> rows first count) :number-col? (mapv number? (first rows))}) (assoc :nextjournal/value (cond->> [(with-viewer :table/body (map (partial with-viewer :table/row) rows))] head (cons (with-viewer :table/head head))))) (-> wrapped-value mark-presented (assoc :nextjournal/width :wide) (assoc :nextjournal/value [(present wrapped-value)]) (assoc :nextjournal/viewer {:render-fn 'v/table-error}))))}) (def table-error-viewer {:name :table-error :render-fn (quote v/table-error) :fetch-opts {:n 1}}) (def code-block-viewer {:name :clerk/code-block :transform-fn (fn [{:as wrapped-value :nextjournal/keys [value]}] (-> wrapped-value (assoc :nextjournal/viewer (if (:fold? value) :code-folded :code)) (update :nextjournal/value :text)))}) (def tagged-value-viewer {:name :tagged-value :render-fn '(fn [{:keys [tag value space?]}] (v/html (v/tagged-value {:space? space?} (str "#" tag) [v/inspect-paginated value]))) :transform-fn (fn [wrapped-value] (-> wrapped-value (update-in [:nextjournal/value :value] present) mark-presented))}) (def result-viewer {:name :clerk/result :render-fn (quote v/result-viewer) :transform-fn mark-presented}) #?(:clj (defn process-blocks [viewers {:as doc :keys [ns]}] (-> doc (update :blocks (partial into [] (comp (mapcat (partial with-block-viewer doc)) (map (comp #(vector (->ViewerEval 'v/inspect) %) process-wrapped-value apply-viewers* (partial ensure-wrapped-with-viewers viewers)))))) (select-keys [:blocks :toc :title]) (cond-> ns (assoc :scope (datafy-scope ns)))))) (def notebook-viewer {:name :clerk/notebook :render-fn (quote v/notebook-viewer) :transform-fn #?(:cljs identity :clj (fn [{:as wrapped-value :nextjournal/keys [viewers]}] (-> wrapped-value (update :nextjournal/value (partial process-blocks viewers)) mark-presented)))}) (def hide-result-viewer {:name :hide-result :transform-fn (fn [_] nil)}) (def default-viewers ;; maybe make this a sorted-map [char-viewer string-viewer number-viewer number-hex-viewer symbol-viewer keyword-viewer nil-viewer boolean-viewer map-entry-viewer var-from-def-viewer read+inspect-viewer vector-viewer set-viewer sequential-viewer map-viewer var-viewer throwable-viewer buffered-image-viewer ideref-viewer regex-viewer fallback-viewer elision-viewer katex-viewer mathjax-viewer html-viewer plotly-viewer vega-lite-viewer markdown-viewer code-viewer code-folded-viewer reagent-viewer row-viewer col-viewer table-viewer table-error-viewer code-block-viewer tagged-value-viewer result-viewer notebook-viewer hide-result-viewer]) (defonce ^{:doc "atom containing a map of and per-namespace viewers or `:defaults` overridden viewers."} !viewers (#?(:clj atom :cljs ratom/atom) {})) #_(reset! !viewers {}) ;; heavily inspired by code from Thomas Heller in shadow-cljs, see ;; https://github.com/thheller/shadow-cljs/blob/1708acb21bcdae244b50293d17633ce35a78a467/src/main/shadow/remote/runtime/obj_support.cljc#L118-L144 (defn rank-val [val] (reduce-kv (fn [res idx pred] (if (and (ifn? pred) (pred val)) (reduced idx) res)) -1 (into [] (map :pred) default-viewers))) (defn resilient-compare [a b] (try (compare a b) (catch #?(:clj Exception :cljs js/Error) _e (compare (rank-val a) (rank-val b))))) (defn ensure-sorted [xs] (cond (sorted? xs) xs (map? xs) (sort-by first resilient-compare xs) (set? xs) (sort resilient-compare xs) :else xs)) (defn find-viewer [viewers select-fn] (first (filter select-fn viewers))) #_(find-viewer default-viewers (comp #{string?} :pred)) #_(find-viewer default-viewers (comp #{:elision} :name)) (defn find-named-viewer [viewers viewer-name] (find-viewer viewers (comp #{viewer-name} :name))) #_(find-named-viewer default-viewers :elision) (defn viewer-for [viewers x] (or (when-let [selected-viewer (->viewer x)] (if (keyword? selected-viewer) (or (find-named-viewer viewers selected-viewer) (throw (ex-info (str "cannot find viewer named " selected-viewer) {:selected-viewer selected-viewer :viewers viewers}))) selected-viewer)) (find-viewer viewers (let [v (->value x)] (fn [{:keys [pred]}] (and (ifn? pred) (pred v))))) (throw (ex-info (str "cannot find matching viewer for value") {:value (->value x) :viewers viewers :x x})))) #_(viewer-for default-viewers [1 2 3]) #_(viewer-for default-viewers {:nextjournal/value [1 2 3]}) #_(viewer-for default-viewers 42) #_(viewer-for default-viewers (with-viewer :html [:h1 "Hello Hiccup"])) #_(viewer-for default-viewers (with-viewer {:transform-fn identity} [:h1 "Hello Hiccup"])) (defn ensure-wrapped-with-viewers ([x] (ensure-wrapped-with-viewers (get-viewers *ns*) x)) ([viewers x] (-> x ensure-wrapped (update :nextjournal/viewers (fn [x-viewers] (or x-viewers viewers)))))) #_(ensure-wrapped-with-viewers 42) #_(ensure-wrapped-with-viewers {:nextjournal/value 42 :nextjournal/viewers [:boo]}) (defn ->opts [wrapped-value] (select-keys wrapped-value [:nextjournal/width :nextjournal/opts :!budget :budget :path :current-path :offset])) (defn apply-viewers* [wrapped-value] (when (empty? (->viewers wrapped-value)) (throw (ex-info "cannot apply empty viewers" {:wrapped-value wrapped-value}))) (let [viewers (->viewers wrapped-value) {:as viewer :keys [render-fn transform-fn]} (viewer-for viewers wrapped-value) transformed-value (ensure-wrapped-with-viewers viewers (cond-> (dissoc wrapped-value :nextjournal/viewer) transform-fn transform-fn)) wrapped-value' (cond-> transformed-value (-> transformed-value ->value wrapped-value?) (merge (->value transformed-value)))] (if (and transform-fn (not render-fn)) (recur wrapped-value') (-> wrapped-value' (assoc :nextjournal/viewer viewer) (merge (->opts wrapped-value)))))) (defn apply-viewers [x] (apply-viewers* (ensure-wrapped-with-viewers x))) #_(apply-viewers 42) #_(apply-viewers {:one :two}) #_(apply-viewers {:one :two}) #_(apply-viewers [1 2 3]) #_(apply-viewers (range 3)) #_(apply-viewers (clojure.java.io/file "notebooks")) #_(apply-viewers (md "# Hello")) #_(apply-viewers (html [:h1 "hi"])) #_(apply-viewers (with-viewer :elision {:remaining 10 :count 30 :offset 19})) #_(apply-viewers (with-viewer (->Form '(fn [name] (html [:<> "Hello " name]))) "James")) #_(apply-viewers (with-viewers [{:pred (constantly true) :render-fn '(fn [x] [:h1 "hi"])}] 42)) (defn count-viewers "Helper function to walk a given `x` and replace the viewers with their counts. Useful for debugging." [x] (w/postwalk #(if (wrapped-value? %) (cond-> (dissoc % :!budget) (:nextjournal/viewers %) (-> #_% (update :nextjournal/viewers count) (set/rename-keys {:nextjournal/viewers :nextjournal/viewers-count}))) %) x)) (defn bounded-count-opts [n xs] (when-not (number? n) (throw (ex-info "n must be a number?" {:n n :xs xs}))) (let [limit (+ n #?(:clj config/*bounded-count-limit* :cljs 10000)) total (try (bounded-count limit xs) (catch #?(:clj Exception :cljs js/Error) _ nil))] (cond-> {} total (assoc :total total) (or (not total) (= total limit)) (assoc :unbounded? true)))) #_(bounded-count-opts 20 (range)) #_(bounded-count-opts 20 (range 3234567)) (defn drop+take-xf "Takes a map with optional `:n` and `:offset` and returns a transducer that drops `:offset` and takes `:n`." [{:keys [n offset] :or {offset 0}}] (cond-> (drop offset) (int? n) (comp (take n)))) #_(sequence (drop+take-xf {:n 10}) (range 100)) #_(sequence (drop+take-xf {:n 10 :offset 10}) (range 100)) #_(sequence (drop+take-xf {}) (range 9)) (declare assign-closing-parens) (defn process-render-fn [{:as viewer :keys [render-fn]}] (cond-> viewer (and render-fn (not (viewer-fn? render-fn))) (update :render-fn ->viewer-fn))) (defn process-viewer [viewer] (if-not (map? viewer) viewer (-> viewer (dissoc :pred :transform-fn :update-viewers-fn) process-render-fn))) #_(process-viewer {:render-fn '(v/html [:h1]) :transform-fn mark-presented}) (defn process-wrapped-value [wrapped-value] (-> wrapped-value (select-keys [:nextjournal/viewer :nextjournal/value :nextjournal/width :nextjournal/content-type :nextjournal/opts :path :offset :n]) (update :nextjournal/viewer process-viewer))) #_(process-wrapped-value (apply-viewers 42)) (defn make-elision [viewers fetch-opts] (->> (with-viewer :elision fetch-opts) (ensure-wrapped-with-viewers viewers) apply-viewers process-wrapped-value)) #_(make-elision default-viewers {:n 20}) (defn find-elision [desc] (->value (first (filter (comp #{:elision} :name :nextjournal/viewer) (tree-seq (some-fn map? vector?) #(cond-> % (map? %) vals) desc))))) (defn ->fetch-opts [wrapped-value] (merge (-> wrapped-value ->viewer :fetch-opts) (select-keys wrapped-value [:path :offset]))) (defn get-elision [wrapped-value] (let [{:as fetch-opts :keys [path offset n]} (->fetch-opts wrapped-value)] (merge fetch-opts (bounded-count-opts n (->value wrapped-value))))) #_(get-elision (present (range))) #_(get-elision (present "abc")) #_(get-elision (present (str/join (repeat 1000 "abc")))) (defn get-fetch-opts-n [wrapped-value] (-> wrapped-value ->fetch-opts :n)) (defn inherit-opts [{:as wrapped-value :nextjournal/keys [viewers]} value path-segment] (-> (ensure-wrapped-with-viewers viewers value) (merge (->opts wrapped-value)) (dissoc :offset) (update :path (fnil conj []) path-segment) (update :current-path (fnil conj []) path-segment))) (defn present+paginate-children [{:as wrapped-value :nextjournal/keys [viewers preserve-keys?] :keys [!budget budget]}] (let [{:as fetch-opts :keys [path offset n]} (->fetch-opts wrapped-value) xs (->value wrapped-value) paginate? (and (number? n) (not preserve-keys?)) fetch-opts' (cond-> fetch-opts (and paginate? !budget (not (map-entry? xs))) (update :n min @!budget)) children (if preserve-keys? (into {} (map (fn [[k v]] [k (present* (inherit-opts wrapped-value v k))])) xs) (into [] (comp (if paginate? (drop+take-xf fetch-opts') identity) (map-indexed (fn [i x] (present* (inherit-opts wrapped-value x (+ i (or offset 0)))))) (remove nil?)) (ensure-sorted xs))) {:as elision :keys [total unbounded?]} (and paginate? (get-elision wrapped-value)) new-offset (when paginate? (or (some-> children peek :path peek inc) 0))] (cond-> children (and paginate? (or unbounded? (< new-offset total))) (conj (let [fetch-opts (assoc elision :offset new-offset)] (make-elision viewers fetch-opts)))))) (defn present+paginate-string [{:as wrapped-value :nextjournal/keys [viewers viewer value]}] (let [{:as elision :keys [n total path offset]} (and (-> viewer :fetch-opts :n) (get-elision wrapped-value))] (if (and n (< n total)) (let [new-offset (min (+ (or offset 0) n) total)] (cond-> [(subs value (or offset 0) new-offset)] (pos? (- total new-offset)) (conj (let [fetch-opts (-> elision (assoc :offset new-offset :replace-path (conj path new-offset)))] (make-elision viewers fetch-opts))) true ensure-wrapped)) value))) (defn ^:private present* [{:as wrapped-value :keys [path current-path !budget] :nextjournal/keys [viewers]}] (when (empty? viewers) (throw (ex-info "cannot present* with empty viewers" {:wrapped-value wrapped-value}))) (let [{:as wrapped-value :nextjournal/keys [viewers presented?]} (apply-viewers* wrapped-value) descend? (< (count current-path) (count path)) xs (->value wrapped-value)] #_(prn :xs xs :type (type xs) :path path :current-path current-path :descend? descend?) (when (and !budget (not descend?) (not presented?)) (swap! !budget #(max (dec %) 0))) (-> (merge (->opts wrapped-value) (with-viewer (->viewer wrapped-value) (cond presented? wrapped-value descend? ;; TODO: can this be unified, simplified, or even dropped in favor of continuation? (let [idx (first (drop (count current-path) path))] (present* (-> (ensure-wrapped-with-viewers viewers (cond (and (map? xs) (keyword? idx)) (get xs idx) (or (map? xs) (set? xs)) (nth (seq (ensure-sorted xs)) idx) (associative? xs) (get xs idx) (sequential? xs) (nth xs idx))) (merge (->opts wrapped-value)) (update :current-path (fnil conj []) idx)))) (string? xs) (present+paginate-string wrapped-value) (and xs (seqable? xs)) (present+paginate-children wrapped-value) :else ;; leaf value xs))) process-wrapped-value))) (defn present "Returns a subset of a given `value`." ([x] (present x {})) ([x opts] (-> (ensure-wrapped-with-viewers x) (merge {:!budget (atom (:budget opts 200)) :path (:path opts []) :current-path (:current-path opts [])} opts) present* assign-closing-parens))) (comment (present 42) (present [42]) (-> (present (range 100)) ->value peek) (present {:hello [1 2 3]}) (present {:one [1 2 3] 1 2 3 4}) (present [1 2 [1 [2] 3] 4 5]) (present (clojure.java.io/file "notebooks")) (present {:viewers [{:pred sequential? :render-fn pr-str}]} (range 100)) (present (map vector (range))) (present (subs (slurp "/usr/share/dict/words") 0 1000)) (present (plotly {:data [{:z [[1 2 3] [3 2 1]] :type "surface"}]})) (present [(with-viewer :html [:h1 "hi"])]) (present (with-viewer :html [:ul (for [x (range 3)] [:li x])])) (present (range)) (present {1 [2]}) (present (with-viewer '(fn [name] (html [:<> "Hello " name])) "James"))) (defn desc->values "Takes a `description` and returns its value. Inverse of `present`. Mostly useful for debugging." [desc] (let [x (->value desc) viewer-name (-> desc ->viewer :name)] (cond (= viewer-name :elision) (with-meta '… x) (coll? x) (into (case viewer-name ;; TODO: fix table viewer (:map :table) {} (or (empty x) [])) (map desc->values) x) :else x))) #_(desc->values (present [1 [2 {:a :b} 2] 3 (range 100)])) #_(desc->values (present (table (mapv vector (range 30))))) #_(desc->values (present (with-viewer :table (normalize-table-data (repeat 60 ["Adelie" "Biscoe" 50 30 200 5000 :female]))))) (defn path-to-value [path] (conj (interleave path (repeat :nextjournal/value)) :nextjournal/value)) (defn merge-presentations [root more elision] (update-in root (path-to-value (:path elision)) (fn [value] (let [{:keys [offset path]} (-> value peek :nextjournal/value) path-from-value (conj path offset) path-from-more (or (:replace-path elision) ;; string case, TODO find a better way to unify (-> more :nextjournal/value first :path))] (when (not= path-from-value path-from-more) (throw (ex-info "paths mismatch" {:path-from-value path-from-value :path-from-more path-from-more :root root :more more :path-to-value (path-to-value (:path more)) :value value}))) (into (pop value) (:nextjournal/value more)))))) (defn assign-closing-parens ([node] (assign-closing-parens '() node)) ([closing-parens node] (let [value (->value node) viewer (->viewer node) closing (:closing-paren viewer) non-leaf? (and (vector? value) (wrapped-value? (first value))) defer-closing? (and non-leaf? (or (-> value last :nextjournal/viewer :closing-paren) ;; the last element can carry parens (and (= :map-entry (-> value last :nextjournal/viewer :name)) ;; the last element is a map entry whose value can carry parens (-> value last :nextjournal/value last :nextjournal/viewer :closing-paren))))] (cond-> (cond (not closing) node defer-closing? (update node :nextjournal/viewer dissoc :closing-paren) :else (update-in node [:nextjournal/viewer :closing-paren] cons closing-parens)) non-leaf? (update :nextjournal/value (fn [xs] (into [] (map-indexed (fn [i x] (assign-closing-parens (if (and defer-closing? (= (dec (count xs)) i)) (cond->> closing-parens closing (cons closing)) '()) x))) xs))))))) (defn reset-viewers! ([viewers] (reset-viewers! *ns* viewers)) ([scope viewers] (assert (or (#{:default} scope) #?(:clj (instance? clojure.lang.Namespace scope)))) (swap! !viewers assoc scope viewers))) (defn add-viewers! [viewers] (reset-viewers! *ns* (add-viewers (get-default-viewers) viewers)) viewers) (defn ^{:deprecated "0.8"} set-viewers! [viewers] (binding #?(:clj [*out* *err*] :cljs []) (prn "`set-viewers!` has been deprecated, please use `add-viewers!` or `reset-viewers!` instead.")) (add-viewers! viewers)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; public convenience api (def html (partial with-viewer :html)) (def md (partial with-viewer :markdown)) (def plotly (partial with-viewer :plotly)) (def vl (partial with-viewer :vega-lite)) (def table (partial with-viewer :table)) (def row (partial with-viewer-extracting-opts :row)) (def col (partial with-viewer-extracting-opts :col)) (def tex (partial with-viewer :latex)) (def hide-result (partial with-viewer :hide-result)) (def notebook (partial with-viewer :clerk/notebook)) (defn doc-url [path] (->viewer-eval (list 'v/doc-url path))) (def code (partial with-viewer :code)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; examples (def example-viewer {:transform-fn (fn [{:as wrapped-value :nextjournal/keys [viewers] :keys [path current-path]}] (-> wrapped-value mark-preserve-keys (assoc :nextjournal/viewer {:render-fn '(fn [{:keys [form val]} opts] (v/html [:div.flex.flex-wrap {:class "py-[7px]"} [:div [:div.bg-slate-100.px-2.rounded (v/inspect opts form)]] [:div.flex.mt-1 [:div.mx-2.font-sans.text-xs.text-slate-500 {:class "mt-[2px]"} "⇒"] (v/inspect opts val)]]))}) (update-in [:nextjournal/value :form] code)))}) (def examples-viewer {:transform-fn (update-val (fn [examples] (mapv (partial with-viewer example-viewer) examples))) :render-fn '(fn [examples opts] (v/html (into [:div.border-l-2.border-slate-300.pl-4 [:div.uppercase.tracking-wider.text-xs.font-sans.text-slate-500.mt-4.mb-2 "Examples"]] (v/inspect-children opts) examples)))})
50598
(ns nextjournal.clerk.viewer (:require [clojure.string :as str] [clojure.pprint :as pprint] [clojure.datafy :as datafy] [clojure.set :as set] [clojure.walk :as w] #?@(:clj [[clojure.repl :refer [demunge]] [nextjournal.clerk.config :as config] [nextjournal.clerk.hashing :as hashing]] :cljs [[reagent.ratom :as ratom]]) [nextjournal.markdown :as md] [nextjournal.markdown.transform :as md.transform] [lambdaisland.uri.normalize :as uri.normalize]) #?(:clj (:import (clojure.lang IDeref) (java.lang Throwable) (java.awt.image BufferedImage) (javax.imageio ImageIO) (java.util Base64)))) (defrecord ViewerEval [form]) (defrecord ViewerFn [form #?(:cljs f)] #?@(:cljs [IFn (-invoke [this x] ((:f this) x)) (-invoke [this x y] ((:f this) x y))])) (defn viewer-fn? [x] (instance? ViewerFn x)) (defn ->viewer-fn [form] (map->ViewerFn {:form form #?@(:cljs [:f (eval form)])})) (defn ->viewer-eval [form] (map->ViewerEval {:form form})) #?(:clj (defmethod print-method ViewerFn [v ^java.io.Writer w] (.write w (str "#viewer-fn " (pr-str `~(:form v)))))) #?(:clj (defmethod print-method ViewerEval [v ^java.io.Writer w] (.write w (str "#viewer-eval " (pr-str `~(:form v)))))) #_(binding [*data-readers* {'viewer-fn ->viewer-fn}] (read-string (pr-str (->viewer-fn '(fn [x] x))))) #_(binding [*data-readers* {'viewer-fn ->viewer-fn}] (read-string (pr-str (->viewer-fn 'number?)))) (comment (def num? (form->fn+form 'number?)) (num? 42) (:form num?) (pr-str num?)) (defn wrapped-value? "Tests if `x` is a map containing a `:nextjournal/value`." [x] (and (map? x) ;; can throw for `sorted-map` (try (contains? x :nextjournal/value) (catch #?(:clj Exception :cljs js/Error) _e false)))) (defn ensure-wrapped "Ensures `x` is wrapped in a map under a `:nextjournal/value` key." ([x] (if (wrapped-value? x) x {:nextjournal/value x})) ([x v] (-> x ensure-wrapped (assoc :nextjournal/viewer v)))) #_(ensure-wrapped 123) #_(ensure-wrapped {:nextjournal/value 456}) (defn ->value "Takes `x` and returns the `:nextjournal/value` from it, or otherwise `x` unmodified." [x] (if (wrapped-value? x) (:nextjournal/value x) x)) #_(->value (with-viewer :code '(+ 1 2 3))) #_(->value 123) (defn ->viewer "Returns the `:nextjournal/viewer` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/viewer x))) #_(->viewer (with-viewer :code '(+ 1 2 3))) #_(->viewer "123") (defn ->viewers "Returns the `:nextjournal/viewers` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/viewers x))) (defn width "Returns the `:nextjournal/width` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/width x))) (defn normalize-viewer-opts [opts] (when-not (map? opts) (throw (ex-info "normalize-viewer-opts not passed `map?` opts" {:opts opts}))) (set/rename-keys opts {:nextjournal.clerk/viewer :nextjournal/viewer :nextjournal.clerk/viewers :nextjournal/viewers :nextjournal.clerk/opts :nextjournal/opts :nextjournal.clerk/width :nextjournal/width})) (defn normalize-viewer [viewer] (cond (keyword? viewer) viewer (map? viewer) viewer (or (symbol? viewer) (seq? viewer) #?(:cljs (fn? viewer))) {:render-fn viewer} #?@(:clj [(fn? viewer) {:transform-fn viewer}]) :else (throw (ex-info "cannot normalize viewer" {:viewer viewer})))) #_(normalize-viewer '#(v/html [:h3 "Hello " % "!"])) #_(normalize-viewer :latex) #_(normalize-viewer {:render-fn '#(v/html [:h3 "Hello " % "!"]) :transform-fn identity}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; public api (defn with-viewer "Wraps the given value `x` and associates it with the given `viewer`. Takes an optional second `viewer-opts` arg." ([viewer x] (with-viewer viewer nil x)) ([viewer viewer-opts x] (merge (when viewer-opts (normalize-viewer-opts viewer-opts)) (-> x ensure-wrapped (assoc :nextjournal/viewer (normalize-viewer viewer)))))) ;; TODO: Think of a better name (defn with-viewer-extracting-opts [viewer & opts+items] (cond (and (map? (first opts+items)) (not (wrapped-value? (first opts+items)))) (with-viewer viewer (first opts+items) (rest opts+items)) (and (sequential? (first opts+items)) (= 1 (count opts+items))) (apply (partial with-viewer viewer) opts+items) :else (with-viewer viewer opts+items))) #_(with-viewer :latex "x^2") #_(with-viewer '#(v/html [:h3 "Hello " % "!"]) "x^2") (defn with-viewers "Binds viewers to types, eg {:boolean view-fn}" [viewers x] (-> x ensure-wrapped (assoc :nextjournal/viewers viewers))) #_(->> "x^2" (with-viewer :latex) (with-viewers [{:name :latex :render-fn :mathjax}])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; table viewer normalization (defn rpad-vec [v length padding] (vec (take length (concat v (repeat padding))))) (def missing-pred :nextjournal/missing) (defn normalize-seq-of-seq [s] (let [max-count (count (apply max-key count s))] {:rows (mapv #(rpad-vec (->value %) max-count missing-pred) s)})) (defn normalize-seq-of-map [s] (let [ks (->> s (mapcat keys) distinct vec)] {:head ks :rows (mapv (fn [m] (mapv #(get m % missing-pred) ks)) s)})) (defn normalize-map-of-seq [m] (let [ks (-> m keys vec) m* (if (seq? (get m (first ks))) (reduce (fn [acc [k s]] (assoc acc k (vec s))) {} m) m)] {:head ks :rows (->> (range (count (val (apply max-key (comp count val) m*)))) (mapv (fn [i] (mapv #(get-in m* [% i] missing-pred) ks))))})) (defn normalize-seq-to-vec [{:keys [head rows]}] (cond-> {:rows (vec rows)} head (assoc :head (vec head)))) (defn use-headers [s] (let [{:as table :keys [rows]} (normalize-seq-of-seq s)] (-> table (assoc :head (first rows)) (update :rows rest)))) (defn normalize-table-data [data] (cond (and (map? data) (-> data :rows sequential?)) (normalize-seq-to-vec data) (and (map? data) (sequential? (first (vals data)))) (normalize-map-of-seq data) (and (sequential? data) (map? (first data))) (normalize-seq-of-map data) (and (sequential? data) (sequential? (first data))) (normalize-seq-of-seq data) :else nil)) (defn demunge-ex-data [ex-data] (update ex-data :trace (fn [traces] (mapv #(update % 0 (comp demunge pr-str)) traces)))) #_(demunge-ex-data (datafy/datafy (ex-info "foo" {:bar :baz}))) (declare present present* !viewers apply-viewers apply-viewers* ensure-wrapped-with-viewers process-viewer process-wrapped-value default-viewers find-named-viewer) (defn inspect-fn [] #?(:clj (->viewer-eval 'v/inspect) :cljs (eval 'v/inspect))) (defn when-wrapped [f] #(cond-> % (wrapped-value? %) f)) (defn inspect-wrapped-value [wrapped-value] [(inspect-fn) (-> wrapped-value apply-viewers process-wrapped-value)]) #_(w/postwalk (when-wrapped inspect-wrapped-value) [1 2 {:a [3 (with-viewer :latex "\\alpha")]} 4]) (defn mark-presented [wrapped-value] (assoc wrapped-value :nextjournal/presented? true)) (defn mark-preserve-keys [wrapped-value] (assoc wrapped-value :nextjournal/preserve-keys? true)) (defn fetch-all [_opts _xs] (throw (ex-info "`fetch-all` is deprecated, please use a `:transform-fn` with `mark-presented` instead." {}))) (defn get-safe ([key] #(get-safe % key)) ([map key] (when (map? map) (try (get map key) ;; can throw for e.g. sorted-map (catch #?(:clj Exception :cljs js/Error) _e nil))))) (def var-from-def? (get-safe :nextjournal.clerk/var-from-def)) (def datafied? (get-safe :nextjournal.clerk/datafied)) (defn with-md-viewer [wrapped-value] (let [{:as node :keys [type]} (->value wrapped-value)] (when-not type (throw (ex-info "no type given for with-md-viewer" {:wrapped-value wrapped-value}))) (with-viewer (keyword "nextjournal.markdown" (name type)) wrapped-value))) (defn into-markup [markup] (fn [{:as wrapped-value :nextjournal/keys [viewers]}] (-> (with-viewer {:name :html- :render-fn 'v/html} wrapped-value) mark-presented (update :nextjournal/value (fn [{:as node :keys [text content]}] (into (cond-> markup (fn? markup) (apply [node])) (cond text [text] content (mapv #(-> (with-md-viewer %) (assoc :nextjournal/viewers viewers) (apply-viewers) (as-> w (if (= :html- (:name (->viewer w))) (->value w) [(inspect-fn) (process-wrapped-value w)]))) content)))))))) #?(:clj (defn ->edn [x] (binding [*print-namespace-maps* false] (pr-str x)))) #_(->edn {:nextjournal/value :foo}) #?(:clj (defn base64-encode-value [{:as result :nextjournal/keys [content-type]}] (update result :nextjournal/value (fn [data] (str "data:" content-type ";base64, " (.encodeToString (Base64/getEncoder) data)))))) (defn apply-viewer-unwrapping-var-from-def [{:as result :nextjournal/keys [value viewer]}] (if viewer (let [{:keys [transform-fn]} (and (map? viewer) viewer) value (if (and (not transform-fn) (get value :nextjournal.clerk/var-from-def)) (-> value :nextjournal.clerk/var-from-def deref) value)] (assoc result :nextjournal/value (if (or (var? viewer) (fn? viewer)) (viewer value) {:nextjournal/value value :nextjournal/viewer (normalize-viewer viewer)}))) result)) #_(apply-viewer-unwrapping-var-from-def {:nextjournal/value [:h1 "hi"] :nextjournal/viewer :html}) #_(apply-viewer-unwrapping-var-from-def {:nextjournal/value [:h1 "hi"] :nextjournal/viewer (resolve 'nextjournal.clerk/html)}) #?(:clj (defn extract-blobs [lazy-load? blob-id presentd-result] (w/postwalk #(cond-> % (and (get % :nextjournal/content-type) lazy-load?) (assoc :nextjournal/value {:blob-id blob-id :path (:path %)}) (and (get % :nextjournal/content-type) (not lazy-load?)) base64-encode-value) presentd-result))) (defn get-default-viewers [] (:default @!viewers default-viewers)) (defn get-viewers ([scope] (get-viewers scope nil)) ([scope value] (or (when value (->viewers value)) (when scope (@!viewers scope)) (get-default-viewers)))) #_(get-viewers nil nil) #?(:clj (defn ->result [{:keys [inline-results?]} {:as result :nextjournal/keys [value blob-id viewers]}] (let [lazy-load? (and (not inline-results?) blob-id) presentd-result (extract-blobs lazy-load? blob-id (present (ensure-wrapped-with-viewers (or viewers (get-viewers *ns*)) value))) opts-from-form-meta (select-keys result [:nextjournal/width :nextjournal/opts])] (merge {:nextjournal/viewer :clerk/result :nextjournal/value (cond-> (try {:nextjournal/edn (->edn (merge presentd-result opts-from-form-meta))} (catch Throwable _e {:nextjournal/string (pr-str value)})) (-> presentd-result ->viewer :name) (assoc :nextjournal/viewer (select-keys (->viewer presentd-result) [:name])) lazy-load? (assoc :nextjournal/fetch-opts {:blob-id blob-id} :nextjournal/hash (hashing/->hash-str [blob-id presentd-result opts-from-form-meta])))} (dissoc presentd-result :nextjournal/value :nextjournal/viewer :nextjournal/viewers) ;; TODO: consider dropping this. Still needed by notebook-viewer fn to read :nextjournal/width option on result blocks opts-from-form-meta)))) (defn result-hidden? [result] (= :hide-result (-> result ->value ->viewer))) (defn ->display [{:as code-cell :keys [result ns?]}] (let [{:nextjournal.clerk/keys [visibility]} result result? (and (contains? code-cell :result) (not (result-hidden? result)) (not (contains? visibility :hide-ns)) (not (and ns? (contains? visibility :hide)))) fold? (and (not (contains? visibility :hide-ns)) (or (contains? visibility :fold) (contains? visibility :fold-ns))) code? (or fold? (contains? visibility :show))] {:result? result? :fold? fold? :code? code?})) #_(->display {:result {:nextjournal.clerk/visibility #{:fold :hide-ns}}}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold-ns}}}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold}} :ns? true}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide} :nextjournal/value {:nextjournal/viewer :hide-result}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide}} :ns? true}) #?(:clj (defn with-block-viewer [doc {:as cell :keys [type]}] (case type :markdown [(with-viewer :markdown (:doc cell))] :code (let [{:as cell :keys [result]} (update cell :result apply-viewer-unwrapping-var-from-def) {:as display-opts :keys [code? result?]} (->display cell)] (cond-> [] code? (conj (with-viewer :clerk/code-block ;; TODO: display analysis could be merged into cell earlier (-> cell (merge display-opts) (dissoc :result)))) result? (conj (->result doc result))))))) (defn update-viewers [viewers select-fn->update-fn] (reduce (fn [viewers [pred update-fn]] (mapv (fn [viewer] (cond-> viewer (pred viewer) update-fn)) viewers)) viewers select-fn->update-fn)) #_(update-viewers default-viewers {:fetch-opts #(dissoc % :fetch-opts)}) (defn add-viewers ([added-viewers] (add-viewers (get-default-viewers) added-viewers)) ([viewers added-viewers] (into (vec added-viewers) viewers))) (def table-missing-viewer {:pred #{:nextjournal/missing} :render-fn '(fn [x] (v/html [:<>]))}) (def table-markup-viewer {:name :table/markup :render-fn '(fn [head+body opts] (v/html (into [:table.text-xs.sans-serif.text-gray-900.dark:text-white.not-prose] (v/inspect-children opts) head+body)))}) (def table-head-viewer {:name :table/head :render-fn '(fn [header-row {:as opts :keys [path number-col?]}] (v/html [:thead.border-b.border-gray-300.dark:border-slate-700 (into [:tr] (map-indexed (fn [i {:as header-cell :nextjournal/keys [value]}] (let [title (when (or (string? value) (keyword? value) (symbol? value)) value)] [:th.relative.pl-6.pr-2.py-1.align-bottom.font-medium (cond-> {:class (when (number-col? i) "text-right")} title (assoc :title title)) [:div.flex.items-center (v/inspect opts header-cell)]]))) header-row)]))}) (def table-body-viewer {:name :table/body :fetch-opts {:n 20} :render-fn '(fn [rows opts] (v/html (into [:tbody] (map-indexed (fn [idx row] (v/inspect (update opts :path conj idx) row))) rows)))}) (def table-row-viewer {:name :table/row :render-fn '(fn [row {:as opts :keys [path number-col?]}] (v/html (into [:tr.hover:bg-gray-200.dark:hover:bg-slate-700 {:class (if (even? (peek path)) "bg-black/5 dark:bg-gray-800" "bg-white dark:bg-gray-900")}] (map-indexed (fn [idx cell] [:td.pl-6.pr-2.py-1 (when (number-col? idx) {:class "text-right"}) (v/inspect opts cell)])) row)))}) (defn update-table-viewers [viewers] (-> viewers (update-viewers {(comp #{string?} :pred) #(assoc % :render-fn (quote v/string-viewer)) (comp #{number?} :pred) #(assoc % :render-fn '(fn [x] (v/html [:span.tabular-nums (if (js/Number.isNaN x) "NaN" (str x))]))) (comp #{:elision} :name) #(assoc % :render-fn '(fn [{:as fetch-opts :keys [total offset unbounded?]} {:keys [num-cols]}] (v/html [v/consume-view-context :fetch-fn (fn [fetch-fn] [:tr.border-t.dark:border-slate-700 [:td.text-center.py-1 {:col-span num-cols :class (if (fn? fetch-fn) "bg-indigo-50 hover:bg-indigo-100 dark:bg-gray-800 dark:hover:bg-slate-700 cursor-pointer" "text-gray-400 text-slate-500") :on-click (fn [_] (when (fn? fetch-fn) (fetch-fn fetch-opts)))} (- total offset) (when unbounded? "+") (if (fn? fetch-fn) " more…" " more elided")]])])))}) (add-viewers [table-missing-viewer table-markup-viewer table-head-viewer table-body-viewer table-row-viewer]))) #?(:clj (def utc-date-format ;; from `clojure.instant/thread-local-utc-date-format` (doto (java.text.SimpleDateFormat. "yyyy-MM-dd'T'HH:mm:ss.SSS-00:00") (.setTimeZone (java.util.TimeZone/getTimeZone "GMT"))))) #?(:clj (defn datafy-scope [scope] (cond (instance? clojure.lang.Namespace scope) {:namespace (-> scope str keyword)} (keyword? scope) scope :else (throw (ex-info (str "Unsupported scope " scope) {:scope scope}))))) #_(datafy-scope *ns*) #_(datafy-scope #'datafy-scope) (defn update-val [f & args] (fn [wrapped-value] (apply update wrapped-value :nextjournal/value f args))) #_((update-val + 1) {:nextjournal/value 41}) (def markdown-viewers [{:name :nextjournal.markdown/doc :transform-fn (into-markup [:div.viewer-markdown])} ;; blocks {:name :nextjournal.markdown/heading :transform-fn (into-markup (fn [{:as node :keys [heading-level]}] [(str "h" heading-level) {:id (uri.normalize/normalize-fragment (md.transform/->text node))}]))} {:name :nextjournal.markdown/image :transform-fn #(with-viewer :html [:img.inline (-> % ->value :attrs)])} {:name :nextjournal.markdown/blockquote :transform-fn (into-markup [:blockquote])} {:name :nextjournal.markdown/paragraph :transform-fn (into-markup [:p])} {:name :nextjournal.markdown/plain :transform-fn (into-markup [:<>])} {:name :nextjournal.markdown/ruler :transform-fn (into-markup [:hr])} {:name :nextjournal.markdown/code :transform-fn (fn [wrapped-value] (with-viewer :html [:div.viewer-code (with-viewer :code (md.transform/->text (->value wrapped-value)))]))} ;; marks {:name :nextjournal.markdown/em :transform-fn (into-markup [:em])} {:name :nextjournal.markdown/strong :transform-fn (into-markup [:strong])} {:name :nextjournal.markdown/monospace :transform-fn (into-markup [:code])} {:name :nextjournal.markdown/strikethrough :transform-fn (into-markup [:s])} {:name :nextjournal.markdown/link :transform-fn (into-markup #(vector :a (:attrs %)))} {:name :nextjournal.markdown/internal-link :transform-fn (into-markup #(vector :a {:href (str "#" (:text %))}))} {:name :nextjournal.markdown/hashtag :transform-fn (into-markup #(vector :a {:href (str "#" (:text %))}))} ;; inlines {:name :nextjournal.markdown/text :transform-fn (into-markup [:span])} {:name :nextjournal.markdown/softbreak :transform-fn (fn [_] (with-viewer :html [:span " "]))} #?(:clj {:name :nextjournal.markdown/inline :transform-fn (comp eval read-string md.transform/->text)}) ;; formulas {:name :nextjournal.markdown/formula :transform-fn (comp :text ->value) :render-fn '(fn [tex] (v/katex-viewer tex {:inline? true}))} {:name :nextjournal.markdown/block-formula :transform-fn (comp :text ->value) :render-fn 'v/katex-viewer} ;; lists {:name :nextjournal.markdown/bullet-list :transform-fn (into-markup [:ul])} {:name :nextjournal.markdown/numbered-list :transform-fn (into-markup [:ol])} {:name :nextjournal.markdown/todo-list :transform-fn (into-markup [:ul.contains-task-list])} {:name :nextjournal.markdown/list-item :transform-fn (into-markup [:li])} {:name :nextjournal.markdown/todo-item :transform-fn (into-markup (fn [{:keys [attrs]}] [:li [:input {:type "checkbox" :default-checked (:checked attrs)}]]))} ;; tables {:name :nextjournal.markdown/table :transform-fn (into-markup [:table])} {:name :nextjournal.markdown/table-head :transform-fn (into-markup [:thead])} {:name :nextjournal.markdown/table-body :transform-fn (into-markup [:tbody])} {:name :nextjournal.markdown/table-row :transform-fn (into-markup [:tr])} {:name :nextjournal.markdown/table-header :transform-fn (into-markup #(vector :th {:style (md.transform/table-alignment (:attrs %))}))} {:name :nextjournal.markdown/table-data :transform-fn (into-markup #(vector :td {:style (md.transform/table-alignment (:attrs %))}))} ;; ToC via [[TOC]] placeholder ignored {:name :nextjournal.markdown/toc :transform-fn (into-markup [:div.toc])} ;; sidenotes {:name :nextjournal.markdown/sidenote :transform-fn (into-markup (fn [{:keys [attrs]}] [:span.sidenote [:sup {:style {:margin-right "3px"}} (-> attrs :ref inc)]]))} {:name :nextjournal.markdown/sidenote-ref :transform-fn (into-markup [:sup.sidenote-ref])}]) (def char-viewer {:pred char? :render-fn '(fn [c] (v/html [:span.cmt-string.inspected-value "\\" c]))}) (def string-viewer {:pred string? :render-fn (quote v/quoted-string-viewer) :fetch-opts {:n 80}}) (def number-viewer {:pred number? :render-fn (quote v/number-viewer)}) (def number-hex-viewer {:name :number-hex :render-fn '(fn [num] (v/number-viewer (str "0x" (.toString (js/Number. num) 16))))}) (def symbol-viewer {:pred symbol? :render-fn '(fn [x] (v/html [:span.cmt-keyword.inspected-value (str x)]))}) (def keyword-viewer {:pred keyword? :render-fn '(fn [x] (v/html [:span.cmt-atom.inspected-value (str x)]))}) (def nil-viewer {:pred nil? :render-fn '(fn [_] (v/html [:span.cmt-default.inspected-value "nil"]))}) (def boolean-viewer {:pred boolean? :render-fn '(fn [x] (v/html [:span.cmt-bool.inspected-value (str x)]))}) (def map-entry-viewer {:pred map-entry? :name :map-entry :render-fn '(fn [xs opts] (v/html (into [:<>] (comp (v/inspect-children opts) (interpose " ")) xs))) :fetch-opts {:n 2}}) (def var-from-def-viewer {:pred var-from-def? :transform-fn (update-val (comp deref :nextjournal.clerk/var-from-def))}) (def read+inspect-viewer {:name :read+inspect :render-fn '(fn [x] (try (v/html [v/inspect-paginated (v/read-string x)]) (catch js/Error _e (v/unreadable-edn-viewer x))))}) (def vector-viewer {:pred vector? :render-fn 'v/coll-viewer :opening-paren "[" :closing-paren "]" :fetch-opts {:n 20}}) (def set-viewer {:pred set? :render-fn 'v/coll-viewer :opening-paren "#{" :closing-paren "}" :fetch-opts {:n 20}}) (def sequential-viewer {:pred sequential? :render-fn 'v/coll-viewer :opening-paren "(" :closing-paren ")" :fetch-opts {:n 20}}) (def map-viewer {:pred map? :name :map :render-fn 'v/map-viewer :opening-paren "{" :closing-paren "}" :fetch-opts {:n 10}}) (def var-viewer {:pred var? :transform-fn (comp symbol ->value) :render-fn '(fn [x] (v/html [:span.inspected-value [:span.cmt-meta "#'" (str x)]]))}) (def throwable-viewer {:pred (fn [e] (instance? #?(:clj Throwable :cljs js/Error) e)) :name :error :render-fn (quote v/throwable-viewer) :transform-fn (comp mark-presented (update-val (comp demunge-ex-data datafy/datafy)))}) (def buffered-image-viewer #?(:clj {:pred #(instance? BufferedImage %) :transform-fn (fn [{image :nextjournal/value}] (let [stream (java.io.ByteArrayOutputStream.) w (.getWidth image) h (.getHeight image) r (float (/ w h))] (ImageIO/write image "png" stream) (-> {:nextjournal/value (.toByteArray stream) :nextjournal/content-type "image/png" :nextjournal/width (if (and (< 2 r) (< 900 w)) :full :wide)} mark-presented))) :render-fn '(fn [blob] (v/html [:figure.flex.flex-col.items-center.not-prose [:img {:src (v/url-for blob)}]]))})) (def ideref-viewer {:pred #(instance? IDeref %) :transform-fn (fn [wrapped-value] (with-viewer :tagged-value {:tag "object" :value (let [r (->value wrapped-value)] (vector (type r) #?(:clj (with-viewer :number-hex (System/identityHashCode r))) (if-let [deref-as-map (resolve 'clojure.core/deref-as-map)] (deref-as-map r) r)))}))}) (def regex-viewer {:pred #?(:clj (partial instance? java.util.regex.Pattern) :cljs regexp?) :transform-fn (fn [wrapped-value] (with-viewer :tagged-value {:tag "" :value (let [regex (->value wrapped-value)] #?(:clj (.pattern regex) :cljs (.-source regex)))}))}) (def fallback-viewer {:pred (constantly :true) :transform-fn (update-val #(with-viewer :read+inspect (pr-str %)))}) (def elision-viewer {:name :elision :render-fn (quote v/elision-viewer) :transform-fn mark-presented}) (def katex-viewer {:name :latex :render-fn (quote v/katex-viewer) :transform-fn mark-presented}) (def mathjax-viewer {:name :mathjax :render-fn (quote v/mathjax-viewer) :transform-fn mark-presented}) (def html-viewer {:name :html :render-fn (quote v/html) :transform-fn (comp mark-presented (update-val (partial w/postwalk (when-wrapped inspect-wrapped-value))))}) (def plotly-viewer {:name :plotly :render-fn (quote v/plotly-viewer) :transform-fn mark-presented}) (def vega-lite-viewer {:name :vega-lite :render-fn (quote v/vega-lite-viewer) :transform-fn mark-presented}) (def markdown-viewer {:name :markdown :transform-fn (fn [wrapped-value] (-> wrapped-value mark-presented (update :nextjournal/value #(cond->> % (string? %) md/parse)) (update :nextjournal/viewers add-viewers markdown-viewers) (with-md-viewer)))}) (def code-viewer {:name :code :render-fn (quote v/code-viewer) :transform-fn (comp mark-presented (update-val (fn [v] (if (string? v) v (str/trim (with-out-str (pprint/pprint v)))))))}) (def code-folded-viewer {:name :code-folded :render-fn (quote v/foldable-code-viewer) :transform-fn (comp mark-presented (update-val (fn [v] (if (string? v) v (with-out-str (pprint/pprint v))))))}) (def reagent-viewer {:name :reagent :render-fn (quote v/reagent-viewer) :transform-fn mark-presented}) (def row-viewer {:name :row :render-fn '(fn [items opts] (let [item-count (count items)] (v/html (into [:div {:class "md:flex md:flex-row md:gap-4 not-prose" :style opts}] (map (fn [item] [:div.flex.items-center.justify-center.flex-auto (v/inspect opts item)])) items))))}) (def col-viewer {:name :col :render-fn '(fn [items opts] (v/html (into [:div {:class "md:flex md:flex-col md:gap-4 clerk-grid not-prose" :style opts}] (map (fn [item] [:div.flex.items-center.justify-center (v/inspect opts item)])) items)))}) (def table-viewer {:name :table :transform-fn (fn [wrapped-value] (if-let [{:keys [head rows]} (normalize-table-data (->value wrapped-value))] (-> wrapped-value (assoc :nextjournal/viewer :table/markup) (update :nextjournal/width #(or % :wide)) (update :nextjournal/viewers update-table-viewers) (assoc :nextjournal/opts {:num-cols (-> rows first count) :number-col? (mapv number? (first rows))}) (assoc :nextjournal/value (cond->> [(with-viewer :table/body (map (partial with-viewer :table/row) rows))] head (cons (with-viewer :table/head head))))) (-> wrapped-value mark-presented (assoc :nextjournal/width :wide) (assoc :nextjournal/value [(present wrapped-value)]) (assoc :nextjournal/viewer {:render-fn 'v/table-error}))))}) (def table-error-viewer {:name :table-error :render-fn (quote v/table-error) :fetch-opts {:n 1}}) (def code-block-viewer {:name :clerk/code-block :transform-fn (fn [{:as wrapped-value :nextjournal/keys [value]}] (-> wrapped-value (assoc :nextjournal/viewer (if (:fold? value) :code-folded :code)) (update :nextjournal/value :text)))}) (def tagged-value-viewer {:name :tagged-value :render-fn '(fn [{:keys [tag value space?]}] (v/html (v/tagged-value {:space? space?} (str "#" tag) [v/inspect-paginated value]))) :transform-fn (fn [wrapped-value] (-> wrapped-value (update-in [:nextjournal/value :value] present) mark-presented))}) (def result-viewer {:name :clerk/result :render-fn (quote v/result-viewer) :transform-fn mark-presented}) #?(:clj (defn process-blocks [viewers {:as doc :keys [ns]}] (-> doc (update :blocks (partial into [] (comp (mapcat (partial with-block-viewer doc)) (map (comp #(vector (->ViewerEval 'v/inspect) %) process-wrapped-value apply-viewers* (partial ensure-wrapped-with-viewers viewers)))))) (select-keys [:blocks :toc :title]) (cond-> ns (assoc :scope (datafy-scope ns)))))) (def notebook-viewer {:name :clerk/notebook :render-fn (quote v/notebook-viewer) :transform-fn #?(:cljs identity :clj (fn [{:as wrapped-value :nextjournal/keys [viewers]}] (-> wrapped-value (update :nextjournal/value (partial process-blocks viewers)) mark-presented)))}) (def hide-result-viewer {:name :hide-result :transform-fn (fn [_] nil)}) (def default-viewers ;; maybe make this a sorted-map [char-viewer string-viewer number-viewer number-hex-viewer symbol-viewer keyword-viewer nil-viewer boolean-viewer map-entry-viewer var-from-def-viewer read+inspect-viewer vector-viewer set-viewer sequential-viewer map-viewer var-viewer throwable-viewer buffered-image-viewer ideref-viewer regex-viewer fallback-viewer elision-viewer katex-viewer mathjax-viewer html-viewer plotly-viewer vega-lite-viewer markdown-viewer code-viewer code-folded-viewer reagent-viewer row-viewer col-viewer table-viewer table-error-viewer code-block-viewer tagged-value-viewer result-viewer notebook-viewer hide-result-viewer]) (defonce ^{:doc "atom containing a map of and per-namespace viewers or `:defaults` overridden viewers."} !viewers (#?(:clj atom :cljs ratom/atom) {})) #_(reset! !viewers {}) ;; heavily inspired by code from <NAME> in shadow-cljs, see ;; https://github.com/thheller/shadow-cljs/blob/1708acb21bcdae244b50293d17633ce35a78a467/src/main/shadow/remote/runtime/obj_support.cljc#L118-L144 (defn rank-val [val] (reduce-kv (fn [res idx pred] (if (and (ifn? pred) (pred val)) (reduced idx) res)) -1 (into [] (map :pred) default-viewers))) (defn resilient-compare [a b] (try (compare a b) (catch #?(:clj Exception :cljs js/Error) _e (compare (rank-val a) (rank-val b))))) (defn ensure-sorted [xs] (cond (sorted? xs) xs (map? xs) (sort-by first resilient-compare xs) (set? xs) (sort resilient-compare xs) :else xs)) (defn find-viewer [viewers select-fn] (first (filter select-fn viewers))) #_(find-viewer default-viewers (comp #{string?} :pred)) #_(find-viewer default-viewers (comp #{:elision} :name)) (defn find-named-viewer [viewers viewer-name] (find-viewer viewers (comp #{viewer-name} :name))) #_(find-named-viewer default-viewers :elision) (defn viewer-for [viewers x] (or (when-let [selected-viewer (->viewer x)] (if (keyword? selected-viewer) (or (find-named-viewer viewers selected-viewer) (throw (ex-info (str "cannot find viewer named " selected-viewer) {:selected-viewer selected-viewer :viewers viewers}))) selected-viewer)) (find-viewer viewers (let [v (->value x)] (fn [{:keys [pred]}] (and (ifn? pred) (pred v))))) (throw (ex-info (str "cannot find matching viewer for value") {:value (->value x) :viewers viewers :x x})))) #_(viewer-for default-viewers [1 2 3]) #_(viewer-for default-viewers {:nextjournal/value [1 2 3]}) #_(viewer-for default-viewers 42) #_(viewer-for default-viewers (with-viewer :html [:h1 "Hello Hiccup"])) #_(viewer-for default-viewers (with-viewer {:transform-fn identity} [:h1 "Hello Hiccup"])) (defn ensure-wrapped-with-viewers ([x] (ensure-wrapped-with-viewers (get-viewers *ns*) x)) ([viewers x] (-> x ensure-wrapped (update :nextjournal/viewers (fn [x-viewers] (or x-viewers viewers)))))) #_(ensure-wrapped-with-viewers 42) #_(ensure-wrapped-with-viewers {:nextjournal/value 42 :nextjournal/viewers [:boo]}) (defn ->opts [wrapped-value] (select-keys wrapped-value [:nextjournal/width :nextjournal/opts :!budget :budget :path :current-path :offset])) (defn apply-viewers* [wrapped-value] (when (empty? (->viewers wrapped-value)) (throw (ex-info "cannot apply empty viewers" {:wrapped-value wrapped-value}))) (let [viewers (->viewers wrapped-value) {:as viewer :keys [render-fn transform-fn]} (viewer-for viewers wrapped-value) transformed-value (ensure-wrapped-with-viewers viewers (cond-> (dissoc wrapped-value :nextjournal/viewer) transform-fn transform-fn)) wrapped-value' (cond-> transformed-value (-> transformed-value ->value wrapped-value?) (merge (->value transformed-value)))] (if (and transform-fn (not render-fn)) (recur wrapped-value') (-> wrapped-value' (assoc :nextjournal/viewer viewer) (merge (->opts wrapped-value)))))) (defn apply-viewers [x] (apply-viewers* (ensure-wrapped-with-viewers x))) #_(apply-viewers 42) #_(apply-viewers {:one :two}) #_(apply-viewers {:one :two}) #_(apply-viewers [1 2 3]) #_(apply-viewers (range 3)) #_(apply-viewers (clojure.java.io/file "notebooks")) #_(apply-viewers (md "# Hello")) #_(apply-viewers (html [:h1 "hi"])) #_(apply-viewers (with-viewer :elision {:remaining 10 :count 30 :offset 19})) #_(apply-viewers (with-viewer (->Form '(fn [name] (html [:<> "Hello " name]))) "<NAME>")) #_(apply-viewers (with-viewers [{:pred (constantly true) :render-fn '(fn [x] [:h1 "hi"])}] 42)) (defn count-viewers "Helper function to walk a given `x` and replace the viewers with their counts. Useful for debugging." [x] (w/postwalk #(if (wrapped-value? %) (cond-> (dissoc % :!budget) (:nextjournal/viewers %) (-> #_% (update :nextjournal/viewers count) (set/rename-keys {:nextjournal/viewers :nextjournal/viewers-count}))) %) x)) (defn bounded-count-opts [n xs] (when-not (number? n) (throw (ex-info "n must be a number?" {:n n :xs xs}))) (let [limit (+ n #?(:clj config/*bounded-count-limit* :cljs 10000)) total (try (bounded-count limit xs) (catch #?(:clj Exception :cljs js/Error) _ nil))] (cond-> {} total (assoc :total total) (or (not total) (= total limit)) (assoc :unbounded? true)))) #_(bounded-count-opts 20 (range)) #_(bounded-count-opts 20 (range 3234567)) (defn drop+take-xf "Takes a map with optional `:n` and `:offset` and returns a transducer that drops `:offset` and takes `:n`." [{:keys [n offset] :or {offset 0}}] (cond-> (drop offset) (int? n) (comp (take n)))) #_(sequence (drop+take-xf {:n 10}) (range 100)) #_(sequence (drop+take-xf {:n 10 :offset 10}) (range 100)) #_(sequence (drop+take-xf {}) (range 9)) (declare assign-closing-parens) (defn process-render-fn [{:as viewer :keys [render-fn]}] (cond-> viewer (and render-fn (not (viewer-fn? render-fn))) (update :render-fn ->viewer-fn))) (defn process-viewer [viewer] (if-not (map? viewer) viewer (-> viewer (dissoc :pred :transform-fn :update-viewers-fn) process-render-fn))) #_(process-viewer {:render-fn '(v/html [:h1]) :transform-fn mark-presented}) (defn process-wrapped-value [wrapped-value] (-> wrapped-value (select-keys [:nextjournal/viewer :nextjournal/value :nextjournal/width :nextjournal/content-type :nextjournal/opts :path :offset :n]) (update :nextjournal/viewer process-viewer))) #_(process-wrapped-value (apply-viewers 42)) (defn make-elision [viewers fetch-opts] (->> (with-viewer :elision fetch-opts) (ensure-wrapped-with-viewers viewers) apply-viewers process-wrapped-value)) #_(make-elision default-viewers {:n 20}) (defn find-elision [desc] (->value (first (filter (comp #{:elision} :name :nextjournal/viewer) (tree-seq (some-fn map? vector?) #(cond-> % (map? %) vals) desc))))) (defn ->fetch-opts [wrapped-value] (merge (-> wrapped-value ->viewer :fetch-opts) (select-keys wrapped-value [:path :offset]))) (defn get-elision [wrapped-value] (let [{:as fetch-opts :keys [path offset n]} (->fetch-opts wrapped-value)] (merge fetch-opts (bounded-count-opts n (->value wrapped-value))))) #_(get-elision (present (range))) #_(get-elision (present "abc")) #_(get-elision (present (str/join (repeat 1000 "abc")))) (defn get-fetch-opts-n [wrapped-value] (-> wrapped-value ->fetch-opts :n)) (defn inherit-opts [{:as wrapped-value :nextjournal/keys [viewers]} value path-segment] (-> (ensure-wrapped-with-viewers viewers value) (merge (->opts wrapped-value)) (dissoc :offset) (update :path (fnil conj []) path-segment) (update :current-path (fnil conj []) path-segment))) (defn present+paginate-children [{:as wrapped-value :nextjournal/keys [viewers preserve-keys?] :keys [!budget budget]}] (let [{:as fetch-opts :keys [path offset n]} (->fetch-opts wrapped-value) xs (->value wrapped-value) paginate? (and (number? n) (not preserve-keys?)) fetch-opts' (cond-> fetch-opts (and paginate? !budget (not (map-entry? xs))) (update :n min @!budget)) children (if preserve-keys? (into {} (map (fn [[k v]] [k (present* (inherit-opts wrapped-value v k))])) xs) (into [] (comp (if paginate? (drop+take-xf fetch-opts') identity) (map-indexed (fn [i x] (present* (inherit-opts wrapped-value x (+ i (or offset 0)))))) (remove nil?)) (ensure-sorted xs))) {:as elision :keys [total unbounded?]} (and paginate? (get-elision wrapped-value)) new-offset (when paginate? (or (some-> children peek :path peek inc) 0))] (cond-> children (and paginate? (or unbounded? (< new-offset total))) (conj (let [fetch-opts (assoc elision :offset new-offset)] (make-elision viewers fetch-opts)))))) (defn present+paginate-string [{:as wrapped-value :nextjournal/keys [viewers viewer value]}] (let [{:as elision :keys [n total path offset]} (and (-> viewer :fetch-opts :n) (get-elision wrapped-value))] (if (and n (< n total)) (let [new-offset (min (+ (or offset 0) n) total)] (cond-> [(subs value (or offset 0) new-offset)] (pos? (- total new-offset)) (conj (let [fetch-opts (-> elision (assoc :offset new-offset :replace-path (conj path new-offset)))] (make-elision viewers fetch-opts))) true ensure-wrapped)) value))) (defn ^:private present* [{:as wrapped-value :keys [path current-path !budget] :nextjournal/keys [viewers]}] (when (empty? viewers) (throw (ex-info "cannot present* with empty viewers" {:wrapped-value wrapped-value}))) (let [{:as wrapped-value :nextjournal/keys [viewers presented?]} (apply-viewers* wrapped-value) descend? (< (count current-path) (count path)) xs (->value wrapped-value)] #_(prn :xs xs :type (type xs) :path path :current-path current-path :descend? descend?) (when (and !budget (not descend?) (not presented?)) (swap! !budget #(max (dec %) 0))) (-> (merge (->opts wrapped-value) (with-viewer (->viewer wrapped-value) (cond presented? wrapped-value descend? ;; TODO: can this be unified, simplified, or even dropped in favor of continuation? (let [idx (first (drop (count current-path) path))] (present* (-> (ensure-wrapped-with-viewers viewers (cond (and (map? xs) (keyword? idx)) (get xs idx) (or (map? xs) (set? xs)) (nth (seq (ensure-sorted xs)) idx) (associative? xs) (get xs idx) (sequential? xs) (nth xs idx))) (merge (->opts wrapped-value)) (update :current-path (fnil conj []) idx)))) (string? xs) (present+paginate-string wrapped-value) (and xs (seqable? xs)) (present+paginate-children wrapped-value) :else ;; leaf value xs))) process-wrapped-value))) (defn present "Returns a subset of a given `value`." ([x] (present x {})) ([x opts] (-> (ensure-wrapped-with-viewers x) (merge {:!budget (atom (:budget opts 200)) :path (:path opts []) :current-path (:current-path opts [])} opts) present* assign-closing-parens))) (comment (present 42) (present [42]) (-> (present (range 100)) ->value peek) (present {:hello [1 2 3]}) (present {:one [1 2 3] 1 2 3 4}) (present [1 2 [1 [2] 3] 4 5]) (present (clojure.java.io/file "notebooks")) (present {:viewers [{:pred sequential? :render-fn pr-str}]} (range 100)) (present (map vector (range))) (present (subs (slurp "/usr/share/dict/words") 0 1000)) (present (plotly {:data [{:z [[1 2 3] [3 2 1]] :type "surface"}]})) (present [(with-viewer :html [:h1 "hi"])]) (present (with-viewer :html [:ul (for [x (range 3)] [:li x])])) (present (range)) (present {1 [2]}) (present (with-viewer '(fn [name] (html [:<> "Hello " name])) "<NAME>"))) (defn desc->values "Takes a `description` and returns its value. Inverse of `present`. Mostly useful for debugging." [desc] (let [x (->value desc) viewer-name (-> desc ->viewer :name)] (cond (= viewer-name :elision) (with-meta '… x) (coll? x) (into (case viewer-name ;; TODO: fix table viewer (:map :table) {} (or (empty x) [])) (map desc->values) x) :else x))) #_(desc->values (present [1 [2 {:a :b} 2] 3 (range 100)])) #_(desc->values (present (table (mapv vector (range 30))))) #_(desc->values (present (with-viewer :table (normalize-table-data (repeat 60 ["<NAME>" "<NAME>" 50 30 200 5000 :female]))))) (defn path-to-value [path] (conj (interleave path (repeat :nextjournal/value)) :nextjournal/value)) (defn merge-presentations [root more elision] (update-in root (path-to-value (:path elision)) (fn [value] (let [{:keys [offset path]} (-> value peek :nextjournal/value) path-from-value (conj path offset) path-from-more (or (:replace-path elision) ;; string case, TODO find a better way to unify (-> more :nextjournal/value first :path))] (when (not= path-from-value path-from-more) (throw (ex-info "paths mismatch" {:path-from-value path-from-value :path-from-more path-from-more :root root :more more :path-to-value (path-to-value (:path more)) :value value}))) (into (pop value) (:nextjournal/value more)))))) (defn assign-closing-parens ([node] (assign-closing-parens '() node)) ([closing-parens node] (let [value (->value node) viewer (->viewer node) closing (:closing-paren viewer) non-leaf? (and (vector? value) (wrapped-value? (first value))) defer-closing? (and non-leaf? (or (-> value last :nextjournal/viewer :closing-paren) ;; the last element can carry parens (and (= :map-entry (-> value last :nextjournal/viewer :name)) ;; the last element is a map entry whose value can carry parens (-> value last :nextjournal/value last :nextjournal/viewer :closing-paren))))] (cond-> (cond (not closing) node defer-closing? (update node :nextjournal/viewer dissoc :closing-paren) :else (update-in node [:nextjournal/viewer :closing-paren] cons closing-parens)) non-leaf? (update :nextjournal/value (fn [xs] (into [] (map-indexed (fn [i x] (assign-closing-parens (if (and defer-closing? (= (dec (count xs)) i)) (cond->> closing-parens closing (cons closing)) '()) x))) xs))))))) (defn reset-viewers! ([viewers] (reset-viewers! *ns* viewers)) ([scope viewers] (assert (or (#{:default} scope) #?(:clj (instance? clojure.lang.Namespace scope)))) (swap! !viewers assoc scope viewers))) (defn add-viewers! [viewers] (reset-viewers! *ns* (add-viewers (get-default-viewers) viewers)) viewers) (defn ^{:deprecated "0.8"} set-viewers! [viewers] (binding #?(:clj [*out* *err*] :cljs []) (prn "`set-viewers!` has been deprecated, please use `add-viewers!` or `reset-viewers!` instead.")) (add-viewers! viewers)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; public convenience api (def html (partial with-viewer :html)) (def md (partial with-viewer :markdown)) (def plotly (partial with-viewer :plotly)) (def vl (partial with-viewer :vega-lite)) (def table (partial with-viewer :table)) (def row (partial with-viewer-extracting-opts :row)) (def col (partial with-viewer-extracting-opts :col)) (def tex (partial with-viewer :latex)) (def hide-result (partial with-viewer :hide-result)) (def notebook (partial with-viewer :clerk/notebook)) (defn doc-url [path] (->viewer-eval (list 'v/doc-url path))) (def code (partial with-viewer :code)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; examples (def example-viewer {:transform-fn (fn [{:as wrapped-value :nextjournal/keys [viewers] :keys [path current-path]}] (-> wrapped-value mark-preserve-keys (assoc :nextjournal/viewer {:render-fn '(fn [{:keys [form val]} opts] (v/html [:div.flex.flex-wrap {:class "py-[7px]"} [:div [:div.bg-slate-100.px-2.rounded (v/inspect opts form)]] [:div.flex.mt-1 [:div.mx-2.font-sans.text-xs.text-slate-500 {:class "mt-[2px]"} "⇒"] (v/inspect opts val)]]))}) (update-in [:nextjournal/value :form] code)))}) (def examples-viewer {:transform-fn (update-val (fn [examples] (mapv (partial with-viewer example-viewer) examples))) :render-fn '(fn [examples opts] (v/html (into [:div.border-l-2.border-slate-300.pl-4 [:div.uppercase.tracking-wider.text-xs.font-sans.text-slate-500.mt-4.mb-2 "Examples"]] (v/inspect-children opts) examples)))})
true
(ns nextjournal.clerk.viewer (:require [clojure.string :as str] [clojure.pprint :as pprint] [clojure.datafy :as datafy] [clojure.set :as set] [clojure.walk :as w] #?@(:clj [[clojure.repl :refer [demunge]] [nextjournal.clerk.config :as config] [nextjournal.clerk.hashing :as hashing]] :cljs [[reagent.ratom :as ratom]]) [nextjournal.markdown :as md] [nextjournal.markdown.transform :as md.transform] [lambdaisland.uri.normalize :as uri.normalize]) #?(:clj (:import (clojure.lang IDeref) (java.lang Throwable) (java.awt.image BufferedImage) (javax.imageio ImageIO) (java.util Base64)))) (defrecord ViewerEval [form]) (defrecord ViewerFn [form #?(:cljs f)] #?@(:cljs [IFn (-invoke [this x] ((:f this) x)) (-invoke [this x y] ((:f this) x y))])) (defn viewer-fn? [x] (instance? ViewerFn x)) (defn ->viewer-fn [form] (map->ViewerFn {:form form #?@(:cljs [:f (eval form)])})) (defn ->viewer-eval [form] (map->ViewerEval {:form form})) #?(:clj (defmethod print-method ViewerFn [v ^java.io.Writer w] (.write w (str "#viewer-fn " (pr-str `~(:form v)))))) #?(:clj (defmethod print-method ViewerEval [v ^java.io.Writer w] (.write w (str "#viewer-eval " (pr-str `~(:form v)))))) #_(binding [*data-readers* {'viewer-fn ->viewer-fn}] (read-string (pr-str (->viewer-fn '(fn [x] x))))) #_(binding [*data-readers* {'viewer-fn ->viewer-fn}] (read-string (pr-str (->viewer-fn 'number?)))) (comment (def num? (form->fn+form 'number?)) (num? 42) (:form num?) (pr-str num?)) (defn wrapped-value? "Tests if `x` is a map containing a `:nextjournal/value`." [x] (and (map? x) ;; can throw for `sorted-map` (try (contains? x :nextjournal/value) (catch #?(:clj Exception :cljs js/Error) _e false)))) (defn ensure-wrapped "Ensures `x` is wrapped in a map under a `:nextjournal/value` key." ([x] (if (wrapped-value? x) x {:nextjournal/value x})) ([x v] (-> x ensure-wrapped (assoc :nextjournal/viewer v)))) #_(ensure-wrapped 123) #_(ensure-wrapped {:nextjournal/value 456}) (defn ->value "Takes `x` and returns the `:nextjournal/value` from it, or otherwise `x` unmodified." [x] (if (wrapped-value? x) (:nextjournal/value x) x)) #_(->value (with-viewer :code '(+ 1 2 3))) #_(->value 123) (defn ->viewer "Returns the `:nextjournal/viewer` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/viewer x))) #_(->viewer (with-viewer :code '(+ 1 2 3))) #_(->viewer "123") (defn ->viewers "Returns the `:nextjournal/viewers` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/viewers x))) (defn width "Returns the `:nextjournal/width` for a given wrapped value `x`, `nil` otherwise." [x] (when (wrapped-value? x) (:nextjournal/width x))) (defn normalize-viewer-opts [opts] (when-not (map? opts) (throw (ex-info "normalize-viewer-opts not passed `map?` opts" {:opts opts}))) (set/rename-keys opts {:nextjournal.clerk/viewer :nextjournal/viewer :nextjournal.clerk/viewers :nextjournal/viewers :nextjournal.clerk/opts :nextjournal/opts :nextjournal.clerk/width :nextjournal/width})) (defn normalize-viewer [viewer] (cond (keyword? viewer) viewer (map? viewer) viewer (or (symbol? viewer) (seq? viewer) #?(:cljs (fn? viewer))) {:render-fn viewer} #?@(:clj [(fn? viewer) {:transform-fn viewer}]) :else (throw (ex-info "cannot normalize viewer" {:viewer viewer})))) #_(normalize-viewer '#(v/html [:h3 "Hello " % "!"])) #_(normalize-viewer :latex) #_(normalize-viewer {:render-fn '#(v/html [:h3 "Hello " % "!"]) :transform-fn identity}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; public api (defn with-viewer "Wraps the given value `x` and associates it with the given `viewer`. Takes an optional second `viewer-opts` arg." ([viewer x] (with-viewer viewer nil x)) ([viewer viewer-opts x] (merge (when viewer-opts (normalize-viewer-opts viewer-opts)) (-> x ensure-wrapped (assoc :nextjournal/viewer (normalize-viewer viewer)))))) ;; TODO: Think of a better name (defn with-viewer-extracting-opts [viewer & opts+items] (cond (and (map? (first opts+items)) (not (wrapped-value? (first opts+items)))) (with-viewer viewer (first opts+items) (rest opts+items)) (and (sequential? (first opts+items)) (= 1 (count opts+items))) (apply (partial with-viewer viewer) opts+items) :else (with-viewer viewer opts+items))) #_(with-viewer :latex "x^2") #_(with-viewer '#(v/html [:h3 "Hello " % "!"]) "x^2") (defn with-viewers "Binds viewers to types, eg {:boolean view-fn}" [viewers x] (-> x ensure-wrapped (assoc :nextjournal/viewers viewers))) #_(->> "x^2" (with-viewer :latex) (with-viewers [{:name :latex :render-fn :mathjax}])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; table viewer normalization (defn rpad-vec [v length padding] (vec (take length (concat v (repeat padding))))) (def missing-pred :nextjournal/missing) (defn normalize-seq-of-seq [s] (let [max-count (count (apply max-key count s))] {:rows (mapv #(rpad-vec (->value %) max-count missing-pred) s)})) (defn normalize-seq-of-map [s] (let [ks (->> s (mapcat keys) distinct vec)] {:head ks :rows (mapv (fn [m] (mapv #(get m % missing-pred) ks)) s)})) (defn normalize-map-of-seq [m] (let [ks (-> m keys vec) m* (if (seq? (get m (first ks))) (reduce (fn [acc [k s]] (assoc acc k (vec s))) {} m) m)] {:head ks :rows (->> (range (count (val (apply max-key (comp count val) m*)))) (mapv (fn [i] (mapv #(get-in m* [% i] missing-pred) ks))))})) (defn normalize-seq-to-vec [{:keys [head rows]}] (cond-> {:rows (vec rows)} head (assoc :head (vec head)))) (defn use-headers [s] (let [{:as table :keys [rows]} (normalize-seq-of-seq s)] (-> table (assoc :head (first rows)) (update :rows rest)))) (defn normalize-table-data [data] (cond (and (map? data) (-> data :rows sequential?)) (normalize-seq-to-vec data) (and (map? data) (sequential? (first (vals data)))) (normalize-map-of-seq data) (and (sequential? data) (map? (first data))) (normalize-seq-of-map data) (and (sequential? data) (sequential? (first data))) (normalize-seq-of-seq data) :else nil)) (defn demunge-ex-data [ex-data] (update ex-data :trace (fn [traces] (mapv #(update % 0 (comp demunge pr-str)) traces)))) #_(demunge-ex-data (datafy/datafy (ex-info "foo" {:bar :baz}))) (declare present present* !viewers apply-viewers apply-viewers* ensure-wrapped-with-viewers process-viewer process-wrapped-value default-viewers find-named-viewer) (defn inspect-fn [] #?(:clj (->viewer-eval 'v/inspect) :cljs (eval 'v/inspect))) (defn when-wrapped [f] #(cond-> % (wrapped-value? %) f)) (defn inspect-wrapped-value [wrapped-value] [(inspect-fn) (-> wrapped-value apply-viewers process-wrapped-value)]) #_(w/postwalk (when-wrapped inspect-wrapped-value) [1 2 {:a [3 (with-viewer :latex "\\alpha")]} 4]) (defn mark-presented [wrapped-value] (assoc wrapped-value :nextjournal/presented? true)) (defn mark-preserve-keys [wrapped-value] (assoc wrapped-value :nextjournal/preserve-keys? true)) (defn fetch-all [_opts _xs] (throw (ex-info "`fetch-all` is deprecated, please use a `:transform-fn` with `mark-presented` instead." {}))) (defn get-safe ([key] #(get-safe % key)) ([map key] (when (map? map) (try (get map key) ;; can throw for e.g. sorted-map (catch #?(:clj Exception :cljs js/Error) _e nil))))) (def var-from-def? (get-safe :nextjournal.clerk/var-from-def)) (def datafied? (get-safe :nextjournal.clerk/datafied)) (defn with-md-viewer [wrapped-value] (let [{:as node :keys [type]} (->value wrapped-value)] (when-not type (throw (ex-info "no type given for with-md-viewer" {:wrapped-value wrapped-value}))) (with-viewer (keyword "nextjournal.markdown" (name type)) wrapped-value))) (defn into-markup [markup] (fn [{:as wrapped-value :nextjournal/keys [viewers]}] (-> (with-viewer {:name :html- :render-fn 'v/html} wrapped-value) mark-presented (update :nextjournal/value (fn [{:as node :keys [text content]}] (into (cond-> markup (fn? markup) (apply [node])) (cond text [text] content (mapv #(-> (with-md-viewer %) (assoc :nextjournal/viewers viewers) (apply-viewers) (as-> w (if (= :html- (:name (->viewer w))) (->value w) [(inspect-fn) (process-wrapped-value w)]))) content)))))))) #?(:clj (defn ->edn [x] (binding [*print-namespace-maps* false] (pr-str x)))) #_(->edn {:nextjournal/value :foo}) #?(:clj (defn base64-encode-value [{:as result :nextjournal/keys [content-type]}] (update result :nextjournal/value (fn [data] (str "data:" content-type ";base64, " (.encodeToString (Base64/getEncoder) data)))))) (defn apply-viewer-unwrapping-var-from-def [{:as result :nextjournal/keys [value viewer]}] (if viewer (let [{:keys [transform-fn]} (and (map? viewer) viewer) value (if (and (not transform-fn) (get value :nextjournal.clerk/var-from-def)) (-> value :nextjournal.clerk/var-from-def deref) value)] (assoc result :nextjournal/value (if (or (var? viewer) (fn? viewer)) (viewer value) {:nextjournal/value value :nextjournal/viewer (normalize-viewer viewer)}))) result)) #_(apply-viewer-unwrapping-var-from-def {:nextjournal/value [:h1 "hi"] :nextjournal/viewer :html}) #_(apply-viewer-unwrapping-var-from-def {:nextjournal/value [:h1 "hi"] :nextjournal/viewer (resolve 'nextjournal.clerk/html)}) #?(:clj (defn extract-blobs [lazy-load? blob-id presentd-result] (w/postwalk #(cond-> % (and (get % :nextjournal/content-type) lazy-load?) (assoc :nextjournal/value {:blob-id blob-id :path (:path %)}) (and (get % :nextjournal/content-type) (not lazy-load?)) base64-encode-value) presentd-result))) (defn get-default-viewers [] (:default @!viewers default-viewers)) (defn get-viewers ([scope] (get-viewers scope nil)) ([scope value] (or (when value (->viewers value)) (when scope (@!viewers scope)) (get-default-viewers)))) #_(get-viewers nil nil) #?(:clj (defn ->result [{:keys [inline-results?]} {:as result :nextjournal/keys [value blob-id viewers]}] (let [lazy-load? (and (not inline-results?) blob-id) presentd-result (extract-blobs lazy-load? blob-id (present (ensure-wrapped-with-viewers (or viewers (get-viewers *ns*)) value))) opts-from-form-meta (select-keys result [:nextjournal/width :nextjournal/opts])] (merge {:nextjournal/viewer :clerk/result :nextjournal/value (cond-> (try {:nextjournal/edn (->edn (merge presentd-result opts-from-form-meta))} (catch Throwable _e {:nextjournal/string (pr-str value)})) (-> presentd-result ->viewer :name) (assoc :nextjournal/viewer (select-keys (->viewer presentd-result) [:name])) lazy-load? (assoc :nextjournal/fetch-opts {:blob-id blob-id} :nextjournal/hash (hashing/->hash-str [blob-id presentd-result opts-from-form-meta])))} (dissoc presentd-result :nextjournal/value :nextjournal/viewer :nextjournal/viewers) ;; TODO: consider dropping this. Still needed by notebook-viewer fn to read :nextjournal/width option on result blocks opts-from-form-meta)))) (defn result-hidden? [result] (= :hide-result (-> result ->value ->viewer))) (defn ->display [{:as code-cell :keys [result ns?]}] (let [{:nextjournal.clerk/keys [visibility]} result result? (and (contains? code-cell :result) (not (result-hidden? result)) (not (contains? visibility :hide-ns)) (not (and ns? (contains? visibility :hide)))) fold? (and (not (contains? visibility :hide-ns)) (or (contains? visibility :fold) (contains? visibility :fold-ns))) code? (or fold? (contains? visibility :show))] {:result? result? :fold? fold? :code? code?})) #_(->display {:result {:nextjournal.clerk/visibility #{:fold :hide-ns}}}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold-ns}}}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold}} :ns? true}) #_(->display {:result {:nextjournal.clerk/visibility #{:fold}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide} :nextjournal/value {:nextjournal/viewer :hide-result}} :ns? false}) #_(->display {:result {:nextjournal.clerk/visibility #{:hide}} :ns? true}) #?(:clj (defn with-block-viewer [doc {:as cell :keys [type]}] (case type :markdown [(with-viewer :markdown (:doc cell))] :code (let [{:as cell :keys [result]} (update cell :result apply-viewer-unwrapping-var-from-def) {:as display-opts :keys [code? result?]} (->display cell)] (cond-> [] code? (conj (with-viewer :clerk/code-block ;; TODO: display analysis could be merged into cell earlier (-> cell (merge display-opts) (dissoc :result)))) result? (conj (->result doc result))))))) (defn update-viewers [viewers select-fn->update-fn] (reduce (fn [viewers [pred update-fn]] (mapv (fn [viewer] (cond-> viewer (pred viewer) update-fn)) viewers)) viewers select-fn->update-fn)) #_(update-viewers default-viewers {:fetch-opts #(dissoc % :fetch-opts)}) (defn add-viewers ([added-viewers] (add-viewers (get-default-viewers) added-viewers)) ([viewers added-viewers] (into (vec added-viewers) viewers))) (def table-missing-viewer {:pred #{:nextjournal/missing} :render-fn '(fn [x] (v/html [:<>]))}) (def table-markup-viewer {:name :table/markup :render-fn '(fn [head+body opts] (v/html (into [:table.text-xs.sans-serif.text-gray-900.dark:text-white.not-prose] (v/inspect-children opts) head+body)))}) (def table-head-viewer {:name :table/head :render-fn '(fn [header-row {:as opts :keys [path number-col?]}] (v/html [:thead.border-b.border-gray-300.dark:border-slate-700 (into [:tr] (map-indexed (fn [i {:as header-cell :nextjournal/keys [value]}] (let [title (when (or (string? value) (keyword? value) (symbol? value)) value)] [:th.relative.pl-6.pr-2.py-1.align-bottom.font-medium (cond-> {:class (when (number-col? i) "text-right")} title (assoc :title title)) [:div.flex.items-center (v/inspect opts header-cell)]]))) header-row)]))}) (def table-body-viewer {:name :table/body :fetch-opts {:n 20} :render-fn '(fn [rows opts] (v/html (into [:tbody] (map-indexed (fn [idx row] (v/inspect (update opts :path conj idx) row))) rows)))}) (def table-row-viewer {:name :table/row :render-fn '(fn [row {:as opts :keys [path number-col?]}] (v/html (into [:tr.hover:bg-gray-200.dark:hover:bg-slate-700 {:class (if (even? (peek path)) "bg-black/5 dark:bg-gray-800" "bg-white dark:bg-gray-900")}] (map-indexed (fn [idx cell] [:td.pl-6.pr-2.py-1 (when (number-col? idx) {:class "text-right"}) (v/inspect opts cell)])) row)))}) (defn update-table-viewers [viewers] (-> viewers (update-viewers {(comp #{string?} :pred) #(assoc % :render-fn (quote v/string-viewer)) (comp #{number?} :pred) #(assoc % :render-fn '(fn [x] (v/html [:span.tabular-nums (if (js/Number.isNaN x) "NaN" (str x))]))) (comp #{:elision} :name) #(assoc % :render-fn '(fn [{:as fetch-opts :keys [total offset unbounded?]} {:keys [num-cols]}] (v/html [v/consume-view-context :fetch-fn (fn [fetch-fn] [:tr.border-t.dark:border-slate-700 [:td.text-center.py-1 {:col-span num-cols :class (if (fn? fetch-fn) "bg-indigo-50 hover:bg-indigo-100 dark:bg-gray-800 dark:hover:bg-slate-700 cursor-pointer" "text-gray-400 text-slate-500") :on-click (fn [_] (when (fn? fetch-fn) (fetch-fn fetch-opts)))} (- total offset) (when unbounded? "+") (if (fn? fetch-fn) " more…" " more elided")]])])))}) (add-viewers [table-missing-viewer table-markup-viewer table-head-viewer table-body-viewer table-row-viewer]))) #?(:clj (def utc-date-format ;; from `clojure.instant/thread-local-utc-date-format` (doto (java.text.SimpleDateFormat. "yyyy-MM-dd'T'HH:mm:ss.SSS-00:00") (.setTimeZone (java.util.TimeZone/getTimeZone "GMT"))))) #?(:clj (defn datafy-scope [scope] (cond (instance? clojure.lang.Namespace scope) {:namespace (-> scope str keyword)} (keyword? scope) scope :else (throw (ex-info (str "Unsupported scope " scope) {:scope scope}))))) #_(datafy-scope *ns*) #_(datafy-scope #'datafy-scope) (defn update-val [f & args] (fn [wrapped-value] (apply update wrapped-value :nextjournal/value f args))) #_((update-val + 1) {:nextjournal/value 41}) (def markdown-viewers [{:name :nextjournal.markdown/doc :transform-fn (into-markup [:div.viewer-markdown])} ;; blocks {:name :nextjournal.markdown/heading :transform-fn (into-markup (fn [{:as node :keys [heading-level]}] [(str "h" heading-level) {:id (uri.normalize/normalize-fragment (md.transform/->text node))}]))} {:name :nextjournal.markdown/image :transform-fn #(with-viewer :html [:img.inline (-> % ->value :attrs)])} {:name :nextjournal.markdown/blockquote :transform-fn (into-markup [:blockquote])} {:name :nextjournal.markdown/paragraph :transform-fn (into-markup [:p])} {:name :nextjournal.markdown/plain :transform-fn (into-markup [:<>])} {:name :nextjournal.markdown/ruler :transform-fn (into-markup [:hr])} {:name :nextjournal.markdown/code :transform-fn (fn [wrapped-value] (with-viewer :html [:div.viewer-code (with-viewer :code (md.transform/->text (->value wrapped-value)))]))} ;; marks {:name :nextjournal.markdown/em :transform-fn (into-markup [:em])} {:name :nextjournal.markdown/strong :transform-fn (into-markup [:strong])} {:name :nextjournal.markdown/monospace :transform-fn (into-markup [:code])} {:name :nextjournal.markdown/strikethrough :transform-fn (into-markup [:s])} {:name :nextjournal.markdown/link :transform-fn (into-markup #(vector :a (:attrs %)))} {:name :nextjournal.markdown/internal-link :transform-fn (into-markup #(vector :a {:href (str "#" (:text %))}))} {:name :nextjournal.markdown/hashtag :transform-fn (into-markup #(vector :a {:href (str "#" (:text %))}))} ;; inlines {:name :nextjournal.markdown/text :transform-fn (into-markup [:span])} {:name :nextjournal.markdown/softbreak :transform-fn (fn [_] (with-viewer :html [:span " "]))} #?(:clj {:name :nextjournal.markdown/inline :transform-fn (comp eval read-string md.transform/->text)}) ;; formulas {:name :nextjournal.markdown/formula :transform-fn (comp :text ->value) :render-fn '(fn [tex] (v/katex-viewer tex {:inline? true}))} {:name :nextjournal.markdown/block-formula :transform-fn (comp :text ->value) :render-fn 'v/katex-viewer} ;; lists {:name :nextjournal.markdown/bullet-list :transform-fn (into-markup [:ul])} {:name :nextjournal.markdown/numbered-list :transform-fn (into-markup [:ol])} {:name :nextjournal.markdown/todo-list :transform-fn (into-markup [:ul.contains-task-list])} {:name :nextjournal.markdown/list-item :transform-fn (into-markup [:li])} {:name :nextjournal.markdown/todo-item :transform-fn (into-markup (fn [{:keys [attrs]}] [:li [:input {:type "checkbox" :default-checked (:checked attrs)}]]))} ;; tables {:name :nextjournal.markdown/table :transform-fn (into-markup [:table])} {:name :nextjournal.markdown/table-head :transform-fn (into-markup [:thead])} {:name :nextjournal.markdown/table-body :transform-fn (into-markup [:tbody])} {:name :nextjournal.markdown/table-row :transform-fn (into-markup [:tr])} {:name :nextjournal.markdown/table-header :transform-fn (into-markup #(vector :th {:style (md.transform/table-alignment (:attrs %))}))} {:name :nextjournal.markdown/table-data :transform-fn (into-markup #(vector :td {:style (md.transform/table-alignment (:attrs %))}))} ;; ToC via [[TOC]] placeholder ignored {:name :nextjournal.markdown/toc :transform-fn (into-markup [:div.toc])} ;; sidenotes {:name :nextjournal.markdown/sidenote :transform-fn (into-markup (fn [{:keys [attrs]}] [:span.sidenote [:sup {:style {:margin-right "3px"}} (-> attrs :ref inc)]]))} {:name :nextjournal.markdown/sidenote-ref :transform-fn (into-markup [:sup.sidenote-ref])}]) (def char-viewer {:pred char? :render-fn '(fn [c] (v/html [:span.cmt-string.inspected-value "\\" c]))}) (def string-viewer {:pred string? :render-fn (quote v/quoted-string-viewer) :fetch-opts {:n 80}}) (def number-viewer {:pred number? :render-fn (quote v/number-viewer)}) (def number-hex-viewer {:name :number-hex :render-fn '(fn [num] (v/number-viewer (str "0x" (.toString (js/Number. num) 16))))}) (def symbol-viewer {:pred symbol? :render-fn '(fn [x] (v/html [:span.cmt-keyword.inspected-value (str x)]))}) (def keyword-viewer {:pred keyword? :render-fn '(fn [x] (v/html [:span.cmt-atom.inspected-value (str x)]))}) (def nil-viewer {:pred nil? :render-fn '(fn [_] (v/html [:span.cmt-default.inspected-value "nil"]))}) (def boolean-viewer {:pred boolean? :render-fn '(fn [x] (v/html [:span.cmt-bool.inspected-value (str x)]))}) (def map-entry-viewer {:pred map-entry? :name :map-entry :render-fn '(fn [xs opts] (v/html (into [:<>] (comp (v/inspect-children opts) (interpose " ")) xs))) :fetch-opts {:n 2}}) (def var-from-def-viewer {:pred var-from-def? :transform-fn (update-val (comp deref :nextjournal.clerk/var-from-def))}) (def read+inspect-viewer {:name :read+inspect :render-fn '(fn [x] (try (v/html [v/inspect-paginated (v/read-string x)]) (catch js/Error _e (v/unreadable-edn-viewer x))))}) (def vector-viewer {:pred vector? :render-fn 'v/coll-viewer :opening-paren "[" :closing-paren "]" :fetch-opts {:n 20}}) (def set-viewer {:pred set? :render-fn 'v/coll-viewer :opening-paren "#{" :closing-paren "}" :fetch-opts {:n 20}}) (def sequential-viewer {:pred sequential? :render-fn 'v/coll-viewer :opening-paren "(" :closing-paren ")" :fetch-opts {:n 20}}) (def map-viewer {:pred map? :name :map :render-fn 'v/map-viewer :opening-paren "{" :closing-paren "}" :fetch-opts {:n 10}}) (def var-viewer {:pred var? :transform-fn (comp symbol ->value) :render-fn '(fn [x] (v/html [:span.inspected-value [:span.cmt-meta "#'" (str x)]]))}) (def throwable-viewer {:pred (fn [e] (instance? #?(:clj Throwable :cljs js/Error) e)) :name :error :render-fn (quote v/throwable-viewer) :transform-fn (comp mark-presented (update-val (comp demunge-ex-data datafy/datafy)))}) (def buffered-image-viewer #?(:clj {:pred #(instance? BufferedImage %) :transform-fn (fn [{image :nextjournal/value}] (let [stream (java.io.ByteArrayOutputStream.) w (.getWidth image) h (.getHeight image) r (float (/ w h))] (ImageIO/write image "png" stream) (-> {:nextjournal/value (.toByteArray stream) :nextjournal/content-type "image/png" :nextjournal/width (if (and (< 2 r) (< 900 w)) :full :wide)} mark-presented))) :render-fn '(fn [blob] (v/html [:figure.flex.flex-col.items-center.not-prose [:img {:src (v/url-for blob)}]]))})) (def ideref-viewer {:pred #(instance? IDeref %) :transform-fn (fn [wrapped-value] (with-viewer :tagged-value {:tag "object" :value (let [r (->value wrapped-value)] (vector (type r) #?(:clj (with-viewer :number-hex (System/identityHashCode r))) (if-let [deref-as-map (resolve 'clojure.core/deref-as-map)] (deref-as-map r) r)))}))}) (def regex-viewer {:pred #?(:clj (partial instance? java.util.regex.Pattern) :cljs regexp?) :transform-fn (fn [wrapped-value] (with-viewer :tagged-value {:tag "" :value (let [regex (->value wrapped-value)] #?(:clj (.pattern regex) :cljs (.-source regex)))}))}) (def fallback-viewer {:pred (constantly :true) :transform-fn (update-val #(with-viewer :read+inspect (pr-str %)))}) (def elision-viewer {:name :elision :render-fn (quote v/elision-viewer) :transform-fn mark-presented}) (def katex-viewer {:name :latex :render-fn (quote v/katex-viewer) :transform-fn mark-presented}) (def mathjax-viewer {:name :mathjax :render-fn (quote v/mathjax-viewer) :transform-fn mark-presented}) (def html-viewer {:name :html :render-fn (quote v/html) :transform-fn (comp mark-presented (update-val (partial w/postwalk (when-wrapped inspect-wrapped-value))))}) (def plotly-viewer {:name :plotly :render-fn (quote v/plotly-viewer) :transform-fn mark-presented}) (def vega-lite-viewer {:name :vega-lite :render-fn (quote v/vega-lite-viewer) :transform-fn mark-presented}) (def markdown-viewer {:name :markdown :transform-fn (fn [wrapped-value] (-> wrapped-value mark-presented (update :nextjournal/value #(cond->> % (string? %) md/parse)) (update :nextjournal/viewers add-viewers markdown-viewers) (with-md-viewer)))}) (def code-viewer {:name :code :render-fn (quote v/code-viewer) :transform-fn (comp mark-presented (update-val (fn [v] (if (string? v) v (str/trim (with-out-str (pprint/pprint v)))))))}) (def code-folded-viewer {:name :code-folded :render-fn (quote v/foldable-code-viewer) :transform-fn (comp mark-presented (update-val (fn [v] (if (string? v) v (with-out-str (pprint/pprint v))))))}) (def reagent-viewer {:name :reagent :render-fn (quote v/reagent-viewer) :transform-fn mark-presented}) (def row-viewer {:name :row :render-fn '(fn [items opts] (let [item-count (count items)] (v/html (into [:div {:class "md:flex md:flex-row md:gap-4 not-prose" :style opts}] (map (fn [item] [:div.flex.items-center.justify-center.flex-auto (v/inspect opts item)])) items))))}) (def col-viewer {:name :col :render-fn '(fn [items opts] (v/html (into [:div {:class "md:flex md:flex-col md:gap-4 clerk-grid not-prose" :style opts}] (map (fn [item] [:div.flex.items-center.justify-center (v/inspect opts item)])) items)))}) (def table-viewer {:name :table :transform-fn (fn [wrapped-value] (if-let [{:keys [head rows]} (normalize-table-data (->value wrapped-value))] (-> wrapped-value (assoc :nextjournal/viewer :table/markup) (update :nextjournal/width #(or % :wide)) (update :nextjournal/viewers update-table-viewers) (assoc :nextjournal/opts {:num-cols (-> rows first count) :number-col? (mapv number? (first rows))}) (assoc :nextjournal/value (cond->> [(with-viewer :table/body (map (partial with-viewer :table/row) rows))] head (cons (with-viewer :table/head head))))) (-> wrapped-value mark-presented (assoc :nextjournal/width :wide) (assoc :nextjournal/value [(present wrapped-value)]) (assoc :nextjournal/viewer {:render-fn 'v/table-error}))))}) (def table-error-viewer {:name :table-error :render-fn (quote v/table-error) :fetch-opts {:n 1}}) (def code-block-viewer {:name :clerk/code-block :transform-fn (fn [{:as wrapped-value :nextjournal/keys [value]}] (-> wrapped-value (assoc :nextjournal/viewer (if (:fold? value) :code-folded :code)) (update :nextjournal/value :text)))}) (def tagged-value-viewer {:name :tagged-value :render-fn '(fn [{:keys [tag value space?]}] (v/html (v/tagged-value {:space? space?} (str "#" tag) [v/inspect-paginated value]))) :transform-fn (fn [wrapped-value] (-> wrapped-value (update-in [:nextjournal/value :value] present) mark-presented))}) (def result-viewer {:name :clerk/result :render-fn (quote v/result-viewer) :transform-fn mark-presented}) #?(:clj (defn process-blocks [viewers {:as doc :keys [ns]}] (-> doc (update :blocks (partial into [] (comp (mapcat (partial with-block-viewer doc)) (map (comp #(vector (->ViewerEval 'v/inspect) %) process-wrapped-value apply-viewers* (partial ensure-wrapped-with-viewers viewers)))))) (select-keys [:blocks :toc :title]) (cond-> ns (assoc :scope (datafy-scope ns)))))) (def notebook-viewer {:name :clerk/notebook :render-fn (quote v/notebook-viewer) :transform-fn #?(:cljs identity :clj (fn [{:as wrapped-value :nextjournal/keys [viewers]}] (-> wrapped-value (update :nextjournal/value (partial process-blocks viewers)) mark-presented)))}) (def hide-result-viewer {:name :hide-result :transform-fn (fn [_] nil)}) (def default-viewers ;; maybe make this a sorted-map [char-viewer string-viewer number-viewer number-hex-viewer symbol-viewer keyword-viewer nil-viewer boolean-viewer map-entry-viewer var-from-def-viewer read+inspect-viewer vector-viewer set-viewer sequential-viewer map-viewer var-viewer throwable-viewer buffered-image-viewer ideref-viewer regex-viewer fallback-viewer elision-viewer katex-viewer mathjax-viewer html-viewer plotly-viewer vega-lite-viewer markdown-viewer code-viewer code-folded-viewer reagent-viewer row-viewer col-viewer table-viewer table-error-viewer code-block-viewer tagged-value-viewer result-viewer notebook-viewer hide-result-viewer]) (defonce ^{:doc "atom containing a map of and per-namespace viewers or `:defaults` overridden viewers."} !viewers (#?(:clj atom :cljs ratom/atom) {})) #_(reset! !viewers {}) ;; heavily inspired by code from PI:NAME:<NAME>END_PI in shadow-cljs, see ;; https://github.com/thheller/shadow-cljs/blob/1708acb21bcdae244b50293d17633ce35a78a467/src/main/shadow/remote/runtime/obj_support.cljc#L118-L144 (defn rank-val [val] (reduce-kv (fn [res idx pred] (if (and (ifn? pred) (pred val)) (reduced idx) res)) -1 (into [] (map :pred) default-viewers))) (defn resilient-compare [a b] (try (compare a b) (catch #?(:clj Exception :cljs js/Error) _e (compare (rank-val a) (rank-val b))))) (defn ensure-sorted [xs] (cond (sorted? xs) xs (map? xs) (sort-by first resilient-compare xs) (set? xs) (sort resilient-compare xs) :else xs)) (defn find-viewer [viewers select-fn] (first (filter select-fn viewers))) #_(find-viewer default-viewers (comp #{string?} :pred)) #_(find-viewer default-viewers (comp #{:elision} :name)) (defn find-named-viewer [viewers viewer-name] (find-viewer viewers (comp #{viewer-name} :name))) #_(find-named-viewer default-viewers :elision) (defn viewer-for [viewers x] (or (when-let [selected-viewer (->viewer x)] (if (keyword? selected-viewer) (or (find-named-viewer viewers selected-viewer) (throw (ex-info (str "cannot find viewer named " selected-viewer) {:selected-viewer selected-viewer :viewers viewers}))) selected-viewer)) (find-viewer viewers (let [v (->value x)] (fn [{:keys [pred]}] (and (ifn? pred) (pred v))))) (throw (ex-info (str "cannot find matching viewer for value") {:value (->value x) :viewers viewers :x x})))) #_(viewer-for default-viewers [1 2 3]) #_(viewer-for default-viewers {:nextjournal/value [1 2 3]}) #_(viewer-for default-viewers 42) #_(viewer-for default-viewers (with-viewer :html [:h1 "Hello Hiccup"])) #_(viewer-for default-viewers (with-viewer {:transform-fn identity} [:h1 "Hello Hiccup"])) (defn ensure-wrapped-with-viewers ([x] (ensure-wrapped-with-viewers (get-viewers *ns*) x)) ([viewers x] (-> x ensure-wrapped (update :nextjournal/viewers (fn [x-viewers] (or x-viewers viewers)))))) #_(ensure-wrapped-with-viewers 42) #_(ensure-wrapped-with-viewers {:nextjournal/value 42 :nextjournal/viewers [:boo]}) (defn ->opts [wrapped-value] (select-keys wrapped-value [:nextjournal/width :nextjournal/opts :!budget :budget :path :current-path :offset])) (defn apply-viewers* [wrapped-value] (when (empty? (->viewers wrapped-value)) (throw (ex-info "cannot apply empty viewers" {:wrapped-value wrapped-value}))) (let [viewers (->viewers wrapped-value) {:as viewer :keys [render-fn transform-fn]} (viewer-for viewers wrapped-value) transformed-value (ensure-wrapped-with-viewers viewers (cond-> (dissoc wrapped-value :nextjournal/viewer) transform-fn transform-fn)) wrapped-value' (cond-> transformed-value (-> transformed-value ->value wrapped-value?) (merge (->value transformed-value)))] (if (and transform-fn (not render-fn)) (recur wrapped-value') (-> wrapped-value' (assoc :nextjournal/viewer viewer) (merge (->opts wrapped-value)))))) (defn apply-viewers [x] (apply-viewers* (ensure-wrapped-with-viewers x))) #_(apply-viewers 42) #_(apply-viewers {:one :two}) #_(apply-viewers {:one :two}) #_(apply-viewers [1 2 3]) #_(apply-viewers (range 3)) #_(apply-viewers (clojure.java.io/file "notebooks")) #_(apply-viewers (md "# Hello")) #_(apply-viewers (html [:h1 "hi"])) #_(apply-viewers (with-viewer :elision {:remaining 10 :count 30 :offset 19})) #_(apply-viewers (with-viewer (->Form '(fn [name] (html [:<> "Hello " name]))) "PI:NAME:<NAME>END_PI")) #_(apply-viewers (with-viewers [{:pred (constantly true) :render-fn '(fn [x] [:h1 "hi"])}] 42)) (defn count-viewers "Helper function to walk a given `x` and replace the viewers with their counts. Useful for debugging." [x] (w/postwalk #(if (wrapped-value? %) (cond-> (dissoc % :!budget) (:nextjournal/viewers %) (-> #_% (update :nextjournal/viewers count) (set/rename-keys {:nextjournal/viewers :nextjournal/viewers-count}))) %) x)) (defn bounded-count-opts [n xs] (when-not (number? n) (throw (ex-info "n must be a number?" {:n n :xs xs}))) (let [limit (+ n #?(:clj config/*bounded-count-limit* :cljs 10000)) total (try (bounded-count limit xs) (catch #?(:clj Exception :cljs js/Error) _ nil))] (cond-> {} total (assoc :total total) (or (not total) (= total limit)) (assoc :unbounded? true)))) #_(bounded-count-opts 20 (range)) #_(bounded-count-opts 20 (range 3234567)) (defn drop+take-xf "Takes a map with optional `:n` and `:offset` and returns a transducer that drops `:offset` and takes `:n`." [{:keys [n offset] :or {offset 0}}] (cond-> (drop offset) (int? n) (comp (take n)))) #_(sequence (drop+take-xf {:n 10}) (range 100)) #_(sequence (drop+take-xf {:n 10 :offset 10}) (range 100)) #_(sequence (drop+take-xf {}) (range 9)) (declare assign-closing-parens) (defn process-render-fn [{:as viewer :keys [render-fn]}] (cond-> viewer (and render-fn (not (viewer-fn? render-fn))) (update :render-fn ->viewer-fn))) (defn process-viewer [viewer] (if-not (map? viewer) viewer (-> viewer (dissoc :pred :transform-fn :update-viewers-fn) process-render-fn))) #_(process-viewer {:render-fn '(v/html [:h1]) :transform-fn mark-presented}) (defn process-wrapped-value [wrapped-value] (-> wrapped-value (select-keys [:nextjournal/viewer :nextjournal/value :nextjournal/width :nextjournal/content-type :nextjournal/opts :path :offset :n]) (update :nextjournal/viewer process-viewer))) #_(process-wrapped-value (apply-viewers 42)) (defn make-elision [viewers fetch-opts] (->> (with-viewer :elision fetch-opts) (ensure-wrapped-with-viewers viewers) apply-viewers process-wrapped-value)) #_(make-elision default-viewers {:n 20}) (defn find-elision [desc] (->value (first (filter (comp #{:elision} :name :nextjournal/viewer) (tree-seq (some-fn map? vector?) #(cond-> % (map? %) vals) desc))))) (defn ->fetch-opts [wrapped-value] (merge (-> wrapped-value ->viewer :fetch-opts) (select-keys wrapped-value [:path :offset]))) (defn get-elision [wrapped-value] (let [{:as fetch-opts :keys [path offset n]} (->fetch-opts wrapped-value)] (merge fetch-opts (bounded-count-opts n (->value wrapped-value))))) #_(get-elision (present (range))) #_(get-elision (present "abc")) #_(get-elision (present (str/join (repeat 1000 "abc")))) (defn get-fetch-opts-n [wrapped-value] (-> wrapped-value ->fetch-opts :n)) (defn inherit-opts [{:as wrapped-value :nextjournal/keys [viewers]} value path-segment] (-> (ensure-wrapped-with-viewers viewers value) (merge (->opts wrapped-value)) (dissoc :offset) (update :path (fnil conj []) path-segment) (update :current-path (fnil conj []) path-segment))) (defn present+paginate-children [{:as wrapped-value :nextjournal/keys [viewers preserve-keys?] :keys [!budget budget]}] (let [{:as fetch-opts :keys [path offset n]} (->fetch-opts wrapped-value) xs (->value wrapped-value) paginate? (and (number? n) (not preserve-keys?)) fetch-opts' (cond-> fetch-opts (and paginate? !budget (not (map-entry? xs))) (update :n min @!budget)) children (if preserve-keys? (into {} (map (fn [[k v]] [k (present* (inherit-opts wrapped-value v k))])) xs) (into [] (comp (if paginate? (drop+take-xf fetch-opts') identity) (map-indexed (fn [i x] (present* (inherit-opts wrapped-value x (+ i (or offset 0)))))) (remove nil?)) (ensure-sorted xs))) {:as elision :keys [total unbounded?]} (and paginate? (get-elision wrapped-value)) new-offset (when paginate? (or (some-> children peek :path peek inc) 0))] (cond-> children (and paginate? (or unbounded? (< new-offset total))) (conj (let [fetch-opts (assoc elision :offset new-offset)] (make-elision viewers fetch-opts)))))) (defn present+paginate-string [{:as wrapped-value :nextjournal/keys [viewers viewer value]}] (let [{:as elision :keys [n total path offset]} (and (-> viewer :fetch-opts :n) (get-elision wrapped-value))] (if (and n (< n total)) (let [new-offset (min (+ (or offset 0) n) total)] (cond-> [(subs value (or offset 0) new-offset)] (pos? (- total new-offset)) (conj (let [fetch-opts (-> elision (assoc :offset new-offset :replace-path (conj path new-offset)))] (make-elision viewers fetch-opts))) true ensure-wrapped)) value))) (defn ^:private present* [{:as wrapped-value :keys [path current-path !budget] :nextjournal/keys [viewers]}] (when (empty? viewers) (throw (ex-info "cannot present* with empty viewers" {:wrapped-value wrapped-value}))) (let [{:as wrapped-value :nextjournal/keys [viewers presented?]} (apply-viewers* wrapped-value) descend? (< (count current-path) (count path)) xs (->value wrapped-value)] #_(prn :xs xs :type (type xs) :path path :current-path current-path :descend? descend?) (when (and !budget (not descend?) (not presented?)) (swap! !budget #(max (dec %) 0))) (-> (merge (->opts wrapped-value) (with-viewer (->viewer wrapped-value) (cond presented? wrapped-value descend? ;; TODO: can this be unified, simplified, or even dropped in favor of continuation? (let [idx (first (drop (count current-path) path))] (present* (-> (ensure-wrapped-with-viewers viewers (cond (and (map? xs) (keyword? idx)) (get xs idx) (or (map? xs) (set? xs)) (nth (seq (ensure-sorted xs)) idx) (associative? xs) (get xs idx) (sequential? xs) (nth xs idx))) (merge (->opts wrapped-value)) (update :current-path (fnil conj []) idx)))) (string? xs) (present+paginate-string wrapped-value) (and xs (seqable? xs)) (present+paginate-children wrapped-value) :else ;; leaf value xs))) process-wrapped-value))) (defn present "Returns a subset of a given `value`." ([x] (present x {})) ([x opts] (-> (ensure-wrapped-with-viewers x) (merge {:!budget (atom (:budget opts 200)) :path (:path opts []) :current-path (:current-path opts [])} opts) present* assign-closing-parens))) (comment (present 42) (present [42]) (-> (present (range 100)) ->value peek) (present {:hello [1 2 3]}) (present {:one [1 2 3] 1 2 3 4}) (present [1 2 [1 [2] 3] 4 5]) (present (clojure.java.io/file "notebooks")) (present {:viewers [{:pred sequential? :render-fn pr-str}]} (range 100)) (present (map vector (range))) (present (subs (slurp "/usr/share/dict/words") 0 1000)) (present (plotly {:data [{:z [[1 2 3] [3 2 1]] :type "surface"}]})) (present [(with-viewer :html [:h1 "hi"])]) (present (with-viewer :html [:ul (for [x (range 3)] [:li x])])) (present (range)) (present {1 [2]}) (present (with-viewer '(fn [name] (html [:<> "Hello " name])) "PI:NAME:<NAME>END_PI"))) (defn desc->values "Takes a `description` and returns its value. Inverse of `present`. Mostly useful for debugging." [desc] (let [x (->value desc) viewer-name (-> desc ->viewer :name)] (cond (= viewer-name :elision) (with-meta '… x) (coll? x) (into (case viewer-name ;; TODO: fix table viewer (:map :table) {} (or (empty x) [])) (map desc->values) x) :else x))) #_(desc->values (present [1 [2 {:a :b} 2] 3 (range 100)])) #_(desc->values (present (table (mapv vector (range 30))))) #_(desc->values (present (with-viewer :table (normalize-table-data (repeat 60 ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" 50 30 200 5000 :female]))))) (defn path-to-value [path] (conj (interleave path (repeat :nextjournal/value)) :nextjournal/value)) (defn merge-presentations [root more elision] (update-in root (path-to-value (:path elision)) (fn [value] (let [{:keys [offset path]} (-> value peek :nextjournal/value) path-from-value (conj path offset) path-from-more (or (:replace-path elision) ;; string case, TODO find a better way to unify (-> more :nextjournal/value first :path))] (when (not= path-from-value path-from-more) (throw (ex-info "paths mismatch" {:path-from-value path-from-value :path-from-more path-from-more :root root :more more :path-to-value (path-to-value (:path more)) :value value}))) (into (pop value) (:nextjournal/value more)))))) (defn assign-closing-parens ([node] (assign-closing-parens '() node)) ([closing-parens node] (let [value (->value node) viewer (->viewer node) closing (:closing-paren viewer) non-leaf? (and (vector? value) (wrapped-value? (first value))) defer-closing? (and non-leaf? (or (-> value last :nextjournal/viewer :closing-paren) ;; the last element can carry parens (and (= :map-entry (-> value last :nextjournal/viewer :name)) ;; the last element is a map entry whose value can carry parens (-> value last :nextjournal/value last :nextjournal/viewer :closing-paren))))] (cond-> (cond (not closing) node defer-closing? (update node :nextjournal/viewer dissoc :closing-paren) :else (update-in node [:nextjournal/viewer :closing-paren] cons closing-parens)) non-leaf? (update :nextjournal/value (fn [xs] (into [] (map-indexed (fn [i x] (assign-closing-parens (if (and defer-closing? (= (dec (count xs)) i)) (cond->> closing-parens closing (cons closing)) '()) x))) xs))))))) (defn reset-viewers! ([viewers] (reset-viewers! *ns* viewers)) ([scope viewers] (assert (or (#{:default} scope) #?(:clj (instance? clojure.lang.Namespace scope)))) (swap! !viewers assoc scope viewers))) (defn add-viewers! [viewers] (reset-viewers! *ns* (add-viewers (get-default-viewers) viewers)) viewers) (defn ^{:deprecated "0.8"} set-viewers! [viewers] (binding #?(:clj [*out* *err*] :cljs []) (prn "`set-viewers!` has been deprecated, please use `add-viewers!` or `reset-viewers!` instead.")) (add-viewers! viewers)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; public convenience api (def html (partial with-viewer :html)) (def md (partial with-viewer :markdown)) (def plotly (partial with-viewer :plotly)) (def vl (partial with-viewer :vega-lite)) (def table (partial with-viewer :table)) (def row (partial with-viewer-extracting-opts :row)) (def col (partial with-viewer-extracting-opts :col)) (def tex (partial with-viewer :latex)) (def hide-result (partial with-viewer :hide-result)) (def notebook (partial with-viewer :clerk/notebook)) (defn doc-url [path] (->viewer-eval (list 'v/doc-url path))) (def code (partial with-viewer :code)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; examples (def example-viewer {:transform-fn (fn [{:as wrapped-value :nextjournal/keys [viewers] :keys [path current-path]}] (-> wrapped-value mark-preserve-keys (assoc :nextjournal/viewer {:render-fn '(fn [{:keys [form val]} opts] (v/html [:div.flex.flex-wrap {:class "py-[7px]"} [:div [:div.bg-slate-100.px-2.rounded (v/inspect opts form)]] [:div.flex.mt-1 [:div.mx-2.font-sans.text-xs.text-slate-500 {:class "mt-[2px]"} "⇒"] (v/inspect opts val)]]))}) (update-in [:nextjournal/value :form] code)))}) (def examples-viewer {:transform-fn (update-val (fn [examples] (mapv (partial with-viewer example-viewer) examples))) :render-fn '(fn [examples opts] (v/html (into [:div.border-l-2.border-slate-300.pl-4 [:div.uppercase.tracking-wider.text-xs.font-sans.text-slate-500.mt-4.mb-2 "Examples"]] (v/inspect-children opts) examples)))})
[ { "context": "L_CONTROL\n [{:ID \\\"AUTH_KEY\\\" :DisplayName \\\"Some Name\\\"}\n {:URI \\\"http://groups/group-uri\\\"}", "end": 216, "score": 0.6656014919281006, "start": 212, "tag": "NAME", "value": "Some" }, { "context": "NTROL\n [{:ID \\\"AUTH_KEY\\\" :DisplayName \\\"Some Name\\\"}\n {:URI \\\"http://groups/group-uri\\\"}]\n ", "end": 221, "score": 0.7172280550003052, "start": 217, "tag": "USERNAME", "value": "Name" } ]
src/io/pithos/acl.clj
exoscale/pithos
222
(ns io.pithos.acl "The purpose of this namespace is to coerce to and from the internal representation of ACLs. The current representation is: {:FULL_CONTROL [{:ID \"AUTH_KEY\" :DisplayName \"Some Name\"} {:URI \"http://groups/group-uri\"}] ...} " (:require [clojure.data.xml :refer [parse-str emit-str indent-str]] [clojure.zip :refer [xml-zip node root]] [clojure.data.zip :refer [children]] [clojure.data.zip.xml :refer [xml-> xml1-> text]] [io.pithos.xml :refer [seq->xml]])) ;; ### XML ACL parsing functions ;; ;; We're doing a very sloppy type of schema validation ;; this should likely move to a stricter XSD validation ;; phase. (def ^{:doc "List of known permissions. Valid in ACLs"} valid-permission? #{:FULL_CONTROL :READ :WRITE :READ_ACP :WRITE_ACP}) (def ^{:doc "List of known tags in grantees"} valid-grantee-tag? #{:ID :DisplayName :URI :EmailAddress}) (def ^{:doc "List of known URIs"} known-uris {"http://acs.amazonaws.com/groups/global/AllUsers" "anonymous"}) (def ^{:doc "List of known Groups"} known-groups (reduce merge {} (map (juxt val key) known-uris))) (defn node->grantee-spec "Produce a grantee specifier (ID, DisplayName or URI)" [n] (let [{:keys [tag content]} (node n) text (first content)] (when (and (valid-grantee-tag? tag) (string? text)) (cond (= :URI tag) (hash-map tag (or (known-uris text) text)) (= :EmailAddress tag) (hash-map :ID text) :else (hash-map tag text))))) (defn node->grantee "Produce a valid grantee." [n] (reduce merge {} (xml-> n children node->grantee-spec))) (defn node->grant "Each grant in an input body shoudl contain at least an ID and DisplayName or a URI" [node] (hash-map (xml1-> node :Permission text (fnil keyword "invalid")) (vec (xml-> node :Grantee node->grantee)))) (defn safe-xml-zip "Ingest an XML representation, safely, throwing explicit and details errors." [src] (try (let [tree (xml-zip (parse-str src)) {:keys [tag]} (root tree)] (when-not (= :AccessControlPolicy tag) (throw (ex-info "XML Root Node should be AccessControlPolicy" {:type :invalid-xml-root-node :expected :AccessControlPolicy :got tag}))) tree) (catch clojure.lang.ExceptionInfo e (throw e)) (catch Exception e (throw (ex-info "Invalid XML in ACL Body" {:type :invalid-acl-xml :status-code 400}))))) (defn xml->acl "Given an XML source, try to parse it and return valid" [src] (let [xml-tree (safe-xml-zip src) policies (xml-> xml-tree :AccessControlList :Grant node->grant) policy (apply merge-with (comp vec concat) policies)] (when-not (every? valid-permission? (keys policy)) (throw (ex-info "Invalid XML Acl Body" {:type :invalid-acl-xml :status-code 400}))) policy)) (defn grant->permission "Generate grant XML tags from a hash map of permissions to grantees" [[permission grantees]] (let [xmlns-xsi "http://www.w3.org/2001/XMLSchema-instance"] (for [{:keys [ID DisplayName URI]} grantees] [:Grant (if URI [:Grantee {:xmlns:xsi xmlns-xsi :xsi:type "Group"} [:URI (or (known-groups URI) URI)] [:DisplayName (or DisplayName URI)]] [:Grantee {:xmlns:xsi xmlns-xsi :xsi:type "CanonicalUser"} [:ID ID] [:DisplayName (or DisplayName ID)]]) [:Permission (name permission)]]))) (defn as-xml "Given an internal representation of an ACL, output a valid XML representation. Optionaly supply a boolean to indicate whether to indent the output" ([grants indent?] (let [xmlns "http://s3.amazonaws.com/doc/2006-03-01/" format (if indent? indent-str emit-str)] (format (seq->xml [:AccessControlPolicy {:xmlns xmlns} [:Owner [:ID "foo"] [:DisplayName "bar"]] (apply vector :AccessControlList (mapcat grant->permission grants))])))) ([grants] (as-xml grants false)))
95513
(ns io.pithos.acl "The purpose of this namespace is to coerce to and from the internal representation of ACLs. The current representation is: {:FULL_CONTROL [{:ID \"AUTH_KEY\" :DisplayName \"<NAME> Name\"} {:URI \"http://groups/group-uri\"}] ...} " (:require [clojure.data.xml :refer [parse-str emit-str indent-str]] [clojure.zip :refer [xml-zip node root]] [clojure.data.zip :refer [children]] [clojure.data.zip.xml :refer [xml-> xml1-> text]] [io.pithos.xml :refer [seq->xml]])) ;; ### XML ACL parsing functions ;; ;; We're doing a very sloppy type of schema validation ;; this should likely move to a stricter XSD validation ;; phase. (def ^{:doc "List of known permissions. Valid in ACLs"} valid-permission? #{:FULL_CONTROL :READ :WRITE :READ_ACP :WRITE_ACP}) (def ^{:doc "List of known tags in grantees"} valid-grantee-tag? #{:ID :DisplayName :URI :EmailAddress}) (def ^{:doc "List of known URIs"} known-uris {"http://acs.amazonaws.com/groups/global/AllUsers" "anonymous"}) (def ^{:doc "List of known Groups"} known-groups (reduce merge {} (map (juxt val key) known-uris))) (defn node->grantee-spec "Produce a grantee specifier (ID, DisplayName or URI)" [n] (let [{:keys [tag content]} (node n) text (first content)] (when (and (valid-grantee-tag? tag) (string? text)) (cond (= :URI tag) (hash-map tag (or (known-uris text) text)) (= :EmailAddress tag) (hash-map :ID text) :else (hash-map tag text))))) (defn node->grantee "Produce a valid grantee." [n] (reduce merge {} (xml-> n children node->grantee-spec))) (defn node->grant "Each grant in an input body shoudl contain at least an ID and DisplayName or a URI" [node] (hash-map (xml1-> node :Permission text (fnil keyword "invalid")) (vec (xml-> node :Grantee node->grantee)))) (defn safe-xml-zip "Ingest an XML representation, safely, throwing explicit and details errors." [src] (try (let [tree (xml-zip (parse-str src)) {:keys [tag]} (root tree)] (when-not (= :AccessControlPolicy tag) (throw (ex-info "XML Root Node should be AccessControlPolicy" {:type :invalid-xml-root-node :expected :AccessControlPolicy :got tag}))) tree) (catch clojure.lang.ExceptionInfo e (throw e)) (catch Exception e (throw (ex-info "Invalid XML in ACL Body" {:type :invalid-acl-xml :status-code 400}))))) (defn xml->acl "Given an XML source, try to parse it and return valid" [src] (let [xml-tree (safe-xml-zip src) policies (xml-> xml-tree :AccessControlList :Grant node->grant) policy (apply merge-with (comp vec concat) policies)] (when-not (every? valid-permission? (keys policy)) (throw (ex-info "Invalid XML Acl Body" {:type :invalid-acl-xml :status-code 400}))) policy)) (defn grant->permission "Generate grant XML tags from a hash map of permissions to grantees" [[permission grantees]] (let [xmlns-xsi "http://www.w3.org/2001/XMLSchema-instance"] (for [{:keys [ID DisplayName URI]} grantees] [:Grant (if URI [:Grantee {:xmlns:xsi xmlns-xsi :xsi:type "Group"} [:URI (or (known-groups URI) URI)] [:DisplayName (or DisplayName URI)]] [:Grantee {:xmlns:xsi xmlns-xsi :xsi:type "CanonicalUser"} [:ID ID] [:DisplayName (or DisplayName ID)]]) [:Permission (name permission)]]))) (defn as-xml "Given an internal representation of an ACL, output a valid XML representation. Optionaly supply a boolean to indicate whether to indent the output" ([grants indent?] (let [xmlns "http://s3.amazonaws.com/doc/2006-03-01/" format (if indent? indent-str emit-str)] (format (seq->xml [:AccessControlPolicy {:xmlns xmlns} [:Owner [:ID "foo"] [:DisplayName "bar"]] (apply vector :AccessControlList (mapcat grant->permission grants))])))) ([grants] (as-xml grants false)))
true
(ns io.pithos.acl "The purpose of this namespace is to coerce to and from the internal representation of ACLs. The current representation is: {:FULL_CONTROL [{:ID \"AUTH_KEY\" :DisplayName \"PI:NAME:<NAME>END_PI Name\"} {:URI \"http://groups/group-uri\"}] ...} " (:require [clojure.data.xml :refer [parse-str emit-str indent-str]] [clojure.zip :refer [xml-zip node root]] [clojure.data.zip :refer [children]] [clojure.data.zip.xml :refer [xml-> xml1-> text]] [io.pithos.xml :refer [seq->xml]])) ;; ### XML ACL parsing functions ;; ;; We're doing a very sloppy type of schema validation ;; this should likely move to a stricter XSD validation ;; phase. (def ^{:doc "List of known permissions. Valid in ACLs"} valid-permission? #{:FULL_CONTROL :READ :WRITE :READ_ACP :WRITE_ACP}) (def ^{:doc "List of known tags in grantees"} valid-grantee-tag? #{:ID :DisplayName :URI :EmailAddress}) (def ^{:doc "List of known URIs"} known-uris {"http://acs.amazonaws.com/groups/global/AllUsers" "anonymous"}) (def ^{:doc "List of known Groups"} known-groups (reduce merge {} (map (juxt val key) known-uris))) (defn node->grantee-spec "Produce a grantee specifier (ID, DisplayName or URI)" [n] (let [{:keys [tag content]} (node n) text (first content)] (when (and (valid-grantee-tag? tag) (string? text)) (cond (= :URI tag) (hash-map tag (or (known-uris text) text)) (= :EmailAddress tag) (hash-map :ID text) :else (hash-map tag text))))) (defn node->grantee "Produce a valid grantee." [n] (reduce merge {} (xml-> n children node->grantee-spec))) (defn node->grant "Each grant in an input body shoudl contain at least an ID and DisplayName or a URI" [node] (hash-map (xml1-> node :Permission text (fnil keyword "invalid")) (vec (xml-> node :Grantee node->grantee)))) (defn safe-xml-zip "Ingest an XML representation, safely, throwing explicit and details errors." [src] (try (let [tree (xml-zip (parse-str src)) {:keys [tag]} (root tree)] (when-not (= :AccessControlPolicy tag) (throw (ex-info "XML Root Node should be AccessControlPolicy" {:type :invalid-xml-root-node :expected :AccessControlPolicy :got tag}))) tree) (catch clojure.lang.ExceptionInfo e (throw e)) (catch Exception e (throw (ex-info "Invalid XML in ACL Body" {:type :invalid-acl-xml :status-code 400}))))) (defn xml->acl "Given an XML source, try to parse it and return valid" [src] (let [xml-tree (safe-xml-zip src) policies (xml-> xml-tree :AccessControlList :Grant node->grant) policy (apply merge-with (comp vec concat) policies)] (when-not (every? valid-permission? (keys policy)) (throw (ex-info "Invalid XML Acl Body" {:type :invalid-acl-xml :status-code 400}))) policy)) (defn grant->permission "Generate grant XML tags from a hash map of permissions to grantees" [[permission grantees]] (let [xmlns-xsi "http://www.w3.org/2001/XMLSchema-instance"] (for [{:keys [ID DisplayName URI]} grantees] [:Grant (if URI [:Grantee {:xmlns:xsi xmlns-xsi :xsi:type "Group"} [:URI (or (known-groups URI) URI)] [:DisplayName (or DisplayName URI)]] [:Grantee {:xmlns:xsi xmlns-xsi :xsi:type "CanonicalUser"} [:ID ID] [:DisplayName (or DisplayName ID)]]) [:Permission (name permission)]]))) (defn as-xml "Given an internal representation of an ACL, output a valid XML representation. Optionaly supply a boolean to indicate whether to indent the output" ([grants indent?] (let [xmlns "http://s3.amazonaws.com/doc/2006-03-01/" format (if indent? indent-str emit-str)] (format (seq->xml [:AccessControlPolicy {:xmlns xmlns} [:Owner [:ID "foo"] [:DisplayName "bar"]] (apply vector :AccessControlList (mapcat grant->permission grants))])))) ([grants] (as-xml grants false)))
[ { "context": " :name \"42\"\n ", "end": 6041, "score": 0.5310879945755005, "start": 6040, "tag": "NAME", "value": "4" }, { "context": " :bearer-token \"fake-token\"\n :team-name \"", "end": 6476, "score": 0.5829978585243225, "start": 6466, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :bearer-token \"fake-token\"\n :team-name \"", "end": 7769, "score": 0.5639308094978333, "start": 7759, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :bearer-token \"fake-token\"\n :team-name \"", "end": 9149, "score": 0.6592671871185303, "start": 9139, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :name \"43\"\n ", "end": 10569, "score": 0.7259361743927002, "start": 10567, "tag": "NAME", "value": "43" }, { "context": " :bearer-token \"fake-token\"\n :team-name \"", "end": 11406, "score": 0.8824203014373779, "start": 11396, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :name \"43\"\n ", "end": 12175, "score": 0.7877312898635864, "start": 12173, "tag": "NAME", "value": "43" }, { "context": " :name \"42\"\n ", "end": 12621, "score": 0.6480749845504761, "start": 12619, "tag": "NAME", "value": "42" }, { "context": " :name \"42\"\n ", "end": 13252, "score": 0.49873560667037964, "start": 13251, "tag": "NAME", "value": "4" }, { "context": " :name \"42\"\n ", "end": 13253, "score": 0.4823686480522156, "start": 13252, "tag": "USERNAME", "value": "2" }, { "context": " :name \"41\"\n ", "end": 13729, "score": 0.5511963367462158, "start": 13727, "tag": "USERNAME", "value": "41" }, { "context": " :name \"41\"\n ", "end": 14377, "score": 0.5898080468177795, "start": 14375, "tag": "USERNAME", "value": "41" }, { "context": " :bearer-token \"fake-token\"\n :team-name \"", "end": 15426, "score": 0.8947126269340515, "start": 15416, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :name \"42\"\n ", "end": 16559, "score": 0.8874414563179016, "start": 16558, "tag": "NAME", "value": "4" }, { "context": " :name \"41\"\n ", "end": 17005, "score": 0.7097553014755249, "start": 17004, "tag": "NAME", "value": "4" }, { "context": " :bearer-token \"fake-token\"\n ", "end": 17663, "score": 0.5057709813117981, "start": 17653, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :name \"42\"\n ", "end": 18374, "score": 0.8777473568916321, "start": 18373, "tag": "NAME", "value": "4" }, { "context": " :bearer-token \"fake-token\"\n ", "end": 21761, "score": 0.7723560333251953, "start": 21751, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :bearer-token \"fake-token\"\n ", "end": 23880, "score": 0.5331463813781738, "start": 23870, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :bearer-token \"fake-token\"\n ", "end": 28037, "score": 0.9050310254096985, "start": 28027, "tag": "PASSWORD", "value": "fake-token" }, { "context": "tart 1617735354000 :end 1617735361000 :worker \"poiuy0987\"}]\n (:tasks build))))))\n\n (testi", "end": 28317, "score": 0.5699948072433472, "start": 28313, "tag": "USERNAME", "value": "uy09" }, { "context": "5354 :origin {:id \"defg987\"} :selected_worker \"poiuy0987\"}}))\n (let [[[_, [build]]] (sut/concourse-bu", "end": 30023, "score": 0.5870057344436646, "start": 30017, "tag": "USERNAME", "value": "uy0987" }, { "context": " :bearer-token \"fake-token\"\n ", "end": 30188, "score": 0.7925154566764832, "start": 30178, "tag": "PASSWORD", "value": "fake-token" }, { "context": " :start 1617735352000 :end 1617735352000 :worker \"qwerty1234\"}\n {:name \"another task (task)\"", "end": 30361, "score": 0.7551349997520447, "start": 30354, "tag": "USERNAME", "value": "qwerty1" }, { "context": " :start 1617735354000 :end 1617735354000 :worker \"poiuy0987\"}]\n (:tasks build))))))\n\n (testing", "end": 30470, "score": 0.9432947039604187, "start": 30461, "tag": "USERNAME", "value": "poiuy0987" } ]
test/build_facts/concourse/builds_test.clj
cburgmer/build-facts
5
(ns build-facts.concourse.builds-test (:require [build-facts.concourse.builds :as sut] [cheshire.core :as j] [clj-http.fake :as fake] [clj-time [coerce :as tc] [core :as t]] [clojure.string :as string] [clojure.test :refer :all])) (defn- successful-json-response [body] (fn [_] {:status 200 :body (j/generate-string body)})) (defn- a-job [team-name pipeline-name job-name] {:team_name team-name :pipeline_name pipeline-name :name job-name}) (defn- all-jobs [& jobs] ["http://concourse:8000/api/v1/jobs" (successful-json-response jobs)]) (defn- some-builds-up-to [up-to-id team-name pipeline-name job-name & builds] [(format "http://concourse:8000/api/v1/teams/%s/pipelines/%s/jobs/%s/builds?to=%s" team-name pipeline-name job-name up-to-id) (successful-json-response (map #(assoc % :pipeline_name pipeline-name :job_name job-name) builds))]) (defn- some-builds [team-name pipeline-name job-name & builds] (apply some-builds-up-to (concat ["" team-name pipeline-name job-name] builds))) (defn- some-resources [build-id & inputs] [(format "http://concourse:8000/api/v1/builds/%s/resources" build-id) (successful-json-response {:inputs inputs})]) (defn- a-task [id name] {:id id :task {:name name}}) (defn- a-resource-put [id name] {:on_success {:step {:id id :put {:name name}}}}) (defn- some-plan ([build-id] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (successful-json-response {:plan {:do []}})]) ([build-id step] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (successful-json-response {:plan step})])) (defn- no-plan [build-id] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (fn [_] {:status 404})]) (defn- some-events [build-id & event-data] (let [events (concat (map-indexed (fn [idx data] (format "id: %s\nevent: event\ndata: %s" idx (j/generate-string data))) event-data) [(format "id: %s\nevent: end\ndata" (count event-data)) ""])] [(format "http://concourse:8000/api/v1/builds/%s/events" build-id) (fn [_] {:status 200 :body (string/join "\n\n" events)})])) (defn- valid-session [] ["http://concourse:8000/api/v1/user" (successful-json-response {})]) (defn- serve-up [& routes] (into {} routes)) (defn- unix-time-in-s [& params] (/ (tc/to-long (apply t/date-time params)) 1000)) (deftest test-concourse-builds (testing "should sync a successful build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should sync a failing build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "failed" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle a started build and not request any further resources" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "started" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)})) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "ongoing" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle aborted build without start time" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "aborted" :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642401000 :end 1451642401000}]]))))) (testing "should handle errored build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "errored" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000, :end 1451642401000}]]))))) (testing "should not sync builds from a different team" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job") (a-job "another-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds "another-team" "my-pipeline" "my-job" {:id 10 :name "43" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-resources 10) (some-plan 4) (some-plan 10) (some-events 4) (some-events 10)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle pagination for long build histories" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 5 :name "43" :status "succeeded" :start_time (unix-time-in-s 2016 2 1 12 0 0) :end_time (unix-time-in-s 2016 2 1 12 0 1)} {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds-up-to 4 "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)} {:id 2 :name "41" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 2 0 0) :end_time (unix-time-in-s 2016 1 1 2 0 1)}) (some-builds-up-to 2 "my-team" "my-pipeline" "my-job" {:id 2 :name "41" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 2 0 0) :end_time (unix-time-in-s 2016 1 1 2 0 1)}) (some-resources 5) (some-resources 4) (some-resources 2) (some-plan 5) (some-plan 4) (some-plan 2) (some-events 5) (some-events 4) (some-events 2)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "43" :outcome "pass" :start 1454328000000 :end 1454328001000} {:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000} {:job-name "my-pipeline my-job" :build-id "41" :outcome "pass" :start 1451613600000 :end 1451613601000}]]))))) (testing "should resolve builds lazily" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)} {:id 3 :name "41" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 9 0 0) :end_time (unix-time-in-s 2016 1 1 9 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (let [[[_ builds]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})] (first builds)))) ; should not error due to route for build #3 not defined (testing "should handle multiple jobs" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job") (a-job "my-team" "my-pipeline" "another-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds "my-team" "my-pipeline" "another-job" {:id 10 :name "10" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-resources 10) (some-plan 4) (some-plan 10) (some-events 4) (some-events 10)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]] ["my-pipeline another-job" [{:job-name "my-pipeline another-job" :build-id "10" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should expose inputs" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4 {:name "git" :version {:ref "abcd1234"}} {:name "version" :version {:number "1113.0.0"}}) (some-plan 4) (some-events 4)) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})] (is (= [{:revision "abcd1234" :source-id "git[ref]"} {:revision "1113.0.0" :source-id "version[number]"}] (:inputs build)))))) (testing "should expose tasks" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "task one") (a-task "defg987" "another task")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}} {:data {:time 1617735353 :origin {:id "abcd1234"}}} {:data {:time 1617735354 :origin {:id "defg987"}}} {:data {:time 1617735360 :origin {:id "defg987"}}} {:data {:time 1617735361 :origin {:id "defg987"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735351000 :end 1617735353000} {:name "another task (task)" :start 1617735354000 :end 1617735361000}] (:tasks build)))))) (testing "should only report tasks which have been run" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "a task") (a-resource-put "defg9876" "docker")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})] (is (= [{:name "a task (task)" :start 1617735351000 :end 1617735351000}] (:tasks build)))))) (testing "should report worker for task" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "task one") (a-task "defg987" "another task")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}} {:event "selected-worker" :data {:time 1617735352 :origin {:id "abcd1234"} :selected_worker "qwerty1234"}} {:data {:time 1617735353 :origin {:id "abcd1234"}}} {:event "selected-worker" :data {:time 1617735354 :origin {:id "defg987"} :selected_worker "poiuy0987"}} {:data {:time 1617735360 :origin {:id "defg987"}}} {:data {:time 1617735361 :origin {:id "defg987"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735351000 :end 1617735353000 :worker "qwerty1234"} {:name "another task (task)" :start 1617735354000 :end 1617735361000 :worker "poiuy0987"}] (:tasks build)))))) (testing "should handle a plan with an on_failure step" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:on_failure {:step (a-task "abcd1234" "task one") :on_failure (a-task "defg987" "another task")}}) (some-events 4 {:event "selected-worker" :data {:time 1617735352 :origin {:id "abcd1234"} :selected_worker "qwerty1234"}} {:event "selected-worker" :data {:time 1617735354 :origin {:id "defg987"} :selected_worker "poiuy0987"}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735352000 :end 1617735352000 :worker "qwerty1234"} {:name "another task (task)" :start 1617735354000 :end 1617735354000 :worker "poiuy0987"}] (:tasks build)))))) (testing "should make no requests for builds if they are not accessed" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job"))) ;; no expectation, implicitly tests by not failing from missing route (first (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})))) (testing "should handle an aborted build if no plan existed yet" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "aborted" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (no-plan 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000 :end 1451642401000}]]))))))
65587
(ns build-facts.concourse.builds-test (:require [build-facts.concourse.builds :as sut] [cheshire.core :as j] [clj-http.fake :as fake] [clj-time [coerce :as tc] [core :as t]] [clojure.string :as string] [clojure.test :refer :all])) (defn- successful-json-response [body] (fn [_] {:status 200 :body (j/generate-string body)})) (defn- a-job [team-name pipeline-name job-name] {:team_name team-name :pipeline_name pipeline-name :name job-name}) (defn- all-jobs [& jobs] ["http://concourse:8000/api/v1/jobs" (successful-json-response jobs)]) (defn- some-builds-up-to [up-to-id team-name pipeline-name job-name & builds] [(format "http://concourse:8000/api/v1/teams/%s/pipelines/%s/jobs/%s/builds?to=%s" team-name pipeline-name job-name up-to-id) (successful-json-response (map #(assoc % :pipeline_name pipeline-name :job_name job-name) builds))]) (defn- some-builds [team-name pipeline-name job-name & builds] (apply some-builds-up-to (concat ["" team-name pipeline-name job-name] builds))) (defn- some-resources [build-id & inputs] [(format "http://concourse:8000/api/v1/builds/%s/resources" build-id) (successful-json-response {:inputs inputs})]) (defn- a-task [id name] {:id id :task {:name name}}) (defn- a-resource-put [id name] {:on_success {:step {:id id :put {:name name}}}}) (defn- some-plan ([build-id] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (successful-json-response {:plan {:do []}})]) ([build-id step] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (successful-json-response {:plan step})])) (defn- no-plan [build-id] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (fn [_] {:status 404})]) (defn- some-events [build-id & event-data] (let [events (concat (map-indexed (fn [idx data] (format "id: %s\nevent: event\ndata: %s" idx (j/generate-string data))) event-data) [(format "id: %s\nevent: end\ndata" (count event-data)) ""])] [(format "http://concourse:8000/api/v1/builds/%s/events" build-id) (fn [_] {:status 200 :body (string/join "\n\n" events)})])) (defn- valid-session [] ["http://concourse:8000/api/v1/user" (successful-json-response {})]) (defn- serve-up [& routes] (into {} routes)) (defn- unix-time-in-s [& params] (/ (tc/to-long (apply t/date-time params)) 1000)) (deftest test-concourse-builds (testing "should sync a successful build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should sync a failing build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "failed" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle a started build and not request any further resources" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "<NAME>2" :status "started" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)})) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "ongoing" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle aborted build without start time" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "aborted" :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642401000 :end 1451642401000}]]))))) (testing "should handle errored build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "errored" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000, :end 1451642401000}]]))))) (testing "should not sync builds from a different team" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job") (a-job "another-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds "another-team" "my-pipeline" "my-job" {:id 10 :name "<NAME>" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-resources 10) (some-plan 4) (some-plan 10) (some-events 4) (some-events 10)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle pagination for long build histories" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 5 :name "<NAME>" :status "succeeded" :start_time (unix-time-in-s 2016 2 1 12 0 0) :end_time (unix-time-in-s 2016 2 1 12 0 1)} {:id 4 :name "<NAME>" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds-up-to 4 "my-team" "my-pipeline" "my-job" {:id 4 :name "<NAME>2" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)} {:id 2 :name "41" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 2 0 0) :end_time (unix-time-in-s 2016 1 1 2 0 1)}) (some-builds-up-to 2 "my-team" "my-pipeline" "my-job" {:id 2 :name "41" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 2 0 0) :end_time (unix-time-in-s 2016 1 1 2 0 1)}) (some-resources 5) (some-resources 4) (some-resources 2) (some-plan 5) (some-plan 4) (some-plan 2) (some-events 5) (some-events 4) (some-events 2)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "43" :outcome "pass" :start 1454328000000 :end 1454328001000} {:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000} {:job-name "my-pipeline my-job" :build-id "41" :outcome "pass" :start 1451613600000 :end 1451613601000}]]))))) (testing "should resolve builds lazily" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "<NAME>2" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)} {:id 3 :name "<NAME>1" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 9 0 0) :end_time (unix-time-in-s 2016 1 1 9 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (let [[[_ builds]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"})] (first builds)))) ; should not error due to route for build #3 not defined (testing "should handle multiple jobs" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job") (a-job "my-team" "my-pipeline" "another-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "<NAME>2" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds "my-team" "my-pipeline" "another-job" {:id 10 :name "10" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-resources 10) (some-plan 4) (some-plan 10) (some-events 4) (some-events 10)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]] ["my-pipeline another-job" [{:job-name "my-pipeline another-job" :build-id "10" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should expose inputs" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4 {:name "git" :version {:ref "abcd1234"}} {:name "version" :version {:number "1113.0.0"}}) (some-plan 4) (some-events 4)) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"})] (is (= [{:revision "abcd1234" :source-id "git[ref]"} {:revision "1113.0.0" :source-id "version[number]"}] (:inputs build)))))) (testing "should expose tasks" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "task one") (a-task "defg987" "another task")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}} {:data {:time 1617735353 :origin {:id "abcd1234"}}} {:data {:time 1617735354 :origin {:id "defg987"}}} {:data {:time 1617735360 :origin {:id "defg987"}}} {:data {:time 1617735361 :origin {:id "defg987"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735351000 :end 1617735353000} {:name "another task (task)" :start 1617735354000 :end 1617735361000}] (:tasks build)))))) (testing "should only report tasks which have been run" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "a task") (a-resource-put "defg9876" "docker")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})] (is (= [{:name "a task (task)" :start 1617735351000 :end 1617735351000}] (:tasks build)))))) (testing "should report worker for task" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "task one") (a-task "defg987" "another task")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}} {:event "selected-worker" :data {:time 1617735352 :origin {:id "abcd1234"} :selected_worker "qwerty1234"}} {:data {:time 1617735353 :origin {:id "abcd1234"}}} {:event "selected-worker" :data {:time 1617735354 :origin {:id "defg987"} :selected_worker "poiuy0987"}} {:data {:time 1617735360 :origin {:id "defg987"}}} {:data {:time 1617735361 :origin {:id "defg987"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735351000 :end 1617735353000 :worker "qwerty1234"} {:name "another task (task)" :start 1617735354000 :end 1617735361000 :worker "poiuy0987"}] (:tasks build)))))) (testing "should handle a plan with an on_failure step" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:on_failure {:step (a-task "abcd1234" "task one") :on_failure (a-task "defg987" "another task")}}) (some-events 4 {:event "selected-worker" :data {:time 1617735352 :origin {:id "abcd1234"} :selected_worker "qwerty1234"}} {:event "selected-worker" :data {:time 1617735354 :origin {:id "defg987"} :selected_worker "poiuy0987"}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "<PASSWORD>" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735352000 :end 1617735352000 :worker "qwerty1234"} {:name "another task (task)" :start 1617735354000 :end 1617735354000 :worker "poiuy0987"}] (:tasks build)))))) (testing "should make no requests for builds if they are not accessed" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job"))) ;; no expectation, implicitly tests by not failing from missing route (first (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})))) (testing "should handle an aborted build if no plan existed yet" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "aborted" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (no-plan 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000 :end 1451642401000}]]))))))
true
(ns build-facts.concourse.builds-test (:require [build-facts.concourse.builds :as sut] [cheshire.core :as j] [clj-http.fake :as fake] [clj-time [coerce :as tc] [core :as t]] [clojure.string :as string] [clojure.test :refer :all])) (defn- successful-json-response [body] (fn [_] {:status 200 :body (j/generate-string body)})) (defn- a-job [team-name pipeline-name job-name] {:team_name team-name :pipeline_name pipeline-name :name job-name}) (defn- all-jobs [& jobs] ["http://concourse:8000/api/v1/jobs" (successful-json-response jobs)]) (defn- some-builds-up-to [up-to-id team-name pipeline-name job-name & builds] [(format "http://concourse:8000/api/v1/teams/%s/pipelines/%s/jobs/%s/builds?to=%s" team-name pipeline-name job-name up-to-id) (successful-json-response (map #(assoc % :pipeline_name pipeline-name :job_name job-name) builds))]) (defn- some-builds [team-name pipeline-name job-name & builds] (apply some-builds-up-to (concat ["" team-name pipeline-name job-name] builds))) (defn- some-resources [build-id & inputs] [(format "http://concourse:8000/api/v1/builds/%s/resources" build-id) (successful-json-response {:inputs inputs})]) (defn- a-task [id name] {:id id :task {:name name}}) (defn- a-resource-put [id name] {:on_success {:step {:id id :put {:name name}}}}) (defn- some-plan ([build-id] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (successful-json-response {:plan {:do []}})]) ([build-id step] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (successful-json-response {:plan step})])) (defn- no-plan [build-id] [(format "http://concourse:8000/api/v1/builds/%s/plan" build-id) (fn [_] {:status 404})]) (defn- some-events [build-id & event-data] (let [events (concat (map-indexed (fn [idx data] (format "id: %s\nevent: event\ndata: %s" idx (j/generate-string data))) event-data) [(format "id: %s\nevent: end\ndata" (count event-data)) ""])] [(format "http://concourse:8000/api/v1/builds/%s/events" build-id) (fn [_] {:status 200 :body (string/join "\n\n" events)})])) (defn- valid-session [] ["http://concourse:8000/api/v1/user" (successful-json-response {})]) (defn- serve-up [& routes] (into {} routes)) (defn- unix-time-in-s [& params] (/ (tc/to-long (apply t/date-time params)) 1000)) (deftest test-concourse-builds (testing "should sync a successful build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should sync a failing build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "failed" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle a started build and not request any further resources" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "PI:NAME:<NAME>END_PI2" :status "started" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)})) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "ongoing" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle aborted build without start time" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "aborted" :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642401000 :end 1451642401000}]]))))) (testing "should handle errored build" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "errored" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000, :end 1451642401000}]]))))) (testing "should not sync builds from a different team" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job") (a-job "another-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds "another-team" "my-pipeline" "my-job" {:id 10 :name "PI:NAME:<NAME>END_PI" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-resources 10) (some-plan 4) (some-plan 10) (some-events 4) (some-events 10)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should handle pagination for long build histories" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 5 :name "PI:NAME:<NAME>END_PI" :status "succeeded" :start_time (unix-time-in-s 2016 2 1 12 0 0) :end_time (unix-time-in-s 2016 2 1 12 0 1)} {:id 4 :name "PI:NAME:<NAME>END_PI" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds-up-to 4 "my-team" "my-pipeline" "my-job" {:id 4 :name "PI:NAME:<NAME>END_PI2" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)} {:id 2 :name "41" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 2 0 0) :end_time (unix-time-in-s 2016 1 1 2 0 1)}) (some-builds-up-to 2 "my-team" "my-pipeline" "my-job" {:id 2 :name "41" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 2 0 0) :end_time (unix-time-in-s 2016 1 1 2 0 1)}) (some-resources 5) (some-resources 4) (some-resources 2) (some-plan 5) (some-plan 4) (some-plan 2) (some-events 5) (some-events 4) (some-events 2)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "43" :outcome "pass" :start 1454328000000 :end 1454328001000} {:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000} {:job-name "my-pipeline my-job" :build-id "41" :outcome "pass" :start 1451613600000 :end 1451613601000}]]))))) (testing "should resolve builds lazily" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "PI:NAME:<NAME>END_PI2" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)} {:id 3 :name "PI:NAME:<NAME>END_PI1" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 9 0 0) :end_time (unix-time-in-s 2016 1 1 9 0 1)}) (some-resources 4) (some-plan 4) (some-events 4)) (let [[[_ builds]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"})] (first builds)))) ; should not error due to route for build #3 not defined (testing "should handle multiple jobs" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job") (a-job "my-team" "my-pipeline" "another-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "PI:NAME:<NAME>END_PI2" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-builds "my-team" "my-pipeline" "another-job" {:id 10 :name "10" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-resources 10) (some-plan 4) (some-plan 10) (some-events 4) (some-events 10)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "pass" :start 1451642400000 :end 1451642401000}]] ["my-pipeline another-job" [{:job-name "my-pipeline another-job" :build-id "10" :outcome "pass" :start 1451642400000 :end 1451642401000}]]))))) (testing "should expose inputs" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4 {:name "git" :version {:ref "abcd1234"}} {:name "version" :version {:number "1113.0.0"}}) (some-plan 4) (some-events 4)) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"})] (is (= [{:revision "abcd1234" :source-id "git[ref]"} {:revision "1113.0.0" :source-id "version[number]"}] (:inputs build)))))) (testing "should expose tasks" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "task one") (a-task "defg987" "another task")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}} {:data {:time 1617735353 :origin {:id "abcd1234"}}} {:data {:time 1617735354 :origin {:id "defg987"}}} {:data {:time 1617735360 :origin {:id "defg987"}}} {:data {:time 1617735361 :origin {:id "defg987"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735351000 :end 1617735353000} {:name "another task (task)" :start 1617735354000 :end 1617735361000}] (:tasks build)))))) (testing "should only report tasks which have been run" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "a task") (a-resource-put "defg9876" "docker")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})] (is (= [{:name "a task (task)" :start 1617735351000 :end 1617735351000}] (:tasks build)))))) (testing "should report worker for task" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:do [(a-task "abcd1234" "task one") (a-task "defg987" "another task")]}) (some-events 4 {:data {:time 1617735351 :origin {:id "abcd1234"}}} {:event "selected-worker" :data {:time 1617735352 :origin {:id "abcd1234"} :selected_worker "qwerty1234"}} {:data {:time 1617735353 :origin {:id "abcd1234"}}} {:event "selected-worker" :data {:time 1617735354 :origin {:id "defg987"} :selected_worker "poiuy0987"}} {:data {:time 1617735360 :origin {:id "defg987"}}} {:data {:time 1617735361 :origin {:id "defg987"}}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735351000 :end 1617735353000 :worker "qwerty1234"} {:name "another task (task)" :start 1617735354000 :end 1617735361000 :worker "poiuy0987"}] (:tasks build)))))) (testing "should handle a plan with an on_failure step" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "succeeded" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (some-plan 4 {:on_failure {:step (a-task "abcd1234" "task one") :on_failure (a-task "defg987" "another task")}}) (some-events 4 {:event "selected-worker" :data {:time 1617735352 :origin {:id "abcd1234"} :selected_worker "qwerty1234"}} {:event "selected-worker" :data {:time 1617735354 :origin {:id "defg987"} :selected_worker "poiuy0987"}})) (let [[[_, [build]]] (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "PI:PASSWORD:<PASSWORD>END_PI" :team-name "my-team"})] (is (= [{:name "task one (task)" :start 1617735352000 :end 1617735352000 :worker "qwerty1234"} {:name "another task (task)" :start 1617735354000 :end 1617735354000 :worker "poiuy0987"}] (:tasks build)))))) (testing "should make no requests for builds if they are not accessed" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job"))) ;; no expectation, implicitly tests by not failing from missing route (first (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"})))) (testing "should handle an aborted build if no plan existed yet" (fake/with-fake-routes-in-isolation (serve-up (valid-session) (all-jobs (a-job "my-team" "my-pipeline" "my-job")) (some-builds "my-team" "my-pipeline" "my-job" {:id 4 :name "42" :status "aborted" :start_time (unix-time-in-s 2016 1 1 10 0 0) :end_time (unix-time-in-s 2016 1 1 10 0 1)}) (some-resources 4) (no-plan 4)) (is (= (sut/concourse-builds {:base-url "http://concourse:8000" :bearer-token "fake-token" :team-name "my-team"}) '(["my-pipeline my-job" [{:job-name "my-pipeline my-job" :build-id "42" :outcome "fail" :start 1451642400000 :end 1451642401000}]]))))))
[ { "context": "t Employee :Name :ID)\n (def e (struct Employee \"John\" 1))\n (println \"Employee: \", e)\n)\n(main)\n", "end": 125, "score": 0.9975141286849976, "start": 121, "tag": "NAME", "value": "John" } ]
ed/l/clojure/examples/whatever/struct.clj
cn007b/stash
0
(ns clojure.examples.struct (:gen-class)) (defn main [] (defstruct Employee :Name :ID) (def e (struct Employee "John" 1)) (println "Employee: ", e) ) (main)
867
(ns clojure.examples.struct (:gen-class)) (defn main [] (defstruct Employee :Name :ID) (def e (struct Employee "<NAME>" 1)) (println "Employee: ", e) ) (main)
true
(ns clojure.examples.struct (:gen-class)) (defn main [] (defstruct Employee :Name :ID) (def e (struct Employee "PI:NAME:<NAME>END_PI" 1)) (println "Employee: ", e) ) (main)
[ { "context": "-companies\n (let [game-data {:companies [{:name \"Al\"}\n {:name \"Be\"}\n ", "end": 1695, "score": 0.7762704491615295, "start": 1693, "tag": "NAME", "value": "Al" }, { "context": "name \"Al\"}\n {:name \"Be\"}\n {:name \"Ca\"}]\n ", "end": 1739, "score": 0.7299854159355164, "start": 1737, "tag": "NAME", "value": "Be" }, { "context": "t-get-share-values-with-company-names\n (is (= [[\"Altair Starways\" 1800] [\"Betelgeuse, Ltd.\" 700]\n [\"Capel", "end": 4256, "score": 0.9691364169120789, "start": 4241, "tag": "NAME", "value": "Altair Starways" } ]
test/starlanes/finance/company_test.clj
oubiwann/clj-starlanes
1
(ns starlanes.finance.company-test (:require [clojure.test :refer :all] [starlanes.finance.company :as company] [starlanes.util :as util])) (deftest test-get-new-company (let [result (company/get-new-company)] (is (= (result :name) ""))) (let [result (company/get-new-company "A")] (is (= (result :name) "A")))) (deftest test-add-company (is (= [{:name "Al"} {:name "Be"} {:name "Ca"}] (util/fake-game-data :companies))) (let [[company-name game-data] (company/add-company util/fake-game-data)] (is (= [{:name "Al"} {:name "Be"} {:name "Ca"} {:name "De"}] (game-data :companies))) (is (= ["Er"] (game-data :companies-queue))) (is (= "De" company-name)) (let [[company-name game-data] (company/add-company game-data)] (is (= [{:name "Al"} {:name "Be"} {:name "Ca"} {:name "De"} {:name "Er"}] (game-data :companies))) (is (= [] (game-data :companies-queue))) (is (= "Er" company-name))))) (deftest test-filter-company (let [companies [{:name "A"} {:name "B"}]] (is (= [{:name "A"} {:name "B"}] (company/filter-company "a" companies))) (is (= [{:name "B"}] (company/filter-company "A" companies))))) (deftest test-remove-company (let [game-data {:companies [{:name "Al"} {:name "Be"}] :companies-queue ["Ca" "De" "Er"]} game-data (company/remove-company "Al" game-data)] (is (= [{:name "Be"}] (game-data :companies))) (is (= ["Al" "Ca" "De" "Er"] (game-data :companies-queue))))) (deftest test-remove-companies (let [game-data {:companies [{:name "Al"} {:name "Be"} {:name "Ca"}] :companies-queue ["De" "Er"]} game-data (company/remove-companies ["Al" "Ca"] game-data)] (is (= [{:name "Be"}] (game-data :companies))) (is (= ["Al" "Ca" "De" "Er"] (game-data :companies-queue))))) (deftest test-get-companies-base-counts (let [counts (company/get-companies-base-counts util/fake-game-data)] (is (= {"A" 3, "C" 1, "B" 2} counts)) (is (= 3 (counts "A"))) (is (= 2 (counts "B"))) (is (= 1 (counts "C"))) (is (= nil (counts "Z"))))) (deftest test-get-company-base-count (is (= 3 (company/get-company-base-count "A" util/fake-game-data))) (is (= 2 (company/get-company-base-count "B" util/fake-game-data))) (is (= 1 (company/get-company-base-count "C" util/fake-game-data))) (is (= 0 (company/get-company-base-count "Z" util/fake-game-data)))) (deftest test-get-company-star-count (is (= 3 (company/get-company-star-count "A" util/fake-game-data))) (is (= 1 (company/get-company-star-count "B" util/fake-game-data))) (is (= 0 (company/get-company-star-count "C" util/fake-game-data))) (is (= 0 (company/get-company-star-count "Z" util/fake-game-data)))) (deftest test-get-companies-star-counts (is (= {"A" 3, "B" 1} (company/get-companies-star-counts util/fake-game-data)))) (deftest test-get-share-value (is (= 1800 (company/get-share-value "A" util/fake-game-data))) (is (= 700 (company/get-share-value "B" util/fake-game-data))) (is (= 100 (company/get-share-value "C" util/fake-game-data))) (is (= 0 (company/get-share-value "Z" util/fake-game-data))) (is (= 0 (company/get-share-value "" util/fake-game-data))) (is (= 0 (company/get-share-value nil util/fake-game-data))) (testing "Edge cases" (let [fake-game-data {}] (is (= 0 (company/get-share-value "A" fake-game-data))) (is (= 0 (company/get-share-value "B" fake-game-data))) (is (= 0 (company/get-share-value "C" fake-game-data))) (is (= 0 (company/get-share-value "Z" fake-game-data))) (is (= 0 (company/get-share-value "" fake-game-data))) (is (= 0 (company/get-share-value nil fake-game-data)))))) (deftest test-get-share-values (is (= [1800 700 100] (company/get-share-values util/fake-game-data)))) (deftest test-get-share-values-with-company (is (= [[1800 "A"] [700 "B"] [100 "C"]] (company/get-share-values-with-company util/fake-game-data)))) (deftest test-get-share-values-with-company-names (is (= [["Altair Starways" 1800] ["Betelgeuse, Ltd." 700] ["Capella Cargo Co." 100]] (company/get-share-values-with-company-names util/fake-game-data)))) (deftest test-get-company-value (is (= 2880000 (company/get-company-value "A" util/fake-game-data))) (is (= 700000 (company/get-company-value "B" util/fake-game-data))) (is (= 60000 (company/get-company-value "C" util/fake-game-data)))) (deftest test-get-companies-values (is (= {:A 2880000, :B 700000, :C 60000} (company/get-companies-values util/fake-game-data))) (is (= {:A 2880000, :B 700000, :C 60000} (company/get-companies-values ["A" "B" "C"] util/fake-game-data)))) (deftest test-get-filtered-companies (is (= [[:a5 "C"] [:d1 "A"] [:e1 "A"] [:e2 "A"]] (company/get-filtered-companies ["A" "C"] util/fake-game-data))) (is (= [[:a3 "B"] [:a5 "C"] [:b3 "B"]] (company/get-filtered-companies ["B" "C"] util/fake-game-data))) (is (= [[:a3 "B"] [:b3 "B"]] (company/get-filtered-companies ["B"] util/fake-game-data)))) (deftest test-get-greatest-company (is (= "A" (company/get-greatest-company (util/get-companies-letters) util/fake-game-data))) (is (= "C" (company/get-greatest-company ["C"] util/fake-game-data))) (is (= "A" (company/get-greatest-company ["A" "C"] util/fake-game-data))) (is (= "B" (company/get-greatest-company ["B" "C"] util/fake-game-data))) (is (= "C" (company/get-greatest-company ["C" "D" "E"] util/fake-game-data))) (testing "This one needs to mock out the random function used to choose in the event of a tie." (with-redefs [rand-nth (fn [data] (first data))] (is (= "E" (company/get-greatest-company ["D" "E"] util/fake-game-data)))))) (deftest test-get-losers (is (= ["A" "B" "D"] (company/get-losers "C" ["A" "B" "C" "D"])))) (deftest test-set-new-owner (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [star-map ((company/set-new-owner "A" "F" util/fake-game-data) :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "F" (star-map :d1))) (is (= "F" (star-map :e1))) (is (= "F" (star-map :e2))))) (deftest test-set-new-owners (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [star-map ((company/set-new-owners ["A" "B" "C"] "F" util/fake-game-data) :star-map)] (is (= "F" (star-map :a3))) (is (= "F" (star-map :a5))) (is (= "F" (star-map :b3))) (is (= "F" (star-map :d1))) (is (= "F" (star-map :e1))) (is (= "F" (star-map :e2))))) (deftest test-merge-companies (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [game-data (company/-merge-companies :a4 [[:a3 "B"] [:b3 "B"] [:a5 "C"]] util/fake-game-data) star-map (game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "B" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))))
104660
(ns starlanes.finance.company-test (:require [clojure.test :refer :all] [starlanes.finance.company :as company] [starlanes.util :as util])) (deftest test-get-new-company (let [result (company/get-new-company)] (is (= (result :name) ""))) (let [result (company/get-new-company "A")] (is (= (result :name) "A")))) (deftest test-add-company (is (= [{:name "Al"} {:name "Be"} {:name "Ca"}] (util/fake-game-data :companies))) (let [[company-name game-data] (company/add-company util/fake-game-data)] (is (= [{:name "Al"} {:name "Be"} {:name "Ca"} {:name "De"}] (game-data :companies))) (is (= ["Er"] (game-data :companies-queue))) (is (= "De" company-name)) (let [[company-name game-data] (company/add-company game-data)] (is (= [{:name "Al"} {:name "Be"} {:name "Ca"} {:name "De"} {:name "Er"}] (game-data :companies))) (is (= [] (game-data :companies-queue))) (is (= "Er" company-name))))) (deftest test-filter-company (let [companies [{:name "A"} {:name "B"}]] (is (= [{:name "A"} {:name "B"}] (company/filter-company "a" companies))) (is (= [{:name "B"}] (company/filter-company "A" companies))))) (deftest test-remove-company (let [game-data {:companies [{:name "Al"} {:name "Be"}] :companies-queue ["Ca" "De" "Er"]} game-data (company/remove-company "Al" game-data)] (is (= [{:name "Be"}] (game-data :companies))) (is (= ["Al" "Ca" "De" "Er"] (game-data :companies-queue))))) (deftest test-remove-companies (let [game-data {:companies [{:name "<NAME>"} {:name "<NAME>"} {:name "Ca"}] :companies-queue ["De" "Er"]} game-data (company/remove-companies ["Al" "Ca"] game-data)] (is (= [{:name "Be"}] (game-data :companies))) (is (= ["Al" "Ca" "De" "Er"] (game-data :companies-queue))))) (deftest test-get-companies-base-counts (let [counts (company/get-companies-base-counts util/fake-game-data)] (is (= {"A" 3, "C" 1, "B" 2} counts)) (is (= 3 (counts "A"))) (is (= 2 (counts "B"))) (is (= 1 (counts "C"))) (is (= nil (counts "Z"))))) (deftest test-get-company-base-count (is (= 3 (company/get-company-base-count "A" util/fake-game-data))) (is (= 2 (company/get-company-base-count "B" util/fake-game-data))) (is (= 1 (company/get-company-base-count "C" util/fake-game-data))) (is (= 0 (company/get-company-base-count "Z" util/fake-game-data)))) (deftest test-get-company-star-count (is (= 3 (company/get-company-star-count "A" util/fake-game-data))) (is (= 1 (company/get-company-star-count "B" util/fake-game-data))) (is (= 0 (company/get-company-star-count "C" util/fake-game-data))) (is (= 0 (company/get-company-star-count "Z" util/fake-game-data)))) (deftest test-get-companies-star-counts (is (= {"A" 3, "B" 1} (company/get-companies-star-counts util/fake-game-data)))) (deftest test-get-share-value (is (= 1800 (company/get-share-value "A" util/fake-game-data))) (is (= 700 (company/get-share-value "B" util/fake-game-data))) (is (= 100 (company/get-share-value "C" util/fake-game-data))) (is (= 0 (company/get-share-value "Z" util/fake-game-data))) (is (= 0 (company/get-share-value "" util/fake-game-data))) (is (= 0 (company/get-share-value nil util/fake-game-data))) (testing "Edge cases" (let [fake-game-data {}] (is (= 0 (company/get-share-value "A" fake-game-data))) (is (= 0 (company/get-share-value "B" fake-game-data))) (is (= 0 (company/get-share-value "C" fake-game-data))) (is (= 0 (company/get-share-value "Z" fake-game-data))) (is (= 0 (company/get-share-value "" fake-game-data))) (is (= 0 (company/get-share-value nil fake-game-data)))))) (deftest test-get-share-values (is (= [1800 700 100] (company/get-share-values util/fake-game-data)))) (deftest test-get-share-values-with-company (is (= [[1800 "A"] [700 "B"] [100 "C"]] (company/get-share-values-with-company util/fake-game-data)))) (deftest test-get-share-values-with-company-names (is (= [["<NAME>" 1800] ["Betelgeuse, Ltd." 700] ["Capella Cargo Co." 100]] (company/get-share-values-with-company-names util/fake-game-data)))) (deftest test-get-company-value (is (= 2880000 (company/get-company-value "A" util/fake-game-data))) (is (= 700000 (company/get-company-value "B" util/fake-game-data))) (is (= 60000 (company/get-company-value "C" util/fake-game-data)))) (deftest test-get-companies-values (is (= {:A 2880000, :B 700000, :C 60000} (company/get-companies-values util/fake-game-data))) (is (= {:A 2880000, :B 700000, :C 60000} (company/get-companies-values ["A" "B" "C"] util/fake-game-data)))) (deftest test-get-filtered-companies (is (= [[:a5 "C"] [:d1 "A"] [:e1 "A"] [:e2 "A"]] (company/get-filtered-companies ["A" "C"] util/fake-game-data))) (is (= [[:a3 "B"] [:a5 "C"] [:b3 "B"]] (company/get-filtered-companies ["B" "C"] util/fake-game-data))) (is (= [[:a3 "B"] [:b3 "B"]] (company/get-filtered-companies ["B"] util/fake-game-data)))) (deftest test-get-greatest-company (is (= "A" (company/get-greatest-company (util/get-companies-letters) util/fake-game-data))) (is (= "C" (company/get-greatest-company ["C"] util/fake-game-data))) (is (= "A" (company/get-greatest-company ["A" "C"] util/fake-game-data))) (is (= "B" (company/get-greatest-company ["B" "C"] util/fake-game-data))) (is (= "C" (company/get-greatest-company ["C" "D" "E"] util/fake-game-data))) (testing "This one needs to mock out the random function used to choose in the event of a tie." (with-redefs [rand-nth (fn [data] (first data))] (is (= "E" (company/get-greatest-company ["D" "E"] util/fake-game-data)))))) (deftest test-get-losers (is (= ["A" "B" "D"] (company/get-losers "C" ["A" "B" "C" "D"])))) (deftest test-set-new-owner (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [star-map ((company/set-new-owner "A" "F" util/fake-game-data) :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "F" (star-map :d1))) (is (= "F" (star-map :e1))) (is (= "F" (star-map :e2))))) (deftest test-set-new-owners (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [star-map ((company/set-new-owners ["A" "B" "C"] "F" util/fake-game-data) :star-map)] (is (= "F" (star-map :a3))) (is (= "F" (star-map :a5))) (is (= "F" (star-map :b3))) (is (= "F" (star-map :d1))) (is (= "F" (star-map :e1))) (is (= "F" (star-map :e2))))) (deftest test-merge-companies (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [game-data (company/-merge-companies :a4 [[:a3 "B"] [:b3 "B"] [:a5 "C"]] util/fake-game-data) star-map (game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "B" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))))
true
(ns starlanes.finance.company-test (:require [clojure.test :refer :all] [starlanes.finance.company :as company] [starlanes.util :as util])) (deftest test-get-new-company (let [result (company/get-new-company)] (is (= (result :name) ""))) (let [result (company/get-new-company "A")] (is (= (result :name) "A")))) (deftest test-add-company (is (= [{:name "Al"} {:name "Be"} {:name "Ca"}] (util/fake-game-data :companies))) (let [[company-name game-data] (company/add-company util/fake-game-data)] (is (= [{:name "Al"} {:name "Be"} {:name "Ca"} {:name "De"}] (game-data :companies))) (is (= ["Er"] (game-data :companies-queue))) (is (= "De" company-name)) (let [[company-name game-data] (company/add-company game-data)] (is (= [{:name "Al"} {:name "Be"} {:name "Ca"} {:name "De"} {:name "Er"}] (game-data :companies))) (is (= [] (game-data :companies-queue))) (is (= "Er" company-name))))) (deftest test-filter-company (let [companies [{:name "A"} {:name "B"}]] (is (= [{:name "A"} {:name "B"}] (company/filter-company "a" companies))) (is (= [{:name "B"}] (company/filter-company "A" companies))))) (deftest test-remove-company (let [game-data {:companies [{:name "Al"} {:name "Be"}] :companies-queue ["Ca" "De" "Er"]} game-data (company/remove-company "Al" game-data)] (is (= [{:name "Be"}] (game-data :companies))) (is (= ["Al" "Ca" "De" "Er"] (game-data :companies-queue))))) (deftest test-remove-companies (let [game-data {:companies [{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"} {:name "Ca"}] :companies-queue ["De" "Er"]} game-data (company/remove-companies ["Al" "Ca"] game-data)] (is (= [{:name "Be"}] (game-data :companies))) (is (= ["Al" "Ca" "De" "Er"] (game-data :companies-queue))))) (deftest test-get-companies-base-counts (let [counts (company/get-companies-base-counts util/fake-game-data)] (is (= {"A" 3, "C" 1, "B" 2} counts)) (is (= 3 (counts "A"))) (is (= 2 (counts "B"))) (is (= 1 (counts "C"))) (is (= nil (counts "Z"))))) (deftest test-get-company-base-count (is (= 3 (company/get-company-base-count "A" util/fake-game-data))) (is (= 2 (company/get-company-base-count "B" util/fake-game-data))) (is (= 1 (company/get-company-base-count "C" util/fake-game-data))) (is (= 0 (company/get-company-base-count "Z" util/fake-game-data)))) (deftest test-get-company-star-count (is (= 3 (company/get-company-star-count "A" util/fake-game-data))) (is (= 1 (company/get-company-star-count "B" util/fake-game-data))) (is (= 0 (company/get-company-star-count "C" util/fake-game-data))) (is (= 0 (company/get-company-star-count "Z" util/fake-game-data)))) (deftest test-get-companies-star-counts (is (= {"A" 3, "B" 1} (company/get-companies-star-counts util/fake-game-data)))) (deftest test-get-share-value (is (= 1800 (company/get-share-value "A" util/fake-game-data))) (is (= 700 (company/get-share-value "B" util/fake-game-data))) (is (= 100 (company/get-share-value "C" util/fake-game-data))) (is (= 0 (company/get-share-value "Z" util/fake-game-data))) (is (= 0 (company/get-share-value "" util/fake-game-data))) (is (= 0 (company/get-share-value nil util/fake-game-data))) (testing "Edge cases" (let [fake-game-data {}] (is (= 0 (company/get-share-value "A" fake-game-data))) (is (= 0 (company/get-share-value "B" fake-game-data))) (is (= 0 (company/get-share-value "C" fake-game-data))) (is (= 0 (company/get-share-value "Z" fake-game-data))) (is (= 0 (company/get-share-value "" fake-game-data))) (is (= 0 (company/get-share-value nil fake-game-data)))))) (deftest test-get-share-values (is (= [1800 700 100] (company/get-share-values util/fake-game-data)))) (deftest test-get-share-values-with-company (is (= [[1800 "A"] [700 "B"] [100 "C"]] (company/get-share-values-with-company util/fake-game-data)))) (deftest test-get-share-values-with-company-names (is (= [["PI:NAME:<NAME>END_PI" 1800] ["Betelgeuse, Ltd." 700] ["Capella Cargo Co." 100]] (company/get-share-values-with-company-names util/fake-game-data)))) (deftest test-get-company-value (is (= 2880000 (company/get-company-value "A" util/fake-game-data))) (is (= 700000 (company/get-company-value "B" util/fake-game-data))) (is (= 60000 (company/get-company-value "C" util/fake-game-data)))) (deftest test-get-companies-values (is (= {:A 2880000, :B 700000, :C 60000} (company/get-companies-values util/fake-game-data))) (is (= {:A 2880000, :B 700000, :C 60000} (company/get-companies-values ["A" "B" "C"] util/fake-game-data)))) (deftest test-get-filtered-companies (is (= [[:a5 "C"] [:d1 "A"] [:e1 "A"] [:e2 "A"]] (company/get-filtered-companies ["A" "C"] util/fake-game-data))) (is (= [[:a3 "B"] [:a5 "C"] [:b3 "B"]] (company/get-filtered-companies ["B" "C"] util/fake-game-data))) (is (= [[:a3 "B"] [:b3 "B"]] (company/get-filtered-companies ["B"] util/fake-game-data)))) (deftest test-get-greatest-company (is (= "A" (company/get-greatest-company (util/get-companies-letters) util/fake-game-data))) (is (= "C" (company/get-greatest-company ["C"] util/fake-game-data))) (is (= "A" (company/get-greatest-company ["A" "C"] util/fake-game-data))) (is (= "B" (company/get-greatest-company ["B" "C"] util/fake-game-data))) (is (= "C" (company/get-greatest-company ["C" "D" "E"] util/fake-game-data))) (testing "This one needs to mock out the random function used to choose in the event of a tie." (with-redefs [rand-nth (fn [data] (first data))] (is (= "E" (company/get-greatest-company ["D" "E"] util/fake-game-data)))))) (deftest test-get-losers (is (= ["A" "B" "D"] (company/get-losers "C" ["A" "B" "C" "D"])))) (deftest test-set-new-owner (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [star-map ((company/set-new-owner "A" "F" util/fake-game-data) :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "F" (star-map :d1))) (is (= "F" (star-map :e1))) (is (= "F" (star-map :e2))))) (deftest test-set-new-owners (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [star-map ((company/set-new-owners ["A" "B" "C"] "F" util/fake-game-data) :star-map)] (is (= "F" (star-map :a3))) (is (= "F" (star-map :a5))) (is (= "F" (star-map :b3))) (is (= "F" (star-map :d1))) (is (= "F" (star-map :e1))) (is (= "F" (star-map :e2))))) (deftest test-merge-companies (let [star-map (util/fake-game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "C" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))) (let [game-data (company/-merge-companies :a4 [[:a3 "B"] [:b3 "B"] [:a5 "C"]] util/fake-game-data) star-map (game-data :star-map)] (is (= "B" (star-map :a3))) (is (= "B" (star-map :a5))) (is (= "B" (star-map :b3))) (is (= "A" (star-map :d1))) (is (= "A" (star-map :e1))) (is (= "A" (star-map :e2)))))
[ { "context": "o_world\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n :size 1})\n\n(defmacro thread-local [& body]\n ", "end": 1068, "score": 0.999316930770874, "start": 1053, "tag": "PASSWORD", "value": "benchmarkdbpass" } ]
frameworks/Clojure/aleph/src/hello/handler.clj
http4k/FrameworkBenchmarks
2
(ns hello.handler (:require [aleph.http :as http] [aleph.netty :as netty] [byte-streams :as bs] [clj-async-profiler.core :as prof] [hiccup.page :as hp] [hiccup.util :as hu] [jsonista.core :as json] [manifold.deferred :as d] [porsas.async :as async]) (:import (clojure.lang IDeref) (io.netty.channel ChannelOption) (io.netty.buffer PooledByteBufAllocator) (java.util.function Supplier) (java.util.concurrent ThreadLocalRandom) (porsas.async Context)) (:gen-class)) (def plaintext-response {:status 200 :headers {"Content-Type" "text/plain"} :body (bs/to-byte-array "Hello, World!")}) (def json-response {:status 200 :headers {"Content-Type" "application/json"}}) (def html-response {:status 200 :headers {"Content-Type" "text/html; charset=utf-8"}}) (def db-spec {:uri "postgresql://tfb-database:5432/hello_world" :user "benchmarkdbuser" :password "benchmarkdbpass" :size 1}) (defmacro thread-local [& body] `(let [tl# (ThreadLocal/withInitial (reify Supplier (get [_] ~@body)))] (reify IDeref (deref [_] (.get tl#))))) (def pool "PostgreSQL pool of connections (`PgPool`)." (thread-local (async/pool db-spec))) (defn random "Generate a random number between 1 and 10'000." [] (unchecked-inc (.nextInt (ThreadLocalRandom/current) 10000))) (defn sanitize-queries-param "Sanitizes the `queries` parameter. Clamps the value between 1 and 500. Invalid (string) values become 1." [request] (let [queries (-> request :query-string (subs 8)) n (try (Integer/parseInt queries) (catch Exception _ 1))] ; default to 1 on parse failure (cond (< n 1) 1 (> n 500) 500 :else n))) (def ^Context query-mapper "Map each row into a record." (async/context {:row (async/rs->compiled-record)})) (defn query-one-random-world "Query a random world on the database. Return a `CompletableFuture`." [] (async/query-one query-mapper @pool ["SELECT id, randomnumber FROM world WHERE id=$1" (random)])) (defn update-world "Update a world on the database. Return a `CompletableFuture`." [{:keys [randomNumber id]}] (async/query @pool ["UPDATE world SET randomnumber=$1 WHERE id=$2" randomNumber id])) (defn run-queries "Run a number of `queries` on the database to fetch a random world. Return a `manifold.deferred`." [queries] (apply d/zip (take queries (repeatedly query-one-random-world)))) (defn query-fortunes "Query the fortunes on database. Return a `CompletableFuture`." [] (async/query query-mapper @pool ["SELECT id, message from FORTUNE"])) (defn get-fortunes "Fetch the full list of Fortunes from the database, sort them by the fortune message text. Return a `CompletableFuture` with the results." [] (d/chain (query-fortunes) (fn [fortunes] (sort-by :message (conj fortunes {:id 0 :message "Additional fortune added at request time."}))))) (defn update-and-persist "Fetch a number of `queries` random world from the database. Compute a new `randomNumber` for each of them a return a `CompletableFuture` with the updated worlds." [queries] (d/chain' (run-queries queries) (fn [worlds] (let [worlds' (mapv #(assoc % :randomNumber (random)) worlds)] (d/chain' (apply d/zip (mapv update-world worlds')) (fn [_] worlds')))))) (defn fortunes-hiccup "Render the given fortunes to simple HTML using Hiccup." [fortunes] (hp/html5 [:head [:title "Fortunes"]] [:body [:table [:tr [:th "id"] [:th "message"]] (for [x fortunes] [:tr [:td (:id x)] [:td (hu/escape-html (:message x))]])]])) (defn handler "Ring handler representing the different tests." [req] (let [uri (:uri req)] (cond (.equals "/plaintext" uri) plaintext-response (.equals "/json" uri) (assoc json-response :body (json/write-value-as-bytes {:message "Hello, World!"})) (.equals "/db" uri) (-> (query-one-random-world) (d/chain (fn [world] (assoc json-response :body (json/write-value-as-bytes world))))) (.equals "/queries" uri) (-> (sanitize-queries-param req) (run-queries) (d/chain (fn [worlds] (assoc json-response :body (json/write-value-as-bytes worlds))))) (.equals "/fortunes" uri) (d/chain' (get-fortunes) fortunes-hiccup (fn [body] (assoc html-response :body body))) (.equals "/updates" uri) (-> (sanitize-queries-param req) (update-and-persist) (d/chain (fn [worlds] (assoc json-response :body (json/write-value-as-bytes worlds))))) :else {:status 404}))) ;;; (defn -main [& _] (netty/leak-detector-level! :disabled) (http/start-server handler {:port 8080 :raw-stream? true :epoll? true :executor :none :bootstrap-transform (fn [bootstrap] (.option bootstrap ChannelOption/ALLOCATOR PooledByteBufAllocator/DEFAULT) (.childOption bootstrap ChannelOption/ALLOCATOR PooledByteBufAllocator/DEFAULT)) :pipeline-transform (fn [pipeline] (.remove pipeline "continue-handler"))}) ;; Uncomment to enable async-profiler #_ (do (prof/profile-for 60 #_ {:transform (fn [s] (when-not (re-find #"(writev|__libc|epoll_wait|write|__pthread)" s) s))}) (prof/serve-files 8081)))
30107
(ns hello.handler (:require [aleph.http :as http] [aleph.netty :as netty] [byte-streams :as bs] [clj-async-profiler.core :as prof] [hiccup.page :as hp] [hiccup.util :as hu] [jsonista.core :as json] [manifold.deferred :as d] [porsas.async :as async]) (:import (clojure.lang IDeref) (io.netty.channel ChannelOption) (io.netty.buffer PooledByteBufAllocator) (java.util.function Supplier) (java.util.concurrent ThreadLocalRandom) (porsas.async Context)) (:gen-class)) (def plaintext-response {:status 200 :headers {"Content-Type" "text/plain"} :body (bs/to-byte-array "Hello, World!")}) (def json-response {:status 200 :headers {"Content-Type" "application/json"}}) (def html-response {:status 200 :headers {"Content-Type" "text/html; charset=utf-8"}}) (def db-spec {:uri "postgresql://tfb-database:5432/hello_world" :user "benchmarkdbuser" :password "<PASSWORD>" :size 1}) (defmacro thread-local [& body] `(let [tl# (ThreadLocal/withInitial (reify Supplier (get [_] ~@body)))] (reify IDeref (deref [_] (.get tl#))))) (def pool "PostgreSQL pool of connections (`PgPool`)." (thread-local (async/pool db-spec))) (defn random "Generate a random number between 1 and 10'000." [] (unchecked-inc (.nextInt (ThreadLocalRandom/current) 10000))) (defn sanitize-queries-param "Sanitizes the `queries` parameter. Clamps the value between 1 and 500. Invalid (string) values become 1." [request] (let [queries (-> request :query-string (subs 8)) n (try (Integer/parseInt queries) (catch Exception _ 1))] ; default to 1 on parse failure (cond (< n 1) 1 (> n 500) 500 :else n))) (def ^Context query-mapper "Map each row into a record." (async/context {:row (async/rs->compiled-record)})) (defn query-one-random-world "Query a random world on the database. Return a `CompletableFuture`." [] (async/query-one query-mapper @pool ["SELECT id, randomnumber FROM world WHERE id=$1" (random)])) (defn update-world "Update a world on the database. Return a `CompletableFuture`." [{:keys [randomNumber id]}] (async/query @pool ["UPDATE world SET randomnumber=$1 WHERE id=$2" randomNumber id])) (defn run-queries "Run a number of `queries` on the database to fetch a random world. Return a `manifold.deferred`." [queries] (apply d/zip (take queries (repeatedly query-one-random-world)))) (defn query-fortunes "Query the fortunes on database. Return a `CompletableFuture`." [] (async/query query-mapper @pool ["SELECT id, message from FORTUNE"])) (defn get-fortunes "Fetch the full list of Fortunes from the database, sort them by the fortune message text. Return a `CompletableFuture` with the results." [] (d/chain (query-fortunes) (fn [fortunes] (sort-by :message (conj fortunes {:id 0 :message "Additional fortune added at request time."}))))) (defn update-and-persist "Fetch a number of `queries` random world from the database. Compute a new `randomNumber` for each of them a return a `CompletableFuture` with the updated worlds." [queries] (d/chain' (run-queries queries) (fn [worlds] (let [worlds' (mapv #(assoc % :randomNumber (random)) worlds)] (d/chain' (apply d/zip (mapv update-world worlds')) (fn [_] worlds')))))) (defn fortunes-hiccup "Render the given fortunes to simple HTML using Hiccup." [fortunes] (hp/html5 [:head [:title "Fortunes"]] [:body [:table [:tr [:th "id"] [:th "message"]] (for [x fortunes] [:tr [:td (:id x)] [:td (hu/escape-html (:message x))]])]])) (defn handler "Ring handler representing the different tests." [req] (let [uri (:uri req)] (cond (.equals "/plaintext" uri) plaintext-response (.equals "/json" uri) (assoc json-response :body (json/write-value-as-bytes {:message "Hello, World!"})) (.equals "/db" uri) (-> (query-one-random-world) (d/chain (fn [world] (assoc json-response :body (json/write-value-as-bytes world))))) (.equals "/queries" uri) (-> (sanitize-queries-param req) (run-queries) (d/chain (fn [worlds] (assoc json-response :body (json/write-value-as-bytes worlds))))) (.equals "/fortunes" uri) (d/chain' (get-fortunes) fortunes-hiccup (fn [body] (assoc html-response :body body))) (.equals "/updates" uri) (-> (sanitize-queries-param req) (update-and-persist) (d/chain (fn [worlds] (assoc json-response :body (json/write-value-as-bytes worlds))))) :else {:status 404}))) ;;; (defn -main [& _] (netty/leak-detector-level! :disabled) (http/start-server handler {:port 8080 :raw-stream? true :epoll? true :executor :none :bootstrap-transform (fn [bootstrap] (.option bootstrap ChannelOption/ALLOCATOR PooledByteBufAllocator/DEFAULT) (.childOption bootstrap ChannelOption/ALLOCATOR PooledByteBufAllocator/DEFAULT)) :pipeline-transform (fn [pipeline] (.remove pipeline "continue-handler"))}) ;; Uncomment to enable async-profiler #_ (do (prof/profile-for 60 #_ {:transform (fn [s] (when-not (re-find #"(writev|__libc|epoll_wait|write|__pthread)" s) s))}) (prof/serve-files 8081)))
true
(ns hello.handler (:require [aleph.http :as http] [aleph.netty :as netty] [byte-streams :as bs] [clj-async-profiler.core :as prof] [hiccup.page :as hp] [hiccup.util :as hu] [jsonista.core :as json] [manifold.deferred :as d] [porsas.async :as async]) (:import (clojure.lang IDeref) (io.netty.channel ChannelOption) (io.netty.buffer PooledByteBufAllocator) (java.util.function Supplier) (java.util.concurrent ThreadLocalRandom) (porsas.async Context)) (:gen-class)) (def plaintext-response {:status 200 :headers {"Content-Type" "text/plain"} :body (bs/to-byte-array "Hello, World!")}) (def json-response {:status 200 :headers {"Content-Type" "application/json"}}) (def html-response {:status 200 :headers {"Content-Type" "text/html; charset=utf-8"}}) (def db-spec {:uri "postgresql://tfb-database:5432/hello_world" :user "benchmarkdbuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :size 1}) (defmacro thread-local [& body] `(let [tl# (ThreadLocal/withInitial (reify Supplier (get [_] ~@body)))] (reify IDeref (deref [_] (.get tl#))))) (def pool "PostgreSQL pool of connections (`PgPool`)." (thread-local (async/pool db-spec))) (defn random "Generate a random number between 1 and 10'000." [] (unchecked-inc (.nextInt (ThreadLocalRandom/current) 10000))) (defn sanitize-queries-param "Sanitizes the `queries` parameter. Clamps the value between 1 and 500. Invalid (string) values become 1." [request] (let [queries (-> request :query-string (subs 8)) n (try (Integer/parseInt queries) (catch Exception _ 1))] ; default to 1 on parse failure (cond (< n 1) 1 (> n 500) 500 :else n))) (def ^Context query-mapper "Map each row into a record." (async/context {:row (async/rs->compiled-record)})) (defn query-one-random-world "Query a random world on the database. Return a `CompletableFuture`." [] (async/query-one query-mapper @pool ["SELECT id, randomnumber FROM world WHERE id=$1" (random)])) (defn update-world "Update a world on the database. Return a `CompletableFuture`." [{:keys [randomNumber id]}] (async/query @pool ["UPDATE world SET randomnumber=$1 WHERE id=$2" randomNumber id])) (defn run-queries "Run a number of `queries` on the database to fetch a random world. Return a `manifold.deferred`." [queries] (apply d/zip (take queries (repeatedly query-one-random-world)))) (defn query-fortunes "Query the fortunes on database. Return a `CompletableFuture`." [] (async/query query-mapper @pool ["SELECT id, message from FORTUNE"])) (defn get-fortunes "Fetch the full list of Fortunes from the database, sort them by the fortune message text. Return a `CompletableFuture` with the results." [] (d/chain (query-fortunes) (fn [fortunes] (sort-by :message (conj fortunes {:id 0 :message "Additional fortune added at request time."}))))) (defn update-and-persist "Fetch a number of `queries` random world from the database. Compute a new `randomNumber` for each of them a return a `CompletableFuture` with the updated worlds." [queries] (d/chain' (run-queries queries) (fn [worlds] (let [worlds' (mapv #(assoc % :randomNumber (random)) worlds)] (d/chain' (apply d/zip (mapv update-world worlds')) (fn [_] worlds')))))) (defn fortunes-hiccup "Render the given fortunes to simple HTML using Hiccup." [fortunes] (hp/html5 [:head [:title "Fortunes"]] [:body [:table [:tr [:th "id"] [:th "message"]] (for [x fortunes] [:tr [:td (:id x)] [:td (hu/escape-html (:message x))]])]])) (defn handler "Ring handler representing the different tests." [req] (let [uri (:uri req)] (cond (.equals "/plaintext" uri) plaintext-response (.equals "/json" uri) (assoc json-response :body (json/write-value-as-bytes {:message "Hello, World!"})) (.equals "/db" uri) (-> (query-one-random-world) (d/chain (fn [world] (assoc json-response :body (json/write-value-as-bytes world))))) (.equals "/queries" uri) (-> (sanitize-queries-param req) (run-queries) (d/chain (fn [worlds] (assoc json-response :body (json/write-value-as-bytes worlds))))) (.equals "/fortunes" uri) (d/chain' (get-fortunes) fortunes-hiccup (fn [body] (assoc html-response :body body))) (.equals "/updates" uri) (-> (sanitize-queries-param req) (update-and-persist) (d/chain (fn [worlds] (assoc json-response :body (json/write-value-as-bytes worlds))))) :else {:status 404}))) ;;; (defn -main [& _] (netty/leak-detector-level! :disabled) (http/start-server handler {:port 8080 :raw-stream? true :epoll? true :executor :none :bootstrap-transform (fn [bootstrap] (.option bootstrap ChannelOption/ALLOCATOR PooledByteBufAllocator/DEFAULT) (.childOption bootstrap ChannelOption/ALLOCATOR PooledByteBufAllocator/DEFAULT)) :pipeline-transform (fn [pipeline] (.remove pipeline "continue-handler"))}) ;; Uncomment to enable async-profiler #_ (do (prof/profile-for 60 #_ {:transform (fn [s] (when-not (re-find #"(writev|__libc|epoll_wait|write|__pthread)" s) s))}) (prof/serve-files 8081)))
[ { "context": "\n(def update-roles-rules\n {:name [[v/member #{\"merlin\" \"morgana\" \"percival\" \"mordred\" \"oberon\" \"lancelo", "end": 2014, "score": 0.9344732761383057, "start": 2008, "tag": "NAME", "value": "merlin" }, { "context": "ate-roles-rules\n {:name [[v/member #{\"merlin\" \"morgana\" \"percival\" \"mordred\" \"oberon\" \"lancelot1\" \"lance", "end": 2024, "score": 0.7812201380729675, "start": 2017, "tag": "NAME", "value": "morgana" }, { "context": "rules\n {:name [[v/member #{\"merlin\" \"morgana\" \"percival\" \"mordred\" \"oberon\" \"lancelot1\" \"lancelot2\" \"twin", "end": 2035, "score": 0.875493049621582, "start": 2027, "tag": "NAME", "value": "percival" }, { "context": "ame [[v/member #{\"merlin\" \"morgana\" \"percival\" \"mordred\" \"oberon\" \"lancelot1\" \"lancelot2\" \"twins\"}]]\n :", "end": 2045, "score": 0.9885136485099792, "start": 2038, "tag": "NAME", "value": "mordred" }, { "context": "member #{\"merlin\" \"morgana\" \"percival\" \"mordred\" \"oberon\" \"lancelot1\" \"lancelot2\" \"twins\"}]]\n :status [[", "end": 2054, "score": 0.9765361547470093, "start": 2048, "tag": "NAME", "value": "oberon" } ]
src/clj/avalon/rules/games.clj
baritonehands/avalon
5
(ns avalon.rules.games (:require [bouncer.core :as b] [bouncer.validators :as v] [avalon.models.games :as games] [avalon.models.crud :as crud] [avalon.rules.quests :as quests])) (def good {:specials #{:merlin :percival :good-lancelot1 :good-lancelot2 :twin1 :twin2} :counts [3 4 4 5 6 6]}) (def bad {:specials #{:mordred :morgana :oberon :evil-lancelot1 :evil-lancelot2} :counts [2 2 3 3 3 4]}) (defn good? [role] (or (contains? (:specials good) role) (= role :good))) (def bad? (complement good?)) (defn- add-doubles [single one two] (fn [roles] (if (roles single) (disj (conj roles one two) single) roles))) (def add-lancelot1 (add-doubles :lancelot1 :good-lancelot1 :evil-lancelot1)) (def add-lancelot2 (add-doubles :lancelot2 :good-lancelot2 :evil-lancelot2)) (def add-twins (add-doubles :twins :twin1 :twin2)) (defn valid-specials? [game team] (fn [roles] (let [roles (-> (add-twins roles) add-lancelot1 add-lancelot2) specials (:specials team) counts (:counts team) num-players (count (:people game)) in-play (count (filter specials roles))] (if (and (>= num-players 5) (<= num-players 10)) (>= (get counts (- num-players 5)) in-play))))) (defn play-game-rules [game] {:people [[v/min-count 5 :message "Too few players"] [v/max-count 10 :message "Too many players"]] :status [[#{:waiting} :message "Game already started"]] :roles [[(valid-specials? game bad) :message "Too many evil roles"] [(valid-specials? game good) :message "Too many good roles"]]}) (defn- create-validator [rules-fn] (fn [id key] (let [game (crud/get games/games id) rules (rules-fn game) valid (b/valid? game rules) errors (first (b/validate game rules))] [valid {key errors}]))) (def valid-play? (create-validator play-game-rules)) (def update-roles-rules {:name [[v/member #{"merlin" "morgana" "percival" "mordred" "oberon" "lancelot1" "lancelot2" "twins"}]] :status [[#{:waiting} :message "Roles cannot be updated after game is started"]]}) (defn valid-role? [id name key] (let [game (crud/get games/games id) to-validate {:name name :status (.status game)} valid (b/valid? to-validate update-roles-rules) errors (first (b/validate to-validate update-roles-rules))] [valid {key errors}])) (defn quests-complete? [{:keys [people] :as game} quests] (->> (for [[n result] (map-indexed vector quests) :when result] (quests/failed? (count people) n result)) (frequencies) (vals) (not-any? #(>= % 3)))) (defn quest-rules [{:keys [quests people] :as game}] (let [counts (quests/counts (count people)) quest-needs (get counts (count quests) 0)] {:quests [[#(quests-complete? game %) :message "Game Over"]] :names [[v/min-count quest-needs :message "Too few players"] [v/max-count quest-needs :message "Too many players"]] :people [[v/min-count quest-needs :message "Too few players"] [v/max-count quest-needs :message "Too many players"]] :vote [[nil? :message "Vote already in progress"]]})) (defn valid-quest? [id data-key error-key] (fn [ctx] (if (= :delete (get-in ctx [:request :request-method])) true (let [game (crud/get games/games id) names (get-in ctx [data-key :names]) rules (quest-rules game) to-validate {:names names :quests (:quests game) :people (games/people-named game names) :vote (:vote game)} valid (b/valid? to-validate rules) errors (first (b/validate to-validate rules))] [valid {error-key errors}])))) (defn reset-rules [game] {:status [[#{:playing} :message "Game not started"]]}) (def valid-reset? (create-validator reset-rules)) (defn assign-team [m team roles n] (let [special (filter (:specials m) roles) size ((:counts m) (- n 5)) use-assassin (and (= team :bad) (roles :merlin) (> size (count special))) special (if use-assassin (conj special :assassin) special) unnamed (repeat (- size (count special)) team)] (concat special unnamed))) (defn assign-roles [game] (let [people (.people game) roles (-> (add-twins (.roles game)) add-lancelot1 add-lancelot2) blue (assign-team good :good roles (count people)) red (assign-team bad :bad roles (count people))] (zipmap people (shuffle (concat red blue)))))
116498
(ns avalon.rules.games (:require [bouncer.core :as b] [bouncer.validators :as v] [avalon.models.games :as games] [avalon.models.crud :as crud] [avalon.rules.quests :as quests])) (def good {:specials #{:merlin :percival :good-lancelot1 :good-lancelot2 :twin1 :twin2} :counts [3 4 4 5 6 6]}) (def bad {:specials #{:mordred :morgana :oberon :evil-lancelot1 :evil-lancelot2} :counts [2 2 3 3 3 4]}) (defn good? [role] (or (contains? (:specials good) role) (= role :good))) (def bad? (complement good?)) (defn- add-doubles [single one two] (fn [roles] (if (roles single) (disj (conj roles one two) single) roles))) (def add-lancelot1 (add-doubles :lancelot1 :good-lancelot1 :evil-lancelot1)) (def add-lancelot2 (add-doubles :lancelot2 :good-lancelot2 :evil-lancelot2)) (def add-twins (add-doubles :twins :twin1 :twin2)) (defn valid-specials? [game team] (fn [roles] (let [roles (-> (add-twins roles) add-lancelot1 add-lancelot2) specials (:specials team) counts (:counts team) num-players (count (:people game)) in-play (count (filter specials roles))] (if (and (>= num-players 5) (<= num-players 10)) (>= (get counts (- num-players 5)) in-play))))) (defn play-game-rules [game] {:people [[v/min-count 5 :message "Too few players"] [v/max-count 10 :message "Too many players"]] :status [[#{:waiting} :message "Game already started"]] :roles [[(valid-specials? game bad) :message "Too many evil roles"] [(valid-specials? game good) :message "Too many good roles"]]}) (defn- create-validator [rules-fn] (fn [id key] (let [game (crud/get games/games id) rules (rules-fn game) valid (b/valid? game rules) errors (first (b/validate game rules))] [valid {key errors}]))) (def valid-play? (create-validator play-game-rules)) (def update-roles-rules {:name [[v/member #{"<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "lancelot1" "lancelot2" "twins"}]] :status [[#{:waiting} :message "Roles cannot be updated after game is started"]]}) (defn valid-role? [id name key] (let [game (crud/get games/games id) to-validate {:name name :status (.status game)} valid (b/valid? to-validate update-roles-rules) errors (first (b/validate to-validate update-roles-rules))] [valid {key errors}])) (defn quests-complete? [{:keys [people] :as game} quests] (->> (for [[n result] (map-indexed vector quests) :when result] (quests/failed? (count people) n result)) (frequencies) (vals) (not-any? #(>= % 3)))) (defn quest-rules [{:keys [quests people] :as game}] (let [counts (quests/counts (count people)) quest-needs (get counts (count quests) 0)] {:quests [[#(quests-complete? game %) :message "Game Over"]] :names [[v/min-count quest-needs :message "Too few players"] [v/max-count quest-needs :message "Too many players"]] :people [[v/min-count quest-needs :message "Too few players"] [v/max-count quest-needs :message "Too many players"]] :vote [[nil? :message "Vote already in progress"]]})) (defn valid-quest? [id data-key error-key] (fn [ctx] (if (= :delete (get-in ctx [:request :request-method])) true (let [game (crud/get games/games id) names (get-in ctx [data-key :names]) rules (quest-rules game) to-validate {:names names :quests (:quests game) :people (games/people-named game names) :vote (:vote game)} valid (b/valid? to-validate rules) errors (first (b/validate to-validate rules))] [valid {error-key errors}])))) (defn reset-rules [game] {:status [[#{:playing} :message "Game not started"]]}) (def valid-reset? (create-validator reset-rules)) (defn assign-team [m team roles n] (let [special (filter (:specials m) roles) size ((:counts m) (- n 5)) use-assassin (and (= team :bad) (roles :merlin) (> size (count special))) special (if use-assassin (conj special :assassin) special) unnamed (repeat (- size (count special)) team)] (concat special unnamed))) (defn assign-roles [game] (let [people (.people game) roles (-> (add-twins (.roles game)) add-lancelot1 add-lancelot2) blue (assign-team good :good roles (count people)) red (assign-team bad :bad roles (count people))] (zipmap people (shuffle (concat red blue)))))
true
(ns avalon.rules.games (:require [bouncer.core :as b] [bouncer.validators :as v] [avalon.models.games :as games] [avalon.models.crud :as crud] [avalon.rules.quests :as quests])) (def good {:specials #{:merlin :percival :good-lancelot1 :good-lancelot2 :twin1 :twin2} :counts [3 4 4 5 6 6]}) (def bad {:specials #{:mordred :morgana :oberon :evil-lancelot1 :evil-lancelot2} :counts [2 2 3 3 3 4]}) (defn good? [role] (or (contains? (:specials good) role) (= role :good))) (def bad? (complement good?)) (defn- add-doubles [single one two] (fn [roles] (if (roles single) (disj (conj roles one two) single) roles))) (def add-lancelot1 (add-doubles :lancelot1 :good-lancelot1 :evil-lancelot1)) (def add-lancelot2 (add-doubles :lancelot2 :good-lancelot2 :evil-lancelot2)) (def add-twins (add-doubles :twins :twin1 :twin2)) (defn valid-specials? [game team] (fn [roles] (let [roles (-> (add-twins roles) add-lancelot1 add-lancelot2) specials (:specials team) counts (:counts team) num-players (count (:people game)) in-play (count (filter specials roles))] (if (and (>= num-players 5) (<= num-players 10)) (>= (get counts (- num-players 5)) in-play))))) (defn play-game-rules [game] {:people [[v/min-count 5 :message "Too few players"] [v/max-count 10 :message "Too many players"]] :status [[#{:waiting} :message "Game already started"]] :roles [[(valid-specials? game bad) :message "Too many evil roles"] [(valid-specials? game good) :message "Too many good roles"]]}) (defn- create-validator [rules-fn] (fn [id key] (let [game (crud/get games/games id) rules (rules-fn game) valid (b/valid? game rules) errors (first (b/validate game rules))] [valid {key errors}]))) (def valid-play? (create-validator play-game-rules)) (def update-roles-rules {:name [[v/member #{"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" "lancelot1" "lancelot2" "twins"}]] :status [[#{:waiting} :message "Roles cannot be updated after game is started"]]}) (defn valid-role? [id name key] (let [game (crud/get games/games id) to-validate {:name name :status (.status game)} valid (b/valid? to-validate update-roles-rules) errors (first (b/validate to-validate update-roles-rules))] [valid {key errors}])) (defn quests-complete? [{:keys [people] :as game} quests] (->> (for [[n result] (map-indexed vector quests) :when result] (quests/failed? (count people) n result)) (frequencies) (vals) (not-any? #(>= % 3)))) (defn quest-rules [{:keys [quests people] :as game}] (let [counts (quests/counts (count people)) quest-needs (get counts (count quests) 0)] {:quests [[#(quests-complete? game %) :message "Game Over"]] :names [[v/min-count quest-needs :message "Too few players"] [v/max-count quest-needs :message "Too many players"]] :people [[v/min-count quest-needs :message "Too few players"] [v/max-count quest-needs :message "Too many players"]] :vote [[nil? :message "Vote already in progress"]]})) (defn valid-quest? [id data-key error-key] (fn [ctx] (if (= :delete (get-in ctx [:request :request-method])) true (let [game (crud/get games/games id) names (get-in ctx [data-key :names]) rules (quest-rules game) to-validate {:names names :quests (:quests game) :people (games/people-named game names) :vote (:vote game)} valid (b/valid? to-validate rules) errors (first (b/validate to-validate rules))] [valid {error-key errors}])))) (defn reset-rules [game] {:status [[#{:playing} :message "Game not started"]]}) (def valid-reset? (create-validator reset-rules)) (defn assign-team [m team roles n] (let [special (filter (:specials m) roles) size ((:counts m) (- n 5)) use-assassin (and (= team :bad) (roles :merlin) (> size (count special))) special (if use-assassin (conj special :assassin) special) unnamed (repeat (- size (count special)) team)] (concat special unnamed))) (defn assign-roles [game] (let [people (.people game) roles (-> (add-twins (.roles game)) add-lancelot1 add-lancelot2) blue (assign-team good :good roles (count people)) red (assign-team bad :bad roles (count people))] (zipmap people (shuffle (concat red blue)))))
[ { "context": "irst-name\n;; (s/with-gen string?\n;; #(s/gen #{\"Steve\" \"Sam\" \"Gretchen\"})))\n\n;; (s/def ::last-name\n;; ", "end": 1543, "score": 0.9997563362121582, "start": 1538, "tag": "NAME", "value": "Steve" }, { "context": "e\n;; (s/with-gen string?\n;; #(s/gen #{\"Steve\" \"Sam\" \"Gretchen\"})))\n\n;; (s/def ::last-name\n;; (s/wit", "end": 1549, "score": 0.9997797608375549, "start": 1546, "tag": "NAME", "value": "Sam" }, { "context": "(s/with-gen string?\n;; #(s/gen #{\"Steve\" \"Sam\" \"Gretchen\"})))\n\n;; (s/def ::last-name\n;; (s/with-gen strin", "end": 1560, "score": 0.9997251033782959, "start": 1552, "tag": "NAME", "value": "Gretchen" }, { "context": "last-name\n;; (s/with-gen string?\n;; #(s/gen #{\"Adams\" \"Turner\" \"Black\"})))\n\n;; (s/def ::person\n;; (s/", "end": 1634, "score": 0.9997864365577698, "start": 1629, "tag": "NAME", "value": "Adams" }, { "context": "e\n;; (s/with-gen string?\n;; #(s/gen #{\"Adams\" \"Turner\" \"Black\"})))\n\n;; (s/def ::person\n;; (s/keys :req", "end": 1643, "score": 0.9996827244758606, "start": 1637, "tag": "NAME", "value": "Turner" }, { "context": "with-gen string?\n;; #(s/gen #{\"Adams\" \"Turner\" \"Black\"})))\n\n;; (s/def ::person\n;; (s/keys :req [::firs", "end": 1651, "score": 0.9995594620704651, "start": 1646, "tag": "NAME", "value": "Black" } ]
src/cljc/cube_test/twizzlers/db.cljc
vt5491/cube-test
1
(ns cube-test.twizzlers.db (:require [re-frame.core :as re-frame] [clojure.spec.alpha :as s] [clojure.test.check.generators :as gen] [clojure.pprint :refer [pprint]] [cube-test.utils :as utils])) (def dummy 7) (comment (+ 1 1) (print {:a 7, :b 8}) (pprint (gen/generate (s/gen ::first-name))) (pprint (gen/generate (s/gen ::last-name))) (pprint (gen/generate (s/gen ::person))) dummy ,) (def default-db { ;; :name "re-frame" ; ::twizzlers [] :scenes { :space-port {:path "models/space_portal/" :fn "space_portal.glb" :loaded false} :hemisferic {:path "models/hemisferic/" :fn "hemisferic.glb" :loaded false}} :twizzlers []}) ; :msgs-2 [] ; :ints [0 2] ; :max-id 0 ; :input-id 2}) (defn init-db [db] ; (utils/merge-dbs db cube-test.msg-cube.spec.db/default-db) (utils/merge-dbs db default-db)) ;; specs ;; Individual twizzler ;; (s/def ::twizzler-id int?) ;; (s/def :twz/id int?) (s/def ::id int?) ;; (s/def ::twizzler ;; (s/keys :req [::twizzler-id])) (s/def ::twizzler (s/keys :req [::id])) ;; (s/def ::twz ;; (s/keys :req [:twz/id])) (s/def ::db-spec (s/keys :req-un [::twizzlers])) ; (s/def ::db-spec (s/keys :req [::twizzlers])) ;; collective twizzlers ; (s/def ::twizzlers vector?) ;; (s/def ::twizzlers vector?) ;; (s/def ::twizzlers (s/coll-of ::twizzler? :kind vector?)) (s/def ::twizzlers (s/coll-of ::twizzler :kind vector?)) ;; example from david nolen talk ;; (s/def ::first-name ;; (s/with-gen string? ;; #(s/gen #{"Steve" "Sam" "Gretchen"}))) ;; (s/def ::last-name ;; (s/with-gen string? ;; #(s/gen #{"Adams" "Turner" "Black"}))) ;; (s/def ::person ;; (s/keys :req [::first-name ::last-name])) (comment ;; (s/valid? ::msg {::text "abc", ::msg-level :INFO})) ;; (s/valid? ::twizzler {:twizzler-id 1}) ;; (s/valid? ::twizzler {::twizzler-id 1}) (s/valid? ::twizzler {::id 1}) ;; (s/valid? ::twz {:twz/id 1}) ,)
22317
(ns cube-test.twizzlers.db (:require [re-frame.core :as re-frame] [clojure.spec.alpha :as s] [clojure.test.check.generators :as gen] [clojure.pprint :refer [pprint]] [cube-test.utils :as utils])) (def dummy 7) (comment (+ 1 1) (print {:a 7, :b 8}) (pprint (gen/generate (s/gen ::first-name))) (pprint (gen/generate (s/gen ::last-name))) (pprint (gen/generate (s/gen ::person))) dummy ,) (def default-db { ;; :name "re-frame" ; ::twizzlers [] :scenes { :space-port {:path "models/space_portal/" :fn "space_portal.glb" :loaded false} :hemisferic {:path "models/hemisferic/" :fn "hemisferic.glb" :loaded false}} :twizzlers []}) ; :msgs-2 [] ; :ints [0 2] ; :max-id 0 ; :input-id 2}) (defn init-db [db] ; (utils/merge-dbs db cube-test.msg-cube.spec.db/default-db) (utils/merge-dbs db default-db)) ;; specs ;; Individual twizzler ;; (s/def ::twizzler-id int?) ;; (s/def :twz/id int?) (s/def ::id int?) ;; (s/def ::twizzler ;; (s/keys :req [::twizzler-id])) (s/def ::twizzler (s/keys :req [::id])) ;; (s/def ::twz ;; (s/keys :req [:twz/id])) (s/def ::db-spec (s/keys :req-un [::twizzlers])) ; (s/def ::db-spec (s/keys :req [::twizzlers])) ;; collective twizzlers ; (s/def ::twizzlers vector?) ;; (s/def ::twizzlers vector?) ;; (s/def ::twizzlers (s/coll-of ::twizzler? :kind vector?)) (s/def ::twizzlers (s/coll-of ::twizzler :kind vector?)) ;; example from david nolen talk ;; (s/def ::first-name ;; (s/with-gen string? ;; #(s/gen #{"<NAME>" "<NAME>" "<NAME>"}))) ;; (s/def ::last-name ;; (s/with-gen string? ;; #(s/gen #{"<NAME>" "<NAME>" "<NAME>"}))) ;; (s/def ::person ;; (s/keys :req [::first-name ::last-name])) (comment ;; (s/valid? ::msg {::text "abc", ::msg-level :INFO})) ;; (s/valid? ::twizzler {:twizzler-id 1}) ;; (s/valid? ::twizzler {::twizzler-id 1}) (s/valid? ::twizzler {::id 1}) ;; (s/valid? ::twz {:twz/id 1}) ,)
true
(ns cube-test.twizzlers.db (:require [re-frame.core :as re-frame] [clojure.spec.alpha :as s] [clojure.test.check.generators :as gen] [clojure.pprint :refer [pprint]] [cube-test.utils :as utils])) (def dummy 7) (comment (+ 1 1) (print {:a 7, :b 8}) (pprint (gen/generate (s/gen ::first-name))) (pprint (gen/generate (s/gen ::last-name))) (pprint (gen/generate (s/gen ::person))) dummy ,) (def default-db { ;; :name "re-frame" ; ::twizzlers [] :scenes { :space-port {:path "models/space_portal/" :fn "space_portal.glb" :loaded false} :hemisferic {:path "models/hemisferic/" :fn "hemisferic.glb" :loaded false}} :twizzlers []}) ; :msgs-2 [] ; :ints [0 2] ; :max-id 0 ; :input-id 2}) (defn init-db [db] ; (utils/merge-dbs db cube-test.msg-cube.spec.db/default-db) (utils/merge-dbs db default-db)) ;; specs ;; Individual twizzler ;; (s/def ::twizzler-id int?) ;; (s/def :twz/id int?) (s/def ::id int?) ;; (s/def ::twizzler ;; (s/keys :req [::twizzler-id])) (s/def ::twizzler (s/keys :req [::id])) ;; (s/def ::twz ;; (s/keys :req [:twz/id])) (s/def ::db-spec (s/keys :req-un [::twizzlers])) ; (s/def ::db-spec (s/keys :req [::twizzlers])) ;; collective twizzlers ; (s/def ::twizzlers vector?) ;; (s/def ::twizzlers vector?) ;; (s/def ::twizzlers (s/coll-of ::twizzler? :kind vector?)) (s/def ::twizzlers (s/coll-of ::twizzler :kind vector?)) ;; example from david nolen talk ;; (s/def ::first-name ;; (s/with-gen string? ;; #(s/gen #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}))) ;; (s/def ::last-name ;; (s/with-gen string? ;; #(s/gen #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"}))) ;; (s/def ::person ;; (s/keys :req [::first-name ::last-name])) (comment ;; (s/valid? ::msg {::text "abc", ::msg-level :INFO})) ;; (s/valid? ::twizzler {:twizzler-id 1}) ;; (s/valid? ::twizzler {::twizzler-id 1}) (s/valid? ::twizzler {::id 1}) ;; (s/valid? ::twz {:twz/id 1}) ,)
[ { "context": "lient-123\"\n :client-secret \"secret-456\"\n :auth-url \"https://o", "end": 452, "score": 0.9984269142150879, "start": 442, "tag": "KEY", "value": "secret-456" } ]
test/objective8/integration/front_end/sign_in.clj
d-cent/objective8
23
(ns objective8.integration.front-end.sign-in (:require [midje.sweet :refer :all] [peridot.core :as p] [objective8.integration.integration-helpers :as helpers] [objective8.utils :as utils] [objective8.config :as config] [objective8.core :as core] [ring.mock.request :as mock])) (def okta-credentials {:client-id "client-123" :client-secret "secret-456" :auth-url "https://okta-instance.com"}) (def default-app (core/front-end-handler helpers/test-config)) (def private-mode-app (core/front-end-handler helpers/test-config)) (defn mock-get-request [path] (mock/request :get path)) (facts "Private mode" (fact "When disabled, endpoints should not be redirected" (binding [config/environment (assoc config/environment :private-mode-enabled false)] (p/request (helpers/front-end-context) utils/host-url) =not=> (helpers/check-redirects-to "/sign-in" 302))) (fact "when enabled, endpoints should be redirected to sign in" (binding [config/environment (assoc config/environment :private-mode-enabled true)] (p/request (helpers/front-end-context) utils/host-url) => (helpers/check-redirects-to "/sign-in" 302))) (tabular (fact "when Okta credentials provided, endpoints should be redirected to sign in" ;TODO - work out how to reconfigure friend to have a different auth url. No Idea where the authenticate middleware is configured. (binding [config/environment (assoc config/environment :okta-credentials okta-credentials :private-mode-enabled ?private)] (p/request (helpers/front-end-context) utils/host-url) => (helpers/check-redirects-to "/sign-in" 302))) ?private true false))
34132
(ns objective8.integration.front-end.sign-in (:require [midje.sweet :refer :all] [peridot.core :as p] [objective8.integration.integration-helpers :as helpers] [objective8.utils :as utils] [objective8.config :as config] [objective8.core :as core] [ring.mock.request :as mock])) (def okta-credentials {:client-id "client-123" :client-secret "<KEY>" :auth-url "https://okta-instance.com"}) (def default-app (core/front-end-handler helpers/test-config)) (def private-mode-app (core/front-end-handler helpers/test-config)) (defn mock-get-request [path] (mock/request :get path)) (facts "Private mode" (fact "When disabled, endpoints should not be redirected" (binding [config/environment (assoc config/environment :private-mode-enabled false)] (p/request (helpers/front-end-context) utils/host-url) =not=> (helpers/check-redirects-to "/sign-in" 302))) (fact "when enabled, endpoints should be redirected to sign in" (binding [config/environment (assoc config/environment :private-mode-enabled true)] (p/request (helpers/front-end-context) utils/host-url) => (helpers/check-redirects-to "/sign-in" 302))) (tabular (fact "when Okta credentials provided, endpoints should be redirected to sign in" ;TODO - work out how to reconfigure friend to have a different auth url. No Idea where the authenticate middleware is configured. (binding [config/environment (assoc config/environment :okta-credentials okta-credentials :private-mode-enabled ?private)] (p/request (helpers/front-end-context) utils/host-url) => (helpers/check-redirects-to "/sign-in" 302))) ?private true false))
true
(ns objective8.integration.front-end.sign-in (:require [midje.sweet :refer :all] [peridot.core :as p] [objective8.integration.integration-helpers :as helpers] [objective8.utils :as utils] [objective8.config :as config] [objective8.core :as core] [ring.mock.request :as mock])) (def okta-credentials {:client-id "client-123" :client-secret "PI:KEY:<KEY>END_PI" :auth-url "https://okta-instance.com"}) (def default-app (core/front-end-handler helpers/test-config)) (def private-mode-app (core/front-end-handler helpers/test-config)) (defn mock-get-request [path] (mock/request :get path)) (facts "Private mode" (fact "When disabled, endpoints should not be redirected" (binding [config/environment (assoc config/environment :private-mode-enabled false)] (p/request (helpers/front-end-context) utils/host-url) =not=> (helpers/check-redirects-to "/sign-in" 302))) (fact "when enabled, endpoints should be redirected to sign in" (binding [config/environment (assoc config/environment :private-mode-enabled true)] (p/request (helpers/front-end-context) utils/host-url) => (helpers/check-redirects-to "/sign-in" 302))) (tabular (fact "when Okta credentials provided, endpoints should be redirected to sign in" ;TODO - work out how to reconfigure friend to have a different auth url. No Idea where the authenticate middleware is configured. (binding [config/environment (assoc config/environment :okta-credentials okta-credentials :private-mode-enabled ?private)] (p/request (helpers/front-end-context) utils/host-url) => (helpers/check-redirects-to "/sign-in" 302))) ?private true false))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald, Kristina Lisa Klinkner\" :date \"2016-10-20\"\n ", "end": 105, "score": 0.9998747110366821, "start": 87, "tag": "NAME", "value": "John Alan McDonald" }, { "context": ":warn-on-boxed)\n(ns ^{:author \"John Alan McDonald, Kristina Lisa Klinkner\" :date \"2016-10-20\"\n :doc \"Turn Java data st", "end": 129, "score": 0.9998725652694702, "start": 107, "tag": "NAME", "value": "Kristina Lisa Klinkner" } ]
src/main/clojure/zana/functions/wrappers.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald, Kristina Lisa Klinkner" :date "2016-10-20" :doc "Turn Java data structures into Clojure functions. Really just specialized versions of <code>memoize</code>." } zana.functions.wrappers (:refer-clojure :exclude [with-meta]) (:require [clojure.string :as s] [zana.commons.core :as commons] [zana.collections.generic :as g] [zana.collections.hppc :as hppc] [zana.collections.guava :as guava] [zana.functions.generic :as zfg] [zana.functions.inverse :as inverse] [zana.geometry.z1 :as z1]) (:import [com.google.common.collect ImmutableMap] [zana.java.functions ArrayLookup])) ;;------------------------------------------------------------------------------ ;; preserve return type hints with adding meta data (defn ^:no-doc with-meta [f ^clojure.lang.IPersistentMap m] (cond (instance? clojure.lang.IFn$OD f) (zana.java.functions.IFnODWithMeta/wrap ^clojure.lang.IFn$OD f m) (instance? clojure.lang.IFn$OL f) (zana.java.functions.IFnOLWithMeta/wrap ^clojure.lang.IFn$OL f m) (instance? clojure.lang.IFn f) (zana.java.functions.IFnWithMeta/wrap ^clojure.lang.IFn f m) (instance? clojure.lang.IObj f) (clojure.core/with-meta f m))) ;;------------------------------------------------------------------------------ ;; array lookup when in range, default value otherwise ;;------------------------------------------------------------------------------ (defn array-lookup? [f] (instance? ArrayLookup f)) (defn array-lookup (^clojure.lang.IFn [values ^String name default] (ArrayLookup/make (into-array values) name default)) (^clojure.lang.IFn [values name] (array-lookup values name nil)) (^clojure.lang.IFn [values] (array-lookup values ""))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain ArrayLookup [^ArrayLookup f] Long/TYPE) (defmethod zfg/codomain ArrayLookup [^ArrayLookup f] Object) (defmethod zfg/support ArrayLookup [^ArrayLookup f] (z1/interval 0 (g/count f))) ;; Does this need to be sorted? (defmethod zfg/range ArrayLookup [^ArrayLookup f] (guava/sort (seq (.getValues f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ArrayLookup [^ArrayLookup f ^java.io.Writer w] (.write w (str "A[" (s/join " " (map pr-str (.getValues f))) ";" (print-str (.fallback f)) "]"))) ;;------------------------------------------------------------------------------ ;; map lookup with default value ;;------------------------------------------------------------------------------ ;; TODO: force m to be an ImmutableMap? (deftype MapLookup [^java.util.Map m ^String nm ^Object default ^clojure.lang.IPersistentMap mta] clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault m k default)) clojure.lang.Named (getName [this] nm) clojure.lang.IObj (withMeta [this mta] (MapLookup. m default nm mta)) (meta [this] mta) Object (equals [this that] (and (instance? MapLookup that) (.equals m (.m ^MapLookup that)))) ;; (identical? m (.m ^MapLookup that)))) (hashCode [this] (System/identityHashCode m)) (toString [this] (str "[" m " " default "]"))) ; Iterable (iterator [this] (assert false "not an iterator")) ; java.util.Map (get [this k] (assert false "not a map"))) ;;------------------------------------------------------------------------------ (defn map-lookup (^clojure.lang.IFn [^java.util.Map m ^String nm default] (MapLookup. (ImmutableMap/copyOf m) nm default {})) (^clojure.lang.IFn [m nm] (map-lookup m nm nil)) (^clojure.lang.IFn [m] (map-lookup m ""))) ;;------------------------------------------------------------------------------ (defn map-lookup? [f] (instance? MapLookup f)) (defn entries ^java.util.Map [^MapLookup f] (.m f)) ;;------------------------------------------------------------------------------ (defn map-index (^clojure.lang.IFn$OD [^clojure.lang.IFn k ^clojure.lang.IFn z ^Iterable data ^String nm ^Object default] (let [b (java.util.HashMap.)] (g/mapc #(.put b (k %) (z %)) data) (MapLookup. (java.util.Collections/unmodifiableMap b) nm default {}))) (^clojure.lang.IFn$OD [k z data] (map-index k z data nil (commons/name z)))) ;;------------------------------------------------------------------------------ (defmethod zfg/support MapLookup [^MapLookup f] (guava/sort (.keySet ^java.util.Map (.m f)))) ;;------------------------------------------------------------------------------ ;; object->double map lookup with default NaN ;;------------------------------------------------------------------------------ ;; !! mutable if a reference to odm is held elsewhere (deftype ODMLookup [^com.carrotsearch.hppc.ObjectDoubleHashMap odm ^String nm ^double default ^clojure.lang.IPersistentMap m] clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault odm k default)) clojure.lang.IFn$OD (invokePrim [this k] (double (.getOrDefault odm k default))) clojure.lang.Named (getName [this] nm) clojure.lang.IObj (withMeta [this m] (ODMLookup. odm default nm m)) (meta [this] m) Object (equals [this that] (and (instance? ODMLookup that) (identical? m (.m ^ODMLookup that)))) (hashCode [this] (System/identityHashCode odm)) (toString [this] (str "[" (hppc/entries odm) " " default "]"))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain ODMLookup [^ODMLookup f] Object) (defmethod zfg/codomain ODMLookup [^ODMLookup f] Double/TYPE) (defmethod zfg/support ODMLookup [^ODMLookup f] (guava/sort (java.util.Arrays/asList (.toArray (.keys ^com.carrotsearch.hppc.ObjectFloatHashMap (.odm f)))))) (defmethod zfg/range ODMLookup [^ODMLookup f] (hppc/range (.values ^com.carrotsearch.hppc.ObjectFloatHashMap (.odm f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ODMLookup [^ODMLookup f ^java.io.Writer w] (.write w (str "[" (hppc/entries (.odm f)) "; " (.default f)"]"))) ;;------------------------------------------------------------------------------ (defn odm-lookup (^clojure.lang.IFn$OD [odm ^String nm default] (ODMLookup. odm nm default {})) (^clojure.lang.IFn$OD [odm nm] (odm-lookup odm nm Double/NaN )) (^clojure.lang.IFn$OD [odm] (odm-lookup odm ""))) ;;------------------------------------------------------------------------------ (defn double-lookup (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable data] (let [m (com.carrotsearch.hppc.ObjectDoubleHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (.invokePrim x datum))) data) (odm-lookup m (str (commons/name x) "-lookup")))) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable ks ^Iterable data] (assert (== (g/count ks) (g/count data))) (let [m (com.carrotsearch.hppc.ObjectDoubleHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (.invokePrim x datum))) ks data) (odm-lookup m (str (commons/name x) "-lookup"))))) ;;------------------------------------------------------------------------------ ;; object->long map lookup with default Long/MIN_VALUE ;;------------------------------------------------------------------------------ (deftype OLMLookup [^com.carrotsearch.hppc.ObjectLongHashMap olm ^String nm ^long default ^clojure.lang.IPersistentMap m] clojure.lang.Named (getName [this] nm) clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault olm k default)) clojure.lang.IFn$OL (invokePrim [this k] (.getOrDefault olm k default)) zana.functions.inverse.Invertible (inverse [this] (let [a (object-array (inc (hppc/max-value olm)))] (doseq [k (hppc/keys olm)] (aset a (.get olm k) k)) (array-lookup a))) clojure.lang.IObj (withMeta [this m] (OLMLookup. olm default nm m)) (meta [this] m) Object (equals [this that] (and (instance? OLMLookup that) (.equals olm (.olm ^OLMLookup that)))) ;; (identical? olm (.olm ^OLMLookup that)))) (hashCode [this] (System/identityHashCode olm)) (toString [this] (str "[" (hppc/entries olm) " " default "]"))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain OLMLookup [^OLMLookup f] Object) (defmethod zfg/codomain OLMLookup [^OLMLookup f] Long/TYPE) (defmethod zfg/support OLMLookup [^OLMLookup f] (guava/sort (java.util.Arrays/asList (.toArray (.keys ^com.carrotsearch.hppc.ObjectLongHashMap (.olm f)))))) (defmethod zfg/range OLMLookup [^OLMLookup f] (hppc/range (.values ^com.carrotsearch.hppc.ObjectLongHashMap (.olm f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method OLMLookup [^OLMLookup f ^java.io.Writer w] (.write w (str "[" (hppc/entries (.olm f)) "; " (.default f)"]"))) ;;------------------------------------------------------------------------------ (defn olm-lookup (^clojure.lang.IFn$OL [olm ^String nm default] (OLMLookup. olm nm default {})) (^clojure.lang.IFn$OL [olm nm] (olm-lookup olm nm Long/MIN_VALUE)) (^clojure.lang.IFn$OL [olm] (olm-lookup olm ""))) ;;------------------------------------------------------------------------------ (defn long-lookup (^clojure.lang.IFn$OL [^clojure.lang.IFn$OL x ^Iterable data] (let [m (com.carrotsearch.hppc.ObjectLongHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (.invokePrim x datum))) data) (olm-lookup m (commons/name x)))) (^clojure.lang.IFn$OL [^clojure.lang.IFn$OL x ^Iterable ks ^Iterable data] (assert (== (g/count ks) (g/count data))) (let [m (com.carrotsearch.hppc.ObjectLongHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (.invokePrim x datum))) ks data) (olm-lookup m (commons/name x))))) ;;------------------------------------------------------------------------------ (extend-type ArrayLookup zana.functions.inverse/Invertible (inverse [this] (let [olm (hppc/object-long-map)] (doseq [i (range (g/count this))] (.put olm i (this i))) (olm-lookup olm (or (commons/name this) ""))))) ;;------------------------------------------------------------------------------ #_(defn rank-function [things] (let [olm (hppc/object-long-map)] (g/mapc (fn [i xi] (.put olm xi (long i))) (range (g/count things)) things) (olm-lookup olm "ranks" (long -1)))) ;;------------------------------------------------------------------------------ ;; object->object identity map lookup with default nil ;; Note: identity map for speed --- may be a premature optimization ;;------------------------------------------------------------------------------ ;; !! mutable if a reference to m is held elsewhere (deftype IdentityMapLookup [^java.util.IdentityHashMap m] clojure.lang.IFn (invoke [this k] (.get m k)) Object (equals [this that] (and (instance? IdentityMapLookup that) (identical? m (.m ^IdentityMapLookup that)))) (hashCode [this] (System/identityHashCode m))) ;;------------------------------------------------------------------------------ (defn- object-lookup (^clojure.lang.IFn$OD [^java.util.IdentityHashMap m] (IdentityMapLookup. m)) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable data] (let [m (java.util.IdentityHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (x datum))) data) (object-lookup m))) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable ks ^Iterable data] (let [m (java.util.IdentityHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (x datum))) ks data) (object-lookup m)))) ;;------------------------------------------------------------------------------ (defn lookup-function "<ul> <li>Return a function, <code>f</code>, wrapping the map-like object <code>m</code>, such that <code>(f k)</code> == <code>(get m k)</code>. </li> <li>Create a map where the keys are the elements of <code>data</code> and the values are the values of <code>x</code>. </li> <li>Create a map where the keys are the elements of <code>ks</code> and the values are <code>x</code> mapped over <code>data</code>. This strange case is used in permutation importance statistics. </li> </ul>" (^clojure.lang.IFn [m] (cond (instance? com.carrotsearch.hppc.ObjectDoubleHashMap m) (odm-lookup m) (instance? com.carrotsearch.hppc.ObjectLongHashMap m) (olm-lookup m) (instance? java.util.IdentityHashMap m) (object-lookup m) :else (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class m)))))) (^clojure.lang.IFn [^clojure.lang.IFn x ^Iterable data] (cond (instance? clojure.lang.IFn$OD x) (double-lookup x data) (instance? clojure.lang.IFn$OL x) (long-lookup x data) (instance? clojure.lang.IFn x) (object-lookup x data) :else ;; redundant now, but we might generalize later (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class x) (class data)))))) ;; for taiga.permutation, etc. (^clojure.lang.IFn [^clojure.lang.IFn x ^Iterable ks ^Iterable data] (cond (instance? clojure.lang.IFn$OD x) (double-lookup x ks data) (instance? clojure.lang.IFn$OL x) (long-lookup x ks data) (instance? clojure.lang.IFn x) (object-lookup x ks data) :else ;; redundant now, but we might generalize later (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class x) (class ks) (class data))))))) ;;------------------------------------------------------------------------------ (defn dataset-id "This is used when taking the union of a collection of datasets, to create an attribute function that tells you which dataset each record came from. Given a map key->Iterable, where the Iterables are disjoint (no elements in common) return a function that maps any element of any of the Iterables to the corresponding key." ^clojure.lang.IFn [^java.util.Map k-iterable-map] (let [n (reduce-kv (fn [^long n k v] (+ n (g/count v))) 0 k-iterable-map) m (java.util.IdentityHashMap. (int n))] (doseq [[k ^Iterable v] k-iterable-map] (let [it (g/iterator v)] (while (g/has-next? it) (.put m (g/next-item it) k)))) (lookup-function m))) ;;------------------------------------------------------------------------------ ;; reduce -> function ;;------------------------------------------------------------------------------ ;; TODO: general reduction (defn sums ^clojure.lang.IFn [^clojure.lang.IFn k ^clojure.lang.IFn v ^Iterable data] (let [m (hppc/sums k v data)] (cond (instance? com.carrotsearch.hppc.ObjectLongHashMap m) (olm-lookup m 0 (str (commons/name v) "-per-" (commons/name k))) (instance? com.carrotsearch.hppc.ObjectDoubleHashMap m) (odm-lookup m 0.0 (str (commons/name v) "-per-" (commons/name k))) :else (throw (IllegalArgumentException. (print-str "can't handle: " (class m))))))) ;;------------------------------------------------------------------------------
122451
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>, <NAME>" :date "2016-10-20" :doc "Turn Java data structures into Clojure functions. Really just specialized versions of <code>memoize</code>." } zana.functions.wrappers (:refer-clojure :exclude [with-meta]) (:require [clojure.string :as s] [zana.commons.core :as commons] [zana.collections.generic :as g] [zana.collections.hppc :as hppc] [zana.collections.guava :as guava] [zana.functions.generic :as zfg] [zana.functions.inverse :as inverse] [zana.geometry.z1 :as z1]) (:import [com.google.common.collect ImmutableMap] [zana.java.functions ArrayLookup])) ;;------------------------------------------------------------------------------ ;; preserve return type hints with adding meta data (defn ^:no-doc with-meta [f ^clojure.lang.IPersistentMap m] (cond (instance? clojure.lang.IFn$OD f) (zana.java.functions.IFnODWithMeta/wrap ^clojure.lang.IFn$OD f m) (instance? clojure.lang.IFn$OL f) (zana.java.functions.IFnOLWithMeta/wrap ^clojure.lang.IFn$OL f m) (instance? clojure.lang.IFn f) (zana.java.functions.IFnWithMeta/wrap ^clojure.lang.IFn f m) (instance? clojure.lang.IObj f) (clojure.core/with-meta f m))) ;;------------------------------------------------------------------------------ ;; array lookup when in range, default value otherwise ;;------------------------------------------------------------------------------ (defn array-lookup? [f] (instance? ArrayLookup f)) (defn array-lookup (^clojure.lang.IFn [values ^String name default] (ArrayLookup/make (into-array values) name default)) (^clojure.lang.IFn [values name] (array-lookup values name nil)) (^clojure.lang.IFn [values] (array-lookup values ""))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain ArrayLookup [^ArrayLookup f] Long/TYPE) (defmethod zfg/codomain ArrayLookup [^ArrayLookup f] Object) (defmethod zfg/support ArrayLookup [^ArrayLookup f] (z1/interval 0 (g/count f))) ;; Does this need to be sorted? (defmethod zfg/range ArrayLookup [^ArrayLookup f] (guava/sort (seq (.getValues f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ArrayLookup [^ArrayLookup f ^java.io.Writer w] (.write w (str "A[" (s/join " " (map pr-str (.getValues f))) ";" (print-str (.fallback f)) "]"))) ;;------------------------------------------------------------------------------ ;; map lookup with default value ;;------------------------------------------------------------------------------ ;; TODO: force m to be an ImmutableMap? (deftype MapLookup [^java.util.Map m ^String nm ^Object default ^clojure.lang.IPersistentMap mta] clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault m k default)) clojure.lang.Named (getName [this] nm) clojure.lang.IObj (withMeta [this mta] (MapLookup. m default nm mta)) (meta [this] mta) Object (equals [this that] (and (instance? MapLookup that) (.equals m (.m ^MapLookup that)))) ;; (identical? m (.m ^MapLookup that)))) (hashCode [this] (System/identityHashCode m)) (toString [this] (str "[" m " " default "]"))) ; Iterable (iterator [this] (assert false "not an iterator")) ; java.util.Map (get [this k] (assert false "not a map"))) ;;------------------------------------------------------------------------------ (defn map-lookup (^clojure.lang.IFn [^java.util.Map m ^String nm default] (MapLookup. (ImmutableMap/copyOf m) nm default {})) (^clojure.lang.IFn [m nm] (map-lookup m nm nil)) (^clojure.lang.IFn [m] (map-lookup m ""))) ;;------------------------------------------------------------------------------ (defn map-lookup? [f] (instance? MapLookup f)) (defn entries ^java.util.Map [^MapLookup f] (.m f)) ;;------------------------------------------------------------------------------ (defn map-index (^clojure.lang.IFn$OD [^clojure.lang.IFn k ^clojure.lang.IFn z ^Iterable data ^String nm ^Object default] (let [b (java.util.HashMap.)] (g/mapc #(.put b (k %) (z %)) data) (MapLookup. (java.util.Collections/unmodifiableMap b) nm default {}))) (^clojure.lang.IFn$OD [k z data] (map-index k z data nil (commons/name z)))) ;;------------------------------------------------------------------------------ (defmethod zfg/support MapLookup [^MapLookup f] (guava/sort (.keySet ^java.util.Map (.m f)))) ;;------------------------------------------------------------------------------ ;; object->double map lookup with default NaN ;;------------------------------------------------------------------------------ ;; !! mutable if a reference to odm is held elsewhere (deftype ODMLookup [^com.carrotsearch.hppc.ObjectDoubleHashMap odm ^String nm ^double default ^clojure.lang.IPersistentMap m] clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault odm k default)) clojure.lang.IFn$OD (invokePrim [this k] (double (.getOrDefault odm k default))) clojure.lang.Named (getName [this] nm) clojure.lang.IObj (withMeta [this m] (ODMLookup. odm default nm m)) (meta [this] m) Object (equals [this that] (and (instance? ODMLookup that) (identical? m (.m ^ODMLookup that)))) (hashCode [this] (System/identityHashCode odm)) (toString [this] (str "[" (hppc/entries odm) " " default "]"))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain ODMLookup [^ODMLookup f] Object) (defmethod zfg/codomain ODMLookup [^ODMLookup f] Double/TYPE) (defmethod zfg/support ODMLookup [^ODMLookup f] (guava/sort (java.util.Arrays/asList (.toArray (.keys ^com.carrotsearch.hppc.ObjectFloatHashMap (.odm f)))))) (defmethod zfg/range ODMLookup [^ODMLookup f] (hppc/range (.values ^com.carrotsearch.hppc.ObjectFloatHashMap (.odm f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ODMLookup [^ODMLookup f ^java.io.Writer w] (.write w (str "[" (hppc/entries (.odm f)) "; " (.default f)"]"))) ;;------------------------------------------------------------------------------ (defn odm-lookup (^clojure.lang.IFn$OD [odm ^String nm default] (ODMLookup. odm nm default {})) (^clojure.lang.IFn$OD [odm nm] (odm-lookup odm nm Double/NaN )) (^clojure.lang.IFn$OD [odm] (odm-lookup odm ""))) ;;------------------------------------------------------------------------------ (defn double-lookup (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable data] (let [m (com.carrotsearch.hppc.ObjectDoubleHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (.invokePrim x datum))) data) (odm-lookup m (str (commons/name x) "-lookup")))) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable ks ^Iterable data] (assert (== (g/count ks) (g/count data))) (let [m (com.carrotsearch.hppc.ObjectDoubleHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (.invokePrim x datum))) ks data) (odm-lookup m (str (commons/name x) "-lookup"))))) ;;------------------------------------------------------------------------------ ;; object->long map lookup with default Long/MIN_VALUE ;;------------------------------------------------------------------------------ (deftype OLMLookup [^com.carrotsearch.hppc.ObjectLongHashMap olm ^String nm ^long default ^clojure.lang.IPersistentMap m] clojure.lang.Named (getName [this] nm) clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault olm k default)) clojure.lang.IFn$OL (invokePrim [this k] (.getOrDefault olm k default)) zana.functions.inverse.Invertible (inverse [this] (let [a (object-array (inc (hppc/max-value olm)))] (doseq [k (hppc/keys olm)] (aset a (.get olm k) k)) (array-lookup a))) clojure.lang.IObj (withMeta [this m] (OLMLookup. olm default nm m)) (meta [this] m) Object (equals [this that] (and (instance? OLMLookup that) (.equals olm (.olm ^OLMLookup that)))) ;; (identical? olm (.olm ^OLMLookup that)))) (hashCode [this] (System/identityHashCode olm)) (toString [this] (str "[" (hppc/entries olm) " " default "]"))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain OLMLookup [^OLMLookup f] Object) (defmethod zfg/codomain OLMLookup [^OLMLookup f] Long/TYPE) (defmethod zfg/support OLMLookup [^OLMLookup f] (guava/sort (java.util.Arrays/asList (.toArray (.keys ^com.carrotsearch.hppc.ObjectLongHashMap (.olm f)))))) (defmethod zfg/range OLMLookup [^OLMLookup f] (hppc/range (.values ^com.carrotsearch.hppc.ObjectLongHashMap (.olm f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method OLMLookup [^OLMLookup f ^java.io.Writer w] (.write w (str "[" (hppc/entries (.olm f)) "; " (.default f)"]"))) ;;------------------------------------------------------------------------------ (defn olm-lookup (^clojure.lang.IFn$OL [olm ^String nm default] (OLMLookup. olm nm default {})) (^clojure.lang.IFn$OL [olm nm] (olm-lookup olm nm Long/MIN_VALUE)) (^clojure.lang.IFn$OL [olm] (olm-lookup olm ""))) ;;------------------------------------------------------------------------------ (defn long-lookup (^clojure.lang.IFn$OL [^clojure.lang.IFn$OL x ^Iterable data] (let [m (com.carrotsearch.hppc.ObjectLongHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (.invokePrim x datum))) data) (olm-lookup m (commons/name x)))) (^clojure.lang.IFn$OL [^clojure.lang.IFn$OL x ^Iterable ks ^Iterable data] (assert (== (g/count ks) (g/count data))) (let [m (com.carrotsearch.hppc.ObjectLongHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (.invokePrim x datum))) ks data) (olm-lookup m (commons/name x))))) ;;------------------------------------------------------------------------------ (extend-type ArrayLookup zana.functions.inverse/Invertible (inverse [this] (let [olm (hppc/object-long-map)] (doseq [i (range (g/count this))] (.put olm i (this i))) (olm-lookup olm (or (commons/name this) ""))))) ;;------------------------------------------------------------------------------ #_(defn rank-function [things] (let [olm (hppc/object-long-map)] (g/mapc (fn [i xi] (.put olm xi (long i))) (range (g/count things)) things) (olm-lookup olm "ranks" (long -1)))) ;;------------------------------------------------------------------------------ ;; object->object identity map lookup with default nil ;; Note: identity map for speed --- may be a premature optimization ;;------------------------------------------------------------------------------ ;; !! mutable if a reference to m is held elsewhere (deftype IdentityMapLookup [^java.util.IdentityHashMap m] clojure.lang.IFn (invoke [this k] (.get m k)) Object (equals [this that] (and (instance? IdentityMapLookup that) (identical? m (.m ^IdentityMapLookup that)))) (hashCode [this] (System/identityHashCode m))) ;;------------------------------------------------------------------------------ (defn- object-lookup (^clojure.lang.IFn$OD [^java.util.IdentityHashMap m] (IdentityMapLookup. m)) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable data] (let [m (java.util.IdentityHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (x datum))) data) (object-lookup m))) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable ks ^Iterable data] (let [m (java.util.IdentityHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (x datum))) ks data) (object-lookup m)))) ;;------------------------------------------------------------------------------ (defn lookup-function "<ul> <li>Return a function, <code>f</code>, wrapping the map-like object <code>m</code>, such that <code>(f k)</code> == <code>(get m k)</code>. </li> <li>Create a map where the keys are the elements of <code>data</code> and the values are the values of <code>x</code>. </li> <li>Create a map where the keys are the elements of <code>ks</code> and the values are <code>x</code> mapped over <code>data</code>. This strange case is used in permutation importance statistics. </li> </ul>" (^clojure.lang.IFn [m] (cond (instance? com.carrotsearch.hppc.ObjectDoubleHashMap m) (odm-lookup m) (instance? com.carrotsearch.hppc.ObjectLongHashMap m) (olm-lookup m) (instance? java.util.IdentityHashMap m) (object-lookup m) :else (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class m)))))) (^clojure.lang.IFn [^clojure.lang.IFn x ^Iterable data] (cond (instance? clojure.lang.IFn$OD x) (double-lookup x data) (instance? clojure.lang.IFn$OL x) (long-lookup x data) (instance? clojure.lang.IFn x) (object-lookup x data) :else ;; redundant now, but we might generalize later (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class x) (class data)))))) ;; for taiga.permutation, etc. (^clojure.lang.IFn [^clojure.lang.IFn x ^Iterable ks ^Iterable data] (cond (instance? clojure.lang.IFn$OD x) (double-lookup x ks data) (instance? clojure.lang.IFn$OL x) (long-lookup x ks data) (instance? clojure.lang.IFn x) (object-lookup x ks data) :else ;; redundant now, but we might generalize later (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class x) (class ks) (class data))))))) ;;------------------------------------------------------------------------------ (defn dataset-id "This is used when taking the union of a collection of datasets, to create an attribute function that tells you which dataset each record came from. Given a map key->Iterable, where the Iterables are disjoint (no elements in common) return a function that maps any element of any of the Iterables to the corresponding key." ^clojure.lang.IFn [^java.util.Map k-iterable-map] (let [n (reduce-kv (fn [^long n k v] (+ n (g/count v))) 0 k-iterable-map) m (java.util.IdentityHashMap. (int n))] (doseq [[k ^Iterable v] k-iterable-map] (let [it (g/iterator v)] (while (g/has-next? it) (.put m (g/next-item it) k)))) (lookup-function m))) ;;------------------------------------------------------------------------------ ;; reduce -> function ;;------------------------------------------------------------------------------ ;; TODO: general reduction (defn sums ^clojure.lang.IFn [^clojure.lang.IFn k ^clojure.lang.IFn v ^Iterable data] (let [m (hppc/sums k v data)] (cond (instance? com.carrotsearch.hppc.ObjectLongHashMap m) (olm-lookup m 0 (str (commons/name v) "-per-" (commons/name k))) (instance? com.carrotsearch.hppc.ObjectDoubleHashMap m) (odm-lookup m 0.0 (str (commons/name v) "-per-" (commons/name k))) :else (throw (IllegalArgumentException. (print-str "can't handle: " (class m))))))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" :date "2016-10-20" :doc "Turn Java data structures into Clojure functions. Really just specialized versions of <code>memoize</code>." } zana.functions.wrappers (:refer-clojure :exclude [with-meta]) (:require [clojure.string :as s] [zana.commons.core :as commons] [zana.collections.generic :as g] [zana.collections.hppc :as hppc] [zana.collections.guava :as guava] [zana.functions.generic :as zfg] [zana.functions.inverse :as inverse] [zana.geometry.z1 :as z1]) (:import [com.google.common.collect ImmutableMap] [zana.java.functions ArrayLookup])) ;;------------------------------------------------------------------------------ ;; preserve return type hints with adding meta data (defn ^:no-doc with-meta [f ^clojure.lang.IPersistentMap m] (cond (instance? clojure.lang.IFn$OD f) (zana.java.functions.IFnODWithMeta/wrap ^clojure.lang.IFn$OD f m) (instance? clojure.lang.IFn$OL f) (zana.java.functions.IFnOLWithMeta/wrap ^clojure.lang.IFn$OL f m) (instance? clojure.lang.IFn f) (zana.java.functions.IFnWithMeta/wrap ^clojure.lang.IFn f m) (instance? clojure.lang.IObj f) (clojure.core/with-meta f m))) ;;------------------------------------------------------------------------------ ;; array lookup when in range, default value otherwise ;;------------------------------------------------------------------------------ (defn array-lookup? [f] (instance? ArrayLookup f)) (defn array-lookup (^clojure.lang.IFn [values ^String name default] (ArrayLookup/make (into-array values) name default)) (^clojure.lang.IFn [values name] (array-lookup values name nil)) (^clojure.lang.IFn [values] (array-lookup values ""))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain ArrayLookup [^ArrayLookup f] Long/TYPE) (defmethod zfg/codomain ArrayLookup [^ArrayLookup f] Object) (defmethod zfg/support ArrayLookup [^ArrayLookup f] (z1/interval 0 (g/count f))) ;; Does this need to be sorted? (defmethod zfg/range ArrayLookup [^ArrayLookup f] (guava/sort (seq (.getValues f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ArrayLookup [^ArrayLookup f ^java.io.Writer w] (.write w (str "A[" (s/join " " (map pr-str (.getValues f))) ";" (print-str (.fallback f)) "]"))) ;;------------------------------------------------------------------------------ ;; map lookup with default value ;;------------------------------------------------------------------------------ ;; TODO: force m to be an ImmutableMap? (deftype MapLookup [^java.util.Map m ^String nm ^Object default ^clojure.lang.IPersistentMap mta] clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault m k default)) clojure.lang.Named (getName [this] nm) clojure.lang.IObj (withMeta [this mta] (MapLookup. m default nm mta)) (meta [this] mta) Object (equals [this that] (and (instance? MapLookup that) (.equals m (.m ^MapLookup that)))) ;; (identical? m (.m ^MapLookup that)))) (hashCode [this] (System/identityHashCode m)) (toString [this] (str "[" m " " default "]"))) ; Iterable (iterator [this] (assert false "not an iterator")) ; java.util.Map (get [this k] (assert false "not a map"))) ;;------------------------------------------------------------------------------ (defn map-lookup (^clojure.lang.IFn [^java.util.Map m ^String nm default] (MapLookup. (ImmutableMap/copyOf m) nm default {})) (^clojure.lang.IFn [m nm] (map-lookup m nm nil)) (^clojure.lang.IFn [m] (map-lookup m ""))) ;;------------------------------------------------------------------------------ (defn map-lookup? [f] (instance? MapLookup f)) (defn entries ^java.util.Map [^MapLookup f] (.m f)) ;;------------------------------------------------------------------------------ (defn map-index (^clojure.lang.IFn$OD [^clojure.lang.IFn k ^clojure.lang.IFn z ^Iterable data ^String nm ^Object default] (let [b (java.util.HashMap.)] (g/mapc #(.put b (k %) (z %)) data) (MapLookup. (java.util.Collections/unmodifiableMap b) nm default {}))) (^clojure.lang.IFn$OD [k z data] (map-index k z data nil (commons/name z)))) ;;------------------------------------------------------------------------------ (defmethod zfg/support MapLookup [^MapLookup f] (guava/sort (.keySet ^java.util.Map (.m f)))) ;;------------------------------------------------------------------------------ ;; object->double map lookup with default NaN ;;------------------------------------------------------------------------------ ;; !! mutable if a reference to odm is held elsewhere (deftype ODMLookup [^com.carrotsearch.hppc.ObjectDoubleHashMap odm ^String nm ^double default ^clojure.lang.IPersistentMap m] clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault odm k default)) clojure.lang.IFn$OD (invokePrim [this k] (double (.getOrDefault odm k default))) clojure.lang.Named (getName [this] nm) clojure.lang.IObj (withMeta [this m] (ODMLookup. odm default nm m)) (meta [this] m) Object (equals [this that] (and (instance? ODMLookup that) (identical? m (.m ^ODMLookup that)))) (hashCode [this] (System/identityHashCode odm)) (toString [this] (str "[" (hppc/entries odm) " " default "]"))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain ODMLookup [^ODMLookup f] Object) (defmethod zfg/codomain ODMLookup [^ODMLookup f] Double/TYPE) (defmethod zfg/support ODMLookup [^ODMLookup f] (guava/sort (java.util.Arrays/asList (.toArray (.keys ^com.carrotsearch.hppc.ObjectFloatHashMap (.odm f)))))) (defmethod zfg/range ODMLookup [^ODMLookup f] (hppc/range (.values ^com.carrotsearch.hppc.ObjectFloatHashMap (.odm f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ODMLookup [^ODMLookup f ^java.io.Writer w] (.write w (str "[" (hppc/entries (.odm f)) "; " (.default f)"]"))) ;;------------------------------------------------------------------------------ (defn odm-lookup (^clojure.lang.IFn$OD [odm ^String nm default] (ODMLookup. odm nm default {})) (^clojure.lang.IFn$OD [odm nm] (odm-lookup odm nm Double/NaN )) (^clojure.lang.IFn$OD [odm] (odm-lookup odm ""))) ;;------------------------------------------------------------------------------ (defn double-lookup (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable data] (let [m (com.carrotsearch.hppc.ObjectDoubleHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (.invokePrim x datum))) data) (odm-lookup m (str (commons/name x) "-lookup")))) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable ks ^Iterable data] (assert (== (g/count ks) (g/count data))) (let [m (com.carrotsearch.hppc.ObjectDoubleHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (.invokePrim x datum))) ks data) (odm-lookup m (str (commons/name x) "-lookup"))))) ;;------------------------------------------------------------------------------ ;; object->long map lookup with default Long/MIN_VALUE ;;------------------------------------------------------------------------------ (deftype OLMLookup [^com.carrotsearch.hppc.ObjectLongHashMap olm ^String nm ^long default ^clojure.lang.IPersistentMap m] clojure.lang.Named (getName [this] nm) clojure.lang.Fn clojure.lang.IFn (invoke [this k] (.getOrDefault olm k default)) clojure.lang.IFn$OL (invokePrim [this k] (.getOrDefault olm k default)) zana.functions.inverse.Invertible (inverse [this] (let [a (object-array (inc (hppc/max-value olm)))] (doseq [k (hppc/keys olm)] (aset a (.get olm k) k)) (array-lookup a))) clojure.lang.IObj (withMeta [this m] (OLMLookup. olm default nm m)) (meta [this] m) Object (equals [this that] (and (instance? OLMLookup that) (.equals olm (.olm ^OLMLookup that)))) ;; (identical? olm (.olm ^OLMLookup that)))) (hashCode [this] (System/identityHashCode olm)) (toString [this] (str "[" (hppc/entries olm) " " default "]"))) ;;------------------------------------------------------------------------------ (defmethod zfg/domain OLMLookup [^OLMLookup f] Object) (defmethod zfg/codomain OLMLookup [^OLMLookup f] Long/TYPE) (defmethod zfg/support OLMLookup [^OLMLookup f] (guava/sort (java.util.Arrays/asList (.toArray (.keys ^com.carrotsearch.hppc.ObjectLongHashMap (.olm f)))))) (defmethod zfg/range OLMLookup [^OLMLookup f] (hppc/range (.values ^com.carrotsearch.hppc.ObjectLongHashMap (.olm f)))) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method OLMLookup [^OLMLookup f ^java.io.Writer w] (.write w (str "[" (hppc/entries (.olm f)) "; " (.default f)"]"))) ;;------------------------------------------------------------------------------ (defn olm-lookup (^clojure.lang.IFn$OL [olm ^String nm default] (OLMLookup. olm nm default {})) (^clojure.lang.IFn$OL [olm nm] (olm-lookup olm nm Long/MIN_VALUE)) (^clojure.lang.IFn$OL [olm] (olm-lookup olm ""))) ;;------------------------------------------------------------------------------ (defn long-lookup (^clojure.lang.IFn$OL [^clojure.lang.IFn$OL x ^Iterable data] (let [m (com.carrotsearch.hppc.ObjectLongHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (.invokePrim x datum))) data) (olm-lookup m (commons/name x)))) (^clojure.lang.IFn$OL [^clojure.lang.IFn$OL x ^Iterable ks ^Iterable data] (assert (== (g/count ks) (g/count data))) (let [m (com.carrotsearch.hppc.ObjectLongHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (.invokePrim x datum))) ks data) (olm-lookup m (commons/name x))))) ;;------------------------------------------------------------------------------ (extend-type ArrayLookup zana.functions.inverse/Invertible (inverse [this] (let [olm (hppc/object-long-map)] (doseq [i (range (g/count this))] (.put olm i (this i))) (olm-lookup olm (or (commons/name this) ""))))) ;;------------------------------------------------------------------------------ #_(defn rank-function [things] (let [olm (hppc/object-long-map)] (g/mapc (fn [i xi] (.put olm xi (long i))) (range (g/count things)) things) (olm-lookup olm "ranks" (long -1)))) ;;------------------------------------------------------------------------------ ;; object->object identity map lookup with default nil ;; Note: identity map for speed --- may be a premature optimization ;;------------------------------------------------------------------------------ ;; !! mutable if a reference to m is held elsewhere (deftype IdentityMapLookup [^java.util.IdentityHashMap m] clojure.lang.IFn (invoke [this k] (.get m k)) Object (equals [this that] (and (instance? IdentityMapLookup that) (identical? m (.m ^IdentityMapLookup that)))) (hashCode [this] (System/identityHashCode m))) ;;------------------------------------------------------------------------------ (defn- object-lookup (^clojure.lang.IFn$OD [^java.util.IdentityHashMap m] (IdentityMapLookup. m)) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable data] (let [m (java.util.IdentityHashMap. (g/count data))] (g/mapc (fn put [datum] (.put m datum (x datum))) data) (object-lookup m))) (^clojure.lang.IFn$OD [^clojure.lang.IFn$OD x ^Iterable ks ^Iterable data] (let [m (java.util.IdentityHashMap. (g/count data))] (g/mapc (fn put [k datum] (.put m k (x datum))) ks data) (object-lookup m)))) ;;------------------------------------------------------------------------------ (defn lookup-function "<ul> <li>Return a function, <code>f</code>, wrapping the map-like object <code>m</code>, such that <code>(f k)</code> == <code>(get m k)</code>. </li> <li>Create a map where the keys are the elements of <code>data</code> and the values are the values of <code>x</code>. </li> <li>Create a map where the keys are the elements of <code>ks</code> and the values are <code>x</code> mapped over <code>data</code>. This strange case is used in permutation importance statistics. </li> </ul>" (^clojure.lang.IFn [m] (cond (instance? com.carrotsearch.hppc.ObjectDoubleHashMap m) (odm-lookup m) (instance? com.carrotsearch.hppc.ObjectLongHashMap m) (olm-lookup m) (instance? java.util.IdentityHashMap m) (object-lookup m) :else (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class m)))))) (^clojure.lang.IFn [^clojure.lang.IFn x ^Iterable data] (cond (instance? clojure.lang.IFn$OD x) (double-lookup x data) (instance? clojure.lang.IFn$OL x) (long-lookup x data) (instance? clojure.lang.IFn x) (object-lookup x data) :else ;; redundant now, but we might generalize later (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class x) (class data)))))) ;; for taiga.permutation, etc. (^clojure.lang.IFn [^clojure.lang.IFn x ^Iterable ks ^Iterable data] (cond (instance? clojure.lang.IFn$OD x) (double-lookup x ks data) (instance? clojure.lang.IFn$OL x) (long-lookup x ks data) (instance? clojure.lang.IFn x) (object-lookup x ks data) :else ;; redundant now, but we might generalize later (throw (IllegalArgumentException. (print-str "can't create a lookup function from" (class x) (class ks) (class data))))))) ;;------------------------------------------------------------------------------ (defn dataset-id "This is used when taking the union of a collection of datasets, to create an attribute function that tells you which dataset each record came from. Given a map key->Iterable, where the Iterables are disjoint (no elements in common) return a function that maps any element of any of the Iterables to the corresponding key." ^clojure.lang.IFn [^java.util.Map k-iterable-map] (let [n (reduce-kv (fn [^long n k v] (+ n (g/count v))) 0 k-iterable-map) m (java.util.IdentityHashMap. (int n))] (doseq [[k ^Iterable v] k-iterable-map] (let [it (g/iterator v)] (while (g/has-next? it) (.put m (g/next-item it) k)))) (lookup-function m))) ;;------------------------------------------------------------------------------ ;; reduce -> function ;;------------------------------------------------------------------------------ ;; TODO: general reduction (defn sums ^clojure.lang.IFn [^clojure.lang.IFn k ^clojure.lang.IFn v ^Iterable data] (let [m (hppc/sums k v data)] (cond (instance? com.carrotsearch.hppc.ObjectLongHashMap m) (olm-lookup m 0 (str (commons/name v) "-per-" (commons/name k))) (instance? com.carrotsearch.hppc.ObjectDoubleHashMap m) (odm-lookup m 0.0 (str (commons/name v) "-per-" (commons/name k))) :else (throw (IllegalArgumentException. (print-str "can't handle: " (class m))))))) ;;------------------------------------------------------------------------------
[ { "context": "esting \"order of token filters\"\n (let [text \"brown foxes\"\n analyzer (analysis/create {:token-fi", "end": 3899, "score": 0.7919653654098511, "start": 3888, "tag": "NAME", "value": "brown foxes" }, { "context": "oken-strings text analyzer))))\n\n (let [text \"brown foxes\"\n analyzer (analysis/create {:token-fi", "end": 4161, "score": 0.8007417917251587, "start": 4150, "tag": "NAME", "value": "brown foxes" }, { "context": "ensitivity of a component name\"\n (let [text \"brown foxes\"\n porter-stemmer-name \"porterStem\"\n ", "end": 4474, "score": 0.6709112524986267, "start": 4463, "tag": "NAME", "value": "brown foxes" } ]
test/lmgrep/lucene/analysis_test.clj
dainiusjocas/lucene-grep
165
(ns lmgrep.lucene.analysis-test (:require [clojure.test :refer [deftest testing is]] [clojure.string :as str] [lmgrep.lucene.analyzer :as analysis] [lmgrep.lucene.text-analysis :as ta] [jsonista.core :as json])) (deftest predefined-analyzers (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (= ["brown" "fox"] (ta/text->token-strings text analyzer)))) (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "CollationKeyAnalyzer"}})] (is (= ["The brown foxes"] (ta/text->token-strings text analyzer))))) (deftest graph-from-token-stream (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (string? (ta/text->graph text analyzer))))) (deftest detailed-analysis (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (= [{:end_offset 9 :position 0 :positionLength 1 :start_offset 4 :token "brown" :type "<ALPHANUM>"} {:end_offset 15 :position 2 :positionLength 1 :start_offset 10 :token "fox" :type "<ALPHANUM>"}] (map (fn [m] (into {} m)) (ta/text->tokens text analyzer)))))) (deftest analysis-construction-from-components (let [text "The quick brown fox" analyzer (analysis/create {:tokenizer {:name "standard"} :token-filters [{:name "uppercase"}]})] (is (= ["THE" "QUICK" "BROWN" "FOX"] (ta/text->token-strings text analyzer))) (testing "specifying tokenizer is optional" (let [analyzer (analysis/create {:token-filters [{:name "uppercase"}]})] (is (= ["THE" "QUICK" "BROWN" "FOX"] (ta/text->token-strings text analyzer))))) (testing "specifying empty lists works as expected" (let [analyzer (analysis/create {:tokenizer {} :token-filters [] :char-filters []})] (is (= ["The" "quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "providing an empty conf returns proper analyzer" (let [analyzer (analysis/create {})] (is (= ["The" "quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "if char filters work" (let [text "<title>foo</title>" analyzer (analysis/create {:char-filters [{:name "htmlStrip"}]})] (is (= ["foo"] (ta/text->token-strings text analyzer))))) (testing "stopwords token filter with default word list" (let [analyzer (analysis/create {:token-filters [{:name "lowercase"} {:name "stop"}]})] (is (= ["quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "stopwords token filter from a custom file" (let [text "my foo bar baz text" analyzer (analysis/create {:token-filters [{:name "lowercase"} {:name "stop" :args {:words "test/resources/stops.txt"}}]})] (is (= ["my" "text"] (ta/text->token-strings text analyzer))))) (testing "MappingCharFilter file resources" (let [text "my foo bar baz text" analyzer (analysis/create {:char-filters [{:name "mapping" :args {:mapping "test/resources/mapping.txt"}}]})] (is (= ["my" "bar" "bar" "baz" "text"] (ta/text->token-strings text analyzer))))) (testing "order of token filters" (let [text "brown foxes" analyzer (analysis/create {:token-filters [{:name "uppercase"} {:name "porterStem"}]})] (is (= ["BROWN" "FOXES"] (ta/text->token-strings text analyzer)))) (let [text "brown foxes" analyzer (analysis/create {:token-filters [{:name "porterStem"} {:name "uppercase"}]})] (is (= ["BROWN" "FOX"] (ta/text->token-strings text analyzer))))) (testing "case sensitivity of a component name" (let [text "brown foxes" porter-stemmer-name "porterStem" lowercased-ported-stemmer-name (str/lower-case porter-stemmer-name) analyzer-1 (analysis/create {:token-filters [{:name porter-stemmer-name}]}) analyzer-2 (analysis/create {:token-filters [{:name lowercased-ported-stemmer-name}]})] (is (not= porter-stemmer-name lowercased-ported-stemmer-name)) (is (= (ta/text->token-strings text analyzer-1) (ta/text->token-strings text analyzer-2))))))) (deftest tokenizer-tests (let [text "The quick brown fox" analyzer (analysis/create {:tokenizer {:name "edgengram" :args {:maxGramSize 5}}})] (is (= ["T" "Th" "The" "The " "The q"] (ta/text->token-strings text analyzer))))) (deftest word-delimiter-graph (let [text "TestClass" analyzer (analysis/create {:token-filters [{:name "worddelimitergraph" :args {"generateWordParts" 1 "generateNumberParts" 1 "preserveOriginal" 1 "splitOnCaseChange" 1}}]})] (is (= ["TestClass" "Test" "Class"] (ta/text->token-strings text analyzer))))) (deftest lithuanian-snowball-stemmer-token-filter-factory (let [text "lietus lyja" analyzer (analysis/create {:token-filters [{:name "lithuanianSnowballStem"}]})] (is (= ["liet" "lyj"] (ta/text->token-strings text analyzer))))) (deftest try-all-predefined-analyzers (let [text "cats and dogs" analyzer-names (keys analysis/predefined-analyzers)] (is (seq analyzer-names)) (doseq [an analyzer-names] (try (let [analyzer (analysis/create {:analyzer {:name an}})] (is (seq (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/analyzers/%s.json" an) (json/write-value-as-string {:analyzer {:name an}}))) (catch Exception e (println (format "Failed analyzer: '%s'" an)) (.printStackTrace e)))))) (deftest try-all-char-filters (let [text "cats and dogs" char-filter-names (keys analysis/char-filter-name->class) args {"patternreplace" {"pattern" "foo"}}] (is (seq char-filter-names)) (doseq [char-filter-name char-filter-names] (try (let [conf {:char-filters [(if-let [a (get args char-filter-name)] {:name char-filter-name :args a} {:name char-filter-name})]} analyzer (analysis/create conf)] (is (seq (ta/text->token-strings text analyzer)) (spit (format "test/resources/binary/charfilters/%s.json" char-filter-name) (json/write-value-as-string conf)))) (catch Exception e (println (format "Failed char filter name: '%s' class: '%s'" char-filter-name (get analysis/char-filter-name->class char-filter-name))) (throw e)))))) (deftest try-all-tokenizers (let [text "cats and dogs" components analysis/tokenizer-name->class tokenizer-names (keys components) args {"simplepatternsplit" {"pattern" " "} "simplepattern" {"pattern" " "} "pattern" {"pattern" " "}}] (is (seq tokenizer-names)) (doseq [tokenizer-name tokenizer-names] (try (let [conf {:tokenizer (if-let [a (get args tokenizer-name)] {:name tokenizer-name :args a} {:name tokenizer-name})} analyzer (analysis/create conf)] (is (seq (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/tokenizers/%s.json" tokenizer-name) (json/write-value-as-string conf))) (catch Exception e (println (format "Failed tokenizer name: '%s' class: '%s'" tokenizer-name (get components tokenizer-name))) (throw e)))))) (deftest try-all-token-filters (let [text "cats and dogs" components analysis/token-filter-name->class token-filter-names (keys components) args {"limittokencount" {"maxTokenCount" 5} "delimitedpayload" {"encoder" "float"} "limittokenoffset" {"maxStartOffset" 5} "length" {"min" 1 "max" 5} "type" {"types" "test/resources/stops.txt"} "ngram" {"minGramSize" 1 "maxGramSize" 5} "protectedterm" {"protected" "test/resources/stops.txt"} "edgengram" {"minGramSize" 1 "maxGramSize" 5} "limittokenposition" {"maxTokenPosition" 2} "codepointcount" {"min" 1 "max" 5} "numericpayload" {"payload" 24 "typeMatch" "word"} "patternreplace" {"pattern" " "} "patterncapturegroup" {"pattern" " "} "patterntyping" {"patternFile" "test/resources/pattern.txt"} "dictionarycompoundword" {"dictionary" "test/resources/stops.txt"} "synonymgraph" {"synonyms" "test/resources/mapping.txt"} "hyphenationcompoundword" {"hyphenator" "test/resources/hyphenation_hyphenator.xml"} "hunspellstem" {"dictionary" "test/resources/hunspell_dict.dic" "affix" "test/resources/hunspell_dict.aff"} "dropifflagged" {"dropFlags" "2"}}] (is (seq token-filter-names)) (doseq [token-filter-name token-filter-names] (try (let [analyzer-conf {:token-filters [(if-let [a (get args token-filter-name)] {:name token-filter-name :args a} {:name token-filter-name})]} analyzer (analysis/create analyzer-conf)] (is (vector? (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/tokenfilters/%s.json" token-filter-name) (json/write-value-as-string analyzer-conf))) (catch Exception e (println (format "Failed token filter name: '%s' class: '%s'" token-filter-name (get components token-filter-name))) (throw e))))))
14725
(ns lmgrep.lucene.analysis-test (:require [clojure.test :refer [deftest testing is]] [clojure.string :as str] [lmgrep.lucene.analyzer :as analysis] [lmgrep.lucene.text-analysis :as ta] [jsonista.core :as json])) (deftest predefined-analyzers (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (= ["brown" "fox"] (ta/text->token-strings text analyzer)))) (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "CollationKeyAnalyzer"}})] (is (= ["The brown foxes"] (ta/text->token-strings text analyzer))))) (deftest graph-from-token-stream (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (string? (ta/text->graph text analyzer))))) (deftest detailed-analysis (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (= [{:end_offset 9 :position 0 :positionLength 1 :start_offset 4 :token "brown" :type "<ALPHANUM>"} {:end_offset 15 :position 2 :positionLength 1 :start_offset 10 :token "fox" :type "<ALPHANUM>"}] (map (fn [m] (into {} m)) (ta/text->tokens text analyzer)))))) (deftest analysis-construction-from-components (let [text "The quick brown fox" analyzer (analysis/create {:tokenizer {:name "standard"} :token-filters [{:name "uppercase"}]})] (is (= ["THE" "QUICK" "BROWN" "FOX"] (ta/text->token-strings text analyzer))) (testing "specifying tokenizer is optional" (let [analyzer (analysis/create {:token-filters [{:name "uppercase"}]})] (is (= ["THE" "QUICK" "BROWN" "FOX"] (ta/text->token-strings text analyzer))))) (testing "specifying empty lists works as expected" (let [analyzer (analysis/create {:tokenizer {} :token-filters [] :char-filters []})] (is (= ["The" "quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "providing an empty conf returns proper analyzer" (let [analyzer (analysis/create {})] (is (= ["The" "quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "if char filters work" (let [text "<title>foo</title>" analyzer (analysis/create {:char-filters [{:name "htmlStrip"}]})] (is (= ["foo"] (ta/text->token-strings text analyzer))))) (testing "stopwords token filter with default word list" (let [analyzer (analysis/create {:token-filters [{:name "lowercase"} {:name "stop"}]})] (is (= ["quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "stopwords token filter from a custom file" (let [text "my foo bar baz text" analyzer (analysis/create {:token-filters [{:name "lowercase"} {:name "stop" :args {:words "test/resources/stops.txt"}}]})] (is (= ["my" "text"] (ta/text->token-strings text analyzer))))) (testing "MappingCharFilter file resources" (let [text "my foo bar baz text" analyzer (analysis/create {:char-filters [{:name "mapping" :args {:mapping "test/resources/mapping.txt"}}]})] (is (= ["my" "bar" "bar" "baz" "text"] (ta/text->token-strings text analyzer))))) (testing "order of token filters" (let [text "<NAME>" analyzer (analysis/create {:token-filters [{:name "uppercase"} {:name "porterStem"}]})] (is (= ["BROWN" "FOXES"] (ta/text->token-strings text analyzer)))) (let [text "<NAME>" analyzer (analysis/create {:token-filters [{:name "porterStem"} {:name "uppercase"}]})] (is (= ["BROWN" "FOX"] (ta/text->token-strings text analyzer))))) (testing "case sensitivity of a component name" (let [text "<NAME>" porter-stemmer-name "porterStem" lowercased-ported-stemmer-name (str/lower-case porter-stemmer-name) analyzer-1 (analysis/create {:token-filters [{:name porter-stemmer-name}]}) analyzer-2 (analysis/create {:token-filters [{:name lowercased-ported-stemmer-name}]})] (is (not= porter-stemmer-name lowercased-ported-stemmer-name)) (is (= (ta/text->token-strings text analyzer-1) (ta/text->token-strings text analyzer-2))))))) (deftest tokenizer-tests (let [text "The quick brown fox" analyzer (analysis/create {:tokenizer {:name "edgengram" :args {:maxGramSize 5}}})] (is (= ["T" "Th" "The" "The " "The q"] (ta/text->token-strings text analyzer))))) (deftest word-delimiter-graph (let [text "TestClass" analyzer (analysis/create {:token-filters [{:name "worddelimitergraph" :args {"generateWordParts" 1 "generateNumberParts" 1 "preserveOriginal" 1 "splitOnCaseChange" 1}}]})] (is (= ["TestClass" "Test" "Class"] (ta/text->token-strings text analyzer))))) (deftest lithuanian-snowball-stemmer-token-filter-factory (let [text "lietus lyja" analyzer (analysis/create {:token-filters [{:name "lithuanianSnowballStem"}]})] (is (= ["liet" "lyj"] (ta/text->token-strings text analyzer))))) (deftest try-all-predefined-analyzers (let [text "cats and dogs" analyzer-names (keys analysis/predefined-analyzers)] (is (seq analyzer-names)) (doseq [an analyzer-names] (try (let [analyzer (analysis/create {:analyzer {:name an}})] (is (seq (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/analyzers/%s.json" an) (json/write-value-as-string {:analyzer {:name an}}))) (catch Exception e (println (format "Failed analyzer: '%s'" an)) (.printStackTrace e)))))) (deftest try-all-char-filters (let [text "cats and dogs" char-filter-names (keys analysis/char-filter-name->class) args {"patternreplace" {"pattern" "foo"}}] (is (seq char-filter-names)) (doseq [char-filter-name char-filter-names] (try (let [conf {:char-filters [(if-let [a (get args char-filter-name)] {:name char-filter-name :args a} {:name char-filter-name})]} analyzer (analysis/create conf)] (is (seq (ta/text->token-strings text analyzer)) (spit (format "test/resources/binary/charfilters/%s.json" char-filter-name) (json/write-value-as-string conf)))) (catch Exception e (println (format "Failed char filter name: '%s' class: '%s'" char-filter-name (get analysis/char-filter-name->class char-filter-name))) (throw e)))))) (deftest try-all-tokenizers (let [text "cats and dogs" components analysis/tokenizer-name->class tokenizer-names (keys components) args {"simplepatternsplit" {"pattern" " "} "simplepattern" {"pattern" " "} "pattern" {"pattern" " "}}] (is (seq tokenizer-names)) (doseq [tokenizer-name tokenizer-names] (try (let [conf {:tokenizer (if-let [a (get args tokenizer-name)] {:name tokenizer-name :args a} {:name tokenizer-name})} analyzer (analysis/create conf)] (is (seq (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/tokenizers/%s.json" tokenizer-name) (json/write-value-as-string conf))) (catch Exception e (println (format "Failed tokenizer name: '%s' class: '%s'" tokenizer-name (get components tokenizer-name))) (throw e)))))) (deftest try-all-token-filters (let [text "cats and dogs" components analysis/token-filter-name->class token-filter-names (keys components) args {"limittokencount" {"maxTokenCount" 5} "delimitedpayload" {"encoder" "float"} "limittokenoffset" {"maxStartOffset" 5} "length" {"min" 1 "max" 5} "type" {"types" "test/resources/stops.txt"} "ngram" {"minGramSize" 1 "maxGramSize" 5} "protectedterm" {"protected" "test/resources/stops.txt"} "edgengram" {"minGramSize" 1 "maxGramSize" 5} "limittokenposition" {"maxTokenPosition" 2} "codepointcount" {"min" 1 "max" 5} "numericpayload" {"payload" 24 "typeMatch" "word"} "patternreplace" {"pattern" " "} "patterncapturegroup" {"pattern" " "} "patterntyping" {"patternFile" "test/resources/pattern.txt"} "dictionarycompoundword" {"dictionary" "test/resources/stops.txt"} "synonymgraph" {"synonyms" "test/resources/mapping.txt"} "hyphenationcompoundword" {"hyphenator" "test/resources/hyphenation_hyphenator.xml"} "hunspellstem" {"dictionary" "test/resources/hunspell_dict.dic" "affix" "test/resources/hunspell_dict.aff"} "dropifflagged" {"dropFlags" "2"}}] (is (seq token-filter-names)) (doseq [token-filter-name token-filter-names] (try (let [analyzer-conf {:token-filters [(if-let [a (get args token-filter-name)] {:name token-filter-name :args a} {:name token-filter-name})]} analyzer (analysis/create analyzer-conf)] (is (vector? (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/tokenfilters/%s.json" token-filter-name) (json/write-value-as-string analyzer-conf))) (catch Exception e (println (format "Failed token filter name: '%s' class: '%s'" token-filter-name (get components token-filter-name))) (throw e))))))
true
(ns lmgrep.lucene.analysis-test (:require [clojure.test :refer [deftest testing is]] [clojure.string :as str] [lmgrep.lucene.analyzer :as analysis] [lmgrep.lucene.text-analysis :as ta] [jsonista.core :as json])) (deftest predefined-analyzers (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (= ["brown" "fox"] (ta/text->token-strings text analyzer)))) (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "CollationKeyAnalyzer"}})] (is (= ["The brown foxes"] (ta/text->token-strings text analyzer))))) (deftest graph-from-token-stream (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (string? (ta/text->graph text analyzer))))) (deftest detailed-analysis (let [text "The brown foxes" analyzer (analysis/create {:analyzer {:name "EnglishAnalyzer"}})] (is (= [{:end_offset 9 :position 0 :positionLength 1 :start_offset 4 :token "brown" :type "<ALPHANUM>"} {:end_offset 15 :position 2 :positionLength 1 :start_offset 10 :token "fox" :type "<ALPHANUM>"}] (map (fn [m] (into {} m)) (ta/text->tokens text analyzer)))))) (deftest analysis-construction-from-components (let [text "The quick brown fox" analyzer (analysis/create {:tokenizer {:name "standard"} :token-filters [{:name "uppercase"}]})] (is (= ["THE" "QUICK" "BROWN" "FOX"] (ta/text->token-strings text analyzer))) (testing "specifying tokenizer is optional" (let [analyzer (analysis/create {:token-filters [{:name "uppercase"}]})] (is (= ["THE" "QUICK" "BROWN" "FOX"] (ta/text->token-strings text analyzer))))) (testing "specifying empty lists works as expected" (let [analyzer (analysis/create {:tokenizer {} :token-filters [] :char-filters []})] (is (= ["The" "quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "providing an empty conf returns proper analyzer" (let [analyzer (analysis/create {})] (is (= ["The" "quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "if char filters work" (let [text "<title>foo</title>" analyzer (analysis/create {:char-filters [{:name "htmlStrip"}]})] (is (= ["foo"] (ta/text->token-strings text analyzer))))) (testing "stopwords token filter with default word list" (let [analyzer (analysis/create {:token-filters [{:name "lowercase"} {:name "stop"}]})] (is (= ["quick" "brown" "fox"] (ta/text->token-strings text analyzer))))) (testing "stopwords token filter from a custom file" (let [text "my foo bar baz text" analyzer (analysis/create {:token-filters [{:name "lowercase"} {:name "stop" :args {:words "test/resources/stops.txt"}}]})] (is (= ["my" "text"] (ta/text->token-strings text analyzer))))) (testing "MappingCharFilter file resources" (let [text "my foo bar baz text" analyzer (analysis/create {:char-filters [{:name "mapping" :args {:mapping "test/resources/mapping.txt"}}]})] (is (= ["my" "bar" "bar" "baz" "text"] (ta/text->token-strings text analyzer))))) (testing "order of token filters" (let [text "PI:NAME:<NAME>END_PI" analyzer (analysis/create {:token-filters [{:name "uppercase"} {:name "porterStem"}]})] (is (= ["BROWN" "FOXES"] (ta/text->token-strings text analyzer)))) (let [text "PI:NAME:<NAME>END_PI" analyzer (analysis/create {:token-filters [{:name "porterStem"} {:name "uppercase"}]})] (is (= ["BROWN" "FOX"] (ta/text->token-strings text analyzer))))) (testing "case sensitivity of a component name" (let [text "PI:NAME:<NAME>END_PI" porter-stemmer-name "porterStem" lowercased-ported-stemmer-name (str/lower-case porter-stemmer-name) analyzer-1 (analysis/create {:token-filters [{:name porter-stemmer-name}]}) analyzer-2 (analysis/create {:token-filters [{:name lowercased-ported-stemmer-name}]})] (is (not= porter-stemmer-name lowercased-ported-stemmer-name)) (is (= (ta/text->token-strings text analyzer-1) (ta/text->token-strings text analyzer-2))))))) (deftest tokenizer-tests (let [text "The quick brown fox" analyzer (analysis/create {:tokenizer {:name "edgengram" :args {:maxGramSize 5}}})] (is (= ["T" "Th" "The" "The " "The q"] (ta/text->token-strings text analyzer))))) (deftest word-delimiter-graph (let [text "TestClass" analyzer (analysis/create {:token-filters [{:name "worddelimitergraph" :args {"generateWordParts" 1 "generateNumberParts" 1 "preserveOriginal" 1 "splitOnCaseChange" 1}}]})] (is (= ["TestClass" "Test" "Class"] (ta/text->token-strings text analyzer))))) (deftest lithuanian-snowball-stemmer-token-filter-factory (let [text "lietus lyja" analyzer (analysis/create {:token-filters [{:name "lithuanianSnowballStem"}]})] (is (= ["liet" "lyj"] (ta/text->token-strings text analyzer))))) (deftest try-all-predefined-analyzers (let [text "cats and dogs" analyzer-names (keys analysis/predefined-analyzers)] (is (seq analyzer-names)) (doseq [an analyzer-names] (try (let [analyzer (analysis/create {:analyzer {:name an}})] (is (seq (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/analyzers/%s.json" an) (json/write-value-as-string {:analyzer {:name an}}))) (catch Exception e (println (format "Failed analyzer: '%s'" an)) (.printStackTrace e)))))) (deftest try-all-char-filters (let [text "cats and dogs" char-filter-names (keys analysis/char-filter-name->class) args {"patternreplace" {"pattern" "foo"}}] (is (seq char-filter-names)) (doseq [char-filter-name char-filter-names] (try (let [conf {:char-filters [(if-let [a (get args char-filter-name)] {:name char-filter-name :args a} {:name char-filter-name})]} analyzer (analysis/create conf)] (is (seq (ta/text->token-strings text analyzer)) (spit (format "test/resources/binary/charfilters/%s.json" char-filter-name) (json/write-value-as-string conf)))) (catch Exception e (println (format "Failed char filter name: '%s' class: '%s'" char-filter-name (get analysis/char-filter-name->class char-filter-name))) (throw e)))))) (deftest try-all-tokenizers (let [text "cats and dogs" components analysis/tokenizer-name->class tokenizer-names (keys components) args {"simplepatternsplit" {"pattern" " "} "simplepattern" {"pattern" " "} "pattern" {"pattern" " "}}] (is (seq tokenizer-names)) (doseq [tokenizer-name tokenizer-names] (try (let [conf {:tokenizer (if-let [a (get args tokenizer-name)] {:name tokenizer-name :args a} {:name tokenizer-name})} analyzer (analysis/create conf)] (is (seq (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/tokenizers/%s.json" tokenizer-name) (json/write-value-as-string conf))) (catch Exception e (println (format "Failed tokenizer name: '%s' class: '%s'" tokenizer-name (get components tokenizer-name))) (throw e)))))) (deftest try-all-token-filters (let [text "cats and dogs" components analysis/token-filter-name->class token-filter-names (keys components) args {"limittokencount" {"maxTokenCount" 5} "delimitedpayload" {"encoder" "float"} "limittokenoffset" {"maxStartOffset" 5} "length" {"min" 1 "max" 5} "type" {"types" "test/resources/stops.txt"} "ngram" {"minGramSize" 1 "maxGramSize" 5} "protectedterm" {"protected" "test/resources/stops.txt"} "edgengram" {"minGramSize" 1 "maxGramSize" 5} "limittokenposition" {"maxTokenPosition" 2} "codepointcount" {"min" 1 "max" 5} "numericpayload" {"payload" 24 "typeMatch" "word"} "patternreplace" {"pattern" " "} "patterncapturegroup" {"pattern" " "} "patterntyping" {"patternFile" "test/resources/pattern.txt"} "dictionarycompoundword" {"dictionary" "test/resources/stops.txt"} "synonymgraph" {"synonyms" "test/resources/mapping.txt"} "hyphenationcompoundword" {"hyphenator" "test/resources/hyphenation_hyphenator.xml"} "hunspellstem" {"dictionary" "test/resources/hunspell_dict.dic" "affix" "test/resources/hunspell_dict.aff"} "dropifflagged" {"dropFlags" "2"}}] (is (seq token-filter-names)) (doseq [token-filter-name token-filter-names] (try (let [analyzer-conf {:token-filters [(if-let [a (get args token-filter-name)] {:name token-filter-name :args a} {:name token-filter-name})]} analyzer (analysis/create analyzer-conf)] (is (vector? (ta/text->token-strings text analyzer))) (spit (format "test/resources/binary/tokenfilters/%s.json" token-filter-name) (json/write-value-as-string analyzer-conf))) (catch Exception e (println (format "Failed token filter name: '%s' class: '%s'" token-filter-name (get components token-filter-name))) (throw e))))))
[ { "context": "apetus\"]]\n [\"Uranus\" [\"Miranda\" \"Ariel\" \"Umbriel\" \"Titania\" \"Oberon\"]]\n ", "end": 766, "score": 0.6489079594612122, "start": 765, "tag": "NAME", "value": "A" } ]
Chapter 08 Code/niko/vaadin2/example01-splitpanel/ex1.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(ns ex1 (:import [com.vaadin.ui AbstractComponentContainer Button Button$ClickEvent Button$ClickListener Component GridLayout Label Window Window$CloseListener HorizontalSplitPanel Panel Tree VerticalLayout VerticalSplitPanel Window])) (defonce planets [["Mercury" []] ["Venus" []] ["Earth" ["The Moon"]] ["Mars" ["Phobos" "Deimos"]] ["Jupiter" ["Io" "Europe" "Ganymedes" "Callisto"]] ["Saturn" ["Titan" "Tethys" "Dione" "Rhea" "Iapetus"]] ["Uranus" ["Miranda" "Ariel" "Umbriel" "Titania" "Oberon"]] ["Neptune" ["Triton" "Proteus" "Nereid" "Larissa"]]]) (defn add-moons [tree planet moons] (reduce (fn [tree moon] (doto tree (.addItem moon) (.setParent moon planet) (.setChildrenAllowed moon false))) tree moons)) (defn add-planet [tree [planet moons]] (.addItem tree planet) (if (empty? moons) (.setChildrenAllowed tree planet false) (do (add-moons tree planet moons) (.expandItemsRecursively tree planet))) tree) (defn planet-tree [] (let [tree (Tree. "The Planets and Major Moons")] (reduce add-planet tree planets))) (defn main [app] (let [layout (VerticalLayout.) panel (Panel. "Panel for split panel III") hsplit (HorizontalSplitPanel.)] (.setContent panel hsplit) (.setSizeFull layout) (.setFirstComponent hsplit (planet-tree)) (.setSecondComponent hsplit (Label. "Hello this is a wonderful world !")) (doto (VerticalLayout.) (.addComponent panel))))
14684
(ns ex1 (:import [com.vaadin.ui AbstractComponentContainer Button Button$ClickEvent Button$ClickListener Component GridLayout Label Window Window$CloseListener HorizontalSplitPanel Panel Tree VerticalLayout VerticalSplitPanel Window])) (defonce planets [["Mercury" []] ["Venus" []] ["Earth" ["The Moon"]] ["Mars" ["Phobos" "Deimos"]] ["Jupiter" ["Io" "Europe" "Ganymedes" "Callisto"]] ["Saturn" ["Titan" "Tethys" "Dione" "Rhea" "Iapetus"]] ["Uranus" ["Miranda" "<NAME>riel" "Umbriel" "Titania" "Oberon"]] ["Neptune" ["Triton" "Proteus" "Nereid" "Larissa"]]]) (defn add-moons [tree planet moons] (reduce (fn [tree moon] (doto tree (.addItem moon) (.setParent moon planet) (.setChildrenAllowed moon false))) tree moons)) (defn add-planet [tree [planet moons]] (.addItem tree planet) (if (empty? moons) (.setChildrenAllowed tree planet false) (do (add-moons tree planet moons) (.expandItemsRecursively tree planet))) tree) (defn planet-tree [] (let [tree (Tree. "The Planets and Major Moons")] (reduce add-planet tree planets))) (defn main [app] (let [layout (VerticalLayout.) panel (Panel. "Panel for split panel III") hsplit (HorizontalSplitPanel.)] (.setContent panel hsplit) (.setSizeFull layout) (.setFirstComponent hsplit (planet-tree)) (.setSecondComponent hsplit (Label. "Hello this is a wonderful world !")) (doto (VerticalLayout.) (.addComponent panel))))
true
(ns ex1 (:import [com.vaadin.ui AbstractComponentContainer Button Button$ClickEvent Button$ClickListener Component GridLayout Label Window Window$CloseListener HorizontalSplitPanel Panel Tree VerticalLayout VerticalSplitPanel Window])) (defonce planets [["Mercury" []] ["Venus" []] ["Earth" ["The Moon"]] ["Mars" ["Phobos" "Deimos"]] ["Jupiter" ["Io" "Europe" "Ganymedes" "Callisto"]] ["Saturn" ["Titan" "Tethys" "Dione" "Rhea" "Iapetus"]] ["Uranus" ["Miranda" "PI:NAME:<NAME>END_PIriel" "Umbriel" "Titania" "Oberon"]] ["Neptune" ["Triton" "Proteus" "Nereid" "Larissa"]]]) (defn add-moons [tree planet moons] (reduce (fn [tree moon] (doto tree (.addItem moon) (.setParent moon planet) (.setChildrenAllowed moon false))) tree moons)) (defn add-planet [tree [planet moons]] (.addItem tree planet) (if (empty? moons) (.setChildrenAllowed tree planet false) (do (add-moons tree planet moons) (.expandItemsRecursively tree planet))) tree) (defn planet-tree [] (let [tree (Tree. "The Planets and Major Moons")] (reduce add-planet tree planets))) (defn main [app] (let [layout (VerticalLayout.) panel (Panel. "Panel for split panel III") hsplit (HorizontalSplitPanel.)] (.setContent panel hsplit) (.setSizeFull layout) (.setFirstComponent hsplit (planet-tree)) (.setSecondComponent hsplit (Label. "Hello this is a wonderful world !")) (doto (VerticalLayout.) (.addComponent panel))))
[ { "context": "1 :body \"Created user.\"} (wahu/add-person {:name \"Joel Victor\"\n ", "end": 1066, "score": 0.9997985363006592, "start": 1055, "tag": "NAME", "value": "Joel Victor" }, { "context": "body \"Updated user.\"} (wahu/update-person {:name \"Joel Victor\"\n ", "end": 1308, "score": 0.9997828006744385, "start": 1297, "tag": "NAME", "value": "Joel Victor" }, { "context": "s 200 :body \"Deleted user.\"} (wahu/delete-person \"Joel Victor\"))))", "end": 1546, "score": 0.999614417552948, "start": 1535, "tag": "NAME", "value": "Joel Victor" } ]
save-points/8/test/workshop_app/handlers/users_test_2.clj
inclojure-org/intermediate-clojure-workshop
22
(ns workshop-app.handlers.users-test-2 (:require [clojure.test :refer :all] [workshop-app.handlers.users :as wahu] [workshop-app.db.sqlite :as wads] [workshop-app.db.in-mem :as wadim])) ;; pattern 2. don't create the connection but instead redefine ;; it to an inmemory implementation. ;; these are useful when you communicate to a database over ;; a network (use-fixtures :each (fn [t] (with-redefs [wads/conn wadim/conn wads/create! wadim/create! wads/update! wadim/update! wads/read (fn [conn k] {"dob" (wadim/read conn k)}) wads/delete! wadim/delete!] (t)))) (deftest all-handlers-test (testing "Testing all handlers in one go." (are [expected-response actual-response] (= expected-response actual-response) {:status 201 :body "Created user."} (wahu/add-person {:name "Joel Victor" :dob "2001-01-01"}) {:status 200 :body "Updated user."} (wahu/update-person {:name "Joel Victor" :dob "2000-01-01"}) {:status 200 :body "Deleted user."} (wahu/delete-person "Joel Victor"))))
102635
(ns workshop-app.handlers.users-test-2 (:require [clojure.test :refer :all] [workshop-app.handlers.users :as wahu] [workshop-app.db.sqlite :as wads] [workshop-app.db.in-mem :as wadim])) ;; pattern 2. don't create the connection but instead redefine ;; it to an inmemory implementation. ;; these are useful when you communicate to a database over ;; a network (use-fixtures :each (fn [t] (with-redefs [wads/conn wadim/conn wads/create! wadim/create! wads/update! wadim/update! wads/read (fn [conn k] {"dob" (wadim/read conn k)}) wads/delete! wadim/delete!] (t)))) (deftest all-handlers-test (testing "Testing all handlers in one go." (are [expected-response actual-response] (= expected-response actual-response) {:status 201 :body "Created user."} (wahu/add-person {:name "<NAME>" :dob "2001-01-01"}) {:status 200 :body "Updated user."} (wahu/update-person {:name "<NAME>" :dob "2000-01-01"}) {:status 200 :body "Deleted user."} (wahu/delete-person "<NAME>"))))
true
(ns workshop-app.handlers.users-test-2 (:require [clojure.test :refer :all] [workshop-app.handlers.users :as wahu] [workshop-app.db.sqlite :as wads] [workshop-app.db.in-mem :as wadim])) ;; pattern 2. don't create the connection but instead redefine ;; it to an inmemory implementation. ;; these are useful when you communicate to a database over ;; a network (use-fixtures :each (fn [t] (with-redefs [wads/conn wadim/conn wads/create! wadim/create! wads/update! wadim/update! wads/read (fn [conn k] {"dob" (wadim/read conn k)}) wads/delete! wadim/delete!] (t)))) (deftest all-handlers-test (testing "Testing all handlers in one go." (are [expected-response actual-response] (= expected-response actual-response) {:status 201 :body "Created user."} (wahu/add-person {:name "PI:NAME:<NAME>END_PI" :dob "2001-01-01"}) {:status 200 :body "Updated user."} (wahu/update-person {:name "PI:NAME:<NAME>END_PI" :dob "2000-01-01"}) {:status 200 :body "Deleted user."} (wahu/delete-person "PI:NAME:<NAME>END_PI"))))
[ { "context": ";; Copyright (C) 2009-2011 Brendan Ribera. All rights reserved.\n;; Distributed under the MI", "end": 41, "score": 0.9998709559440613, "start": 27, "tag": "NAME", "value": "Brendan Ribera" } ]
src/kdtree.cljc
abscondment/clj-kdtree
31
;; Copyright (C) 2009-2011 Brendan Ribera. All rights reserved. ;; Distributed under the MIT License; see the file LICENSE ;; at the root of this distribution. (ns kdtree) (defrecord Node [left right value]) (defrecord Result [point ^double dist-squared]) (defn- dist-squared "Compute the K-dimensional distance between two points" [^doubles a ^doubles b] (loop [res (double 0.0) ind (long 0)] (if (== ind (alength a)) res (let [v (- (aget a ind) (aget b ind))] (recur (+ res (* v v)) (inc ind)))))) (defn- build-tree-internal [points depth] (if (empty? points) nil (let [point-count (count points) k (count (nth points 0)) dimension (mod depth k) points (vec (sort-by #(nth % dimension) points)) median (quot point-count 2) split-point (loop [n median] (cond (= 0 n) n (= (nth (points n) dimension) (nth (points (dec n)) dimension)) (recur (dec n)) :else n)) left-tree (build-tree-internal (subvec points 0 split-point) (inc depth)) right-tree (build-tree-internal (subvec points (inc split-point)) (inc depth))] (Node. left-tree right-tree (double-array (nth points split-point)) (meta (nth points split-point)) nil)))) (defn build-tree "Construct a Kd-tree from points. Assumes all points are of the same dimension." [points] (build-tree-internal points 0)) (defn- insert-internal [tree ^doubles point depth point-meta] (let [k (alength point) dimension (mod depth k)] (if (nil? tree) (Node. nil nil point point-meta nil) (let [^doubles value (:value tree) go-to-left? (< (aget point dimension) (aget value dimension)) left (if go-to-left? (insert-internal (:left tree) point (inc depth) point-meta) (:left tree)) right (if-not go-to-left? (insert-internal (:right tree) point (inc depth) point-meta) (:right tree))] (Node. left right value (meta tree) nil))))) (defn insert "Adds a point to an existing tree." [tree point] (insert-internal tree (double-array point) 0 (meta point))) (defn- find-min-internal [tree dimension depth] (when tree (let [k (count (:value tree)) min-node (fn [node1 node2] (let [^doubles value1 (:value node1) ^doubles value2 (:value node2)] (if (or (nil? value2) (< (aget value1 dimension) (aget value2 dimension))) node1 node2)))] (if (= dimension (mod depth k)) ;; if we're at the dimension of interest, follow the left branch or ;; take the value - left is always smaller in the current dimension (if (:left tree) (recur (:left tree) dimension (inc depth)) tree) ;; otherwise, compare min of self & children (-> tree (min-node (find-min-internal (:left tree) dimension (inc depth))) (min-node (find-min-internal (:right tree) dimension (inc depth)))))))) (defn find-min "Locate the point with the smallest value in a given dimension. Used internally by the delete function. Runs in O(√n) time for a balanced tree." [tree dimension] (let [res (find-min-internal tree dimension 0)] (with-meta (vec (:value res)) (meta res)))) (defn- points= "Compares 2 points represented by arrays of doubles and return true if they are equal" [^doubles a ^doubles b] (loop [i 0] (cond (== i (alength a)) true (== (aget a i) (aget b i)) (recur (inc i)) :else false))) (defn- delete-internal [tree ^doubles point depth] (when tree (let [^doubles value (:value tree) k (alength value) dimension (mod depth k)] (cond ;; point is not here (not (points= point value)) (let [go-to-left? (< (aget point dimension) (aget value dimension)) left (if go-to-left? (delete-internal (:left tree) point (inc depth)) (:left tree)) right (if-not go-to-left? (delete-internal (:right tree) point (inc depth)) (:right tree))] (Node. left right (:value tree) (meta tree) nil)) ;; point is here... three cases: ;; right is not null. (:right tree) (let [min (find-min-internal (:right tree) dimension (inc depth))] (Node. (:left tree) (delete-internal (:right tree) (:value min) (inc depth)) (:value min) (meta min) nil)) ;; left if not null (:left tree) (let [min (find-min-internal (:left tree) dimension (inc depth))] (Node. nil (delete-internal (:left tree) (:value min) (inc depth)) (:value min) (meta min) nil)) ;; both left and right are null :default nil)))) (defn delete "Delete value at the given point. Runs in O(log n) time for a balanced tree." [tree point] (delete-internal tree (double-array point) 0)) (defn- insert-sorted! "Inserts value to sorted transient vector. Vector will not grow bigger than n elements." [vec value ^long n] (if (and (== (count vec) n) (> (:dist-squared value) (:dist-squared (nth vec (dec n))))) vec (loop [ind (long 0) value value vec vec] (cond (= ind n) vec (= ind (count vec)) (conj! vec value) :default (let [existing (nth vec ind)] (if (< (:dist-squared value) (:dist-squared existing)) (recur (inc ind) existing (assoc! vec ind value)) (recur (inc ind) value vec))))))) (defn- nearest-neighbor-internal [tree ^doubles point n dimension best] (if ;; Empty tree? The best list is unchanged. (nil? tree) best ;; Otherwise, recurse! (let [dimension (long dimension) next-dimension (unchecked-remainder-int (unchecked-inc dimension) (alength point)) ^doubles v (:value tree) dim-dist (double (- (aget point dimension) (aget v dimension))) closest-semiplane ((if (> dim-dist 0.0) :right :left) tree) farthest-semiplane ((if (> dim-dist 0.0) :left :right) tree) ;; Compute best list for the near-side of the search order best-with-cur (insert-sorted! best (Result. v (dist-squared v point) (meta tree) nil) n) best-near (nearest-neighbor-internal closest-semiplane point n next-dimension best-with-cur) worst-nearest (->> (dec (count best-near)) (nth best-near) :dist-squared)] ;; If the square distance of our search node to point in the ;; current dimension is still better than the *worst* of the near- ;; side best list, there may be a better solution on the far ;; side. Compute & combine with near-side solutions. (if (< (* dim-dist dim-dist) worst-nearest) (recur farthest-semiplane point n next-dimension best-near) best-near)))) (defn nearest-neighbor "Compute n nearest neighbors for a point. If n is omitted, the result is the nearest neighbor; otherwise, the result is a list of length n." ([tree point] (first (nearest-neighbor tree point 1))) ([tree point n] (->> (transient []) (nearest-neighbor-internal tree (double-array point) n 0) (persistent!) (map #(update-in % [:point] vec))))) (defn- inside-interval? [interval ^doubles point] (let [n (alength point)] (loop [ind 0] (if (== ind n) true (let [^doubles axis-intv (nth interval ind) left (double (aget axis-intv 0)) right (double (aget axis-intv 1)) value (double (aget point ind))] (if (<= left value right) (recur (inc ind)) false)))))) (defn- interval-search-internal [tree interval ^long depth accum] (if (nil? tree) accum (let [^doubles point (:value tree) ;; If current points inside interval - add it to accum. accum (if (inside-interval? interval point) (conj! accum (with-meta (vec point) (meta tree))) accum) k (unchecked-remainder-int depth (alength point)) dim-value (double (aget point k)) ^doubles dim-boundaries (nth interval k) left-boundary (double (aget dim-boundaries 0)) right-boundary (double (aget dim-boundaries 1)) ;;; Go to right subtree only if current dimension value is not to the right of the interval. accum (if (<= dim-value right-boundary) (interval-search-internal (:right tree) interval (unchecked-inc depth) accum) accum) ;; Go to left subtree only if current dimension is not to the left of the interval. accum (if (> dim-value left-boundary) (interval-search-internal (:left tree) interval (unchecked-inc depth) accum) accum)] accum))) (defn interval-search "Find all points inside given interval. Interval is a sequence of boundaries for each dimension. Example: interval 0≤x≤10, 5≤y≤20 represented as [[0 10] [5 20]]" [tree interval] (->> (transient []) (interval-search-internal tree (vec (map double-array interval)) 0) (persistent!)))
62770
;; Copyright (C) 2009-2011 <NAME>. All rights reserved. ;; Distributed under the MIT License; see the file LICENSE ;; at the root of this distribution. (ns kdtree) (defrecord Node [left right value]) (defrecord Result [point ^double dist-squared]) (defn- dist-squared "Compute the K-dimensional distance between two points" [^doubles a ^doubles b] (loop [res (double 0.0) ind (long 0)] (if (== ind (alength a)) res (let [v (- (aget a ind) (aget b ind))] (recur (+ res (* v v)) (inc ind)))))) (defn- build-tree-internal [points depth] (if (empty? points) nil (let [point-count (count points) k (count (nth points 0)) dimension (mod depth k) points (vec (sort-by #(nth % dimension) points)) median (quot point-count 2) split-point (loop [n median] (cond (= 0 n) n (= (nth (points n) dimension) (nth (points (dec n)) dimension)) (recur (dec n)) :else n)) left-tree (build-tree-internal (subvec points 0 split-point) (inc depth)) right-tree (build-tree-internal (subvec points (inc split-point)) (inc depth))] (Node. left-tree right-tree (double-array (nth points split-point)) (meta (nth points split-point)) nil)))) (defn build-tree "Construct a Kd-tree from points. Assumes all points are of the same dimension." [points] (build-tree-internal points 0)) (defn- insert-internal [tree ^doubles point depth point-meta] (let [k (alength point) dimension (mod depth k)] (if (nil? tree) (Node. nil nil point point-meta nil) (let [^doubles value (:value tree) go-to-left? (< (aget point dimension) (aget value dimension)) left (if go-to-left? (insert-internal (:left tree) point (inc depth) point-meta) (:left tree)) right (if-not go-to-left? (insert-internal (:right tree) point (inc depth) point-meta) (:right tree))] (Node. left right value (meta tree) nil))))) (defn insert "Adds a point to an existing tree." [tree point] (insert-internal tree (double-array point) 0 (meta point))) (defn- find-min-internal [tree dimension depth] (when tree (let [k (count (:value tree)) min-node (fn [node1 node2] (let [^doubles value1 (:value node1) ^doubles value2 (:value node2)] (if (or (nil? value2) (< (aget value1 dimension) (aget value2 dimension))) node1 node2)))] (if (= dimension (mod depth k)) ;; if we're at the dimension of interest, follow the left branch or ;; take the value - left is always smaller in the current dimension (if (:left tree) (recur (:left tree) dimension (inc depth)) tree) ;; otherwise, compare min of self & children (-> tree (min-node (find-min-internal (:left tree) dimension (inc depth))) (min-node (find-min-internal (:right tree) dimension (inc depth)))))))) (defn find-min "Locate the point with the smallest value in a given dimension. Used internally by the delete function. Runs in O(√n) time for a balanced tree." [tree dimension] (let [res (find-min-internal tree dimension 0)] (with-meta (vec (:value res)) (meta res)))) (defn- points= "Compares 2 points represented by arrays of doubles and return true if they are equal" [^doubles a ^doubles b] (loop [i 0] (cond (== i (alength a)) true (== (aget a i) (aget b i)) (recur (inc i)) :else false))) (defn- delete-internal [tree ^doubles point depth] (when tree (let [^doubles value (:value tree) k (alength value) dimension (mod depth k)] (cond ;; point is not here (not (points= point value)) (let [go-to-left? (< (aget point dimension) (aget value dimension)) left (if go-to-left? (delete-internal (:left tree) point (inc depth)) (:left tree)) right (if-not go-to-left? (delete-internal (:right tree) point (inc depth)) (:right tree))] (Node. left right (:value tree) (meta tree) nil)) ;; point is here... three cases: ;; right is not null. (:right tree) (let [min (find-min-internal (:right tree) dimension (inc depth))] (Node. (:left tree) (delete-internal (:right tree) (:value min) (inc depth)) (:value min) (meta min) nil)) ;; left if not null (:left tree) (let [min (find-min-internal (:left tree) dimension (inc depth))] (Node. nil (delete-internal (:left tree) (:value min) (inc depth)) (:value min) (meta min) nil)) ;; both left and right are null :default nil)))) (defn delete "Delete value at the given point. Runs in O(log n) time for a balanced tree." [tree point] (delete-internal tree (double-array point) 0)) (defn- insert-sorted! "Inserts value to sorted transient vector. Vector will not grow bigger than n elements." [vec value ^long n] (if (and (== (count vec) n) (> (:dist-squared value) (:dist-squared (nth vec (dec n))))) vec (loop [ind (long 0) value value vec vec] (cond (= ind n) vec (= ind (count vec)) (conj! vec value) :default (let [existing (nth vec ind)] (if (< (:dist-squared value) (:dist-squared existing)) (recur (inc ind) existing (assoc! vec ind value)) (recur (inc ind) value vec))))))) (defn- nearest-neighbor-internal [tree ^doubles point n dimension best] (if ;; Empty tree? The best list is unchanged. (nil? tree) best ;; Otherwise, recurse! (let [dimension (long dimension) next-dimension (unchecked-remainder-int (unchecked-inc dimension) (alength point)) ^doubles v (:value tree) dim-dist (double (- (aget point dimension) (aget v dimension))) closest-semiplane ((if (> dim-dist 0.0) :right :left) tree) farthest-semiplane ((if (> dim-dist 0.0) :left :right) tree) ;; Compute best list for the near-side of the search order best-with-cur (insert-sorted! best (Result. v (dist-squared v point) (meta tree) nil) n) best-near (nearest-neighbor-internal closest-semiplane point n next-dimension best-with-cur) worst-nearest (->> (dec (count best-near)) (nth best-near) :dist-squared)] ;; If the square distance of our search node to point in the ;; current dimension is still better than the *worst* of the near- ;; side best list, there may be a better solution on the far ;; side. Compute & combine with near-side solutions. (if (< (* dim-dist dim-dist) worst-nearest) (recur farthest-semiplane point n next-dimension best-near) best-near)))) (defn nearest-neighbor "Compute n nearest neighbors for a point. If n is omitted, the result is the nearest neighbor; otherwise, the result is a list of length n." ([tree point] (first (nearest-neighbor tree point 1))) ([tree point n] (->> (transient []) (nearest-neighbor-internal tree (double-array point) n 0) (persistent!) (map #(update-in % [:point] vec))))) (defn- inside-interval? [interval ^doubles point] (let [n (alength point)] (loop [ind 0] (if (== ind n) true (let [^doubles axis-intv (nth interval ind) left (double (aget axis-intv 0)) right (double (aget axis-intv 1)) value (double (aget point ind))] (if (<= left value right) (recur (inc ind)) false)))))) (defn- interval-search-internal [tree interval ^long depth accum] (if (nil? tree) accum (let [^doubles point (:value tree) ;; If current points inside interval - add it to accum. accum (if (inside-interval? interval point) (conj! accum (with-meta (vec point) (meta tree))) accum) k (unchecked-remainder-int depth (alength point)) dim-value (double (aget point k)) ^doubles dim-boundaries (nth interval k) left-boundary (double (aget dim-boundaries 0)) right-boundary (double (aget dim-boundaries 1)) ;;; Go to right subtree only if current dimension value is not to the right of the interval. accum (if (<= dim-value right-boundary) (interval-search-internal (:right tree) interval (unchecked-inc depth) accum) accum) ;; Go to left subtree only if current dimension is not to the left of the interval. accum (if (> dim-value left-boundary) (interval-search-internal (:left tree) interval (unchecked-inc depth) accum) accum)] accum))) (defn interval-search "Find all points inside given interval. Interval is a sequence of boundaries for each dimension. Example: interval 0≤x≤10, 5≤y≤20 represented as [[0 10] [5 20]]" [tree interval] (->> (transient []) (interval-search-internal tree (vec (map double-array interval)) 0) (persistent!)))
true
;; Copyright (C) 2009-2011 PI:NAME:<NAME>END_PI. All rights reserved. ;; Distributed under the MIT License; see the file LICENSE ;; at the root of this distribution. (ns kdtree) (defrecord Node [left right value]) (defrecord Result [point ^double dist-squared]) (defn- dist-squared "Compute the K-dimensional distance between two points" [^doubles a ^doubles b] (loop [res (double 0.0) ind (long 0)] (if (== ind (alength a)) res (let [v (- (aget a ind) (aget b ind))] (recur (+ res (* v v)) (inc ind)))))) (defn- build-tree-internal [points depth] (if (empty? points) nil (let [point-count (count points) k (count (nth points 0)) dimension (mod depth k) points (vec (sort-by #(nth % dimension) points)) median (quot point-count 2) split-point (loop [n median] (cond (= 0 n) n (= (nth (points n) dimension) (nth (points (dec n)) dimension)) (recur (dec n)) :else n)) left-tree (build-tree-internal (subvec points 0 split-point) (inc depth)) right-tree (build-tree-internal (subvec points (inc split-point)) (inc depth))] (Node. left-tree right-tree (double-array (nth points split-point)) (meta (nth points split-point)) nil)))) (defn build-tree "Construct a Kd-tree from points. Assumes all points are of the same dimension." [points] (build-tree-internal points 0)) (defn- insert-internal [tree ^doubles point depth point-meta] (let [k (alength point) dimension (mod depth k)] (if (nil? tree) (Node. nil nil point point-meta nil) (let [^doubles value (:value tree) go-to-left? (< (aget point dimension) (aget value dimension)) left (if go-to-left? (insert-internal (:left tree) point (inc depth) point-meta) (:left tree)) right (if-not go-to-left? (insert-internal (:right tree) point (inc depth) point-meta) (:right tree))] (Node. left right value (meta tree) nil))))) (defn insert "Adds a point to an existing tree." [tree point] (insert-internal tree (double-array point) 0 (meta point))) (defn- find-min-internal [tree dimension depth] (when tree (let [k (count (:value tree)) min-node (fn [node1 node2] (let [^doubles value1 (:value node1) ^doubles value2 (:value node2)] (if (or (nil? value2) (< (aget value1 dimension) (aget value2 dimension))) node1 node2)))] (if (= dimension (mod depth k)) ;; if we're at the dimension of interest, follow the left branch or ;; take the value - left is always smaller in the current dimension (if (:left tree) (recur (:left tree) dimension (inc depth)) tree) ;; otherwise, compare min of self & children (-> tree (min-node (find-min-internal (:left tree) dimension (inc depth))) (min-node (find-min-internal (:right tree) dimension (inc depth)))))))) (defn find-min "Locate the point with the smallest value in a given dimension. Used internally by the delete function. Runs in O(√n) time for a balanced tree." [tree dimension] (let [res (find-min-internal tree dimension 0)] (with-meta (vec (:value res)) (meta res)))) (defn- points= "Compares 2 points represented by arrays of doubles and return true if they are equal" [^doubles a ^doubles b] (loop [i 0] (cond (== i (alength a)) true (== (aget a i) (aget b i)) (recur (inc i)) :else false))) (defn- delete-internal [tree ^doubles point depth] (when tree (let [^doubles value (:value tree) k (alength value) dimension (mod depth k)] (cond ;; point is not here (not (points= point value)) (let [go-to-left? (< (aget point dimension) (aget value dimension)) left (if go-to-left? (delete-internal (:left tree) point (inc depth)) (:left tree)) right (if-not go-to-left? (delete-internal (:right tree) point (inc depth)) (:right tree))] (Node. left right (:value tree) (meta tree) nil)) ;; point is here... three cases: ;; right is not null. (:right tree) (let [min (find-min-internal (:right tree) dimension (inc depth))] (Node. (:left tree) (delete-internal (:right tree) (:value min) (inc depth)) (:value min) (meta min) nil)) ;; left if not null (:left tree) (let [min (find-min-internal (:left tree) dimension (inc depth))] (Node. nil (delete-internal (:left tree) (:value min) (inc depth)) (:value min) (meta min) nil)) ;; both left and right are null :default nil)))) (defn delete "Delete value at the given point. Runs in O(log n) time for a balanced tree." [tree point] (delete-internal tree (double-array point) 0)) (defn- insert-sorted! "Inserts value to sorted transient vector. Vector will not grow bigger than n elements." [vec value ^long n] (if (and (== (count vec) n) (> (:dist-squared value) (:dist-squared (nth vec (dec n))))) vec (loop [ind (long 0) value value vec vec] (cond (= ind n) vec (= ind (count vec)) (conj! vec value) :default (let [existing (nth vec ind)] (if (< (:dist-squared value) (:dist-squared existing)) (recur (inc ind) existing (assoc! vec ind value)) (recur (inc ind) value vec))))))) (defn- nearest-neighbor-internal [tree ^doubles point n dimension best] (if ;; Empty tree? The best list is unchanged. (nil? tree) best ;; Otherwise, recurse! (let [dimension (long dimension) next-dimension (unchecked-remainder-int (unchecked-inc dimension) (alength point)) ^doubles v (:value tree) dim-dist (double (- (aget point dimension) (aget v dimension))) closest-semiplane ((if (> dim-dist 0.0) :right :left) tree) farthest-semiplane ((if (> dim-dist 0.0) :left :right) tree) ;; Compute best list for the near-side of the search order best-with-cur (insert-sorted! best (Result. v (dist-squared v point) (meta tree) nil) n) best-near (nearest-neighbor-internal closest-semiplane point n next-dimension best-with-cur) worst-nearest (->> (dec (count best-near)) (nth best-near) :dist-squared)] ;; If the square distance of our search node to point in the ;; current dimension is still better than the *worst* of the near- ;; side best list, there may be a better solution on the far ;; side. Compute & combine with near-side solutions. (if (< (* dim-dist dim-dist) worst-nearest) (recur farthest-semiplane point n next-dimension best-near) best-near)))) (defn nearest-neighbor "Compute n nearest neighbors for a point. If n is omitted, the result is the nearest neighbor; otherwise, the result is a list of length n." ([tree point] (first (nearest-neighbor tree point 1))) ([tree point n] (->> (transient []) (nearest-neighbor-internal tree (double-array point) n 0) (persistent!) (map #(update-in % [:point] vec))))) (defn- inside-interval? [interval ^doubles point] (let [n (alength point)] (loop [ind 0] (if (== ind n) true (let [^doubles axis-intv (nth interval ind) left (double (aget axis-intv 0)) right (double (aget axis-intv 1)) value (double (aget point ind))] (if (<= left value right) (recur (inc ind)) false)))))) (defn- interval-search-internal [tree interval ^long depth accum] (if (nil? tree) accum (let [^doubles point (:value tree) ;; If current points inside interval - add it to accum. accum (if (inside-interval? interval point) (conj! accum (with-meta (vec point) (meta tree))) accum) k (unchecked-remainder-int depth (alength point)) dim-value (double (aget point k)) ^doubles dim-boundaries (nth interval k) left-boundary (double (aget dim-boundaries 0)) right-boundary (double (aget dim-boundaries 1)) ;;; Go to right subtree only if current dimension value is not to the right of the interval. accum (if (<= dim-value right-boundary) (interval-search-internal (:right tree) interval (unchecked-inc depth) accum) accum) ;; Go to left subtree only if current dimension is not to the left of the interval. accum (if (> dim-value left-boundary) (interval-search-internal (:left tree) interval (unchecked-inc depth) accum) accum)] accum))) (defn interval-search "Find all points inside given interval. Interval is a sequence of boundaries for each dimension. Example: interval 0≤x≤10, 5≤y≤20 represented as [[0 10] [5 20]]" [tree interval] (->> (transient []) (interval-search-internal tree (vec (map double-array interval)) 0) (persistent!)))
[ { "context": "ct com.alliander.chainsaw/core \"0.1.0\"\n :author \"Alliander NV <https://www.alliander.com/>\"\n :description \"", "end": 68, "score": 0.9974281191825867, "start": 59, "tag": "NAME", "value": "Alliander" }, { "context": "y for taoensso/timbre\"\n :url \"https://github.com/aliander/chainsaw\"\n :license {:name \"Apache License, Vers", "end": 202, "score": 0.6309829950332642, "start": 194, "tag": "USERNAME", "value": "aliander" } ]
core/project.clj
Alliander/chainsaw
1
(defproject com.alliander.chainsaw/core "0.1.0" :author "Alliander NV <https://www.alliander.com/>" :description "Data driven logging library for taoensso/timbre" :url "https://github.com/aliander/chainsaw" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo} :scm {:dir ".."} :dependencies [[org.clojure/clojure "1.8.0"] [com.taoensso/encore "2.91.1"] [com.taoensso/timbre "4.10.0"]])
96257
(defproject com.alliander.chainsaw/core "0.1.0" :author "<NAME> NV <https://www.alliander.com/>" :description "Data driven logging library for taoensso/timbre" :url "https://github.com/aliander/chainsaw" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo} :scm {:dir ".."} :dependencies [[org.clojure/clojure "1.8.0"] [com.taoensso/encore "2.91.1"] [com.taoensso/timbre "4.10.0"]])
true
(defproject com.alliander.chainsaw/core "0.1.0" :author "PI:NAME:<NAME>END_PI NV <https://www.alliander.com/>" :description "Data driven logging library for taoensso/timbre" :url "https://github.com/aliander/chainsaw" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0" :distribution :repo} :scm {:dir ".."} :dependencies [[org.clojure/clojure "1.8.0"] [com.taoensso/encore "2.91.1"] [com.taoensso/timbre "4.10.0"]])
[ { "context": "temp-file)\n initial-content {\"token-1\" {\"foo1\" \"bar\", \"hello\" \"world1\"}\n ", "end": 1636, "score": 0.828902542591095, "start": 1631, "tag": "KEY", "value": "foo1\"" }, { "context": "le)\n initial-content {\"token-1\" {\"foo1\" \"bar\", \"hello\" \"world1\"}\n \"tok", "end": 1643, "score": 0.7023575305938721, "start": 1638, "tag": "KEY", "value": "bar\"," }, { "context": " initial-content {\"token-1\" {\"foo1\" \"bar\", \"hello\" \"world1\"}\n \"token-3\" {", "end": 1650, "score": 0.5792044401168823, "start": 1645, "tag": "KEY", "value": "hello" }, { "context": "l-content {\"token-1\" {\"foo1\" \"bar\", \"hello\" \"world1\"}\n \"token-3\" {\"foo3\" \"b", "end": 1659, "score": 0.9908210635185242, "start": 1658, "tag": "KEY", "value": "1" }, { "context": " \"world1\"}\n \"token-3\" {\"foo3\" \"bar\", \"hello\" \"world3\"}\n ", "end": 1705, "score": 0.9448526501655579, "start": 1701, "tag": "KEY", "value": "foo3" }, { "context": "1\"}\n \"token-3\" {\"foo3\" \"bar\", \"hello\" \"world3\"}\n \"t", "end": 1711, "score": 0.9353052973747253, "start": 1708, "tag": "KEY", "value": "bar" }, { "context": " \"token-3\" {\"foo3\" \"bar\", \"hello\" \"world3\"}\n \"token-5\" {\"foo5\" \"b", "end": 1729, "score": 0.9376557469367981, "start": 1728, "tag": "KEY", "value": "3" }, { "context": " \"world3\"}\n \"token-5\" {\"foo5\" \"bar\", \"hello\" \"world5\"}}]\n (write-to-file ", "end": 1775, "score": 0.9087637066841125, "start": 1771, "tag": "KEY", "value": "foo5" }, { "context": "3\"}\n \"token-5\" {\"foo5\" \"bar\", \"hello\" \"world5\"}}]\n (write-to-file my-tem", "end": 1781, "score": 0.6562725305557251, "start": 1778, "tag": "KEY", "value": "bar" }, { "context": " \"token-5\" {\"foo5\" \"bar\", \"hello\" \"world5\"}}]\n (write-to-file my-temp-file-path initia", "end": 1799, "score": 0.8141247034072876, "start": 1798, "tag": "KEY", "value": "5" }, { "context": "{\"cpus\" 1, \"mem\" 1024, \"name\" \"token-1\", \"owner\" \"test-user\"}\n \"token-etag\" \"etag", "end": 3665, "score": 0.767937183380127, "start": 3656, "tag": "USERNAME", "value": "test-user" }, { "context": "{\"cpus\" 1, \"mem\" 1024, \"name\" \"token-2\", \"owner\" \"test-user\"}\n \"token-etag\" \"etag", "end": 3828, "score": 0.8878827691078186, "start": 3819, "tag": "USERNAME", "value": "test-user" }, { "context": "{\"cpus\" 1, \"mem\" 1024, \"name\" \"token-3\", \"owner\" \"test-user\"}\n \"token-etag\" \"etag", "end": 3991, "score": 0.6751229166984558, "start": 3982, "tag": "USERNAME", "value": "test-user" }, { "context": "ag\" \"etag-token-3\"}\n \"token-5\" {\"foo5\" \"bar\", \"hello\" \"world5\", \"token-etag\" \"etag-toke", "end": 4086, "score": 0.7225483059883118, "start": 4082, "tag": "KEY", "value": "foo5" }, { "context": "ag-token-3\"}\n \"token-5\" {\"foo5\" \"bar\", \"hello\" \"world5\", \"token-etag\" \"etag-token-5-ol", "end": 4092, "score": 0.7047070860862732, "start": 4089, "tag": "KEY", "value": "bar" }, { "context": " \"token-5\" {\"foo5\" \"bar\", \"hello\" \"world5\", \"token-etag\" \"etag-token-5-old\"}\n ", "end": 4110, "score": 0.7942387461662292, "start": 4104, "tag": "PASSWORD", "value": "world5" }, { "context": "\"etag-token-5-old\"}\n \"token-7\" {\"foo7\" \"bar\", \"hello\" \"world7\", \"token-etag\" \"etag-toke", "end": 4180, "score": 0.7102372646331787, "start": 4176, "tag": "KEY", "value": "foo7" }, { "context": "oken-5-old\"}\n \"token-7\" {\"foo7\" \"bar\", \"hello\" \"world7\", \"token-etag\" \"etag-token-7-ol", "end": 4186, "score": 0.3439180552959442, "start": 4183, "tag": "KEY", "value": "bar" }, { "context": " \"token-7\" {\"foo7\" \"bar\", \"hello\" \"world7\", \"token-etag\" \"etag-token-7-old\"}}\n ", "end": 4204, "score": 0.7259691953659058, "start": 4198, "tag": "PASSWORD", "value": "world7" }, { "context": "1\"}\n \"token-3\" {\"foo3\" \"bar\", \"hello\" \"world3\"}\n ", "end": 4585, "score": 0.9589470624923706, "start": 4584, "tag": "KEY", "value": "3" }, { "context": " \"token-3\" {\"foo3\" \"bar\", \"hello\" \"world3\"}\n \"token-5\" {\"foo5", "end": 4609, "score": 0.6723581552505493, "start": 4603, "tag": "PASSWORD", "value": "world3" }, { "context": "3\"}\n \"token-5\" {\"foo5\" \"bar\", \"hello\" \"world5\"}\n ", "end": 4659, "score": 0.9079633355140686, "start": 4658, "tag": "KEY", "value": "5" }, { "context": " \"token-5\" {\"foo5\" \"bar\", \"hello\" \"world5\"}\n \"token-7\" {\"foo7", "end": 4683, "score": 0.8549305200576782, "start": 4677, "tag": "PASSWORD", "value": "world5" }, { "context": "5\"}\n \"token-7\" {\"foo7\" \"bar\", \"hello\" \"world7\"}}]\n (write-to-f", "end": 4733, "score": 0.8935248851776123, "start": 4732, "tag": "KEY", "value": "7" }, { "context": " \"token-7\" {\"foo7\" \"bar\", \"hello\" \"world7\"}}]\n (write-to-file my-temp-file-path in", "end": 4757, "score": 0.7806346416473389, "start": 4751, "tag": "PASSWORD", "value": "world7" }, { "context": "{\"cpus\" 1, \"mem\" 1024, \"name\" \"token-1\", \"owner\" \"test-user\"}\n \"token-etag\" \"etag", "end": 5024, "score": 0.8522834181785583, "start": 5015, "tag": "USERNAME", "value": "test-user" }, { "context": "{\"cpus\" 1, \"mem\" 1024, \"name\" \"token-2\", \"owner\" \"test-user\"}\n \"token-etag\" \"etag", "end": 5187, "score": 0.8766608238220215, "start": 5178, "tag": "USERNAME", "value": "test-user" }, { "context": "{\"cpus\" 1, \"mem\" 1024, \"name\" \"token-3\", \"owner\" \"test-user\"}\n \"token-etag\" \"etag", "end": 5350, "score": 0.8133425116539001, "start": 5341, "tag": "USERNAME", "value": "test-user" } ]
token-syncer/test/token_syncer/commands/backup_test.clj
mokshjawa/waiter
0
;; ;; 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 token-syncer.commands.backup-test (:require [clojure.test :refer :all] [token-syncer.cli :as cli] [token-syncer.commands.backup :refer :all]) (:import (java.io File))) (defn- create-temp-file "Creates a temporary file." [] (File/createTempFile "temp-" ".json")) (defn- file->path "Returns the absolute path of the file." [^File file] (.getAbsolutePath file)) (defmacro with-temp-file "Uses a temporary file for some content and deletes it immediately after running the body." [bindings & body] (cond (and (= (count bindings) 2) (symbol? (bindings 0))) `(let ~bindings (try ~@body (finally (.delete ~(bindings 0))))) :else (throw (IllegalArgumentException. "with-temp-file requires a single Symbol in bindings")))) (deftest test-read-from-and-write-to-file (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"foo1" "bar", "hello" "world1"} "token-3" {"foo3" "bar", "hello" "world3"} "token-5" {"foo5" "bar", "hello" "world5"}}] (write-to-file my-temp-file-path initial-content) (is (= initial-content (read-from-file my-temp-file-path)))))) (deftest test-backup (let [test-cluster-url "http://www.test-cluster.com" waiter-api {:load-token (fn [cluster-url token] (is (= test-cluster-url cluster-url)) {:description {"cpus" 1, "mem" 1024, "name" token, "owner" "test-user"} :token-etag (str "etag-" token)}) :load-token-list (fn [cluster-url] (is (= test-cluster-url cluster-url)) [{"etag" "etag-token-1", "token" "token-1"} {"etag" "etag-token-2", "token" "token-2"} {"etag" "etag-token-3", "token" "token-3"}])} file-operations-api {:read-from-file read-from-file :write-to-file write-to-file}] (testing "backup in accrete mode" (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"foo1" "bar", "hello" "world1", "token-etag" "etag-token-1-old"} "token-3" {"foo3" "bar", "hello" "world3", "token-etag" "etag-token-3-old"} "token-5" {"foo5" "bar", "hello" "world5", "token-etag" "etag-token-5-old"} "token-7" {"foo7" "bar", "hello" "world7", "token-etag" "etag-token-7-old"}}] (write-to-file my-temp-file-path initial-content) (backup-tokens waiter-api file-operations-api test-cluster-url my-temp-file-path true) (is (= {"token-1" {"description" {"cpus" 1, "mem" 1024, "name" "token-1", "owner" "test-user"} "token-etag" "etag-token-1"} "token-2" {"description" {"cpus" 1, "mem" 1024, "name" "token-2", "owner" "test-user"} "token-etag" "etag-token-2"} "token-3" {"description" {"cpus" 1, "mem" 1024, "name" "token-3", "owner" "test-user"} "token-etag" "etag-token-3"} "token-5" {"foo5" "bar", "hello" "world5", "token-etag" "etag-token-5-old"} "token-7" {"foo7" "bar", "hello" "world7", "token-etag" "etag-token-7-old"}} (read-from-file my-temp-file-path)))))) (testing "backup without accrete mode" (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"foo1" "bar", "hello" "world1"} "token-3" {"foo3" "bar", "hello" "world3"} "token-5" {"foo5" "bar", "hello" "world5"} "token-7" {"foo7" "bar", "hello" "world7"}}] (write-to-file my-temp-file-path initial-content) (backup-tokens waiter-api file-operations-api test-cluster-url my-temp-file-path false) (is (= {"token-1" {"description" {"cpus" 1, "mem" 1024, "name" "token-1", "owner" "test-user"} "token-etag" "etag-token-1"} "token-2" {"description" {"cpus" 1, "mem" 1024, "name" "token-2", "owner" "test-user"} "token-etag" "etag-token-2"} "token-3" {"description" {"cpus" 1, "mem" 1024, "name" "token-3", "owner" "test-user"} "token-etag" "etag-token-3"}} (read-from-file my-temp-file-path)))))))) (deftest test-backup-tokens-config (let [test-command-config (assoc backup-tokens-config :command-name "test-command") waiter-api {:load-token (constantly {}) :load-token-list (constantly {})} context {:waiter-api waiter-api} file-operations-api {:read-from-file (constantly {}) :write-to-file (constantly {})}] (with-redefs [init-file-operations-api (constantly file-operations-api)] (let [args []] (is (= {:exit-code 1 :message "test-command: expected 2 arguments FILE URL, provided 0: []"} (cli/process-command test-command-config context args)))) (with-out-str (let [args ["-h"]] (is (= {:exit-code 0 :message "test-command: displayed documentation"} (cli/process-command test-command-config context args))))) (let [args ["some-file.txt" "http://cluster-1.com" "http://cluster-2.com"]] (is (= {:exit-code 1 :message "test-command: expected 2 arguments FILE URL, provided 3: [\"some-file.txt\" \"http://cluster-1.com\" \"http://cluster-2.com\"]"} (cli/process-command test-command-config context args)))) (let [args ["some-file.txt" "http://cluster-1.com"] invocation-promise (promise)] (with-redefs [backup-tokens (fn [in-waiter-api in-file-operations-api cluster-url file accrete] (is (= waiter-api in-waiter-api)) (is (= file-operations-api in-file-operations-api)) (deliver invocation-promise ::invoked))] (is (= {:exit-code 0 :message "test-command: exiting with code 0"} (cli/process-command test-command-config context args))) (is (= ::invoked (deref invocation-promise 0 ::un-initialized))))))))
3100
;; ;; 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 token-syncer.commands.backup-test (:require [clojure.test :refer :all] [token-syncer.cli :as cli] [token-syncer.commands.backup :refer :all]) (:import (java.io File))) (defn- create-temp-file "Creates a temporary file." [] (File/createTempFile "temp-" ".json")) (defn- file->path "Returns the absolute path of the file." [^File file] (.getAbsolutePath file)) (defmacro with-temp-file "Uses a temporary file for some content and deletes it immediately after running the body." [bindings & body] (cond (and (= (count bindings) 2) (symbol? (bindings 0))) `(let ~bindings (try ~@body (finally (.delete ~(bindings 0))))) :else (throw (IllegalArgumentException. "with-temp-file requires a single Symbol in bindings")))) (deftest test-read-from-and-write-to-file (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"<KEY> "<KEY> "<KEY>" "world<KEY>"} "token-3" {"<KEY>" "<KEY>", "hello" "world<KEY>"} "token-5" {"<KEY>" "<KEY>", "hello" "world<KEY>"}}] (write-to-file my-temp-file-path initial-content) (is (= initial-content (read-from-file my-temp-file-path)))))) (deftest test-backup (let [test-cluster-url "http://www.test-cluster.com" waiter-api {:load-token (fn [cluster-url token] (is (= test-cluster-url cluster-url)) {:description {"cpus" 1, "mem" 1024, "name" token, "owner" "test-user"} :token-etag (str "etag-" token)}) :load-token-list (fn [cluster-url] (is (= test-cluster-url cluster-url)) [{"etag" "etag-token-1", "token" "token-1"} {"etag" "etag-token-2", "token" "token-2"} {"etag" "etag-token-3", "token" "token-3"}])} file-operations-api {:read-from-file read-from-file :write-to-file write-to-file}] (testing "backup in accrete mode" (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"foo1" "bar", "hello" "world1", "token-etag" "etag-token-1-old"} "token-3" {"foo3" "bar", "hello" "world3", "token-etag" "etag-token-3-old"} "token-5" {"foo5" "bar", "hello" "world5", "token-etag" "etag-token-5-old"} "token-7" {"foo7" "bar", "hello" "world7", "token-etag" "etag-token-7-old"}}] (write-to-file my-temp-file-path initial-content) (backup-tokens waiter-api file-operations-api test-cluster-url my-temp-file-path true) (is (= {"token-1" {"description" {"cpus" 1, "mem" 1024, "name" "token-1", "owner" "test-user"} "token-etag" "etag-token-1"} "token-2" {"description" {"cpus" 1, "mem" 1024, "name" "token-2", "owner" "test-user"} "token-etag" "etag-token-2"} "token-3" {"description" {"cpus" 1, "mem" 1024, "name" "token-3", "owner" "test-user"} "token-etag" "etag-token-3"} "token-5" {"<KEY>" "<KEY>", "hello" "<PASSWORD>", "token-etag" "etag-token-5-old"} "token-7" {"<KEY>" "<KEY>", "hello" "<PASSWORD>", "token-etag" "etag-token-7-old"}} (read-from-file my-temp-file-path)))))) (testing "backup without accrete mode" (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"foo1" "bar", "hello" "world1"} "token-3" {"foo<KEY>" "bar", "hello" "<PASSWORD>"} "token-5" {"foo<KEY>" "bar", "hello" "<PASSWORD>"} "token-7" {"foo<KEY>" "bar", "hello" "<PASSWORD>"}}] (write-to-file my-temp-file-path initial-content) (backup-tokens waiter-api file-operations-api test-cluster-url my-temp-file-path false) (is (= {"token-1" {"description" {"cpus" 1, "mem" 1024, "name" "token-1", "owner" "test-user"} "token-etag" "etag-token-1"} "token-2" {"description" {"cpus" 1, "mem" 1024, "name" "token-2", "owner" "test-user"} "token-etag" "etag-token-2"} "token-3" {"description" {"cpus" 1, "mem" 1024, "name" "token-3", "owner" "test-user"} "token-etag" "etag-token-3"}} (read-from-file my-temp-file-path)))))))) (deftest test-backup-tokens-config (let [test-command-config (assoc backup-tokens-config :command-name "test-command") waiter-api {:load-token (constantly {}) :load-token-list (constantly {})} context {:waiter-api waiter-api} file-operations-api {:read-from-file (constantly {}) :write-to-file (constantly {})}] (with-redefs [init-file-operations-api (constantly file-operations-api)] (let [args []] (is (= {:exit-code 1 :message "test-command: expected 2 arguments FILE URL, provided 0: []"} (cli/process-command test-command-config context args)))) (with-out-str (let [args ["-h"]] (is (= {:exit-code 0 :message "test-command: displayed documentation"} (cli/process-command test-command-config context args))))) (let [args ["some-file.txt" "http://cluster-1.com" "http://cluster-2.com"]] (is (= {:exit-code 1 :message "test-command: expected 2 arguments FILE URL, provided 3: [\"some-file.txt\" \"http://cluster-1.com\" \"http://cluster-2.com\"]"} (cli/process-command test-command-config context args)))) (let [args ["some-file.txt" "http://cluster-1.com"] invocation-promise (promise)] (with-redefs [backup-tokens (fn [in-waiter-api in-file-operations-api cluster-url file accrete] (is (= waiter-api in-waiter-api)) (is (= file-operations-api in-file-operations-api)) (deliver invocation-promise ::invoked))] (is (= {:exit-code 0 :message "test-command: exiting with code 0"} (cli/process-command test-command-config context args))) (is (= ::invoked (deref invocation-promise 0 ::un-initialized))))))))
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 token-syncer.commands.backup-test (:require [clojure.test :refer :all] [token-syncer.cli :as cli] [token-syncer.commands.backup :refer :all]) (:import (java.io File))) (defn- create-temp-file "Creates a temporary file." [] (File/createTempFile "temp-" ".json")) (defn- file->path "Returns the absolute path of the file." [^File file] (.getAbsolutePath file)) (defmacro with-temp-file "Uses a temporary file for some content and deletes it immediately after running the body." [bindings & body] (cond (and (= (count bindings) 2) (symbol? (bindings 0))) `(let ~bindings (try ~@body (finally (.delete ~(bindings 0))))) :else (throw (IllegalArgumentException. "with-temp-file requires a single Symbol in bindings")))) (deftest test-read-from-and-write-to-file (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI" "worldPI:KEY:<KEY>END_PI"} "token-3" {"PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI", "hello" "worldPI:KEY:<KEY>END_PI"} "token-5" {"PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI", "hello" "worldPI:KEY:<KEY>END_PI"}}] (write-to-file my-temp-file-path initial-content) (is (= initial-content (read-from-file my-temp-file-path)))))) (deftest test-backup (let [test-cluster-url "http://www.test-cluster.com" waiter-api {:load-token (fn [cluster-url token] (is (= test-cluster-url cluster-url)) {:description {"cpus" 1, "mem" 1024, "name" token, "owner" "test-user"} :token-etag (str "etag-" token)}) :load-token-list (fn [cluster-url] (is (= test-cluster-url cluster-url)) [{"etag" "etag-token-1", "token" "token-1"} {"etag" "etag-token-2", "token" "token-2"} {"etag" "etag-token-3", "token" "token-3"}])} file-operations-api {:read-from-file read-from-file :write-to-file write-to-file}] (testing "backup in accrete mode" (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"foo1" "bar", "hello" "world1", "token-etag" "etag-token-1-old"} "token-3" {"foo3" "bar", "hello" "world3", "token-etag" "etag-token-3-old"} "token-5" {"foo5" "bar", "hello" "world5", "token-etag" "etag-token-5-old"} "token-7" {"foo7" "bar", "hello" "world7", "token-etag" "etag-token-7-old"}}] (write-to-file my-temp-file-path initial-content) (backup-tokens waiter-api file-operations-api test-cluster-url my-temp-file-path true) (is (= {"token-1" {"description" {"cpus" 1, "mem" 1024, "name" "token-1", "owner" "test-user"} "token-etag" "etag-token-1"} "token-2" {"description" {"cpus" 1, "mem" 1024, "name" "token-2", "owner" "test-user"} "token-etag" "etag-token-2"} "token-3" {"description" {"cpus" 1, "mem" 1024, "name" "token-3", "owner" "test-user"} "token-etag" "etag-token-3"} "token-5" {"PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI", "hello" "PI:PASSWORD:<PASSWORD>END_PI", "token-etag" "etag-token-5-old"} "token-7" {"PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI", "hello" "PI:PASSWORD:<PASSWORD>END_PI", "token-etag" "etag-token-7-old"}} (read-from-file my-temp-file-path)))))) (testing "backup without accrete mode" (with-temp-file [my-temp-file (create-temp-file)] (let [my-temp-file-path (file->path my-temp-file) initial-content {"token-1" {"foo1" "bar", "hello" "world1"} "token-3" {"fooPI:KEY:<KEY>END_PI" "bar", "hello" "PI:PASSWORD:<PASSWORD>END_PI"} "token-5" {"fooPI:KEY:<KEY>END_PI" "bar", "hello" "PI:PASSWORD:<PASSWORD>END_PI"} "token-7" {"fooPI:KEY:<KEY>END_PI" "bar", "hello" "PI:PASSWORD:<PASSWORD>END_PI"}}] (write-to-file my-temp-file-path initial-content) (backup-tokens waiter-api file-operations-api test-cluster-url my-temp-file-path false) (is (= {"token-1" {"description" {"cpus" 1, "mem" 1024, "name" "token-1", "owner" "test-user"} "token-etag" "etag-token-1"} "token-2" {"description" {"cpus" 1, "mem" 1024, "name" "token-2", "owner" "test-user"} "token-etag" "etag-token-2"} "token-3" {"description" {"cpus" 1, "mem" 1024, "name" "token-3", "owner" "test-user"} "token-etag" "etag-token-3"}} (read-from-file my-temp-file-path)))))))) (deftest test-backup-tokens-config (let [test-command-config (assoc backup-tokens-config :command-name "test-command") waiter-api {:load-token (constantly {}) :load-token-list (constantly {})} context {:waiter-api waiter-api} file-operations-api {:read-from-file (constantly {}) :write-to-file (constantly {})}] (with-redefs [init-file-operations-api (constantly file-operations-api)] (let [args []] (is (= {:exit-code 1 :message "test-command: expected 2 arguments FILE URL, provided 0: []"} (cli/process-command test-command-config context args)))) (with-out-str (let [args ["-h"]] (is (= {:exit-code 0 :message "test-command: displayed documentation"} (cli/process-command test-command-config context args))))) (let [args ["some-file.txt" "http://cluster-1.com" "http://cluster-2.com"]] (is (= {:exit-code 1 :message "test-command: expected 2 arguments FILE URL, provided 3: [\"some-file.txt\" \"http://cluster-1.com\" \"http://cluster-2.com\"]"} (cli/process-command test-command-config context args)))) (let [args ["some-file.txt" "http://cluster-1.com"] invocation-promise (promise)] (with-redefs [backup-tokens (fn [in-waiter-api in-file-operations-api cluster-url file accrete] (is (= waiter-api in-waiter-api)) (is (= file-operations-api in-file-operations-api)) (deliver invocation-promise ::invoked))] (is (= {:exit-code 0 :message "test-command: exiting with code 0"} (cli/process-command test-command-config context args))) (is (= ::invoked (deref invocation-promise 0 ::un-initialized))))))))
[ { "context": "\n (dom/p {:style {:margin-top \"150px\"}} \"Conrad\"))\n\n (dom/section\n (dom/p \"As a f", "end": 8103, "score": 0.9275715947151184, "start": 8097, "tag": "NAME", "value": "Conrad" } ]
src/cljs/new_website/talks.cljs
chstan/personal-website
0
(ns new-website.talks (:require [om.core :as om :include-macros true] [om-tools.dom :as dom :include-macros true] [om-tools.core :refer-macros [defcomponent defcomponentmethod]] [dommy.core :as dommy :refer-macros [sel sel1]] [clojure.string :as str] [ajax.core :refer [GET POST]] [ajax.edn :refer [edn-response-format]] [goog.string :as gstring] [goog.string.format] [new-website.utility :as util] [new-website.mixins :refer [set-interval-mixin reveal-mixin]])) (defmulti talk-view (fn [talk _] (:kind talk))) (defcomponentmethod talk-view :zanbato-tech-talk [talk _] (render [_] (dom/div {:class "talks-wrapper"} (dom/p (dom/strong (str (:presentation-title talk))) (str ", " (:date talk) ". ") (if (= "#" (:presentation-url talk)) (dom/a {:href "#"} "[upcoming]") (dom/a {:href (:presentation-url talk)} "[slides]")))))) (defcomponentmethod talk-view :default [talk _] (render [_] (dom/div {:class "talks-wrapper"} (dom/p (dom/strong (str (:presentation-title talk))) (str " at " (:name talk) ", " (:location talk) ". " (:date talk) ". ") (if (= "#" (:presentation-url talk)) (dom/a {:href "#"} "[upcoming]") (dom/a {:href (:presentation-url talk)} "[slides]")))))) (defcomponent talks-view [state owner] (will-mount [_] (if-not (:talks @state) (GET (util/edn-endpoint "talks") {:headers {"Accept" "application/edn"} :response-format (edn-response-format) :handler (fn [resp] (om/transact! state :talks (constantly resp)))}))) (render [_] (dom/div (for [[kind label] [[:zanbato-tech-talk "Tech talks at Zanbato"] [:invited "Invited talks"] [:other "Other talks"]]] (dom/div {:class "talks-container"} (dom/div {:class "talks-section-header"} (dom/p label)) (om/build-all talk-view (filter #(= kind (:kind %)) (:talks @state)))))))) (defcomponent graph [{:keys [xy-range fns]} owner] (:mixins set-interval-mixin) (init-state [_] {:idx 0 :step 0.02 :x-start -1 :cx -1 :theta 0 :interval-id nil}) (did-mount [_] (.set-interval owner (fn [] (om/update-state! owner (fn [{:keys [x-start idx step cx] :as o-state}] (-> o-state (update-in [:idx] (if (> cx 1.3) (constantly 0) inc)) (update-in [:cx] (constantly (+ x-start (* idx step)))) (update-in [:theta] (constantly (if (> cx 1.3) 0 (/ (- cx x-start) 2.3)))))))) 40)) (render-state [_ {:keys [cx theta]}] (let [[[xl xu] [yl yu]] xy-range scale 100 test-fn (first fns)] (dom/div {:style {:width "100%" :height "100%"}} (dom/div (dom/span {:class "formula" :style {:color "red"}} "f(") (dom/span {:class "formula" :style {:color "green"}} "x(\\theta)") (dom/span {:class "formula" :style {:color "red"}} ")") (dom/span {:class "formula"} "\\leq") (dom/span {:class "formula" :style {:color "blue"}} "(1 - ") (dom/span {:class "formula" :style {:color "green"}} "\\theta") (dom/span {:class "formula" :style {:color "blue"}} ")\\cdot f(-1) + ") (dom/span {:class "formula" :style {:color "green"}} "\\theta") (dom/span {:class "formula" :style {:color "blue"}} "\\cdot f(1.3)")) (dom/svg {:width "100%" :height "100%" :style {:border "none"} :viewBox (str/join " " (map (partial * scale) [xl yl (- xu xl) (- yu yl)]))} (dom/g {:transform "scale(1, -1)"} (dom/g {:transform "translate(0, -400)"} (let [delta 0.1] (for [x (range xl xu delta)] (dom/line {:x1 (* 100 x) :x2 (* 100 (+ x delta)) :y1 (* 100 (test-fn x)) :y2 (* 100 (test-fn (+ x delta))) :stroke (cond (> x 1.3) "black" (< x -1) "black" :else "red") :stroke-width 3}))) (dom/line {:x1 (* 100 -1) :x2 (* 100 1.3) :y1 (* 100 (test-fn -1)) :y2 (* 100 (test-fn 1.3)) :stroke "blue" :stroke-width "5"}) (dom/line {:x1 (* 100 -1) :x2 (* 100 1.3) :y1 -50 :y2 -50 :stroke "green" :stroke-width "3"}) (dom/circle {:cx (* 100 cx) :cy (* 100 (test-fn cx)) :r "15" :fill "red"}) (dom/circle {:cx (* 100 cx) :cy (* 100 (+ (* (- 1 theta) (test-fn -1)) (* theta (test-fn 1.3)))) :r "15" :fill "blue"}) (dom/circle {:cx (* 100 cx) :cy -50 :r "15" :fill "green"})))))))) (defcomponent knockout-datasync-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "Data Synchronization in Knockout") (dom/p {:style {:margin-top "150px"}} "Conrad")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "Some things reactive frameworks do well...")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "... and some pains of keeping the client and server updated")) (dom/section (dom/div (dom/span "Knockout")) (dom/p "MVVM") (dom/p {:class "fragment"} "Don't think about view-state manipulations that occur when data changes") (dom/p {:class "fragment"} "Continuous updates as the single source of truth") (dom/p {:class "fragment"} "But Knockout and React are really only view layers")) (dom/section (dom/span "What are the implications of this?")) (dom/section (dom/span "... It's a good thing, but it leaves the question of how we keep the client and server in sync pretty open")) (dom/section (dom/div (dom/span "Huge number of ideas about how to address this")) (dom/div {:class "fragment" :style {:margin-top "40px"}} (dom/strong "Lightweight: ") (dom/p "In view-model AJAX") (dom/p "ko.mapping")) (dom/div {:class "fragment" :style {:margin-top "40px"}} (dom/strong "Not so lightweight: ") (dom/p "Falcor (Netflix)") (dom/p "Relay (Facebook)") (dom/p "Seems like a billion others"))) (dom/section (dom/div (dom/span "Can gain nice properties: ")) (dom/p "Maximally decouple view-logic from sync-logic") (dom/p {:class "fragment"} "Optimistic updates become trivial to implement") (dom/p {:class "fragment"} "Impose structure on dependencies in the view model")) (dom/section (dom/div (dom/span "Knockout provides two powerful utilities:")) (dom/p {:class "fragment"} "Binding handlers") (dom/p {:class "fragment"} "Extenders")) (dom/section (dom/span "Wanted to see what it would take to build a sync layer on top of observables...")))))) (defcomponent data-engineering-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "What's Data Engineering? (And what have we been doing?)") (dom/p {:style {:margin-top "150px"}} "Conrad")) (dom/section (dom/p "As a first thought...") (dom/p {:class "fragment"} "\"Scale\"")) (dom/section (dom/h4 "\"I've been doing a lot with big data recently!\"") (dom/p {:class "fragment"} "(Overhead at the Palo Alto Blue Bottle of a psychology study with " (dom/span {:class "formula"} "n=20000") ")")) (dom/section (dom/p "On the other hand...")) (dom/section (dom/p "Google has on order of {{ mind bogglingly large number }} bytes of data")) (dom/section (dom/p "I'm not going to focus on these because they're relatively uninteresting") (dom/p {:class "fragment"} "Zanbato doesn't have big data (yet?)")) (dom/section (dom/p "There are relatively good tools to deal with data \"at scale\"") (dom/p {:class "fragment"} "(Thanks Google)")) (dom/section (dom/p "That doesn't prevent people from pursuing ridiculous ideas") (dom/a {:href "https://algorithmia.com/"} "https://algorithmia.com/")) (dom/section (dom/span "Critical: Instead of moving data around, ") (dom/span {:class "fragment"} "move code around")) (dom/section (dom/h3 "So what's data engineering?")) (dom/section (dom/p "As a short answer: preparing data for use in some analaysis or product")) (dom/section (dom/p (dom/span {:style {:font-weight 500}} "AKA: ") "Your data science project consumes vectors but you have to feed it pictures, blog post comment threads, paper shipping logs, toxicity records of decomposing leaves found around your Cupertino headquarters sent to you by a third party lab in a proprietary (semi-corrupted) format, turnstile counts from the Library of Congress, and a steady stream of Twitter mentions where people spelled your name slightly wrong")) (dom/section (dom/p "This is just to say that there's a lot of work that goes into preparing data for use in a substantial project")) (dom/section (dom/h4 "Schema Matching") (dom/span {:class "fragment"} "We need to impose stucture onto different sources")) (dom/section (dom/h4 "Entity Recognition") (dom/span {:class "fragment"} "Need to be able to reason about different sources when they're describing the same 'thing'")) (dom/section (dom/h4 "Pipelines") (dom/p {:class "fragment"} "Compositional and simple to understand") (dom/p {:class "fragment"} "De-and-re-constructible approach almost necessary to deal with flexibiity inherent in data science/engineering")) (dom/section (dom/h4 "Data science is exploratory but...") (dom/p {:class "fragment"} "Need to be able to ask questions of data, have a dialog")) (dom/section (dom/h4 "...rate of change is inverse to length of the feedback cycle") (dom/p {:class "fragment"} "Fine when you have a few MB of JSON data, use a REPL") (dom/p {:class "fragment"} "Harder when you're dealing with 100s of GBs of data that's changing and fetched over FTP")) (dom/section (dom/h4 "One of the most important goals of data engineering is to enable fast feedback") (dom/p {:class "fragment"} "Build software to provide a fast and consistent way to access data for heterogenous sources")) (dom/section (dom/p "This stuff's a pain, can a computer do it for me?")) (dom/section (dom/h4 "Some belief that software might be able to do this automatically") (dom/p {:class "fragment"} "Likely what will happen is that tooling will improve in ways that make technical aspects simpler") (dom/p {:class "fragment"} "If you're data is already in a form that a computer can automatically understand it's probably pretty close to 'integrated'")) (dom/section (dom/h4 "Questions?")))))) (defcomponent subgradient-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "Subgradient Iteration + DCP") (dom/p {:style {:margin-top "150px"}} "Conrad")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "...an excuse to talk about convex optimization...")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "...structural features in problem solving.")) (dom/section (dom/span "Convex?") (dom/div {:class "fragment" :style {:width "800px" :height "300px" :margin "auto" :padding-top "50px"}} (->graph {:xy-range [[-2 2] [-1 5]] :fns [(fn [x] (* x x))]}))) (dom/section (dom/div {:class "table-div" :style {:text-align "left" :margin "auto"}} (dom/div (dom/div (dom/span {:class "formula" :style {:padding-right "20px"}} "\\text{minimize:}")) (dom/div (dom/span {:class "formula" :style {:padding-right "20px"}} "\\text{subject to:}"))) (dom/div (dom/div (dom/span {:class "formula"} "f(x)")) (dom/div (dom/div (dom/span {:class "formula"} "x \\in A"))))) (dom/div {:style {:margin-top "80px"}} (dom/span {:class "formula"} "f, A") (dom/span {:style {:padding-left "10px" :font-weight "300"}} " convex (in their respective meanings)"))) (dom/section (dom/span "Why bother with C optimization?") (dom/p {:style {:margin-top "50px"} :class "fragment"} "Convex and spectral optimization can be done globally") (dom/p {:style {:margin-top "50px"} :class "fragment"} "Convex is simpler")) (dom/section (dom/span {:style {:margin-bottom "60px"}} "Why bother with C optimization?") (dom/ul (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Linear programming") (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Least squares") (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Regularizations of many important problems") (dom/li {:style {:margin-top "50px" :font-weight "normal"} :class "fragment"} "Controls (autonomous vehicles, drones, rockets)"))) (dom/section (dom/span "Solving the general problem") (dom/p {:style {:margin-top "50px"}} "Weirdly simple solutions exist") (dom/p {:class "fragment" :style {:margin-top "50px"}} "(even without differentiability)") (dom/p {:class "fragment" :style {:margin-top "50px"}} "(but this one requires something like it)")) (dom/section (dom/span "Subgradient Iteration") (dom/p "Idea is to follow the slope of the function down...") (dom/p "...in a \"generous\" enough interpretation of \"slope\" and \"down\"")) (dom/section (dom/span "Subgradient") (dom/p "Even if a function isn't differentiable, it can be subdifferentiable") (dom/img {:style {:border "none" :box-shadow "none" :width "80%"} :src "/img/subdifferential.png"})) (dom/section (dom/span "Optimizing") (dom/div {:style {:margin-top "80px"}} (dom/span {:class "formula" :style {:font-weight 300}} "x^{(k+1)} = x^{(k)} - \\alpha_k g^{(k)}")) (dom/div (dom/span {:class "formula" :style {:font-weight 300}} "g") (dom/span {:style {:font-weight 300}} " can be any subgradient")) (dom/div {:style {:margin-top "40px" :font-weight 300}} (dom/span "Requires approximately ") (dom/span {:class "formula"} "(\\frac{R G}{\\epsilon})^2") (dom/span " steps"))) (dom/section (dom/span "Optimizing") (dom/div (dom/img {:style {:border "none" :box-shadow "none" :padding-left "10%" :padding-top "70px" :width "80%"} :src "/img/descent.png"})) (dom/p "Not descent!")) (dom/section (dom/span "Symbolic subdifferentiation") (dom/p "How do we find these things?") (let [sexprs '(subdifferential [:abs :x] {:x 0})] (dom/div {:class "fragment"} (dom/pre (dom/code {:class "clojure"} (str sexprs))) (dom/span {:class "formula"} "\\Downarrow") (dom/pre (dom/code {:class "clojure"} "[{:range [-1 1]}]"))))) (dom/section (dom/div (dom/span "Subgradient Rules")) (dom/p "For expressions made up of pieces with computable subgradients, we can use") (dom/ul {:class "fragment" :style {:font-weight 300}} (dom/li "Supremum") (dom/li "Expectation") (dom/li "Chain rule (much like the calculus one)") (dom/li "Duality") (dom/li "+ many others"))) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "Can use similar methods to study the curvature of functions")) (dom/section (dom/img {:style {:border "none" :box-shadow "none" :width "80%"} :src "/img/dcp.png"})) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "CVX and others are compilers for the grammar of convex problems") (dom/p {:class "fragment"} "Their machine ops are high level algorithms,") (dom/p {:class "fragment"} "SOCP solver runs")) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "Targets are drones and embedded systems,") (dom/p {:class "fragment"} "but also distributed systems like Spark + Kafka")))))) (defcomponent subgradient-talk-wrapper [_ _] (render [_] (->subgradient-talk-view {}))) (defcomponent knockout-datasync-talk-wrapper [_ _] (render [_] (->knockout-datasync-talk-view {}))) (defcomponent data-engineering-talk-wrapper [_ _] (render [_] (->data-engineering-talk-view {})))
5369
(ns new-website.talks (:require [om.core :as om :include-macros true] [om-tools.dom :as dom :include-macros true] [om-tools.core :refer-macros [defcomponent defcomponentmethod]] [dommy.core :as dommy :refer-macros [sel sel1]] [clojure.string :as str] [ajax.core :refer [GET POST]] [ajax.edn :refer [edn-response-format]] [goog.string :as gstring] [goog.string.format] [new-website.utility :as util] [new-website.mixins :refer [set-interval-mixin reveal-mixin]])) (defmulti talk-view (fn [talk _] (:kind talk))) (defcomponentmethod talk-view :zanbato-tech-talk [talk _] (render [_] (dom/div {:class "talks-wrapper"} (dom/p (dom/strong (str (:presentation-title talk))) (str ", " (:date talk) ". ") (if (= "#" (:presentation-url talk)) (dom/a {:href "#"} "[upcoming]") (dom/a {:href (:presentation-url talk)} "[slides]")))))) (defcomponentmethod talk-view :default [talk _] (render [_] (dom/div {:class "talks-wrapper"} (dom/p (dom/strong (str (:presentation-title talk))) (str " at " (:name talk) ", " (:location talk) ". " (:date talk) ". ") (if (= "#" (:presentation-url talk)) (dom/a {:href "#"} "[upcoming]") (dom/a {:href (:presentation-url talk)} "[slides]")))))) (defcomponent talks-view [state owner] (will-mount [_] (if-not (:talks @state) (GET (util/edn-endpoint "talks") {:headers {"Accept" "application/edn"} :response-format (edn-response-format) :handler (fn [resp] (om/transact! state :talks (constantly resp)))}))) (render [_] (dom/div (for [[kind label] [[:zanbato-tech-talk "Tech talks at Zanbato"] [:invited "Invited talks"] [:other "Other talks"]]] (dom/div {:class "talks-container"} (dom/div {:class "talks-section-header"} (dom/p label)) (om/build-all talk-view (filter #(= kind (:kind %)) (:talks @state)))))))) (defcomponent graph [{:keys [xy-range fns]} owner] (:mixins set-interval-mixin) (init-state [_] {:idx 0 :step 0.02 :x-start -1 :cx -1 :theta 0 :interval-id nil}) (did-mount [_] (.set-interval owner (fn [] (om/update-state! owner (fn [{:keys [x-start idx step cx] :as o-state}] (-> o-state (update-in [:idx] (if (> cx 1.3) (constantly 0) inc)) (update-in [:cx] (constantly (+ x-start (* idx step)))) (update-in [:theta] (constantly (if (> cx 1.3) 0 (/ (- cx x-start) 2.3)))))))) 40)) (render-state [_ {:keys [cx theta]}] (let [[[xl xu] [yl yu]] xy-range scale 100 test-fn (first fns)] (dom/div {:style {:width "100%" :height "100%"}} (dom/div (dom/span {:class "formula" :style {:color "red"}} "f(") (dom/span {:class "formula" :style {:color "green"}} "x(\\theta)") (dom/span {:class "formula" :style {:color "red"}} ")") (dom/span {:class "formula"} "\\leq") (dom/span {:class "formula" :style {:color "blue"}} "(1 - ") (dom/span {:class "formula" :style {:color "green"}} "\\theta") (dom/span {:class "formula" :style {:color "blue"}} ")\\cdot f(-1) + ") (dom/span {:class "formula" :style {:color "green"}} "\\theta") (dom/span {:class "formula" :style {:color "blue"}} "\\cdot f(1.3)")) (dom/svg {:width "100%" :height "100%" :style {:border "none"} :viewBox (str/join " " (map (partial * scale) [xl yl (- xu xl) (- yu yl)]))} (dom/g {:transform "scale(1, -1)"} (dom/g {:transform "translate(0, -400)"} (let [delta 0.1] (for [x (range xl xu delta)] (dom/line {:x1 (* 100 x) :x2 (* 100 (+ x delta)) :y1 (* 100 (test-fn x)) :y2 (* 100 (test-fn (+ x delta))) :stroke (cond (> x 1.3) "black" (< x -1) "black" :else "red") :stroke-width 3}))) (dom/line {:x1 (* 100 -1) :x2 (* 100 1.3) :y1 (* 100 (test-fn -1)) :y2 (* 100 (test-fn 1.3)) :stroke "blue" :stroke-width "5"}) (dom/line {:x1 (* 100 -1) :x2 (* 100 1.3) :y1 -50 :y2 -50 :stroke "green" :stroke-width "3"}) (dom/circle {:cx (* 100 cx) :cy (* 100 (test-fn cx)) :r "15" :fill "red"}) (dom/circle {:cx (* 100 cx) :cy (* 100 (+ (* (- 1 theta) (test-fn -1)) (* theta (test-fn 1.3)))) :r "15" :fill "blue"}) (dom/circle {:cx (* 100 cx) :cy -50 :r "15" :fill "green"})))))))) (defcomponent knockout-datasync-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "Data Synchronization in Knockout") (dom/p {:style {:margin-top "150px"}} "Conrad")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "Some things reactive frameworks do well...")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "... and some pains of keeping the client and server updated")) (dom/section (dom/div (dom/span "Knockout")) (dom/p "MVVM") (dom/p {:class "fragment"} "Don't think about view-state manipulations that occur when data changes") (dom/p {:class "fragment"} "Continuous updates as the single source of truth") (dom/p {:class "fragment"} "But Knockout and React are really only view layers")) (dom/section (dom/span "What are the implications of this?")) (dom/section (dom/span "... It's a good thing, but it leaves the question of how we keep the client and server in sync pretty open")) (dom/section (dom/div (dom/span "Huge number of ideas about how to address this")) (dom/div {:class "fragment" :style {:margin-top "40px"}} (dom/strong "Lightweight: ") (dom/p "In view-model AJAX") (dom/p "ko.mapping")) (dom/div {:class "fragment" :style {:margin-top "40px"}} (dom/strong "Not so lightweight: ") (dom/p "Falcor (Netflix)") (dom/p "Relay (Facebook)") (dom/p "Seems like a billion others"))) (dom/section (dom/div (dom/span "Can gain nice properties: ")) (dom/p "Maximally decouple view-logic from sync-logic") (dom/p {:class "fragment"} "Optimistic updates become trivial to implement") (dom/p {:class "fragment"} "Impose structure on dependencies in the view model")) (dom/section (dom/div (dom/span "Knockout provides two powerful utilities:")) (dom/p {:class "fragment"} "Binding handlers") (dom/p {:class "fragment"} "Extenders")) (dom/section (dom/span "Wanted to see what it would take to build a sync layer on top of observables...")))))) (defcomponent data-engineering-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "What's Data Engineering? (And what have we been doing?)") (dom/p {:style {:margin-top "150px"}} "<NAME>")) (dom/section (dom/p "As a first thought...") (dom/p {:class "fragment"} "\"Scale\"")) (dom/section (dom/h4 "\"I've been doing a lot with big data recently!\"") (dom/p {:class "fragment"} "(Overhead at the Palo Alto Blue Bottle of a psychology study with " (dom/span {:class "formula"} "n=20000") ")")) (dom/section (dom/p "On the other hand...")) (dom/section (dom/p "Google has on order of {{ mind bogglingly large number }} bytes of data")) (dom/section (dom/p "I'm not going to focus on these because they're relatively uninteresting") (dom/p {:class "fragment"} "Zanbato doesn't have big data (yet?)")) (dom/section (dom/p "There are relatively good tools to deal with data \"at scale\"") (dom/p {:class "fragment"} "(Thanks Google)")) (dom/section (dom/p "That doesn't prevent people from pursuing ridiculous ideas") (dom/a {:href "https://algorithmia.com/"} "https://algorithmia.com/")) (dom/section (dom/span "Critical: Instead of moving data around, ") (dom/span {:class "fragment"} "move code around")) (dom/section (dom/h3 "So what's data engineering?")) (dom/section (dom/p "As a short answer: preparing data for use in some analaysis or product")) (dom/section (dom/p (dom/span {:style {:font-weight 500}} "AKA: ") "Your data science project consumes vectors but you have to feed it pictures, blog post comment threads, paper shipping logs, toxicity records of decomposing leaves found around your Cupertino headquarters sent to you by a third party lab in a proprietary (semi-corrupted) format, turnstile counts from the Library of Congress, and a steady stream of Twitter mentions where people spelled your name slightly wrong")) (dom/section (dom/p "This is just to say that there's a lot of work that goes into preparing data for use in a substantial project")) (dom/section (dom/h4 "Schema Matching") (dom/span {:class "fragment"} "We need to impose stucture onto different sources")) (dom/section (dom/h4 "Entity Recognition") (dom/span {:class "fragment"} "Need to be able to reason about different sources when they're describing the same 'thing'")) (dom/section (dom/h4 "Pipelines") (dom/p {:class "fragment"} "Compositional and simple to understand") (dom/p {:class "fragment"} "De-and-re-constructible approach almost necessary to deal with flexibiity inherent in data science/engineering")) (dom/section (dom/h4 "Data science is exploratory but...") (dom/p {:class "fragment"} "Need to be able to ask questions of data, have a dialog")) (dom/section (dom/h4 "...rate of change is inverse to length of the feedback cycle") (dom/p {:class "fragment"} "Fine when you have a few MB of JSON data, use a REPL") (dom/p {:class "fragment"} "Harder when you're dealing with 100s of GBs of data that's changing and fetched over FTP")) (dom/section (dom/h4 "One of the most important goals of data engineering is to enable fast feedback") (dom/p {:class "fragment"} "Build software to provide a fast and consistent way to access data for heterogenous sources")) (dom/section (dom/p "This stuff's a pain, can a computer do it for me?")) (dom/section (dom/h4 "Some belief that software might be able to do this automatically") (dom/p {:class "fragment"} "Likely what will happen is that tooling will improve in ways that make technical aspects simpler") (dom/p {:class "fragment"} "If you're data is already in a form that a computer can automatically understand it's probably pretty close to 'integrated'")) (dom/section (dom/h4 "Questions?")))))) (defcomponent subgradient-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "Subgradient Iteration + DCP") (dom/p {:style {:margin-top "150px"}} "Conrad")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "...an excuse to talk about convex optimization...")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "...structural features in problem solving.")) (dom/section (dom/span "Convex?") (dom/div {:class "fragment" :style {:width "800px" :height "300px" :margin "auto" :padding-top "50px"}} (->graph {:xy-range [[-2 2] [-1 5]] :fns [(fn [x] (* x x))]}))) (dom/section (dom/div {:class "table-div" :style {:text-align "left" :margin "auto"}} (dom/div (dom/div (dom/span {:class "formula" :style {:padding-right "20px"}} "\\text{minimize:}")) (dom/div (dom/span {:class "formula" :style {:padding-right "20px"}} "\\text{subject to:}"))) (dom/div (dom/div (dom/span {:class "formula"} "f(x)")) (dom/div (dom/div (dom/span {:class "formula"} "x \\in A"))))) (dom/div {:style {:margin-top "80px"}} (dom/span {:class "formula"} "f, A") (dom/span {:style {:padding-left "10px" :font-weight "300"}} " convex (in their respective meanings)"))) (dom/section (dom/span "Why bother with C optimization?") (dom/p {:style {:margin-top "50px"} :class "fragment"} "Convex and spectral optimization can be done globally") (dom/p {:style {:margin-top "50px"} :class "fragment"} "Convex is simpler")) (dom/section (dom/span {:style {:margin-bottom "60px"}} "Why bother with C optimization?") (dom/ul (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Linear programming") (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Least squares") (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Regularizations of many important problems") (dom/li {:style {:margin-top "50px" :font-weight "normal"} :class "fragment"} "Controls (autonomous vehicles, drones, rockets)"))) (dom/section (dom/span "Solving the general problem") (dom/p {:style {:margin-top "50px"}} "Weirdly simple solutions exist") (dom/p {:class "fragment" :style {:margin-top "50px"}} "(even without differentiability)") (dom/p {:class "fragment" :style {:margin-top "50px"}} "(but this one requires something like it)")) (dom/section (dom/span "Subgradient Iteration") (dom/p "Idea is to follow the slope of the function down...") (dom/p "...in a \"generous\" enough interpretation of \"slope\" and \"down\"")) (dom/section (dom/span "Subgradient") (dom/p "Even if a function isn't differentiable, it can be subdifferentiable") (dom/img {:style {:border "none" :box-shadow "none" :width "80%"} :src "/img/subdifferential.png"})) (dom/section (dom/span "Optimizing") (dom/div {:style {:margin-top "80px"}} (dom/span {:class "formula" :style {:font-weight 300}} "x^{(k+1)} = x^{(k)} - \\alpha_k g^{(k)}")) (dom/div (dom/span {:class "formula" :style {:font-weight 300}} "g") (dom/span {:style {:font-weight 300}} " can be any subgradient")) (dom/div {:style {:margin-top "40px" :font-weight 300}} (dom/span "Requires approximately ") (dom/span {:class "formula"} "(\\frac{R G}{\\epsilon})^2") (dom/span " steps"))) (dom/section (dom/span "Optimizing") (dom/div (dom/img {:style {:border "none" :box-shadow "none" :padding-left "10%" :padding-top "70px" :width "80%"} :src "/img/descent.png"})) (dom/p "Not descent!")) (dom/section (dom/span "Symbolic subdifferentiation") (dom/p "How do we find these things?") (let [sexprs '(subdifferential [:abs :x] {:x 0})] (dom/div {:class "fragment"} (dom/pre (dom/code {:class "clojure"} (str sexprs))) (dom/span {:class "formula"} "\\Downarrow") (dom/pre (dom/code {:class "clojure"} "[{:range [-1 1]}]"))))) (dom/section (dom/div (dom/span "Subgradient Rules")) (dom/p "For expressions made up of pieces with computable subgradients, we can use") (dom/ul {:class "fragment" :style {:font-weight 300}} (dom/li "Supremum") (dom/li "Expectation") (dom/li "Chain rule (much like the calculus one)") (dom/li "Duality") (dom/li "+ many others"))) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "Can use similar methods to study the curvature of functions")) (dom/section (dom/img {:style {:border "none" :box-shadow "none" :width "80%"} :src "/img/dcp.png"})) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "CVX and others are compilers for the grammar of convex problems") (dom/p {:class "fragment"} "Their machine ops are high level algorithms,") (dom/p {:class "fragment"} "SOCP solver runs")) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "Targets are drones and embedded systems,") (dom/p {:class "fragment"} "but also distributed systems like Spark + Kafka")))))) (defcomponent subgradient-talk-wrapper [_ _] (render [_] (->subgradient-talk-view {}))) (defcomponent knockout-datasync-talk-wrapper [_ _] (render [_] (->knockout-datasync-talk-view {}))) (defcomponent data-engineering-talk-wrapper [_ _] (render [_] (->data-engineering-talk-view {})))
true
(ns new-website.talks (:require [om.core :as om :include-macros true] [om-tools.dom :as dom :include-macros true] [om-tools.core :refer-macros [defcomponent defcomponentmethod]] [dommy.core :as dommy :refer-macros [sel sel1]] [clojure.string :as str] [ajax.core :refer [GET POST]] [ajax.edn :refer [edn-response-format]] [goog.string :as gstring] [goog.string.format] [new-website.utility :as util] [new-website.mixins :refer [set-interval-mixin reveal-mixin]])) (defmulti talk-view (fn [talk _] (:kind talk))) (defcomponentmethod talk-view :zanbato-tech-talk [talk _] (render [_] (dom/div {:class "talks-wrapper"} (dom/p (dom/strong (str (:presentation-title talk))) (str ", " (:date talk) ". ") (if (= "#" (:presentation-url talk)) (dom/a {:href "#"} "[upcoming]") (dom/a {:href (:presentation-url talk)} "[slides]")))))) (defcomponentmethod talk-view :default [talk _] (render [_] (dom/div {:class "talks-wrapper"} (dom/p (dom/strong (str (:presentation-title talk))) (str " at " (:name talk) ", " (:location talk) ". " (:date talk) ". ") (if (= "#" (:presentation-url talk)) (dom/a {:href "#"} "[upcoming]") (dom/a {:href (:presentation-url talk)} "[slides]")))))) (defcomponent talks-view [state owner] (will-mount [_] (if-not (:talks @state) (GET (util/edn-endpoint "talks") {:headers {"Accept" "application/edn"} :response-format (edn-response-format) :handler (fn [resp] (om/transact! state :talks (constantly resp)))}))) (render [_] (dom/div (for [[kind label] [[:zanbato-tech-talk "Tech talks at Zanbato"] [:invited "Invited talks"] [:other "Other talks"]]] (dom/div {:class "talks-container"} (dom/div {:class "talks-section-header"} (dom/p label)) (om/build-all talk-view (filter #(= kind (:kind %)) (:talks @state)))))))) (defcomponent graph [{:keys [xy-range fns]} owner] (:mixins set-interval-mixin) (init-state [_] {:idx 0 :step 0.02 :x-start -1 :cx -1 :theta 0 :interval-id nil}) (did-mount [_] (.set-interval owner (fn [] (om/update-state! owner (fn [{:keys [x-start idx step cx] :as o-state}] (-> o-state (update-in [:idx] (if (> cx 1.3) (constantly 0) inc)) (update-in [:cx] (constantly (+ x-start (* idx step)))) (update-in [:theta] (constantly (if (> cx 1.3) 0 (/ (- cx x-start) 2.3)))))))) 40)) (render-state [_ {:keys [cx theta]}] (let [[[xl xu] [yl yu]] xy-range scale 100 test-fn (first fns)] (dom/div {:style {:width "100%" :height "100%"}} (dom/div (dom/span {:class "formula" :style {:color "red"}} "f(") (dom/span {:class "formula" :style {:color "green"}} "x(\\theta)") (dom/span {:class "formula" :style {:color "red"}} ")") (dom/span {:class "formula"} "\\leq") (dom/span {:class "formula" :style {:color "blue"}} "(1 - ") (dom/span {:class "formula" :style {:color "green"}} "\\theta") (dom/span {:class "formula" :style {:color "blue"}} ")\\cdot f(-1) + ") (dom/span {:class "formula" :style {:color "green"}} "\\theta") (dom/span {:class "formula" :style {:color "blue"}} "\\cdot f(1.3)")) (dom/svg {:width "100%" :height "100%" :style {:border "none"} :viewBox (str/join " " (map (partial * scale) [xl yl (- xu xl) (- yu yl)]))} (dom/g {:transform "scale(1, -1)"} (dom/g {:transform "translate(0, -400)"} (let [delta 0.1] (for [x (range xl xu delta)] (dom/line {:x1 (* 100 x) :x2 (* 100 (+ x delta)) :y1 (* 100 (test-fn x)) :y2 (* 100 (test-fn (+ x delta))) :stroke (cond (> x 1.3) "black" (< x -1) "black" :else "red") :stroke-width 3}))) (dom/line {:x1 (* 100 -1) :x2 (* 100 1.3) :y1 (* 100 (test-fn -1)) :y2 (* 100 (test-fn 1.3)) :stroke "blue" :stroke-width "5"}) (dom/line {:x1 (* 100 -1) :x2 (* 100 1.3) :y1 -50 :y2 -50 :stroke "green" :stroke-width "3"}) (dom/circle {:cx (* 100 cx) :cy (* 100 (test-fn cx)) :r "15" :fill "red"}) (dom/circle {:cx (* 100 cx) :cy (* 100 (+ (* (- 1 theta) (test-fn -1)) (* theta (test-fn 1.3)))) :r "15" :fill "blue"}) (dom/circle {:cx (* 100 cx) :cy -50 :r "15" :fill "green"})))))))) (defcomponent knockout-datasync-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "Data Synchronization in Knockout") (dom/p {:style {:margin-top "150px"}} "Conrad")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "Some things reactive frameworks do well...")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "... and some pains of keeping the client and server updated")) (dom/section (dom/div (dom/span "Knockout")) (dom/p "MVVM") (dom/p {:class "fragment"} "Don't think about view-state manipulations that occur when data changes") (dom/p {:class "fragment"} "Continuous updates as the single source of truth") (dom/p {:class "fragment"} "But Knockout and React are really only view layers")) (dom/section (dom/span "What are the implications of this?")) (dom/section (dom/span "... It's a good thing, but it leaves the question of how we keep the client and server in sync pretty open")) (dom/section (dom/div (dom/span "Huge number of ideas about how to address this")) (dom/div {:class "fragment" :style {:margin-top "40px"}} (dom/strong "Lightweight: ") (dom/p "In view-model AJAX") (dom/p "ko.mapping")) (dom/div {:class "fragment" :style {:margin-top "40px"}} (dom/strong "Not so lightweight: ") (dom/p "Falcor (Netflix)") (dom/p "Relay (Facebook)") (dom/p "Seems like a billion others"))) (dom/section (dom/div (dom/span "Can gain nice properties: ")) (dom/p "Maximally decouple view-logic from sync-logic") (dom/p {:class "fragment"} "Optimistic updates become trivial to implement") (dom/p {:class "fragment"} "Impose structure on dependencies in the view model")) (dom/section (dom/div (dom/span "Knockout provides two powerful utilities:")) (dom/p {:class "fragment"} "Binding handlers") (dom/p {:class "fragment"} "Extenders")) (dom/section (dom/span "Wanted to see what it would take to build a sync layer on top of observables...")))))) (defcomponent data-engineering-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "What's Data Engineering? (And what have we been doing?)") (dom/p {:style {:margin-top "150px"}} "PI:NAME:<NAME>END_PI")) (dom/section (dom/p "As a first thought...") (dom/p {:class "fragment"} "\"Scale\"")) (dom/section (dom/h4 "\"I've been doing a lot with big data recently!\"") (dom/p {:class "fragment"} "(Overhead at the Palo Alto Blue Bottle of a psychology study with " (dom/span {:class "formula"} "n=20000") ")")) (dom/section (dom/p "On the other hand...")) (dom/section (dom/p "Google has on order of {{ mind bogglingly large number }} bytes of data")) (dom/section (dom/p "I'm not going to focus on these because they're relatively uninteresting") (dom/p {:class "fragment"} "Zanbato doesn't have big data (yet?)")) (dom/section (dom/p "There are relatively good tools to deal with data \"at scale\"") (dom/p {:class "fragment"} "(Thanks Google)")) (dom/section (dom/p "That doesn't prevent people from pursuing ridiculous ideas") (dom/a {:href "https://algorithmia.com/"} "https://algorithmia.com/")) (dom/section (dom/span "Critical: Instead of moving data around, ") (dom/span {:class "fragment"} "move code around")) (dom/section (dom/h3 "So what's data engineering?")) (dom/section (dom/p "As a short answer: preparing data for use in some analaysis or product")) (dom/section (dom/p (dom/span {:style {:font-weight 500}} "AKA: ") "Your data science project consumes vectors but you have to feed it pictures, blog post comment threads, paper shipping logs, toxicity records of decomposing leaves found around your Cupertino headquarters sent to you by a third party lab in a proprietary (semi-corrupted) format, turnstile counts from the Library of Congress, and a steady stream of Twitter mentions where people spelled your name slightly wrong")) (dom/section (dom/p "This is just to say that there's a lot of work that goes into preparing data for use in a substantial project")) (dom/section (dom/h4 "Schema Matching") (dom/span {:class "fragment"} "We need to impose stucture onto different sources")) (dom/section (dom/h4 "Entity Recognition") (dom/span {:class "fragment"} "Need to be able to reason about different sources when they're describing the same 'thing'")) (dom/section (dom/h4 "Pipelines") (dom/p {:class "fragment"} "Compositional and simple to understand") (dom/p {:class "fragment"} "De-and-re-constructible approach almost necessary to deal with flexibiity inherent in data science/engineering")) (dom/section (dom/h4 "Data science is exploratory but...") (dom/p {:class "fragment"} "Need to be able to ask questions of data, have a dialog")) (dom/section (dom/h4 "...rate of change is inverse to length of the feedback cycle") (dom/p {:class "fragment"} "Fine when you have a few MB of JSON data, use a REPL") (dom/p {:class "fragment"} "Harder when you're dealing with 100s of GBs of data that's changing and fetched over FTP")) (dom/section (dom/h4 "One of the most important goals of data engineering is to enable fast feedback") (dom/p {:class "fragment"} "Build software to provide a fast and consistent way to access data for heterogenous sources")) (dom/section (dom/p "This stuff's a pain, can a computer do it for me?")) (dom/section (dom/h4 "Some belief that software might be able to do this automatically") (dom/p {:class "fragment"} "Likely what will happen is that tooling will improve in ways that make technical aspects simpler") (dom/p {:class "fragment"} "If you're data is already in a form that a computer can automatically understand it's probably pretty close to 'integrated'")) (dom/section (dom/h4 "Questions?")))))) (defcomponent subgradient-talk-view [_ _] (:mixins reveal-mixin) (render [_] (dom/div {:class "reveal"} (dom/div {:class "slides"} (dom/section (dom/h3 "Subgradient Iteration + DCP") (dom/p {:style {:margin-top "150px"}} "Conrad")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "...an excuse to talk about convex optimization...")) (dom/section (dom/span {:style {:margin-bottom "40px"}} "...structural features in problem solving.")) (dom/section (dom/span "Convex?") (dom/div {:class "fragment" :style {:width "800px" :height "300px" :margin "auto" :padding-top "50px"}} (->graph {:xy-range [[-2 2] [-1 5]] :fns [(fn [x] (* x x))]}))) (dom/section (dom/div {:class "table-div" :style {:text-align "left" :margin "auto"}} (dom/div (dom/div (dom/span {:class "formula" :style {:padding-right "20px"}} "\\text{minimize:}")) (dom/div (dom/span {:class "formula" :style {:padding-right "20px"}} "\\text{subject to:}"))) (dom/div (dom/div (dom/span {:class "formula"} "f(x)")) (dom/div (dom/div (dom/span {:class "formula"} "x \\in A"))))) (dom/div {:style {:margin-top "80px"}} (dom/span {:class "formula"} "f, A") (dom/span {:style {:padding-left "10px" :font-weight "300"}} " convex (in their respective meanings)"))) (dom/section (dom/span "Why bother with C optimization?") (dom/p {:style {:margin-top "50px"} :class "fragment"} "Convex and spectral optimization can be done globally") (dom/p {:style {:margin-top "50px"} :class "fragment"} "Convex is simpler")) (dom/section (dom/span {:style {:margin-bottom "60px"}} "Why bother with C optimization?") (dom/ul (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Linear programming") (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Least squares") (dom/li {:style {:margin-top "50px" :font-weight "300"} :class "fragment"} "Regularizations of many important problems") (dom/li {:style {:margin-top "50px" :font-weight "normal"} :class "fragment"} "Controls (autonomous vehicles, drones, rockets)"))) (dom/section (dom/span "Solving the general problem") (dom/p {:style {:margin-top "50px"}} "Weirdly simple solutions exist") (dom/p {:class "fragment" :style {:margin-top "50px"}} "(even without differentiability)") (dom/p {:class "fragment" :style {:margin-top "50px"}} "(but this one requires something like it)")) (dom/section (dom/span "Subgradient Iteration") (dom/p "Idea is to follow the slope of the function down...") (dom/p "...in a \"generous\" enough interpretation of \"slope\" and \"down\"")) (dom/section (dom/span "Subgradient") (dom/p "Even if a function isn't differentiable, it can be subdifferentiable") (dom/img {:style {:border "none" :box-shadow "none" :width "80%"} :src "/img/subdifferential.png"})) (dom/section (dom/span "Optimizing") (dom/div {:style {:margin-top "80px"}} (dom/span {:class "formula" :style {:font-weight 300}} "x^{(k+1)} = x^{(k)} - \\alpha_k g^{(k)}")) (dom/div (dom/span {:class "formula" :style {:font-weight 300}} "g") (dom/span {:style {:font-weight 300}} " can be any subgradient")) (dom/div {:style {:margin-top "40px" :font-weight 300}} (dom/span "Requires approximately ") (dom/span {:class "formula"} "(\\frac{R G}{\\epsilon})^2") (dom/span " steps"))) (dom/section (dom/span "Optimizing") (dom/div (dom/img {:style {:border "none" :box-shadow "none" :padding-left "10%" :padding-top "70px" :width "80%"} :src "/img/descent.png"})) (dom/p "Not descent!")) (dom/section (dom/span "Symbolic subdifferentiation") (dom/p "How do we find these things?") (let [sexprs '(subdifferential [:abs :x] {:x 0})] (dom/div {:class "fragment"} (dom/pre (dom/code {:class "clojure"} (str sexprs))) (dom/span {:class "formula"} "\\Downarrow") (dom/pre (dom/code {:class "clojure"} "[{:range [-1 1]}]"))))) (dom/section (dom/div (dom/span "Subgradient Rules")) (dom/p "For expressions made up of pieces with computable subgradients, we can use") (dom/ul {:class "fragment" :style {:font-weight 300}} (dom/li "Supremum") (dom/li "Expectation") (dom/li "Chain rule (much like the calculus one)") (dom/li "Duality") (dom/li "+ many others"))) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "Can use similar methods to study the curvature of functions")) (dom/section (dom/img {:style {:border "none" :box-shadow "none" :width "80%"} :src "/img/dcp.png"})) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "CVX and others are compilers for the grammar of convex problems") (dom/p {:class "fragment"} "Their machine ops are high level algorithms,") (dom/p {:class "fragment"} "SOCP solver runs")) (dom/section (dom/div (dom/span "Disciplined Convex Programming")) (dom/p "Targets are drones and embedded systems,") (dom/p {:class "fragment"} "but also distributed systems like Spark + Kafka")))))) (defcomponent subgradient-talk-wrapper [_ _] (render [_] (->subgradient-talk-view {}))) (defcomponent knockout-datasync-talk-wrapper [_ _] (render [_] (->knockout-datasync-talk-view {}))) (defcomponent data-engineering-talk-wrapper [_ _] (render [_] (->data-engineering-talk-view {})))
[ { "context": "ed auto\n }\n ethernet eth1 {\n address 192.168.1.1/24\n description Local\n duplex auto\n", "end": 1525, "score": 0.9996820092201233, "start": 1514, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": " authoritative enable\n subnet 192.168.1.0/24 {\n /* 192.168.1.1-192.168.1.4 ", "end": 1872, "score": 0.999681830406189, "start": 1861, "tag": "IP_ADDRESS", "value": "192.168.1.0" }, { "context": " subnet 192.168.1.0/24 {\n /* 192.168.1.1-192.168.1.4 used by router, controller, dns *", "end": 1908, "score": 0.999598503112793, "start": 1897, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": "t 192.168.1.0/24 {\n /* 192.168.1.1-192.168.1.4 used by router, controller, dns */\n ", "end": 1912, "score": 0.9785131216049194, "start": 1909, "tag": "IP_ADDRESS", "value": "192" }, { "context": "2.168.1.0/24 {\n /* 192.168.1.1-192.168.1.4 used by router, controller, dns */\n ", "end": 1920, "score": 0.9630306959152222, "start": 1913, "tag": "IP_ADDRESS", "value": "168.1.4" }, { "context": " by router, controller, dns */\n /* 192.168.1.5-192.168.1.37 used by metallb */\n ", "end": 1990, "score": 0.999593198299408, "start": 1979, "tag": "IP_ADDRESS", "value": "192.168.1.5" }, { "context": "controller, dns */\n /* 192.168.1.5-192.168.1.37 used by metallb */\n /* 192.168.", "end": 2003, "score": 0.9957170486450195, "start": 1991, "tag": "IP_ADDRESS", "value": "192.168.1.37" }, { "context": "168.1.37 used by metallb */\n /* 192.168.1.245 used by clash */\n de", "end": 2058, "score": 0.9997106194496155, "start": 2045, "tag": "IP_ADDRESS", "value": "192.168.1.245" }, { "context": " used by clash */\n default-router 192.168.1.1\n dns-server 192.168.1.1\n ", "end": 2132, "score": 0.9997238516807556, "start": 2121, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": "ult-router 192.168.1.1\n dns-server 192.168.1.1\n lease 86400\n start", "end": 2171, "score": 0.9997055530548096, "start": 2160, "tag": "IP_ADDRESS", "value": "192.168.1.1" }, { "context": " lease 86400\n start 192.168.1.38 {\n stop 192.168.1.243\n ", "end": 2234, "score": 0.9997337460517883, "start": 2222, "tag": "IP_ADDRESS", "value": "192.168.1.38" }, { "context": " start 192.168.1.38 {\n stop 192.168.1.243\n }\n }\n }\n ", "end": 2275, "score": 0.9997409582138062, "start": 2262, "tag": "IP_ADDRESS", "value": "192.168.1.243" }, { "context": " listen-on eth1\n name-server 1.1.1.1\n name-server 1.0.0.1\n optio", "end": 2494, "score": 0.999724268913269, "start": 2487, "tag": "IP_ADDRESS", "value": "1.1.1.1" }, { "context": " name-server 1.1.1.1\n name-server 1.0.0.1\n options server=/local.d20.fan/192.168", "end": 2526, "score": 0.9997149705886841, "start": 2519, "tag": "IP_ADDRESS", "value": "1.0.0.1" }, { "context": "1.0.0.1\n options server=/local.d20.fan/192.168.1.3\n\n /* PlayStation5 */\n optio", "end": 2580, "score": 0.8888902068138123, "start": 2569, "tag": "IP_ADDRESS", "value": "192.168.1.3" }, { "context": " /* PlayStation5 */\n options dhcp-host=00:e4:21:e8:79:0c,set:LAN1,set:Proxy\n /* Asrock B360M Pr", "end": 2660, "score": 0.995065450668335, "start": 2643, "tag": "IP_ADDRESS", "value": "00:e4:21:e8:79:0c" }, { "context": "srock B360M Pro4 */\n options dhcp-host=70:85:c2:cb:22:7b,set:LAN1,set:Proxy\n options dhcp-optio", "end": 2763, "score": 0.9779138565063477, "start": 2746, "tag": "IP_ADDRESS", "value": "70:85:c2:cb:22:7b" }, { "context": " options dhcp-option=tag:Proxy,option:router,192.168.1.245\n options dhcp-option=tag:Proxy,option:", "end": 2852, "score": 0.9997326731681824, "start": 2839, "tag": "IP_ADDRESS", "value": "192.168.1.245" }, { "context": " options dhcp-option=tag:Proxy,option:dns-server,192.168.1.245\n }\n }\n gui {\n http-port 80\n ", "end": 2926, "score": 0.9997183680534363, "start": 2913, "tag": "IP_ADDRESS", "value": "192.168.1.245" }, { "context": "\n }\n host-name ubnt\n login {\n user ubnt {\n authentication {\n en", "end": 3445, "score": 0.9891514182090759, "start": 3441, "tag": "USERNAME", "value": "ubnt" }, { "context": "uthentication {\n encrypted-password $5$e0a1UbX/3smy/MwE$TmornS/dFXgNmFaP/jIG1BTLjbJ2ULiUXmTkwysqdOD\n plaintext-password \"\"\n ", "end": 3575, "score": 0.9871569871902466, "start": 3512, "tag": "PASSWORD", "value": "$5$e0a1UbX/3smy/MwE$TmornS/dFXgNmFaP/jIG1BTLjbJ2ULiUXmTkwysqdOD" } ]
configs/edgerouter/config.boot
fancl20/homeserver-configs
0
firewall { all-ping enable broadcast-ping disable ipv6-receive-redirects disable ipv6-src-route disable ip-src-route disable log-martians enable name WAN_IN { default-action drop description "WAN to internal" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } } name WAN_LOCAL { default-action drop description "WAN to router" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } } receive-redirects disable send-redirects enable source-validation disable syn-cookies enable } interfaces { ethernet eth0 { address dhcp description Internet duplex auto firewall { in { name WAN_IN } local { name WAN_LOCAL } } speed auto } ethernet eth1 { address 192.168.1.1/24 description Local duplex auto speed auto } ethernet eth2 { duplex auto speed auto } loopback lo { } } service { dhcp-server { disabled false hostfile-update disable shared-network-name LAN1 { authoritative enable subnet 192.168.1.0/24 { /* 192.168.1.1-192.168.1.4 used by router, controller, dns */ /* 192.168.1.5-192.168.1.37 used by metallb */ /* 192.168.1.245 used by clash */ default-router 192.168.1.1 dns-server 192.168.1.1 lease 86400 start 192.168.1.38 { stop 192.168.1.243 } } } static-arp disable use-dnsmasq enable } dns { forwarding { cache-size 150 listen-on eth1 name-server 1.1.1.1 name-server 1.0.0.1 options server=/local.d20.fan/192.168.1.3 /* PlayStation5 */ options dhcp-host=00:e4:21:e8:79:0c,set:LAN1,set:Proxy /* Asrock B360M Pro4 */ options dhcp-host=70:85:c2:cb:22:7b,set:LAN1,set:Proxy options dhcp-option=tag:Proxy,option:router,192.168.1.245 options dhcp-option=tag:Proxy,option:dns-server,192.168.1.245 } } gui { http-port 80 https-port 443 older-ciphers enable } nat { rule 5010 { description "masquerade for WAN" outbound-interface eth0 type masquerade } } ssh { port 22 protocol-version v2 } unms { } } system { analytics-handler { send-analytics-report true } crash-handler { send-crash-report true } host-name ubnt login { user ubnt { authentication { encrypted-password $5$e0a1UbX/3smy/MwE$TmornS/dFXgNmFaP/jIG1BTLjbJ2ULiUXmTkwysqdOD plaintext-password "" } full-name "" level admin } } ntp { server 0.ubnt.pool.ntp.org { } server 1.ubnt.pool.ntp.org { } server 2.ubnt.pool.ntp.org { } server 3.ubnt.pool.ntp.org { } } syslog { global { facility all { level notice } facility protocols { level debug } } } time-zone UTC } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "config-management@1:conntrack@1:cron@1:dhcp-relay@1:dhcp-server@4:firewall@5:ipsec@5:nat@3:qos@1:quagga@2:suspend@1:system@5:ubnt-l2tp@1:ubnt-pptp@1:ubnt-udapi-server@1:ubnt-unms@2:ubnt-util@1:vrrp@1:vyatta-netflow@1:webgui@1:webproxy@1:zone-policy@1" === */ /* Release version: v2.0.9-hotfix.2.5402463.210511.1317 */
99481
firewall { all-ping enable broadcast-ping disable ipv6-receive-redirects disable ipv6-src-route disable ip-src-route disable log-martians enable name WAN_IN { default-action drop description "WAN to internal" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } } name WAN_LOCAL { default-action drop description "WAN to router" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } } receive-redirects disable send-redirects enable source-validation disable syn-cookies enable } interfaces { ethernet eth0 { address dhcp description Internet duplex auto firewall { in { name WAN_IN } local { name WAN_LOCAL } } speed auto } ethernet eth1 { address 192.168.1.1/24 description Local duplex auto speed auto } ethernet eth2 { duplex auto speed auto } loopback lo { } } service { dhcp-server { disabled false hostfile-update disable shared-network-name LAN1 { authoritative enable subnet 192.168.1.0/24 { /* 192.168.1.1-192.168.1.4 used by router, controller, dns */ /* 192.168.1.5-192.168.1.37 used by metallb */ /* 192.168.1.245 used by clash */ default-router 192.168.1.1 dns-server 192.168.1.1 lease 86400 start 192.168.1.38 { stop 192.168.1.243 } } } static-arp disable use-dnsmasq enable } dns { forwarding { cache-size 150 listen-on eth1 name-server 1.1.1.1 name-server 1.0.0.1 options server=/local.d20.fan/192.168.1.3 /* PlayStation5 */ options dhcp-host=00:e4:21:e8:79:0c,set:LAN1,set:Proxy /* Asrock B360M Pro4 */ options dhcp-host=70:85:c2:cb:22:7b,set:LAN1,set:Proxy options dhcp-option=tag:Proxy,option:router,192.168.1.245 options dhcp-option=tag:Proxy,option:dns-server,192.168.1.245 } } gui { http-port 80 https-port 443 older-ciphers enable } nat { rule 5010 { description "masquerade for WAN" outbound-interface eth0 type masquerade } } ssh { port 22 protocol-version v2 } unms { } } system { analytics-handler { send-analytics-report true } crash-handler { send-crash-report true } host-name ubnt login { user ubnt { authentication { encrypted-password <PASSWORD> plaintext-password "" } full-name "" level admin } } ntp { server 0.ubnt.pool.ntp.org { } server 1.ubnt.pool.ntp.org { } server 2.ubnt.pool.ntp.org { } server 3.ubnt.pool.ntp.org { } } syslog { global { facility all { level notice } facility protocols { level debug } } } time-zone UTC } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "config-management@1:conntrack@1:cron@1:dhcp-relay@1:dhcp-server@4:firewall@5:ipsec@5:nat@3:qos@1:quagga@2:suspend@1:system@5:ubnt-l2tp@1:ubnt-pptp@1:ubnt-udapi-server@1:ubnt-unms@2:ubnt-util@1:vrrp@1:vyatta-netflow@1:webgui@1:webproxy@1:zone-policy@1" === */ /* Release version: v2.0.9-hotfix.2.5402463.210511.1317 */
true
firewall { all-ping enable broadcast-ping disable ipv6-receive-redirects disable ipv6-src-route disable ip-src-route disable log-martians enable name WAN_IN { default-action drop description "WAN to internal" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } } name WAN_LOCAL { default-action drop description "WAN to router" rule 10 { action accept description "Allow established/related" state { established enable related enable } } rule 20 { action drop description "Drop invalid state" state { invalid enable } } } receive-redirects disable send-redirects enable source-validation disable syn-cookies enable } interfaces { ethernet eth0 { address dhcp description Internet duplex auto firewall { in { name WAN_IN } local { name WAN_LOCAL } } speed auto } ethernet eth1 { address 192.168.1.1/24 description Local duplex auto speed auto } ethernet eth2 { duplex auto speed auto } loopback lo { } } service { dhcp-server { disabled false hostfile-update disable shared-network-name LAN1 { authoritative enable subnet 192.168.1.0/24 { /* 192.168.1.1-192.168.1.4 used by router, controller, dns */ /* 192.168.1.5-192.168.1.37 used by metallb */ /* 192.168.1.245 used by clash */ default-router 192.168.1.1 dns-server 192.168.1.1 lease 86400 start 192.168.1.38 { stop 192.168.1.243 } } } static-arp disable use-dnsmasq enable } dns { forwarding { cache-size 150 listen-on eth1 name-server 1.1.1.1 name-server 1.0.0.1 options server=/local.d20.fan/192.168.1.3 /* PlayStation5 */ options dhcp-host=00:e4:21:e8:79:0c,set:LAN1,set:Proxy /* Asrock B360M Pro4 */ options dhcp-host=70:85:c2:cb:22:7b,set:LAN1,set:Proxy options dhcp-option=tag:Proxy,option:router,192.168.1.245 options dhcp-option=tag:Proxy,option:dns-server,192.168.1.245 } } gui { http-port 80 https-port 443 older-ciphers enable } nat { rule 5010 { description "masquerade for WAN" outbound-interface eth0 type masquerade } } ssh { port 22 protocol-version v2 } unms { } } system { analytics-handler { send-analytics-report true } crash-handler { send-crash-report true } host-name ubnt login { user ubnt { authentication { encrypted-password PI:PASSWORD:<PASSWORD>END_PI plaintext-password "" } full-name "" level admin } } ntp { server 0.ubnt.pool.ntp.org { } server 1.ubnt.pool.ntp.org { } server 2.ubnt.pool.ntp.org { } server 3.ubnt.pool.ntp.org { } } syslog { global { facility all { level notice } facility protocols { level debug } } } time-zone UTC } /* Warning: Do not remove the following line. */ /* === vyatta-config-version: "config-management@1:conntrack@1:cron@1:dhcp-relay@1:dhcp-server@4:firewall@5:ipsec@5:nat@3:qos@1:quagga@2:suspend@1:system@5:ubnt-l2tp@1:ubnt-pptp@1:ubnt-udapi-server@1:ubnt-unms@2:ubnt-util@1:vrrp@1:vyatta-netflow@1:webgui@1:webproxy@1:zone-policy@1" === */ /* Release version: v2.0.9-hotfix.2.5402463.210511.1317 */
[ { "context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9995479583740234, "start": 21, "tag": "NAME", "value": "Peter Monks" } ]
src/lice_comb/deps.clj
pmonks/lice-comb
3
; ; 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 lice-comb.deps "deps (in tools.deps lib-map format) related functionality." (:require [clojure.string :as s] [clojure.reflect :as cr] [clojure.edn :as edn] [lice-comb.spdx :as spdx] [lice-comb.maven :as mvn] [lice-comb.files :as f] [lice-comb.data :as d] [lice-comb.utils :as u])) (def ^:private overrides-uri (d/uri-for-data "/deps/overrides.edn")) (def ^:private overrides (try (edn/read-string (slurp overrides-uri)) (catch Exception e (throw (ex-info (str "Unexpected " (cr/typename (type e)) " while reading " overrides-uri ". Please check your internet connection and try again.") {} e))))) (def ^:private fallbacks-uri (d/uri-for-data "/deps/fallbacks.edn")) (def ^:private fallbacks (try (edn/read-string (slurp fallbacks-uri)) (catch Exception e (throw (ex-info (str "Unexpected " (cr/typename (type e)) " while reading " fallbacks-uri ". Please check your internet connection and try again.") {} e))))) (defn- check-overrides "Checks if an override should be used for the given dep" ([ga] (check-overrides ga nil)) ([ga v] (let [gav (symbol (str ga (when v (str "@" v))))] (:licenses (get overrides gav (get overrides ga)))))) ; Lookup overrides both with and without the version (defn- check-fallbacks "Checks if a fallback should be used for the given dep, given the set of detected ids" [ga ids] (if (or (empty? ids) (every? #(not (spdx/spdx-id? %)) ids)) (:licenses (get fallbacks ga {:licenses ids})) ids)) (defmulti dep->ids "Attempt to detect the license(s) in a tools.deps style dep (a MapEntry or two-element sequence of [groupId/artifactId dep-info])." {:arglists '([[ga info]])} (fn [[_ info]] (:deps/manifest info))) (defmethod dep->ids :mvn [dep] (when dep (let [[ga info] dep [group-id artifact-id] (s/split (str ga) #"/") version (:mvn/version info)] (if-let [override (check-overrides ga version)] override (let [pom-uri (mvn/pom-uri-for-gav group-id artifact-id version) license-ids (check-fallbacks ga (if-let [license-ids (mvn/pom->ids pom-uri)] license-ids (u/nset (mapcat f/zip->ids (:paths info)))))] ; If we didn't find any licenses in the dep's POM, check the dep's JAR(s) too license-ids))))) (defmethod dep->ids :deps [dep] (when dep (let [[ga info] dep version (:git/sha info)] (if-let [override (check-overrides ga version)] override (check-fallbacks ga (f/dir->ids (:deps/root info))))))) (defmethod dep->ids nil [_]) (defmethod dep->ids :default [dep] (throw (ex-info (str "Unexpected manifest type '" (:deps/manifest (second dep)) "' for dependency " dep) {:dep dep}))) (defn deps-licenses "Attempt to detect the license(s) in a tools.deps 'lib map', returning a new lib map with the licenses assoc'ed in (in key :lice-comb/licenses)" [deps] (when deps (into {} (pmap #(let [[k v] %] [k (assoc v :lice-comb/licenses (dep->ids [k v]))]) deps))))
19827
; ; 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 lice-comb.deps "deps (in tools.deps lib-map format) related functionality." (:require [clojure.string :as s] [clojure.reflect :as cr] [clojure.edn :as edn] [lice-comb.spdx :as spdx] [lice-comb.maven :as mvn] [lice-comb.files :as f] [lice-comb.data :as d] [lice-comb.utils :as u])) (def ^:private overrides-uri (d/uri-for-data "/deps/overrides.edn")) (def ^:private overrides (try (edn/read-string (slurp overrides-uri)) (catch Exception e (throw (ex-info (str "Unexpected " (cr/typename (type e)) " while reading " overrides-uri ". Please check your internet connection and try again.") {} e))))) (def ^:private fallbacks-uri (d/uri-for-data "/deps/fallbacks.edn")) (def ^:private fallbacks (try (edn/read-string (slurp fallbacks-uri)) (catch Exception e (throw (ex-info (str "Unexpected " (cr/typename (type e)) " while reading " fallbacks-uri ". Please check your internet connection and try again.") {} e))))) (defn- check-overrides "Checks if an override should be used for the given dep" ([ga] (check-overrides ga nil)) ([ga v] (let [gav (symbol (str ga (when v (str "@" v))))] (:licenses (get overrides gav (get overrides ga)))))) ; Lookup overrides both with and without the version (defn- check-fallbacks "Checks if a fallback should be used for the given dep, given the set of detected ids" [ga ids] (if (or (empty? ids) (every? #(not (spdx/spdx-id? %)) ids)) (:licenses (get fallbacks ga {:licenses ids})) ids)) (defmulti dep->ids "Attempt to detect the license(s) in a tools.deps style dep (a MapEntry or two-element sequence of [groupId/artifactId dep-info])." {:arglists '([[ga info]])} (fn [[_ info]] (:deps/manifest info))) (defmethod dep->ids :mvn [dep] (when dep (let [[ga info] dep [group-id artifact-id] (s/split (str ga) #"/") version (:mvn/version info)] (if-let [override (check-overrides ga version)] override (let [pom-uri (mvn/pom-uri-for-gav group-id artifact-id version) license-ids (check-fallbacks ga (if-let [license-ids (mvn/pom->ids pom-uri)] license-ids (u/nset (mapcat f/zip->ids (:paths info)))))] ; If we didn't find any licenses in the dep's POM, check the dep's JAR(s) too license-ids))))) (defmethod dep->ids :deps [dep] (when dep (let [[ga info] dep version (:git/sha info)] (if-let [override (check-overrides ga version)] override (check-fallbacks ga (f/dir->ids (:deps/root info))))))) (defmethod dep->ids nil [_]) (defmethod dep->ids :default [dep] (throw (ex-info (str "Unexpected manifest type '" (:deps/manifest (second dep)) "' for dependency " dep) {:dep dep}))) (defn deps-licenses "Attempt to detect the license(s) in a tools.deps 'lib map', returning a new lib map with the licenses assoc'ed in (in key :lice-comb/licenses)" [deps] (when deps (into {} (pmap #(let [[k v] %] [k (assoc v :lice-comb/licenses (dep->ids [k v]))]) deps))))
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 lice-comb.deps "deps (in tools.deps lib-map format) related functionality." (:require [clojure.string :as s] [clojure.reflect :as cr] [clojure.edn :as edn] [lice-comb.spdx :as spdx] [lice-comb.maven :as mvn] [lice-comb.files :as f] [lice-comb.data :as d] [lice-comb.utils :as u])) (def ^:private overrides-uri (d/uri-for-data "/deps/overrides.edn")) (def ^:private overrides (try (edn/read-string (slurp overrides-uri)) (catch Exception e (throw (ex-info (str "Unexpected " (cr/typename (type e)) " while reading " overrides-uri ". Please check your internet connection and try again.") {} e))))) (def ^:private fallbacks-uri (d/uri-for-data "/deps/fallbacks.edn")) (def ^:private fallbacks (try (edn/read-string (slurp fallbacks-uri)) (catch Exception e (throw (ex-info (str "Unexpected " (cr/typename (type e)) " while reading " fallbacks-uri ". Please check your internet connection and try again.") {} e))))) (defn- check-overrides "Checks if an override should be used for the given dep" ([ga] (check-overrides ga nil)) ([ga v] (let [gav (symbol (str ga (when v (str "@" v))))] (:licenses (get overrides gav (get overrides ga)))))) ; Lookup overrides both with and without the version (defn- check-fallbacks "Checks if a fallback should be used for the given dep, given the set of detected ids" [ga ids] (if (or (empty? ids) (every? #(not (spdx/spdx-id? %)) ids)) (:licenses (get fallbacks ga {:licenses ids})) ids)) (defmulti dep->ids "Attempt to detect the license(s) in a tools.deps style dep (a MapEntry or two-element sequence of [groupId/artifactId dep-info])." {:arglists '([[ga info]])} (fn [[_ info]] (:deps/manifest info))) (defmethod dep->ids :mvn [dep] (when dep (let [[ga info] dep [group-id artifact-id] (s/split (str ga) #"/") version (:mvn/version info)] (if-let [override (check-overrides ga version)] override (let [pom-uri (mvn/pom-uri-for-gav group-id artifact-id version) license-ids (check-fallbacks ga (if-let [license-ids (mvn/pom->ids pom-uri)] license-ids (u/nset (mapcat f/zip->ids (:paths info)))))] ; If we didn't find any licenses in the dep's POM, check the dep's JAR(s) too license-ids))))) (defmethod dep->ids :deps [dep] (when dep (let [[ga info] dep version (:git/sha info)] (if-let [override (check-overrides ga version)] override (check-fallbacks ga (f/dir->ids (:deps/root info))))))) (defmethod dep->ids nil [_]) (defmethod dep->ids :default [dep] (throw (ex-info (str "Unexpected manifest type '" (:deps/manifest (second dep)) "' for dependency " dep) {:dep dep}))) (defn deps-licenses "Attempt to detect the license(s) in a tools.deps 'lib map', returning a new lib map with the licenses assoc'ed in (in key :lice-comb/licenses)" [deps] (when deps (into {} (pmap #(let [[k v] %] [k (assoc v :lice-comb/licenses (dep->ids [k v]))]) deps))))
[ { "context": "aiter-url service-id-1)))\n (let [token (str \"^SERVICE-ID#\" service-id-1)\n response (make-request-with-debug-", "end": 48131, "score": 0.6569136381149292, "start": 48104, "tag": "KEY", "value": "\"^SERVICE-ID#\" service-id-1" }, { "context": "085631ee3d7af9\"\n :token \"token-with-bad-namespace\"\n :cmd \"not-used\"\n ", "end": 50802, "score": 0.8595600128173828, "start": 50778, "tag": "PASSWORD", "value": "token-with-bad-namespace" }, { "context": "ter-url \"/pathabc\" :headers {\"X-Waiter-Token\" \"bad#token\"})]\n (is (str/includes? (:body response) \"", "end": 53277, "score": 0.5807579159736633, "start": 53271, "tag": "PASSWORD", "value": "#token" }, { "context": "085631ee3d7af9\"\n :token \"bad#token\"\n :cmd \"not-used\"\n ", "end": 54875, "score": 0.9532982707023621, "start": 54866, "tag": "PASSWORD", "value": "bad#token" }, { "context": "md-type\" \"shell\"\n \"token\" (rand-name)\n \"cmd\" \"exit 0\"\n ", "end": 56486, "score": 0.5222879648208618, "start": 56482, "tag": "USERNAME", "value": "rand" }, { "context": "ype\" \"shell\"\n \"token\" (rand-name)\n \"cmd\" \"exit 0\"\n ", "end": 56491, "score": 0.5696139335632324, "start": 56487, "tag": "KEY", "value": "name" }, { "context": "bles\n (testing-using-waiter-url\n (let [token (rand-name)\n binary (kitchen-cmd)\n to", "end": 57319, "score": 0.48805516958236694, "start": 57315, "tag": "USERNAME", "value": "rand" }, { "context": "\n (testing-using-waiter-url\n (let [token (rand-name)\n binary (kitchen-cmd)\n token-r", "end": 57324, "score": 0.6418402194976807, "start": 57320, "tag": "KEY", "value": "name" }, { "context": "ects\n (testing-using-waiter-url\n (let [token (rand-name)\n token-response (post-token waiter-url ", "end": 58467, "score": 0.5319654941558838, "start": 58458, "tag": "KEY", "value": "rand-name" }, { "context": "port\n (testing-using-waiter-url\n (let [token (rand-name)\n binary (kitchen-cmd)\n service", "end": 60634, "score": 0.6676461100578308, "start": 60625, "tag": "KEY", "value": "rand-name" } ]
waiter/integration/waiter/token_request_test.clj
twosigmajab/waiter
0
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.token-request-test (:require [clj-time.core :as t] [clojure.data.json :as json] [clojure.string :as str] [clojure.test :refer :all] [clojure.tools.logging :as log] [clojure.walk :as walk] [plumbing.core :as pc] [waiter.headers :as headers] [waiter.service-description :as sd] [waiter.util.client-tools :refer :all] [waiter.util.date-utils :as du] [waiter.util.utils :as utils] [waiter.token :as token]) (:import (java.net URL) (org.joda.time DateTime))) (defn- waiter-url->token-url [waiter-url] (str HTTP-SCHEME waiter-url "/token")) (defn- retrieve-token-root [waiter-url] (-> (waiter-settings waiter-url) (get-in [:cluster-config :name]))) (defn- retrieve-token-cluster [waiter-url] (let [settings-json (waiter-settings waiter-url) default-cluster (get-in settings-json [:cluster-config :name]) cluster-calculator-config (-> settings-json (get-in [:token-config :cluster-calculator]) (update :kind keyword) (as-> $ (update-in $ [(:kind $) :factory-fn] symbol))) cluster-calculator (utils/create-component cluster-calculator-config :context {:default-cluster default-cluster})] (token/calculate-cluster cluster-calculator {:headers {"host" waiter-url}}))) (deftest ^:parallel ^:integration-fast test-update-token-cache-consistency (testing-using-waiter-url (let [service-id-prefix (rand-name "testhostname") token (rand-name) update-token-fn (fn [version] (let [{:keys [status]} (post-token waiter-url {:name service-id-prefix :cpus 1 :mem 1250 :version version :cmd "test command" :health-check-url "/ping" :permitted-user "*" :run-as-user (retrieve-username) :token token})] (is (= 200 status)))) validate-token-fn (fn [version num-threads num-iter] (parallelize-requests num-threads num-iter (fn [] (let [{:keys [body status]} (get-token waiter-url token)] (is (= 200 status)) (is (every? #(str/includes? (str body) (str %)) [service-id-prefix "1250" version "test command"])) (is (not-any? #(str/includes? (str body) (str %)) ["invalid"])))))) update-and-validate-token-fn (fn [version] (log/info "creating configuration using token" token "with version" version) (update-token-fn version) (log/info "asserting configuration for token" token "from routers (best-effort)") (validate-token-fn version 10 10)) version1 "123987132937213712" version2 "656760465406467480" version3 "678219671796032121"] (try (update-and-validate-token-fn version1) (update-and-validate-token-fn version2) (update-and-validate-token-fn version3) (finally (delete-token-and-assert waiter-url token)))))) (defn- name-from-service-description [waiter-url service-id] (get-in (service-settings waiter-url service-id) [:service-description :name])) (defn- service-id->source-tokens-entries [waiter-url service-id] (some-> (service-settings waiter-url service-id) :source-tokens walk/stringify-keys set)) (defn- token->etag [waiter-url token] (-> (get-token waiter-url token :query-params {"token" token}) :headers (get "etag"))) (defn- make-source-tokens-entries [waiter-url & tokens] (mapv (fn [token] {"token" token "version" (token->etag waiter-url token)}) tokens)) (defn- create-token-name [waiter-url service-id-prefix] (str service-id-prefix "." (subs waiter-url 0 (str/index-of waiter-url ":")))) (defn- list-tokens [waiter-url owner cookies query-params] (let [tokens-response (make-request waiter-url "/tokens" :cookies cookies :query-params query-params)] (log/debug "retrieved tokens for owner " owner ":" (:body tokens-response)) tokens-response)) (defn- parse-token-description "Parses a response as json and keywordizes the map." [response-body] (try (-> response-body str json/read-str pc/keywordize-map) (catch Exception _ (is false (str "Failed to parse token " response-body))))) (defmacro assert-token-response "Asserts the token data in the response" ([response token-root token-cluster service-id-prefix deleted] `(assert-token-response ~response ~token-root ~token-cluster ~service-id-prefix ~deleted true)) ([response token-root token-cluster service-id-prefix deleted include-metadata] `(let [body# (:body ~response) token-description# (parse-token-description body#)] (assert-response-status ~response 200) (when ~include-metadata (is (contains? token-description# :cluster)) (is (contains? token-description# :last-update-time)) (is (contains? token-description# :last-update-user)) (is (contains? token-description# :owner)) (is (contains? token-description# :root))) (is (= (cond-> {:health-check-url "/probe" :name ~service-id-prefix :owner (retrieve-username)} ~include-metadata (assoc :cluster ~token-cluster :last-update-user (retrieve-username) :root ~token-root) (and ~deleted ~include-metadata) (assoc :deleted ~deleted)) (dissoc token-description# :last-update-time :previous)))))) (deftest ^:parallel ^:integration-fast test-token-create-delete (testing-using-waiter-url (let [service-id-prefix (rand-name) token-prefix (create-token-name waiter-url service-id-prefix) {:keys [cookies]} (make-request waiter-url "/waiter-auth") num-tokens-to-create 10 tokens-to-create (map #(str "token" %1 "." token-prefix) (range num-tokens-to-create)) current-user (System/getProperty "user.name") token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (log/info "creating token without parameters should fail") (let [token (str service-id-prefix ".empty") {:keys [body] :as response} (post-token waiter-url {:token token})] (assert-response-status response 400) (is (str/includes? (str body) (str "No parameters provided for " token)) (str body))) (log/info "creating the tokens") (doseq [token tokens-to-create] (let [response (post-token waiter-url {:health-check-url "/check" :name service-id-prefix :token token})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully created " token))))) (testing "update without etags" (doseq [token tokens-to-create] (let [response (post-token waiter-url {:health-check-url "/health" :name service-id-prefix :token token})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully updated " token)))))) (testing "update with etags" (doseq [token tokens-to-create] (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (select-keys [:name]) (assoc :health-check-url "/probe" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully updated " token)))))) (testing "update without changes" (doseq [token tokens-to-create] (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str (select-keys sd/token-user-editable-keys) walk/keywordize-keys (assoc :token token)) current-etag (get headers "etag") response (post-token waiter-url token-description :headers {"if-match" current-etag})] (assert-response-status response 200) (is (str/includes? (:body response) (str "No changes detected for " token))) (is (= current-etag (get-in response [:headers "etag"])))))) (testing "token retrieval - presence of etag header" (doseq [token tokens-to-create] (testing "via query parameters" (let [{:keys [headers] :as response} (get-token waiter-url token :cookies cookies :query-params {"include" "metadata" "token" token} :request-headers {}) actual-etag (get headers "etag")] (assert-response-status response 200) (let [token-description (-> response :body json/read-str)] (is (= {"health-check-url" "/check", "name" service-id-prefix} (-> token-description (get-in (repeat 2 "previous")) (select-keys sd/service-parameter-keys)))) (is (= {"health-check-url" "/health", "name" service-id-prefix} (-> token-description (get-in (repeat 1 "previous")) (select-keys sd/service-parameter-keys))))) (is actual-etag))) (testing "via x-waiter-token header" (let [{:keys [body headers] :as response} (get-token waiter-url token :cookies cookies) actual-etag (get headers "etag")] (assert-response-status response 200) (is actual-etag) (when actual-etag (let [convert-last-update-time (fn [{:strs [last-update-time] :as service-description}] (cond-> service-description last-update-time (assoc "last-update-time" (-> last-update-time du/str-to-date .getMillis)))) expected-etag (str "E-" (-> body json/read-str convert-last-update-time (dissoc "previous") sd/parameters->id))] (is (= expected-etag actual-etag)))))))) (log/info "ensuring tokens can be retrieved and listed on each router") (doseq [token tokens-to-create] (doseq [[_ router-url] (routers waiter-url)] (-> (get-token router-url token :cookies cookies :query-params {"include" "none"}) (assert-token-response token-root token-cluster service-id-prefix false false)) (-> (get-token router-url token :cookies cookies :query-params {"include" "metadata"}) (assert-token-response token-root token-cluster service-id-prefix false true)) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (some (fn [token-entry] (= token (get token-entry "token"))) tokens))))) (log/info "soft-deleting the tokens") (doseq [token tokens-to-create] (delete-token-and-assert waiter-url token :hard-delete false)) (log/info "ensuring tokens can no longer be retrieved on each router without include=deleted parameter") (doseq [token tokens-to-create] (doseq [[router-id router-url] (routers waiter-url)] (let [router-state (kv-store-state router-url :cookies cookies) cache-data (get-in router-state ["state" "cache" "data"]) token-cache-data (get cache-data (keyword token))] (is (nil? token-cache-data) (str token " data not nil (" token-cache-data ") on " router-id ", cache data =" cache-data))) (let [{:keys [body] :as response} (get-token router-url token :cookies cookies)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body))) (-> (get-token router-url token :cookies cookies :query-params {"include" ["deleted" "metadata"]}) (assert-token-response token-root token-cluster service-id-prefix true)) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (not-any? (fn [token-entry] (= token (get token-entry "token"))) tokens))) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (some (fn [token-entry] (= token (get token-entry "token"))) tokens))))) (log/info "hard-deleting the tokens") (doseq [token tokens-to-create] (delete-token-and-assert waiter-url token) (doseq [[_ router-url] (routers waiter-url)] (let [{:keys [body] :as response} (get-token router-url token :cookies cookies)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str {:body body :token token}))) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) token-entries (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) token-entries)) (is (every? (fn [token-entry] (contains? token-entry "etag")) token-entries)))) ;; the token must be removed from at least one router (others may have temporarily cached values) (is (some (fn [router-url] (let [{:keys [body]} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) token-entries (json/read-str body)] (not-any? (fn [token-entry] (= token (get token-entry "token"))) token-entries))) (vals (routers waiter-url))) (str token " entry found in list of deleted tokens on all routers"))) (log/info "ensuring tokens can no longer be retrieved on each router with include=deleted parameter after hard-delete") (doseq [token tokens-to-create] (doseq [[_ router-url] (routers waiter-url)] (let [{:keys [body] :as response} (get-token router-url token :cookies cookies :query-params {"include" "deleted"})] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body)))))))) (deftest ^:parallel ^:integration-fast ^:resource-heavy test-service-list-filtering (testing-using-waiter-url (let [service-name (rand-name) token-1 (create-token-name waiter-url (str "www." service-name ".t1")) token-2 (create-token-name waiter-url (str "www." service-name ".t2")) service-ids-atom (atom #{}) token->version->etag-atom (atom {}) all-tokens [token-1 token-2] all-version-suffixes ["v1" "v2" "v3"] router-id->router-url (routers waiter-url) {:keys [cookies]} (make-request waiter-url "/waiter-auth")] (doseq [version-suffix all-version-suffixes] (doseq [token all-tokens] (let [token-description (merge (kitchen-request-headers :prefix "") {:fallback-period-secs 0 :name (str service-name "." (hash token)) :token token :version (str service-name "." version-suffix)}) {:keys [headers] :as response} (post-token waiter-url token-description)] (assert-response-status response 200) (let [token-etag (get headers "etag")] (log/info token "->" token-etag) (is (-> token-etag str/blank? not)) (let [{:keys [service-id] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "/environment" :headers %))] (assert-response-status response 200) (is (-> service-id str/blank? not)) (swap! service-ids-atom conj service-id) ;; ensure all routers know about the service (doseq [[_ router-url] router-id->router-url] (let [response (make-request-with-debug-info {:x-waiter-token token} #(make-request router-url "/environment" :headers % :cookies cookies))] (assert-response-status response 200) (is (= service-id (:service-id response)))))) (swap! token->version->etag-atom assoc-in [token version-suffix] token-etag))))) (is (= (* (count all-tokens) (count all-version-suffixes)) (count @service-ids-atom)) (str {:service-ids @service-ids-atom})) (testing "star in token filter" (doseq [[_ router-url] (routers waiter-url)] (let [query-params {"token" (str "www." service-name ".t*")} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-tokens (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :token))) services)] (assert-response-status response 200) (is (= (count @service-ids-atom) (count service-tokens)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-tokens service-tokens}))))) (doseq [loop-token all-tokens] (doseq [[_ router-url] (routers waiter-url)] (let [query-params {"token" loop-token} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-tokens (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :token))) services)] (assert-response-status response 200) (is (= 3 (count service-tokens)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-tokens service-tokens})))) (doseq [version-suffix all-version-suffixes] (doseq [[_ router-url] (routers waiter-url)] (let [loop-etag (get-in @token->version->etag-atom [loop-token version-suffix]) query-params {"token-version" loop-etag} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-token-versions (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :version))) services)] (assert-response-status response 200) (is (= 1 (count service-token-versions)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-token-versions service-token-versions})))))) (doseq [service-id @service-ids-atom] (delete-service waiter-url service-id))))) (defn- service-id->metadata-id [waiter-url service-id] (get-in (service-settings waiter-url service-id) [:service-description :metadata :id])) (deftest ^:parallel ^:integration-fast test-hostname-token (testing-using-waiter-url (let [service-id-prefix (rand-name) token-prefix (str "token-" (rand-int 3000000)) token (create-token-name waiter-url token-prefix) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (testing "hostname-token-test" (try (log/info "basic hostname as token test") (let [current-user (retrieve-username) service-description (assoc (kitchen-request-headers) :x-waiter-metric-group "waiter_test" :x-waiter-name token-prefix :x-waiter-permitted-user "*" :x-waiter-run-as-user current-user)] (testing "hostname-token-creation" (log/info "creating configuration using token" token) (let [{:keys [body status]} (post-token waiter-url {:health-check-url "/probe" :metric-group "waiter_test" :metadata {"id" token-prefix} :name service-id-prefix :token token})] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (let [token-response (get-token waiter-url token) response-body (json/read-str (:body token-response))] (is (contains? response-body "last-update-time")) (is (= {"cluster" token-cluster "health-check-url" "/probe" "last-update-user" (retrieve-username) "metadata" {"id" token-prefix} "metric-group" "waiter_test" "name" service-id-prefix "owner" (retrieve-username) "previous" {} "root" token-root} (dissoc response-body "last-update-time")))) (log/info "asserted retrieval of configuration for token" token)) (testing "support-for-token-with-x-waiter-headers" (log/info "request with hostname token" token "along with x-waiter headers") (let [request-headers (merge service-description {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id)))) (log/info "request with hostname token" token "along with x-waiter headers except permitted-user") (let [request-headers (merge (dissoc service-description :x-waiter-permitted-user) {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id))) ;; the above request hashes to a different service-id than the rest of the test, so we need to cleanup (delete-service waiter-url service-id)) (log/info "request with hostname token" token "along with x-waiter headers except run-as-user") (let [request-headers (merge (dissoc service-description :x-waiter-run-as-user) {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id))) (testing "backend request headers" (let [{:keys [body] :as response} (make-request waiter-url "/request-info" :headers request-headers) {:strs [headers]} (json/read-str (str body))] (assert-response-status response 200) (is (contains? headers "x-waiter-auth-principal")) (is (contains? headers "x-waiter-authenticated-principal")))) ;; the above request hashes to a different service-id only when running as someone other than current-user ;; when the service-id is different, we need to cleanup (when (not= (System/getProperty "user.name") current-user) (delete-service waiter-url service-id))) (log/info "request with hostname token" token "along with missing x-waiter headers except cmd") (let [request-headers (merge (dissoc service-description :x-waiter-cmd) {"host" token}) path "/foo" {:keys [body] :as response} (make-request waiter-url path :headers request-headers)] (is (some #(str/includes? body %) ["cmd must be a non-empty string" "Invalid command or version"]) (str "response body was: " response)) (assert-response-status response 400)) (log/info "request with hostname token and x-waiter-debug token" token "along with x-waiter headers") (let [request-headers (merge service-description {:x-waiter-debug "true", "host" token}) path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (delete-service waiter-url service-id)))) (finally (delete-token-and-assert waiter-url token))))))) (deftest ^:parallel ^:integration-fast test-token-administer-unaffected-by-run-as-user-permissions (testing-using-waiter-url (let [service-id-prefix (rand-name) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (testing "token-administering" (testing "active-token" (let [last-update-time (System/currentTimeMillis) token (create-token-name waiter-url service-id-prefix)] (let [token-description {:health-check-url "/probe" :name service-id-prefix :owner (retrieve-username) :run-as-user (retrieve-username) :token token} response (post-token waiter-url token-description)] (assert-response-status response 200)) (testing "if-match-required during update" (let [token-description {:health-check-url "/probe-1" :last-update-time last-update-time :name service-id-prefix :owner (retrieve-username) :token token} {:keys [body] :as response} (post-token waiter-url token-description :headers {} :query-params {"update-mode" "admin"})] (assert-response-status response 400) (is (str/includes? body "Must specify if-match header for admin mode token updates")))) (try (testing "successful admin mode update" (log/info "creating configuration using token" token) (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (assoc :health-check-url "/probe-2" :last-update-time last-update-time :owner (retrieve-username) :run-as-user "i-do-not-exist-but-will-not-be-checked" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")} :query-params {"update-mode" "admin"})] (assert-response-status response 200) (log/info "created configuration using token" token)) (let [token-response (get-token waiter-url token) response-body (json/read-str (:body token-response))] (is (= {"cluster" token-cluster "health-check-url" "/probe-2" "last-update-time" (-> last-update-time DateTime. du/date-to-str) "last-update-user" (retrieve-username) "name" service-id-prefix, "owner" (retrieve-username) "root" token-root "run-as-user" "i-do-not-exist-but-will-not-be-checked"} (dissoc response-body "previous"))) (log/info "asserted retrieval of configuration for token" token))) (testing "update with invalid etag" (let [token-description {:health-check-url "/probe-3" :last-update-time last-update-time :name service-id-prefix :owner (retrieve-username) :run-as-user "foo-bar" :token token} {:keys [body] :as response} (post-token waiter-url token-description :headers {"host" token "if-match" "1010"} :query-params {"update-mode" "admin"})] (assert-response-status response 412) (is (str/includes? (str body) "Cannot modify stale token")))) (testing "hard-delete without etag" (let [{:keys [body] :as response} (make-request waiter-url "/token" :headers {"host" token} :method :delete :query-params {"hard-delete" true})] (assert-response-status response 400) (is (str/includes? (str body) "Must specify if-match header for token hard deletes")))) (testing "hard-delete with invalid etag" (let [{:keys [body] :as response} (make-request waiter-url "/token" :headers {"host" token "if-match" "1010"} :method :delete :query-params {"hard-delete" true})] (assert-response-status response 412) (is (str/includes? (str body) "Cannot modify stale token")))) (finally (delete-token-and-assert waiter-url token))))) (testing "deleted-token" (let [last-update-time (System/currentTimeMillis) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-description {:health-check-url "/probe-3" :name service-id-prefix :owner (retrieve-username) :token token} response (post-token waiter-url token-description :headers {"host" token})] (assert-response-status response 200)) (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (assoc :deleted true :health-check-url "/probe" :last-update-time last-update-time :run-as-user "foo-bar" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")} :query-params {"update-mode" "admin"})] (assert-response-status response 200)) (log/info "created configuration using token" token) (let [{:keys [body] :as response} (get-token waiter-url token)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body))) (let [token-response (get-token waiter-url token :query-params {"include" ["deleted" "metadata"]}) response-body (json/read-str (:body token-response))] (is (= {"cluster" token-cluster "deleted" true "health-check-url" "/probe" "last-update-time" (-> last-update-time DateTime. du/date-to-str) "last-update-user" (retrieve-username) "name" service-id-prefix "owner" (retrieve-username) "root" token-root "run-as-user" "foo-bar"} (dissoc response-body "previous")))) (log/info "asserted retrieval of configuration for token" token) (finally (delete-token-and-assert waiter-url token))))))))) (deftest ^:parallel ^:integration-fast test-named-token (testing-using-waiter-url (log/info "basic named token test") (let [service-id-prefix (rand-name) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix))) (log/info "asserted retrieval of configuration for token" token) (log/info "making Waiter request with token" token "in header") (let [request-headers {:x-waiter-token token} path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id)))) (log/info "making Waiter request with token and x-waiter-debug token" token "in header") (let [request-headers {:x-waiter-debug "true", :x-waiter-token token} path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (delete-service waiter-url service-id)) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-star-run-as-user-token (testing-using-waiter-url (let [service-id-prefix (rand-name) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :run-as-user "*" :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix))) (log/info "asserted retrieval of configuration for token" token) (let [{:keys [body] :as token-response} (get-token waiter-url token) token-description (try (json/read-str (str body)) (catch Exception _ (is false (str "Failed to parse token" body))))] (assert-response-status token-response 200) (is (= "/status" (token-description "health-check-url"))) (is (= service-id-prefix (token-description "name"))) (is (= "*" (token-description "run-as-user"))) (is (System/getProperty "user.name") (token-description "owner"))) (log/info "making Waiter request with token" token "in header") (let [request-headers {:x-waiter-token token} path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= (retrieve-username) (:run-as-user (service-id->service-description waiter-url service-id))))) (log/info "making Waiter request with token and x-waiter-debug token" token "in header") (let [request-headers {:x-waiter-debug "true", :x-waiter-token token} path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (delete-service waiter-url service-id)) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast ^:explicit test-on-the-fly-to-token (testing-using-waiter-url (let [name-string (rand-name) {:keys [cookies] :as canary-response} (make-request-with-debug-info {:x-waiter-name name-string} #(make-kitchen-request waiter-url %)) service-id-1 (:service-id canary-response)] (with-service-cleanup service-id-1 (is (str/includes? service-id-1 name-string) (str "ERROR: App-name is missing " name-string)) (assert-service-on-all-routers waiter-url service-id-1 cookies) (is (nil? (service-id->source-tokens-entries waiter-url service-id-1))) (let [token (str "^SERVICE-ID#" service-id-1) response (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "" :headers %)) service-id-2 (:service-id response)] (with-service-cleanup service-id-2 (assert-response-status response 200) (is service-id-2) (is (= service-id-1 service-id-2) "The on-the-fly and token-based service ids do not match") (assert-service-on-all-routers waiter-url service-id-1 cookies) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id-2))))))))) (deftest ^:parallel ^:integration-fast test-namespace-token (testing-using-waiter-url (log/info "basic token with namespace field test") (let [service-id-prefix (rand-name) target-user (retrieve-username) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :namespace target-user :run-as-user target-user :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix)) (let [{:strs [namespace run-as-user] :as token-json} (try-parse-json response-body)] (is (= target-user run-as-user)) (is (= target-user namespace)))) (log/info "asserted retrieval of configuration for token" token) (finally (delete-token-and-assert waiter-url token)))) (testing "can't create token with bad namespace" (let [service-desc {:name (rand-name "notused") :cpus 1 :debug true :mem 1024 :version "universe b10452d0b0380ce61764543847085631ee3d7af9" :token "token-with-bad-namespace" :cmd "not-used" :permitted-user "*" :namespace "not-run-as-user" :run-as-user (retrieve-username) :health-check-url "/not-used"} response (post-token waiter-url service-desc)] (is (str/includes? (:body response) "Service namespace must either be omitted or match the run-as-user")) (assert-response-status response 400))))) (deftest ^:parallel ^:integration-fast test-bad-token (testing-using-waiter-url (let [common-headers {"x-waiter-cmd" "foo-bar" "x-waiter-cmd-type" "shell"}] (testing "ignore missing token when have service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "missing_token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400))) (testing "ignore invalid token when have service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "bad/token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400))) (testing "ignore invalid token when have invalid service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "bad/token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400)))) (testing "can't use missing token server" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token"})] (is (str/includes? (:body response) "Unable to identify service using waiter headers/token")) (assert-response-status response 400))) (testing "can't use invalid token server" (let [response (make-request waiter-url "/pathabc" :headers {"host" "bad/token"})] (is (str/includes? (:body response) "Unable to identify service using waiter headers/token")) (assert-response-status response 400))) (testing "can't use invalid token that's valid for zookeeper" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "bad#token"})] (is (str/includes? (:body response) "Token not found: bad#token")) (assert-response-status response 400))) (testing "can't use invalid token" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "bad/token"})] (is (str/includes? (:body response) "Token not found: bad/token")) (assert-response-status response 400))) (testing "can't use invalid token with host set" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token" "X-Waiter-Token" "bad/token"})] (is (str/includes? (:body response) "Token not found: bad/token")) (assert-response-status response 400))) (testing "can't use missing token with host set" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token" "X-Waiter-Token" "missing_token"})] (is (str/includes? (:body response) "Token not found: missing_token")) (assert-response-status response 400))) (testing "can't use missing token" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "missing_token"})] (is (str/includes? (:body response) "Token not found: missing_token")) (assert-response-status response 400))) (testing "can't create bad token" (let [service-desc {:name (rand-name "notused") :cpus 1 :debug true :mem 1024 :version "universe b10452d0b0380ce61764543847085631ee3d7af9" :token "bad#token" :cmd "not-used" :permitted-user "*" :run-as-user (retrieve-username) :health-check-url "/not-used"} response (post-token waiter-url service-desc)] (is (str/includes? (:body response) "Token must match pattern")) (assert-response-status response 400))))) (deftest ^:parallel ^:integration-fast test-token-metadata (testing-using-waiter-url (let [token (rand-name) service-desc {:name token :cpus 1 :mem 100 :version "1" :cmd-type "shell" :token token :cmd "exit 0" :run-as-user (retrieve-username) :health-check-url "/not-used" :metadata {"a" "b", "c" "d"}} register-response (post-token waiter-url service-desc) {:keys [body]} (get-token waiter-url token)] (assert-response-status register-response 200) (is (= (:metadata service-desc) (get (json/read-str body) "metadata"))) (delete-token-and-assert waiter-url token) (delete-service waiter-url (:name service-desc))))) (deftest ^:parallel ^:integration-fast test-token-bad-metadata (testing-using-waiter-url (let [service-desc {"name" "token-bad-metadata" "cpus" 1 "mem" 100 "version" "1" "cmd-type" "shell" "token" (rand-name) "cmd" "exit 0" "run-as-user" (retrieve-username) "health-check-url" "/not-used" "metadata" {"a" "b", "c" {"d" "e"}}} register-response (post-token waiter-url service-desc)] (is (= 400 (:status register-response)))))) (deftest ^:parallel ^:integration-fast test-token-bad-payload (testing-using-waiter-url (let [{:keys [status]} (make-request waiter-url "/token" :body "i'm bad at json" :headers {"host" "test-token"} :method :post)] (is (= 400 status))))) (deftest ^:parallel ^:integration-fast test-token-environment-variables (testing-using-waiter-url (let [token (rand-name) binary (kitchen-cmd) token-response (post-token waiter-url {:cmd "$BINARY -p $PORT0" :cmd-type "shell" :version "does-not-matter" :name token :env {"BINARY" binary} :token token}) {:keys [service-id status] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-light-request waiter-url %)) {:keys [env] :as service-description} (response->service-description waiter-url response)] (is (= 200 (:status token-response)) (:body token-response)) (is (= 200 status)) (is (= {:BINARY binary} env) (str service-description)) (delete-token-and-assert waiter-url token) (delete-service waiter-url service-id)))) (deftest ^:parallel ^:integration-fast test-token-https-redirects (testing-using-waiter-url (let [token (rand-name) token-response (post-token waiter-url {:cmd (str (kitchen-cmd) " -p $PORT0") :cmd-type "shell" :https-redirect true :name token :version "does-not-matter" :token token})] (assert-response-status token-response 200) (testing "https redirects" (let [request-headers {:x-waiter-token token} url (URL. (str "http://" waiter-url)) endpoint "/request-info"] (testing "get request" (let [{:keys [headers] :as response} (make-kitchen-request waiter-url request-headers :method :get :path endpoint)] (assert-response-status response 301) (is (= (str "https://" (.getHost url) endpoint) (get headers "location"))) (is (str/starts-with? (str (get headers "server")) "waiter") (str "headers:" headers)))) (testing "post request" (let [{:keys [headers] :as response} (make-kitchen-request waiter-url request-headers :method :post :path endpoint)] (assert-response-status response 307) (is (= (str "https://" (.getHost url) endpoint) (get headers "location"))) (is (str/starts-with? (str (get headers "server")) "waiter") (str "headers:" headers)))))) (delete-token-and-assert waiter-url token)))) (defmacro run-token-param-support [waiter-url request-fn request-headers expected-env] `(let [response# (make-request-with-debug-info ~request-headers ~request-fn) service-description# (response->service-description ~waiter-url response#) service-id# (:service-id response#)] (is (= 200 (:status response#))) (is (= ~expected-env (:env service-description#)) (str service-description#)) (delete-service ~waiter-url service-id#) service-id#)) (deftest ^:parallel ^:integration-fast test-token-param-support (testing-using-waiter-url (let [token (rand-name) binary (kitchen-cmd) service-description {:allowed-params ["FAA" "FEE" "FII" "FOO" "FUU"] :cmd "$BINARY -p $PORT0" :cmd-type "shell" :env {"BINARY" binary "FEE" "FIE" "FOO" "BAR"} :name "test-token-param-support" :version "does-not-matter"} kitchen-request #(make-kitchen-request waiter-url % :path "/environment")] (try (let [token-description (assoc service-description :token token) token-response (post-token waiter-url token-description :query-params {"update-mode" "admin"})] (assert-response-status token-response 200) (let [request-headers {:x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured"))) (let [request-headers {:x-waiter-allowed-params "" :x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured")))) (let [token-description (-> service-description (dissoc :allowed-params) (assoc :token (str token ".1"))) token-response (post-token waiter-url token-description :query-params {"update-mode" "admin"})] (assert-response-status token-response 200) (let [request-headers {:x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured")))) (let [service-ids (set [(run-token-param-support waiter-url kitchen-request {:x-waiter-token token} {:BINARY binary :FEE "FIE" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-allowed-params ["FEE" "FII" "FOO"] :x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-allowed-params "FEE,FOO" :x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-param-fee "value-1p" :x-waiter-param-foo "value-2p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "value-2p"})])] (is (= 5 (count service-ids)) "Unique service-ids were not created!")) (finally (delete-token-and-assert waiter-url token) (delete-token-and-assert waiter-url (str token ".1"))))))) (deftest ^:parallel ^:integration-fast test-token-invalid-environment-variables (testing-using-waiter-url (let [{:keys [body status]} (post-token waiter-url {:env {"HOME" "/my/home"} :token (rand-name)})] (is (= 400 status)) (is (not (str/includes? body "clojure")) body) (is (str/includes? body "The following environment variable keys are reserved: HOME.") body)))) (deftest ^:parallel ^:integration-fast test-token-parameters-exceed-limits (testing-using-waiter-url (let [constraints (setting waiter-url [:service-description-constraints]) max-constraints (sd/extract-max-constraints constraints)] (is (seq max-constraints)) (doseq [[parameter max-constraint] max-constraints] (let [string-param? (contains? headers/params-with-str-value (name parameter)) param-value (if string-param? (apply str parameter " " (repeat max-constraint "x")) (inc max-constraint)) {:keys [body status]} (post-token waiter-url {parameter param-value :token (rand-name)})] (is (= 400 status)) (is (not (str/includes? body "clojure")) body) (is (every? #(str/includes? body %) ["The following fields exceed their allowed limits" (if string-param? (str (name parameter) " must be at most " max-constraint " characters") (str (name parameter) " is " param-value " but the max allowed is " max-constraint))]) body)))))) (deftest ^:parallel ^:integration-fast test-auto-run-as-requester-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) service-description (-> (kitchen-request-headers :prefix "") (assoc :name service-name :permitted-user "*") (dissoc :run-as-user)) waiter-port (.getPort (URL. (str "http://" waiter-url))) waiter-port (if (neg? waiter-port) 80 waiter-port) host-header (str token ":" waiter-port) has-x-waiter-consent? (partial some #(= (:name %) "x-waiter-consent")) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (try (testing "token creation" (let [token-description (assoc service-description :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "token retrieval" (let [token-response (get-token waiter-url token) response-body (-> token-response (:body) (json/read-str) (pc/keywordize-map))] (is (nil? (get response-body :run-as-user))) (is (contains? response-body :last-update-time)) (is (= (assoc service-description :cluster token-cluster :last-update-user (retrieve-username) :owner (retrieve-username) :previous {} :root token-root) (dissoc response-body :last-update-time))))) (testing "expecting redirect" (let [{:keys [headers] :as response} (make-request waiter-url "/hello-world" :headers {"host" host-header})] (is (= (str "/waiter-consent/hello-world") (get headers "location"))) (assert-response-status response 303))) (testing "waiter-consent" (let [consent-path (str "/waiter-consent/hello-world") {:keys [body] :as response} (make-request waiter-url consent-path :headers {"host" host-header}) service-id (when-let [service-id-index (str/index-of body "name=\"service-id\"")] (when-let [value-index (str/index-of body "value=\"" service-id-index)] (when-let [end-index (str/index-of body "\"" (+ value-index 7))] (subs body (+ value-index 7) end-index))))] (is service-id) (assert-response-status response 200) (let [cookies-atom (atom nil)] (testing "approval of specific service" (let [{:keys [body cookies] :as response} (make-request waiter-url "/waiter-consent" :headers {"host" host-header "referer" (str "http://" host-header) "origin" (str "http://" host-header) "x-requested-with" "XMLHttpRequest"} :method :post :multipart {"mode" "service" "service-id" service-id})] (reset! cookies-atom cookies) (is (= "Added cookie x-waiter-consent" body)) ; x-waiter-consent should be emitted Waiter (is (has-x-waiter-consent? cookies)) (assert-response-status response 200))) (testing "auto run-as-user population on expected service-id" (let [service-id-atom (atom nil)] (try (let [expected-service-id service-id {:keys [body cookies service-id] :as response} (make-request-with-debug-info {"host" host-header} #(make-request waiter-url "/hello-world" :cookies @cookies-atom :headers %1)) {:keys [service-description]} (service-settings waiter-url service-id) {:keys [run-as-user permitted-user]} service-description] (reset! service-id-atom service-id) (is (= "Hello World" body)) ; x-waiter-consent should not be re-emitted Waiter (is (not (has-x-waiter-consent? cookies))) (is (= expected-service-id service-id)) (is (not (str/blank? permitted-user))) (is (= run-as-user permitted-user)) (assert-response-status response 200)) (finally (when @service-id-atom (delete-service waiter-url @service-id-atom)))))) (testing "token update" (let [updated-service-name (rand-name) token-description (assoc service-description :name updated-service-name :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "expecting redirect after token update" (let [{:keys [headers] :as response} (make-request waiter-url "/hello-world" :cookies @cookies-atom :headers {"host" host-header})] (is (= (str "/waiter-consent/hello-world") (get headers "location"))) (assert-response-status response 303))) (testing "approval of token" (let [{:keys [body cookies] :as response} (make-request waiter-url "/waiter-consent" :cookies @cookies-atom :headers {"host" host-header "referer" (str "http://" host-header) "origin" (str "http://" host-header) "x-requested-with" "XMLHttpRequest"} :method :post :multipart {"mode" "token"})] (reset! cookies-atom cookies) (is (= "Added cookie x-waiter-consent" body)) ; x-waiter-consent should be emitted Waiter (is (has-x-waiter-consent? cookies)) (assert-response-status response 200))) (testing "auto run-as-user population on approved token" (let [service-id-atom (atom nil)] (try (let [previous-service-id service-id {:keys [body cookies service-id] :as response} (make-request-with-debug-info {"host" host-header "x-waiter-fallback-period-secs" 0} #(make-request waiter-url "/hello-world" :cookies @cookies-atom :headers %1))] (reset! service-id-atom service-id) (is (= "Hello World" body)) ; x-waiter-consent should not be re-emitted Waiter (is (not (has-x-waiter-consent? cookies))) (is (not= previous-service-id service-id)) (assert-response-status response 200)) (finally (when @service-id-atom (delete-service waiter-url @service-id-atom))))))))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-authentication-disabled-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) current-user (retrieve-username) service-description (-> (kitchen-request-headers :prefix "") (assoc :authentication "disabled" :name service-name :permitted-user "*" :run-as-user current-user)) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url) request-headers {:x-waiter-token token}] (try (testing "token creation" (let [token-description (assoc service-description :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "token retrieval" (let [token-response (get-token waiter-url token) response-body (-> token-response :body json/read-str pc/keywordize-map)] (is (contains? response-body :last-update-time)) (is (= (assoc service-description :authentication "disabled" :cluster token-cluster :last-update-user current-user :owner current-user :previous {} :root token-root) (dissoc response-body :last-update-time))))) (testing "successful request" (let [{:keys [body] :as response} (make-request waiter-url "/hello-world" :headers request-headers :disable-auth true)] (assert-response-status response 200) (is (= "Hello World" body)))) (testing "backend request headers" (let [{:keys [body] :as response} (make-request waiter-url "/request-info" :headers request-headers :disable-auth true) {:strs [headers]} (json/read-str (str body)) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (not (contains? headers "x-waiter-auth-principal"))) (is (not (contains? headers "x-waiter-authenticated-principal"))) (is (contains? headers "x-cid")) (delete-service waiter-url service-id))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-slow ^:resource-heavy test-service-fallback-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) scheduler-syncer-interval-secs (setting waiter-url [:scheduler-syncer-interval-secs]) fallback-period-secs 30 service-description-1 (-> (kitchen-request-headers :prefix "") (assoc :fallback-period-secs fallback-period-secs :name (str service-name "-v1") :permitted-user "*" :run-as-user (retrieve-username) :version "version-1")) request-headers {:x-waiter-token token} service-id-headers (assoc request-headers :x-waiter-fallback-period-secs 0) kitchen-env-service-id (fn [] (let [kitchen-response (make-request-with-debug-info request-headers #(make-request waiter-url "/environment" :headers %)) kitchen-service-id (-> kitchen-response :body (json/read-str) (get "WAITER_SERVICE_ID"))] (is (= kitchen-service-id (:service-id kitchen-response))) kitchen-service-id)) waiter-routers (routers waiter-url) {:keys [cookies]} (make-request waiter-url "/waiter-auth") await-healthy-service-on-routers (fn await-healthy-service-on-routers [service-id] (wait-for (fn [] (every? (fn [[_ router-url]] (-> (fallback-state router-url :cookies cookies) :state :healthy-service-ids set (contains? service-id))) waiter-routers)) :interval 1 :timeout (inc scheduler-syncer-interval-secs))) await-service-deletion-on-routers (fn await-service-deletion-on-routers [service-id] (wait-for (fn [] (every? (fn [[_ router-url]] (-> (service-state router-url service-id :cookies cookies) :state :service-maintainer-state :maintainer-chan-available false?)) waiter-routers)) :interval 1 :timeout (inc scheduler-syncer-interval-secs))) thread-sleep (fn [time-in-secs] (-> time-in-secs inc t/seconds t/in-millis Thread/sleep))] (try (let [token-description-1 (assoc service-description-1 :token token) post-response (post-token waiter-url token-description-1) _ (assert-response-status post-response 200) service-id-1 (retrieve-service-id waiter-url service-id-headers)] (testing "token response contains fallback and owner" (let [{:keys [body] :as response} (get-token waiter-url token :query-params {})] (assert-response-status response 200) (is (= (assoc service-description-1 :owner (retrieve-username)) (-> body json/read-str walk/keywordize-keys))))) (with-service-cleanup service-id-1 (is (= service-id-1 (kitchen-env-service-id))) ;; allow syncer state to get updated (await-healthy-service-on-routers service-id-1) (let [service-description-2 (assoc service-description-1 :name (str service-name "-v2") :version "version-2") token-description-2 (assoc service-description-2 :token token) post-response (post-token waiter-url token-description-2) _ (assert-response-status post-response 200) service-id-2 (retrieve-service-id waiter-url service-id-headers)] (with-service-cleanup service-id-2 (is (not= service-id-1 service-id-2)) ;; fallback to service-id-1 (is (= service-id-1 (retrieve-service-id waiter-url request-headers))) (is (= service-id-1 (kitchen-env-service-id))) (thread-sleep fallback-period-secs) ;; outside fallback duration (is (= service-id-2 (kitchen-env-service-id))) ;; allow syncer state to get updated (await-healthy-service-on-routers service-id-2) (let [sleep-duration (* 2 scheduler-syncer-interval-secs) service-description-3 (-> service-description-1 (assoc :name (str service-name "-v3") :version "version-3") (update "cmd" (fn [c] (str "sleep " sleep-duration " && " c)))) token-description-3 (assoc service-description-3 :token token) post-response (post-token waiter-url token-description-3) _ (assert-response-status post-response 200) service-id-3 (retrieve-service-id waiter-url service-id-headers)] (with-service-cleanup service-id-3 (is (not= service-id-1 service-id-3)) (is (not= service-id-2 service-id-3)) ;; fallback to service-id-2 (is (= service-id-2 (retrieve-service-id waiter-url request-headers))) (is (= service-id-2 (kitchen-env-service-id))) (thread-sleep fallback-period-secs) ;; outside fallback duration (is (= service-id-3 (kitchen-env-service-id))) ;; delete service-id-3 to trigger fallback logic on next request (delete-service waiter-url service-id-3) ;; allow syncer state to get updated (await-service-deletion-on-routers service-id-3) ;; outside fallback duration (is (= service-id-3 (kitchen-env-service-id))))))))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-valid-fallback-service-resolution (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) request-headers {:x-waiter-token token} fallback-period-secs 300 token-description-1 (-> (kitchen-request-headers :prefix "") (assoc :fallback-period-secs fallback-period-secs :idle-timeout-mins 1 :name (str service-name "-v1") :permitted-user "*" :run-as-user (retrieve-username) :run-as-user (retrieve-username) :token token :version "version-1")) token-description-2 (-> token-description-1 (assoc :name (str service-name "-v2") :version "version-2") (dissoc :cpus :mem :version)) token-description-3 (-> token-description-1 (assoc :cmd (kitchen-cmd (str "-p $PORT0 --start-up-sleep-ms 240000")) :grace-period-secs 300 :name (str service-name "-v3") :version "version-3"))] (assert-response-status (post-token waiter-url token-description-1) 200) (let [service-id-1 (retrieve-service-id waiter-url request-headers)] (with-service-cleanup service-id-1 (let [response-1 (make-request-with-debug-info request-headers #(make-request waiter-url "/hello" :headers %))] (assert-response-status response-1 200) (is (= service-id-1 (:service-id response-1)))) ;; allow every router to learn about the new instance (let [{:keys [cookies]} (make-request waiter-url "/waiter-auth")] (doseq [[_ router-url] (routers waiter-url)] (is (wait-for (fn [] (let [active-instances (-> (service-settings router-url service-id-1 :cookies cookies) (get-in [:instances :active-instances]))] (and (seq active-instances) (some :healthy? active-instances)))))))) (assert-response-status (post-token waiter-url token-description-2) 200) (assert-response-status (make-request waiter-url "/hello" :headers request-headers) 400) (assert-response-status (post-token waiter-url token-description-3) 200) (let [service-id-2 (retrieve-service-id waiter-url (assoc request-headers :x-waiter-fallback-period-secs 0))] (is (not= service-id-1 service-id-2)) (with-service-cleanup service-id-2 (let [response-2 (make-request-with-debug-info request-headers #(make-request waiter-url "/hello" :headers %))] (assert-response-status response-2 200) (is (= service-id-1 (:service-id response-2)))))))))))
86140
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.token-request-test (:require [clj-time.core :as t] [clojure.data.json :as json] [clojure.string :as str] [clojure.test :refer :all] [clojure.tools.logging :as log] [clojure.walk :as walk] [plumbing.core :as pc] [waiter.headers :as headers] [waiter.service-description :as sd] [waiter.util.client-tools :refer :all] [waiter.util.date-utils :as du] [waiter.util.utils :as utils] [waiter.token :as token]) (:import (java.net URL) (org.joda.time DateTime))) (defn- waiter-url->token-url [waiter-url] (str HTTP-SCHEME waiter-url "/token")) (defn- retrieve-token-root [waiter-url] (-> (waiter-settings waiter-url) (get-in [:cluster-config :name]))) (defn- retrieve-token-cluster [waiter-url] (let [settings-json (waiter-settings waiter-url) default-cluster (get-in settings-json [:cluster-config :name]) cluster-calculator-config (-> settings-json (get-in [:token-config :cluster-calculator]) (update :kind keyword) (as-> $ (update-in $ [(:kind $) :factory-fn] symbol))) cluster-calculator (utils/create-component cluster-calculator-config :context {:default-cluster default-cluster})] (token/calculate-cluster cluster-calculator {:headers {"host" waiter-url}}))) (deftest ^:parallel ^:integration-fast test-update-token-cache-consistency (testing-using-waiter-url (let [service-id-prefix (rand-name "testhostname") token (rand-name) update-token-fn (fn [version] (let [{:keys [status]} (post-token waiter-url {:name service-id-prefix :cpus 1 :mem 1250 :version version :cmd "test command" :health-check-url "/ping" :permitted-user "*" :run-as-user (retrieve-username) :token token})] (is (= 200 status)))) validate-token-fn (fn [version num-threads num-iter] (parallelize-requests num-threads num-iter (fn [] (let [{:keys [body status]} (get-token waiter-url token)] (is (= 200 status)) (is (every? #(str/includes? (str body) (str %)) [service-id-prefix "1250" version "test command"])) (is (not-any? #(str/includes? (str body) (str %)) ["invalid"])))))) update-and-validate-token-fn (fn [version] (log/info "creating configuration using token" token "with version" version) (update-token-fn version) (log/info "asserting configuration for token" token "from routers (best-effort)") (validate-token-fn version 10 10)) version1 "123987132937213712" version2 "656760465406467480" version3 "678219671796032121"] (try (update-and-validate-token-fn version1) (update-and-validate-token-fn version2) (update-and-validate-token-fn version3) (finally (delete-token-and-assert waiter-url token)))))) (defn- name-from-service-description [waiter-url service-id] (get-in (service-settings waiter-url service-id) [:service-description :name])) (defn- service-id->source-tokens-entries [waiter-url service-id] (some-> (service-settings waiter-url service-id) :source-tokens walk/stringify-keys set)) (defn- token->etag [waiter-url token] (-> (get-token waiter-url token :query-params {"token" token}) :headers (get "etag"))) (defn- make-source-tokens-entries [waiter-url & tokens] (mapv (fn [token] {"token" token "version" (token->etag waiter-url token)}) tokens)) (defn- create-token-name [waiter-url service-id-prefix] (str service-id-prefix "." (subs waiter-url 0 (str/index-of waiter-url ":")))) (defn- list-tokens [waiter-url owner cookies query-params] (let [tokens-response (make-request waiter-url "/tokens" :cookies cookies :query-params query-params)] (log/debug "retrieved tokens for owner " owner ":" (:body tokens-response)) tokens-response)) (defn- parse-token-description "Parses a response as json and keywordizes the map." [response-body] (try (-> response-body str json/read-str pc/keywordize-map) (catch Exception _ (is false (str "Failed to parse token " response-body))))) (defmacro assert-token-response "Asserts the token data in the response" ([response token-root token-cluster service-id-prefix deleted] `(assert-token-response ~response ~token-root ~token-cluster ~service-id-prefix ~deleted true)) ([response token-root token-cluster service-id-prefix deleted include-metadata] `(let [body# (:body ~response) token-description# (parse-token-description body#)] (assert-response-status ~response 200) (when ~include-metadata (is (contains? token-description# :cluster)) (is (contains? token-description# :last-update-time)) (is (contains? token-description# :last-update-user)) (is (contains? token-description# :owner)) (is (contains? token-description# :root))) (is (= (cond-> {:health-check-url "/probe" :name ~service-id-prefix :owner (retrieve-username)} ~include-metadata (assoc :cluster ~token-cluster :last-update-user (retrieve-username) :root ~token-root) (and ~deleted ~include-metadata) (assoc :deleted ~deleted)) (dissoc token-description# :last-update-time :previous)))))) (deftest ^:parallel ^:integration-fast test-token-create-delete (testing-using-waiter-url (let [service-id-prefix (rand-name) token-prefix (create-token-name waiter-url service-id-prefix) {:keys [cookies]} (make-request waiter-url "/waiter-auth") num-tokens-to-create 10 tokens-to-create (map #(str "token" %1 "." token-prefix) (range num-tokens-to-create)) current-user (System/getProperty "user.name") token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (log/info "creating token without parameters should fail") (let [token (str service-id-prefix ".empty") {:keys [body] :as response} (post-token waiter-url {:token token})] (assert-response-status response 400) (is (str/includes? (str body) (str "No parameters provided for " token)) (str body))) (log/info "creating the tokens") (doseq [token tokens-to-create] (let [response (post-token waiter-url {:health-check-url "/check" :name service-id-prefix :token token})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully created " token))))) (testing "update without etags" (doseq [token tokens-to-create] (let [response (post-token waiter-url {:health-check-url "/health" :name service-id-prefix :token token})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully updated " token)))))) (testing "update with etags" (doseq [token tokens-to-create] (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (select-keys [:name]) (assoc :health-check-url "/probe" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully updated " token)))))) (testing "update without changes" (doseq [token tokens-to-create] (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str (select-keys sd/token-user-editable-keys) walk/keywordize-keys (assoc :token token)) current-etag (get headers "etag") response (post-token waiter-url token-description :headers {"if-match" current-etag})] (assert-response-status response 200) (is (str/includes? (:body response) (str "No changes detected for " token))) (is (= current-etag (get-in response [:headers "etag"])))))) (testing "token retrieval - presence of etag header" (doseq [token tokens-to-create] (testing "via query parameters" (let [{:keys [headers] :as response} (get-token waiter-url token :cookies cookies :query-params {"include" "metadata" "token" token} :request-headers {}) actual-etag (get headers "etag")] (assert-response-status response 200) (let [token-description (-> response :body json/read-str)] (is (= {"health-check-url" "/check", "name" service-id-prefix} (-> token-description (get-in (repeat 2 "previous")) (select-keys sd/service-parameter-keys)))) (is (= {"health-check-url" "/health", "name" service-id-prefix} (-> token-description (get-in (repeat 1 "previous")) (select-keys sd/service-parameter-keys))))) (is actual-etag))) (testing "via x-waiter-token header" (let [{:keys [body headers] :as response} (get-token waiter-url token :cookies cookies) actual-etag (get headers "etag")] (assert-response-status response 200) (is actual-etag) (when actual-etag (let [convert-last-update-time (fn [{:strs [last-update-time] :as service-description}] (cond-> service-description last-update-time (assoc "last-update-time" (-> last-update-time du/str-to-date .getMillis)))) expected-etag (str "E-" (-> body json/read-str convert-last-update-time (dissoc "previous") sd/parameters->id))] (is (= expected-etag actual-etag)))))))) (log/info "ensuring tokens can be retrieved and listed on each router") (doseq [token tokens-to-create] (doseq [[_ router-url] (routers waiter-url)] (-> (get-token router-url token :cookies cookies :query-params {"include" "none"}) (assert-token-response token-root token-cluster service-id-prefix false false)) (-> (get-token router-url token :cookies cookies :query-params {"include" "metadata"}) (assert-token-response token-root token-cluster service-id-prefix false true)) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (some (fn [token-entry] (= token (get token-entry "token"))) tokens))))) (log/info "soft-deleting the tokens") (doseq [token tokens-to-create] (delete-token-and-assert waiter-url token :hard-delete false)) (log/info "ensuring tokens can no longer be retrieved on each router without include=deleted parameter") (doseq [token tokens-to-create] (doseq [[router-id router-url] (routers waiter-url)] (let [router-state (kv-store-state router-url :cookies cookies) cache-data (get-in router-state ["state" "cache" "data"]) token-cache-data (get cache-data (keyword token))] (is (nil? token-cache-data) (str token " data not nil (" token-cache-data ") on " router-id ", cache data =" cache-data))) (let [{:keys [body] :as response} (get-token router-url token :cookies cookies)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body))) (-> (get-token router-url token :cookies cookies :query-params {"include" ["deleted" "metadata"]}) (assert-token-response token-root token-cluster service-id-prefix true)) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (not-any? (fn [token-entry] (= token (get token-entry "token"))) tokens))) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (some (fn [token-entry] (= token (get token-entry "token"))) tokens))))) (log/info "hard-deleting the tokens") (doseq [token tokens-to-create] (delete-token-and-assert waiter-url token) (doseq [[_ router-url] (routers waiter-url)] (let [{:keys [body] :as response} (get-token router-url token :cookies cookies)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str {:body body :token token}))) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) token-entries (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) token-entries)) (is (every? (fn [token-entry] (contains? token-entry "etag")) token-entries)))) ;; the token must be removed from at least one router (others may have temporarily cached values) (is (some (fn [router-url] (let [{:keys [body]} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) token-entries (json/read-str body)] (not-any? (fn [token-entry] (= token (get token-entry "token"))) token-entries))) (vals (routers waiter-url))) (str token " entry found in list of deleted tokens on all routers"))) (log/info "ensuring tokens can no longer be retrieved on each router with include=deleted parameter after hard-delete") (doseq [token tokens-to-create] (doseq [[_ router-url] (routers waiter-url)] (let [{:keys [body] :as response} (get-token router-url token :cookies cookies :query-params {"include" "deleted"})] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body)))))))) (deftest ^:parallel ^:integration-fast ^:resource-heavy test-service-list-filtering (testing-using-waiter-url (let [service-name (rand-name) token-1 (create-token-name waiter-url (str "www." service-name ".t1")) token-2 (create-token-name waiter-url (str "www." service-name ".t2")) service-ids-atom (atom #{}) token->version->etag-atom (atom {}) all-tokens [token-1 token-2] all-version-suffixes ["v1" "v2" "v3"] router-id->router-url (routers waiter-url) {:keys [cookies]} (make-request waiter-url "/waiter-auth")] (doseq [version-suffix all-version-suffixes] (doseq [token all-tokens] (let [token-description (merge (kitchen-request-headers :prefix "") {:fallback-period-secs 0 :name (str service-name "." (hash token)) :token token :version (str service-name "." version-suffix)}) {:keys [headers] :as response} (post-token waiter-url token-description)] (assert-response-status response 200) (let [token-etag (get headers "etag")] (log/info token "->" token-etag) (is (-> token-etag str/blank? not)) (let [{:keys [service-id] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "/environment" :headers %))] (assert-response-status response 200) (is (-> service-id str/blank? not)) (swap! service-ids-atom conj service-id) ;; ensure all routers know about the service (doseq [[_ router-url] router-id->router-url] (let [response (make-request-with-debug-info {:x-waiter-token token} #(make-request router-url "/environment" :headers % :cookies cookies))] (assert-response-status response 200) (is (= service-id (:service-id response)))))) (swap! token->version->etag-atom assoc-in [token version-suffix] token-etag))))) (is (= (* (count all-tokens) (count all-version-suffixes)) (count @service-ids-atom)) (str {:service-ids @service-ids-atom})) (testing "star in token filter" (doseq [[_ router-url] (routers waiter-url)] (let [query-params {"token" (str "www." service-name ".t*")} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-tokens (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :token))) services)] (assert-response-status response 200) (is (= (count @service-ids-atom) (count service-tokens)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-tokens service-tokens}))))) (doseq [loop-token all-tokens] (doseq [[_ router-url] (routers waiter-url)] (let [query-params {"token" loop-token} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-tokens (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :token))) services)] (assert-response-status response 200) (is (= 3 (count service-tokens)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-tokens service-tokens})))) (doseq [version-suffix all-version-suffixes] (doseq [[_ router-url] (routers waiter-url)] (let [loop-etag (get-in @token->version->etag-atom [loop-token version-suffix]) query-params {"token-version" loop-etag} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-token-versions (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :version))) services)] (assert-response-status response 200) (is (= 1 (count service-token-versions)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-token-versions service-token-versions})))))) (doseq [service-id @service-ids-atom] (delete-service waiter-url service-id))))) (defn- service-id->metadata-id [waiter-url service-id] (get-in (service-settings waiter-url service-id) [:service-description :metadata :id])) (deftest ^:parallel ^:integration-fast test-hostname-token (testing-using-waiter-url (let [service-id-prefix (rand-name) token-prefix (str "token-" (rand-int 3000000)) token (create-token-name waiter-url token-prefix) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (testing "hostname-token-test" (try (log/info "basic hostname as token test") (let [current-user (retrieve-username) service-description (assoc (kitchen-request-headers) :x-waiter-metric-group "waiter_test" :x-waiter-name token-prefix :x-waiter-permitted-user "*" :x-waiter-run-as-user current-user)] (testing "hostname-token-creation" (log/info "creating configuration using token" token) (let [{:keys [body status]} (post-token waiter-url {:health-check-url "/probe" :metric-group "waiter_test" :metadata {"id" token-prefix} :name service-id-prefix :token token})] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (let [token-response (get-token waiter-url token) response-body (json/read-str (:body token-response))] (is (contains? response-body "last-update-time")) (is (= {"cluster" token-cluster "health-check-url" "/probe" "last-update-user" (retrieve-username) "metadata" {"id" token-prefix} "metric-group" "waiter_test" "name" service-id-prefix "owner" (retrieve-username) "previous" {} "root" token-root} (dissoc response-body "last-update-time")))) (log/info "asserted retrieval of configuration for token" token)) (testing "support-for-token-with-x-waiter-headers" (log/info "request with hostname token" token "along with x-waiter headers") (let [request-headers (merge service-description {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id)))) (log/info "request with hostname token" token "along with x-waiter headers except permitted-user") (let [request-headers (merge (dissoc service-description :x-waiter-permitted-user) {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id))) ;; the above request hashes to a different service-id than the rest of the test, so we need to cleanup (delete-service waiter-url service-id)) (log/info "request with hostname token" token "along with x-waiter headers except run-as-user") (let [request-headers (merge (dissoc service-description :x-waiter-run-as-user) {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id))) (testing "backend request headers" (let [{:keys [body] :as response} (make-request waiter-url "/request-info" :headers request-headers) {:strs [headers]} (json/read-str (str body))] (assert-response-status response 200) (is (contains? headers "x-waiter-auth-principal")) (is (contains? headers "x-waiter-authenticated-principal")))) ;; the above request hashes to a different service-id only when running as someone other than current-user ;; when the service-id is different, we need to cleanup (when (not= (System/getProperty "user.name") current-user) (delete-service waiter-url service-id))) (log/info "request with hostname token" token "along with missing x-waiter headers except cmd") (let [request-headers (merge (dissoc service-description :x-waiter-cmd) {"host" token}) path "/foo" {:keys [body] :as response} (make-request waiter-url path :headers request-headers)] (is (some #(str/includes? body %) ["cmd must be a non-empty string" "Invalid command or version"]) (str "response body was: " response)) (assert-response-status response 400)) (log/info "request with hostname token and x-waiter-debug token" token "along with x-waiter headers") (let [request-headers (merge service-description {:x-waiter-debug "true", "host" token}) path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (delete-service waiter-url service-id)))) (finally (delete-token-and-assert waiter-url token))))))) (deftest ^:parallel ^:integration-fast test-token-administer-unaffected-by-run-as-user-permissions (testing-using-waiter-url (let [service-id-prefix (rand-name) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (testing "token-administering" (testing "active-token" (let [last-update-time (System/currentTimeMillis) token (create-token-name waiter-url service-id-prefix)] (let [token-description {:health-check-url "/probe" :name service-id-prefix :owner (retrieve-username) :run-as-user (retrieve-username) :token token} response (post-token waiter-url token-description)] (assert-response-status response 200)) (testing "if-match-required during update" (let [token-description {:health-check-url "/probe-1" :last-update-time last-update-time :name service-id-prefix :owner (retrieve-username) :token token} {:keys [body] :as response} (post-token waiter-url token-description :headers {} :query-params {"update-mode" "admin"})] (assert-response-status response 400) (is (str/includes? body "Must specify if-match header for admin mode token updates")))) (try (testing "successful admin mode update" (log/info "creating configuration using token" token) (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (assoc :health-check-url "/probe-2" :last-update-time last-update-time :owner (retrieve-username) :run-as-user "i-do-not-exist-but-will-not-be-checked" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")} :query-params {"update-mode" "admin"})] (assert-response-status response 200) (log/info "created configuration using token" token)) (let [token-response (get-token waiter-url token) response-body (json/read-str (:body token-response))] (is (= {"cluster" token-cluster "health-check-url" "/probe-2" "last-update-time" (-> last-update-time DateTime. du/date-to-str) "last-update-user" (retrieve-username) "name" service-id-prefix, "owner" (retrieve-username) "root" token-root "run-as-user" "i-do-not-exist-but-will-not-be-checked"} (dissoc response-body "previous"))) (log/info "asserted retrieval of configuration for token" token))) (testing "update with invalid etag" (let [token-description {:health-check-url "/probe-3" :last-update-time last-update-time :name service-id-prefix :owner (retrieve-username) :run-as-user "foo-bar" :token token} {:keys [body] :as response} (post-token waiter-url token-description :headers {"host" token "if-match" "1010"} :query-params {"update-mode" "admin"})] (assert-response-status response 412) (is (str/includes? (str body) "Cannot modify stale token")))) (testing "hard-delete without etag" (let [{:keys [body] :as response} (make-request waiter-url "/token" :headers {"host" token} :method :delete :query-params {"hard-delete" true})] (assert-response-status response 400) (is (str/includes? (str body) "Must specify if-match header for token hard deletes")))) (testing "hard-delete with invalid etag" (let [{:keys [body] :as response} (make-request waiter-url "/token" :headers {"host" token "if-match" "1010"} :method :delete :query-params {"hard-delete" true})] (assert-response-status response 412) (is (str/includes? (str body) "Cannot modify stale token")))) (finally (delete-token-and-assert waiter-url token))))) (testing "deleted-token" (let [last-update-time (System/currentTimeMillis) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-description {:health-check-url "/probe-3" :name service-id-prefix :owner (retrieve-username) :token token} response (post-token waiter-url token-description :headers {"host" token})] (assert-response-status response 200)) (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (assoc :deleted true :health-check-url "/probe" :last-update-time last-update-time :run-as-user "foo-bar" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")} :query-params {"update-mode" "admin"})] (assert-response-status response 200)) (log/info "created configuration using token" token) (let [{:keys [body] :as response} (get-token waiter-url token)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body))) (let [token-response (get-token waiter-url token :query-params {"include" ["deleted" "metadata"]}) response-body (json/read-str (:body token-response))] (is (= {"cluster" token-cluster "deleted" true "health-check-url" "/probe" "last-update-time" (-> last-update-time DateTime. du/date-to-str) "last-update-user" (retrieve-username) "name" service-id-prefix "owner" (retrieve-username) "root" token-root "run-as-user" "foo-bar"} (dissoc response-body "previous")))) (log/info "asserted retrieval of configuration for token" token) (finally (delete-token-and-assert waiter-url token))))))))) (deftest ^:parallel ^:integration-fast test-named-token (testing-using-waiter-url (log/info "basic named token test") (let [service-id-prefix (rand-name) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix))) (log/info "asserted retrieval of configuration for token" token) (log/info "making Waiter request with token" token "in header") (let [request-headers {:x-waiter-token token} path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id)))) (log/info "making Waiter request with token and x-waiter-debug token" token "in header") (let [request-headers {:x-waiter-debug "true", :x-waiter-token token} path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (delete-service waiter-url service-id)) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-star-run-as-user-token (testing-using-waiter-url (let [service-id-prefix (rand-name) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :run-as-user "*" :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix))) (log/info "asserted retrieval of configuration for token" token) (let [{:keys [body] :as token-response} (get-token waiter-url token) token-description (try (json/read-str (str body)) (catch Exception _ (is false (str "Failed to parse token" body))))] (assert-response-status token-response 200) (is (= "/status" (token-description "health-check-url"))) (is (= service-id-prefix (token-description "name"))) (is (= "*" (token-description "run-as-user"))) (is (System/getProperty "user.name") (token-description "owner"))) (log/info "making Waiter request with token" token "in header") (let [request-headers {:x-waiter-token token} path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= (retrieve-username) (:run-as-user (service-id->service-description waiter-url service-id))))) (log/info "making Waiter request with token and x-waiter-debug token" token "in header") (let [request-headers {:x-waiter-debug "true", :x-waiter-token token} path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (delete-service waiter-url service-id)) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast ^:explicit test-on-the-fly-to-token (testing-using-waiter-url (let [name-string (rand-name) {:keys [cookies] :as canary-response} (make-request-with-debug-info {:x-waiter-name name-string} #(make-kitchen-request waiter-url %)) service-id-1 (:service-id canary-response)] (with-service-cleanup service-id-1 (is (str/includes? service-id-1 name-string) (str "ERROR: App-name is missing " name-string)) (assert-service-on-all-routers waiter-url service-id-1 cookies) (is (nil? (service-id->source-tokens-entries waiter-url service-id-1))) (let [token (str <KEY>) response (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "" :headers %)) service-id-2 (:service-id response)] (with-service-cleanup service-id-2 (assert-response-status response 200) (is service-id-2) (is (= service-id-1 service-id-2) "The on-the-fly and token-based service ids do not match") (assert-service-on-all-routers waiter-url service-id-1 cookies) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id-2))))))))) (deftest ^:parallel ^:integration-fast test-namespace-token (testing-using-waiter-url (log/info "basic token with namespace field test") (let [service-id-prefix (rand-name) target-user (retrieve-username) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :namespace target-user :run-as-user target-user :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix)) (let [{:strs [namespace run-as-user] :as token-json} (try-parse-json response-body)] (is (= target-user run-as-user)) (is (= target-user namespace)))) (log/info "asserted retrieval of configuration for token" token) (finally (delete-token-and-assert waiter-url token)))) (testing "can't create token with bad namespace" (let [service-desc {:name (rand-name "notused") :cpus 1 :debug true :mem 1024 :version "universe b10452d0b0380ce61764543847085631ee3d7af9" :token "<PASSWORD>" :cmd "not-used" :permitted-user "*" :namespace "not-run-as-user" :run-as-user (retrieve-username) :health-check-url "/not-used"} response (post-token waiter-url service-desc)] (is (str/includes? (:body response) "Service namespace must either be omitted or match the run-as-user")) (assert-response-status response 400))))) (deftest ^:parallel ^:integration-fast test-bad-token (testing-using-waiter-url (let [common-headers {"x-waiter-cmd" "foo-bar" "x-waiter-cmd-type" "shell"}] (testing "ignore missing token when have service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "missing_token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400))) (testing "ignore invalid token when have service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "bad/token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400))) (testing "ignore invalid token when have invalid service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "bad/token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400)))) (testing "can't use missing token server" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token"})] (is (str/includes? (:body response) "Unable to identify service using waiter headers/token")) (assert-response-status response 400))) (testing "can't use invalid token server" (let [response (make-request waiter-url "/pathabc" :headers {"host" "bad/token"})] (is (str/includes? (:body response) "Unable to identify service using waiter headers/token")) (assert-response-status response 400))) (testing "can't use invalid token that's valid for zookeeper" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "bad<PASSWORD>"})] (is (str/includes? (:body response) "Token not found: bad#token")) (assert-response-status response 400))) (testing "can't use invalid token" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "bad/token"})] (is (str/includes? (:body response) "Token not found: bad/token")) (assert-response-status response 400))) (testing "can't use invalid token with host set" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token" "X-Waiter-Token" "bad/token"})] (is (str/includes? (:body response) "Token not found: bad/token")) (assert-response-status response 400))) (testing "can't use missing token with host set" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token" "X-Waiter-Token" "missing_token"})] (is (str/includes? (:body response) "Token not found: missing_token")) (assert-response-status response 400))) (testing "can't use missing token" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "missing_token"})] (is (str/includes? (:body response) "Token not found: missing_token")) (assert-response-status response 400))) (testing "can't create bad token" (let [service-desc {:name (rand-name "notused") :cpus 1 :debug true :mem 1024 :version "universe b10452d0b0380ce61764543847085631ee3d7af9" :token "<PASSWORD>" :cmd "not-used" :permitted-user "*" :run-as-user (retrieve-username) :health-check-url "/not-used"} response (post-token waiter-url service-desc)] (is (str/includes? (:body response) "Token must match pattern")) (assert-response-status response 400))))) (deftest ^:parallel ^:integration-fast test-token-metadata (testing-using-waiter-url (let [token (rand-name) service-desc {:name token :cpus 1 :mem 100 :version "1" :cmd-type "shell" :token token :cmd "exit 0" :run-as-user (retrieve-username) :health-check-url "/not-used" :metadata {"a" "b", "c" "d"}} register-response (post-token waiter-url service-desc) {:keys [body]} (get-token waiter-url token)] (assert-response-status register-response 200) (is (= (:metadata service-desc) (get (json/read-str body) "metadata"))) (delete-token-and-assert waiter-url token) (delete-service waiter-url (:name service-desc))))) (deftest ^:parallel ^:integration-fast test-token-bad-metadata (testing-using-waiter-url (let [service-desc {"name" "token-bad-metadata" "cpus" 1 "mem" 100 "version" "1" "cmd-type" "shell" "token" (rand-<KEY>) "cmd" "exit 0" "run-as-user" (retrieve-username) "health-check-url" "/not-used" "metadata" {"a" "b", "c" {"d" "e"}}} register-response (post-token waiter-url service-desc)] (is (= 400 (:status register-response)))))) (deftest ^:parallel ^:integration-fast test-token-bad-payload (testing-using-waiter-url (let [{:keys [status]} (make-request waiter-url "/token" :body "i'm bad at json" :headers {"host" "test-token"} :method :post)] (is (= 400 status))))) (deftest ^:parallel ^:integration-fast test-token-environment-variables (testing-using-waiter-url (let [token (rand-<KEY>) binary (kitchen-cmd) token-response (post-token waiter-url {:cmd "$BINARY -p $PORT0" :cmd-type "shell" :version "does-not-matter" :name token :env {"BINARY" binary} :token token}) {:keys [service-id status] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-light-request waiter-url %)) {:keys [env] :as service-description} (response->service-description waiter-url response)] (is (= 200 (:status token-response)) (:body token-response)) (is (= 200 status)) (is (= {:BINARY binary} env) (str service-description)) (delete-token-and-assert waiter-url token) (delete-service waiter-url service-id)))) (deftest ^:parallel ^:integration-fast test-token-https-redirects (testing-using-waiter-url (let [token (<KEY>) token-response (post-token waiter-url {:cmd (str (kitchen-cmd) " -p $PORT0") :cmd-type "shell" :https-redirect true :name token :version "does-not-matter" :token token})] (assert-response-status token-response 200) (testing "https redirects" (let [request-headers {:x-waiter-token token} url (URL. (str "http://" waiter-url)) endpoint "/request-info"] (testing "get request" (let [{:keys [headers] :as response} (make-kitchen-request waiter-url request-headers :method :get :path endpoint)] (assert-response-status response 301) (is (= (str "https://" (.getHost url) endpoint) (get headers "location"))) (is (str/starts-with? (str (get headers "server")) "waiter") (str "headers:" headers)))) (testing "post request" (let [{:keys [headers] :as response} (make-kitchen-request waiter-url request-headers :method :post :path endpoint)] (assert-response-status response 307) (is (= (str "https://" (.getHost url) endpoint) (get headers "location"))) (is (str/starts-with? (str (get headers "server")) "waiter") (str "headers:" headers)))))) (delete-token-and-assert waiter-url token)))) (defmacro run-token-param-support [waiter-url request-fn request-headers expected-env] `(let [response# (make-request-with-debug-info ~request-headers ~request-fn) service-description# (response->service-description ~waiter-url response#) service-id# (:service-id response#)] (is (= 200 (:status response#))) (is (= ~expected-env (:env service-description#)) (str service-description#)) (delete-service ~waiter-url service-id#) service-id#)) (deftest ^:parallel ^:integration-fast test-token-param-support (testing-using-waiter-url (let [token (<KEY>) binary (kitchen-cmd) service-description {:allowed-params ["FAA" "FEE" "FII" "FOO" "FUU"] :cmd "$BINARY -p $PORT0" :cmd-type "shell" :env {"BINARY" binary "FEE" "FIE" "FOO" "BAR"} :name "test-token-param-support" :version "does-not-matter"} kitchen-request #(make-kitchen-request waiter-url % :path "/environment")] (try (let [token-description (assoc service-description :token token) token-response (post-token waiter-url token-description :query-params {"update-mode" "admin"})] (assert-response-status token-response 200) (let [request-headers {:x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured"))) (let [request-headers {:x-waiter-allowed-params "" :x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured")))) (let [token-description (-> service-description (dissoc :allowed-params) (assoc :token (str token ".1"))) token-response (post-token waiter-url token-description :query-params {"update-mode" "admin"})] (assert-response-status token-response 200) (let [request-headers {:x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured")))) (let [service-ids (set [(run-token-param-support waiter-url kitchen-request {:x-waiter-token token} {:BINARY binary :FEE "FIE" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-allowed-params ["FEE" "FII" "FOO"] :x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-allowed-params "FEE,FOO" :x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-param-fee "value-1p" :x-waiter-param-foo "value-2p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "value-2p"})])] (is (= 5 (count service-ids)) "Unique service-ids were not created!")) (finally (delete-token-and-assert waiter-url token) (delete-token-and-assert waiter-url (str token ".1"))))))) (deftest ^:parallel ^:integration-fast test-token-invalid-environment-variables (testing-using-waiter-url (let [{:keys [body status]} (post-token waiter-url {:env {"HOME" "/my/home"} :token (rand-name)})] (is (= 400 status)) (is (not (str/includes? body "clojure")) body) (is (str/includes? body "The following environment variable keys are reserved: HOME.") body)))) (deftest ^:parallel ^:integration-fast test-token-parameters-exceed-limits (testing-using-waiter-url (let [constraints (setting waiter-url [:service-description-constraints]) max-constraints (sd/extract-max-constraints constraints)] (is (seq max-constraints)) (doseq [[parameter max-constraint] max-constraints] (let [string-param? (contains? headers/params-with-str-value (name parameter)) param-value (if string-param? (apply str parameter " " (repeat max-constraint "x")) (inc max-constraint)) {:keys [body status]} (post-token waiter-url {parameter param-value :token (rand-name)})] (is (= 400 status)) (is (not (str/includes? body "clojure")) body) (is (every? #(str/includes? body %) ["The following fields exceed their allowed limits" (if string-param? (str (name parameter) " must be at most " max-constraint " characters") (str (name parameter) " is " param-value " but the max allowed is " max-constraint))]) body)))))) (deftest ^:parallel ^:integration-fast test-auto-run-as-requester-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) service-description (-> (kitchen-request-headers :prefix "") (assoc :name service-name :permitted-user "*") (dissoc :run-as-user)) waiter-port (.getPort (URL. (str "http://" waiter-url))) waiter-port (if (neg? waiter-port) 80 waiter-port) host-header (str token ":" waiter-port) has-x-waiter-consent? (partial some #(= (:name %) "x-waiter-consent")) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (try (testing "token creation" (let [token-description (assoc service-description :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "token retrieval" (let [token-response (get-token waiter-url token) response-body (-> token-response (:body) (json/read-str) (pc/keywordize-map))] (is (nil? (get response-body :run-as-user))) (is (contains? response-body :last-update-time)) (is (= (assoc service-description :cluster token-cluster :last-update-user (retrieve-username) :owner (retrieve-username) :previous {} :root token-root) (dissoc response-body :last-update-time))))) (testing "expecting redirect" (let [{:keys [headers] :as response} (make-request waiter-url "/hello-world" :headers {"host" host-header})] (is (= (str "/waiter-consent/hello-world") (get headers "location"))) (assert-response-status response 303))) (testing "waiter-consent" (let [consent-path (str "/waiter-consent/hello-world") {:keys [body] :as response} (make-request waiter-url consent-path :headers {"host" host-header}) service-id (when-let [service-id-index (str/index-of body "name=\"service-id\"")] (when-let [value-index (str/index-of body "value=\"" service-id-index)] (when-let [end-index (str/index-of body "\"" (+ value-index 7))] (subs body (+ value-index 7) end-index))))] (is service-id) (assert-response-status response 200) (let [cookies-atom (atom nil)] (testing "approval of specific service" (let [{:keys [body cookies] :as response} (make-request waiter-url "/waiter-consent" :headers {"host" host-header "referer" (str "http://" host-header) "origin" (str "http://" host-header) "x-requested-with" "XMLHttpRequest"} :method :post :multipart {"mode" "service" "service-id" service-id})] (reset! cookies-atom cookies) (is (= "Added cookie x-waiter-consent" body)) ; x-waiter-consent should be emitted Waiter (is (has-x-waiter-consent? cookies)) (assert-response-status response 200))) (testing "auto run-as-user population on expected service-id" (let [service-id-atom (atom nil)] (try (let [expected-service-id service-id {:keys [body cookies service-id] :as response} (make-request-with-debug-info {"host" host-header} #(make-request waiter-url "/hello-world" :cookies @cookies-atom :headers %1)) {:keys [service-description]} (service-settings waiter-url service-id) {:keys [run-as-user permitted-user]} service-description] (reset! service-id-atom service-id) (is (= "Hello World" body)) ; x-waiter-consent should not be re-emitted Waiter (is (not (has-x-waiter-consent? cookies))) (is (= expected-service-id service-id)) (is (not (str/blank? permitted-user))) (is (= run-as-user permitted-user)) (assert-response-status response 200)) (finally (when @service-id-atom (delete-service waiter-url @service-id-atom)))))) (testing "token update" (let [updated-service-name (rand-name) token-description (assoc service-description :name updated-service-name :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "expecting redirect after token update" (let [{:keys [headers] :as response} (make-request waiter-url "/hello-world" :cookies @cookies-atom :headers {"host" host-header})] (is (= (str "/waiter-consent/hello-world") (get headers "location"))) (assert-response-status response 303))) (testing "approval of token" (let [{:keys [body cookies] :as response} (make-request waiter-url "/waiter-consent" :cookies @cookies-atom :headers {"host" host-header "referer" (str "http://" host-header) "origin" (str "http://" host-header) "x-requested-with" "XMLHttpRequest"} :method :post :multipart {"mode" "token"})] (reset! cookies-atom cookies) (is (= "Added cookie x-waiter-consent" body)) ; x-waiter-consent should be emitted Waiter (is (has-x-waiter-consent? cookies)) (assert-response-status response 200))) (testing "auto run-as-user population on approved token" (let [service-id-atom (atom nil)] (try (let [previous-service-id service-id {:keys [body cookies service-id] :as response} (make-request-with-debug-info {"host" host-header "x-waiter-fallback-period-secs" 0} #(make-request waiter-url "/hello-world" :cookies @cookies-atom :headers %1))] (reset! service-id-atom service-id) (is (= "Hello World" body)) ; x-waiter-consent should not be re-emitted Waiter (is (not (has-x-waiter-consent? cookies))) (is (not= previous-service-id service-id)) (assert-response-status response 200)) (finally (when @service-id-atom (delete-service waiter-url @service-id-atom))))))))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-authentication-disabled-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) current-user (retrieve-username) service-description (-> (kitchen-request-headers :prefix "") (assoc :authentication "disabled" :name service-name :permitted-user "*" :run-as-user current-user)) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url) request-headers {:x-waiter-token token}] (try (testing "token creation" (let [token-description (assoc service-description :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "token retrieval" (let [token-response (get-token waiter-url token) response-body (-> token-response :body json/read-str pc/keywordize-map)] (is (contains? response-body :last-update-time)) (is (= (assoc service-description :authentication "disabled" :cluster token-cluster :last-update-user current-user :owner current-user :previous {} :root token-root) (dissoc response-body :last-update-time))))) (testing "successful request" (let [{:keys [body] :as response} (make-request waiter-url "/hello-world" :headers request-headers :disable-auth true)] (assert-response-status response 200) (is (= "Hello World" body)))) (testing "backend request headers" (let [{:keys [body] :as response} (make-request waiter-url "/request-info" :headers request-headers :disable-auth true) {:strs [headers]} (json/read-str (str body)) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (not (contains? headers "x-waiter-auth-principal"))) (is (not (contains? headers "x-waiter-authenticated-principal"))) (is (contains? headers "x-cid")) (delete-service waiter-url service-id))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-slow ^:resource-heavy test-service-fallback-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) scheduler-syncer-interval-secs (setting waiter-url [:scheduler-syncer-interval-secs]) fallback-period-secs 30 service-description-1 (-> (kitchen-request-headers :prefix "") (assoc :fallback-period-secs fallback-period-secs :name (str service-name "-v1") :permitted-user "*" :run-as-user (retrieve-username) :version "version-1")) request-headers {:x-waiter-token token} service-id-headers (assoc request-headers :x-waiter-fallback-period-secs 0) kitchen-env-service-id (fn [] (let [kitchen-response (make-request-with-debug-info request-headers #(make-request waiter-url "/environment" :headers %)) kitchen-service-id (-> kitchen-response :body (json/read-str) (get "WAITER_SERVICE_ID"))] (is (= kitchen-service-id (:service-id kitchen-response))) kitchen-service-id)) waiter-routers (routers waiter-url) {:keys [cookies]} (make-request waiter-url "/waiter-auth") await-healthy-service-on-routers (fn await-healthy-service-on-routers [service-id] (wait-for (fn [] (every? (fn [[_ router-url]] (-> (fallback-state router-url :cookies cookies) :state :healthy-service-ids set (contains? service-id))) waiter-routers)) :interval 1 :timeout (inc scheduler-syncer-interval-secs))) await-service-deletion-on-routers (fn await-service-deletion-on-routers [service-id] (wait-for (fn [] (every? (fn [[_ router-url]] (-> (service-state router-url service-id :cookies cookies) :state :service-maintainer-state :maintainer-chan-available false?)) waiter-routers)) :interval 1 :timeout (inc scheduler-syncer-interval-secs))) thread-sleep (fn [time-in-secs] (-> time-in-secs inc t/seconds t/in-millis Thread/sleep))] (try (let [token-description-1 (assoc service-description-1 :token token) post-response (post-token waiter-url token-description-1) _ (assert-response-status post-response 200) service-id-1 (retrieve-service-id waiter-url service-id-headers)] (testing "token response contains fallback and owner" (let [{:keys [body] :as response} (get-token waiter-url token :query-params {})] (assert-response-status response 200) (is (= (assoc service-description-1 :owner (retrieve-username)) (-> body json/read-str walk/keywordize-keys))))) (with-service-cleanup service-id-1 (is (= service-id-1 (kitchen-env-service-id))) ;; allow syncer state to get updated (await-healthy-service-on-routers service-id-1) (let [service-description-2 (assoc service-description-1 :name (str service-name "-v2") :version "version-2") token-description-2 (assoc service-description-2 :token token) post-response (post-token waiter-url token-description-2) _ (assert-response-status post-response 200) service-id-2 (retrieve-service-id waiter-url service-id-headers)] (with-service-cleanup service-id-2 (is (not= service-id-1 service-id-2)) ;; fallback to service-id-1 (is (= service-id-1 (retrieve-service-id waiter-url request-headers))) (is (= service-id-1 (kitchen-env-service-id))) (thread-sleep fallback-period-secs) ;; outside fallback duration (is (= service-id-2 (kitchen-env-service-id))) ;; allow syncer state to get updated (await-healthy-service-on-routers service-id-2) (let [sleep-duration (* 2 scheduler-syncer-interval-secs) service-description-3 (-> service-description-1 (assoc :name (str service-name "-v3") :version "version-3") (update "cmd" (fn [c] (str "sleep " sleep-duration " && " c)))) token-description-3 (assoc service-description-3 :token token) post-response (post-token waiter-url token-description-3) _ (assert-response-status post-response 200) service-id-3 (retrieve-service-id waiter-url service-id-headers)] (with-service-cleanup service-id-3 (is (not= service-id-1 service-id-3)) (is (not= service-id-2 service-id-3)) ;; fallback to service-id-2 (is (= service-id-2 (retrieve-service-id waiter-url request-headers))) (is (= service-id-2 (kitchen-env-service-id))) (thread-sleep fallback-period-secs) ;; outside fallback duration (is (= service-id-3 (kitchen-env-service-id))) ;; delete service-id-3 to trigger fallback logic on next request (delete-service waiter-url service-id-3) ;; allow syncer state to get updated (await-service-deletion-on-routers service-id-3) ;; outside fallback duration (is (= service-id-3 (kitchen-env-service-id))))))))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-valid-fallback-service-resolution (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) request-headers {:x-waiter-token token} fallback-period-secs 300 token-description-1 (-> (kitchen-request-headers :prefix "") (assoc :fallback-period-secs fallback-period-secs :idle-timeout-mins 1 :name (str service-name "-v1") :permitted-user "*" :run-as-user (retrieve-username) :run-as-user (retrieve-username) :token token :version "version-1")) token-description-2 (-> token-description-1 (assoc :name (str service-name "-v2") :version "version-2") (dissoc :cpus :mem :version)) token-description-3 (-> token-description-1 (assoc :cmd (kitchen-cmd (str "-p $PORT0 --start-up-sleep-ms 240000")) :grace-period-secs 300 :name (str service-name "-v3") :version "version-3"))] (assert-response-status (post-token waiter-url token-description-1) 200) (let [service-id-1 (retrieve-service-id waiter-url request-headers)] (with-service-cleanup service-id-1 (let [response-1 (make-request-with-debug-info request-headers #(make-request waiter-url "/hello" :headers %))] (assert-response-status response-1 200) (is (= service-id-1 (:service-id response-1)))) ;; allow every router to learn about the new instance (let [{:keys [cookies]} (make-request waiter-url "/waiter-auth")] (doseq [[_ router-url] (routers waiter-url)] (is (wait-for (fn [] (let [active-instances (-> (service-settings router-url service-id-1 :cookies cookies) (get-in [:instances :active-instances]))] (and (seq active-instances) (some :healthy? active-instances)))))))) (assert-response-status (post-token waiter-url token-description-2) 200) (assert-response-status (make-request waiter-url "/hello" :headers request-headers) 400) (assert-response-status (post-token waiter-url token-description-3) 200) (let [service-id-2 (retrieve-service-id waiter-url (assoc request-headers :x-waiter-fallback-period-secs 0))] (is (not= service-id-1 service-id-2)) (with-service-cleanup service-id-2 (let [response-2 (make-request-with-debug-info request-headers #(make-request waiter-url "/hello" :headers %))] (assert-response-status response-2 200) (is (= service-id-1 (:service-id response-2)))))))))))
true
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.token-request-test (:require [clj-time.core :as t] [clojure.data.json :as json] [clojure.string :as str] [clojure.test :refer :all] [clojure.tools.logging :as log] [clojure.walk :as walk] [plumbing.core :as pc] [waiter.headers :as headers] [waiter.service-description :as sd] [waiter.util.client-tools :refer :all] [waiter.util.date-utils :as du] [waiter.util.utils :as utils] [waiter.token :as token]) (:import (java.net URL) (org.joda.time DateTime))) (defn- waiter-url->token-url [waiter-url] (str HTTP-SCHEME waiter-url "/token")) (defn- retrieve-token-root [waiter-url] (-> (waiter-settings waiter-url) (get-in [:cluster-config :name]))) (defn- retrieve-token-cluster [waiter-url] (let [settings-json (waiter-settings waiter-url) default-cluster (get-in settings-json [:cluster-config :name]) cluster-calculator-config (-> settings-json (get-in [:token-config :cluster-calculator]) (update :kind keyword) (as-> $ (update-in $ [(:kind $) :factory-fn] symbol))) cluster-calculator (utils/create-component cluster-calculator-config :context {:default-cluster default-cluster})] (token/calculate-cluster cluster-calculator {:headers {"host" waiter-url}}))) (deftest ^:parallel ^:integration-fast test-update-token-cache-consistency (testing-using-waiter-url (let [service-id-prefix (rand-name "testhostname") token (rand-name) update-token-fn (fn [version] (let [{:keys [status]} (post-token waiter-url {:name service-id-prefix :cpus 1 :mem 1250 :version version :cmd "test command" :health-check-url "/ping" :permitted-user "*" :run-as-user (retrieve-username) :token token})] (is (= 200 status)))) validate-token-fn (fn [version num-threads num-iter] (parallelize-requests num-threads num-iter (fn [] (let [{:keys [body status]} (get-token waiter-url token)] (is (= 200 status)) (is (every? #(str/includes? (str body) (str %)) [service-id-prefix "1250" version "test command"])) (is (not-any? #(str/includes? (str body) (str %)) ["invalid"])))))) update-and-validate-token-fn (fn [version] (log/info "creating configuration using token" token "with version" version) (update-token-fn version) (log/info "asserting configuration for token" token "from routers (best-effort)") (validate-token-fn version 10 10)) version1 "123987132937213712" version2 "656760465406467480" version3 "678219671796032121"] (try (update-and-validate-token-fn version1) (update-and-validate-token-fn version2) (update-and-validate-token-fn version3) (finally (delete-token-and-assert waiter-url token)))))) (defn- name-from-service-description [waiter-url service-id] (get-in (service-settings waiter-url service-id) [:service-description :name])) (defn- service-id->source-tokens-entries [waiter-url service-id] (some-> (service-settings waiter-url service-id) :source-tokens walk/stringify-keys set)) (defn- token->etag [waiter-url token] (-> (get-token waiter-url token :query-params {"token" token}) :headers (get "etag"))) (defn- make-source-tokens-entries [waiter-url & tokens] (mapv (fn [token] {"token" token "version" (token->etag waiter-url token)}) tokens)) (defn- create-token-name [waiter-url service-id-prefix] (str service-id-prefix "." (subs waiter-url 0 (str/index-of waiter-url ":")))) (defn- list-tokens [waiter-url owner cookies query-params] (let [tokens-response (make-request waiter-url "/tokens" :cookies cookies :query-params query-params)] (log/debug "retrieved tokens for owner " owner ":" (:body tokens-response)) tokens-response)) (defn- parse-token-description "Parses a response as json and keywordizes the map." [response-body] (try (-> response-body str json/read-str pc/keywordize-map) (catch Exception _ (is false (str "Failed to parse token " response-body))))) (defmacro assert-token-response "Asserts the token data in the response" ([response token-root token-cluster service-id-prefix deleted] `(assert-token-response ~response ~token-root ~token-cluster ~service-id-prefix ~deleted true)) ([response token-root token-cluster service-id-prefix deleted include-metadata] `(let [body# (:body ~response) token-description# (parse-token-description body#)] (assert-response-status ~response 200) (when ~include-metadata (is (contains? token-description# :cluster)) (is (contains? token-description# :last-update-time)) (is (contains? token-description# :last-update-user)) (is (contains? token-description# :owner)) (is (contains? token-description# :root))) (is (= (cond-> {:health-check-url "/probe" :name ~service-id-prefix :owner (retrieve-username)} ~include-metadata (assoc :cluster ~token-cluster :last-update-user (retrieve-username) :root ~token-root) (and ~deleted ~include-metadata) (assoc :deleted ~deleted)) (dissoc token-description# :last-update-time :previous)))))) (deftest ^:parallel ^:integration-fast test-token-create-delete (testing-using-waiter-url (let [service-id-prefix (rand-name) token-prefix (create-token-name waiter-url service-id-prefix) {:keys [cookies]} (make-request waiter-url "/waiter-auth") num-tokens-to-create 10 tokens-to-create (map #(str "token" %1 "." token-prefix) (range num-tokens-to-create)) current-user (System/getProperty "user.name") token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (log/info "creating token without parameters should fail") (let [token (str service-id-prefix ".empty") {:keys [body] :as response} (post-token waiter-url {:token token})] (assert-response-status response 400) (is (str/includes? (str body) (str "No parameters provided for " token)) (str body))) (log/info "creating the tokens") (doseq [token tokens-to-create] (let [response (post-token waiter-url {:health-check-url "/check" :name service-id-prefix :token token})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully created " token))))) (testing "update without etags" (doseq [token tokens-to-create] (let [response (post-token waiter-url {:health-check-url "/health" :name service-id-prefix :token token})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully updated " token)))))) (testing "update with etags" (doseq [token tokens-to-create] (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (select-keys [:name]) (assoc :health-check-url "/probe" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")})] (assert-response-status response 200) (is (str/includes? (:body response) (str "Successfully updated " token)))))) (testing "update without changes" (doseq [token tokens-to-create] (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str (select-keys sd/token-user-editable-keys) walk/keywordize-keys (assoc :token token)) current-etag (get headers "etag") response (post-token waiter-url token-description :headers {"if-match" current-etag})] (assert-response-status response 200) (is (str/includes? (:body response) (str "No changes detected for " token))) (is (= current-etag (get-in response [:headers "etag"])))))) (testing "token retrieval - presence of etag header" (doseq [token tokens-to-create] (testing "via query parameters" (let [{:keys [headers] :as response} (get-token waiter-url token :cookies cookies :query-params {"include" "metadata" "token" token} :request-headers {}) actual-etag (get headers "etag")] (assert-response-status response 200) (let [token-description (-> response :body json/read-str)] (is (= {"health-check-url" "/check", "name" service-id-prefix} (-> token-description (get-in (repeat 2 "previous")) (select-keys sd/service-parameter-keys)))) (is (= {"health-check-url" "/health", "name" service-id-prefix} (-> token-description (get-in (repeat 1 "previous")) (select-keys sd/service-parameter-keys))))) (is actual-etag))) (testing "via x-waiter-token header" (let [{:keys [body headers] :as response} (get-token waiter-url token :cookies cookies) actual-etag (get headers "etag")] (assert-response-status response 200) (is actual-etag) (when actual-etag (let [convert-last-update-time (fn [{:strs [last-update-time] :as service-description}] (cond-> service-description last-update-time (assoc "last-update-time" (-> last-update-time du/str-to-date .getMillis)))) expected-etag (str "E-" (-> body json/read-str convert-last-update-time (dissoc "previous") sd/parameters->id))] (is (= expected-etag actual-etag)))))))) (log/info "ensuring tokens can be retrieved and listed on each router") (doseq [token tokens-to-create] (doseq [[_ router-url] (routers waiter-url)] (-> (get-token router-url token :cookies cookies :query-params {"include" "none"}) (assert-token-response token-root token-cluster service-id-prefix false false)) (-> (get-token router-url token :cookies cookies :query-params {"include" "metadata"}) (assert-token-response token-root token-cluster service-id-prefix false true)) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (some (fn [token-entry] (= token (get token-entry "token"))) tokens))))) (log/info "soft-deleting the tokens") (doseq [token tokens-to-create] (delete-token-and-assert waiter-url token :hard-delete false)) (log/info "ensuring tokens can no longer be retrieved on each router without include=deleted parameter") (doseq [token tokens-to-create] (doseq [[router-id router-url] (routers waiter-url)] (let [router-state (kv-store-state router-url :cookies cookies) cache-data (get-in router-state ["state" "cache" "data"]) token-cache-data (get cache-data (keyword token))] (is (nil? token-cache-data) (str token " data not nil (" token-cache-data ") on " router-id ", cache data =" cache-data))) (let [{:keys [body] :as response} (get-token router-url token :cookies cookies)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body))) (-> (get-token router-url token :cookies cookies :query-params {"include" ["deleted" "metadata"]}) (assert-token-response token-root token-cluster service-id-prefix true)) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (not-any? (fn [token-entry] (= token (get token-entry "token"))) tokens))) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) tokens (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) tokens)) (is (every? (fn [token-entry] (contains? token-entry "etag")) tokens)) (is (some (fn [token-entry] (= token (get token-entry "token"))) tokens))))) (log/info "hard-deleting the tokens") (doseq [token tokens-to-create] (delete-token-and-assert waiter-url token) (doseq [[_ router-url] (routers waiter-url)] (let [{:keys [body] :as response} (get-token router-url token :cookies cookies)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str {:body body :token token}))) (let [{:keys [body] :as tokens-response} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) token-entries (json/read-str body)] (assert-response-status tokens-response 200) (is (every? (fn [token-entry] (contains? token-entry "deleted")) token-entries)) (is (every? (fn [token-entry] (contains? token-entry "etag")) token-entries)))) ;; the token must be removed from at least one router (others may have temporarily cached values) (is (some (fn [router-url] (let [{:keys [body]} (list-tokens router-url current-user cookies {"include" ["deleted" "metadata"]}) token-entries (json/read-str body)] (not-any? (fn [token-entry] (= token (get token-entry "token"))) token-entries))) (vals (routers waiter-url))) (str token " entry found in list of deleted tokens on all routers"))) (log/info "ensuring tokens can no longer be retrieved on each router with include=deleted parameter after hard-delete") (doseq [token tokens-to-create] (doseq [[_ router-url] (routers waiter-url)] (let [{:keys [body] :as response} (get-token router-url token :cookies cookies :query-params {"include" "deleted"})] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body)))))))) (deftest ^:parallel ^:integration-fast ^:resource-heavy test-service-list-filtering (testing-using-waiter-url (let [service-name (rand-name) token-1 (create-token-name waiter-url (str "www." service-name ".t1")) token-2 (create-token-name waiter-url (str "www." service-name ".t2")) service-ids-atom (atom #{}) token->version->etag-atom (atom {}) all-tokens [token-1 token-2] all-version-suffixes ["v1" "v2" "v3"] router-id->router-url (routers waiter-url) {:keys [cookies]} (make-request waiter-url "/waiter-auth")] (doseq [version-suffix all-version-suffixes] (doseq [token all-tokens] (let [token-description (merge (kitchen-request-headers :prefix "") {:fallback-period-secs 0 :name (str service-name "." (hash token)) :token token :version (str service-name "." version-suffix)}) {:keys [headers] :as response} (post-token waiter-url token-description)] (assert-response-status response 200) (let [token-etag (get headers "etag")] (log/info token "->" token-etag) (is (-> token-etag str/blank? not)) (let [{:keys [service-id] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "/environment" :headers %))] (assert-response-status response 200) (is (-> service-id str/blank? not)) (swap! service-ids-atom conj service-id) ;; ensure all routers know about the service (doseq [[_ router-url] router-id->router-url] (let [response (make-request-with-debug-info {:x-waiter-token token} #(make-request router-url "/environment" :headers % :cookies cookies))] (assert-response-status response 200) (is (= service-id (:service-id response)))))) (swap! token->version->etag-atom assoc-in [token version-suffix] token-etag))))) (is (= (* (count all-tokens) (count all-version-suffixes)) (count @service-ids-atom)) (str {:service-ids @service-ids-atom})) (testing "star in token filter" (doseq [[_ router-url] (routers waiter-url)] (let [query-params {"token" (str "www." service-name ".t*")} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-tokens (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :token))) services)] (assert-response-status response 200) (is (= (count @service-ids-atom) (count service-tokens)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-tokens service-tokens}))))) (doseq [loop-token all-tokens] (doseq [[_ router-url] (routers waiter-url)] (let [query-params {"token" loop-token} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-tokens (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :token))) services)] (assert-response-status response 200) (is (= 3 (count service-tokens)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-tokens service-tokens})))) (doseq [version-suffix all-version-suffixes] (doseq [[_ router-url] (routers waiter-url)] (let [loop-etag (get-in @token->version->etag-atom [loop-token version-suffix]) query-params {"token-version" loop-etag} _ (log/info query-params) {:keys [body] :as response} (make-request router-url "/apps" :cookies cookies :query-params query-params) services (json/read-str body) service-token-versions (mapcat (fn [entry] (some->> entry walk/keywordize-keys :source-tokens flatten (map :version))) services)] (assert-response-status response 200) (is (= 1 (count service-token-versions)) (str {:query-params query-params :router-url router-url :service-count (count services) :service-token-versions service-token-versions})))))) (doseq [service-id @service-ids-atom] (delete-service waiter-url service-id))))) (defn- service-id->metadata-id [waiter-url service-id] (get-in (service-settings waiter-url service-id) [:service-description :metadata :id])) (deftest ^:parallel ^:integration-fast test-hostname-token (testing-using-waiter-url (let [service-id-prefix (rand-name) token-prefix (str "token-" (rand-int 3000000)) token (create-token-name waiter-url token-prefix) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (testing "hostname-token-test" (try (log/info "basic hostname as token test") (let [current-user (retrieve-username) service-description (assoc (kitchen-request-headers) :x-waiter-metric-group "waiter_test" :x-waiter-name token-prefix :x-waiter-permitted-user "*" :x-waiter-run-as-user current-user)] (testing "hostname-token-creation" (log/info "creating configuration using token" token) (let [{:keys [body status]} (post-token waiter-url {:health-check-url "/probe" :metric-group "waiter_test" :metadata {"id" token-prefix} :name service-id-prefix :token token})] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (let [token-response (get-token waiter-url token) response-body (json/read-str (:body token-response))] (is (contains? response-body "last-update-time")) (is (= {"cluster" token-cluster "health-check-url" "/probe" "last-update-user" (retrieve-username) "metadata" {"id" token-prefix} "metric-group" "waiter_test" "name" service-id-prefix "owner" (retrieve-username) "previous" {} "root" token-root} (dissoc response-body "last-update-time")))) (log/info "asserted retrieval of configuration for token" token)) (testing "support-for-token-with-x-waiter-headers" (log/info "request with hostname token" token "along with x-waiter headers") (let [request-headers (merge service-description {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id)))) (log/info "request with hostname token" token "along with x-waiter headers except permitted-user") (let [request-headers (merge (dissoc service-description :x-waiter-permitted-user) {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id))) ;; the above request hashes to a different service-id than the rest of the test, so we need to cleanup (delete-service waiter-url service-id)) (log/info "request with hostname token" token "along with x-waiter headers except run-as-user") (let [request-headers (merge (dissoc service-description :x-waiter-run-as-user) {"host" token}) path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (is (= token-prefix (service-id->metadata-id waiter-url service-id))) (testing "backend request headers" (let [{:keys [body] :as response} (make-request waiter-url "/request-info" :headers request-headers) {:strs [headers]} (json/read-str (str body))] (assert-response-status response 200) (is (contains? headers "x-waiter-auth-principal")) (is (contains? headers "x-waiter-authenticated-principal")))) ;; the above request hashes to a different service-id only when running as someone other than current-user ;; when the service-id is different, we need to cleanup (when (not= (System/getProperty "user.name") current-user) (delete-service waiter-url service-id))) (log/info "request with hostname token" token "along with missing x-waiter headers except cmd") (let [request-headers (merge (dissoc service-description :x-waiter-cmd) {"host" token}) path "/foo" {:keys [body] :as response} (make-request waiter-url path :headers request-headers)] (is (some #(str/includes? body %) ["cmd must be a non-empty string" "Invalid command or version"]) (str "response body was: " response)) (assert-response-status response 400)) (log/info "request with hostname token and x-waiter-debug token" token "along with x-waiter headers") (let [request-headers (merge service-description {:x-waiter-debug "true", "host" token}) path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= token-prefix (name-from-service-description waiter-url service-id))) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (is (= "waiter_test" (service-id->metric-group waiter-url service-id)) (str {:service-id service-id :token token})) (delete-service waiter-url service-id)))) (finally (delete-token-and-assert waiter-url token))))))) (deftest ^:parallel ^:integration-fast test-token-administer-unaffected-by-run-as-user-permissions (testing-using-waiter-url (let [service-id-prefix (rand-name) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (testing "token-administering" (testing "active-token" (let [last-update-time (System/currentTimeMillis) token (create-token-name waiter-url service-id-prefix)] (let [token-description {:health-check-url "/probe" :name service-id-prefix :owner (retrieve-username) :run-as-user (retrieve-username) :token token} response (post-token waiter-url token-description)] (assert-response-status response 200)) (testing "if-match-required during update" (let [token-description {:health-check-url "/probe-1" :last-update-time last-update-time :name service-id-prefix :owner (retrieve-username) :token token} {:keys [body] :as response} (post-token waiter-url token-description :headers {} :query-params {"update-mode" "admin"})] (assert-response-status response 400) (is (str/includes? body "Must specify if-match header for admin mode token updates")))) (try (testing "successful admin mode update" (log/info "creating configuration using token" token) (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (assoc :health-check-url "/probe-2" :last-update-time last-update-time :owner (retrieve-username) :run-as-user "i-do-not-exist-but-will-not-be-checked" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")} :query-params {"update-mode" "admin"})] (assert-response-status response 200) (log/info "created configuration using token" token)) (let [token-response (get-token waiter-url token) response-body (json/read-str (:body token-response))] (is (= {"cluster" token-cluster "health-check-url" "/probe-2" "last-update-time" (-> last-update-time DateTime. du/date-to-str) "last-update-user" (retrieve-username) "name" service-id-prefix, "owner" (retrieve-username) "root" token-root "run-as-user" "i-do-not-exist-but-will-not-be-checked"} (dissoc response-body "previous"))) (log/info "asserted retrieval of configuration for token" token))) (testing "update with invalid etag" (let [token-description {:health-check-url "/probe-3" :last-update-time last-update-time :name service-id-prefix :owner (retrieve-username) :run-as-user "foo-bar" :token token} {:keys [body] :as response} (post-token waiter-url token-description :headers {"host" token "if-match" "1010"} :query-params {"update-mode" "admin"})] (assert-response-status response 412) (is (str/includes? (str body) "Cannot modify stale token")))) (testing "hard-delete without etag" (let [{:keys [body] :as response} (make-request waiter-url "/token" :headers {"host" token} :method :delete :query-params {"hard-delete" true})] (assert-response-status response 400) (is (str/includes? (str body) "Must specify if-match header for token hard deletes")))) (testing "hard-delete with invalid etag" (let [{:keys [body] :as response} (make-request waiter-url "/token" :headers {"host" token "if-match" "1010"} :method :delete :query-params {"hard-delete" true})] (assert-response-status response 412) (is (str/includes? (str body) "Cannot modify stale token")))) (finally (delete-token-and-assert waiter-url token))))) (testing "deleted-token" (let [last-update-time (System/currentTimeMillis) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-description {:health-check-url "/probe-3" :name service-id-prefix :owner (retrieve-username) :token token} response (post-token waiter-url token-description :headers {"host" token})] (assert-response-status response 200)) (let [{:keys [body headers]} (get-token waiter-url token) token-description (-> body json/read-str walk/keywordize-keys (assoc :deleted true :health-check-url "/probe" :last-update-time last-update-time :run-as-user "foo-bar" :token token)) response (post-token waiter-url token-description :headers {"if-match" (get headers "etag")} :query-params {"update-mode" "admin"})] (assert-response-status response 200)) (log/info "created configuration using token" token) (let [{:keys [body] :as response} (get-token waiter-url token)] (assert-response-status response 404) (is (str/includes? (str body) "Couldn't find token") (str body))) (let [token-response (get-token waiter-url token :query-params {"include" ["deleted" "metadata"]}) response-body (json/read-str (:body token-response))] (is (= {"cluster" token-cluster "deleted" true "health-check-url" "/probe" "last-update-time" (-> last-update-time DateTime. du/date-to-str) "last-update-user" (retrieve-username) "name" service-id-prefix "owner" (retrieve-username) "root" token-root "run-as-user" "foo-bar"} (dissoc response-body "previous")))) (log/info "asserted retrieval of configuration for token" token) (finally (delete-token-and-assert waiter-url token))))))))) (deftest ^:parallel ^:integration-fast test-named-token (testing-using-waiter-url (log/info "basic named token test") (let [service-id-prefix (rand-name) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix))) (log/info "asserted retrieval of configuration for token" token) (log/info "making Waiter request with token" token "in header") (let [request-headers {:x-waiter-token token} path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id)))) (log/info "making Waiter request with token and x-waiter-debug token" token "in header") (let [request-headers {:x-waiter-debug "true", :x-waiter-token token} path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (delete-service waiter-url service-id)) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-star-run-as-user-token (testing-using-waiter-url (let [service-id-prefix (rand-name) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :run-as-user "*" :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix))) (log/info "asserted retrieval of configuration for token" token) (let [{:keys [body] :as token-response} (get-token waiter-url token) token-description (try (json/read-str (str body)) (catch Exception _ (is false (str "Failed to parse token" body))))] (assert-response-status token-response 200) (is (= "/status" (token-description "health-check-url"))) (is (= service-id-prefix (token-description "name"))) (is (= "*" (token-description "run-as-user"))) (is (System/getProperty "user.name") (token-description "owner"))) (log/info "making Waiter request with token" token "in header") (let [request-headers {:x-waiter-token token} path "/foo" response (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (= (retrieve-username) (:run-as-user (service-id->service-description waiter-url service-id))))) (log/info "making Waiter request with token and x-waiter-debug token" token "in header") (let [request-headers {:x-waiter-debug "true", :x-waiter-token token} path "/foo" {:keys [headers request-headers] :as response} (make-request waiter-url path :headers request-headers) service-id (retrieve-service-id waiter-url request-headers)] (assert-response-status response 200) (is (= (name-from-service-description waiter-url service-id) service-id-prefix)) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id))) (is (every? #(not (str/blank? (get headers %))) (concat required-response-headers (retrieve-debug-response-headers waiter-url))) (str headers)) (delete-service waiter-url service-id)) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast ^:explicit test-on-the-fly-to-token (testing-using-waiter-url (let [name-string (rand-name) {:keys [cookies] :as canary-response} (make-request-with-debug-info {:x-waiter-name name-string} #(make-kitchen-request waiter-url %)) service-id-1 (:service-id canary-response)] (with-service-cleanup service-id-1 (is (str/includes? service-id-1 name-string) (str "ERROR: App-name is missing " name-string)) (assert-service-on-all-routers waiter-url service-id-1 cookies) (is (nil? (service-id->source-tokens-entries waiter-url service-id-1))) (let [token (str PI:KEY:<KEY>END_PI) response (make-request-with-debug-info {:x-waiter-token token} #(make-request waiter-url "" :headers %)) service-id-2 (:service-id response)] (with-service-cleanup service-id-2 (assert-response-status response 200) (is service-id-2) (is (= service-id-1 service-id-2) "The on-the-fly and token-based service ids do not match") (assert-service-on-all-routers waiter-url service-id-1 cookies) (is (= #{(make-source-tokens-entries waiter-url token)} (service-id->source-tokens-entries waiter-url service-id-2))))))))) (deftest ^:parallel ^:integration-fast test-namespace-token (testing-using-waiter-url (log/info "basic token with namespace field test") (let [service-id-prefix (rand-name) target-user (retrieve-username) token (create-token-name waiter-url service-id-prefix)] (try (log/info "creating configuration using token" token) (let [token-definition (assoc (kitchen-request-headers :prefix "") :name service-id-prefix :namespace target-user :run-as-user target-user :token token) {:keys [body status]} (post-token waiter-url token-definition)] (when (not= 200 status) (log/info "error:" body) (is (not body)))) (log/info "created configuration using token" token) (log/info "retrieving configuration for token" token) (let [token-response (get-token waiter-url token) response-body (str (:body token-response))] (when (not (str/includes? response-body service-id-prefix)) (log/info response-body)) (assert-response-status token-response 200) (is (str/includes? response-body service-id-prefix)) (let [{:strs [namespace run-as-user] :as token-json} (try-parse-json response-body)] (is (= target-user run-as-user)) (is (= target-user namespace)))) (log/info "asserted retrieval of configuration for token" token) (finally (delete-token-and-assert waiter-url token)))) (testing "can't create token with bad namespace" (let [service-desc {:name (rand-name "notused") :cpus 1 :debug true :mem 1024 :version "universe b10452d0b0380ce61764543847085631ee3d7af9" :token "PI:PASSWORD:<PASSWORD>END_PI" :cmd "not-used" :permitted-user "*" :namespace "not-run-as-user" :run-as-user (retrieve-username) :health-check-url "/not-used"} response (post-token waiter-url service-desc)] (is (str/includes? (:body response) "Service namespace must either be omitted or match the run-as-user")) (assert-response-status response 400))))) (deftest ^:parallel ^:integration-fast test-bad-token (testing-using-waiter-url (let [common-headers {"x-waiter-cmd" "foo-bar" "x-waiter-cmd-type" "shell"}] (testing "ignore missing token when have service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "missing_token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400))) (testing "ignore invalid token when have service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "bad/token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400))) (testing "ignore invalid token when have invalid service description" (let [response (make-request waiter-url "/pathabc" :headers (assoc common-headers "host" "bad/token"))] (is (str/includes? (:body response) "Service description using waiter headers/token improperly configured")) (assert-response-status response 400)))) (testing "can't use missing token server" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token"})] (is (str/includes? (:body response) "Unable to identify service using waiter headers/token")) (assert-response-status response 400))) (testing "can't use invalid token server" (let [response (make-request waiter-url "/pathabc" :headers {"host" "bad/token"})] (is (str/includes? (:body response) "Unable to identify service using waiter headers/token")) (assert-response-status response 400))) (testing "can't use invalid token that's valid for zookeeper" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "badPI:PASSWORD:<PASSWORD>END_PI"})] (is (str/includes? (:body response) "Token not found: bad#token")) (assert-response-status response 400))) (testing "can't use invalid token" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "bad/token"})] (is (str/includes? (:body response) "Token not found: bad/token")) (assert-response-status response 400))) (testing "can't use invalid token with host set" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token" "X-Waiter-Token" "bad/token"})] (is (str/includes? (:body response) "Token not found: bad/token")) (assert-response-status response 400))) (testing "can't use missing token with host set" (let [response (make-request waiter-url "/pathabc" :headers {"host" "missing_token" "X-Waiter-Token" "missing_token"})] (is (str/includes? (:body response) "Token not found: missing_token")) (assert-response-status response 400))) (testing "can't use missing token" (let [response (make-request waiter-url "/pathabc" :headers {"X-Waiter-Token" "missing_token"})] (is (str/includes? (:body response) "Token not found: missing_token")) (assert-response-status response 400))) (testing "can't create bad token" (let [service-desc {:name (rand-name "notused") :cpus 1 :debug true :mem 1024 :version "universe b10452d0b0380ce61764543847085631ee3d7af9" :token "PI:PASSWORD:<PASSWORD>END_PI" :cmd "not-used" :permitted-user "*" :run-as-user (retrieve-username) :health-check-url "/not-used"} response (post-token waiter-url service-desc)] (is (str/includes? (:body response) "Token must match pattern")) (assert-response-status response 400))))) (deftest ^:parallel ^:integration-fast test-token-metadata (testing-using-waiter-url (let [token (rand-name) service-desc {:name token :cpus 1 :mem 100 :version "1" :cmd-type "shell" :token token :cmd "exit 0" :run-as-user (retrieve-username) :health-check-url "/not-used" :metadata {"a" "b", "c" "d"}} register-response (post-token waiter-url service-desc) {:keys [body]} (get-token waiter-url token)] (assert-response-status register-response 200) (is (= (:metadata service-desc) (get (json/read-str body) "metadata"))) (delete-token-and-assert waiter-url token) (delete-service waiter-url (:name service-desc))))) (deftest ^:parallel ^:integration-fast test-token-bad-metadata (testing-using-waiter-url (let [service-desc {"name" "token-bad-metadata" "cpus" 1 "mem" 100 "version" "1" "cmd-type" "shell" "token" (rand-PI:KEY:<KEY>END_PI) "cmd" "exit 0" "run-as-user" (retrieve-username) "health-check-url" "/not-used" "metadata" {"a" "b", "c" {"d" "e"}}} register-response (post-token waiter-url service-desc)] (is (= 400 (:status register-response)))))) (deftest ^:parallel ^:integration-fast test-token-bad-payload (testing-using-waiter-url (let [{:keys [status]} (make-request waiter-url "/token" :body "i'm bad at json" :headers {"host" "test-token"} :method :post)] (is (= 400 status))))) (deftest ^:parallel ^:integration-fast test-token-environment-variables (testing-using-waiter-url (let [token (rand-PI:KEY:<KEY>END_PI) binary (kitchen-cmd) token-response (post-token waiter-url {:cmd "$BINARY -p $PORT0" :cmd-type "shell" :version "does-not-matter" :name token :env {"BINARY" binary} :token token}) {:keys [service-id status] :as response} (make-request-with-debug-info {:x-waiter-token token} #(make-light-request waiter-url %)) {:keys [env] :as service-description} (response->service-description waiter-url response)] (is (= 200 (:status token-response)) (:body token-response)) (is (= 200 status)) (is (= {:BINARY binary} env) (str service-description)) (delete-token-and-assert waiter-url token) (delete-service waiter-url service-id)))) (deftest ^:parallel ^:integration-fast test-token-https-redirects (testing-using-waiter-url (let [token (PI:KEY:<KEY>END_PI) token-response (post-token waiter-url {:cmd (str (kitchen-cmd) " -p $PORT0") :cmd-type "shell" :https-redirect true :name token :version "does-not-matter" :token token})] (assert-response-status token-response 200) (testing "https redirects" (let [request-headers {:x-waiter-token token} url (URL. (str "http://" waiter-url)) endpoint "/request-info"] (testing "get request" (let [{:keys [headers] :as response} (make-kitchen-request waiter-url request-headers :method :get :path endpoint)] (assert-response-status response 301) (is (= (str "https://" (.getHost url) endpoint) (get headers "location"))) (is (str/starts-with? (str (get headers "server")) "waiter") (str "headers:" headers)))) (testing "post request" (let [{:keys [headers] :as response} (make-kitchen-request waiter-url request-headers :method :post :path endpoint)] (assert-response-status response 307) (is (= (str "https://" (.getHost url) endpoint) (get headers "location"))) (is (str/starts-with? (str (get headers "server")) "waiter") (str "headers:" headers)))))) (delete-token-and-assert waiter-url token)))) (defmacro run-token-param-support [waiter-url request-fn request-headers expected-env] `(let [response# (make-request-with-debug-info ~request-headers ~request-fn) service-description# (response->service-description ~waiter-url response#) service-id# (:service-id response#)] (is (= 200 (:status response#))) (is (= ~expected-env (:env service-description#)) (str service-description#)) (delete-service ~waiter-url service-id#) service-id#)) (deftest ^:parallel ^:integration-fast test-token-param-support (testing-using-waiter-url (let [token (PI:KEY:<KEY>END_PI) binary (kitchen-cmd) service-description {:allowed-params ["FAA" "FEE" "FII" "FOO" "FUU"] :cmd "$BINARY -p $PORT0" :cmd-type "shell" :env {"BINARY" binary "FEE" "FIE" "FOO" "BAR"} :name "test-token-param-support" :version "does-not-matter"} kitchen-request #(make-kitchen-request waiter-url % :path "/environment")] (try (let [token-description (assoc service-description :token token) token-response (post-token waiter-url token-description :query-params {"update-mode" "admin"})] (assert-response-status token-response 200) (let [request-headers {:x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured"))) (let [request-headers {:x-waiter-allowed-params "" :x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured")))) (let [token-description (-> service-description (dissoc :allowed-params) (assoc :token (str token ".1"))) token-response (post-token waiter-url token-description :query-params {"update-mode" "admin"})] (assert-response-status token-response 200) (let [request-headers {:x-waiter-param-my_variable "value-1" :x-waiter-token token} {:keys [body status]} (make-request-with-debug-info request-headers kitchen-request)] (is (= 400 status)) (is (str/includes? body "Some params cannot be configured")))) (let [service-ids (set [(run-token-param-support waiter-url kitchen-request {:x-waiter-token token} {:BINARY binary :FEE "FIE" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-allowed-params ["FEE" "FII" "FOO"] :x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-allowed-params "FEE,FOO" :x-waiter-param-fee "value-1p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "BAR"}) (run-token-param-support waiter-url kitchen-request {:x-waiter-param-fee "value-1p" :x-waiter-param-foo "value-2p" :x-waiter-token token} {:BINARY binary :FEE "value-1p" :FOO "value-2p"})])] (is (= 5 (count service-ids)) "Unique service-ids were not created!")) (finally (delete-token-and-assert waiter-url token) (delete-token-and-assert waiter-url (str token ".1"))))))) (deftest ^:parallel ^:integration-fast test-token-invalid-environment-variables (testing-using-waiter-url (let [{:keys [body status]} (post-token waiter-url {:env {"HOME" "/my/home"} :token (rand-name)})] (is (= 400 status)) (is (not (str/includes? body "clojure")) body) (is (str/includes? body "The following environment variable keys are reserved: HOME.") body)))) (deftest ^:parallel ^:integration-fast test-token-parameters-exceed-limits (testing-using-waiter-url (let [constraints (setting waiter-url [:service-description-constraints]) max-constraints (sd/extract-max-constraints constraints)] (is (seq max-constraints)) (doseq [[parameter max-constraint] max-constraints] (let [string-param? (contains? headers/params-with-str-value (name parameter)) param-value (if string-param? (apply str parameter " " (repeat max-constraint "x")) (inc max-constraint)) {:keys [body status]} (post-token waiter-url {parameter param-value :token (rand-name)})] (is (= 400 status)) (is (not (str/includes? body "clojure")) body) (is (every? #(str/includes? body %) ["The following fields exceed their allowed limits" (if string-param? (str (name parameter) " must be at most " max-constraint " characters") (str (name parameter) " is " param-value " but the max allowed is " max-constraint))]) body)))))) (deftest ^:parallel ^:integration-fast test-auto-run-as-requester-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) service-description (-> (kitchen-request-headers :prefix "") (assoc :name service-name :permitted-user "*") (dissoc :run-as-user)) waiter-port (.getPort (URL. (str "http://" waiter-url))) waiter-port (if (neg? waiter-port) 80 waiter-port) host-header (str token ":" waiter-port) has-x-waiter-consent? (partial some #(= (:name %) "x-waiter-consent")) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url)] (try (testing "token creation" (let [token-description (assoc service-description :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "token retrieval" (let [token-response (get-token waiter-url token) response-body (-> token-response (:body) (json/read-str) (pc/keywordize-map))] (is (nil? (get response-body :run-as-user))) (is (contains? response-body :last-update-time)) (is (= (assoc service-description :cluster token-cluster :last-update-user (retrieve-username) :owner (retrieve-username) :previous {} :root token-root) (dissoc response-body :last-update-time))))) (testing "expecting redirect" (let [{:keys [headers] :as response} (make-request waiter-url "/hello-world" :headers {"host" host-header})] (is (= (str "/waiter-consent/hello-world") (get headers "location"))) (assert-response-status response 303))) (testing "waiter-consent" (let [consent-path (str "/waiter-consent/hello-world") {:keys [body] :as response} (make-request waiter-url consent-path :headers {"host" host-header}) service-id (when-let [service-id-index (str/index-of body "name=\"service-id\"")] (when-let [value-index (str/index-of body "value=\"" service-id-index)] (when-let [end-index (str/index-of body "\"" (+ value-index 7))] (subs body (+ value-index 7) end-index))))] (is service-id) (assert-response-status response 200) (let [cookies-atom (atom nil)] (testing "approval of specific service" (let [{:keys [body cookies] :as response} (make-request waiter-url "/waiter-consent" :headers {"host" host-header "referer" (str "http://" host-header) "origin" (str "http://" host-header) "x-requested-with" "XMLHttpRequest"} :method :post :multipart {"mode" "service" "service-id" service-id})] (reset! cookies-atom cookies) (is (= "Added cookie x-waiter-consent" body)) ; x-waiter-consent should be emitted Waiter (is (has-x-waiter-consent? cookies)) (assert-response-status response 200))) (testing "auto run-as-user population on expected service-id" (let [service-id-atom (atom nil)] (try (let [expected-service-id service-id {:keys [body cookies service-id] :as response} (make-request-with-debug-info {"host" host-header} #(make-request waiter-url "/hello-world" :cookies @cookies-atom :headers %1)) {:keys [service-description]} (service-settings waiter-url service-id) {:keys [run-as-user permitted-user]} service-description] (reset! service-id-atom service-id) (is (= "Hello World" body)) ; x-waiter-consent should not be re-emitted Waiter (is (not (has-x-waiter-consent? cookies))) (is (= expected-service-id service-id)) (is (not (str/blank? permitted-user))) (is (= run-as-user permitted-user)) (assert-response-status response 200)) (finally (when @service-id-atom (delete-service waiter-url @service-id-atom)))))) (testing "token update" (let [updated-service-name (rand-name) token-description (assoc service-description :name updated-service-name :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "expecting redirect after token update" (let [{:keys [headers] :as response} (make-request waiter-url "/hello-world" :cookies @cookies-atom :headers {"host" host-header})] (is (= (str "/waiter-consent/hello-world") (get headers "location"))) (assert-response-status response 303))) (testing "approval of token" (let [{:keys [body cookies] :as response} (make-request waiter-url "/waiter-consent" :cookies @cookies-atom :headers {"host" host-header "referer" (str "http://" host-header) "origin" (str "http://" host-header) "x-requested-with" "XMLHttpRequest"} :method :post :multipart {"mode" "token"})] (reset! cookies-atom cookies) (is (= "Added cookie x-waiter-consent" body)) ; x-waiter-consent should be emitted Waiter (is (has-x-waiter-consent? cookies)) (assert-response-status response 200))) (testing "auto run-as-user population on approved token" (let [service-id-atom (atom nil)] (try (let [previous-service-id service-id {:keys [body cookies service-id] :as response} (make-request-with-debug-info {"host" host-header "x-waiter-fallback-period-secs" 0} #(make-request waiter-url "/hello-world" :cookies @cookies-atom :headers %1))] (reset! service-id-atom service-id) (is (= "Hello World" body)) ; x-waiter-consent should not be re-emitted Waiter (is (not (has-x-waiter-consent? cookies))) (is (not= previous-service-id service-id)) (assert-response-status response 200)) (finally (when @service-id-atom (delete-service waiter-url @service-id-atom))))))))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-authentication-disabled-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) current-user (retrieve-username) service-description (-> (kitchen-request-headers :prefix "") (assoc :authentication "disabled" :name service-name :permitted-user "*" :run-as-user current-user)) token-root (retrieve-token-root waiter-url) token-cluster (retrieve-token-cluster waiter-url) request-headers {:x-waiter-token token}] (try (testing "token creation" (let [token-description (assoc service-description :token token) response (post-token waiter-url token-description)] (assert-response-status response 200))) (testing "token retrieval" (let [token-response (get-token waiter-url token) response-body (-> token-response :body json/read-str pc/keywordize-map)] (is (contains? response-body :last-update-time)) (is (= (assoc service-description :authentication "disabled" :cluster token-cluster :last-update-user current-user :owner current-user :previous {} :root token-root) (dissoc response-body :last-update-time))))) (testing "successful request" (let [{:keys [body] :as response} (make-request waiter-url "/hello-world" :headers request-headers :disable-auth true)] (assert-response-status response 200) (is (= "Hello World" body)))) (testing "backend request headers" (let [{:keys [body] :as response} (make-request waiter-url "/request-info" :headers request-headers :disable-auth true) {:strs [headers]} (json/read-str (str body)) service-id (retrieve-service-id waiter-url (:request-headers response))] (assert-response-status response 200) (is (not (contains? headers "x-waiter-auth-principal"))) (is (not (contains? headers "x-waiter-authenticated-principal"))) (is (contains? headers "x-cid")) (delete-service waiter-url service-id))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-slow ^:resource-heavy test-service-fallback-support (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) scheduler-syncer-interval-secs (setting waiter-url [:scheduler-syncer-interval-secs]) fallback-period-secs 30 service-description-1 (-> (kitchen-request-headers :prefix "") (assoc :fallback-period-secs fallback-period-secs :name (str service-name "-v1") :permitted-user "*" :run-as-user (retrieve-username) :version "version-1")) request-headers {:x-waiter-token token} service-id-headers (assoc request-headers :x-waiter-fallback-period-secs 0) kitchen-env-service-id (fn [] (let [kitchen-response (make-request-with-debug-info request-headers #(make-request waiter-url "/environment" :headers %)) kitchen-service-id (-> kitchen-response :body (json/read-str) (get "WAITER_SERVICE_ID"))] (is (= kitchen-service-id (:service-id kitchen-response))) kitchen-service-id)) waiter-routers (routers waiter-url) {:keys [cookies]} (make-request waiter-url "/waiter-auth") await-healthy-service-on-routers (fn await-healthy-service-on-routers [service-id] (wait-for (fn [] (every? (fn [[_ router-url]] (-> (fallback-state router-url :cookies cookies) :state :healthy-service-ids set (contains? service-id))) waiter-routers)) :interval 1 :timeout (inc scheduler-syncer-interval-secs))) await-service-deletion-on-routers (fn await-service-deletion-on-routers [service-id] (wait-for (fn [] (every? (fn [[_ router-url]] (-> (service-state router-url service-id :cookies cookies) :state :service-maintainer-state :maintainer-chan-available false?)) waiter-routers)) :interval 1 :timeout (inc scheduler-syncer-interval-secs))) thread-sleep (fn [time-in-secs] (-> time-in-secs inc t/seconds t/in-millis Thread/sleep))] (try (let [token-description-1 (assoc service-description-1 :token token) post-response (post-token waiter-url token-description-1) _ (assert-response-status post-response 200) service-id-1 (retrieve-service-id waiter-url service-id-headers)] (testing "token response contains fallback and owner" (let [{:keys [body] :as response} (get-token waiter-url token :query-params {})] (assert-response-status response 200) (is (= (assoc service-description-1 :owner (retrieve-username)) (-> body json/read-str walk/keywordize-keys))))) (with-service-cleanup service-id-1 (is (= service-id-1 (kitchen-env-service-id))) ;; allow syncer state to get updated (await-healthy-service-on-routers service-id-1) (let [service-description-2 (assoc service-description-1 :name (str service-name "-v2") :version "version-2") token-description-2 (assoc service-description-2 :token token) post-response (post-token waiter-url token-description-2) _ (assert-response-status post-response 200) service-id-2 (retrieve-service-id waiter-url service-id-headers)] (with-service-cleanup service-id-2 (is (not= service-id-1 service-id-2)) ;; fallback to service-id-1 (is (= service-id-1 (retrieve-service-id waiter-url request-headers))) (is (= service-id-1 (kitchen-env-service-id))) (thread-sleep fallback-period-secs) ;; outside fallback duration (is (= service-id-2 (kitchen-env-service-id))) ;; allow syncer state to get updated (await-healthy-service-on-routers service-id-2) (let [sleep-duration (* 2 scheduler-syncer-interval-secs) service-description-3 (-> service-description-1 (assoc :name (str service-name "-v3") :version "version-3") (update "cmd" (fn [c] (str "sleep " sleep-duration " && " c)))) token-description-3 (assoc service-description-3 :token token) post-response (post-token waiter-url token-description-3) _ (assert-response-status post-response 200) service-id-3 (retrieve-service-id waiter-url service-id-headers)] (with-service-cleanup service-id-3 (is (not= service-id-1 service-id-3)) (is (not= service-id-2 service-id-3)) ;; fallback to service-id-2 (is (= service-id-2 (retrieve-service-id waiter-url request-headers))) (is (= service-id-2 (kitchen-env-service-id))) (thread-sleep fallback-period-secs) ;; outside fallback duration (is (= service-id-3 (kitchen-env-service-id))) ;; delete service-id-3 to trigger fallback logic on next request (delete-service waiter-url service-id-3) ;; allow syncer state to get updated (await-service-deletion-on-routers service-id-3) ;; outside fallback duration (is (= service-id-3 (kitchen-env-service-id))))))))) (finally (delete-token-and-assert waiter-url token)))))) (deftest ^:parallel ^:integration-fast test-valid-fallback-service-resolution (testing-using-waiter-url (let [service-name (rand-name) token (create-token-name waiter-url service-name) request-headers {:x-waiter-token token} fallback-period-secs 300 token-description-1 (-> (kitchen-request-headers :prefix "") (assoc :fallback-period-secs fallback-period-secs :idle-timeout-mins 1 :name (str service-name "-v1") :permitted-user "*" :run-as-user (retrieve-username) :run-as-user (retrieve-username) :token token :version "version-1")) token-description-2 (-> token-description-1 (assoc :name (str service-name "-v2") :version "version-2") (dissoc :cpus :mem :version)) token-description-3 (-> token-description-1 (assoc :cmd (kitchen-cmd (str "-p $PORT0 --start-up-sleep-ms 240000")) :grace-period-secs 300 :name (str service-name "-v3") :version "version-3"))] (assert-response-status (post-token waiter-url token-description-1) 200) (let [service-id-1 (retrieve-service-id waiter-url request-headers)] (with-service-cleanup service-id-1 (let [response-1 (make-request-with-debug-info request-headers #(make-request waiter-url "/hello" :headers %))] (assert-response-status response-1 200) (is (= service-id-1 (:service-id response-1)))) ;; allow every router to learn about the new instance (let [{:keys [cookies]} (make-request waiter-url "/waiter-auth")] (doseq [[_ router-url] (routers waiter-url)] (is (wait-for (fn [] (let [active-instances (-> (service-settings router-url service-id-1 :cookies cookies) (get-in [:instances :active-instances]))] (and (seq active-instances) (some :healthy? active-instances)))))))) (assert-response-status (post-token waiter-url token-description-2) 200) (assert-response-status (make-request waiter-url "/hello" :headers request-headers) 400) (assert-response-status (post-token waiter-url token-description-3) 200) (let [service-id-2 (retrieve-service-id waiter-url (assoc request-headers :x-waiter-fallback-period-secs 0))] (is (not= service-id-1 service-id-2)) (with-service-cleanup service-id-2 (let [response-2 (make-request-with-debug-info request-headers #(make-request waiter-url "/hello" :headers %))] (assert-response-status response-2 200) (is (= service-id-1 (:service-id response-2)))))))))))
[ { "context": "api]))\n\n;; -- Constants\n\n(def user-pwd-cache-key \"user-pwd\")\n(def db-ignored-keys [:services])\n\n;; -- Middle", "end": 564, "score": 0.9882134795188904, "start": 556, "tag": "KEY", "value": "user-pwd" }, { "context": "-----------------------\n;; See https://github.com/Day8/re-frame/wiki/Using-Handler-Middleware\n\n(defn che", "end": 710, "score": 0.9876611232757568, "start": 706, "tag": "USERNAME", "value": "Day8" }, { "context": "sign-in api/signin]\n (sign-in :user {:username (:user user-pwd) :password (:pwd user-pwd)}\n ", "end": 5942, "score": 0.9852231740951538, "start": 5936, "tag": "USERNAME", "value": "(:user" }, { "context": " api/signin]\n (sign-in :user {:username (:user user-pwd) :password (:pwd user-pwd)}\n :on", "end": 5947, "score": 0.5426560044288635, "start": 5943, "tag": "USERNAME", "value": "user" }, { "context": "ignin]\n (sign-in :user {:username (:user user-pwd) :password (:pwd user-pwd)}\n :on-suc", "end": 5951, "score": 0.8243433833122253, "start": 5948, "tag": "USERNAME", "value": "pwd" }, { "context": "ign-in :user {:username (:user user-pwd) :password (:pwd user-pwd)}\n :on-success (fn [user-re", "end": 5968, "score": 0.8724683523178101, "start": 5963, "tag": "PASSWORD", "value": "(:pwd" }, { "context": " :user {:username (:user user-pwd) :password (:pwd user-pwd)}\n :on-success (fn [user-res] (dispa", "end": 5977, "score": 0.9929683804512024, "start": 5969, "tag": "PASSWORD", "value": "user-pwd" }, { "context": "er-pwd]\n {:user {:username (:user user-pwd) :password (:pwd user-pwd)}})\n :context-", "end": 6785, "score": 0.9678512811660767, "start": 6779, "tag": "USERNAME", "value": "(:user" }, { "context": " {:user {:username (:user user-pwd) :password (:pwd user-pwd)}})\n :context-fn (fn [db user]", "end": 6811, "score": 0.8273730278015137, "start": 6806, "tag": "PASSWORD", "value": "(:pwd" }, { "context": "{:user {:username (:user user-pwd) :password (:pwd user-pwd)}})\n :context-fn (fn [db user] user)\n :", "end": 6820, "score": 0.8516416549682617, "start": 6812, "tag": "PASSWORD", "value": "user-pwd" } ]
src/trustroots/handlers.cljs
Trustroots/Trustroots-React-Native
32
(ns trustroots.handlers (:require [clojure.walk :refer [keywordize-keys]] [reagent.core :as reagent] [re-frame.core :refer [register-handler after dispatch dispatch-sync]] [schema.core :as s :include-macros true] [trustroots.domain.main :as main :refer [app-db schema]] [trustroots.helpers :refer [log info debug current-route]] [trustroots.db :as db] [trustroots.domain.auth :as auth] [trustroots.api :as api])) ;; -- Constants (def user-pwd-cache-key "user-pwd") (def db-ignored-keys [:services]) ;; -- Middleware ------------------------------------------------------------ ;; See https://github.com/Day8/re-frame/wiki/Using-Handler-Middleware (defn check-and-throw "throw an exception if db doesn't match the schema." [a-schema db] (when-let [problems (s/check a-schema db)] (info db) (info problems) (throw (js/Error. (str "Schema check failed: " problems))))) (def validate-schema-mw (if goog.DEBUG (after (partial check-and-throw schema)) [])) ;; Helpers ;; ------------------------------------------------------------------------ (defn register-handler-for [event-name handler-fn] "Simplify register handler calls by automatically registring middleware and by droping event name from event arguments" (register-handler event-name validate-schema-mw (fn [db evt] (debug (str "Dispatch " event-name)) (apply handler-fn (concat [db] (rest evt)))))) (defn add-in-progress-event-for [db event-key] db) (defn remove-in-progress-event-for [db event-key] db) (defn keyword-with-suffix [event-key suffix] (keyword (namespace event-key) (str (name event-key) suffix))) (defn register-api-call-handler [& {:keys [begin-api-event-key api-call init-fn params-fn success-fn error-fn context-fn]}] ;; optional (let [on-success-key (keyword-with-suffix begin-api-event-key "/success") on-error-key (keyword-with-suffix begin-api-event-key "/error")] (register-handler begin-api-event-key validate-schema-mw (fn [db evt] (debug (str "Dispatch " begin-api-event-key)) (let [init-db (if init-fn (apply init-fn (concat [db] (rest evt))) db) context (when context-fn (apply context-fn (concat [init-db] (rest evt)))) on-api-success (fn [api-response] (dispatch [on-success-key (:data api-response) context])) on-api-error (fn [error-response] (dispatch [on-error-key error-response context])) partial-api-call (partial api-call :on-success on-api-success :on-error on-api-error) params (flatten (vec (apply params-fn (concat [init-db] (rest evt)))))] (apply partial-api-call params) (add-in-progress-event-for init-db begin-api-event-key)))) (register-handler on-success-key validate-schema-mw (fn [db evt] (-> db (remove-in-progress-event-for begin-api-event-key) (#(apply success-fn (concat [%1] (rest evt))))))) (register-handler on-error-key validate-schema-mw (fn [db evt] (-> db (remove-in-progress-event-for begin-api-event-key) (#(apply error-fn (concat [%1] (rest evt))))))))) ;; Generic handlers ;; ------------------------------------------------------------- (register-handler-for :initialize-db (fn [_ _] (info app-db) (db/cache-load user-pwd-cache-key (fn [data] (dispatch [:auth/login data])) identity) app-db)) (register-handler-for :register-service (fn [db service-key service] (assoc-in db [:services service-key] service))) ;; Navigation handlers ;; ------------------------------------------------------------- (register-handler-for :set-page (fn [db value] (let [navigator (get-in db [:services :navigator])] (.push navigator (clj->js {:index (-> navigator (.getCurrentRoutes) (.-length)) :name (str value)}))) (assoc-in db [:page] value))) (register-handler-for :navigate/back (fn [db _] (let [navigator (get-in db [:services :navigator])] (if (< 1 (-> navigator (.getCurrentRoutes) (.-length))) (do (.pop navigator) (assoc-in db [:page] (current-route navigator))) db)))) ;; DB handlers ;; ------------------------------------------------------------- (register-handler-for :set-db (fn [db new-state] (if-let [problems (s/check schema new-state)] (do (log problems) db) new-state))) (register-handler-for :storage-error (fn [db err-event error] (log error) ;; currently do nothing error handling should be here db)) (register-handler-for :load-db (fn [db _] (db/load #(dispatch [:set-db %1]) #(dispatch [:storage-error :load-db %1])) db)) (register-handler-for :save-db (fn [db _] (println db) (let [db-filtered (apply dissoc db db-ignored-keys)] (db/save! db-filtered #(dispatch [:storage-error :save-db %1])) db))) ;; db handlers ;; ------------------------------------------------------------- ;; (register-handler-for ;; :logout ;; (fn [db _] ;; (api/signout ;; :on-success (fn [])) ;; (auth/set-user! db nil) ;; (dispatch [:save-db]) ;; (dispatch [:set-page :login]) ;; (-> app-db ;; (assoc :services (:services db))))) ;; we need to preserve the instance of Navigator and Toaster (register-handler-for :login (fn [db user-pwd] (let [sign-in api/signin] (sign-in :user {:username (:user user-pwd) :password (:pwd user-pwd)} :on-success (fn [user-res] (dispatch [:auth-success (:data user-res)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:auth-fail]) :network-error (dispatch [:set-offline true]) (dispatch [:unknown-error]))) (-> db (auth/set-in-progress! true) (auth/set-user! nil) (auth/set-error! nil))))) (register-api-call-handler :begin-api-event-key :auth/login :api-call api/signin :init-fn (fn [db user] (-> db (auth/set-user! nil) (auth/set-error! nil))) :params-fn (fn [db user-pwd] {:user {:username (:user user-pwd) :password (:pwd user-pwd)}}) :context-fn (fn [db user] user) :success-fn (fn [db user context] (db/cache! user-pwd-cache-key context) (when (= (:page db) :login) (dispatch [:set-page :inbox])) (-> db (auth/set-user! user))) :error-fn (fn [db] (-> db (auth/set-error! "Authentication failed")))) (register-api-call-handler :begin-api-event-key :auth/logout :api-call api/signout :params-fn (fn [db _] {}) :success-fn (fn [db _ _] (dispatch [:save-db]) (db/cache! user-pwd-cache-key nil) (dispatch [:set-page :login]) (-> app-db (assoc :services (:services db)))) ;; we need to preserve the instance of Navigator and Toaster :error-fn (fn [db] (-> db (auth/set-error! "Logout failed")))) (register-handler-for :auth-fail (fn [db error] (-> db (auth/set-in-progress! false) (auth/set-user! nil) (auth/set-error! "Authentication failed")))) (register-handler-for :auth-success (fn [db user] (dispatch [:save-db]) (when (= (:page db) "login") (dispatch [:set-page :inbox])) (-> db (auth/set-in-progress! false) (auth/set-user! user) (auth/set-error! nil)))) (register-handler-for :set-offline (fn [db mode] (when-let [toaster (get-in db [:services :toaster])] (log toaster) (toaster "You are currently offline" 5000)) (assoc db :network-state mode))) ;; get inbox (register-handler-for :inbox/fetch (fn [db user-pwd] (let [get-messages api/inbox] (get-messages :on-success (fn [data] (dispatch [:inbox/fetch-success (:data data)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch :inbox/fetch-fail)) (dispatch [:unknown-error]))) db))) (register-handler-for :inbox/fetch-success (fn [db data] (assoc db :message/inbox data))) (register-handler-for :inbox/fetch-fail (fn [db data] db)) ;; Get one message thread (=converstion) ;; ---------------------- (register-handler-for :conversation/fetch (fn [db user-id] (let [get-messages (partial api/conversation-with user-id)] (get-messages :on-success (fn [data] (dispatch [:conversation/fetch-success user-id (:data data)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch [:conversation/fetch-fail user-id])) (dispatch [:unknown-error]))) db))) (register-handler-for :conversation/fetch-success (fn [db user-id data] (assoc-in db [:message/conversation-with user-id] data))) (register-handler-for :conversation/fetch-fail (fn [db user-id] db)) (register-handler-for :show/conversation-with (fn [db user-id] (dispatch [:conversation/fetch user-id]) (dispatch [:set-page :conversation]) (assoc db :message/current-conversation user-id))) ;; Send message ;; ------------ (register-handler-for :flush (fn [db _] (reagent/flush) db)) (register-handler-for :message/update-draft-with (fn [db to-user-id content] (dispatch [:flush]) (assoc-in db [:message/draft-with to-user-id] content))) (register-handler-for :message/send-to (fn [db to-user-id] (let [content (get-in db [:message/draft-with to-user-id]) send-message (partial api/send-message-to to-user-id content)] (send-message :on-success (fn [data] (dispatch [:message/send-to-success to-user-id (:data data)])) :on-error (fn [error] (log error) (condp = (:type error) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch [:message/send-to-fail to-user-id content])) (dispatch [:unknown-error])))) (assoc-in db [:message/draft-with to-user-id] "")))) (register-handler-for :message/send-to-success (fn [db to-user-id message] (update-in db [:message/conversation-with to-user-id] #(conj %1 message)))) (register-handler-for :message/send-to-fail (fn [db user-id content] db)) ;; Hardware related event listeners ;; ---------------------------------- (def react-native (js/require "react-native")) (defn check-network-state [] (-> react-native (.-NetInfo) (.-isConnected) (.fetch) (.done #(dispatch [:set-offline (not %)])))) (register-handler-for :initialize-hardware (fn [db _] ;; register event listeners ;; check once ;; Currently any way to check NetInfo does not work ;; This is left here as warning ;;(js/setTimeout ;; check-nework-state ;; 15000) db)) (comment (re-frame.core/dispatch [:set-page :inbox]) (re-frame.core/dispatch [:inbox/fetch]) (re-frame.core/subscribe [:inbox/get]))
48951
(ns trustroots.handlers (:require [clojure.walk :refer [keywordize-keys]] [reagent.core :as reagent] [re-frame.core :refer [register-handler after dispatch dispatch-sync]] [schema.core :as s :include-macros true] [trustroots.domain.main :as main :refer [app-db schema]] [trustroots.helpers :refer [log info debug current-route]] [trustroots.db :as db] [trustroots.domain.auth :as auth] [trustroots.api :as api])) ;; -- Constants (def user-pwd-cache-key "<KEY>") (def db-ignored-keys [:services]) ;; -- Middleware ------------------------------------------------------------ ;; See https://github.com/Day8/re-frame/wiki/Using-Handler-Middleware (defn check-and-throw "throw an exception if db doesn't match the schema." [a-schema db] (when-let [problems (s/check a-schema db)] (info db) (info problems) (throw (js/Error. (str "Schema check failed: " problems))))) (def validate-schema-mw (if goog.DEBUG (after (partial check-and-throw schema)) [])) ;; Helpers ;; ------------------------------------------------------------------------ (defn register-handler-for [event-name handler-fn] "Simplify register handler calls by automatically registring middleware and by droping event name from event arguments" (register-handler event-name validate-schema-mw (fn [db evt] (debug (str "Dispatch " event-name)) (apply handler-fn (concat [db] (rest evt)))))) (defn add-in-progress-event-for [db event-key] db) (defn remove-in-progress-event-for [db event-key] db) (defn keyword-with-suffix [event-key suffix] (keyword (namespace event-key) (str (name event-key) suffix))) (defn register-api-call-handler [& {:keys [begin-api-event-key api-call init-fn params-fn success-fn error-fn context-fn]}] ;; optional (let [on-success-key (keyword-with-suffix begin-api-event-key "/success") on-error-key (keyword-with-suffix begin-api-event-key "/error")] (register-handler begin-api-event-key validate-schema-mw (fn [db evt] (debug (str "Dispatch " begin-api-event-key)) (let [init-db (if init-fn (apply init-fn (concat [db] (rest evt))) db) context (when context-fn (apply context-fn (concat [init-db] (rest evt)))) on-api-success (fn [api-response] (dispatch [on-success-key (:data api-response) context])) on-api-error (fn [error-response] (dispatch [on-error-key error-response context])) partial-api-call (partial api-call :on-success on-api-success :on-error on-api-error) params (flatten (vec (apply params-fn (concat [init-db] (rest evt)))))] (apply partial-api-call params) (add-in-progress-event-for init-db begin-api-event-key)))) (register-handler on-success-key validate-schema-mw (fn [db evt] (-> db (remove-in-progress-event-for begin-api-event-key) (#(apply success-fn (concat [%1] (rest evt))))))) (register-handler on-error-key validate-schema-mw (fn [db evt] (-> db (remove-in-progress-event-for begin-api-event-key) (#(apply error-fn (concat [%1] (rest evt))))))))) ;; Generic handlers ;; ------------------------------------------------------------- (register-handler-for :initialize-db (fn [_ _] (info app-db) (db/cache-load user-pwd-cache-key (fn [data] (dispatch [:auth/login data])) identity) app-db)) (register-handler-for :register-service (fn [db service-key service] (assoc-in db [:services service-key] service))) ;; Navigation handlers ;; ------------------------------------------------------------- (register-handler-for :set-page (fn [db value] (let [navigator (get-in db [:services :navigator])] (.push navigator (clj->js {:index (-> navigator (.getCurrentRoutes) (.-length)) :name (str value)}))) (assoc-in db [:page] value))) (register-handler-for :navigate/back (fn [db _] (let [navigator (get-in db [:services :navigator])] (if (< 1 (-> navigator (.getCurrentRoutes) (.-length))) (do (.pop navigator) (assoc-in db [:page] (current-route navigator))) db)))) ;; DB handlers ;; ------------------------------------------------------------- (register-handler-for :set-db (fn [db new-state] (if-let [problems (s/check schema new-state)] (do (log problems) db) new-state))) (register-handler-for :storage-error (fn [db err-event error] (log error) ;; currently do nothing error handling should be here db)) (register-handler-for :load-db (fn [db _] (db/load #(dispatch [:set-db %1]) #(dispatch [:storage-error :load-db %1])) db)) (register-handler-for :save-db (fn [db _] (println db) (let [db-filtered (apply dissoc db db-ignored-keys)] (db/save! db-filtered #(dispatch [:storage-error :save-db %1])) db))) ;; db handlers ;; ------------------------------------------------------------- ;; (register-handler-for ;; :logout ;; (fn [db _] ;; (api/signout ;; :on-success (fn [])) ;; (auth/set-user! db nil) ;; (dispatch [:save-db]) ;; (dispatch [:set-page :login]) ;; (-> app-db ;; (assoc :services (:services db))))) ;; we need to preserve the instance of Navigator and Toaster (register-handler-for :login (fn [db user-pwd] (let [sign-in api/signin] (sign-in :user {:username (:user user-pwd) :password <PASSWORD> <KEY>)} :on-success (fn [user-res] (dispatch [:auth-success (:data user-res)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:auth-fail]) :network-error (dispatch [:set-offline true]) (dispatch [:unknown-error]))) (-> db (auth/set-in-progress! true) (auth/set-user! nil) (auth/set-error! nil))))) (register-api-call-handler :begin-api-event-key :auth/login :api-call api/signin :init-fn (fn [db user] (-> db (auth/set-user! nil) (auth/set-error! nil))) :params-fn (fn [db user-pwd] {:user {:username (:user user-pwd) :password <PASSWORD> <KEY>)}}) :context-fn (fn [db user] user) :success-fn (fn [db user context] (db/cache! user-pwd-cache-key context) (when (= (:page db) :login) (dispatch [:set-page :inbox])) (-> db (auth/set-user! user))) :error-fn (fn [db] (-> db (auth/set-error! "Authentication failed")))) (register-api-call-handler :begin-api-event-key :auth/logout :api-call api/signout :params-fn (fn [db _] {}) :success-fn (fn [db _ _] (dispatch [:save-db]) (db/cache! user-pwd-cache-key nil) (dispatch [:set-page :login]) (-> app-db (assoc :services (:services db)))) ;; we need to preserve the instance of Navigator and Toaster :error-fn (fn [db] (-> db (auth/set-error! "Logout failed")))) (register-handler-for :auth-fail (fn [db error] (-> db (auth/set-in-progress! false) (auth/set-user! nil) (auth/set-error! "Authentication failed")))) (register-handler-for :auth-success (fn [db user] (dispatch [:save-db]) (when (= (:page db) "login") (dispatch [:set-page :inbox])) (-> db (auth/set-in-progress! false) (auth/set-user! user) (auth/set-error! nil)))) (register-handler-for :set-offline (fn [db mode] (when-let [toaster (get-in db [:services :toaster])] (log toaster) (toaster "You are currently offline" 5000)) (assoc db :network-state mode))) ;; get inbox (register-handler-for :inbox/fetch (fn [db user-pwd] (let [get-messages api/inbox] (get-messages :on-success (fn [data] (dispatch [:inbox/fetch-success (:data data)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch :inbox/fetch-fail)) (dispatch [:unknown-error]))) db))) (register-handler-for :inbox/fetch-success (fn [db data] (assoc db :message/inbox data))) (register-handler-for :inbox/fetch-fail (fn [db data] db)) ;; Get one message thread (=converstion) ;; ---------------------- (register-handler-for :conversation/fetch (fn [db user-id] (let [get-messages (partial api/conversation-with user-id)] (get-messages :on-success (fn [data] (dispatch [:conversation/fetch-success user-id (:data data)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch [:conversation/fetch-fail user-id])) (dispatch [:unknown-error]))) db))) (register-handler-for :conversation/fetch-success (fn [db user-id data] (assoc-in db [:message/conversation-with user-id] data))) (register-handler-for :conversation/fetch-fail (fn [db user-id] db)) (register-handler-for :show/conversation-with (fn [db user-id] (dispatch [:conversation/fetch user-id]) (dispatch [:set-page :conversation]) (assoc db :message/current-conversation user-id))) ;; Send message ;; ------------ (register-handler-for :flush (fn [db _] (reagent/flush) db)) (register-handler-for :message/update-draft-with (fn [db to-user-id content] (dispatch [:flush]) (assoc-in db [:message/draft-with to-user-id] content))) (register-handler-for :message/send-to (fn [db to-user-id] (let [content (get-in db [:message/draft-with to-user-id]) send-message (partial api/send-message-to to-user-id content)] (send-message :on-success (fn [data] (dispatch [:message/send-to-success to-user-id (:data data)])) :on-error (fn [error] (log error) (condp = (:type error) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch [:message/send-to-fail to-user-id content])) (dispatch [:unknown-error])))) (assoc-in db [:message/draft-with to-user-id] "")))) (register-handler-for :message/send-to-success (fn [db to-user-id message] (update-in db [:message/conversation-with to-user-id] #(conj %1 message)))) (register-handler-for :message/send-to-fail (fn [db user-id content] db)) ;; Hardware related event listeners ;; ---------------------------------- (def react-native (js/require "react-native")) (defn check-network-state [] (-> react-native (.-NetInfo) (.-isConnected) (.fetch) (.done #(dispatch [:set-offline (not %)])))) (register-handler-for :initialize-hardware (fn [db _] ;; register event listeners ;; check once ;; Currently any way to check NetInfo does not work ;; This is left here as warning ;;(js/setTimeout ;; check-nework-state ;; 15000) db)) (comment (re-frame.core/dispatch [:set-page :inbox]) (re-frame.core/dispatch [:inbox/fetch]) (re-frame.core/subscribe [:inbox/get]))
true
(ns trustroots.handlers (:require [clojure.walk :refer [keywordize-keys]] [reagent.core :as reagent] [re-frame.core :refer [register-handler after dispatch dispatch-sync]] [schema.core :as s :include-macros true] [trustroots.domain.main :as main :refer [app-db schema]] [trustroots.helpers :refer [log info debug current-route]] [trustroots.db :as db] [trustroots.domain.auth :as auth] [trustroots.api :as api])) ;; -- Constants (def user-pwd-cache-key "PI:KEY:<KEY>END_PI") (def db-ignored-keys [:services]) ;; -- Middleware ------------------------------------------------------------ ;; See https://github.com/Day8/re-frame/wiki/Using-Handler-Middleware (defn check-and-throw "throw an exception if db doesn't match the schema." [a-schema db] (when-let [problems (s/check a-schema db)] (info db) (info problems) (throw (js/Error. (str "Schema check failed: " problems))))) (def validate-schema-mw (if goog.DEBUG (after (partial check-and-throw schema)) [])) ;; Helpers ;; ------------------------------------------------------------------------ (defn register-handler-for [event-name handler-fn] "Simplify register handler calls by automatically registring middleware and by droping event name from event arguments" (register-handler event-name validate-schema-mw (fn [db evt] (debug (str "Dispatch " event-name)) (apply handler-fn (concat [db] (rest evt)))))) (defn add-in-progress-event-for [db event-key] db) (defn remove-in-progress-event-for [db event-key] db) (defn keyword-with-suffix [event-key suffix] (keyword (namespace event-key) (str (name event-key) suffix))) (defn register-api-call-handler [& {:keys [begin-api-event-key api-call init-fn params-fn success-fn error-fn context-fn]}] ;; optional (let [on-success-key (keyword-with-suffix begin-api-event-key "/success") on-error-key (keyword-with-suffix begin-api-event-key "/error")] (register-handler begin-api-event-key validate-schema-mw (fn [db evt] (debug (str "Dispatch " begin-api-event-key)) (let [init-db (if init-fn (apply init-fn (concat [db] (rest evt))) db) context (when context-fn (apply context-fn (concat [init-db] (rest evt)))) on-api-success (fn [api-response] (dispatch [on-success-key (:data api-response) context])) on-api-error (fn [error-response] (dispatch [on-error-key error-response context])) partial-api-call (partial api-call :on-success on-api-success :on-error on-api-error) params (flatten (vec (apply params-fn (concat [init-db] (rest evt)))))] (apply partial-api-call params) (add-in-progress-event-for init-db begin-api-event-key)))) (register-handler on-success-key validate-schema-mw (fn [db evt] (-> db (remove-in-progress-event-for begin-api-event-key) (#(apply success-fn (concat [%1] (rest evt))))))) (register-handler on-error-key validate-schema-mw (fn [db evt] (-> db (remove-in-progress-event-for begin-api-event-key) (#(apply error-fn (concat [%1] (rest evt))))))))) ;; Generic handlers ;; ------------------------------------------------------------- (register-handler-for :initialize-db (fn [_ _] (info app-db) (db/cache-load user-pwd-cache-key (fn [data] (dispatch [:auth/login data])) identity) app-db)) (register-handler-for :register-service (fn [db service-key service] (assoc-in db [:services service-key] service))) ;; Navigation handlers ;; ------------------------------------------------------------- (register-handler-for :set-page (fn [db value] (let [navigator (get-in db [:services :navigator])] (.push navigator (clj->js {:index (-> navigator (.getCurrentRoutes) (.-length)) :name (str value)}))) (assoc-in db [:page] value))) (register-handler-for :navigate/back (fn [db _] (let [navigator (get-in db [:services :navigator])] (if (< 1 (-> navigator (.getCurrentRoutes) (.-length))) (do (.pop navigator) (assoc-in db [:page] (current-route navigator))) db)))) ;; DB handlers ;; ------------------------------------------------------------- (register-handler-for :set-db (fn [db new-state] (if-let [problems (s/check schema new-state)] (do (log problems) db) new-state))) (register-handler-for :storage-error (fn [db err-event error] (log error) ;; currently do nothing error handling should be here db)) (register-handler-for :load-db (fn [db _] (db/load #(dispatch [:set-db %1]) #(dispatch [:storage-error :load-db %1])) db)) (register-handler-for :save-db (fn [db _] (println db) (let [db-filtered (apply dissoc db db-ignored-keys)] (db/save! db-filtered #(dispatch [:storage-error :save-db %1])) db))) ;; db handlers ;; ------------------------------------------------------------- ;; (register-handler-for ;; :logout ;; (fn [db _] ;; (api/signout ;; :on-success (fn [])) ;; (auth/set-user! db nil) ;; (dispatch [:save-db]) ;; (dispatch [:set-page :login]) ;; (-> app-db ;; (assoc :services (:services db))))) ;; we need to preserve the instance of Navigator and Toaster (register-handler-for :login (fn [db user-pwd] (let [sign-in api/signin] (sign-in :user {:username (:user user-pwd) :password PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<KEY>END_PI)} :on-success (fn [user-res] (dispatch [:auth-success (:data user-res)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:auth-fail]) :network-error (dispatch [:set-offline true]) (dispatch [:unknown-error]))) (-> db (auth/set-in-progress! true) (auth/set-user! nil) (auth/set-error! nil))))) (register-api-call-handler :begin-api-event-key :auth/login :api-call api/signin :init-fn (fn [db user] (-> db (auth/set-user! nil) (auth/set-error! nil))) :params-fn (fn [db user-pwd] {:user {:username (:user user-pwd) :password PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<KEY>END_PI)}}) :context-fn (fn [db user] user) :success-fn (fn [db user context] (db/cache! user-pwd-cache-key context) (when (= (:page db) :login) (dispatch [:set-page :inbox])) (-> db (auth/set-user! user))) :error-fn (fn [db] (-> db (auth/set-error! "Authentication failed")))) (register-api-call-handler :begin-api-event-key :auth/logout :api-call api/signout :params-fn (fn [db _] {}) :success-fn (fn [db _ _] (dispatch [:save-db]) (db/cache! user-pwd-cache-key nil) (dispatch [:set-page :login]) (-> app-db (assoc :services (:services db)))) ;; we need to preserve the instance of Navigator and Toaster :error-fn (fn [db] (-> db (auth/set-error! "Logout failed")))) (register-handler-for :auth-fail (fn [db error] (-> db (auth/set-in-progress! false) (auth/set-user! nil) (auth/set-error! "Authentication failed")))) (register-handler-for :auth-success (fn [db user] (dispatch [:save-db]) (when (= (:page db) "login") (dispatch [:set-page :inbox])) (-> db (auth/set-in-progress! false) (auth/set-user! user) (auth/set-error! nil)))) (register-handler-for :set-offline (fn [db mode] (when-let [toaster (get-in db [:services :toaster])] (log toaster) (toaster "You are currently offline" 5000)) (assoc db :network-state mode))) ;; get inbox (register-handler-for :inbox/fetch (fn [db user-pwd] (let [get-messages api/inbox] (get-messages :on-success (fn [data] (dispatch [:inbox/fetch-success (:data data)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch :inbox/fetch-fail)) (dispatch [:unknown-error]))) db))) (register-handler-for :inbox/fetch-success (fn [db data] (assoc db :message/inbox data))) (register-handler-for :inbox/fetch-fail (fn [db data] db)) ;; Get one message thread (=converstion) ;; ---------------------- (register-handler-for :conversation/fetch (fn [db user-id] (let [get-messages (partial api/conversation-with user-id)] (get-messages :on-success (fn [data] (dispatch [:conversation/fetch-success user-id (:data data)])) :on-error #(condp = (:type %) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch [:conversation/fetch-fail user-id])) (dispatch [:unknown-error]))) db))) (register-handler-for :conversation/fetch-success (fn [db user-id data] (assoc-in db [:message/conversation-with user-id] data))) (register-handler-for :conversation/fetch-fail (fn [db user-id] db)) (register-handler-for :show/conversation-with (fn [db user-id] (dispatch [:conversation/fetch user-id]) (dispatch [:set-page :conversation]) (assoc db :message/current-conversation user-id))) ;; Send message ;; ------------ (register-handler-for :flush (fn [db _] (reagent/flush) db)) (register-handler-for :message/update-draft-with (fn [db to-user-id content] (dispatch [:flush]) (assoc-in db [:message/draft-with to-user-id] content))) (register-handler-for :message/send-to (fn [db to-user-id] (let [content (get-in db [:message/draft-with to-user-id]) send-message (partial api/send-message-to to-user-id content)] (send-message :on-success (fn [data] (dispatch [:message/send-to-success to-user-id (:data data)])) :on-error (fn [error] (log error) (condp = (:type error) :invalid-credentials (dispatch [:logout]) :network-error (do (dispatch [:set-offline true]) (dispatch [:message/send-to-fail to-user-id content])) (dispatch [:unknown-error])))) (assoc-in db [:message/draft-with to-user-id] "")))) (register-handler-for :message/send-to-success (fn [db to-user-id message] (update-in db [:message/conversation-with to-user-id] #(conj %1 message)))) (register-handler-for :message/send-to-fail (fn [db user-id content] db)) ;; Hardware related event listeners ;; ---------------------------------- (def react-native (js/require "react-native")) (defn check-network-state [] (-> react-native (.-NetInfo) (.-isConnected) (.fetch) (.done #(dispatch [:set-offline (not %)])))) (register-handler-for :initialize-hardware (fn [db _] ;; register event listeners ;; check once ;; Currently any way to check NetInfo does not work ;; This is left here as warning ;;(js/setTimeout ;; check-nework-state ;; 15000) db)) (comment (re-frame.core/dispatch [:set-page :inbox]) (re-frame.core/dispatch [:inbox/fetch]) (re-frame.core/subscribe [:inbox/get]))
[ { "context": " primes using a Sieve of Eratosthenes algorithm by Richard Bird.\"\n []\n (letfn [(mltpls [p] (let [p2 (* 2 p)]\n ", "end": 118, "score": 0.9997400641441345, "start": 106, "tag": "NAME", "value": "Richard Bird" } ]
Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-9.clj
LaudateCorpus1/RosettaCodeData
1
(defn primes-Bird "Computes the unbounded sequence of primes using a Sieve of Eratosthenes algorithm by Richard Bird." [] (letfn [(mltpls [p] (let [p2 (* 2 p)] (letfn [(nxtmltpl [c] (cons c (lazy-seq (nxtmltpl (+ c p2)))))] (nxtmltpl (* p p))))), (allmtpls [ps] (cons (mltpls (first ps)) (lazy-seq (allmtpls (next ps))))), (union [xs ys] (let [xv (first xs), yv (first ys)] (if (< xv yv) (cons xv (lazy-seq (union (next xs) ys))) (if (< yv xv) (cons yv (lazy-seq (union xs (next ys)))) (cons xv (lazy-seq (union (next xs) (next ys)))))))), (mrgmltpls [mltplss] (cons (first (first mltplss)) (lazy-seq (union (next (first mltplss)) (mrgmltpls (next mltplss)))))), (minusStrtAt [n cmpsts] (loop [n n, cmpsts cmpsts] (if (< n (first cmpsts)) (cons n (lazy-seq (minusStrtAt (+ n 2) cmpsts))) (recur (+ n 2) (next cmpsts)))))] (do (def oddprms (cons 3 (lazy-seq (let [cmpsts (-> oddprms (allmtpls) (mrgmltpls))] (minusStrtAt 5 cmpsts))))) (cons 2 (lazy-seq oddprms)))))
2785
(defn primes-Bird "Computes the unbounded sequence of primes using a Sieve of Eratosthenes algorithm by <NAME>." [] (letfn [(mltpls [p] (let [p2 (* 2 p)] (letfn [(nxtmltpl [c] (cons c (lazy-seq (nxtmltpl (+ c p2)))))] (nxtmltpl (* p p))))), (allmtpls [ps] (cons (mltpls (first ps)) (lazy-seq (allmtpls (next ps))))), (union [xs ys] (let [xv (first xs), yv (first ys)] (if (< xv yv) (cons xv (lazy-seq (union (next xs) ys))) (if (< yv xv) (cons yv (lazy-seq (union xs (next ys)))) (cons xv (lazy-seq (union (next xs) (next ys)))))))), (mrgmltpls [mltplss] (cons (first (first mltplss)) (lazy-seq (union (next (first mltplss)) (mrgmltpls (next mltplss)))))), (minusStrtAt [n cmpsts] (loop [n n, cmpsts cmpsts] (if (< n (first cmpsts)) (cons n (lazy-seq (minusStrtAt (+ n 2) cmpsts))) (recur (+ n 2) (next cmpsts)))))] (do (def oddprms (cons 3 (lazy-seq (let [cmpsts (-> oddprms (allmtpls) (mrgmltpls))] (minusStrtAt 5 cmpsts))))) (cons 2 (lazy-seq oddprms)))))
true
(defn primes-Bird "Computes the unbounded sequence of primes using a Sieve of Eratosthenes algorithm by PI:NAME:<NAME>END_PI." [] (letfn [(mltpls [p] (let [p2 (* 2 p)] (letfn [(nxtmltpl [c] (cons c (lazy-seq (nxtmltpl (+ c p2)))))] (nxtmltpl (* p p))))), (allmtpls [ps] (cons (mltpls (first ps)) (lazy-seq (allmtpls (next ps))))), (union [xs ys] (let [xv (first xs), yv (first ys)] (if (< xv yv) (cons xv (lazy-seq (union (next xs) ys))) (if (< yv xv) (cons yv (lazy-seq (union xs (next ys)))) (cons xv (lazy-seq (union (next xs) (next ys)))))))), (mrgmltpls [mltplss] (cons (first (first mltplss)) (lazy-seq (union (next (first mltplss)) (mrgmltpls (next mltplss)))))), (minusStrtAt [n cmpsts] (loop [n n, cmpsts cmpsts] (if (< n (first cmpsts)) (cons n (lazy-seq (minusStrtAt (+ n 2) cmpsts))) (recur (+ n 2) (next cmpsts)))))] (do (def oddprms (cons 3 (lazy-seq (let [cmpsts (-> oddprms (allmtpls) (mrgmltpls))] (minusStrtAt 5 cmpsts))))) (cons 2 (lazy-seq oddprms)))))
[ { "context": "f data [(Item. \"Excalibur\" \"The legendary sword of King Arthur\" 12 1024)\n (Item. \"Steel Armor\" \"Protec", "end": 364, "score": 0.9074833393096924, "start": 353, "tag": "NAME", "value": "King Arthur" } ]
Solutions/ChalkPE/Game Shop/1/core.clj
pravin1237/ProgrammingPractice
32
(ns game-shop.core) (defrecord Item [name description weight value]) (defn Describe [item] (printf "Name = %s%n" (:name item)) (printf "Description = %s%n" (:description item)) (printf "Weight = %s lbs%n" (:weight item)) (printf "Value = %s gold coins%n" (:value item))) (def data [(Item. "Excalibur" "The legendary sword of King Arthur" 12 1024) (Item. "Steel Armor" "Protective covering made by steel" 15 805)]) (doseq [item data] (Describe item) (println))
81824
(ns game-shop.core) (defrecord Item [name description weight value]) (defn Describe [item] (printf "Name = %s%n" (:name item)) (printf "Description = %s%n" (:description item)) (printf "Weight = %s lbs%n" (:weight item)) (printf "Value = %s gold coins%n" (:value item))) (def data [(Item. "Excalibur" "The legendary sword of <NAME>" 12 1024) (Item. "Steel Armor" "Protective covering made by steel" 15 805)]) (doseq [item data] (Describe item) (println))
true
(ns game-shop.core) (defrecord Item [name description weight value]) (defn Describe [item] (printf "Name = %s%n" (:name item)) (printf "Description = %s%n" (:description item)) (printf "Weight = %s lbs%n" (:weight item)) (printf "Value = %s gold coins%n" (:value item))) (def data [(Item. "Excalibur" "The legendary sword of PI:NAME:<NAME>END_PI" 12 1024) (Item. "Steel Armor" "Protective covering made by steel" 15 805)]) (doseq [item data] (Describe item) (println))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-09-09\"\n :doc \"Utilities for HPP", "end": 105, "score": 0.9998752474784851, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/main/clojure/zana/collections/hppc.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-09-09" :doc "Utilities for HPPC: High Performance Primitive Collections for Java." } zana.collections.hppc (:refer-clojure :exclude [double-array empty? filter frequencies get inc keys range reduce]) (:require [zana.collections.generic :as g] [zana.collections.maps :as maps] [zana.collections.sets :as sets]) (:import [clojure.lang IFn IFn$OD IFn$OL] [com.carrotsearch.hppc DoubleContainer FloatContainer LongContainer LongObjectHashMap ObjectContainer ObjectDoubleHashMap ObjectFloatHashMap ObjectIntHashMap ObjectLongHashMap ObjectLongMap] [com.carrotsearch.hppc.cursors DoubleCursor FloatCursor LongCursor ObjectCursor ObjectDoubleCursor ObjectFloatCursor ObjectIntCursor ObjectLongCursor] [com.google.common.collect ImmutableList ImmutableSet] [java.util Arrays Collection Collections Map Map$Entry Set])) ;;------------------------------------------------------------------------------ ;; TODO: replace defmulti with defprotocol? ;;------------------------------------------------------------------------------ (defmethod maps/keys ObjectIntHashMap [^ObjectIntHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectLongHashMap [^ObjectLongHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectDoubleHashMap [^ObjectDoubleHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectFloatHashMap [^ObjectFloatHashMap m] (into [] (.toArray (.keys m)))) ;;------------------------------------------------------------------------------ (defmethod g/empty? ObjectIntHashMap [^ObjectIntHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectLongHashMap [^ObjectLongHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectDoubleHashMap [^ObjectDoubleHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectFloatHashMap [^ObjectFloatHashMap m] (< 0 (.size m))) ;;------------------------------------------------------------------------------ (defmulti entries class) ;; TODO: return a vector? sort? method macro? (defmethod entries ObjectIntHashMap [^ObjectIntHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectIntCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectLongHashMap [^ObjectLongHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectLongCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectDoubleHashMap [^ObjectDoubleHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectDoubleCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectFloatHashMap [^ObjectFloatHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectFloatCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) ;;------------------------------------------------------------------------------ (defmulti ^Long/TYPE max-value class) (defmethod max-value LongContainer ^long [^LongContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [l1 Long/MIN_VALUE] (if (.hasNext i) (let [l (.value ^LongCursor (.next i)) l1 (if (> l l1) l l1)] (recur l1)) l1)))) (defmethod max-value ObjectLongMap ^long [^ObjectLongMap olm] (max-value (.values olm))) ;;------------------------------------------------------------------------------ ;; not quite the same as values --- return intervals for numerical containers. ;; TODO: replace with 'span' of values (defmulti range class) (defmethod range LongContainer [^LongContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [l0 Long/MAX_VALUE l1 Long/MIN_VALUE] (if (.hasNext i) (let [l (.value ^LongCursor (.next i)) l0 (if (< l l0) l l0) l1 (if (> l l1) l l1)] (recur l0 l1)) [l0 (+ 1 l1)])))) (defmethod range DoubleContainer [^DoubleContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [d0 Double/POSITIVE_INFINITY d1 Double/NEGATIVE_INFINITY] (if (.hasNext i) (let [d (.value ^DoubleCursor (.next i)) d0 (if (< d d0) d d0) d1 (if (> d d1) d d1)] (recur d0 d1)) [d0 d1])))) (defmethod range FloatContainer [^FloatContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [d0 Float/POSITIVE_INFINITY d1 Float/NEGATIVE_INFINITY] (if (.hasNext i) (let [d (float (.value ^FloatCursor (.next i))) d0 (float (if (< d d0) d d0)) d1 (float (if (> d d1) d d1))] (recur d0 d1)) [d0 d1])))) ;;------------------------------------------------------------------------------ ;; TODO: more factories (defn object-double-map (^com.carrotsearch.hppc.ObjectDoubleHashMap [] (ObjectDoubleHashMap.)) (^com.carrotsearch.hppc.ObjectDoubleHashMap [^Map m] (let [odohm (ObjectDoubleHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put odohm (.getKey entry) (double (.getValue entry))))) odohm))) (defn object-double-map? [x] (instance? ObjectDoubleHashMap x)) ;;------------------------------------------------------------------------------ (defn object-float-map (^com.carrotsearch.hppc.ObjectFloatHashMap [] (ObjectFloatHashMap.)) (^com.carrotsearch.hppc.ObjectFloatHashMap [x] (if-not (instance? java.util.Map x) (ObjectFloatHashMap. (int x)) (let [^java.util.Map m x odohm (ObjectFloatHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put odohm (.getKey entry) (float (.getValue entry))))) odohm)))) (defn object-float-map? [x] (instance? ObjectFloatHashMap x)) ;;------------------------------------------------------------------------------ (defn object-long-map (^com.carrotsearch.hppc.ObjectLongHashMap [] (ObjectLongHashMap.)) (^com.carrotsearch.hppc.ObjectLongHashMap [^Map m] (let [mm (ObjectLongHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put mm (.getKey entry) (long (.getValue entry))))) mm))) (defn object-long-map? [x] (instance? ObjectLongHashMap x)) ;;------------------------------------------------------------------------------ (defn long-object-map (^com.carrotsearch.hppc.LongObjectHashMap [] (LongObjectHashMap.)) (^com.carrotsearch.hppc.LongObjectHashMap [^Map m] (let [mm (LongObjectHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put mm (long (.getKey entry)) (.getValue entry)))) mm))) (defn long-object-map? [x] (instance? LongObjectHashMap x)) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? (defn get (^double [^ObjectDoubleHashMap m k ^double default] (.getOrDefault m k default)) (^double [^ObjectDoubleHashMap m k] (get m k Double/NaN))) (defn put ^double [^ObjectDoubleHashMap m k ^double v] (.put m k v)) (defn add [^ObjectDoubleHashMap m k ^double v] (.addTo m k v)) (defn inc [m k] (cond (instance? ObjectDoubleHashMap m) (.addTo ^ObjectDoubleHashMap m k (double 1.0)) (instance? ObjectLongHashMap m) (.addTo ^ObjectLongHashMap m k (long 1)) :else (throw (UnsupportedOperationException.)))) ;;------------------------------------------------------------------------------ (defn key-array ^objects [m] (cond (instance? ObjectDoubleHashMap m) (.toArray (.keys ^ObjectDoubleHashMap m)) (instance? ObjectFloatHashMap m) (.toArray (.keys ^ObjectFloatHashMap m)) (instance? ObjectIntHashMap m) (.toArray (.keys ^ObjectIntHashMap m)) :else (throw (UnsupportedOperationException. (str "Can't get keys for " m))))) (defn keys ^Iterable [m] (cond (instance? ObjectDoubleHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectDoubleHashMap m)))) (instance? ObjectFloatHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectFloatHashMap m)))) (instance? ObjectIntHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectIntHashMap m)))) (instance? ObjectLongHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectLongHashMap m)))) :else (throw (UnsupportedOperationException. (str "Can't get keys for " m))))) ;;------------------------------------------------------------------------------ (defmethod g/filter [IFn ObjectIntHashMap] [^IFn f ^ObjectIntHashMap m] (let [i (.iterator m) mm (ObjectIntHashMap. (.size m))] (while (.hasNext i) (let [^ObjectIntCursor c (.next i) k (.key c) v (.value c)] (when (f k v) (.put mm k v)))) mm)) (defmethod g/filter [IFn ObjectDoubleHashMap] [^IFn f ^ObjectDoubleHashMap m] (let [i (.iterator m) mm (ObjectDoubleHashMap. (.size m))] (while (.hasNext i) (let [^ObjectDoubleCursor c (.next i) k (.key c) v (.value c)] (when (f k v) (.put mm k v)))) mm)) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? ;; TODO: automated method generation? (defn reduceObjectIntHashMap [f x0 ^ObjectIntHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectIntCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduceObjectLongHashMap [f x0 ^ObjectLongHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectLongCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduceObjectDoubleHashMap [f x0 ^ObjectDoubleHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectDoubleCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduce [f init m] (cond (instance? ObjectIntHashMap m) (reduceObjectIntHashMap f init m) (instance? ObjectLongHashMap m) (reduceObjectLongHashMap f init m) (instance? ObjectDoubleHashMap m) (reduceObjectDoubleHashMap f init m) :else (throw (IllegalArgumentException. (str "Don't know how to reduce a " (class m)))))) ;;------------------------------------------------------------------------------ #_(defn frequencies ^com.carrotsearch.hppc.ObjectIntHashMap ([^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (.addTo m (.next it) (int 1))) m)) ([^IFn f ^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (.addTo m (f (.next it)) (int 1))) m)) ([^IFn x ^IFn y ^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (let [di (.next it) xy [(x di) (y di)]] (.addTo m xy (int 1)))) m))) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? protocol? (defn mode [^ObjectLongHashMap m] (let [[k _] (reduce (fn [[k ^long v] ki ^long vi] (if (> vi v) [ki vi] [k v])) [nil -1] m)] k)) ;;------------------------------------------------------------------------------ (defn- sums-double ^com.carrotsearch.hppc.ObjectDoubleHashMap [^IFn k ^IFn$OD v ^Iterable data] (let [m (ObjectDoubleHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn- sums-long ^com.carrotsearch.hppc.ObjectLongHashMap [^IFn k ^IFn$OL v ^Iterable data] (let [m (ObjectLongHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn- sums-generic ^com.carrotsearch.hppc.ObjectDoubleHashMap [^IFn k ^IFn v ^Iterable data] (let [m (ObjectDoubleHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn sums [^IFn k ^IFn v ^Iterable data] (cond (instance? IFn$OD v) (sums-double k v data) (instance? IFn$OL v) (sums-long k v data) :else (throw (IllegalArgumentException. (print-str "can't handle:" v))))) ;;------------------------------------------------------------------------------ ;; Sparse vectors ;;------------------------------------------------------------------------------ ;; could use a DoubleArrayList (defn double-array ^doubles [^ObjectDoubleHashMap odohm keys] (cond (instance? Collection keys) (let [^Collection keys keys n (.size keys) it (.iterator keys) a (clojure.core/double-array n)] (dotimes [i (int n)] (let [index (.indexOf odohm (.next it))] (when-not (neg? index) (aset a i (.indexGet odohm index))))) a) (.isArray (class keys)) (let [^objects keys keys n (alength keys) a (clojure.core/double-array n)] (dotimes [i (int n)] (let [index (.indexOf odohm (aget keys i))] (when-not (neg? index) (aset a i (.indexGet odohm index))))) a) :else (throw (UnsupportedOperationException. (str "Can't evaluate map at keys in " keys))))) ;; Treating the maps as sparse representations of vectors where the keys ;; correspond to the canonical basis vectors of a vector space whose dimensions ;; correspond to any java Object (equivalence classes of objects under .equal). (defn inner-product ^double [^ObjectDoubleHashMap m0 ^ObjectDoubleHashMap m1] ;; iterate over the sparsest vector (if (> (.size m0) (.size m1)) (inner-product m1 m0) (let [i (.iterator m0)] (loop [sum (double 0.0)] (if (.hasNext i) (let [^ObjectDoubleCursor oic (.next i) index (.indexGet m1 (.key oic))] (if-not (neg? index) (recur (+ sum (* (.value oic) (.indexGet m1 index)))) (recur sum))) sum))))) ;;------------------------------------------------------------------------------ ;; Treating the maps as sparse representations of vectors where the keys ;; correspond to the canonical basis vectors of a vector space whose dimensions ;; correspond to any java Object (equivalence classes of objects under .equal). (defn add-values ^com.carrotsearch.hppc.ObjectDoubleHashMap [^ObjectDoubleHashMap m0 ^ObjectDoubleHashMap m1] (let [sum (ObjectDoubleHashMap.) i (.iterator (sets/union (keys m0) (keys m1)))] (while (.hasNext i) (let [k (.next i) i0 (.indexOf m0 k) i1 (.indexOf m1 k)] (if-not (neg? i0) (if-not (neg? i1) (.put sum k (+ (.indexGet m0 i0) (.indexGet m1 i1))) (.put sum k (.indexGet m0 i0))) (.put sum k (.indexGet m1 i1))))) sum)) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ObjectLongHashMap [^ObjectLongHashMap m ^java.io.Writer w] (.write w (pr-str (entries m)))) ;;------------------------------------------------------------------------------
26597
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-09-09" :doc "Utilities for HPPC: High Performance Primitive Collections for Java." } zana.collections.hppc (:refer-clojure :exclude [double-array empty? filter frequencies get inc keys range reduce]) (:require [zana.collections.generic :as g] [zana.collections.maps :as maps] [zana.collections.sets :as sets]) (:import [clojure.lang IFn IFn$OD IFn$OL] [com.carrotsearch.hppc DoubleContainer FloatContainer LongContainer LongObjectHashMap ObjectContainer ObjectDoubleHashMap ObjectFloatHashMap ObjectIntHashMap ObjectLongHashMap ObjectLongMap] [com.carrotsearch.hppc.cursors DoubleCursor FloatCursor LongCursor ObjectCursor ObjectDoubleCursor ObjectFloatCursor ObjectIntCursor ObjectLongCursor] [com.google.common.collect ImmutableList ImmutableSet] [java.util Arrays Collection Collections Map Map$Entry Set])) ;;------------------------------------------------------------------------------ ;; TODO: replace defmulti with defprotocol? ;;------------------------------------------------------------------------------ (defmethod maps/keys ObjectIntHashMap [^ObjectIntHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectLongHashMap [^ObjectLongHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectDoubleHashMap [^ObjectDoubleHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectFloatHashMap [^ObjectFloatHashMap m] (into [] (.toArray (.keys m)))) ;;------------------------------------------------------------------------------ (defmethod g/empty? ObjectIntHashMap [^ObjectIntHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectLongHashMap [^ObjectLongHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectDoubleHashMap [^ObjectDoubleHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectFloatHashMap [^ObjectFloatHashMap m] (< 0 (.size m))) ;;------------------------------------------------------------------------------ (defmulti entries class) ;; TODO: return a vector? sort? method macro? (defmethod entries ObjectIntHashMap [^ObjectIntHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectIntCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectLongHashMap [^ObjectLongHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectLongCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectDoubleHashMap [^ObjectDoubleHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectDoubleCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectFloatHashMap [^ObjectFloatHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectFloatCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) ;;------------------------------------------------------------------------------ (defmulti ^Long/TYPE max-value class) (defmethod max-value LongContainer ^long [^LongContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [l1 Long/MIN_VALUE] (if (.hasNext i) (let [l (.value ^LongCursor (.next i)) l1 (if (> l l1) l l1)] (recur l1)) l1)))) (defmethod max-value ObjectLongMap ^long [^ObjectLongMap olm] (max-value (.values olm))) ;;------------------------------------------------------------------------------ ;; not quite the same as values --- return intervals for numerical containers. ;; TODO: replace with 'span' of values (defmulti range class) (defmethod range LongContainer [^LongContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [l0 Long/MAX_VALUE l1 Long/MIN_VALUE] (if (.hasNext i) (let [l (.value ^LongCursor (.next i)) l0 (if (< l l0) l l0) l1 (if (> l l1) l l1)] (recur l0 l1)) [l0 (+ 1 l1)])))) (defmethod range DoubleContainer [^DoubleContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [d0 Double/POSITIVE_INFINITY d1 Double/NEGATIVE_INFINITY] (if (.hasNext i) (let [d (.value ^DoubleCursor (.next i)) d0 (if (< d d0) d d0) d1 (if (> d d1) d d1)] (recur d0 d1)) [d0 d1])))) (defmethod range FloatContainer [^FloatContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [d0 Float/POSITIVE_INFINITY d1 Float/NEGATIVE_INFINITY] (if (.hasNext i) (let [d (float (.value ^FloatCursor (.next i))) d0 (float (if (< d d0) d d0)) d1 (float (if (> d d1) d d1))] (recur d0 d1)) [d0 d1])))) ;;------------------------------------------------------------------------------ ;; TODO: more factories (defn object-double-map (^com.carrotsearch.hppc.ObjectDoubleHashMap [] (ObjectDoubleHashMap.)) (^com.carrotsearch.hppc.ObjectDoubleHashMap [^Map m] (let [odohm (ObjectDoubleHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put odohm (.getKey entry) (double (.getValue entry))))) odohm))) (defn object-double-map? [x] (instance? ObjectDoubleHashMap x)) ;;------------------------------------------------------------------------------ (defn object-float-map (^com.carrotsearch.hppc.ObjectFloatHashMap [] (ObjectFloatHashMap.)) (^com.carrotsearch.hppc.ObjectFloatHashMap [x] (if-not (instance? java.util.Map x) (ObjectFloatHashMap. (int x)) (let [^java.util.Map m x odohm (ObjectFloatHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put odohm (.getKey entry) (float (.getValue entry))))) odohm)))) (defn object-float-map? [x] (instance? ObjectFloatHashMap x)) ;;------------------------------------------------------------------------------ (defn object-long-map (^com.carrotsearch.hppc.ObjectLongHashMap [] (ObjectLongHashMap.)) (^com.carrotsearch.hppc.ObjectLongHashMap [^Map m] (let [mm (ObjectLongHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put mm (.getKey entry) (long (.getValue entry))))) mm))) (defn object-long-map? [x] (instance? ObjectLongHashMap x)) ;;------------------------------------------------------------------------------ (defn long-object-map (^com.carrotsearch.hppc.LongObjectHashMap [] (LongObjectHashMap.)) (^com.carrotsearch.hppc.LongObjectHashMap [^Map m] (let [mm (LongObjectHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put mm (long (.getKey entry)) (.getValue entry)))) mm))) (defn long-object-map? [x] (instance? LongObjectHashMap x)) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? (defn get (^double [^ObjectDoubleHashMap m k ^double default] (.getOrDefault m k default)) (^double [^ObjectDoubleHashMap m k] (get m k Double/NaN))) (defn put ^double [^ObjectDoubleHashMap m k ^double v] (.put m k v)) (defn add [^ObjectDoubleHashMap m k ^double v] (.addTo m k v)) (defn inc [m k] (cond (instance? ObjectDoubleHashMap m) (.addTo ^ObjectDoubleHashMap m k (double 1.0)) (instance? ObjectLongHashMap m) (.addTo ^ObjectLongHashMap m k (long 1)) :else (throw (UnsupportedOperationException.)))) ;;------------------------------------------------------------------------------ (defn key-array ^objects [m] (cond (instance? ObjectDoubleHashMap m) (.toArray (.keys ^ObjectDoubleHashMap m)) (instance? ObjectFloatHashMap m) (.toArray (.keys ^ObjectFloatHashMap m)) (instance? ObjectIntHashMap m) (.toArray (.keys ^ObjectIntHashMap m)) :else (throw (UnsupportedOperationException. (str "Can't get keys for " m))))) (defn keys ^Iterable [m] (cond (instance? ObjectDoubleHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectDoubleHashMap m)))) (instance? ObjectFloatHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectFloatHashMap m)))) (instance? ObjectIntHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectIntHashMap m)))) (instance? ObjectLongHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectLongHashMap m)))) :else (throw (UnsupportedOperationException. (str "Can't get keys for " m))))) ;;------------------------------------------------------------------------------ (defmethod g/filter [IFn ObjectIntHashMap] [^IFn f ^ObjectIntHashMap m] (let [i (.iterator m) mm (ObjectIntHashMap. (.size m))] (while (.hasNext i) (let [^ObjectIntCursor c (.next i) k (.key c) v (.value c)] (when (f k v) (.put mm k v)))) mm)) (defmethod g/filter [IFn ObjectDoubleHashMap] [^IFn f ^ObjectDoubleHashMap m] (let [i (.iterator m) mm (ObjectDoubleHashMap. (.size m))] (while (.hasNext i) (let [^ObjectDoubleCursor c (.next i) k (.key c) v (.value c)] (when (f k v) (.put mm k v)))) mm)) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? ;; TODO: automated method generation? (defn reduceObjectIntHashMap [f x0 ^ObjectIntHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectIntCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduceObjectLongHashMap [f x0 ^ObjectLongHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectLongCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduceObjectDoubleHashMap [f x0 ^ObjectDoubleHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectDoubleCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduce [f init m] (cond (instance? ObjectIntHashMap m) (reduceObjectIntHashMap f init m) (instance? ObjectLongHashMap m) (reduceObjectLongHashMap f init m) (instance? ObjectDoubleHashMap m) (reduceObjectDoubleHashMap f init m) :else (throw (IllegalArgumentException. (str "Don't know how to reduce a " (class m)))))) ;;------------------------------------------------------------------------------ #_(defn frequencies ^com.carrotsearch.hppc.ObjectIntHashMap ([^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (.addTo m (.next it) (int 1))) m)) ([^IFn f ^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (.addTo m (f (.next it)) (int 1))) m)) ([^IFn x ^IFn y ^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (let [di (.next it) xy [(x di) (y di)]] (.addTo m xy (int 1)))) m))) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? protocol? (defn mode [^ObjectLongHashMap m] (let [[k _] (reduce (fn [[k ^long v] ki ^long vi] (if (> vi v) [ki vi] [k v])) [nil -1] m)] k)) ;;------------------------------------------------------------------------------ (defn- sums-double ^com.carrotsearch.hppc.ObjectDoubleHashMap [^IFn k ^IFn$OD v ^Iterable data] (let [m (ObjectDoubleHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn- sums-long ^com.carrotsearch.hppc.ObjectLongHashMap [^IFn k ^IFn$OL v ^Iterable data] (let [m (ObjectLongHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn- sums-generic ^com.carrotsearch.hppc.ObjectDoubleHashMap [^IFn k ^IFn v ^Iterable data] (let [m (ObjectDoubleHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn sums [^IFn k ^IFn v ^Iterable data] (cond (instance? IFn$OD v) (sums-double k v data) (instance? IFn$OL v) (sums-long k v data) :else (throw (IllegalArgumentException. (print-str "can't handle:" v))))) ;;------------------------------------------------------------------------------ ;; Sparse vectors ;;------------------------------------------------------------------------------ ;; could use a DoubleArrayList (defn double-array ^doubles [^ObjectDoubleHashMap odohm keys] (cond (instance? Collection keys) (let [^Collection keys keys n (.size keys) it (.iterator keys) a (clojure.core/double-array n)] (dotimes [i (int n)] (let [index (.indexOf odohm (.next it))] (when-not (neg? index) (aset a i (.indexGet odohm index))))) a) (.isArray (class keys)) (let [^objects keys keys n (alength keys) a (clojure.core/double-array n)] (dotimes [i (int n)] (let [index (.indexOf odohm (aget keys i))] (when-not (neg? index) (aset a i (.indexGet odohm index))))) a) :else (throw (UnsupportedOperationException. (str "Can't evaluate map at keys in " keys))))) ;; Treating the maps as sparse representations of vectors where the keys ;; correspond to the canonical basis vectors of a vector space whose dimensions ;; correspond to any java Object (equivalence classes of objects under .equal). (defn inner-product ^double [^ObjectDoubleHashMap m0 ^ObjectDoubleHashMap m1] ;; iterate over the sparsest vector (if (> (.size m0) (.size m1)) (inner-product m1 m0) (let [i (.iterator m0)] (loop [sum (double 0.0)] (if (.hasNext i) (let [^ObjectDoubleCursor oic (.next i) index (.indexGet m1 (.key oic))] (if-not (neg? index) (recur (+ sum (* (.value oic) (.indexGet m1 index)))) (recur sum))) sum))))) ;;------------------------------------------------------------------------------ ;; Treating the maps as sparse representations of vectors where the keys ;; correspond to the canonical basis vectors of a vector space whose dimensions ;; correspond to any java Object (equivalence classes of objects under .equal). (defn add-values ^com.carrotsearch.hppc.ObjectDoubleHashMap [^ObjectDoubleHashMap m0 ^ObjectDoubleHashMap m1] (let [sum (ObjectDoubleHashMap.) i (.iterator (sets/union (keys m0) (keys m1)))] (while (.hasNext i) (let [k (.next i) i0 (.indexOf m0 k) i1 (.indexOf m1 k)] (if-not (neg? i0) (if-not (neg? i1) (.put sum k (+ (.indexGet m0 i0) (.indexGet m1 i1))) (.put sum k (.indexGet m0 i0))) (.put sum k (.indexGet m1 i1))))) sum)) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ObjectLongHashMap [^ObjectLongHashMap m ^java.io.Writer w] (.write w (pr-str (entries m)))) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-09-09" :doc "Utilities for HPPC: High Performance Primitive Collections for Java." } zana.collections.hppc (:refer-clojure :exclude [double-array empty? filter frequencies get inc keys range reduce]) (:require [zana.collections.generic :as g] [zana.collections.maps :as maps] [zana.collections.sets :as sets]) (:import [clojure.lang IFn IFn$OD IFn$OL] [com.carrotsearch.hppc DoubleContainer FloatContainer LongContainer LongObjectHashMap ObjectContainer ObjectDoubleHashMap ObjectFloatHashMap ObjectIntHashMap ObjectLongHashMap ObjectLongMap] [com.carrotsearch.hppc.cursors DoubleCursor FloatCursor LongCursor ObjectCursor ObjectDoubleCursor ObjectFloatCursor ObjectIntCursor ObjectLongCursor] [com.google.common.collect ImmutableList ImmutableSet] [java.util Arrays Collection Collections Map Map$Entry Set])) ;;------------------------------------------------------------------------------ ;; TODO: replace defmulti with defprotocol? ;;------------------------------------------------------------------------------ (defmethod maps/keys ObjectIntHashMap [^ObjectIntHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectLongHashMap [^ObjectLongHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectDoubleHashMap [^ObjectDoubleHashMap m] (into [] (.toArray (.keys m)))) (defmethod maps/keys ObjectFloatHashMap [^ObjectFloatHashMap m] (into [] (.toArray (.keys m)))) ;;------------------------------------------------------------------------------ (defmethod g/empty? ObjectIntHashMap [^ObjectIntHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectLongHashMap [^ObjectLongHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectDoubleHashMap [^ObjectDoubleHashMap m] (< 0 (.size m))) (defmethod g/empty? ObjectFloatHashMap [^ObjectFloatHashMap m] (< 0 (.size m))) ;;------------------------------------------------------------------------------ (defmulti entries class) ;; TODO: return a vector? sort? method macro? (defmethod entries ObjectIntHashMap [^ObjectIntHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectIntCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectLongHashMap [^ObjectLongHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectLongCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectDoubleHashMap [^ObjectDoubleHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectDoubleCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) (defmethod entries ObjectFloatHashMap [^ObjectFloatHashMap olm] (let [i (.iterator olm)] (loop [entries (transient {})] (if (.hasNext i) (let [^ObjectFloatCursor c (.next i)] (recur (assoc! entries (.key c) (.value c)))) (persistent! entries))))) ;;------------------------------------------------------------------------------ (defmulti ^Long/TYPE max-value class) (defmethod max-value LongContainer ^long [^LongContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [l1 Long/MIN_VALUE] (if (.hasNext i) (let [l (.value ^LongCursor (.next i)) l1 (if (> l l1) l l1)] (recur l1)) l1)))) (defmethod max-value ObjectLongMap ^long [^ObjectLongMap olm] (max-value (.values olm))) ;;------------------------------------------------------------------------------ ;; not quite the same as values --- return intervals for numerical containers. ;; TODO: replace with 'span' of values (defmulti range class) (defmethod range LongContainer [^LongContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [l0 Long/MAX_VALUE l1 Long/MIN_VALUE] (if (.hasNext i) (let [l (.value ^LongCursor (.next i)) l0 (if (< l l0) l l0) l1 (if (> l l1) l l1)] (recur l0 l1)) [l0 (+ 1 l1)])))) (defmethod range DoubleContainer [^DoubleContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [d0 Double/POSITIVE_INFINITY d1 Double/NEGATIVE_INFINITY] (if (.hasNext i) (let [d (.value ^DoubleCursor (.next i)) d0 (if (< d d0) d d0) d1 (if (> d d1) d d1)] (recur d0 d1)) [d0 d1])))) (defmethod range FloatContainer [^FloatContainer container] (assert (> (.size container) 0)) (let [i (.iterator container)] (loop [d0 Float/POSITIVE_INFINITY d1 Float/NEGATIVE_INFINITY] (if (.hasNext i) (let [d (float (.value ^FloatCursor (.next i))) d0 (float (if (< d d0) d d0)) d1 (float (if (> d d1) d d1))] (recur d0 d1)) [d0 d1])))) ;;------------------------------------------------------------------------------ ;; TODO: more factories (defn object-double-map (^com.carrotsearch.hppc.ObjectDoubleHashMap [] (ObjectDoubleHashMap.)) (^com.carrotsearch.hppc.ObjectDoubleHashMap [^Map m] (let [odohm (ObjectDoubleHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put odohm (.getKey entry) (double (.getValue entry))))) odohm))) (defn object-double-map? [x] (instance? ObjectDoubleHashMap x)) ;;------------------------------------------------------------------------------ (defn object-float-map (^com.carrotsearch.hppc.ObjectFloatHashMap [] (ObjectFloatHashMap.)) (^com.carrotsearch.hppc.ObjectFloatHashMap [x] (if-not (instance? java.util.Map x) (ObjectFloatHashMap. (int x)) (let [^java.util.Map m x odohm (ObjectFloatHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put odohm (.getKey entry) (float (.getValue entry))))) odohm)))) (defn object-float-map? [x] (instance? ObjectFloatHashMap x)) ;;------------------------------------------------------------------------------ (defn object-long-map (^com.carrotsearch.hppc.ObjectLongHashMap [] (ObjectLongHashMap.)) (^com.carrotsearch.hppc.ObjectLongHashMap [^Map m] (let [mm (ObjectLongHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put mm (.getKey entry) (long (.getValue entry))))) mm))) (defn object-long-map? [x] (instance? ObjectLongHashMap x)) ;;------------------------------------------------------------------------------ (defn long-object-map (^com.carrotsearch.hppc.LongObjectHashMap [] (LongObjectHashMap.)) (^com.carrotsearch.hppc.LongObjectHashMap [^Map m] (let [mm (LongObjectHashMap. (.size m)) entries (.iterator (.entrySet m))] (while (.hasNext entries) (let [^Map$Entry entry (.next entries)] (.put mm (long (.getKey entry)) (.getValue entry)))) mm))) (defn long-object-map? [x] (instance? LongObjectHashMap x)) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? (defn get (^double [^ObjectDoubleHashMap m k ^double default] (.getOrDefault m k default)) (^double [^ObjectDoubleHashMap m k] (get m k Double/NaN))) (defn put ^double [^ObjectDoubleHashMap m k ^double v] (.put m k v)) (defn add [^ObjectDoubleHashMap m k ^double v] (.addTo m k v)) (defn inc [m k] (cond (instance? ObjectDoubleHashMap m) (.addTo ^ObjectDoubleHashMap m k (double 1.0)) (instance? ObjectLongHashMap m) (.addTo ^ObjectLongHashMap m k (long 1)) :else (throw (UnsupportedOperationException.)))) ;;------------------------------------------------------------------------------ (defn key-array ^objects [m] (cond (instance? ObjectDoubleHashMap m) (.toArray (.keys ^ObjectDoubleHashMap m)) (instance? ObjectFloatHashMap m) (.toArray (.keys ^ObjectFloatHashMap m)) (instance? ObjectIntHashMap m) (.toArray (.keys ^ObjectIntHashMap m)) :else (throw (UnsupportedOperationException. (str "Can't get keys for " m))))) (defn keys ^Iterable [m] (cond (instance? ObjectDoubleHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectDoubleHashMap m)))) (instance? ObjectFloatHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectFloatHashMap m)))) (instance? ObjectIntHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectIntHashMap m)))) (instance? ObjectLongHashMap m) (Collections/unmodifiableList (Arrays/asList (.toArray (.keys ^ObjectLongHashMap m)))) :else (throw (UnsupportedOperationException. (str "Can't get keys for " m))))) ;;------------------------------------------------------------------------------ (defmethod g/filter [IFn ObjectIntHashMap] [^IFn f ^ObjectIntHashMap m] (let [i (.iterator m) mm (ObjectIntHashMap. (.size m))] (while (.hasNext i) (let [^ObjectIntCursor c (.next i) k (.key c) v (.value c)] (when (f k v) (.put mm k v)))) mm)) (defmethod g/filter [IFn ObjectDoubleHashMap] [^IFn f ^ObjectDoubleHashMap m] (let [i (.iterator m) mm (ObjectDoubleHashMap. (.size m))] (while (.hasNext i) (let [^ObjectDoubleCursor c (.next i) k (.key c) v (.value c)] (when (f k v) (.put mm k v)))) mm)) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? ;; TODO: automated method generation? (defn reduceObjectIntHashMap [f x0 ^ObjectIntHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectIntCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduceObjectLongHashMap [f x0 ^ObjectLongHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectLongCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduceObjectDoubleHashMap [f x0 ^ObjectDoubleHashMap m] (let [i (.iterator m)] (loop [x x0] (if (.hasNext i) (let [^ObjectDoubleCursor oic (.next i) k (.key oic) v (.value oic)] (recur (f x k v))) x)))) (defn reduce [f init m] (cond (instance? ObjectIntHashMap m) (reduceObjectIntHashMap f init m) (instance? ObjectLongHashMap m) (reduceObjectLongHashMap f init m) (instance? ObjectDoubleHashMap m) (reduceObjectDoubleHashMap f init m) :else (throw (IllegalArgumentException. (str "Don't know how to reduce a " (class m)))))) ;;------------------------------------------------------------------------------ #_(defn frequencies ^com.carrotsearch.hppc.ObjectIntHashMap ([^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (.addTo m (.next it) (int 1))) m)) ([^IFn f ^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (.addTo m (f (.next it)) (int 1))) m)) ([^IFn x ^IFn y ^Iterable data] (let [m (ObjectIntHashMap.) it (.iterator data)] (while (.hasNext it) (let [di (.next it) xy [(x di) (y di)]] (.addTo m xy (int 1)))) m))) ;;------------------------------------------------------------------------------ ;; TODO: multimethods? protocol? (defn mode [^ObjectLongHashMap m] (let [[k _] (reduce (fn [[k ^long v] ki ^long vi] (if (> vi v) [ki vi] [k v])) [nil -1] m)] k)) ;;------------------------------------------------------------------------------ (defn- sums-double ^com.carrotsearch.hppc.ObjectDoubleHashMap [^IFn k ^IFn$OD v ^Iterable data] (let [m (ObjectDoubleHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn- sums-long ^com.carrotsearch.hppc.ObjectLongHashMap [^IFn k ^IFn$OL v ^Iterable data] (let [m (ObjectLongHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn- sums-generic ^com.carrotsearch.hppc.ObjectDoubleHashMap [^IFn k ^IFn v ^Iterable data] (let [m (ObjectDoubleHashMap.) it (.iterator data)] (while (.hasNext it) (let [x (.next it)] (.addTo m (k x) (v x)))) m)) (defn sums [^IFn k ^IFn v ^Iterable data] (cond (instance? IFn$OD v) (sums-double k v data) (instance? IFn$OL v) (sums-long k v data) :else (throw (IllegalArgumentException. (print-str "can't handle:" v))))) ;;------------------------------------------------------------------------------ ;; Sparse vectors ;;------------------------------------------------------------------------------ ;; could use a DoubleArrayList (defn double-array ^doubles [^ObjectDoubleHashMap odohm keys] (cond (instance? Collection keys) (let [^Collection keys keys n (.size keys) it (.iterator keys) a (clojure.core/double-array n)] (dotimes [i (int n)] (let [index (.indexOf odohm (.next it))] (when-not (neg? index) (aset a i (.indexGet odohm index))))) a) (.isArray (class keys)) (let [^objects keys keys n (alength keys) a (clojure.core/double-array n)] (dotimes [i (int n)] (let [index (.indexOf odohm (aget keys i))] (when-not (neg? index) (aset a i (.indexGet odohm index))))) a) :else (throw (UnsupportedOperationException. (str "Can't evaluate map at keys in " keys))))) ;; Treating the maps as sparse representations of vectors where the keys ;; correspond to the canonical basis vectors of a vector space whose dimensions ;; correspond to any java Object (equivalence classes of objects under .equal). (defn inner-product ^double [^ObjectDoubleHashMap m0 ^ObjectDoubleHashMap m1] ;; iterate over the sparsest vector (if (> (.size m0) (.size m1)) (inner-product m1 m0) (let [i (.iterator m0)] (loop [sum (double 0.0)] (if (.hasNext i) (let [^ObjectDoubleCursor oic (.next i) index (.indexGet m1 (.key oic))] (if-not (neg? index) (recur (+ sum (* (.value oic) (.indexGet m1 index)))) (recur sum))) sum))))) ;;------------------------------------------------------------------------------ ;; Treating the maps as sparse representations of vectors where the keys ;; correspond to the canonical basis vectors of a vector space whose dimensions ;; correspond to any java Object (equivalence classes of objects under .equal). (defn add-values ^com.carrotsearch.hppc.ObjectDoubleHashMap [^ObjectDoubleHashMap m0 ^ObjectDoubleHashMap m1] (let [sum (ObjectDoubleHashMap.) i (.iterator (sets/union (keys m0) (keys m1)))] (while (.hasNext i) (let [k (.next i) i0 (.indexOf m0 k) i1 (.indexOf m1 k)] (if-not (neg? i0) (if-not (neg? i1) (.put sum k (+ (.indexGet m0 i0) (.indexGet m1 i1))) (.put sum k (.indexGet m0 i0))) (.put sum k (.indexGet m1 i1))))) sum)) ;;------------------------------------------------------------------------------ (defmethod clojure.core/print-method ObjectLongHashMap [^ObjectLongHashMap m ^java.io.Writer w] (.write w (pr-str (entries m)))) ;;------------------------------------------------------------------------------
[ { "context": "r.transmit.config/echo-system-token (constantly \"zort\")]\n (is (= {:token \"zort\"\n :foo \"ba", "end": 340, "score": 0.7869142889976501, "start": 337, "tag": "KEY", "value": "ort" }, { "context": "em-token (constantly \"zort\")]\n (is (= {:token \"zort\"\n :foo \"bar\"}\n (config/with-", "end": 368, "score": 0.6076188683509827, "start": 364, "tag": "KEY", "value": "zort" } ]
transmit-lib/test/cmr/transmit/test/config.clj
sxu123/Common-Metadata-Repository
0
(ns cmr.transmit.test.config (:require [clojure.test :refer :all] [cmr.transmit.config :as config])) (deftest with-echo-system-token-test (is (= {:token "mock-echo-system-token" :foo "bar"} (config/with-echo-system-token {:foo "bar"}))) (with-redefs [cmr.transmit.config/echo-system-token (constantly "zort")] (is (= {:token "zort" :foo "bar"} (config/with-echo-system-token {:foo "bar"})))))
70876
(ns cmr.transmit.test.config (:require [clojure.test :refer :all] [cmr.transmit.config :as config])) (deftest with-echo-system-token-test (is (= {:token "mock-echo-system-token" :foo "bar"} (config/with-echo-system-token {:foo "bar"}))) (with-redefs [cmr.transmit.config/echo-system-token (constantly "z<KEY>")] (is (= {:token "<KEY>" :foo "bar"} (config/with-echo-system-token {:foo "bar"})))))
true
(ns cmr.transmit.test.config (:require [clojure.test :refer :all] [cmr.transmit.config :as config])) (deftest with-echo-system-token-test (is (= {:token "mock-echo-system-token" :foo "bar"} (config/with-echo-system-token {:foo "bar"}))) (with-redefs [cmr.transmit.config/echo-system-token (constantly "zPI:KEY:<KEY>END_PI")] (is (= {:token "PI:KEY:<KEY>END_PI" :foo "bar"} (config/with-echo-system-token {:foo "bar"})))))
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns ^{:doc \"\"\n :autho", "end": 597, "score": 0.999875545501709, "start": 584, "tag": "NAME", "value": "Kenneth Leung" }, { "context": "ll rights reserved.\n\n(ns ^{:doc \"\"\n :author \"Kenneth Leung\"}\n\n czlab.loki.player\n\n (:require [czlab.basal.", "end": 663, "score": 0.9998815655708313, "start": 650, "tag": "NAME", "value": "Kenneth Leung" }, { "context": " {:userid userid\n :passwd passwd\n :id (c/x->kw \"player#\" (u/seqint2)", "end": 1465, "score": 0.9984305500984192, "start": 1459, "tag": "PASSWORD", "value": "passwd" } ]
src/main/clojure/czlab/loki/player.clj
llnek/loki
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns ^{:doc "" :author "Kenneth Leung"} czlab.loki.player (:require [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.loki.session :as ss])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; player-db ;; {player-id -> {:p player :s {id -> session}}} (def ^:private player-db (atom {})) ;; map of nicknames (def ^:private userid-db (atom {})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/decl-object<> LokiPlayer) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- player<> "" [userid passwd] (c/object<> LokiPlayer {:userid userid :passwd passwd :id (c/x->kw "player#" (u/seqint2))})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- create-player "" [^String userid ^chars passwd] {:pre [(c/hgl? userid)]} (locking userid-db (if (c/!in? @userid-db userid) (let [p (player<> userid passwd) pid (:id p)] (swap! player-db assoc pid p) (swap! userid-db assoc userid pid)))) (@player-db (@userid-db userid))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn remove-player "" [userid] (locking userid-db (when-some [pid (@userid-db userid)] (swap! userid-db dissoc userid) (swap! player-db dissoc pid)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lookup-player "" ([userid pwd] (create-player userid pwd)) ([userid] (-> (@userid-db userid) (@player-db)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn logout "" [player] (ss/remove-sessions player) (remove-player (:userid player))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
48363
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns ^{:doc "" :author "<NAME>"} czlab.loki.player (:require [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.loki.session :as ss])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; player-db ;; {player-id -> {:p player :s {id -> session}}} (def ^:private player-db (atom {})) ;; map of nicknames (def ^:private userid-db (atom {})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/decl-object<> LokiPlayer) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- player<> "" [userid passwd] (c/object<> LokiPlayer {:userid userid :passwd <PASSWORD> :id (c/x->kw "player#" (u/seqint2))})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- create-player "" [^String userid ^chars passwd] {:pre [(c/hgl? userid)]} (locking userid-db (if (c/!in? @userid-db userid) (let [p (player<> userid passwd) pid (:id p)] (swap! player-db assoc pid p) (swap! userid-db assoc userid pid)))) (@player-db (@userid-db userid))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn remove-player "" [userid] (locking userid-db (when-some [pid (@userid-db userid)] (swap! userid-db dissoc userid) (swap! player-db dissoc pid)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lookup-player "" ([userid pwd] (create-player userid pwd)) ([userid] (-> (@userid-db userid) (@player-db)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn logout "" [player] (ss/remove-sessions player) (remove-player (:userid player))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns ^{:doc "" :author "PI:NAME:<NAME>END_PI"} czlab.loki.player (:require [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.loki.session :as ss])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; player-db ;; {player-id -> {:p player :s {id -> session}}} (def ^:private player-db (atom {})) ;; map of nicknames (def ^:private userid-db (atom {})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/decl-object<> LokiPlayer) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- player<> "" [userid passwd] (c/object<> LokiPlayer {:userid userid :passwd PI:PASSWORD:<PASSWORD>END_PI :id (c/x->kw "player#" (u/seqint2))})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- create-player "" [^String userid ^chars passwd] {:pre [(c/hgl? userid)]} (locking userid-db (if (c/!in? @userid-db userid) (let [p (player<> userid passwd) pid (:id p)] (swap! player-db assoc pid p) (swap! userid-db assoc userid pid)))) (@player-db (@userid-db userid))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn remove-player "" [userid] (locking userid-db (when-some [pid (@userid-db userid)] (swap! userid-db dissoc userid) (swap! player-db dissoc pid)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn lookup-player "" ([userid pwd] (create-player userid pwd)) ([userid] (-> (@userid-db userid) (@player-db)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn logout "" [player] (ss/remove-sessions player) (remove-player (:userid player))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright 2015 Xebia B.V.\n;\n; Licensed under the Apache License, Version 2", "end": 107, "score": 0.9741256833076477, "start": 98, "tag": "NAME", "value": "Xebia B.V" }, { "context": "er user\n :password pass\n :init-pool-size 1\n ", "end": 3198, "score": 0.9985364079475403, "start": 3194, "tag": "PASSWORD", "value": "pass" } ]
src/main/clojure/com/xebia/visualreview/service/persistence/database.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.persistence.database (:require [clojure.java.jdbc :as j] [clojure.java.io :as io] [clojure.tools.logging :as log] [com.xebia.visualreview.service.persistence.util :as putil]) (:import [com.mchange.v2.c3p0 PooledDataSource ComboPooledDataSource] (org.h2.jdbc JdbcSQLException))) (defn pooled-datasource [spec] (let [cpds (doto (ComboPooledDataSource.) (.setDriverClass (:classname spec)) (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) (.setUser (:user spec)) (.setPassword (:password spec)) (.setMaxPoolSize (:max-pool-size spec)) (.setMinPoolSize (:min-pool-size spec)) (.setInitialPoolSize (:init-pool-size spec)) ;; expire excess connections after 30 minutes of inactivity: (.setMaxIdleTimeExcessConnections (* 30 60)) (.setAcquireRetryAttempts 3) ;; expire connections after 3 hours of inactivity: (.setMaxIdleTime (* 3 60 60)))] {:datasource cpds})) (defonce conn {}) (defn- read-db-script [name] (let [res (io/resource (str "dbscripts/h2/" name ".sql"))] (if (nil? res) false (slurp res)))) (defn- run-db-script! [conn script] (j/execute! conn [script])) (defn get-current-schema-version [conn] (let [no-schema-version 0] (or (try (putil/query-single conn ["select svalue from SYSTEM where skey = 'schema_version'"] :row-fn (fn [row] (Long/parseLong (:svalue row)))) (catch JdbcSQLException e no-schema-version)) no-schema-version))) (defn update-db-schema! [conn] (loop [version (inc (get-current-schema-version conn))] (let [db-script (read-db-script version)] (when db-script (do (log/info (str "Running database schema update to version " version " ..")) (run-db-script! conn db-script) (putil/update! conn :system {:svalue version} ["skey = 'schema_version'"]) (log/info (str "..done schema update to version " version)) (recur (inc version))))))) (defn init! [db-uri user pass] {:pre [db-uri user]} (let [db-spec {:classname "org.h2.Driver" :subprotocol "h2" :subname db-uri :user user :password pass :init-pool-size 1 :min-pool-size 1 :max-pool-size 1} conn (alter-var-root #'conn (constantly (pooled-datasource db-spec)))] (do (log/info "Initializing database..") (update-db-schema! conn) (log/info "..done initializing database") conn))) (defn close-connection [] (when-let [db-conn ^PooledDataSource (:datasource conn)] (.close db-conn)))
39773
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; 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.persistence.database (:require [clojure.java.jdbc :as j] [clojure.java.io :as io] [clojure.tools.logging :as log] [com.xebia.visualreview.service.persistence.util :as putil]) (:import [com.mchange.v2.c3p0 PooledDataSource ComboPooledDataSource] (org.h2.jdbc JdbcSQLException))) (defn pooled-datasource [spec] (let [cpds (doto (ComboPooledDataSource.) (.setDriverClass (:classname spec)) (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) (.setUser (:user spec)) (.setPassword (:password spec)) (.setMaxPoolSize (:max-pool-size spec)) (.setMinPoolSize (:min-pool-size spec)) (.setInitialPoolSize (:init-pool-size spec)) ;; expire excess connections after 30 minutes of inactivity: (.setMaxIdleTimeExcessConnections (* 30 60)) (.setAcquireRetryAttempts 3) ;; expire connections after 3 hours of inactivity: (.setMaxIdleTime (* 3 60 60)))] {:datasource cpds})) (defonce conn {}) (defn- read-db-script [name] (let [res (io/resource (str "dbscripts/h2/" name ".sql"))] (if (nil? res) false (slurp res)))) (defn- run-db-script! [conn script] (j/execute! conn [script])) (defn get-current-schema-version [conn] (let [no-schema-version 0] (or (try (putil/query-single conn ["select svalue from SYSTEM where skey = 'schema_version'"] :row-fn (fn [row] (Long/parseLong (:svalue row)))) (catch JdbcSQLException e no-schema-version)) no-schema-version))) (defn update-db-schema! [conn] (loop [version (inc (get-current-schema-version conn))] (let [db-script (read-db-script version)] (when db-script (do (log/info (str "Running database schema update to version " version " ..")) (run-db-script! conn db-script) (putil/update! conn :system {:svalue version} ["skey = 'schema_version'"]) (log/info (str "..done schema update to version " version)) (recur (inc version))))))) (defn init! [db-uri user pass] {:pre [db-uri user]} (let [db-spec {:classname "org.h2.Driver" :subprotocol "h2" :subname db-uri :user user :password <PASSWORD> :init-pool-size 1 :min-pool-size 1 :max-pool-size 1} conn (alter-var-root #'conn (constantly (pooled-datasource db-spec)))] (do (log/info "Initializing database..") (update-db-schema! conn) (log/info "..done initializing database") conn))) (defn close-connection [] (when-let [db-conn ^PooledDataSource (:datasource conn)] (.close db-conn)))
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.persistence.database (:require [clojure.java.jdbc :as j] [clojure.java.io :as io] [clojure.tools.logging :as log] [com.xebia.visualreview.service.persistence.util :as putil]) (:import [com.mchange.v2.c3p0 PooledDataSource ComboPooledDataSource] (org.h2.jdbc JdbcSQLException))) (defn pooled-datasource [spec] (let [cpds (doto (ComboPooledDataSource.) (.setDriverClass (:classname spec)) (.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec))) (.setUser (:user spec)) (.setPassword (:password spec)) (.setMaxPoolSize (:max-pool-size spec)) (.setMinPoolSize (:min-pool-size spec)) (.setInitialPoolSize (:init-pool-size spec)) ;; expire excess connections after 30 minutes of inactivity: (.setMaxIdleTimeExcessConnections (* 30 60)) (.setAcquireRetryAttempts 3) ;; expire connections after 3 hours of inactivity: (.setMaxIdleTime (* 3 60 60)))] {:datasource cpds})) (defonce conn {}) (defn- read-db-script [name] (let [res (io/resource (str "dbscripts/h2/" name ".sql"))] (if (nil? res) false (slurp res)))) (defn- run-db-script! [conn script] (j/execute! conn [script])) (defn get-current-schema-version [conn] (let [no-schema-version 0] (or (try (putil/query-single conn ["select svalue from SYSTEM where skey = 'schema_version'"] :row-fn (fn [row] (Long/parseLong (:svalue row)))) (catch JdbcSQLException e no-schema-version)) no-schema-version))) (defn update-db-schema! [conn] (loop [version (inc (get-current-schema-version conn))] (let [db-script (read-db-script version)] (when db-script (do (log/info (str "Running database schema update to version " version " ..")) (run-db-script! conn db-script) (putil/update! conn :system {:svalue version} ["skey = 'schema_version'"]) (log/info (str "..done schema update to version " version)) (recur (inc version))))))) (defn init! [db-uri user pass] {:pre [db-uri user]} (let [db-spec {:classname "org.h2.Driver" :subprotocol "h2" :subname db-uri :user user :password PI:PASSWORD:<PASSWORD>END_PI :init-pool-size 1 :min-pool-size 1 :max-pool-size 1} conn (alter-var-root #'conn (constantly (pooled-datasource db-spec)))] (do (log/info "Initializing database..") (update-db-schema! conn) (log/info "..done initializing database") conn))) (defn close-connection [] (when-let [db-conn ^PooledDataSource (:datasource conn)] (.close db-conn)))
[ { "context": "(ns ^{:author \"Yuji Hamaguchi\"}\n excelAsRDS.Utility\n (:require [clojure.data.", "end": 29, "score": 0.9998692870140076, "start": 15, "tag": "NAME", "value": "Yuji Hamaguchi" } ]
src/excelAsRDS/Utility.clj
yujihamaguchi/excelAsRDS
1
(ns ^{:author "Yuji Hamaguchi"} excelAsRDS.Utility (:require [clojure.data.json :as json :only [read-json write-str]] [clojure.java.io :as io :only [reader]] [clojure.set :refer :all]) (:gen-class :name excelAsRDS.Utility :methods [#^{:static true} [isEqualJSONStrAsSet [String String] Boolean] #^{:static true} [differenceJSONStrAsSet [String String] String]])) (defn isEqualJSONStrAsSet "Returns true if arguments are equal to each other as set, false otherwise." [set1-json set2-json] (let [set1 (set (json/read-json set1-json)) set2 (set (json/read-json set2-json))] (= set1 set2))) (defn -isEqualJSONStrAsSet [set1-json set2-json] (isEqualJSONStrAsSet set1-json set2-json)) (defn differenceJSONStrAsSet "Returns different arguments. (set1 - set2)" [set1-json set2-json] (let [set1 (set (json/read-json set1-json)) set2 (set (json/read-json set2-json))] (json/write-str (difference set1 set2)))) (defn -differenceJSONStrAsSet [set1-json set2-json] (differenceJSONStrAsSet set1-json set2-json))
67776
(ns ^{:author "<NAME>"} excelAsRDS.Utility (:require [clojure.data.json :as json :only [read-json write-str]] [clojure.java.io :as io :only [reader]] [clojure.set :refer :all]) (:gen-class :name excelAsRDS.Utility :methods [#^{:static true} [isEqualJSONStrAsSet [String String] Boolean] #^{:static true} [differenceJSONStrAsSet [String String] String]])) (defn isEqualJSONStrAsSet "Returns true if arguments are equal to each other as set, false otherwise." [set1-json set2-json] (let [set1 (set (json/read-json set1-json)) set2 (set (json/read-json set2-json))] (= set1 set2))) (defn -isEqualJSONStrAsSet [set1-json set2-json] (isEqualJSONStrAsSet set1-json set2-json)) (defn differenceJSONStrAsSet "Returns different arguments. (set1 - set2)" [set1-json set2-json] (let [set1 (set (json/read-json set1-json)) set2 (set (json/read-json set2-json))] (json/write-str (difference set1 set2)))) (defn -differenceJSONStrAsSet [set1-json set2-json] (differenceJSONStrAsSet set1-json set2-json))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} excelAsRDS.Utility (:require [clojure.data.json :as json :only [read-json write-str]] [clojure.java.io :as io :only [reader]] [clojure.set :refer :all]) (:gen-class :name excelAsRDS.Utility :methods [#^{:static true} [isEqualJSONStrAsSet [String String] Boolean] #^{:static true} [differenceJSONStrAsSet [String String] String]])) (defn isEqualJSONStrAsSet "Returns true if arguments are equal to each other as set, false otherwise." [set1-json set2-json] (let [set1 (set (json/read-json set1-json)) set2 (set (json/read-json set2-json))] (= set1 set2))) (defn -isEqualJSONStrAsSet [set1-json set2-json] (isEqualJSONStrAsSet set1-json set2-json)) (defn differenceJSONStrAsSet "Returns different arguments. (set1 - set2)" [set1-json set2-json] (let [set1 (set (json/read-json set1-json)) set2 (set (json/read-json set2-json))] (json/write-str (difference set1 set2)))) (defn -differenceJSONStrAsSet [set1-json set2-json] (differenceJSONStrAsSet set1-json set2-json))
[ { "context": ";; Authors: Sung Pae <self@sungpae.com>\n\n(ns vim-clojure-static.test\n ", "end": 20, "score": 0.9998809695243835, "start": 12, "tag": "NAME", "value": "Sung Pae" }, { "context": ";; Authors: Sung Pae <self@sungpae.com>\n\n(ns vim-clojure-static.test\n (:require [clojur", "end": 38, "score": 0.9999278783798218, "start": 22, "tag": "EMAIL", "value": "self@sungpae.com" } ]
dot_vim/bundle/vim-clojure-static/clj/src/vim_clojure_static/test.clj
nyimbi/dot_files
1
;; Authors: Sung Pae <self@sungpae.com> (ns vim-clojure-static.test (:require [clojure.edn :as edn] [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.string :as string] [clojure.test :as test]) (:import (java.io File) (java.util List))) (defn vim-exec "Spit buf into file, then execute vim-expr after Vim loads the file. The value of vim-expr is evaluated as EDN and returned." [file buf vim-expr] (let [tmp (File/createTempFile "vim-clojure-static.test." ".out")] (try (io/make-parents file) (spit file buf) (spit tmp (str "let @x = " vim-expr)) (shell/sh "vim" "-N" "-u" "vim/test-runtime.vim" "-c" (str "source " tmp " | call writefile([@x], " (pr-str (str tmp)) ") | quitall!") file) (edn/read-string (slurp tmp)) (finally (.delete tmp))))) (defn syn-id-names "Map lines of clojure text to vim synID names at each column as keywords: (syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …} First parameter is the file that is used to communicate with Vim. The file is not deleted to allow manual inspection." [file & lines] (into {} (map (fn [l ids] [l (mapv keyword ids)]) lines (vim-exec file (string/join \newline lines) "ClojureSynIDNames()")))) (defn subfmt "Extract a subsequence of seq s corresponding to the character positions of %s in format spec fmt" [fmt s] (let [f (seq (format fmt \o001)) i (.indexOf ^List f \o001)] (->> s (drop i) (drop-last (- (count f) i 1))))) (defmacro defsyntaxtest "Create a new testing var with tests in the format: (defsyntaxtest example [format [test-string test-predicate …]] [\"#\\\"%s\\\"\" [\"123\" #(every? (partial = :clojureRegexp) %) …]] […]) At runtime the syn-id-names of the strings (which are placed in the format spec) are passed to their associated predicates. The format spec should contain a single `%s`." {:require [#'test/deftest]} [name & body] (assert (every? (fn [[fmt tests]] (and (string? fmt) (coll? tests) (even? (count tests)))) body)) (let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]] (let [[ss λs] (apply map list (partition 2 tests)) ss (map #(format fmt %) ss)] [(concat strings ss) (conj contexts {:fmt fmt :ss ss :λs λs})])) [[] []] body) syntable (gensym "syntable")] `(test/deftest ~name ;; Shellout to vim should happen at runtime (let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)] ~@(map (fn [{:keys [fmt ss λs]}] `(test/testing ~fmt ~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s))))) ss λs))) contexts))))) (defmacro defpredicates "Create two complementary predicate vars, `sym` and `!sym`, which test if all members of a passed collection are equal to `kw`" [sym kw] `(do (defn ~sym ~(str "Returns true if all elements of coll equal " kw) {:arglists '~'[coll]} [coll#] (every? (partial = ~kw) coll#)) (defn ~(symbol (str \! sym)) ~(str "Returns true if any alements of coll do not equal " kw) {:arglists '~'[coll]} [coll#] (boolean (some (partial not= ~kw) coll#))))) (defn benchmark [n file buf & exprs] (vim-exec file buf (format "Benchmark(%d, %s)" n (string/join \, (map pr-str exprs)))))
69604
;; Authors: <NAME> <<EMAIL>> (ns vim-clojure-static.test (:require [clojure.edn :as edn] [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.string :as string] [clojure.test :as test]) (:import (java.io File) (java.util List))) (defn vim-exec "Spit buf into file, then execute vim-expr after Vim loads the file. The value of vim-expr is evaluated as EDN and returned." [file buf vim-expr] (let [tmp (File/createTempFile "vim-clojure-static.test." ".out")] (try (io/make-parents file) (spit file buf) (spit tmp (str "let @x = " vim-expr)) (shell/sh "vim" "-N" "-u" "vim/test-runtime.vim" "-c" (str "source " tmp " | call writefile([@x], " (pr-str (str tmp)) ") | quitall!") file) (edn/read-string (slurp tmp)) (finally (.delete tmp))))) (defn syn-id-names "Map lines of clojure text to vim synID names at each column as keywords: (syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …} First parameter is the file that is used to communicate with Vim. The file is not deleted to allow manual inspection." [file & lines] (into {} (map (fn [l ids] [l (mapv keyword ids)]) lines (vim-exec file (string/join \newline lines) "ClojureSynIDNames()")))) (defn subfmt "Extract a subsequence of seq s corresponding to the character positions of %s in format spec fmt" [fmt s] (let [f (seq (format fmt \o001)) i (.indexOf ^List f \o001)] (->> s (drop i) (drop-last (- (count f) i 1))))) (defmacro defsyntaxtest "Create a new testing var with tests in the format: (defsyntaxtest example [format [test-string test-predicate …]] [\"#\\\"%s\\\"\" [\"123\" #(every? (partial = :clojureRegexp) %) …]] […]) At runtime the syn-id-names of the strings (which are placed in the format spec) are passed to their associated predicates. The format spec should contain a single `%s`." {:require [#'test/deftest]} [name & body] (assert (every? (fn [[fmt tests]] (and (string? fmt) (coll? tests) (even? (count tests)))) body)) (let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]] (let [[ss λs] (apply map list (partition 2 tests)) ss (map #(format fmt %) ss)] [(concat strings ss) (conj contexts {:fmt fmt :ss ss :λs λs})])) [[] []] body) syntable (gensym "syntable")] `(test/deftest ~name ;; Shellout to vim should happen at runtime (let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)] ~@(map (fn [{:keys [fmt ss λs]}] `(test/testing ~fmt ~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s))))) ss λs))) contexts))))) (defmacro defpredicates "Create two complementary predicate vars, `sym` and `!sym`, which test if all members of a passed collection are equal to `kw`" [sym kw] `(do (defn ~sym ~(str "Returns true if all elements of coll equal " kw) {:arglists '~'[coll]} [coll#] (every? (partial = ~kw) coll#)) (defn ~(symbol (str \! sym)) ~(str "Returns true if any alements of coll do not equal " kw) {:arglists '~'[coll]} [coll#] (boolean (some (partial not= ~kw) coll#))))) (defn benchmark [n file buf & exprs] (vim-exec file buf (format "Benchmark(%d, %s)" n (string/join \, (map pr-str exprs)))))
true
;; Authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (ns vim-clojure-static.test (:require [clojure.edn :as edn] [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.string :as string] [clojure.test :as test]) (:import (java.io File) (java.util List))) (defn vim-exec "Spit buf into file, then execute vim-expr after Vim loads the file. The value of vim-expr is evaluated as EDN and returned." [file buf vim-expr] (let [tmp (File/createTempFile "vim-clojure-static.test." ".out")] (try (io/make-parents file) (spit file buf) (spit tmp (str "let @x = " vim-expr)) (shell/sh "vim" "-N" "-u" "vim/test-runtime.vim" "-c" (str "source " tmp " | call writefile([@x], " (pr-str (str tmp)) ") | quitall!") file) (edn/read-string (slurp tmp)) (finally (.delete tmp))))) (defn syn-id-names "Map lines of clojure text to vim synID names at each column as keywords: (syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …} First parameter is the file that is used to communicate with Vim. The file is not deleted to allow manual inspection." [file & lines] (into {} (map (fn [l ids] [l (mapv keyword ids)]) lines (vim-exec file (string/join \newline lines) "ClojureSynIDNames()")))) (defn subfmt "Extract a subsequence of seq s corresponding to the character positions of %s in format spec fmt" [fmt s] (let [f (seq (format fmt \o001)) i (.indexOf ^List f \o001)] (->> s (drop i) (drop-last (- (count f) i 1))))) (defmacro defsyntaxtest "Create a new testing var with tests in the format: (defsyntaxtest example [format [test-string test-predicate …]] [\"#\\\"%s\\\"\" [\"123\" #(every? (partial = :clojureRegexp) %) …]] […]) At runtime the syn-id-names of the strings (which are placed in the format spec) are passed to their associated predicates. The format spec should contain a single `%s`." {:require [#'test/deftest]} [name & body] (assert (every? (fn [[fmt tests]] (and (string? fmt) (coll? tests) (even? (count tests)))) body)) (let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]] (let [[ss λs] (apply map list (partition 2 tests)) ss (map #(format fmt %) ss)] [(concat strings ss) (conj contexts {:fmt fmt :ss ss :λs λs})])) [[] []] body) syntable (gensym "syntable")] `(test/deftest ~name ;; Shellout to vim should happen at runtime (let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)] ~@(map (fn [{:keys [fmt ss λs]}] `(test/testing ~fmt ~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s))))) ss λs))) contexts))))) (defmacro defpredicates "Create two complementary predicate vars, `sym` and `!sym`, which test if all members of a passed collection are equal to `kw`" [sym kw] `(do (defn ~sym ~(str "Returns true if all elements of coll equal " kw) {:arglists '~'[coll]} [coll#] (every? (partial = ~kw) coll#)) (defn ~(symbol (str \! sym)) ~(str "Returns true if any alements of coll do not equal " kw) {:arglists '~'[coll]} [coll#] (boolean (some (partial not= ~kw) coll#))))) (defn benchmark [n file buf & exprs] (vim-exec file buf (format "Benchmark(%d, %s)" n (string/join \, (map pr-str exprs)))))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998596906661987, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "ice, or any other, from this software.\n\n;; Author: Shawn Hoover\n\n(ns clojure.test-clojure.agents\n (:use clojure.", "end": 487, "score": 0.9998934864997864, "start": 475, "tag": "NAME", "value": "Shawn Hoover" } ]
ThirdParty/clojure-1.1.0/test/clojure/test_clojure/agents.clj
allertonm/Couverjure
3
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;; Author: Shawn Hoover (ns clojure.test-clojure.agents (:use clojure.test)) (deftest handle-all-throwables-during-agent-actions ;; Bug fixed in r1198; previously hung Clojure or didn't report agent errors ;; after OutOfMemoryError, yet wouldn't execute new actions. (let [agt (agent nil)] (send agt (fn [state] (throw (Throwable. "just testing Throwables")))) (try ;; Let the action finish; eat the "agent has errors" error that bubbles up (await agt) (catch RuntimeException _)) (is (instance? Throwable (first (agent-errors agt)))) (is (= 1 (count (agent-errors agt)))) ;; And now send an action that should work (clear-agent-errors agt) (is (= nil @agt)) (send agt nil?) (await agt) (is (true? @agt)))) ; http://clojure.org/agents ; agent ; deref, @-reader-macro, agent-errors ; send send-off clear-agent-errors ; await await-for ; set-validator get-validator ; add-watch remove-watch ; shutdown-agents
4231
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;; Author: <NAME> (ns clojure.test-clojure.agents (:use clojure.test)) (deftest handle-all-throwables-during-agent-actions ;; Bug fixed in r1198; previously hung Clojure or didn't report agent errors ;; after OutOfMemoryError, yet wouldn't execute new actions. (let [agt (agent nil)] (send agt (fn [state] (throw (Throwable. "just testing Throwables")))) (try ;; Let the action finish; eat the "agent has errors" error that bubbles up (await agt) (catch RuntimeException _)) (is (instance? Throwable (first (agent-errors agt)))) (is (= 1 (count (agent-errors agt)))) ;; And now send an action that should work (clear-agent-errors agt) (is (= nil @agt)) (send agt nil?) (await agt) (is (true? @agt)))) ; http://clojure.org/agents ; agent ; deref, @-reader-macro, agent-errors ; send send-off clear-agent-errors ; await await-for ; set-validator get-validator ; add-watch remove-watch ; shutdown-agents
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. ;; Author: PI:NAME:<NAME>END_PI (ns clojure.test-clojure.agents (:use clojure.test)) (deftest handle-all-throwables-during-agent-actions ;; Bug fixed in r1198; previously hung Clojure or didn't report agent errors ;; after OutOfMemoryError, yet wouldn't execute new actions. (let [agt (agent nil)] (send agt (fn [state] (throw (Throwable. "just testing Throwables")))) (try ;; Let the action finish; eat the "agent has errors" error that bubbles up (await agt) (catch RuntimeException _)) (is (instance? Throwable (first (agent-errors agt)))) (is (= 1 (count (agent-errors agt)))) ;; And now send an action that should work (clear-agent-errors agt) (is (= nil @agt)) (send agt nil?) (await agt) (is (true? @agt)))) ; http://clojure.org/agents ; agent ; deref, @-reader-macro, agent-errors ; send send-off clear-agent-errors ; await await-for ; set-validator get-validator ; add-watch remove-watch ; shutdown-agents
[ { "context": " \"--driver\" \"mysql\" \"--host\" \"127.0.0.1\" \"--port\" \"3306\"\n \"--dbuser\"", "end": 222, "score": 0.9997088313102722, "start": 213, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " \"--dbuser\" \"root\" \"--dbpass\" dbpwd\n \"--dbname\" dbname\n ", "end": 296, "score": 0.9111843109130859, "start": 291, "tag": "PASSWORD", "value": "dbpwd" } ]
services/load-genbank.clj
jsa-aerial/aerobio
3
{ :name "load-genbank", :path "", :func (fn [dbname dbpwd gbfile] (if (pg/eoi? gbfile) (pg/done) (let [ret (pg/bp_load_genbank "--driver" "mysql" "--host" "127.0.0.1" "--port" "3306" "--dbuser" "root" "--dbpass" dbpwd "--dbname" dbname "--format" "genbank" "--safe" "--noupdate" "--lookup" gbfile {:verbose true :throw false}) exit-code @(ret :exit-code) exit (if (= 0 exit-code) :success exit-code) err (get-in ret [:proc :err])] {:name "load-genbank" :value gbfile :exit exit :err (mapv identity err)}))) :description "Function wrapping bp_load_seqdatabase.pl with params for genbank files. dbname is the biosql database to load data into and dbpwd is the pw for the root user." }
6930
{ :name "load-genbank", :path "", :func (fn [dbname dbpwd gbfile] (if (pg/eoi? gbfile) (pg/done) (let [ret (pg/bp_load_genbank "--driver" "mysql" "--host" "127.0.0.1" "--port" "3306" "--dbuser" "root" "--dbpass" <PASSWORD> "--dbname" dbname "--format" "genbank" "--safe" "--noupdate" "--lookup" gbfile {:verbose true :throw false}) exit-code @(ret :exit-code) exit (if (= 0 exit-code) :success exit-code) err (get-in ret [:proc :err])] {:name "load-genbank" :value gbfile :exit exit :err (mapv identity err)}))) :description "Function wrapping bp_load_seqdatabase.pl with params for genbank files. dbname is the biosql database to load data into and dbpwd is the pw for the root user." }
true
{ :name "load-genbank", :path "", :func (fn [dbname dbpwd gbfile] (if (pg/eoi? gbfile) (pg/done) (let [ret (pg/bp_load_genbank "--driver" "mysql" "--host" "127.0.0.1" "--port" "3306" "--dbuser" "root" "--dbpass" PI:PASSWORD:<PASSWORD>END_PI "--dbname" dbname "--format" "genbank" "--safe" "--noupdate" "--lookup" gbfile {:verbose true :throw false}) exit-code @(ret :exit-code) exit (if (= 0 exit-code) :success exit-code) err (get-in ret [:proc :err])] {:name "load-genbank" :value gbfile :exit exit :err (mapv identity err)}))) :description "Function wrapping bp_load_seqdatabase.pl with params for genbank files. dbname is the biosql database to load data into and dbpwd is the pw for the root user." }
[ { "context": "(comment\n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License", "end": 48, "score": 0.9998836517333984, "start": 36, "tag": "NAME", "value": "Ronen Narkis" }, { "context": "comment\n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version ", "end": 61, "score": 0.8654582500457764, "start": 51, "tag": "EMAIL", "value": "arkisr.com" } ]
src/re_core/security.clj
celestial-ops/core
1
(comment re-core, Copyright 2012 Ronen Narkis, narkisr.com Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns re-core.security (:use [re-core.common :only (gen-uuid)] [gelfino.timbre :only (set-tid)] [re-core.common :only (import-logging)]) (:require [slingshot.slingshot :refer [throw+ try+]] [re-core.roles :as roles] [re-core.persistency.users :as u] [clojure.core.strint :refer (<<)] [cemerick.friend :as friend] (cemerick.friend [workflows :as workflows] [credentials :as creds]))) (import-logging) (def ^:dynamic current-user "Grab current user, by default uses friend unless binded differently" (fn [] (friend/current-authentication))) (defmacro set-user [u & body] `(binding [current-user (fn [] ~u)] ~@body)) (defn user-tracking [app] "A tiny middleware to track api access" (fn [{:keys [uri request-method] :as req}] (set-tid (gen-uuid) (info request-method " on " uri "by" (current-user)) (app req)))) (defn login-redirect [{:keys [form-params params] :as request}] (let [ user (java.net.URLEncoder/encode (or (get form-params "username") (:username params ""))) param (<< "&login_failed=Y&user=~{user}")] (ring.util.response/redirect (<< "/login?~{param}")))) (defn sign-in-resp [req] {:status 401 :body "please sign in first"}) (defn user-with-pass [id] {:post [(not-empty (% :password ))]} (u/get-user! id)) (defn check-creds "Runs bcrypt password check if user exists" [creds] (if (u/user-exists? (:username creds)) (try (creds/bcrypt-credential-fn user-with-pass creds) (catch IllegalArgumentException e (throw+ {} "Please ask admin to reset your password, persisted hashed version has been correupted"))) nil)) (defn secured-app [routes] (friend/authenticate (friend/wrap-authorize (user-tracking routes) roles/user) {:allow-anon? false :credential-fn check-creds :unauthenticated-handler sign-in-resp :workflows [ (workflows/interactive-form :login-failure-handler login-redirect) (workflows/http-basic :realm "basic-re-core")]}))
2348
(comment re-core, Copyright 2012 <NAME>, n<EMAIL> Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns re-core.security (:use [re-core.common :only (gen-uuid)] [gelfino.timbre :only (set-tid)] [re-core.common :only (import-logging)]) (:require [slingshot.slingshot :refer [throw+ try+]] [re-core.roles :as roles] [re-core.persistency.users :as u] [clojure.core.strint :refer (<<)] [cemerick.friend :as friend] (cemerick.friend [workflows :as workflows] [credentials :as creds]))) (import-logging) (def ^:dynamic current-user "Grab current user, by default uses friend unless binded differently" (fn [] (friend/current-authentication))) (defmacro set-user [u & body] `(binding [current-user (fn [] ~u)] ~@body)) (defn user-tracking [app] "A tiny middleware to track api access" (fn [{:keys [uri request-method] :as req}] (set-tid (gen-uuid) (info request-method " on " uri "by" (current-user)) (app req)))) (defn login-redirect [{:keys [form-params params] :as request}] (let [ user (java.net.URLEncoder/encode (or (get form-params "username") (:username params ""))) param (<< "&login_failed=Y&user=~{user}")] (ring.util.response/redirect (<< "/login?~{param}")))) (defn sign-in-resp [req] {:status 401 :body "please sign in first"}) (defn user-with-pass [id] {:post [(not-empty (% :password ))]} (u/get-user! id)) (defn check-creds "Runs bcrypt password check if user exists" [creds] (if (u/user-exists? (:username creds)) (try (creds/bcrypt-credential-fn user-with-pass creds) (catch IllegalArgumentException e (throw+ {} "Please ask admin to reset your password, persisted hashed version has been correupted"))) nil)) (defn secured-app [routes] (friend/authenticate (friend/wrap-authorize (user-tracking routes) roles/user) {:allow-anon? false :credential-fn check-creds :unauthenticated-handler sign-in-resp :workflows [ (workflows/interactive-form :login-failure-handler login-redirect) (workflows/http-basic :realm "basic-re-core")]}))
true
(comment re-core, Copyright 2012 PI:NAME:<NAME>END_PI, nPI:EMAIL:<EMAIL>END_PI Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.) (ns re-core.security (:use [re-core.common :only (gen-uuid)] [gelfino.timbre :only (set-tid)] [re-core.common :only (import-logging)]) (:require [slingshot.slingshot :refer [throw+ try+]] [re-core.roles :as roles] [re-core.persistency.users :as u] [clojure.core.strint :refer (<<)] [cemerick.friend :as friend] (cemerick.friend [workflows :as workflows] [credentials :as creds]))) (import-logging) (def ^:dynamic current-user "Grab current user, by default uses friend unless binded differently" (fn [] (friend/current-authentication))) (defmacro set-user [u & body] `(binding [current-user (fn [] ~u)] ~@body)) (defn user-tracking [app] "A tiny middleware to track api access" (fn [{:keys [uri request-method] :as req}] (set-tid (gen-uuid) (info request-method " on " uri "by" (current-user)) (app req)))) (defn login-redirect [{:keys [form-params params] :as request}] (let [ user (java.net.URLEncoder/encode (or (get form-params "username") (:username params ""))) param (<< "&login_failed=Y&user=~{user}")] (ring.util.response/redirect (<< "/login?~{param}")))) (defn sign-in-resp [req] {:status 401 :body "please sign in first"}) (defn user-with-pass [id] {:post [(not-empty (% :password ))]} (u/get-user! id)) (defn check-creds "Runs bcrypt password check if user exists" [creds] (if (u/user-exists? (:username creds)) (try (creds/bcrypt-credential-fn user-with-pass creds) (catch IllegalArgumentException e (throw+ {} "Please ask admin to reset your password, persisted hashed version has been correupted"))) nil)) (defn secured-app [routes] (friend/authenticate (friend/wrap-authorize (user-tracking routes) roles/user) {:allow-anon? false :credential-fn check-creds :unauthenticated-handler sign-in-resp :workflows [ (workflows/interactive-form :login-failure-handler login-redirect) (workflows/http-basic :realm "basic-re-core")]}))
[ { "context": ":doc \"Digest Creation for Pandect\"\n :author \"Yannick Scherer\"}\n pandect.core\n (:require [pandect.buffer :ref", "end": 71, "score": 0.9998447895050049, "start": 56, "tag": "NAME", "value": "Yannick Scherer" } ]
src/clojure/pandect/core.clj
projetoeureka/pandect
0
(ns ^{:doc "Digest Creation for Pandect" :author "Yannick Scherer"} pandect.core (:require [pandect.buffer :refer [*buffer-size*]] [pandect.utils.potemkin :refer [import-vars]] [pandect.codegen :refer [algorithms algorithm-namespace]])) (set! *warn-on-reflection* true) (set! *unchecked-math* true) ;; ## Re-export all algorithms (defn- collect-algorithm-functions [ns algorithm-symbol] (require ns) (let [s (name algorithm-symbol)] (->> (ns-publics ns) (map (comp first)) (filter #(.startsWith (name %) s))))) (defmacro ^:private reexport-algos [] `(do (import-vars pandect.buffer/with-buffer-size) ~@(for [algo (algorithms) :let [ns (algorithm-namespace algo)]] `(do (require '~ns) (import-vars [~ns ~@(collect-algorithm-functions ns algo)]))))) (reexport-algos)
104999
(ns ^{:doc "Digest Creation for Pandect" :author "<NAME>"} pandect.core (:require [pandect.buffer :refer [*buffer-size*]] [pandect.utils.potemkin :refer [import-vars]] [pandect.codegen :refer [algorithms algorithm-namespace]])) (set! *warn-on-reflection* true) (set! *unchecked-math* true) ;; ## Re-export all algorithms (defn- collect-algorithm-functions [ns algorithm-symbol] (require ns) (let [s (name algorithm-symbol)] (->> (ns-publics ns) (map (comp first)) (filter #(.startsWith (name %) s))))) (defmacro ^:private reexport-algos [] `(do (import-vars pandect.buffer/with-buffer-size) ~@(for [algo (algorithms) :let [ns (algorithm-namespace algo)]] `(do (require '~ns) (import-vars [~ns ~@(collect-algorithm-functions ns algo)]))))) (reexport-algos)
true
(ns ^{:doc "Digest Creation for Pandect" :author "PI:NAME:<NAME>END_PI"} pandect.core (:require [pandect.buffer :refer [*buffer-size*]] [pandect.utils.potemkin :refer [import-vars]] [pandect.codegen :refer [algorithms algorithm-namespace]])) (set! *warn-on-reflection* true) (set! *unchecked-math* true) ;; ## Re-export all algorithms (defn- collect-algorithm-functions [ns algorithm-symbol] (require ns) (let [s (name algorithm-symbol)] (->> (ns-publics ns) (map (comp first)) (filter #(.startsWith (name %) s))))) (defmacro ^:private reexport-algos [] `(do (import-vars pandect.buffer/with-buffer-size) ~@(for [algo (algorithms) :let [ns (algorithm-namespace algo)]] `(do (require '~ns) (import-vars [~ns ~@(collect-algorithm-functions ns algo)]))))) (reexport-algos)
[ { "context": "ades.lakes.elements.java.numbers.sum\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-03-27\"\n :version \"2017-04-20\"}", "end": 303, "score": 0.9863373041152954, "start": 267, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/test/clojure/palisades/lakes/elements/test/numbers/sum.clj
palisades-lakes/les-elemens
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.test.numbers.sum {:doc "Unit tests for palisades.lakes.elements.java.numbers.sum" :author "palisades dot lakes at gmail dot com" :since "2017-03-27" :version "2017-04-20"} (:require [clojure.test :as test] [palisades.lakes.elements.api :as mc]) (:import [java.math BigDecimal] [clojure.lang Numbers Ratio] [palisades.lakes.elements.java.numbers.sum Kahan Naive Pairwise])) ;;---------------------------------------------------------------- (def integers [1 2 3 4]) (def fractions [0.1 0.2 0.3 0.4]) ;;---------------------------------------------------------------- (test/deftest naive (let [x (double-array integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (double-array fractions)] (test/is (== 1.0 (Naive/sum x)))) (let [x (mc/array-of-BigDecimal integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (mc/array-of-BigDecimal fractions)] (test/is (== 1.0 (Naive/sum x)))) (let [x (mc/array-of-Ratio integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (mc/array-of-Ratio fractions)] (test/is (== 1.0 (Naive/sum x))))) ;---------------------------------------------------------------- (test/deftest pairwise (let [x (double-array [1.0 2.0 3.0 4.0])] (test/is (== 10.0 (Pairwise/sum x))))) ;;----------------------------------------------------------------
47976
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.test.numbers.sum {:doc "Unit tests for palisades.lakes.elements.java.numbers.sum" :author "<EMAIL>" :since "2017-03-27" :version "2017-04-20"} (:require [clojure.test :as test] [palisades.lakes.elements.api :as mc]) (:import [java.math BigDecimal] [clojure.lang Numbers Ratio] [palisades.lakes.elements.java.numbers.sum Kahan Naive Pairwise])) ;;---------------------------------------------------------------- (def integers [1 2 3 4]) (def fractions [0.1 0.2 0.3 0.4]) ;;---------------------------------------------------------------- (test/deftest naive (let [x (double-array integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (double-array fractions)] (test/is (== 1.0 (Naive/sum x)))) (let [x (mc/array-of-BigDecimal integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (mc/array-of-BigDecimal fractions)] (test/is (== 1.0 (Naive/sum x)))) (let [x (mc/array-of-Ratio integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (mc/array-of-Ratio fractions)] (test/is (== 1.0 (Naive/sum x))))) ;---------------------------------------------------------------- (test/deftest pairwise (let [x (double-array [1.0 2.0 3.0 4.0])] (test/is (== 10.0 (Pairwise/sum x))))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.elements.test.numbers.sum {:doc "Unit tests for palisades.lakes.elements.java.numbers.sum" :author "PI:EMAIL:<EMAIL>END_PI" :since "2017-03-27" :version "2017-04-20"} (:require [clojure.test :as test] [palisades.lakes.elements.api :as mc]) (:import [java.math BigDecimal] [clojure.lang Numbers Ratio] [palisades.lakes.elements.java.numbers.sum Kahan Naive Pairwise])) ;;---------------------------------------------------------------- (def integers [1 2 3 4]) (def fractions [0.1 0.2 0.3 0.4]) ;;---------------------------------------------------------------- (test/deftest naive (let [x (double-array integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (double-array fractions)] (test/is (== 1.0 (Naive/sum x)))) (let [x (mc/array-of-BigDecimal integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (mc/array-of-BigDecimal fractions)] (test/is (== 1.0 (Naive/sum x)))) (let [x (mc/array-of-Ratio integers)] (test/is (== 10.0 (Naive/sum x)))) (let [x (mc/array-of-Ratio fractions)] (test/is (== 1.0 (Naive/sum x))))) ;---------------------------------------------------------------- (test/deftest pairwise (let [x (double-array [1.0 2.0 3.0 4.0])] (test/is (== 10.0 (Pairwise/sum x))))) ;;----------------------------------------------------------------
[ { "context": "]))\n\n(deftest test-outfields-query\n (let [age [[\"nathan\" 25]]]\n (is (= [\"?age\"]\n (get-out-fi", "end": 257, "score": 0.9647773504257202, "start": 251, "tag": "NAME", "value": "nathan" }, { "context": "sum+1))))\n\n(deftest test-construct\n (let [age [[\"alice\" 25] [\"bob\" 30]]\n gender [[\"alice\" \"f\"]\n ", "end": 1715, "score": 0.9655424356460571, "start": 1710, "tag": "NAME", "value": "alice" }, { "context": "eftest test-construct\n (let [age [[\"alice\" 25] [\"bob\" 30]]\n gender [[\"alice\" \"f\"]\n ", "end": 1726, "score": 0.9166949987411499, "start": 1723, "tag": "NAME", "value": "bob" }, { "context": "]\n gender [[\"alice\" \"f\"]\n [\"charlie\" \"m\"]]]\n (test?- [[\"alice\" 26 \"f\"]\n ", "end": 1788, "score": 0.8556690812110901, "start": 1781, "tag": "NAME", "value": "charlie" }, { "context": "\n [\"charlie\" \"m\"]]]\n (test?- [[\"alice\" 26 \"f\"]\n [\"bob\" 31 nil]]\n ", "end": 1817, "score": 0.9052191376686096, "start": 1812, "tag": "NAME", "value": "alice" }, { "context": "\"]]]\n (test?- [[\"alice\" 26 \"f\"]\n [\"bob\" 31 nil]]\n (apply construct\n ", "end": 1845, "score": 0.8650097250938416, "start": 1842, "tag": "NAME", "value": "bob" }, { "context": "urns\n (let [nums [[1] [2] [3]]\n people [[\"alice\"] [\"bob\"]]]\n (is (= (set [[1] [3]])\n ", "end": 5088, "score": 0.963117778301239, "start": 5083, "tag": "NAME", "value": "alice" }, { "context": "t [nums [[1] [2] [3]]\n people [[\"alice\"] [\"bob\"]]]\n (is (= (set [[1] [3]])\n (set (?", "end": 5096, "score": 0.9572641849517822, "start": 5093, "tag": "NAME", "value": "bob" }, { "context": " (set (first res))))\n (is (= (set [[\"alicea\"] [\"boba\"]])\n (set (second res)))))))", "end": 5674, "score": 0.8017705678939819, "start": 5668, "tag": "NAME", "value": "alicea" }, { "context": "et (first res))))\n (is (= (set [[\"alicea\"] [\"boba\"]])\n (set (second res)))))))\n\n(deftes", "end": 5683, "score": 0.558775007724762, "start": 5679, "tag": "NAME", "value": "boba" }, { "context": ")))))))\n\n(deftest test-negation\n (let [age [[\"nathan\" 25] [\"nathan\" 24]\n [\"alice\" 23] [", "end": 5773, "score": 0.9880273342132568, "start": 5767, "tag": "NAME", "value": "nathan" }, { "context": "est test-negation\n (let [age [[\"nathan\" 25] [\"nathan\" 24]\n [\"alice\" 23] [\"george\" 31]]\n", "end": 5787, "score": 0.9902318716049194, "start": 5781, "tag": "NAME", "value": "nathan" }, { "context": " [[\"nathan\" 25] [\"nathan\" 24]\n [\"alice\" 23] [\"george\" 31]]\n gender [[\"nathan\" \"m\"", "end": 5816, "score": 0.9895229339599609, "start": 5811, "tag": "NAME", "value": "alice" }, { "context": " [\"alice\" 23] [\"george\" 31]]\n gender [[\"nathan\" \"m\"] [\"emily\" \"f\"]\n [\"george", "end": 5856, "score": 0.627637505531311, "start": 5855, "tag": "NAME", "value": "n" }, { "context": "] [\"george\" 31]]\n gender [[\"nathan\" \"m\"] [\"emily\" \"f\"]\n [\"george\" \"m\"] [\"bob\" \"m", "end": 5872, "score": 0.5607065558433533, "start": 5870, "tag": "NAME", "value": "em" }, { "context": " [\"george\" \"m\"] [\"bob\" \"m\"]]\n follows [[\"nathan\" \"bob\"] [\"nathan\" \"alice\"]\n [\"ali", "end": 5951, "score": 0.9866763949394226, "start": 5945, "tag": "NAME", "value": "nathan" }, { "context": "ge\" \"m\"] [\"bob\" \"m\"]]\n follows [[\"nathan\" \"bob\"] [\"nathan\" \"alice\"]\n [\"alice\" \"n", "end": 5957, "score": 0.9632235765457153, "start": 5954, "tag": "NAME", "value": "bob" }, { "context": " [\"bob\" \"m\"]]\n follows [[\"nathan\" \"bob\"] [\"nathan\" \"alice\"]\n [\"alice\" \"nathan\"] [\"a", "end": 5968, "score": 0.9950686693191528, "start": 5962, "tag": "NAME", "value": "nathan" }, { "context": "m\"]]\n follows [[\"nathan\" \"bob\"] [\"nathan\" \"alice\"]\n [\"alice\" \"nathan\"] [\"alice\" \"j", "end": 5976, "score": 0.9966521859169006, "start": 5971, "tag": "NAME", "value": "alice" }, { "context": "han\" \"bob\"] [\"nathan\" \"alice\"]\n [\"alice\" \"nathan\"] [\"alice\" \"jim\"]\n [\"bob", "end": 6003, "score": 0.9935532808303833, "start": 5998, "tag": "NAME", "value": "alice" }, { "context": "b\"] [\"nathan\" \"alice\"]\n [\"alice\" \"nathan\"] [\"alice\" \"jim\"]\n [\"bob\" \"nathan", "end": 6012, "score": 0.9983059763908386, "start": 6006, "tag": "NAME", "value": "nathan" }, { "context": "n\" \"alice\"]\n [\"alice\" \"nathan\"] [\"alice\" \"jim\"]\n [\"bob\" \"nathan\"]]]\n (", "end": 6022, "score": 0.9920656085014343, "start": 6017, "tag": "NAME", "value": "alice" }, { "context": "e\"]\n [\"alice\" \"nathan\"] [\"alice\" \"jim\"]\n [\"bob\" \"nathan\"]]]\n (test?<", "end": 6028, "score": 0.9968565702438354, "start": 6025, "tag": "NAME", "value": "jim" }, { "context": "ice\" \"nathan\"] [\"alice\" \"jim\"]\n [\"bob\" \"nathan\"]]]\n (test?<- [[\"george\"]]\n ", "end": 6053, "score": 0.9753171801567078, "start": 6050, "tag": "NAME", "value": "bob" }, { "context": "nathan\"] [\"alice\" \"jim\"]\n [\"bob\" \"nathan\"]]]\n (test?<- [[\"george\"]]\n [?p]\n ", "end": 6062, "score": 0.9978406429290771, "start": 6056, "tag": "NAME", "value": "nathan" }, { "context": ")\n (:distinct false))\n (test?<- [[\"nathan\"] [\"nathan\"]\n [\"alice\"]]\n ", "end": 6226, "score": 0.9889525175094604, "start": 6220, "tag": "NAME", "value": "nathan" }, { "context": " (:distinct false))\n (test?<- [[\"nathan\"] [\"nathan\"]\n [\"alice\"]]\n [?p]\n ", "end": 6237, "score": 0.9939870834350586, "start": 6231, "tag": "NAME", "value": "nathan" }, { "context": " (test?<- [[\"nathan\"] [\"nathan\"]\n [\"alice\"]]\n [?p]\n (age ?p _)\n ", "end": 6261, "score": 0.9908843636512756, "start": 6256, "tag": "NAME", "value": "alice" }, { "context": ")\n (:distinct false))\n (test?<- [[\"alice\"]]\n [?p]\n (age ?p _)\n ", "end": 6396, "score": 0.9974513053894043, "start": 6391, "tag": "NAME", "value": "alice" }, { "context": " (age ?p _)\n (follows ?p \"nathan\" :> true)\n (:distinct false))\n (te", "end": 6474, "score": 0.9985917210578918, "start": 6468, "tag": "NAME", "value": "nathan" }, { "context": ")\n (:distinct false))\n (test?<- [[\"nathan\"] [\"nathan\"]\n [\"george\"]]\n ", "end": 6539, "score": 0.999280571937561, "start": 6533, "tag": "NAME", "value": "nathan" }, { "context": " (:distinct false))\n (test?<- [[\"nathan\"] [\"nathan\"]\n [\"george\"]]\n [?p]\n ", "end": 6550, "score": 0.9993573427200317, "start": 6544, "tag": "NAME", "value": "nathan" }, { "context": " (test?<- [[\"nathan\"] [\"nathan\"]\n [\"george\"]]\n [?p]\n (age ?p _)\n ", "end": 6575, "score": 0.9987083077430725, "start": 6569, "tag": "NAME", "value": "george" }, { "context": " (age ?p _)\n (follows ?p \"nathan\" :> false)\n (:distinct false))\n (t", "end": 6653, "score": 0.9995319247245789, "start": 6647, "tag": "NAME", "value": "nathan" }, { "context": ")\n (:distinct false))\n (test?<- [[\"nathan\" true true] [\"nathan\" true true]\n [\"", "end": 6719, "score": 0.999130129814148, "start": 6713, "tag": "NAME", "value": "nathan" }, { "context": "inct false))\n (test?<- [[\"nathan\" true true] [\"nathan\" true true]\n [\"alice\" true false] [\"", "end": 6740, "score": 0.9993807673454285, "start": 6734, "tag": "NAME", "value": "nathan" }, { "context": "\" true true] [\"nathan\" true true]\n [\"alice\" true false] [\"george\" false true]]\n ", "end": 6774, "score": 0.9988396763801575, "start": 6769, "tag": "NAME", "value": "alice" }, { "context": "\" true true]\n [\"alice\" true false] [\"george\" false true]]\n [?p ?isfollows ?ismale", "end": 6796, "score": 0.9989720582962036, "start": 6790, "tag": "NAME", "value": "george" }, { "context": ")\n (:distinct false))\n (test?<- [[\"nathan\" true true]\n [\"nathan\" true true]]\n ", "end": 7008, "score": 0.9994193315505981, "start": 7002, "tag": "NAME", "value": "nathan" }, { "context": " (test?<- [[\"nathan\" true true]\n [\"nathan\" true true]]\n [?p ?isfollows ?ismale]", "end": 7043, "score": 0.9994031190872192, "start": 7037, "tag": "NAME", "value": "nathan" }, { "context": " (:distinct false))]\n (test?<- [[\"nathan\"] [\"bob\"]]\n [?p]\n (ge", "end": 7414, "score": 0.9991714954376221, "start": 7408, "tag": "NAME", "value": "nathan" }, { "context": " (:distinct false))]\n (test?<- [[\"nathan\"] [\"bob\"]]\n [?p]\n (gender ?p ", "end": 7422, "score": 0.999206006526947, "start": 7419, "tag": "NAME", "value": "bob" }, { "context": ")\n (:distinct false))\n (test?<- [[\"alice\"]]\n [?p]\n (age ?p _)\n ", "end": 7706, "score": 0.9981772899627686, "start": 7701, "tag": "NAME", "value": "alice" } ]
test/cascalog/api_secondary_test.clj
Factual/cascalog
1
(ns cascalog.api-secondary-test (:use clojure.test cascalog.api cascalog.testing) (:import [cascading.tuple Fields]) (:require [cascalog.ops :as c] [cascalog.io :as io])) (deftest test-outfields-query (let [age [["nathan" 25]]] (is (= ["?age"] (get-out-fields (<- [?age] (age _ ?age))))) (is (= ["!!age2" "!!age"] (get-out-fields (<- [!!age2 !!age] (age ?person !!age) (age ?person !!age2))))) (is (= ["?person" "!a"] (get-out-fields (<- [?person !a] (age ?person !a))))) (is (= ["!a" "!count"] (get-out-fields (<- [!a !count] (age _ !a) (c/count !count))))))) (deftest test-outfields-tap (is (thrown? AssertionError (get-out-fields (memory-source-tap Fields/ALL [])))) (is (= ["!age"] (get-out-fields (memory-source-tap ["!age"] [])))) (is (= ["?age" "field2"] (get-out-fields (memory-source-tap ["?age" "field2"] []))))) (defbufferop sum+1 [tuples] [(inc (reduce + (map first tuples)))]) (defn op-to-pairs [sq op] (<- [?c] (sq ?a ?b) (op ?a ?b :> ?c) (:distinct false))) (deftest test-use-var (let [nums [[1 1] [2 2] [1 3]]] (test?<- [[2] [4] [4]] [?sum] (nums ?a ?b) (#'+ ?a ?b :> ?sum) (:distinct false)) (test?- [[0] [0] [-2]] (op-to-pairs nums #'-) [[5]] (op-to-pairs nums #'sum+1) [[5]] (op-to-pairs nums sum+1)))) (deftest test-construct (let [age [["alice" 25] ["bob" 30]] gender [["alice" "f"] ["charlie" "m"]]] (test?- [["alice" 26 "f"] ["bob" 31 nil]] (apply construct {} ["?p" "?a2" "!!g"] [(-> [[age "?p" "?a"] [#'inc "?a" :> "?a2"]] (conj [gender "?p" "!!g"]))])))) (deftest test-cascalog-tap-source (io/with-log-level :fatal (let [num [[1]] gen (<- [?n] (num ?raw) (inc ?raw :> ?n) (:distinct false)) tap1 (cascalog-tap num nil)] (test?<- [[1]] [?n] (tap1 ?n) (:distinct false)) (test?<- [[2]] [?n] ((cascalog-tap gen nil) ?n) (:distinct false)) (test?<- [[1]] [?n] ((cascalog-tap (cascalog-tap tap1 nil) nil) ?n) (:distinct false))))) (deftest test-cascalog-tap-sink (io/with-log-level :fatal (let [num [[2]]] (with-expected-sinks [sink1 [[2]] sink2 [[3]] sink3 [[2]]] (?<- (cascalog-tap nil sink1) [?n] (num ?n) (:distinct false)) (?<- (cascalog-tap nil (fn [sq] [sink2 (<- [?n2] (sq ?n) (inc ?n :> ?n2) (:distinct false))])) [?n] (num ?n) (:distinct false)) (?<- (cascalog-tap nil (cascalog-tap nil sink3)) [?n] (num ?n) (:distinct false)))))) (deftest test-cascalog-tap-source-and-sink (io/with-log-level :fatal (with-expected-sinks [sink1 [[4]]] (let [tap (cascalog-tap [[3]] sink1)] (?<- tap [?n] (tap ?raw) (inc ?raw :> ?n) (:distinct false)))))) (deftest test-symmetric-ops (let [nums [[1 2 3] [10 20 30] [100 200 300]]] (test?<- [[111 222 333 1 2 3 100 200 300]] [?s1 ?s2 ?s3 ?min1 ?min2 ?min3 ?max1 ?max2 ?max3] (nums ?a ?b ?c) (c/sum ?a ?b ?c :> ?s1 ?s2 ?s3) (c/min ?a ?b ?c :> ?min1 ?min2 ?min3) (c/max ?a ?b ?c :> ?max1 ?max2 ?max3)))) (deftest test-first-n (let [sq (name-vars [[1 1] [1 3] [1 2] [2 1] [3 4]] ["?a" "?b"])] (test?- [[1 1] [1 2]] (c/first-n sq 2 :sort ["?a" "?b"])) (test?- [[3 4] [2 1]] (c/first-n sq 2 :sort "?a" :reverse true)) (is (= 2 (count (first (??- (c/first-n sq 2)))))))) (deftest test-flow-name (let [nums [[1] [2]]] (with-expected-sinks [sink1 [[1] [2]] sink2 [[2] [3]]] (is (= "lalala" (.getName (compile-flow {:name "lalala"} (stdout) (<- [?n] (nums ?n)))))) (?<- "flow1" sink1 [?n] (nums ?n) (:distinct false)) (?- "flow2" sink2 (<- [?n2] (nums ?n) (inc ?n :> ?n2) (:distinct false))) (is (= '(([1] [2])) (??- "flow3" (<- [?n] (nums ?n) (:distinct false)))))))) (deftest test-data-structure (let [src [[1 5] [5 6] [8 2]] nums [[1] [2]]] (test?<- [[1 5]] [?a ?b] (nums ?a) (src ?a ?b)))) (deftest test-memory-returns (let [nums [[1] [2] [3]] people [["alice"] ["bob"]]] (is (= (set [[1] [3]]) (set (??<- [?num] (nums ?num) (odd? ?num) (:distinct false))))) (let [res (??- (<- [?val] (nums ?num) (inc ?num :> ?val) (:distinct false)) (<- [?res] (people ?person) (str ?person "a" :> ?res) (:distinct false)))] (is (= (set [[2] [3] [4]]) (set (first res)))) (is (= (set [["alicea"] ["boba"]]) (set (second res))))))) (deftest test-negation (let [age [["nathan" 25] ["nathan" 24] ["alice" 23] ["george" 31]] gender [["nathan" "m"] ["emily" "f"] ["george" "m"] ["bob" "m"]] follows [["nathan" "bob"] ["nathan" "alice"] ["alice" "nathan"] ["alice" "jim"] ["bob" "nathan"]]] (test?<- [["george"]] [?p] (age ?p _) (follows ?p _ :> false) (:distinct false)) (test?<- [["nathan"] ["nathan"] ["alice"]] [?p] (age ?p _) (follows ?p _ :> true) (:distinct false)) (test?<- [["alice"]] [?p] (age ?p _) (follows ?p "nathan" :> true) (:distinct false)) (test?<- [["nathan"] ["nathan"] ["george"]] [?p] (age ?p _) (follows ?p "nathan" :> false) (:distinct false)) (test?<- [["nathan" true true] ["nathan" true true] ["alice" true false] ["george" false true]] [?p ?isfollows ?ismale] (age ?p _) (follows ?p _ :> ?isfollows) (gender ?p "m" :> ?ismale) (:distinct false)) (test?<- [["nathan" true true] ["nathan" true true]] [?p ?isfollows ?ismale] (age ?p _) (follows ?p _ :> ?isfollows) (gender ?p "m" :> ?ismale) (= ?ismale ?isfollows) (:distinct false)) (let [old (<- [?p ?a] (age ?p ?a) (> ?a 30) (:distinct false))] (test?<- [["nathan"] ["bob"]] [?p] (gender ?p "m") (old ?p _ :> false) (:distinct false))) (test?<- [[24] [31]] [?n] (age _ ?n) ([[25] [23]] ?n :> false) (:distinct false)) (test?<- [["alice"]] [?p] (age ?p _) ((c/negate gender) ?p _) (:distinct false)))) ;; TODO: test within massive joins (more than one join field, after other joins complete, etc.) (deftest test-negation-errors (let [nums [[1] [2] [3]] pairs [[3 4] [4 5]]] (thrown?<- Exception [?n] (nums ?n) (pairs ?n ?n2 :> false) (odd? ?n2)))) (defmultibufferop count-sum [seq1 seq2] [[(count seq1) (reduce + (map second seq2))]]) (defmultibufferop [count-arg [arg]] [seq1 seq2 seq3] [[(count seq1) (count seq2) (count seq3)] [arg arg arg]]) (deftest test-multigroup (let [val1 [["a" 1] ["b" 2] ["a" 10]] val2 [["b" 6] ["b" 18] ["c" 3] ["c" 4]] gen1 (name-vars val1 ["?key" "?val1"]) gen2 (name-vars val2 ["?key" "?val2"]) gen3 (name-vars val1 ["?key" "?val2"])] (test?- [["a" 2 0] ["b" 1 24] ["c" 0 7]] (multigroup [?key] [?count ?sum] count-sum gen1 gen2)) (test?- [["a" 2 2 0] ["a" 9 9 9] ["b" 1 1 2] ["b" 9 9 9] ["c" 0 0 2] ["c" 9 9 9]] (multigroup [?key] [?v1 ?v2 ?v3] [count-arg [9]] gen1 gen1 gen2))))
68581
(ns cascalog.api-secondary-test (:use clojure.test cascalog.api cascalog.testing) (:import [cascading.tuple Fields]) (:require [cascalog.ops :as c] [cascalog.io :as io])) (deftest test-outfields-query (let [age [["<NAME>" 25]]] (is (= ["?age"] (get-out-fields (<- [?age] (age _ ?age))))) (is (= ["!!age2" "!!age"] (get-out-fields (<- [!!age2 !!age] (age ?person !!age) (age ?person !!age2))))) (is (= ["?person" "!a"] (get-out-fields (<- [?person !a] (age ?person !a))))) (is (= ["!a" "!count"] (get-out-fields (<- [!a !count] (age _ !a) (c/count !count))))))) (deftest test-outfields-tap (is (thrown? AssertionError (get-out-fields (memory-source-tap Fields/ALL [])))) (is (= ["!age"] (get-out-fields (memory-source-tap ["!age"] [])))) (is (= ["?age" "field2"] (get-out-fields (memory-source-tap ["?age" "field2"] []))))) (defbufferop sum+1 [tuples] [(inc (reduce + (map first tuples)))]) (defn op-to-pairs [sq op] (<- [?c] (sq ?a ?b) (op ?a ?b :> ?c) (:distinct false))) (deftest test-use-var (let [nums [[1 1] [2 2] [1 3]]] (test?<- [[2] [4] [4]] [?sum] (nums ?a ?b) (#'+ ?a ?b :> ?sum) (:distinct false)) (test?- [[0] [0] [-2]] (op-to-pairs nums #'-) [[5]] (op-to-pairs nums #'sum+1) [[5]] (op-to-pairs nums sum+1)))) (deftest test-construct (let [age [["<NAME>" 25] ["<NAME>" 30]] gender [["alice" "f"] ["<NAME>" "m"]]] (test?- [["<NAME>" 26 "f"] ["<NAME>" 31 nil]] (apply construct {} ["?p" "?a2" "!!g"] [(-> [[age "?p" "?a"] [#'inc "?a" :> "?a2"]] (conj [gender "?p" "!!g"]))])))) (deftest test-cascalog-tap-source (io/with-log-level :fatal (let [num [[1]] gen (<- [?n] (num ?raw) (inc ?raw :> ?n) (:distinct false)) tap1 (cascalog-tap num nil)] (test?<- [[1]] [?n] (tap1 ?n) (:distinct false)) (test?<- [[2]] [?n] ((cascalog-tap gen nil) ?n) (:distinct false)) (test?<- [[1]] [?n] ((cascalog-tap (cascalog-tap tap1 nil) nil) ?n) (:distinct false))))) (deftest test-cascalog-tap-sink (io/with-log-level :fatal (let [num [[2]]] (with-expected-sinks [sink1 [[2]] sink2 [[3]] sink3 [[2]]] (?<- (cascalog-tap nil sink1) [?n] (num ?n) (:distinct false)) (?<- (cascalog-tap nil (fn [sq] [sink2 (<- [?n2] (sq ?n) (inc ?n :> ?n2) (:distinct false))])) [?n] (num ?n) (:distinct false)) (?<- (cascalog-tap nil (cascalog-tap nil sink3)) [?n] (num ?n) (:distinct false)))))) (deftest test-cascalog-tap-source-and-sink (io/with-log-level :fatal (with-expected-sinks [sink1 [[4]]] (let [tap (cascalog-tap [[3]] sink1)] (?<- tap [?n] (tap ?raw) (inc ?raw :> ?n) (:distinct false)))))) (deftest test-symmetric-ops (let [nums [[1 2 3] [10 20 30] [100 200 300]]] (test?<- [[111 222 333 1 2 3 100 200 300]] [?s1 ?s2 ?s3 ?min1 ?min2 ?min3 ?max1 ?max2 ?max3] (nums ?a ?b ?c) (c/sum ?a ?b ?c :> ?s1 ?s2 ?s3) (c/min ?a ?b ?c :> ?min1 ?min2 ?min3) (c/max ?a ?b ?c :> ?max1 ?max2 ?max3)))) (deftest test-first-n (let [sq (name-vars [[1 1] [1 3] [1 2] [2 1] [3 4]] ["?a" "?b"])] (test?- [[1 1] [1 2]] (c/first-n sq 2 :sort ["?a" "?b"])) (test?- [[3 4] [2 1]] (c/first-n sq 2 :sort "?a" :reverse true)) (is (= 2 (count (first (??- (c/first-n sq 2)))))))) (deftest test-flow-name (let [nums [[1] [2]]] (with-expected-sinks [sink1 [[1] [2]] sink2 [[2] [3]]] (is (= "lalala" (.getName (compile-flow {:name "lalala"} (stdout) (<- [?n] (nums ?n)))))) (?<- "flow1" sink1 [?n] (nums ?n) (:distinct false)) (?- "flow2" sink2 (<- [?n2] (nums ?n) (inc ?n :> ?n2) (:distinct false))) (is (= '(([1] [2])) (??- "flow3" (<- [?n] (nums ?n) (:distinct false)))))))) (deftest test-data-structure (let [src [[1 5] [5 6] [8 2]] nums [[1] [2]]] (test?<- [[1 5]] [?a ?b] (nums ?a) (src ?a ?b)))) (deftest test-memory-returns (let [nums [[1] [2] [3]] people [["<NAME>"] ["<NAME>"]]] (is (= (set [[1] [3]]) (set (??<- [?num] (nums ?num) (odd? ?num) (:distinct false))))) (let [res (??- (<- [?val] (nums ?num) (inc ?num :> ?val) (:distinct false)) (<- [?res] (people ?person) (str ?person "a" :> ?res) (:distinct false)))] (is (= (set [[2] [3] [4]]) (set (first res)))) (is (= (set [["<NAME>"] ["<NAME>"]]) (set (second res))))))) (deftest test-negation (let [age [["<NAME>" 25] ["<NAME>" 24] ["<NAME>" 23] ["george" 31]] gender [["<NAME>athan" "m"] ["<NAME>ily" "f"] ["george" "m"] ["bob" "m"]] follows [["<NAME>" "<NAME>"] ["<NAME>" "<NAME>"] ["<NAME>" "<NAME>"] ["<NAME>" "<NAME>"] ["<NAME>" "<NAME>"]]] (test?<- [["george"]] [?p] (age ?p _) (follows ?p _ :> false) (:distinct false)) (test?<- [["<NAME>"] ["<NAME>"] ["<NAME>"]] [?p] (age ?p _) (follows ?p _ :> true) (:distinct false)) (test?<- [["<NAME>"]] [?p] (age ?p _) (follows ?p "<NAME>" :> true) (:distinct false)) (test?<- [["<NAME>"] ["<NAME>"] ["<NAME>"]] [?p] (age ?p _) (follows ?p "<NAME>" :> false) (:distinct false)) (test?<- [["<NAME>" true true] ["<NAME>" true true] ["<NAME>" true false] ["<NAME>" false true]] [?p ?isfollows ?ismale] (age ?p _) (follows ?p _ :> ?isfollows) (gender ?p "m" :> ?ismale) (:distinct false)) (test?<- [["<NAME>" true true] ["<NAME>" true true]] [?p ?isfollows ?ismale] (age ?p _) (follows ?p _ :> ?isfollows) (gender ?p "m" :> ?ismale) (= ?ismale ?isfollows) (:distinct false)) (let [old (<- [?p ?a] (age ?p ?a) (> ?a 30) (:distinct false))] (test?<- [["<NAME>"] ["<NAME>"]] [?p] (gender ?p "m") (old ?p _ :> false) (:distinct false))) (test?<- [[24] [31]] [?n] (age _ ?n) ([[25] [23]] ?n :> false) (:distinct false)) (test?<- [["<NAME>"]] [?p] (age ?p _) ((c/negate gender) ?p _) (:distinct false)))) ;; TODO: test within massive joins (more than one join field, after other joins complete, etc.) (deftest test-negation-errors (let [nums [[1] [2] [3]] pairs [[3 4] [4 5]]] (thrown?<- Exception [?n] (nums ?n) (pairs ?n ?n2 :> false) (odd? ?n2)))) (defmultibufferop count-sum [seq1 seq2] [[(count seq1) (reduce + (map second seq2))]]) (defmultibufferop [count-arg [arg]] [seq1 seq2 seq3] [[(count seq1) (count seq2) (count seq3)] [arg arg arg]]) (deftest test-multigroup (let [val1 [["a" 1] ["b" 2] ["a" 10]] val2 [["b" 6] ["b" 18] ["c" 3] ["c" 4]] gen1 (name-vars val1 ["?key" "?val1"]) gen2 (name-vars val2 ["?key" "?val2"]) gen3 (name-vars val1 ["?key" "?val2"])] (test?- [["a" 2 0] ["b" 1 24] ["c" 0 7]] (multigroup [?key] [?count ?sum] count-sum gen1 gen2)) (test?- [["a" 2 2 0] ["a" 9 9 9] ["b" 1 1 2] ["b" 9 9 9] ["c" 0 0 2] ["c" 9 9 9]] (multigroup [?key] [?v1 ?v2 ?v3] [count-arg [9]] gen1 gen1 gen2))))
true
(ns cascalog.api-secondary-test (:use clojure.test cascalog.api cascalog.testing) (:import [cascading.tuple Fields]) (:require [cascalog.ops :as c] [cascalog.io :as io])) (deftest test-outfields-query (let [age [["PI:NAME:<NAME>END_PI" 25]]] (is (= ["?age"] (get-out-fields (<- [?age] (age _ ?age))))) (is (= ["!!age2" "!!age"] (get-out-fields (<- [!!age2 !!age] (age ?person !!age) (age ?person !!age2))))) (is (= ["?person" "!a"] (get-out-fields (<- [?person !a] (age ?person !a))))) (is (= ["!a" "!count"] (get-out-fields (<- [!a !count] (age _ !a) (c/count !count))))))) (deftest test-outfields-tap (is (thrown? AssertionError (get-out-fields (memory-source-tap Fields/ALL [])))) (is (= ["!age"] (get-out-fields (memory-source-tap ["!age"] [])))) (is (= ["?age" "field2"] (get-out-fields (memory-source-tap ["?age" "field2"] []))))) (defbufferop sum+1 [tuples] [(inc (reduce + (map first tuples)))]) (defn op-to-pairs [sq op] (<- [?c] (sq ?a ?b) (op ?a ?b :> ?c) (:distinct false))) (deftest test-use-var (let [nums [[1 1] [2 2] [1 3]]] (test?<- [[2] [4] [4]] [?sum] (nums ?a ?b) (#'+ ?a ?b :> ?sum) (:distinct false)) (test?- [[0] [0] [-2]] (op-to-pairs nums #'-) [[5]] (op-to-pairs nums #'sum+1) [[5]] (op-to-pairs nums sum+1)))) (deftest test-construct (let [age [["PI:NAME:<NAME>END_PI" 25] ["PI:NAME:<NAME>END_PI" 30]] gender [["alice" "f"] ["PI:NAME:<NAME>END_PI" "m"]]] (test?- [["PI:NAME:<NAME>END_PI" 26 "f"] ["PI:NAME:<NAME>END_PI" 31 nil]] (apply construct {} ["?p" "?a2" "!!g"] [(-> [[age "?p" "?a"] [#'inc "?a" :> "?a2"]] (conj [gender "?p" "!!g"]))])))) (deftest test-cascalog-tap-source (io/with-log-level :fatal (let [num [[1]] gen (<- [?n] (num ?raw) (inc ?raw :> ?n) (:distinct false)) tap1 (cascalog-tap num nil)] (test?<- [[1]] [?n] (tap1 ?n) (:distinct false)) (test?<- [[2]] [?n] ((cascalog-tap gen nil) ?n) (:distinct false)) (test?<- [[1]] [?n] ((cascalog-tap (cascalog-tap tap1 nil) nil) ?n) (:distinct false))))) (deftest test-cascalog-tap-sink (io/with-log-level :fatal (let [num [[2]]] (with-expected-sinks [sink1 [[2]] sink2 [[3]] sink3 [[2]]] (?<- (cascalog-tap nil sink1) [?n] (num ?n) (:distinct false)) (?<- (cascalog-tap nil (fn [sq] [sink2 (<- [?n2] (sq ?n) (inc ?n :> ?n2) (:distinct false))])) [?n] (num ?n) (:distinct false)) (?<- (cascalog-tap nil (cascalog-tap nil sink3)) [?n] (num ?n) (:distinct false)))))) (deftest test-cascalog-tap-source-and-sink (io/with-log-level :fatal (with-expected-sinks [sink1 [[4]]] (let [tap (cascalog-tap [[3]] sink1)] (?<- tap [?n] (tap ?raw) (inc ?raw :> ?n) (:distinct false)))))) (deftest test-symmetric-ops (let [nums [[1 2 3] [10 20 30] [100 200 300]]] (test?<- [[111 222 333 1 2 3 100 200 300]] [?s1 ?s2 ?s3 ?min1 ?min2 ?min3 ?max1 ?max2 ?max3] (nums ?a ?b ?c) (c/sum ?a ?b ?c :> ?s1 ?s2 ?s3) (c/min ?a ?b ?c :> ?min1 ?min2 ?min3) (c/max ?a ?b ?c :> ?max1 ?max2 ?max3)))) (deftest test-first-n (let [sq (name-vars [[1 1] [1 3] [1 2] [2 1] [3 4]] ["?a" "?b"])] (test?- [[1 1] [1 2]] (c/first-n sq 2 :sort ["?a" "?b"])) (test?- [[3 4] [2 1]] (c/first-n sq 2 :sort "?a" :reverse true)) (is (= 2 (count (first (??- (c/first-n sq 2)))))))) (deftest test-flow-name (let [nums [[1] [2]]] (with-expected-sinks [sink1 [[1] [2]] sink2 [[2] [3]]] (is (= "lalala" (.getName (compile-flow {:name "lalala"} (stdout) (<- [?n] (nums ?n)))))) (?<- "flow1" sink1 [?n] (nums ?n) (:distinct false)) (?- "flow2" sink2 (<- [?n2] (nums ?n) (inc ?n :> ?n2) (:distinct false))) (is (= '(([1] [2])) (??- "flow3" (<- [?n] (nums ?n) (:distinct false)))))))) (deftest test-data-structure (let [src [[1 5] [5 6] [8 2]] nums [[1] [2]]] (test?<- [[1 5]] [?a ?b] (nums ?a) (src ?a ?b)))) (deftest test-memory-returns (let [nums [[1] [2] [3]] people [["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]]] (is (= (set [[1] [3]]) (set (??<- [?num] (nums ?num) (odd? ?num) (:distinct false))))) (let [res (??- (<- [?val] (nums ?num) (inc ?num :> ?val) (:distinct false)) (<- [?res] (people ?person) (str ?person "a" :> ?res) (:distinct false)))] (is (= (set [[2] [3] [4]]) (set (first res)))) (is (= (set [["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]]) (set (second res))))))) (deftest test-negation (let [age [["PI:NAME:<NAME>END_PI" 25] ["PI:NAME:<NAME>END_PI" 24] ["PI:NAME:<NAME>END_PI" 23] ["george" 31]] gender [["PI:NAME:<NAME>END_PIathan" "m"] ["PI:NAME:<NAME>END_PIily" "f"] ["george" "m"] ["bob" "m"]] follows [["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]]] (test?<- [["george"]] [?p] (age ?p _) (follows ?p _ :> false) (:distinct false)) (test?<- [["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]] [?p] (age ?p _) (follows ?p _ :> true) (:distinct false)) (test?<- [["PI:NAME:<NAME>END_PI"]] [?p] (age ?p _) (follows ?p "PI:NAME:<NAME>END_PI" :> true) (:distinct false)) (test?<- [["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]] [?p] (age ?p _) (follows ?p "PI:NAME:<NAME>END_PI" :> false) (:distinct false)) (test?<- [["PI:NAME:<NAME>END_PI" true true] ["PI:NAME:<NAME>END_PI" true true] ["PI:NAME:<NAME>END_PI" true false] ["PI:NAME:<NAME>END_PI" false true]] [?p ?isfollows ?ismale] (age ?p _) (follows ?p _ :> ?isfollows) (gender ?p "m" :> ?ismale) (:distinct false)) (test?<- [["PI:NAME:<NAME>END_PI" true true] ["PI:NAME:<NAME>END_PI" true true]] [?p ?isfollows ?ismale] (age ?p _) (follows ?p _ :> ?isfollows) (gender ?p "m" :> ?ismale) (= ?ismale ?isfollows) (:distinct false)) (let [old (<- [?p ?a] (age ?p ?a) (> ?a 30) (:distinct false))] (test?<- [["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]] [?p] (gender ?p "m") (old ?p _ :> false) (:distinct false))) (test?<- [[24] [31]] [?n] (age _ ?n) ([[25] [23]] ?n :> false) (:distinct false)) (test?<- [["PI:NAME:<NAME>END_PI"]] [?p] (age ?p _) ((c/negate gender) ?p _) (:distinct false)))) ;; TODO: test within massive joins (more than one join field, after other joins complete, etc.) (deftest test-negation-errors (let [nums [[1] [2] [3]] pairs [[3 4] [4 5]]] (thrown?<- Exception [?n] (nums ?n) (pairs ?n ?n2 :> false) (odd? ?n2)))) (defmultibufferop count-sum [seq1 seq2] [[(count seq1) (reduce + (map second seq2))]]) (defmultibufferop [count-arg [arg]] [seq1 seq2 seq3] [[(count seq1) (count seq2) (count seq3)] [arg arg arg]]) (deftest test-multigroup (let [val1 [["a" 1] ["b" 2] ["a" 10]] val2 [["b" 6] ["b" 18] ["c" 3] ["c" 4]] gen1 (name-vars val1 ["?key" "?val1"]) gen2 (name-vars val2 ["?key" "?val2"]) gen3 (name-vars val1 ["?key" "?val2"])] (test?- [["a" 2 0] ["b" 1 24] ["c" 0 7]] (multigroup [?key] [?count ?sum] count-sum gen1 gen2)) (test?- [["a" 2 2 0] ["a" 9 9 9] ["b" 1 1 2] ["b" 9 9 9] ["c" 0 0 2] ["c" 9 9 9]] (multigroup [?key] [?v1 ?v2 ?v3] [count-arg [9]] gen1 gen1 gen2))))
[ { "context": "\n (gen/one-of\n [(gen-rsa-keyspec [1024 2048 4096])\n (gen-ec-keyspec :ecdh pgp-gen/ellipt", "end": 1685, "score": 0.9963892102241516, "start": 1671, "tag": "KEY", "value": "1024 2048 4096" } ]
test/clj_pgp/test/encryption.clj
aclev/clj-pgp
0
(ns clj-pgp.test.encryption (:require [byte-streams :refer [bytes=]] [clojure.java.io :as io] [clojure.test :refer :all] [clojure.test.check :as check] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] (clj-pgp [core :as pgp] [generate :as pgp-gen] [message :as pgp-msg] [tags :as tags]) [clj-pgp.test.keys :refer [gen-ec-keyspec gen-rsa-keyspec memospec->keypair]]) (:import java.io.ByteArrayOutputStream java.security.SecureRandom)) (defn test-encryption-scenario "Tests that encrypting and decrypting data with the given keypairs/passphrases returns the original data." [keyspecs data compress cipher armor] (testing (str "Encrypting " (count data) " bytes with " cipher " for keys " (pr-str keyspecs) (when compress (str " compressed with " compress)) " encoded in " (if armor "ascii" "binary")) (let [encryptors (map memospec->keypair keyspecs) ciphertext (pgp-msg/encrypt data encryptors :compress compress :cipher cipher :armor armor)] (is (not (bytes= data ciphertext)) "ciphertext bytes differ from data") (doseq [decryptor encryptors] (is (bytes= data (pgp-msg/decrypt ciphertext decryptor)) "decrypting the ciphertext returns plaintext")) [encryptors ciphertext]))) (def gen-encryptors (->> (gen/tuple gen/boolean (gen/not-empty gen/string-ascii) (gen/vector (gen/one-of [(gen-rsa-keyspec [1024 2048 4096]) (gen-ec-keyspec :ecdh pgp-gen/elliptic-curve-names)]))) (gen/fmap (fn [[p pass keypairs]] (-> (if p (cons pass keypairs) keypairs) set shuffle))) gen/not-empty)) (def data-encryption-property (prop/for-all* [gen-encryptors (gen/not-empty gen/bytes) (gen/elements (cons nil pgp/compression-algorithms)) (gen/elements (remove #{:null :safer :camellia-256} pgp/symmetric-key-algorithms)) gen/boolean] test-encryption-scenario)) (deftest pgp-messages (let [rsa (pgp-gen/rsa-keypair-generator 1024) keypair (pgp-gen/generate-keypair rsa :rsa-general) data "My hidden data files"] (is (thrown? IllegalArgumentException (pgp-msg/encrypted-data-stream nil :aes-128 [])) "Encryption with no encryptors throws an exception") (is (thrown? IllegalArgumentException (pgp-msg/encrypt data :not-an-encryptor :integrity-check false :random (SecureRandom.))) "Encryption with an invalid encryptor throws an exception") (is (thrown? IllegalArgumentException (pgp-msg/encrypt data ["bar" "baz"])) "Encryption with multiple passphrases throws an exception") (testing "uncompressed unenciphered data" (let [envelope (pgp-msg/package data)] (is (not (bytes= data envelope)) "Message should wrap a literal packet around the data.") (is (bytes= data (:data (first (pgp-msg/read-messages envelope)))) "Literal packet message should be readable with no decryptors."))) (let [ciphertext (pgp-msg/encrypt data keypair)] (is (bytes= data (pgp-msg/decrypt ciphertext (constantly keypair))) "Decrypting with a keypair-retrieval function returns the data.") (is (thrown? IllegalArgumentException (pgp-msg/decrypt ciphertext "passphrase")) "Decrypting without a matching key throws an exception")))) (deftest encryption-scenarios (testing "passphrase-only encryption" (test-encryption-scenario ["s3cr3t"] "The data blobble" nil :aes-128 true)) (testing "RSA key encryption" (test-encryption-scenario [[:rsa :rsa-encrypt 1024]] "Secret stuff to hide from prying eyes" nil :aes-128 false)) (testing "ECDH key encryption" (test-encryption-scenario [[:ec :ecdh "secp256r1"]] "Foooooood is nice" :zip :aes-256 true)) (testing "passphrase and multi-key encryption" (test-encryption-scenario ["frobble bisvarkian" [:rsa :rsa-general 1024] [:ec :ecdh "sect409r1"]] "Good news, everyone!" :bzip2 :aes-256 true)))
123367
(ns clj-pgp.test.encryption (:require [byte-streams :refer [bytes=]] [clojure.java.io :as io] [clojure.test :refer :all] [clojure.test.check :as check] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] (clj-pgp [core :as pgp] [generate :as pgp-gen] [message :as pgp-msg] [tags :as tags]) [clj-pgp.test.keys :refer [gen-ec-keyspec gen-rsa-keyspec memospec->keypair]]) (:import java.io.ByteArrayOutputStream java.security.SecureRandom)) (defn test-encryption-scenario "Tests that encrypting and decrypting data with the given keypairs/passphrases returns the original data." [keyspecs data compress cipher armor] (testing (str "Encrypting " (count data) " bytes with " cipher " for keys " (pr-str keyspecs) (when compress (str " compressed with " compress)) " encoded in " (if armor "ascii" "binary")) (let [encryptors (map memospec->keypair keyspecs) ciphertext (pgp-msg/encrypt data encryptors :compress compress :cipher cipher :armor armor)] (is (not (bytes= data ciphertext)) "ciphertext bytes differ from data") (doseq [decryptor encryptors] (is (bytes= data (pgp-msg/decrypt ciphertext decryptor)) "decrypting the ciphertext returns plaintext")) [encryptors ciphertext]))) (def gen-encryptors (->> (gen/tuple gen/boolean (gen/not-empty gen/string-ascii) (gen/vector (gen/one-of [(gen-rsa-keyspec [<KEY>]) (gen-ec-keyspec :ecdh pgp-gen/elliptic-curve-names)]))) (gen/fmap (fn [[p pass keypairs]] (-> (if p (cons pass keypairs) keypairs) set shuffle))) gen/not-empty)) (def data-encryption-property (prop/for-all* [gen-encryptors (gen/not-empty gen/bytes) (gen/elements (cons nil pgp/compression-algorithms)) (gen/elements (remove #{:null :safer :camellia-256} pgp/symmetric-key-algorithms)) gen/boolean] test-encryption-scenario)) (deftest pgp-messages (let [rsa (pgp-gen/rsa-keypair-generator 1024) keypair (pgp-gen/generate-keypair rsa :rsa-general) data "My hidden data files"] (is (thrown? IllegalArgumentException (pgp-msg/encrypted-data-stream nil :aes-128 [])) "Encryption with no encryptors throws an exception") (is (thrown? IllegalArgumentException (pgp-msg/encrypt data :not-an-encryptor :integrity-check false :random (SecureRandom.))) "Encryption with an invalid encryptor throws an exception") (is (thrown? IllegalArgumentException (pgp-msg/encrypt data ["bar" "baz"])) "Encryption with multiple passphrases throws an exception") (testing "uncompressed unenciphered data" (let [envelope (pgp-msg/package data)] (is (not (bytes= data envelope)) "Message should wrap a literal packet around the data.") (is (bytes= data (:data (first (pgp-msg/read-messages envelope)))) "Literal packet message should be readable with no decryptors."))) (let [ciphertext (pgp-msg/encrypt data keypair)] (is (bytes= data (pgp-msg/decrypt ciphertext (constantly keypair))) "Decrypting with a keypair-retrieval function returns the data.") (is (thrown? IllegalArgumentException (pgp-msg/decrypt ciphertext "passphrase")) "Decrypting without a matching key throws an exception")))) (deftest encryption-scenarios (testing "passphrase-only encryption" (test-encryption-scenario ["s3cr3t"] "The data blobble" nil :aes-128 true)) (testing "RSA key encryption" (test-encryption-scenario [[:rsa :rsa-encrypt 1024]] "Secret stuff to hide from prying eyes" nil :aes-128 false)) (testing "ECDH key encryption" (test-encryption-scenario [[:ec :ecdh "secp256r1"]] "Foooooood is nice" :zip :aes-256 true)) (testing "passphrase and multi-key encryption" (test-encryption-scenario ["frobble bisvarkian" [:rsa :rsa-general 1024] [:ec :ecdh "sect409r1"]] "Good news, everyone!" :bzip2 :aes-256 true)))
true
(ns clj-pgp.test.encryption (:require [byte-streams :refer [bytes=]] [clojure.java.io :as io] [clojure.test :refer :all] [clojure.test.check :as check] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] (clj-pgp [core :as pgp] [generate :as pgp-gen] [message :as pgp-msg] [tags :as tags]) [clj-pgp.test.keys :refer [gen-ec-keyspec gen-rsa-keyspec memospec->keypair]]) (:import java.io.ByteArrayOutputStream java.security.SecureRandom)) (defn test-encryption-scenario "Tests that encrypting and decrypting data with the given keypairs/passphrases returns the original data." [keyspecs data compress cipher armor] (testing (str "Encrypting " (count data) " bytes with " cipher " for keys " (pr-str keyspecs) (when compress (str " compressed with " compress)) " encoded in " (if armor "ascii" "binary")) (let [encryptors (map memospec->keypair keyspecs) ciphertext (pgp-msg/encrypt data encryptors :compress compress :cipher cipher :armor armor)] (is (not (bytes= data ciphertext)) "ciphertext bytes differ from data") (doseq [decryptor encryptors] (is (bytes= data (pgp-msg/decrypt ciphertext decryptor)) "decrypting the ciphertext returns plaintext")) [encryptors ciphertext]))) (def gen-encryptors (->> (gen/tuple gen/boolean (gen/not-empty gen/string-ascii) (gen/vector (gen/one-of [(gen-rsa-keyspec [PI:KEY:<KEY>END_PI]) (gen-ec-keyspec :ecdh pgp-gen/elliptic-curve-names)]))) (gen/fmap (fn [[p pass keypairs]] (-> (if p (cons pass keypairs) keypairs) set shuffle))) gen/not-empty)) (def data-encryption-property (prop/for-all* [gen-encryptors (gen/not-empty gen/bytes) (gen/elements (cons nil pgp/compression-algorithms)) (gen/elements (remove #{:null :safer :camellia-256} pgp/symmetric-key-algorithms)) gen/boolean] test-encryption-scenario)) (deftest pgp-messages (let [rsa (pgp-gen/rsa-keypair-generator 1024) keypair (pgp-gen/generate-keypair rsa :rsa-general) data "My hidden data files"] (is (thrown? IllegalArgumentException (pgp-msg/encrypted-data-stream nil :aes-128 [])) "Encryption with no encryptors throws an exception") (is (thrown? IllegalArgumentException (pgp-msg/encrypt data :not-an-encryptor :integrity-check false :random (SecureRandom.))) "Encryption with an invalid encryptor throws an exception") (is (thrown? IllegalArgumentException (pgp-msg/encrypt data ["bar" "baz"])) "Encryption with multiple passphrases throws an exception") (testing "uncompressed unenciphered data" (let [envelope (pgp-msg/package data)] (is (not (bytes= data envelope)) "Message should wrap a literal packet around the data.") (is (bytes= data (:data (first (pgp-msg/read-messages envelope)))) "Literal packet message should be readable with no decryptors."))) (let [ciphertext (pgp-msg/encrypt data keypair)] (is (bytes= data (pgp-msg/decrypt ciphertext (constantly keypair))) "Decrypting with a keypair-retrieval function returns the data.") (is (thrown? IllegalArgumentException (pgp-msg/decrypt ciphertext "passphrase")) "Decrypting without a matching key throws an exception")))) (deftest encryption-scenarios (testing "passphrase-only encryption" (test-encryption-scenario ["s3cr3t"] "The data blobble" nil :aes-128 true)) (testing "RSA key encryption" (test-encryption-scenario [[:rsa :rsa-encrypt 1024]] "Secret stuff to hide from prying eyes" nil :aes-128 false)) (testing "ECDH key encryption" (test-encryption-scenario [[:ec :ecdh "secp256r1"]] "Foooooood is nice" :zip :aes-256 true)) (testing "passphrase and multi-key encryption" (test-encryption-scenario ["frobble bisvarkian" [:rsa :rsa-general 1024] [:ec :ecdh "sect409r1"]] "Good news, everyone!" :bzip2 :aes-256 true)))
[ { "context": " for Clojure built on the CERN Colt Library\n\n;; by David Edgar Liebke http://incanter.org\n;; March 11, 2009\n\n;; Copyrig", "end": 104, "score": 0.9998950958251953, "start": 86, "tag": "NAME", "value": "David Edgar Liebke" }, { "context": "//incanter.org\n;; March 11, 2009\n\n;; Copyright (c) David Edgar Liebke, 2009. All rights reserved. The use\n;; and distr", "end": 179, "score": 0.9998929500579834, "start": 161, "tag": "NAME", "value": "David Edgar Liebke" }, { "context": "ld be done with replacement\n\n\n References:\n 1. Clifford E. Lunneborg, Data Analysis by Resampling Concepts a", "end": 48999, "score": 0.69108647108078, "start": 48989, "tag": "NAME", "value": "Clifford E" }, { "context": "eplacement\n\n\n References:\n 1. Clifford E. Lunneborg, Data Analysis by Resampling Concepts and Applica", "end": 49010, "score": 0.6685574054718018, "start": 49005, "tag": "NAME", "value": "eborg" }, { "context": "sis by Resampling Concepts and Applications\n ;; Clifford E. Lunneborg (pages 119-122)\n\n (use '(incanter core stats c", "end": 49267, "score": 0.8493696451187134, "start": 49246, "tag": "NAME", "value": "Clifford E. Lunneborg" } ]
test/conflicts/mined/incanter-29762d615c2538747b46e35d1b7afda14ccb98eb-2b0fbb78144bf68ecc481f9d8a0fdb6267bddb9/O.clj
nazrhom/vcs-clojure
3
;;; stats.clj -- Statistics library for Clojure built on the CERN Colt Library ;; by David Edgar Liebke http://incanter.org ;; March 11, 2009 ;; Copyright (c) David Edgar Liebke, 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. ;; CHANGE LOG ;; March 11, 2009: First version (ns incanter.stats (:gen-class) (:import (cern.colt.list.tdouble DoubleArrayList) (cern.jet.random.tdouble Gamma Beta Binomial ChiSquare DoubleUniform Exponential NegativeBinomial Normal Poisson StudentT) (cern.jet.random.tdouble.engine DoubleMersenneTwister) (cern.jet.stat.tdouble DoubleDescriptive Probability)) (:use [incanter.core :only (abs plus minus div mult mmult to-list bind-columns gamma pow sqrt diag trans regularized-beta ncol nrow identity-matrix decomp-cholesky decomp-svd matrix length sum sum-of-squares sel matrix? cumulative-sum solve vectorize bind-rows)])) (defn indicator " Returns a sequence of ones and zeros, where ones are returned when the given predicate is true for corresponding element in the given collection, and zero otherwise. Examples: (use 'incanter.stats) (indicator #(neg? %) (sample-normal 10)) ;; return the sum of the positive values in a normal sample (def x (sample-normal 100)) (sum (mult x (indicator #(pos? %) x))) " ([pred coll] (for [el coll] (if (pred el) 1 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CONTINOUS DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; F DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-f " Returns the F pdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's df function. Options: :df1 (default 1) :df2 (default 1) See also: cdf-f and quantile-f References: http://en.wikipedia.org/wiki/F_distribution http://mathworld.wolfram.com/F-Distribution.html http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-f 1.0 :df1 5 :df2 2) " ([x & options] (let [opts (when options (apply assoc {} options)) df1 (or (:df1 opts) 0) df2 (or (:df2 opts) 1) pdf-fx (fn [x] (* (/ (gamma (/ (+ df1 df2) 2)) (* (gamma (/ df1 2)) (gamma (/ df2 2)))) (pow (/ df1 df2) (/ df1 2)) (pow x (- (/ df1 2) 1)) (pow (+ 1 (* (/ df1 df2) x)) (- 0 (/ (+ df1 df2) 2))))) ] (if (coll? x) (map pdf-fx x) (pdf-fx x))))) (defn cdf-f " Returns the F-distribution cdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pf function. Options: :df1 (default 1) :df2 (default 1) See also: pdf-f and quantile-f References: http://en.wikipedia.org/wiki/F_distribution http://mathworld.wolfram.com/F-Distribution.html http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-f 1.0 :df1 5 :df2 2) " ([x & options] (let [opts (when options (apply assoc {} options)) lower-tail? (if (false? (:lower-tail opts)) false true) df1 (or (:df1 opts) 1) df2 (or (:df2 opts) 1) cdf-fx (if lower-tail? (fn [x1] (regularized-beta (/ (* df1 x1) (+ df2 (* df1 x1))) (/ df1 2) (/ df2 2))) (fn [x1] (- 1 (regularized-beta (/ (* df1 x1) (+ df2 (* df1 x1))) (/ df1 2) (/ df2 2))))) ] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NORMAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-normal " Returns the Normal pdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dnorm function. Options: :mean (default 0) :sd (default 1) See also: cdf-normal, quantile-normal, sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-normal 1.96 :mean -2 :sd (sqrt 0.5)) " ([x & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) dist (Normal. mean sd (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-normal " Returns the Normal cdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pnorm function. Options: :mean (default 0) :sd (default 1) See also: pdf-normal, quantile-normal, sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-normal 1.96 :mean -2 :sd (sqrt 0.5)) " ([x & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) dist (Normal. mean sd (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn quantile-normal " Returns the inverse of the Normal CDF for the given probability. It will return a sequence of values, if given a sequence of probabilities. This is equivalent to R's qnorm function. Options: :mean (default 0) :sd (default 1) Returns: a value x, where (cdf-normal x) = probability See also: pdf-normal, cdf-normal, and sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/Probability.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Quantile Example: (quantile-normal 0.975) (quantile-normal [0.025 0.975] :mean -2 :sd (sqrt 0.5)) " ([probability & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) x (if (coll? probability) (map #(Probability/normalInverse %) probability) (Probability/normalInverse probability))] (plus mean (mult sd x))))) (defn sample-normal " Returns a sample of the given size from a Normal distribution This is equivalent to R's rnorm function. Options: :mean (default 0) :sd (default 1) See also: pdf-normal, cdf-normal, quantile-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution Example: (sample-normal 1000 :mean -2 :sd (sqrt 0.5)) " ([size & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1)] (if (= size 1) (Normal/staticNextDouble mean sd) (for [_ (range size)] (Normal/staticNextDouble mean sd)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; MULTIVARIATE NORMAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sample-mvn " Returns a sample of the given size from a Multivariate Normal distribution. This is equivalent to R's mvtnorm::rmvnorm function. Arguments: size -- the size of the sample to return Options: :mean (default (repeat (ncol sigma) 0)) :sigma (default (identity-matrix (count mean))) Examples: (use '(incanter core stats charts)) (def mvn-samp (sample-mvn 1000 :mean [7 5] :sigma (matrix [[2 1.5] [1.5 3]]))) (covariance mvn-samp) (def means (map mean (trans mvn-samp))) ;; plot scatter-plot of points (def mvn-plot (scatter-plot (sel mvn-samp :cols 0) (sel mvn-samp :cols 1))) (view mvn-plot) ;; add centroid to plot (add-points mvn-plot [(first means)] [(second means)]) ;; add regression line to scatter plot (def x (sel mvn-samp :cols 0)) (def y (sel mvn-samp :cols 1)) (def lm (linear-model y x)) (add-lines mvn-plot x (:fitted lm)) References: http://en.wikipedia.org/wiki/Multivariate_normal " ([size & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) (if (:sigma opts) (repeat (ncol (:sigma opts)) 0) [0])) sigma (or (:sigma opts) (identity-matrix (count mean))) p (count mean) chol (decomp-cholesky sigma) norm-samp (mmult (matrix (sample-normal (* size p)) p) chol) ] (if (> (nrow norm-samp) 1) (matrix (map #(plus % (trans mean)) norm-samp)) (matrix (plus norm-samp (trans mean))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UNIFORM DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-uniform " Returns the Uniform pdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dunif function. Options: :min (default 0) :max (default 1) See also: cdf-uniform and sample-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-uniform 5) (pdf-uniform 5 :min 1 :max 10) " ([x & options] (let [opts (when options (apply assoc {} options)) min (double (or (:min opts) 0.0)) max (double (or (:max opts) 1.0)) dist (DoubleUniform. min max (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-uniform " Returns the Uniform cdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's punif function. Options: :min (default 0) :max (default 1) See also: pdf-uniform and sample-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-uniform 5) (cdf-uniform 5 :min 1 :max 10) " ([x & options] (let [opts (when options (apply assoc {} options)) min (double (or (:min opts) 0.0)) max (double (or (:max opts) 1.0)) dist (DoubleUniform. min max (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn sample-uniform " Returns a sample of the given size from a Uniform distribution. This is equivalent to R's runif function. Options: :min (default 0) :max (default 1) :integers (default false) See also: pdf-uniform and cdf-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution Example: (sample-uniform 1000) (sample-uniform 1000 :min 1 :max 10) " ([size & options] (let [opts (when options (apply assoc {} options)) min-val (double (or (:min opts) 0.0)) max-val (double (or (:max opts) 1.0)) ints? (if (true? (:integers opts)) true false) dist (DoubleUniform. min-val max-val (DoubleMersenneTwister.))] (if (= size 1) (if ints? (DoubleUniform/staticNextIntFromTo min-val max-val) (DoubleUniform/staticNextDoubleFromTo min-val max-val)) (if ints? (for [_ (range size)] (DoubleUniform/staticNextIntFromTo min-val max-val)) (for [_ (range size)] (DoubleUniform/staticNextDoubleFromTo min-val max-val))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BETA DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-beta " Returns the Beta pdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dbeta function. Options: :alpha (default 1) :beta (default 1) See also: cdf-beta and sample-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-beta 0.5 :alpha 1 :beta 2) " ([x & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1) dist (Beta. alpha beta (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-beta " Returns the Beta cdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pbeta function. Options: :alpha (default 1) :beta (default 1) :lower-tail (default true) See also: pdf-beta and sample-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-beta 0.5 :alpha 1 :beta 2) (cdf-beta 0.5 :alpha 1 :beta 2 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/beta alpha beta x1)) (fn [x1] (- 1 (Probability/betaComplemented alpha beta x1))))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-beta " Returns a sample of the given size from a Beta distribution. This is equivalent to R's rbeta function. Options: :alpha (default 1) :beta (default 1) These default values produce a Uniform distribution. See also: pdf-beta and cdf-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution Example: (sample-beta 1000 :alpha 1 :beta 2) " ([size & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1)] (if (= size 1) (Beta/staticNextDouble alpha beta) (for [_ (range size)] (Beta/staticNextDouble alpha beta)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; GAMMA DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-gamma " Returns the Gamma pdf for the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dgamma function. Options: :shape (default 1) :rate (default 1) See also: cdf-gamma and sample-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-gamma 10 :shape 1 :rate 2) " ([x & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1) dist (Gamma. shape rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-gamma " Returns the Gamma cdf for the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pgamma function. Options: :shape (default 1) :rate (default 1) :lower-tail (default true) See also: pdf-gamma and sample-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-gamma 10 :shape 1 :rate 2) (cdf-gamma 3 :shape 1 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/gamma rate shape x1)) (fn [x1] (Probability/gammaComplemented rate shape x1)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-gamma " Returns a sample of the given size from a Gamma distribution. This is equivalent to R's rgamma function. Options: :shape (default 1) :rate (default 1) See also: pdf-gamma, cdf-gamma, and quantile-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution Example: (sample-gamma 1000 :shape 1 :rate 2) " ([size & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1)] (if (= size 1) (Gamma/staticNextDouble shape rate) (for [_ (range size)] (Gamma/staticNextDouble shape rate)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CHI SQUARE DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-chisq " Returns the Chi Square pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dchisq function. Options: :df (default 1) See also: cdf-chisq and sample-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-chisq 5.0 :df 2) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) dist (ChiSquare. df (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-chisq " Returns the Chi Square cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pchisq function. Options: :df (default 1) :lower-tail (default true) See also: pdf-chisq and sample-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-chisq 5.0 :df 2) (cdf-chisq 5.0 :df 2 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/chiSquare df x1)) (fn [x1] (Probability/chiSquareComplemented df x1)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-chisq " Returns a sample of the given size from a Chi Square distribution Same as R's rchisq function. Options: :df (default 1) See also: pdf-chisq and cdf-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution Example: (sample-chisq 1000 :df 2) " ([size & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1)] (if (= size 1) (ChiSquare/staticNextDouble df) (for [_ (range size)] (ChiSquare/staticNextDouble df)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; STUDENT'S T DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-t " Returns the Student's t pdf for the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dt function. Options: :df (default 1) See also: cdf-t, quantile-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-t 1.2 :df 10) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) dist (StudentT. df (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-t " Returns the Student's t cdf for the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pt function. Options: :df (default 1) See also: pdf-t, quantile-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-t 1.2 :df 10) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/studentT df x1)) (fn [x1] (- 1 (Probability/studentT df x1))))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn quantile-t " Returns the inverse of the Student's t CDF for the given probability (i.e. the quantile). It will return a sequence of values, if x is a sequence of probabilities. This is equivalent to R's qt function. Options: :df (default 1) Returns: a value x, where (cdf-t x) = probability See also: pdf-t, cdf-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/Probability.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Quantile Example: (quantile-t 0.975) (quantile-t [0.025 0.975] :df 25) (def df [1 2 3 4 5 6 7 8 9 10 20 50 100 1000]) (map #(quantile-t 0.025 :df %) df) " ([probability & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) to-alpha (fn [prob] ;; need to convert the probability to an alpha value (if (< prob 1/2) (* 2 prob) (* 2 (- 1 prob)))) sign-fx (fn [x1 prob] (if (< prob 1/2) (* -1 x1) x1)) x (if (coll? probability) (map #(sign-fx (Probability/studentTInverse (to-alpha %) df) %) probability) (sign-fx (Probability/studentTInverse (to-alpha probability) df) probability))] x))) (defn sample-t " Returns a sample of the given size from a Student's t distribution. Same as R's rt function. Options: :df (default 1) See also: pdf-t, cdf-t, and quantile-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution Example: (cdf-t 1000 :df 10) " ([size & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1)] (if (= size 1) (StudentT/staticNextDouble df) (for [_ (range size)] (StudentT/staticNextDouble df)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; EXPONENTIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-exp " Returns the Exponential pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dexp Options: :rate (default 1) See also: cdf-exp and sample-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-exp 2.0 :rate 1/2) " ([x & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1) dist (Exponential. rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-exp " Returns the Exponential cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pexp Options: :rate (default 1) See also: pdf-exp and sample-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-exp 2.0 :rate 1/2) " ([x & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1) dist (Exponential. rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn sample-exp " Returns a sample of the given size from a Exponential distribution. Same as R's rexp Options: :rate (default 1) See also: pdf-exp, and cdf-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution Example: (sample-exp 1000 :rate 1/2) " ([size & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1)] (if (= size 1) (Exponential/staticNextDouble rate) (for [_ (range size)] (Exponential/staticNextDouble rate)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; WISHART DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sample-wishart " Returns a p-by-p symmetric distribution drawn from a Wishart distribution Options: :p (default 2) -- number of dimensions of resulting matrix :df (default p) -- degree of freedoms (aka n), df <= p :scale (default (identity-matrix p)) -- positive definite matrix (aka V) Examples: (use 'incanter.stats) (sample-wishart :df 10 :p 4) ;; calculate the mean of 1000 wishart matrices, should equal (mult df scale) (div (reduce plus (for [_ (range 1000)] (sample-wishart :p 4))) 1000) References: http://en.wikipedia.org/wiki/Wishart_distribution# " ([& options] (let [opts (when options (apply assoc {} options)) scale (or (:scale opts) (when (:p opts) (identity-matrix (:p opts)))) p (count scale) df (or (:df opts) p) diagonal (for [i (range 1 (inc p))] (pow (sample-chisq 1 :df (inc (- df i))) 1/2)) mat (diag diagonal) indices (for [i (range p) j (range p) :when (< j i)] [i j]) _ (doseq [indx indices] (.set mat (first indx) (second indx) (sample-normal 1))) chol (decomp-cholesky scale) x (mmult chol mat (trans mat) (trans chol))] x))) (defn sample-inv-wishart " Returns a p-by-p symmetric distribution drawn from an inverse-Wishart distribution Options: :p (default 2) -- number of dimensions of resulting matrix :df (default p) -- degree of freedoms (aka n), df <= p :scale (default (identity-matrix p)) -- positive definite matrix (aka V) Examples: (use 'incanter.stats) (sample-inv-wishart :df 10 :p 4) ;; calculate the mean of 1000 wishart matrices, should equal (mult df scale) (div (reduce plus (for [_ (range 1000)] (sample-wishart :p 4))) 1000) References: http://en.wikipedia.org/wiki/Inverse-Wishart_distribution " ([& options] (let [opts (when options (apply assoc {} options)) scale (or (:scale opts) (when (:p opts) (identity-matrix (:p opts)))) p (count scale) df (or (:df opts) p)] (solve (sample-wishart :p p :df df :scale scale))))) (defn sample-dirichlet " Examples: (use '(incanter core stats charts)) ;; a total of 1447 adults were polled to indicate their preferences for ;; candidate 1 (y1=727), candidate 2 (y2=583), or some other candidate or no ;; preference (y3=137). ;; the counts y1, y2, and y3 are assumed to have a multinomial distribution ;; If a uniform prior distribution is assigned to the multinomial vector ;; theta = (th1, th2, th3), then the posterior distribution of theta is ;; proportional to g(theta) = th1^y1 * th2^y2 * th3^y3, which is a ;; dirichlet distribution with parameters (y1+1, y2+1, y3+1) (def theta (sample-dirichlet 1000 [(inc 727) (inc 583) (inc 137)])) ;; view means, 95% CI, and histograms of the proportion parameters (mean (sel theta :cols 0)) (quantile (sel theta :cols 0) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 0))) (mean (sel theta :cols 1)) (quantile (sel theta :cols 1) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 1))) (mean (sel theta :cols 2)) (quantile (sel theta :cols 2) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 2))) ;; view a histogram of the difference in proportions between the first ;; two candidates (view (histogram (minus (sel theta :cols 0) (sel theta :cols 1)))) " ([size alpha] (let [W (trans (for [a alpha] (sample-gamma size :shape a :rate 1))) T (map sum W)] (matrix (map #(div %1 %2) W T))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DISCRETE DISTRIBUTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BINOMIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-binomial " Returns the Bionomial pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dbinom Options: :size (default 1) :prob (default 1/2) See also: cdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-binomial 10 :prob 1/4 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2) dist (Binomial. n p (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-binomial " Returns the Bionomial cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pbinom Options: :size (default 1) :prob (default 1/2) :lower-tail (default true) See also: pdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-binomial 10 :prob 1/4 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/binomial x1 n p)) (fn [x1] (Probability/binomialComplemented x1 n p)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-binomial " Returns a sample of the given size from a Binomial distribution. Same as R's rbinom Options: :size (default 1) :prob (default 1/2) See also: cdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution Example: (sample-binomial 1000 :prob 1/4 :size 20) " ([size & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2)] (if (= size 1) (Binomial/staticNextInt n p) (for [_ (range size)] (Binomial/staticNextInt n p)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; POISSON DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-poisson " Returns the Poisson pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dpois Options: :lambda (default 1) See also: cdf-poisson and sample-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-poisson 5 :lambda 10) " ([x & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1) dist (Poisson. lambda (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-poisson " Returns the Poisson cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's ppois Options: :lambda (default 1) :lower-tail (default true) See also: cdf-poisson and sample-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-poisson 5 :lambda 10) " ([x & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/poisson x1 lambda)) (fn [x1] (Probability/poissonComplemented x1 lambda)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-poisson " Returns a sample of the given size from a Poisson distribution. Same as R's rpois Options: :lambda (default 1) See also: pdf-poisson and cdf-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution Example: (sample-poisson 1000 :lambda 10) " ([size & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1)] (if (= size 1) (Poisson/staticNextInt lambda) (for [_ (range size)] (Poisson/staticNextInt lambda)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NEGATIVE BINOMIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-neg-binomial " Returns the Negative Binomial pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dnbinom Options: :size (default 10) :prob (default 1/2) See also: cdf-neg-binomial and sample-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-neg-binomial 10 :prob 1/2 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2) dist (NegativeBinomial. size prob (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-neg-binomial " Returns the Negative Binomial cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dnbinom Options: :size (default 10) :prob (default 1/2) See also: cdf-neg-binomial and sample-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-neg-binomial 10 :prob 1/2 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/negativeBinomial x1 size prob)) (fn [x1] (Probability/negativeBinomialComplemented x1 size prob)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-neg-binomial " Returns a sample of the given size from a Negative Binomial distribution. Same as R's rnbinom Options: :size (default 10) :prob (default 1/2) See also: pdf-neg-binomial and cdf-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution Example: (sample-neg-binomial 1000 :prob 1/2 :size 20) " ([size & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2)] (if (= size 1) (NegativeBinomial/staticNextInt size prob) (for [_ (range size)] (NegativeBinomial/staticNextInt size prob)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; EMPIRICAL DISTRIBUTION ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn cdf-empirical " Returns a step-function representing the empirical cdf of the given data. Equivalent to R's ecdf function. The following description is from the ecdf help in R: The e.c.d.f. (empirical cumulative distribution function) Fn is a step function with jumps i/n at observation values, where i is the number of tied observations at that value. Missing values are ignored. For observations 'x'= (x1,x2, ... xn), Fn is the fraction of observations less or equal to t, i.e., Fn(t) = #{x_i <= t} / n = 1/n sum(i=1,n) Indicator(xi <= t). Examples: (use '(incanter core stats charts)) (def exam1 [192 160 183 136 162 165 181 188 150 163 192 164 184 189 183 181 188 191 190 184 171 177 125 192 149 188 154 151 159 141 171 153 169 168 168 157 160 190 166 150]) ;; the ecdf function returns an empirical cdf function for the given data (def ecdf (cdf-empirical exam1)) ;; plot the data's empircal cdf (view (scatter-plot exam1 (map ecdf exam1))) " ([x] (fn [t] (div (sum (indicator #(<= % t) x)) (count x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; STATISTICAL FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mean " Returns the mean of the data, x. Examples: (mean (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Mean " ([x] (let [xx (to-list x)] (DoubleDescriptive/mean (DoubleArrayList. (double-array xx)))))) (defn variance " Returns the sample variance of the data, x. Equivalent to R's var function. Examples: (variance (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Sample_variance#Population_variance_and_sample_variance " ([x] (DoubleDescriptive/sampleVariance (length x) (sum x) (sum-of-squares x)))) (defn covariance " Returns the sample covariance of x and y. Examples: ;; create some data that covaries (def x (sample-normal 100)) (def err (sample-normal 100)) (def y (plus (mult 5 x) err)) ;; estimate the covariance of x and y (covariance x y) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Covariance " ([x y] (let [ xx (to-list x) yy (to-list y) ] (DoubleDescriptive/covariance (DoubleArrayList. (double-array xx)) (DoubleArrayList. (double-array yy))))) ([mat] (let [n (ncol mat)] (matrix (for [i (range n) j (range n)] (covariance (sel mat true i) (sel mat true j))) n)))) (defn sd " Returns the sample standard deviation of the data, x. Equivalent to R's sd function. Examples: (sd (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Standard_deviation " ([x] ;; population sd, not the sample sd ;(DoubleDescriptive/sampleStandardDeviation (length x) (variance x)))) ;; return the sample standard deviation (sqrt (variance x)))) (defn correlation " Returns the sample correlation of x and y, or the correlation matrix of the given matrix. Examples: References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Correlation " ([x y] (let [ xx (to-list x) yy (to-list y) ] (DoubleDescriptive/correlation (DoubleArrayList. (double-array xx)) (sd x) (DoubleArrayList. (double-array yy)) (sd y)))) ([mat] (div (covariance mat) (sqrt (mmult (diag (covariance mat)) (trans (diag (covariance mat)))))))) (defn median " Returns the median of the data, x. Examples: (median (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Median " ([x] (let [xx (sort (to-list x))] (DoubleDescriptive/median (DoubleArrayList. (double-array xx)))))) (defn kurtosis " Returns the kurtosis of the data, x. \"Kurtosis is a measure of the \"peakedness\" of the probability distribution of a real-valued random variable. Higher kurtosis means more of the variance is due to infrequent extreme deviations, as opposed to frequent modestly-sized deviations.\" (Wikipedia) Examples: (kurtosis (sample-normal 100000)) ;; approximately 0 (kurtosis (sample-gamma 100000)) ;; approximately 6 References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Kurtosis " ([x] (DoubleDescriptive/kurtosis (DoubleArrayList. (double-array x)) (mean x) (variance x)))) (defn skewness " Returns the skewness of the data, x. \"Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable.\" (Wikipedia) Examples: (skewness (sample-normal 100000)) ;; approximately 0 (skewness (sample-gamma 100000)) ;; approximately 2 References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Skewness " ([x] (DoubleDescriptive/skew (DoubleArrayList. (double-array x)) (mean x) (sd x)))) (defn quantile " Returns the quantiles of the data, x. By default it returns the min, 25th-percentile, 50th-percentile, 75th-percentile, and max value. Options: :probs (default [0.0 0.25 0.5 0.75 1.0]) Examples: (quantile (sample-normal 100)) (quantile (sample-normal 100) :probs [0.025 0.975]) (quantile (sample-normal 100) :probs 0.975) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Quantile " ([x & options] (let [opts (when options (apply assoc {} options)) _x (if (matrix? x) (to-list x) x) data (DoubleArrayList. (double-array (sort _x))) probs (cond (number? (:probs opts)) (:probs opts) (coll? (:probs opts)) (DoubleArrayList. (double-array (:probs opts))) :default (DoubleArrayList. (double-array [0.0 0.25 0.5 0.75 1.0])))] (if (number? probs) (DoubleDescriptive/quantile data probs) (seq (.elements (DoubleDescriptive/quantiles data probs))))))) (defn sample " Returns a sample of the given size from the given collection. If replacement is set to false it returns a set, otherwise it returns a list. Arguments: x -- collection to be sampled from Options: :size -- (default (count x) sample size :replacement (default true) -- sample with replacement Examples: (sample (range 10)) ; permutation of numbers zero through ten (sample [:red :green :blue] :size 10) ; choose 10 items that are either :red, :green, or :blue. (sample (seq \"abcdefghijklmnopqrstuvwxyz\") :size 4 :replacement false) ; choose 4 random letters. " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) (count x)) replacement? (if (false? (:replacement opts)) false true) max-idx (dec (count x))] (if (= size 1) (nth x (rand-int (inc max-idx))) (if replacement? (map #(nth x %) (sample-uniform size :min 0 :max max-idx :integers true)) (if (> size (count x)) (throw (Exception. "'size' can't be larger than (count x) without replacement!")) (map #(nth x %) (loop [samp-indices [] indices-set #{}] (if (= (count samp-indices) size) samp-indices (let [i (sample-uniform 1 :min 0 :max max-idx :integers true)] (if (contains? indices-set i) (recur samp-indices indices-set) (recur (conj samp-indices i) (conj indices-set i))))))))))))) (defn bootstrap " Returns a bootstrap sample of the given statistic on the given data. Arguments: data -- vector of data to resample from statistic -- a function that returns a value given a vector of data Options: :size -- the number of bootstrap samples to return :smooth -- (default false) smoothing option :smooth-sd -- (default (/ (sqrt (count data)))) determines the standard deviation of the noise to use for smoothing :replacement -- (default true) determines if sampling of the data should be done with replacement References: 1. Clifford E. Lunneborg, Data Analysis by Resampling Concepts and Applications, 2000, pages 105-117 2. http://en.wikipedia.org/wiki/Bootstrapping_(statistics) Examples: ;; example from Data Analysis by Resampling Concepts and Applications ;; Clifford E. Lunneborg (pages 119-122) (use '(incanter core stats charts)) ;; weights (in grams) of 50 randomly sampled bags of preztels (def weights [464 447 446 454 450 457 450 442 433 452 449 454 450 438 448 449 457 451 456 452 450 463 464 453 452 447 439 449 468 443 433 460 452 447 447 446 450 459 466 433 445 453 454 446 464 450 456 456 447 469]) ;; calculate the sample median, 450 (median weights) ;; generate bootstrap sample (def t* (bootstrap weights median :size 2000)) ;; view histogram of bootstrap histogram (view (histogram t*)) ;; calculate the mean of the bootstrap median ~ 450.644 (mean t*) ;; calculate the standard error ~ 1.083 (def se (sd t*)) ;; 90% standard normal CI ~ (448.219 451.781) (plus (median weights) (mult (quantile-normal [0.05 0.95]) se)) ;; 90% symmetric percentile CI ~ (449.0 452.5) (quantile t* :probs [0.05 0.95]) ;; 90% non-symmetric percentile CI ~ (447.5 451.0) (minus (* 2 (median weights)) (quantile t* :probs [0.95 0.05])) ;; calculate bias (- (mean t*) (median weights)) ;; ~ 0.644 ;; example with smoothing ;; Newcomb's speed of light data (use '(incanter core stats charts)) ;; A numeric vector giving the Third Series of measurements of the ;; passage time of light recorded by Newcomb in 1882. The given ;; values divided by 1000 plus 24 give the time in millionths of a ;; second for light to traverse a known distance. The 'true' value is ;; now considered to be 33.02. (def speed-of-light [28 -44 29 30 24 28 37 32 36 27 26 28 29 26 27 22 23 20 25 25 36 23 31 32 24 27 33 16 24 29 36 21 28 26 27 27 32 25 28 24 40 21 31 32 28 26 30 27 26 24 32 29 34 -2 25 19 36 29 30 22 28 33 39 25 16 23]) ;; view histogram of data to see outlier observations (view (histogram speed-of-light :nbins 30)) (def samp (bootstrap speed-of-light median :size 10000)) (view (histogram samp :density true :nbins 30)) (mean samp) (quantile samp :probs [0.025 0.975]) (def smooth-samp (bootstrap speed-of-light median :size 10000 :smooth true)) (view (histogram smooth-samp :density true :nbins 30)) (mean smooth-samp) (quantile smooth-samp :probs [0.025 0.975]) " ([data statistic & options] (let [opts (when options (apply assoc {} options)) size (:size opts) replacement (if (false? (:replacement opts)) false true) n (or (:n opts) (count data)) smooth? (true? (:smooth opts)) smooth-sd (or (:smooth-sd opts) (/ (sqrt n))) B1 100 B2 25 max-iter 10 D 0.01 samp (if (nil? size) (loop [stats (for [_ (range B1)] (statistic (sample data :size n :replacement replacement))) k 0] (let [stats2 (concat stats (for [_ (range B2)] (statistic (sample data :size n :replacement replacement)))) se1 (sd stats) se2 (sd stats2)] (if (or (= k max-iter) (< (* (- 1 D) se1) se2 (* (+ 1 D) se1))) stats2 (recur stats2 (inc k))))) (for [_ (range size)] (statistic (sample data :size n :replacement replacement)))) samp-size (count samp)] (if smooth? (plus samp (sample-normal samp-size :sd smooth-sd)) samp)))) (defn cumulative-mean " Returns a sequence of cumulative means for the given collection. For instance The first value equals the first value of the argument, the second value is the mean of the first two arguments, the third is the mean of the first three arguments, etc. Examples: (cumulative-mean (sample-normal 100)) " ([coll] (map / (cumulative-sum coll) (range 1 (inc (count coll)))))) (defn sweep " Return an array obtained from an input array by sweeping out a summary statistic. Based to R's sweep function. Arguments: x is an sequence Options: :stat (default mean) the statistic to sweep out :fun (defaul minus) the function used to sweep the stat out Example: (use '(incanter core stats)) (def x (sample-normal 30 :mean 10 :sd 5)) (sweep x) ;; center the data around mean (sweep x :stat sd :fun div) ;; divide data by its sd " ([x & options] (let [opts (when options (apply assoc {} options)) stat-fn (or (:stat opts) mean) fun (or (:fun opts) minus) stat (stat-fn x)] (fun x stat)))) (defn permute " If provided a single argument, returns a permuted version of the given collection. (perm x) is the same as (sample x). If provided two arguments, returns two lists that are permutations across the given collections. In other words, each of the new collections will contain elements from both of the given collections. Useful for permutation tests or randomization tests. Examples: (permute (range 10)) (permute (range 10) (range 10 20)) " ([x] (sample x)) ([x y] (let [n1 (count x) samp (sample (concat x y) :replacement false) new-x (take n1 samp) new-y (drop n1 samp)] (list new-x new-y)))) (defn sample-permutations " If provided a two arguments (n x), it returns a list of n permutations of x. If provided three (n x y) arguments, returns a list with two with n permutations of each arguments, where each permutation is drawn from the pooled arguments. Arguments: n -- number of randomized versions of the original two groups to return x -- group 1 y -- (default nil) group 2 Examples: (use '(incanter core stats)) (sample-permutations 10 (range 10)) (sample-permutations 10 (range 10) (range 10 20)) ;; extended example with plant-growth data (use '(incanter core stats datasets charts)) ;; load the plant-growth dataset (def data (to-matrix (get-dataset :plant-growth))) ;; break the first column of the data into groups based on treatment (second column). (def groups (group-by data 1 :cols 0)) ;; define a function for the statistic of interest (defn means-diff [x y] (minus (mean x) (mean y))) ;; calculate the difference in sample means between the two groups (def samp-mean-diff (means-diff (first groups) (second groups))) ;; 0.371 ;; create 500 permuted versions of the original two groups (def permuted-groups (sample-permutations 1000 (first groups) (second groups))) ;; calculate the difference of means of the 500 samples (def permuted-means-diffs1 (map means-diff (first permuted-groups) (second permuted-groups))) ;; use an indicator function that returns 1 when the randomized means diff is greater ;; than the original sample mean, and zero otherwise. Then take the mean of this sequence ;; of ones and zeros. That is the proportion of times you would see a value more extreme ;; than the sample mean (i.e. the p-value). (mean (indicator #(> % samp-mean-diff) permuted-means-diffs1)) ;; 0.088 ;; calculate the 95% confidence interval of the null hypothesis. If the ;; sample difference in means is outside of this range, that is evidence ;; that the two means are statistically significantly different. (quantile permuted-means-diffs1 :probs [0.025 0.975]) ;; (-0.606 0.595) ;; Plot a histogram of the permuted-means-diffs using the density option, ;; instead of the default frequency, and then add a normal pdf curve with ;; the mean and sd of permuted-means-diffs data for a visual comparison. (doto (histogram permuted-means-diffs1 :density true) (add-lines (range -1 1 0.01) (pdf-normal (range -1 1 0.01) :mean (mean permuted-means-diffs1) :sd (sd permuted-means-diffs1))) view) ;; compare the means of treatment 2 and control (def permuted-groups (sample-permutations 1000 (first groups) (last groups))) (def permuted-means-diffs2 (map means-diff (first permuted-groups) (second permuted-groups))) (def samp-mean-diff (means-diff (first groups) (last groups))) ;; -0.4939 (mean (indicator #(< % samp-mean-diff) permuted-means-diffs2)) ;; 0.022 (quantile permuted-means-diffs2 :probs [0.025 0.975]) ;; (-0.478 0.466) ;; compare the means of treatment 1 and treatment 2 (def permuted-groups (sample-permutations 1000 (second groups) (last groups))) (def permuted-means-diffs3 (map means-diff (first permuted-groups) (second permuted-groups))) (def samp-mean-diff (means-diff (second groups) (last groups))) ;; -0.865 (mean (indicator #(< % samp-mean-diff) permuted-means-diffs3)) ;; 0.002 (quantile permuted-means-diffs3 :probs [0.025 0.975]) ;; (-0.676 0.646) (doto (box-plot permuted-means-diffs1) (add-box-plot permuted-means-diffs2) (add-box-plot permuted-means-diffs3) view) Further Reading: http://en.wikipedia.org/wiki/Resampling_(statistics) " ([n x] (loop [samp '() i 0] (if (= i n) samp (recur (conj samp (sample x)) (inc i))))) ([n x y] (let [pool (concat x y) m1 (count x)] (loop [samp-x '() samp-y '() i 0] (if (= i n) (list samp-x samp-y) (let [perm-samp (sample pool) new-x (take m1 perm-samp) new-y (drop m1 perm-samp)] (recur (conj samp-x new-x) (conj samp-y new-y) (inc i)))))))) ;;;;;;;;;;;;;;; OLS REGRESSION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;; (defn linear-model " Returns the results of performing a OLS linear regression of y on x. Arguments: y is a vector (or sequence) of values for the dependent variable x is a vector or matrix of values for the independent variables Options: :intercept (default true) indicates weather an intercept term should be included Returns: a map, of type ::linear-model, containing: :design-matrix -- a matrix containing the independent variables, and an intercept columns :coefs -- the regression coefficients :t-tests -- t-test values of coefficients :t-probs -- p-values for t-test values of coefficients :coefs-ci -- 95% percentile confidence interval :fitted -- the predicted values of y :residuals -- the residuals of each observation :std-errors -- the standard errors of the coeffients :sse -- the sum of squared errors, also called the residual sum of squares :ssr -- the regression sum of squares, also called the explained sum of squares :sst -- the total sum of squares (proportional to the sample variance) :r-square -- coefficient of determination Examples: (use '(incanter core stats datasets charts)) (def iris (to-matrix (get-dataset :iris) :dummies true)) (def y (sel iris :cols 0)) (def x (sel iris :cols (range 1 6))) (def iris-lm (linear-model y x)) ; with intercept term (keys iris-lm) ; see what fields are included (:coefs iris-lm) (:sse iris-lm) (quantile (:residuals iris-lm)) (:r-square iris-lm) (:adj-r-square iris-lm) (:f-stat iris-lm) (:f-prob iris-lm) (:df iris-lm) (def x1 (range 0.0 3 0.1)) (view (xy-plot x1 (cdf-f x1 :df1 4 :df2 144))) References: http://en.wikipedia.org/wiki/OLS_Regression http://en.wikipedia.org/wiki/Coefficient_of_determination " ([y x & options] (let [opts (when options (apply assoc {} options)) intercept? (if (false? (:intercept opts)) false true) _x (if intercept? (bind-columns (replicate (nrow x) 1) x) x) xtx (mmult (trans _x) _x) xtxi (if (number? xtx) (/ 1 xtx) (solve xtx)) xty (mmult (trans _x) y) coefs (if (and (number? xtxi) (number? xty)) (* xtxi xty) (to-list (if (or (number? xtxi) (number? xty)) (mult xtxi xty) (mmult xtxi xty)))) fitted (to-list (if (number? coefs) (mult _x coefs) (mmult _x coefs))) resid (to-list (minus y fitted)) sse (sum-of-squares resid) ssr (sum-of-squares (minus fitted (mean fitted))) sst (+ sse ssr) r-square (/ ssr sst) n (nrow y) p (ncol _x) p-1 (if intercept? (- p 1) p) adj-r-square (- 1 (* (- 1 r-square) (/ (- n 1) (- n p 1)))) mse (/ sse (- n p)) msr (/ ssr p-1) f-stat (/ msr mse) df1 p-1 df2 (- n p) f-prob (cdf-f f-stat :df1 df1 :df2 df2 :lower-tail false) coef-var (mult mse xtxi) std-errors (sqrt (diag coef-var)) t-tests (div coefs std-errors) t-probs (mult 2 (cdf-t (abs t-tests) :df df2 :lower-tail false)) t-95 (mult (quantile-t 0.975 :df df2) std-errors) coefs-ci (if (number? std-errors) [(plus coefs t-95) (minus coefs t-95)] (partition 2 (interleave (minus coefs t-95) (plus coefs t-95)))) ] (with-meta {:x _x :y y :fitted fitted :design-matrix _x :coefs coefs :t-tests t-tests :t-probs t-probs :coefs-ci coefs-ci :residuals resid :std-errors std-errors :sse sse :ssr ssr :sst sst :mse mse :msr msr :f-stat f-stat :f-prob f-prob :df [df1 df2] :coef-var coef-var :r-square r-square :adj-r-square adj-r-square } {:type ::linear-model})))) (defn t-test " Argument: x : sample to test Options: :y (default nil) :mu (default (mean y) or 0) population mean :alternative (default :two-sided) other choices :less :greater :var-equal TODO (default false) variance equal :paired TODO (default false) paired test :conf-level (default 0.95) for returned confidence interval Examples: (t-test (range 1 11) :mu 0) (t-test (range 1 11) :mu 0 :alternative :less) (t-test (range 1 11) :mu 0 :alternative :greater) (t-test (range 1 11) :y (range 7 21)) (t-test (range 1 11) :y (range 7 21) :alternative :less) (t-test (range 1 11) :y (range 7 21) :alternative :greater) (t-test (range 1 11) :y (conj (range 7 21) 200)) References: http://en.wikipedia.org/wiki/T_test http://www.socialresearchmethods.net/kb/stat_t.php " ([x & options] (let [opts (when options (apply assoc {} options)) y (or (:y opts) nil) one-sample? (nil? y) mu (or (:mu opts) (if y (mean y) 0)) paired? (if (true? (:paired opts)) true false) var-equal? (if (true? (:var-equal opts)) true false) conf-level (or (:conf-level opts) 0.95) alternative (or (:alternative opts) :two-sided) x-mean (mean x) x-var (variance x) n1 (count x) y-mean (if one-sample? nil (mean y)) y-var (if one-sample? nil (variance y)) n2 (if one-sample? nil (count y)) t-stat (if one-sample? (/ (- x-mean mu) (/ (sqrt x-var) (sqrt n1))) ;; calculate Welch's t test (/ (- x-mean y-mean) (sqrt (+ (/ x-var n1) (/ y-var n2))))) df (if one-sample? (dec n1) ;; calculate Welch-Satterthwaite equation (/ (pow (+ (/ x-var n1) (/ y-var n2)) 2) (+ (/ (pow (/ x-var n1) 2) (dec n1)) (/ (pow (/ y-var n2) 2) (dec n2))))) lower-tail? (cond (= alternative :two-sided) (if (neg? t-stat) true false) (= alternative :lower) (if (neg? t-stat) false true) (= alternative :greater) (if one-sample? (if (neg? t-stat) true false) (if (neg? t-stat) false true))) one-sided-p (cdf-t t-stat :df df :lower-tail lower-tail?) qt (if (= alternative :two-sided) (quantile-t (/ (- 1 conf-level) 2) :df df) (quantile-t (- 1 conf-level) :df df))] {:t-stat t-stat :df df :x-mean x-mean :x-var x-var :n1 n1 :y-mean y-mean :y-var y-var :n2 n2 :p-value (if (= alternative :two-sided) (* 2 one-sided-p) one-sided-p) :conf-int (if one-sample? ;; one-sample confidence interval [(if (= alternative :less) Double/NEGATIVE_INFINITY (+ x-mean (/ (* qt (sqrt x-var)) (sqrt n1)))) (if (= alternative :greater) Double/POSITIVE_INFINITY (- x-mean (/ (* qt (sqrt x-var)) (sqrt n1))))] ;; two-sample confidence interval [(if (= alternative :less) Double/NEGATIVE_INFINITY (+ (- x-mean y-mean) (* qt (sqrt (+ (/ x-var n1) (/ y-var n2)))))) (if (= alternative :greater) Double/POSITIVE_INFINITY (- (- x-mean y-mean) (* qt (sqrt (+ (/ x-var n1) (/ y-var n2))))))]) }))) (defn tabulate " Cross-tabulates the values of the given numeric matrix. Returns a hash-map with the following fields: :table -- the table of counts for each combination of values, this table is only returned if x has two-columns :levels -- a sequence of sequences, where each sequence list the levels (possible values) of the corresponding column of x. :margins -- a sequence of sequences, where each sequence represents the marginal total for each level of the corresponding column of x. :counts -- a hash-map, where vectors of unique combinations of the cross-tabulated levels are the keys and the values are the total count of each combination. :N -- the grand-total for the contingency table Examples: (use '(incanter core stats)) (tabulate [1 2 3 2 3 2 4 3 5]) (tabulate (sample-poisson 100 :lambda 5)) (use '(incanter core stats datasets)) (def math-prog (to-matrix (get-dataset :math-prog))) (tabulate (sel math-prog :cols [1 2])) (def data (matrix [[1 0 1] [1 1 1] [1 1 1] [1 0 1] [0 0 0] [1 1 1] [1 1 1] [1 0 1] [1 1 0]])) (tabulate data) (def data (matrix [[1 0] [1 1] [1 1] [1 0] [0 0] [1 1] [1 1] [1 0] [1 1]])) (tabulate data) " ([x & options] (let [opts (when options (apply assoc {} options)) _x (if (matrix? x) x (matrix x)) p (ncol _x) n (nrow _x) levels (for [i (range p)] (sort (seq (into #{} (sel _x :cols i))))) margins (for [j (range p)] (loop [marg {} i (int 0)] (if (= i n) marg (let [lvl (sel _x :rows i :cols j)] (recur (let [cnt (get marg lvl)] (if cnt (assoc marg lvl (inc cnt)) (assoc marg lvl 1))) (inc i)))))) counts (loop [tab {} i (int 0)] (if (= i n) tab (recur (let [row (if (> p 1) (to-list (nth _x i)) (nth _x i)) cnt (get tab row)] (if (nil? cnt) (assoc tab row 1) (assoc tab row (inc cnt)))) (inc i)))) n-levels (map #(count (keys %)) margins)] {:counts counts :margins margins :table (when (= p 2) (matrix (for [r (first levels) c (second levels)] (let [c (get counts (to-list (trans [r c])))] (if c c 0))) (second n-levels))) :n-vars p :N (reduce + (vals (first margins))) :n-levels n-levels :levels levels}))) (defn chisq-test " Performs chi-squared contingency table tests and goodness-of-fit tests. If the optional argument :y is not provided then a goodness-of-fit test is performed. In this case, the hypothesis tested is whether the population probabilities equal those in :probs, or are all equal if :probs is not given. If :y is provided, it must be a sequence of integers that is the same length as x. A contingency table is computed from x and :y. Then, Pearson's chi-squared test of the null hypothesis that the joint distribution of the cell counts in a 2-dimensional contingency table is the product of the row and column marginals is performed. By default the Yates' continuity correction for 2x2 contingency tables is performed, this can be disabled by setting the :correct option to false. Options: :x -- a sequence of numbers. :y -- a sequence of numbers :table -- a contigency table. If one dimensional, the test is a goodness-of-fit :probs (when (nil? y) -- (repeat n-levels (/ n-levels))) :freq (default nil) -- if given, these are rescaled to probabilities :correct (default true) -- use Yates' correction for continuity for 2x2 contingency tables Returns: :X-sq -- the Pearson X-squared test statistics :p-value -- the p-value for the test statistic :df -- the degress of freedom Examples: (use '(incanter core stats)) (chisq-test :x [1 2 3 2 3 2 4 3 5]) ;; X-sq 2.6667 ;; create a one-dimensional table of this data (def table (matrix [1 3 3 1 1])) (chisq-test :table table) ;; X-sq 2.6667 (chisq-test :table (trans table)) ;; throws exception (chisq-test :x [1 0 0 0 1 1 1 0 0 1 0 0 1 1 1 1]) ;; 0.25 (use '(incanter core stats datasets)) (def math-prog (to-matrix (get-dataset :math-prog))) (def x (sel math-prog :cols 1)) (def y (sel math-prog :cols 2)) (chisq-test :x x :y y) ;; X-sq = 1.24145, df=1, p-value = 0.26519 (chisq-test :x x :y y :correct false) ;; X-sq = 2.01094, df=1, p-value = 0.15617 (def table (matrix [[31 12] [9 8]])) (chisq-test :table table) ;; X-sq = 1.24145, df=1, p-value = 0.26519 (chisq-test :table table :correct false) ;; X-sq = 2.01094, df=1, p-value = 0.15617 ;; use the detabulate function to create data rows corresponding to the table (def detab (detabulate :table table)) (chisq-test :x (sel detab :cols 0) :y (sel detab :cols 1)) ;; look at the hair-eye-color data ;; turn the count data for males into a contigency table (def male (matrix (sel (get-dataset :hair-eye-color) :cols 3 :rows (range 16)) 4)) (chisq-test :table male) ;; X-sq = 41.280, df = 9, p-value = 4.44E-6 ;; turn the count data for females into a contigency table (def female (matrix (sel (get-dataset :hair-eye-color) :cols 3 :rows (range 16 32)) 4)) (chisq-test :table female) ;; X-sq = 106.664, df = 9, p-value = 7.014E-19, ;; supply probabilities to goodness-of-fit test (def table [89 37 30 28 2]) (def probs [0.40 0.20 0.20 0.19 0.01]) (chisq-test :table table :probs probs) ;; X-sq = 5.7947, df = 4, p-value = 0.215 ;; use frequencies instead of probabilities (def freq [40 20 20 15 5]) (chisq-test :table table :freq freq) ;; X-sq = 9.9901, df = 4, p-value = 0.04059 References: http://www.itl.nist.gov/div898/handbook/eda/section3/eda35f.htm http://en.wikipedia.org/wiki/Pearson's_chi-square_test http://en.wikipedia.org/wiki/Yates'_chi-square_test " ([& options] (let [opts (when options (apply assoc {} options)) correct (if (false? (:correct opts)) false true) x (:x opts) y (:y opts) table? (if (:table opts) true false) xtab (when (or x y) (if y (tabulate (bind-columns x y)) (tabulate x))) table (cond table? (:table opts) (and x y) (:table xtab)) two-samp? (if (or (and x y) (and table? (and (> (nrow table) 1) (> (ncol table) 1)))) true false) r-levels (if table? (range (nrow table)) (first (:levels xtab))) c-levels (if table? (range (ncol table)) (second (:levels xtab))) r-margins (if table? (if two-samp? (apply hash-map (interleave r-levels (map sum (trans table)))) (if (> (nrow table) 1) (to-list table) (throw (Exception. "One dimensional tables must have only a single column")))) (second (:margins xtab))) c-margins (if table? (if two-samp? (apply hash-map (interleave c-levels (map sum table))) 0) (first (:margins xtab))) counts (if two-samp? (vectorize table) table) N (if table? (sum counts) (:N xtab)) n (when (not two-samp?) (count r-levels)) df (if two-samp? (* (dec (nrow table)) (dec (ncol table))) (dec n)) probs (when (not two-samp?) (cond (:probs opts) (:probs opts) (:freq opts) (div (:freq opts) (sum (:freq opts))) :else (repeat n (/ n)))) E (if two-samp? (for [r r-levels c c-levels] (/ (* (c-margins c) (r-margins r)) N)) (mult N probs)) X-sq (if (and correct (and (= (count r-levels) 2) (= (count c-levels) 2))) (reduce + (map (fn [o e] (/ (pow (- (abs (- o e)) 0.5) 2) e)) counts E)) (reduce + (map (fn [o e] (/ (pow (- o e) 2) e)) counts E))) ] {:X-sq X-sq :df df :two-samp? two-samp? :p-value (cdf-chisq X-sq :df df :lower-tail false) :probs probs :N N :table table :col-levels c-levels :row-levels r-levels :col-margins c-margins :row-margins r-margins :E E}))) (defn principal-components " Performs a principal components analysis on the given data matrix. Equivalent to R's prcomp function. Returns: A map with the following fields: :std-dev -- the standard deviations of the principal compoenents (i.e. the square roots of the eigenvalues of the correlation matrix, though the calculation is actually done with the singular values of the data matrix. :rotation -- the matrix of variable loadings (i.e. a matrix whose columns contain the eigenvectors). Examples: (use '(incanter core stats charts datasets)) ;; load the iris dataset (def iris (to-matrix (get-dataset :iris))) ;; run the pca (def pca (principal-components (sel iris :cols (range 4)))) ;; extract the first two principal components (def pc1 (sel (:rotation pca) :cols 0)) (def pc2 (sel (:rotation pca) :cols 1)) ;; project the first four dimension of the iris data onto the first ;; two principal components (def x1 (mmult (sel iris :cols (range 4)) pc1)) (def x2 (mmult (sel iris :cols (range 4)) pc2)) ;; now plot the transformed data, coloring each species a different color (doto (scatter-plot (sel x1 :rows (range 50)) (sel x2 :rows (range 50)) :x-label \"PC1\" :y-label \"PC2\" :title \"Iris PCA\") (add-points (sel x1 :rows (range 50 100)) (sel x2 :rows (range 50 100))) (add-points (sel x1 :rows (range 100 150)) (sel x2 :rows (range 100 150))) view) ;; alternatively, the :group-by option can be used in scatter-plot (view (scatter-plot x1 x2 :group-by (sel iris :cols 4) :x-label \"PC1\" :y-label \"PC2\" :title \"Iris PCA\")) References: http://en.wikipedia.org/wiki/Principal_component_analysis " ([x & options] (let [svd (decomp-svd (correlation x)) rotation (:V svd) std-dev (sqrt (:S svd))] {:std-dev std-dev :rotation rotation}))) (defn detabulate " Take a contingency table of counts and returns a matrix of observations. Examples: (use '(incanter core stats datasets)) (def by-gender (group-by (get-dataset :hair-eye-color) 2)) (def table (matrix (sel (first by-gender) :cols 3) 4)) (detabulate :table table) (tabulate (detabulate :table table)) ;; example 2 (def data (matrix [[1 0] [1 1] [1 1] [1 0] [0 0] [1 1] [1 1] [1 0] [1 1]])) (tabulate data) (tabulate (detabulate :table (:table (tabulate data)))) " ([& options] (let [opts (when options (apply assoc {} options)) table (:table opts) row-labels (when table (or (:row-labels opts) (range (nrow table)))) col-labels (when table (or (:col-labels opts) (range (ncol table)))) data (apply bind-rows (apply concat (for [r row-labels c col-labels] (repeat (sel table :rows r :cols c) [r c]))))] data)))
78088
;;; stats.clj -- Statistics library for Clojure built on the CERN Colt Library ;; by <NAME> http://incanter.org ;; March 11, 2009 ;; Copyright (c) <NAME>, 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. ;; CHANGE LOG ;; March 11, 2009: First version (ns incanter.stats (:gen-class) (:import (cern.colt.list.tdouble DoubleArrayList) (cern.jet.random.tdouble Gamma Beta Binomial ChiSquare DoubleUniform Exponential NegativeBinomial Normal Poisson StudentT) (cern.jet.random.tdouble.engine DoubleMersenneTwister) (cern.jet.stat.tdouble DoubleDescriptive Probability)) (:use [incanter.core :only (abs plus minus div mult mmult to-list bind-columns gamma pow sqrt diag trans regularized-beta ncol nrow identity-matrix decomp-cholesky decomp-svd matrix length sum sum-of-squares sel matrix? cumulative-sum solve vectorize bind-rows)])) (defn indicator " Returns a sequence of ones and zeros, where ones are returned when the given predicate is true for corresponding element in the given collection, and zero otherwise. Examples: (use 'incanter.stats) (indicator #(neg? %) (sample-normal 10)) ;; return the sum of the positive values in a normal sample (def x (sample-normal 100)) (sum (mult x (indicator #(pos? %) x))) " ([pred coll] (for [el coll] (if (pred el) 1 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CONTINOUS DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; F DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-f " Returns the F pdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's df function. Options: :df1 (default 1) :df2 (default 1) See also: cdf-f and quantile-f References: http://en.wikipedia.org/wiki/F_distribution http://mathworld.wolfram.com/F-Distribution.html http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-f 1.0 :df1 5 :df2 2) " ([x & options] (let [opts (when options (apply assoc {} options)) df1 (or (:df1 opts) 0) df2 (or (:df2 opts) 1) pdf-fx (fn [x] (* (/ (gamma (/ (+ df1 df2) 2)) (* (gamma (/ df1 2)) (gamma (/ df2 2)))) (pow (/ df1 df2) (/ df1 2)) (pow x (- (/ df1 2) 1)) (pow (+ 1 (* (/ df1 df2) x)) (- 0 (/ (+ df1 df2) 2))))) ] (if (coll? x) (map pdf-fx x) (pdf-fx x))))) (defn cdf-f " Returns the F-distribution cdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pf function. Options: :df1 (default 1) :df2 (default 1) See also: pdf-f and quantile-f References: http://en.wikipedia.org/wiki/F_distribution http://mathworld.wolfram.com/F-Distribution.html http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-f 1.0 :df1 5 :df2 2) " ([x & options] (let [opts (when options (apply assoc {} options)) lower-tail? (if (false? (:lower-tail opts)) false true) df1 (or (:df1 opts) 1) df2 (or (:df2 opts) 1) cdf-fx (if lower-tail? (fn [x1] (regularized-beta (/ (* df1 x1) (+ df2 (* df1 x1))) (/ df1 2) (/ df2 2))) (fn [x1] (- 1 (regularized-beta (/ (* df1 x1) (+ df2 (* df1 x1))) (/ df1 2) (/ df2 2))))) ] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NORMAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-normal " Returns the Normal pdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dnorm function. Options: :mean (default 0) :sd (default 1) See also: cdf-normal, quantile-normal, sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-normal 1.96 :mean -2 :sd (sqrt 0.5)) " ([x & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) dist (Normal. mean sd (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-normal " Returns the Normal cdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pnorm function. Options: :mean (default 0) :sd (default 1) See also: pdf-normal, quantile-normal, sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-normal 1.96 :mean -2 :sd (sqrt 0.5)) " ([x & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) dist (Normal. mean sd (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn quantile-normal " Returns the inverse of the Normal CDF for the given probability. It will return a sequence of values, if given a sequence of probabilities. This is equivalent to R's qnorm function. Options: :mean (default 0) :sd (default 1) Returns: a value x, where (cdf-normal x) = probability See also: pdf-normal, cdf-normal, and sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/Probability.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Quantile Example: (quantile-normal 0.975) (quantile-normal [0.025 0.975] :mean -2 :sd (sqrt 0.5)) " ([probability & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) x (if (coll? probability) (map #(Probability/normalInverse %) probability) (Probability/normalInverse probability))] (plus mean (mult sd x))))) (defn sample-normal " Returns a sample of the given size from a Normal distribution This is equivalent to R's rnorm function. Options: :mean (default 0) :sd (default 1) See also: pdf-normal, cdf-normal, quantile-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution Example: (sample-normal 1000 :mean -2 :sd (sqrt 0.5)) " ([size & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1)] (if (= size 1) (Normal/staticNextDouble mean sd) (for [_ (range size)] (Normal/staticNextDouble mean sd)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; MULTIVARIATE NORMAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sample-mvn " Returns a sample of the given size from a Multivariate Normal distribution. This is equivalent to R's mvtnorm::rmvnorm function. Arguments: size -- the size of the sample to return Options: :mean (default (repeat (ncol sigma) 0)) :sigma (default (identity-matrix (count mean))) Examples: (use '(incanter core stats charts)) (def mvn-samp (sample-mvn 1000 :mean [7 5] :sigma (matrix [[2 1.5] [1.5 3]]))) (covariance mvn-samp) (def means (map mean (trans mvn-samp))) ;; plot scatter-plot of points (def mvn-plot (scatter-plot (sel mvn-samp :cols 0) (sel mvn-samp :cols 1))) (view mvn-plot) ;; add centroid to plot (add-points mvn-plot [(first means)] [(second means)]) ;; add regression line to scatter plot (def x (sel mvn-samp :cols 0)) (def y (sel mvn-samp :cols 1)) (def lm (linear-model y x)) (add-lines mvn-plot x (:fitted lm)) References: http://en.wikipedia.org/wiki/Multivariate_normal " ([size & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) (if (:sigma opts) (repeat (ncol (:sigma opts)) 0) [0])) sigma (or (:sigma opts) (identity-matrix (count mean))) p (count mean) chol (decomp-cholesky sigma) norm-samp (mmult (matrix (sample-normal (* size p)) p) chol) ] (if (> (nrow norm-samp) 1) (matrix (map #(plus % (trans mean)) norm-samp)) (matrix (plus norm-samp (trans mean))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UNIFORM DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-uniform " Returns the Uniform pdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dunif function. Options: :min (default 0) :max (default 1) See also: cdf-uniform and sample-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-uniform 5) (pdf-uniform 5 :min 1 :max 10) " ([x & options] (let [opts (when options (apply assoc {} options)) min (double (or (:min opts) 0.0)) max (double (or (:max opts) 1.0)) dist (DoubleUniform. min max (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-uniform " Returns the Uniform cdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's punif function. Options: :min (default 0) :max (default 1) See also: pdf-uniform and sample-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-uniform 5) (cdf-uniform 5 :min 1 :max 10) " ([x & options] (let [opts (when options (apply assoc {} options)) min (double (or (:min opts) 0.0)) max (double (or (:max opts) 1.0)) dist (DoubleUniform. min max (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn sample-uniform " Returns a sample of the given size from a Uniform distribution. This is equivalent to R's runif function. Options: :min (default 0) :max (default 1) :integers (default false) See also: pdf-uniform and cdf-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution Example: (sample-uniform 1000) (sample-uniform 1000 :min 1 :max 10) " ([size & options] (let [opts (when options (apply assoc {} options)) min-val (double (or (:min opts) 0.0)) max-val (double (or (:max opts) 1.0)) ints? (if (true? (:integers opts)) true false) dist (DoubleUniform. min-val max-val (DoubleMersenneTwister.))] (if (= size 1) (if ints? (DoubleUniform/staticNextIntFromTo min-val max-val) (DoubleUniform/staticNextDoubleFromTo min-val max-val)) (if ints? (for [_ (range size)] (DoubleUniform/staticNextIntFromTo min-val max-val)) (for [_ (range size)] (DoubleUniform/staticNextDoubleFromTo min-val max-val))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BETA DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-beta " Returns the Beta pdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dbeta function. Options: :alpha (default 1) :beta (default 1) See also: cdf-beta and sample-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-beta 0.5 :alpha 1 :beta 2) " ([x & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1) dist (Beta. alpha beta (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-beta " Returns the Beta cdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pbeta function. Options: :alpha (default 1) :beta (default 1) :lower-tail (default true) See also: pdf-beta and sample-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-beta 0.5 :alpha 1 :beta 2) (cdf-beta 0.5 :alpha 1 :beta 2 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/beta alpha beta x1)) (fn [x1] (- 1 (Probability/betaComplemented alpha beta x1))))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-beta " Returns a sample of the given size from a Beta distribution. This is equivalent to R's rbeta function. Options: :alpha (default 1) :beta (default 1) These default values produce a Uniform distribution. See also: pdf-beta and cdf-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution Example: (sample-beta 1000 :alpha 1 :beta 2) " ([size & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1)] (if (= size 1) (Beta/staticNextDouble alpha beta) (for [_ (range size)] (Beta/staticNextDouble alpha beta)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; GAMMA DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-gamma " Returns the Gamma pdf for the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dgamma function. Options: :shape (default 1) :rate (default 1) See also: cdf-gamma and sample-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-gamma 10 :shape 1 :rate 2) " ([x & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1) dist (Gamma. shape rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-gamma " Returns the Gamma cdf for the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pgamma function. Options: :shape (default 1) :rate (default 1) :lower-tail (default true) See also: pdf-gamma and sample-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-gamma 10 :shape 1 :rate 2) (cdf-gamma 3 :shape 1 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/gamma rate shape x1)) (fn [x1] (Probability/gammaComplemented rate shape x1)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-gamma " Returns a sample of the given size from a Gamma distribution. This is equivalent to R's rgamma function. Options: :shape (default 1) :rate (default 1) See also: pdf-gamma, cdf-gamma, and quantile-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution Example: (sample-gamma 1000 :shape 1 :rate 2) " ([size & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1)] (if (= size 1) (Gamma/staticNextDouble shape rate) (for [_ (range size)] (Gamma/staticNextDouble shape rate)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CHI SQUARE DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-chisq " Returns the Chi Square pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dchisq function. Options: :df (default 1) See also: cdf-chisq and sample-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-chisq 5.0 :df 2) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) dist (ChiSquare. df (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-chisq " Returns the Chi Square cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pchisq function. Options: :df (default 1) :lower-tail (default true) See also: pdf-chisq and sample-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-chisq 5.0 :df 2) (cdf-chisq 5.0 :df 2 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/chiSquare df x1)) (fn [x1] (Probability/chiSquareComplemented df x1)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-chisq " Returns a sample of the given size from a Chi Square distribution Same as R's rchisq function. Options: :df (default 1) See also: pdf-chisq and cdf-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution Example: (sample-chisq 1000 :df 2) " ([size & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1)] (if (= size 1) (ChiSquare/staticNextDouble df) (for [_ (range size)] (ChiSquare/staticNextDouble df)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; STUDENT'S T DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-t " Returns the Student's t pdf for the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dt function. Options: :df (default 1) See also: cdf-t, quantile-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-t 1.2 :df 10) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) dist (StudentT. df (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-t " Returns the Student's t cdf for the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pt function. Options: :df (default 1) See also: pdf-t, quantile-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-t 1.2 :df 10) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/studentT df x1)) (fn [x1] (- 1 (Probability/studentT df x1))))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn quantile-t " Returns the inverse of the Student's t CDF for the given probability (i.e. the quantile). It will return a sequence of values, if x is a sequence of probabilities. This is equivalent to R's qt function. Options: :df (default 1) Returns: a value x, where (cdf-t x) = probability See also: pdf-t, cdf-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/Probability.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Quantile Example: (quantile-t 0.975) (quantile-t [0.025 0.975] :df 25) (def df [1 2 3 4 5 6 7 8 9 10 20 50 100 1000]) (map #(quantile-t 0.025 :df %) df) " ([probability & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) to-alpha (fn [prob] ;; need to convert the probability to an alpha value (if (< prob 1/2) (* 2 prob) (* 2 (- 1 prob)))) sign-fx (fn [x1 prob] (if (< prob 1/2) (* -1 x1) x1)) x (if (coll? probability) (map #(sign-fx (Probability/studentTInverse (to-alpha %) df) %) probability) (sign-fx (Probability/studentTInverse (to-alpha probability) df) probability))] x))) (defn sample-t " Returns a sample of the given size from a Student's t distribution. Same as R's rt function. Options: :df (default 1) See also: pdf-t, cdf-t, and quantile-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution Example: (cdf-t 1000 :df 10) " ([size & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1)] (if (= size 1) (StudentT/staticNextDouble df) (for [_ (range size)] (StudentT/staticNextDouble df)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; EXPONENTIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-exp " Returns the Exponential pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dexp Options: :rate (default 1) See also: cdf-exp and sample-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-exp 2.0 :rate 1/2) " ([x & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1) dist (Exponential. rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-exp " Returns the Exponential cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pexp Options: :rate (default 1) See also: pdf-exp and sample-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-exp 2.0 :rate 1/2) " ([x & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1) dist (Exponential. rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn sample-exp " Returns a sample of the given size from a Exponential distribution. Same as R's rexp Options: :rate (default 1) See also: pdf-exp, and cdf-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution Example: (sample-exp 1000 :rate 1/2) " ([size & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1)] (if (= size 1) (Exponential/staticNextDouble rate) (for [_ (range size)] (Exponential/staticNextDouble rate)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; WISHART DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sample-wishart " Returns a p-by-p symmetric distribution drawn from a Wishart distribution Options: :p (default 2) -- number of dimensions of resulting matrix :df (default p) -- degree of freedoms (aka n), df <= p :scale (default (identity-matrix p)) -- positive definite matrix (aka V) Examples: (use 'incanter.stats) (sample-wishart :df 10 :p 4) ;; calculate the mean of 1000 wishart matrices, should equal (mult df scale) (div (reduce plus (for [_ (range 1000)] (sample-wishart :p 4))) 1000) References: http://en.wikipedia.org/wiki/Wishart_distribution# " ([& options] (let [opts (when options (apply assoc {} options)) scale (or (:scale opts) (when (:p opts) (identity-matrix (:p opts)))) p (count scale) df (or (:df opts) p) diagonal (for [i (range 1 (inc p))] (pow (sample-chisq 1 :df (inc (- df i))) 1/2)) mat (diag diagonal) indices (for [i (range p) j (range p) :when (< j i)] [i j]) _ (doseq [indx indices] (.set mat (first indx) (second indx) (sample-normal 1))) chol (decomp-cholesky scale) x (mmult chol mat (trans mat) (trans chol))] x))) (defn sample-inv-wishart " Returns a p-by-p symmetric distribution drawn from an inverse-Wishart distribution Options: :p (default 2) -- number of dimensions of resulting matrix :df (default p) -- degree of freedoms (aka n), df <= p :scale (default (identity-matrix p)) -- positive definite matrix (aka V) Examples: (use 'incanter.stats) (sample-inv-wishart :df 10 :p 4) ;; calculate the mean of 1000 wishart matrices, should equal (mult df scale) (div (reduce plus (for [_ (range 1000)] (sample-wishart :p 4))) 1000) References: http://en.wikipedia.org/wiki/Inverse-Wishart_distribution " ([& options] (let [opts (when options (apply assoc {} options)) scale (or (:scale opts) (when (:p opts) (identity-matrix (:p opts)))) p (count scale) df (or (:df opts) p)] (solve (sample-wishart :p p :df df :scale scale))))) (defn sample-dirichlet " Examples: (use '(incanter core stats charts)) ;; a total of 1447 adults were polled to indicate their preferences for ;; candidate 1 (y1=727), candidate 2 (y2=583), or some other candidate or no ;; preference (y3=137). ;; the counts y1, y2, and y3 are assumed to have a multinomial distribution ;; If a uniform prior distribution is assigned to the multinomial vector ;; theta = (th1, th2, th3), then the posterior distribution of theta is ;; proportional to g(theta) = th1^y1 * th2^y2 * th3^y3, which is a ;; dirichlet distribution with parameters (y1+1, y2+1, y3+1) (def theta (sample-dirichlet 1000 [(inc 727) (inc 583) (inc 137)])) ;; view means, 95% CI, and histograms of the proportion parameters (mean (sel theta :cols 0)) (quantile (sel theta :cols 0) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 0))) (mean (sel theta :cols 1)) (quantile (sel theta :cols 1) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 1))) (mean (sel theta :cols 2)) (quantile (sel theta :cols 2) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 2))) ;; view a histogram of the difference in proportions between the first ;; two candidates (view (histogram (minus (sel theta :cols 0) (sel theta :cols 1)))) " ([size alpha] (let [W (trans (for [a alpha] (sample-gamma size :shape a :rate 1))) T (map sum W)] (matrix (map #(div %1 %2) W T))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DISCRETE DISTRIBUTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BINOMIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-binomial " Returns the Bionomial pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dbinom Options: :size (default 1) :prob (default 1/2) See also: cdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-binomial 10 :prob 1/4 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2) dist (Binomial. n p (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-binomial " Returns the Bionomial cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pbinom Options: :size (default 1) :prob (default 1/2) :lower-tail (default true) See also: pdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-binomial 10 :prob 1/4 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/binomial x1 n p)) (fn [x1] (Probability/binomialComplemented x1 n p)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-binomial " Returns a sample of the given size from a Binomial distribution. Same as R's rbinom Options: :size (default 1) :prob (default 1/2) See also: cdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution Example: (sample-binomial 1000 :prob 1/4 :size 20) " ([size & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2)] (if (= size 1) (Binomial/staticNextInt n p) (for [_ (range size)] (Binomial/staticNextInt n p)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; POISSON DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-poisson " Returns the Poisson pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dpois Options: :lambda (default 1) See also: cdf-poisson and sample-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-poisson 5 :lambda 10) " ([x & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1) dist (Poisson. lambda (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-poisson " Returns the Poisson cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's ppois Options: :lambda (default 1) :lower-tail (default true) See also: cdf-poisson and sample-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-poisson 5 :lambda 10) " ([x & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/poisson x1 lambda)) (fn [x1] (Probability/poissonComplemented x1 lambda)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-poisson " Returns a sample of the given size from a Poisson distribution. Same as R's rpois Options: :lambda (default 1) See also: pdf-poisson and cdf-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution Example: (sample-poisson 1000 :lambda 10) " ([size & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1)] (if (= size 1) (Poisson/staticNextInt lambda) (for [_ (range size)] (Poisson/staticNextInt lambda)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NEGATIVE BINOMIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-neg-binomial " Returns the Negative Binomial pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dnbinom Options: :size (default 10) :prob (default 1/2) See also: cdf-neg-binomial and sample-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-neg-binomial 10 :prob 1/2 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2) dist (NegativeBinomial. size prob (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-neg-binomial " Returns the Negative Binomial cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dnbinom Options: :size (default 10) :prob (default 1/2) See also: cdf-neg-binomial and sample-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-neg-binomial 10 :prob 1/2 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/negativeBinomial x1 size prob)) (fn [x1] (Probability/negativeBinomialComplemented x1 size prob)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-neg-binomial " Returns a sample of the given size from a Negative Binomial distribution. Same as R's rnbinom Options: :size (default 10) :prob (default 1/2) See also: pdf-neg-binomial and cdf-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution Example: (sample-neg-binomial 1000 :prob 1/2 :size 20) " ([size & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2)] (if (= size 1) (NegativeBinomial/staticNextInt size prob) (for [_ (range size)] (NegativeBinomial/staticNextInt size prob)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; EMPIRICAL DISTRIBUTION ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn cdf-empirical " Returns a step-function representing the empirical cdf of the given data. Equivalent to R's ecdf function. The following description is from the ecdf help in R: The e.c.d.f. (empirical cumulative distribution function) Fn is a step function with jumps i/n at observation values, where i is the number of tied observations at that value. Missing values are ignored. For observations 'x'= (x1,x2, ... xn), Fn is the fraction of observations less or equal to t, i.e., Fn(t) = #{x_i <= t} / n = 1/n sum(i=1,n) Indicator(xi <= t). Examples: (use '(incanter core stats charts)) (def exam1 [192 160 183 136 162 165 181 188 150 163 192 164 184 189 183 181 188 191 190 184 171 177 125 192 149 188 154 151 159 141 171 153 169 168 168 157 160 190 166 150]) ;; the ecdf function returns an empirical cdf function for the given data (def ecdf (cdf-empirical exam1)) ;; plot the data's empircal cdf (view (scatter-plot exam1 (map ecdf exam1))) " ([x] (fn [t] (div (sum (indicator #(<= % t) x)) (count x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; STATISTICAL FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mean " Returns the mean of the data, x. Examples: (mean (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Mean " ([x] (let [xx (to-list x)] (DoubleDescriptive/mean (DoubleArrayList. (double-array xx)))))) (defn variance " Returns the sample variance of the data, x. Equivalent to R's var function. Examples: (variance (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Sample_variance#Population_variance_and_sample_variance " ([x] (DoubleDescriptive/sampleVariance (length x) (sum x) (sum-of-squares x)))) (defn covariance " Returns the sample covariance of x and y. Examples: ;; create some data that covaries (def x (sample-normal 100)) (def err (sample-normal 100)) (def y (plus (mult 5 x) err)) ;; estimate the covariance of x and y (covariance x y) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Covariance " ([x y] (let [ xx (to-list x) yy (to-list y) ] (DoubleDescriptive/covariance (DoubleArrayList. (double-array xx)) (DoubleArrayList. (double-array yy))))) ([mat] (let [n (ncol mat)] (matrix (for [i (range n) j (range n)] (covariance (sel mat true i) (sel mat true j))) n)))) (defn sd " Returns the sample standard deviation of the data, x. Equivalent to R's sd function. Examples: (sd (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Standard_deviation " ([x] ;; population sd, not the sample sd ;(DoubleDescriptive/sampleStandardDeviation (length x) (variance x)))) ;; return the sample standard deviation (sqrt (variance x)))) (defn correlation " Returns the sample correlation of x and y, or the correlation matrix of the given matrix. Examples: References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Correlation " ([x y] (let [ xx (to-list x) yy (to-list y) ] (DoubleDescriptive/correlation (DoubleArrayList. (double-array xx)) (sd x) (DoubleArrayList. (double-array yy)) (sd y)))) ([mat] (div (covariance mat) (sqrt (mmult (diag (covariance mat)) (trans (diag (covariance mat)))))))) (defn median " Returns the median of the data, x. Examples: (median (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Median " ([x] (let [xx (sort (to-list x))] (DoubleDescriptive/median (DoubleArrayList. (double-array xx)))))) (defn kurtosis " Returns the kurtosis of the data, x. \"Kurtosis is a measure of the \"peakedness\" of the probability distribution of a real-valued random variable. Higher kurtosis means more of the variance is due to infrequent extreme deviations, as opposed to frequent modestly-sized deviations.\" (Wikipedia) Examples: (kurtosis (sample-normal 100000)) ;; approximately 0 (kurtosis (sample-gamma 100000)) ;; approximately 6 References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Kurtosis " ([x] (DoubleDescriptive/kurtosis (DoubleArrayList. (double-array x)) (mean x) (variance x)))) (defn skewness " Returns the skewness of the data, x. \"Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable.\" (Wikipedia) Examples: (skewness (sample-normal 100000)) ;; approximately 0 (skewness (sample-gamma 100000)) ;; approximately 2 References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Skewness " ([x] (DoubleDescriptive/skew (DoubleArrayList. (double-array x)) (mean x) (sd x)))) (defn quantile " Returns the quantiles of the data, x. By default it returns the min, 25th-percentile, 50th-percentile, 75th-percentile, and max value. Options: :probs (default [0.0 0.25 0.5 0.75 1.0]) Examples: (quantile (sample-normal 100)) (quantile (sample-normal 100) :probs [0.025 0.975]) (quantile (sample-normal 100) :probs 0.975) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Quantile " ([x & options] (let [opts (when options (apply assoc {} options)) _x (if (matrix? x) (to-list x) x) data (DoubleArrayList. (double-array (sort _x))) probs (cond (number? (:probs opts)) (:probs opts) (coll? (:probs opts)) (DoubleArrayList. (double-array (:probs opts))) :default (DoubleArrayList. (double-array [0.0 0.25 0.5 0.75 1.0])))] (if (number? probs) (DoubleDescriptive/quantile data probs) (seq (.elements (DoubleDescriptive/quantiles data probs))))))) (defn sample " Returns a sample of the given size from the given collection. If replacement is set to false it returns a set, otherwise it returns a list. Arguments: x -- collection to be sampled from Options: :size -- (default (count x) sample size :replacement (default true) -- sample with replacement Examples: (sample (range 10)) ; permutation of numbers zero through ten (sample [:red :green :blue] :size 10) ; choose 10 items that are either :red, :green, or :blue. (sample (seq \"abcdefghijklmnopqrstuvwxyz\") :size 4 :replacement false) ; choose 4 random letters. " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) (count x)) replacement? (if (false? (:replacement opts)) false true) max-idx (dec (count x))] (if (= size 1) (nth x (rand-int (inc max-idx))) (if replacement? (map #(nth x %) (sample-uniform size :min 0 :max max-idx :integers true)) (if (> size (count x)) (throw (Exception. "'size' can't be larger than (count x) without replacement!")) (map #(nth x %) (loop [samp-indices [] indices-set #{}] (if (= (count samp-indices) size) samp-indices (let [i (sample-uniform 1 :min 0 :max max-idx :integers true)] (if (contains? indices-set i) (recur samp-indices indices-set) (recur (conj samp-indices i) (conj indices-set i))))))))))))) (defn bootstrap " Returns a bootstrap sample of the given statistic on the given data. Arguments: data -- vector of data to resample from statistic -- a function that returns a value given a vector of data Options: :size -- the number of bootstrap samples to return :smooth -- (default false) smoothing option :smooth-sd -- (default (/ (sqrt (count data)))) determines the standard deviation of the noise to use for smoothing :replacement -- (default true) determines if sampling of the data should be done with replacement References: 1. <NAME>. Lunn<NAME>, Data Analysis by Resampling Concepts and Applications, 2000, pages 105-117 2. http://en.wikipedia.org/wiki/Bootstrapping_(statistics) Examples: ;; example from Data Analysis by Resampling Concepts and Applications ;; <NAME> (pages 119-122) (use '(incanter core stats charts)) ;; weights (in grams) of 50 randomly sampled bags of preztels (def weights [464 447 446 454 450 457 450 442 433 452 449 454 450 438 448 449 457 451 456 452 450 463 464 453 452 447 439 449 468 443 433 460 452 447 447 446 450 459 466 433 445 453 454 446 464 450 456 456 447 469]) ;; calculate the sample median, 450 (median weights) ;; generate bootstrap sample (def t* (bootstrap weights median :size 2000)) ;; view histogram of bootstrap histogram (view (histogram t*)) ;; calculate the mean of the bootstrap median ~ 450.644 (mean t*) ;; calculate the standard error ~ 1.083 (def se (sd t*)) ;; 90% standard normal CI ~ (448.219 451.781) (plus (median weights) (mult (quantile-normal [0.05 0.95]) se)) ;; 90% symmetric percentile CI ~ (449.0 452.5) (quantile t* :probs [0.05 0.95]) ;; 90% non-symmetric percentile CI ~ (447.5 451.0) (minus (* 2 (median weights)) (quantile t* :probs [0.95 0.05])) ;; calculate bias (- (mean t*) (median weights)) ;; ~ 0.644 ;; example with smoothing ;; Newcomb's speed of light data (use '(incanter core stats charts)) ;; A numeric vector giving the Third Series of measurements of the ;; passage time of light recorded by Newcomb in 1882. The given ;; values divided by 1000 plus 24 give the time in millionths of a ;; second for light to traverse a known distance. The 'true' value is ;; now considered to be 33.02. (def speed-of-light [28 -44 29 30 24 28 37 32 36 27 26 28 29 26 27 22 23 20 25 25 36 23 31 32 24 27 33 16 24 29 36 21 28 26 27 27 32 25 28 24 40 21 31 32 28 26 30 27 26 24 32 29 34 -2 25 19 36 29 30 22 28 33 39 25 16 23]) ;; view histogram of data to see outlier observations (view (histogram speed-of-light :nbins 30)) (def samp (bootstrap speed-of-light median :size 10000)) (view (histogram samp :density true :nbins 30)) (mean samp) (quantile samp :probs [0.025 0.975]) (def smooth-samp (bootstrap speed-of-light median :size 10000 :smooth true)) (view (histogram smooth-samp :density true :nbins 30)) (mean smooth-samp) (quantile smooth-samp :probs [0.025 0.975]) " ([data statistic & options] (let [opts (when options (apply assoc {} options)) size (:size opts) replacement (if (false? (:replacement opts)) false true) n (or (:n opts) (count data)) smooth? (true? (:smooth opts)) smooth-sd (or (:smooth-sd opts) (/ (sqrt n))) B1 100 B2 25 max-iter 10 D 0.01 samp (if (nil? size) (loop [stats (for [_ (range B1)] (statistic (sample data :size n :replacement replacement))) k 0] (let [stats2 (concat stats (for [_ (range B2)] (statistic (sample data :size n :replacement replacement)))) se1 (sd stats) se2 (sd stats2)] (if (or (= k max-iter) (< (* (- 1 D) se1) se2 (* (+ 1 D) se1))) stats2 (recur stats2 (inc k))))) (for [_ (range size)] (statistic (sample data :size n :replacement replacement)))) samp-size (count samp)] (if smooth? (plus samp (sample-normal samp-size :sd smooth-sd)) samp)))) (defn cumulative-mean " Returns a sequence of cumulative means for the given collection. For instance The first value equals the first value of the argument, the second value is the mean of the first two arguments, the third is the mean of the first three arguments, etc. Examples: (cumulative-mean (sample-normal 100)) " ([coll] (map / (cumulative-sum coll) (range 1 (inc (count coll)))))) (defn sweep " Return an array obtained from an input array by sweeping out a summary statistic. Based to R's sweep function. Arguments: x is an sequence Options: :stat (default mean) the statistic to sweep out :fun (defaul minus) the function used to sweep the stat out Example: (use '(incanter core stats)) (def x (sample-normal 30 :mean 10 :sd 5)) (sweep x) ;; center the data around mean (sweep x :stat sd :fun div) ;; divide data by its sd " ([x & options] (let [opts (when options (apply assoc {} options)) stat-fn (or (:stat opts) mean) fun (or (:fun opts) minus) stat (stat-fn x)] (fun x stat)))) (defn permute " If provided a single argument, returns a permuted version of the given collection. (perm x) is the same as (sample x). If provided two arguments, returns two lists that are permutations across the given collections. In other words, each of the new collections will contain elements from both of the given collections. Useful for permutation tests or randomization tests. Examples: (permute (range 10)) (permute (range 10) (range 10 20)) " ([x] (sample x)) ([x y] (let [n1 (count x) samp (sample (concat x y) :replacement false) new-x (take n1 samp) new-y (drop n1 samp)] (list new-x new-y)))) (defn sample-permutations " If provided a two arguments (n x), it returns a list of n permutations of x. If provided three (n x y) arguments, returns a list with two with n permutations of each arguments, where each permutation is drawn from the pooled arguments. Arguments: n -- number of randomized versions of the original two groups to return x -- group 1 y -- (default nil) group 2 Examples: (use '(incanter core stats)) (sample-permutations 10 (range 10)) (sample-permutations 10 (range 10) (range 10 20)) ;; extended example with plant-growth data (use '(incanter core stats datasets charts)) ;; load the plant-growth dataset (def data (to-matrix (get-dataset :plant-growth))) ;; break the first column of the data into groups based on treatment (second column). (def groups (group-by data 1 :cols 0)) ;; define a function for the statistic of interest (defn means-diff [x y] (minus (mean x) (mean y))) ;; calculate the difference in sample means between the two groups (def samp-mean-diff (means-diff (first groups) (second groups))) ;; 0.371 ;; create 500 permuted versions of the original two groups (def permuted-groups (sample-permutations 1000 (first groups) (second groups))) ;; calculate the difference of means of the 500 samples (def permuted-means-diffs1 (map means-diff (first permuted-groups) (second permuted-groups))) ;; use an indicator function that returns 1 when the randomized means diff is greater ;; than the original sample mean, and zero otherwise. Then take the mean of this sequence ;; of ones and zeros. That is the proportion of times you would see a value more extreme ;; than the sample mean (i.e. the p-value). (mean (indicator #(> % samp-mean-diff) permuted-means-diffs1)) ;; 0.088 ;; calculate the 95% confidence interval of the null hypothesis. If the ;; sample difference in means is outside of this range, that is evidence ;; that the two means are statistically significantly different. (quantile permuted-means-diffs1 :probs [0.025 0.975]) ;; (-0.606 0.595) ;; Plot a histogram of the permuted-means-diffs using the density option, ;; instead of the default frequency, and then add a normal pdf curve with ;; the mean and sd of permuted-means-diffs data for a visual comparison. (doto (histogram permuted-means-diffs1 :density true) (add-lines (range -1 1 0.01) (pdf-normal (range -1 1 0.01) :mean (mean permuted-means-diffs1) :sd (sd permuted-means-diffs1))) view) ;; compare the means of treatment 2 and control (def permuted-groups (sample-permutations 1000 (first groups) (last groups))) (def permuted-means-diffs2 (map means-diff (first permuted-groups) (second permuted-groups))) (def samp-mean-diff (means-diff (first groups) (last groups))) ;; -0.4939 (mean (indicator #(< % samp-mean-diff) permuted-means-diffs2)) ;; 0.022 (quantile permuted-means-diffs2 :probs [0.025 0.975]) ;; (-0.478 0.466) ;; compare the means of treatment 1 and treatment 2 (def permuted-groups (sample-permutations 1000 (second groups) (last groups))) (def permuted-means-diffs3 (map means-diff (first permuted-groups) (second permuted-groups))) (def samp-mean-diff (means-diff (second groups) (last groups))) ;; -0.865 (mean (indicator #(< % samp-mean-diff) permuted-means-diffs3)) ;; 0.002 (quantile permuted-means-diffs3 :probs [0.025 0.975]) ;; (-0.676 0.646) (doto (box-plot permuted-means-diffs1) (add-box-plot permuted-means-diffs2) (add-box-plot permuted-means-diffs3) view) Further Reading: http://en.wikipedia.org/wiki/Resampling_(statistics) " ([n x] (loop [samp '() i 0] (if (= i n) samp (recur (conj samp (sample x)) (inc i))))) ([n x y] (let [pool (concat x y) m1 (count x)] (loop [samp-x '() samp-y '() i 0] (if (= i n) (list samp-x samp-y) (let [perm-samp (sample pool) new-x (take m1 perm-samp) new-y (drop m1 perm-samp)] (recur (conj samp-x new-x) (conj samp-y new-y) (inc i)))))))) ;;;;;;;;;;;;;;; OLS REGRESSION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;; (defn linear-model " Returns the results of performing a OLS linear regression of y on x. Arguments: y is a vector (or sequence) of values for the dependent variable x is a vector or matrix of values for the independent variables Options: :intercept (default true) indicates weather an intercept term should be included Returns: a map, of type ::linear-model, containing: :design-matrix -- a matrix containing the independent variables, and an intercept columns :coefs -- the regression coefficients :t-tests -- t-test values of coefficients :t-probs -- p-values for t-test values of coefficients :coefs-ci -- 95% percentile confidence interval :fitted -- the predicted values of y :residuals -- the residuals of each observation :std-errors -- the standard errors of the coeffients :sse -- the sum of squared errors, also called the residual sum of squares :ssr -- the regression sum of squares, also called the explained sum of squares :sst -- the total sum of squares (proportional to the sample variance) :r-square -- coefficient of determination Examples: (use '(incanter core stats datasets charts)) (def iris (to-matrix (get-dataset :iris) :dummies true)) (def y (sel iris :cols 0)) (def x (sel iris :cols (range 1 6))) (def iris-lm (linear-model y x)) ; with intercept term (keys iris-lm) ; see what fields are included (:coefs iris-lm) (:sse iris-lm) (quantile (:residuals iris-lm)) (:r-square iris-lm) (:adj-r-square iris-lm) (:f-stat iris-lm) (:f-prob iris-lm) (:df iris-lm) (def x1 (range 0.0 3 0.1)) (view (xy-plot x1 (cdf-f x1 :df1 4 :df2 144))) References: http://en.wikipedia.org/wiki/OLS_Regression http://en.wikipedia.org/wiki/Coefficient_of_determination " ([y x & options] (let [opts (when options (apply assoc {} options)) intercept? (if (false? (:intercept opts)) false true) _x (if intercept? (bind-columns (replicate (nrow x) 1) x) x) xtx (mmult (trans _x) _x) xtxi (if (number? xtx) (/ 1 xtx) (solve xtx)) xty (mmult (trans _x) y) coefs (if (and (number? xtxi) (number? xty)) (* xtxi xty) (to-list (if (or (number? xtxi) (number? xty)) (mult xtxi xty) (mmult xtxi xty)))) fitted (to-list (if (number? coefs) (mult _x coefs) (mmult _x coefs))) resid (to-list (minus y fitted)) sse (sum-of-squares resid) ssr (sum-of-squares (minus fitted (mean fitted))) sst (+ sse ssr) r-square (/ ssr sst) n (nrow y) p (ncol _x) p-1 (if intercept? (- p 1) p) adj-r-square (- 1 (* (- 1 r-square) (/ (- n 1) (- n p 1)))) mse (/ sse (- n p)) msr (/ ssr p-1) f-stat (/ msr mse) df1 p-1 df2 (- n p) f-prob (cdf-f f-stat :df1 df1 :df2 df2 :lower-tail false) coef-var (mult mse xtxi) std-errors (sqrt (diag coef-var)) t-tests (div coefs std-errors) t-probs (mult 2 (cdf-t (abs t-tests) :df df2 :lower-tail false)) t-95 (mult (quantile-t 0.975 :df df2) std-errors) coefs-ci (if (number? std-errors) [(plus coefs t-95) (minus coefs t-95)] (partition 2 (interleave (minus coefs t-95) (plus coefs t-95)))) ] (with-meta {:x _x :y y :fitted fitted :design-matrix _x :coefs coefs :t-tests t-tests :t-probs t-probs :coefs-ci coefs-ci :residuals resid :std-errors std-errors :sse sse :ssr ssr :sst sst :mse mse :msr msr :f-stat f-stat :f-prob f-prob :df [df1 df2] :coef-var coef-var :r-square r-square :adj-r-square adj-r-square } {:type ::linear-model})))) (defn t-test " Argument: x : sample to test Options: :y (default nil) :mu (default (mean y) or 0) population mean :alternative (default :two-sided) other choices :less :greater :var-equal TODO (default false) variance equal :paired TODO (default false) paired test :conf-level (default 0.95) for returned confidence interval Examples: (t-test (range 1 11) :mu 0) (t-test (range 1 11) :mu 0 :alternative :less) (t-test (range 1 11) :mu 0 :alternative :greater) (t-test (range 1 11) :y (range 7 21)) (t-test (range 1 11) :y (range 7 21) :alternative :less) (t-test (range 1 11) :y (range 7 21) :alternative :greater) (t-test (range 1 11) :y (conj (range 7 21) 200)) References: http://en.wikipedia.org/wiki/T_test http://www.socialresearchmethods.net/kb/stat_t.php " ([x & options] (let [opts (when options (apply assoc {} options)) y (or (:y opts) nil) one-sample? (nil? y) mu (or (:mu opts) (if y (mean y) 0)) paired? (if (true? (:paired opts)) true false) var-equal? (if (true? (:var-equal opts)) true false) conf-level (or (:conf-level opts) 0.95) alternative (or (:alternative opts) :two-sided) x-mean (mean x) x-var (variance x) n1 (count x) y-mean (if one-sample? nil (mean y)) y-var (if one-sample? nil (variance y)) n2 (if one-sample? nil (count y)) t-stat (if one-sample? (/ (- x-mean mu) (/ (sqrt x-var) (sqrt n1))) ;; calculate Welch's t test (/ (- x-mean y-mean) (sqrt (+ (/ x-var n1) (/ y-var n2))))) df (if one-sample? (dec n1) ;; calculate Welch-Satterthwaite equation (/ (pow (+ (/ x-var n1) (/ y-var n2)) 2) (+ (/ (pow (/ x-var n1) 2) (dec n1)) (/ (pow (/ y-var n2) 2) (dec n2))))) lower-tail? (cond (= alternative :two-sided) (if (neg? t-stat) true false) (= alternative :lower) (if (neg? t-stat) false true) (= alternative :greater) (if one-sample? (if (neg? t-stat) true false) (if (neg? t-stat) false true))) one-sided-p (cdf-t t-stat :df df :lower-tail lower-tail?) qt (if (= alternative :two-sided) (quantile-t (/ (- 1 conf-level) 2) :df df) (quantile-t (- 1 conf-level) :df df))] {:t-stat t-stat :df df :x-mean x-mean :x-var x-var :n1 n1 :y-mean y-mean :y-var y-var :n2 n2 :p-value (if (= alternative :two-sided) (* 2 one-sided-p) one-sided-p) :conf-int (if one-sample? ;; one-sample confidence interval [(if (= alternative :less) Double/NEGATIVE_INFINITY (+ x-mean (/ (* qt (sqrt x-var)) (sqrt n1)))) (if (= alternative :greater) Double/POSITIVE_INFINITY (- x-mean (/ (* qt (sqrt x-var)) (sqrt n1))))] ;; two-sample confidence interval [(if (= alternative :less) Double/NEGATIVE_INFINITY (+ (- x-mean y-mean) (* qt (sqrt (+ (/ x-var n1) (/ y-var n2)))))) (if (= alternative :greater) Double/POSITIVE_INFINITY (- (- x-mean y-mean) (* qt (sqrt (+ (/ x-var n1) (/ y-var n2))))))]) }))) (defn tabulate " Cross-tabulates the values of the given numeric matrix. Returns a hash-map with the following fields: :table -- the table of counts for each combination of values, this table is only returned if x has two-columns :levels -- a sequence of sequences, where each sequence list the levels (possible values) of the corresponding column of x. :margins -- a sequence of sequences, where each sequence represents the marginal total for each level of the corresponding column of x. :counts -- a hash-map, where vectors of unique combinations of the cross-tabulated levels are the keys and the values are the total count of each combination. :N -- the grand-total for the contingency table Examples: (use '(incanter core stats)) (tabulate [1 2 3 2 3 2 4 3 5]) (tabulate (sample-poisson 100 :lambda 5)) (use '(incanter core stats datasets)) (def math-prog (to-matrix (get-dataset :math-prog))) (tabulate (sel math-prog :cols [1 2])) (def data (matrix [[1 0 1] [1 1 1] [1 1 1] [1 0 1] [0 0 0] [1 1 1] [1 1 1] [1 0 1] [1 1 0]])) (tabulate data) (def data (matrix [[1 0] [1 1] [1 1] [1 0] [0 0] [1 1] [1 1] [1 0] [1 1]])) (tabulate data) " ([x & options] (let [opts (when options (apply assoc {} options)) _x (if (matrix? x) x (matrix x)) p (ncol _x) n (nrow _x) levels (for [i (range p)] (sort (seq (into #{} (sel _x :cols i))))) margins (for [j (range p)] (loop [marg {} i (int 0)] (if (= i n) marg (let [lvl (sel _x :rows i :cols j)] (recur (let [cnt (get marg lvl)] (if cnt (assoc marg lvl (inc cnt)) (assoc marg lvl 1))) (inc i)))))) counts (loop [tab {} i (int 0)] (if (= i n) tab (recur (let [row (if (> p 1) (to-list (nth _x i)) (nth _x i)) cnt (get tab row)] (if (nil? cnt) (assoc tab row 1) (assoc tab row (inc cnt)))) (inc i)))) n-levels (map #(count (keys %)) margins)] {:counts counts :margins margins :table (when (= p 2) (matrix (for [r (first levels) c (second levels)] (let [c (get counts (to-list (trans [r c])))] (if c c 0))) (second n-levels))) :n-vars p :N (reduce + (vals (first margins))) :n-levels n-levels :levels levels}))) (defn chisq-test " Performs chi-squared contingency table tests and goodness-of-fit tests. If the optional argument :y is not provided then a goodness-of-fit test is performed. In this case, the hypothesis tested is whether the population probabilities equal those in :probs, or are all equal if :probs is not given. If :y is provided, it must be a sequence of integers that is the same length as x. A contingency table is computed from x and :y. Then, Pearson's chi-squared test of the null hypothesis that the joint distribution of the cell counts in a 2-dimensional contingency table is the product of the row and column marginals is performed. By default the Yates' continuity correction for 2x2 contingency tables is performed, this can be disabled by setting the :correct option to false. Options: :x -- a sequence of numbers. :y -- a sequence of numbers :table -- a contigency table. If one dimensional, the test is a goodness-of-fit :probs (when (nil? y) -- (repeat n-levels (/ n-levels))) :freq (default nil) -- if given, these are rescaled to probabilities :correct (default true) -- use Yates' correction for continuity for 2x2 contingency tables Returns: :X-sq -- the Pearson X-squared test statistics :p-value -- the p-value for the test statistic :df -- the degress of freedom Examples: (use '(incanter core stats)) (chisq-test :x [1 2 3 2 3 2 4 3 5]) ;; X-sq 2.6667 ;; create a one-dimensional table of this data (def table (matrix [1 3 3 1 1])) (chisq-test :table table) ;; X-sq 2.6667 (chisq-test :table (trans table)) ;; throws exception (chisq-test :x [1 0 0 0 1 1 1 0 0 1 0 0 1 1 1 1]) ;; 0.25 (use '(incanter core stats datasets)) (def math-prog (to-matrix (get-dataset :math-prog))) (def x (sel math-prog :cols 1)) (def y (sel math-prog :cols 2)) (chisq-test :x x :y y) ;; X-sq = 1.24145, df=1, p-value = 0.26519 (chisq-test :x x :y y :correct false) ;; X-sq = 2.01094, df=1, p-value = 0.15617 (def table (matrix [[31 12] [9 8]])) (chisq-test :table table) ;; X-sq = 1.24145, df=1, p-value = 0.26519 (chisq-test :table table :correct false) ;; X-sq = 2.01094, df=1, p-value = 0.15617 ;; use the detabulate function to create data rows corresponding to the table (def detab (detabulate :table table)) (chisq-test :x (sel detab :cols 0) :y (sel detab :cols 1)) ;; look at the hair-eye-color data ;; turn the count data for males into a contigency table (def male (matrix (sel (get-dataset :hair-eye-color) :cols 3 :rows (range 16)) 4)) (chisq-test :table male) ;; X-sq = 41.280, df = 9, p-value = 4.44E-6 ;; turn the count data for females into a contigency table (def female (matrix (sel (get-dataset :hair-eye-color) :cols 3 :rows (range 16 32)) 4)) (chisq-test :table female) ;; X-sq = 106.664, df = 9, p-value = 7.014E-19, ;; supply probabilities to goodness-of-fit test (def table [89 37 30 28 2]) (def probs [0.40 0.20 0.20 0.19 0.01]) (chisq-test :table table :probs probs) ;; X-sq = 5.7947, df = 4, p-value = 0.215 ;; use frequencies instead of probabilities (def freq [40 20 20 15 5]) (chisq-test :table table :freq freq) ;; X-sq = 9.9901, df = 4, p-value = 0.04059 References: http://www.itl.nist.gov/div898/handbook/eda/section3/eda35f.htm http://en.wikipedia.org/wiki/Pearson's_chi-square_test http://en.wikipedia.org/wiki/Yates'_chi-square_test " ([& options] (let [opts (when options (apply assoc {} options)) correct (if (false? (:correct opts)) false true) x (:x opts) y (:y opts) table? (if (:table opts) true false) xtab (when (or x y) (if y (tabulate (bind-columns x y)) (tabulate x))) table (cond table? (:table opts) (and x y) (:table xtab)) two-samp? (if (or (and x y) (and table? (and (> (nrow table) 1) (> (ncol table) 1)))) true false) r-levels (if table? (range (nrow table)) (first (:levels xtab))) c-levels (if table? (range (ncol table)) (second (:levels xtab))) r-margins (if table? (if two-samp? (apply hash-map (interleave r-levels (map sum (trans table)))) (if (> (nrow table) 1) (to-list table) (throw (Exception. "One dimensional tables must have only a single column")))) (second (:margins xtab))) c-margins (if table? (if two-samp? (apply hash-map (interleave c-levels (map sum table))) 0) (first (:margins xtab))) counts (if two-samp? (vectorize table) table) N (if table? (sum counts) (:N xtab)) n (when (not two-samp?) (count r-levels)) df (if two-samp? (* (dec (nrow table)) (dec (ncol table))) (dec n)) probs (when (not two-samp?) (cond (:probs opts) (:probs opts) (:freq opts) (div (:freq opts) (sum (:freq opts))) :else (repeat n (/ n)))) E (if two-samp? (for [r r-levels c c-levels] (/ (* (c-margins c) (r-margins r)) N)) (mult N probs)) X-sq (if (and correct (and (= (count r-levels) 2) (= (count c-levels) 2))) (reduce + (map (fn [o e] (/ (pow (- (abs (- o e)) 0.5) 2) e)) counts E)) (reduce + (map (fn [o e] (/ (pow (- o e) 2) e)) counts E))) ] {:X-sq X-sq :df df :two-samp? two-samp? :p-value (cdf-chisq X-sq :df df :lower-tail false) :probs probs :N N :table table :col-levels c-levels :row-levels r-levels :col-margins c-margins :row-margins r-margins :E E}))) (defn principal-components " Performs a principal components analysis on the given data matrix. Equivalent to R's prcomp function. Returns: A map with the following fields: :std-dev -- the standard deviations of the principal compoenents (i.e. the square roots of the eigenvalues of the correlation matrix, though the calculation is actually done with the singular values of the data matrix. :rotation -- the matrix of variable loadings (i.e. a matrix whose columns contain the eigenvectors). Examples: (use '(incanter core stats charts datasets)) ;; load the iris dataset (def iris (to-matrix (get-dataset :iris))) ;; run the pca (def pca (principal-components (sel iris :cols (range 4)))) ;; extract the first two principal components (def pc1 (sel (:rotation pca) :cols 0)) (def pc2 (sel (:rotation pca) :cols 1)) ;; project the first four dimension of the iris data onto the first ;; two principal components (def x1 (mmult (sel iris :cols (range 4)) pc1)) (def x2 (mmult (sel iris :cols (range 4)) pc2)) ;; now plot the transformed data, coloring each species a different color (doto (scatter-plot (sel x1 :rows (range 50)) (sel x2 :rows (range 50)) :x-label \"PC1\" :y-label \"PC2\" :title \"Iris PCA\") (add-points (sel x1 :rows (range 50 100)) (sel x2 :rows (range 50 100))) (add-points (sel x1 :rows (range 100 150)) (sel x2 :rows (range 100 150))) view) ;; alternatively, the :group-by option can be used in scatter-plot (view (scatter-plot x1 x2 :group-by (sel iris :cols 4) :x-label \"PC1\" :y-label \"PC2\" :title \"Iris PCA\")) References: http://en.wikipedia.org/wiki/Principal_component_analysis " ([x & options] (let [svd (decomp-svd (correlation x)) rotation (:V svd) std-dev (sqrt (:S svd))] {:std-dev std-dev :rotation rotation}))) (defn detabulate " Take a contingency table of counts and returns a matrix of observations. Examples: (use '(incanter core stats datasets)) (def by-gender (group-by (get-dataset :hair-eye-color) 2)) (def table (matrix (sel (first by-gender) :cols 3) 4)) (detabulate :table table) (tabulate (detabulate :table table)) ;; example 2 (def data (matrix [[1 0] [1 1] [1 1] [1 0] [0 0] [1 1] [1 1] [1 0] [1 1]])) (tabulate data) (tabulate (detabulate :table (:table (tabulate data)))) " ([& options] (let [opts (when options (apply assoc {} options)) table (:table opts) row-labels (when table (or (:row-labels opts) (range (nrow table)))) col-labels (when table (or (:col-labels opts) (range (ncol table)))) data (apply bind-rows (apply concat (for [r row-labels c col-labels] (repeat (sel table :rows r :cols c) [r c]))))] data)))
true
;;; stats.clj -- Statistics library for Clojure built on the CERN Colt Library ;; by PI:NAME:<NAME>END_PI http://incanter.org ;; March 11, 2009 ;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. All rights reserved. The use ;; and distribution terms for this software are covered by the Eclipse ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. ;; CHANGE LOG ;; March 11, 2009: First version (ns incanter.stats (:gen-class) (:import (cern.colt.list.tdouble DoubleArrayList) (cern.jet.random.tdouble Gamma Beta Binomial ChiSquare DoubleUniform Exponential NegativeBinomial Normal Poisson StudentT) (cern.jet.random.tdouble.engine DoubleMersenneTwister) (cern.jet.stat.tdouble DoubleDescriptive Probability)) (:use [incanter.core :only (abs plus minus div mult mmult to-list bind-columns gamma pow sqrt diag trans regularized-beta ncol nrow identity-matrix decomp-cholesky decomp-svd matrix length sum sum-of-squares sel matrix? cumulative-sum solve vectorize bind-rows)])) (defn indicator " Returns a sequence of ones and zeros, where ones are returned when the given predicate is true for corresponding element in the given collection, and zero otherwise. Examples: (use 'incanter.stats) (indicator #(neg? %) (sample-normal 10)) ;; return the sum of the positive values in a normal sample (def x (sample-normal 100)) (sum (mult x (indicator #(pos? %) x))) " ([pred coll] (for [el coll] (if (pred el) 1 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CONTINOUS DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; F DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-f " Returns the F pdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's df function. Options: :df1 (default 1) :df2 (default 1) See also: cdf-f and quantile-f References: http://en.wikipedia.org/wiki/F_distribution http://mathworld.wolfram.com/F-Distribution.html http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-f 1.0 :df1 5 :df2 2) " ([x & options] (let [opts (when options (apply assoc {} options)) df1 (or (:df1 opts) 0) df2 (or (:df2 opts) 1) pdf-fx (fn [x] (* (/ (gamma (/ (+ df1 df2) 2)) (* (gamma (/ df1 2)) (gamma (/ df2 2)))) (pow (/ df1 df2) (/ df1 2)) (pow x (- (/ df1 2) 1)) (pow (+ 1 (* (/ df1 df2) x)) (- 0 (/ (+ df1 df2) 2))))) ] (if (coll? x) (map pdf-fx x) (pdf-fx x))))) (defn cdf-f " Returns the F-distribution cdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pf function. Options: :df1 (default 1) :df2 (default 1) See also: pdf-f and quantile-f References: http://en.wikipedia.org/wiki/F_distribution http://mathworld.wolfram.com/F-Distribution.html http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-f 1.0 :df1 5 :df2 2) " ([x & options] (let [opts (when options (apply assoc {} options)) lower-tail? (if (false? (:lower-tail opts)) false true) df1 (or (:df1 opts) 1) df2 (or (:df2 opts) 1) cdf-fx (if lower-tail? (fn [x1] (regularized-beta (/ (* df1 x1) (+ df2 (* df1 x1))) (/ df1 2) (/ df2 2))) (fn [x1] (- 1 (regularized-beta (/ (* df1 x1) (+ df2 (* df1 x1))) (/ df1 2) (/ df2 2))))) ] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NORMAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-normal " Returns the Normal pdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dnorm function. Options: :mean (default 0) :sd (default 1) See also: cdf-normal, quantile-normal, sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-normal 1.96 :mean -2 :sd (sqrt 0.5)) " ([x & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) dist (Normal. mean sd (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-normal " Returns the Normal cdf of the given value, x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pnorm function. Options: :mean (default 0) :sd (default 1) See also: pdf-normal, quantile-normal, sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-normal 1.96 :mean -2 :sd (sqrt 0.5)) " ([x & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) dist (Normal. mean sd (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn quantile-normal " Returns the inverse of the Normal CDF for the given probability. It will return a sequence of values, if given a sequence of probabilities. This is equivalent to R's qnorm function. Options: :mean (default 0) :sd (default 1) Returns: a value x, where (cdf-normal x) = probability See also: pdf-normal, cdf-normal, and sample-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/Probability.html http://en.wikipedia.org/wiki/Normal_distribution http://en.wikipedia.org/wiki/Quantile Example: (quantile-normal 0.975) (quantile-normal [0.025 0.975] :mean -2 :sd (sqrt 0.5)) " ([probability & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1) x (if (coll? probability) (map #(Probability/normalInverse %) probability) (Probability/normalInverse probability))] (plus mean (mult sd x))))) (defn sample-normal " Returns a sample of the given size from a Normal distribution This is equivalent to R's rnorm function. Options: :mean (default 0) :sd (default 1) See also: pdf-normal, cdf-normal, quantile-normal References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Normal.html http://en.wikipedia.org/wiki/Normal_distribution Example: (sample-normal 1000 :mean -2 :sd (sqrt 0.5)) " ([size & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) 0) sd (or (:sd opts) 1)] (if (= size 1) (Normal/staticNextDouble mean sd) (for [_ (range size)] (Normal/staticNextDouble mean sd)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; MULTIVARIATE NORMAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sample-mvn " Returns a sample of the given size from a Multivariate Normal distribution. This is equivalent to R's mvtnorm::rmvnorm function. Arguments: size -- the size of the sample to return Options: :mean (default (repeat (ncol sigma) 0)) :sigma (default (identity-matrix (count mean))) Examples: (use '(incanter core stats charts)) (def mvn-samp (sample-mvn 1000 :mean [7 5] :sigma (matrix [[2 1.5] [1.5 3]]))) (covariance mvn-samp) (def means (map mean (trans mvn-samp))) ;; plot scatter-plot of points (def mvn-plot (scatter-plot (sel mvn-samp :cols 0) (sel mvn-samp :cols 1))) (view mvn-plot) ;; add centroid to plot (add-points mvn-plot [(first means)] [(second means)]) ;; add regression line to scatter plot (def x (sel mvn-samp :cols 0)) (def y (sel mvn-samp :cols 1)) (def lm (linear-model y x)) (add-lines mvn-plot x (:fitted lm)) References: http://en.wikipedia.org/wiki/Multivariate_normal " ([size & options] (let [opts (when options (apply assoc {} options)) mean (or (:mean opts) (if (:sigma opts) (repeat (ncol (:sigma opts)) 0) [0])) sigma (or (:sigma opts) (identity-matrix (count mean))) p (count mean) chol (decomp-cholesky sigma) norm-samp (mmult (matrix (sample-normal (* size p)) p) chol) ] (if (> (nrow norm-samp) 1) (matrix (map #(plus % (trans mean)) norm-samp)) (matrix (plus norm-samp (trans mean))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UNIFORM DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-uniform " Returns the Uniform pdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dunif function. Options: :min (default 0) :max (default 1) See also: cdf-uniform and sample-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-uniform 5) (pdf-uniform 5 :min 1 :max 10) " ([x & options] (let [opts (when options (apply assoc {} options)) min (double (or (:min opts) 0.0)) max (double (or (:max opts) 1.0)) dist (DoubleUniform. min max (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-uniform " Returns the Uniform cdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's punif function. Options: :min (default 0) :max (default 1) See also: pdf-uniform and sample-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-uniform 5) (cdf-uniform 5 :min 1 :max 10) " ([x & options] (let [opts (when options (apply assoc {} options)) min (double (or (:min opts) 0.0)) max (double (or (:max opts) 1.0)) dist (DoubleUniform. min max (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn sample-uniform " Returns a sample of the given size from a Uniform distribution. This is equivalent to R's runif function. Options: :min (default 0) :max (default 1) :integers (default false) See also: pdf-uniform and cdf-uniform References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/DoubleUniform.html http://en.wikipedia.org/wiki/Uniform_distribution Example: (sample-uniform 1000) (sample-uniform 1000 :min 1 :max 10) " ([size & options] (let [opts (when options (apply assoc {} options)) min-val (double (or (:min opts) 0.0)) max-val (double (or (:max opts) 1.0)) ints? (if (true? (:integers opts)) true false) dist (DoubleUniform. min-val max-val (DoubleMersenneTwister.))] (if (= size 1) (if ints? (DoubleUniform/staticNextIntFromTo min-val max-val) (DoubleUniform/staticNextDoubleFromTo min-val max-val)) (if ints? (for [_ (range size)] (DoubleUniform/staticNextIntFromTo min-val max-val)) (for [_ (range size)] (DoubleUniform/staticNextDoubleFromTo min-val max-val))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BETA DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-beta " Returns the Beta pdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dbeta function. Options: :alpha (default 1) :beta (default 1) See also: cdf-beta and sample-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-beta 0.5 :alpha 1 :beta 2) " ([x & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1) dist (Beta. alpha beta (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-beta " Returns the Beta cdf of the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pbeta function. Options: :alpha (default 1) :beta (default 1) :lower-tail (default true) See also: pdf-beta and sample-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-beta 0.5 :alpha 1 :beta 2) (cdf-beta 0.5 :alpha 1 :beta 2 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/beta alpha beta x1)) (fn [x1] (- 1 (Probability/betaComplemented alpha beta x1))))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-beta " Returns a sample of the given size from a Beta distribution. This is equivalent to R's rbeta function. Options: :alpha (default 1) :beta (default 1) These default values produce a Uniform distribution. See also: pdf-beta and cdf-beta References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Beta.html http://en.wikipedia.org/wiki/Beta_distribution Example: (sample-beta 1000 :alpha 1 :beta 2) " ([size & options] (let [opts (when options (apply assoc {} options)) alpha (or (:alpha opts) 1) beta (or (:beta opts) 1)] (if (= size 1) (Beta/staticNextDouble alpha beta) (for [_ (range size)] (Beta/staticNextDouble alpha beta)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; GAMMA DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-gamma " Returns the Gamma pdf for the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's dgamma function. Options: :shape (default 1) :rate (default 1) See also: cdf-gamma and sample-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-gamma 10 :shape 1 :rate 2) " ([x & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1) dist (Gamma. shape rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-gamma " Returns the Gamma cdf for the given value of x. It will return a sequence of values, if x is a sequence. This is equivalent to R's pgamma function. Options: :shape (default 1) :rate (default 1) :lower-tail (default true) See also: pdf-gamma and sample-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-gamma 10 :shape 1 :rate 2) (cdf-gamma 3 :shape 1 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/gamma rate shape x1)) (fn [x1] (Probability/gammaComplemented rate shape x1)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-gamma " Returns a sample of the given size from a Gamma distribution. This is equivalent to R's rgamma function. Options: :shape (default 1) :rate (default 1) See also: pdf-gamma, cdf-gamma, and quantile-gamma References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Gamma.html http://en.wikipedia.org/wiki/Gamma_distribution Example: (sample-gamma 1000 :shape 1 :rate 2) " ([size & options] (let [opts (when options (apply assoc {} options)) shape (or (:shape opts) 1) rate (or (:rate opts) 1)] (if (= size 1) (Gamma/staticNextDouble shape rate) (for [_ (range size)] (Gamma/staticNextDouble shape rate)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CHI SQUARE DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-chisq " Returns the Chi Square pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dchisq function. Options: :df (default 1) See also: cdf-chisq and sample-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-chisq 5.0 :df 2) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) dist (ChiSquare. df (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-chisq " Returns the Chi Square cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pchisq function. Options: :df (default 1) :lower-tail (default true) See also: pdf-chisq and sample-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-chisq 5.0 :df 2) (cdf-chisq 5.0 :df 2 :lower-tail false) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/chiSquare df x1)) (fn [x1] (Probability/chiSquareComplemented df x1)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-chisq " Returns a sample of the given size from a Chi Square distribution Same as R's rchisq function. Options: :df (default 1) See also: pdf-chisq and cdf-chisq References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/ChiSquare.html http://en.wikipedia.org/wiki/Chi_square_distribution Example: (sample-chisq 1000 :df 2) " ([size & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1)] (if (= size 1) (ChiSquare/staticNextDouble df) (for [_ (range size)] (ChiSquare/staticNextDouble df)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; STUDENT'S T DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-t " Returns the Student's t pdf for the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dt function. Options: :df (default 1) See also: cdf-t, quantile-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-t 1.2 :df 10) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) dist (StudentT. df (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-t " Returns the Student's t cdf for the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pt function. Options: :df (default 1) See also: pdf-t, quantile-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-t 1.2 :df 10) " ([x & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/studentT df x1)) (fn [x1] (- 1 (Probability/studentT df x1))))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn quantile-t " Returns the inverse of the Student's t CDF for the given probability (i.e. the quantile). It will return a sequence of values, if x is a sequence of probabilities. This is equivalent to R's qt function. Options: :df (default 1) Returns: a value x, where (cdf-t x) = probability See also: pdf-t, cdf-t, and sample-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/Probability.html http://en.wikipedia.org/wiki/Student-t_distribution http://en.wikipedia.org/wiki/Quantile Example: (quantile-t 0.975) (quantile-t [0.025 0.975] :df 25) (def df [1 2 3 4 5 6 7 8 9 10 20 50 100 1000]) (map #(quantile-t 0.025 :df %) df) " ([probability & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1) to-alpha (fn [prob] ;; need to convert the probability to an alpha value (if (< prob 1/2) (* 2 prob) (* 2 (- 1 prob)))) sign-fx (fn [x1 prob] (if (< prob 1/2) (* -1 x1) x1)) x (if (coll? probability) (map #(sign-fx (Probability/studentTInverse (to-alpha %) df) %) probability) (sign-fx (Probability/studentTInverse (to-alpha probability) df) probability))] x))) (defn sample-t " Returns a sample of the given size from a Student's t distribution. Same as R's rt function. Options: :df (default 1) See also: pdf-t, cdf-t, and quantile-t References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/StudentT.html http://en.wikipedia.org/wiki/Student-t_distribution Example: (cdf-t 1000 :df 10) " ([size & options] (let [opts (when options (apply assoc {} options)) df (or (:df opts) 1)] (if (= size 1) (StudentT/staticNextDouble df) (for [_ (range size)] (StudentT/staticNextDouble df)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; EXPONENTIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-exp " Returns the Exponential pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dexp Options: :rate (default 1) See also: cdf-exp and sample-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-exp 2.0 :rate 1/2) " ([x & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1) dist (Exponential. rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-exp " Returns the Exponential cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pexp Options: :rate (default 1) See also: pdf-exp and sample-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-exp 2.0 :rate 1/2) " ([x & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1) dist (Exponential. rate (DoubleMersenneTwister.))] (if (coll? x) (map #(.cdf dist %) x) (.cdf dist x))))) (defn sample-exp " Returns a sample of the given size from a Exponential distribution. Same as R's rexp Options: :rate (default 1) See also: pdf-exp, and cdf-exp References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Exponential.html http://en.wikipedia.org/wiki/Exponential_distribution Example: (sample-exp 1000 :rate 1/2) " ([size & options] (let [opts (when options (apply assoc {} options)) rate (or (:rate opts) 1)] (if (= size 1) (Exponential/staticNextDouble rate) (for [_ (range size)] (Exponential/staticNextDouble rate)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; WISHART DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn sample-wishart " Returns a p-by-p symmetric distribution drawn from a Wishart distribution Options: :p (default 2) -- number of dimensions of resulting matrix :df (default p) -- degree of freedoms (aka n), df <= p :scale (default (identity-matrix p)) -- positive definite matrix (aka V) Examples: (use 'incanter.stats) (sample-wishart :df 10 :p 4) ;; calculate the mean of 1000 wishart matrices, should equal (mult df scale) (div (reduce plus (for [_ (range 1000)] (sample-wishart :p 4))) 1000) References: http://en.wikipedia.org/wiki/Wishart_distribution# " ([& options] (let [opts (when options (apply assoc {} options)) scale (or (:scale opts) (when (:p opts) (identity-matrix (:p opts)))) p (count scale) df (or (:df opts) p) diagonal (for [i (range 1 (inc p))] (pow (sample-chisq 1 :df (inc (- df i))) 1/2)) mat (diag diagonal) indices (for [i (range p) j (range p) :when (< j i)] [i j]) _ (doseq [indx indices] (.set mat (first indx) (second indx) (sample-normal 1))) chol (decomp-cholesky scale) x (mmult chol mat (trans mat) (trans chol))] x))) (defn sample-inv-wishart " Returns a p-by-p symmetric distribution drawn from an inverse-Wishart distribution Options: :p (default 2) -- number of dimensions of resulting matrix :df (default p) -- degree of freedoms (aka n), df <= p :scale (default (identity-matrix p)) -- positive definite matrix (aka V) Examples: (use 'incanter.stats) (sample-inv-wishart :df 10 :p 4) ;; calculate the mean of 1000 wishart matrices, should equal (mult df scale) (div (reduce plus (for [_ (range 1000)] (sample-wishart :p 4))) 1000) References: http://en.wikipedia.org/wiki/Inverse-Wishart_distribution " ([& options] (let [opts (when options (apply assoc {} options)) scale (or (:scale opts) (when (:p opts) (identity-matrix (:p opts)))) p (count scale) df (or (:df opts) p)] (solve (sample-wishart :p p :df df :scale scale))))) (defn sample-dirichlet " Examples: (use '(incanter core stats charts)) ;; a total of 1447 adults were polled to indicate their preferences for ;; candidate 1 (y1=727), candidate 2 (y2=583), or some other candidate or no ;; preference (y3=137). ;; the counts y1, y2, and y3 are assumed to have a multinomial distribution ;; If a uniform prior distribution is assigned to the multinomial vector ;; theta = (th1, th2, th3), then the posterior distribution of theta is ;; proportional to g(theta) = th1^y1 * th2^y2 * th3^y3, which is a ;; dirichlet distribution with parameters (y1+1, y2+1, y3+1) (def theta (sample-dirichlet 1000 [(inc 727) (inc 583) (inc 137)])) ;; view means, 95% CI, and histograms of the proportion parameters (mean (sel theta :cols 0)) (quantile (sel theta :cols 0) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 0))) (mean (sel theta :cols 1)) (quantile (sel theta :cols 1) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 1))) (mean (sel theta :cols 2)) (quantile (sel theta :cols 2) :probs [0.0275 0.975]) (view (histogram (sel theta :cols 2))) ;; view a histogram of the difference in proportions between the first ;; two candidates (view (histogram (minus (sel theta :cols 0) (sel theta :cols 1)))) " ([size alpha] (let [W (trans (for [a alpha] (sample-gamma size :shape a :rate 1))) T (map sum W)] (matrix (map #(div %1 %2) W T))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DISCRETE DISTRIBUTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BINOMIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-binomial " Returns the Bionomial pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dbinom Options: :size (default 1) :prob (default 1/2) See also: cdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-binomial 10 :prob 1/4 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2) dist (Binomial. n p (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-binomial " Returns the Bionomial cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's pbinom Options: :size (default 1) :prob (default 1/2) :lower-tail (default true) See also: pdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-binomial 10 :prob 1/4 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/binomial x1 n p)) (fn [x1] (Probability/binomialComplemented x1 n p)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-binomial " Returns a sample of the given size from a Binomial distribution. Same as R's rbinom Options: :size (default 1) :prob (default 1/2) See also: cdf-binomial and sample-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Binomial.html http://en.wikipedia.org/wiki/Binomial_distribution Example: (sample-binomial 1000 :prob 1/4 :size 20) " ([size & options] (let [opts (when options (apply assoc {} options)) n (or (:size opts) 1) p (or (:prob opts) 1/2)] (if (= size 1) (Binomial/staticNextInt n p) (for [_ (range size)] (Binomial/staticNextInt n p)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; POISSON DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-poisson " Returns the Poisson pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dpois Options: :lambda (default 1) See also: cdf-poisson and sample-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-poisson 5 :lambda 10) " ([x & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1) dist (Poisson. lambda (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-poisson " Returns the Poisson cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's ppois Options: :lambda (default 1) :lower-tail (default true) See also: cdf-poisson and sample-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-poisson 5 :lambda 10) " ([x & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/poisson x1 lambda)) (fn [x1] (Probability/poissonComplemented x1 lambda)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-poisson " Returns a sample of the given size from a Poisson distribution. Same as R's rpois Options: :lambda (default 1) See also: pdf-poisson and cdf-poisson References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/Poisson.html http://en.wikipedia.org/wiki/Poisson_distribution Example: (sample-poisson 1000 :lambda 10) " ([size & options] (let [opts (when options (apply assoc {} options)) lambda (or (:lambda opts) 1)] (if (= size 1) (Poisson/staticNextInt lambda) (for [_ (range size)] (Poisson/staticNextInt lambda)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; NEGATIVE BINOMIAL DISTRIBUTION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pdf-neg-binomial " Returns the Negative Binomial pdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dnbinom Options: :size (default 10) :prob (default 1/2) See also: cdf-neg-binomial and sample-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution http://en.wikipedia.org/wiki/Probability_density_function Example: (pdf-neg-binomial 10 :prob 1/2 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2) dist (NegativeBinomial. size prob (DoubleMersenneTwister.))] (if (coll? x) (map #(.pdf dist %) x) (.pdf dist x))))) (defn cdf-neg-binomial " Returns the Negative Binomial cdf of the given value of x. It will return a sequence of values, if x is a sequence. Same as R's dnbinom Options: :size (default 10) :prob (default 1/2) See also: cdf-neg-binomial and sample-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution http://en.wikipedia.org/wiki/Cumulative_distribution_function Example: (cdf-neg-binomial 10 :prob 1/2 :size 20) " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2) lower-tail? (if (false? (:lower-tail opts)) false true) cdf-fx (if lower-tail? (fn [x1] (Probability/negativeBinomial x1 size prob)) (fn [x1] (Probability/negativeBinomialComplemented x1 size prob)))] (if (coll? x) (map cdf-fx x) (cdf-fx x))))) (defn sample-neg-binomial " Returns a sample of the given size from a Negative Binomial distribution. Same as R's rnbinom Options: :size (default 10) :prob (default 1/2) See also: pdf-neg-binomial and cdf-neg-binomial References: http://incanter.org/docs/parallelcolt/api/cern/jet/random/tdouble/NegativeBinomial.html http://en.wikipedia.org/wiki/Negative_binomial_distribution Example: (sample-neg-binomial 1000 :prob 1/2 :size 20) " ([size & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) 10) prob (or (:prob opts) 1/2)] (if (= size 1) (NegativeBinomial/staticNextInt size prob) (for [_ (range size)] (NegativeBinomial/staticNextInt size prob)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; EMPIRICAL DISTRIBUTION ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn cdf-empirical " Returns a step-function representing the empirical cdf of the given data. Equivalent to R's ecdf function. The following description is from the ecdf help in R: The e.c.d.f. (empirical cumulative distribution function) Fn is a step function with jumps i/n at observation values, where i is the number of tied observations at that value. Missing values are ignored. For observations 'x'= (x1,x2, ... xn), Fn is the fraction of observations less or equal to t, i.e., Fn(t) = #{x_i <= t} / n = 1/n sum(i=1,n) Indicator(xi <= t). Examples: (use '(incanter core stats charts)) (def exam1 [192 160 183 136 162 165 181 188 150 163 192 164 184 189 183 181 188 191 190 184 171 177 125 192 149 188 154 151 159 141 171 153 169 168 168 157 160 190 166 150]) ;; the ecdf function returns an empirical cdf function for the given data (def ecdf (cdf-empirical exam1)) ;; plot the data's empircal cdf (view (scatter-plot exam1 (map ecdf exam1))) " ([x] (fn [t] (div (sum (indicator #(<= % t) x)) (count x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; STATISTICAL FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn mean " Returns the mean of the data, x. Examples: (mean (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Mean " ([x] (let [xx (to-list x)] (DoubleDescriptive/mean (DoubleArrayList. (double-array xx)))))) (defn variance " Returns the sample variance of the data, x. Equivalent to R's var function. Examples: (variance (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Sample_variance#Population_variance_and_sample_variance " ([x] (DoubleDescriptive/sampleVariance (length x) (sum x) (sum-of-squares x)))) (defn covariance " Returns the sample covariance of x and y. Examples: ;; create some data that covaries (def x (sample-normal 100)) (def err (sample-normal 100)) (def y (plus (mult 5 x) err)) ;; estimate the covariance of x and y (covariance x y) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Covariance " ([x y] (let [ xx (to-list x) yy (to-list y) ] (DoubleDescriptive/covariance (DoubleArrayList. (double-array xx)) (DoubleArrayList. (double-array yy))))) ([mat] (let [n (ncol mat)] (matrix (for [i (range n) j (range n)] (covariance (sel mat true i) (sel mat true j))) n)))) (defn sd " Returns the sample standard deviation of the data, x. Equivalent to R's sd function. Examples: (sd (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Standard_deviation " ([x] ;; population sd, not the sample sd ;(DoubleDescriptive/sampleStandardDeviation (length x) (variance x)))) ;; return the sample standard deviation (sqrt (variance x)))) (defn correlation " Returns the sample correlation of x and y, or the correlation matrix of the given matrix. Examples: References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Correlation " ([x y] (let [ xx (to-list x) yy (to-list y) ] (DoubleDescriptive/correlation (DoubleArrayList. (double-array xx)) (sd x) (DoubleArrayList. (double-array yy)) (sd y)))) ([mat] (div (covariance mat) (sqrt (mmult (diag (covariance mat)) (trans (diag (covariance mat)))))))) (defn median " Returns the median of the data, x. Examples: (median (sample-normal 100)) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Median " ([x] (let [xx (sort (to-list x))] (DoubleDescriptive/median (DoubleArrayList. (double-array xx)))))) (defn kurtosis " Returns the kurtosis of the data, x. \"Kurtosis is a measure of the \"peakedness\" of the probability distribution of a real-valued random variable. Higher kurtosis means more of the variance is due to infrequent extreme deviations, as opposed to frequent modestly-sized deviations.\" (Wikipedia) Examples: (kurtosis (sample-normal 100000)) ;; approximately 0 (kurtosis (sample-gamma 100000)) ;; approximately 6 References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Kurtosis " ([x] (DoubleDescriptive/kurtosis (DoubleArrayList. (double-array x)) (mean x) (variance x)))) (defn skewness " Returns the skewness of the data, x. \"Skewness is a measure of the asymmetry of the probability distribution of a real-valued random variable.\" (Wikipedia) Examples: (skewness (sample-normal 100000)) ;; approximately 0 (skewness (sample-gamma 100000)) ;; approximately 2 References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Skewness " ([x] (DoubleDescriptive/skew (DoubleArrayList. (double-array x)) (mean x) (sd x)))) (defn quantile " Returns the quantiles of the data, x. By default it returns the min, 25th-percentile, 50th-percentile, 75th-percentile, and max value. Options: :probs (default [0.0 0.25 0.5 0.75 1.0]) Examples: (quantile (sample-normal 100)) (quantile (sample-normal 100) :probs [0.025 0.975]) (quantile (sample-normal 100) :probs 0.975) References: http://incanter.org/docs/parallelcolt/api/cern/jet/stat/tdouble/DoubleDescriptive.html http://en.wikipedia.org/wiki/Quantile " ([x & options] (let [opts (when options (apply assoc {} options)) _x (if (matrix? x) (to-list x) x) data (DoubleArrayList. (double-array (sort _x))) probs (cond (number? (:probs opts)) (:probs opts) (coll? (:probs opts)) (DoubleArrayList. (double-array (:probs opts))) :default (DoubleArrayList. (double-array [0.0 0.25 0.5 0.75 1.0])))] (if (number? probs) (DoubleDescriptive/quantile data probs) (seq (.elements (DoubleDescriptive/quantiles data probs))))))) (defn sample " Returns a sample of the given size from the given collection. If replacement is set to false it returns a set, otherwise it returns a list. Arguments: x -- collection to be sampled from Options: :size -- (default (count x) sample size :replacement (default true) -- sample with replacement Examples: (sample (range 10)) ; permutation of numbers zero through ten (sample [:red :green :blue] :size 10) ; choose 10 items that are either :red, :green, or :blue. (sample (seq \"abcdefghijklmnopqrstuvwxyz\") :size 4 :replacement false) ; choose 4 random letters. " ([x & options] (let [opts (when options (apply assoc {} options)) size (or (:size opts) (count x)) replacement? (if (false? (:replacement opts)) false true) max-idx (dec (count x))] (if (= size 1) (nth x (rand-int (inc max-idx))) (if replacement? (map #(nth x %) (sample-uniform size :min 0 :max max-idx :integers true)) (if (> size (count x)) (throw (Exception. "'size' can't be larger than (count x) without replacement!")) (map #(nth x %) (loop [samp-indices [] indices-set #{}] (if (= (count samp-indices) size) samp-indices (let [i (sample-uniform 1 :min 0 :max max-idx :integers true)] (if (contains? indices-set i) (recur samp-indices indices-set) (recur (conj samp-indices i) (conj indices-set i))))))))))))) (defn bootstrap " Returns a bootstrap sample of the given statistic on the given data. Arguments: data -- vector of data to resample from statistic -- a function that returns a value given a vector of data Options: :size -- the number of bootstrap samples to return :smooth -- (default false) smoothing option :smooth-sd -- (default (/ (sqrt (count data)))) determines the standard deviation of the noise to use for smoothing :replacement -- (default true) determines if sampling of the data should be done with replacement References: 1. PI:NAME:<NAME>END_PI. LunnPI:NAME:<NAME>END_PI, Data Analysis by Resampling Concepts and Applications, 2000, pages 105-117 2. http://en.wikipedia.org/wiki/Bootstrapping_(statistics) Examples: ;; example from Data Analysis by Resampling Concepts and Applications ;; PI:NAME:<NAME>END_PI (pages 119-122) (use '(incanter core stats charts)) ;; weights (in grams) of 50 randomly sampled bags of preztels (def weights [464 447 446 454 450 457 450 442 433 452 449 454 450 438 448 449 457 451 456 452 450 463 464 453 452 447 439 449 468 443 433 460 452 447 447 446 450 459 466 433 445 453 454 446 464 450 456 456 447 469]) ;; calculate the sample median, 450 (median weights) ;; generate bootstrap sample (def t* (bootstrap weights median :size 2000)) ;; view histogram of bootstrap histogram (view (histogram t*)) ;; calculate the mean of the bootstrap median ~ 450.644 (mean t*) ;; calculate the standard error ~ 1.083 (def se (sd t*)) ;; 90% standard normal CI ~ (448.219 451.781) (plus (median weights) (mult (quantile-normal [0.05 0.95]) se)) ;; 90% symmetric percentile CI ~ (449.0 452.5) (quantile t* :probs [0.05 0.95]) ;; 90% non-symmetric percentile CI ~ (447.5 451.0) (minus (* 2 (median weights)) (quantile t* :probs [0.95 0.05])) ;; calculate bias (- (mean t*) (median weights)) ;; ~ 0.644 ;; example with smoothing ;; Newcomb's speed of light data (use '(incanter core stats charts)) ;; A numeric vector giving the Third Series of measurements of the ;; passage time of light recorded by Newcomb in 1882. The given ;; values divided by 1000 plus 24 give the time in millionths of a ;; second for light to traverse a known distance. The 'true' value is ;; now considered to be 33.02. (def speed-of-light [28 -44 29 30 24 28 37 32 36 27 26 28 29 26 27 22 23 20 25 25 36 23 31 32 24 27 33 16 24 29 36 21 28 26 27 27 32 25 28 24 40 21 31 32 28 26 30 27 26 24 32 29 34 -2 25 19 36 29 30 22 28 33 39 25 16 23]) ;; view histogram of data to see outlier observations (view (histogram speed-of-light :nbins 30)) (def samp (bootstrap speed-of-light median :size 10000)) (view (histogram samp :density true :nbins 30)) (mean samp) (quantile samp :probs [0.025 0.975]) (def smooth-samp (bootstrap speed-of-light median :size 10000 :smooth true)) (view (histogram smooth-samp :density true :nbins 30)) (mean smooth-samp) (quantile smooth-samp :probs [0.025 0.975]) " ([data statistic & options] (let [opts (when options (apply assoc {} options)) size (:size opts) replacement (if (false? (:replacement opts)) false true) n (or (:n opts) (count data)) smooth? (true? (:smooth opts)) smooth-sd (or (:smooth-sd opts) (/ (sqrt n))) B1 100 B2 25 max-iter 10 D 0.01 samp (if (nil? size) (loop [stats (for [_ (range B1)] (statistic (sample data :size n :replacement replacement))) k 0] (let [stats2 (concat stats (for [_ (range B2)] (statistic (sample data :size n :replacement replacement)))) se1 (sd stats) se2 (sd stats2)] (if (or (= k max-iter) (< (* (- 1 D) se1) se2 (* (+ 1 D) se1))) stats2 (recur stats2 (inc k))))) (for [_ (range size)] (statistic (sample data :size n :replacement replacement)))) samp-size (count samp)] (if smooth? (plus samp (sample-normal samp-size :sd smooth-sd)) samp)))) (defn cumulative-mean " Returns a sequence of cumulative means for the given collection. For instance The first value equals the first value of the argument, the second value is the mean of the first two arguments, the third is the mean of the first three arguments, etc. Examples: (cumulative-mean (sample-normal 100)) " ([coll] (map / (cumulative-sum coll) (range 1 (inc (count coll)))))) (defn sweep " Return an array obtained from an input array by sweeping out a summary statistic. Based to R's sweep function. Arguments: x is an sequence Options: :stat (default mean) the statistic to sweep out :fun (defaul minus) the function used to sweep the stat out Example: (use '(incanter core stats)) (def x (sample-normal 30 :mean 10 :sd 5)) (sweep x) ;; center the data around mean (sweep x :stat sd :fun div) ;; divide data by its sd " ([x & options] (let [opts (when options (apply assoc {} options)) stat-fn (or (:stat opts) mean) fun (or (:fun opts) minus) stat (stat-fn x)] (fun x stat)))) (defn permute " If provided a single argument, returns a permuted version of the given collection. (perm x) is the same as (sample x). If provided two arguments, returns two lists that are permutations across the given collections. In other words, each of the new collections will contain elements from both of the given collections. Useful for permutation tests or randomization tests. Examples: (permute (range 10)) (permute (range 10) (range 10 20)) " ([x] (sample x)) ([x y] (let [n1 (count x) samp (sample (concat x y) :replacement false) new-x (take n1 samp) new-y (drop n1 samp)] (list new-x new-y)))) (defn sample-permutations " If provided a two arguments (n x), it returns a list of n permutations of x. If provided three (n x y) arguments, returns a list with two with n permutations of each arguments, where each permutation is drawn from the pooled arguments. Arguments: n -- number of randomized versions of the original two groups to return x -- group 1 y -- (default nil) group 2 Examples: (use '(incanter core stats)) (sample-permutations 10 (range 10)) (sample-permutations 10 (range 10) (range 10 20)) ;; extended example with plant-growth data (use '(incanter core stats datasets charts)) ;; load the plant-growth dataset (def data (to-matrix (get-dataset :plant-growth))) ;; break the first column of the data into groups based on treatment (second column). (def groups (group-by data 1 :cols 0)) ;; define a function for the statistic of interest (defn means-diff [x y] (minus (mean x) (mean y))) ;; calculate the difference in sample means between the two groups (def samp-mean-diff (means-diff (first groups) (second groups))) ;; 0.371 ;; create 500 permuted versions of the original two groups (def permuted-groups (sample-permutations 1000 (first groups) (second groups))) ;; calculate the difference of means of the 500 samples (def permuted-means-diffs1 (map means-diff (first permuted-groups) (second permuted-groups))) ;; use an indicator function that returns 1 when the randomized means diff is greater ;; than the original sample mean, and zero otherwise. Then take the mean of this sequence ;; of ones and zeros. That is the proportion of times you would see a value more extreme ;; than the sample mean (i.e. the p-value). (mean (indicator #(> % samp-mean-diff) permuted-means-diffs1)) ;; 0.088 ;; calculate the 95% confidence interval of the null hypothesis. If the ;; sample difference in means is outside of this range, that is evidence ;; that the two means are statistically significantly different. (quantile permuted-means-diffs1 :probs [0.025 0.975]) ;; (-0.606 0.595) ;; Plot a histogram of the permuted-means-diffs using the density option, ;; instead of the default frequency, and then add a normal pdf curve with ;; the mean and sd of permuted-means-diffs data for a visual comparison. (doto (histogram permuted-means-diffs1 :density true) (add-lines (range -1 1 0.01) (pdf-normal (range -1 1 0.01) :mean (mean permuted-means-diffs1) :sd (sd permuted-means-diffs1))) view) ;; compare the means of treatment 2 and control (def permuted-groups (sample-permutations 1000 (first groups) (last groups))) (def permuted-means-diffs2 (map means-diff (first permuted-groups) (second permuted-groups))) (def samp-mean-diff (means-diff (first groups) (last groups))) ;; -0.4939 (mean (indicator #(< % samp-mean-diff) permuted-means-diffs2)) ;; 0.022 (quantile permuted-means-diffs2 :probs [0.025 0.975]) ;; (-0.478 0.466) ;; compare the means of treatment 1 and treatment 2 (def permuted-groups (sample-permutations 1000 (second groups) (last groups))) (def permuted-means-diffs3 (map means-diff (first permuted-groups) (second permuted-groups))) (def samp-mean-diff (means-diff (second groups) (last groups))) ;; -0.865 (mean (indicator #(< % samp-mean-diff) permuted-means-diffs3)) ;; 0.002 (quantile permuted-means-diffs3 :probs [0.025 0.975]) ;; (-0.676 0.646) (doto (box-plot permuted-means-diffs1) (add-box-plot permuted-means-diffs2) (add-box-plot permuted-means-diffs3) view) Further Reading: http://en.wikipedia.org/wiki/Resampling_(statistics) " ([n x] (loop [samp '() i 0] (if (= i n) samp (recur (conj samp (sample x)) (inc i))))) ([n x y] (let [pool (concat x y) m1 (count x)] (loop [samp-x '() samp-y '() i 0] (if (= i n) (list samp-x samp-y) (let [perm-samp (sample pool) new-x (take m1 perm-samp) new-y (drop m1 perm-samp)] (recur (conj samp-x new-x) (conj samp-y new-y) (inc i)))))))) ;;;;;;;;;;;;;;; OLS REGRESSION FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;; (defn linear-model " Returns the results of performing a OLS linear regression of y on x. Arguments: y is a vector (or sequence) of values for the dependent variable x is a vector or matrix of values for the independent variables Options: :intercept (default true) indicates weather an intercept term should be included Returns: a map, of type ::linear-model, containing: :design-matrix -- a matrix containing the independent variables, and an intercept columns :coefs -- the regression coefficients :t-tests -- t-test values of coefficients :t-probs -- p-values for t-test values of coefficients :coefs-ci -- 95% percentile confidence interval :fitted -- the predicted values of y :residuals -- the residuals of each observation :std-errors -- the standard errors of the coeffients :sse -- the sum of squared errors, also called the residual sum of squares :ssr -- the regression sum of squares, also called the explained sum of squares :sst -- the total sum of squares (proportional to the sample variance) :r-square -- coefficient of determination Examples: (use '(incanter core stats datasets charts)) (def iris (to-matrix (get-dataset :iris) :dummies true)) (def y (sel iris :cols 0)) (def x (sel iris :cols (range 1 6))) (def iris-lm (linear-model y x)) ; with intercept term (keys iris-lm) ; see what fields are included (:coefs iris-lm) (:sse iris-lm) (quantile (:residuals iris-lm)) (:r-square iris-lm) (:adj-r-square iris-lm) (:f-stat iris-lm) (:f-prob iris-lm) (:df iris-lm) (def x1 (range 0.0 3 0.1)) (view (xy-plot x1 (cdf-f x1 :df1 4 :df2 144))) References: http://en.wikipedia.org/wiki/OLS_Regression http://en.wikipedia.org/wiki/Coefficient_of_determination " ([y x & options] (let [opts (when options (apply assoc {} options)) intercept? (if (false? (:intercept opts)) false true) _x (if intercept? (bind-columns (replicate (nrow x) 1) x) x) xtx (mmult (trans _x) _x) xtxi (if (number? xtx) (/ 1 xtx) (solve xtx)) xty (mmult (trans _x) y) coefs (if (and (number? xtxi) (number? xty)) (* xtxi xty) (to-list (if (or (number? xtxi) (number? xty)) (mult xtxi xty) (mmult xtxi xty)))) fitted (to-list (if (number? coefs) (mult _x coefs) (mmult _x coefs))) resid (to-list (minus y fitted)) sse (sum-of-squares resid) ssr (sum-of-squares (minus fitted (mean fitted))) sst (+ sse ssr) r-square (/ ssr sst) n (nrow y) p (ncol _x) p-1 (if intercept? (- p 1) p) adj-r-square (- 1 (* (- 1 r-square) (/ (- n 1) (- n p 1)))) mse (/ sse (- n p)) msr (/ ssr p-1) f-stat (/ msr mse) df1 p-1 df2 (- n p) f-prob (cdf-f f-stat :df1 df1 :df2 df2 :lower-tail false) coef-var (mult mse xtxi) std-errors (sqrt (diag coef-var)) t-tests (div coefs std-errors) t-probs (mult 2 (cdf-t (abs t-tests) :df df2 :lower-tail false)) t-95 (mult (quantile-t 0.975 :df df2) std-errors) coefs-ci (if (number? std-errors) [(plus coefs t-95) (minus coefs t-95)] (partition 2 (interleave (minus coefs t-95) (plus coefs t-95)))) ] (with-meta {:x _x :y y :fitted fitted :design-matrix _x :coefs coefs :t-tests t-tests :t-probs t-probs :coefs-ci coefs-ci :residuals resid :std-errors std-errors :sse sse :ssr ssr :sst sst :mse mse :msr msr :f-stat f-stat :f-prob f-prob :df [df1 df2] :coef-var coef-var :r-square r-square :adj-r-square adj-r-square } {:type ::linear-model})))) (defn t-test " Argument: x : sample to test Options: :y (default nil) :mu (default (mean y) or 0) population mean :alternative (default :two-sided) other choices :less :greater :var-equal TODO (default false) variance equal :paired TODO (default false) paired test :conf-level (default 0.95) for returned confidence interval Examples: (t-test (range 1 11) :mu 0) (t-test (range 1 11) :mu 0 :alternative :less) (t-test (range 1 11) :mu 0 :alternative :greater) (t-test (range 1 11) :y (range 7 21)) (t-test (range 1 11) :y (range 7 21) :alternative :less) (t-test (range 1 11) :y (range 7 21) :alternative :greater) (t-test (range 1 11) :y (conj (range 7 21) 200)) References: http://en.wikipedia.org/wiki/T_test http://www.socialresearchmethods.net/kb/stat_t.php " ([x & options] (let [opts (when options (apply assoc {} options)) y (or (:y opts) nil) one-sample? (nil? y) mu (or (:mu opts) (if y (mean y) 0)) paired? (if (true? (:paired opts)) true false) var-equal? (if (true? (:var-equal opts)) true false) conf-level (or (:conf-level opts) 0.95) alternative (or (:alternative opts) :two-sided) x-mean (mean x) x-var (variance x) n1 (count x) y-mean (if one-sample? nil (mean y)) y-var (if one-sample? nil (variance y)) n2 (if one-sample? nil (count y)) t-stat (if one-sample? (/ (- x-mean mu) (/ (sqrt x-var) (sqrt n1))) ;; calculate Welch's t test (/ (- x-mean y-mean) (sqrt (+ (/ x-var n1) (/ y-var n2))))) df (if one-sample? (dec n1) ;; calculate Welch-Satterthwaite equation (/ (pow (+ (/ x-var n1) (/ y-var n2)) 2) (+ (/ (pow (/ x-var n1) 2) (dec n1)) (/ (pow (/ y-var n2) 2) (dec n2))))) lower-tail? (cond (= alternative :two-sided) (if (neg? t-stat) true false) (= alternative :lower) (if (neg? t-stat) false true) (= alternative :greater) (if one-sample? (if (neg? t-stat) true false) (if (neg? t-stat) false true))) one-sided-p (cdf-t t-stat :df df :lower-tail lower-tail?) qt (if (= alternative :two-sided) (quantile-t (/ (- 1 conf-level) 2) :df df) (quantile-t (- 1 conf-level) :df df))] {:t-stat t-stat :df df :x-mean x-mean :x-var x-var :n1 n1 :y-mean y-mean :y-var y-var :n2 n2 :p-value (if (= alternative :two-sided) (* 2 one-sided-p) one-sided-p) :conf-int (if one-sample? ;; one-sample confidence interval [(if (= alternative :less) Double/NEGATIVE_INFINITY (+ x-mean (/ (* qt (sqrt x-var)) (sqrt n1)))) (if (= alternative :greater) Double/POSITIVE_INFINITY (- x-mean (/ (* qt (sqrt x-var)) (sqrt n1))))] ;; two-sample confidence interval [(if (= alternative :less) Double/NEGATIVE_INFINITY (+ (- x-mean y-mean) (* qt (sqrt (+ (/ x-var n1) (/ y-var n2)))))) (if (= alternative :greater) Double/POSITIVE_INFINITY (- (- x-mean y-mean) (* qt (sqrt (+ (/ x-var n1) (/ y-var n2))))))]) }))) (defn tabulate " Cross-tabulates the values of the given numeric matrix. Returns a hash-map with the following fields: :table -- the table of counts for each combination of values, this table is only returned if x has two-columns :levels -- a sequence of sequences, where each sequence list the levels (possible values) of the corresponding column of x. :margins -- a sequence of sequences, where each sequence represents the marginal total for each level of the corresponding column of x. :counts -- a hash-map, where vectors of unique combinations of the cross-tabulated levels are the keys and the values are the total count of each combination. :N -- the grand-total for the contingency table Examples: (use '(incanter core stats)) (tabulate [1 2 3 2 3 2 4 3 5]) (tabulate (sample-poisson 100 :lambda 5)) (use '(incanter core stats datasets)) (def math-prog (to-matrix (get-dataset :math-prog))) (tabulate (sel math-prog :cols [1 2])) (def data (matrix [[1 0 1] [1 1 1] [1 1 1] [1 0 1] [0 0 0] [1 1 1] [1 1 1] [1 0 1] [1 1 0]])) (tabulate data) (def data (matrix [[1 0] [1 1] [1 1] [1 0] [0 0] [1 1] [1 1] [1 0] [1 1]])) (tabulate data) " ([x & options] (let [opts (when options (apply assoc {} options)) _x (if (matrix? x) x (matrix x)) p (ncol _x) n (nrow _x) levels (for [i (range p)] (sort (seq (into #{} (sel _x :cols i))))) margins (for [j (range p)] (loop [marg {} i (int 0)] (if (= i n) marg (let [lvl (sel _x :rows i :cols j)] (recur (let [cnt (get marg lvl)] (if cnt (assoc marg lvl (inc cnt)) (assoc marg lvl 1))) (inc i)))))) counts (loop [tab {} i (int 0)] (if (= i n) tab (recur (let [row (if (> p 1) (to-list (nth _x i)) (nth _x i)) cnt (get tab row)] (if (nil? cnt) (assoc tab row 1) (assoc tab row (inc cnt)))) (inc i)))) n-levels (map #(count (keys %)) margins)] {:counts counts :margins margins :table (when (= p 2) (matrix (for [r (first levels) c (second levels)] (let [c (get counts (to-list (trans [r c])))] (if c c 0))) (second n-levels))) :n-vars p :N (reduce + (vals (first margins))) :n-levels n-levels :levels levels}))) (defn chisq-test " Performs chi-squared contingency table tests and goodness-of-fit tests. If the optional argument :y is not provided then a goodness-of-fit test is performed. In this case, the hypothesis tested is whether the population probabilities equal those in :probs, or are all equal if :probs is not given. If :y is provided, it must be a sequence of integers that is the same length as x. A contingency table is computed from x and :y. Then, Pearson's chi-squared test of the null hypothesis that the joint distribution of the cell counts in a 2-dimensional contingency table is the product of the row and column marginals is performed. By default the Yates' continuity correction for 2x2 contingency tables is performed, this can be disabled by setting the :correct option to false. Options: :x -- a sequence of numbers. :y -- a sequence of numbers :table -- a contigency table. If one dimensional, the test is a goodness-of-fit :probs (when (nil? y) -- (repeat n-levels (/ n-levels))) :freq (default nil) -- if given, these are rescaled to probabilities :correct (default true) -- use Yates' correction for continuity for 2x2 contingency tables Returns: :X-sq -- the Pearson X-squared test statistics :p-value -- the p-value for the test statistic :df -- the degress of freedom Examples: (use '(incanter core stats)) (chisq-test :x [1 2 3 2 3 2 4 3 5]) ;; X-sq 2.6667 ;; create a one-dimensional table of this data (def table (matrix [1 3 3 1 1])) (chisq-test :table table) ;; X-sq 2.6667 (chisq-test :table (trans table)) ;; throws exception (chisq-test :x [1 0 0 0 1 1 1 0 0 1 0 0 1 1 1 1]) ;; 0.25 (use '(incanter core stats datasets)) (def math-prog (to-matrix (get-dataset :math-prog))) (def x (sel math-prog :cols 1)) (def y (sel math-prog :cols 2)) (chisq-test :x x :y y) ;; X-sq = 1.24145, df=1, p-value = 0.26519 (chisq-test :x x :y y :correct false) ;; X-sq = 2.01094, df=1, p-value = 0.15617 (def table (matrix [[31 12] [9 8]])) (chisq-test :table table) ;; X-sq = 1.24145, df=1, p-value = 0.26519 (chisq-test :table table :correct false) ;; X-sq = 2.01094, df=1, p-value = 0.15617 ;; use the detabulate function to create data rows corresponding to the table (def detab (detabulate :table table)) (chisq-test :x (sel detab :cols 0) :y (sel detab :cols 1)) ;; look at the hair-eye-color data ;; turn the count data for males into a contigency table (def male (matrix (sel (get-dataset :hair-eye-color) :cols 3 :rows (range 16)) 4)) (chisq-test :table male) ;; X-sq = 41.280, df = 9, p-value = 4.44E-6 ;; turn the count data for females into a contigency table (def female (matrix (sel (get-dataset :hair-eye-color) :cols 3 :rows (range 16 32)) 4)) (chisq-test :table female) ;; X-sq = 106.664, df = 9, p-value = 7.014E-19, ;; supply probabilities to goodness-of-fit test (def table [89 37 30 28 2]) (def probs [0.40 0.20 0.20 0.19 0.01]) (chisq-test :table table :probs probs) ;; X-sq = 5.7947, df = 4, p-value = 0.215 ;; use frequencies instead of probabilities (def freq [40 20 20 15 5]) (chisq-test :table table :freq freq) ;; X-sq = 9.9901, df = 4, p-value = 0.04059 References: http://www.itl.nist.gov/div898/handbook/eda/section3/eda35f.htm http://en.wikipedia.org/wiki/Pearson's_chi-square_test http://en.wikipedia.org/wiki/Yates'_chi-square_test " ([& options] (let [opts (when options (apply assoc {} options)) correct (if (false? (:correct opts)) false true) x (:x opts) y (:y opts) table? (if (:table opts) true false) xtab (when (or x y) (if y (tabulate (bind-columns x y)) (tabulate x))) table (cond table? (:table opts) (and x y) (:table xtab)) two-samp? (if (or (and x y) (and table? (and (> (nrow table) 1) (> (ncol table) 1)))) true false) r-levels (if table? (range (nrow table)) (first (:levels xtab))) c-levels (if table? (range (ncol table)) (second (:levels xtab))) r-margins (if table? (if two-samp? (apply hash-map (interleave r-levels (map sum (trans table)))) (if (> (nrow table) 1) (to-list table) (throw (Exception. "One dimensional tables must have only a single column")))) (second (:margins xtab))) c-margins (if table? (if two-samp? (apply hash-map (interleave c-levels (map sum table))) 0) (first (:margins xtab))) counts (if two-samp? (vectorize table) table) N (if table? (sum counts) (:N xtab)) n (when (not two-samp?) (count r-levels)) df (if two-samp? (* (dec (nrow table)) (dec (ncol table))) (dec n)) probs (when (not two-samp?) (cond (:probs opts) (:probs opts) (:freq opts) (div (:freq opts) (sum (:freq opts))) :else (repeat n (/ n)))) E (if two-samp? (for [r r-levels c c-levels] (/ (* (c-margins c) (r-margins r)) N)) (mult N probs)) X-sq (if (and correct (and (= (count r-levels) 2) (= (count c-levels) 2))) (reduce + (map (fn [o e] (/ (pow (- (abs (- o e)) 0.5) 2) e)) counts E)) (reduce + (map (fn [o e] (/ (pow (- o e) 2) e)) counts E))) ] {:X-sq X-sq :df df :two-samp? two-samp? :p-value (cdf-chisq X-sq :df df :lower-tail false) :probs probs :N N :table table :col-levels c-levels :row-levels r-levels :col-margins c-margins :row-margins r-margins :E E}))) (defn principal-components " Performs a principal components analysis on the given data matrix. Equivalent to R's prcomp function. Returns: A map with the following fields: :std-dev -- the standard deviations of the principal compoenents (i.e. the square roots of the eigenvalues of the correlation matrix, though the calculation is actually done with the singular values of the data matrix. :rotation -- the matrix of variable loadings (i.e. a matrix whose columns contain the eigenvectors). Examples: (use '(incanter core stats charts datasets)) ;; load the iris dataset (def iris (to-matrix (get-dataset :iris))) ;; run the pca (def pca (principal-components (sel iris :cols (range 4)))) ;; extract the first two principal components (def pc1 (sel (:rotation pca) :cols 0)) (def pc2 (sel (:rotation pca) :cols 1)) ;; project the first four dimension of the iris data onto the first ;; two principal components (def x1 (mmult (sel iris :cols (range 4)) pc1)) (def x2 (mmult (sel iris :cols (range 4)) pc2)) ;; now plot the transformed data, coloring each species a different color (doto (scatter-plot (sel x1 :rows (range 50)) (sel x2 :rows (range 50)) :x-label \"PC1\" :y-label \"PC2\" :title \"Iris PCA\") (add-points (sel x1 :rows (range 50 100)) (sel x2 :rows (range 50 100))) (add-points (sel x1 :rows (range 100 150)) (sel x2 :rows (range 100 150))) view) ;; alternatively, the :group-by option can be used in scatter-plot (view (scatter-plot x1 x2 :group-by (sel iris :cols 4) :x-label \"PC1\" :y-label \"PC2\" :title \"Iris PCA\")) References: http://en.wikipedia.org/wiki/Principal_component_analysis " ([x & options] (let [svd (decomp-svd (correlation x)) rotation (:V svd) std-dev (sqrt (:S svd))] {:std-dev std-dev :rotation rotation}))) (defn detabulate " Take a contingency table of counts and returns a matrix of observations. Examples: (use '(incanter core stats datasets)) (def by-gender (group-by (get-dataset :hair-eye-color) 2)) (def table (matrix (sel (first by-gender) :cols 3) 4)) (detabulate :table table) (tabulate (detabulate :table table)) ;; example 2 (def data (matrix [[1 0] [1 1] [1 1] [1 0] [0 0] [1 1] [1 1] [1 0] [1 1]])) (tabulate data) (tabulate (detabulate :table (:table (tabulate data)))) " ([& options] (let [opts (when options (apply assoc {} options)) table (:table opts) row-labels (when table (or (:row-labels opts) (range (nrow table)))) col-labels (when table (or (:col-labels opts) (range (ncol table)))) data (apply bind-rows (apply concat (for [r row-labels c col-labels] (repeat (sel table :rows r :cols c) [r c]))))] data)))
[ { "context": "ms query-params\n :key \"page-1\"})\n (map\n (fn [i]\n (let [key (str", "end": 5799, "score": 0.8513243198394775, "start": 5793, "tag": "KEY", "value": "page-1" } ]
src/cljs/wombats_web_client/panels/games.cljs
emilyseibert/battle-bots-web-client
0
(ns wombats-web-client.panels.games (:require [cemerick.url :refer [map->query url]] [re-frame.core :as re-frame] [reagent.core :as reagent] [wombats-web-client.components.cards.game :refer [game-card]] [wombats-web-client.routes :refer [nav!]] [wombats-web-client.events.games :refer [get-games-query-params]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defonce empty-open-page "Sorry, there are no games to join at the moment.") (defonce empty-my-open-page "You haven’t joined any games yet.") (defonce empty-my-finished-page "None of your games have ended yet! Check back later.") (defonce empty-finished-page "No games have ended yet! Check back later.") (defonce total-items 4) ;; Number of items shown to the left and right of the page chooser ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- construct-query-params [{:keys [closed page mine]}] ;; Make sure that if page is invalid, replace it with a 1 (let [page (js/Number page) page (if (or (js/isNaN page) (< page 1)) 1 page)] (str "/?page=" page (when closed "&closed") (when mine "&mine")))) (defn- construct-nav-token [] (let [{:keys [closed page mine]} @(re-frame/subscribe [:games/query-params]) page (js/Number page)] (str "/?page=" page (when closed "&closed") (when mine "&mine")))) (defn- nav-open! [query-params] (let [updated-params (dissoc query-params :closed)] (nav! (construct-query-params updated-params)))) (defn- nav-finished! [query-params] (let [updated-params (merge query-params {:closed true})] (nav! (construct-query-params updated-params)))) (defn- toggle-mine! "This is triggered whenever you press SHOW MY GAMES" [{:keys [mine] :as query-params}] (nav! (construct-query-params (merge query-params {:mine (not mine)})))) (defn- page-link [query-params page-number] (construct-query-params (merge query-params {:page page-number}))) (defn- previous-page-link [{:keys [page] :as query-params}] (construct-query-params (merge query-params {:page (- (js/Number page) 1)}))) (defn- next-page-link [{:keys [page] :as query-params}] (construct-query-params {:page (+ (js/Number page) 1)})) (defn get-user-in-game [players current-user] (let [current-username (:user/github-username current-user)] (filter (fn [player] (let [user (:player/user player) github-username (:user/github-username user)] (= github-username current-username))) players))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Lifecycle Methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- query-params-on-change "Ensure the URL has valid query params" [query-params] (when-not query-params (nav! (construct-query-params query-params)))) (defn- update-component [query-params] (query-params-on-change query-params) (get-games-query-params query-params)) (defn- component-will-receive-props [this [_ query-params]] (update-component query-params)) (defn- component-will-mount [query-params] (update-component query-params)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Render Methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tab-view-toggle [query-params] (let [closed (:closed query-params)] [:div.tab-game-toggle [:div.game-tab {:class (when-not closed "active") :on-click #(nav-open! query-params)} "OPEN"] [:div.game-tab {:class (when closed "active") :on-click #(nav-finished! query-params)} "FINISHED"]])) (defn my-game-toggle [{:keys [mine] :as query-params}] [:div.my-game-toggle-wrapper {:on-click #(toggle-mine! query-params)} [:div.checkbox {:class (when mine "selected")}] [:div.desc "SHOW MY GAMES"]]) (defn get-empty-state [{:keys [closed mine]}] [:div.empty-text (cond (and closed mine) empty-my-finished-page (and (not closed) mine) empty-my-open-page (and closed (not mine)) empty-finished-page (and (not closed) (not mine)) empty-open-page)]) (defn- render-page-selector [{:keys [new-page page query-params key]}] (let [link (page-link query-params new-page)] [:a.page {:key key :class-name (when (= new-page page) "current") :href link :on-click #(do (.preventDefault %) (nav! link))} new-page])) (defn- page-selector-item-offset [{:keys [offset page query-params key]}] (let [new-page (+ page offset)] (render-page-selector {:new-page new-page :page page :query-params query-params :key key}))) (defn- calculate-offset "Given total-items and current index calculate the necessary offset" [total-items i] (get (vec (range (- (/ total-items 2)) (inc (/ total-items 2))))i)) (defn- render-ellipsis [key] [:span.page.ellipsis {:key key} "..."]) (defn- page-switcher [{:keys [page] :as query-params}] (let [prev-link (previous-page-link query-params) next-link (next-page-link query-params) page (js/Number page)] [:div.page-toggle [:a.nav-link {:class-name (when (= 1 page) "disabled") :href prev-link :on-click #(do (.preventDefault %) (nav! prev-link))} "PREVIOUS"] (render-page-selector {:new-page 1 :page page :query-params query-params :key "page-1"}) (map (fn [i] (let [key (str "page-" i)] (cond ;; First case: 2 3 4 5 ... (<= page 4) (if (= i total-items) (render-ellipsis key) (let [new-page (+ i 2)] (render-page-selector {:new-page new-page :page page :query-params query-params :key key}))) ;; Second case ... 4 5 6 ... (> page 4) (cond (or (zero? i) (= i total-items)) (render-ellipsis key) (= i (/ total-items 2)) (page-selector-item-offset {:offset 0 :page page :query-params query-params :key key}) (<= i (dec (/ total-items 2))) (page-selector-item-offset {:offset (calculate-offset total-items i) :page page :query-params query-params :key key}) (>= i (inc (/ total-items 2))) (page-selector-item-offset {:offset (calculate-offset total-items i) :page page :query-params query-params :key key}))))) (range 0 (inc total-items))) ;; TODO max length goes here [:a.nav-link {:href next-link :on-click #(do (.preventDefault %) (nav! next-link))} "NEXT"]])) (defn main-panel [query-params] (let [current-user (re-frame/subscribe [:current-user]) games (re-frame/subscribe [:games/games])] [:div.games-panel [:div.toggles [tab-view-toggle query-params] [my-game-toggle query-params]] [:div.games (if (empty? @games) [get-empty-state query-params] [:ul.games-list (doall (map (fn [[_ game]] (let [status (:game/status game) players (:game/players game) user-in-game (first (get-user-in-game players @current-user)) is-joinable (and (= :pending-open status) (nil? user-in-game)) is-full (= :pending-closed status) is-playing (or (= :active status) (= :active-intermission status)) num-joined (count players)] ^{:key (:game/id game)} [game-card game user-in-game is-joinable is-full is-playing num-joined])) @games))]) [page-switcher query-params]]])) (defn games [query-params] (reagent/create-class {:component-will-mount #(component-will-mount query-params) :component-will-receive-props component-will-receive-props :reagent-render (fn [query-params] [main-panel query-params])}))
90611
(ns wombats-web-client.panels.games (:require [cemerick.url :refer [map->query url]] [re-frame.core :as re-frame] [reagent.core :as reagent] [wombats-web-client.components.cards.game :refer [game-card]] [wombats-web-client.routes :refer [nav!]] [wombats-web-client.events.games :refer [get-games-query-params]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defonce empty-open-page "Sorry, there are no games to join at the moment.") (defonce empty-my-open-page "You haven’t joined any games yet.") (defonce empty-my-finished-page "None of your games have ended yet! Check back later.") (defonce empty-finished-page "No games have ended yet! Check back later.") (defonce total-items 4) ;; Number of items shown to the left and right of the page chooser ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- construct-query-params [{:keys [closed page mine]}] ;; Make sure that if page is invalid, replace it with a 1 (let [page (js/Number page) page (if (or (js/isNaN page) (< page 1)) 1 page)] (str "/?page=" page (when closed "&closed") (when mine "&mine")))) (defn- construct-nav-token [] (let [{:keys [closed page mine]} @(re-frame/subscribe [:games/query-params]) page (js/Number page)] (str "/?page=" page (when closed "&closed") (when mine "&mine")))) (defn- nav-open! [query-params] (let [updated-params (dissoc query-params :closed)] (nav! (construct-query-params updated-params)))) (defn- nav-finished! [query-params] (let [updated-params (merge query-params {:closed true})] (nav! (construct-query-params updated-params)))) (defn- toggle-mine! "This is triggered whenever you press SHOW MY GAMES" [{:keys [mine] :as query-params}] (nav! (construct-query-params (merge query-params {:mine (not mine)})))) (defn- page-link [query-params page-number] (construct-query-params (merge query-params {:page page-number}))) (defn- previous-page-link [{:keys [page] :as query-params}] (construct-query-params (merge query-params {:page (- (js/Number page) 1)}))) (defn- next-page-link [{:keys [page] :as query-params}] (construct-query-params {:page (+ (js/Number page) 1)})) (defn get-user-in-game [players current-user] (let [current-username (:user/github-username current-user)] (filter (fn [player] (let [user (:player/user player) github-username (:user/github-username user)] (= github-username current-username))) players))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Lifecycle Methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- query-params-on-change "Ensure the URL has valid query params" [query-params] (when-not query-params (nav! (construct-query-params query-params)))) (defn- update-component [query-params] (query-params-on-change query-params) (get-games-query-params query-params)) (defn- component-will-receive-props [this [_ query-params]] (update-component query-params)) (defn- component-will-mount [query-params] (update-component query-params)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Render Methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tab-view-toggle [query-params] (let [closed (:closed query-params)] [:div.tab-game-toggle [:div.game-tab {:class (when-not closed "active") :on-click #(nav-open! query-params)} "OPEN"] [:div.game-tab {:class (when closed "active") :on-click #(nav-finished! query-params)} "FINISHED"]])) (defn my-game-toggle [{:keys [mine] :as query-params}] [:div.my-game-toggle-wrapper {:on-click #(toggle-mine! query-params)} [:div.checkbox {:class (when mine "selected")}] [:div.desc "SHOW MY GAMES"]]) (defn get-empty-state [{:keys [closed mine]}] [:div.empty-text (cond (and closed mine) empty-my-finished-page (and (not closed) mine) empty-my-open-page (and closed (not mine)) empty-finished-page (and (not closed) (not mine)) empty-open-page)]) (defn- render-page-selector [{:keys [new-page page query-params key]}] (let [link (page-link query-params new-page)] [:a.page {:key key :class-name (when (= new-page page) "current") :href link :on-click #(do (.preventDefault %) (nav! link))} new-page])) (defn- page-selector-item-offset [{:keys [offset page query-params key]}] (let [new-page (+ page offset)] (render-page-selector {:new-page new-page :page page :query-params query-params :key key}))) (defn- calculate-offset "Given total-items and current index calculate the necessary offset" [total-items i] (get (vec (range (- (/ total-items 2)) (inc (/ total-items 2))))i)) (defn- render-ellipsis [key] [:span.page.ellipsis {:key key} "..."]) (defn- page-switcher [{:keys [page] :as query-params}] (let [prev-link (previous-page-link query-params) next-link (next-page-link query-params) page (js/Number page)] [:div.page-toggle [:a.nav-link {:class-name (when (= 1 page) "disabled") :href prev-link :on-click #(do (.preventDefault %) (nav! prev-link))} "PREVIOUS"] (render-page-selector {:new-page 1 :page page :query-params query-params :key "<KEY>"}) (map (fn [i] (let [key (str "page-" i)] (cond ;; First case: 2 3 4 5 ... (<= page 4) (if (= i total-items) (render-ellipsis key) (let [new-page (+ i 2)] (render-page-selector {:new-page new-page :page page :query-params query-params :key key}))) ;; Second case ... 4 5 6 ... (> page 4) (cond (or (zero? i) (= i total-items)) (render-ellipsis key) (= i (/ total-items 2)) (page-selector-item-offset {:offset 0 :page page :query-params query-params :key key}) (<= i (dec (/ total-items 2))) (page-selector-item-offset {:offset (calculate-offset total-items i) :page page :query-params query-params :key key}) (>= i (inc (/ total-items 2))) (page-selector-item-offset {:offset (calculate-offset total-items i) :page page :query-params query-params :key key}))))) (range 0 (inc total-items))) ;; TODO max length goes here [:a.nav-link {:href next-link :on-click #(do (.preventDefault %) (nav! next-link))} "NEXT"]])) (defn main-panel [query-params] (let [current-user (re-frame/subscribe [:current-user]) games (re-frame/subscribe [:games/games])] [:div.games-panel [:div.toggles [tab-view-toggle query-params] [my-game-toggle query-params]] [:div.games (if (empty? @games) [get-empty-state query-params] [:ul.games-list (doall (map (fn [[_ game]] (let [status (:game/status game) players (:game/players game) user-in-game (first (get-user-in-game players @current-user)) is-joinable (and (= :pending-open status) (nil? user-in-game)) is-full (= :pending-closed status) is-playing (or (= :active status) (= :active-intermission status)) num-joined (count players)] ^{:key (:game/id game)} [game-card game user-in-game is-joinable is-full is-playing num-joined])) @games))]) [page-switcher query-params]]])) (defn games [query-params] (reagent/create-class {:component-will-mount #(component-will-mount query-params) :component-will-receive-props component-will-receive-props :reagent-render (fn [query-params] [main-panel query-params])}))
true
(ns wombats-web-client.panels.games (:require [cemerick.url :refer [map->query url]] [re-frame.core :as re-frame] [reagent.core :as reagent] [wombats-web-client.components.cards.game :refer [game-card]] [wombats-web-client.routes :refer [nav!]] [wombats-web-client.events.games :refer [get-games-query-params]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defonce empty-open-page "Sorry, there are no games to join at the moment.") (defonce empty-my-open-page "You haven’t joined any games yet.") (defonce empty-my-finished-page "None of your games have ended yet! Check back later.") (defonce empty-finished-page "No games have ended yet! Check back later.") (defonce total-items 4) ;; Number of items shown to the left and right of the page chooser ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- construct-query-params [{:keys [closed page mine]}] ;; Make sure that if page is invalid, replace it with a 1 (let [page (js/Number page) page (if (or (js/isNaN page) (< page 1)) 1 page)] (str "/?page=" page (when closed "&closed") (when mine "&mine")))) (defn- construct-nav-token [] (let [{:keys [closed page mine]} @(re-frame/subscribe [:games/query-params]) page (js/Number page)] (str "/?page=" page (when closed "&closed") (when mine "&mine")))) (defn- nav-open! [query-params] (let [updated-params (dissoc query-params :closed)] (nav! (construct-query-params updated-params)))) (defn- nav-finished! [query-params] (let [updated-params (merge query-params {:closed true})] (nav! (construct-query-params updated-params)))) (defn- toggle-mine! "This is triggered whenever you press SHOW MY GAMES" [{:keys [mine] :as query-params}] (nav! (construct-query-params (merge query-params {:mine (not mine)})))) (defn- page-link [query-params page-number] (construct-query-params (merge query-params {:page page-number}))) (defn- previous-page-link [{:keys [page] :as query-params}] (construct-query-params (merge query-params {:page (- (js/Number page) 1)}))) (defn- next-page-link [{:keys [page] :as query-params}] (construct-query-params {:page (+ (js/Number page) 1)})) (defn get-user-in-game [players current-user] (let [current-username (:user/github-username current-user)] (filter (fn [player] (let [user (:player/user player) github-username (:user/github-username user)] (= github-username current-username))) players))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Lifecycle Methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- query-params-on-change "Ensure the URL has valid query params" [query-params] (when-not query-params (nav! (construct-query-params query-params)))) (defn- update-component [query-params] (query-params-on-change query-params) (get-games-query-params query-params)) (defn- component-will-receive-props [this [_ query-params]] (update-component query-params)) (defn- component-will-mount [query-params] (update-component query-params)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Render Methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tab-view-toggle [query-params] (let [closed (:closed query-params)] [:div.tab-game-toggle [:div.game-tab {:class (when-not closed "active") :on-click #(nav-open! query-params)} "OPEN"] [:div.game-tab {:class (when closed "active") :on-click #(nav-finished! query-params)} "FINISHED"]])) (defn my-game-toggle [{:keys [mine] :as query-params}] [:div.my-game-toggle-wrapper {:on-click #(toggle-mine! query-params)} [:div.checkbox {:class (when mine "selected")}] [:div.desc "SHOW MY GAMES"]]) (defn get-empty-state [{:keys [closed mine]}] [:div.empty-text (cond (and closed mine) empty-my-finished-page (and (not closed) mine) empty-my-open-page (and closed (not mine)) empty-finished-page (and (not closed) (not mine)) empty-open-page)]) (defn- render-page-selector [{:keys [new-page page query-params key]}] (let [link (page-link query-params new-page)] [:a.page {:key key :class-name (when (= new-page page) "current") :href link :on-click #(do (.preventDefault %) (nav! link))} new-page])) (defn- page-selector-item-offset [{:keys [offset page query-params key]}] (let [new-page (+ page offset)] (render-page-selector {:new-page new-page :page page :query-params query-params :key key}))) (defn- calculate-offset "Given total-items and current index calculate the necessary offset" [total-items i] (get (vec (range (- (/ total-items 2)) (inc (/ total-items 2))))i)) (defn- render-ellipsis [key] [:span.page.ellipsis {:key key} "..."]) (defn- page-switcher [{:keys [page] :as query-params}] (let [prev-link (previous-page-link query-params) next-link (next-page-link query-params) page (js/Number page)] [:div.page-toggle [:a.nav-link {:class-name (when (= 1 page) "disabled") :href prev-link :on-click #(do (.preventDefault %) (nav! prev-link))} "PREVIOUS"] (render-page-selector {:new-page 1 :page page :query-params query-params :key "PI:KEY:<KEY>END_PI"}) (map (fn [i] (let [key (str "page-" i)] (cond ;; First case: 2 3 4 5 ... (<= page 4) (if (= i total-items) (render-ellipsis key) (let [new-page (+ i 2)] (render-page-selector {:new-page new-page :page page :query-params query-params :key key}))) ;; Second case ... 4 5 6 ... (> page 4) (cond (or (zero? i) (= i total-items)) (render-ellipsis key) (= i (/ total-items 2)) (page-selector-item-offset {:offset 0 :page page :query-params query-params :key key}) (<= i (dec (/ total-items 2))) (page-selector-item-offset {:offset (calculate-offset total-items i) :page page :query-params query-params :key key}) (>= i (inc (/ total-items 2))) (page-selector-item-offset {:offset (calculate-offset total-items i) :page page :query-params query-params :key key}))))) (range 0 (inc total-items))) ;; TODO max length goes here [:a.nav-link {:href next-link :on-click #(do (.preventDefault %) (nav! next-link))} "NEXT"]])) (defn main-panel [query-params] (let [current-user (re-frame/subscribe [:current-user]) games (re-frame/subscribe [:games/games])] [:div.games-panel [:div.toggles [tab-view-toggle query-params] [my-game-toggle query-params]] [:div.games (if (empty? @games) [get-empty-state query-params] [:ul.games-list (doall (map (fn [[_ game]] (let [status (:game/status game) players (:game/players game) user-in-game (first (get-user-in-game players @current-user)) is-joinable (and (= :pending-open status) (nil? user-in-game)) is-full (= :pending-closed status) is-playing (or (= :active status) (= :active-intermission status)) num-joined (count players)] ^{:key (:game/id game)} [game-card game user-in-game is-joinable is-full is-playing num-joined])) @games))]) [page-switcher query-params]]])) (defn games [query-params] (reagent/create-class {:component-will-mount #(component-will-mount query-params) :component-will-receive-props component-will-receive-props :reagent-render (fn [query-params] [main-panel query-params])}))
[ { "context": "nsols.nlparse.config]] namespace.\"\n :author \"Paul Landes\"}\n zensols.nlparse.parse\n (:require [clojure.", "end": 383, "score": 0.9998921155929565, "start": 372, "tag": "NAME", "value": "Paul Landes" }, { "context": "annotations are [given\n here](https://github.com/plandes/clj-nlp-parse/blob/master/doc/annotation-definiti", "end": 4140, "score": 0.9986139535903931, "start": 4133, "tag": "USERNAME", "value": "plandes" }, { "context": ").\n\n See [test\n token-regex](https://github.com/plandes/clj-nlp-parse/blob/v0.0.11/test-resources/token-r", "end": 4253, "score": 0.9975872039794922, "start": 4246, "tag": "USERNAME", "value": "plandes" } ]
src/clojure/zensols/nlparse/parse.clj
plandes/clj-nlp-parse
33
(ns ^{:doc "Parse an utterance using the Stanford CoreNLP and the ClearNLP SRL. This is the main client entry point to the package. A default out of the box parser works that comes with components listed in [[zensols.nlparse.config/all-components]]. If you want to customzie or add your own parser plug in, see the [[zensols.nlparse.config]] namespace." :author "Paul Landes"} zensols.nlparse.parse (:require [clojure.string :as str] [clojure.tools.logging :as log] [clojure.set :as set]) (:require [zensols.actioncli.util :refer (trunc with-timeout)]) (:require [zensols.nlparse.config :as conf] [zensols.nlparse.stanford :as sp] [zensols.nlparse.srl :as srl])) (def sentimnet-labels "All labels returned by [[sentiment-score-to-label]] in order of positive to negative." ["very positive" "positive" "very negative" "negative" "neutral"]) (def penn-treebank-pos-tags "Alphabetical list of part-of-speech tags used in the [Penn Treebank Project](https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html)." {"CC" "Coordinating conjunction" "CD" "Cardinal number" "DT" "Determiner" "EX" "Existential there" "FW" "Foreign word" "IN" "Preposition or subordinating conjunction" "JJ" "Adjective" "JJR" "Adjective, comparative" "JJS" "Adjective, superlative" "LS" "List item marker" "MD" "Modal" "NN" "Noun, singular or mass" "NNS" "Noun, plural" "NNP" "Proper noun, singular" "NNPS" "Proper noun, plural" "PDT" "Predeterminer" "POS" "Possessive ending" "PRP" "Personal pronoun" "PRP$" "Possessive pronoun" "RB" "Adverb" "RBR" "Adverb, comparative" "RBS" "Adverb, superlative" "RP" "Particle" "SYM" "Symbol" "TO" "to" "UH" "Interjection" "VB" "Verb, base form" "VBD" "Verb, past tense" "VBG" "Verb, gerund or present participle" "VBN" "Verb, past participle" "VBP" "Verb, non-3rd person singular present" "VBZ" "Verb, 3rd person singular present" "WDT" "Wh-determiner" "WP" "Wh-pronoun" "WP$" "Possessive wh-pronoun" "WRB" "Wh-adverb"}) (defn pos-description "Get a human readable description of *pos-tag*." [pos-tag] (get penn-treebank-pos-tags pos-tag)) ;; POS tag adjust (def ^:private noun-tags #{"NN" "NNS" "NNP" "NNPS"}) (def ^:private verb-tags #{"VB" "VBD" "VBG" "VBN" "VBP" "VBZ"}) (def ^:private adjective-tags #{"JJ" "JJR" "JJS"}) (def ^:private adverb-tags #{"RB" "RBR" "RBS" "WRB"}) (def ^:private pos-tag-list #{"$" "#" "''" "," "-LRB-" "-RRB-" "." ":" "CC" "CD" "DT" "IN" "JJ" "MD" "NN" "NNP" "NNPS" "NNS" "PDT" "POS" "PRP" "RB" "RP" "SYM" "VB" "VBD" "VBG" "VBN" "VBP" "VBZ" "LS"}) (def ^:private wh-tags #{"WDT" "WRB" "WP" "WP$"}) (defn pos-tags "Get a sequence of POS tags based on **type** (if given) and all otherwise. **type** is a symbol and one of `noun`, `verb`, `adjective`, `adverb`, and `wh`. See [[pos-tag-types]]." ([type] (case type noun noun-tags verb verb-tags adjective adjective-tags adverb adverb-tags wh wh-tags)) ([] (set/union (set (keys penn-treebank-pos-tags)) pos-tag-list))) (defn pos-tag-types "Return types of POS tags (i.e. `noun`, `verb`, etc). See [[pos-tags]]." [] #{"noun" "verb" "adjective" "adverb" "wh"}) (defn pos-tag-type "Return the POS tag type (ie. `verb` yeilds `VB`). The return (function range) is the input to [[pos-tags]]." [tag] (->> (map (fn [type] (if (contains? (pos-tags type) tag) type)) '(noun verb adjective adverb wh)) (remove nil?) first)) (defn- parse-no-timeout [utterance] (->> (conf/parse-functions) (reduce (fn [last-res parse-fn] (log/debugf "next parser: %s" parse-fn) (parse-fn last-res)) utterance))) (defn parse "Parse natural language **utterance** returning a symbol expression tree of it's meaning. This returns a symbolic expression (map of maps). A definition of these and structure of these annotations are [given here](https://github.com/plandes/clj-nlp-parse/blob/master/doc/annotation-definitions.md). See [test token-regex](https://github.com/plandes/clj-nlp-parse/blob/v0.0.11/test-resources/token-regex.txt#L3) for example of `entity-tag`." [utterance] (let [timeout-millis (conf/parse-timeout)] (log/infof "parsing (t=%s): <%s>" (or timeout-millis "inf") (trunc utterance)) (if timeout-millis (with-timeout timeout-millis (parse-no-timeout utterance)) (parse-no-timeout utterance)))) (defn tokens "Get all tokens across all sentences." [panon] (->> panon :sents (map :tokens) (apply concat))) (defn token "Get the 0-based **index**th token." [panon index] (nth (tokens panon) index)) (defn sent "Get the 0-based **index**th sentence." [panon index] (nth (:sents panon) index)) (defn root-dependency "Get the text of the root node of the dependency tree." [sent] (->> sent :dependency-parse-tree first :token-index dec (nth (:tokens sent)))) (defn overlap? "Return whether two ranges overlap inclusively. Both parameters have the form: `[start end]`." [a b] (let [[sa ea] a [sb eb] b] (and (<= sa eb) (<= sb ea)))) (defn in-range? "Return whether **inner** range sits in inclusive range **outter**. Both parameters have the form: `[start end]`." [outter inner] (let [[so eo] outter [si ei] inner] (and (>= si so) (<= ei eo)))) (defn token-in-range? "Return whether token **tok** is in tuple **range**." [token range] (in-range? range (:token-range token))) (defn mentions "Get all mentions from parse annotation **panon**. Keys ---- * **:mention-keys** top level keys of mentions to use and defaults to `[:mentions :tok-re-mentions]`" [panon & {:keys [mention-keys] :or {mention-keys [:mentions :tok-re-mentions]}}] (->> mention-keys (map #(get panon %)) (apply concat))) (defn mention-for-token "Return a mention for token **tok** (if any)." [panon token] (->> (:mentions panon) (filter #(->> % :token-range (token-in-range? token))))) (defn tokens-by-sentence "Return the tokens for **sent-index** in the **token-range**." [panon sent-index token-range] (let [sent (-> panon :sents (nth sent-index) :tokens)] (->> sent (drop (first token-range)) (take (- (second token-range) (first token-range)))))) (defn tokens-for-mention "Return tokens for **mention**." [panon mention] (let [{:keys [token-range sent-index]} mention sents (->> panon :sents)] (when (and mention (< sent-index (count sents))) (->> sents (#(nth % sent-index)) :tokens (filter #(token-in-range? % (:token-range mention))))))) (defn token-mentions "Return mentions with a `:tokens` key that includes token maps from the sentence level." ([panon] (token-mentions panon (mentions panon))) ([panon mentions] (->> mentions (map (fn [mention] (->> mention (tokens-for-mention panon) (assoc mention :tokens))))))) (defn sentiment-score-to-label "Create a human readable tag from the sentiment score. See [[sentimnet-labels]]." [sentiment-score] (cond (nil? sentiment-score) nil (> sentiment-score 1) "very positive" (= sentiment-score 1) "positive" (< sentiment-score -1) "very negative" (= sentiment-score -1) "negative" (= 0 sentiment-score) "neutral"))
3657
(ns ^{:doc "Parse an utterance using the Stanford CoreNLP and the ClearNLP SRL. This is the main client entry point to the package. A default out of the box parser works that comes with components listed in [[zensols.nlparse.config/all-components]]. If you want to customzie or add your own parser plug in, see the [[zensols.nlparse.config]] namespace." :author "<NAME>"} zensols.nlparse.parse (:require [clojure.string :as str] [clojure.tools.logging :as log] [clojure.set :as set]) (:require [zensols.actioncli.util :refer (trunc with-timeout)]) (:require [zensols.nlparse.config :as conf] [zensols.nlparse.stanford :as sp] [zensols.nlparse.srl :as srl])) (def sentimnet-labels "All labels returned by [[sentiment-score-to-label]] in order of positive to negative." ["very positive" "positive" "very negative" "negative" "neutral"]) (def penn-treebank-pos-tags "Alphabetical list of part-of-speech tags used in the [Penn Treebank Project](https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html)." {"CC" "Coordinating conjunction" "CD" "Cardinal number" "DT" "Determiner" "EX" "Existential there" "FW" "Foreign word" "IN" "Preposition or subordinating conjunction" "JJ" "Adjective" "JJR" "Adjective, comparative" "JJS" "Adjective, superlative" "LS" "List item marker" "MD" "Modal" "NN" "Noun, singular or mass" "NNS" "Noun, plural" "NNP" "Proper noun, singular" "NNPS" "Proper noun, plural" "PDT" "Predeterminer" "POS" "Possessive ending" "PRP" "Personal pronoun" "PRP$" "Possessive pronoun" "RB" "Adverb" "RBR" "Adverb, comparative" "RBS" "Adverb, superlative" "RP" "Particle" "SYM" "Symbol" "TO" "to" "UH" "Interjection" "VB" "Verb, base form" "VBD" "Verb, past tense" "VBG" "Verb, gerund or present participle" "VBN" "Verb, past participle" "VBP" "Verb, non-3rd person singular present" "VBZ" "Verb, 3rd person singular present" "WDT" "Wh-determiner" "WP" "Wh-pronoun" "WP$" "Possessive wh-pronoun" "WRB" "Wh-adverb"}) (defn pos-description "Get a human readable description of *pos-tag*." [pos-tag] (get penn-treebank-pos-tags pos-tag)) ;; POS tag adjust (def ^:private noun-tags #{"NN" "NNS" "NNP" "NNPS"}) (def ^:private verb-tags #{"VB" "VBD" "VBG" "VBN" "VBP" "VBZ"}) (def ^:private adjective-tags #{"JJ" "JJR" "JJS"}) (def ^:private adverb-tags #{"RB" "RBR" "RBS" "WRB"}) (def ^:private pos-tag-list #{"$" "#" "''" "," "-LRB-" "-RRB-" "." ":" "CC" "CD" "DT" "IN" "JJ" "MD" "NN" "NNP" "NNPS" "NNS" "PDT" "POS" "PRP" "RB" "RP" "SYM" "VB" "VBD" "VBG" "VBN" "VBP" "VBZ" "LS"}) (def ^:private wh-tags #{"WDT" "WRB" "WP" "WP$"}) (defn pos-tags "Get a sequence of POS tags based on **type** (if given) and all otherwise. **type** is a symbol and one of `noun`, `verb`, `adjective`, `adverb`, and `wh`. See [[pos-tag-types]]." ([type] (case type noun noun-tags verb verb-tags adjective adjective-tags adverb adverb-tags wh wh-tags)) ([] (set/union (set (keys penn-treebank-pos-tags)) pos-tag-list))) (defn pos-tag-types "Return types of POS tags (i.e. `noun`, `verb`, etc). See [[pos-tags]]." [] #{"noun" "verb" "adjective" "adverb" "wh"}) (defn pos-tag-type "Return the POS tag type (ie. `verb` yeilds `VB`). The return (function range) is the input to [[pos-tags]]." [tag] (->> (map (fn [type] (if (contains? (pos-tags type) tag) type)) '(noun verb adjective adverb wh)) (remove nil?) first)) (defn- parse-no-timeout [utterance] (->> (conf/parse-functions) (reduce (fn [last-res parse-fn] (log/debugf "next parser: %s" parse-fn) (parse-fn last-res)) utterance))) (defn parse "Parse natural language **utterance** returning a symbol expression tree of it's meaning. This returns a symbolic expression (map of maps). A definition of these and structure of these annotations are [given here](https://github.com/plandes/clj-nlp-parse/blob/master/doc/annotation-definitions.md). See [test token-regex](https://github.com/plandes/clj-nlp-parse/blob/v0.0.11/test-resources/token-regex.txt#L3) for example of `entity-tag`." [utterance] (let [timeout-millis (conf/parse-timeout)] (log/infof "parsing (t=%s): <%s>" (or timeout-millis "inf") (trunc utterance)) (if timeout-millis (with-timeout timeout-millis (parse-no-timeout utterance)) (parse-no-timeout utterance)))) (defn tokens "Get all tokens across all sentences." [panon] (->> panon :sents (map :tokens) (apply concat))) (defn token "Get the 0-based **index**th token." [panon index] (nth (tokens panon) index)) (defn sent "Get the 0-based **index**th sentence." [panon index] (nth (:sents panon) index)) (defn root-dependency "Get the text of the root node of the dependency tree." [sent] (->> sent :dependency-parse-tree first :token-index dec (nth (:tokens sent)))) (defn overlap? "Return whether two ranges overlap inclusively. Both parameters have the form: `[start end]`." [a b] (let [[sa ea] a [sb eb] b] (and (<= sa eb) (<= sb ea)))) (defn in-range? "Return whether **inner** range sits in inclusive range **outter**. Both parameters have the form: `[start end]`." [outter inner] (let [[so eo] outter [si ei] inner] (and (>= si so) (<= ei eo)))) (defn token-in-range? "Return whether token **tok** is in tuple **range**." [token range] (in-range? range (:token-range token))) (defn mentions "Get all mentions from parse annotation **panon**. Keys ---- * **:mention-keys** top level keys of mentions to use and defaults to `[:mentions :tok-re-mentions]`" [panon & {:keys [mention-keys] :or {mention-keys [:mentions :tok-re-mentions]}}] (->> mention-keys (map #(get panon %)) (apply concat))) (defn mention-for-token "Return a mention for token **tok** (if any)." [panon token] (->> (:mentions panon) (filter #(->> % :token-range (token-in-range? token))))) (defn tokens-by-sentence "Return the tokens for **sent-index** in the **token-range**." [panon sent-index token-range] (let [sent (-> panon :sents (nth sent-index) :tokens)] (->> sent (drop (first token-range)) (take (- (second token-range) (first token-range)))))) (defn tokens-for-mention "Return tokens for **mention**." [panon mention] (let [{:keys [token-range sent-index]} mention sents (->> panon :sents)] (when (and mention (< sent-index (count sents))) (->> sents (#(nth % sent-index)) :tokens (filter #(token-in-range? % (:token-range mention))))))) (defn token-mentions "Return mentions with a `:tokens` key that includes token maps from the sentence level." ([panon] (token-mentions panon (mentions panon))) ([panon mentions] (->> mentions (map (fn [mention] (->> mention (tokens-for-mention panon) (assoc mention :tokens))))))) (defn sentiment-score-to-label "Create a human readable tag from the sentiment score. See [[sentimnet-labels]]." [sentiment-score] (cond (nil? sentiment-score) nil (> sentiment-score 1) "very positive" (= sentiment-score 1) "positive" (< sentiment-score -1) "very negative" (= sentiment-score -1) "negative" (= 0 sentiment-score) "neutral"))
true
(ns ^{:doc "Parse an utterance using the Stanford CoreNLP and the ClearNLP SRL. This is the main client entry point to the package. A default out of the box parser works that comes with components listed in [[zensols.nlparse.config/all-components]]. If you want to customzie or add your own parser plug in, see the [[zensols.nlparse.config]] namespace." :author "PI:NAME:<NAME>END_PI"} zensols.nlparse.parse (:require [clojure.string :as str] [clojure.tools.logging :as log] [clojure.set :as set]) (:require [zensols.actioncli.util :refer (trunc with-timeout)]) (:require [zensols.nlparse.config :as conf] [zensols.nlparse.stanford :as sp] [zensols.nlparse.srl :as srl])) (def sentimnet-labels "All labels returned by [[sentiment-score-to-label]] in order of positive to negative." ["very positive" "positive" "very negative" "negative" "neutral"]) (def penn-treebank-pos-tags "Alphabetical list of part-of-speech tags used in the [Penn Treebank Project](https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html)." {"CC" "Coordinating conjunction" "CD" "Cardinal number" "DT" "Determiner" "EX" "Existential there" "FW" "Foreign word" "IN" "Preposition or subordinating conjunction" "JJ" "Adjective" "JJR" "Adjective, comparative" "JJS" "Adjective, superlative" "LS" "List item marker" "MD" "Modal" "NN" "Noun, singular or mass" "NNS" "Noun, plural" "NNP" "Proper noun, singular" "NNPS" "Proper noun, plural" "PDT" "Predeterminer" "POS" "Possessive ending" "PRP" "Personal pronoun" "PRP$" "Possessive pronoun" "RB" "Adverb" "RBR" "Adverb, comparative" "RBS" "Adverb, superlative" "RP" "Particle" "SYM" "Symbol" "TO" "to" "UH" "Interjection" "VB" "Verb, base form" "VBD" "Verb, past tense" "VBG" "Verb, gerund or present participle" "VBN" "Verb, past participle" "VBP" "Verb, non-3rd person singular present" "VBZ" "Verb, 3rd person singular present" "WDT" "Wh-determiner" "WP" "Wh-pronoun" "WP$" "Possessive wh-pronoun" "WRB" "Wh-adverb"}) (defn pos-description "Get a human readable description of *pos-tag*." [pos-tag] (get penn-treebank-pos-tags pos-tag)) ;; POS tag adjust (def ^:private noun-tags #{"NN" "NNS" "NNP" "NNPS"}) (def ^:private verb-tags #{"VB" "VBD" "VBG" "VBN" "VBP" "VBZ"}) (def ^:private adjective-tags #{"JJ" "JJR" "JJS"}) (def ^:private adverb-tags #{"RB" "RBR" "RBS" "WRB"}) (def ^:private pos-tag-list #{"$" "#" "''" "," "-LRB-" "-RRB-" "." ":" "CC" "CD" "DT" "IN" "JJ" "MD" "NN" "NNP" "NNPS" "NNS" "PDT" "POS" "PRP" "RB" "RP" "SYM" "VB" "VBD" "VBG" "VBN" "VBP" "VBZ" "LS"}) (def ^:private wh-tags #{"WDT" "WRB" "WP" "WP$"}) (defn pos-tags "Get a sequence of POS tags based on **type** (if given) and all otherwise. **type** is a symbol and one of `noun`, `verb`, `adjective`, `adverb`, and `wh`. See [[pos-tag-types]]." ([type] (case type noun noun-tags verb verb-tags adjective adjective-tags adverb adverb-tags wh wh-tags)) ([] (set/union (set (keys penn-treebank-pos-tags)) pos-tag-list))) (defn pos-tag-types "Return types of POS tags (i.e. `noun`, `verb`, etc). See [[pos-tags]]." [] #{"noun" "verb" "adjective" "adverb" "wh"}) (defn pos-tag-type "Return the POS tag type (ie. `verb` yeilds `VB`). The return (function range) is the input to [[pos-tags]]." [tag] (->> (map (fn [type] (if (contains? (pos-tags type) tag) type)) '(noun verb adjective adverb wh)) (remove nil?) first)) (defn- parse-no-timeout [utterance] (->> (conf/parse-functions) (reduce (fn [last-res parse-fn] (log/debugf "next parser: %s" parse-fn) (parse-fn last-res)) utterance))) (defn parse "Parse natural language **utterance** returning a symbol expression tree of it's meaning. This returns a symbolic expression (map of maps). A definition of these and structure of these annotations are [given here](https://github.com/plandes/clj-nlp-parse/blob/master/doc/annotation-definitions.md). See [test token-regex](https://github.com/plandes/clj-nlp-parse/blob/v0.0.11/test-resources/token-regex.txt#L3) for example of `entity-tag`." [utterance] (let [timeout-millis (conf/parse-timeout)] (log/infof "parsing (t=%s): <%s>" (or timeout-millis "inf") (trunc utterance)) (if timeout-millis (with-timeout timeout-millis (parse-no-timeout utterance)) (parse-no-timeout utterance)))) (defn tokens "Get all tokens across all sentences." [panon] (->> panon :sents (map :tokens) (apply concat))) (defn token "Get the 0-based **index**th token." [panon index] (nth (tokens panon) index)) (defn sent "Get the 0-based **index**th sentence." [panon index] (nth (:sents panon) index)) (defn root-dependency "Get the text of the root node of the dependency tree." [sent] (->> sent :dependency-parse-tree first :token-index dec (nth (:tokens sent)))) (defn overlap? "Return whether two ranges overlap inclusively. Both parameters have the form: `[start end]`." [a b] (let [[sa ea] a [sb eb] b] (and (<= sa eb) (<= sb ea)))) (defn in-range? "Return whether **inner** range sits in inclusive range **outter**. Both parameters have the form: `[start end]`." [outter inner] (let [[so eo] outter [si ei] inner] (and (>= si so) (<= ei eo)))) (defn token-in-range? "Return whether token **tok** is in tuple **range**." [token range] (in-range? range (:token-range token))) (defn mentions "Get all mentions from parse annotation **panon**. Keys ---- * **:mention-keys** top level keys of mentions to use and defaults to `[:mentions :tok-re-mentions]`" [panon & {:keys [mention-keys] :or {mention-keys [:mentions :tok-re-mentions]}}] (->> mention-keys (map #(get panon %)) (apply concat))) (defn mention-for-token "Return a mention for token **tok** (if any)." [panon token] (->> (:mentions panon) (filter #(->> % :token-range (token-in-range? token))))) (defn tokens-by-sentence "Return the tokens for **sent-index** in the **token-range**." [panon sent-index token-range] (let [sent (-> panon :sents (nth sent-index) :tokens)] (->> sent (drop (first token-range)) (take (- (second token-range) (first token-range)))))) (defn tokens-for-mention "Return tokens for **mention**." [panon mention] (let [{:keys [token-range sent-index]} mention sents (->> panon :sents)] (when (and mention (< sent-index (count sents))) (->> sents (#(nth % sent-index)) :tokens (filter #(token-in-range? % (:token-range mention))))))) (defn token-mentions "Return mentions with a `:tokens` key that includes token maps from the sentence level." ([panon] (token-mentions panon (mentions panon))) ([panon mentions] (->> mentions (map (fn [mention] (->> mention (tokens-for-mention panon) (assoc mention :tokens))))))) (defn sentiment-score-to-label "Create a human readable tag from the sentiment score. See [[sentimnet-labels]]." [sentiment-score] (cond (nil? sentiment-score) nil (> sentiment-score 1) "very positive" (= sentiment-score 1) "positive" (< sentiment-score -1) "very negative" (= sentiment-score -1) "negative" (= 0 sentiment-score) "neutral"))
[ { "context": "n\n :email email\n :name name\n :password password\n :enabled? enabled\n :created-at created_a", "end": 607, "score": 0.9970733523368835, "start": 599, "tag": "PASSWORD", "value": "password" } ]
src/cerber/mappers.clj
schmudde/cerber-oauth2-provider
52
(ns cerber.mappers (:require [cerber.helpers :as helpers] [taoensso.nippy :as nippy])) (defn row->token [row] (when-let [{:keys [client_id user_id login scope secret created_at expires_at]} row] {:client-id client_id :user-id user_id :login login :scope scope :secret secret :created-at created_at :expires-at expires_at})) (defn row->user [row] (when-let [{:keys [id login email name password roles created_at modified_at activated_at blocked_at enabled]} row] {:id id :login login :email email :name name :password password :enabled? enabled :created-at created_at :modified-at modified_at :activated-at activated_at :blocked-at blocked_at :roles (helpers/str->keywords roles)})) (defn row->session [row] (when-let [{:keys [sid content created_at expires_at]} row] {:sid sid :content (nippy/thaw content) :expires-at expires_at :created-at created_at})) (defn row->client [row] (when-let [{:keys [id secret info approved scopes grants redirects enabled created_at modified_at activated_at blocked_at]} row] {:id id :secret secret :info info :approved? approved :enabled? enabled :scopes (helpers/str->coll scopes) :grants (helpers/str->coll grants) :redirects (helpers/str->coll redirects) :created-at created_at :modified-at modified_at :activated-at activated_at :blocked-at blocked_at})) (defn row->authcode [row] (when-let [{:keys [client_id login code scope redirect_uri created_at expires_at]} row] {:client-id client_id :login login :code code :scope scope :redirect-uri redirect_uri :expires-at expires_at :created-at created_at}))
39934
(ns cerber.mappers (:require [cerber.helpers :as helpers] [taoensso.nippy :as nippy])) (defn row->token [row] (when-let [{:keys [client_id user_id login scope secret created_at expires_at]} row] {:client-id client_id :user-id user_id :login login :scope scope :secret secret :created-at created_at :expires-at expires_at})) (defn row->user [row] (when-let [{:keys [id login email name password roles created_at modified_at activated_at blocked_at enabled]} row] {:id id :login login :email email :name name :password <PASSWORD> :enabled? enabled :created-at created_at :modified-at modified_at :activated-at activated_at :blocked-at blocked_at :roles (helpers/str->keywords roles)})) (defn row->session [row] (when-let [{:keys [sid content created_at expires_at]} row] {:sid sid :content (nippy/thaw content) :expires-at expires_at :created-at created_at})) (defn row->client [row] (when-let [{:keys [id secret info approved scopes grants redirects enabled created_at modified_at activated_at blocked_at]} row] {:id id :secret secret :info info :approved? approved :enabled? enabled :scopes (helpers/str->coll scopes) :grants (helpers/str->coll grants) :redirects (helpers/str->coll redirects) :created-at created_at :modified-at modified_at :activated-at activated_at :blocked-at blocked_at})) (defn row->authcode [row] (when-let [{:keys [client_id login code scope redirect_uri created_at expires_at]} row] {:client-id client_id :login login :code code :scope scope :redirect-uri redirect_uri :expires-at expires_at :created-at created_at}))
true
(ns cerber.mappers (:require [cerber.helpers :as helpers] [taoensso.nippy :as nippy])) (defn row->token [row] (when-let [{:keys [client_id user_id login scope secret created_at expires_at]} row] {:client-id client_id :user-id user_id :login login :scope scope :secret secret :created-at created_at :expires-at expires_at})) (defn row->user [row] (when-let [{:keys [id login email name password roles created_at modified_at activated_at blocked_at enabled]} row] {:id id :login login :email email :name name :password PI:PASSWORD:<PASSWORD>END_PI :enabled? enabled :created-at created_at :modified-at modified_at :activated-at activated_at :blocked-at blocked_at :roles (helpers/str->keywords roles)})) (defn row->session [row] (when-let [{:keys [sid content created_at expires_at]} row] {:sid sid :content (nippy/thaw content) :expires-at expires_at :created-at created_at})) (defn row->client [row] (when-let [{:keys [id secret info approved scopes grants redirects enabled created_at modified_at activated_at blocked_at]} row] {:id id :secret secret :info info :approved? approved :enabled? enabled :scopes (helpers/str->coll scopes) :grants (helpers/str->coll grants) :redirects (helpers/str->coll redirects) :created-at created_at :modified-at modified_at :activated-at activated_at :blocked-at blocked_at})) (defn row->authcode [row] (when-let [{:keys [client_id login code scope redirect_uri created_at expires_at]} row] {:client-id client_id :login login :code code :scope scope :redirect-uri redirect_uri :expires-at expires_at :created-at created_at}))
[ { "context": "----------------------------\n;; Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved.\n;;\n;; This file is pr", "end": 111, "score": 0.8638984560966492, "start": 93, "tag": "NAME", "value": "Basho Technologies" } ]
src/sumo/mr_helpers.clj
reiddraper/sumo
3
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 Basho Technologies, Inc. All Rights Reserved. ;; ;; This file is provided 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 sumo.mr-helpers) ;; MapReduce function descriptions are simply ;; hashes. They describe the phase, language, ;; etc. for a particular MapReduce phase. (def ^:private js {:language "javascript"}) (def ^:private erlang {:language "erlang"}) (defn- wrap-map [input] {:map input}) (defn- wrap-reduce [input] {:reduce input}) (defn- empty-if-nil [k v] (if (nil? v) {} {k v})) ;; Javascript functions from source ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn map-js [source & {:keys [keep]}] (wrap-map (merge {:source source} (empty-if-nil :keep keep) js))) (defn reduce-js [source & {:keys [keep]}] (wrap-reduce (merge {:source source} (empty-if-nil :keep keep) js))) ;; Erlang functions from source ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn map-erlang [module function & {:keys [keep]}] (wrap-map (merge {:module module :function function} (empty-if-nil :keep keep) erlang))) (defn reduce-erlang [module function & {:keys [keep]}] (wrap-reduce (merge {:module module :function function} (empty-if-nil :keep keep) erlang)))
71832
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 <NAME>, Inc. All Rights Reserved. ;; ;; This file is provided 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 sumo.mr-helpers) ;; MapReduce function descriptions are simply ;; hashes. They describe the phase, language, ;; etc. for a particular MapReduce phase. (def ^:private js {:language "javascript"}) (def ^:private erlang {:language "erlang"}) (defn- wrap-map [input] {:map input}) (defn- wrap-reduce [input] {:reduce input}) (defn- empty-if-nil [k v] (if (nil? v) {} {k v})) ;; Javascript functions from source ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn map-js [source & {:keys [keep]}] (wrap-map (merge {:source source} (empty-if-nil :keep keep) js))) (defn reduce-js [source & {:keys [keep]}] (wrap-reduce (merge {:source source} (empty-if-nil :keep keep) js))) ;; Erlang functions from source ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn map-erlang [module function & {:keys [keep]}] (wrap-map (merge {:module module :function function} (empty-if-nil :keep keep) erlang))) (defn reduce-erlang [module function & {:keys [keep]}] (wrap-reduce (merge {:module module :function function} (empty-if-nil :keep keep) erlang)))
true
;; ------------------------------------------------------------------- ;; Copyright (c) 2011 PI:NAME:<NAME>END_PI, Inc. All Rights Reserved. ;; ;; This file is provided 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 sumo.mr-helpers) ;; MapReduce function descriptions are simply ;; hashes. They describe the phase, language, ;; etc. for a particular MapReduce phase. (def ^:private js {:language "javascript"}) (def ^:private erlang {:language "erlang"}) (defn- wrap-map [input] {:map input}) (defn- wrap-reduce [input] {:reduce input}) (defn- empty-if-nil [k v] (if (nil? v) {} {k v})) ;; Javascript functions from source ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn map-js [source & {:keys [keep]}] (wrap-map (merge {:source source} (empty-if-nil :keep keep) js))) (defn reduce-js [source & {:keys [keep]}] (wrap-reduce (merge {:source source} (empty-if-nil :keep keep) js))) ;; Erlang functions from source ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn map-erlang [module function & {:keys [keep]}] (wrap-map (merge {:module module :function function} (empty-if-nil :keep keep) erlang))) (defn reduce-erlang [module function & {:keys [keep]}] (wrap-reduce (merge {:module module :function function} (empty-if-nil :keep keep) erlang)))
[ { "context": " [clojure.spec.alpha :as s]))\n\n(def token \"ZaBpdrqzpzcmbdEzd1kB\")\n\n(def results-db (atom []))\n(def queries (atom ", "end": 364, "score": 0.9284830689430237, "start": 344, "tag": "KEY", "value": "ZaBpdrqzpzcmbdEzd1kB" } ]
GraphQL/implementation/src/gql/fault_finding_experiment.clj
zclj/replication-packages
8
(ns gql.fault-finding-experiment (:require [gql.generators :as gqlgen] [gql.query-data :as data] [gql.git-lab-specs :as gspecs] [clojure.test.check.properties :as prop] [org.httpkit.client :as http] [clojure.data.json :as json] [clojure.spec.alpha :as s])) (def token "ZaBpdrqzpzcmbdEzd1kB") (def results-db (atom [])) (def queries (atom [])) (defn run-query [query-str] (let [response @(http/request {:url "http://localhost/api/graphql" :method :post :headers {"PRIVATE-TOKEN" token} :content-type "application/json" :form-params {"query" query-str}})] {:body (json/read-str (:body response) :key-fn keyword) :status-code (:status response)})) (defn valid-result? [payload] ;;(println (str "Validating " payload)) (every? identity (map eval (reduce (fn [acc p] (conj acc `(s/valid? ~(keyword "gql.git-lab-specs.Query" (name (key p))) ~(val p)))) [] payload)))) (def test-property (let [schema (-> data/gitlab-schema :data :__schema)] (prop/for-all [ query-tree (gqlgen/gen-gql-nodes (nth (:types schema) 2) (:types schema) 3 ;; gqlgen/resolve-arg-gen-alphanumeric gqlgen/resolve-arg-gen-string )] (let [result (run-query (gqlgen/make-query query-tree))] (swap! results-db conj {:query (gqlgen/make-query query-tree) :result result :query-tree query-tree}) (swap! queries conj (gqlgen/make-query query-tree)) (and (= (:status-code result) 200) (valid-result? (:data (:body result))) ;;(= (:errors (:body result)) nil) ))))) (defn run-tests [] (reset! results-db []) (reset! queries []) (clojure.test.check/quick-check 10000 test-property)) (defn result-errors [] (reduce (fn [acc result] (let [error (-> result :result :body :errors)] (if error (conj acc error) acc))) [] @results-db)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Fault finding (run-tests)
79944
(ns gql.fault-finding-experiment (:require [gql.generators :as gqlgen] [gql.query-data :as data] [gql.git-lab-specs :as gspecs] [clojure.test.check.properties :as prop] [org.httpkit.client :as http] [clojure.data.json :as json] [clojure.spec.alpha :as s])) (def token "<KEY>") (def results-db (atom [])) (def queries (atom [])) (defn run-query [query-str] (let [response @(http/request {:url "http://localhost/api/graphql" :method :post :headers {"PRIVATE-TOKEN" token} :content-type "application/json" :form-params {"query" query-str}})] {:body (json/read-str (:body response) :key-fn keyword) :status-code (:status response)})) (defn valid-result? [payload] ;;(println (str "Validating " payload)) (every? identity (map eval (reduce (fn [acc p] (conj acc `(s/valid? ~(keyword "gql.git-lab-specs.Query" (name (key p))) ~(val p)))) [] payload)))) (def test-property (let [schema (-> data/gitlab-schema :data :__schema)] (prop/for-all [ query-tree (gqlgen/gen-gql-nodes (nth (:types schema) 2) (:types schema) 3 ;; gqlgen/resolve-arg-gen-alphanumeric gqlgen/resolve-arg-gen-string )] (let [result (run-query (gqlgen/make-query query-tree))] (swap! results-db conj {:query (gqlgen/make-query query-tree) :result result :query-tree query-tree}) (swap! queries conj (gqlgen/make-query query-tree)) (and (= (:status-code result) 200) (valid-result? (:data (:body result))) ;;(= (:errors (:body result)) nil) ))))) (defn run-tests [] (reset! results-db []) (reset! queries []) (clojure.test.check/quick-check 10000 test-property)) (defn result-errors [] (reduce (fn [acc result] (let [error (-> result :result :body :errors)] (if error (conj acc error) acc))) [] @results-db)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Fault finding (run-tests)
true
(ns gql.fault-finding-experiment (:require [gql.generators :as gqlgen] [gql.query-data :as data] [gql.git-lab-specs :as gspecs] [clojure.test.check.properties :as prop] [org.httpkit.client :as http] [clojure.data.json :as json] [clojure.spec.alpha :as s])) (def token "PI:KEY:<KEY>END_PI") (def results-db (atom [])) (def queries (atom [])) (defn run-query [query-str] (let [response @(http/request {:url "http://localhost/api/graphql" :method :post :headers {"PRIVATE-TOKEN" token} :content-type "application/json" :form-params {"query" query-str}})] {:body (json/read-str (:body response) :key-fn keyword) :status-code (:status response)})) (defn valid-result? [payload] ;;(println (str "Validating " payload)) (every? identity (map eval (reduce (fn [acc p] (conj acc `(s/valid? ~(keyword "gql.git-lab-specs.Query" (name (key p))) ~(val p)))) [] payload)))) (def test-property (let [schema (-> data/gitlab-schema :data :__schema)] (prop/for-all [ query-tree (gqlgen/gen-gql-nodes (nth (:types schema) 2) (:types schema) 3 ;; gqlgen/resolve-arg-gen-alphanumeric gqlgen/resolve-arg-gen-string )] (let [result (run-query (gqlgen/make-query query-tree))] (swap! results-db conj {:query (gqlgen/make-query query-tree) :result result :query-tree query-tree}) (swap! queries conj (gqlgen/make-query query-tree)) (and (= (:status-code result) 200) (valid-result? (:data (:body result))) ;;(= (:errors (:body result)) nil) ))))) (defn run-tests [] (reset! results-db []) (reset! queries []) (clojure.test.check/quick-check 10000 test-property)) (defn result-errors [] (reduce (fn [acc result] (let [error (-> result :result :body :errors)] (if error (conj acc error) acc))) [] @results-db)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Fault finding (run-tests)
[ { "context": "alid-security-token-test\n (is (= {:errors [\"Token ABC123 does not exist\"], :status 401}\n (searc", "end": 1657, "score": 0.49447301030158997, "start": 1654, "tag": "KEY", "value": "ABC" }, { "context": "-security-token-test\n (is (= {:errors [\"Token ABC123 does not exist\"], :status 401}\n (search/f", "end": 1660, "score": 0.803776741027832, "start": 1657, "tag": "PASSWORD", "value": "123" }, { "context": "}\n (search/find-refs :collection {:token \"ABC123\"}))))\n\n(deftest expired-security-token-test\n ", "end": 1743, "score": 0.5800052285194397, "start": 1740, "tag": "KEY", "value": "ABC" }, { "context": " (search/find-refs :collection {:token \"ABC123\"}))))\n\n(deftest expired-security-token-test\n (is", "end": 1746, "score": 0.7048889994621277, "start": 1743, "tag": "PASSWORD", "value": "123" } ]
system-int-test/test/cmr/system_int_test/search/acls/collection_acl_search_test.clj
mschmele/Common-Metadata-Repository
0
(ns cmr.system-int-test.search.acls.collection-acl-search-test "Tests searching for collections with ACLs in place" (:require [cmr.common-app.test.side-api :as side] [clojure.test :refer :all] [clojure.string :as str] [cmr.acl.acl-fetcher :as acl-fetcher] [cmr.common.services.messages :as msg] [cmr.common.util :refer [are2] :as util] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.data2.atom :as da] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.data2.opendata :as od] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.dev-system-util :as dev-sys-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.metadata-db-util :as mdb] [cmr.system-int-test.utils.search-util :as search] [cmr.transmit.access-control :as ac] [cmr.transmit.config :as tc])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3" "provguid4" "PROV4"} {:grant-all-search? false}) (search/freeze-resume-time-fixture)])) (comment (dev-sys-util/reset) (ingest/create-provider {:provider-guid "PROV1" :provider-id "PROV1"}) (ingest/create-provider {:provider-guid "PROV2" :provider-id "PROV2"}) (ingest/create-provider {:provider-guid "PROV3" :provider-id "PROV3"})) (deftest invalid-security-token-test (is (= {:errors ["Token ABC123 does not exist"], :status 401} (search/find-refs :collection {:token "ABC123"})))) (deftest expired-security-token-test (is (= {:errors ["Token [expired-token] has expired."], :status 401} (search/find-refs :collection {:token "expired-token"})))) (deftest collection-search-with-no-acls-test ;; system token can see all collections with no ACLs (let [guest-token (e/login-guest (s/context)) c1-echo (d/ingest "PROV1" (dc/collection {:entry-title "c1-echo" :access-value 1}) {:format :echo10}) c1-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c1-dif" :access-value 1}) {:format :dif}) c1-dif10 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "c1-dif10" :access-value 1}) {:format :dif10}) c1-iso (d/ingest "PROV1" (dc/collection {:entry-title "c1-iso" :access-value 1}) {:format :iso19115}) c1-smap (d/ingest "PROV1" (dc/collection {:entry-title "c1-smap" :access-value 1}) {:format :iso-smap})] (index/wait-until-indexed) ;;;;system token sees everything (is (d/refs-match? [c1-echo c1-dif c1-dif10 c1-iso c1-smap] (search/find-refs :collection {:token (tc/echo-system-token)}))) ;;guest user sees nothing (is (d/refs-match? [] (search/find-refs :collection {:token guest-token}))))) (deftest collection-search-with-restriction-flag-acls-test (let [guest-token (e/login-guest (s/context)) c1-echo (d/ingest "PROV1" (dc/collection {:entry-title "c1-echo" :access-value 1}) {:format :echo10}) c2-echo (d/ingest "PROV1" (dc/collection {:entry-title "c2-echo" :access-value 0}) {:format :echo10}) c1-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c1-dif" :access-value 1}) {:format :dif}) c2-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c2-dif" :access-value 0}) {:format :dif}) c1-dif10 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "c1-dif10" :access-value 1}) {:format :dif10}) c2-dif10 (d/ingest "PROV2" (dc/collection-dif10 {:entry-title "c2-dif10" :access-value 0}) {:format :dif10}) c1-iso (d/ingest "PROV1" (dc/collection {:entry-title "c1-iso" :access-value 1}) {:format :iso19115}) c2-iso (d/ingest "PROV1" (dc/collection {:entry-title "c2-iso" :access-value 0}) {:format :iso19115}) ;; access-value is not supported in ISO-SMAP, so it won't be found c1-smap (d/ingest "PROV1" (dc/collection {:entry-title "c1-smap" :access-value 1}) {:format :iso-smap}) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3"}))] (index/wait-until-indexed) ;; grant restriction flag acl (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["c1-echo" "c2-echo" "c1-dif" "c2-dif" "c1-dif10" "c1-iso" "c2-iso" "c1-smap" "coll3"] {:min-value 0.5 :max-value 1.5}))) (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) (is (d/refs-match? [c1-echo c1-dif c1-dif10 c1-iso] (search/find-refs :collection {:token guest-token}))))) (deftest collection-search-with-acls-test (let [group1-concept-id (e/get-or-create-group (s/context) "group1") group2-concept-id (e/get-or-create-group (s/context) "group2") group3-concept-id (e/get-or-create-group (s/context) "group3") coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "coll2"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3"})) coll4 (d/ingest "PROV1" (dc/collection {:entry-title "coll4" :access-value 5.0})) ;; no permission granted on coll5 coll5 (d/ingest "PROV1" (dc/collection {:entry-title "coll5"})) ;; PROV2 coll6 (d/ingest "PROV2" (dc/collection {:entry-title "coll6"})) coll7 (d/ingest "PROV2" (dc/collection {:entry-title "coll7"})) ;; A dif collection coll8 (d/ingest "PROV2" (dc/collection-dif {:entry-title "coll8" :short-name "S8" :version-id "V8" :long-name "coll8"}) {:format :dif}) ;; added for atom results coll8 (assoc coll8 :original-format "DIF") ;; PROV3 coll9 (d/ingest "PROV3" (dc/collection {:entry-title "coll9"})) coll10 (d/ingest "PROV3" (dc/collection {:entry-title "coll10" :access-value 12.0})) ;; PROV4 ;; group3 has permission to read this collection revision coll11-1 (d/ingest "PROV4" (dc/collection {:entry-title "coll11-entry-title" :native-id "coll11"})) ;; tombstone coll11-2 (assoc (ingest/delete-concept (d/item->concept coll11-1)) :entry-title "coll11-entry-title" :deleted true :revision-id 2) ;; no permissions to read this revision since entry-title has changed coll11-3 (d/ingest "PROV4" (dc/collection {:entry-title "coll11" :native-id "coll11"})) ;; group 3 has permission to read this collection revision coll12-1 (d/ingest "PROV4" (dc/collection {:entry-title "coll12-entry-title" :native-id "coll12"})) ;; no permissions to read this collection since entry-title has changed coll12-2 (d/ingest "PROV4" (dc/collection {:entry-title "coll12" :native-id "coll12"})) ;; no permision to see this tombstone since it has same entry-title as coll12-2 coll12-3 (assoc (ingest/delete-concept (d/item->concept coll12-2)) :deleted true :revision-id 2) all-colls [coll1 coll2 coll3 coll4 coll5 coll6 coll7 coll8 coll9 coll10] guest-permitted-collections [coll1 coll4 coll6 coll7 coll8 coll9] guest-token (e/login-guest (s/context)) user1-token (e/login (s/context) "user1") user2-token (e/login (s/context) "user2" [group1-concept-id]) user3-token (e/login (s/context) "user3" [group1-concept-id group2-concept-id]) user4-token (e/login (s/context) "user4" [group3-concept-id])] (index/wait-until-indexed) ;; Grant guests permission to coll1 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["notexist"]))) ;; restriction flag acl grants matches coll4 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll4"] {:min-value 4 :max-value 6}))) ;; Grant undefined access values in prov3 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV3" (e/coll-id nil {:include_undefined_value true}))) ;; all collections in prov2 granted to guests (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2")) ;; grant registered users permission to coll2 and coll4 (e/grant-registered-users (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll2" "coll4"]))) ;; grant specific group permission to coll3, coll6, and coll8 (e/grant-group (s/context) group1-concept-id (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll3"]))) (e/grant-group (s/context) group2-concept-id (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll6" "coll8"]))) (e/grant-group (s/context) group3-concept-id (e/coll-catalog-item-id "PROV4" (e/coll-id ["coll11-entry-title" "coll12-entry-title"]))) (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) (testing "parameter search acl enforcement" (are [token items] (d/refs-match? items (search/find-refs :collection (when token {:token token}))) ;; not logged in should be guest nil guest-permitted-collections ;; login and use guest token guest-token guest-permitted-collections ;; test searching as a user user1-token [coll2 coll4] ;; Test searching with users in groups user2-token [coll2 coll4 coll3] user3-token [coll2 coll4 coll3 coll6 coll8])) (testing "token can be sent through a header" (is (d/refs-match? [coll2 coll4] (search/find-refs :collection {} {:headers {"Echo-Token" user1-token}})))) (testing "aql search parameter enforcement" (is (d/refs-match? [coll2 coll4] (search/find-refs-with-aql :collection [] {} {:headers {"Echo-Token" user1-token}})))) (testing "Direct transformer retrieval acl enforcement" (testing "registered user" (d/assert-metadata-results-match :echo10 [coll2 coll4] (search/find-metadata :collection :echo10 {:token user1-token :concept-id (conj (map :concept-id all-colls) "C9999-PROV1")}))) (testing "guest access" (d/assert-metadata-results-match :echo10 guest-permitted-collections (search/find-metadata :collection :echo10 {:token guest-token :concept-id (map :concept-id all-colls)}))) (testing "Empty token matches guest access" (d/assert-metadata-results-match :echo10 guest-permitted-collections (search/find-metadata :collection :echo10 {:token "" :concept-id (map :concept-id all-colls)}))) (testing "user in groups" (d/assert-metadata-results-match :echo10 [coll4 coll6 coll3 coll8 coll2] (search/find-metadata :collection :echo10 {:token user3-token :concept-id (map :concept-id all-colls)})))) (testing "ATOM ACL enforcement" (testing "all items" (let [coll-atom (da/collections->expected-atom guest-permitted-collections (format "collections.atom?token=%s&page_size=100" guest-token))] (is (= coll-atom (:results (search/find-concepts-atom :collection {:token guest-token :page-size 100})))))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) coll-atom (da/collections->expected-atom guest-permitted-collections (str "collections.atom?token=" guest-token "&page_size=100&concept_id=" (str/join "&concept_id=" concept-ids)))] (is (= coll-atom (:results (search/find-concepts-atom :collection {:token guest-token :page-size 100 :concept-id concept-ids}))))))) (testing "JSON ACL enforcement" (testing "all items" (let [coll-json (da/collections->expected-atom guest-permitted-collections (format "collections.json?token=%s&page_size=100" guest-token))] (is (= coll-json (:results (search/find-concepts-json :collection {:token guest-token :page-size 100})))))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) coll-json (da/collections->expected-atom guest-permitted-collections (str "collections.json?token=" guest-token "&page_size=100&concept_id=" (str/join "&concept_id=" concept-ids)))] (is (= coll-json (:results (search/find-concepts-json :collection {:token guest-token :page-size 100 :concept-id concept-ids}))))))) (testing "opendata ACL enforcement" (testing "all items" (let [actual-od (search/find-concepts-opendata :collection {:token guest-token :page-size 100})] (od/assert-collection-opendata-results-match guest-permitted-collections actual-od))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) actual-od (search/find-concepts-opendata :collection {:token guest-token :page-size 100 :concept-id concept-ids})] (od/assert-collection-opendata-results-match guest-permitted-collections actual-od)))) (testing "all_revisions" (are2 [collections params] (d/refs-match? collections (search/find-refs :collection params)) ;; only old revisions satisfy ACL - they should not be returned "provider-id all-revisions=false" [] {:provider-id "PROV4" :all-revisions false :token user4-token} ;; only permissioned revisions are returned - including tombstones "provider-id all-revisions=true" [coll11-1 coll11-2 coll12-1] {:provider-id "PROV4" :all-revisions true :token user4-token} ;; none of the revisions are readable by guest users "provider-id all-revisions=true no token" [] {:provider-id "PROV4" :all-revisions true})))) ;; This tests that when acls change after collections have been indexed that collections will be ;; reindexed when ingest detects the acl hash has change. (deftest acl-change-test (let [coll1 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "coll1"}) {:format :dif10}) coll2-umm (dc/collection {:entry-title "coll2" :short-name "short1"}) coll2-1 (d/ingest "PROV1" coll2-umm) ;; 2 versions of collection 2 will allow us to test the force reindex option after we ;; force delete the latest version of coll2-2 coll2-2 (d/ingest "PROV1" (assoc-in coll2-umm [:product :short-name] "short2")) coll3 (d/ingest "PROV2" (dc/collection-dif10 {:entry-title "coll3"}) {:format :dif10}) coll4 (d/ingest "PROV2" (dc/collection {:entry-title "coll4"})) _ (index/wait-until-indexed) acl1 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) acl2 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll3"])))] (testing "normal reindex collection permitted groups" (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) ;; before acls change (is (d/refs-match? [coll1 coll3] (search/find-refs :collection {}))) ;; Grant collection 2 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll2"]))) ;; Ungrant collection 3 (e/ungrant (s/context) acl2) ;; Try searching again before the reindexing (is (d/refs-match? [coll1 coll3] (search/find-refs :collection {}))) ;; Reindex collection permitted groups (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) ;; Search after reindexing (is (d/refs-match? [coll1 coll2-2] (search/find-refs :collection {})))) (testing "reindex all collections" ;; Grant collection 4 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll4"]))) ;; Try before reindexing (is (d/refs-match? [coll1 coll2-2] (search/find-refs :collection {}))) ;; Reindex all collections ;; manually check the logs here. It should say it's reindexing provider 1 and provider 3 as well. (ingest/reindex-all-collections) (index/wait-until-indexed) ;; Search after reindexing (is (d/refs-match? [coll1 coll2-2 coll4] (search/find-refs :collection {})))) ;; Tests reindexing using the force current version option (testing "Force version reindex all collections" ;; Verify we can find coll2 with the lastest data (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; Delete the latest version of coll2 (is (= 200 (:status (mdb/force-delete-concept (:concept-id coll2-2) 2)))) (index/wait-until-indexed) ;; After deleting the latest version of coll2 we will still find that. (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; Reindexing all the collections doesn't solve the problem (ingest/reindex-all-collections) (index/wait-until-indexed) (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; A force reindex all collections will make elastic take the earlier version of the collections. (ingest/reindex-all-collections {:force-version true}) (index/wait-until-indexed) (d/assert-refs-match [] (search/find-refs :collection {:short-name "short2"})) (d/assert-refs-match [coll2-1] (search/find-refs :collection {:short-name "short1"}))))) ;; Verifies that tokens are cached by checking that a logged out token still works after it was used. ;; This isn't the desired behavior. It's just a side effect that shows it's working. (deftest cache-token-test (let [coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1"})) acl1 (e/grant-registered-users (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) user1-token (e/login (s/context) "user1") user2-token (e/login (s/context) "user2")] (index/wait-until-indexed) ;; A logged out token is normally not useful (e/logout (s/context) user2-token) (is (= {:errors ["Token ABC-2 does not exist"], :status 401} (search/find-refs :collection {:token user2-token}))) ;; Use user1-token so it will be cached (is (d/refs-match? [coll1] (search/find-refs :collection {:token user1-token}))) ;; logout (e/logout (s/context) user1-token) ;; The token should be cached (is (d/refs-match? [coll1] (search/find-refs :collection {:token user1-token})))))
49478
(ns cmr.system-int-test.search.acls.collection-acl-search-test "Tests searching for collections with ACLs in place" (:require [cmr.common-app.test.side-api :as side] [clojure.test :refer :all] [clojure.string :as str] [cmr.acl.acl-fetcher :as acl-fetcher] [cmr.common.services.messages :as msg] [cmr.common.util :refer [are2] :as util] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.data2.atom :as da] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.data2.opendata :as od] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.dev-system-util :as dev-sys-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.metadata-db-util :as mdb] [cmr.system-int-test.utils.search-util :as search] [cmr.transmit.access-control :as ac] [cmr.transmit.config :as tc])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3" "provguid4" "PROV4"} {:grant-all-search? false}) (search/freeze-resume-time-fixture)])) (comment (dev-sys-util/reset) (ingest/create-provider {:provider-guid "PROV1" :provider-id "PROV1"}) (ingest/create-provider {:provider-guid "PROV2" :provider-id "PROV2"}) (ingest/create-provider {:provider-guid "PROV3" :provider-id "PROV3"})) (deftest invalid-security-token-test (is (= {:errors ["Token <KEY> <PASSWORD> does not exist"], :status 401} (search/find-refs :collection {:token "<KEY> <PASSWORD>"})))) (deftest expired-security-token-test (is (= {:errors ["Token [expired-token] has expired."], :status 401} (search/find-refs :collection {:token "expired-token"})))) (deftest collection-search-with-no-acls-test ;; system token can see all collections with no ACLs (let [guest-token (e/login-guest (s/context)) c1-echo (d/ingest "PROV1" (dc/collection {:entry-title "c1-echo" :access-value 1}) {:format :echo10}) c1-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c1-dif" :access-value 1}) {:format :dif}) c1-dif10 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "c1-dif10" :access-value 1}) {:format :dif10}) c1-iso (d/ingest "PROV1" (dc/collection {:entry-title "c1-iso" :access-value 1}) {:format :iso19115}) c1-smap (d/ingest "PROV1" (dc/collection {:entry-title "c1-smap" :access-value 1}) {:format :iso-smap})] (index/wait-until-indexed) ;;;;system token sees everything (is (d/refs-match? [c1-echo c1-dif c1-dif10 c1-iso c1-smap] (search/find-refs :collection {:token (tc/echo-system-token)}))) ;;guest user sees nothing (is (d/refs-match? [] (search/find-refs :collection {:token guest-token}))))) (deftest collection-search-with-restriction-flag-acls-test (let [guest-token (e/login-guest (s/context)) c1-echo (d/ingest "PROV1" (dc/collection {:entry-title "c1-echo" :access-value 1}) {:format :echo10}) c2-echo (d/ingest "PROV1" (dc/collection {:entry-title "c2-echo" :access-value 0}) {:format :echo10}) c1-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c1-dif" :access-value 1}) {:format :dif}) c2-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c2-dif" :access-value 0}) {:format :dif}) c1-dif10 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "c1-dif10" :access-value 1}) {:format :dif10}) c2-dif10 (d/ingest "PROV2" (dc/collection-dif10 {:entry-title "c2-dif10" :access-value 0}) {:format :dif10}) c1-iso (d/ingest "PROV1" (dc/collection {:entry-title "c1-iso" :access-value 1}) {:format :iso19115}) c2-iso (d/ingest "PROV1" (dc/collection {:entry-title "c2-iso" :access-value 0}) {:format :iso19115}) ;; access-value is not supported in ISO-SMAP, so it won't be found c1-smap (d/ingest "PROV1" (dc/collection {:entry-title "c1-smap" :access-value 1}) {:format :iso-smap}) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3"}))] (index/wait-until-indexed) ;; grant restriction flag acl (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["c1-echo" "c2-echo" "c1-dif" "c2-dif" "c1-dif10" "c1-iso" "c2-iso" "c1-smap" "coll3"] {:min-value 0.5 :max-value 1.5}))) (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) (is (d/refs-match? [c1-echo c1-dif c1-dif10 c1-iso] (search/find-refs :collection {:token guest-token}))))) (deftest collection-search-with-acls-test (let [group1-concept-id (e/get-or-create-group (s/context) "group1") group2-concept-id (e/get-or-create-group (s/context) "group2") group3-concept-id (e/get-or-create-group (s/context) "group3") coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "coll2"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3"})) coll4 (d/ingest "PROV1" (dc/collection {:entry-title "coll4" :access-value 5.0})) ;; no permission granted on coll5 coll5 (d/ingest "PROV1" (dc/collection {:entry-title "coll5"})) ;; PROV2 coll6 (d/ingest "PROV2" (dc/collection {:entry-title "coll6"})) coll7 (d/ingest "PROV2" (dc/collection {:entry-title "coll7"})) ;; A dif collection coll8 (d/ingest "PROV2" (dc/collection-dif {:entry-title "coll8" :short-name "S8" :version-id "V8" :long-name "coll8"}) {:format :dif}) ;; added for atom results coll8 (assoc coll8 :original-format "DIF") ;; PROV3 coll9 (d/ingest "PROV3" (dc/collection {:entry-title "coll9"})) coll10 (d/ingest "PROV3" (dc/collection {:entry-title "coll10" :access-value 12.0})) ;; PROV4 ;; group3 has permission to read this collection revision coll11-1 (d/ingest "PROV4" (dc/collection {:entry-title "coll11-entry-title" :native-id "coll11"})) ;; tombstone coll11-2 (assoc (ingest/delete-concept (d/item->concept coll11-1)) :entry-title "coll11-entry-title" :deleted true :revision-id 2) ;; no permissions to read this revision since entry-title has changed coll11-3 (d/ingest "PROV4" (dc/collection {:entry-title "coll11" :native-id "coll11"})) ;; group 3 has permission to read this collection revision coll12-1 (d/ingest "PROV4" (dc/collection {:entry-title "coll12-entry-title" :native-id "coll12"})) ;; no permissions to read this collection since entry-title has changed coll12-2 (d/ingest "PROV4" (dc/collection {:entry-title "coll12" :native-id "coll12"})) ;; no permision to see this tombstone since it has same entry-title as coll12-2 coll12-3 (assoc (ingest/delete-concept (d/item->concept coll12-2)) :deleted true :revision-id 2) all-colls [coll1 coll2 coll3 coll4 coll5 coll6 coll7 coll8 coll9 coll10] guest-permitted-collections [coll1 coll4 coll6 coll7 coll8 coll9] guest-token (e/login-guest (s/context)) user1-token (e/login (s/context) "user1") user2-token (e/login (s/context) "user2" [group1-concept-id]) user3-token (e/login (s/context) "user3" [group1-concept-id group2-concept-id]) user4-token (e/login (s/context) "user4" [group3-concept-id])] (index/wait-until-indexed) ;; Grant guests permission to coll1 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["notexist"]))) ;; restriction flag acl grants matches coll4 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll4"] {:min-value 4 :max-value 6}))) ;; Grant undefined access values in prov3 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV3" (e/coll-id nil {:include_undefined_value true}))) ;; all collections in prov2 granted to guests (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2")) ;; grant registered users permission to coll2 and coll4 (e/grant-registered-users (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll2" "coll4"]))) ;; grant specific group permission to coll3, coll6, and coll8 (e/grant-group (s/context) group1-concept-id (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll3"]))) (e/grant-group (s/context) group2-concept-id (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll6" "coll8"]))) (e/grant-group (s/context) group3-concept-id (e/coll-catalog-item-id "PROV4" (e/coll-id ["coll11-entry-title" "coll12-entry-title"]))) (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) (testing "parameter search acl enforcement" (are [token items] (d/refs-match? items (search/find-refs :collection (when token {:token token}))) ;; not logged in should be guest nil guest-permitted-collections ;; login and use guest token guest-token guest-permitted-collections ;; test searching as a user user1-token [coll2 coll4] ;; Test searching with users in groups user2-token [coll2 coll4 coll3] user3-token [coll2 coll4 coll3 coll6 coll8])) (testing "token can be sent through a header" (is (d/refs-match? [coll2 coll4] (search/find-refs :collection {} {:headers {"Echo-Token" user1-token}})))) (testing "aql search parameter enforcement" (is (d/refs-match? [coll2 coll4] (search/find-refs-with-aql :collection [] {} {:headers {"Echo-Token" user1-token}})))) (testing "Direct transformer retrieval acl enforcement" (testing "registered user" (d/assert-metadata-results-match :echo10 [coll2 coll4] (search/find-metadata :collection :echo10 {:token user1-token :concept-id (conj (map :concept-id all-colls) "C9999-PROV1")}))) (testing "guest access" (d/assert-metadata-results-match :echo10 guest-permitted-collections (search/find-metadata :collection :echo10 {:token guest-token :concept-id (map :concept-id all-colls)}))) (testing "Empty token matches guest access" (d/assert-metadata-results-match :echo10 guest-permitted-collections (search/find-metadata :collection :echo10 {:token "" :concept-id (map :concept-id all-colls)}))) (testing "user in groups" (d/assert-metadata-results-match :echo10 [coll4 coll6 coll3 coll8 coll2] (search/find-metadata :collection :echo10 {:token user3-token :concept-id (map :concept-id all-colls)})))) (testing "ATOM ACL enforcement" (testing "all items" (let [coll-atom (da/collections->expected-atom guest-permitted-collections (format "collections.atom?token=%s&page_size=100" guest-token))] (is (= coll-atom (:results (search/find-concepts-atom :collection {:token guest-token :page-size 100})))))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) coll-atom (da/collections->expected-atom guest-permitted-collections (str "collections.atom?token=" guest-token "&page_size=100&concept_id=" (str/join "&concept_id=" concept-ids)))] (is (= coll-atom (:results (search/find-concepts-atom :collection {:token guest-token :page-size 100 :concept-id concept-ids}))))))) (testing "JSON ACL enforcement" (testing "all items" (let [coll-json (da/collections->expected-atom guest-permitted-collections (format "collections.json?token=%s&page_size=100" guest-token))] (is (= coll-json (:results (search/find-concepts-json :collection {:token guest-token :page-size 100})))))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) coll-json (da/collections->expected-atom guest-permitted-collections (str "collections.json?token=" guest-token "&page_size=100&concept_id=" (str/join "&concept_id=" concept-ids)))] (is (= coll-json (:results (search/find-concepts-json :collection {:token guest-token :page-size 100 :concept-id concept-ids}))))))) (testing "opendata ACL enforcement" (testing "all items" (let [actual-od (search/find-concepts-opendata :collection {:token guest-token :page-size 100})] (od/assert-collection-opendata-results-match guest-permitted-collections actual-od))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) actual-od (search/find-concepts-opendata :collection {:token guest-token :page-size 100 :concept-id concept-ids})] (od/assert-collection-opendata-results-match guest-permitted-collections actual-od)))) (testing "all_revisions" (are2 [collections params] (d/refs-match? collections (search/find-refs :collection params)) ;; only old revisions satisfy ACL - they should not be returned "provider-id all-revisions=false" [] {:provider-id "PROV4" :all-revisions false :token user4-token} ;; only permissioned revisions are returned - including tombstones "provider-id all-revisions=true" [coll11-1 coll11-2 coll12-1] {:provider-id "PROV4" :all-revisions true :token user4-token} ;; none of the revisions are readable by guest users "provider-id all-revisions=true no token" [] {:provider-id "PROV4" :all-revisions true})))) ;; This tests that when acls change after collections have been indexed that collections will be ;; reindexed when ingest detects the acl hash has change. (deftest acl-change-test (let [coll1 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "coll1"}) {:format :dif10}) coll2-umm (dc/collection {:entry-title "coll2" :short-name "short1"}) coll2-1 (d/ingest "PROV1" coll2-umm) ;; 2 versions of collection 2 will allow us to test the force reindex option after we ;; force delete the latest version of coll2-2 coll2-2 (d/ingest "PROV1" (assoc-in coll2-umm [:product :short-name] "short2")) coll3 (d/ingest "PROV2" (dc/collection-dif10 {:entry-title "coll3"}) {:format :dif10}) coll4 (d/ingest "PROV2" (dc/collection {:entry-title "coll4"})) _ (index/wait-until-indexed) acl1 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) acl2 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll3"])))] (testing "normal reindex collection permitted groups" (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) ;; before acls change (is (d/refs-match? [coll1 coll3] (search/find-refs :collection {}))) ;; Grant collection 2 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll2"]))) ;; Ungrant collection 3 (e/ungrant (s/context) acl2) ;; Try searching again before the reindexing (is (d/refs-match? [coll1 coll3] (search/find-refs :collection {}))) ;; Reindex collection permitted groups (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) ;; Search after reindexing (is (d/refs-match? [coll1 coll2-2] (search/find-refs :collection {})))) (testing "reindex all collections" ;; Grant collection 4 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll4"]))) ;; Try before reindexing (is (d/refs-match? [coll1 coll2-2] (search/find-refs :collection {}))) ;; Reindex all collections ;; manually check the logs here. It should say it's reindexing provider 1 and provider 3 as well. (ingest/reindex-all-collections) (index/wait-until-indexed) ;; Search after reindexing (is (d/refs-match? [coll1 coll2-2 coll4] (search/find-refs :collection {})))) ;; Tests reindexing using the force current version option (testing "Force version reindex all collections" ;; Verify we can find coll2 with the lastest data (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; Delete the latest version of coll2 (is (= 200 (:status (mdb/force-delete-concept (:concept-id coll2-2) 2)))) (index/wait-until-indexed) ;; After deleting the latest version of coll2 we will still find that. (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; Reindexing all the collections doesn't solve the problem (ingest/reindex-all-collections) (index/wait-until-indexed) (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; A force reindex all collections will make elastic take the earlier version of the collections. (ingest/reindex-all-collections {:force-version true}) (index/wait-until-indexed) (d/assert-refs-match [] (search/find-refs :collection {:short-name "short2"})) (d/assert-refs-match [coll2-1] (search/find-refs :collection {:short-name "short1"}))))) ;; Verifies that tokens are cached by checking that a logged out token still works after it was used. ;; This isn't the desired behavior. It's just a side effect that shows it's working. (deftest cache-token-test (let [coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1"})) acl1 (e/grant-registered-users (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) user1-token (e/login (s/context) "user1") user2-token (e/login (s/context) "user2")] (index/wait-until-indexed) ;; A logged out token is normally not useful (e/logout (s/context) user2-token) (is (= {:errors ["Token ABC-2 does not exist"], :status 401} (search/find-refs :collection {:token user2-token}))) ;; Use user1-token so it will be cached (is (d/refs-match? [coll1] (search/find-refs :collection {:token user1-token}))) ;; logout (e/logout (s/context) user1-token) ;; The token should be cached (is (d/refs-match? [coll1] (search/find-refs :collection {:token user1-token})))))
true
(ns cmr.system-int-test.search.acls.collection-acl-search-test "Tests searching for collections with ACLs in place" (:require [cmr.common-app.test.side-api :as side] [clojure.test :refer :all] [clojure.string :as str] [cmr.acl.acl-fetcher :as acl-fetcher] [cmr.common.services.messages :as msg] [cmr.common.util :refer [are2] :as util] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.data2.atom :as da] [cmr.system-int-test.data2.collection :as dc] [cmr.system-int-test.data2.core :as d] [cmr.system-int-test.data2.opendata :as od] [cmr.system-int-test.system :as s] [cmr.system-int-test.utils.dev-system-util :as dev-sys-util] [cmr.system-int-test.utils.index-util :as index] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.metadata-db-util :as mdb] [cmr.system-int-test.utils.search-util :as search] [cmr.transmit.access-control :as ac] [cmr.transmit.config :as tc])) (use-fixtures :each (join-fixtures [(ingest/reset-fixture {"provguid1" "PROV1" "provguid2" "PROV2" "provguid3" "PROV3" "provguid4" "PROV4"} {:grant-all-search? false}) (search/freeze-resume-time-fixture)])) (comment (dev-sys-util/reset) (ingest/create-provider {:provider-guid "PROV1" :provider-id "PROV1"}) (ingest/create-provider {:provider-guid "PROV2" :provider-id "PROV2"}) (ingest/create-provider {:provider-guid "PROV3" :provider-id "PROV3"})) (deftest invalid-security-token-test (is (= {:errors ["Token PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI does not exist"], :status 401} (search/find-refs :collection {:token "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI"})))) (deftest expired-security-token-test (is (= {:errors ["Token [expired-token] has expired."], :status 401} (search/find-refs :collection {:token "expired-token"})))) (deftest collection-search-with-no-acls-test ;; system token can see all collections with no ACLs (let [guest-token (e/login-guest (s/context)) c1-echo (d/ingest "PROV1" (dc/collection {:entry-title "c1-echo" :access-value 1}) {:format :echo10}) c1-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c1-dif" :access-value 1}) {:format :dif}) c1-dif10 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "c1-dif10" :access-value 1}) {:format :dif10}) c1-iso (d/ingest "PROV1" (dc/collection {:entry-title "c1-iso" :access-value 1}) {:format :iso19115}) c1-smap (d/ingest "PROV1" (dc/collection {:entry-title "c1-smap" :access-value 1}) {:format :iso-smap})] (index/wait-until-indexed) ;;;;system token sees everything (is (d/refs-match? [c1-echo c1-dif c1-dif10 c1-iso c1-smap] (search/find-refs :collection {:token (tc/echo-system-token)}))) ;;guest user sees nothing (is (d/refs-match? [] (search/find-refs :collection {:token guest-token}))))) (deftest collection-search-with-restriction-flag-acls-test (let [guest-token (e/login-guest (s/context)) c1-echo (d/ingest "PROV1" (dc/collection {:entry-title "c1-echo" :access-value 1}) {:format :echo10}) c2-echo (d/ingest "PROV1" (dc/collection {:entry-title "c2-echo" :access-value 0}) {:format :echo10}) c1-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c1-dif" :access-value 1}) {:format :dif}) c2-dif (d/ingest "PROV1" (dc/collection-dif {:entry-title "c2-dif" :access-value 0}) {:format :dif}) c1-dif10 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "c1-dif10" :access-value 1}) {:format :dif10}) c2-dif10 (d/ingest "PROV2" (dc/collection-dif10 {:entry-title "c2-dif10" :access-value 0}) {:format :dif10}) c1-iso (d/ingest "PROV1" (dc/collection {:entry-title "c1-iso" :access-value 1}) {:format :iso19115}) c2-iso (d/ingest "PROV1" (dc/collection {:entry-title "c2-iso" :access-value 0}) {:format :iso19115}) ;; access-value is not supported in ISO-SMAP, so it won't be found c1-smap (d/ingest "PROV1" (dc/collection {:entry-title "c1-smap" :access-value 1}) {:format :iso-smap}) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3"}))] (index/wait-until-indexed) ;; grant restriction flag acl (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["c1-echo" "c2-echo" "c1-dif" "c2-dif" "c1-dif10" "c1-iso" "c2-iso" "c1-smap" "coll3"] {:min-value 0.5 :max-value 1.5}))) (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) (is (d/refs-match? [c1-echo c1-dif c1-dif10 c1-iso] (search/find-refs :collection {:token guest-token}))))) (deftest collection-search-with-acls-test (let [group1-concept-id (e/get-or-create-group (s/context) "group1") group2-concept-id (e/get-or-create-group (s/context) "group2") group3-concept-id (e/get-or-create-group (s/context) "group3") coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1"})) coll2 (d/ingest "PROV1" (dc/collection {:entry-title "coll2"})) coll3 (d/ingest "PROV1" (dc/collection {:entry-title "coll3"})) coll4 (d/ingest "PROV1" (dc/collection {:entry-title "coll4" :access-value 5.0})) ;; no permission granted on coll5 coll5 (d/ingest "PROV1" (dc/collection {:entry-title "coll5"})) ;; PROV2 coll6 (d/ingest "PROV2" (dc/collection {:entry-title "coll6"})) coll7 (d/ingest "PROV2" (dc/collection {:entry-title "coll7"})) ;; A dif collection coll8 (d/ingest "PROV2" (dc/collection-dif {:entry-title "coll8" :short-name "S8" :version-id "V8" :long-name "coll8"}) {:format :dif}) ;; added for atom results coll8 (assoc coll8 :original-format "DIF") ;; PROV3 coll9 (d/ingest "PROV3" (dc/collection {:entry-title "coll9"})) coll10 (d/ingest "PROV3" (dc/collection {:entry-title "coll10" :access-value 12.0})) ;; PROV4 ;; group3 has permission to read this collection revision coll11-1 (d/ingest "PROV4" (dc/collection {:entry-title "coll11-entry-title" :native-id "coll11"})) ;; tombstone coll11-2 (assoc (ingest/delete-concept (d/item->concept coll11-1)) :entry-title "coll11-entry-title" :deleted true :revision-id 2) ;; no permissions to read this revision since entry-title has changed coll11-3 (d/ingest "PROV4" (dc/collection {:entry-title "coll11" :native-id "coll11"})) ;; group 3 has permission to read this collection revision coll12-1 (d/ingest "PROV4" (dc/collection {:entry-title "coll12-entry-title" :native-id "coll12"})) ;; no permissions to read this collection since entry-title has changed coll12-2 (d/ingest "PROV4" (dc/collection {:entry-title "coll12" :native-id "coll12"})) ;; no permision to see this tombstone since it has same entry-title as coll12-2 coll12-3 (assoc (ingest/delete-concept (d/item->concept coll12-2)) :deleted true :revision-id 2) all-colls [coll1 coll2 coll3 coll4 coll5 coll6 coll7 coll8 coll9 coll10] guest-permitted-collections [coll1 coll4 coll6 coll7 coll8 coll9] guest-token (e/login-guest (s/context)) user1-token (e/login (s/context) "user1") user2-token (e/login (s/context) "user2" [group1-concept-id]) user3-token (e/login (s/context) "user3" [group1-concept-id group2-concept-id]) user4-token (e/login (s/context) "user4" [group3-concept-id])] (index/wait-until-indexed) ;; Grant guests permission to coll1 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["notexist"]))) ;; restriction flag acl grants matches coll4 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll4"] {:min-value 4 :max-value 6}))) ;; Grant undefined access values in prov3 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV3" (e/coll-id nil {:include_undefined_value true}))) ;; all collections in prov2 granted to guests (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2")) ;; grant registered users permission to coll2 and coll4 (e/grant-registered-users (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll2" "coll4"]))) ;; grant specific group permission to coll3, coll6, and coll8 (e/grant-group (s/context) group1-concept-id (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll3"]))) (e/grant-group (s/context) group2-concept-id (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll6" "coll8"]))) (e/grant-group (s/context) group3-concept-id (e/coll-catalog-item-id "PROV4" (e/coll-id ["coll11-entry-title" "coll12-entry-title"]))) (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) (testing "parameter search acl enforcement" (are [token items] (d/refs-match? items (search/find-refs :collection (when token {:token token}))) ;; not logged in should be guest nil guest-permitted-collections ;; login and use guest token guest-token guest-permitted-collections ;; test searching as a user user1-token [coll2 coll4] ;; Test searching with users in groups user2-token [coll2 coll4 coll3] user3-token [coll2 coll4 coll3 coll6 coll8])) (testing "token can be sent through a header" (is (d/refs-match? [coll2 coll4] (search/find-refs :collection {} {:headers {"Echo-Token" user1-token}})))) (testing "aql search parameter enforcement" (is (d/refs-match? [coll2 coll4] (search/find-refs-with-aql :collection [] {} {:headers {"Echo-Token" user1-token}})))) (testing "Direct transformer retrieval acl enforcement" (testing "registered user" (d/assert-metadata-results-match :echo10 [coll2 coll4] (search/find-metadata :collection :echo10 {:token user1-token :concept-id (conj (map :concept-id all-colls) "C9999-PROV1")}))) (testing "guest access" (d/assert-metadata-results-match :echo10 guest-permitted-collections (search/find-metadata :collection :echo10 {:token guest-token :concept-id (map :concept-id all-colls)}))) (testing "Empty token matches guest access" (d/assert-metadata-results-match :echo10 guest-permitted-collections (search/find-metadata :collection :echo10 {:token "" :concept-id (map :concept-id all-colls)}))) (testing "user in groups" (d/assert-metadata-results-match :echo10 [coll4 coll6 coll3 coll8 coll2] (search/find-metadata :collection :echo10 {:token user3-token :concept-id (map :concept-id all-colls)})))) (testing "ATOM ACL enforcement" (testing "all items" (let [coll-atom (da/collections->expected-atom guest-permitted-collections (format "collections.atom?token=%s&page_size=100" guest-token))] (is (= coll-atom (:results (search/find-concepts-atom :collection {:token guest-token :page-size 100})))))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) coll-atom (da/collections->expected-atom guest-permitted-collections (str "collections.atom?token=" guest-token "&page_size=100&concept_id=" (str/join "&concept_id=" concept-ids)))] (is (= coll-atom (:results (search/find-concepts-atom :collection {:token guest-token :page-size 100 :concept-id concept-ids}))))))) (testing "JSON ACL enforcement" (testing "all items" (let [coll-json (da/collections->expected-atom guest-permitted-collections (format "collections.json?token=%s&page_size=100" guest-token))] (is (= coll-json (:results (search/find-concepts-json :collection {:token guest-token :page-size 100})))))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) coll-json (da/collections->expected-atom guest-permitted-collections (str "collections.json?token=" guest-token "&page_size=100&concept_id=" (str/join "&concept_id=" concept-ids)))] (is (= coll-json (:results (search/find-concepts-json :collection {:token guest-token :page-size 100 :concept-id concept-ids}))))))) (testing "opendata ACL enforcement" (testing "all items" (let [actual-od (search/find-concepts-opendata :collection {:token guest-token :page-size 100})] (od/assert-collection-opendata-results-match guest-permitted-collections actual-od))) (testing "by concept id" (let [concept-ids (map :concept-id all-colls) actual-od (search/find-concepts-opendata :collection {:token guest-token :page-size 100 :concept-id concept-ids})] (od/assert-collection-opendata-results-match guest-permitted-collections actual-od)))) (testing "all_revisions" (are2 [collections params] (d/refs-match? collections (search/find-refs :collection params)) ;; only old revisions satisfy ACL - they should not be returned "provider-id all-revisions=false" [] {:provider-id "PROV4" :all-revisions false :token user4-token} ;; only permissioned revisions are returned - including tombstones "provider-id all-revisions=true" [coll11-1 coll11-2 coll12-1] {:provider-id "PROV4" :all-revisions true :token user4-token} ;; none of the revisions are readable by guest users "provider-id all-revisions=true no token" [] {:provider-id "PROV4" :all-revisions true})))) ;; This tests that when acls change after collections have been indexed that collections will be ;; reindexed when ingest detects the acl hash has change. (deftest acl-change-test (let [coll1 (d/ingest "PROV1" (dc/collection-dif10 {:entry-title "coll1"}) {:format :dif10}) coll2-umm (dc/collection {:entry-title "coll2" :short-name "short1"}) coll2-1 (d/ingest "PROV1" coll2-umm) ;; 2 versions of collection 2 will allow us to test the force reindex option after we ;; force delete the latest version of coll2-2 coll2-2 (d/ingest "PROV1" (assoc-in coll2-umm [:product :short-name] "short2")) coll3 (d/ingest "PROV2" (dc/collection-dif10 {:entry-title "coll3"}) {:format :dif10}) coll4 (d/ingest "PROV2" (dc/collection {:entry-title "coll4"})) _ (index/wait-until-indexed) acl1 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) acl2 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll3"])))] (testing "normal reindex collection permitted groups" (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) ;; before acls change (is (d/refs-match? [coll1 coll3] (search/find-refs :collection {}))) ;; Grant collection 2 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll2"]))) ;; Ungrant collection 3 (e/ungrant (s/context) acl2) ;; Try searching again before the reindexing (is (d/refs-match? [coll1 coll3] (search/find-refs :collection {}))) ;; Reindex collection permitted groups (ingest/reindex-collection-permitted-groups (tc/echo-system-token)) (index/wait-until-indexed) ;; Search after reindexing (is (d/refs-match? [coll1 coll2-2] (search/find-refs :collection {})))) (testing "reindex all collections" ;; Grant collection 4 (e/grant-guest (s/context) (e/coll-catalog-item-id "PROV2" (e/coll-id ["coll4"]))) ;; Try before reindexing (is (d/refs-match? [coll1 coll2-2] (search/find-refs :collection {}))) ;; Reindex all collections ;; manually check the logs here. It should say it's reindexing provider 1 and provider 3 as well. (ingest/reindex-all-collections) (index/wait-until-indexed) ;; Search after reindexing (is (d/refs-match? [coll1 coll2-2 coll4] (search/find-refs :collection {})))) ;; Tests reindexing using the force current version option (testing "Force version reindex all collections" ;; Verify we can find coll2 with the lastest data (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; Delete the latest version of coll2 (is (= 200 (:status (mdb/force-delete-concept (:concept-id coll2-2) 2)))) (index/wait-until-indexed) ;; After deleting the latest version of coll2 we will still find that. (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; Reindexing all the collections doesn't solve the problem (ingest/reindex-all-collections) (index/wait-until-indexed) (d/assert-refs-match [coll2-2] (search/find-refs :collection {:short-name "short2"})) ;; A force reindex all collections will make elastic take the earlier version of the collections. (ingest/reindex-all-collections {:force-version true}) (index/wait-until-indexed) (d/assert-refs-match [] (search/find-refs :collection {:short-name "short2"})) (d/assert-refs-match [coll2-1] (search/find-refs :collection {:short-name "short1"}))))) ;; Verifies that tokens are cached by checking that a logged out token still works after it was used. ;; This isn't the desired behavior. It's just a side effect that shows it's working. (deftest cache-token-test (let [coll1 (d/ingest "PROV1" (dc/collection {:entry-title "coll1"})) acl1 (e/grant-registered-users (s/context) (e/coll-catalog-item-id "PROV1" (e/coll-id ["coll1"]))) user1-token (e/login (s/context) "user1") user2-token (e/login (s/context) "user2")] (index/wait-until-indexed) ;; A logged out token is normally not useful (e/logout (s/context) user2-token) (is (= {:errors ["Token ABC-2 does not exist"], :status 401} (search/find-refs :collection {:token user2-token}))) ;; Use user1-token so it will be cached (is (d/refs-match? [coll1] (search/find-refs :collection {:token user1-token}))) ;; logout (e/logout (s/context) user1-token) ;; The token should be cached (is (d/refs-match? [coll1] (search/find-refs :collection {:token user1-token})))))
[ { "context": "name)\n :user \"sa\"\n :password \"scott_tiger\"})\n\n(with-connection db\n\t(delete-rows :cities [\"i", "end": 544, "score": 0.9990989565849304, "start": 533, "tag": "PASSWORD", "value": "scott_tiger" } ]
mssql/clojure/delete/mssql_delete.clj
ekzemplaro/data_base_language
3
; ----------------------------------------------------------------- ; ; mssql_delete.clj ; ; Jul/17/2014 ; ; ----------------------------------------------------------------- (use 'clojure.java.jdbc) ; (println "*** 開始 ***") (let [db-host "host_mssql;" db-name "databaseName=city" id (first *command-line-args*) ] (println id) (def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver" :subprotocol "sqlserver" :subname (str "//" db-host db-name) :user "sa" :password "scott_tiger"}) (with-connection db (delete-rows :cities ["id=?" id]) )) (println "*** 終了 ***") ; -----------------------------------------------------------------
37876
; ----------------------------------------------------------------- ; ; mssql_delete.clj ; ; Jul/17/2014 ; ; ----------------------------------------------------------------- (use 'clojure.java.jdbc) ; (println "*** 開始 ***") (let [db-host "host_mssql;" db-name "databaseName=city" id (first *command-line-args*) ] (println id) (def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver" :subprotocol "sqlserver" :subname (str "//" db-host db-name) :user "sa" :password "<PASSWORD>"}) (with-connection db (delete-rows :cities ["id=?" id]) )) (println "*** 終了 ***") ; -----------------------------------------------------------------
true
; ----------------------------------------------------------------- ; ; mssql_delete.clj ; ; Jul/17/2014 ; ; ----------------------------------------------------------------- (use 'clojure.java.jdbc) ; (println "*** 開始 ***") (let [db-host "host_mssql;" db-name "databaseName=city" id (first *command-line-args*) ] (println id) (def db {:classname "com.microsoft.sqlserver.jdbc.SQLServerDriver" :subprotocol "sqlserver" :subname (str "//" db-host db-name) :user "sa" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (with-connection db (delete-rows :cities ["id=?" id]) )) (println "*** 終了 ***") ; -----------------------------------------------------------------
[ { "context": " (assoc-in [:session :user-login] \"valid@web.co.uk\")\n profile)]\n ", "end": 6664, "score": 0.999919593334198, "start": 6649, "tag": "EMAIL", "value": "valid@web.co.uk" }, { "context": " [:.clj--unconfirmed-email]) first html/text) => \"valid@web.co.uk\")))\n\n(facts \"about displaying authorised clients\"", "end": 6904, "score": 0.9999187588691711, "start": 6889, "tag": "EMAIL", "value": "valid@web.co.uk" }, { "context": " (assoc-in [:context :user-login] \"valid@web.co.uk\")\n (assoc-in [:context :user", "end": 8484, "score": 0.9999284148216248, "start": 8469, "tag": "EMAIL", "value": "valid@web.co.uk" }, { "context": " (assoc-in [:context :user-first-name] \"Frank\")\n (assoc-in [:context :user", "end": 8553, "score": 0.9997148513793945, "start": 8548, "tag": "NAME", "value": "Frank" }, { "context": " (assoc-in [:context :user-last-name] \"Lasty\")\n (assoc-in [:context :user", "end": 8621, "score": 0.9995620250701904, "start": 8616, "tag": "NAME", "value": "Lasty" }, { "context": "/select [:.clj--card-email]) first html/text) => \"valid@web.co.uk\")\n\n (fact \"it should display full name\"\n ", "end": 8899, "score": 0.9999276399612427, "start": 8884, "tag": "EMAIL", "value": "valid@web.co.uk" }, { "context": "l/select [:.clj--card-name]) first html/text) => \"Frank Lasty\")\n\n (fact \"it should display profile pict", "end": 9037, "score": 0.9992696642875671, "start": 9026, "tag": "NAME", "value": "Frank Lasty" } ]
test/stonecutter/test/view/profile.clj
d-cent/stonecutter
39
(ns stonecutter.test.view.profile (:require [midje.sweet :refer :all] [net.cgrand.enlive-html :as html] [stonecutter.routes :as r] [stonecutter.test.view.test-helpers :as th] [stonecutter.translation :as t] [stonecutter.view.profile :refer [profile]] [stonecutter.helper :as helper] [stonecutter.config :as config])) (fact "profile should return some html" (let [page (-> (th/create-request) profile)] (html/select page [:body]) =not=> empty?)) (fact "work in progress should be removed from page" (let [page (-> (th/create-request) profile)] page => th/work-in-progress-removed)) (fact "sign out link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--sign-out__link] :href (r/path :sign-out)))) (fact "profile link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--profile__link] :href (r/path :show-profile)))) (fact "change password link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-password__link] :href (r/path :show-change-password-form)))) (fact "change profile details link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-profile-details__link] :href (r/path :show-change-profile-form)))) (fact "change email link should go to the correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-email__link] :href (r/path :show-change-email-form)))) (fact "delete account link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--delete-account__link] :href (r/path :show-delete-account-confirmation)))) (fact "download vCard link should go to correct endpoint" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--download-vcard__link]) => (th/has-form-action? (r/path :download-vcard)))) (fact "update profile picture should post to correct endpoint" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--card-photo-upload]) => (th/has-form-action? (r/path :update-profile-image)))) (fact (let [translator (t/translations-fn t/translation-map) request (-> (th/create-request translator) (assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id "some-client-id"}]))] (th/test-translations "profile" profile request))) (fact "csrf token should be inserted" (let [page (-> (th/create-request) (assoc-in [:context :confirmed?] false) profile)] page => (th/element-exists? [:input#__anti-forgery-token]))) (facts "about displaying navigation bar" (fact "apps and users links are not displayed if the user role is not admin" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--apps-list__link])) => empty? (-> page (html/select [:.clj--users-list__link])) => empty?)) (fact "apps and users links are displayed and go to the correct endpoint if the user role is admin" (let [page (-> (th/create-request) (assoc-in [:session :role] (:admin config/roles)) profile)] (-> page (html/select [:.clj--apps-list__link])) =not=> empty? (-> page (html/select [:.clj--user-list__link])) =not=> empty? page => (th/has-attr? [:.clj--apps-list__link] :href (r/path :show-apps-list)) page => (th/has-attr? [:.clj--user-list__link] :href (r/path :show-user-list))))) (facts "about flash messages" (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--flash-message-container])) => empty?)) (tabular (fact "appropriate flash message is displayed on page when a flash key is included in the request" (let [page (-> (th/create-request) (assoc :flash ?flash-key) profile)] (-> page (html/select [:.clj--flash-message-container])) =not=> empty? (-> page (html/select [:.clj--flash-message-text]) first :attrs :data-l8n) => ?translation-key)) ?flash-key ?translation-key :email-changed "content:flash/email-changed" :password-changed "content:flash/password-changed" :email-confirmed "content:flash/email-confirmed" :confirmation-email-sent "content:flash/confirmation-email-sent" :email-already-confirmed "content:flash/email-already-confirmed")) (facts "about image upload errors" (fact "no errors are displayed by default" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--profile-image-error-container] :hidden "hidden"))) (tabular (fact "appropriate error message is displayed on page when an image error key is included in the request" (let [page (-> (th/create-request) (assoc :flash ?error-key) profile)] (-> page (html/select [:.clj--profile-image-error-container])) =not=> empty? (-> page (html/select [:.clj--profile-image-error-text]) first :attrs :data-l8n) => ?translation-key)) ?error-key ?translation-key :not-image "content:upload-profile-picture/file-not-image-validation-message" :too-large "content:upload-profile-picture/file-too-large-validation-message" :unsupported-extension "content:upload-profile-picture/file-type-not-supported-validation-message")) (facts "about displaying email confirmation status" (fact "the unconfirmed email message is removed when :confirmed? context is not false" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--unconfirmed-email-message-container])) => empty?)) (fact "accounts with unconfirmed email addresses display unconfirmed message as if it were a flash message" (let [page (-> (th/create-request) (assoc-in [:context :confirmed?] false) (assoc-in [:session :user-login] "valid@web.co.uk") profile)] (-> page (html/select [:.clj--unconfirmed-email-message-container])) =not=> empty? (-> page (html/select [:.clj--unconfirmed-email]) first html/text) => "valid@web.co.uk"))) (facts "about displaying authorised clients" (fact "names of authorised clients are displayed" (let [page (-> (th/create-request) (assoc-in [:context :authorised-clients] [{:name "Bloc Party"} {:name "Tabletennis Party"}]) profile)] (-> page (html/select [:.func--app__list]) first html/text) => (contains #"Bloc Party[\s\S]+Tabletennis Party"))) (fact "unshare card button links include the client_id query param" (let [client-id "bloc_party_client-id" page (-> (th/create-request) (assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id client-id}]) profile)] page => (th/has-attr? [:.clj--app-item__unshare-link] :href (str (r/path :show-unshare-profile-card) "?client_id=" client-id)))) (fact "empty application-list item is used when there are no authorised clients" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--authorised-app__list-item--empty]) =not=> empty? (html/select page [:.clj--authorised-app__list-item]) => empty?))) (facts "about displaying profile card" (let [page (-> (th/create-request) (assoc-in [:context :user-login] "valid@web.co.uk") (assoc-in [:context :user-first-name] "Frank") (assoc-in [:context :user-last-name] "Lasty") (assoc-in [:context :user-profile-picture] "/images/temp-avatar-300x300.png") profile)] (fact "it should display email address" (-> page (html/select [:.clj--card-email]) first html/text) => "valid@web.co.uk") (fact "it should display full name" (-> page (html/select [:.clj--card-name]) first html/text) => "Frank Lasty") (fact "it should display profile picture" (-> page (html/select [:.clj--card-image :img]) first :attrs :src) => "/images/temp-avatar-300x300.png")))
40344
(ns stonecutter.test.view.profile (:require [midje.sweet :refer :all] [net.cgrand.enlive-html :as html] [stonecutter.routes :as r] [stonecutter.test.view.test-helpers :as th] [stonecutter.translation :as t] [stonecutter.view.profile :refer [profile]] [stonecutter.helper :as helper] [stonecutter.config :as config])) (fact "profile should return some html" (let [page (-> (th/create-request) profile)] (html/select page [:body]) =not=> empty?)) (fact "work in progress should be removed from page" (let [page (-> (th/create-request) profile)] page => th/work-in-progress-removed)) (fact "sign out link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--sign-out__link] :href (r/path :sign-out)))) (fact "profile link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--profile__link] :href (r/path :show-profile)))) (fact "change password link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-password__link] :href (r/path :show-change-password-form)))) (fact "change profile details link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-profile-details__link] :href (r/path :show-change-profile-form)))) (fact "change email link should go to the correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-email__link] :href (r/path :show-change-email-form)))) (fact "delete account link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--delete-account__link] :href (r/path :show-delete-account-confirmation)))) (fact "download vCard link should go to correct endpoint" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--download-vcard__link]) => (th/has-form-action? (r/path :download-vcard)))) (fact "update profile picture should post to correct endpoint" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--card-photo-upload]) => (th/has-form-action? (r/path :update-profile-image)))) (fact (let [translator (t/translations-fn t/translation-map) request (-> (th/create-request translator) (assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id "some-client-id"}]))] (th/test-translations "profile" profile request))) (fact "csrf token should be inserted" (let [page (-> (th/create-request) (assoc-in [:context :confirmed?] false) profile)] page => (th/element-exists? [:input#__anti-forgery-token]))) (facts "about displaying navigation bar" (fact "apps and users links are not displayed if the user role is not admin" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--apps-list__link])) => empty? (-> page (html/select [:.clj--users-list__link])) => empty?)) (fact "apps and users links are displayed and go to the correct endpoint if the user role is admin" (let [page (-> (th/create-request) (assoc-in [:session :role] (:admin config/roles)) profile)] (-> page (html/select [:.clj--apps-list__link])) =not=> empty? (-> page (html/select [:.clj--user-list__link])) =not=> empty? page => (th/has-attr? [:.clj--apps-list__link] :href (r/path :show-apps-list)) page => (th/has-attr? [:.clj--user-list__link] :href (r/path :show-user-list))))) (facts "about flash messages" (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--flash-message-container])) => empty?)) (tabular (fact "appropriate flash message is displayed on page when a flash key is included in the request" (let [page (-> (th/create-request) (assoc :flash ?flash-key) profile)] (-> page (html/select [:.clj--flash-message-container])) =not=> empty? (-> page (html/select [:.clj--flash-message-text]) first :attrs :data-l8n) => ?translation-key)) ?flash-key ?translation-key :email-changed "content:flash/email-changed" :password-changed "content:flash/password-changed" :email-confirmed "content:flash/email-confirmed" :confirmation-email-sent "content:flash/confirmation-email-sent" :email-already-confirmed "content:flash/email-already-confirmed")) (facts "about image upload errors" (fact "no errors are displayed by default" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--profile-image-error-container] :hidden "hidden"))) (tabular (fact "appropriate error message is displayed on page when an image error key is included in the request" (let [page (-> (th/create-request) (assoc :flash ?error-key) profile)] (-> page (html/select [:.clj--profile-image-error-container])) =not=> empty? (-> page (html/select [:.clj--profile-image-error-text]) first :attrs :data-l8n) => ?translation-key)) ?error-key ?translation-key :not-image "content:upload-profile-picture/file-not-image-validation-message" :too-large "content:upload-profile-picture/file-too-large-validation-message" :unsupported-extension "content:upload-profile-picture/file-type-not-supported-validation-message")) (facts "about displaying email confirmation status" (fact "the unconfirmed email message is removed when :confirmed? context is not false" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--unconfirmed-email-message-container])) => empty?)) (fact "accounts with unconfirmed email addresses display unconfirmed message as if it were a flash message" (let [page (-> (th/create-request) (assoc-in [:context :confirmed?] false) (assoc-in [:session :user-login] "<EMAIL>") profile)] (-> page (html/select [:.clj--unconfirmed-email-message-container])) =not=> empty? (-> page (html/select [:.clj--unconfirmed-email]) first html/text) => "<EMAIL>"))) (facts "about displaying authorised clients" (fact "names of authorised clients are displayed" (let [page (-> (th/create-request) (assoc-in [:context :authorised-clients] [{:name "Bloc Party"} {:name "Tabletennis Party"}]) profile)] (-> page (html/select [:.func--app__list]) first html/text) => (contains #"Bloc Party[\s\S]+Tabletennis Party"))) (fact "unshare card button links include the client_id query param" (let [client-id "bloc_party_client-id" page (-> (th/create-request) (assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id client-id}]) profile)] page => (th/has-attr? [:.clj--app-item__unshare-link] :href (str (r/path :show-unshare-profile-card) "?client_id=" client-id)))) (fact "empty application-list item is used when there are no authorised clients" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--authorised-app__list-item--empty]) =not=> empty? (html/select page [:.clj--authorised-app__list-item]) => empty?))) (facts "about displaying profile card" (let [page (-> (th/create-request) (assoc-in [:context :user-login] "<EMAIL>") (assoc-in [:context :user-first-name] "<NAME>") (assoc-in [:context :user-last-name] "<NAME>") (assoc-in [:context :user-profile-picture] "/images/temp-avatar-300x300.png") profile)] (fact "it should display email address" (-> page (html/select [:.clj--card-email]) first html/text) => "<EMAIL>") (fact "it should display full name" (-> page (html/select [:.clj--card-name]) first html/text) => "<NAME>") (fact "it should display profile picture" (-> page (html/select [:.clj--card-image :img]) first :attrs :src) => "/images/temp-avatar-300x300.png")))
true
(ns stonecutter.test.view.profile (:require [midje.sweet :refer :all] [net.cgrand.enlive-html :as html] [stonecutter.routes :as r] [stonecutter.test.view.test-helpers :as th] [stonecutter.translation :as t] [stonecutter.view.profile :refer [profile]] [stonecutter.helper :as helper] [stonecutter.config :as config])) (fact "profile should return some html" (let [page (-> (th/create-request) profile)] (html/select page [:body]) =not=> empty?)) (fact "work in progress should be removed from page" (let [page (-> (th/create-request) profile)] page => th/work-in-progress-removed)) (fact "sign out link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--sign-out__link] :href (r/path :sign-out)))) (fact "profile link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--profile__link] :href (r/path :show-profile)))) (fact "change password link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-password__link] :href (r/path :show-change-password-form)))) (fact "change profile details link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-profile-details__link] :href (r/path :show-change-profile-form)))) (fact "change email link should go to the correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--change-email__link] :href (r/path :show-change-email-form)))) (fact "delete account link should go to correct endpoint" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--delete-account__link] :href (r/path :show-delete-account-confirmation)))) (fact "download vCard link should go to correct endpoint" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--download-vcard__link]) => (th/has-form-action? (r/path :download-vcard)))) (fact "update profile picture should post to correct endpoint" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--card-photo-upload]) => (th/has-form-action? (r/path :update-profile-image)))) (fact (let [translator (t/translations-fn t/translation-map) request (-> (th/create-request translator) (assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id "some-client-id"}]))] (th/test-translations "profile" profile request))) (fact "csrf token should be inserted" (let [page (-> (th/create-request) (assoc-in [:context :confirmed?] false) profile)] page => (th/element-exists? [:input#__anti-forgery-token]))) (facts "about displaying navigation bar" (fact "apps and users links are not displayed if the user role is not admin" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--apps-list__link])) => empty? (-> page (html/select [:.clj--users-list__link])) => empty?)) (fact "apps and users links are displayed and go to the correct endpoint if the user role is admin" (let [page (-> (th/create-request) (assoc-in [:session :role] (:admin config/roles)) profile)] (-> page (html/select [:.clj--apps-list__link])) =not=> empty? (-> page (html/select [:.clj--user-list__link])) =not=> empty? page => (th/has-attr? [:.clj--apps-list__link] :href (r/path :show-apps-list)) page => (th/has-attr? [:.clj--user-list__link] :href (r/path :show-user-list))))) (facts "about flash messages" (fact "no flash messages are displayed by default" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--flash-message-container])) => empty?)) (tabular (fact "appropriate flash message is displayed on page when a flash key is included in the request" (let [page (-> (th/create-request) (assoc :flash ?flash-key) profile)] (-> page (html/select [:.clj--flash-message-container])) =not=> empty? (-> page (html/select [:.clj--flash-message-text]) first :attrs :data-l8n) => ?translation-key)) ?flash-key ?translation-key :email-changed "content:flash/email-changed" :password-changed "content:flash/password-changed" :email-confirmed "content:flash/email-confirmed" :confirmation-email-sent "content:flash/confirmation-email-sent" :email-already-confirmed "content:flash/email-already-confirmed")) (facts "about image upload errors" (fact "no errors are displayed by default" (let [page (-> (th/create-request) profile)] page => (th/has-attr? [:.clj--profile-image-error-container] :hidden "hidden"))) (tabular (fact "appropriate error message is displayed on page when an image error key is included in the request" (let [page (-> (th/create-request) (assoc :flash ?error-key) profile)] (-> page (html/select [:.clj--profile-image-error-container])) =not=> empty? (-> page (html/select [:.clj--profile-image-error-text]) first :attrs :data-l8n) => ?translation-key)) ?error-key ?translation-key :not-image "content:upload-profile-picture/file-not-image-validation-message" :too-large "content:upload-profile-picture/file-too-large-validation-message" :unsupported-extension "content:upload-profile-picture/file-type-not-supported-validation-message")) (facts "about displaying email confirmation status" (fact "the unconfirmed email message is removed when :confirmed? context is not false" (let [page (-> (th/create-request) profile)] (-> page (html/select [:.clj--unconfirmed-email-message-container])) => empty?)) (fact "accounts with unconfirmed email addresses display unconfirmed message as if it were a flash message" (let [page (-> (th/create-request) (assoc-in [:context :confirmed?] false) (assoc-in [:session :user-login] "PI:EMAIL:<EMAIL>END_PI") profile)] (-> page (html/select [:.clj--unconfirmed-email-message-container])) =not=> empty? (-> page (html/select [:.clj--unconfirmed-email]) first html/text) => "PI:EMAIL:<EMAIL>END_PI"))) (facts "about displaying authorised clients" (fact "names of authorised clients are displayed" (let [page (-> (th/create-request) (assoc-in [:context :authorised-clients] [{:name "Bloc Party"} {:name "Tabletennis Party"}]) profile)] (-> page (html/select [:.func--app__list]) first html/text) => (contains #"Bloc Party[\s\S]+Tabletennis Party"))) (fact "unshare card button links include the client_id query param" (let [client-id "bloc_party_client-id" page (-> (th/create-request) (assoc-in [:context :authorised-clients] [{:name "Bloc Party" :client-id client-id}]) profile)] page => (th/has-attr? [:.clj--app-item__unshare-link] :href (str (r/path :show-unshare-profile-card) "?client_id=" client-id)))) (fact "empty application-list item is used when there are no authorised clients" (let [page (-> (th/create-request) profile)] (html/select page [:.clj--authorised-app__list-item--empty]) =not=> empty? (html/select page [:.clj--authorised-app__list-item]) => empty?))) (facts "about displaying profile card" (let [page (-> (th/create-request) (assoc-in [:context :user-login] "PI:EMAIL:<EMAIL>END_PI") (assoc-in [:context :user-first-name] "PI:NAME:<NAME>END_PI") (assoc-in [:context :user-last-name] "PI:NAME:<NAME>END_PI") (assoc-in [:context :user-profile-picture] "/images/temp-avatar-300x300.png") profile)] (fact "it should display email address" (-> page (html/select [:.clj--card-email]) first html/text) => "PI:EMAIL:<EMAIL>END_PI") (fact "it should display full name" (-> page (html/select [:.clj--card-name]) first html/text) => "PI:NAME:<NAME>END_PI") (fact "it should display profile picture" (-> page (html/select [:.clj--card-image :img]) first :attrs :src) => "/images/temp-avatar-300x300.png")))
[ { "context": "\"Client-side search results view.\"\n :author \"Eric Weinstein <eric.q.weinstein@gmail.com>\"}\n cityshelf.views.", "end": 75, "score": 0.9998883008956909, "start": 61, "tag": "NAME", "value": "Eric Weinstein" }, { "context": "rch results view.\"\n :author \"Eric Weinstein <eric.q.weinstein@gmail.com>\"}\n cityshelf.views.search\n (:require [cityshel", "end": 103, "score": 0.999931275844574, "start": 77, "tag": "EMAIL", "value": "eric.q.weinstein@gmail.com" } ]
src/cityshelf/views/search.cljs
ericqweinstein/cityshelf
0
(ns ^{:doc "Client-side search results view." :author "Eric Weinstein <eric.q.weinstein@gmail.com>"} cityshelf.views.search (:require [cityshelf.components.gallery :refer [gallery]] [cityshelf.components.search :refer [search]] [cityshelf.session :as session])) (defn index "The content for the search results page." [] [:div [search] [:h1.subheading "WHICH OF THESE BOOKS ARE YOU LOOKING FOR?"] [gallery (first (session/get! :results))]])
22067
(ns ^{:doc "Client-side search results view." :author "<NAME> <<EMAIL>>"} cityshelf.views.search (:require [cityshelf.components.gallery :refer [gallery]] [cityshelf.components.search :refer [search]] [cityshelf.session :as session])) (defn index "The content for the search results page." [] [:div [search] [:h1.subheading "WHICH OF THESE BOOKS ARE YOU LOOKING FOR?"] [gallery (first (session/get! :results))]])
true
(ns ^{:doc "Client-side search results view." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"} cityshelf.views.search (:require [cityshelf.components.gallery :refer [gallery]] [cityshelf.components.search :refer [search]] [cityshelf.session :as session])) (defn index "The content for the search results page." [] [:div [search] [:h1.subheading "WHICH OF THESE BOOKS ARE YOU LOOKING FOR?"] [gallery (first (session/get! :results))]])
[ { "context": "ts :is-many :Animal])\n\n(deftest test-diff\n (let [peter (human {:name \"Peter\" :age 17})\n paul (hu", "end": 8424, "score": 0.7235901951789856, "start": 8419, "tag": "NAME", "value": "peter" }, { "context": "\n\n(deftest test-diff\n (let [peter (human {:name \"Peter\" :age 17})\n paul (human {:name \"Paul\" :a", "end": 8445, "score": 0.9980630874633789, "start": 8440, "tag": "NAME", "value": "Peter" }, { "context": "let [peter (human {:name \"Peter\" :age 17})\n paul (human {:name \"Paul\" :age 18})\n #_mary ", "end": 8469, "score": 0.9777581691741943, "start": 8465, "tag": "NAME", "value": "paul" }, { "context": "me \"Peter\" :age 17})\n paul (human {:name \"Paul\" :age 18})\n #_mary #_(human {:name \"Mary", "end": 8490, "score": 0.9986299872398376, "start": 8486, "tag": "NAME", "value": "Paul" }, { "context": "Paul\" :age 18})\n #_mary #_(human {:name \"Mary\" :age 18 :pets [(dog {:name \"George\"}) (cat {:na", "end": 8540, "score": 0.9986134767532349, "start": 8536, "tag": "NAME", "value": "Mary" }, { "context": ") (cat {:name \"Ringo\"})]})]\n (is (= (diff peter paul)\n [{:name \"Peter\" :age 17} {:name \"Paul", "end": 8634, "score": 0.7518209218978882, "start": 8630, "tag": "NAME", "value": "paul" }, { "context": "\n (is (= (diff peter paul)\n [{:name \"Peter\" :age 17} {:name \"Paul\" :age 18} {}]))\n (is (=", "end": 8661, "score": 0.9968479871749878, "start": 8656, "tag": "NAME", "value": "Peter" }, { "context": "paul)\n [{:name \"Peter\" :age 17} {:name \"Paul\" :age 18} {}]))\n (is (= (diff peter (human {:n", "end": 8684, "score": 0.9978237152099609, "start": 8680, "tag": "NAME", "value": "Paul" }, { "context": "e 18} {}]))\n (is (= (diff peter (human {:name \"Peter\" :age 25}))\n [{:age 17} {:age 25} {:nam", "end": 8744, "score": 0.9980659484863281, "start": 8739, "tag": "NAME", "value": "Peter" }, { "context": "age 25}))\n [{:age 17} {:age 25} {:name \"Peter\"}]))\n (is (= (diff peter (human {:age 25}))\n ", "end": 8802, "score": 0.9970105886459351, "start": 8797, "tag": "NAME", "value": "Peter" }, { "context": "diff peter (human {:age 25}))\n [{:name \"Peter\" :age 17} {:age 25} {}]))\n\n #_(is (= (diff mar", "end": 8875, "score": 0.9982889890670776, "start": 8870, "tag": "NAME", "value": "Peter" }, { "context": "er\" :age 17} {:age 25} {}]))\n\n #_(is (= (diff mary (human {:name \"Mary\" :age 18 :pets [(cat {:name \"", "end": 8926, "score": 0.4205326437950134, "start": 8923, "tag": "NAME", "value": "ary" }, { "context": "25} {}]))\n\n #_(is (= (diff mary (human {:name \"Mary\" :age 18 :pets [(cat {:name \"Ringo\"}) (dog {:name", "end": 8946, "score": 0.9988216757774353, "start": 8942, "tag": "NAME", "value": "Mary" }, { "context": " [{} {} {:age 18,\n :name \"Mary\",\n :pets #{(cat {:name \"Ringo", "end": 9074, "score": 0.998332142829895, "start": 9070, "tag": "NAME", "value": "Mary" }, { "context": "\"Mary\",\n :pets #{(cat {:name \"Ringo\"}) (dog {:name \"George\"})}}]))))\n\n;;;;;;;;;;;;;;;", "end": 9124, "score": 0.9998359680175781, "start": 9119, "tag": "NAME", "value": "Ringo" }, { "context": " :pets #{(cat {:name \"Ringo\"}) (dog {:name \"George\"})}}]))))\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 9147, "score": 0.9998416900634766, "start": 9141, "tag": "NAME", "value": "George" } ]
test/spark/spec_tacular_test.clj
SparkFund/spec-tacular
105
(ns spark.spec-tacular-test (:use spark.spec-tacular clojure.test [spark.spec-tacular.generators :exclude [prop-check-components]]) (:require [clojure.core.typed :as t] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :as ct])) ;; ----------------------------------------------------------------------------- ;; defspec (defspec TestSpec1 [val1 :is-a :long :required] [val2 :is-a :string] [val3 :is-a :long :default-value 3] [val4 :is-a :keyword :default-value (fn [] :val)] [val5 :is-a :TestSpec3]) (deftest test-TestSpec1 (testing "valid" (is (some? (get-spec :TestSpec1))) (is (some? (get-spec :TestSpec1 :TestSpec1))) (is (some? (get-spec {:spec-tacular/spec :TestSpec1}))) (is (some? (get-spec (get-spec :TestSpec1)))) (let [good (testspec1 {:val1 3 :val2 "hi"})] (is (testspec1? good)) (is (= (:val1 good) 3)) (is (= (:val2 good) "hi")) (is (= (:val3 good) 3)) (is (= (:val4 good) :val)) (is (= (keys good) [:val1 :val2 :val3 :val4])) (testing "has-spec?" (is (has-spec? good)) (is (not (has-spec? 5))))) (is (= (count (into #{} [(testspec1 {:val1 5}) (testspec1 {:val1 5})])) 1))) (testing "invalid" (is (not (testspec1? {:val1 3 :val2 "hi"})) "not a record") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"required" (testspec1 {:val1 nil})) "missing required field") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"required" (testspec1 {:val2 1})) "missing required field") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"invalid type" (testspec1 {:val1 0 :val2 1})) "wrong type") (is (thrown? clojure.lang.ExceptionInfo (testspec1 {:val1 3 :extra-key true})) "extra key"))) ;; ----------------------------------------------------------------------------- ;; link (defspec TestSpec2 (:link [ts1 :is-a :TestSpec1])) (defspec TestSpec3) (deftest test-TestSpec2 (is (doall (testspec2 {:ts1 (testspec1 {:val1 42})}))) (testing "order of spec definition does not matter" (is (testspec1? (testspec1 {:val1 1 :val5 (testspec3)})))) (testing "links are not checked" (let [ts1 (i_TestSpec1. {::bad-key true} (atom {}) nil)] (is (testspec2 {:ts1 ts1}))))) ;; ----------------------------------------------------------------------------- ;; booleans, is-many (defspec TestSpec4 [val1 :is-a :boolean] [val2 :is-many :boolean]) (deftest test-TestSpec4 (testing "booleans" (is (some? (check-component! (get-spec :TestSpec4) :val1 false))) (is (testspec4? (testspec4 {:val1 false}))) (is (some? (re-find #"false" (pr-str (testspec4 {:val1 false}))))))) ;; ----------------------------------------------------------------------------- ;; required (defspec TestSpec5 [name :is-a :string :required]) (deftest test-TestSpec5 (testing "empty string" (is (some? (check-component! (get-spec :TestSpec5) :name ""))))) ;; ----------------------------------------------------------------------------- ;; forward references (defspec A [b :is-a :B]) (defspec B [a :is-a :A]) ;; ----------------------------------------------------------------------------- ;; unions (defunion testunion :TestSpec2 :TestSpec3) (defspec ES [foo :is-a :testunion]) (defspec ESParent [es :is-a :ES]) (deftest test-defunion (is (some? (get-spec :testunion))) (is (= (get-spec :testunion {:spec-tacular/spec :TestSpec2}) (get-spec :TestSpec2))) (is (= (:elements (get-spec :testunion)) #{:TestSpec2 :TestSpec3})) (is (testunion? (testspec2 {}))) (is (instance? spark.spec_tacular.spec.UnionSpec (get-spec :testunion))) (is (check-component! (get-spec :ES) :foo (testspec2 {}))) (is (thrown? clojure.lang.ExceptionInfo (check-component! (get-spec :ES) :foo :nope))) (is (thrown? clojure.lang.ExceptionInfo (es (testspec1 {:val1 1})))) (is (thrown? clojure.lang.ExceptionInfo (get-spec :testunion (testspec1 {:val1 1})))) (is (thrown? clojure.lang.ExceptionInfo (esparent {:es {:foo (testspec1 {:val1 1})}}))) (is (thrown? clojure.lang.ExceptionInfo (es {:foo (a {})})))) (defunion UnionFoo :UnionForward) (defspec UnionForward) (defspec TestSpec6 [union :is-many :UnionFoo]) ;; ----------------------------------------------------------------------------- ;; enums (defenum IsEnum how now brown cow) (defspec HasEnum [word :is-a :IsEnum] [words :is-many :IsEnum]) (deftest test-defenum (is (isenum? :IsEnum/how)) (is (isenum? :IsEnum/cow)) (is (= (get-spec :IsEnum) (get-spec :IsEnum/how) IsEnum)) (is (hasenum {:word :IsEnum/how})) (is (hasenum? (hasenum {:word :IsEnum/now}))) (is (isenum? (:word (hasenum {:word :IsEnum/brown})))) (is (every? isenum? (:words (hasenum {:words #{:IsEnum/how :IsEnum/cow}}))))) ;; ----------------------------------------------------------------------------- ;; complex (defspec Link (:link [ts1 :is-a :TestSpec1] [ts2 :is-many :TestSpec2]) [ts3 :is-a :TestSpec3] [ts4 :is-many :TestSpec4] [s1 :is-many :string]) (deftest test-refless= (is (refless= #{false} #{false})) (is (refless= #{nil} #{nil}))) (deftest test-link (let [many [(testspec2) (testspec2 {:ts1 (testspec1 {:val1 42})})] l (link {:ts1 (testspec1 {:val1 42}) :ts2 many :ts3 (testspec3) :ts4 [(testspec4 {:val1 false})]})] (is (link? l)) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not a map" (recursive-ctor :TestSpec2 many))) (is (= (:ts2 l) (set many))) (is (doall (with-out-str (prn l))))) (let [l (link {:s1 ["a" "b" "c"]})] (is (link? l))) (let [l (link {:ts3 nil})] (is (link? l)) (is (not (:ts3 l)))) (let [l1 (link {:ts3 (assoc (testspec3) :db-ref 1)})] (is (= (refless l1) (link {:ts3 (testspec3)})))) (let [l1 (link {:ts3 (testspec3 {:db-ref 1}) :db-ref 3}) l2 (link {:ts3 (testspec3 {:db-ref 2}) :db-ref 4})] (is (refless= [[[l1]]] [[[l2]]]) "refless equality")) (testing "is-many" (is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]}) (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]}))) (is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]}) (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]}))))) (defspec TestSpec7 [nums :is-many :long]) (deftest test-is-many (is (= (testspec7 {:nums [1 2 3 4]}) (testspec7 {:nums #{1 2 3 4}})))) (defspec TestSpec8 [day :is-a :calendarday]) (deftest test-calendarday (is (= (:day (assoc (testspec8) :day "2015-1-1")) (clj-time.core/date-time 2015 1 1)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; random testing (defn prop-check-components "property for verifying that check-component!, create!, and update! work correctly" [spec-key] (let [sp-gen (mk-spec-generator spec-key) spec (get-spec spec-key) gen (gen/bind sp-gen gen/return) fields (map :name (:items spec))] (prop/for-all [instance gen] (and (every? #(check-component! spec % (get instance %)) fields) (do (with-out-str (prn instance)) true))))) (ct/defspec gen-TestSpec3 100 (prop-check-components :TestSpec3)) (ct/defspec gen-TestSpec1 100 (prop-check-components :TestSpec1)) (ct/defspec gen-TestSpec2 100 (prop-check-components :TestSpec2)) (ct/defspec gen-TestSpec4 100 (prop-check-components :TestSpec4)) (ct/defspec gen-TestSpec5 100 (prop-check-components :TestSpec5)) (ct/defspec gen-testunion 100 (prop-check-components :testunion)) (ct/defspec gen-ES 100 (prop-check-components :ES)) (ct/defspec gen-ESParent 100 (prop-check-components :ESParent)) (ct/defspec gen-TestSpec6 100 (prop-check-components :TestSpec6)) (ct/defspec gen-Link 100 (prop-check-components :Link)) (ct/defspec gen-HasEnum 100 (prop-check-components :HasEnum)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; diff (defspec Human [name :is-a :string] [age :is-a :long] [pets :is-many :Animal]) (deftest test-diff (let [peter (human {:name "Peter" :age 17}) paul (human {:name "Paul" :age 18}) #_mary #_(human {:name "Mary" :age 18 :pets [(dog {:name "George"}) (cat {:name "Ringo"})]})] (is (= (diff peter paul) [{:name "Peter" :age 17} {:name "Paul" :age 18} {}])) (is (= (diff peter (human {:name "Peter" :age 25})) [{:age 17} {:age 25} {:name "Peter"}])) (is (= (diff peter (human {:age 25})) [{:name "Peter" :age 17} {:age 25} {}])) #_(is (= (diff mary (human {:name "Mary" :age 18 :pets [(cat {:name "Ringo"}) (dog {:name "George"})]})) [{} {} {:age 18, :name "Mary", :pets #{(cat {:name "Ringo"}) (dog {:name "George"})}}])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; docstrings (defspec Complicated "A complicated thing that really needs documentation" [name :is-a :string]) (defunion Complexity "Complexity is complicated" :Complicated) (defenum Complications "Simple isn't easy" Simple Easy) (deftest test-docstrings (is (= "A complicated thing that really needs documentation" (:doc (meta #'Complicated)))) (is (= "Complexity is complicated" (:doc (meta #'Complexity)))) (is (= "Simple isn't easy" (:doc (meta #'Complications))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns (def ns-specs (namespace->specs *ns*)) (deftest test-namespace->specs (let [[a b both] (clojure.data/diff (into #{} (map :name ns-specs)) #{:TestSpec1 :TestSpec2 :TestSpec3 :TestSpec4 :TestSpec5 :testunion :ES :ESParent :UnionFoo :UnionForward :A :B :Link :Human :TestSpec6 :TestSpec7 :IsEnum :HasEnum :TestSpec8 :Complicated :Complexity :Complications})] (is (= (count both) 22) "total number of specs") (is (nil? b) "no missing specs") (is (nil? a) "no extra specs")))
16591
(ns spark.spec-tacular-test (:use spark.spec-tacular clojure.test [spark.spec-tacular.generators :exclude [prop-check-components]]) (:require [clojure.core.typed :as t] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :as ct])) ;; ----------------------------------------------------------------------------- ;; defspec (defspec TestSpec1 [val1 :is-a :long :required] [val2 :is-a :string] [val3 :is-a :long :default-value 3] [val4 :is-a :keyword :default-value (fn [] :val)] [val5 :is-a :TestSpec3]) (deftest test-TestSpec1 (testing "valid" (is (some? (get-spec :TestSpec1))) (is (some? (get-spec :TestSpec1 :TestSpec1))) (is (some? (get-spec {:spec-tacular/spec :TestSpec1}))) (is (some? (get-spec (get-spec :TestSpec1)))) (let [good (testspec1 {:val1 3 :val2 "hi"})] (is (testspec1? good)) (is (= (:val1 good) 3)) (is (= (:val2 good) "hi")) (is (= (:val3 good) 3)) (is (= (:val4 good) :val)) (is (= (keys good) [:val1 :val2 :val3 :val4])) (testing "has-spec?" (is (has-spec? good)) (is (not (has-spec? 5))))) (is (= (count (into #{} [(testspec1 {:val1 5}) (testspec1 {:val1 5})])) 1))) (testing "invalid" (is (not (testspec1? {:val1 3 :val2 "hi"})) "not a record") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"required" (testspec1 {:val1 nil})) "missing required field") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"required" (testspec1 {:val2 1})) "missing required field") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"invalid type" (testspec1 {:val1 0 :val2 1})) "wrong type") (is (thrown? clojure.lang.ExceptionInfo (testspec1 {:val1 3 :extra-key true})) "extra key"))) ;; ----------------------------------------------------------------------------- ;; link (defspec TestSpec2 (:link [ts1 :is-a :TestSpec1])) (defspec TestSpec3) (deftest test-TestSpec2 (is (doall (testspec2 {:ts1 (testspec1 {:val1 42})}))) (testing "order of spec definition does not matter" (is (testspec1? (testspec1 {:val1 1 :val5 (testspec3)})))) (testing "links are not checked" (let [ts1 (i_TestSpec1. {::bad-key true} (atom {}) nil)] (is (testspec2 {:ts1 ts1}))))) ;; ----------------------------------------------------------------------------- ;; booleans, is-many (defspec TestSpec4 [val1 :is-a :boolean] [val2 :is-many :boolean]) (deftest test-TestSpec4 (testing "booleans" (is (some? (check-component! (get-spec :TestSpec4) :val1 false))) (is (testspec4? (testspec4 {:val1 false}))) (is (some? (re-find #"false" (pr-str (testspec4 {:val1 false}))))))) ;; ----------------------------------------------------------------------------- ;; required (defspec TestSpec5 [name :is-a :string :required]) (deftest test-TestSpec5 (testing "empty string" (is (some? (check-component! (get-spec :TestSpec5) :name ""))))) ;; ----------------------------------------------------------------------------- ;; forward references (defspec A [b :is-a :B]) (defspec B [a :is-a :A]) ;; ----------------------------------------------------------------------------- ;; unions (defunion testunion :TestSpec2 :TestSpec3) (defspec ES [foo :is-a :testunion]) (defspec ESParent [es :is-a :ES]) (deftest test-defunion (is (some? (get-spec :testunion))) (is (= (get-spec :testunion {:spec-tacular/spec :TestSpec2}) (get-spec :TestSpec2))) (is (= (:elements (get-spec :testunion)) #{:TestSpec2 :TestSpec3})) (is (testunion? (testspec2 {}))) (is (instance? spark.spec_tacular.spec.UnionSpec (get-spec :testunion))) (is (check-component! (get-spec :ES) :foo (testspec2 {}))) (is (thrown? clojure.lang.ExceptionInfo (check-component! (get-spec :ES) :foo :nope))) (is (thrown? clojure.lang.ExceptionInfo (es (testspec1 {:val1 1})))) (is (thrown? clojure.lang.ExceptionInfo (get-spec :testunion (testspec1 {:val1 1})))) (is (thrown? clojure.lang.ExceptionInfo (esparent {:es {:foo (testspec1 {:val1 1})}}))) (is (thrown? clojure.lang.ExceptionInfo (es {:foo (a {})})))) (defunion UnionFoo :UnionForward) (defspec UnionForward) (defspec TestSpec6 [union :is-many :UnionFoo]) ;; ----------------------------------------------------------------------------- ;; enums (defenum IsEnum how now brown cow) (defspec HasEnum [word :is-a :IsEnum] [words :is-many :IsEnum]) (deftest test-defenum (is (isenum? :IsEnum/how)) (is (isenum? :IsEnum/cow)) (is (= (get-spec :IsEnum) (get-spec :IsEnum/how) IsEnum)) (is (hasenum {:word :IsEnum/how})) (is (hasenum? (hasenum {:word :IsEnum/now}))) (is (isenum? (:word (hasenum {:word :IsEnum/brown})))) (is (every? isenum? (:words (hasenum {:words #{:IsEnum/how :IsEnum/cow}}))))) ;; ----------------------------------------------------------------------------- ;; complex (defspec Link (:link [ts1 :is-a :TestSpec1] [ts2 :is-many :TestSpec2]) [ts3 :is-a :TestSpec3] [ts4 :is-many :TestSpec4] [s1 :is-many :string]) (deftest test-refless= (is (refless= #{false} #{false})) (is (refless= #{nil} #{nil}))) (deftest test-link (let [many [(testspec2) (testspec2 {:ts1 (testspec1 {:val1 42})})] l (link {:ts1 (testspec1 {:val1 42}) :ts2 many :ts3 (testspec3) :ts4 [(testspec4 {:val1 false})]})] (is (link? l)) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not a map" (recursive-ctor :TestSpec2 many))) (is (= (:ts2 l) (set many))) (is (doall (with-out-str (prn l))))) (let [l (link {:s1 ["a" "b" "c"]})] (is (link? l))) (let [l (link {:ts3 nil})] (is (link? l)) (is (not (:ts3 l)))) (let [l1 (link {:ts3 (assoc (testspec3) :db-ref 1)})] (is (= (refless l1) (link {:ts3 (testspec3)})))) (let [l1 (link {:ts3 (testspec3 {:db-ref 1}) :db-ref 3}) l2 (link {:ts3 (testspec3 {:db-ref 2}) :db-ref 4})] (is (refless= [[[l1]]] [[[l2]]]) "refless equality")) (testing "is-many" (is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]}) (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]}))) (is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]}) (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]}))))) (defspec TestSpec7 [nums :is-many :long]) (deftest test-is-many (is (= (testspec7 {:nums [1 2 3 4]}) (testspec7 {:nums #{1 2 3 4}})))) (defspec TestSpec8 [day :is-a :calendarday]) (deftest test-calendarday (is (= (:day (assoc (testspec8) :day "2015-1-1")) (clj-time.core/date-time 2015 1 1)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; random testing (defn prop-check-components "property for verifying that check-component!, create!, and update! work correctly" [spec-key] (let [sp-gen (mk-spec-generator spec-key) spec (get-spec spec-key) gen (gen/bind sp-gen gen/return) fields (map :name (:items spec))] (prop/for-all [instance gen] (and (every? #(check-component! spec % (get instance %)) fields) (do (with-out-str (prn instance)) true))))) (ct/defspec gen-TestSpec3 100 (prop-check-components :TestSpec3)) (ct/defspec gen-TestSpec1 100 (prop-check-components :TestSpec1)) (ct/defspec gen-TestSpec2 100 (prop-check-components :TestSpec2)) (ct/defspec gen-TestSpec4 100 (prop-check-components :TestSpec4)) (ct/defspec gen-TestSpec5 100 (prop-check-components :TestSpec5)) (ct/defspec gen-testunion 100 (prop-check-components :testunion)) (ct/defspec gen-ES 100 (prop-check-components :ES)) (ct/defspec gen-ESParent 100 (prop-check-components :ESParent)) (ct/defspec gen-TestSpec6 100 (prop-check-components :TestSpec6)) (ct/defspec gen-Link 100 (prop-check-components :Link)) (ct/defspec gen-HasEnum 100 (prop-check-components :HasEnum)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; diff (defspec Human [name :is-a :string] [age :is-a :long] [pets :is-many :Animal]) (deftest test-diff (let [<NAME> (human {:name "<NAME>" :age 17}) <NAME> (human {:name "<NAME>" :age 18}) #_mary #_(human {:name "<NAME>" :age 18 :pets [(dog {:name "George"}) (cat {:name "Ringo"})]})] (is (= (diff peter <NAME>) [{:name "<NAME>" :age 17} {:name "<NAME>" :age 18} {}])) (is (= (diff peter (human {:name "<NAME>" :age 25})) [{:age 17} {:age 25} {:name "<NAME>"}])) (is (= (diff peter (human {:age 25})) [{:name "<NAME>" :age 17} {:age 25} {}])) #_(is (= (diff m<NAME> (human {:name "<NAME>" :age 18 :pets [(cat {:name "Ringo"}) (dog {:name "George"})]})) [{} {} {:age 18, :name "<NAME>", :pets #{(cat {:name "<NAME>"}) (dog {:name "<NAME>"})}}])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; docstrings (defspec Complicated "A complicated thing that really needs documentation" [name :is-a :string]) (defunion Complexity "Complexity is complicated" :Complicated) (defenum Complications "Simple isn't easy" Simple Easy) (deftest test-docstrings (is (= "A complicated thing that really needs documentation" (:doc (meta #'Complicated)))) (is (= "Complexity is complicated" (:doc (meta #'Complexity)))) (is (= "Simple isn't easy" (:doc (meta #'Complications))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns (def ns-specs (namespace->specs *ns*)) (deftest test-namespace->specs (let [[a b both] (clojure.data/diff (into #{} (map :name ns-specs)) #{:TestSpec1 :TestSpec2 :TestSpec3 :TestSpec4 :TestSpec5 :testunion :ES :ESParent :UnionFoo :UnionForward :A :B :Link :Human :TestSpec6 :TestSpec7 :IsEnum :HasEnum :TestSpec8 :Complicated :Complexity :Complications})] (is (= (count both) 22) "total number of specs") (is (nil? b) "no missing specs") (is (nil? a) "no extra specs")))
true
(ns spark.spec-tacular-test (:use spark.spec-tacular clojure.test [spark.spec-tacular.generators :exclude [prop-check-components]]) (:require [clojure.core.typed :as t] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :as ct])) ;; ----------------------------------------------------------------------------- ;; defspec (defspec TestSpec1 [val1 :is-a :long :required] [val2 :is-a :string] [val3 :is-a :long :default-value 3] [val4 :is-a :keyword :default-value (fn [] :val)] [val5 :is-a :TestSpec3]) (deftest test-TestSpec1 (testing "valid" (is (some? (get-spec :TestSpec1))) (is (some? (get-spec :TestSpec1 :TestSpec1))) (is (some? (get-spec {:spec-tacular/spec :TestSpec1}))) (is (some? (get-spec (get-spec :TestSpec1)))) (let [good (testspec1 {:val1 3 :val2 "hi"})] (is (testspec1? good)) (is (= (:val1 good) 3)) (is (= (:val2 good) "hi")) (is (= (:val3 good) 3)) (is (= (:val4 good) :val)) (is (= (keys good) [:val1 :val2 :val3 :val4])) (testing "has-spec?" (is (has-spec? good)) (is (not (has-spec? 5))))) (is (= (count (into #{} [(testspec1 {:val1 5}) (testspec1 {:val1 5})])) 1))) (testing "invalid" (is (not (testspec1? {:val1 3 :val2 "hi"})) "not a record") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"required" (testspec1 {:val1 nil})) "missing required field") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"required" (testspec1 {:val2 1})) "missing required field") (is (thrown-with-msg? clojure.lang.ExceptionInfo #"invalid type" (testspec1 {:val1 0 :val2 1})) "wrong type") (is (thrown? clojure.lang.ExceptionInfo (testspec1 {:val1 3 :extra-key true})) "extra key"))) ;; ----------------------------------------------------------------------------- ;; link (defspec TestSpec2 (:link [ts1 :is-a :TestSpec1])) (defspec TestSpec3) (deftest test-TestSpec2 (is (doall (testspec2 {:ts1 (testspec1 {:val1 42})}))) (testing "order of spec definition does not matter" (is (testspec1? (testspec1 {:val1 1 :val5 (testspec3)})))) (testing "links are not checked" (let [ts1 (i_TestSpec1. {::bad-key true} (atom {}) nil)] (is (testspec2 {:ts1 ts1}))))) ;; ----------------------------------------------------------------------------- ;; booleans, is-many (defspec TestSpec4 [val1 :is-a :boolean] [val2 :is-many :boolean]) (deftest test-TestSpec4 (testing "booleans" (is (some? (check-component! (get-spec :TestSpec4) :val1 false))) (is (testspec4? (testspec4 {:val1 false}))) (is (some? (re-find #"false" (pr-str (testspec4 {:val1 false}))))))) ;; ----------------------------------------------------------------------------- ;; required (defspec TestSpec5 [name :is-a :string :required]) (deftest test-TestSpec5 (testing "empty string" (is (some? (check-component! (get-spec :TestSpec5) :name ""))))) ;; ----------------------------------------------------------------------------- ;; forward references (defspec A [b :is-a :B]) (defspec B [a :is-a :A]) ;; ----------------------------------------------------------------------------- ;; unions (defunion testunion :TestSpec2 :TestSpec3) (defspec ES [foo :is-a :testunion]) (defspec ESParent [es :is-a :ES]) (deftest test-defunion (is (some? (get-spec :testunion))) (is (= (get-spec :testunion {:spec-tacular/spec :TestSpec2}) (get-spec :TestSpec2))) (is (= (:elements (get-spec :testunion)) #{:TestSpec2 :TestSpec3})) (is (testunion? (testspec2 {}))) (is (instance? spark.spec_tacular.spec.UnionSpec (get-spec :testunion))) (is (check-component! (get-spec :ES) :foo (testspec2 {}))) (is (thrown? clojure.lang.ExceptionInfo (check-component! (get-spec :ES) :foo :nope))) (is (thrown? clojure.lang.ExceptionInfo (es (testspec1 {:val1 1})))) (is (thrown? clojure.lang.ExceptionInfo (get-spec :testunion (testspec1 {:val1 1})))) (is (thrown? clojure.lang.ExceptionInfo (esparent {:es {:foo (testspec1 {:val1 1})}}))) (is (thrown? clojure.lang.ExceptionInfo (es {:foo (a {})})))) (defunion UnionFoo :UnionForward) (defspec UnionForward) (defspec TestSpec6 [union :is-many :UnionFoo]) ;; ----------------------------------------------------------------------------- ;; enums (defenum IsEnum how now brown cow) (defspec HasEnum [word :is-a :IsEnum] [words :is-many :IsEnum]) (deftest test-defenum (is (isenum? :IsEnum/how)) (is (isenum? :IsEnum/cow)) (is (= (get-spec :IsEnum) (get-spec :IsEnum/how) IsEnum)) (is (hasenum {:word :IsEnum/how})) (is (hasenum? (hasenum {:word :IsEnum/now}))) (is (isenum? (:word (hasenum {:word :IsEnum/brown})))) (is (every? isenum? (:words (hasenum {:words #{:IsEnum/how :IsEnum/cow}}))))) ;; ----------------------------------------------------------------------------- ;; complex (defspec Link (:link [ts1 :is-a :TestSpec1] [ts2 :is-many :TestSpec2]) [ts3 :is-a :TestSpec3] [ts4 :is-many :TestSpec4] [s1 :is-many :string]) (deftest test-refless= (is (refless= #{false} #{false})) (is (refless= #{nil} #{nil}))) (deftest test-link (let [many [(testspec2) (testspec2 {:ts1 (testspec1 {:val1 42})})] l (link {:ts1 (testspec1 {:val1 42}) :ts2 many :ts3 (testspec3) :ts4 [(testspec4 {:val1 false})]})] (is (link? l)) (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not a map" (recursive-ctor :TestSpec2 many))) (is (= (:ts2 l) (set many))) (is (doall (with-out-str (prn l))))) (let [l (link {:s1 ["a" "b" "c"]})] (is (link? l))) (let [l (link {:ts3 nil})] (is (link? l)) (is (not (:ts3 l)))) (let [l1 (link {:ts3 (assoc (testspec3) :db-ref 1)})] (is (= (refless l1) (link {:ts3 (testspec3)})))) (let [l1 (link {:ts3 (testspec3 {:db-ref 1}) :db-ref 3}) l2 (link {:ts3 (testspec3 {:db-ref 2}) :db-ref 4})] (is (refless= [[[l1]]] [[[l2]]]) "refless equality")) (testing "is-many" (is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]}) (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]}))) (is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]}) (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]}))))) (defspec TestSpec7 [nums :is-many :long]) (deftest test-is-many (is (= (testspec7 {:nums [1 2 3 4]}) (testspec7 {:nums #{1 2 3 4}})))) (defspec TestSpec8 [day :is-a :calendarday]) (deftest test-calendarday (is (= (:day (assoc (testspec8) :day "2015-1-1")) (clj-time.core/date-time 2015 1 1)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; random testing (defn prop-check-components "property for verifying that check-component!, create!, and update! work correctly" [spec-key] (let [sp-gen (mk-spec-generator spec-key) spec (get-spec spec-key) gen (gen/bind sp-gen gen/return) fields (map :name (:items spec))] (prop/for-all [instance gen] (and (every? #(check-component! spec % (get instance %)) fields) (do (with-out-str (prn instance)) true))))) (ct/defspec gen-TestSpec3 100 (prop-check-components :TestSpec3)) (ct/defspec gen-TestSpec1 100 (prop-check-components :TestSpec1)) (ct/defspec gen-TestSpec2 100 (prop-check-components :TestSpec2)) (ct/defspec gen-TestSpec4 100 (prop-check-components :TestSpec4)) (ct/defspec gen-TestSpec5 100 (prop-check-components :TestSpec5)) (ct/defspec gen-testunion 100 (prop-check-components :testunion)) (ct/defspec gen-ES 100 (prop-check-components :ES)) (ct/defspec gen-ESParent 100 (prop-check-components :ESParent)) (ct/defspec gen-TestSpec6 100 (prop-check-components :TestSpec6)) (ct/defspec gen-Link 100 (prop-check-components :Link)) (ct/defspec gen-HasEnum 100 (prop-check-components :HasEnum)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; diff (defspec Human [name :is-a :string] [age :is-a :long] [pets :is-many :Animal]) (deftest test-diff (let [PI:NAME:<NAME>END_PI (human {:name "PI:NAME:<NAME>END_PI" :age 17}) PI:NAME:<NAME>END_PI (human {:name "PI:NAME:<NAME>END_PI" :age 18}) #_mary #_(human {:name "PI:NAME:<NAME>END_PI" :age 18 :pets [(dog {:name "George"}) (cat {:name "Ringo"})]})] (is (= (diff peter PI:NAME:<NAME>END_PI) [{:name "PI:NAME:<NAME>END_PI" :age 17} {:name "PI:NAME:<NAME>END_PI" :age 18} {}])) (is (= (diff peter (human {:name "PI:NAME:<NAME>END_PI" :age 25})) [{:age 17} {:age 25} {:name "PI:NAME:<NAME>END_PI"}])) (is (= (diff peter (human {:age 25})) [{:name "PI:NAME:<NAME>END_PI" :age 17} {:age 25} {}])) #_(is (= (diff mPI:NAME:<NAME>END_PI (human {:name "PI:NAME:<NAME>END_PI" :age 18 :pets [(cat {:name "Ringo"}) (dog {:name "George"})]})) [{} {} {:age 18, :name "PI:NAME:<NAME>END_PI", :pets #{(cat {:name "PI:NAME:<NAME>END_PI"}) (dog {:name "PI:NAME:<NAME>END_PI"})}}])))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; docstrings (defspec Complicated "A complicated thing that really needs documentation" [name :is-a :string]) (defunion Complexity "Complexity is complicated" :Complicated) (defenum Complications "Simple isn't easy" Simple Easy) (deftest test-docstrings (is (= "A complicated thing that really needs documentation" (:doc (meta #'Complicated)))) (is (= "Complexity is complicated" (:doc (meta #'Complexity)))) (is (= "Simple isn't easy" (:doc (meta #'Complications))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns (def ns-specs (namespace->specs *ns*)) (deftest test-namespace->specs (let [[a b both] (clojure.data/diff (into #{} (map :name ns-specs)) #{:TestSpec1 :TestSpec2 :TestSpec3 :TestSpec4 :TestSpec5 :testunion :ES :ESParent :UnionFoo :UnionForward :A :B :Link :Human :TestSpec6 :TestSpec7 :IsEnum :HasEnum :TestSpec8 :Complicated :Complexity :Complications})] (is (= (count both) 22) "total number of specs") (is (nil? b) "no missing specs") (is (nil? a) "no extra specs")))
[ { "context": "redicate Logic, tests\n\n; Copyright (c) 2016 - 2020 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 91, "score": 0.9998735785484314, "start": 77, "tag": "NAME", "value": "Burkhardt Renz" } ]
test/lwb/pred/sat_test.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Predicate Logic, tests ; Copyright (c) 2016 - 2020 Burkhardt Renz, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.pred.sat-test (:require [clojure.test :refer :all] [lwb.pred.sat :refer :all] [clojure.spec.test.alpha :as stest])) (stest/instrument) (deftest sat-intern-test1 (is (= (#'lwb.pred.sat/sat-intern 'R {'R [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(not R) {'R [:pred 0]} #{:e1 :e2} :one) {'R #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R Q (not S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(or R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(impl R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(equiv R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(xor R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and (not R) (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, 'S #{[:e1]}, :univ #{:e1 :e2}})) ) (deftest sat-intern-test2 (is (= (#'lwb.pred.sat/sat-intern '(forall [x] (= x (f x))) {'f [:func 1]} #{:e1 :e2} :one) {'f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(exists [x y] (and (not (= x y)) (= x (f x)) (= y (f y)))) {'f [:func 1]} #{:e1 :e2} :all) '({f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}}))) (is (= (#'lwb.pred.sat/sat-intern '(forall [x] (R x)) {'R [:pred 1]} #{:e1 :e2 :e3} :one) {'R #{[:e3] [:e1] [:e2]} :univ #{:e1 :e2 :e3}})) ) (run-tests)
4275
; lwb Logic WorkBench -- Predicate Logic, tests ; Copyright (c) 2016 - 2020 <NAME>, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.pred.sat-test (:require [clojure.test :refer :all] [lwb.pred.sat :refer :all] [clojure.spec.test.alpha :as stest])) (stest/instrument) (deftest sat-intern-test1 (is (= (#'lwb.pred.sat/sat-intern 'R {'R [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(not R) {'R [:pred 0]} #{:e1 :e2} :one) {'R #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R Q (not S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(or R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(impl R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(equiv R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(xor R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and (not R) (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, 'S #{[:e1]}, :univ #{:e1 :e2}})) ) (deftest sat-intern-test2 (is (= (#'lwb.pred.sat/sat-intern '(forall [x] (= x (f x))) {'f [:func 1]} #{:e1 :e2} :one) {'f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(exists [x y] (and (not (= x y)) (= x (f x)) (= y (f y)))) {'f [:func 1]} #{:e1 :e2} :all) '({f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}}))) (is (= (#'lwb.pred.sat/sat-intern '(forall [x] (R x)) {'R [:pred 1]} #{:e1 :e2 :e3} :one) {'R #{[:e3] [:e1] [:e2]} :univ #{:e1 :e2 :e3}})) ) (run-tests)
true
; lwb Logic WorkBench -- Predicate Logic, tests ; Copyright (c) 2016 - 2020 PI:NAME:<NAME>END_PI, THM. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php). ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.pred.sat-test (:require [clojure.test :refer :all] [lwb.pred.sat :refer :all] [clojure.spec.test.alpha :as stest])) (stest/instrument) (deftest sat-intern-test1 (is (= (#'lwb.pred.sat/sat-intern 'R {'R [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(not R) {'R [:pred 0]} #{:e1 :e2} :one) {'R #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R Q (not S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(or R Q S) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(impl R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(equiv R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(xor R Q) {'R [:pred 0] 'Q [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{[:e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and R (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{[:e1]}, 'Q #{[:e1]}, 'S #{}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(and (not R) (ite R Q S)) {'R [:pred 0] 'Q [:pred 0] 'S [:pred 0]} #{:e1 :e2} :one) {'R #{}, 'Q #{}, 'S #{[:e1]}, :univ #{:e1 :e2}})) ) (deftest sat-intern-test2 (is (= (#'lwb.pred.sat/sat-intern '(forall [x] (= x (f x))) {'f [:func 1]} #{:e1 :e2} :one) {'f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}})) (is (= (#'lwb.pred.sat/sat-intern '(exists [x y] (and (not (= x y)) (= x (f x)) (= y (f y)))) {'f [:func 1]} #{:e1 :e2} :all) '({f #{[:e2 :e2] [:e1 :e1]}, :univ #{:e1 :e2}}))) (is (= (#'lwb.pred.sat/sat-intern '(forall [x] (R x)) {'R [:pred 1]} #{:e1 :e2 :e3} :one) {'R #{[:e3] [:e1] [:e2]} :univ #{:e1 :e2 :e3}})) ) (run-tests)
[ { "context": "\"center\"})\n\n(defn header []\n [intro\n [heading \"Aron Strandberg\"]])\n\n(defn about []\n [section\n [heading \"About", "end": 1158, "score": 0.9995479583740234, "start": 1143, "tag": "NAME", "value": "Aron Strandberg" } ]
src/as/components.cljs
aronstrandberg/aron
0
(ns as.components (:require [reagent.core :as r] [cljss.reagent :refer-macros [defstyled]])) (def text-color "#f8f9f8") (def background "#f92b28") (defstyled container :div {:width "100%" :min-height "100vh" :display "flex" :flex-direction "column" :justify-content "center" :align-items "center" :background-color background}) (defstyled section :div {:flex "1" :width "90%" :max-width "40rem" :display "flex" :flex-direction "column" :align-items "flex-start" :justify-content "center" :text-align "left"}) (defstyled heading :h4 {:text-transform "uppercase" :font-weight 400 :letter-spacing "0.05em" :text-align "left" :color text-color}) (defstyled text :p {:font-size "1rem" :line-height 1.6 :color text-color :text-align "left" :margin 0}) (defstyled intro :div {:height "20vh" :display "flex" :flex-direction "column" :justify-content "center" :align-items "center"}) (defstyled f :div {:margin "3rem 0" :width "100%" :display "flex" :justify-content "center" :text-align "center"}) (defn header [] [intro [heading "Aron Strandberg"]]) (defn about [] [section [heading "About me"] [text "I'm a software developer from Stockholm, Sweden. I'm currently pursuing a Master's degree in computer science at the Royal Institute of Technology. Besides programming, I'm interested in fashion, photography, and bartending."]]) (defn work [] [section [heading "Work"] [text "Currently, I'm working with digital health care at " [:a {:href "http://kry.se"} "KRY"] ". Previously, I've worked with financial APIs at " [:a {:href "http://www.trioptima.com"} "TriOptima"] ", and university recruitment solutions at " [:a {:href "http://sqore.com"} "Sqore"] ". Besides software development, I've also worked as a bartender, art director, and team leader at DKM, and as a photographer at " [:a {:href "http://osqledaren.se"} "Osqledaren"] "."]]) (defn studs [] [section [heading "Projects — Studs"] [text "I served as Art Director for the student project " [:a {:href "http://studieresan.se"} "Studs"] " in 2018. As part of the project's design team, I helped develop the graphical profile, designed print work, and designed and developed a React frontend for " [:a {:href "http://studieresan.se"} "studieresan.se"] "."]]) (defn izumi [] [section [heading "Projects — Izumi"] [text [:a {:href "http://izumi.netlify.com"} "Izumi"] " is a Tabata timer. Unable to find a decent Tabata timer for HIIT training, I set out to create my own. Izumi is built using React and Redux."]]) (defn footer [] [section [f {:dangerouslySetInnerHTML {:__html "&times;"}}]]) (defn home-page [] [container [header] [about] [work] [studs] [izumi] [footer]])
69742
(ns as.components (:require [reagent.core :as r] [cljss.reagent :refer-macros [defstyled]])) (def text-color "#f8f9f8") (def background "#f92b28") (defstyled container :div {:width "100%" :min-height "100vh" :display "flex" :flex-direction "column" :justify-content "center" :align-items "center" :background-color background}) (defstyled section :div {:flex "1" :width "90%" :max-width "40rem" :display "flex" :flex-direction "column" :align-items "flex-start" :justify-content "center" :text-align "left"}) (defstyled heading :h4 {:text-transform "uppercase" :font-weight 400 :letter-spacing "0.05em" :text-align "left" :color text-color}) (defstyled text :p {:font-size "1rem" :line-height 1.6 :color text-color :text-align "left" :margin 0}) (defstyled intro :div {:height "20vh" :display "flex" :flex-direction "column" :justify-content "center" :align-items "center"}) (defstyled f :div {:margin "3rem 0" :width "100%" :display "flex" :justify-content "center" :text-align "center"}) (defn header [] [intro [heading "<NAME>"]]) (defn about [] [section [heading "About me"] [text "I'm a software developer from Stockholm, Sweden. I'm currently pursuing a Master's degree in computer science at the Royal Institute of Technology. Besides programming, I'm interested in fashion, photography, and bartending."]]) (defn work [] [section [heading "Work"] [text "Currently, I'm working with digital health care at " [:a {:href "http://kry.se"} "KRY"] ". Previously, I've worked with financial APIs at " [:a {:href "http://www.trioptima.com"} "TriOptima"] ", and university recruitment solutions at " [:a {:href "http://sqore.com"} "Sqore"] ". Besides software development, I've also worked as a bartender, art director, and team leader at DKM, and as a photographer at " [:a {:href "http://osqledaren.se"} "Osqledaren"] "."]]) (defn studs [] [section [heading "Projects — Studs"] [text "I served as Art Director for the student project " [:a {:href "http://studieresan.se"} "Studs"] " in 2018. As part of the project's design team, I helped develop the graphical profile, designed print work, and designed and developed a React frontend for " [:a {:href "http://studieresan.se"} "studieresan.se"] "."]]) (defn izumi [] [section [heading "Projects — Izumi"] [text [:a {:href "http://izumi.netlify.com"} "Izumi"] " is a Tabata timer. Unable to find a decent Tabata timer for HIIT training, I set out to create my own. Izumi is built using React and Redux."]]) (defn footer [] [section [f {:dangerouslySetInnerHTML {:__html "&times;"}}]]) (defn home-page [] [container [header] [about] [work] [studs] [izumi] [footer]])
true
(ns as.components (:require [reagent.core :as r] [cljss.reagent :refer-macros [defstyled]])) (def text-color "#f8f9f8") (def background "#f92b28") (defstyled container :div {:width "100%" :min-height "100vh" :display "flex" :flex-direction "column" :justify-content "center" :align-items "center" :background-color background}) (defstyled section :div {:flex "1" :width "90%" :max-width "40rem" :display "flex" :flex-direction "column" :align-items "flex-start" :justify-content "center" :text-align "left"}) (defstyled heading :h4 {:text-transform "uppercase" :font-weight 400 :letter-spacing "0.05em" :text-align "left" :color text-color}) (defstyled text :p {:font-size "1rem" :line-height 1.6 :color text-color :text-align "left" :margin 0}) (defstyled intro :div {:height "20vh" :display "flex" :flex-direction "column" :justify-content "center" :align-items "center"}) (defstyled f :div {:margin "3rem 0" :width "100%" :display "flex" :justify-content "center" :text-align "center"}) (defn header [] [intro [heading "PI:NAME:<NAME>END_PI"]]) (defn about [] [section [heading "About me"] [text "I'm a software developer from Stockholm, Sweden. I'm currently pursuing a Master's degree in computer science at the Royal Institute of Technology. Besides programming, I'm interested in fashion, photography, and bartending."]]) (defn work [] [section [heading "Work"] [text "Currently, I'm working with digital health care at " [:a {:href "http://kry.se"} "KRY"] ". Previously, I've worked with financial APIs at " [:a {:href "http://www.trioptima.com"} "TriOptima"] ", and university recruitment solutions at " [:a {:href "http://sqore.com"} "Sqore"] ". Besides software development, I've also worked as a bartender, art director, and team leader at DKM, and as a photographer at " [:a {:href "http://osqledaren.se"} "Osqledaren"] "."]]) (defn studs [] [section [heading "Projects — Studs"] [text "I served as Art Director for the student project " [:a {:href "http://studieresan.se"} "Studs"] " in 2018. As part of the project's design team, I helped develop the graphical profile, designed print work, and designed and developed a React frontend for " [:a {:href "http://studieresan.se"} "studieresan.se"] "."]]) (defn izumi [] [section [heading "Projects — Izumi"] [text [:a {:href "http://izumi.netlify.com"} "Izumi"] " is a Tabata timer. Unable to find a decent Tabata timer for HIIT training, I set out to create my own. Izumi is built using React and Redux."]]) (defn footer [] [section [f {:dangerouslySetInnerHTML {:__html "&times;"}}]]) (defn home-page [] [container [header] [about] [work] [studs] [izumi] [footer]])
[ { "context": ";\n; Copyright 2021, 2022 Dmitrii Pisarenko\n;\n; Permission is hereby granted, free of charge,", "end": 42, "score": 0.9998501539230347, "start": 25, "tag": "NAME", "value": "Dmitrii Pisarenko" } ]
process-engine/src/main/resources/com/dpisarenko/common.clj
mentiflectax/minimal-crypto-exchange
0
; ; Copyright 2021, 2022 Dmitrii Pisarenko ; ; 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 com.dpisarenko.common) ; Macros (start) (defmacro log-info [msg] (list '. 'logger 'info msg) ) (defmacro now [] (list 'new 'java.util.Date)) ; Macros (end)
27149
; ; Copyright 2021, 2022 <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 com.dpisarenko.common) ; Macros (start) (defmacro log-info [msg] (list '. 'logger 'info msg) ) (defmacro now [] (list 'new 'java.util.Date)) ; Macros (end)
true
; ; Copyright 2021, 2022 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 com.dpisarenko.common) ; Macros (start) (defmacro log-info [msg] (list '. 'logger 'info msg) ) (defmacro now [] (list 'new 'java.util.Date)) ; Macros (end)
[ { "context": " (env-str :pgdatabase))]\n [\"-U\" \"--username PGUSER\" \"Database User\"\n :default-fn (fn [_]\n ", "end": 1265, "score": 0.8978508710861206, "start": 1259, "tag": "USERNAME", "value": "PGUSER" }, { "context": " (env-str :pguser))]\n [\"-P\" \"--password PGPASSWORD\" \"Database User's Password\"\n :default-fn (fn [", "end": 1376, "score": 0.9153351783752441, "start": 1366, "tag": "PASSWORD", "value": "PGPASSWORD" } ]
src/clj/pgmig/main.clj
borkdude/pgmig
82
(ns pgmig.main (:require [pgmig.migration :as migration] [environ.core :as environ] [mount.core :as mount] [clojure.string :as str] [clojure.tools.cli :as cli] [taoensso.timbre :as log] [pgmig.config :as config] [clojure.java.io :as io]) (:gen-class)) (def env (atom {})) (defn env-str [k] (get @env k)) (defn env-int [k] (when-let [es (env-str k)] (Long/parseLong es))) (defn env-kw [k] (when-let [es (env-str k)] (keyword es))) (def cli-options [["-a" "--adapter ADAPTER" "Database Adapter" :default-fn (fn [_] (or (env-str :adapter) "postgresql")) :default-desc "postgresql"] ["-h" "--host PGHOST" "Database Host Address" :default-fn (fn [_] (or (env-str :pghost) "localhost")) :default-desc "localhost"] ["-p" "--port PGPORT" "Database Port Number" :default-fn (fn [_] (or (env-int :pgport) 5432)) :default-desc "5432" :parse-fn #(Integer/parseInt %)] ["-d" "--dbname PGDATABASE" "Database Name" :default-fn (fn [_] (env-str :pgdatabase))] ["-U" "--username PGUSER" "Database User" :default-fn (fn [_] (env-str :pguser))] ["-P" "--password PGPASSWORD" "Database User's Password" :default-fn (fn [_] (env-str :pgpassword))] ["-j" "--jdbc-url JDBC_URL" "JDBC Connection URL" :default-fn (fn [_] (env-str :jdbc-url))] ["-r" "--resource-dir RESOURCE_DIR" "Resources Directory" :default-fn (fn [_] (or (env-str :resource-dir) config/DEFAULT-MIGRATION-DIR)) :default-desc config/DEFAULT-MIGRATION-DIR] ["-l" "--level LEVEL" "Verbosity Level (trace/debug/info/warn/error)" :default-fn (fn [_] (or (env-kw :level) :warn)) :default-desc "warn" :parse-fn (comp keyword str/lower-case)] ["-f" "--format " "Migration FORMAT (sql/clj/edn)" :default-fn (fn [_] (or (env-kw :format) :sql)) :default-desc "sql" :parse-fn (comp keyword str/lower-case)] ["-c" "--classpath " "Classpath for migration support code" :default-fn (fn [_] (or (env-str :classpath) "."))] ["-V" "--version" "Print PGMig version and quit"] ["" "--help"]]) (defn error-msg [errors] (str "The following errors occurred while parsing your command:\n\n" (str/join \newline errors))) (defn exit [msg] (println msg) (System/exit 0)) (defn exit-error [status msg] (binding [*out* *err*] (println msg) (System/exit status))) (defn usage [options-summary] (->> ["Standalone PostgreSQL Migration Runner" "" "Usage: pgmig [options] action [ids]" "" "Options:" options-summary "" "Actions:" "init initialize the database" "list list migrations already applied" "pending list pending migrations" "migrate apply pending migrations" "up apply given migration ids" "down rollback given migration ids" "reset rollback and re-apply all migrations" "create create a new migration with current timestamp"] (str/join \newline))) (defn version [] (let [pgmig-version (slurp (io/resource "PGMIG_VERSION"))] (str "pgmig " pgmig-version))) (defn validate-command [{:keys [action options] :as command}] (if-let [resource-dir (config/get-resource-dir options)] (assoc-in command [:options :resource-dir] resource-dir) (assoc command :exit-message (str "Cannot access resources directory '" (:resource-dir options) "'")))) (defn parse-and-validate-args "Validate command line arguments. Either return a map indicating the program should exit (with a error message, and optional ok status), or a map indicating the action the program should take and the options provided." [args] (let [{:keys [options arguments errors summary]} (cli/parse-opts args cli-options)] (cond (:help options) ; help => exit OK with usage summary {:exit-message (usage summary) :ok? true} (:version options) ; help => exit OK version string {:exit-message (version) :ok? true} errors ; errors => exit with description of errors {:exit-message (error-msg errors)} ;; custom validation on arguments (and (= (count arguments) 1) (#{"init" "list" "pending" "migrate" "reset"} (first arguments))) (validate-command {:action (first arguments) :options options}) (and (> (count arguments) 1) (#{"create"} (first arguments))) (validate-command {:action (first arguments) :arguments (str/join " " (rest arguments)) :options options}) (and (> (count arguments) 1) (#{"up" "down" "create"} (first arguments))) (validate-command {:action (first arguments) :arguments (map #(Long/parseLong %) (rest arguments)) :options options}) :else ; failed custom validation => exit with usage summary {:exit-message (usage summary)}))) (defn stop-app [] (doseq [component (:stopped (mount/stop))] (log/info component "stopped")) (shutdown-agents)) (defn run-action [args options] (let [{:keys [action arguments]} args] (case action "init" (migration/init options) "list" (migration/list-migrations options) "pending" (migration/pending options) "migrate" (migration/migrate options) "reset" (migration/reset options) "up" (migration/up arguments options) "down" (migration/down arguments options) "create" (migration/create arguments options)))) (defn start-app [args] (doseq [component (-> args mount/start-with-args :started)] (log/info component "started")) (.addShutdownHook (Runtime/getRuntime) (Thread. ^Runnable stop-app))) (defn read-env [] (let [merge-env #'environ/merge-env read-system-env #'environ/read-system-env read-system-props #'environ/read-system-props] (merge-env (read-system-env) (read-system-props)))) (defn -main [& raw-args] (reset! env (read-env)) (let [{:keys [exit-message ok? options] :as args} (parse-and-validate-args raw-args)] (if-not exit-message (do (start-app options) (run-action args options)) (if ok? (exit exit-message) (exit-error 1 exit-message)))))
32877
(ns pgmig.main (:require [pgmig.migration :as migration] [environ.core :as environ] [mount.core :as mount] [clojure.string :as str] [clojure.tools.cli :as cli] [taoensso.timbre :as log] [pgmig.config :as config] [clojure.java.io :as io]) (:gen-class)) (def env (atom {})) (defn env-str [k] (get @env k)) (defn env-int [k] (when-let [es (env-str k)] (Long/parseLong es))) (defn env-kw [k] (when-let [es (env-str k)] (keyword es))) (def cli-options [["-a" "--adapter ADAPTER" "Database Adapter" :default-fn (fn [_] (or (env-str :adapter) "postgresql")) :default-desc "postgresql"] ["-h" "--host PGHOST" "Database Host Address" :default-fn (fn [_] (or (env-str :pghost) "localhost")) :default-desc "localhost"] ["-p" "--port PGPORT" "Database Port Number" :default-fn (fn [_] (or (env-int :pgport) 5432)) :default-desc "5432" :parse-fn #(Integer/parseInt %)] ["-d" "--dbname PGDATABASE" "Database Name" :default-fn (fn [_] (env-str :pgdatabase))] ["-U" "--username PGUSER" "Database User" :default-fn (fn [_] (env-str :pguser))] ["-P" "--password <PASSWORD>" "Database User's Password" :default-fn (fn [_] (env-str :pgpassword))] ["-j" "--jdbc-url JDBC_URL" "JDBC Connection URL" :default-fn (fn [_] (env-str :jdbc-url))] ["-r" "--resource-dir RESOURCE_DIR" "Resources Directory" :default-fn (fn [_] (or (env-str :resource-dir) config/DEFAULT-MIGRATION-DIR)) :default-desc config/DEFAULT-MIGRATION-DIR] ["-l" "--level LEVEL" "Verbosity Level (trace/debug/info/warn/error)" :default-fn (fn [_] (or (env-kw :level) :warn)) :default-desc "warn" :parse-fn (comp keyword str/lower-case)] ["-f" "--format " "Migration FORMAT (sql/clj/edn)" :default-fn (fn [_] (or (env-kw :format) :sql)) :default-desc "sql" :parse-fn (comp keyword str/lower-case)] ["-c" "--classpath " "Classpath for migration support code" :default-fn (fn [_] (or (env-str :classpath) "."))] ["-V" "--version" "Print PGMig version and quit"] ["" "--help"]]) (defn error-msg [errors] (str "The following errors occurred while parsing your command:\n\n" (str/join \newline errors))) (defn exit [msg] (println msg) (System/exit 0)) (defn exit-error [status msg] (binding [*out* *err*] (println msg) (System/exit status))) (defn usage [options-summary] (->> ["Standalone PostgreSQL Migration Runner" "" "Usage: pgmig [options] action [ids]" "" "Options:" options-summary "" "Actions:" "init initialize the database" "list list migrations already applied" "pending list pending migrations" "migrate apply pending migrations" "up apply given migration ids" "down rollback given migration ids" "reset rollback and re-apply all migrations" "create create a new migration with current timestamp"] (str/join \newline))) (defn version [] (let [pgmig-version (slurp (io/resource "PGMIG_VERSION"))] (str "pgmig " pgmig-version))) (defn validate-command [{:keys [action options] :as command}] (if-let [resource-dir (config/get-resource-dir options)] (assoc-in command [:options :resource-dir] resource-dir) (assoc command :exit-message (str "Cannot access resources directory '" (:resource-dir options) "'")))) (defn parse-and-validate-args "Validate command line arguments. Either return a map indicating the program should exit (with a error message, and optional ok status), or a map indicating the action the program should take and the options provided." [args] (let [{:keys [options arguments errors summary]} (cli/parse-opts args cli-options)] (cond (:help options) ; help => exit OK with usage summary {:exit-message (usage summary) :ok? true} (:version options) ; help => exit OK version string {:exit-message (version) :ok? true} errors ; errors => exit with description of errors {:exit-message (error-msg errors)} ;; custom validation on arguments (and (= (count arguments) 1) (#{"init" "list" "pending" "migrate" "reset"} (first arguments))) (validate-command {:action (first arguments) :options options}) (and (> (count arguments) 1) (#{"create"} (first arguments))) (validate-command {:action (first arguments) :arguments (str/join " " (rest arguments)) :options options}) (and (> (count arguments) 1) (#{"up" "down" "create"} (first arguments))) (validate-command {:action (first arguments) :arguments (map #(Long/parseLong %) (rest arguments)) :options options}) :else ; failed custom validation => exit with usage summary {:exit-message (usage summary)}))) (defn stop-app [] (doseq [component (:stopped (mount/stop))] (log/info component "stopped")) (shutdown-agents)) (defn run-action [args options] (let [{:keys [action arguments]} args] (case action "init" (migration/init options) "list" (migration/list-migrations options) "pending" (migration/pending options) "migrate" (migration/migrate options) "reset" (migration/reset options) "up" (migration/up arguments options) "down" (migration/down arguments options) "create" (migration/create arguments options)))) (defn start-app [args] (doseq [component (-> args mount/start-with-args :started)] (log/info component "started")) (.addShutdownHook (Runtime/getRuntime) (Thread. ^Runnable stop-app))) (defn read-env [] (let [merge-env #'environ/merge-env read-system-env #'environ/read-system-env read-system-props #'environ/read-system-props] (merge-env (read-system-env) (read-system-props)))) (defn -main [& raw-args] (reset! env (read-env)) (let [{:keys [exit-message ok? options] :as args} (parse-and-validate-args raw-args)] (if-not exit-message (do (start-app options) (run-action args options)) (if ok? (exit exit-message) (exit-error 1 exit-message)))))
true
(ns pgmig.main (:require [pgmig.migration :as migration] [environ.core :as environ] [mount.core :as mount] [clojure.string :as str] [clojure.tools.cli :as cli] [taoensso.timbre :as log] [pgmig.config :as config] [clojure.java.io :as io]) (:gen-class)) (def env (atom {})) (defn env-str [k] (get @env k)) (defn env-int [k] (when-let [es (env-str k)] (Long/parseLong es))) (defn env-kw [k] (when-let [es (env-str k)] (keyword es))) (def cli-options [["-a" "--adapter ADAPTER" "Database Adapter" :default-fn (fn [_] (or (env-str :adapter) "postgresql")) :default-desc "postgresql"] ["-h" "--host PGHOST" "Database Host Address" :default-fn (fn [_] (or (env-str :pghost) "localhost")) :default-desc "localhost"] ["-p" "--port PGPORT" "Database Port Number" :default-fn (fn [_] (or (env-int :pgport) 5432)) :default-desc "5432" :parse-fn #(Integer/parseInt %)] ["-d" "--dbname PGDATABASE" "Database Name" :default-fn (fn [_] (env-str :pgdatabase))] ["-U" "--username PGUSER" "Database User" :default-fn (fn [_] (env-str :pguser))] ["-P" "--password PI:PASSWORD:<PASSWORD>END_PI" "Database User's Password" :default-fn (fn [_] (env-str :pgpassword))] ["-j" "--jdbc-url JDBC_URL" "JDBC Connection URL" :default-fn (fn [_] (env-str :jdbc-url))] ["-r" "--resource-dir RESOURCE_DIR" "Resources Directory" :default-fn (fn [_] (or (env-str :resource-dir) config/DEFAULT-MIGRATION-DIR)) :default-desc config/DEFAULT-MIGRATION-DIR] ["-l" "--level LEVEL" "Verbosity Level (trace/debug/info/warn/error)" :default-fn (fn [_] (or (env-kw :level) :warn)) :default-desc "warn" :parse-fn (comp keyword str/lower-case)] ["-f" "--format " "Migration FORMAT (sql/clj/edn)" :default-fn (fn [_] (or (env-kw :format) :sql)) :default-desc "sql" :parse-fn (comp keyword str/lower-case)] ["-c" "--classpath " "Classpath for migration support code" :default-fn (fn [_] (or (env-str :classpath) "."))] ["-V" "--version" "Print PGMig version and quit"] ["" "--help"]]) (defn error-msg [errors] (str "The following errors occurred while parsing your command:\n\n" (str/join \newline errors))) (defn exit [msg] (println msg) (System/exit 0)) (defn exit-error [status msg] (binding [*out* *err*] (println msg) (System/exit status))) (defn usage [options-summary] (->> ["Standalone PostgreSQL Migration Runner" "" "Usage: pgmig [options] action [ids]" "" "Options:" options-summary "" "Actions:" "init initialize the database" "list list migrations already applied" "pending list pending migrations" "migrate apply pending migrations" "up apply given migration ids" "down rollback given migration ids" "reset rollback and re-apply all migrations" "create create a new migration with current timestamp"] (str/join \newline))) (defn version [] (let [pgmig-version (slurp (io/resource "PGMIG_VERSION"))] (str "pgmig " pgmig-version))) (defn validate-command [{:keys [action options] :as command}] (if-let [resource-dir (config/get-resource-dir options)] (assoc-in command [:options :resource-dir] resource-dir) (assoc command :exit-message (str "Cannot access resources directory '" (:resource-dir options) "'")))) (defn parse-and-validate-args "Validate command line arguments. Either return a map indicating the program should exit (with a error message, and optional ok status), or a map indicating the action the program should take and the options provided." [args] (let [{:keys [options arguments errors summary]} (cli/parse-opts args cli-options)] (cond (:help options) ; help => exit OK with usage summary {:exit-message (usage summary) :ok? true} (:version options) ; help => exit OK version string {:exit-message (version) :ok? true} errors ; errors => exit with description of errors {:exit-message (error-msg errors)} ;; custom validation on arguments (and (= (count arguments) 1) (#{"init" "list" "pending" "migrate" "reset"} (first arguments))) (validate-command {:action (first arguments) :options options}) (and (> (count arguments) 1) (#{"create"} (first arguments))) (validate-command {:action (first arguments) :arguments (str/join " " (rest arguments)) :options options}) (and (> (count arguments) 1) (#{"up" "down" "create"} (first arguments))) (validate-command {:action (first arguments) :arguments (map #(Long/parseLong %) (rest arguments)) :options options}) :else ; failed custom validation => exit with usage summary {:exit-message (usage summary)}))) (defn stop-app [] (doseq [component (:stopped (mount/stop))] (log/info component "stopped")) (shutdown-agents)) (defn run-action [args options] (let [{:keys [action arguments]} args] (case action "init" (migration/init options) "list" (migration/list-migrations options) "pending" (migration/pending options) "migrate" (migration/migrate options) "reset" (migration/reset options) "up" (migration/up arguments options) "down" (migration/down arguments options) "create" (migration/create arguments options)))) (defn start-app [args] (doseq [component (-> args mount/start-with-args :started)] (log/info component "started")) (.addShutdownHook (Runtime/getRuntime) (Thread. ^Runnable stop-app))) (defn read-env [] (let [merge-env #'environ/merge-env read-system-env #'environ/read-system-env read-system-props #'environ/read-system-props] (merge-env (read-system-env) (read-system-props)))) (defn -main [& raw-args] (reset! env (read-env)) (let [{:keys [exit-message ok? options] :as args} (parse-and-validate-args raw-args)] (if-not exit-message (do (start-app options) (run-action args options)) (if ok? (exit exit-message) (exit-error 1 exit-message)))))
[ { "context": ";; Copyright (c) Jeffrey Straszheim. All rights reserved. The use and\n;; distributi", "end": 36, "score": 0.999872624874115, "start": 18, "tag": "NAME", "value": "Jeffrey Straszheim" }, { "context": "ed])))))\n\n(deftest test-reverse-map\n (let [map {:fred 1 :sally 2 :joey 3}\n map-1 (assoc map :mar", "end": 1452, "score": 0.8647661209106445, "start": 1448, "tag": "NAME", "value": "fred" }, { "context": "\n\n(deftest test-reverse-map\n (let [map {:fred 1 :sally 2 :joey 3}\n map-1 (assoc map :mary 3)]\n ", "end": 1461, "score": 0.8125346302986145, "start": 1456, "tag": "NAME", "value": "sally" }, { "context": "c map :mary 3)]\n (is (= (reverse-map map) {1 :fred 2 :sally 3 :joey}))\n (is (or (= (reverse-map m", "end": 1545, "score": 0.7517132759094238, "start": 1542, "tag": "NAME", "value": "red" }, { "context": " :joey}))\n (is (or (= (reverse-map map-1) {1 :fred 2 :sally 3 :joey})\n (= (reverse-map ma", "end": 1609, "score": 0.740314781665802, "start": 1606, "tag": "NAME", "value": "red" }, { "context": "3 :joey})\n (= (reverse-map map-1) {1 :fred 2 :sally 3 :mary})))))\n\n(def some-maps\n [\n ", "end": 1672, "score": 0.7465295791625977, "start": 1669, "tag": "NAME", "value": "red" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/datalog/tests/test_util.clj
allertonm/Couverjure
3
;; Copyright (c) Jeffrey Straszheim. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse Public ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can ;; be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. You must not remove this notice, or any other, ;; from this software. ;; ;; test-util.clj ;; ;; A Clojure implementation of Datalog -- Utilities Tests ;; ;; straszheimjeffrey (gmail) ;; Created 11 Feburary 2009 (ns clojure.contrib.datalog.tests.test-util (:use clojure.test clojure.contrib.datalog.util) (:use [clojure.contrib.except :only (throwf)])) (deftest test-is-var? (is (is-var? '?x)) (is (is-var? '?)) (is (not (is-var? '??x))) (is (not (is-var? '??))) (is (not (is-var? 'x))) (is (not (is-var? "fred"))) (is (not (is-var? :q)))) (deftest test-map-values (let [map {:fred 1 :sally 2}] (is (= (map-values #(* 2 %) map) {:fred 2 :sally 4})) (is (= (map-values identity {}) {})))) (deftest test-keys-to-vals (let [map {:fred 1 :sally 2 :joey 3}] (is (= (set (keys-to-vals map [:fred :sally])) #{1 2})) (is (= (set (keys-to-vals map [:fred :sally :becky])) #{1 2})) (is (empty? (keys-to-vals map []))) (is (empty? (keys-to-vals {} [:fred]))))) (deftest test-reverse-map (let [map {:fred 1 :sally 2 :joey 3} map-1 (assoc map :mary 3)] (is (= (reverse-map map) {1 :fred 2 :sally 3 :joey})) (is (or (= (reverse-map map-1) {1 :fred 2 :sally 3 :joey}) (= (reverse-map map-1) {1 :fred 2 :sally 3 :mary}))))) (def some-maps [ { :a 1 :b 2 } { :c 3 :b 3 } { :d 4 :a 1 } { :g 4 :b 4 } { :a 2 :b 1 } { :e 1 :f 1 } ]) (def reduced (preduce + some-maps)) (def merged (apply merge-with + some-maps)) (deftest test-preduce (is (= reduced merged))) (comment (run-tests) ) ; End of file
8695
;; Copyright (c) <NAME>. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse Public ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can ;; be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. You must not remove this notice, or any other, ;; from this software. ;; ;; test-util.clj ;; ;; A Clojure implementation of Datalog -- Utilities Tests ;; ;; straszheimjeffrey (gmail) ;; Created 11 Feburary 2009 (ns clojure.contrib.datalog.tests.test-util (:use clojure.test clojure.contrib.datalog.util) (:use [clojure.contrib.except :only (throwf)])) (deftest test-is-var? (is (is-var? '?x)) (is (is-var? '?)) (is (not (is-var? '??x))) (is (not (is-var? '??))) (is (not (is-var? 'x))) (is (not (is-var? "fred"))) (is (not (is-var? :q)))) (deftest test-map-values (let [map {:fred 1 :sally 2}] (is (= (map-values #(* 2 %) map) {:fred 2 :sally 4})) (is (= (map-values identity {}) {})))) (deftest test-keys-to-vals (let [map {:fred 1 :sally 2 :joey 3}] (is (= (set (keys-to-vals map [:fred :sally])) #{1 2})) (is (= (set (keys-to-vals map [:fred :sally :becky])) #{1 2})) (is (empty? (keys-to-vals map []))) (is (empty? (keys-to-vals {} [:fred]))))) (deftest test-reverse-map (let [map {:<NAME> 1 :<NAME> 2 :joey 3} map-1 (assoc map :mary 3)] (is (= (reverse-map map) {1 :f<NAME> 2 :sally 3 :joey})) (is (or (= (reverse-map map-1) {1 :f<NAME> 2 :sally 3 :joey}) (= (reverse-map map-1) {1 :f<NAME> 2 :sally 3 :mary}))))) (def some-maps [ { :a 1 :b 2 } { :c 3 :b 3 } { :d 4 :a 1 } { :g 4 :b 4 } { :a 2 :b 1 } { :e 1 :f 1 } ]) (def reduced (preduce + some-maps)) (def merged (apply merge-with + some-maps)) (deftest test-preduce (is (= reduced merged))) (comment (run-tests) ) ; End of file
true
;; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. The use and ;; distribution terms for this software are covered by the Eclipse Public ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can ;; be found in the file epl-v10.html at the root of this distribution. By ;; using this software in any fashion, you are agreeing to be bound by the ;; terms of this license. You must not remove this notice, or any other, ;; from this software. ;; ;; test-util.clj ;; ;; A Clojure implementation of Datalog -- Utilities Tests ;; ;; straszheimjeffrey (gmail) ;; Created 11 Feburary 2009 (ns clojure.contrib.datalog.tests.test-util (:use clojure.test clojure.contrib.datalog.util) (:use [clojure.contrib.except :only (throwf)])) (deftest test-is-var? (is (is-var? '?x)) (is (is-var? '?)) (is (not (is-var? '??x))) (is (not (is-var? '??))) (is (not (is-var? 'x))) (is (not (is-var? "fred"))) (is (not (is-var? :q)))) (deftest test-map-values (let [map {:fred 1 :sally 2}] (is (= (map-values #(* 2 %) map) {:fred 2 :sally 4})) (is (= (map-values identity {}) {})))) (deftest test-keys-to-vals (let [map {:fred 1 :sally 2 :joey 3}] (is (= (set (keys-to-vals map [:fred :sally])) #{1 2})) (is (= (set (keys-to-vals map [:fred :sally :becky])) #{1 2})) (is (empty? (keys-to-vals map []))) (is (empty? (keys-to-vals {} [:fred]))))) (deftest test-reverse-map (let [map {:PI:NAME:<NAME>END_PI 1 :PI:NAME:<NAME>END_PI 2 :joey 3} map-1 (assoc map :mary 3)] (is (= (reverse-map map) {1 :fPI:NAME:<NAME>END_PI 2 :sally 3 :joey})) (is (or (= (reverse-map map-1) {1 :fPI:NAME:<NAME>END_PI 2 :sally 3 :joey}) (= (reverse-map map-1) {1 :fPI:NAME:<NAME>END_PI 2 :sally 3 :mary}))))) (def some-maps [ { :a 1 :b 2 } { :c 3 :b 3 } { :d 4 :a 1 } { :g 4 :b 4 } { :a 2 :b 1 } { :e 1 :f 1 } ]) (def reduced (preduce + some-maps)) (def merged (apply merge-with + some-maps)) (deftest test-preduce (is (= reduced merged))) (comment (run-tests) ) ; End of file
[ { "context": "fa-creative-commons-by\"}]]\n [:span \" David Schmudde 2020\"]]]\n [:div.tc.mt3\n ", "end": 1464, "score": 0.999865710735321, "start": 1450, "tag": "NAME", "value": "David Schmudde" }, { "context": "k.dim\n {:href \"https://twitter.com/dschmudde\"}\n [:i {:class \"fab fa-twitter\" }]", "end": 1612, "score": 0.9995590448379517, "start": 1603, "tag": "USERNAME", "value": "dschmudde" }, { "context": "im\n {:href \"https://mastodon.social/@schmudde\"}\n [:i {:class \"fab fa-mastodon\"}]", "end": 1760, "score": 0.9208499789237976, "start": 1751, "tag": "USERNAME", "value": "@schmudde" }, { "context": "5.dib.ph2.link.dim\n {:href \"mailto:d@schmud.de\"}\n [:i {:class \"fas fa-envelope\"}]", "end": 1893, "score": 0.9999208450317383, "start": 1882, "tag": "EMAIL", "value": "d@schmud.de" }, { "context": "age\"}]\n [:meta {:name \"twitter:creator\" :content \"@dschmudde\"}]\n [:meta {:property \"og:url\" :content (str \"h", "end": 2636, "score": 0.9996827244758606, "start": 2625, "tag": "USERNAME", "value": "\"@dschmudde" }, { "context": "404\"}]\n [:meta {:property \"og:author\" :content \"David Schmudde\"}]\n [:meta {:property \"og:image\" :content (str ", "end": 2830, "score": 0.9998787045478821, "start": 2816, "tag": "NAME", "value": "David Schmudde" } ]
src/core.clj
schmudde/netart.today
1
(ns core (:require [about :as about] [hiccup.page :as page] [clojure.edn :as edn])) (def artworks (edn/read-string (slurp "resources/art.edn"))) (def metadata {:domain "netart.today"}) (def jodi "http://asdfg.jodi.org/-------------------------------/-------------------------------/-------------------------------/-------------------------------/-----------------------401qe663/vb663e.html") (defn dispatch-link ([link] (case link :home [:a.f3.b.link.underline-hover.hover-blue.red {:href "../index.html"} "home"] :first-artwork [:a.f3.b.link.underline-hover.hover-blue.red {:href "pages/0.html"} "Enter &rarr;"] :about [:a.f3.b.link.underline-hover.hover-blue.red {:href "about.html"} "about"])) ([link next-artwork] [:a.f3.b.link.underline-hover.hover-blue.red {:href next-artwork} "next &rarr;"])) (defn get-image-url [resource-url art] (str resource-url "img/" (:image art))) (def header [:header.ph5-ns.ph3.pv2 [:h1 [:a.link.dim.navy {:href (str "http://" (:domain metadata))} "Gallery 404"]] [:h2 "The net.art Gallery"]]) (def footer [:footer.pv4.ph3.ph5-m.ph6-l.mid-gray [:div.tc {:property "license"} [:small [:a.link {:href "https://creativecommons.org/licenses/by/4.0/" :rel "license"} [:i {:class "fab fa-creative-commons"}] "&nbsp;" [:i {:class "fab fa-creative-commons-by"}]] [:span " David Schmudde 2020"]]] [:div.tc.mt3 [:div [:a.f5.dib.ph2.link.dim {:href "https://twitter.com/dschmudde"} [:i {:class "fab fa-twitter" }]] [:a.f5.dib.ph2.link.dim {:href "https://mastodon.social/@schmudde"} [:i {:class "fab fa-mastodon"}]] [:a.f5.dib.ph2.link.dim {:href "mailto:d@schmud.de"} [:i {:class "fas fa-envelope"}]]]]]) (defn head-template [resource-url] [:head [:title "net.art today"] [:meta {:charset "utf-8"}] [:meta {:http-equiv "Content-Type" :content "text/html"}] [:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}] [:link {:rel "stylesheet" :href (str resource-url "css/fontawesome/all.min.css")}] [:meta {:name "description" :content "The culture of a generation, lost to time."}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0, user-scalable=no"}] [:meta {:name "keywords" :content "netart rhizome Monoskop"}] [:meta {:name "twitter:card" :content "summary_large_image"}] [:meta {:name "twitter:creator" :content "@dschmudde"}] [:meta {:property "og:url" :content (str "http://" (:domain metadata))}] [:meta {:property "og:title" :content "Gallery 404"}] [:meta {:property "og:author" :content "David Schmudde"}] [:meta {:property "og:image" :content (str "http://www." (:domain metadata) "/" (get-image-url resource-url (first artworks)))}] [:meta {:property "og:description" :content "The culture of a generation, lost to time."}] [:link {:rel "stylesheet" :href (str resource-url "css/tachyons.min.css")}] [:link {:rel "stylesheet" :href (str resource-url "css/netart.css")}]]) (defn art->hiccup [resource-url art] (let [img-url (get-image-url resource-url art) current-archive (:current-archive art)] [:div.cf.ph3.ph5-ns.pv3 ;; image [:div.fn.fl-ns.w-60-l.pr4-l [:figure {:vocab "http://schema.org/" :typeof "ImageObject"} [:img {:alt (:title art) :title resource-url :src img-url :property "contentUrl"}] [:figcaption [:small.fr [:span {:property "license"} [:a.link {:href "https://creativecommons.org/licenses/by/4.0/" :rel "license"} [:i {:class "fab fa-creative-commons"}] "&nbsp;" [:i {:class "fab fa-creative-commons-by"}]]] "&nbsp;" [:a {:href (:url art)} "retrieved " (:retrieved art)]] [:i (:title art)] "&nbsp;"] [:meta {:property "acquireLicensePage" :content "https://schmud.de/pages/about.html"}]]] ;; info [:div.fn.fl-ns.w-40-l.pt3.pt0-l [:h2.f2.lh-title.fw9.mb3.mt0.pt3.bt.bw2 (:title art)] [:div [:p.f3.mid-gray.lh-title (:artist art) [:br ] [:time.f6.ttu.tracked.gray (:date art) ]] [:blockquote.ml0.mt0.pl3.black-90.bl.bw2.b--blue (:desc art) [:cite.f6.ttu.tracked.fs-normal " ~ " [:a {:href (:desc-source art)} " source"]]] [:p "Original link via " [:a {:href (:link-from-url art)} (:link-from art)] (when current-archive [:span ", currently archived at " [:a {:href (:current-archive-url art)} current-archive]])]]] ])) (defn make-index-page [artwork] (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 [:h1.f-headline.lh-solid "Gallery 404"] [:h1.f-subheadline.lh-solid.mt0 "The net.art Gallery"] [:section.flex-auto [:div.pa3 (dispatch-link :first-artwork)] [:div.pa3.tj [:p.w-50-ns "The culture of a generation, lost to time."] [:div [:img.ph2 {:src (str "resources/img/icons/netscape.png") :alt "netscape missing image icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/netscape-plugin.gif") :alt "netscape missing plugin icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/chrome.png") :alt "chrome can't find page icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/firefox.png") :alt "firefox can't find page icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/chrome-error-code.png") :alt "chrome crash icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/plugin-1.png") :alt "chrome missing plugin icon" :class "icons"}]] [:br] [:p.w-50-ns [:a {:href "pages/about.html"} "About Gallery 404"] " and the preservation of digital artifacts."] [:p.w-50-ns "The net.art embedded on this page is " [:em "ASDFG.JODI.ORG"] " by JODI from 1998."]]] [:div.h-100-ns.absolute-ns.top-0-ns.w-100 {:class "jodi"} [:iframe.h-100-ns.fr-ns {:src jodi :width 300 :title "JODI"}]]] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"} ] ])) (defn make-about-page [] (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "../resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 ;; .ph5-ns.ph3.pv2 header [:nav.ph5-ns.ph3 (dispatch-link :home) "&nbsp;&nbsp;" (dispatch-link :next-artwork "0.html")] [:section.flex-auto.ph5-ns.ph3 (about/about-article "../resources/")] footer] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"} ]])) (defn make-art-page [artwork filename next-artwork] (let [nav (if next-artwork (dispatch-link :next-artwork next-artwork) (dispatch-link :home))] (spit (str "pages/" filename) (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "../resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 header [:nav.ph5-ns.ph3 (dispatch-link :about) "&nbsp;&nbsp;" nav] [:section.flex-auto (art->hiccup "../resources/" artwork)] footer] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"}] ])))) (defn make-pages [artworks] (loop [artworks artworks coll (range (count artworks)) ;; TODO: make a set cnt 0 last-artwork "index.html"] (let [this-artwork (str cnt ".html") next-artwork (when (second coll) (str (second coll) ".html"))] (when-not (empty? artworks) (print "[" last-artwork " | " this-artwork " | " next-artwork "]") (make-art-page (first artworks) this-artwork next-artwork ) (recur (rest artworks) (rest coll) (inc cnt) this-artwork))))) (defn -main [] (do (spit "index.html" (make-index-page (first artworks))) (spit "pages/about.html" (make-about-page)) (make-pages artworks))) (-main)
5402
(ns core (:require [about :as about] [hiccup.page :as page] [clojure.edn :as edn])) (def artworks (edn/read-string (slurp "resources/art.edn"))) (def metadata {:domain "netart.today"}) (def jodi "http://asdfg.jodi.org/-------------------------------/-------------------------------/-------------------------------/-------------------------------/-----------------------401qe663/vb663e.html") (defn dispatch-link ([link] (case link :home [:a.f3.b.link.underline-hover.hover-blue.red {:href "../index.html"} "home"] :first-artwork [:a.f3.b.link.underline-hover.hover-blue.red {:href "pages/0.html"} "Enter &rarr;"] :about [:a.f3.b.link.underline-hover.hover-blue.red {:href "about.html"} "about"])) ([link next-artwork] [:a.f3.b.link.underline-hover.hover-blue.red {:href next-artwork} "next &rarr;"])) (defn get-image-url [resource-url art] (str resource-url "img/" (:image art))) (def header [:header.ph5-ns.ph3.pv2 [:h1 [:a.link.dim.navy {:href (str "http://" (:domain metadata))} "Gallery 404"]] [:h2 "The net.art Gallery"]]) (def footer [:footer.pv4.ph3.ph5-m.ph6-l.mid-gray [:div.tc {:property "license"} [:small [:a.link {:href "https://creativecommons.org/licenses/by/4.0/" :rel "license"} [:i {:class "fab fa-creative-commons"}] "&nbsp;" [:i {:class "fab fa-creative-commons-by"}]] [:span " <NAME> 2020"]]] [:div.tc.mt3 [:div [:a.f5.dib.ph2.link.dim {:href "https://twitter.com/dschmudde"} [:i {:class "fab fa-twitter" }]] [:a.f5.dib.ph2.link.dim {:href "https://mastodon.social/@schmudde"} [:i {:class "fab fa-mastodon"}]] [:a.f5.dib.ph2.link.dim {:href "mailto:<EMAIL>"} [:i {:class "fas fa-envelope"}]]]]]) (defn head-template [resource-url] [:head [:title "net.art today"] [:meta {:charset "utf-8"}] [:meta {:http-equiv "Content-Type" :content "text/html"}] [:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}] [:link {:rel "stylesheet" :href (str resource-url "css/fontawesome/all.min.css")}] [:meta {:name "description" :content "The culture of a generation, lost to time."}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0, user-scalable=no"}] [:meta {:name "keywords" :content "netart rhizome Monoskop"}] [:meta {:name "twitter:card" :content "summary_large_image"}] [:meta {:name "twitter:creator" :content "@dschmudde"}] [:meta {:property "og:url" :content (str "http://" (:domain metadata))}] [:meta {:property "og:title" :content "Gallery 404"}] [:meta {:property "og:author" :content "<NAME>"}] [:meta {:property "og:image" :content (str "http://www." (:domain metadata) "/" (get-image-url resource-url (first artworks)))}] [:meta {:property "og:description" :content "The culture of a generation, lost to time."}] [:link {:rel "stylesheet" :href (str resource-url "css/tachyons.min.css")}] [:link {:rel "stylesheet" :href (str resource-url "css/netart.css")}]]) (defn art->hiccup [resource-url art] (let [img-url (get-image-url resource-url art) current-archive (:current-archive art)] [:div.cf.ph3.ph5-ns.pv3 ;; image [:div.fn.fl-ns.w-60-l.pr4-l [:figure {:vocab "http://schema.org/" :typeof "ImageObject"} [:img {:alt (:title art) :title resource-url :src img-url :property "contentUrl"}] [:figcaption [:small.fr [:span {:property "license"} [:a.link {:href "https://creativecommons.org/licenses/by/4.0/" :rel "license"} [:i {:class "fab fa-creative-commons"}] "&nbsp;" [:i {:class "fab fa-creative-commons-by"}]]] "&nbsp;" [:a {:href (:url art)} "retrieved " (:retrieved art)]] [:i (:title art)] "&nbsp;"] [:meta {:property "acquireLicensePage" :content "https://schmud.de/pages/about.html"}]]] ;; info [:div.fn.fl-ns.w-40-l.pt3.pt0-l [:h2.f2.lh-title.fw9.mb3.mt0.pt3.bt.bw2 (:title art)] [:div [:p.f3.mid-gray.lh-title (:artist art) [:br ] [:time.f6.ttu.tracked.gray (:date art) ]] [:blockquote.ml0.mt0.pl3.black-90.bl.bw2.b--blue (:desc art) [:cite.f6.ttu.tracked.fs-normal " ~ " [:a {:href (:desc-source art)} " source"]]] [:p "Original link via " [:a {:href (:link-from-url art)} (:link-from art)] (when current-archive [:span ", currently archived at " [:a {:href (:current-archive-url art)} current-archive]])]]] ])) (defn make-index-page [artwork] (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 [:h1.f-headline.lh-solid "Gallery 404"] [:h1.f-subheadline.lh-solid.mt0 "The net.art Gallery"] [:section.flex-auto [:div.pa3 (dispatch-link :first-artwork)] [:div.pa3.tj [:p.w-50-ns "The culture of a generation, lost to time."] [:div [:img.ph2 {:src (str "resources/img/icons/netscape.png") :alt "netscape missing image icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/netscape-plugin.gif") :alt "netscape missing plugin icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/chrome.png") :alt "chrome can't find page icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/firefox.png") :alt "firefox can't find page icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/chrome-error-code.png") :alt "chrome crash icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/plugin-1.png") :alt "chrome missing plugin icon" :class "icons"}]] [:br] [:p.w-50-ns [:a {:href "pages/about.html"} "About Gallery 404"] " and the preservation of digital artifacts."] [:p.w-50-ns "The net.art embedded on this page is " [:em "ASDFG.JODI.ORG"] " by JODI from 1998."]]] [:div.h-100-ns.absolute-ns.top-0-ns.w-100 {:class "jodi"} [:iframe.h-100-ns.fr-ns {:src jodi :width 300 :title "JODI"}]]] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"} ] ])) (defn make-about-page [] (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "../resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 ;; .ph5-ns.ph3.pv2 header [:nav.ph5-ns.ph3 (dispatch-link :home) "&nbsp;&nbsp;" (dispatch-link :next-artwork "0.html")] [:section.flex-auto.ph5-ns.ph3 (about/about-article "../resources/")] footer] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"} ]])) (defn make-art-page [artwork filename next-artwork] (let [nav (if next-artwork (dispatch-link :next-artwork next-artwork) (dispatch-link :home))] (spit (str "pages/" filename) (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "../resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 header [:nav.ph5-ns.ph3 (dispatch-link :about) "&nbsp;&nbsp;" nav] [:section.flex-auto (art->hiccup "../resources/" artwork)] footer] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"}] ])))) (defn make-pages [artworks] (loop [artworks artworks coll (range (count artworks)) ;; TODO: make a set cnt 0 last-artwork "index.html"] (let [this-artwork (str cnt ".html") next-artwork (when (second coll) (str (second coll) ".html"))] (when-not (empty? artworks) (print "[" last-artwork " | " this-artwork " | " next-artwork "]") (make-art-page (first artworks) this-artwork next-artwork ) (recur (rest artworks) (rest coll) (inc cnt) this-artwork))))) (defn -main [] (do (spit "index.html" (make-index-page (first artworks))) (spit "pages/about.html" (make-about-page)) (make-pages artworks))) (-main)
true
(ns core (:require [about :as about] [hiccup.page :as page] [clojure.edn :as edn])) (def artworks (edn/read-string (slurp "resources/art.edn"))) (def metadata {:domain "netart.today"}) (def jodi "http://asdfg.jodi.org/-------------------------------/-------------------------------/-------------------------------/-------------------------------/-----------------------401qe663/vb663e.html") (defn dispatch-link ([link] (case link :home [:a.f3.b.link.underline-hover.hover-blue.red {:href "../index.html"} "home"] :first-artwork [:a.f3.b.link.underline-hover.hover-blue.red {:href "pages/0.html"} "Enter &rarr;"] :about [:a.f3.b.link.underline-hover.hover-blue.red {:href "about.html"} "about"])) ([link next-artwork] [:a.f3.b.link.underline-hover.hover-blue.red {:href next-artwork} "next &rarr;"])) (defn get-image-url [resource-url art] (str resource-url "img/" (:image art))) (def header [:header.ph5-ns.ph3.pv2 [:h1 [:a.link.dim.navy {:href (str "http://" (:domain metadata))} "Gallery 404"]] [:h2 "The net.art Gallery"]]) (def footer [:footer.pv4.ph3.ph5-m.ph6-l.mid-gray [:div.tc {:property "license"} [:small [:a.link {:href "https://creativecommons.org/licenses/by/4.0/" :rel "license"} [:i {:class "fab fa-creative-commons"}] "&nbsp;" [:i {:class "fab fa-creative-commons-by"}]] [:span " PI:NAME:<NAME>END_PI 2020"]]] [:div.tc.mt3 [:div [:a.f5.dib.ph2.link.dim {:href "https://twitter.com/dschmudde"} [:i {:class "fab fa-twitter" }]] [:a.f5.dib.ph2.link.dim {:href "https://mastodon.social/@schmudde"} [:i {:class "fab fa-mastodon"}]] [:a.f5.dib.ph2.link.dim {:href "mailto:PI:EMAIL:<EMAIL>END_PI"} [:i {:class "fas fa-envelope"}]]]]]) (defn head-template [resource-url] [:head [:title "net.art today"] [:meta {:charset "utf-8"}] [:meta {:http-equiv "Content-Type" :content "text/html"}] [:link {:rel "icon" :href "/favicon.ico" :type "image/x-icon"}] [:link {:rel "stylesheet" :href (str resource-url "css/fontawesome/all.min.css")}] [:meta {:name "description" :content "The culture of a generation, lost to time."}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0, user-scalable=no"}] [:meta {:name "keywords" :content "netart rhizome Monoskop"}] [:meta {:name "twitter:card" :content "summary_large_image"}] [:meta {:name "twitter:creator" :content "@dschmudde"}] [:meta {:property "og:url" :content (str "http://" (:domain metadata))}] [:meta {:property "og:title" :content "Gallery 404"}] [:meta {:property "og:author" :content "PI:NAME:<NAME>END_PI"}] [:meta {:property "og:image" :content (str "http://www." (:domain metadata) "/" (get-image-url resource-url (first artworks)))}] [:meta {:property "og:description" :content "The culture of a generation, lost to time."}] [:link {:rel "stylesheet" :href (str resource-url "css/tachyons.min.css")}] [:link {:rel "stylesheet" :href (str resource-url "css/netart.css")}]]) (defn art->hiccup [resource-url art] (let [img-url (get-image-url resource-url art) current-archive (:current-archive art)] [:div.cf.ph3.ph5-ns.pv3 ;; image [:div.fn.fl-ns.w-60-l.pr4-l [:figure {:vocab "http://schema.org/" :typeof "ImageObject"} [:img {:alt (:title art) :title resource-url :src img-url :property "contentUrl"}] [:figcaption [:small.fr [:span {:property "license"} [:a.link {:href "https://creativecommons.org/licenses/by/4.0/" :rel "license"} [:i {:class "fab fa-creative-commons"}] "&nbsp;" [:i {:class "fab fa-creative-commons-by"}]]] "&nbsp;" [:a {:href (:url art)} "retrieved " (:retrieved art)]] [:i (:title art)] "&nbsp;"] [:meta {:property "acquireLicensePage" :content "https://schmud.de/pages/about.html"}]]] ;; info [:div.fn.fl-ns.w-40-l.pt3.pt0-l [:h2.f2.lh-title.fw9.mb3.mt0.pt3.bt.bw2 (:title art)] [:div [:p.f3.mid-gray.lh-title (:artist art) [:br ] [:time.f6.ttu.tracked.gray (:date art) ]] [:blockquote.ml0.mt0.pl3.black-90.bl.bw2.b--blue (:desc art) [:cite.f6.ttu.tracked.fs-normal " ~ " [:a {:href (:desc-source art)} " source"]]] [:p "Original link via " [:a {:href (:link-from-url art)} (:link-from art)] (when current-archive [:span ", currently archived at " [:a {:href (:current-archive-url art)} current-archive]])]]] ])) (defn make-index-page [artwork] (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 [:h1.f-headline.lh-solid "Gallery 404"] [:h1.f-subheadline.lh-solid.mt0 "The net.art Gallery"] [:section.flex-auto [:div.pa3 (dispatch-link :first-artwork)] [:div.pa3.tj [:p.w-50-ns "The culture of a generation, lost to time."] [:div [:img.ph2 {:src (str "resources/img/icons/netscape.png") :alt "netscape missing image icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/netscape-plugin.gif") :alt "netscape missing plugin icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/chrome.png") :alt "chrome can't find page icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/firefox.png") :alt "firefox can't find page icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/chrome-error-code.png") :alt "chrome crash icon" :class "icons"}] [:img.ph2 {:src (str "resources/img/icons/plugin-1.png") :alt "chrome missing plugin icon" :class "icons"}]] [:br] [:p.w-50-ns [:a {:href "pages/about.html"} "About Gallery 404"] " and the preservation of digital artifacts."] [:p.w-50-ns "The net.art embedded on this page is " [:em "ASDFG.JODI.ORG"] " by JODI from 1998."]]] [:div.h-100-ns.absolute-ns.top-0-ns.w-100 {:class "jodi"} [:iframe.h-100-ns.fr-ns {:src jodi :width 300 :title "JODI"}]]] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"} ] ])) (defn make-about-page [] (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "../resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 ;; .ph5-ns.ph3.pv2 header [:nav.ph5-ns.ph3 (dispatch-link :home) "&nbsp;&nbsp;" (dispatch-link :next-artwork "0.html")] [:section.flex-auto.ph5-ns.ph3 (about/about-article "../resources/")] footer] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"} ]])) (defn make-art-page [artwork filename next-artwork] (let [nav (if next-artwork (dispatch-link :next-artwork next-artwork) (dispatch-link :home))] (spit (str "pages/" filename) (page/html5 {:lang "en" :itemscope "itemscope" :itemtype "http://schema.org/WebPage"} (head-template "../resources/") [:body.sans-serif [:main.flex.flex-column.min-vh-100 header [:nav.ph5-ns.ph3 (dispatch-link :about) "&nbsp;&nbsp;" nav] [:section.flex-auto (art->hiccup "../resources/" artwork)] footer] [:script {:data-goatcounter "https://beyondtheframe.goatcounter.com/count" :async true :src "//gc.zgo.at/count.js"}] ])))) (defn make-pages [artworks] (loop [artworks artworks coll (range (count artworks)) ;; TODO: make a set cnt 0 last-artwork "index.html"] (let [this-artwork (str cnt ".html") next-artwork (when (second coll) (str (second coll) ".html"))] (when-not (empty? artworks) (print "[" last-artwork " | " this-artwork " | " next-artwork "]") (make-art-page (first artworks) this-artwork next-artwork ) (recur (rest artworks) (rest coll) (inc cnt) this-artwork))))) (defn -main [] (do (spit "index.html" (make-index-page (first artworks))) (spit "pages/about.html" (make-about-page)) (make-pages artworks))) (-main)
[ { "context": " constants for dealing with secrets.\"\n {:author \"Isaak Uchakaev\"\n :last-update-date \"01-04-2021\"})\n\n(def digits", "end": 116, "score": 0.9998828768730164, "start": 102, "tag": "NAME", "value": "Isaak Uchakaev" } ]
src/secrets/constants.clj
lk-geimfari/secrets.clj
66
(ns secrets.constants "This module contains useful constants for dealing with secrets." {:author "Isaak Uchakaev" :last-update-date "01-04-2021"}) (def digits "0123456789") (def octdigits "01234567") (def hexdigits (str digits "abcdef" "ABCDEF")) (def ascii-lowercase "abcdefghijklmnopqrstuvwxyz") (def ascii-uppercase "ABCDEFGHIJKLMNOPQRSTUVWXYZ") (def punctuation "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") (def ascii-letters (str ascii-lowercase ascii-uppercase))
57203
(ns secrets.constants "This module contains useful constants for dealing with secrets." {:author "<NAME>" :last-update-date "01-04-2021"}) (def digits "0123456789") (def octdigits "01234567") (def hexdigits (str digits "abcdef" "ABCDEF")) (def ascii-lowercase "abcdefghijklmnopqrstuvwxyz") (def ascii-uppercase "ABCDEFGHIJKLMNOPQRSTUVWXYZ") (def punctuation "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") (def ascii-letters (str ascii-lowercase ascii-uppercase))
true
(ns secrets.constants "This module contains useful constants for dealing with secrets." {:author "PI:NAME:<NAME>END_PI" :last-update-date "01-04-2021"}) (def digits "0123456789") (def octdigits "01234567") (def hexdigits (str digits "abcdef" "ABCDEF")) (def ascii-lowercase "abcdefghijklmnopqrstuvwxyz") (def ascii-uppercase "ABCDEFGHIJKLMNOPQRSTUVWXYZ") (def punctuation "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") (def ascii-letters (str ascii-lowercase ascii-uppercase))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.999798059463501, "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.9998123049736023, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/internal/util_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 internal.util-test (:require [clojure.set :as set] [clojure.test :refer :all] [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [dynamo.graph :as g] [integration.test-util :as test-util] [internal.util :as util])) (deftest test-parse-number-parse-int (are [input expected-number expected-int] (and (= expected-number (util/parse-number input)) (= expected-int (util/parse-int input))) "43" 43 43 "43.0" 43.0 43 "43." 43.0 43 "72.02" 72.02 nil "009.0008" 9.0008 nil "009" 9 9 "010" 10 10 "-010" -10 -10 "0.025" 0.025 nil ".025" nil nil "." nil nil ".0" nil nil "0." 0.0 0 "0" 0 0 "000" 0 0 "89blah" nil nil "z29" nil nil "(exploit-me)" nil nil "-92837482734982347.00789" -9.2837482734982352E16 nil)) (def gen-set (gen/fmap set (gen/vector gen/nat))) (defspec apply-deltas-invariants 100 (prop/for-all [[oldset newset] (gen/tuple gen-set gen-set)] (let [[removal-ops addition-ops] (util/apply-deltas oldset newset (fn [out] (reduce conj [] out)) (fn [in] (reduce conj [] in))) old-minus-new (set/difference oldset newset) new-minus-old (set/difference newset oldset)] (and (= (count removal-ops) (count old-minus-new)) (= (count addition-ops) (count new-minus-old)) (= 1 (apply max 1 (vals (frequencies removal-ops)))) (= 1 (apply max 1 (vals (frequencies addition-ops)))))))) (deftest stringifying-keywords (are [s k] (= s (util/keyword->label k)) "Word" :word "Two Words" :two-words "2words" :2words "2 Words" :2-words "More Than Two Words" :more-than-two-words "More Than 2words" :more-than2words)) (g/defnk external-fnk [a b c d]) (deftest determining-inputs-required (testing "fnks" (are [f i] (= i (util/inputs-needed f)) external-fnk #{:a :b :c :d} #'external-fnk #{:a :b :c :d} (g/fnk [one two three]) #{:one :two :three} '(g/fnk [one two three]) #{:one :two :three}))) (deftest seq-starts-with?-test (is (true? (util/seq-starts-with? [] []))) (is (true? (util/seq-starts-with? [1] []))) (is (true? (util/seq-starts-with? [1] [1]))) (is (true? (util/seq-starts-with? [1 2 3] [1 2]))) (is (true? (util/seq-starts-with? [nil] [nil]))) (is (true? (util/seq-starts-with? [nil 1 2] [nil 1]))) (is (true? (util/seq-starts-with? (range 3) (range 2)))) (is (true? (util/seq-starts-with? "abc" "ab"))) (is (false? (util/seq-starts-with? [] [1]))) (is (false? (util/seq-starts-with? [1 2] [1 2 3]))) (is (false? (util/seq-starts-with? [nil 1] [nil 1 2])))) (deftest first-where-test (is (= 2 (util/first-where even? (range 1 4)))) (is (nil? (util/first-where nil? [:a :b nil :d]))) (is (= [:d 4] (util/first-where (fn [[k _]] (= :d k)) (sorted-map :a 1 :b 2 :c 3 :d 4)))) (is (= :e (util/first-where #(= :e %) (list :a nil :c nil :e)))) (is (= "f" (util/first-where #(= "f" %) (sorted-set "f" "e" "d" "c" "b" "a")))) (is (nil? (util/first-where nil? nil))) (is (nil? (util/first-where even? nil))) (is (nil? (util/first-where even? []))) (is (nil? (util/first-where even? [1 3 5]))) (testing "stops calling pred after first true" (let [pred (test-util/make-call-logger (constantly true))] (is (= 0 (util/first-where pred (range 10)))) (is (= 1 (count (test-util/call-logger-calls pred))))))) (deftest first-index-where-test (is (= 1 (util/first-index-where even? (range 1 4)))) (is (= 2 (util/first-index-where nil? [:a :b nil :d]))) (is (= 3 (util/first-index-where #(Character/isDigit %) "abc123def"))) (is (= 3 (util/first-index-where (fn [[k _]] (= :d k)) (sorted-map :a 1 :b 2 :c 3 :d 4)))) (is (= 4 (util/first-index-where #(= :e %) (list :a nil :c nil :e)))) (is (= 5 (util/first-index-where #(= "f" %) (sorted-set "f" "e" "d" "c" "b" "a")))) (is (nil? (util/first-index-where nil? nil))) (is (nil? (util/first-index-where even? nil))) (is (nil? (util/first-index-where even? []))) (is (nil? (util/first-index-where even? [1 3 5]))) (testing "stops calling pred after first true" (let [pred (test-util/make-call-logger (constantly true))] (is (= 0 (util/first-index-where pred (range 10)))) (is (= 1 (count (test-util/call-logger-calls pred))))))) (deftest only-test (is (= :a (util/only [:a]))) (is (= :b (util/only #{:b}))) (is (= :c (util/only '(:c)))) (is (= [:d 4] (util/only {:d 4}))) (is (nil? (util/only [nil]))) (is (nil? (util/only nil))) (is (nil? (util/only []))) (is (nil? (util/only [:a :b]))) (is (nil? (util/only #{:a :b}))) (is (nil? (util/only '(:a :b)))) (is (nil? (util/only {:a 1 :b 2}))))
93733
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 <NAME>, <NAME> ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns internal.util-test (:require [clojure.set :as set] [clojure.test :refer :all] [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [dynamo.graph :as g] [integration.test-util :as test-util] [internal.util :as util])) (deftest test-parse-number-parse-int (are [input expected-number expected-int] (and (= expected-number (util/parse-number input)) (= expected-int (util/parse-int input))) "43" 43 43 "43.0" 43.0 43 "43." 43.0 43 "72.02" 72.02 nil "009.0008" 9.0008 nil "009" 9 9 "010" 10 10 "-010" -10 -10 "0.025" 0.025 nil ".025" nil nil "." nil nil ".0" nil nil "0." 0.0 0 "0" 0 0 "000" 0 0 "89blah" nil nil "z29" nil nil "(exploit-me)" nil nil "-92837482734982347.00789" -9.2837482734982352E16 nil)) (def gen-set (gen/fmap set (gen/vector gen/nat))) (defspec apply-deltas-invariants 100 (prop/for-all [[oldset newset] (gen/tuple gen-set gen-set)] (let [[removal-ops addition-ops] (util/apply-deltas oldset newset (fn [out] (reduce conj [] out)) (fn [in] (reduce conj [] in))) old-minus-new (set/difference oldset newset) new-minus-old (set/difference newset oldset)] (and (= (count removal-ops) (count old-minus-new)) (= (count addition-ops) (count new-minus-old)) (= 1 (apply max 1 (vals (frequencies removal-ops)))) (= 1 (apply max 1 (vals (frequencies addition-ops)))))))) (deftest stringifying-keywords (are [s k] (= s (util/keyword->label k)) "Word" :word "Two Words" :two-words "2words" :2words "2 Words" :2-words "More Than Two Words" :more-than-two-words "More Than 2words" :more-than2words)) (g/defnk external-fnk [a b c d]) (deftest determining-inputs-required (testing "fnks" (are [f i] (= i (util/inputs-needed f)) external-fnk #{:a :b :c :d} #'external-fnk #{:a :b :c :d} (g/fnk [one two three]) #{:one :two :three} '(g/fnk [one two three]) #{:one :two :three}))) (deftest seq-starts-with?-test (is (true? (util/seq-starts-with? [] []))) (is (true? (util/seq-starts-with? [1] []))) (is (true? (util/seq-starts-with? [1] [1]))) (is (true? (util/seq-starts-with? [1 2 3] [1 2]))) (is (true? (util/seq-starts-with? [nil] [nil]))) (is (true? (util/seq-starts-with? [nil 1 2] [nil 1]))) (is (true? (util/seq-starts-with? (range 3) (range 2)))) (is (true? (util/seq-starts-with? "abc" "ab"))) (is (false? (util/seq-starts-with? [] [1]))) (is (false? (util/seq-starts-with? [1 2] [1 2 3]))) (is (false? (util/seq-starts-with? [nil 1] [nil 1 2])))) (deftest first-where-test (is (= 2 (util/first-where even? (range 1 4)))) (is (nil? (util/first-where nil? [:a :b nil :d]))) (is (= [:d 4] (util/first-where (fn [[k _]] (= :d k)) (sorted-map :a 1 :b 2 :c 3 :d 4)))) (is (= :e (util/first-where #(= :e %) (list :a nil :c nil :e)))) (is (= "f" (util/first-where #(= "f" %) (sorted-set "f" "e" "d" "c" "b" "a")))) (is (nil? (util/first-where nil? nil))) (is (nil? (util/first-where even? nil))) (is (nil? (util/first-where even? []))) (is (nil? (util/first-where even? [1 3 5]))) (testing "stops calling pred after first true" (let [pred (test-util/make-call-logger (constantly true))] (is (= 0 (util/first-where pred (range 10)))) (is (= 1 (count (test-util/call-logger-calls pred))))))) (deftest first-index-where-test (is (= 1 (util/first-index-where even? (range 1 4)))) (is (= 2 (util/first-index-where nil? [:a :b nil :d]))) (is (= 3 (util/first-index-where #(Character/isDigit %) "abc123def"))) (is (= 3 (util/first-index-where (fn [[k _]] (= :d k)) (sorted-map :a 1 :b 2 :c 3 :d 4)))) (is (= 4 (util/first-index-where #(= :e %) (list :a nil :c nil :e)))) (is (= 5 (util/first-index-where #(= "f" %) (sorted-set "f" "e" "d" "c" "b" "a")))) (is (nil? (util/first-index-where nil? nil))) (is (nil? (util/first-index-where even? nil))) (is (nil? (util/first-index-where even? []))) (is (nil? (util/first-index-where even? [1 3 5]))) (testing "stops calling pred after first true" (let [pred (test-util/make-call-logger (constantly true))] (is (= 0 (util/first-index-where pred (range 10)))) (is (= 1 (count (test-util/call-logger-calls pred))))))) (deftest only-test (is (= :a (util/only [:a]))) (is (= :b (util/only #{:b}))) (is (= :c (util/only '(:c)))) (is (= [:d 4] (util/only {:d 4}))) (is (nil? (util/only [nil]))) (is (nil? (util/only nil))) (is (nil? (util/only []))) (is (nil? (util/only [:a :b]))) (is (nil? (util/only #{:a :b}))) (is (nil? (util/only '(:a :b)))) (is (nil? (util/only {:a 1 :b 2}))))
true
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns internal.util-test (:require [clojure.set :as set] [clojure.test :refer :all] [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [dynamo.graph :as g] [integration.test-util :as test-util] [internal.util :as util])) (deftest test-parse-number-parse-int (are [input expected-number expected-int] (and (= expected-number (util/parse-number input)) (= expected-int (util/parse-int input))) "43" 43 43 "43.0" 43.0 43 "43." 43.0 43 "72.02" 72.02 nil "009.0008" 9.0008 nil "009" 9 9 "010" 10 10 "-010" -10 -10 "0.025" 0.025 nil ".025" nil nil "." nil nil ".0" nil nil "0." 0.0 0 "0" 0 0 "000" 0 0 "89blah" nil nil "z29" nil nil "(exploit-me)" nil nil "-92837482734982347.00789" -9.2837482734982352E16 nil)) (def gen-set (gen/fmap set (gen/vector gen/nat))) (defspec apply-deltas-invariants 100 (prop/for-all [[oldset newset] (gen/tuple gen-set gen-set)] (let [[removal-ops addition-ops] (util/apply-deltas oldset newset (fn [out] (reduce conj [] out)) (fn [in] (reduce conj [] in))) old-minus-new (set/difference oldset newset) new-minus-old (set/difference newset oldset)] (and (= (count removal-ops) (count old-minus-new)) (= (count addition-ops) (count new-minus-old)) (= 1 (apply max 1 (vals (frequencies removal-ops)))) (= 1 (apply max 1 (vals (frequencies addition-ops)))))))) (deftest stringifying-keywords (are [s k] (= s (util/keyword->label k)) "Word" :word "Two Words" :two-words "2words" :2words "2 Words" :2-words "More Than Two Words" :more-than-two-words "More Than 2words" :more-than2words)) (g/defnk external-fnk [a b c d]) (deftest determining-inputs-required (testing "fnks" (are [f i] (= i (util/inputs-needed f)) external-fnk #{:a :b :c :d} #'external-fnk #{:a :b :c :d} (g/fnk [one two three]) #{:one :two :three} '(g/fnk [one two three]) #{:one :two :three}))) (deftest seq-starts-with?-test (is (true? (util/seq-starts-with? [] []))) (is (true? (util/seq-starts-with? [1] []))) (is (true? (util/seq-starts-with? [1] [1]))) (is (true? (util/seq-starts-with? [1 2 3] [1 2]))) (is (true? (util/seq-starts-with? [nil] [nil]))) (is (true? (util/seq-starts-with? [nil 1 2] [nil 1]))) (is (true? (util/seq-starts-with? (range 3) (range 2)))) (is (true? (util/seq-starts-with? "abc" "ab"))) (is (false? (util/seq-starts-with? [] [1]))) (is (false? (util/seq-starts-with? [1 2] [1 2 3]))) (is (false? (util/seq-starts-with? [nil 1] [nil 1 2])))) (deftest first-where-test (is (= 2 (util/first-where even? (range 1 4)))) (is (nil? (util/first-where nil? [:a :b nil :d]))) (is (= [:d 4] (util/first-where (fn [[k _]] (= :d k)) (sorted-map :a 1 :b 2 :c 3 :d 4)))) (is (= :e (util/first-where #(= :e %) (list :a nil :c nil :e)))) (is (= "f" (util/first-where #(= "f" %) (sorted-set "f" "e" "d" "c" "b" "a")))) (is (nil? (util/first-where nil? nil))) (is (nil? (util/first-where even? nil))) (is (nil? (util/first-where even? []))) (is (nil? (util/first-where even? [1 3 5]))) (testing "stops calling pred after first true" (let [pred (test-util/make-call-logger (constantly true))] (is (= 0 (util/first-where pred (range 10)))) (is (= 1 (count (test-util/call-logger-calls pred))))))) (deftest first-index-where-test (is (= 1 (util/first-index-where even? (range 1 4)))) (is (= 2 (util/first-index-where nil? [:a :b nil :d]))) (is (= 3 (util/first-index-where #(Character/isDigit %) "abc123def"))) (is (= 3 (util/first-index-where (fn [[k _]] (= :d k)) (sorted-map :a 1 :b 2 :c 3 :d 4)))) (is (= 4 (util/first-index-where #(= :e %) (list :a nil :c nil :e)))) (is (= 5 (util/first-index-where #(= "f" %) (sorted-set "f" "e" "d" "c" "b" "a")))) (is (nil? (util/first-index-where nil? nil))) (is (nil? (util/first-index-where even? nil))) (is (nil? (util/first-index-where even? []))) (is (nil? (util/first-index-where even? [1 3 5]))) (testing "stops calling pred after first true" (let [pred (test-util/make-call-logger (constantly true))] (is (= 0 (util/first-index-where pred (range 10)))) (is (= 1 (count (test-util/call-logger-calls pred))))))) (deftest only-test (is (= :a (util/only [:a]))) (is (= :b (util/only #{:b}))) (is (= :c (util/only '(:c)))) (is (= [:d 4] (util/only {:d 4}))) (is (nil? (util/only [nil]))) (is (nil? (util/only nil))) (is (nil? (util/only []))) (is (nil? (util/only [:a :b]))) (is (nil? (util/only #{:a :b}))) (is (nil? (util/only '(:a :b)))) (is (nil? (util/only {:a 1 :b 2}))))
[ { "context": "4708-a51a-b3d403c491db\",\n \"actor\" {\"name\" \"Alice Faux\", \"mbox\" \"mailto:alice@example.org\"},\n \"ve", "end": 1203, "score": 0.9997813105583191, "start": 1193, "tag": "NAME", "value": "Alice Faux" }, { "context": " \"actor\" {\"name\" \"Alice Faux\", \"mbox\" \"mailto:alice@example.org\"},\n \"verb\" {\"id\" \"https://adlnet.gov/expap", "end": 1238, "score": 0.9999238848686218, "start": 1221, "tag": "EMAIL", "value": "alice@example.org" }, { "context": "4708-a51a-b3d403c491db\",\n \"actor\" {\"name\" \"Alice Faux\", \"mbox\" \"mailto:alice@example.org\"},\n \"ve", "end": 1979, "score": 0.9998475909233093, "start": 1969, "tag": "NAME", "value": "Alice Faux" }, { "context": " \"actor\" {\"name\" \"Alice Faux\", \"mbox\" \"mailto:alice@example.org\"},\n \"verb\" {\"id\" \"https://adlnet.gov/expap", "end": 2014, "score": 0.9999210238456726, "start": 1997, "tag": "EMAIL", "value": "alice@example.org" }, { "context": " :all [{\"mbox\" \"mailto:milt@yetanalytics.com\"\n ", "end": 4618, "score": 0.9999228119850159, "start": 4597, "tag": "EMAIL", "value": "milt@yetanalytics.com" }, { "context": " \"name\" \"milt\"\n ", "end": 4681, "score": 0.7341746091842651, "start": 4677, "tag": "NAME", "value": "milt" } ]
src/test/com/yetanalytics/datasim/xapi/profile/template/rule_test.clj
yetanalytics/datasim
12
(ns com.yetanalytics.datasim.xapi.profile.template.rule-test (:require [clojure.test :refer :all] [com.yetanalytics.datasim.xapi.profile.template.rule :refer [parse-rule apply-rules-gen follows-rule?] :as r] [com.yetanalytics.datasim.input :as input] [clojure.java.io :as io] [cheshire.core :as json] [clojure.spec.alpha :as s] [xapi-schema.spec :as xs])) ;; we can pull some actual rules from cmi5 (def cmi5-templates (:templates (input/from-location :profile :json "dev-resources/profiles/cmi5/fixed.json"))) (def all-rules (mapcat :rules cmi5-templates)) ;; A simple statement to augment (def simple-statement (with-open [r (io/reader "dev-resources/xapi/statements/simple.json")] (json/parse-stream r))) (deftest parse-rule-test (testing "parses cmi5 rules" (is (every? (comp nil? (partial s/explain-data ::r/parsed-rule)) (map parse-rule all-rules))))) (deftest follows-rule?-test (testing "given a statement that follows the rule, it returns true" (is (true? (follows-rule? ;; statement {"id" "59de1b06-bb6c-4708-a51a-b3d403c491db", "actor" {"name" "Alice Faux", "mbox" "mailto:alice@example.org"}, "verb" {"id" "https://adlnet.gov/expapi/verbs/launched"}, "object" {"id" "https://example.org/career/1054719918", "definition" {"type" "https://w3id.org/xapi/tla/activity-types/career"}, "objectType" "Activity"}, "context" {"registration" "d7acfddb-f4c2-49f4-a081-ad1fb8490448"}, "timestamp" "2021-03-18T17:36:22.131Z"} ;; rule {:presence "excluded", :location [#{"context"} #{"contextActivities"}]} )))) (testing "given a statement that doesn't follow the rule, it returns false" (is (false? (follows-rule? ;; statement {"id" "59de1b06-bb6c-4708-a51a-b3d403c491db", "actor" {"name" "Alice Faux", "mbox" "mailto:alice@example.org"}, "verb" {"id" "https://adlnet.gov/expapi/verbs/launched"}, "object" {"id" "https://example.org/career/1054719918", "definition" {"type" "https://w3id.org/xapi/tla/activity-types/career"}, "objectType" "Activity"}, "context" {"contextActivities" {"category" [{"id" "https://w3id.org/xapi/tla/v0.13"}]}, "registration" "d7acfddb-f4c2-49f4-a081-ad1fb8490448"}, "timestamp" "2021-03-18T17:36:22.131Z"} ;; rule {:presence "excluded", :location [#{"context"} #{"contextActivities"}]}))))) (deftest apply-rules-gen-test (testing "individual rule application" (doseq [{:keys [rules]} cmi5-templates rule rules] (testing (format "rule: %s" rule) (let [processed (apply-rules-gen simple-statement [rule] :seed 42)] (testing "follows rule" (is (follows-rule? processed (parse-rule rule)))) (testing "is a valid statement" (is (nil? (s/explain-data ::xs/statement processed)))))))) (testing "collected rule application" (doseq [{:keys [id rules]} cmi5-templates] (testing (format "template: %s" id) (let [processed (apply-rules-gen simple-statement rules :seed 42)] (testing "follows rules" (is (every? (partial follows-rule? processed) (map parse-rule rules)))) (testing "is a valid statement" (is (nil? (s/explain-data ::xs/statement processed)))))))) (testing "various cases" (are [case-name statement rules] (let [processed (apply-rules-gen simple-statement rules :seed 42)] (and (every? (partial follows-rule? processed) (map parse-rule rules)) (is (nil? (s/explain-data ::xs/statement processed))) case-name)) "group as actor" simple-statement [;; TODO: Right now this will only apply the second rule if the first is present ;; the path->spec function can't resolve ["actor" "member"] {:location "$.actor.objectType" :presence "included" :all ["Group"]} {:location "$.actor.member[0]" :presence "included" :all [{"mbox" "mailto:milt@yetanalytics.com" "name" "milt" "objectType" "Agent"}]}])))
16554
(ns com.yetanalytics.datasim.xapi.profile.template.rule-test (:require [clojure.test :refer :all] [com.yetanalytics.datasim.xapi.profile.template.rule :refer [parse-rule apply-rules-gen follows-rule?] :as r] [com.yetanalytics.datasim.input :as input] [clojure.java.io :as io] [cheshire.core :as json] [clojure.spec.alpha :as s] [xapi-schema.spec :as xs])) ;; we can pull some actual rules from cmi5 (def cmi5-templates (:templates (input/from-location :profile :json "dev-resources/profiles/cmi5/fixed.json"))) (def all-rules (mapcat :rules cmi5-templates)) ;; A simple statement to augment (def simple-statement (with-open [r (io/reader "dev-resources/xapi/statements/simple.json")] (json/parse-stream r))) (deftest parse-rule-test (testing "parses cmi5 rules" (is (every? (comp nil? (partial s/explain-data ::r/parsed-rule)) (map parse-rule all-rules))))) (deftest follows-rule?-test (testing "given a statement that follows the rule, it returns true" (is (true? (follows-rule? ;; statement {"id" "59de1b06-bb6c-4708-a51a-b3d403c491db", "actor" {"name" "<NAME>", "mbox" "mailto:<EMAIL>"}, "verb" {"id" "https://adlnet.gov/expapi/verbs/launched"}, "object" {"id" "https://example.org/career/1054719918", "definition" {"type" "https://w3id.org/xapi/tla/activity-types/career"}, "objectType" "Activity"}, "context" {"registration" "d7acfddb-f4c2-49f4-a081-ad1fb8490448"}, "timestamp" "2021-03-18T17:36:22.131Z"} ;; rule {:presence "excluded", :location [#{"context"} #{"contextActivities"}]} )))) (testing "given a statement that doesn't follow the rule, it returns false" (is (false? (follows-rule? ;; statement {"id" "59de1b06-bb6c-4708-a51a-b3d403c491db", "actor" {"name" "<NAME>", "mbox" "mailto:<EMAIL>"}, "verb" {"id" "https://adlnet.gov/expapi/verbs/launched"}, "object" {"id" "https://example.org/career/1054719918", "definition" {"type" "https://w3id.org/xapi/tla/activity-types/career"}, "objectType" "Activity"}, "context" {"contextActivities" {"category" [{"id" "https://w3id.org/xapi/tla/v0.13"}]}, "registration" "d7acfddb-f4c2-49f4-a081-ad1fb8490448"}, "timestamp" "2021-03-18T17:36:22.131Z"} ;; rule {:presence "excluded", :location [#{"context"} #{"contextActivities"}]}))))) (deftest apply-rules-gen-test (testing "individual rule application" (doseq [{:keys [rules]} cmi5-templates rule rules] (testing (format "rule: %s" rule) (let [processed (apply-rules-gen simple-statement [rule] :seed 42)] (testing "follows rule" (is (follows-rule? processed (parse-rule rule)))) (testing "is a valid statement" (is (nil? (s/explain-data ::xs/statement processed)))))))) (testing "collected rule application" (doseq [{:keys [id rules]} cmi5-templates] (testing (format "template: %s" id) (let [processed (apply-rules-gen simple-statement rules :seed 42)] (testing "follows rules" (is (every? (partial follows-rule? processed) (map parse-rule rules)))) (testing "is a valid statement" (is (nil? (s/explain-data ::xs/statement processed)))))))) (testing "various cases" (are [case-name statement rules] (let [processed (apply-rules-gen simple-statement rules :seed 42)] (and (every? (partial follows-rule? processed) (map parse-rule rules)) (is (nil? (s/explain-data ::xs/statement processed))) case-name)) "group as actor" simple-statement [;; TODO: Right now this will only apply the second rule if the first is present ;; the path->spec function can't resolve ["actor" "member"] {:location "$.actor.objectType" :presence "included" :all ["Group"]} {:location "$.actor.member[0]" :presence "included" :all [{"mbox" "mailto:<EMAIL>" "name" "<NAME>" "objectType" "Agent"}]}])))
true
(ns com.yetanalytics.datasim.xapi.profile.template.rule-test (:require [clojure.test :refer :all] [com.yetanalytics.datasim.xapi.profile.template.rule :refer [parse-rule apply-rules-gen follows-rule?] :as r] [com.yetanalytics.datasim.input :as input] [clojure.java.io :as io] [cheshire.core :as json] [clojure.spec.alpha :as s] [xapi-schema.spec :as xs])) ;; we can pull some actual rules from cmi5 (def cmi5-templates (:templates (input/from-location :profile :json "dev-resources/profiles/cmi5/fixed.json"))) (def all-rules (mapcat :rules cmi5-templates)) ;; A simple statement to augment (def simple-statement (with-open [r (io/reader "dev-resources/xapi/statements/simple.json")] (json/parse-stream r))) (deftest parse-rule-test (testing "parses cmi5 rules" (is (every? (comp nil? (partial s/explain-data ::r/parsed-rule)) (map parse-rule all-rules))))) (deftest follows-rule?-test (testing "given a statement that follows the rule, it returns true" (is (true? (follows-rule? ;; statement {"id" "59de1b06-bb6c-4708-a51a-b3d403c491db", "actor" {"name" "PI:NAME:<NAME>END_PI", "mbox" "mailto:PI:EMAIL:<EMAIL>END_PI"}, "verb" {"id" "https://adlnet.gov/expapi/verbs/launched"}, "object" {"id" "https://example.org/career/1054719918", "definition" {"type" "https://w3id.org/xapi/tla/activity-types/career"}, "objectType" "Activity"}, "context" {"registration" "d7acfddb-f4c2-49f4-a081-ad1fb8490448"}, "timestamp" "2021-03-18T17:36:22.131Z"} ;; rule {:presence "excluded", :location [#{"context"} #{"contextActivities"}]} )))) (testing "given a statement that doesn't follow the rule, it returns false" (is (false? (follows-rule? ;; statement {"id" "59de1b06-bb6c-4708-a51a-b3d403c491db", "actor" {"name" "PI:NAME:<NAME>END_PI", "mbox" "mailto:PI:EMAIL:<EMAIL>END_PI"}, "verb" {"id" "https://adlnet.gov/expapi/verbs/launched"}, "object" {"id" "https://example.org/career/1054719918", "definition" {"type" "https://w3id.org/xapi/tla/activity-types/career"}, "objectType" "Activity"}, "context" {"contextActivities" {"category" [{"id" "https://w3id.org/xapi/tla/v0.13"}]}, "registration" "d7acfddb-f4c2-49f4-a081-ad1fb8490448"}, "timestamp" "2021-03-18T17:36:22.131Z"} ;; rule {:presence "excluded", :location [#{"context"} #{"contextActivities"}]}))))) (deftest apply-rules-gen-test (testing "individual rule application" (doseq [{:keys [rules]} cmi5-templates rule rules] (testing (format "rule: %s" rule) (let [processed (apply-rules-gen simple-statement [rule] :seed 42)] (testing "follows rule" (is (follows-rule? processed (parse-rule rule)))) (testing "is a valid statement" (is (nil? (s/explain-data ::xs/statement processed)))))))) (testing "collected rule application" (doseq [{:keys [id rules]} cmi5-templates] (testing (format "template: %s" id) (let [processed (apply-rules-gen simple-statement rules :seed 42)] (testing "follows rules" (is (every? (partial follows-rule? processed) (map parse-rule rules)))) (testing "is a valid statement" (is (nil? (s/explain-data ::xs/statement processed)))))))) (testing "various cases" (are [case-name statement rules] (let [processed (apply-rules-gen simple-statement rules :seed 42)] (and (every? (partial follows-rule? processed) (map parse-rule rules)) (is (nil? (s/explain-data ::xs/statement processed))) case-name)) "group as actor" simple-statement [;; TODO: Right now this will only apply the second rule if the first is present ;; the path->spec function can't resolve ["actor" "member"] {:location "$.actor.objectType" :presence "included" :all ["Group"]} {:location "$.actor.member[0]" :presence "included" :all [{"mbox" "mailto:PI:EMAIL:<EMAIL>END_PI" "name" "PI:NAME:<NAME>END_PI" "objectType" "Agent"}]}])))
[ { "context": "tion-link id))]\n (send-message conn {:from \"mobile@boundlessgeo.com\"\n :to (str recipient)", "end": 2160, "score": 0.9999203085899353, "start": 2137, "tag": "EMAIL", "value": "mobile@boundlessgeo.com" } ]
server/src/spacon/components/notification/core.clj
martinwilkerson-scisys/spatialconnect-server
1
;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 spacon.components.notification.core (:require [com.stuartsierra.component :as component] [spacon.components.mqtt.core :as mqttapi] [clojure.core.async :refer [chan <!! >!! close! go alt!]] [postal.core :refer [send-message]] [spacon.components.notification.db :as notifmodel] [clojure.tools.logging :as log])) (defn- send->device [mqtt device-id message] (mqttapi/publish-map mqtt (str "/notify/" device-id) message)) (defn- send->devices [mqtt devices message] (map (fn [device-id] (send->device mqtt device-id message)) devices)) (defn- send->all [mqtt message] (mqttapi/publish-map mqtt "/notify" message)) (defn- send->mobile [mqtt message] (case (count (:to message)) 0 (send->all mqtt message) 1 (send->device mqtt (first (:to message)) message) (send->devices mqtt (:to message) message)) (map notifmodel/mark-as-sent (:notif_id message))) (def conn {:host (or (System/getenv "SMTP_HOST") "email-smtp.us-east-1.amazonaws.com") :ssl true :user (System/getenv "SMTP_USERNAME") :pass (System/getenv "SMTP_PASSWORD")}) (defn- build-notification-link [id] (let [hostname (or (System/getenv "HOSTNAME") (.getHostName (java.net.InetAddress/getLocalHost)))] (str "http://" hostname "/notifications/" id))) (defn- email-recipient [id recipient message] (let [body (str (build-notification-link id))] (send-message conn {:from "mobile@boundlessgeo.com" :to (str recipient) :subject (str (:title message)) :body body}))) (defn- send->email [message] (let [recipients (do (zipmap (:notif-ids message) (:to message)))] (doall (map (fn [[id recipient]] (email-recipient id recipient message) (notifmodel/mark-as-sent id)) recipients)))) (defn- process-channel [mqtt input-channel] (go (while true (let [v (<!! input-channel)] (case (:output_type v) :email (send->email v) :mobile (if-not (empty? mqtt) (send->mobile mqtt v)) ; For Signal that doesn't have an mqtt component "default"))))) (defn notify [notifcomp message message-type info] (let [ids (map :id (notifmodel/create-notifications (:to message) message-type info))] (go (>!! (:send-channel notifcomp) (assoc message :notif-ids ids))))) (defn find-notif-by-id [notif-comp id] (notifmodel/find-notif-by-id id)) (defrecord NotificationComponent [mqtt] component/Lifecycle (start [this] (log/debug "Starting Notification Component") (let [c (chan)] (process-channel mqtt c) (assoc this :mqtt mqtt :send-channel c))) (stop [this] (log/debug "Stopping Notification Component") (close! (:send-channel this)) this)) (defrecord SignalNotificationComponent [] component/Lifecycle (start [this] (log/debug "Starting Signal") (let [c (chan)] (process-channel nil c) (assoc this :send-channel c))) (stop [this] this)) (defn make-notification-component [] (->NotificationComponent nil)) (defn make-signal-notification-component [] (->SignalNotificationComponent))
94464
;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 spacon.components.notification.core (:require [com.stuartsierra.component :as component] [spacon.components.mqtt.core :as mqttapi] [clojure.core.async :refer [chan <!! >!! close! go alt!]] [postal.core :refer [send-message]] [spacon.components.notification.db :as notifmodel] [clojure.tools.logging :as log])) (defn- send->device [mqtt device-id message] (mqttapi/publish-map mqtt (str "/notify/" device-id) message)) (defn- send->devices [mqtt devices message] (map (fn [device-id] (send->device mqtt device-id message)) devices)) (defn- send->all [mqtt message] (mqttapi/publish-map mqtt "/notify" message)) (defn- send->mobile [mqtt message] (case (count (:to message)) 0 (send->all mqtt message) 1 (send->device mqtt (first (:to message)) message) (send->devices mqtt (:to message) message)) (map notifmodel/mark-as-sent (:notif_id message))) (def conn {:host (or (System/getenv "SMTP_HOST") "email-smtp.us-east-1.amazonaws.com") :ssl true :user (System/getenv "SMTP_USERNAME") :pass (System/getenv "SMTP_PASSWORD")}) (defn- build-notification-link [id] (let [hostname (or (System/getenv "HOSTNAME") (.getHostName (java.net.InetAddress/getLocalHost)))] (str "http://" hostname "/notifications/" id))) (defn- email-recipient [id recipient message] (let [body (str (build-notification-link id))] (send-message conn {:from "<EMAIL>" :to (str recipient) :subject (str (:title message)) :body body}))) (defn- send->email [message] (let [recipients (do (zipmap (:notif-ids message) (:to message)))] (doall (map (fn [[id recipient]] (email-recipient id recipient message) (notifmodel/mark-as-sent id)) recipients)))) (defn- process-channel [mqtt input-channel] (go (while true (let [v (<!! input-channel)] (case (:output_type v) :email (send->email v) :mobile (if-not (empty? mqtt) (send->mobile mqtt v)) ; For Signal that doesn't have an mqtt component "default"))))) (defn notify [notifcomp message message-type info] (let [ids (map :id (notifmodel/create-notifications (:to message) message-type info))] (go (>!! (:send-channel notifcomp) (assoc message :notif-ids ids))))) (defn find-notif-by-id [notif-comp id] (notifmodel/find-notif-by-id id)) (defrecord NotificationComponent [mqtt] component/Lifecycle (start [this] (log/debug "Starting Notification Component") (let [c (chan)] (process-channel mqtt c) (assoc this :mqtt mqtt :send-channel c))) (stop [this] (log/debug "Stopping Notification Component") (close! (:send-channel this)) this)) (defrecord SignalNotificationComponent [] component/Lifecycle (start [this] (log/debug "Starting Signal") (let [c (chan)] (process-channel nil c) (assoc this :send-channel c))) (stop [this] this)) (defn make-notification-component [] (->NotificationComponent nil)) (defn make-signal-notification-component [] (->SignalNotificationComponent))
true
;; Copyright 2016-2017 Boundless, http://boundlessgeo.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 spacon.components.notification.core (:require [com.stuartsierra.component :as component] [spacon.components.mqtt.core :as mqttapi] [clojure.core.async :refer [chan <!! >!! close! go alt!]] [postal.core :refer [send-message]] [spacon.components.notification.db :as notifmodel] [clojure.tools.logging :as log])) (defn- send->device [mqtt device-id message] (mqttapi/publish-map mqtt (str "/notify/" device-id) message)) (defn- send->devices [mqtt devices message] (map (fn [device-id] (send->device mqtt device-id message)) devices)) (defn- send->all [mqtt message] (mqttapi/publish-map mqtt "/notify" message)) (defn- send->mobile [mqtt message] (case (count (:to message)) 0 (send->all mqtt message) 1 (send->device mqtt (first (:to message)) message) (send->devices mqtt (:to message) message)) (map notifmodel/mark-as-sent (:notif_id message))) (def conn {:host (or (System/getenv "SMTP_HOST") "email-smtp.us-east-1.amazonaws.com") :ssl true :user (System/getenv "SMTP_USERNAME") :pass (System/getenv "SMTP_PASSWORD")}) (defn- build-notification-link [id] (let [hostname (or (System/getenv "HOSTNAME") (.getHostName (java.net.InetAddress/getLocalHost)))] (str "http://" hostname "/notifications/" id))) (defn- email-recipient [id recipient message] (let [body (str (build-notification-link id))] (send-message conn {:from "PI:EMAIL:<EMAIL>END_PI" :to (str recipient) :subject (str (:title message)) :body body}))) (defn- send->email [message] (let [recipients (do (zipmap (:notif-ids message) (:to message)))] (doall (map (fn [[id recipient]] (email-recipient id recipient message) (notifmodel/mark-as-sent id)) recipients)))) (defn- process-channel [mqtt input-channel] (go (while true (let [v (<!! input-channel)] (case (:output_type v) :email (send->email v) :mobile (if-not (empty? mqtt) (send->mobile mqtt v)) ; For Signal that doesn't have an mqtt component "default"))))) (defn notify [notifcomp message message-type info] (let [ids (map :id (notifmodel/create-notifications (:to message) message-type info))] (go (>!! (:send-channel notifcomp) (assoc message :notif-ids ids))))) (defn find-notif-by-id [notif-comp id] (notifmodel/find-notif-by-id id)) (defrecord NotificationComponent [mqtt] component/Lifecycle (start [this] (log/debug "Starting Notification Component") (let [c (chan)] (process-channel mqtt c) (assoc this :mqtt mqtt :send-channel c))) (stop [this] (log/debug "Stopping Notification Component") (close! (:send-channel this)) this)) (defrecord SignalNotificationComponent [] component/Lifecycle (start [this] (log/debug "Starting Signal") (let [c (chan)] (process-channel nil c) (assoc this :send-channel c))) (stop [this] this)) (defn make-notification-component [] (->NotificationComponent nil)) (defn make-signal-notification-component [] (->SignalNotificationComponent))
[ { "context": "w-password)\n (check-password re-new-password)\n\n (check-new-passwords-mat", "end": 5833, "score": 0.762820839881897, "start": 5818, "tag": "PASSWORD", "value": "re-new-password" }, { "context": "4)))\n\n(defn get-auth-user\n [user]\n {:username (:username user)\n :created (number-of-days (:created-d", "end": 9588, "score": 0.9922060966491699, "start": 9578, "tag": "USERNAME", "value": "(:username" }, { "context": " get-auth-user\n [user]\n {:username (:username user)\n :created (number-of-days (:created-date u", "end": 9593, "score": 0.9801621437072754, "start": 9589, "tag": "USERNAME", "value": "user" }, { "context": "RuntimeException. \"Not valid GitHub Username. Ex: ertugrulcetin\"))))\n\n(defn check-twitter\n [twitter]\n (if-not (", "end": 10998, "score": 0.999433696269989, "start": 10985, "tag": "USERNAME", "value": "ertugrulcetin" }, { "context": "RuntimeException. \"Not valid Twitter Username. Ex: ertuctn\"))))\n\n(defn check-show-email?\n [show-emai", "end": 11149, "score": 0.9570834636688232, "start": 11149, "tag": "USERNAME", "value": "" }, { "context": "untimeException. \"Not valid Twitter Username. Ex: ertuctn\"))))\n\n(defn check-show-email?\n [show-email?]\n (", "end": 11157, "score": 0.9987009167671204, "start": 11150, "tag": "USERNAME", "value": "ertuctn" } ]
src/clj/controller/user.clj
wuleicanada/ClojureNews
254
(ns clj.controller.user (:require [liberator.core :refer [resource defresource]] [clj.util.resource :as resource-util] [clj.dao.user :as user-dao] [cljc.validation :as validation] [cljc.string-util :as string-util] [pandect.algo.sha256 :as hash] [clojure.string :as str] [postal.core :refer [send-message]]) (:import (java.util Date))) (declare itself? number-of-days get-auth-user check-username check-user-exist check-user-has-email check-about check-email check-website check-github check-twitter check-show-email? check-email-exists check-password check-new-passwords-match check-current-pass-not-equals-new-pass check-password-match) (defn user [username] (resource :allowed-methods [:get] :available-media-types resource-util/avaliable-media-types :handle-ok (fn [ctx] (if-not (validation/username? username) (throw (RuntimeException. "Not valid username"))) (if-let [user (user-dao/find-by-username username)] (if (itself? ctx user) (merge {:auth? true} (get-auth-user user)) (if (:show-email? user) (merge {:auth? false} (get-auth-user user)) (merge {:auth? false} (dissoc (get-auth-user user) :email)))) (throw (RuntimeException. "No such user")))) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn update-user [username] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :authorized? (fn [ctx] (if-let [cookie (resource-util/get-cookie ctx)] (if-let [username (resource-util/get-username-from-cookie ctx)] (if-let [user (user-dao/find-by-username username)] (if (= cookie (:cookie user)) {:user-obj user}))))) :allowed? (fn [ctx] (= username (-> ctx :user-obj :username))) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) about (:about data-as-map) email (:email data-as-map) website (:website data-as-map) github (:github data-as-map) twitter (:twitter data-as-map) show-email? (:show-email? data-as-map)] (check-about about) (check-email email) (check-website website) (check-github github) (check-twitter twitter) (check-show-email? show-email?) (when-not (str/blank? email) (check-email-exists (-> ctx :user-obj :username) email)) (try (let [show-email-updated-user (update-in (string-util/trim-map-values data-as-map) [:show-email?] #(if (= "yes" %) true false)) about-updated-user (update-in show-email-updated-user [:about] #(apply str (interpose "\n" (string-util/new-line-tokens %)))) email-updated-user (update-in about-updated-user [:email] #(if (str/blank? %) nil email))] (user-dao/update-user-info-by-username username email-updated-user)) (catch Exception e (throw (RuntimeException. "Something went wrong.")))))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:update? true}) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn change-password [username] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :authorized? (fn [ctx] (if-let [cookie (resource-util/get-cookie ctx)] (if-let [username (resource-util/get-username-from-cookie ctx)] (if-let [user (user-dao/find-by-username username)] (if (= cookie (:cookie user)) {:user-obj user}))))) :allowed? (fn [ctx] (= username (-> ctx :user-obj :username))) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) current-password (:current-password data-as-map) new-password (:new-password data-as-map) re-new-password (:re-new-password data-as-map)] (check-password current-password) (check-password new-password) (check-password re-new-password) (check-new-passwords-match new-password re-new-password) (check-current-pass-not-equals-new-pass current-password new-password) (check-password-match (-> ctx :user-obj) current-password) (user-dao/update-password-by-username (-> ctx :user-obj :username) (hash/sha256 new-password)))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:password-changed? true}) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn forgot-password [] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) username (when (:username data-as-map) (str/lower-case (:username data-as-map)))] (check-username username) (let [user (check-user-exist username)] (check-user-has-email user) (let [new-pass (resource-util/random-password) conn {:host "smtp.gmail.com" :ssl true :user (System/getenv "EMAIL") :pass (System/getenv "EMAIL_PASSWORD")}] (try (send-message conn {:from (System/getenv "EMAIL") :to (:email user) :subject "Password Recovery | Clojure News" :body [:alternative {:type "text/html" :content (str "<html><body><p>Some Clojurist (hopefully you) requested we reset your password at Clojure News.<br/> Here is your new password: " (str "<b>" new-pass "</b>") "</p> <p>You can change your password from your profile.</p> </body></html>")}]}) (user-dao/update-password-by-username username (hash/sha256 new-pass)) (catch Exception e (throw (RuntimeException. "Could not send e-mail.Please try again in a few minutes.")))))))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:message-sent? true}) :handle-exception #(resource-util/get-exception-message %))) (defn itself? [ctx user] (if-let [cookie (resource-util/get-cookie ctx)] (if (= cookie (:cookie user)) true))) (defn number-of-days [^Date start ^Date end] (-> (- (.getTime end) (.getTime start)) (quot 1000) (quot 60) (quot 60) (quot 24))) (defn get-auth-user [user] {:username (:username user) :created (number-of-days (:created-date user) (Date.)) :karma (:karma user) :show-email? (:show-email? user) :about (:about user) :email (:email user) :website (:website user) :github (:github user) :twitter (:twitter user)}) (defn check-username [username] (if-not (validation/username? username) (throw (RuntimeException. "Usernames can only contain letters, digits and underscores, and should be between 2 and 15 characters long. Please choose another.")))) (defn check-user-exist [username] (if-let [user (user-dao/find-by-username username)] user (throw (RuntimeException. "There is no such a user.")))) (defn check-user-has-email [user] (when-not (:email user) (throw (RuntimeException. "This user has no email.Please contact us.")))) (defn check-about [about] (if-not (validation/about? about) (throw (RuntimeException. "About should be between 0 and 500 characters long.")))) (defn check-email [email] (if-not (validation/email? email) (throw (RuntimeException. "Not valid email.")))) (defn check-website [website] (if-not (validation/url? website) (throw (RuntimeException. "Not valid url. Ex: https://www.google.com")))) (defn check-github [github] (if-not (validation/github-or-twitter? github) (throw (RuntimeException. "Not valid GitHub Username. Ex: ertugrulcetin")))) (defn check-twitter [twitter] (if-not (validation/github-or-twitter? twitter) (throw (RuntimeException. "Not valid Twitter Username. Ex: ertuctn")))) (defn check-show-email? [show-email?] (if-not (validation/show-email?? show-email?) (throw (RuntimeException. "Not valid show email option.")))) (defn check-email-exists [username email] (if-let [user (user-dao/find-by-email email)] (if-not (= (:username user) username) (throw (RuntimeException. "This email has already been taken by another user."))))) (defn check-password [password] (if-not (validation/password? password) (throw (RuntimeException. "Passwords should be between 8 and 128 characters long. Please choose another.")))) (defn check-new-passwords-match [password re-password] (if-not (= password re-password) (throw (RuntimeException. "New passwords don't match.")))) (defn check-current-pass-not-equals-new-pass [current-password new-password] (if (= current-password new-password) (throw (RuntimeException. "New password can not be the old password.")))) (defn check-password-match [user password] (if-not (= (:password user) (hash/sha256 password)) (throw (RuntimeException. "Password does not match."))))
11770
(ns clj.controller.user (:require [liberator.core :refer [resource defresource]] [clj.util.resource :as resource-util] [clj.dao.user :as user-dao] [cljc.validation :as validation] [cljc.string-util :as string-util] [pandect.algo.sha256 :as hash] [clojure.string :as str] [postal.core :refer [send-message]]) (:import (java.util Date))) (declare itself? number-of-days get-auth-user check-username check-user-exist check-user-has-email check-about check-email check-website check-github check-twitter check-show-email? check-email-exists check-password check-new-passwords-match check-current-pass-not-equals-new-pass check-password-match) (defn user [username] (resource :allowed-methods [:get] :available-media-types resource-util/avaliable-media-types :handle-ok (fn [ctx] (if-not (validation/username? username) (throw (RuntimeException. "Not valid username"))) (if-let [user (user-dao/find-by-username username)] (if (itself? ctx user) (merge {:auth? true} (get-auth-user user)) (if (:show-email? user) (merge {:auth? false} (get-auth-user user)) (merge {:auth? false} (dissoc (get-auth-user user) :email)))) (throw (RuntimeException. "No such user")))) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn update-user [username] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :authorized? (fn [ctx] (if-let [cookie (resource-util/get-cookie ctx)] (if-let [username (resource-util/get-username-from-cookie ctx)] (if-let [user (user-dao/find-by-username username)] (if (= cookie (:cookie user)) {:user-obj user}))))) :allowed? (fn [ctx] (= username (-> ctx :user-obj :username))) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) about (:about data-as-map) email (:email data-as-map) website (:website data-as-map) github (:github data-as-map) twitter (:twitter data-as-map) show-email? (:show-email? data-as-map)] (check-about about) (check-email email) (check-website website) (check-github github) (check-twitter twitter) (check-show-email? show-email?) (when-not (str/blank? email) (check-email-exists (-> ctx :user-obj :username) email)) (try (let [show-email-updated-user (update-in (string-util/trim-map-values data-as-map) [:show-email?] #(if (= "yes" %) true false)) about-updated-user (update-in show-email-updated-user [:about] #(apply str (interpose "\n" (string-util/new-line-tokens %)))) email-updated-user (update-in about-updated-user [:email] #(if (str/blank? %) nil email))] (user-dao/update-user-info-by-username username email-updated-user)) (catch Exception e (throw (RuntimeException. "Something went wrong.")))))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:update? true}) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn change-password [username] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :authorized? (fn [ctx] (if-let [cookie (resource-util/get-cookie ctx)] (if-let [username (resource-util/get-username-from-cookie ctx)] (if-let [user (user-dao/find-by-username username)] (if (= cookie (:cookie user)) {:user-obj user}))))) :allowed? (fn [ctx] (= username (-> ctx :user-obj :username))) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) current-password (:current-password data-as-map) new-password (:new-password data-as-map) re-new-password (:re-new-password data-as-map)] (check-password current-password) (check-password new-password) (check-password <PASSWORD>) (check-new-passwords-match new-password re-new-password) (check-current-pass-not-equals-new-pass current-password new-password) (check-password-match (-> ctx :user-obj) current-password) (user-dao/update-password-by-username (-> ctx :user-obj :username) (hash/sha256 new-password)))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:password-changed? true}) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn forgot-password [] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) username (when (:username data-as-map) (str/lower-case (:username data-as-map)))] (check-username username) (let [user (check-user-exist username)] (check-user-has-email user) (let [new-pass (resource-util/random-password) conn {:host "smtp.gmail.com" :ssl true :user (System/getenv "EMAIL") :pass (System/getenv "EMAIL_PASSWORD")}] (try (send-message conn {:from (System/getenv "EMAIL") :to (:email user) :subject "Password Recovery | Clojure News" :body [:alternative {:type "text/html" :content (str "<html><body><p>Some Clojurist (hopefully you) requested we reset your password at Clojure News.<br/> Here is your new password: " (str "<b>" new-pass "</b>") "</p> <p>You can change your password from your profile.</p> </body></html>")}]}) (user-dao/update-password-by-username username (hash/sha256 new-pass)) (catch Exception e (throw (RuntimeException. "Could not send e-mail.Please try again in a few minutes.")))))))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:message-sent? true}) :handle-exception #(resource-util/get-exception-message %))) (defn itself? [ctx user] (if-let [cookie (resource-util/get-cookie ctx)] (if (= cookie (:cookie user)) true))) (defn number-of-days [^Date start ^Date end] (-> (- (.getTime end) (.getTime start)) (quot 1000) (quot 60) (quot 60) (quot 24))) (defn get-auth-user [user] {:username (:username user) :created (number-of-days (:created-date user) (Date.)) :karma (:karma user) :show-email? (:show-email? user) :about (:about user) :email (:email user) :website (:website user) :github (:github user) :twitter (:twitter user)}) (defn check-username [username] (if-not (validation/username? username) (throw (RuntimeException. "Usernames can only contain letters, digits and underscores, and should be between 2 and 15 characters long. Please choose another.")))) (defn check-user-exist [username] (if-let [user (user-dao/find-by-username username)] user (throw (RuntimeException. "There is no such a user.")))) (defn check-user-has-email [user] (when-not (:email user) (throw (RuntimeException. "This user has no email.Please contact us.")))) (defn check-about [about] (if-not (validation/about? about) (throw (RuntimeException. "About should be between 0 and 500 characters long.")))) (defn check-email [email] (if-not (validation/email? email) (throw (RuntimeException. "Not valid email.")))) (defn check-website [website] (if-not (validation/url? website) (throw (RuntimeException. "Not valid url. Ex: https://www.google.com")))) (defn check-github [github] (if-not (validation/github-or-twitter? github) (throw (RuntimeException. "Not valid GitHub Username. Ex: ertugrulcetin")))) (defn check-twitter [twitter] (if-not (validation/github-or-twitter? twitter) (throw (RuntimeException. "Not valid Twitter Username. Ex: ertuctn")))) (defn check-show-email? [show-email?] (if-not (validation/show-email?? show-email?) (throw (RuntimeException. "Not valid show email option.")))) (defn check-email-exists [username email] (if-let [user (user-dao/find-by-email email)] (if-not (= (:username user) username) (throw (RuntimeException. "This email has already been taken by another user."))))) (defn check-password [password] (if-not (validation/password? password) (throw (RuntimeException. "Passwords should be between 8 and 128 characters long. Please choose another.")))) (defn check-new-passwords-match [password re-password] (if-not (= password re-password) (throw (RuntimeException. "New passwords don't match.")))) (defn check-current-pass-not-equals-new-pass [current-password new-password] (if (= current-password new-password) (throw (RuntimeException. "New password can not be the old password.")))) (defn check-password-match [user password] (if-not (= (:password user) (hash/sha256 password)) (throw (RuntimeException. "Password does not match."))))
true
(ns clj.controller.user (:require [liberator.core :refer [resource defresource]] [clj.util.resource :as resource-util] [clj.dao.user :as user-dao] [cljc.validation :as validation] [cljc.string-util :as string-util] [pandect.algo.sha256 :as hash] [clojure.string :as str] [postal.core :refer [send-message]]) (:import (java.util Date))) (declare itself? number-of-days get-auth-user check-username check-user-exist check-user-has-email check-about check-email check-website check-github check-twitter check-show-email? check-email-exists check-password check-new-passwords-match check-current-pass-not-equals-new-pass check-password-match) (defn user [username] (resource :allowed-methods [:get] :available-media-types resource-util/avaliable-media-types :handle-ok (fn [ctx] (if-not (validation/username? username) (throw (RuntimeException. "Not valid username"))) (if-let [user (user-dao/find-by-username username)] (if (itself? ctx user) (merge {:auth? true} (get-auth-user user)) (if (:show-email? user) (merge {:auth? false} (get-auth-user user)) (merge {:auth? false} (dissoc (get-auth-user user) :email)))) (throw (RuntimeException. "No such user")))) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn update-user [username] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :authorized? (fn [ctx] (if-let [cookie (resource-util/get-cookie ctx)] (if-let [username (resource-util/get-username-from-cookie ctx)] (if-let [user (user-dao/find-by-username username)] (if (= cookie (:cookie user)) {:user-obj user}))))) :allowed? (fn [ctx] (= username (-> ctx :user-obj :username))) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) about (:about data-as-map) email (:email data-as-map) website (:website data-as-map) github (:github data-as-map) twitter (:twitter data-as-map) show-email? (:show-email? data-as-map)] (check-about about) (check-email email) (check-website website) (check-github github) (check-twitter twitter) (check-show-email? show-email?) (when-not (str/blank? email) (check-email-exists (-> ctx :user-obj :username) email)) (try (let [show-email-updated-user (update-in (string-util/trim-map-values data-as-map) [:show-email?] #(if (= "yes" %) true false)) about-updated-user (update-in show-email-updated-user [:about] #(apply str (interpose "\n" (string-util/new-line-tokens %)))) email-updated-user (update-in about-updated-user [:email] #(if (str/blank? %) nil email))] (user-dao/update-user-info-by-username username email-updated-user)) (catch Exception e (throw (RuntimeException. "Something went wrong.")))))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:update? true}) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn change-password [username] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :authorized? (fn [ctx] (if-let [cookie (resource-util/get-cookie ctx)] (if-let [username (resource-util/get-username-from-cookie ctx)] (if-let [user (user-dao/find-by-username username)] (if (= cookie (:cookie user)) {:user-obj user}))))) :allowed? (fn [ctx] (= username (-> ctx :user-obj :username))) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) current-password (:current-password data-as-map) new-password (:new-password data-as-map) re-new-password (:re-new-password data-as-map)] (check-password current-password) (check-password new-password) (check-password PI:PASSWORD:<PASSWORD>END_PI) (check-new-passwords-match new-password re-new-password) (check-current-pass-not-equals-new-pass current-password new-password) (check-password-match (-> ctx :user-obj) current-password) (user-dao/update-password-by-username (-> ctx :user-obj :username) (hash/sha256 new-password)))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:password-changed? true}) :handle-exception (fn [ctx] (resource-util/get-exception-message ctx)))) (defn forgot-password [] (resource :allowed-methods [:post] :available-media-types resource-util/avaliable-media-types :known-content-type? #(resource-util/check-content-type % resource-util/avaliable-media-types) :malformed? #(resource-util/parse-json % ::data) :post! (fn [ctx] (let [data-as-map (resource-util/convert-data-map (::data ctx)) username (when (:username data-as-map) (str/lower-case (:username data-as-map)))] (check-username username) (let [user (check-user-exist username)] (check-user-has-email user) (let [new-pass (resource-util/random-password) conn {:host "smtp.gmail.com" :ssl true :user (System/getenv "EMAIL") :pass (System/getenv "EMAIL_PASSWORD")}] (try (send-message conn {:from (System/getenv "EMAIL") :to (:email user) :subject "Password Recovery | Clojure News" :body [:alternative {:type "text/html" :content (str "<html><body><p>Some Clojurist (hopefully you) requested we reset your password at Clojure News.<br/> Here is your new password: " (str "<b>" new-pass "</b>") "</p> <p>You can change your password from your profile.</p> </body></html>")}]}) (user-dao/update-password-by-username username (hash/sha256 new-pass)) (catch Exception e (throw (RuntimeException. "Could not send e-mail.Please try again in a few minutes.")))))))) :new? (fn [_] false) :respond-with-entity? (fn [_] true) :handle-ok (fn [_] {:message-sent? true}) :handle-exception #(resource-util/get-exception-message %))) (defn itself? [ctx user] (if-let [cookie (resource-util/get-cookie ctx)] (if (= cookie (:cookie user)) true))) (defn number-of-days [^Date start ^Date end] (-> (- (.getTime end) (.getTime start)) (quot 1000) (quot 60) (quot 60) (quot 24))) (defn get-auth-user [user] {:username (:username user) :created (number-of-days (:created-date user) (Date.)) :karma (:karma user) :show-email? (:show-email? user) :about (:about user) :email (:email user) :website (:website user) :github (:github user) :twitter (:twitter user)}) (defn check-username [username] (if-not (validation/username? username) (throw (RuntimeException. "Usernames can only contain letters, digits and underscores, and should be between 2 and 15 characters long. Please choose another.")))) (defn check-user-exist [username] (if-let [user (user-dao/find-by-username username)] user (throw (RuntimeException. "There is no such a user.")))) (defn check-user-has-email [user] (when-not (:email user) (throw (RuntimeException. "This user has no email.Please contact us.")))) (defn check-about [about] (if-not (validation/about? about) (throw (RuntimeException. "About should be between 0 and 500 characters long.")))) (defn check-email [email] (if-not (validation/email? email) (throw (RuntimeException. "Not valid email.")))) (defn check-website [website] (if-not (validation/url? website) (throw (RuntimeException. "Not valid url. Ex: https://www.google.com")))) (defn check-github [github] (if-not (validation/github-or-twitter? github) (throw (RuntimeException. "Not valid GitHub Username. Ex: ertugrulcetin")))) (defn check-twitter [twitter] (if-not (validation/github-or-twitter? twitter) (throw (RuntimeException. "Not valid Twitter Username. Ex: ertuctn")))) (defn check-show-email? [show-email?] (if-not (validation/show-email?? show-email?) (throw (RuntimeException. "Not valid show email option.")))) (defn check-email-exists [username email] (if-let [user (user-dao/find-by-email email)] (if-not (= (:username user) username) (throw (RuntimeException. "This email has already been taken by another user."))))) (defn check-password [password] (if-not (validation/password? password) (throw (RuntimeException. "Passwords should be between 8 and 128 characters long. Please choose another.")))) (defn check-new-passwords-match [password re-password] (if-not (= password re-password) (throw (RuntimeException. "New passwords don't match.")))) (defn check-current-pass-not-equals-new-pass [current-password new-password] (if (= current-password new-password) (throw (RuntimeException. "New password can not be the old password.")))) (defn check-password-match [user password] (if-not (= (:password user) (hash/sha256 password)) (throw (RuntimeException. "Password does not match."))))
[ { "context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.", "end": 32, "score": 0.9995545744895935, "start": 21, "tag": "NAME", "value": "Peter Monks" } ]
src/futbot/videos.clj
pmonks/futbot
3
; ; 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 futbot.videos (:require [clojure.tools.logging :as log] [java-time :as tm] [futbot.message-util :as mu] [futbot.source.youtube :as yt])) (def ist-youtube-channel-id "UCmzFaEBQlLmMTWS0IQ90tgA") (defn post-youtube-video! [{:keys [discord-message-channel youtube-channels education-and-resources-channel-id]} youtube-channel-id video] (let [channel-info (get youtube-channels youtube-channel-id) channel-title (org.jsoup.parser.Parser/unescapeEntities (:title channel-info) true) message (str (:emoji channel-info) (if channel-title (str " A new **" channel-title "** video has been posted: **") " A new video has been posted: **") (org.jsoup.parser.Parser/unescapeEntities (:title video) true) "**: https://www.youtube.com/watch?v=" (:id video) (when-not (= youtube-channel-id ist-youtube-channel-id) (str "\nDiscuss in " (mu/channel-link education-and-resources-channel-id) ".")))] (mu/create-message! discord-message-channel (:channel-id channel-info) :content message))) (defn check-for-new-youtube-videos-and-post! "Checks whether any new videos have been posted to the given YouTube channel in the last day, and posts it to the given Discord channel if so." [{:keys [youtube-api-token youtube-channels] :as config} youtube-channel-id] (let [channel-title (:title (get youtube-channels youtube-channel-id))] (if-let [new-videos (yt/videos youtube-api-token (tm/minus (tm/instant) (tm/days 1)) youtube-channel-id)] (doall (map (partial post-youtube-video! config youtube-channel-id) new-videos)) (log/info (str "No new videos found in YouTube channel " (if channel-title channel-title (str "-unknown (" youtube-channel-id ")-")))))))
50765
; ; 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 futbot.videos (:require [clojure.tools.logging :as log] [java-time :as tm] [futbot.message-util :as mu] [futbot.source.youtube :as yt])) (def ist-youtube-channel-id "UCmzFaEBQlLmMTWS0IQ90tgA") (defn post-youtube-video! [{:keys [discord-message-channel youtube-channels education-and-resources-channel-id]} youtube-channel-id video] (let [channel-info (get youtube-channels youtube-channel-id) channel-title (org.jsoup.parser.Parser/unescapeEntities (:title channel-info) true) message (str (:emoji channel-info) (if channel-title (str " A new **" channel-title "** video has been posted: **") " A new video has been posted: **") (org.jsoup.parser.Parser/unescapeEntities (:title video) true) "**: https://www.youtube.com/watch?v=" (:id video) (when-not (= youtube-channel-id ist-youtube-channel-id) (str "\nDiscuss in " (mu/channel-link education-and-resources-channel-id) ".")))] (mu/create-message! discord-message-channel (:channel-id channel-info) :content message))) (defn check-for-new-youtube-videos-and-post! "Checks whether any new videos have been posted to the given YouTube channel in the last day, and posts it to the given Discord channel if so." [{:keys [youtube-api-token youtube-channels] :as config} youtube-channel-id] (let [channel-title (:title (get youtube-channels youtube-channel-id))] (if-let [new-videos (yt/videos youtube-api-token (tm/minus (tm/instant) (tm/days 1)) youtube-channel-id)] (doall (map (partial post-youtube-video! config youtube-channel-id) new-videos)) (log/info (str "No new videos found in YouTube channel " (if channel-title channel-title (str "-unknown (" youtube-channel-id ")-")))))))
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 futbot.videos (:require [clojure.tools.logging :as log] [java-time :as tm] [futbot.message-util :as mu] [futbot.source.youtube :as yt])) (def ist-youtube-channel-id "UCmzFaEBQlLmMTWS0IQ90tgA") (defn post-youtube-video! [{:keys [discord-message-channel youtube-channels education-and-resources-channel-id]} youtube-channel-id video] (let [channel-info (get youtube-channels youtube-channel-id) channel-title (org.jsoup.parser.Parser/unescapeEntities (:title channel-info) true) message (str (:emoji channel-info) (if channel-title (str " A new **" channel-title "** video has been posted: **") " A new video has been posted: **") (org.jsoup.parser.Parser/unescapeEntities (:title video) true) "**: https://www.youtube.com/watch?v=" (:id video) (when-not (= youtube-channel-id ist-youtube-channel-id) (str "\nDiscuss in " (mu/channel-link education-and-resources-channel-id) ".")))] (mu/create-message! discord-message-channel (:channel-id channel-info) :content message))) (defn check-for-new-youtube-videos-and-post! "Checks whether any new videos have been posted to the given YouTube channel in the last day, and posts it to the given Discord channel if so." [{:keys [youtube-api-token youtube-channels] :as config} youtube-channel-id] (let [channel-title (:title (get youtube-channels youtube-channel-id))] (if-let [new-videos (yt/videos youtube-api-token (tm/minus (tm/instant) (tm/days 1)) youtube-channel-id)] (doall (map (partial post-youtube-video! config youtube-channel-id) new-videos)) (log/info (str "No new videos found in YouTube channel " (if channel-title channel-title (str "-unknown (" youtube-channel-id ")-")))))))
[ { "context": "db-test-env-var :mysql :password)]\n {:password password})\n (when (= context :db)\n {:db database-nam", "end": 2218, "score": 0.9990493655204773, "start": 2210, "tag": "PASSWORD", "value": "password" } ]
c#-metabase/test/metabase/test/data/mysql.clj
hanakhry/Crime_Admin
0
(ns metabase.test.data.mysql "Code for creating / destroying a MySQL database from a `DatabaseDefinition`." (:require [metabase.test.data.interface :as tx] [metabase.test.data.sql :as sql.tx] [metabase.test.data.sql-jdbc :as sql-jdbc.tx] [metabase.test.data.sql-jdbc.execute :as execute] [metabase.test.data.sql-jdbc.load-data :as load-data])) (sql-jdbc.tx/add-test-extensions! :mysql) (doseq [[base-type database-type] {:type/BigInteger "BIGINT" :type/Boolean "BOOLEAN" :type/Date "DATE" ;; (3) is fractional seconds precision, i.e. millisecond precision :type/DateTime "DATETIME(3)" ;; MySQL is extra dumb and can't have two `TIMESTAMP` columns without default ;; values — see ;; https://stackoverflow.com/questions/11601034/unable-to-create-2-timestamp-columns-in-1-mysql-table. ;; They also have to have non-zero values. See also ;; https://dba.stackexchange.com/questions/6171/invalid-default-value-for-datetime-when-changing-to-utf8-general-ci :type/DateTimeWithTZ "TIMESTAMP(3) DEFAULT '1970-01-01 00:00:01'" :type/Decimal "DECIMAL" :type/Float "DOUBLE" :type/Integer "INTEGER" :type/Text "TEXT" :type/Time "TIME(3)"}] (defmethod sql.tx/field-base-type->sql-type [:mysql base-type] [_ _] database-type)) (defmethod tx/dbdef->connection-details :mysql [_ context {:keys [database-name]}] (merge {:host (tx/db-test-env-var-or-throw :mysql :host "localhost") :port (tx/db-test-env-var-or-throw :mysql :port 3306) :user (tx/db-test-env-var :mysql :user "root")} (when-let [password (tx/db-test-env-var :mysql :password)] {:password password}) (when (= context :db) {:db database-name}))) (defmethod tx/aggregate-column-info :mysql ([driver ag-type] ((get-method tx/aggregate-column-info ::tx/test-extensions) driver ag-type)) ([driver ag-type field] (merge ((get-method tx/aggregate-column-info ::tx/test-extensions) driver ag-type field) (when (= ag-type :sum) {:base_type :type/Decimal})))) ;; TODO - we might be able to do SQL all at once by setting `allowMultiQueries=true` on the connection string (defmethod execute/execute-sql! :mysql [& args] (apply execute/sequentially-execute-sql! args)) (defmethod load-data/load-data! :mysql [& args] (apply load-data/load-data-all-at-once! args)) (defmethod sql.tx/pk-sql-type :mysql [_] "INTEGER NOT NULL AUTO_INCREMENT")
42764
(ns metabase.test.data.mysql "Code for creating / destroying a MySQL database from a `DatabaseDefinition`." (:require [metabase.test.data.interface :as tx] [metabase.test.data.sql :as sql.tx] [metabase.test.data.sql-jdbc :as sql-jdbc.tx] [metabase.test.data.sql-jdbc.execute :as execute] [metabase.test.data.sql-jdbc.load-data :as load-data])) (sql-jdbc.tx/add-test-extensions! :mysql) (doseq [[base-type database-type] {:type/BigInteger "BIGINT" :type/Boolean "BOOLEAN" :type/Date "DATE" ;; (3) is fractional seconds precision, i.e. millisecond precision :type/DateTime "DATETIME(3)" ;; MySQL is extra dumb and can't have two `TIMESTAMP` columns without default ;; values — see ;; https://stackoverflow.com/questions/11601034/unable-to-create-2-timestamp-columns-in-1-mysql-table. ;; They also have to have non-zero values. See also ;; https://dba.stackexchange.com/questions/6171/invalid-default-value-for-datetime-when-changing-to-utf8-general-ci :type/DateTimeWithTZ "TIMESTAMP(3) DEFAULT '1970-01-01 00:00:01'" :type/Decimal "DECIMAL" :type/Float "DOUBLE" :type/Integer "INTEGER" :type/Text "TEXT" :type/Time "TIME(3)"}] (defmethod sql.tx/field-base-type->sql-type [:mysql base-type] [_ _] database-type)) (defmethod tx/dbdef->connection-details :mysql [_ context {:keys [database-name]}] (merge {:host (tx/db-test-env-var-or-throw :mysql :host "localhost") :port (tx/db-test-env-var-or-throw :mysql :port 3306) :user (tx/db-test-env-var :mysql :user "root")} (when-let [password (tx/db-test-env-var :mysql :password)] {:password <PASSWORD>}) (when (= context :db) {:db database-name}))) (defmethod tx/aggregate-column-info :mysql ([driver ag-type] ((get-method tx/aggregate-column-info ::tx/test-extensions) driver ag-type)) ([driver ag-type field] (merge ((get-method tx/aggregate-column-info ::tx/test-extensions) driver ag-type field) (when (= ag-type :sum) {:base_type :type/Decimal})))) ;; TODO - we might be able to do SQL all at once by setting `allowMultiQueries=true` on the connection string (defmethod execute/execute-sql! :mysql [& args] (apply execute/sequentially-execute-sql! args)) (defmethod load-data/load-data! :mysql [& args] (apply load-data/load-data-all-at-once! args)) (defmethod sql.tx/pk-sql-type :mysql [_] "INTEGER NOT NULL AUTO_INCREMENT")
true
(ns metabase.test.data.mysql "Code for creating / destroying a MySQL database from a `DatabaseDefinition`." (:require [metabase.test.data.interface :as tx] [metabase.test.data.sql :as sql.tx] [metabase.test.data.sql-jdbc :as sql-jdbc.tx] [metabase.test.data.sql-jdbc.execute :as execute] [metabase.test.data.sql-jdbc.load-data :as load-data])) (sql-jdbc.tx/add-test-extensions! :mysql) (doseq [[base-type database-type] {:type/BigInteger "BIGINT" :type/Boolean "BOOLEAN" :type/Date "DATE" ;; (3) is fractional seconds precision, i.e. millisecond precision :type/DateTime "DATETIME(3)" ;; MySQL is extra dumb and can't have two `TIMESTAMP` columns without default ;; values — see ;; https://stackoverflow.com/questions/11601034/unable-to-create-2-timestamp-columns-in-1-mysql-table. ;; They also have to have non-zero values. See also ;; https://dba.stackexchange.com/questions/6171/invalid-default-value-for-datetime-when-changing-to-utf8-general-ci :type/DateTimeWithTZ "TIMESTAMP(3) DEFAULT '1970-01-01 00:00:01'" :type/Decimal "DECIMAL" :type/Float "DOUBLE" :type/Integer "INTEGER" :type/Text "TEXT" :type/Time "TIME(3)"}] (defmethod sql.tx/field-base-type->sql-type [:mysql base-type] [_ _] database-type)) (defmethod tx/dbdef->connection-details :mysql [_ context {:keys [database-name]}] (merge {:host (tx/db-test-env-var-or-throw :mysql :host "localhost") :port (tx/db-test-env-var-or-throw :mysql :port 3306) :user (tx/db-test-env-var :mysql :user "root")} (when-let [password (tx/db-test-env-var :mysql :password)] {:password PI:PASSWORD:<PASSWORD>END_PI}) (when (= context :db) {:db database-name}))) (defmethod tx/aggregate-column-info :mysql ([driver ag-type] ((get-method tx/aggregate-column-info ::tx/test-extensions) driver ag-type)) ([driver ag-type field] (merge ((get-method tx/aggregate-column-info ::tx/test-extensions) driver ag-type field) (when (= ag-type :sum) {:base_type :type/Decimal})))) ;; TODO - we might be able to do SQL all at once by setting `allowMultiQueries=true` on the connection string (defmethod execute/execute-sql! :mysql [& args] (apply execute/sequentially-execute-sql! args)) (defmethod load-data/load-data! :mysql [& args] (apply load-data/load-data-all-at-once! args)) (defmethod sql.tx/pk-sql-type :mysql [_] "INTEGER NOT NULL AUTO_INCREMENT")
[ { "context": " [{:keys [winners]}]\n [:section.winners\n [:h2 \"dzisiejsi zwycięzcy\"]\n (if (seq winners)\n [:ul\n (for [{:ke", "end": 1859, "score": 0.9484973549842834, "start": 1840, "tag": "NAME", "value": "dzisiejsi zwycięzcy" }, { "context": "asteczek.\"]\n [:dt \"kiedy wyniki?\"]\n [:dd \"Jutro. Niedługo po tym, jak Ministerstwo Zdrowia opublikuje oficj", "end": 2877, "score": 0.9015869498252869, "start": 2862, "tag": "NAME", "value": "Jutro. Niedługo" }, { "context": "dłowy?\"]\n [:dd [:a {:href \"https://github.com/nathell/koronalotek\"} \"Proszsz.\"]]\n [:dt \"czy nosić m", "end": 3528, "score": 0.9994427561759949, "start": 3521, "tag": "USERNAME", "value": "nathell" } ]
src/koronalotek/handler.clj
nathell/koronalotek
2
(ns koronalotek.handler (:require [clojure.string :as string] [hiccup2.core :refer [html]] [koronalotek.state :refer [state]] [koronalotek.time :as time] [ring.middleware.content-type :refer [wrap-content-type]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]])) (defn winners-count [{:keys [date cases]}] (let [month-names ["stycznia" "lutego" "marca" "kwietnia" "maja" "czerwca" "lipca" "sierpnia" "września" "października" "listopada" "grudnia"] new-cases (if (and (contains? #{2 3 4} (mod cases 10)) (not (contains? #{12 13 14} (mod cases 100)))) "nowe przypadki" "nowych przypadków") [y m d] (map #(Long/parseLong %) (string/split date #"-"))] [:div {:class "winners-count"} [:div d " " (month-names (dec m))] [:div.number (str cases)] [:div new-cases [:br "w Polsce"]]])) (defn banner [] (try (let [content (read-string (slurp "banner.edn"))] [:section.banner [:button.close {:onclick "document.querySelector('.banner').classList.add('hidden')"} "×"] content]) (catch Exception _ nil))) (defn layout [& content] (str "<!DOCTYPE html>\n" (html [:html [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}] [:link {:rel "stylesheet" :href "style.css"}] [:title "koronalotek"]] (into [:body (banner) [:section.title [:h1 [:a.faq-link {:href "/faq"} "ℹ️"] [:a.korona {:href "/"} "korona"] [:wbr] [:a.lotek {:href "/"} [:span "lotek"]]]]] content)]))) (defn winners [{:keys [winners]}] [:section.winners [:h2 "dzisiejsi zwycięzcy"] (if (seq winners) [:ul (for [{:keys [name guess delta]} winners] [:li [:b guess] " (" (cond (zero? delta) [:b "dokładnie!"] (pos? delta) "+" (neg? delta) "−") (when-not (zero? delta) (Math/abs delta)) ") – " name])] [:ul [:li "to pierwsze losowanie – jeszcze nie było zwycięzców!"]])]) (defn faq [] (layout [:section.faq [:h2 "FAQ"] [:dl [:dt "co można wygrać?"] [:dd "Wieczną sławę i chwałę. Chyba że przyjdzie Sasin i ufunduje coś jeszcze."] [:dt "czy można typować więcej niż raz?"] [:dd "Można. Głosy oddawane z automatu będą usuwane, podobnie jak za wiele głosów jednej osoby."] [:dt "jakie dane są zbierane?"] [:dd "Imię (albo cokolwiek, co wpiszesz w polu na imię), zgadnięta liczba przypadków, numer IP, data i czas oddania głosu." [:br] "Strona " [:em "nie"] " używa ciasteczek."] [:dt "kiedy wyniki?"] [:dd "Jutro. Niedługo po tym, jak Ministerstwo Zdrowia opublikuje oficjalne dane z ostatniej doby – na ogół ok. 10:30. Wyniki pobierane są automatycznie, chyba że coś się zepsuje albo MZ zmieni format danych – wtedy notowanie z danego dnia może nie dojść do skutku. Głosy oddane po publikacji danych przez MZ nie są brane pod uwagę."] [:dt "dlaczego nie ma mnie na liście?"] [:dd "Nie zgadłoś, zagłosowałoś za późno albo Twój głos nie spodobał się administracji."] [:dt "kto za tym stoi?"] [:dd "Jak to kto? " [:a {:href "http://danieljanus.pl"} "Rząd światowy."]] [:dt "może by tak kod źródłowy?"] [:dd [:a {:href "https://github.com/nathell/koronalotek"} "Proszsz."]] [:dt "czy nosić maseczkę?"] [:dd [:a {:href "https://pws.byu.edu/covid-19-and-masks"} "Tak."]] [:dt "nie ma żadnej pandemii!"] [:dd "Spadaj, foliarzu."] [:p [:a {:href "/"} "wróć na stronę główną"]]]])) (defn page [] (layout [:section.next [:h2 "zgaduj zgadula"] [:form {:action "/" :method "post"} [:label {:for "guess"} "ile przypadków jutro?"] [:input {:type "number" :name "guess" :min 0}] [:label {:for "name"} "Twoje imię"] [:input {:type "text" :name "name"}] [:button "zgaduję"]]] (winners-count @state) (winners @state))) (defn success-img [] [:section.success [:p [:a {:href "https://zrzutka.pl/9v584r"} [:img {:src "help.jpg"}]]] [:p [:a {:href "https://zrzutka.pl/9v584r"} "uratuj życie, kup śpiwór zamarzającej osobie"]] [:p [:a {:href "https://nowyswiat.online/to-dzieje-sie-teraz-przy-bialoruskiej-granicy-rozmowa-ze-swiadkiem-wydarzen/"} "co się dzieje na granicy?"]]]) (defn confirmation [ok?] (layout [:section.next [:h2 (if ok? "mamy Twój typ" "coś nie tak")] (when ok? (success-img)) [:p [:a {:href "/"} "wróć na stronę główną"]]])) (defn validate-guess [{{:strs [guess name] :as params} :form-params, :keys [remote-addr headers]}] (try (when (and (string? guess) (string? name)) (let [guess (Long/parseLong guess) ip (or (get headers "x-real-ip") remote-addr)] (when (>= guess 0) {:guess guess, :name name, :timestamp (time/now), :ip ip}))) (catch Exception _ nil))) (defn html-response [body] {:status 200, :headers {"content-type" "text/html; charset=utf-8"}, :body body}) (defn handle-guess [request] (if-let [guess (validate-guess request)] (do (let [new-state (swap! state update :guesses conj guess)] (spit "state.edn" (pr-str new-state))) (html-response (confirmation true))) (html-response (confirmation false)))) (defn basic-handler [{:keys [request-method uri] :as request}] (condp = [request-method uri] [:get "/"] (html-response (page)) [:get "/faq"] (html-response (faq)) [:post "/"] (handle-guess request) {:status 404, :headers {"Content-Type" "text/plain; charset=utf-8"}, :body "żodyn"})) (def handler (-> basic-handler (wrap-params) (wrap-resource "/") (wrap-content-type)))
559
(ns koronalotek.handler (:require [clojure.string :as string] [hiccup2.core :refer [html]] [koronalotek.state :refer [state]] [koronalotek.time :as time] [ring.middleware.content-type :refer [wrap-content-type]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]])) (defn winners-count [{:keys [date cases]}] (let [month-names ["stycznia" "lutego" "marca" "kwietnia" "maja" "czerwca" "lipca" "sierpnia" "września" "października" "listopada" "grudnia"] new-cases (if (and (contains? #{2 3 4} (mod cases 10)) (not (contains? #{12 13 14} (mod cases 100)))) "nowe przypadki" "nowych przypadków") [y m d] (map #(Long/parseLong %) (string/split date #"-"))] [:div {:class "winners-count"} [:div d " " (month-names (dec m))] [:div.number (str cases)] [:div new-cases [:br "w Polsce"]]])) (defn banner [] (try (let [content (read-string (slurp "banner.edn"))] [:section.banner [:button.close {:onclick "document.querySelector('.banner').classList.add('hidden')"} "×"] content]) (catch Exception _ nil))) (defn layout [& content] (str "<!DOCTYPE html>\n" (html [:html [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}] [:link {:rel "stylesheet" :href "style.css"}] [:title "koronalotek"]] (into [:body (banner) [:section.title [:h1 [:a.faq-link {:href "/faq"} "ℹ️"] [:a.korona {:href "/"} "korona"] [:wbr] [:a.lotek {:href "/"} [:span "lotek"]]]]] content)]))) (defn winners [{:keys [winners]}] [:section.winners [:h2 "<NAME>"] (if (seq winners) [:ul (for [{:keys [name guess delta]} winners] [:li [:b guess] " (" (cond (zero? delta) [:b "dokładnie!"] (pos? delta) "+" (neg? delta) "−") (when-not (zero? delta) (Math/abs delta)) ") – " name])] [:ul [:li "to pierwsze losowanie – jeszcze nie było zwycięzców!"]])]) (defn faq [] (layout [:section.faq [:h2 "FAQ"] [:dl [:dt "co można wygrać?"] [:dd "Wieczną sławę i chwałę. Chyba że przyjdzie Sasin i ufunduje coś jeszcze."] [:dt "czy można typować więcej niż raz?"] [:dd "Można. Głosy oddawane z automatu będą usuwane, podobnie jak za wiele głosów jednej osoby."] [:dt "jakie dane są zbierane?"] [:dd "Imię (albo cokolwiek, co wpiszesz w polu na imię), zgadnięta liczba przypadków, numer IP, data i czas oddania głosu." [:br] "Strona " [:em "nie"] " używa ciasteczek."] [:dt "kiedy wyniki?"] [:dd "<NAME> po tym, jak Ministerstwo Zdrowia opublikuje oficjalne dane z ostatniej doby – na ogół ok. 10:30. Wyniki pobierane są automatycznie, chyba że coś się zepsuje albo MZ zmieni format danych – wtedy notowanie z danego dnia może nie dojść do skutku. Głosy oddane po publikacji danych przez MZ nie są brane pod uwagę."] [:dt "dlaczego nie ma mnie na liście?"] [:dd "Nie zgadłoś, zagłosowałoś za późno albo Twój głos nie spodobał się administracji."] [:dt "kto za tym stoi?"] [:dd "Jak to kto? " [:a {:href "http://danieljanus.pl"} "Rząd światowy."]] [:dt "może by tak kod źródłowy?"] [:dd [:a {:href "https://github.com/nathell/koronalotek"} "Proszsz."]] [:dt "czy nosić maseczkę?"] [:dd [:a {:href "https://pws.byu.edu/covid-19-and-masks"} "Tak."]] [:dt "nie ma żadnej pandemii!"] [:dd "Spadaj, foliarzu."] [:p [:a {:href "/"} "wróć na stronę główną"]]]])) (defn page [] (layout [:section.next [:h2 "zgaduj zgadula"] [:form {:action "/" :method "post"} [:label {:for "guess"} "ile przypadków jutro?"] [:input {:type "number" :name "guess" :min 0}] [:label {:for "name"} "Twoje imię"] [:input {:type "text" :name "name"}] [:button "zgaduję"]]] (winners-count @state) (winners @state))) (defn success-img [] [:section.success [:p [:a {:href "https://zrzutka.pl/9v584r"} [:img {:src "help.jpg"}]]] [:p [:a {:href "https://zrzutka.pl/9v584r"} "uratuj życie, kup śpiwór zamarzającej osobie"]] [:p [:a {:href "https://nowyswiat.online/to-dzieje-sie-teraz-przy-bialoruskiej-granicy-rozmowa-ze-swiadkiem-wydarzen/"} "co się dzieje na granicy?"]]]) (defn confirmation [ok?] (layout [:section.next [:h2 (if ok? "mamy Twój typ" "coś nie tak")] (when ok? (success-img)) [:p [:a {:href "/"} "wróć na stronę główną"]]])) (defn validate-guess [{{:strs [guess name] :as params} :form-params, :keys [remote-addr headers]}] (try (when (and (string? guess) (string? name)) (let [guess (Long/parseLong guess) ip (or (get headers "x-real-ip") remote-addr)] (when (>= guess 0) {:guess guess, :name name, :timestamp (time/now), :ip ip}))) (catch Exception _ nil))) (defn html-response [body] {:status 200, :headers {"content-type" "text/html; charset=utf-8"}, :body body}) (defn handle-guess [request] (if-let [guess (validate-guess request)] (do (let [new-state (swap! state update :guesses conj guess)] (spit "state.edn" (pr-str new-state))) (html-response (confirmation true))) (html-response (confirmation false)))) (defn basic-handler [{:keys [request-method uri] :as request}] (condp = [request-method uri] [:get "/"] (html-response (page)) [:get "/faq"] (html-response (faq)) [:post "/"] (handle-guess request) {:status 404, :headers {"Content-Type" "text/plain; charset=utf-8"}, :body "żodyn"})) (def handler (-> basic-handler (wrap-params) (wrap-resource "/") (wrap-content-type)))
true
(ns koronalotek.handler (:require [clojure.string :as string] [hiccup2.core :refer [html]] [koronalotek.state :refer [state]] [koronalotek.time :as time] [ring.middleware.content-type :refer [wrap-content-type]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.resource :refer [wrap-resource]])) (defn winners-count [{:keys [date cases]}] (let [month-names ["stycznia" "lutego" "marca" "kwietnia" "maja" "czerwca" "lipca" "sierpnia" "września" "października" "listopada" "grudnia"] new-cases (if (and (contains? #{2 3 4} (mod cases 10)) (not (contains? #{12 13 14} (mod cases 100)))) "nowe przypadki" "nowych przypadków") [y m d] (map #(Long/parseLong %) (string/split date #"-"))] [:div {:class "winners-count"} [:div d " " (month-names (dec m))] [:div.number (str cases)] [:div new-cases [:br "w Polsce"]]])) (defn banner [] (try (let [content (read-string (slurp "banner.edn"))] [:section.banner [:button.close {:onclick "document.querySelector('.banner').classList.add('hidden')"} "×"] content]) (catch Exception _ nil))) (defn layout [& content] (str "<!DOCTYPE html>\n" (html [:html [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}] [:link {:rel "stylesheet" :href "style.css"}] [:title "koronalotek"]] (into [:body (banner) [:section.title [:h1 [:a.faq-link {:href "/faq"} "ℹ️"] [:a.korona {:href "/"} "korona"] [:wbr] [:a.lotek {:href "/"} [:span "lotek"]]]]] content)]))) (defn winners [{:keys [winners]}] [:section.winners [:h2 "PI:NAME:<NAME>END_PI"] (if (seq winners) [:ul (for [{:keys [name guess delta]} winners] [:li [:b guess] " (" (cond (zero? delta) [:b "dokładnie!"] (pos? delta) "+" (neg? delta) "−") (when-not (zero? delta) (Math/abs delta)) ") – " name])] [:ul [:li "to pierwsze losowanie – jeszcze nie było zwycięzców!"]])]) (defn faq [] (layout [:section.faq [:h2 "FAQ"] [:dl [:dt "co można wygrać?"] [:dd "Wieczną sławę i chwałę. Chyba że przyjdzie Sasin i ufunduje coś jeszcze."] [:dt "czy można typować więcej niż raz?"] [:dd "Można. Głosy oddawane z automatu będą usuwane, podobnie jak za wiele głosów jednej osoby."] [:dt "jakie dane są zbierane?"] [:dd "Imię (albo cokolwiek, co wpiszesz w polu na imię), zgadnięta liczba przypadków, numer IP, data i czas oddania głosu." [:br] "Strona " [:em "nie"] " używa ciasteczek."] [:dt "kiedy wyniki?"] [:dd "PI:NAME:<NAME>END_PI po tym, jak Ministerstwo Zdrowia opublikuje oficjalne dane z ostatniej doby – na ogół ok. 10:30. Wyniki pobierane są automatycznie, chyba że coś się zepsuje albo MZ zmieni format danych – wtedy notowanie z danego dnia może nie dojść do skutku. Głosy oddane po publikacji danych przez MZ nie są brane pod uwagę."] [:dt "dlaczego nie ma mnie na liście?"] [:dd "Nie zgadłoś, zagłosowałoś za późno albo Twój głos nie spodobał się administracji."] [:dt "kto za tym stoi?"] [:dd "Jak to kto? " [:a {:href "http://danieljanus.pl"} "Rząd światowy."]] [:dt "może by tak kod źródłowy?"] [:dd [:a {:href "https://github.com/nathell/koronalotek"} "Proszsz."]] [:dt "czy nosić maseczkę?"] [:dd [:a {:href "https://pws.byu.edu/covid-19-and-masks"} "Tak."]] [:dt "nie ma żadnej pandemii!"] [:dd "Spadaj, foliarzu."] [:p [:a {:href "/"} "wróć na stronę główną"]]]])) (defn page [] (layout [:section.next [:h2 "zgaduj zgadula"] [:form {:action "/" :method "post"} [:label {:for "guess"} "ile przypadków jutro?"] [:input {:type "number" :name "guess" :min 0}] [:label {:for "name"} "Twoje imię"] [:input {:type "text" :name "name"}] [:button "zgaduję"]]] (winners-count @state) (winners @state))) (defn success-img [] [:section.success [:p [:a {:href "https://zrzutka.pl/9v584r"} [:img {:src "help.jpg"}]]] [:p [:a {:href "https://zrzutka.pl/9v584r"} "uratuj życie, kup śpiwór zamarzającej osobie"]] [:p [:a {:href "https://nowyswiat.online/to-dzieje-sie-teraz-przy-bialoruskiej-granicy-rozmowa-ze-swiadkiem-wydarzen/"} "co się dzieje na granicy?"]]]) (defn confirmation [ok?] (layout [:section.next [:h2 (if ok? "mamy Twój typ" "coś nie tak")] (when ok? (success-img)) [:p [:a {:href "/"} "wróć na stronę główną"]]])) (defn validate-guess [{{:strs [guess name] :as params} :form-params, :keys [remote-addr headers]}] (try (when (and (string? guess) (string? name)) (let [guess (Long/parseLong guess) ip (or (get headers "x-real-ip") remote-addr)] (when (>= guess 0) {:guess guess, :name name, :timestamp (time/now), :ip ip}))) (catch Exception _ nil))) (defn html-response [body] {:status 200, :headers {"content-type" "text/html; charset=utf-8"}, :body body}) (defn handle-guess [request] (if-let [guess (validate-guess request)] (do (let [new-state (swap! state update :guesses conj guess)] (spit "state.edn" (pr-str new-state))) (html-response (confirmation true))) (html-response (confirmation false)))) (defn basic-handler [{:keys [request-method uri] :as request}] (condp = [request-method uri] [:get "/"] (html-response (page)) [:get "/faq"] (html-response (faq)) [:post "/"] (handle-guess request) {:status 404, :headers {"Content-Type" "text/plain; charset=utf-8"}, :body "żodyn"})) (def handler (-> basic-handler (wrap-params) (wrap-resource "/") (wrap-content-type)))
[ { "context": "et \"list\"))\n\n(generate-string {:friends {:friend \"nico\" :age 15}})\n\n(parse-smile\n (generate-smile {:foo ", "end": 281, "score": 0.7809801697731018, "start": 277, "tag": "NAME", "value": "nico" }, { "context": "(parse-smile\n (generate-smile {:friends {:friend \"nico\" :age 15}}))\n\n\n(println\n (generate-string {:frien", "end": 403, "score": 0.908608615398407, "start": 399, "tag": "NAME", "value": "nico" }, { "context": "\n\n\n(println\n (generate-string {:friends {:friend \"nico\" :age 15}} {:pretty true}))\n\n(parse-string \"{\\\"fr", "end": 470, "score": 0.8760322332382202, "start": 466, "tag": "NAME", "value": "nico" }, { "context": "rue}))\n\n(parse-string \"{\\\"friends\\\":{\\\"friend\\\":\\\"nico\\\",\\\"age\\\":15}}\" (fn [k] (keyword (.toUpperCase k)", "end": 546, "score": 0.8421554565429688, "start": 542, "tag": "NAME", "value": "nico" } ]
Chapter 04 Code/code-niko/src/chapter04/somejson.clj
PacktPublishing/Clojure-Programming-Cookbook
14
(require '[cheshire.core :refer :all]) (def url "http://api.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&cluster=yes&appid=2de143494c0b295cca9337e1e96b00e0") (def slurped (slurp url)) (-> slurped parse-string (get "list")) (generate-string {:friends {:friend "nico" :age 15}}) (parse-smile (generate-smile {:foo "bar" :baz 5})) (parse-smile (generate-smile {:friends {:friend "nico" :age 15}})) (println (generate-string {:friends {:friend "nico" :age 15}} {:pretty true})) (parse-string "{\"friends\":{\"friend\":\"nico\",\"age\":15}}" (fn [k] (keyword (.toUpperCase k))))
10234
(require '[cheshire.core :refer :all]) (def url "http://api.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&cluster=yes&appid=2de143494c0b295cca9337e1e96b00e0") (def slurped (slurp url)) (-> slurped parse-string (get "list")) (generate-string {:friends {:friend "<NAME>" :age 15}}) (parse-smile (generate-smile {:foo "bar" :baz 5})) (parse-smile (generate-smile {:friends {:friend "<NAME>" :age 15}})) (println (generate-string {:friends {:friend "<NAME>" :age 15}} {:pretty true})) (parse-string "{\"friends\":{\"friend\":\"<NAME>\",\"age\":15}}" (fn [k] (keyword (.toUpperCase k))))
true
(require '[cheshire.core :refer :all]) (def url "http://api.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&cluster=yes&appid=2de143494c0b295cca9337e1e96b00e0") (def slurped (slurp url)) (-> slurped parse-string (get "list")) (generate-string {:friends {:friend "PI:NAME:<NAME>END_PI" :age 15}}) (parse-smile (generate-smile {:foo "bar" :baz 5})) (parse-smile (generate-smile {:friends {:friend "PI:NAME:<NAME>END_PI" :age 15}})) (println (generate-string {:friends {:friend "PI:NAME:<NAME>END_PI" :age 15}} {:pretty true})) (parse-string "{\"friends\":{\"friend\":\"PI:NAME:<NAME>END_PI\",\"age\":15}}" (fn [k] (keyword (.toUpperCase k))))
[ { "context": "@verify\n [:> js/ReactRecaptcha {:sitekey \"6Lcmw00UAAAAAOOKJDoeVNEsVuJFJ6ka3dSbGaIV\"\n :verifyCallback ", "end": 8584, "score": 0.9996752738952637, "start": 8544, "tag": "KEY", "value": "6Lcmw00UAAAAAOOKJDoeVNEsVuJFJ6ka3dSbGaIV" } ]
web-app/src/payme/core.cljs
Atul9/payme
11
(ns payme.core (:require [reagent.core :as reagent :refer [atom cursor]] [cljs.core.async :refer [go <! timeout]] [cljs-http.client :as http] [clojure.string :as s] [cljsjs.react-recaptcha] [reagent.cookies :as cookies] [goog.crypt.base64 :as b64] [goog.crypt :as cr] [rocks.clj.transit.core :as transit] [cljsjs.react-datetime]) (:require-macros [cljs.core.async :refer [go]])) (def datetime (reagent/adapt-react-class js/Datetime)) (enable-console-print!) (def app-state (atom {:messages [] :params (or (when-let [d (cookies/get "payme_invoice")] (transit/from-transit (cr/utf8ByteArrayToString (b64/decodeStringToByteArray d true)))) {})})) (defn write-cookie [] (cookies/set! "payme_invoice" (b64/encodeByteArray (cr/stringToUtf8ByteArray (transit/to-transit (:params @app-state))) true))) (defn focus-element [id] (.focus (.getElementById js/document id))) (defn on-enter [f & [g]] (let [g (or g identity)] (fn [e] (case (.-key e) "Enter" (do (go (f)) (.preventDefault e) e) e)))) (defn message-view [message] [:div.card.message message]) (defn email-view [] (let [email (cursor app-state [:params :email])] (fn [] [:span.card.email [:input {:type :string :id "email-view" :value @email :placeholder "Your email" :on-change (fn [e] (reset! email (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-email-view")) :tab-index 9}]]))) (defn client-email-view [] (let [client-email (cursor app-state [:params :client-email])] (fn [] [:span.card.client-email [:input {:type :string :id "client-email-view" :value @client-email :placeholder "Client's email" :on-change (fn [e] (reset! client-email (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "send-button-view")) :tab-index 10}]]))) (defn task-view [] (let [task (cursor app-state [:params :task])] (fn [] [:div.card.task [:input {:type :string :id "task-view" :value @task :placeholder "What did you work on?" :on-change (fn [e] (reset! task (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "hours-view")) :tab-index 5}]]))) (defn hours-view [] (let [hours (cursor app-state [:params :hours])] (fn [] [:div.card.hours [:input {:type :string :id "hours-view" :value @hours :placeholder "Number of units" :on-change (fn [e] (reset! hours (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "rate-view")) :tab-index 6}]]))) (defn rate-view [] (let [rate (cursor app-state [:params :rate])] (fn [] [:div.card.rate [:input {:type :string :id "rate-view" :value @rate :placeholder "Rate per unit" :on-change (fn [e] (reset! rate (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "number-view")) :tab-index 7}]]))) (defn company-view [] (let [company (cursor app-state [:params :company])] (fn [] [:div.card.company [:input {:type :string :id "company-view" :value @company :placeholder "Your company name" :on-change (fn [e] (reset! company (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "company-address-view")) :auto-focus true :tab-index 1}]]))) (defn company-address-view [] (let [company-address (cursor app-state [:params :company-address])] (fn [] [:div.card.company-address [:input {:type :string :id "company-address-view" :value @company-address :placeholder "Your company address" :on-change (fn [e] (reset! company-address (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-company-view")) :tab-index 2}]]))) (defn client-company-view [] (let [client-company (cursor app-state [:params :client-company])] (fn [] [:div.card.client-company [:input {:type :string :id "client-company-view" :value @client-company :placeholder "Client company name" :on-change (fn [e] (reset! client-company (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-company-address-view")) :tab-index 3}]]))) (defn client-company-address-view [] (let [client-company-address (cursor app-state [:params :client-company-address])] (fn [] [:div.card.client-company-address [:input {:type :string :id "client-company-address-view" :value @client-company-address :placeholder "Client company address" :on-change (fn [e] (reset! client-company-address (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "task-view")) :tab-index 4}]]))) (defn terms-view [] (let [terms (cursor app-state [:params :terms])] (fn [] [:div.card.terms [:textarea {:type :string :id "terms-view" :value (s/replace (str @terms) "<ENTER>" "\n") :on-change (fn [e] (reset! terms (s/replace (str (.. e -target -value)) "\n" "<ENTER>")) (write-cookie))}]]))) (defn number-view [] (let [number (cursor app-state [:params :number])] (fn [] [:input {:type :string :id "number-view" :value @number :on-change (fn [e] (reset! number (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "email-view")) :tab-index 8}]))) (defn send-invoice [verify message g-recaptcha-response] (go (reset! message "Sending your invoice...") (reset! verify false) (let [date (:date @app-state) params (->> (:params @app-state) (map (fn [[k v]] (let [k (-> k name (s/replace "-" "_") keyword)] [k v]))) (into {})) params (cond-> params date (assoc :date date)) {:keys [success body] :as response} (<! (http/post "/invoice" {:json-params params :query-params {:g-recaptcha-response g-recaptcha-response}}))] (<! (timeout 500)) (if success (reset! message "Done! Your invoice has been sent") (reset! message (str "\nResult: " body))) (<! (timeout 2000)) (reset! message nil)))) (defn ready-view [] (let [verify (cursor app-state [:verify]) message (atom nil)] (fn [] [:div.card.ready (when @message [:div @message]) (when @verify [:> js/ReactRecaptcha {:sitekey "6Lcmw00UAAAAAOOKJDoeVNEsVuJFJ6ka3dSbGaIV" :verifyCallback (fn [g-recaptcha-response] (send-invoice verify message (js->clj g-recaptcha-response)))}])]))) (defn send-button-view [] (let [verify (cursor app-state [:verify])] (fn [] [:button.send-button {:id "send-button-view" :on-click #(reset! verify true) :tab-index 11} "Send"]))) (defn send-view [] (let [verify (cursor app-state [:verify])] (fn [] (if-not @verify [:div [email-view] [client-email-view] [send-button-view]] [:div])))) (defn hello-world [] (let [hours (cursor app-state [:params :hours]) rate (cursor app-state [:params :rate]) date (cursor app-state [:date])] (fn [] (let [total (* (.parseFloat js/window @hours) (.parseFloat js/window @rate)) total (if (js/isNaN total) 0 (.toFixed total 2))] [:div [:form (for [[i component] (map-indexed vector (:messages @app-state))] (with-meta component {:key i}))] [:div.invoice {:style {:max-width "1024px"}} [:h1#title "INVOICE"] [:div#number "#" [number-view]] [:div#date [:span "Date: "] [datetime {:default-value (js/Date.) :time-format false :on-change #(reset! date (.format % "MMMM DD, YYYY")) :style {:display :inline} :date-format "MMMM DD, YYYY" :close-on-select true}]] [:div.balance [:span "Balance Due: "] [:span.value "$" total]] [:div#company [company-view] [company-address-view]] [:div "Bill to:"] [:div#client_company [client-company-view] [client-company-address-view]] [:table#items [:thead [:tr [:th [:div "Item"]] [:th [:div "Quantity"]] [:th [:div "Rate"]] [:th [:div "Amount"]]]] [:tbody [:tr [:td [task-view]] [:td [hours-view]] [:td [rate-view]] [:td [:span.value "$" total]]]]] [:div.balance [:span "Subtotal: "] [:span.value "$" total]] [:div.balance [:span "Total: "] [:span.value "$" total]] [:div "Terms:"] [terms-view]] [:div.send [send-view] [ready-view]]])))) (reagent/render-component [hello-world] (. js/document (getElementById "app")))
87545
(ns payme.core (:require [reagent.core :as reagent :refer [atom cursor]] [cljs.core.async :refer [go <! timeout]] [cljs-http.client :as http] [clojure.string :as s] [cljsjs.react-recaptcha] [reagent.cookies :as cookies] [goog.crypt.base64 :as b64] [goog.crypt :as cr] [rocks.clj.transit.core :as transit] [cljsjs.react-datetime]) (:require-macros [cljs.core.async :refer [go]])) (def datetime (reagent/adapt-react-class js/Datetime)) (enable-console-print!) (def app-state (atom {:messages [] :params (or (when-let [d (cookies/get "payme_invoice")] (transit/from-transit (cr/utf8ByteArrayToString (b64/decodeStringToByteArray d true)))) {})})) (defn write-cookie [] (cookies/set! "payme_invoice" (b64/encodeByteArray (cr/stringToUtf8ByteArray (transit/to-transit (:params @app-state))) true))) (defn focus-element [id] (.focus (.getElementById js/document id))) (defn on-enter [f & [g]] (let [g (or g identity)] (fn [e] (case (.-key e) "Enter" (do (go (f)) (.preventDefault e) e) e)))) (defn message-view [message] [:div.card.message message]) (defn email-view [] (let [email (cursor app-state [:params :email])] (fn [] [:span.card.email [:input {:type :string :id "email-view" :value @email :placeholder "Your email" :on-change (fn [e] (reset! email (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-email-view")) :tab-index 9}]]))) (defn client-email-view [] (let [client-email (cursor app-state [:params :client-email])] (fn [] [:span.card.client-email [:input {:type :string :id "client-email-view" :value @client-email :placeholder "Client's email" :on-change (fn [e] (reset! client-email (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "send-button-view")) :tab-index 10}]]))) (defn task-view [] (let [task (cursor app-state [:params :task])] (fn [] [:div.card.task [:input {:type :string :id "task-view" :value @task :placeholder "What did you work on?" :on-change (fn [e] (reset! task (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "hours-view")) :tab-index 5}]]))) (defn hours-view [] (let [hours (cursor app-state [:params :hours])] (fn [] [:div.card.hours [:input {:type :string :id "hours-view" :value @hours :placeholder "Number of units" :on-change (fn [e] (reset! hours (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "rate-view")) :tab-index 6}]]))) (defn rate-view [] (let [rate (cursor app-state [:params :rate])] (fn [] [:div.card.rate [:input {:type :string :id "rate-view" :value @rate :placeholder "Rate per unit" :on-change (fn [e] (reset! rate (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "number-view")) :tab-index 7}]]))) (defn company-view [] (let [company (cursor app-state [:params :company])] (fn [] [:div.card.company [:input {:type :string :id "company-view" :value @company :placeholder "Your company name" :on-change (fn [e] (reset! company (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "company-address-view")) :auto-focus true :tab-index 1}]]))) (defn company-address-view [] (let [company-address (cursor app-state [:params :company-address])] (fn [] [:div.card.company-address [:input {:type :string :id "company-address-view" :value @company-address :placeholder "Your company address" :on-change (fn [e] (reset! company-address (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-company-view")) :tab-index 2}]]))) (defn client-company-view [] (let [client-company (cursor app-state [:params :client-company])] (fn [] [:div.card.client-company [:input {:type :string :id "client-company-view" :value @client-company :placeholder "Client company name" :on-change (fn [e] (reset! client-company (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-company-address-view")) :tab-index 3}]]))) (defn client-company-address-view [] (let [client-company-address (cursor app-state [:params :client-company-address])] (fn [] [:div.card.client-company-address [:input {:type :string :id "client-company-address-view" :value @client-company-address :placeholder "Client company address" :on-change (fn [e] (reset! client-company-address (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "task-view")) :tab-index 4}]]))) (defn terms-view [] (let [terms (cursor app-state [:params :terms])] (fn [] [:div.card.terms [:textarea {:type :string :id "terms-view" :value (s/replace (str @terms) "<ENTER>" "\n") :on-change (fn [e] (reset! terms (s/replace (str (.. e -target -value)) "\n" "<ENTER>")) (write-cookie))}]]))) (defn number-view [] (let [number (cursor app-state [:params :number])] (fn [] [:input {:type :string :id "number-view" :value @number :on-change (fn [e] (reset! number (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "email-view")) :tab-index 8}]))) (defn send-invoice [verify message g-recaptcha-response] (go (reset! message "Sending your invoice...") (reset! verify false) (let [date (:date @app-state) params (->> (:params @app-state) (map (fn [[k v]] (let [k (-> k name (s/replace "-" "_") keyword)] [k v]))) (into {})) params (cond-> params date (assoc :date date)) {:keys [success body] :as response} (<! (http/post "/invoice" {:json-params params :query-params {:g-recaptcha-response g-recaptcha-response}}))] (<! (timeout 500)) (if success (reset! message "Done! Your invoice has been sent") (reset! message (str "\nResult: " body))) (<! (timeout 2000)) (reset! message nil)))) (defn ready-view [] (let [verify (cursor app-state [:verify]) message (atom nil)] (fn [] [:div.card.ready (when @message [:div @message]) (when @verify [:> js/ReactRecaptcha {:sitekey "<KEY>" :verifyCallback (fn [g-recaptcha-response] (send-invoice verify message (js->clj g-recaptcha-response)))}])]))) (defn send-button-view [] (let [verify (cursor app-state [:verify])] (fn [] [:button.send-button {:id "send-button-view" :on-click #(reset! verify true) :tab-index 11} "Send"]))) (defn send-view [] (let [verify (cursor app-state [:verify])] (fn [] (if-not @verify [:div [email-view] [client-email-view] [send-button-view]] [:div])))) (defn hello-world [] (let [hours (cursor app-state [:params :hours]) rate (cursor app-state [:params :rate]) date (cursor app-state [:date])] (fn [] (let [total (* (.parseFloat js/window @hours) (.parseFloat js/window @rate)) total (if (js/isNaN total) 0 (.toFixed total 2))] [:div [:form (for [[i component] (map-indexed vector (:messages @app-state))] (with-meta component {:key i}))] [:div.invoice {:style {:max-width "1024px"}} [:h1#title "INVOICE"] [:div#number "#" [number-view]] [:div#date [:span "Date: "] [datetime {:default-value (js/Date.) :time-format false :on-change #(reset! date (.format % "MMMM DD, YYYY")) :style {:display :inline} :date-format "MMMM DD, YYYY" :close-on-select true}]] [:div.balance [:span "Balance Due: "] [:span.value "$" total]] [:div#company [company-view] [company-address-view]] [:div "Bill to:"] [:div#client_company [client-company-view] [client-company-address-view]] [:table#items [:thead [:tr [:th [:div "Item"]] [:th [:div "Quantity"]] [:th [:div "Rate"]] [:th [:div "Amount"]]]] [:tbody [:tr [:td [task-view]] [:td [hours-view]] [:td [rate-view]] [:td [:span.value "$" total]]]]] [:div.balance [:span "Subtotal: "] [:span.value "$" total]] [:div.balance [:span "Total: "] [:span.value "$" total]] [:div "Terms:"] [terms-view]] [:div.send [send-view] [ready-view]]])))) (reagent/render-component [hello-world] (. js/document (getElementById "app")))
true
(ns payme.core (:require [reagent.core :as reagent :refer [atom cursor]] [cljs.core.async :refer [go <! timeout]] [cljs-http.client :as http] [clojure.string :as s] [cljsjs.react-recaptcha] [reagent.cookies :as cookies] [goog.crypt.base64 :as b64] [goog.crypt :as cr] [rocks.clj.transit.core :as transit] [cljsjs.react-datetime]) (:require-macros [cljs.core.async :refer [go]])) (def datetime (reagent/adapt-react-class js/Datetime)) (enable-console-print!) (def app-state (atom {:messages [] :params (or (when-let [d (cookies/get "payme_invoice")] (transit/from-transit (cr/utf8ByteArrayToString (b64/decodeStringToByteArray d true)))) {})})) (defn write-cookie [] (cookies/set! "payme_invoice" (b64/encodeByteArray (cr/stringToUtf8ByteArray (transit/to-transit (:params @app-state))) true))) (defn focus-element [id] (.focus (.getElementById js/document id))) (defn on-enter [f & [g]] (let [g (or g identity)] (fn [e] (case (.-key e) "Enter" (do (go (f)) (.preventDefault e) e) e)))) (defn message-view [message] [:div.card.message message]) (defn email-view [] (let [email (cursor app-state [:params :email])] (fn [] [:span.card.email [:input {:type :string :id "email-view" :value @email :placeholder "Your email" :on-change (fn [e] (reset! email (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-email-view")) :tab-index 9}]]))) (defn client-email-view [] (let [client-email (cursor app-state [:params :client-email])] (fn [] [:span.card.client-email [:input {:type :string :id "client-email-view" :value @client-email :placeholder "Client's email" :on-change (fn [e] (reset! client-email (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "send-button-view")) :tab-index 10}]]))) (defn task-view [] (let [task (cursor app-state [:params :task])] (fn [] [:div.card.task [:input {:type :string :id "task-view" :value @task :placeholder "What did you work on?" :on-change (fn [e] (reset! task (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "hours-view")) :tab-index 5}]]))) (defn hours-view [] (let [hours (cursor app-state [:params :hours])] (fn [] [:div.card.hours [:input {:type :string :id "hours-view" :value @hours :placeholder "Number of units" :on-change (fn [e] (reset! hours (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "rate-view")) :tab-index 6}]]))) (defn rate-view [] (let [rate (cursor app-state [:params :rate])] (fn [] [:div.card.rate [:input {:type :string :id "rate-view" :value @rate :placeholder "Rate per unit" :on-change (fn [e] (reset! rate (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "number-view")) :tab-index 7}]]))) (defn company-view [] (let [company (cursor app-state [:params :company])] (fn [] [:div.card.company [:input {:type :string :id "company-view" :value @company :placeholder "Your company name" :on-change (fn [e] (reset! company (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "company-address-view")) :auto-focus true :tab-index 1}]]))) (defn company-address-view [] (let [company-address (cursor app-state [:params :company-address])] (fn [] [:div.card.company-address [:input {:type :string :id "company-address-view" :value @company-address :placeholder "Your company address" :on-change (fn [e] (reset! company-address (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-company-view")) :tab-index 2}]]))) (defn client-company-view [] (let [client-company (cursor app-state [:params :client-company])] (fn [] [:div.card.client-company [:input {:type :string :id "client-company-view" :value @client-company :placeholder "Client company name" :on-change (fn [e] (reset! client-company (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "client-company-address-view")) :tab-index 3}]]))) (defn client-company-address-view [] (let [client-company-address (cursor app-state [:params :client-company-address])] (fn [] [:div.card.client-company-address [:input {:type :string :id "client-company-address-view" :value @client-company-address :placeholder "Client company address" :on-change (fn [e] (reset! client-company-address (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "task-view")) :tab-index 4}]]))) (defn terms-view [] (let [terms (cursor app-state [:params :terms])] (fn [] [:div.card.terms [:textarea {:type :string :id "terms-view" :value (s/replace (str @terms) "<ENTER>" "\n") :on-change (fn [e] (reset! terms (s/replace (str (.. e -target -value)) "\n" "<ENTER>")) (write-cookie))}]]))) (defn number-view [] (let [number (cursor app-state [:params :number])] (fn [] [:input {:type :string :id "number-view" :value @number :on-change (fn [e] (reset! number (.. e -target -value)) (write-cookie)) :on-key-press (on-enter #(focus-element "email-view")) :tab-index 8}]))) (defn send-invoice [verify message g-recaptcha-response] (go (reset! message "Sending your invoice...") (reset! verify false) (let [date (:date @app-state) params (->> (:params @app-state) (map (fn [[k v]] (let [k (-> k name (s/replace "-" "_") keyword)] [k v]))) (into {})) params (cond-> params date (assoc :date date)) {:keys [success body] :as response} (<! (http/post "/invoice" {:json-params params :query-params {:g-recaptcha-response g-recaptcha-response}}))] (<! (timeout 500)) (if success (reset! message "Done! Your invoice has been sent") (reset! message (str "\nResult: " body))) (<! (timeout 2000)) (reset! message nil)))) (defn ready-view [] (let [verify (cursor app-state [:verify]) message (atom nil)] (fn [] [:div.card.ready (when @message [:div @message]) (when @verify [:> js/ReactRecaptcha {:sitekey "PI:KEY:<KEY>END_PI" :verifyCallback (fn [g-recaptcha-response] (send-invoice verify message (js->clj g-recaptcha-response)))}])]))) (defn send-button-view [] (let [verify (cursor app-state [:verify])] (fn [] [:button.send-button {:id "send-button-view" :on-click #(reset! verify true) :tab-index 11} "Send"]))) (defn send-view [] (let [verify (cursor app-state [:verify])] (fn [] (if-not @verify [:div [email-view] [client-email-view] [send-button-view]] [:div])))) (defn hello-world [] (let [hours (cursor app-state [:params :hours]) rate (cursor app-state [:params :rate]) date (cursor app-state [:date])] (fn [] (let [total (* (.parseFloat js/window @hours) (.parseFloat js/window @rate)) total (if (js/isNaN total) 0 (.toFixed total 2))] [:div [:form (for [[i component] (map-indexed vector (:messages @app-state))] (with-meta component {:key i}))] [:div.invoice {:style {:max-width "1024px"}} [:h1#title "INVOICE"] [:div#number "#" [number-view]] [:div#date [:span "Date: "] [datetime {:default-value (js/Date.) :time-format false :on-change #(reset! date (.format % "MMMM DD, YYYY")) :style {:display :inline} :date-format "MMMM DD, YYYY" :close-on-select true}]] [:div.balance [:span "Balance Due: "] [:span.value "$" total]] [:div#company [company-view] [company-address-view]] [:div "Bill to:"] [:div#client_company [client-company-view] [client-company-address-view]] [:table#items [:thead [:tr [:th [:div "Item"]] [:th [:div "Quantity"]] [:th [:div "Rate"]] [:th [:div "Amount"]]]] [:tbody [:tr [:td [task-view]] [:td [hours-view]] [:td [rate-view]] [:td [:span.value "$" total]]]]] [:div.balance [:span "Subtotal: "] [:span.value "$" total]] [:div.balance [:span "Total: "] [:span.value "$" total]] [:div "Terms:"] [terms-view]] [:div.send [send-view] [ready-view]]])))) (reagent/render-component [hello-world] (. js/document (getElementById "app")))
[ { "context": "go crazy when I hear a cymbal\")\n\n(def cipher-key \"ICE\")\n\n(def ciphertext (apply str (u/hexstr->str \"0b3", "end": 260, "score": 0.9866009950637817, "start": 257, "tag": "KEY", "value": "ICE" }, { "context": "ICE\")\n\n(def ciphertext (apply str (u/hexstr->str \"0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f\")))\n\n\n(defn encrypt'\n [data key]\n (apply str (m", "end": 455, "score": 0.9992533326148987, "start": 307, "tag": "KEY", "value": "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f" } ]
test/set1/repeating_xor_test.clj
milapsheth/Crypto-Challenges
3
(ns set1.repeating-xor-test (:require [clojure.test :refer :all] [set1.repeating-xor :refer :all] [util.tools :as u])) (def plaintext "Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal") (def cipher-key "ICE") (def ciphertext (apply str (u/hexstr->str "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"))) (defn encrypt' [data key] (apply str (map char (encrypt (map int data) (map int key))))) (deftest repeating-xor-test (testing "Didn't encrypt well" (is (= ciphertext (encrypt' plaintext cipher-key)))))
34096
(ns set1.repeating-xor-test (:require [clojure.test :refer :all] [set1.repeating-xor :refer :all] [util.tools :as u])) (def plaintext "Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal") (def cipher-key "<KEY>") (def ciphertext (apply str (u/hexstr->str "<KEY>"))) (defn encrypt' [data key] (apply str (map char (encrypt (map int data) (map int key))))) (deftest repeating-xor-test (testing "Didn't encrypt well" (is (= ciphertext (encrypt' plaintext cipher-key)))))
true
(ns set1.repeating-xor-test (:require [clojure.test :refer :all] [set1.repeating-xor :refer :all] [util.tools :as u])) (def plaintext "Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal") (def cipher-key "PI:KEY:<KEY>END_PI") (def ciphertext (apply str (u/hexstr->str "PI:KEY:<KEY>END_PI"))) (defn encrypt' [data key] (apply str (map char (encrypt (map int data) (map int key))))) (deftest repeating-xor-test (testing "Didn't encrypt well" (is (= ciphertext (encrypt' plaintext cipher-key)))))
[ { "context": "ith-hystrix {:group-key \"bar\"\n :com", "end": 3418, "score": 0.5654412508010864, "start": 3415, "tag": "KEY", "value": "bar" }, { "context": " :command-key \"bar\"\n :thr", "end": 3504, "score": 0.5638812780380249, "start": 3501, "tag": "KEY", "value": "bar" }, { "context": " :thread-pool-key \"bar\"\n :thr", "end": 3590, "score": 0.5255813002586365, "start": 3587, "tag": "KEY", "value": "bar" } ]
test/bulwark/core_test.clj
gojektech/bulwark
11
(ns bulwark.core-test (:require [clojure.test :refer :all] [bulwark.core :as bulwark] [clojure.stacktrace :as stacktrace]) (:import (com.netflix.hystrix.exception HystrixRuntimeException) (org.slf4j MDC))) (defmacro catch-and-return [& body] `(try ~@body (catch Exception e# e#))) (deftest with-hystrix-works (testing "Successful call" (let [fallback (fn [_] "failure") result (bulwark/with-hystrix {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} "success")] (is (= "success" result)))) (testing "Successful call without a fallback" (let [result (bulwark/with-hystrix {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} "success")] (is (= "success" result)))) (testing "Fallback when exception is thrown" (let [fallback (fn [{:keys [failed-execution-exception]}] {:status "failure" :exception failed-execution-exception}) result (bulwark/with-hystrix {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (throw (ex-info "foo" {:error "foo"})) "success")] (is (= "failure" (:status result))) (is (= {:error "foo"} (-> result :exception ex-data))))) (testing "When an exception is thrown without a fallback" (let [exception (catch-and-return (bulwark/with-hystrix {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (throw (ex-info "foo" {:error "foo"})) "success"))] (is (= {:error "foo"} (-> exception stacktrace/root-cause ex-data))))) (testing "Fallback when body times out" (let [fallback (fn [{:keys [response-timed-out?]}] {:status "failure" :response-timed-out? response-timed-out?}) result (bulwark/with-hystrix {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (Thread/sleep 200) "success")] (is (= {:status "failure" :response-timed-out? true} result)))) (testing "When body times out without a fallback" (is (thrown-with-msg? HystrixRuntimeException #"goo timed-out.*" (bulwark/with-hystrix {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (Thread/sleep 200) "success"))))) (deftest with-hystrix-queue-works (testing "Successful call" (let [fallback (fn [_] "failure") result (bulwark/with-hystrix-async {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} {:status "success" :response "success"})] (is (= @result {:status "success" :response "success"})))) (testing "Successful call without a fallback" (let [result (bulwark/with-hystrix-async {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} {:status "success" :response "success"})] (is (= @result {:status "success" :response "success"})))) (testing "Fallback when exception is thrown" (let [fallback (fn [{:keys [failed-execution-exception]}] {:status "failure" :response failed-execution-exception}) result (bulwark/with-hystrix-async {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (throw (ex-info "foo" {:error "foo"})) "success")] (is (= "failure" (:status @result))) (is (= {:error "foo"} (ex-data (:response @result)))))) (testing "When an exception is thrown without a fallback" (let [exception (try @(bulwark/with-hystrix-async {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (throw (ex-info "foo" {:error "foo"})) "success") (catch Exception e e))] (is (= {:error "foo"} (-> exception stacktrace/root-cause ex-data))))) (testing "Fallback when body times out" (let [fallback (fn [{:keys [response-timed-out?]}] {:status "failure" :response-timed-out? response-timed-out?}) result (bulwark/with-hystrix-async {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (Thread/sleep 200) "success")] (is (= {:status "failure" :response-timed-out? true} @result)))) (testing "When body times out without a fallback" (let [exception (catch-and-return @(bulwark/with-hystrix-async {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (Thread/sleep 200) "success"))] (is (instance? HystrixRuntimeException (.getCause exception))) (is (re-matches #"goo timed-out.*" (-> exception (.getCause) (.getMessage))))))) (defn with-mdc [f] (MDC/setContextMap {"a" "1"}) (is (= "1" (MDC/get "a"))) (try (f) (finally (MDC/clear)))) (use-fixtures :once with-mdc) (deftest test-fallback-function (testing "should not clear MDC if running on same thread" (let [main-thread (.getName (Thread/currentThread)) fallback-fn (bulwark/capture-logging-context (fn [] (let [fallback-thread (.getName (Thread/currentThread))] (is (= main-thread fallback-thread)))))] (fallback-fn)) (is (= "1" (MDC/get "a")))) (testing "should clear MDC if fallback is running on different thread" (let [main-thread (.getName (Thread/currentThread)) fallback-fn (bulwark/capture-logging-context (fn [] (let [fallback-thread (.getName (Thread/currentThread))] (is (not= main-thread fallback-thread))))) agnt (agent {})] (send-off agnt (fn [state] (fallback-fn) (is (nil? (MDC/get "a"))) (assoc state :done true))) (await agnt))) (is (= "1" (MDC/get "a"))))
121386
(ns bulwark.core-test (:require [clojure.test :refer :all] [bulwark.core :as bulwark] [clojure.stacktrace :as stacktrace]) (:import (com.netflix.hystrix.exception HystrixRuntimeException) (org.slf4j MDC))) (defmacro catch-and-return [& body] `(try ~@body (catch Exception e# e#))) (deftest with-hystrix-works (testing "Successful call" (let [fallback (fn [_] "failure") result (bulwark/with-hystrix {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} "success")] (is (= "success" result)))) (testing "Successful call without a fallback" (let [result (bulwark/with-hystrix {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} "success")] (is (= "success" result)))) (testing "Fallback when exception is thrown" (let [fallback (fn [{:keys [failed-execution-exception]}] {:status "failure" :exception failed-execution-exception}) result (bulwark/with-hystrix {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (throw (ex-info "foo" {:error "foo"})) "success")] (is (= "failure" (:status result))) (is (= {:error "foo"} (-> result :exception ex-data))))) (testing "When an exception is thrown without a fallback" (let [exception (catch-and-return (bulwark/with-hystrix {:group-key "<KEY>" :command-key "<KEY>" :thread-pool-key "<KEY>" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (throw (ex-info "foo" {:error "foo"})) "success"))] (is (= {:error "foo"} (-> exception stacktrace/root-cause ex-data))))) (testing "Fallback when body times out" (let [fallback (fn [{:keys [response-timed-out?]}] {:status "failure" :response-timed-out? response-timed-out?}) result (bulwark/with-hystrix {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (Thread/sleep 200) "success")] (is (= {:status "failure" :response-timed-out? true} result)))) (testing "When body times out without a fallback" (is (thrown-with-msg? HystrixRuntimeException #"goo timed-out.*" (bulwark/with-hystrix {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (Thread/sleep 200) "success"))))) (deftest with-hystrix-queue-works (testing "Successful call" (let [fallback (fn [_] "failure") result (bulwark/with-hystrix-async {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} {:status "success" :response "success"})] (is (= @result {:status "success" :response "success"})))) (testing "Successful call without a fallback" (let [result (bulwark/with-hystrix-async {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} {:status "success" :response "success"})] (is (= @result {:status "success" :response "success"})))) (testing "Fallback when exception is thrown" (let [fallback (fn [{:keys [failed-execution-exception]}] {:status "failure" :response failed-execution-exception}) result (bulwark/with-hystrix-async {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (throw (ex-info "foo" {:error "foo"})) "success")] (is (= "failure" (:status @result))) (is (= {:error "foo"} (ex-data (:response @result)))))) (testing "When an exception is thrown without a fallback" (let [exception (try @(bulwark/with-hystrix-async {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (throw (ex-info "foo" {:error "foo"})) "success") (catch Exception e e))] (is (= {:error "foo"} (-> exception stacktrace/root-cause ex-data))))) (testing "Fallback when body times out" (let [fallback (fn [{:keys [response-timed-out?]}] {:status "failure" :response-timed-out? response-timed-out?}) result (bulwark/with-hystrix-async {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (Thread/sleep 200) "success")] (is (= {:status "failure" :response-timed-out? true} @result)))) (testing "When body times out without a fallback" (let [exception (catch-and-return @(bulwark/with-hystrix-async {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (Thread/sleep 200) "success"))] (is (instance? HystrixRuntimeException (.getCause exception))) (is (re-matches #"goo timed-out.*" (-> exception (.getCause) (.getMessage))))))) (defn with-mdc [f] (MDC/setContextMap {"a" "1"}) (is (= "1" (MDC/get "a"))) (try (f) (finally (MDC/clear)))) (use-fixtures :once with-mdc) (deftest test-fallback-function (testing "should not clear MDC if running on same thread" (let [main-thread (.getName (Thread/currentThread)) fallback-fn (bulwark/capture-logging-context (fn [] (let [fallback-thread (.getName (Thread/currentThread))] (is (= main-thread fallback-thread)))))] (fallback-fn)) (is (= "1" (MDC/get "a")))) (testing "should clear MDC if fallback is running on different thread" (let [main-thread (.getName (Thread/currentThread)) fallback-fn (bulwark/capture-logging-context (fn [] (let [fallback-thread (.getName (Thread/currentThread))] (is (not= main-thread fallback-thread))))) agnt (agent {})] (send-off agnt (fn [state] (fallback-fn) (is (nil? (MDC/get "a"))) (assoc state :done true))) (await agnt))) (is (= "1" (MDC/get "a"))))
true
(ns bulwark.core-test (:require [clojure.test :refer :all] [bulwark.core :as bulwark] [clojure.stacktrace :as stacktrace]) (:import (com.netflix.hystrix.exception HystrixRuntimeException) (org.slf4j MDC))) (defmacro catch-and-return [& body] `(try ~@body (catch Exception e# e#))) (deftest with-hystrix-works (testing "Successful call" (let [fallback (fn [_] "failure") result (bulwark/with-hystrix {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} "success")] (is (= "success" result)))) (testing "Successful call without a fallback" (let [result (bulwark/with-hystrix {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} "success")] (is (= "success" result)))) (testing "Fallback when exception is thrown" (let [fallback (fn [{:keys [failed-execution-exception]}] {:status "failure" :exception failed-execution-exception}) result (bulwark/with-hystrix {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (throw (ex-info "foo" {:error "foo"})) "success")] (is (= "failure" (:status result))) (is (= {:error "foo"} (-> result :exception ex-data))))) (testing "When an exception is thrown without a fallback" (let [exception (catch-and-return (bulwark/with-hystrix {:group-key "PI:KEY:<KEY>END_PI" :command-key "PI:KEY:<KEY>END_PI" :thread-pool-key "PI:KEY:<KEY>END_PI" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (throw (ex-info "foo" {:error "foo"})) "success"))] (is (= {:error "foo"} (-> exception stacktrace/root-cause ex-data))))) (testing "Fallback when body times out" (let [fallback (fn [{:keys [response-timed-out?]}] {:status "failure" :response-timed-out? response-timed-out?}) result (bulwark/with-hystrix {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (Thread/sleep 200) "success")] (is (= {:status "failure" :response-timed-out? true} result)))) (testing "When body times out without a fallback" (is (thrown-with-msg? HystrixRuntimeException #"goo timed-out.*" (bulwark/with-hystrix {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (Thread/sleep 200) "success"))))) (deftest with-hystrix-queue-works (testing "Successful call" (let [fallback (fn [_] "failure") result (bulwark/with-hystrix-async {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} {:status "success" :response "success"})] (is (= @result {:status "success" :response "success"})))) (testing "Successful call without a fallback" (let [result (bulwark/with-hystrix-async {:group-key "foo" :command-key "foo" :thread-pool-key "foo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} {:status "success" :response "success"})] (is (= @result {:status "success" :response "success"})))) (testing "Fallback when exception is thrown" (let [fallback (fn [{:keys [failed-execution-exception]}] {:status "failure" :response failed-execution-exception}) result (bulwark/with-hystrix-async {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (throw (ex-info "foo" {:error "foo"})) "success")] (is (= "failure" (:status @result))) (is (= {:error "foo"} (ex-data (:response @result)))))) (testing "When an exception is thrown without a fallback" (let [exception (try @(bulwark/with-hystrix-async {:group-key "bar" :command-key "bar" :thread-pool-key "bar" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (throw (ex-info "foo" {:error "foo"})) "success") (catch Exception e e))] (is (= {:error "foo"} (-> exception stacktrace/root-cause ex-data))))) (testing "Fallback when body times out" (let [fallback (fn [{:keys [response-timed-out?]}] {:status "failure" :response-timed-out? response-timed-out?}) result (bulwark/with-hystrix-async {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100 :fallback-fn fallback} (Thread/sleep 200) "success")] (is (= {:status "failure" :response-timed-out? true} @result)))) (testing "When body times out without a fallback" (let [exception (catch-and-return @(bulwark/with-hystrix-async {:group-key "goo" :command-key "goo" :thread-pool-key "goo" :thread-count 2 :breaker-sleep-window-ms 500 :breaker-request-volume-threshold 20 :breaker-error-threshold-percentage 20 :execution-timeout-ms 100} (Thread/sleep 200) "success"))] (is (instance? HystrixRuntimeException (.getCause exception))) (is (re-matches #"goo timed-out.*" (-> exception (.getCause) (.getMessage))))))) (defn with-mdc [f] (MDC/setContextMap {"a" "1"}) (is (= "1" (MDC/get "a"))) (try (f) (finally (MDC/clear)))) (use-fixtures :once with-mdc) (deftest test-fallback-function (testing "should not clear MDC if running on same thread" (let [main-thread (.getName (Thread/currentThread)) fallback-fn (bulwark/capture-logging-context (fn [] (let [fallback-thread (.getName (Thread/currentThread))] (is (= main-thread fallback-thread)))))] (fallback-fn)) (is (= "1" (MDC/get "a")))) (testing "should clear MDC if fallback is running on different thread" (let [main-thread (.getName (Thread/currentThread)) fallback-fn (bulwark/capture-logging-context (fn [] (let [fallback-thread (.getName (Thread/currentThread))] (is (not= main-thread fallback-thread))))) agnt (agent {})] (send-off agnt (fn [state] (fallback-fn) (is (nil? (MDC/get "a"))) (assoc state :done true))) (await agnt))) (is (= "1" (MDC/get "a"))))
[ { "context": " (testing \"stealth\"\n (is (= {:docs [{:author \"juxt\"}\n {:author \"renewdoit\"}]}\n ", "end": 2765, "score": 0.8582171201705933, "start": 2762, "tag": "USERNAME", "value": "uxt" }, { "context": "cs [{:author \"juxt\"}\n {:author \"renewdoit\"}]}\n (pull {:docs [{:author \"juxt\" :pas", "end": 2806, "score": 0.9979721903800964, "start": 2797, "tag": "USERNAME", "value": "renewdoit" }, { "context": "\"renewdoit\"}]}\n (pull {:docs [{:author \"juxt\" :password \"secret\"} {:author \"renewdoit\"}]}\n ", "end": 2850, "score": 0.9789610505104065, "start": 2846, "tag": "USERNAME", "value": "juxt" }, { "context": " (pull {:docs [{:author \"juxt\" :password \"secret\"} {:author \"renewdoit\"}]}\n [{:doc", "end": 2869, "score": 0.9987040162086487, "start": 2863, "tag": "PASSWORD", "value": "secret" }, { "context": "cs [{:author \"juxt\" :password \"secret\"} {:author \"renewdoit\"}]}\n [{:docs [:author :password]}", "end": 2891, "score": 0.9986631274223328, "start": 2882, "tag": "USERNAME", "value": "renewdoit" } ]
test/juxt/pull/core_test.clj
juxt/pull
94
;; Copyright © 2016, JUXT LTD. (ns juxt.pull.core-test (:require [clojure.test :refer :all] [juxt.pull.core :refer :all] [juxt.pull.spec] [orchestra.spec.test :as stest])) (use-fixtures :once (fn [f] (stest/instrument) (f) (stest/unstrument))) (deftest pull-test (let [data {:name "pull" :routes {:main ["/" :abc] :other ["/" :def]} :vhosts {"http://localhost:8080" ^:ref [:routes :main] "https://localhost:8443" ^:ref [:routes :main] "https://localhost:8000" ^:ref [:routes :other]} :server {:port 8080 :vhosts [^:ref [:vhosts "http://localhost:8080"]]}}] (testing "attributes" (is (= {:name "pull"} (pull data [:name])))) (testing "denormalization" (is (= {:server {:port 8080, :vhosts [["/" :abc]]}} (pull data [:server])))) (testing "Specify :no-ref option should not lookup ref" (is (= {:server {:port 8080, :vhosts [[:vhosts "http://localhost:8080"]]}} (pull data [:server] {:no-ref? true})))) (testing "maps" (is (= {:vhosts {"http://localhost:8080" ["/" :abc]}} (pull data [{:vhosts ["http://localhost:8080"]}])))) (testing "wildcard" (is (= 3 (count (:vhosts (pull data [{:vhosts ['*]}])))))))) (deftest sequential-map-attributes-test (testing "from many attributes" (is (= {:docs [{:name "hello"} {:name "ok"}]} (pull {:docs [{:name "hello"} {:name "ok"}]} [{:docs [:name]}]))))) (deftest no-wildcard?-option-test (testing "no-wildcard? will not pull any attributes" (is (= {:name "pull" :docs [{} {}]} (pull {:name "pull" :docs [{:name "ok"} {:name "hello"}]} [:name {:docs '[*]}] {:no-wildcard? true})))) (testing "for plain map attributes, no-wildcard? also prevent their pulling" (is (= {:docs [{} {}]} (pull {:docs [{:name "ok"} {:name "hello"}]} [:docs] {:no-wildcard? true}))))) (deftest shadow-attributes-test (testing "shadow attributes" (is (= {:docs [{:name-len 5} {:name-len 2}]} (pull {:docs [{:name "smart"} {:name "ok"}]} [{:docs [:name-len]}] {:shadow {:name-len #(count (:name %))}})))) (testing "deep shadow attributes" (is (= {:tags [{:name "foo"} {:name "bar"}]} (pull {} [{:tags [:name]}] {:shadow {:tags (fn [_] [{:name "foo" :value "none"} {:name "bar"}])}}))))) (deftest stealth-attibutes-test (testing "stealth" (is (= {:docs [{:author "juxt"} {:author "renewdoit"}]} (pull {:docs [{:author "juxt" :password "secret"} {:author "renewdoit"}]} [{:docs [:author :password]}] {:stealth #{:password}}))))) (deftest pull-in-set (testing "Set value can also be pulled" (is (= {:docs [{:author "bar"} {:author "foo"}]} (pull {:docs #{{:author "foo"} {:author "bar"}}} [{:docs [:author]}]))))) (deftest pull-datomic-entity (testing "Datomic's Entity are also supported" (let [entity (fn [m] (reify datomic.Entity (keySet [_] (.keySet m)) (get [_ k] (.get m k)))) ent {:docs [(entity {:author "foo"}) (entity {:author :bar})]}] (is (= {:docs [{:author "foo"} {:author :bar}]} (pull ent [{:docs [:author]}])))))) (deftest pull-on-nil-values (testing "For nil valued attribute should pulled as nil" (is (= {:a nil} (pull {:a nil} [:a :b]))))) (deftest pull-on-nil (testing "Pull on nil just returns nil" (is (nil? (pull nil [:a]))))) (deftest pull-not-add-nil-key (testing "Pull on map collections should not add nil key" (is (= {:a 1 :c [{:type :wuxing :amount 100} {:type :seed :seed {:id "111"}}]} (pull {:a 1 :c [{:type :wuxing :amount 100} {:type :seed :seed {:id "111"}}]} [:a {:c [:type :amount {:seed [:id]}]}])))))
52630
;; Copyright © 2016, JUXT LTD. (ns juxt.pull.core-test (:require [clojure.test :refer :all] [juxt.pull.core :refer :all] [juxt.pull.spec] [orchestra.spec.test :as stest])) (use-fixtures :once (fn [f] (stest/instrument) (f) (stest/unstrument))) (deftest pull-test (let [data {:name "pull" :routes {:main ["/" :abc] :other ["/" :def]} :vhosts {"http://localhost:8080" ^:ref [:routes :main] "https://localhost:8443" ^:ref [:routes :main] "https://localhost:8000" ^:ref [:routes :other]} :server {:port 8080 :vhosts [^:ref [:vhosts "http://localhost:8080"]]}}] (testing "attributes" (is (= {:name "pull"} (pull data [:name])))) (testing "denormalization" (is (= {:server {:port 8080, :vhosts [["/" :abc]]}} (pull data [:server])))) (testing "Specify :no-ref option should not lookup ref" (is (= {:server {:port 8080, :vhosts [[:vhosts "http://localhost:8080"]]}} (pull data [:server] {:no-ref? true})))) (testing "maps" (is (= {:vhosts {"http://localhost:8080" ["/" :abc]}} (pull data [{:vhosts ["http://localhost:8080"]}])))) (testing "wildcard" (is (= 3 (count (:vhosts (pull data [{:vhosts ['*]}])))))))) (deftest sequential-map-attributes-test (testing "from many attributes" (is (= {:docs [{:name "hello"} {:name "ok"}]} (pull {:docs [{:name "hello"} {:name "ok"}]} [{:docs [:name]}]))))) (deftest no-wildcard?-option-test (testing "no-wildcard? will not pull any attributes" (is (= {:name "pull" :docs [{} {}]} (pull {:name "pull" :docs [{:name "ok"} {:name "hello"}]} [:name {:docs '[*]}] {:no-wildcard? true})))) (testing "for plain map attributes, no-wildcard? also prevent their pulling" (is (= {:docs [{} {}]} (pull {:docs [{:name "ok"} {:name "hello"}]} [:docs] {:no-wildcard? true}))))) (deftest shadow-attributes-test (testing "shadow attributes" (is (= {:docs [{:name-len 5} {:name-len 2}]} (pull {:docs [{:name "smart"} {:name "ok"}]} [{:docs [:name-len]}] {:shadow {:name-len #(count (:name %))}})))) (testing "deep shadow attributes" (is (= {:tags [{:name "foo"} {:name "bar"}]} (pull {} [{:tags [:name]}] {:shadow {:tags (fn [_] [{:name "foo" :value "none"} {:name "bar"}])}}))))) (deftest stealth-attibutes-test (testing "stealth" (is (= {:docs [{:author "juxt"} {:author "renewdoit"}]} (pull {:docs [{:author "juxt" :password "<PASSWORD>"} {:author "renewdoit"}]} [{:docs [:author :password]}] {:stealth #{:password}}))))) (deftest pull-in-set (testing "Set value can also be pulled" (is (= {:docs [{:author "bar"} {:author "foo"}]} (pull {:docs #{{:author "foo"} {:author "bar"}}} [{:docs [:author]}]))))) (deftest pull-datomic-entity (testing "Datomic's Entity are also supported" (let [entity (fn [m] (reify datomic.Entity (keySet [_] (.keySet m)) (get [_ k] (.get m k)))) ent {:docs [(entity {:author "foo"}) (entity {:author :bar})]}] (is (= {:docs [{:author "foo"} {:author :bar}]} (pull ent [{:docs [:author]}])))))) (deftest pull-on-nil-values (testing "For nil valued attribute should pulled as nil" (is (= {:a nil} (pull {:a nil} [:a :b]))))) (deftest pull-on-nil (testing "Pull on nil just returns nil" (is (nil? (pull nil [:a]))))) (deftest pull-not-add-nil-key (testing "Pull on map collections should not add nil key" (is (= {:a 1 :c [{:type :wuxing :amount 100} {:type :seed :seed {:id "111"}}]} (pull {:a 1 :c [{:type :wuxing :amount 100} {:type :seed :seed {:id "111"}}]} [:a {:c [:type :amount {:seed [:id]}]}])))))
true
;; Copyright © 2016, JUXT LTD. (ns juxt.pull.core-test (:require [clojure.test :refer :all] [juxt.pull.core :refer :all] [juxt.pull.spec] [orchestra.spec.test :as stest])) (use-fixtures :once (fn [f] (stest/instrument) (f) (stest/unstrument))) (deftest pull-test (let [data {:name "pull" :routes {:main ["/" :abc] :other ["/" :def]} :vhosts {"http://localhost:8080" ^:ref [:routes :main] "https://localhost:8443" ^:ref [:routes :main] "https://localhost:8000" ^:ref [:routes :other]} :server {:port 8080 :vhosts [^:ref [:vhosts "http://localhost:8080"]]}}] (testing "attributes" (is (= {:name "pull"} (pull data [:name])))) (testing "denormalization" (is (= {:server {:port 8080, :vhosts [["/" :abc]]}} (pull data [:server])))) (testing "Specify :no-ref option should not lookup ref" (is (= {:server {:port 8080, :vhosts [[:vhosts "http://localhost:8080"]]}} (pull data [:server] {:no-ref? true})))) (testing "maps" (is (= {:vhosts {"http://localhost:8080" ["/" :abc]}} (pull data [{:vhosts ["http://localhost:8080"]}])))) (testing "wildcard" (is (= 3 (count (:vhosts (pull data [{:vhosts ['*]}])))))))) (deftest sequential-map-attributes-test (testing "from many attributes" (is (= {:docs [{:name "hello"} {:name "ok"}]} (pull {:docs [{:name "hello"} {:name "ok"}]} [{:docs [:name]}]))))) (deftest no-wildcard?-option-test (testing "no-wildcard? will not pull any attributes" (is (= {:name "pull" :docs [{} {}]} (pull {:name "pull" :docs [{:name "ok"} {:name "hello"}]} [:name {:docs '[*]}] {:no-wildcard? true})))) (testing "for plain map attributes, no-wildcard? also prevent their pulling" (is (= {:docs [{} {}]} (pull {:docs [{:name "ok"} {:name "hello"}]} [:docs] {:no-wildcard? true}))))) (deftest shadow-attributes-test (testing "shadow attributes" (is (= {:docs [{:name-len 5} {:name-len 2}]} (pull {:docs [{:name "smart"} {:name "ok"}]} [{:docs [:name-len]}] {:shadow {:name-len #(count (:name %))}})))) (testing "deep shadow attributes" (is (= {:tags [{:name "foo"} {:name "bar"}]} (pull {} [{:tags [:name]}] {:shadow {:tags (fn [_] [{:name "foo" :value "none"} {:name "bar"}])}}))))) (deftest stealth-attibutes-test (testing "stealth" (is (= {:docs [{:author "juxt"} {:author "renewdoit"}]} (pull {:docs [{:author "juxt" :password "PI:PASSWORD:<PASSWORD>END_PI"} {:author "renewdoit"}]} [{:docs [:author :password]}] {:stealth #{:password}}))))) (deftest pull-in-set (testing "Set value can also be pulled" (is (= {:docs [{:author "bar"} {:author "foo"}]} (pull {:docs #{{:author "foo"} {:author "bar"}}} [{:docs [:author]}]))))) (deftest pull-datomic-entity (testing "Datomic's Entity are also supported" (let [entity (fn [m] (reify datomic.Entity (keySet [_] (.keySet m)) (get [_ k] (.get m k)))) ent {:docs [(entity {:author "foo"}) (entity {:author :bar})]}] (is (= {:docs [{:author "foo"} {:author :bar}]} (pull ent [{:docs [:author]}])))))) (deftest pull-on-nil-values (testing "For nil valued attribute should pulled as nil" (is (= {:a nil} (pull {:a nil} [:a :b]))))) (deftest pull-on-nil (testing "Pull on nil just returns nil" (is (nil? (pull nil [:a]))))) (deftest pull-not-add-nil-key (testing "Pull on map collections should not add nil key" (is (= {:a 1 :c [{:type :wuxing :amount 100} {:type :seed :seed {:id "111"}}]} (pull {:a 1 :c [{:type :wuxing :amount 100} {:type :seed :seed {:id "111"}}]} [:a {:c [:type :amount {:seed [:id]}]}])))))
[ { "context": "n-reflection* true)\n\n\n; sente https://github.com/ptaoussanis/sente/blob/master/example-project/src/example/ser", "end": 989, "score": 0.9996048808097839, "start": 978, "tag": "USERNAME", "value": "ptaoussanis" }, { "context": "servers (:servers state)})\n\n\n; https://github.com/ptaoussanis/sente/blob/master/src/taoensso/sente.cljc#L240-L2", "end": 2378, "score": 0.997368574142456, "start": 2367, "tag": "USERNAME", "value": "ptaoussanis" }, { "context": " (:username login))\n password (or password\n (:password login))\n ", "end": 7532, "score": 0.5946518778800964, "start": 7524, "tag": "PASSWORD", "value": "password" }, { "context": "rl\n :username username})]\n (event/connect state-atom {:server [se", "end": 7694, "score": 0.9977750182151794, "start": 7686, "tag": "USERNAME", "value": "username" }, { "context": "r-key\n :password password\n :username user", "end": 7890, "score": 0.9990155696868896, "start": 7882, "tag": "PASSWORD", "value": "password" }, { "context": "sword\n :username username})))\n (defmethod -event-msg-handler\n :skyl", "end": 7944, "score": 0.9987014532089233, "start": 7936, "tag": "USERNAME", "value": "username" }, { "context": " :uri (:uri request)}})\n\n\n; https://github.com/ring-clojure/ring/pull/447/files\n(defn- connection-content-len", "end": 14417, "score": 0.9995519518852234, "start": 14405, "tag": "USERNAME", "value": "ring-clojure" } ]
graal/clj/skylobby/server_stub.clj
badosu/skylobby
7
(ns skylobby.server-stub (:require [clojure.edn :as edn] [clojure.java.io :as io] [clojure.spec.alpha :as s] [hiccup.core :as hiccup] [muuntaja.core :as m] org.httpkit.server [reitit.ring :as ring] reitit.coercion.spec [reitit.ring.coercion :as rrc] [reitit.ring.middleware.exception :as exception] [reitit.ring.middleware.muuntaja :as muuntaja] [reitit.ring.middleware.parameters :as parameters] [ring.middleware.anti-forgery :as anti-forgery] [ring.middleware.content-type :as content-type] ring.util.response [skylobby.event-stub :as event] [skylobby.fs :as fs] [skylobby.fs.sdfz :as replay] [skylobby.resource :as resource] [skylobby.util :as u] [taoensso.sente :as sente] [taoensso.sente.interfaces :as interfaces] [taoensso.sente.server-adapters.http-kit :refer (get-sch-adapter)] [taoensso.timbre :as log])) (set! *warn-on-reflection* true) ; sente https://github.com/ptaoussanis/sente/blob/master/example-project/src/example/server.clj (defmulti -event-msg-handler :id) (defn event-msg-handler "Wraps `-event-msg-handler` with logging, error catching, etc." [{:as ev-msg :keys [id ?data event]}] (log/info id ?data event) (-event-msg-handler ev-msg)) ; Handle event-msgs on a single thread (defmethod -event-msg-handler :default ; Default/fallback case (no other matching handler) [{:keys [event ?reply-fn]}] (log/warnf "Unhandled event: %s" event) (when ?reply-fn (?reply-fn {:umatched-event-as-echoed-from-server event}))) (defn servers-data [state] {:active-servers (->> state :by-server (map (fn [[server-key server-data]] (let [client-data (:client-data server-data)] {:server-id server-key :server-key server-key :accepted (:accepted server-data) :client? (boolean (:client client-data)) :client-deferred? (boolean (:client-deferred client-data)) :server-url (:server-url client-data) :username (:username client-data)})))) :logins (:logins state) :servers (:servers state)}) ; https://github.com/ptaoussanis/sente/blob/master/src/taoensso/sente.cljc#L240-L243 ; the default edn packer has issues in graalvm (deftype EdnPacker [] interfaces/IPacker (pack [_ x] (pr-str x)) (unpack [_ x] (edn/read-string x))) (defn init [state-atom] (let [packer (EdnPacker.) chsk-server (sente/make-channel-socket-server! (get-sch-adapter) {:authorized?-fn nil :csrf-token-fn nil ; TODO :packer packer :wrap-recv-evs? false}) {:keys [ch-recv send-fn connected-uids]} chsk-server broadcast (fn [message] (let [uids (:any @connected-uids)] (log/info "Broadcasting message" (first message) "to" (count uids) "clients:" (pr-str uids)) (doseq [uid uids] (send-fn uid message)))) push-watcher (fn [_ref _k old-state new-state] (let [new-servers-data (servers-data new-state)] (when (not= (servers-data old-state) new-servers-data) (broadcast [:skylobby/servers new-servers-data]))) (let [new-auto-launch (:auto-launch new-state)] (when (not= (:auto-launch old-state) new-auto-launch) (broadcast [:skylobby/auto-launch new-auto-launch]))) (let [new-logins (:logins new-state)] (when (not= (:logins old-state) new-logins) (broadcast [:skylobby/logins new-logins]))) (doseq [[server-key server-data] (:by-server new-state)] (let [{:keys [auto-unspec battle battles channels users]} server-data] (when (not= auto-unspec (get-in old-state [:by-server server-key :auto-unspec])) (broadcast [:skylobby/auto-unspec {:server-key server-key :auto-unspec auto-unspec}])) (when (not= battle (get-in old-state [:by-server server-key :battle])) (broadcast [:skylobby/battle {:server-key server-key :battle battle}])) (when (not= battles (get-in old-state [:by-server server-key :battles])) (broadcast [:skylobby/battles {:server-key server-key :battles battles}])) (when (not= users (get-in old-state [:by-server server-key :users])) (broadcast [:skylobby/users {:server-key server-key :users users}])) (doseq [[channel-name channel-data] channels] (when (not= channel-data (get-in old-state [:by-server server-key :channels channel-name])) (broadcast [:skylobby/chat {:server-key server-key :channel-name channel-name :channel-data channel-data}]))))))] (add-watch state-atom :push-watcher push-watcher) (add-watch connected-uids :connected-uids (fn [_ _ old-ids new-ids] (when (not= old-ids new-ids) (log/infof "Connected uids change: %s" new-ids)))) (defmethod -event-msg-handler :skylobby/get [{:keys [?data ?reply-fn]}] (log/info "Get" ?data) (when ?reply-fn (?reply-fn get @state-atom ?data))) (defmethod -event-msg-handler :skylobby/get-in [{:keys [?data ?reply-fn]}] (log/info "Get in" ?data) (when ?reply-fn (?reply-fn (get-in @state-atom ?data)))) (defmethod -event-msg-handler :skylobby/assoc-in [{:keys [?data]}] (let [[path v] ?data] (log/info "Assoc in" path v) (swap! state-atom assoc-in path v))) (defmethod -event-msg-handler :skylobby/get-servers [{:keys [?data ?reply-fn]}] (log/info "Get servers data" ?data) (when ?reply-fn (?reply-fn (servers-data @state-atom)))) (defmethod -event-msg-handler :skylobby/join-battle [{:keys [?data]}] (let [[server-key battle-id] ?data server-data (get-in @state-atom [:by-server server-key])] (event/join-battle state-atom (assoc server-data :selected-battle battle-id)))) (defmethod -event-msg-handler :skylobby/leave-battle [{:keys [?data]}] (let [[server-key] ?data server-data (get-in @state-atom [:by-server server-key])] (event/leave-battle state-atom server-data))) (defmethod -event-msg-handler :skylobby/connect-server [{:keys [?data]}] (let [ {:keys [server-url username password]} ?data {:keys [logins servers]} @state-atom login (get logins server-url) username (or username (:username login)) password (or password (:password login)) server-key (u/server-key {:server-url server-url :username username})] (event/connect state-atom {:server [server-url (get servers server-url)] :server-key server-key :password password :username username}))) (defmethod -event-msg-handler :skylobby/disconnect-server [{:keys [?data]}] (let [ {:keys [server-key]} ?data] (event/disconnect state-atom server-key))) (defmethod -event-msg-handler :skylobby/start-battle [{:keys [?data]}] (let [ {:keys [server-key]} ?data {:keys [by-server by-spring-root engine-overrides servers spring-isolation-dir]} @state-atom {:keys [battle client-data] :as server-data} (get by-server server-key) {:keys [server-url username]} client-data spring-root (or (get-in servers [server-url :spring-isolation-dir]) spring-isolation-dir) my-battle-status (get-in battle [:users username :battle-status])] (event/start-battle state-atom (merge server-data {:am-host false ; TODO :am-spec true ; TODO :battle-status my-battle-status :channel-name (u/battle-channel-name battle) :engine-overrides engine-overrides :host-ingame true :spring-isolation-dir spring-root} (resource/spring-root-resources spring-root by-spring-root)))) (defmethod -event-msg-handler :skylobby/send-message [{:keys [?data]}] (let [ {:keys [server-key channel-name message]} ?data {:keys [by-server]} @state-atom {:keys [client-data]} (get by-server server-key)] (event/send-message state-atom {:channel-name channel-name :client-data client-data :message message :server-key server-key}))) (defmethod -event-msg-handler :skylobby/set-battle-mode [{:keys [?data]}] (let [ {:keys [server-key mode]} ?data {:keys [by-server ready-on-unspec]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (swap! state-atom assoc-in [:by-server server-key :auto-unspec] false) (event/set-battle-mode state-atom {:battle-status battle-status :client-data client-data :mode mode :ready-on-unspec ready-on-unspec :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-auto-unspec [{:keys [?data]}] (let [ {:keys [server-key auto-unspec]} ?data {:keys [by-server ready-on-unspec]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (event/set-auto-unspec state-atom { :auto-unspec auto-unspec :battle-status battle-status :client-data client-data :ready-on-unspec ready-on-unspec :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-battle-ready [{:keys [?data]}] (let [ {:keys [server-key ready]} ?data {:keys [by-server]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (event/set-battle-ready state-atom {:client-data client-data :battle-status battle-status :ready ready :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-away [{:keys [?data]}] (let [ {:keys [server-key away]} ?data {:keys [by-server]} @state-atom {:keys [client-data username users]} (get by-server server-key) {:keys [client-status]} (get-in users [:users username])] (event/set-client-status state-atom {:client-data client-data :client-status (assoc client-status :away away) :server-key server-key})))) (sente/start-server-chsk-router! ch-recv event-msg-handler) chsk-server)) (defn index [_] {:status 200 :body (hiccup/html [:head [:meta {:charset "utf-8"}]] [:body [:div#root (let [csrf-token (force anti-forgery/*anti-forgery-token*)] [:div#sente-csrf-token {:data-csrf-token csrf-token}])] [:link {:rel "stylesheet" :href "https://unpkg.com/tachyons@4.12.0/css/tachyons.min.css"}] [:link {:rel "stylesheet" :href "https://fonts.googleapis.com/icon?family=Material+Icons"}] [:script {:src (str "/js/main.js?v=" (u/curr-millis))}]]) :headers {"Content-Type" "text/html"}}) (defn login-handler "Here's where you'll add your server-side login/auth procedure (Friend, etc.). In our simplified example we'll just always successfully authenticate the user with whatever user-id they provided in the auth request." [ring-req] (let [{:keys [session params]} ring-req {:keys [user-id]} params] (log/debugf "Login request: %s" params) {:status 200 :session (assoc session :uid user-id)})) (s/def ::map-name string?) (s/def ::minimap-type string?) ; https://cljdoc.org/d/metosin/reitit/0.5.15/api/reitit.ring.middleware.exception (defn eception-handler [message exception request] {:status 500 :body {:message message :exception (str exception) :uri (:uri request)}}) ; https://github.com/ring-clojure/ring/pull/447/files (defn- connection-content-length [^java.net.URLConnection conn] (let [len (.getContentLength conn)] (when (<= 0 len) len))) (defn- connection-last-modified [^java.net.URLConnection conn] (let [last-mod (.getLastModified conn)] (when-not (zero? last-mod) (java.util.Date. last-mod)))) (defmethod ring.util.response/resource-data :resource [^java.net.URL url] ;; GraalVM resource scheme (let [resource (.openConnection url)] {:content (.getInputStream resource) :content-length (connection-content-length resource) :last-modified (connection-last-modified resource)})) (defn handler [state-atom] (let [{:keys [ajax-post-fn ajax-get-or-ws-handshake-fn]} (init state-atom)] (ring/ring-handler (ring/router [ ["/chsk" {:get {:handler ajax-get-or-ws-handshake-fn} :post {:handler ajax-post-fn}}] ["/login" {:post {:handler login-handler}}] ["/api" ["/math" {:get {:parameters {:query {:x int? :y int?}} :responses {200 {:body {:total int?}}} :handler (fn [{{{:keys [x y]} :query} :parameters}] {:status 200 :body {:total (+ x y)}})}}]] ["/ipc" ["/replay" {:get {:parameters {:query {:path string?}}} :responses {200 {:body {:path string?}}} :handler (fn [{{{:keys [path]} :query} :parameters}] (if-let [file (fs/file path)] (let [parsed-replay (replay/parse-replay file)] (log/info "Loading replay from IPC" path) (swap! state-atom (fn [state] (-> state (assoc :show-replays true :selected-replay parsed-replay :selected-replay-file file) (assoc-in [:parsed-replays-by-path (fs/canonical-path file)] parsed-replay))))) (log/warn "Unable to coerce to file" path)))}]] ["/minimap-image" {:get {:parameters {:query (s/keys :req-un [::map-name] :opt-un [::minimap-type])}} :handler (fn [{{{:keys [map-name minimap-type]} :query} :parameters}] (log/info "Serving minimap image for" map-name "type" minimap-type) (try (let [f (fs/minimap-image-cache-file map-name (when minimap-type {:minimap-type minimap-type}))] {:status 200 :headers {"Content-Type" "image/png"} :body (io/input-stream f)}) (catch Exception e (log/error e "Error in minimap image handler") {:status 500 :headers {"Content-Type" "text/html"} :body (str "Error getting minimap image for" map-name "type" minimap-type)})))}] ["/js/*" (ring/create-resource-handler {:root "public/js" :not-found-handler index})]] {:conflicts (constantly nil) :data {:coercion reitit.coercion.spec/coercion :muuntaja m/instance :middleware [parameters/parameters-middleware rrc/coerce-request-middleware ;anti-forgery/wrap-anti-forgery (exception/create-exception-middleware (merge exception/default-handlers {::exception/wrap (fn [handler e request] (log/error e "Http handler exception") (handler e request))})) content-type/wrap-content-type muuntaja/format-response-middleware rrc/coerce-response-middleware]}}) (ring/create-default-handler {:not-found index :method-not-allowed index :not-acceptable index}))))
98299
(ns skylobby.server-stub (:require [clojure.edn :as edn] [clojure.java.io :as io] [clojure.spec.alpha :as s] [hiccup.core :as hiccup] [muuntaja.core :as m] org.httpkit.server [reitit.ring :as ring] reitit.coercion.spec [reitit.ring.coercion :as rrc] [reitit.ring.middleware.exception :as exception] [reitit.ring.middleware.muuntaja :as muuntaja] [reitit.ring.middleware.parameters :as parameters] [ring.middleware.anti-forgery :as anti-forgery] [ring.middleware.content-type :as content-type] ring.util.response [skylobby.event-stub :as event] [skylobby.fs :as fs] [skylobby.fs.sdfz :as replay] [skylobby.resource :as resource] [skylobby.util :as u] [taoensso.sente :as sente] [taoensso.sente.interfaces :as interfaces] [taoensso.sente.server-adapters.http-kit :refer (get-sch-adapter)] [taoensso.timbre :as log])) (set! *warn-on-reflection* true) ; sente https://github.com/ptaoussanis/sente/blob/master/example-project/src/example/server.clj (defmulti -event-msg-handler :id) (defn event-msg-handler "Wraps `-event-msg-handler` with logging, error catching, etc." [{:as ev-msg :keys [id ?data event]}] (log/info id ?data event) (-event-msg-handler ev-msg)) ; Handle event-msgs on a single thread (defmethod -event-msg-handler :default ; Default/fallback case (no other matching handler) [{:keys [event ?reply-fn]}] (log/warnf "Unhandled event: %s" event) (when ?reply-fn (?reply-fn {:umatched-event-as-echoed-from-server event}))) (defn servers-data [state] {:active-servers (->> state :by-server (map (fn [[server-key server-data]] (let [client-data (:client-data server-data)] {:server-id server-key :server-key server-key :accepted (:accepted server-data) :client? (boolean (:client client-data)) :client-deferred? (boolean (:client-deferred client-data)) :server-url (:server-url client-data) :username (:username client-data)})))) :logins (:logins state) :servers (:servers state)}) ; https://github.com/ptaoussanis/sente/blob/master/src/taoensso/sente.cljc#L240-L243 ; the default edn packer has issues in graalvm (deftype EdnPacker [] interfaces/IPacker (pack [_ x] (pr-str x)) (unpack [_ x] (edn/read-string x))) (defn init [state-atom] (let [packer (EdnPacker.) chsk-server (sente/make-channel-socket-server! (get-sch-adapter) {:authorized?-fn nil :csrf-token-fn nil ; TODO :packer packer :wrap-recv-evs? false}) {:keys [ch-recv send-fn connected-uids]} chsk-server broadcast (fn [message] (let [uids (:any @connected-uids)] (log/info "Broadcasting message" (first message) "to" (count uids) "clients:" (pr-str uids)) (doseq [uid uids] (send-fn uid message)))) push-watcher (fn [_ref _k old-state new-state] (let [new-servers-data (servers-data new-state)] (when (not= (servers-data old-state) new-servers-data) (broadcast [:skylobby/servers new-servers-data]))) (let [new-auto-launch (:auto-launch new-state)] (when (not= (:auto-launch old-state) new-auto-launch) (broadcast [:skylobby/auto-launch new-auto-launch]))) (let [new-logins (:logins new-state)] (when (not= (:logins old-state) new-logins) (broadcast [:skylobby/logins new-logins]))) (doseq [[server-key server-data] (:by-server new-state)] (let [{:keys [auto-unspec battle battles channels users]} server-data] (when (not= auto-unspec (get-in old-state [:by-server server-key :auto-unspec])) (broadcast [:skylobby/auto-unspec {:server-key server-key :auto-unspec auto-unspec}])) (when (not= battle (get-in old-state [:by-server server-key :battle])) (broadcast [:skylobby/battle {:server-key server-key :battle battle}])) (when (not= battles (get-in old-state [:by-server server-key :battles])) (broadcast [:skylobby/battles {:server-key server-key :battles battles}])) (when (not= users (get-in old-state [:by-server server-key :users])) (broadcast [:skylobby/users {:server-key server-key :users users}])) (doseq [[channel-name channel-data] channels] (when (not= channel-data (get-in old-state [:by-server server-key :channels channel-name])) (broadcast [:skylobby/chat {:server-key server-key :channel-name channel-name :channel-data channel-data}]))))))] (add-watch state-atom :push-watcher push-watcher) (add-watch connected-uids :connected-uids (fn [_ _ old-ids new-ids] (when (not= old-ids new-ids) (log/infof "Connected uids change: %s" new-ids)))) (defmethod -event-msg-handler :skylobby/get [{:keys [?data ?reply-fn]}] (log/info "Get" ?data) (when ?reply-fn (?reply-fn get @state-atom ?data))) (defmethod -event-msg-handler :skylobby/get-in [{:keys [?data ?reply-fn]}] (log/info "Get in" ?data) (when ?reply-fn (?reply-fn (get-in @state-atom ?data)))) (defmethod -event-msg-handler :skylobby/assoc-in [{:keys [?data]}] (let [[path v] ?data] (log/info "Assoc in" path v) (swap! state-atom assoc-in path v))) (defmethod -event-msg-handler :skylobby/get-servers [{:keys [?data ?reply-fn]}] (log/info "Get servers data" ?data) (when ?reply-fn (?reply-fn (servers-data @state-atom)))) (defmethod -event-msg-handler :skylobby/join-battle [{:keys [?data]}] (let [[server-key battle-id] ?data server-data (get-in @state-atom [:by-server server-key])] (event/join-battle state-atom (assoc server-data :selected-battle battle-id)))) (defmethod -event-msg-handler :skylobby/leave-battle [{:keys [?data]}] (let [[server-key] ?data server-data (get-in @state-atom [:by-server server-key])] (event/leave-battle state-atom server-data))) (defmethod -event-msg-handler :skylobby/connect-server [{:keys [?data]}] (let [ {:keys [server-url username password]} ?data {:keys [logins servers]} @state-atom login (get logins server-url) username (or username (:username login)) password (or <PASSWORD> (:password login)) server-key (u/server-key {:server-url server-url :username username})] (event/connect state-atom {:server [server-url (get servers server-url)] :server-key server-key :password <PASSWORD> :username username}))) (defmethod -event-msg-handler :skylobby/disconnect-server [{:keys [?data]}] (let [ {:keys [server-key]} ?data] (event/disconnect state-atom server-key))) (defmethod -event-msg-handler :skylobby/start-battle [{:keys [?data]}] (let [ {:keys [server-key]} ?data {:keys [by-server by-spring-root engine-overrides servers spring-isolation-dir]} @state-atom {:keys [battle client-data] :as server-data} (get by-server server-key) {:keys [server-url username]} client-data spring-root (or (get-in servers [server-url :spring-isolation-dir]) spring-isolation-dir) my-battle-status (get-in battle [:users username :battle-status])] (event/start-battle state-atom (merge server-data {:am-host false ; TODO :am-spec true ; TODO :battle-status my-battle-status :channel-name (u/battle-channel-name battle) :engine-overrides engine-overrides :host-ingame true :spring-isolation-dir spring-root} (resource/spring-root-resources spring-root by-spring-root)))) (defmethod -event-msg-handler :skylobby/send-message [{:keys [?data]}] (let [ {:keys [server-key channel-name message]} ?data {:keys [by-server]} @state-atom {:keys [client-data]} (get by-server server-key)] (event/send-message state-atom {:channel-name channel-name :client-data client-data :message message :server-key server-key}))) (defmethod -event-msg-handler :skylobby/set-battle-mode [{:keys [?data]}] (let [ {:keys [server-key mode]} ?data {:keys [by-server ready-on-unspec]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (swap! state-atom assoc-in [:by-server server-key :auto-unspec] false) (event/set-battle-mode state-atom {:battle-status battle-status :client-data client-data :mode mode :ready-on-unspec ready-on-unspec :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-auto-unspec [{:keys [?data]}] (let [ {:keys [server-key auto-unspec]} ?data {:keys [by-server ready-on-unspec]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (event/set-auto-unspec state-atom { :auto-unspec auto-unspec :battle-status battle-status :client-data client-data :ready-on-unspec ready-on-unspec :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-battle-ready [{:keys [?data]}] (let [ {:keys [server-key ready]} ?data {:keys [by-server]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (event/set-battle-ready state-atom {:client-data client-data :battle-status battle-status :ready ready :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-away [{:keys [?data]}] (let [ {:keys [server-key away]} ?data {:keys [by-server]} @state-atom {:keys [client-data username users]} (get by-server server-key) {:keys [client-status]} (get-in users [:users username])] (event/set-client-status state-atom {:client-data client-data :client-status (assoc client-status :away away) :server-key server-key})))) (sente/start-server-chsk-router! ch-recv event-msg-handler) chsk-server)) (defn index [_] {:status 200 :body (hiccup/html [:head [:meta {:charset "utf-8"}]] [:body [:div#root (let [csrf-token (force anti-forgery/*anti-forgery-token*)] [:div#sente-csrf-token {:data-csrf-token csrf-token}])] [:link {:rel "stylesheet" :href "https://unpkg.com/tachyons@4.12.0/css/tachyons.min.css"}] [:link {:rel "stylesheet" :href "https://fonts.googleapis.com/icon?family=Material+Icons"}] [:script {:src (str "/js/main.js?v=" (u/curr-millis))}]]) :headers {"Content-Type" "text/html"}}) (defn login-handler "Here's where you'll add your server-side login/auth procedure (Friend, etc.). In our simplified example we'll just always successfully authenticate the user with whatever user-id they provided in the auth request." [ring-req] (let [{:keys [session params]} ring-req {:keys [user-id]} params] (log/debugf "Login request: %s" params) {:status 200 :session (assoc session :uid user-id)})) (s/def ::map-name string?) (s/def ::minimap-type string?) ; https://cljdoc.org/d/metosin/reitit/0.5.15/api/reitit.ring.middleware.exception (defn eception-handler [message exception request] {:status 500 :body {:message message :exception (str exception) :uri (:uri request)}}) ; https://github.com/ring-clojure/ring/pull/447/files (defn- connection-content-length [^java.net.URLConnection conn] (let [len (.getContentLength conn)] (when (<= 0 len) len))) (defn- connection-last-modified [^java.net.URLConnection conn] (let [last-mod (.getLastModified conn)] (when-not (zero? last-mod) (java.util.Date. last-mod)))) (defmethod ring.util.response/resource-data :resource [^java.net.URL url] ;; GraalVM resource scheme (let [resource (.openConnection url)] {:content (.getInputStream resource) :content-length (connection-content-length resource) :last-modified (connection-last-modified resource)})) (defn handler [state-atom] (let [{:keys [ajax-post-fn ajax-get-or-ws-handshake-fn]} (init state-atom)] (ring/ring-handler (ring/router [ ["/chsk" {:get {:handler ajax-get-or-ws-handshake-fn} :post {:handler ajax-post-fn}}] ["/login" {:post {:handler login-handler}}] ["/api" ["/math" {:get {:parameters {:query {:x int? :y int?}} :responses {200 {:body {:total int?}}} :handler (fn [{{{:keys [x y]} :query} :parameters}] {:status 200 :body {:total (+ x y)}})}}]] ["/ipc" ["/replay" {:get {:parameters {:query {:path string?}}} :responses {200 {:body {:path string?}}} :handler (fn [{{{:keys [path]} :query} :parameters}] (if-let [file (fs/file path)] (let [parsed-replay (replay/parse-replay file)] (log/info "Loading replay from IPC" path) (swap! state-atom (fn [state] (-> state (assoc :show-replays true :selected-replay parsed-replay :selected-replay-file file) (assoc-in [:parsed-replays-by-path (fs/canonical-path file)] parsed-replay))))) (log/warn "Unable to coerce to file" path)))}]] ["/minimap-image" {:get {:parameters {:query (s/keys :req-un [::map-name] :opt-un [::minimap-type])}} :handler (fn [{{{:keys [map-name minimap-type]} :query} :parameters}] (log/info "Serving minimap image for" map-name "type" minimap-type) (try (let [f (fs/minimap-image-cache-file map-name (when minimap-type {:minimap-type minimap-type}))] {:status 200 :headers {"Content-Type" "image/png"} :body (io/input-stream f)}) (catch Exception e (log/error e "Error in minimap image handler") {:status 500 :headers {"Content-Type" "text/html"} :body (str "Error getting minimap image for" map-name "type" minimap-type)})))}] ["/js/*" (ring/create-resource-handler {:root "public/js" :not-found-handler index})]] {:conflicts (constantly nil) :data {:coercion reitit.coercion.spec/coercion :muuntaja m/instance :middleware [parameters/parameters-middleware rrc/coerce-request-middleware ;anti-forgery/wrap-anti-forgery (exception/create-exception-middleware (merge exception/default-handlers {::exception/wrap (fn [handler e request] (log/error e "Http handler exception") (handler e request))})) content-type/wrap-content-type muuntaja/format-response-middleware rrc/coerce-response-middleware]}}) (ring/create-default-handler {:not-found index :method-not-allowed index :not-acceptable index}))))
true
(ns skylobby.server-stub (:require [clojure.edn :as edn] [clojure.java.io :as io] [clojure.spec.alpha :as s] [hiccup.core :as hiccup] [muuntaja.core :as m] org.httpkit.server [reitit.ring :as ring] reitit.coercion.spec [reitit.ring.coercion :as rrc] [reitit.ring.middleware.exception :as exception] [reitit.ring.middleware.muuntaja :as muuntaja] [reitit.ring.middleware.parameters :as parameters] [ring.middleware.anti-forgery :as anti-forgery] [ring.middleware.content-type :as content-type] ring.util.response [skylobby.event-stub :as event] [skylobby.fs :as fs] [skylobby.fs.sdfz :as replay] [skylobby.resource :as resource] [skylobby.util :as u] [taoensso.sente :as sente] [taoensso.sente.interfaces :as interfaces] [taoensso.sente.server-adapters.http-kit :refer (get-sch-adapter)] [taoensso.timbre :as log])) (set! *warn-on-reflection* true) ; sente https://github.com/ptaoussanis/sente/blob/master/example-project/src/example/server.clj (defmulti -event-msg-handler :id) (defn event-msg-handler "Wraps `-event-msg-handler` with logging, error catching, etc." [{:as ev-msg :keys [id ?data event]}] (log/info id ?data event) (-event-msg-handler ev-msg)) ; Handle event-msgs on a single thread (defmethod -event-msg-handler :default ; Default/fallback case (no other matching handler) [{:keys [event ?reply-fn]}] (log/warnf "Unhandled event: %s" event) (when ?reply-fn (?reply-fn {:umatched-event-as-echoed-from-server event}))) (defn servers-data [state] {:active-servers (->> state :by-server (map (fn [[server-key server-data]] (let [client-data (:client-data server-data)] {:server-id server-key :server-key server-key :accepted (:accepted server-data) :client? (boolean (:client client-data)) :client-deferred? (boolean (:client-deferred client-data)) :server-url (:server-url client-data) :username (:username client-data)})))) :logins (:logins state) :servers (:servers state)}) ; https://github.com/ptaoussanis/sente/blob/master/src/taoensso/sente.cljc#L240-L243 ; the default edn packer has issues in graalvm (deftype EdnPacker [] interfaces/IPacker (pack [_ x] (pr-str x)) (unpack [_ x] (edn/read-string x))) (defn init [state-atom] (let [packer (EdnPacker.) chsk-server (sente/make-channel-socket-server! (get-sch-adapter) {:authorized?-fn nil :csrf-token-fn nil ; TODO :packer packer :wrap-recv-evs? false}) {:keys [ch-recv send-fn connected-uids]} chsk-server broadcast (fn [message] (let [uids (:any @connected-uids)] (log/info "Broadcasting message" (first message) "to" (count uids) "clients:" (pr-str uids)) (doseq [uid uids] (send-fn uid message)))) push-watcher (fn [_ref _k old-state new-state] (let [new-servers-data (servers-data new-state)] (when (not= (servers-data old-state) new-servers-data) (broadcast [:skylobby/servers new-servers-data]))) (let [new-auto-launch (:auto-launch new-state)] (when (not= (:auto-launch old-state) new-auto-launch) (broadcast [:skylobby/auto-launch new-auto-launch]))) (let [new-logins (:logins new-state)] (when (not= (:logins old-state) new-logins) (broadcast [:skylobby/logins new-logins]))) (doseq [[server-key server-data] (:by-server new-state)] (let [{:keys [auto-unspec battle battles channels users]} server-data] (when (not= auto-unspec (get-in old-state [:by-server server-key :auto-unspec])) (broadcast [:skylobby/auto-unspec {:server-key server-key :auto-unspec auto-unspec}])) (when (not= battle (get-in old-state [:by-server server-key :battle])) (broadcast [:skylobby/battle {:server-key server-key :battle battle}])) (when (not= battles (get-in old-state [:by-server server-key :battles])) (broadcast [:skylobby/battles {:server-key server-key :battles battles}])) (when (not= users (get-in old-state [:by-server server-key :users])) (broadcast [:skylobby/users {:server-key server-key :users users}])) (doseq [[channel-name channel-data] channels] (when (not= channel-data (get-in old-state [:by-server server-key :channels channel-name])) (broadcast [:skylobby/chat {:server-key server-key :channel-name channel-name :channel-data channel-data}]))))))] (add-watch state-atom :push-watcher push-watcher) (add-watch connected-uids :connected-uids (fn [_ _ old-ids new-ids] (when (not= old-ids new-ids) (log/infof "Connected uids change: %s" new-ids)))) (defmethod -event-msg-handler :skylobby/get [{:keys [?data ?reply-fn]}] (log/info "Get" ?data) (when ?reply-fn (?reply-fn get @state-atom ?data))) (defmethod -event-msg-handler :skylobby/get-in [{:keys [?data ?reply-fn]}] (log/info "Get in" ?data) (when ?reply-fn (?reply-fn (get-in @state-atom ?data)))) (defmethod -event-msg-handler :skylobby/assoc-in [{:keys [?data]}] (let [[path v] ?data] (log/info "Assoc in" path v) (swap! state-atom assoc-in path v))) (defmethod -event-msg-handler :skylobby/get-servers [{:keys [?data ?reply-fn]}] (log/info "Get servers data" ?data) (when ?reply-fn (?reply-fn (servers-data @state-atom)))) (defmethod -event-msg-handler :skylobby/join-battle [{:keys [?data]}] (let [[server-key battle-id] ?data server-data (get-in @state-atom [:by-server server-key])] (event/join-battle state-atom (assoc server-data :selected-battle battle-id)))) (defmethod -event-msg-handler :skylobby/leave-battle [{:keys [?data]}] (let [[server-key] ?data server-data (get-in @state-atom [:by-server server-key])] (event/leave-battle state-atom server-data))) (defmethod -event-msg-handler :skylobby/connect-server [{:keys [?data]}] (let [ {:keys [server-url username password]} ?data {:keys [logins servers]} @state-atom login (get logins server-url) username (or username (:username login)) password (or PI:PASSWORD:<PASSWORD>END_PI (:password login)) server-key (u/server-key {:server-url server-url :username username})] (event/connect state-atom {:server [server-url (get servers server-url)] :server-key server-key :password PI:PASSWORD:<PASSWORD>END_PI :username username}))) (defmethod -event-msg-handler :skylobby/disconnect-server [{:keys [?data]}] (let [ {:keys [server-key]} ?data] (event/disconnect state-atom server-key))) (defmethod -event-msg-handler :skylobby/start-battle [{:keys [?data]}] (let [ {:keys [server-key]} ?data {:keys [by-server by-spring-root engine-overrides servers spring-isolation-dir]} @state-atom {:keys [battle client-data] :as server-data} (get by-server server-key) {:keys [server-url username]} client-data spring-root (or (get-in servers [server-url :spring-isolation-dir]) spring-isolation-dir) my-battle-status (get-in battle [:users username :battle-status])] (event/start-battle state-atom (merge server-data {:am-host false ; TODO :am-spec true ; TODO :battle-status my-battle-status :channel-name (u/battle-channel-name battle) :engine-overrides engine-overrides :host-ingame true :spring-isolation-dir spring-root} (resource/spring-root-resources spring-root by-spring-root)))) (defmethod -event-msg-handler :skylobby/send-message [{:keys [?data]}] (let [ {:keys [server-key channel-name message]} ?data {:keys [by-server]} @state-atom {:keys [client-data]} (get by-server server-key)] (event/send-message state-atom {:channel-name channel-name :client-data client-data :message message :server-key server-key}))) (defmethod -event-msg-handler :skylobby/set-battle-mode [{:keys [?data]}] (let [ {:keys [server-key mode]} ?data {:keys [by-server ready-on-unspec]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (swap! state-atom assoc-in [:by-server server-key :auto-unspec] false) (event/set-battle-mode state-atom {:battle-status battle-status :client-data client-data :mode mode :ready-on-unspec ready-on-unspec :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-auto-unspec [{:keys [?data]}] (let [ {:keys [server-key auto-unspec]} ?data {:keys [by-server ready-on-unspec]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (event/set-auto-unspec state-atom { :auto-unspec auto-unspec :battle-status battle-status :client-data client-data :ready-on-unspec ready-on-unspec :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-battle-ready [{:keys [?data]}] (let [ {:keys [server-key ready]} ?data {:keys [by-server]} @state-atom {:keys [battle client-data username]} (get by-server server-key) {:keys [battle-status team-color]} (get-in battle [:users username])] (event/set-battle-ready state-atom {:client-data client-data :battle-status battle-status :ready ready :server-key server-key :team-color team-color}))) (defmethod -event-msg-handler :skylobby/set-away [{:keys [?data]}] (let [ {:keys [server-key away]} ?data {:keys [by-server]} @state-atom {:keys [client-data username users]} (get by-server server-key) {:keys [client-status]} (get-in users [:users username])] (event/set-client-status state-atom {:client-data client-data :client-status (assoc client-status :away away) :server-key server-key})))) (sente/start-server-chsk-router! ch-recv event-msg-handler) chsk-server)) (defn index [_] {:status 200 :body (hiccup/html [:head [:meta {:charset "utf-8"}]] [:body [:div#root (let [csrf-token (force anti-forgery/*anti-forgery-token*)] [:div#sente-csrf-token {:data-csrf-token csrf-token}])] [:link {:rel "stylesheet" :href "https://unpkg.com/tachyons@4.12.0/css/tachyons.min.css"}] [:link {:rel "stylesheet" :href "https://fonts.googleapis.com/icon?family=Material+Icons"}] [:script {:src (str "/js/main.js?v=" (u/curr-millis))}]]) :headers {"Content-Type" "text/html"}}) (defn login-handler "Here's where you'll add your server-side login/auth procedure (Friend, etc.). In our simplified example we'll just always successfully authenticate the user with whatever user-id they provided in the auth request." [ring-req] (let [{:keys [session params]} ring-req {:keys [user-id]} params] (log/debugf "Login request: %s" params) {:status 200 :session (assoc session :uid user-id)})) (s/def ::map-name string?) (s/def ::minimap-type string?) ; https://cljdoc.org/d/metosin/reitit/0.5.15/api/reitit.ring.middleware.exception (defn eception-handler [message exception request] {:status 500 :body {:message message :exception (str exception) :uri (:uri request)}}) ; https://github.com/ring-clojure/ring/pull/447/files (defn- connection-content-length [^java.net.URLConnection conn] (let [len (.getContentLength conn)] (when (<= 0 len) len))) (defn- connection-last-modified [^java.net.URLConnection conn] (let [last-mod (.getLastModified conn)] (when-not (zero? last-mod) (java.util.Date. last-mod)))) (defmethod ring.util.response/resource-data :resource [^java.net.URL url] ;; GraalVM resource scheme (let [resource (.openConnection url)] {:content (.getInputStream resource) :content-length (connection-content-length resource) :last-modified (connection-last-modified resource)})) (defn handler [state-atom] (let [{:keys [ajax-post-fn ajax-get-or-ws-handshake-fn]} (init state-atom)] (ring/ring-handler (ring/router [ ["/chsk" {:get {:handler ajax-get-or-ws-handshake-fn} :post {:handler ajax-post-fn}}] ["/login" {:post {:handler login-handler}}] ["/api" ["/math" {:get {:parameters {:query {:x int? :y int?}} :responses {200 {:body {:total int?}}} :handler (fn [{{{:keys [x y]} :query} :parameters}] {:status 200 :body {:total (+ x y)}})}}]] ["/ipc" ["/replay" {:get {:parameters {:query {:path string?}}} :responses {200 {:body {:path string?}}} :handler (fn [{{{:keys [path]} :query} :parameters}] (if-let [file (fs/file path)] (let [parsed-replay (replay/parse-replay file)] (log/info "Loading replay from IPC" path) (swap! state-atom (fn [state] (-> state (assoc :show-replays true :selected-replay parsed-replay :selected-replay-file file) (assoc-in [:parsed-replays-by-path (fs/canonical-path file)] parsed-replay))))) (log/warn "Unable to coerce to file" path)))}]] ["/minimap-image" {:get {:parameters {:query (s/keys :req-un [::map-name] :opt-un [::minimap-type])}} :handler (fn [{{{:keys [map-name minimap-type]} :query} :parameters}] (log/info "Serving minimap image for" map-name "type" minimap-type) (try (let [f (fs/minimap-image-cache-file map-name (when minimap-type {:minimap-type minimap-type}))] {:status 200 :headers {"Content-Type" "image/png"} :body (io/input-stream f)}) (catch Exception e (log/error e "Error in minimap image handler") {:status 500 :headers {"Content-Type" "text/html"} :body (str "Error getting minimap image for" map-name "type" minimap-type)})))}] ["/js/*" (ring/create-resource-handler {:root "public/js" :not-found-handler index})]] {:conflicts (constantly nil) :data {:coercion reitit.coercion.spec/coercion :muuntaja m/instance :middleware [parameters/parameters-middleware rrc/coerce-request-middleware ;anti-forgery/wrap-anti-forgery (exception/create-exception-middleware (merge exception/default-handlers {::exception/wrap (fn [handler e request] (log/error e "Http handler exception") (handler e request))})) content-type/wrap-content-type muuntaja/format-response-middleware rrc/coerce-response-middleware]}}) (ring/create-default-handler {:not-found index :method-not-allowed index :not-acceptable index}))))
[ { "context": "n other languages.\n;;\n;; Examples:\n\n(def my-name \"Chris Oakman\")\n(def your-name \"Jimmy Jimbob\")\n(def num-cookies", "end": 363, "score": 0.9998858571052551, "start": 351, "tag": "NAME", "value": "Chris Oakman" }, { "context": "es:\n\n(def my-name \"Chris Oakman\")\n(def your-name \"Jimmy Jimbob\")\n(def num-cookies 5)\n\n;; ~~~~~~~~~~~~~~~~~~~~~~~", "end": 394, "score": 0.9998904466629028, "start": 382, "tag": "NAME", "value": "Jimmy Jimbob" } ]
src-cljs/cljs101/exercises/ex101_def_forms.cljs
oakmac/cljs101
3
(ns cljs101.exercises.ex101-def-forms) (declare my-name your-name my-job my-age your-age) ;; ;; Hello and welcome to the wonderful world of ClojureScript! ;; ;; The most basic of Clojure "forms" are the def forms; def is short for "define" ;; These are similar to const in JavaScript and variables in other languages. ;; ;; Examples: (def my-name "Chris Oakman") (def your-name "Jimmy Jimbob") (def num-cookies 5) ;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ;; Write five def forms below: my-name, your-name, my-job, my-age, your-age ;; ;; Be sure to use Strings for the names and Numbers for the ages.
45359
(ns cljs101.exercises.ex101-def-forms) (declare my-name your-name my-job my-age your-age) ;; ;; Hello and welcome to the wonderful world of ClojureScript! ;; ;; The most basic of Clojure "forms" are the def forms; def is short for "define" ;; These are similar to const in JavaScript and variables in other languages. ;; ;; Examples: (def my-name "<NAME>") (def your-name "<NAME>") (def num-cookies 5) ;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ;; Write five def forms below: my-name, your-name, my-job, my-age, your-age ;; ;; Be sure to use Strings for the names and Numbers for the ages.
true
(ns cljs101.exercises.ex101-def-forms) (declare my-name your-name my-job my-age your-age) ;; ;; Hello and welcome to the wonderful world of ClojureScript! ;; ;; The most basic of Clojure "forms" are the def forms; def is short for "define" ;; These are similar to const in JavaScript and variables in other languages. ;; ;; Examples: (def my-name "PI:NAME:<NAME>END_PI") (def your-name "PI:NAME:<NAME>END_PI") (def num-cookies 5) ;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ;; Write five def forms below: my-name, your-name, my-job, my-age, your-age ;; ;; Be sure to use Strings for the names and Numbers for the ages.
[ { "context": "dbc/db-set-rollback-only! t-con)\n (let [name \"Sam\"\n _ (db/create-user! t-con {:id name", "end": 952, "score": 0.5967755913734436, "start": 949, "tag": "NAME", "value": "Sam" }, { "context": " _ (db/create-user! t-con {:id name, :pass \"somepath\", :email nil})\n game (matcher/initial-s", "end": 1019, "score": 0.9986051321029663, "start": 1011, "tag": "PASSWORD", "value": "somepath" } ]
test/clj/plus_minus/test/multiplayer/persist.clj
Liverm0r/plusminus.me
3
(ns plus-minus.test.multiplayer.persist (:require [plus-minus.db.core :as db] [luminus-migrations.core :as migrations] [clojure.test :refer [use-fixtures deftest is testing]] [clojure.java.jdbc :as jdbc] [clojure.core.async :refer [>!!]] [plus-minus.config :refer [env]] [plus-minus.multiplayer.contract :refer [->Reply ->Result] :as c] [plus-minus.routes.multiplayer.persist] [mount.core :as mount] [plus-minus.routes.multiplayer.persist :as persist] [plus-minus.routes.multiplayer.topics :as topics] [plus-minus.routes.multiplayer.matcher :as matcher] [plus-minus.game.board :as b])) (use-fixtures :once (fn [f] (mount/start #'plus-minus.config/env #'plus-minus.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-saving-replies (jdbc/with-db-transaction [t-con db/*db*] (jdbc/db-set-rollback-only! t-con) (let [name "Sam" _ (db/create-user! t-con {:id name, :pass "somepath", :email nil}) game (matcher/initial-state b/row-count-min name "p2") stop> (persist/subscribe> t-con)] (topics/push! :reply (->Reply :end name (->Result :win :no-moves game))) (Thread/sleep 1000) (let [stats (db/get-online-stats t-con {:id name})] (is (some? stats)) (>!! stop> 1)))))
20891
(ns plus-minus.test.multiplayer.persist (:require [plus-minus.db.core :as db] [luminus-migrations.core :as migrations] [clojure.test :refer [use-fixtures deftest is testing]] [clojure.java.jdbc :as jdbc] [clojure.core.async :refer [>!!]] [plus-minus.config :refer [env]] [plus-minus.multiplayer.contract :refer [->Reply ->Result] :as c] [plus-minus.routes.multiplayer.persist] [mount.core :as mount] [plus-minus.routes.multiplayer.persist :as persist] [plus-minus.routes.multiplayer.topics :as topics] [plus-minus.routes.multiplayer.matcher :as matcher] [plus-minus.game.board :as b])) (use-fixtures :once (fn [f] (mount/start #'plus-minus.config/env #'plus-minus.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-saving-replies (jdbc/with-db-transaction [t-con db/*db*] (jdbc/db-set-rollback-only! t-con) (let [name "<NAME>" _ (db/create-user! t-con {:id name, :pass "<PASSWORD>", :email nil}) game (matcher/initial-state b/row-count-min name "p2") stop> (persist/subscribe> t-con)] (topics/push! :reply (->Reply :end name (->Result :win :no-moves game))) (Thread/sleep 1000) (let [stats (db/get-online-stats t-con {:id name})] (is (some? stats)) (>!! stop> 1)))))
true
(ns plus-minus.test.multiplayer.persist (:require [plus-minus.db.core :as db] [luminus-migrations.core :as migrations] [clojure.test :refer [use-fixtures deftest is testing]] [clojure.java.jdbc :as jdbc] [clojure.core.async :refer [>!!]] [plus-minus.config :refer [env]] [plus-minus.multiplayer.contract :refer [->Reply ->Result] :as c] [plus-minus.routes.multiplayer.persist] [mount.core :as mount] [plus-minus.routes.multiplayer.persist :as persist] [plus-minus.routes.multiplayer.topics :as topics] [plus-minus.routes.multiplayer.matcher :as matcher] [plus-minus.game.board :as b])) (use-fixtures :once (fn [f] (mount/start #'plus-minus.config/env #'plus-minus.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-saving-replies (jdbc/with-db-transaction [t-con db/*db*] (jdbc/db-set-rollback-only! t-con) (let [name "PI:NAME:<NAME>END_PI" _ (db/create-user! t-con {:id name, :pass "PI:PASSWORD:<PASSWORD>END_PI", :email nil}) game (matcher/initial-state b/row-count-min name "p2") stop> (persist/subscribe> t-con)] (topics/push! :reply (->Reply :end name (->Result :win :no-moves game))) (Thread/sleep 1000) (let [stats (db/get-online-stats t-con {:id name})] (is (some? stats)) (>!! stop> 1)))))
[ { "context": "showing\" filter. Just the todos.\n;;\n\n(def ls-key \"clchess\") ;; localstore key\n\n(defn themes->local-stor", "end": 2377, "score": 0.998626708984375, "start": 2370, "tag": "KEY", "value": "clchess" } ]
src/cljs/clchess/db.cljs
ageneau/clchess
6
(ns clchess.db (:require [cljs.reader] [cljs.spec :as s] [clchess.specs.clchess :as app-spec] [clchess.specs.chess :as schess] [clchess.specs.theme :as stheme] [clchess.specs.chessdb :as schessdb] [clchess.specs.view :as sview] [clchess.specs.board :as sboard] [clchess.specs.chessground :as schessground] [re-frame.core :as re-frame] [cognitect.transit :as t] [taoensso.timbre :as log])) ;; -- Default app-db Value --------------------------------------------------- ;; ;; When the application first starts, this will be the value put in app-db ;; Unless, or course, there are todos in the LocalStore (see further below) ;; Look in core.cljs for "(dispatch-sync [:initialise-db])" ;; (def default-value ;; what gets put into app-db by default. {::stheme/theme {::stheme/is-2d true ::stheme/name "light" ::stheme/data-theme "blue" ::stheme/data-theme-3d "Black-White-Aluminium" ::stheme/data-set "cburnett" ::stheme/data-set-3d "Basic" ::stheme/background-img "http://lichess1.org/assets/images/background/landscape.jpg" ::stheme/zoom "80%"} ::sview/view {::sview/is-fullscreen false} ::schessground/board {:viewOnly false :turnColor "white" :lastMove nil :fen "start" :movable {:free false :color "both" :premove true :dests {}} :promotion {:show false}} ::schess/game {::schess/initial-fen "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ::schess/moves [] ::schess/current-ply 0} ::schessdb/databases {} ::app-spec/file-selector {:file-selector/opened false} }) ;; -- Local Storage ---------------------------------------------------------- ;; ;; Part of the clchess challenge is to store todos in LocalStorage, and ;; on app startup, reload the todos from when the program was last run. ;; But we are not to load the setting for the "showing" filter. Just the todos. ;; (def ls-key "clchess") ;; localstore key (defn themes->local-store "Puts theme into localStorage" [theme] (let [w (t/writer :json)] (log/debug "themes->local-store: " theme) (.setItem js/localStorage ls-key (t/write w theme)))) ;; sorted-map writen as an EDN map ;; register a coeffect handler which will load a value from localstore ;; To see it used look in events.clj at the event handler for `:initialise-db` (re-frame/reg-cofx :local-store-themes (fn [cofx _] "Read in themes from localstore, and process into a map we can merge into app-db." (let [r (t/reader :json)] (assoc cofx :local-store-themes (into (sorted-map) (some->> (.getItem js/localStorage ls-key) (t/read r) ))))))
112707
(ns clchess.db (:require [cljs.reader] [cljs.spec :as s] [clchess.specs.clchess :as app-spec] [clchess.specs.chess :as schess] [clchess.specs.theme :as stheme] [clchess.specs.chessdb :as schessdb] [clchess.specs.view :as sview] [clchess.specs.board :as sboard] [clchess.specs.chessground :as schessground] [re-frame.core :as re-frame] [cognitect.transit :as t] [taoensso.timbre :as log])) ;; -- Default app-db Value --------------------------------------------------- ;; ;; When the application first starts, this will be the value put in app-db ;; Unless, or course, there are todos in the LocalStore (see further below) ;; Look in core.cljs for "(dispatch-sync [:initialise-db])" ;; (def default-value ;; what gets put into app-db by default. {::stheme/theme {::stheme/is-2d true ::stheme/name "light" ::stheme/data-theme "blue" ::stheme/data-theme-3d "Black-White-Aluminium" ::stheme/data-set "cburnett" ::stheme/data-set-3d "Basic" ::stheme/background-img "http://lichess1.org/assets/images/background/landscape.jpg" ::stheme/zoom "80%"} ::sview/view {::sview/is-fullscreen false} ::schessground/board {:viewOnly false :turnColor "white" :lastMove nil :fen "start" :movable {:free false :color "both" :premove true :dests {}} :promotion {:show false}} ::schess/game {::schess/initial-fen "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ::schess/moves [] ::schess/current-ply 0} ::schessdb/databases {} ::app-spec/file-selector {:file-selector/opened false} }) ;; -- Local Storage ---------------------------------------------------------- ;; ;; Part of the clchess challenge is to store todos in LocalStorage, and ;; on app startup, reload the todos from when the program was last run. ;; But we are not to load the setting for the "showing" filter. Just the todos. ;; (def ls-key "<KEY>") ;; localstore key (defn themes->local-store "Puts theme into localStorage" [theme] (let [w (t/writer :json)] (log/debug "themes->local-store: " theme) (.setItem js/localStorage ls-key (t/write w theme)))) ;; sorted-map writen as an EDN map ;; register a coeffect handler which will load a value from localstore ;; To see it used look in events.clj at the event handler for `:initialise-db` (re-frame/reg-cofx :local-store-themes (fn [cofx _] "Read in themes from localstore, and process into a map we can merge into app-db." (let [r (t/reader :json)] (assoc cofx :local-store-themes (into (sorted-map) (some->> (.getItem js/localStorage ls-key) (t/read r) ))))))
true
(ns clchess.db (:require [cljs.reader] [cljs.spec :as s] [clchess.specs.clchess :as app-spec] [clchess.specs.chess :as schess] [clchess.specs.theme :as stheme] [clchess.specs.chessdb :as schessdb] [clchess.specs.view :as sview] [clchess.specs.board :as sboard] [clchess.specs.chessground :as schessground] [re-frame.core :as re-frame] [cognitect.transit :as t] [taoensso.timbre :as log])) ;; -- Default app-db Value --------------------------------------------------- ;; ;; When the application first starts, this will be the value put in app-db ;; Unless, or course, there are todos in the LocalStore (see further below) ;; Look in core.cljs for "(dispatch-sync [:initialise-db])" ;; (def default-value ;; what gets put into app-db by default. {::stheme/theme {::stheme/is-2d true ::stheme/name "light" ::stheme/data-theme "blue" ::stheme/data-theme-3d "Black-White-Aluminium" ::stheme/data-set "cburnett" ::stheme/data-set-3d "Basic" ::stheme/background-img "http://lichess1.org/assets/images/background/landscape.jpg" ::stheme/zoom "80%"} ::sview/view {::sview/is-fullscreen false} ::schessground/board {:viewOnly false :turnColor "white" :lastMove nil :fen "start" :movable {:free false :color "both" :premove true :dests {}} :promotion {:show false}} ::schess/game {::schess/initial-fen "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" ::schess/moves [] ::schess/current-ply 0} ::schessdb/databases {} ::app-spec/file-selector {:file-selector/opened false} }) ;; -- Local Storage ---------------------------------------------------------- ;; ;; Part of the clchess challenge is to store todos in LocalStorage, and ;; on app startup, reload the todos from when the program was last run. ;; But we are not to load the setting for the "showing" filter. Just the todos. ;; (def ls-key "PI:KEY:<KEY>END_PI") ;; localstore key (defn themes->local-store "Puts theme into localStorage" [theme] (let [w (t/writer :json)] (log/debug "themes->local-store: " theme) (.setItem js/localStorage ls-key (t/write w theme)))) ;; sorted-map writen as an EDN map ;; register a coeffect handler which will load a value from localstore ;; To see it used look in events.clj at the event handler for `:initialise-db` (re-frame/reg-cofx :local-store-themes (fn [cofx _] "Read in themes from localstore, and process into a map we can merge into app-db." (let [r (t/reader :json)] (assoc cofx :local-store-themes (into (sorted-map) (some->> (.getItem js/localStorage ls-key) (t/read r) ))))))
[ { "context": "tp://overtone.github.io/\"\n :mailing-list {:name \"overtone\"\n :archive \"https://groups.google", "end": 2396, "score": 0.7247207164764404, "start": 2388, "tag": "USERNAME", "value": "overtone" }, { "context": " :archive \"https://groups.google.com/group/overtone\"\n :post \"overtone@googlegroups.co", "end": 2465, "score": 0.6288719177246094, "start": 2461, "tag": "USERNAME", "value": "tone" }, { "context": "oogle.com/group/overtone\"\n :post \"overtone@googlegroups.com\"}\n :license {:name \"The MIT License (MIT)\"\n ", "end": 2516, "score": 0.999916136264801, "start": 2491, "tag": "EMAIL", "value": "overtone@googlegroups.com" } ]
project.clj
jamesblunt/overtone
1
(require 'leiningen.core.eval) (def JVMOPTS "Per os jvm options. Options common to all cases go under `:any`. Options specific to one OS go under the key returned by `leiningen.core.eval/get-os` for that system. Temporarily disabled options can be kept under `:disabled`." {:any ["-Xms512m" "-Xmx1g" ; Minimum and maximum sizes of the heap "-XX:+UseParNewGC" ; Use the new parallel GC in conjunction with "-XX:+UseConcMarkSweepGC" ; the concurrent garbage collector "-XX:+CMSConcurrentMTEnabled" ; Enable multi-threaded concurrent gc work (ParNewGC) "-XX:MaxGCPauseMillis=20" ; Specify a target of 20ms for max gc pauses "-XX:+CMSIncrementalMode" ; Do many small GC cycles to minimize pauses "-XX:MaxNewSize=257m" ; Specify the max and min size of the new "-XX:NewSize=256m" ; generation to be small "-XX:+UseTLAB" ; Uses thread-local object allocation blocks. This ; improves concurrency by reducing contention on ; the shared heap lock. "-XX:MaxTenuringThreshold=0"] ; Makes the full NewSize available to every NewGC ; cycle, and reduces the pause time by not ; evaluating tenured objects. Technically, this ; setting promotes all live objects to the older ; generation, rather than copying them. :macosx ["-Xdock:name=Overtone"] :disabled ["-XX:ConcGCThreads=2" ; Use 2 threads with concurrent gc collections "-XX:TieredCompilation" ; JVM7 - combine both client and server compilation ; strategies "-XX:CompileThreshold=1" ; JIT each function after one execution "-XX:+PrintGC" ; Print GC info to stdout "-XX:+PrintGCDetails" ; - with details "-XX:+PrintGCTimeStamps"]}) ; - and timestamps (defn jvm-opts "Return a complete vector of jvm-opts for the current os." [] (let [os (leiningen.core.eval/get-os)] (vec (set (concat (get JVMOPTS :any) (get JVMOPTS os)))))) (defproject overtone "0.9.1" :description "Collaborative Programmable Music." :url "http://overtone.github.io/" :mailing-list {:name "overtone" :archive "https://groups.google.com/group/overtone" :post "overtone@googlegroups.com"} :license {:name "The MIT License (MIT)" :url "http://opensource.org/licenses/MIT" :distribution :repo :comments "Please use Overtone for good"} :dependencies [[org.clojure/clojure "1.5.1"] [org.clojure/data.json "0.2.3"] [clj-native "0.9.3"] [overtone/at-at "1.2.0"] [overtone/osc-clj "0.9.0"] [overtone/byte-spec "0.3.1"] [overtone/midi-clj "0.5.0"] [overtone/libs.handlers "0.2.0"] [overtone/scsynth "3.5.7.0"] [overtone/scsynth-extras "3.5.7.0"] [clj-glob "1.0.0"]] :profiles {:test {:dependencies [[bultitude "0.2.0"] [polynome "0.2.2"]]}} :test-selectors {:core (fn [m] (not (some m [:gui :hw]))) :gui :gui :hw :hw} :native-path "native" :min-lein-version "2.0.0" :jvm-opts ^:replace ~(jvm-opts))
32566
(require 'leiningen.core.eval) (def JVMOPTS "Per os jvm options. Options common to all cases go under `:any`. Options specific to one OS go under the key returned by `leiningen.core.eval/get-os` for that system. Temporarily disabled options can be kept under `:disabled`." {:any ["-Xms512m" "-Xmx1g" ; Minimum and maximum sizes of the heap "-XX:+UseParNewGC" ; Use the new parallel GC in conjunction with "-XX:+UseConcMarkSweepGC" ; the concurrent garbage collector "-XX:+CMSConcurrentMTEnabled" ; Enable multi-threaded concurrent gc work (ParNewGC) "-XX:MaxGCPauseMillis=20" ; Specify a target of 20ms for max gc pauses "-XX:+CMSIncrementalMode" ; Do many small GC cycles to minimize pauses "-XX:MaxNewSize=257m" ; Specify the max and min size of the new "-XX:NewSize=256m" ; generation to be small "-XX:+UseTLAB" ; Uses thread-local object allocation blocks. This ; improves concurrency by reducing contention on ; the shared heap lock. "-XX:MaxTenuringThreshold=0"] ; Makes the full NewSize available to every NewGC ; cycle, and reduces the pause time by not ; evaluating tenured objects. Technically, this ; setting promotes all live objects to the older ; generation, rather than copying them. :macosx ["-Xdock:name=Overtone"] :disabled ["-XX:ConcGCThreads=2" ; Use 2 threads with concurrent gc collections "-XX:TieredCompilation" ; JVM7 - combine both client and server compilation ; strategies "-XX:CompileThreshold=1" ; JIT each function after one execution "-XX:+PrintGC" ; Print GC info to stdout "-XX:+PrintGCDetails" ; - with details "-XX:+PrintGCTimeStamps"]}) ; - and timestamps (defn jvm-opts "Return a complete vector of jvm-opts for the current os." [] (let [os (leiningen.core.eval/get-os)] (vec (set (concat (get JVMOPTS :any) (get JVMOPTS os)))))) (defproject overtone "0.9.1" :description "Collaborative Programmable Music." :url "http://overtone.github.io/" :mailing-list {:name "overtone" :archive "https://groups.google.com/group/overtone" :post "<EMAIL>"} :license {:name "The MIT License (MIT)" :url "http://opensource.org/licenses/MIT" :distribution :repo :comments "Please use Overtone for good"} :dependencies [[org.clojure/clojure "1.5.1"] [org.clojure/data.json "0.2.3"] [clj-native "0.9.3"] [overtone/at-at "1.2.0"] [overtone/osc-clj "0.9.0"] [overtone/byte-spec "0.3.1"] [overtone/midi-clj "0.5.0"] [overtone/libs.handlers "0.2.0"] [overtone/scsynth "3.5.7.0"] [overtone/scsynth-extras "3.5.7.0"] [clj-glob "1.0.0"]] :profiles {:test {:dependencies [[bultitude "0.2.0"] [polynome "0.2.2"]]}} :test-selectors {:core (fn [m] (not (some m [:gui :hw]))) :gui :gui :hw :hw} :native-path "native" :min-lein-version "2.0.0" :jvm-opts ^:replace ~(jvm-opts))
true
(require 'leiningen.core.eval) (def JVMOPTS "Per os jvm options. Options common to all cases go under `:any`. Options specific to one OS go under the key returned by `leiningen.core.eval/get-os` for that system. Temporarily disabled options can be kept under `:disabled`." {:any ["-Xms512m" "-Xmx1g" ; Minimum and maximum sizes of the heap "-XX:+UseParNewGC" ; Use the new parallel GC in conjunction with "-XX:+UseConcMarkSweepGC" ; the concurrent garbage collector "-XX:+CMSConcurrentMTEnabled" ; Enable multi-threaded concurrent gc work (ParNewGC) "-XX:MaxGCPauseMillis=20" ; Specify a target of 20ms for max gc pauses "-XX:+CMSIncrementalMode" ; Do many small GC cycles to minimize pauses "-XX:MaxNewSize=257m" ; Specify the max and min size of the new "-XX:NewSize=256m" ; generation to be small "-XX:+UseTLAB" ; Uses thread-local object allocation blocks. This ; improves concurrency by reducing contention on ; the shared heap lock. "-XX:MaxTenuringThreshold=0"] ; Makes the full NewSize available to every NewGC ; cycle, and reduces the pause time by not ; evaluating tenured objects. Technically, this ; setting promotes all live objects to the older ; generation, rather than copying them. :macosx ["-Xdock:name=Overtone"] :disabled ["-XX:ConcGCThreads=2" ; Use 2 threads with concurrent gc collections "-XX:TieredCompilation" ; JVM7 - combine both client and server compilation ; strategies "-XX:CompileThreshold=1" ; JIT each function after one execution "-XX:+PrintGC" ; Print GC info to stdout "-XX:+PrintGCDetails" ; - with details "-XX:+PrintGCTimeStamps"]}) ; - and timestamps (defn jvm-opts "Return a complete vector of jvm-opts for the current os." [] (let [os (leiningen.core.eval/get-os)] (vec (set (concat (get JVMOPTS :any) (get JVMOPTS os)))))) (defproject overtone "0.9.1" :description "Collaborative Programmable Music." :url "http://overtone.github.io/" :mailing-list {:name "overtone" :archive "https://groups.google.com/group/overtone" :post "PI:EMAIL:<EMAIL>END_PI"} :license {:name "The MIT License (MIT)" :url "http://opensource.org/licenses/MIT" :distribution :repo :comments "Please use Overtone for good"} :dependencies [[org.clojure/clojure "1.5.1"] [org.clojure/data.json "0.2.3"] [clj-native "0.9.3"] [overtone/at-at "1.2.0"] [overtone/osc-clj "0.9.0"] [overtone/byte-spec "0.3.1"] [overtone/midi-clj "0.5.0"] [overtone/libs.handlers "0.2.0"] [overtone/scsynth "3.5.7.0"] [overtone/scsynth-extras "3.5.7.0"] [clj-glob "1.0.0"]] :profiles {:test {:dependencies [[bultitude "0.2.0"] [polynome "0.2.2"]]}} :test-selectors {:core (fn [m] (not (some m [:gui :hw]))) :gui :gui :hw :hw} :native-path "native" :min-lein-version "2.0.0" :jvm-opts ^:replace ~(jvm-opts))
[ { "context": "id 1\n :person/name \"Joe\"\n :person/age 20\n ", "end": 951, "score": 0.9998050332069397, "start": 948, "tag": "NAME", "value": "Joe" }, { "context": " :person/name \"Sally\"\n :person/age", "end": 1104, "score": 0.9998289346694946, "start": 1099, "tag": "NAME", "value": "Sally" }, { "context": " :person/spouse {:db/id 1 :person/name \"Joe\"}}})\n :ident [:person/id :db/id]}\n (do", "end": 1240, "score": 0.9997661113739014, "start": 1237, "tag": "NAME", "value": "Joe" } ]
src/book/book/queries/recursive_demo_2.cljs
eihli/fulcro-developer-guide
0
(ns book.queries.recursive-demo-2 (:require [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.mutations :refer [defmutation]] [com.fulcrologic.fulcro.dom :as dom])) (declare ui-person) (defmutation make-older [{:keys [id]}] (action [{:keys [state]}] (swap! state update-in [:person/id id :person/age] inc))) (defsc Person [this {:keys [db/id person/name person/spouse person/age]}] {:query (fn [] [:db/id :person/name :person/age {:person/spouse 1}]) ; force limit the depth :initial-state (fn [p] ; this does look screwy...you can nest the same map in the recursive position, ; and it'll just merge into the one that was previously normalized during normalization. ; You need to do this or you won't get the loop in the database. {:db/id 1 :person/name "Joe" :person/age 20 :person/spouse {:db/id 2 :person/name "Sally" :person/age 22 :person/spouse {:db/id 1 :person/name "Joe"}}}) :ident [:person/id :db/id]} (dom/div (dom/div "Name:" name) (dom/div "Age:" age (dom/button {:onClick #(comp/transact! this `[(make-older {:id ~id})])} "Make Older")) (when spouse (dom/ul (dom/div "Spouse:" (ui-person spouse)))))) (def ui-person (comp/factory Person {:keyfn :db/id})) (defsc Root [this {:keys [person-of-interest]}] {:initial-state {:person-of-interest {}} :query [{:person-of-interest (comp/get-query Person)}]} (dom/div (ui-person person-of-interest)))
90012
(ns book.queries.recursive-demo-2 (:require [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.mutations :refer [defmutation]] [com.fulcrologic.fulcro.dom :as dom])) (declare ui-person) (defmutation make-older [{:keys [id]}] (action [{:keys [state]}] (swap! state update-in [:person/id id :person/age] inc))) (defsc Person [this {:keys [db/id person/name person/spouse person/age]}] {:query (fn [] [:db/id :person/name :person/age {:person/spouse 1}]) ; force limit the depth :initial-state (fn [p] ; this does look screwy...you can nest the same map in the recursive position, ; and it'll just merge into the one that was previously normalized during normalization. ; You need to do this or you won't get the loop in the database. {:db/id 1 :person/name "<NAME>" :person/age 20 :person/spouse {:db/id 2 :person/name "<NAME>" :person/age 22 :person/spouse {:db/id 1 :person/name "<NAME>"}}}) :ident [:person/id :db/id]} (dom/div (dom/div "Name:" name) (dom/div "Age:" age (dom/button {:onClick #(comp/transact! this `[(make-older {:id ~id})])} "Make Older")) (when spouse (dom/ul (dom/div "Spouse:" (ui-person spouse)))))) (def ui-person (comp/factory Person {:keyfn :db/id})) (defsc Root [this {:keys [person-of-interest]}] {:initial-state {:person-of-interest {}} :query [{:person-of-interest (comp/get-query Person)}]} (dom/div (ui-person person-of-interest)))
true
(ns book.queries.recursive-demo-2 (:require [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.mutations :refer [defmutation]] [com.fulcrologic.fulcro.dom :as dom])) (declare ui-person) (defmutation make-older [{:keys [id]}] (action [{:keys [state]}] (swap! state update-in [:person/id id :person/age] inc))) (defsc Person [this {:keys [db/id person/name person/spouse person/age]}] {:query (fn [] [:db/id :person/name :person/age {:person/spouse 1}]) ; force limit the depth :initial-state (fn [p] ; this does look screwy...you can nest the same map in the recursive position, ; and it'll just merge into the one that was previously normalized during normalization. ; You need to do this or you won't get the loop in the database. {:db/id 1 :person/name "PI:NAME:<NAME>END_PI" :person/age 20 :person/spouse {:db/id 2 :person/name "PI:NAME:<NAME>END_PI" :person/age 22 :person/spouse {:db/id 1 :person/name "PI:NAME:<NAME>END_PI"}}}) :ident [:person/id :db/id]} (dom/div (dom/div "Name:" name) (dom/div "Age:" age (dom/button {:onClick #(comp/transact! this `[(make-older {:id ~id})])} "Make Older")) (when spouse (dom/ul (dom/div "Spouse:" (ui-person spouse)))))) (def ui-person (comp/factory Person {:keyfn :db/id})) (defsc Root [this {:keys [person-of-interest]}] {:initial-state {:person-of-interest {}} :query [{:person-of-interest (comp/get-query Person)}]} (dom/div (ui-person person-of-interest)))
[ { "context": "efn auth? [username password]\n (and (= username \"admin\")\n (= password \"pass\")\n {:user userna", "end": 7194, "score": 0.9993541836738586, "start": 7189, "tag": "USERNAME", "value": "admin" }, { "context": "]\n (and (= username \"admin\")\n (= password \"pass\")\n {:user username :password password})\n )", "end": 7221, "score": 0.9993225336074829, "start": 7217, "tag": "PASSWORD", "value": "pass" }, { "context": "enticated [username password]\n (and (= username \"admin\")\n (= password \"pass\")\n {:token \"#You", "end": 7340, "score": 0.9993075132369995, "start": 7335, "tag": "USERNAME", "value": "admin" }, { "context": "]\n (and (= username \"admin\")\n (= password \"pass\")\n {:token \"#You_Are_In!\"})\n )\n\n(defn auth", "end": 7367, "score": 0.9988816976547241, "start": 7363, "tag": "PASSWORD", "value": "pass" }, { "context": "\"admin\")\n (= password \"pass\")\n {:token \"#You_Are_In!\"})\n )\n\n(defn authenticated? [token]\n (= token \"#", "end": 7397, "score": 0.9165696501731873, "start": 7385, "tag": "PASSWORD", "value": "\"#You_Are_In" }, { "context": " }\n\n (let [username (get params \"username\")\n password (get params \"passwo", "end": 8699, "score": 0.9986916184425354, "start": 8691, "tag": "USERNAME", "value": "username" }, { "context": "ername\")\n password (get params \"password\")\n ]\n (do\n ", "end": 8751, "score": 0.9363652467727661, "start": 8743, "tag": "PASSWORD", "value": "password" }, { "context": " :access-control-allow-origin [#\"https://yannmjl.github.io\" #\"http://localhost:4200\"]\n ", "end": 14462, "score": 0.8416424989700317, "start": 14460, "tag": "USERNAME", "value": "jl" } ]
src/report/core.clj
YannMjl/web-server-clojure
0
(ns report.core (:use [clojure.set] [clojure.java.io] [ring.middleware.json] [compojure.core :refer :all] [ring.middleware.token-authentication]) (:require [clojure.java.io] [clojure.data.csv] [cheshire.core :refer :all] [compojure.core :refer :all] [compojure.route :as route] [clojure.java.jdbc :as cj] [clj-time.coerce :as clt] [environ.core :refer [env]] [ring.util.http-response :as http] [ring.adapter.jetty :as jetty] [ring.util.response :refer [response]] [ring.middleware.cors :refer [wrap-cors]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.session :refer [wrap-session]] [ring.middleware.json :refer [wrap-json-response]] [ring.middleware.multipart-params :refer [wrap-multipart-params]] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]]) ) ;----------------------------------------------------------------------------------------------------------------------* ;convert string to integer (defn to-int [s] (if (integer? s) s (try (Integer. s) (catch Exception e nil)) ) ) ;connect to the database (def db-url (System/getenv "DATABASE_URL")) ;(def db-url (env :database-url)) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions that do multiple operation on the csv file in order to * ;get its content and generate a report * ;----------------------------------------------------------------------------------------------------------------------* (defn read-file [file] (clojure.string/split-lines (slurp file))) (defn get-org-id [file] (apply str (->> (clojure.string/split-lines file) (map #(clojure.string/split % #",")) (map #(nth % 1)) (map #(clojure.string/split % #"/")) (map #(nth % 0)) (map #(clojure.string/replace % "\"" "")))) ) (defn get-org-memory [org-name file-line] (->> (filter #(= org-name (get-org-id %)) file-line) (map #(clojure.string/split % #",")) (map #(nth % 2)) (map #(re-find #"(\d+)" %)) (map second) (map to-int) (reduce +) (hash-map :name org-name :size)) ) (defn get-org-and-id [file-line org-list] (map (fn [org-name] (get-org-memory org-name file-line)) org-list) ) (defn get-lines-report [file-lines] (let [org-list (distinct (map #(get-org-id %) file-lines))] (get-org-and-id file-lines org-list)) ) (defn file-report [file] (let [file-line (read-file file)] (get-lines-report file-line)) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions that connect and upload a report into the database * ; * ;----------------------------------------------------------------------------------------------------------------------* (defn insert-report-to-database [report date] (let [_name (:name report) _size (:size report) _date (clt/to-sql-date (clt/to-string date))] (cj/insert! db-url :cloudrepo_report {:organization _name :size _size :date _date}) ) ) (defn upload-report-to-database [report date] (map #(insert-report-to-database % date) report) ) (defn upload-file [file] (let [file-name (file :filename) size (file :size)] (do (file-report file)) ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content queries functions that read the report data stored in the postgres * ;database which returns a sub report by organization name or the data uploaded * ;----------------------------------------------------------------------------------------------------------------------* (defn get-full-report [] (cj/query db-url ["SELECT DISTINCT ON (organization)\n organization, size, date\n FROM cloudrepo_report\n ORDER BY organization"]) ) (defn get-full-report-of-date [] (cj/query db-url ["SELECT DISTINCT ON (date)\n organization, size, date\n FROM cloudrepo_report\n ORDER BY date DESC"]) ) (defn view-by-organization [org-name] (cj/query db-url ["SELECT \"organization\", \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) ORDER BY \"date\" DESC" org-name])) (defn view-by-organization-chart [org-name] (cj/query db-url ["SELECT \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) ORDER BY \"date\" ASC" org-name])) (defn view-by-date [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["SELECT \"organization\", \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"date\" = ?) ORDER BY \"size\" DESC" _date]) ) ) (defn view-by-date-chart [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["SELECT \"organization\", \"size\" FROM \"cloudrepo_report\" WHERE (\"date\" = ?) ORDER BY \"organization\" ASC" _date]) ) ) (defn delete-by-name [org-name] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) RETURNING *" org-name] ) ) (defn delete-by-date [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" WHERE (\"date\" = ?) RETURNING *" _date]) ) ) (defn delete-full-report [] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" RETURNING *"] ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content authentication functions * ; * ;----------------------------------------------------------------------------------------------------------------------* (defn auth? [username password] (and (= username "admin") (= password "pass") {:user username :password password}) ) (defn isAuthenticated [username password] (and (= username "admin") (= password "pass") {:token "#You_Are_In!"}) ) (defn authenticated? [token] (= token "#You_Are_In!") ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions for routes and route handler * ;REST API configurations are also set here * ;----------------------------------------------------------------------------------------------------------------------* (defn app-handler [request] {:status 200 :headers {"Content-Type" "application/json" "Access-Control-Allow-Origin" "*" "Access-Control-Allow-Credentials" "false" "Access-Control-Allow-Methods" "POST, GET, DELETE, OPTIONS" "Access-Control-Allow-Headers" "Accept, Content-Type"} :body (generate-string request)} ) (defroutes login-route (GET "/" [] (generate-string (apply str "<h1>Hello Welcome! This is a report page of CloudRepo users</h1>")) ) (POST "/login" {params :params :as req } (let [username (get params "username") password (get params "password") ] (do (auth? username password) (generate-string (isAuthenticated username password)) ) ) ) ;(route/not-found "<h1>not logged in or does not exit</h1>") ) (defroutes protected-routes (GET "/report" [] (println "in get report") (generate-string (get-full-report)) ) (GET "/date" [] (generate-string (get-full-report-of-date)) ) (GET "/date/:input" [input] (generate-string (view-by-date input)) ) (GET "/date-chart/:input" [input] (generate-string (view-by-date-chart input)) ) (GET "/name/:input" [input] (generate-string (view-by-organization input)) ) (GET "/org/:input" [input] (generate-string (view-by-organization-chart input)) ) (GET "/delete-date/:input" [input] (generate-string (delete-by-date input)) ) (GET "/delete-name/:input" [input] (generate-string (delete-by-name input)) ) (GET "/delete-all-record" [] (generate-string (delete-full-report)) ) (POST "/file" {params :params :as req } (let [fileparam (get params "file") file (:tempfile fileparam) dateparam (get params "date") date (clt/to-string dateparam) report (file-report file)] (generate-string (upload-report-to-database report date)) ) ) (route/not-found "<h1>Page not found or does not exit</h1>") ) ;----------------------------------------------------------------------------------------------------------------------* ;Behold, our middleware! Note that it's common to prefix our middleware name * ;with "wrap-", since it surrounds any routes an other middleware "inside" * ; * ; We can attach our middleware directly to the main application handler. All * ; requests/responses will be "filtered" through our logging handler. * ;----------------------------------------------------------------------------------------------------------------------* (defn allow-cross-origin "Middleware function to allow cross origin requests from browsers. When a browser attempts to call an API from a different domain, it makes an OPTIONS request first to see the server's cross origin policy. So, in this method we return that when an OPTIONs request is made. Additionally, for non OPTIONS requests, we need to just returm the 'Access-Control-Allow-Origin' header or else the browser won't read the data properly. The above notes are all based on how Chrome works. " ([handler] (allow-cross-origin handler "*")) ([handler allowed-origins] (fn [request] (if (= (request :request-method) :options) (-> (http/ok) ; Don't pass the requests down, just return what the browser needs to continue. (assoc-in [:headers "Access-Control-Allow-Origin"] allowed-origins) (assoc-in [:headers "Access-Control-Allow-Methods"] "GET,POST,DELETE") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With,Content-Type,Cache-Control,Origin,Accept,Authorization") (assoc :status 200) ) (-> (handler request) ; Pass the request on, but make sure we add this header for CORS support in Chrome. (assoc-in [:headers "Access-Control-Allow-Origin"] allowed-origins)))) ) ) (defn wrap-log-request [handler] (fn [req] ; return handler function (println req) ; perform logging (handler req)) ; pass the request through to the inner handler ) (def log-route (-> login-route wrap-log-request wrap-json-response)) (def secured-routes (-> protected-routes wrap-log-request wrap-json-response ;(wrap-basic-authentication auth?) ;(wrap-token-authentication authenticated?) ) ; With this middleware in place, we are all set to parse JSON request bodies and ; serve up JSON responses ) (def main-routes (-> (routes log-route secured-routes) (allow-cross-origin) ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content the main function that start the server * ;on local host port 5000 * ;----------------------------------------------------------------------------------------------------------------------* (defn -main [& [port]] (let [port (Integer. (or port (env :port) 5000))] (jetty/run-jetty (wrap-cors (wrap-multipart-params main-routes) :access-control-allow-methods #{:get :post :delete :options} :access-control-allow-headers #{:accept :content-type} :access-control-allow-origin [#"https://yannmjl.github.io" #"http://localhost:4200"] ) {:port port :join? false} ) ) ) ;----------------------------------------------------------------------------------------------------------------------*
96899
(ns report.core (:use [clojure.set] [clojure.java.io] [ring.middleware.json] [compojure.core :refer :all] [ring.middleware.token-authentication]) (:require [clojure.java.io] [clojure.data.csv] [cheshire.core :refer :all] [compojure.core :refer :all] [compojure.route :as route] [clojure.java.jdbc :as cj] [clj-time.coerce :as clt] [environ.core :refer [env]] [ring.util.http-response :as http] [ring.adapter.jetty :as jetty] [ring.util.response :refer [response]] [ring.middleware.cors :refer [wrap-cors]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.session :refer [wrap-session]] [ring.middleware.json :refer [wrap-json-response]] [ring.middleware.multipart-params :refer [wrap-multipart-params]] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]]) ) ;----------------------------------------------------------------------------------------------------------------------* ;convert string to integer (defn to-int [s] (if (integer? s) s (try (Integer. s) (catch Exception e nil)) ) ) ;connect to the database (def db-url (System/getenv "DATABASE_URL")) ;(def db-url (env :database-url)) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions that do multiple operation on the csv file in order to * ;get its content and generate a report * ;----------------------------------------------------------------------------------------------------------------------* (defn read-file [file] (clojure.string/split-lines (slurp file))) (defn get-org-id [file] (apply str (->> (clojure.string/split-lines file) (map #(clojure.string/split % #",")) (map #(nth % 1)) (map #(clojure.string/split % #"/")) (map #(nth % 0)) (map #(clojure.string/replace % "\"" "")))) ) (defn get-org-memory [org-name file-line] (->> (filter #(= org-name (get-org-id %)) file-line) (map #(clojure.string/split % #",")) (map #(nth % 2)) (map #(re-find #"(\d+)" %)) (map second) (map to-int) (reduce +) (hash-map :name org-name :size)) ) (defn get-org-and-id [file-line org-list] (map (fn [org-name] (get-org-memory org-name file-line)) org-list) ) (defn get-lines-report [file-lines] (let [org-list (distinct (map #(get-org-id %) file-lines))] (get-org-and-id file-lines org-list)) ) (defn file-report [file] (let [file-line (read-file file)] (get-lines-report file-line)) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions that connect and upload a report into the database * ; * ;----------------------------------------------------------------------------------------------------------------------* (defn insert-report-to-database [report date] (let [_name (:name report) _size (:size report) _date (clt/to-sql-date (clt/to-string date))] (cj/insert! db-url :cloudrepo_report {:organization _name :size _size :date _date}) ) ) (defn upload-report-to-database [report date] (map #(insert-report-to-database % date) report) ) (defn upload-file [file] (let [file-name (file :filename) size (file :size)] (do (file-report file)) ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content queries functions that read the report data stored in the postgres * ;database which returns a sub report by organization name or the data uploaded * ;----------------------------------------------------------------------------------------------------------------------* (defn get-full-report [] (cj/query db-url ["SELECT DISTINCT ON (organization)\n organization, size, date\n FROM cloudrepo_report\n ORDER BY organization"]) ) (defn get-full-report-of-date [] (cj/query db-url ["SELECT DISTINCT ON (date)\n organization, size, date\n FROM cloudrepo_report\n ORDER BY date DESC"]) ) (defn view-by-organization [org-name] (cj/query db-url ["SELECT \"organization\", \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) ORDER BY \"date\" DESC" org-name])) (defn view-by-organization-chart [org-name] (cj/query db-url ["SELECT \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) ORDER BY \"date\" ASC" org-name])) (defn view-by-date [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["SELECT \"organization\", \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"date\" = ?) ORDER BY \"size\" DESC" _date]) ) ) (defn view-by-date-chart [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["SELECT \"organization\", \"size\" FROM \"cloudrepo_report\" WHERE (\"date\" = ?) ORDER BY \"organization\" ASC" _date]) ) ) (defn delete-by-name [org-name] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) RETURNING *" org-name] ) ) (defn delete-by-date [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" WHERE (\"date\" = ?) RETURNING *" _date]) ) ) (defn delete-full-report [] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" RETURNING *"] ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content authentication functions * ; * ;----------------------------------------------------------------------------------------------------------------------* (defn auth? [username password] (and (= username "admin") (= password "<PASSWORD>") {:user username :password password}) ) (defn isAuthenticated [username password] (and (= username "admin") (= password "<PASSWORD>") {:token <PASSWORD>!"}) ) (defn authenticated? [token] (= token "#You_Are_In!") ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions for routes and route handler * ;REST API configurations are also set here * ;----------------------------------------------------------------------------------------------------------------------* (defn app-handler [request] {:status 200 :headers {"Content-Type" "application/json" "Access-Control-Allow-Origin" "*" "Access-Control-Allow-Credentials" "false" "Access-Control-Allow-Methods" "POST, GET, DELETE, OPTIONS" "Access-Control-Allow-Headers" "Accept, Content-Type"} :body (generate-string request)} ) (defroutes login-route (GET "/" [] (generate-string (apply str "<h1>Hello Welcome! This is a report page of CloudRepo users</h1>")) ) (POST "/login" {params :params :as req } (let [username (get params "username") password (get params "<PASSWORD>") ] (do (auth? username password) (generate-string (isAuthenticated username password)) ) ) ) ;(route/not-found "<h1>not logged in or does not exit</h1>") ) (defroutes protected-routes (GET "/report" [] (println "in get report") (generate-string (get-full-report)) ) (GET "/date" [] (generate-string (get-full-report-of-date)) ) (GET "/date/:input" [input] (generate-string (view-by-date input)) ) (GET "/date-chart/:input" [input] (generate-string (view-by-date-chart input)) ) (GET "/name/:input" [input] (generate-string (view-by-organization input)) ) (GET "/org/:input" [input] (generate-string (view-by-organization-chart input)) ) (GET "/delete-date/:input" [input] (generate-string (delete-by-date input)) ) (GET "/delete-name/:input" [input] (generate-string (delete-by-name input)) ) (GET "/delete-all-record" [] (generate-string (delete-full-report)) ) (POST "/file" {params :params :as req } (let [fileparam (get params "file") file (:tempfile fileparam) dateparam (get params "date") date (clt/to-string dateparam) report (file-report file)] (generate-string (upload-report-to-database report date)) ) ) (route/not-found "<h1>Page not found or does not exit</h1>") ) ;----------------------------------------------------------------------------------------------------------------------* ;Behold, our middleware! Note that it's common to prefix our middleware name * ;with "wrap-", since it surrounds any routes an other middleware "inside" * ; * ; We can attach our middleware directly to the main application handler. All * ; requests/responses will be "filtered" through our logging handler. * ;----------------------------------------------------------------------------------------------------------------------* (defn allow-cross-origin "Middleware function to allow cross origin requests from browsers. When a browser attempts to call an API from a different domain, it makes an OPTIONS request first to see the server's cross origin policy. So, in this method we return that when an OPTIONs request is made. Additionally, for non OPTIONS requests, we need to just returm the 'Access-Control-Allow-Origin' header or else the browser won't read the data properly. The above notes are all based on how Chrome works. " ([handler] (allow-cross-origin handler "*")) ([handler allowed-origins] (fn [request] (if (= (request :request-method) :options) (-> (http/ok) ; Don't pass the requests down, just return what the browser needs to continue. (assoc-in [:headers "Access-Control-Allow-Origin"] allowed-origins) (assoc-in [:headers "Access-Control-Allow-Methods"] "GET,POST,DELETE") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With,Content-Type,Cache-Control,Origin,Accept,Authorization") (assoc :status 200) ) (-> (handler request) ; Pass the request on, but make sure we add this header for CORS support in Chrome. (assoc-in [:headers "Access-Control-Allow-Origin"] allowed-origins)))) ) ) (defn wrap-log-request [handler] (fn [req] ; return handler function (println req) ; perform logging (handler req)) ; pass the request through to the inner handler ) (def log-route (-> login-route wrap-log-request wrap-json-response)) (def secured-routes (-> protected-routes wrap-log-request wrap-json-response ;(wrap-basic-authentication auth?) ;(wrap-token-authentication authenticated?) ) ; With this middleware in place, we are all set to parse JSON request bodies and ; serve up JSON responses ) (def main-routes (-> (routes log-route secured-routes) (allow-cross-origin) ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content the main function that start the server * ;on local host port 5000 * ;----------------------------------------------------------------------------------------------------------------------* (defn -main [& [port]] (let [port (Integer. (or port (env :port) 5000))] (jetty/run-jetty (wrap-cors (wrap-multipart-params main-routes) :access-control-allow-methods #{:get :post :delete :options} :access-control-allow-headers #{:accept :content-type} :access-control-allow-origin [#"https://yannmjl.github.io" #"http://localhost:4200"] ) {:port port :join? false} ) ) ) ;----------------------------------------------------------------------------------------------------------------------*
true
(ns report.core (:use [clojure.set] [clojure.java.io] [ring.middleware.json] [compojure.core :refer :all] [ring.middleware.token-authentication]) (:require [clojure.java.io] [clojure.data.csv] [cheshire.core :refer :all] [compojure.core :refer :all] [compojure.route :as route] [clojure.java.jdbc :as cj] [clj-time.coerce :as clt] [environ.core :refer [env]] [ring.util.http-response :as http] [ring.adapter.jetty :as jetty] [ring.util.response :refer [response]] [ring.middleware.cors :refer [wrap-cors]] [ring.middleware.params :refer [wrap-params]] [ring.middleware.session :refer [wrap-session]] [ring.middleware.json :refer [wrap-json-response]] [ring.middleware.multipart-params :refer [wrap-multipart-params]] [ring.middleware.basic-authentication :refer [wrap-basic-authentication]]) ) ;----------------------------------------------------------------------------------------------------------------------* ;convert string to integer (defn to-int [s] (if (integer? s) s (try (Integer. s) (catch Exception e nil)) ) ) ;connect to the database (def db-url (System/getenv "DATABASE_URL")) ;(def db-url (env :database-url)) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions that do multiple operation on the csv file in order to * ;get its content and generate a report * ;----------------------------------------------------------------------------------------------------------------------* (defn read-file [file] (clojure.string/split-lines (slurp file))) (defn get-org-id [file] (apply str (->> (clojure.string/split-lines file) (map #(clojure.string/split % #",")) (map #(nth % 1)) (map #(clojure.string/split % #"/")) (map #(nth % 0)) (map #(clojure.string/replace % "\"" "")))) ) (defn get-org-memory [org-name file-line] (->> (filter #(= org-name (get-org-id %)) file-line) (map #(clojure.string/split % #",")) (map #(nth % 2)) (map #(re-find #"(\d+)" %)) (map second) (map to-int) (reduce +) (hash-map :name org-name :size)) ) (defn get-org-and-id [file-line org-list] (map (fn [org-name] (get-org-memory org-name file-line)) org-list) ) (defn get-lines-report [file-lines] (let [org-list (distinct (map #(get-org-id %) file-lines))] (get-org-and-id file-lines org-list)) ) (defn file-report [file] (let [file-line (read-file file)] (get-lines-report file-line)) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions that connect and upload a report into the database * ; * ;----------------------------------------------------------------------------------------------------------------------* (defn insert-report-to-database [report date] (let [_name (:name report) _size (:size report) _date (clt/to-sql-date (clt/to-string date))] (cj/insert! db-url :cloudrepo_report {:organization _name :size _size :date _date}) ) ) (defn upload-report-to-database [report date] (map #(insert-report-to-database % date) report) ) (defn upload-file [file] (let [file-name (file :filename) size (file :size)] (do (file-report file)) ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content queries functions that read the report data stored in the postgres * ;database which returns a sub report by organization name or the data uploaded * ;----------------------------------------------------------------------------------------------------------------------* (defn get-full-report [] (cj/query db-url ["SELECT DISTINCT ON (organization)\n organization, size, date\n FROM cloudrepo_report\n ORDER BY organization"]) ) (defn get-full-report-of-date [] (cj/query db-url ["SELECT DISTINCT ON (date)\n organization, size, date\n FROM cloudrepo_report\n ORDER BY date DESC"]) ) (defn view-by-organization [org-name] (cj/query db-url ["SELECT \"organization\", \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) ORDER BY \"date\" DESC" org-name])) (defn view-by-organization-chart [org-name] (cj/query db-url ["SELECT \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) ORDER BY \"date\" ASC" org-name])) (defn view-by-date [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["SELECT \"organization\", \"size\", \"date\" FROM \"cloudrepo_report\" WHERE (\"date\" = ?) ORDER BY \"size\" DESC" _date]) ) ) (defn view-by-date-chart [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["SELECT \"organization\", \"size\" FROM \"cloudrepo_report\" WHERE (\"date\" = ?) ORDER BY \"organization\" ASC" _date]) ) ) (defn delete-by-name [org-name] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" WHERE (\"organization\" = ?) RETURNING *" org-name] ) ) (defn delete-by-date [input] (let [_date (clt/to-sql-date (clt/to-string input))] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" WHERE (\"date\" = ?) RETURNING *" _date]) ) ) (defn delete-full-report [] (cj/query db-url ["DELETE FROM \"cloudrepo_report\" RETURNING *"] ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content authentication functions * ; * ;----------------------------------------------------------------------------------------------------------------------* (defn auth? [username password] (and (= username "admin") (= password "PI:PASSWORD:<PASSWORD>END_PI") {:user username :password password}) ) (defn isAuthenticated [username password] (and (= username "admin") (= password "PI:PASSWORD:<PASSWORD>END_PI") {:token PI:PASSWORD:<PASSWORD>END_PI!"}) ) (defn authenticated? [token] (= token "#You_Are_In!") ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content functions for routes and route handler * ;REST API configurations are also set here * ;----------------------------------------------------------------------------------------------------------------------* (defn app-handler [request] {:status 200 :headers {"Content-Type" "application/json" "Access-Control-Allow-Origin" "*" "Access-Control-Allow-Credentials" "false" "Access-Control-Allow-Methods" "POST, GET, DELETE, OPTIONS" "Access-Control-Allow-Headers" "Accept, Content-Type"} :body (generate-string request)} ) (defroutes login-route (GET "/" [] (generate-string (apply str "<h1>Hello Welcome! This is a report page of CloudRepo users</h1>")) ) (POST "/login" {params :params :as req } (let [username (get params "username") password (get params "PI:PASSWORD:<PASSWORD>END_PI") ] (do (auth? username password) (generate-string (isAuthenticated username password)) ) ) ) ;(route/not-found "<h1>not logged in or does not exit</h1>") ) (defroutes protected-routes (GET "/report" [] (println "in get report") (generate-string (get-full-report)) ) (GET "/date" [] (generate-string (get-full-report-of-date)) ) (GET "/date/:input" [input] (generate-string (view-by-date input)) ) (GET "/date-chart/:input" [input] (generate-string (view-by-date-chart input)) ) (GET "/name/:input" [input] (generate-string (view-by-organization input)) ) (GET "/org/:input" [input] (generate-string (view-by-organization-chart input)) ) (GET "/delete-date/:input" [input] (generate-string (delete-by-date input)) ) (GET "/delete-name/:input" [input] (generate-string (delete-by-name input)) ) (GET "/delete-all-record" [] (generate-string (delete-full-report)) ) (POST "/file" {params :params :as req } (let [fileparam (get params "file") file (:tempfile fileparam) dateparam (get params "date") date (clt/to-string dateparam) report (file-report file)] (generate-string (upload-report-to-database report date)) ) ) (route/not-found "<h1>Page not found or does not exit</h1>") ) ;----------------------------------------------------------------------------------------------------------------------* ;Behold, our middleware! Note that it's common to prefix our middleware name * ;with "wrap-", since it surrounds any routes an other middleware "inside" * ; * ; We can attach our middleware directly to the main application handler. All * ; requests/responses will be "filtered" through our logging handler. * ;----------------------------------------------------------------------------------------------------------------------* (defn allow-cross-origin "Middleware function to allow cross origin requests from browsers. When a browser attempts to call an API from a different domain, it makes an OPTIONS request first to see the server's cross origin policy. So, in this method we return that when an OPTIONs request is made. Additionally, for non OPTIONS requests, we need to just returm the 'Access-Control-Allow-Origin' header or else the browser won't read the data properly. The above notes are all based on how Chrome works. " ([handler] (allow-cross-origin handler "*")) ([handler allowed-origins] (fn [request] (if (= (request :request-method) :options) (-> (http/ok) ; Don't pass the requests down, just return what the browser needs to continue. (assoc-in [:headers "Access-Control-Allow-Origin"] allowed-origins) (assoc-in [:headers "Access-Control-Allow-Methods"] "GET,POST,DELETE") (assoc-in [:headers "Access-Control-Allow-Headers"] "X-Requested-With,Content-Type,Cache-Control,Origin,Accept,Authorization") (assoc :status 200) ) (-> (handler request) ; Pass the request on, but make sure we add this header for CORS support in Chrome. (assoc-in [:headers "Access-Control-Allow-Origin"] allowed-origins)))) ) ) (defn wrap-log-request [handler] (fn [req] ; return handler function (println req) ; perform logging (handler req)) ; pass the request through to the inner handler ) (def log-route (-> login-route wrap-log-request wrap-json-response)) (def secured-routes (-> protected-routes wrap-log-request wrap-json-response ;(wrap-basic-authentication auth?) ;(wrap-token-authentication authenticated?) ) ; With this middleware in place, we are all set to parse JSON request bodies and ; serve up JSON responses ) (def main-routes (-> (routes log-route secured-routes) (allow-cross-origin) ) ) ;----------------------------------------------------------------------------------------------------------------------* ;this section content the main function that start the server * ;on local host port 5000 * ;----------------------------------------------------------------------------------------------------------------------* (defn -main [& [port]] (let [port (Integer. (or port (env :port) 5000))] (jetty/run-jetty (wrap-cors (wrap-multipart-params main-routes) :access-control-allow-methods #{:get :post :delete :options} :access-control-allow-headers #{:accept :content-type} :access-control-allow-origin [#"https://yannmjl.github.io" #"http://localhost:4200"] ) {:port port :join? false} ) ) ) ;----------------------------------------------------------------------------------------------------------------------*
[ { "context": "nt {:db con}\n {:name \"some author\"\n :text \"some text\"\n", "end": 2299, "score": 0.6338924169540405, "start": 2288, "tag": "USERNAME", "value": "some author" }, { "context": " (are [k v] (= (k c) v)\n :name \"some author\"\n :text \"some text\")\n ", "end": 2617, "score": 0.5584309101104736, "start": 2613, "tag": "NAME", "value": "some" }, { "context": " (are [k v] (= (k c) v)\n :name \"some author\"\n :text \"some text\")\n (is ", "end": 2624, "score": 0.4964170455932617, "start": 2618, "tag": "USERNAME", "value": "author" } ]
data/test/clojure/b121c8fdc1e9a82fc6ee4de354fa34c06a1f283acomment_sql_datastore_impl_test.clj
harshp8l/deep-learning-lang-detection
84
(ns blog.comment.comment-sql-datastore-impl-test (:require [clojure.test :refer :all] [blog.comment.comment-sql-datastore-impl :refer :all] [clojure.java.jdbc :as jdbc])) ; test functions that operate on the database (deftest database-operations (let [db-spec {:subprotocol "hsqldb" :subname (str "mem:testdb" ";shutdown=true" ";sql.syntax_pgs=true") :user "SA" :password ""}] (jdbc/with-db-connection [con db-spec] (testing "create-comment-table" (is (= (create-comment-table {:db con}) :ok))) (testing "save-comment" (is (= (save-comment {:db con} {:name "some author" :text "some text" :time (java.util.Date.)} "the-article") :ok))) (testing "select-comments" (let [[c] (select-comments {:db con} "the-article")] (are [k v] (= (k c) v) :name "some author" :text "some text")) (is (= (select-comments {:db con} "the-wrong-article") []))) (testing "select-comment-count" (is (= (select-comment-count con "the-article") 1)) (is (= (select-comment-count con "the-wrong-article") 0))) (testing "select-comment-counts" (is (= (select-comment-counts {:db con} ["the-article"]) {"the-article" 1})) (is (= (select-comment-counts {:db con} ["the-wrong-article"]) {"the-wrong-article" 0})))))) ; test functions that manage the database entries (deftest database-management-operations (let [db-spec {:subprotocol "hsqldb" :subname (str "mem:testdb" ";shutdown=true" ";sql.syntax_pgs=true") :user "SA" :password ""}] (jdbc/with-db-connection [con db-spec] (testing "create-comment-table" (is (= (create-comment-table {:db con}) :ok))) (testing "save-comment" (is (= (save-comment {:db con} {:name "some author" :text "some text" :time (java.util.Date.)} "the-article") :ok))) (testing "delete-comment" (let [[c] (select-comments {:db con} "the-article")] (are [k v] (= (k c) v) :name "some author" :text "some text") (is (= (delete-comment {:db con} (str (:id c))) :ok)) (is (= (select-comments {:db con} "the-article") [])))))))
121639
(ns blog.comment.comment-sql-datastore-impl-test (:require [clojure.test :refer :all] [blog.comment.comment-sql-datastore-impl :refer :all] [clojure.java.jdbc :as jdbc])) ; test functions that operate on the database (deftest database-operations (let [db-spec {:subprotocol "hsqldb" :subname (str "mem:testdb" ";shutdown=true" ";sql.syntax_pgs=true") :user "SA" :password ""}] (jdbc/with-db-connection [con db-spec] (testing "create-comment-table" (is (= (create-comment-table {:db con}) :ok))) (testing "save-comment" (is (= (save-comment {:db con} {:name "some author" :text "some text" :time (java.util.Date.)} "the-article") :ok))) (testing "select-comments" (let [[c] (select-comments {:db con} "the-article")] (are [k v] (= (k c) v) :name "some author" :text "some text")) (is (= (select-comments {:db con} "the-wrong-article") []))) (testing "select-comment-count" (is (= (select-comment-count con "the-article") 1)) (is (= (select-comment-count con "the-wrong-article") 0))) (testing "select-comment-counts" (is (= (select-comment-counts {:db con} ["the-article"]) {"the-article" 1})) (is (= (select-comment-counts {:db con} ["the-wrong-article"]) {"the-wrong-article" 0})))))) ; test functions that manage the database entries (deftest database-management-operations (let [db-spec {:subprotocol "hsqldb" :subname (str "mem:testdb" ";shutdown=true" ";sql.syntax_pgs=true") :user "SA" :password ""}] (jdbc/with-db-connection [con db-spec] (testing "create-comment-table" (is (= (create-comment-table {:db con}) :ok))) (testing "save-comment" (is (= (save-comment {:db con} {:name "some author" :text "some text" :time (java.util.Date.)} "the-article") :ok))) (testing "delete-comment" (let [[c] (select-comments {:db con} "the-article")] (are [k v] (= (k c) v) :name "<NAME> author" :text "some text") (is (= (delete-comment {:db con} (str (:id c))) :ok)) (is (= (select-comments {:db con} "the-article") [])))))))
true
(ns blog.comment.comment-sql-datastore-impl-test (:require [clojure.test :refer :all] [blog.comment.comment-sql-datastore-impl :refer :all] [clojure.java.jdbc :as jdbc])) ; test functions that operate on the database (deftest database-operations (let [db-spec {:subprotocol "hsqldb" :subname (str "mem:testdb" ";shutdown=true" ";sql.syntax_pgs=true") :user "SA" :password ""}] (jdbc/with-db-connection [con db-spec] (testing "create-comment-table" (is (= (create-comment-table {:db con}) :ok))) (testing "save-comment" (is (= (save-comment {:db con} {:name "some author" :text "some text" :time (java.util.Date.)} "the-article") :ok))) (testing "select-comments" (let [[c] (select-comments {:db con} "the-article")] (are [k v] (= (k c) v) :name "some author" :text "some text")) (is (= (select-comments {:db con} "the-wrong-article") []))) (testing "select-comment-count" (is (= (select-comment-count con "the-article") 1)) (is (= (select-comment-count con "the-wrong-article") 0))) (testing "select-comment-counts" (is (= (select-comment-counts {:db con} ["the-article"]) {"the-article" 1})) (is (= (select-comment-counts {:db con} ["the-wrong-article"]) {"the-wrong-article" 0})))))) ; test functions that manage the database entries (deftest database-management-operations (let [db-spec {:subprotocol "hsqldb" :subname (str "mem:testdb" ";shutdown=true" ";sql.syntax_pgs=true") :user "SA" :password ""}] (jdbc/with-db-connection [con db-spec] (testing "create-comment-table" (is (= (create-comment-table {:db con}) :ok))) (testing "save-comment" (is (= (save-comment {:db con} {:name "some author" :text "some text" :time (java.util.Date.)} "the-article") :ok))) (testing "delete-comment" (let [[c] (select-comments {:db con} "the-article")] (are [k v] (= (k c) v) :name "PI:NAME:<NAME>END_PI author" :text "some text") (is (= (delete-comment {:db con} (str (:id c))) :ok)) (is (= (select-comments {:db con} "the-article") [])))))))
[ { "context": "hange communication\n;;;;\n;;;; @copyright 2017-2020 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------", "end": 429, "score": 0.9998820424079895, "start": 417, "tag": "NAME", "value": "Dennis Drown" } ]
apps/say_sila/priv/fnode/say/src/weka/core.clj
dendrown/say_sila
0
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Emotion Mining and Machine Learning for Climate Change communication ;;;; ;;;; @copyright 2017-2020 Dennis Drown et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns weka.core (:require [say.genie :refer :all] [say.log :as log] [clojure.java.io :as io] [clojure.string :as str]) (:import [weka.core Instance Instances] [weka.classifiers AbstractClassifier Evaluation] [weka.core.converters AbstractSaver ArffLoader ArffSaver CSVSaver] [weka.filters Filter])) (set! *warn-on-reflection* true) ;;; -------------------------------------------------------------------------- (defprotocol Indexer "Facilitate getting an index from Weka entities. This is currently a trial protocol, expected to grow as we go..." (get-index [entity ^String tag] "Return an index by the column name (tag)")) (extend-protocol Indexer Instances (get-index [insts ^String tag] (.index (.attribute insts tag)))) ;;; -------------------------------------------------------------------------- (defn ^String index0->1 "Converts a 0-based (numeric or string) index to a 1-based String." [i] (str (inc (longify i)))) ;;; -------------------------------------------------------------------------- (defn ^Long index1->0 "Converts a 1-based (numeric or string) index to a 0-based Long." [i] (dec (longify i))) ;; --------------------------------------------------------------------------- (defn attribute-seq " Returns an sequence of the attriutes in the specified dataset. " [^Instances insts] (enumeration-seq (.enumerateAttributes insts))) ;; --------------------------------------------------------------------------- (defn instance-seq " Returns an sequence of the instances in the specified dataset. " [^Instances insts] (enumeration-seq (.enumerateInstances insts))) ;;; -------------------------------------------------------------------------- (defn tag-filename "Turns «/path/to/filename.extn» into «/path/to/filename.tag.EXTN», where EXTN is the specified file type (ftype, which defaults to the origin extension). If ftype is a collection of extensions, e.g. [:arff :csv], then the function returns a map, keyed by these extensions, whose data elements are the tagged versions of fpath." ([fpath tag] (tag-filename fpath tag nil)) ([fpath tag ftype] (let [parts (str/split fpath #"\.") stub (str/join "." (flatten [(butlast parts) (name tag)])) ->tag #(str stub "." (name %))] (cond (coll? ftype) (into {} (map #(vector % (->tag %)) ftype)) ftype (->tag ftype) :else (->tag (last parts)))))) ;;; -------------------------------------------------------------------------- (defn save-file "Writes out the given Instances to the specified ARFF or CSV file. The caller may specify a filetag, which will be inserted into the filename as «/path/to/filename.tag.extn». The default file type is :arff. Returns the filename again as a convenience." ([fpath data] (save-file fpath data :arff)) ([^String fpath ^Instances data ftype] ;(log/debug "FPATH:" fpath) (let [saver (case ftype :arff (ArffSaver.) :csv (CSVSaver.)) fout (io/file fpath)] (.createNewFile fout) (doto ^AbstractSaver saver (.setFile fout) (.setInstances data) (.writeBatch)) fpath)) ([fpath tag data ftype] (save-file (tag-filename fpath tag ftype) data ftype))) ;;; -------------------------------------------------------------------------- (defn save-results "Writes out the given Instances as tagged ARFF and CSV files and returns a filetype-keyed map with the corresponding filename values." [fpath tag data] (let [tag-fpaths (tag-filename fpath tag [:arff :csv])] {:arff (save-file (:arff tag-fpaths) data :arff) :csv (save-file (:csv tag-fpaths) data :csv)})) ;;; -------------------------------------------------------------------------- (defn ^Instances filter-instances "Applies a filter to the specified data Instances." ([data sieve] (filter-instances data sieve [])) ([^Instances data ^Filter sieve opts] (when (not-empty opts) (.setOptions sieve (into-array String opts))) (.setInputFormat sieve data) (Filter/useFilter data sieve))) ;;; -------------------------------------------------------------------------- (defn ^AbstractClassifier make-learner "Instantiates/configures a Weka learning algorithm based on the specified tag." [tag] (let [pke #(str "weka.classifiers.functions.supportVector.PolyKernel -E " %) alg (first (str/split tag #"_")) ^AbstractClassifier learner (case alg "lreg" (weka.classifiers.functions.LinearRegression.) "gproc" (weka.classifiers.functions.GaussianProcesses.) "smo" (weka.classifiers.functions.SMOreg.) "m5rules" (weka.classifiers.rules.M5Rules.) "rforest" (weka.classifiers.trees.RandomForest.))] ;; Instantiate the learner and handle any non-default parameters (when (some #{"gproc_2" "smo_2"} [tag]) (.setOptions learner (into-array ["-K" (pke 2)]))) learner)) ;;; -------------------------------------------------------------------------- (defn- ^Instances prep-instances "Intended as a utility function for load-arff and load-data. This function sets the target class, if specified, and performs data filtering." [^Instances insts target filters] ;; Set the target if we know what it is (when target (.setClass insts (.attribute insts (name target)))) ; Apply any requested filters. (reduce #(filter-instances %1 %2) insts filters)) ;;; -------------------------------------------------------------------------- (defn ^Instances load-arff "Reads in and returns the Instances from the specified ARFF file. The caller may specify any number of filter keywords after the target attribute (or nil to specifically skip setting a class attribute)." ([fpath] (load-arff fpath nil)) ([fpath target & filters] ;; Perform Weka ARFF load and prepare Instances (-> (doto (ArffLoader.) (.setFile (io/file fpath))) (.getDataSet) (prep-instances target filters)))) ;;; -------------------------------------------------------------------------- (defn ^Instances load-dataset "Accepts either an ARFF filepath or a preloaded set of Instances. The function prepares the dataset by setting the target class and applying the specified filters if any." ([fpath] (load-dataset fpath nil)) ([data target & filters] (if (string? data) (apply load-arff data target filters) (prep-instances data target filters)))) ;;; -------------------------------------------------------------------------- (defn white-box? "Returns true if the specified algorithm is considered a «white box model», whose results are generally explainable and interpretable by a human being." [model] ;; FIXME this set is not complete! (contains? #{weka.classifiers.functions.LinearRegression weka.classifiers.functions.Logistic ;weka.classifiers.rules.M5Rules weka.classifiers.trees.J48} (type model))) ;;; -------------------------------------------------------------------------- (defn black-box? "Returns true if the specified algorithm is considered a «black box model», whose results are not readily explainable. " [model] ;; I don't know anybody else...🎵 (not (white-box? model)))
33572
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Emotion Mining and Machine Learning for Climate Change communication ;;;; ;;;; @copyright 2017-2020 <NAME> et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns weka.core (:require [say.genie :refer :all] [say.log :as log] [clojure.java.io :as io] [clojure.string :as str]) (:import [weka.core Instance Instances] [weka.classifiers AbstractClassifier Evaluation] [weka.core.converters AbstractSaver ArffLoader ArffSaver CSVSaver] [weka.filters Filter])) (set! *warn-on-reflection* true) ;;; -------------------------------------------------------------------------- (defprotocol Indexer "Facilitate getting an index from Weka entities. This is currently a trial protocol, expected to grow as we go..." (get-index [entity ^String tag] "Return an index by the column name (tag)")) (extend-protocol Indexer Instances (get-index [insts ^String tag] (.index (.attribute insts tag)))) ;;; -------------------------------------------------------------------------- (defn ^String index0->1 "Converts a 0-based (numeric or string) index to a 1-based String." [i] (str (inc (longify i)))) ;;; -------------------------------------------------------------------------- (defn ^Long index1->0 "Converts a 1-based (numeric or string) index to a 0-based Long." [i] (dec (longify i))) ;; --------------------------------------------------------------------------- (defn attribute-seq " Returns an sequence of the attriutes in the specified dataset. " [^Instances insts] (enumeration-seq (.enumerateAttributes insts))) ;; --------------------------------------------------------------------------- (defn instance-seq " Returns an sequence of the instances in the specified dataset. " [^Instances insts] (enumeration-seq (.enumerateInstances insts))) ;;; -------------------------------------------------------------------------- (defn tag-filename "Turns «/path/to/filename.extn» into «/path/to/filename.tag.EXTN», where EXTN is the specified file type (ftype, which defaults to the origin extension). If ftype is a collection of extensions, e.g. [:arff :csv], then the function returns a map, keyed by these extensions, whose data elements are the tagged versions of fpath." ([fpath tag] (tag-filename fpath tag nil)) ([fpath tag ftype] (let [parts (str/split fpath #"\.") stub (str/join "." (flatten [(butlast parts) (name tag)])) ->tag #(str stub "." (name %))] (cond (coll? ftype) (into {} (map #(vector % (->tag %)) ftype)) ftype (->tag ftype) :else (->tag (last parts)))))) ;;; -------------------------------------------------------------------------- (defn save-file "Writes out the given Instances to the specified ARFF or CSV file. The caller may specify a filetag, which will be inserted into the filename as «/path/to/filename.tag.extn». The default file type is :arff. Returns the filename again as a convenience." ([fpath data] (save-file fpath data :arff)) ([^String fpath ^Instances data ftype] ;(log/debug "FPATH:" fpath) (let [saver (case ftype :arff (ArffSaver.) :csv (CSVSaver.)) fout (io/file fpath)] (.createNewFile fout) (doto ^AbstractSaver saver (.setFile fout) (.setInstances data) (.writeBatch)) fpath)) ([fpath tag data ftype] (save-file (tag-filename fpath tag ftype) data ftype))) ;;; -------------------------------------------------------------------------- (defn save-results "Writes out the given Instances as tagged ARFF and CSV files and returns a filetype-keyed map with the corresponding filename values." [fpath tag data] (let [tag-fpaths (tag-filename fpath tag [:arff :csv])] {:arff (save-file (:arff tag-fpaths) data :arff) :csv (save-file (:csv tag-fpaths) data :csv)})) ;;; -------------------------------------------------------------------------- (defn ^Instances filter-instances "Applies a filter to the specified data Instances." ([data sieve] (filter-instances data sieve [])) ([^Instances data ^Filter sieve opts] (when (not-empty opts) (.setOptions sieve (into-array String opts))) (.setInputFormat sieve data) (Filter/useFilter data sieve))) ;;; -------------------------------------------------------------------------- (defn ^AbstractClassifier make-learner "Instantiates/configures a Weka learning algorithm based on the specified tag." [tag] (let [pke #(str "weka.classifiers.functions.supportVector.PolyKernel -E " %) alg (first (str/split tag #"_")) ^AbstractClassifier learner (case alg "lreg" (weka.classifiers.functions.LinearRegression.) "gproc" (weka.classifiers.functions.GaussianProcesses.) "smo" (weka.classifiers.functions.SMOreg.) "m5rules" (weka.classifiers.rules.M5Rules.) "rforest" (weka.classifiers.trees.RandomForest.))] ;; Instantiate the learner and handle any non-default parameters (when (some #{"gproc_2" "smo_2"} [tag]) (.setOptions learner (into-array ["-K" (pke 2)]))) learner)) ;;; -------------------------------------------------------------------------- (defn- ^Instances prep-instances "Intended as a utility function for load-arff and load-data. This function sets the target class, if specified, and performs data filtering." [^Instances insts target filters] ;; Set the target if we know what it is (when target (.setClass insts (.attribute insts (name target)))) ; Apply any requested filters. (reduce #(filter-instances %1 %2) insts filters)) ;;; -------------------------------------------------------------------------- (defn ^Instances load-arff "Reads in and returns the Instances from the specified ARFF file. The caller may specify any number of filter keywords after the target attribute (or nil to specifically skip setting a class attribute)." ([fpath] (load-arff fpath nil)) ([fpath target & filters] ;; Perform Weka ARFF load and prepare Instances (-> (doto (ArffLoader.) (.setFile (io/file fpath))) (.getDataSet) (prep-instances target filters)))) ;;; -------------------------------------------------------------------------- (defn ^Instances load-dataset "Accepts either an ARFF filepath or a preloaded set of Instances. The function prepares the dataset by setting the target class and applying the specified filters if any." ([fpath] (load-dataset fpath nil)) ([data target & filters] (if (string? data) (apply load-arff data target filters) (prep-instances data target filters)))) ;;; -------------------------------------------------------------------------- (defn white-box? "Returns true if the specified algorithm is considered a «white box model», whose results are generally explainable and interpretable by a human being." [model] ;; FIXME this set is not complete! (contains? #{weka.classifiers.functions.LinearRegression weka.classifiers.functions.Logistic ;weka.classifiers.rules.M5Rules weka.classifiers.trees.J48} (type model))) ;;; -------------------------------------------------------------------------- (defn black-box? "Returns true if the specified algorithm is considered a «black box model», whose results are not readily explainable. " [model] ;; I don't know anybody else...🎵 (not (white-box? model)))
true
;;;; ------------------------------------------------------------------------- ;;;; ;;;; _/_/_/ _/_/_/ _/ _/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/ _/ _/ _/_/_/_/ ;;;; _/ _/ _/ _/ _/ ;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/ ;;;; ;;;; Emotion Mining and Machine Learning for Climate Change communication ;;;; ;;;; @copyright 2017-2020 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal ;;;; ------------------------------------------------------------------------- (ns weka.core (:require [say.genie :refer :all] [say.log :as log] [clojure.java.io :as io] [clojure.string :as str]) (:import [weka.core Instance Instances] [weka.classifiers AbstractClassifier Evaluation] [weka.core.converters AbstractSaver ArffLoader ArffSaver CSVSaver] [weka.filters Filter])) (set! *warn-on-reflection* true) ;;; -------------------------------------------------------------------------- (defprotocol Indexer "Facilitate getting an index from Weka entities. This is currently a trial protocol, expected to grow as we go..." (get-index [entity ^String tag] "Return an index by the column name (tag)")) (extend-protocol Indexer Instances (get-index [insts ^String tag] (.index (.attribute insts tag)))) ;;; -------------------------------------------------------------------------- (defn ^String index0->1 "Converts a 0-based (numeric or string) index to a 1-based String." [i] (str (inc (longify i)))) ;;; -------------------------------------------------------------------------- (defn ^Long index1->0 "Converts a 1-based (numeric or string) index to a 0-based Long." [i] (dec (longify i))) ;; --------------------------------------------------------------------------- (defn attribute-seq " Returns an sequence of the attriutes in the specified dataset. " [^Instances insts] (enumeration-seq (.enumerateAttributes insts))) ;; --------------------------------------------------------------------------- (defn instance-seq " Returns an sequence of the instances in the specified dataset. " [^Instances insts] (enumeration-seq (.enumerateInstances insts))) ;;; -------------------------------------------------------------------------- (defn tag-filename "Turns «/path/to/filename.extn» into «/path/to/filename.tag.EXTN», where EXTN is the specified file type (ftype, which defaults to the origin extension). If ftype is a collection of extensions, e.g. [:arff :csv], then the function returns a map, keyed by these extensions, whose data elements are the tagged versions of fpath." ([fpath tag] (tag-filename fpath tag nil)) ([fpath tag ftype] (let [parts (str/split fpath #"\.") stub (str/join "." (flatten [(butlast parts) (name tag)])) ->tag #(str stub "." (name %))] (cond (coll? ftype) (into {} (map #(vector % (->tag %)) ftype)) ftype (->tag ftype) :else (->tag (last parts)))))) ;;; -------------------------------------------------------------------------- (defn save-file "Writes out the given Instances to the specified ARFF or CSV file. The caller may specify a filetag, which will be inserted into the filename as «/path/to/filename.tag.extn». The default file type is :arff. Returns the filename again as a convenience." ([fpath data] (save-file fpath data :arff)) ([^String fpath ^Instances data ftype] ;(log/debug "FPATH:" fpath) (let [saver (case ftype :arff (ArffSaver.) :csv (CSVSaver.)) fout (io/file fpath)] (.createNewFile fout) (doto ^AbstractSaver saver (.setFile fout) (.setInstances data) (.writeBatch)) fpath)) ([fpath tag data ftype] (save-file (tag-filename fpath tag ftype) data ftype))) ;;; -------------------------------------------------------------------------- (defn save-results "Writes out the given Instances as tagged ARFF and CSV files and returns a filetype-keyed map with the corresponding filename values." [fpath tag data] (let [tag-fpaths (tag-filename fpath tag [:arff :csv])] {:arff (save-file (:arff tag-fpaths) data :arff) :csv (save-file (:csv tag-fpaths) data :csv)})) ;;; -------------------------------------------------------------------------- (defn ^Instances filter-instances "Applies a filter to the specified data Instances." ([data sieve] (filter-instances data sieve [])) ([^Instances data ^Filter sieve opts] (when (not-empty opts) (.setOptions sieve (into-array String opts))) (.setInputFormat sieve data) (Filter/useFilter data sieve))) ;;; -------------------------------------------------------------------------- (defn ^AbstractClassifier make-learner "Instantiates/configures a Weka learning algorithm based on the specified tag." [tag] (let [pke #(str "weka.classifiers.functions.supportVector.PolyKernel -E " %) alg (first (str/split tag #"_")) ^AbstractClassifier learner (case alg "lreg" (weka.classifiers.functions.LinearRegression.) "gproc" (weka.classifiers.functions.GaussianProcesses.) "smo" (weka.classifiers.functions.SMOreg.) "m5rules" (weka.classifiers.rules.M5Rules.) "rforest" (weka.classifiers.trees.RandomForest.))] ;; Instantiate the learner and handle any non-default parameters (when (some #{"gproc_2" "smo_2"} [tag]) (.setOptions learner (into-array ["-K" (pke 2)]))) learner)) ;;; -------------------------------------------------------------------------- (defn- ^Instances prep-instances "Intended as a utility function for load-arff and load-data. This function sets the target class, if specified, and performs data filtering." [^Instances insts target filters] ;; Set the target if we know what it is (when target (.setClass insts (.attribute insts (name target)))) ; Apply any requested filters. (reduce #(filter-instances %1 %2) insts filters)) ;;; -------------------------------------------------------------------------- (defn ^Instances load-arff "Reads in and returns the Instances from the specified ARFF file. The caller may specify any number of filter keywords after the target attribute (or nil to specifically skip setting a class attribute)." ([fpath] (load-arff fpath nil)) ([fpath target & filters] ;; Perform Weka ARFF load and prepare Instances (-> (doto (ArffLoader.) (.setFile (io/file fpath))) (.getDataSet) (prep-instances target filters)))) ;;; -------------------------------------------------------------------------- (defn ^Instances load-dataset "Accepts either an ARFF filepath or a preloaded set of Instances. The function prepares the dataset by setting the target class and applying the specified filters if any." ([fpath] (load-dataset fpath nil)) ([data target & filters] (if (string? data) (apply load-arff data target filters) (prep-instances data target filters)))) ;;; -------------------------------------------------------------------------- (defn white-box? "Returns true if the specified algorithm is considered a «white box model», whose results are generally explainable and interpretable by a human being." [model] ;; FIXME this set is not complete! (contains? #{weka.classifiers.functions.LinearRegression weka.classifiers.functions.Logistic ;weka.classifiers.rules.M5Rules weka.classifiers.trees.J48} (type model))) ;;; -------------------------------------------------------------------------- (defn black-box? "Returns true if the specified algorithm is considered a «black box model», whose results are not readily explainable. " [model] ;; I don't know anybody else...🎵 (not (white-box? model)))
[ { "context": "DO NOT MODIFY ;;\n\n\n(def pokemon-results\n (->> [[\"eevee\" 133] [\"vaporeon\" 134] [\"jolteon\" 135] [\"flare", "end": 285, "score": 0.4846384525299072, "start": 283, "tag": "NAME", "value": "ee" }, { "context": "-results\n (->> [[\"eevee\" 133] [\"vaporeon\" 134] [\"jolteon\" 135] [\"flareon\" 136]\n [\"espeon\" 196] [\"um", "end": 321, "score": 0.5382363796234131, "start": 314, "tag": "NAME", "value": "jolteon" }, { "context": "[[\"eevee\" 133] [\"vaporeon\" 134] [\"jolteon\" 135] [\"flareon\" 136]\n [\"espeon\" 196] [\"umbreon\" 197] [\"le", "end": 337, "score": 0.579840898513794, "start": 330, "tag": "NAME", "value": "flareon" }, { "context": "n\" 134] [\"jolteon\" 135] [\"flareon\" 136]\n [\"espeon\" 196] [\"umbreon\" 197] [\"leafeon\" 470] [\"glaceon\" ", "end": 360, "score": 0.4503920376300812, "start": 354, "tag": "NAME", "value": "espeon" }, { "context": "on\" 135] [\"flareon\" 136]\n [\"espeon\" 196] [\"umbreon\" 197] [\"leafeon\" 470] [\"glaceon\" 471]\n [\"s", "end": 376, "score": 0.5343772768974304, "start": 369, "tag": "NAME", "value": "umbreon" }, { "context": "on\" 136]\n [\"espeon\" 196] [\"umbreon\" 197] [\"leafeon\" 470] [\"glaceon\" 471]\n [\"sylveon\" 700", "end": 387, "score": 0.37332266569137573, "start": 385, "tag": "USERNAME", "value": "le" }, { "context": "\" 136]\n [\"espeon\" 196] [\"umbreon\" 197] [\"leafeon\" 470] [\"glaceon\" 471]\n [\"sylveon\" 700]]\n ", "end": 392, "score": 0.46784889698028564, "start": 387, "tag": "NAME", "value": "afeon" }, { "context": " [\"espeon\" 196] [\"umbreon\" 197] [\"leafeon\" 470] [\"glaceon\" 471]\n [\"sylveon\" 700]]\n (mapv ", "end": 403, "score": 0.4100971221923828, "start": 401, "tag": "USERNAME", "value": "gl" }, { "context": "\"espeon\" 196] [\"umbreon\" 197] [\"leafeon\" 470] [\"glaceon\" 471]\n [\"sylveon\" 700]]\n (mapv (fn [", "end": 408, "score": 0.45820969343185425, "start": 403, "tag": "NAME", "value": "aceon" }, { "context": "n\" 197] [\"leafeon\" 470] [\"glaceon\" 471]\n [\"sylveon\" 700]]\n (mapv (fn [p] {:name (first p)\n ", "end": 430, "score": 0.4721294939517975, "start": 425, "tag": "USERNAME", "value": "sylve" }, { "context": "7] [\"leafeon\" 470] [\"glaceon\" 471]\n [\"sylveon\" 700]]\n (mapv (fn [p] {:name (first p)\n ", "end": 432, "score": 0.4533446729183197, "start": 430, "tag": "NAME", "value": "on" } ]
t/pokegen/api_test.clj
Frosku/pokegen
1
(ns pokegen.api-test (:require [clojure.test :refer :all] [pokegen.api :refer :all] [cheshire.core :as json] [clj-http.fake :refer :all])) ;; DATA DEFINITIONS FOR TESTING FAKE HTTP ROUTES, DO NOT MODIFY ;; (def pokemon-results (->> [["eevee" 133] ["vaporeon" 134] ["jolteon" 135] ["flareon" 136] ["espeon" 196] ["umbreon" 197] ["leafeon" 470] ["glaceon" 471] ["sylveon" 700]] (mapv (fn [p] {:name (first p) :url (build-api-url "pokemon" (second p))})))) (defn pokemon-route-body [] (json/generate-string {:results pokemon-results})) (defn pokemon-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (pokemon-route-body)}) (defn vaporeon-lookup-route-body [] (json/generate-string {:name "vaporeon" :abilities [{:ability {:name "water-absorb"} :is_hidden false} {:ability {:name "hydration"} :is_hidden true}] :stats [{:base_stat 130 :stat {:name "hp"}} {:base_stat 65 :stat {:name "attack"}} {:base_stat 60 :stat {:name "defense"}} {:base_stat 110 :stat {:name "special-attack"}} {:base_stat 95 :stat {:name "special-defense"}} {:base_stat 65 :stat {:name "speed"}}] :types [{:type {:name "water"}}] :moves [{:move {:name "tackle"} :version_group_details [{:level_learned_at 1 :move_learn_method {:name "level-up"} :version_group {:name "sun-moon"}}]}] :species {:name "vaporeon"}})) (defn vaporeon-lookup-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-lookup-route-body)}) (defn vaporeon-species-route-body [] (json/generate-string {:name "vaporeon" :gender_rate 1 :habitat {:name "urban"} :shape {:name "quadruped"} :is_baby false :color {:name "blue"} :evolves_from_species {:name "eevee"} :egg_groups [{:name "ground"}] :names [{:language {:name "en"} :name "Vaporeon"}]})) (defn vaporeon-species-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-species-route-body)}) ;; TESTS START HERE ;; (deftest test-url-building (testing "We can get a user-specified endpoint" (is (= "https://pokeapi.co/api/v2/foo" (build-api-url "foo"))) (is (= "https://pokeapi.co/api/v2/foo/bar" (build-api-url "foo" "bar")))) (testing "We can correctly generate the Pokemon endpoint" (is (= "https://pokeapi.co/api/v2/pokemon" (pokemon-endpoint))))) (defn vaporeon-lookup-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-lookup-route-body)}) (deftest test-getting-pokemon-names (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon?limit=2000" pokemon-route-res} (testing "We can get all Pokemon names" (is (= ["eevee" "vaporeon" "jolteon" "flareon" "espeon" "umbreon" "leafeon" "glaceon" "sylveon"] (all-pokemon-names)))) (testing "We can get random Pokemon names" (with-redefs [clojure.core/shuffle (fn [c] c)] (is (= ["eevee"] (random-pokemon-names))) (is (= ["eevee"] (random-pokemon-names 1))) (is (= ["eevee" "vaporeon"] (random-pokemon-names 2))) (is (= ["eevee" "vaporeon" "jolteon"] (random-pokemon-names 3))))))) (deftest test-looking-up-pokemon (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon/vaporeon" vaporeon-lookup-route-res} (testing "We can get a Pokemon's information" (is (= "vaporeon" (:name (lookup-pokemon-by-name "vaporeon")))) (is (= {:hp 130 :attack 65 :defense 60 :special-attack 110 :special-defense 95 :speed 65} (base-stats "vaporeon"))) (is (= [:water] (types "vaporeon"))) (is (= [{:move "tackle" :method "level-up" :min-level 1}] (learnable-moves "vaporeon"))) (is (= [{:ability "water-absorb" :hidden false} {:ability "hydration" :hidden true}] (abilities "vaporeon")))))) (deftest test-looking-up-pokemon-species (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon/vaporeon" vaporeon-lookup-route-res "https://pokeapi.co/api/v2/pokemon-species/vaporeon" vaporeon-species-route-res} (testing "We can get a Pokemon species' information" (is (= "vaporeon" (:name (lookup-pokemon-species-by-name "vaporeon")))) (is (= {:male 7 :female 1} (gender-distribution "vaporeon"))) (is (= :urban (habitat "vaporeon"))) (is (= :blue (color "vaporeon"))) (is (= false (baby? "vaporeon"))) (is (= :quadruped (anatomy "vaporeon"))) (is (= "eevee" (pre-evolved-form "vaporeon"))) (is (= "Vaporeon" (display-name "vaporeon"))) (is (= [:ground] (egg-groups "vaporeon"))))))
32162
(ns pokegen.api-test (:require [clojure.test :refer :all] [pokegen.api :refer :all] [cheshire.core :as json] [clj-http.fake :refer :all])) ;; DATA DEFINITIONS FOR TESTING FAKE HTTP ROUTES, DO NOT MODIFY ;; (def pokemon-results (->> [["<NAME>vee" 133] ["vaporeon" 134] ["<NAME>" 135] ["<NAME>" 136] ["<NAME>" 196] ["<NAME>" 197] ["le<NAME>" 470] ["gl<NAME>" 471] ["sylve<NAME>" 700]] (mapv (fn [p] {:name (first p) :url (build-api-url "pokemon" (second p))})))) (defn pokemon-route-body [] (json/generate-string {:results pokemon-results})) (defn pokemon-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (pokemon-route-body)}) (defn vaporeon-lookup-route-body [] (json/generate-string {:name "vaporeon" :abilities [{:ability {:name "water-absorb"} :is_hidden false} {:ability {:name "hydration"} :is_hidden true}] :stats [{:base_stat 130 :stat {:name "hp"}} {:base_stat 65 :stat {:name "attack"}} {:base_stat 60 :stat {:name "defense"}} {:base_stat 110 :stat {:name "special-attack"}} {:base_stat 95 :stat {:name "special-defense"}} {:base_stat 65 :stat {:name "speed"}}] :types [{:type {:name "water"}}] :moves [{:move {:name "tackle"} :version_group_details [{:level_learned_at 1 :move_learn_method {:name "level-up"} :version_group {:name "sun-moon"}}]}] :species {:name "vaporeon"}})) (defn vaporeon-lookup-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-lookup-route-body)}) (defn vaporeon-species-route-body [] (json/generate-string {:name "vaporeon" :gender_rate 1 :habitat {:name "urban"} :shape {:name "quadruped"} :is_baby false :color {:name "blue"} :evolves_from_species {:name "eevee"} :egg_groups [{:name "ground"}] :names [{:language {:name "en"} :name "Vaporeon"}]})) (defn vaporeon-species-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-species-route-body)}) ;; TESTS START HERE ;; (deftest test-url-building (testing "We can get a user-specified endpoint" (is (= "https://pokeapi.co/api/v2/foo" (build-api-url "foo"))) (is (= "https://pokeapi.co/api/v2/foo/bar" (build-api-url "foo" "bar")))) (testing "We can correctly generate the Pokemon endpoint" (is (= "https://pokeapi.co/api/v2/pokemon" (pokemon-endpoint))))) (defn vaporeon-lookup-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-lookup-route-body)}) (deftest test-getting-pokemon-names (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon?limit=2000" pokemon-route-res} (testing "We can get all Pokemon names" (is (= ["eevee" "vaporeon" "jolteon" "flareon" "espeon" "umbreon" "leafeon" "glaceon" "sylveon"] (all-pokemon-names)))) (testing "We can get random Pokemon names" (with-redefs [clojure.core/shuffle (fn [c] c)] (is (= ["eevee"] (random-pokemon-names))) (is (= ["eevee"] (random-pokemon-names 1))) (is (= ["eevee" "vaporeon"] (random-pokemon-names 2))) (is (= ["eevee" "vaporeon" "jolteon"] (random-pokemon-names 3))))))) (deftest test-looking-up-pokemon (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon/vaporeon" vaporeon-lookup-route-res} (testing "We can get a Pokemon's information" (is (= "vaporeon" (:name (lookup-pokemon-by-name "vaporeon")))) (is (= {:hp 130 :attack 65 :defense 60 :special-attack 110 :special-defense 95 :speed 65} (base-stats "vaporeon"))) (is (= [:water] (types "vaporeon"))) (is (= [{:move "tackle" :method "level-up" :min-level 1}] (learnable-moves "vaporeon"))) (is (= [{:ability "water-absorb" :hidden false} {:ability "hydration" :hidden true}] (abilities "vaporeon")))))) (deftest test-looking-up-pokemon-species (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon/vaporeon" vaporeon-lookup-route-res "https://pokeapi.co/api/v2/pokemon-species/vaporeon" vaporeon-species-route-res} (testing "We can get a Pokemon species' information" (is (= "vaporeon" (:name (lookup-pokemon-species-by-name "vaporeon")))) (is (= {:male 7 :female 1} (gender-distribution "vaporeon"))) (is (= :urban (habitat "vaporeon"))) (is (= :blue (color "vaporeon"))) (is (= false (baby? "vaporeon"))) (is (= :quadruped (anatomy "vaporeon"))) (is (= "eevee" (pre-evolved-form "vaporeon"))) (is (= "Vaporeon" (display-name "vaporeon"))) (is (= [:ground] (egg-groups "vaporeon"))))))
true
(ns pokegen.api-test (:require [clojure.test :refer :all] [pokegen.api :refer :all] [cheshire.core :as json] [clj-http.fake :refer :all])) ;; DATA DEFINITIONS FOR TESTING FAKE HTTP ROUTES, DO NOT MODIFY ;; (def pokemon-results (->> [["PI:NAME:<NAME>END_PIvee" 133] ["vaporeon" 134] ["PI:NAME:<NAME>END_PI" 135] ["PI:NAME:<NAME>END_PI" 136] ["PI:NAME:<NAME>END_PI" 196] ["PI:NAME:<NAME>END_PI" 197] ["lePI:NAME:<NAME>END_PI" 470] ["glPI:NAME:<NAME>END_PI" 471] ["sylvePI:NAME:<NAME>END_PI" 700]] (mapv (fn [p] {:name (first p) :url (build-api-url "pokemon" (second p))})))) (defn pokemon-route-body [] (json/generate-string {:results pokemon-results})) (defn pokemon-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (pokemon-route-body)}) (defn vaporeon-lookup-route-body [] (json/generate-string {:name "vaporeon" :abilities [{:ability {:name "water-absorb"} :is_hidden false} {:ability {:name "hydration"} :is_hidden true}] :stats [{:base_stat 130 :stat {:name "hp"}} {:base_stat 65 :stat {:name "attack"}} {:base_stat 60 :stat {:name "defense"}} {:base_stat 110 :stat {:name "special-attack"}} {:base_stat 95 :stat {:name "special-defense"}} {:base_stat 65 :stat {:name "speed"}}] :types [{:type {:name "water"}}] :moves [{:move {:name "tackle"} :version_group_details [{:level_learned_at 1 :move_learn_method {:name "level-up"} :version_group {:name "sun-moon"}}]}] :species {:name "vaporeon"}})) (defn vaporeon-lookup-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-lookup-route-body)}) (defn vaporeon-species-route-body [] (json/generate-string {:name "vaporeon" :gender_rate 1 :habitat {:name "urban"} :shape {:name "quadruped"} :is_baby false :color {:name "blue"} :evolves_from_species {:name "eevee"} :egg_groups [{:name "ground"}] :names [{:language {:name "en"} :name "Vaporeon"}]})) (defn vaporeon-species-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-species-route-body)}) ;; TESTS START HERE ;; (deftest test-url-building (testing "We can get a user-specified endpoint" (is (= "https://pokeapi.co/api/v2/foo" (build-api-url "foo"))) (is (= "https://pokeapi.co/api/v2/foo/bar" (build-api-url "foo" "bar")))) (testing "We can correctly generate the Pokemon endpoint" (is (= "https://pokeapi.co/api/v2/pokemon" (pokemon-endpoint))))) (defn vaporeon-lookup-route-res [_] {:status 200 :headers {"Content-Type" "application/json"} :body (vaporeon-lookup-route-body)}) (deftest test-getting-pokemon-names (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon?limit=2000" pokemon-route-res} (testing "We can get all Pokemon names" (is (= ["eevee" "vaporeon" "jolteon" "flareon" "espeon" "umbreon" "leafeon" "glaceon" "sylveon"] (all-pokemon-names)))) (testing "We can get random Pokemon names" (with-redefs [clojure.core/shuffle (fn [c] c)] (is (= ["eevee"] (random-pokemon-names))) (is (= ["eevee"] (random-pokemon-names 1))) (is (= ["eevee" "vaporeon"] (random-pokemon-names 2))) (is (= ["eevee" "vaporeon" "jolteon"] (random-pokemon-names 3))))))) (deftest test-looking-up-pokemon (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon/vaporeon" vaporeon-lookup-route-res} (testing "We can get a Pokemon's information" (is (= "vaporeon" (:name (lookup-pokemon-by-name "vaporeon")))) (is (= {:hp 130 :attack 65 :defense 60 :special-attack 110 :special-defense 95 :speed 65} (base-stats "vaporeon"))) (is (= [:water] (types "vaporeon"))) (is (= [{:move "tackle" :method "level-up" :min-level 1}] (learnable-moves "vaporeon"))) (is (= [{:ability "water-absorb" :hidden false} {:ability "hydration" :hidden true}] (abilities "vaporeon")))))) (deftest test-looking-up-pokemon-species (with-fake-routes-in-isolation {"https://pokeapi.co/api/v2/pokemon/vaporeon" vaporeon-lookup-route-res "https://pokeapi.co/api/v2/pokemon-species/vaporeon" vaporeon-species-route-res} (testing "We can get a Pokemon species' information" (is (= "vaporeon" (:name (lookup-pokemon-species-by-name "vaporeon")))) (is (= {:male 7 :female 1} (gender-distribution "vaporeon"))) (is (= :urban (habitat "vaporeon"))) (is (= :blue (color "vaporeon"))) (is (= false (baby? "vaporeon"))) (is (= :quadruped (anatomy "vaporeon"))) (is (= "eevee" (pre-evolved-form "vaporeon"))) (is (= "Vaporeon" (display-name "vaporeon"))) (is (= [:ground] (egg-groups "vaporeon"))))))
[ { "context": "; Copyright (C) 2008 - 2011 Stefan Marr <mail@stefan-marr.de>\n; \n; Permission is hereby g", "end": 39, "score": 0.9998845458030701, "start": 28, "tag": "NAME", "value": "Stefan Marr" }, { "context": "; Copyright (C) 2008 - 2011 Stefan Marr <mail@stefan-marr.de>\n; \n; Permission is hereby granted, free of charg", "end": 60, "score": 0.9999351501464844, "start": 41, "tag": "EMAIL", "value": "mail@stefan-marr.de" } ]
Clojure/src/snake/player.clj
smarr/Snake
4
; Copyright (C) 2008 - 2011 Stefan Marr <mail@stefan-marr.de> ; ; 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 snake.player (:use snake.agents-helpers) (:use snake.game-master)) (defn- do-move [player-agent direction] (let [{game-master :game-agent self :self} player-agent] (send game-master move self direction)) player-agent) (defn create-human-player "Starts an agent that represents a human player" [] (start-agent-and-initialize {:type :player-human :up (fn [agent] (do-move agent :up )) :left (fn [agent] (do-move agent :left )) :down (fn [agent] (do-move agent :down )) :right (fn [agent] (do-move agent :right)) :self nil ; self represents the agent reference to itself, is set by initialization :game-agent nil })) (defn create-ai-player "Start an agent that represents a simple AI player" [] (start-agent-and-initialize {:type :player-ai :self nil :game-agent nil})) (defn set-game-master [agent-state game-master] (assoc agent-state :game-agent game-master)) (defn game-over [agent-state] (assoc agent-state :state :game-over))
79707
; Copyright (C) 2008 - 2011 <NAME> <<EMAIL>> ; ; 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 snake.player (:use snake.agents-helpers) (:use snake.game-master)) (defn- do-move [player-agent direction] (let [{game-master :game-agent self :self} player-agent] (send game-master move self direction)) player-agent) (defn create-human-player "Starts an agent that represents a human player" [] (start-agent-and-initialize {:type :player-human :up (fn [agent] (do-move agent :up )) :left (fn [agent] (do-move agent :left )) :down (fn [agent] (do-move agent :down )) :right (fn [agent] (do-move agent :right)) :self nil ; self represents the agent reference to itself, is set by initialization :game-agent nil })) (defn create-ai-player "Start an agent that represents a simple AI player" [] (start-agent-and-initialize {:type :player-ai :self nil :game-agent nil})) (defn set-game-master [agent-state game-master] (assoc agent-state :game-agent game-master)) (defn game-over [agent-state] (assoc agent-state :state :game-over))
true
; Copyright (C) 2008 - 2011 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>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 snake.player (:use snake.agents-helpers) (:use snake.game-master)) (defn- do-move [player-agent direction] (let [{game-master :game-agent self :self} player-agent] (send game-master move self direction)) player-agent) (defn create-human-player "Starts an agent that represents a human player" [] (start-agent-and-initialize {:type :player-human :up (fn [agent] (do-move agent :up )) :left (fn [agent] (do-move agent :left )) :down (fn [agent] (do-move agent :down )) :right (fn [agent] (do-move agent :right)) :self nil ; self represents the agent reference to itself, is set by initialization :game-agent nil })) (defn create-ai-player "Start an agent that represents a simple AI player" [] (start-agent-and-initialize {:type :player-ai :self nil :game-agent nil})) (defn set-game-master [agent-state game-master] (assoc agent-state :game-agent game-master)) (defn game-over [agent-state] (assoc agent-state :state :game-over))