Welcome, I'm happy to see you here! Feel free to add a happy example, the more the merrier!
(defn markdown/endnotes ``Gather [^5] type endnotes into closing section, each ending with link back to its reference``
[tree ]
(let [note? |(match $ [:endnote ] true )
notes (filter note? tree )]
(if (empty? notes ) tree
[;(filter (complement note? ) tree ) # save the others
[:section {:class "endnotes" }
[:ol {} ;(map (fn [[_ {:id n } & kids ]]
[:li {:id (string "endnote-" n )}
[:p {} ;kids " " [:a {:href (string "#endnote-ref-" n ) :class "endnote-backref" } "↩" ]]])
notes )]]])))(import sqlite3 :as sql )
(type (sql/open "example.db" )) # => :sqlite3.connection
(abstract? (sql/open "example.db" )) # => true
# Monadish thing capturing stdout, stderr and err codes
(import spork/sh-dsl :as sh )
(defn run `Run quoted shell cmd, returning stdout, stderr and exit code`
[pipeline ]
(let [[r w ] (os/pipe :W )
redirect ['>err ['unquote w ]]
pipe? |(and (tuple? $ ) (= 'short-fn (first $ )))
tokens @[;(mapcat |(if (pipe? $ ) [;redirect $ ] [$ ]) pipeline ) ;redirect ]
errs @""
[res ] (ev/gather
(defer (:close w ) (sh/run-pipeline tokens :capture-output true ))
(defer (:close r ) (ev/read r :all errs )))]
{:pipeline pipeline
:codes (slice res 0 -2 )
:out (string (last res ))
:err (string errs )}))
(defn then `Run quoted shell cmd, returning stdout or raising stderr unless ok? likes it`
[pipeline &named ok? ]
(let [ok? (or ok? |(all zero? ($ :codes )))
outcome (run pipeline )]
(if (ok? outcome ) (outcome :out ) (error (outcome :err )))))
# assuming these files don't exist:
(run '(diff a.txt b.txt )) # {:codes (2) :out "" :pipeline (diff "bla.txt" b.txt) :err "..."}
(then '(diff a.txt b.txt ) :ok? |(<= (last ($ :codes )) 1 )) # normal janet err
# For servers, wrap the handler (e.g. a Joy app) once
(defn header [req name ]
(let [name (string/ascii-lower name )]
(some (fn [[k v ]] (when (and (string? k ) (= name (string/ascii-lower k ))) v ))
(pairs (get req :headers {})))))
(defn with-request-ctx [handler ]
(fn [req ]
(deforester/with-log-ctx {:method (req :method )
:path (first (string/split "?" (req :uri ))) # eg holds tokens
:ip (let [addr (req :remote-addr )] # behind nginx every request is from 127.0.0.1
(if (= addr "127.0.0.1" ) (header req "X-Real-IP" ) addr ))
:user-agent (header req "User-Agent" )
:referer (header req "Referer" )}
(handler req )))) # every log inside the handler, however deep, gets these fields
(def app
(with-request-ctx
(fn [req ]
(deforester/log :info "search" :q "cat" ) # no need to pass req around just to log it
{:status 200 :body "ok" })))
# example call
(app {:method "GET" :uri "/search?q=cat" :remote-addr "127.0.0.1"
:headers {"X-Real-IP" "203.0.113.9" "User-Agent" "curl/8.5" }})# For a server
(defn log-response [res ]
(let [status (get res :status 200 )]
(deforester/log
(cond (>= status 500 ) :error
(= status 404 ) :warn
(and (res :file ) (= status 200 )) :debug
:else :info )
"request"
:status status
:bytes (length (get res :body "" )))))
(log-response {:status 200 :body "hello" })
(log-response {:status 404 })
(log-response {:status 503 :body "down" })(deforester/set-logger! {:min-level :info # :debug will show every file sent
:write (let [f (deforester/file-writer "log.log" )] # avoid making writer each call
(fn [s ] (eprint s ) (f s )))}) (def server # name it, to close it after
(with-dyns [:foo "foo" ]
(def env (curenv )) # must make a closure, otherwise it will use the fiber's env
(net/server "0.0.0.0" 9092 # starts a fiber
(fn [conn ]
# pass the saved env:
(fiber/setenv (fiber/current ) (table/setproto @{} env ))
(:write conn (dyn :foo )) # n.b. stringify if using other :foo value
(:close conn ))
:stream )))
(:read (net/connect "127.0.0.1" 9092 ) 1024 )
(:close server )# By default, top level defs perform better:
(defn let-sum [] (let [a 1 b 2 c 3 ] (+ a b c )))
(def a 1 )
(def b 2 )
(def c 3 )
(defn top-def-sum [] (+ a b c ))
(disasm let-sum ) # (ldi 0 1) (ldi 1 2) (ldi 2 3) (add 3 0 1) (add 3 3 2)
(disasm top-def-sum ) # (ldi 0 1) (addim 1 0 2) (addim 1 1 3)
# But with *optimize* level 3, they are both better
# n.b. func must be (re)defined after *optimize* is set
(setdyn *optimize* 3 )
(defn let-sum [] (let [a 1 b 2 c 3 ] (+ a b c )))
(defn top-def-sum [] (+ a b c ))
(disasm let-sum ) # (ldi 0 6)
(disasm top-def-sum ) # (ldi 0 6)
# currently, implemented optimizations are mostly in 1 and 2 # Janet numbers are "doubles" representing each int up to 2^53 (9007199254740992)
# Above this, they can't, so these both eval to the same thing!
(math/exp2 53 )
(+ 1 (math/exp2 53 ))
# After 2^53, doubles only represent even numbers
# Janet prints numbers above 2^53 in exponent form, hiding the end
(+ 2 (math/exp2 53 )) # 9.00719925474099e+15
# But the odd numbers round interestingly!
# 2^53 + 2, 2^53 + 4 etc. are slots. We choose which to round e.g. 2^53 + 3 into.
# In school, we round .5 up, doubles above 2^53 round .5 to the neighbor divisible by 4!
(def p53 (math/exp2 53 ))
(= (+ p53 1 ) p53 ) # true
(= (+ p53 2 ) p53 ) # false
(= (+ p53 1 ) (+ p53 2 )) # false
(= (+ p53 3 ) (+ p53 2 )) # false
(= (+ p53 3 ) (+ p53 4 )) # true
(= (+ p53 5 ) (+ p53 4 )) # true
(= (+ p53 5 ) (+ p53 6 )) # false
(= (+ p53 7 ) (+ p53 8 )) # true
(= (+ p53 9 ) (+ p53 8 )) # true
# After 2^54, it's the neighbor divisible by 8.
# After 2^55, it's the neighbor divisible by 16!
# It continues this way until 2^1024, which overflows to infinity
(= math/inf (math/exp2 1024 )) # true # If you have a working project.janet file, you can use it from janet-pm with just this:
(import spork/declare-cc )
(dofile "project.janet" :env (declare-cc/jpm-shim-env ))(let (sinlu (array/new 10 )) # 10 element look up table.
(for i 0 10 (put sinlu i (math/sin (* math/pi (/ i 10 )))))
(pp sinlu ))(let (x @["This" "is" "a" ] # Must be array.
y @["test" "of" ]
z ["the" "emergency!" ]) # Tuple OK for part.
(pp (array/join x y z )))
# @["This" "is" "a" "test" "of" "the" "emergency!"] (import spork/json )
(def input `` {"name": "person", "unknown": null, "happy": true, "sad": false} `` )
When calling , the json dictionary becomes a mutable table in janet.
(json/decode input )
@{"happy" true "name" "person" "sad" false "unknown" :null }
pass `true` as the first arg , and json keys become janet keywords.
(json/decode input true )
@{:happy true :name "person" :sad false :unknown :null }
pass `true` as the second arg , and json keys that map to `null` are not hydrated.
(json/decode input true true )
@{:happy true :name "person" :sad false }
(print "The build hash of your Janet executable is " janet/build "." )# Janet v1.42.0 -- See %src/include/janet.h.
(defn set? [position ] (["not set" "set" ] (band janet/config-bits position )))
(printf ```
Configurations:
* NANBOX %s.
* SINGLE_THREADED %s.
* NANBOX_64_POINTER_SHIFT %s.``` (set? 0x1 ) (set? 0x2 ) (set? 0x4 ))
(def cc (ev/thread-chan 99 )) # Sets up a message channel.
(def ww (filewatch/new cc )) # Creates the watcher.
(filewatch/add ww "ftest.janet" :all ) # Watch for all changes.
(filewatch/add ww "fadd.janet" :modify ) # Only care if modified.
(filewatch/listen ww ) # Start filewatcher listening for changes.
# Note that we may still get events for files that have been removed
# so we have to make sure we don't remove them twice.
(var careless "Have we already removed %fadd.janet?" false )
(forever
(let (item (ev/take cc ))
(pp (ev/take cc ))
(when (and (not careless ) (= "fadd.janet" (item :wd-path )))
(print "I don't care about this file anymore." )
(filewatch/remove ww (item :wd-path ))
(set careless true )
)))(def cc (ev/thread-chan 99 )) # Sets up a message channel.
(def ww (filewatch/new cc )) # Creates the watcher.
(filewatch/add ww "ftest.janet" :all ) # Watch for all changes.
(filewatch/add ww "fadd.janet" :modify ) # Only care if modified (Linux-specific flag).
(filewatch/listen ww ) # Start filewatcher listening for changes.
(pp (ev/take cc )) # Print info on first file to change.
(filewatch/unlisten ww ) # Stop caring about changes. (def cc (ev/thread-chan 99 )) # Sets up a message channel.
(def ww (filewatch/new cc )) # Creates the watcher.
(filewatch/add ww "ftest.janet" :all ) # Watch for all changes.
(filewatch/add ww "fadd.janet" :modify ) # Only care if modified.
(filewatch/listen ww ) # Start filewatcher listening for changes.
(pp (ev/take cc )) # Print info on first file to change.
(filewatch/unlisten ww ) # Stop caring about changes.
# This allows the program to exit -- otherwise
# filewatcher listening thread keeps running.
(def cc (ev/thread-chan 99 )) # Sets up a message channel.
(def ww (filewatch/new cc )) # Creates the watcher.
(filewatch/add ww "ftest.janet" :all ) # File to watch.
(filewatch/listen ww ) # Start filewatcher listening for changes.
(ev/spawn-thread # Spawn thread to catch change events.
(print "Waiting..." )
(forever (pp (ev/take cc ))))(def cc (ev/thread-chan 99 )) # Sets up a message channel.
(def ww (filewatch/new cc )) # Creates the watcher.
(filewatch/add ww "ftest.janet" :all ) # File to watch.
(filewatch/listen ww ) # Start filewatcher listening for changes.
(ev/spawn-thread # Spawn thread to catch change events.
(print "Waiting..." )
(forever (pp (ev/take cc ))))