Charting the value of Datomic facts over time - charts

Since Datomic stores assertions and retractions of facts, is it possible to use this built-in storage to chart changes to a value over time, e.g. a price history?

Yes. The command you want is datomic.api/history.
Called with a database value, it returns a special db featuring all datom additions and retractions.
(ns datomic-history-demo.core
(:require [datomic.api :as d :refer [db q]]))
(defn demonstrate []
(let [db-uri '"datomic:mem://fnord"]
(d/delete-database db-uri)
(d/create-database db-uri)
(let [conn (d/connect db-uri)]
(d/transact conn [{:db/id #db/id[:db.part/db]
:db/ident :demo/amount
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db/doc "An interesting quantity."
:db.install/_attribute :db.part/db}])
(let [tempid (dbg (d/tempid :db.part/user))
tx-data #(d/transact conn [{:db/id tempid
:db/doc "initial value"
:demo/amount 5}])
id (dbg (d/resolve-tempid (:db-after tx-data) (:tempids tx-data) tempid))]
#(d/transact conn [{:db/id id
:db/doc "subsequent value"
:demo/amount 17}])
#(d/transact conn [{:db/id id
:db/doc "final value"
:demo/amount 23}])
(let [special-history-db (d/history (db conn))]
(->> (q '[:find ?instant ?e ?amount ?operation
:where
[?e :demo/amount ?amount ?tx ?operation]
[?tx :db/txInstant ?instant]]
special-history-db)
(sort-by first)))))))
(demonstrate)
(comment
;; evaluates to
([#inst "2014-02-25T19:12:24.054-00:00" 17592186045418 5 true]
[#inst "2014-02-25T19:12:24.058-00:00" 17592186045418 5 false]
[#inst "2014-02-25T19:12:24.058-00:00" 17592186045418 17 true]
[#inst "2014-02-25T19:12:24.062-00:00" 17592186045418 23 true]
[#inst "2014-02-25T19:12:24.062-00:00" 17592186045418 17 false])

Related

Ag-grid getRowStyle doesn't work properly

I am trying to implement a row style such that if important columns are missing a value, then it should be red (like an alert). I have the following logic:
(defn missing-requirements? [params]
(not (every? (js->clj (.-data params)) #state/important-tags)))
And this is the main function that is being rendered
(def ag-adapter (r/adapt-react-class (.-AgGridReact js/agGridReact)))
(defn home-page []
[:div [:h2 "Ekspono tag-model"]
[:p "My portfolio / Top Index " [:a {:style {:background-color "#C0C0C0" :float "right" :color "black"}
:href "https://www.google.com" :target "_blank"} "Show problems"]]
[:div {:className "ag-theme-balham" :style {:height 200 :width 700 :color "purple"}}
[ag-adapter {:modules "AllCommunityModules"
:columnDefs #state/cols
:rowData #state/rows
:defaultColDef {:sortable true
:filter "agTextColumnFilter"
:floatingfilter true
:resizable true
:flex 1
:width deafult-col-w}
:getRowStyle (fn [params] (if (error/missing-requirements? params) {:background-color "Green"}))
:sidebars "filters"
:onGridReady (fn [params]
(:gridApi (.-api params))
(:gridColumnApi (.-columnApi params)))}]]])
Just :rowStyle {:background-color "red"} works fine. Does someone know what could be wrong? I have ag-grid-react version 21.0.1-1 as a dependency.
It was solved by adding #js as shown below
:getRowStyle (fn [params] (if (error/missing-requirements? params) #js {:background-color "Green"}))

sbcl: list all valid character encodings

To get the list of all valid encodings for sbcl, I do this:
(let (encoding-list)
(let (symbol-list)
(do-external-symbols (s :keyword)
(push s symbol-list))
(setf symbol-list (sort symbol-list #'string<))
(mapc (lambda (x)
(when (ignore-errors
(with-open-file
(phyle "scratch1"
:direction :output
:if-exists :supersede
:external-format x)
1)) ; <-- produce something non-NIL
(push x encoding-list)))
symbol-list))
(nreverse encoding-list))
Is there an easier way to do this in sbcl? (For example, in clisp, all the encodings are external symbols in the CHARSET package.)
The only "official" list is in the manual. If you don't mind looking into SBCLs internals, external formats are stored in a hash table, SB-IMPL::*EXTERNAL-FORMATS*.
CL-USER> (alexandria:hash-table-keys sb-impl::*external-formats*)
(:UTF32BE :UTF-32BE :UTF32LE :UTF-32LE :UTF16BE :UTF-16BE :UTF16LE :UTF-16LE
:UCS4BE :UCS-4BE :UCS4LE :UCS-4LE :UCS2BE :UCS-2BE :UCS2LE :UCS-2LE :CP932
:|Shift_JIS| :SJIS :SHIFT_JIS :|eucJP| :EUCJP :EUC-JP :CP936 :GBK :|macintosh|
:MACINTOSH :|mac| :MAC :|MacRoman| :|mac-roman| :MAC-ROMAN :|windows-1258|
:WINDOWS-1258 :|cp1258| :CP1258 :|windows-1257| :WINDOWS-1257 :|cp1257|
:CP1257 :|windows-1256| :WINDOWS-1256 :|cp1256| :CP1256 :|windows-1255|
:WINDOWS-1255 :|cp1255| :CP1255 :|cp1254| :CP1254 :|windows-1253|
:WINDOWS-1253 :|cp1253| :CP1253 :|windows-1252| :WINDOWS-1252 :|cp1252|
:CP1252 :|windows-1251| :WINDOWS-1251 :|cp1251| :CP1251 :|windows-1250|
:WINDOWS-1250 :|cp1250| :CP1250 :ISO8859-15 :ISO-8859-15 :LATIN9 :LATIN-9
:|latin-8| :LATIN-8 :|iso-8859-14| :ISO-8859-14 :|latin-7| :LATIN-7
:|iso-8859-13| :ISO-8859-13 :|iso-8859-11| :ISO-8859-11 :|latin-6| :LATIN-6
:|iso-8859-10| :ISO-8859-10 :|latin-5| :LATIN-5 :|iso-8859-9| :ISO-8859-9
:|iso-8859-8| :ISO-8859-8 :|iso-8859-7| :ISO-8859-7 :|iso-8859-6| :ISO-8859-6
:|iso-8859-5| :ISO-8859-5 :|latin-4| :LATIN-4 :|iso-8859-4| :ISO-8859-4
:|latin-3| :LATIN-3 :|iso-8859-3| :ISO-8859-3 :|latin-2| :LATIN-2
:|iso-8859-2| :ISO-8859-2 :|cp874| :CP874 :|cp869| :CP869 :|cp866| :CP866
:|cp865| :CP865 :|cp864| :CP864 :|cp863| :CP863 :|cp862| :CP862 :|cp861|
:CP861 :|cp860| :CP860 :|cp857| :CP857 :|cp855| :CP855 :|cp852| :CP852
:|cp850| :CP850 :|cp437| :CP437 :|x-mac-cyrillic| :X-MAC-CYRILLIC :|koi8-u|
:KOI8-U :|koi8-r| :KOI8-R :IBM037 :IBM-037 :|cp037| :CP037 :EBCDIC-US :UTF8
:UTF-8 :ISO8859-1 :ISO-8859-1 :LATIN1 :LATIN-1 :|646| :ISO-646-US :ISO-646
:ANSI_X3.4-1968 :US-ASCII :ASCII)
Of course, since this is not a public API there is no guarantee that it won't be broken in future releases.

How can I update a chartist chart with new data in ClojureScript?

I am new to ClojureScript and I am trying to update a chart with new data. I am using Chartist and Reagent. Rendering the chart for the first time works fine, but if I change the data for the chartist function, the chart isn't rendered again. I have already tried different things with atoms and tried to use the update function from chartist. Here is the link to the chartist update api
Here is my code so far:
(ns example.core
(:require [clojure.browser.repl :as repl]
[reagent.core :as reagent]
[cljsjs.chartist]
))
(defonce conn
(repl/connect "http://localhost:9000/repl"))
(defonce results(reagent/atom [1 1 6 15 25] ))
(defonce timespan (reagent/atom ["Mar-2012" "Jun-2012" "Nov-2012" "Oct-2013" "Nov-2014"]))
(def global-state (reagent/atom 0))
(defn show-chart
[resultsInChart timespaneInChart]
(let [chart-data {:labels timespaneInChart
:series [resultsInChart]}
options {:width "700px"
:height "380px"}]
(js/Chartist.Line. ".ct-chart" (clj->js chart-data) (clj->js options))))
(defn chart-component
[]
(let [some global-state]
(reagent/create-class
{:component-did-mount #(show-chart #results #timespan)
:component-did-update #(show-chart #results #timespan)
:display-name "chart-component"
:reagent-render (fn []
[:div {:class "ct-chart ct-perfect-fourth"}])})))
(defn home-page []
[:div
[:div
[:p [:button {:on-click #(reset! results [1 1 6 15 5]
)} "Change last Value to 5"]
]
]
]
)
(defn run []
(reagent/render [chart-component](.getElementById js/document "myChart"))
(reagent/render [home-page](.getElementById js/document "app"))
)
Would be great if somebody could help.
Update:
I fixed it with adding figwheel to my project, somehow this solved the problem and the chart gets updated. I also used the update function of Chartist under component-did-update in the end. Here is a link to figwheel https://github.com/bhauman/lein-figwheel

Best way to read (MATLAB) structures from a text file in Clojure / Incanter

I exported my matlab structs to text files so that I can read them in clojure.
I have a text file like:
name
Ali
age
33
friends-ages
30
31
25
47
know I can read this file, but what's the clojure way to convert it into something like:
(def person1
{:name "Ali"
:age 33
:friends-ages [30 31 25 47]})
or lets make it easier:
name
Ali
age
33
to:
(def person1
{:name "Ali"
:age 33})
Assuming each file has a single record,
(defn parse [f]
(let [[_ name _ age _ & friends] (.split (slurp f) "\n")]
{:name name :age age :friends (map read-string friends)}))
(parse "../../../Desktop/t.txt")
you get,
{:name "Ali", :age "33", :friends-ages (30 31 25 47)}
I guess you would need to manually do this conversion from text file (which isn't in any standard serialization formats) to the required set format. If possible, I would suggest that you should extract the MATLAB data in JSON format and that would be easy to read in clojure using the json library.
Here's a solution for your easier problem:
(ns example
(:require [clojure.string :as str]))
(def input "name\nAli\nage\n33\n") ; you'd get this by reading the file
(defn process [data]
(->> (str/split data #"\n")
(partition 2)
(map (fn [[k v]]
[(keyword k)
(try
(Integer/valueOf v)
(catch NumberFormatException _
v))]))
(into {})))
(prn (process input))
The full problem requires better specification of the format: how do you know that the list of ages is done?
I ended up writing an .m file to export my .mat files to text, then imported them by something like the following:
(use '[clojure.string :only (split join)])
(defn kv [[k v]]
[(keyword k) v])
(let [a (split (slurp (java.io.FileReader. fileName)) #"\n")]
(def testNeuron (into {} (map kv (partition 2 a)))))
Thanks to the answers by Hamza and Jouni.
The actual code is more like this:
(def dataPath "/home/ali/Dropbox/Projects/Neurojure/")
(def testFileName "dae062.c1.cylinder.DID.txt")
(defn kv [[k v]]
[(keyword k)
(if (< 0 (count (re-seq #"\d\d\d\dSpikes|\d\d\d\dOcodes|\d\d\d\dOSpikes" k)))
(into [] (map (fn [x] (Integer/valueOf x)) (split v #",")))
(try (Integer/valueOf v)
(catch NumberFormatException _ v)))])
(let [a (split (slurp (java.io.FileReader. (str dataPath testFileName))) #"\n")]
(def testNeuron (into {} (map kv (partition 2 a)))))
and the converted data file looks like this:
ConvertDate
18-Nov-2011
Name
/bgc/data/dae/062/dae062.mat
frameperiod
83.2500000037253
Spike2Version
1.27
unstored
167
rfstr
cm=rf-3.10,9.61:0.00x0.00,-135deg pe20 -2.0,-3.0 fx=0.00,fy=0.00cm=rf-3.10,9.61:0.00x0.00,-135deg pe20 -2.0,-3.0 fx=0.00,fy=0.00
rf
-3.1,9.61,0,0,-135,20,-2,-3,0,0
trange
47371169.75,100193717.5
psych
1
rc
0
Options
expname
cylinder.dxXIdD
Start
94745610.75
End
100193717.5
Area
MT
Ex
perimenter Ali
Trial=>0001Start
47377343
Trial=>0001TrialStart
47377343
Trial=>0001End
47397224.25
Trial=>0001dur
19881.2500000075
Trial=>0001uStim
0
Trial=>0001op
40980
Trial=>0001Trial
1860
Trial=>0001id
15897
Trial=>0001Startev
47377149.5
Trial=>0001serdelay
-46.25
Trial=>0001bstimes
47377195.75
Trial=>0001delay
147.25
Trial=>0001TrueEnd
47397224.25
Trial=>0001CorLoop
0
Trial=>0001dx
0
Trial=>0001Spikes
-1402,-1232,1577,1931,2165,2222,2478,2773,2903,3229,3745,3820,4071,4588,4920,5141,5752,6440,6490,6664,6770,7042,7958,8081,8307,8622,8732,9021,9082,9343,9619,9695,9877,10357,10668,10943,11105,11364,11720,12272,12499,12762,12907,13621,14121,14351,14542,14588,15104,15420,15501,16331,16596,16843,17476,17698,17996,18169,18401,18532,18706,19029,19081,19418,19603,19750,20222
Trial=>0001count
65
Trial=>0001OptionCode
+do+aa+sq+72+se+fc+fb+ap+wt+cf+ws+ts+sw+bw+cs+2a+bm+gm+x2+sp+da+ao+cS+C3+CF
Trial=>0001me
0
Trial=>0001OSpikes
-1976,-1802,-1423,-1360,-1268,-1248,-1140,-244,-220,-164,632,681,730,760,779,786,867,879,924,1062,1161,1252,1268,1431,1533,1632,1946,2210,2235,2273,2285,2296,2305,2496,2532,2541,2732,2787,2806,2822,2840,3095,3292,3431,3598,3614,3837,4100,4482,4504,4515,4651,4768,4794,4936,5020,5160,5184,5300,5314,5710,5764,6431,6453,6471,6553,6561,6584,6791,7018,7124,7880,7905,7940,7968,8011,8315,8330,8352,8568,8666,8748,8756,8766,8797,8836,9038,9297,9328,9360,9471,9632,9639,9721,9939,10196,10363,10375,10387,10410,10931,10953,10969,10986,11038,11118,11135,11405,11692,12018,12163,12258,12492,12512,12525,12884,12899,12919,13156,13183,13638,13674,13842,13988,14110,14298,14310,14321,14606,14617,15124,15132,15150,15289,15341,15620,16293,16305,16342,16364,16441,16604,16692,16932,16997,17059,17086,17210,17368,17495,17626,17639,17651,17677,17718,18013,18247,18353,18553,18691,18722,18887,18941,19438,19774,19938,19959,19967,20004,20240,20306,20500,20623
Trial=>0002Start
47406914
Trial=>0002TrialStart
47406914
Trial=>0002End
47426795.25
Trial=>0002dur
19881.2499999925
...

Racket Server & PostgreSQL - BLOB upload/download without saving to memory or disk

I am trying to make a servlet for the Racket Web Server that would allow a user to upload pictures to the site and display the already uploaded files as images on the same page. I would like to stream the pictures directly in and out of a PostgreSQL database, rather than saving them to a temporary file on disk or in memory. Is it possible? If so, what is the best way to do it? Can it be done with a stateless servlet? Any help is greatly appreciated!
Should be. I recommend the db package from PLaneT (because I wrote it). You can read the docs online.
The PostgreSQL table should have a bytea field for the image contents; on the Racket side it will be represented as a byte string.
In your servlet, you should probably return a response/full structure with the image contents. You'll have to deal with the return code, MIME type, etc yourself. (See the example in the documentation.)
In the name of science, I am posting one half of the answer to my own question. This page will show images that are already in the database. The upload page is still an open question.
Ryan Culpepper helped me in private correspondence beyond of what is posted here. I thank him for his help. All things that may look like black magic come from him, and all clumsy goofs are mine. I will be grateful for all suggestions on how to improve the code.
#lang racket
#|
================================================================================================================
We are assuming that the PostgreSQL database we are connecting to
has a table "person" with columns
"id", "firstname", "lastname" and "portrait".
The "portrait" column contains the OID of a BLOB
that stores the image file we want to display.
Suppose further that the table "person" has a legitimate entry with
id=22, firstname="John", lastname="Doe"
Then the page
http://127.0.0.1/page/22
should display greetings "Hello, John Doe!"
and show the portrait of the person below the greeting.
The portrait itself should be at
http://127.0.0.1/portrait/22.jpg
The program should be run via Racket -t "<filename>"
after defining the environment variables
"DB_USER", "DB_NAME", "DB_PORT", "DB_PASSWORD".
================================================================================================================
|#
(require
web-server/servlet
web-server/servlet-env
web-server/dispatch
web-server/stuffers/hmac-sha1
web-server/http
web-server/http/response-structs
(planet ryanc/db:1:4)
(planet ryanc/db:1:4/util/connect)
net/base64)
;---------------------------------------------------------------------------------------------------------------
; response
;---------------------------------------------------------------------------------------------------------------
(define (start given-request)
(site-dispatch given-request))
(define-values (site-dispatch given-request)
(dispatch-rules
[("page" (integer-arg)) show-page]
[("portrait" (string-arg)) show-portrait]))
(define (show-page given-request given-person-id)
(let* ( [db-person_firstname_lastname
(query-maybe-row my-connection
"SELECT firstname, lastname FROM person WHERE id = $1"
given-person-id)]
[my-firstname (vector-ref db-person_firstname_lastname 0)]
[my-lastname (vector-ref db-person_firstname_lastname 1)])
(response/xexpr
`(html ([xmlns "http://www.w3.org/1999/xhtml"])
(head
(title "Page with a portrait"))
(body
(div ([id "greetings"])
,(string-append
"Hello, " my-firstname " " my-lastname "! "))
(img ( [src ,(string-append "/portrait/"
(number->string given-person-id) ".jpg")])))))))
(define (show-portrait given-request given-portrait-file)
(let* ( [my-user-id (car (regexp-match #rx"^([0-9]+)"
given-portrait-file))]
[my-portrait-oid (query-value my-connection
"SELECT portrait FROM person WHERE id = $1"
(string->number my-user-id))]
[STREAMOUT_CHUNK_SIZE 1000]
[INV_READ #x00040000])
(response
200 ; code
#"Okay" ; message
(current-seconds) ; seconds
#"image/jpeg" ; mime type
empty ; headers
(lambda (given-output-stream) ; body generator
(start-transaction my-connection)
(define object-descriptor
(query-value my-connection
"SELECT LO_OPEN( $1, $2 )" my-portrait-oid INV_READ))
(define (stream-next-chunk)
(begin
(define my-next-chunk
(query-value my-connection
"SELECT LOREAD( $1, $2 )"
object-descriptor STREAMOUT_CHUNK_SIZE))
(if (> (bytes-length my-next-chunk) 0)
(begin
(write-bytes my-next-chunk given-output-stream)
(stream-next-chunk)
#t)
#f)))
(stream-next-chunk)
(commit-transaction my-connection)))))
;---------------------------------------------------------------------------------------------------------------
; database connection
;---------------------------------------------------------------------------------------------------------------
(define my-connection
(virtual-connection
(connection-pool
(lambda ()
(eprintf "(Re)establishing database connection...\n")
(postgresql-connect
#:user (getenv "DB_USER")
#:database (getenv "DB_NAME")
#:port (string->number (getenv "DB_PORT"))
#:socket #f
#:password (getenv "DB_PASSWORD")
#:allow-cleartext-password? #f
#:ssl 'optional ; other choices: 'yes 'no
)))))
;---------------------------------------------------------------------------------------------------------------
; servlet parameters
;---------------------------------------------------------------------------------------------------------------
(serve/servlet start
#:command-line? #t ; #t to use serve/servlet in a start up script for a Web application, and don't want a browser opened or the DrRacket banner printed
#:connection-close? #f ; #t to close every connection after one request. (Otherwise, the client decides based on what HTTP version it uses.)
#:launch-browser? #f
#:quit? #f ; #t makes the URL "/quit" end the server
#:banner? #t ; #t to print an informative banner
#:listen-ip #f ; give an IP to accept connections from external machines
#:port 80 ; 443 is the default for SSL, 80 - for open connections
#:servlet-regexp #rx"" ; #rx"" captures top-level requests
#:stateless? #t
#:server-root-path ; where the server files are rooted, default=(the distribution root)
(build-path ".")
#:ssl? #f
#:log-file (build-path "server.log"))