Simplify toc creation

Simplify toc creation

--- src/catalog/layout/fop.clj
+++ src/catalog/layout/fop.clj
@@ -76,32 +76,34 @@
       (set/subset? items (set layout/subgenres))
       (keep items layout/subgenres))))

-(defn- toc-entry [items path to-depth indent-depth]
-  (let [depth (count path)]
-    [:fo:block (-> {:text-align-last "justify" :role "TOCI"}
-                   (cond-> (>= depth indent-depth) (assoc :start-indent "1em")))
-     [:fo:basic-link {:internal-destination (hash path)}
-      (inline {:role "Reference"} (layout/translations (last path)))
-      " " [:fo:leader {:leader-pattern "dots" :role "NonStruct"}] " "
-      [:fo:page-number-citation {:ref-id (hash path) :role "Reference"}]]
-     (when (and (map? items) (< depth to-depth))
-       (keep #(toc-entry (% items) (conj path %) to-depth indent-depth) (order (keys items))))]))
-
-(defn toc [items path to-depth indent-depth & {:keys [heading? editorial? recommendation-at-end? single-recommendation?]}]
+(defn- toc-entry
+  ([items path depth]
+   (toc-entry items path depth 1))
+  ([items path depth current-depth]
+   [:fo:block (-> {:text-align-last "justify" :role "TOCI"}
+                  (cond-> (> current-depth 1) (assoc :start-indent "1em")))
+    [:fo:basic-link {:internal-destination (hash path)}
+     (inline {:role "Reference"} (layout/translations (last path)))
+     " " [:fo:leader {:leader-pattern "dots" :role "NonStruct"}] " "
+     [:fo:page-number-citation {:ref-id (hash path) :role "Reference"}]]
+    (when (and (map? items) (< current-depth depth))
+      (keep #(toc-entry (% items) (conj path %) depth (inc current-depth)) (order (keys items))))]))
+
+(defn- add-extra-headings [entries editorial? recommendation-at-end? single-recommendation?]
+  (let [recommendation (if single-recommendation? :recommendation :recommendations)]
+    (cond
+      recommendation-at-end? (concat [:editorial] entries [recommendation])
+      editorial? (concat [:editorial recommendation] entries)
+      :else entries)))
+
+(defn toc [items path depth & {:keys [heading? editorial? recommendation-at-end? single-recommendation?]}]
   (when (map? items)
     [:fo:block {:line-height "150%"
                 :role "TOC"}
      (when heading? (heading :h1 :inhalt []))
-     (let [entries (order (keys items))
-           entries (cond
-                     recommendation-at-end? (concat [:editorial] entries [(if single-recommendation?
-                                                                            :recommendation
-                                                                            :recommendations)])
-                     editorial? (concat [:editorial (if single-recommendation?
-                                                      :recommendation
-                                                      :recommendations)] entries)
-                     :else entries)]
-       (keep #(toc-entry (get items %) (conj path %) to-depth indent-depth) entries))]))
+     (let [entries (-> items keys order
+                    (add-extra-headings editorial? recommendation-at-end? single-recommendation?))]
+       (keep #(toc-entry (get items %) (conj path %) depth) entries))]))

 (defn- to-url
   "Return an url given a `record-id`"
@@ -298,7 +300,7 @@
 (defn format-sexp [items fmt level]
   (when-let [items (fmt items)]
     [(heading (level-to-h level) fmt [fmt])
-     (toc items [fmt] 3 3)
+     (toc items [fmt] 2)
      (set-marker (layout/translations fmt))
      (case fmt
        (:hörfilm :ludo) (entries-sexp items)
@@ -425,7 +427,7 @@

       (let [subitems (get items fmt)]
         [:fo:flow {:flow-name "xsl-region-body"}
-         (toc subitems [fmt] 3 3 :heading? true :editorial? true :single-recommendation? true)
+         (toc subitems [fmt] 2 :heading? true :editorial? true :single-recommendation? true)
          (heading :h1 :editorial [fmt :editorial])
          (md-to-fop (slurp "/home/eglic/src/catalog/samples/editorial.md"))
          (heading :h1 :recommendation [fmt :recommendation])
@@ -448,11 +450,11 @@

     (let [subitems (get items fmt)]
       [:fo:flow {:flow-name "xsl-region-body"}
-       (toc subitems [fmt] 3 3 :heading? true :editorial? true :recommendation-at-end? true)
+       (toc subitems [fmt] 2 :heading? true :editorial? true :recommendation-at-end? true)
        (block {:break-before "odd-page"}) ;; the very first format should start on recto
        (heading :h1 :editorial [fmt :editorial])
        (heading :h1 :hörbuch [fmt :hörbuch])
-       (mapcat #(genre-sexp subitems fmt % 1) (order (keys subitems)))
+       (mapcat #(genre-sexp subitems fmt % 2) (order (keys subitems)))
        (heading :h1 :recommendations [fmt :recommendations])])]])

 (defmethod document-sexp :all-formats
@@ -470,7 +472,7 @@
     (header :verso)

     [:fo:flow {:flow-name "xsl-region-body"}
-     (toc items [] 1 2 :heading? true)
+     (toc items [] 1 :heading? true)
      (block {:break-before "odd-page"}) ;; the very first format should start on recto
      (mapcat #(format-sexp items % 1) (order (keys items)))]]])


formatting

formatting

--- src/chat/server/invite.clj
+++ src/chat/server/invite.clj
@@ -180,5 +180,6 @@
                           (img-format/as-stream ext))]
     (s3/put-object creds (env :aws-domain) (str "avatars/" avatar-filename) resized-image
                    {:content-type (f :content-type)})
-    (s3/update-object-acl creds (env :aws-domain) (str "avatars/" avatar-filename) (s3/grant :all-users :read))
+    (s3/update-object-acl creds (env :aws-domain) (str "avatars/" avatar-filename)
+                          (s3/grant :all-users :read))
     (str "https://s3.amazonaws.com/" (env :aws-domain) "/avatars/" avatar-filename)))


fix hook ur

fix hook ur

--- src/ci3/repo/bitbucket.clj
+++ src/ci3/repo/bitbucket.clj
@@ -26,7 +26,7 @@
 (defmethod u/*fn
   ::hook-url
   [{{host :hostname} :env {{nm :name} :metadata} :repository}] (println host)
-  {:hook-url (str host "/" (name nm))})
+  {:hook-url (str host "/webhook/" (name nm))})

 (defmethod u/*fn
   ::not-initialized?
@@ -138,9 +138,4 @@
   (k8s/find k8s/cfg :repositories "ci3")
   (k8s/resolve-secrets (k8s/find k8s/cfg :repositories "ci3"))

-  (u/*apply
-   [::ensure-hook]
-   {:env {:hostname "http://cleo-ci.health-samurai.io"}
-    :repository  (k8s/find k8s/cfg :repositories "ci3")})
-
   )


Refactor ssh connection, fix a bug where adding the default ~/.ssh/id_rsa identity prevented us from connecting with arbitrary SSH keys

--- src/circle/backend/ssh.clj
+++ src/circle/backend/ssh.clj
@@ -44,29 +44,36 @@
      :out (str stdout)
      :err (str stderr)}))

+(defn session
+  "Creates an SSH session on an arbitrary box. All keys are
+  required."
+  [& {:keys [username ip-addr public-key private-key]}]
+  (require-args username ip-addr private-key)
+  (let [agent (ssh/create-ssh-agent false)
+        _ (ssh/add-identity agent "bogus"
+                            (.getBytes private-key)
+                            (when public-key
+                              (.getBytes public-key)) nil)
+        session (ssh/session agent
+                             ip-addr
+                             :username username
+                             :strict-host-key-checking :no)]
+    session))
+
 (defn with-session
-  "Creates an SSH session on an arbitrary box. All keys are
-  required. f is a function of one argument, the ssh session, which
-  can be used with functions in clj-ssh.ssh"
-  [{:keys [username ip-addr public-key private-key]} f]
+  "Calls f, a function of one argument, the ssh session, while connected."
+  [session-args f]
   (require-args username ip-addr public-key private-key)
-  (ssh/with-ssh-agent []
-    ;; JSch wants a name for each keypair, it will not store duplicate
-    ;; keypair names on repeated calls to add-identity. But we always use a new agent, so we're fine.
-    (let [_ (ssh/add-identity ssh/*ssh-agent* "bogus"
-                              (.getBytes private-key)
-                              (.getBytes public-key) nil)
-          session (ssh/session ip-addr
-                               :username username
-                               :strict-host-key-checking :no)]
-      (try-try-again
-       {:sleep 1000
-        :tries 30
-        :catch [com.jcraft.jsch.JSchException]
-        :error-hook (fn [e] (errorf "caught %s" e))}
-       #(try
-          (ssh/with-connection session
-            (f session)))))))
+  (let [s (session session-args)]
+    (try-try-again
+     {:sleep 1000
+      :tries 30
+      :catch [com.jcraft.jsch.JSchException]
+      :error-hook (fn [e] (errorf "caught %s" e))}
+     #(try
+        (ssh/with-connection
+          (f session))))))
+

 (defn remote-exec
   "Node is a map containing the keys required by with-session"


More API documentation

More API documentation

--- src/simple_check/generators.clj
+++ src/simple_check/generators.clj
@@ -32,27 +32,32 @@
 (defn join-rose
   "Turn a tree of trees into a single tree. Does this by concatenating
   children of the inner and outer trees."
+  {:no-doc true}
   [[[inner-root inner-children] children]]
   [inner-root (concat (clojure.core/map join-rose children)
                       inner-children)])

 (defn rose-root
   "Returns the root of a Rose tree."
+  {:no-doc true}
   [[root _children]]
   root)

 (defn rose-children
   "Returns the children of the root of the Rose tree."
+  {:no-doc true}
   [[_root children]]
   children)

 (defn rose-pure
   "Puts a value `x` into a Rose tree, with no children."
+  {:no-doc true}
   [x]
   [x []])

 (defn rose-fmap
   "Applies functions `f` to all values in the tree."
+  {:no-doc true}
   [f [root children]]
   [(f root) (clojure.core/map (partial rose-fmap f) children)])

@@ -60,6 +65,7 @@
   "Takes a Rose tree (m) and a function (k) from
   values to Rose tree and returns a new Rose tree.
   This is the monadic bind (>>=) for Rose trees."
+  {:no-doc true}
   [m k]
   (join-rose (rose-fmap k m)))

@@ -67,12 +73,14 @@
   "Returns a new Rose tree whose values pass `pred`. Values who
   do not pass `pred` have their children cut out as well.
   Takes a list of roses, not a rose"
+  {:no-doc true}
   [pred [root children]]
   [root (clojure.core/map (partial rose-filter pred)
                           (clojure.core/filter (comp pred rose-root) children))])
 (defn rose-permutations
   "Create a seq of vectors, where each rose in turn, has been replaced
   by its children."
+  {:no-doc true}
   [roses]
   (apply concat
          (for [[rose index]
@@ -81,12 +89,14 @@

 (defn zip-rose
   "Apply `f` to the sequence of Rose trees `roses`."
+  {:no-doc true}
   [f roses]
   [(apply f (clojure.core/map rose-root roses))
    (clojure.core/map (partial zip-rose f)
                      (rose-permutations roses))])

 (defn remove-roses
+  {:no-doc true}
   [roses]
   (concat
     [(rest roses)]
@@ -94,6 +104,7 @@
     (rose-permutations (vec roses))))

 (defn shrink-rose
+  {:no-doc true}
   [f roses]
   (if (seq roses)
     [(apply f (clojure.core/map rose-root roses))
@@ -109,22 +120,26 @@
    {:gen generator-fn}))

 (defn call-gen
+  {:no-doc true}
   [{generator-fn :gen} rnd size]
   (generator-fn rnd size))

 (defn gen-pure
+  {:no-doc true}
   [value]
   (make-gen
     (fn [rnd size]
       value)))

 (defn gen-fmap
+  {:no-doc true}
   [k {h :gen}]
   (make-gen
     (fn [rnd size]
       (k (h rnd size)))))

 (defn gen-bind
+  {:no-doc true}
   [{h :gen} k]
   (make-gen
     (fn [rnd size]
@@ -179,10 +194,12 @@
 ;; ---------------------------------------------------------------------------

 (defn random
+  {:no-doc true}
   ([] (Random.))
   ([seed] (Random. seed)))

 (defn make-size-range-seq
+  {:no-doc true}
   [max-size]
   (cycle (range 0 max-size)))

@@ -226,6 +243,9 @@
       (+ (.nextInt rnd (inc diff)) lower))))

 (defn sized
+  "Create a generator that depends on the size parameter.
+  `sized-gen` is a function that takes an integer and returns
+  a generator."
   [sized-gen]
   (make-gen
     (fn [rnd size]
@@ -236,6 +256,7 @@
 ;; ---------------------------------------------------------------------------

 (defn resize
+  "Create a new generator with `size` always bound to `n`."
   [n {gen :gen}]
   (make-gen
     (fn [rnd _size]


Fix typo in comment

Fix typo in comment

--- src/simple_check/generators.clj
+++ src/simple_check/generators.clj
@@ -341,7 +341,7 @@
 (def int
   "Generates a positive or negative integer bounded by the generator's
   `size` parameter.
-  (Really returns a long"
+  (Really returns a long)"
   (sized (fn [size] (choose (- size) size))))

 (def nat


Made trained functions public

Made trained functions public

--- src/clj/asols/trainer.clj
+++ src/clj/asols/trainer.clj
@@ -115,7 +115,7 @@
         out-vec (forward layer (m/array in-vec))]
     (into values (map vector (:nodes layer) out-vec))))

-(defn- forward-pass
+(defn forward-pass
   "Performs forward pass, returns map of nodes outputs"
   [net input-vec]
   (let [input-layer (first (:layers net))
@@ -145,7 +145,7 @@
                                               (network/get-weight net e)))))]
                        [node delta]))))

-(defn- backward
+(defn backward-pass
   "Performs backward pass, returns map of nodes deltas"
   [net target-vec forward-values]
   (let [out-layer (last (:layers net))
@@ -161,7 +161,7 @@
   (let [{:keys [input-vec target-vec]} entry
         {:keys [learning-rate momentum l2-lambda]} train-opts
         forward-values (forward-pass net input-vec)
-        [deltas-map cost-val] (backward net target-vec forward-values)
+        [deltas-map cost-val] (backward-pass net target-vec forward-values)
         delta-w (into {} (for [[[node-from node-to :as e] weight] (:edges net)]
                            (let [delta-w (+ (* -1 learning-rate
                                                (deltas-map node-to)


confirm-ns needs to handle macro case which may refer to libs never explicitly required

--- src/clj/cljs/analyzer.clj
+++ src/clj/cljs/analyzer.clj
@@ -36,6 +36,12 @@
    :fn-arity true
    :fn-deprecated true
    :protocol-deprecated true})
+
+(defn munge-path [ss]
+  (clojure.lang.Compiler/munge (str ss)))
+
+(defn ns->relpath [s]
+  (str (string/replace (munge-path s) \. \/) ".cljs"))

 (def constant-counter (atom 0))

@@ -170,7 +176,10 @@

 (defn confirm-ns [env ns-sym]
   (when (and (nil? (get '#{cljs.core goog Math} ns-sym))
-             (nil? (get (-> env :ns :requires) ns-sym))
+             (nil? (get (-> env :ns :requires) ns-sym))
+             ;; macros may refer to namespaces never explicitly required
+             ;; confirm that the library at least exists
+             (nil? (io/resource (ns->relpath ns-sym)))
              (:undeclared *cljs-warnings*))
     (warning env
       (str "WARNING: No such namespace: " ns-sym))))
@@ -667,12 +676,6 @@
         (= targetexpr ::set-unchecked-if) {:env env :op :no-op}
         :else {:env env :op :set! :form form :target targetexpr :val valexpr
                :children [targetexpr valexpr]})))))
-
-(defn munge-path [ss]
-  (clojure.lang.Compiler/munge (str ss)))
-
-(defn ns->relpath [s]
-  (str (string/replace (munge-path s) \. \/) ".cljs"))

 (declare analyze-file)


check uses-macros

check uses-macros

--- src/clj/cljs/analyzer.clj
+++ src/clj/cljs/analyzer.clj
@@ -662,6 +662,13 @@
                (= (get-in @namespaces [lib :defs sym] ::not-found) ::not-found))
       (warning env
         (str "WARNING: Referred var " lib "/" sym " does not exist")))))
+
+(defn check-uses-macros [uses-macros env]
+  (doseq [[sym lib] uses-macros]
+    (when (and (:undeclared *cljs-warnings*)
+               (nil? (.findInternedVar ^clojure.lang.Namespace (find-ns lib) sym)))
+      (warning env
+        (str "WARNING: Referred macro " lib "/" sym " does not exist")))))

 (defmethod parse 'ns
   [_ env [_ name & args :as form] _]
@@ -757,6 +764,8 @@
     (load-core)
     (doseq [nsym (concat (vals requires-macros) (vals uses-macros))]
       (clojure.core/require nsym))
+    (when (seq uses-macros)
+      (check-uses-macros uses-macros env))
     (swap! namespaces #(-> %
                            (assoc-in [name :name] name)
                            (assoc-in [name :doc] docstring)


#5 compile-file

#5 compile-file

--- src/clj/cljs/compiler.clj
+++ src/clj/cljs/compiler.clj
@@ -863,6 +863,39 @@
              ;;(prn (if (nil? ret) nil ret))
              (recur))))))))

+(defn forms-seq
+  "Seq of forms in a Clojure or ClojureScript file."
+  ([f]
+     (forms-seq f (java.io.PushbackReader. (io/reader f))))
+  ([f ^java.io.PushbackReader rdr]
+     (if-let [form (read rdr nil nil)]
+       (lazy-seq (cons form (forms-seq f rdr)))
+       (.close rdr))))
+
+(defn compile-file
+  "Compiles src to a file of the same name, but
+   with a .js extension, in the src file's directory.
+
+   With dest argument, write file to provided location."
+  ([src]
+     (let [dest (clojure.string/replace src #".cljs$" ".js")]
+       (compile-file src dest)))
+  ([src dest]
+     (with-open [out ^java.io.Writer (io/make-writer (io/file dest) {})]
+       (binding [*out* out
+                 *cljs-ns* 'cljs.user]
+         (doseq [form (forms-seq src)]
+           (emit (analyze {} form)))))))
+
+(comment
+  ;; flex compile-file
+  (do
+    (compile-file "/tmp/hello.cljs" "/tmp/something.js")
+    (slurp "/tmp/hello.js")
+
+    (compile-file "/tmp/somescript.cljs")
+    (slurp "/tmp/somescript.js")))
+
 (comment

 ;;the new way - use the REPL!!


added :ignore-unknown-values and :skip-invalid-rows BQ options ; fixed :without-validation

--- src/clj/datasplash/bq.clj
+++ src/clj/datasplash/bq.clj
@@ -200,7 +200,20 @@
                                   create-disposition-enum
                                   (fn [transform enum] (.withCreateDisposition transform enum)))}
     :without-validation {:docstr "Disables validation until runtime."
-                         :action (fn [transform] (.withoutValidation transform))}
+                         :action (fn [transform without-validation]
+                                   (if without-validation
+                                     (.withoutValidation transform)
+                                     transform))}
+    :ignore-unknown-values {:docstr "Ignores fields which does not match the schema."
+                            :action (fn [transform ignore-unknown-values]
+                                      (if ignore-unknown-values
+                                        (.ignoreUnknownValues transform)
+                                        transform))}
+    :skip-invalid-rows {:docstr "Skips invalid rows. Only works with :streaming write method."
+                        :action (fn [transform skip-invalid-rows]
+                                  (if skip-invalid-rows
+                                    (.skipInvalidRows transform)
+                                    transform))}
     :retry-policy {:docstr "Specify retry policy for failed insert in streaming"
                    :action (select-enum-option-fn
                             :retry-policy


logf variants

logf variants

--- src/clj/shale/logging.clj
+++ src/clj/shale/logging.clj
@@ -35,12 +35,21 @@
 (defmacro info [obj]
   `(timbre/info ~obj))

+(defmacro infof [& args]
+  `(timbre/infof ~@args))
+
 (defmacro warn [obj]
   `(timbre/warn ~obj))
+
+(defmacro warnf [& args]
+  `(timbre/warnf ~@args))

 (defmacro error [obj]
   `(timbre/error ~obj))

+(defmacro errorf [& args]
+  `(timbre/errorf ~@args))
+
 (s/defn ^:always-validate new-logger :- Logger
   []
   (map->Logger {}))


Basic update entities to prove it works

Basic update entities to prove it works

--- src/cljs/engine/core.cljs
+++ src/cljs/engine/core.cljs
@@ -30,24 +30,18 @@
    Iterates through all the entities and renders them to the stage.
    Renders the stage to the screen"
   [renderer stage]
-  (clear-stage stage)
   (info "draw function called")
   (when-not @paused
     (doseq [e @entities]
           (render-entity stage e))
     (.render renderer stage)))

-(defn clear-stage
-  "Remove all children from a stage instance"
-  [stage]
-  (doseq [child (.slice (.-children stage) 0)]
-    (.removeChild stage child)))
-
 (defn update-entity [entity]
   ;; (-> entity
   ;;     update-movement
   ;;     update-collisions
   ;;     )
+  (aset entity "rotation" (+ 0.05 (aget entity "rotation")))
   entity)

 (defn tick-game
@@ -59,11 +53,9 @@
 (defn game-loop
   "Calculate changes based on the time since last change"
   []
-  ;; TODO start timer
-  ;; TODO stop timer
   ;; TODO Calculate the changes since the last game tick
   ;; TODO should this be async? Allows skipping frames
-  (.setInterval js/window #(tick-game time) 1000))
+  (.setInterval js/window #(tick-game time) (/ 1000 60)))

 (def stage (js/PIXI.Stage. 0x66ff99))

@@ -76,7 +68,7 @@
         height 600
         renderer (js/PIXI.CanvasRenderer. width height)]
     (dom/append! (sel1 :body) (.-view renderer))
-    (.setInterval js/window #(draw renderer stage) 1000)))
+    (.setInterval js/window #(draw renderer stage) (/ 1000 60))))

 (defn start []
   (create-entity! stage "static/images/bunny.png")


Add more example on pmap

Add more example on pmap

--- src/clojure/cfbt/ch10.clj
+++ src/clojure/cfbt/ch10.clj
@@ -239,4 +239,61 @@
 ;; => TROLL: Time to eat you, succulent human!
 ;; => SUCCULENT HUMAN: Ooooh! The answer was man meat

-
+;; Per-Thread Binding
+(.write *out* "prints to repl")
+
+(.start) (Thread. #(.write *out* "prints to standard out"))
+
+(let [out *out*]
+  (.start
+   (Thread. #(binding [*out* out]
+               (.write *out* "prints to repl from thread")))))
+
+
+(.start (Thread. (bound-fn [] (.write *out* "print to repl from thread!"))))
+
+;; Altering the Var Root
+
+(def power-source "hair")
+
+(alter-var-root #'power-source (fn [_] "7-eleven parking lot"))
+
+power-source ;; "7-eleven parking lot"
+
+(with-redefs [*out* *out*]
+  (doto (Thread. #(println "with redefs allow me to show up in the REPL"))
+    .start
+    .join))
+
+;; pmap examples
+(defn always-1
+  []
+  1)
+
+(take 5 (repeatedly always-1)) ;; (1 1 1 1 1)
+
+;; lazy sequence of random numbers between 0 and 9
+(take 5 (repeatedly (partial rand-int 10))) ;; (0 5 8 4 9)
+
+;; compare the performance of pmap and map
+(def alphabet-length 26)
+
+;; Vector of chars, A-Z
+(def letters (mapv (comp str char (partial + 65)) (range alphabet-length)))
+
+(defn random-string
+  "Returns a random string of specified length"
+  [length]
+  (apply str (take length (repeatedly #(rand-nth letters)))))
+
+(defn random-string-list
+  [list-length string-length]
+  (doall (take list-length (repeatedly (partial random-string string-length)))))
+
+(def orc-names (random-string-list 3000 7000))
+
+(time (dorun (map clojure.string/lower-case orc-names)))
+;; Elapsed time: 320.863699 msec
+
+(time (dorun (pmap clojure.string/lower-case orc-names)))
+;; Elapsed time: 184.969880 msec


Moar.

Moar.

--- src/clojurecraft/core.clj
+++ src/clojurecraft/core.clj
@@ -164,6 +164,7 @@
             (= packet-type :login) (read-packet-login conn)
             (= packet-type :chat) (read-packet-chat conn)
             (= packet-type :timeupdate) (read-packet-timeupdate conn)
+            (= packet-type :equipment) (read-packet-equipment conn)
             :else (str "UNKNOWN PACKET TYPE: " packet-id)
             ))
         (println "\n\n\n")))


CLJS-1192: eliminate JDK8 API dependency in cljs.repl.node

--- src/clj/cljs/repl/node.clj
+++ src/clj/cljs/repl/node.clj
@@ -82,7 +82,7 @@
   ;; we really do want system-default encoding here
   (with-open [^java.io.Reader in (-> in InputStreamReader. BufferedReader.)]
     (loop [buf (char-array 1024)]
-      (when (.isAlive proc)
+      (when (try (.exitValue proc) false (catch IllegalThreadStateException _ true))
         (try
           (let [len (.read in buf)]
             (when-not (neg? len)


Factorial and primefactors computation

Factorial and primefactors computation

--- src/clj_mrazik/irc_bot.clj
+++ src/clj_mrazik/irc_bot.clj
@@ -63,6 +63,18 @@
      " " (rand-nth adjectives)
      " " (rand-nth nouns)))

+(defn primefactors
+    ([n]
+        (primefactors n 2 '()))
+    ([n candidate accumulator]
+        (cond (<= n 1) (reverse accumulator)
+              (zero? (rem n candidate)) (recur (/ n candidate) candidate (cons candidate accumulator))
+              :else (recur n (inc candidate) accumulator))))
+
+(defn factorial
+    [n]
+    (reduce *' (range 1 (inc n))))
+
 (defn prepare-reply-text
     [incomming-message nick input-text]
     (let [in-channel? (message-to-channel? incomming-message)
@@ -80,7 +92,7 @@
                           "die"      "thanks for your feedback, I appreciate it"
                           "Good bot" "I know"
                           "Good bot." "I know"
-                          (random-message))]
+                                                    (random-message)))]
         (str prefix response)))

 (defn on-incoming-message


Bugfix: Fixed regression on thread display

Commit d28f9f5 did not consider that we had to add the :html to the
loaded thread as well.

--- src/cljs/memento/core.cljs
+++ src/cljs/memento/core.cljs
@@ -123,6 +123,18 @@

 (def history
   (pushy/pushy set-page! bidi-matcher #_(partial bidi/match-route routes)))
+
+
+;;;;-------------------------
+;;;; Helpers
+;;;;-------------------------
+
+(defn add-html-to-thoughts
+  "Receives a list of thoughts and converts the markdown to html, adding it
+  to the map as a :html attribute"
+  [thoughts]
+  (map #(assoc % :html (md->html (:thought %) :replacement-transformers md-transformers))
+       thoughts))

@@ -236,12 +248,10 @@
 (register-handler
   :memories-load-success
   (fn [app-state [_ memories]]
-    (let [transformed (map #(assoc % :html (md->html (:thought %) :replacement-transformers md-transformers))
-                           (:results memories))]
-      (-> app-state
-          (assoc-in [:search-state :list] (concat (get-in app-state [:search-state :list]) transformed))
-          (assoc-in [:search-state :last-result] memories)
-          (assoc-in [:ui-state :is-searching?] false)))
+    (-> app-state
+        (assoc-in [:search-state :list] (concat (get-in app-state [:search-state :list]) (add-html-to-thoughts (:results memories))))
+        (assoc-in [:search-state :last-result] memories)
+        (assoc-in [:ui-state :is-searching?] false))
     ))

 (register-handler
@@ -357,7 +367,7 @@
     (dispatch [:state-ui-section :remember])
     (-> app-state
         (assoc-in [:ui-state :show-thread?] true)
-        (assoc-in [:note :thread] (:results result)))
+        (assoc-in [:note :thread] (add-html-to-thoughts (:results result))))
     ))


Fix core.clj

Fix core.clj

--- src/clojure/cljam/core.clj
+++ src/clojure/cljam/core.clj
@@ -10,8 +10,7 @@
                    [fasta :as fa]
                    [fasta-indexer :as fai]
                    [dict :as dict]
-                   [pileup :as plp]
-                   [mpileup :as mplp])
+                   [pileup :as plp])
             [cljam.util.sam-util :refer [stringify-header stringify-alignment]])
   (:gen-class))

@@ -162,7 +161,7 @@
         (println "Not sorted")
         (System/exit 1))
       (doseq [rname (map :name (read-refs r))
-              line  (mplp/mpileup r rname)]
+              line  (plp/mpileup r rname)]
         (if-not (zero? (:count line))
          (println (clojure.string/join \tab (map val line))))))
     nil))


Removed old (use ).

Removed old (use ).

--- src/clojure_robby/core.clj
+++ src/clojure_robby/core.clj
@@ -1,9 +1,6 @@
 (ns clojure-robby.core
   (:gen-class)
   (:use clojure-robby.genetic))
-
-
-;(use 'clojure-robby.genetic)

 ; Evolution functions


Added :description to get-links

Added :description to get-links

--- src/hackerati_interval_web_app/schema.clj
+++ src/hackerati_interval_web_app/schema.clj
@@ -76,14 +76,14 @@
 (defn get-links
   ([]
      (->> (select products)
-          (map :url)))
+          (map #(select-keys % [:url :description]))))
   ([username]
      (->> (select users
                   (fields [:products.url])
                   (join [tracked-links :trackedlinks] {:users.userid :trackedlinks.userid})
                   (join [products :products] {:products.productid :trackedlinks.productid})
                   (where {:username username}))
-          (map :url))))
+          (map #(select-keys % [:url :description] )))))

 (defn get-user-pw [username]
   (->> (select users


fixing typos & broken hiccup link

fixing typos & broken hiccup link

--- doc/.template/posts/03-edit-template.html.clj
+++ doc/.template/posts/03-edit-template.html.clj
@@ -1,5 +1,5 @@
 (h2 "Template file")
-(p "Template files are compiled with [hiccup](aa).")
+(p "Template files are compiled with [hiccup](https://github.com/weavejester/hiccup/).")

 (h3 "Example")
@@ -8,10 +8,10 @@
 ; @layout  default
 ; @title   misaki

-;; definition your clojure function
+;; define a custom clojure function
 (defn header [s] [:header [:h1 s]])

-;; "site" variable to access template options
+;; passing the "site" variable for access to template options
 (header (:title site))

 [:h2 "Posts"]
@@ -22,7 +22,7 @@

 ; /Example

-(h3 "Tempalte options")
+(h3 "Template options")
 (p "Template option format:")

 #-CLJ
@@ -39,9 +39,9 @@
    ]
   )

-(h4 "Access tepalte options")
+(h4 "Access template options")

-(p "misaki provides `site` variable to access defined tempalte options. For example, you can access template title with `(:title site)`.")
+(p "misaki provides a `site` variable with access to various template options. For example, you can access the template title with `(:title site)`.")

 (h4 "Site updated date")
@@ -52,13 +52,13 @@

 (h3 "Functions")

-(p "You can define your own function in template or layout. However, special variable(e.g., `site` and `contents`) is not accessible in those functions.")
+(p "You can define your own function in template or layout. However, the special misaki variables (e.g., `site` and `contents`) are not accessible in those functions.")

 ; /Functions

 (h3 "Posts")

-(p "`(:posts site)` is post data list.")
+(p "`(:posts site)` contains a list of clojure hash-maps, one for each blog post.")

 (h4 "Post data format")
@@ -83,7 +83,7 @@

 (h3 "Post tags")

-(p "`(:tags site)` is all post's tag data list.")
+(p "`(:tags site)` contains a list of hash-maps for a post's tags.")

 (h4 "Tag data format")
@@ -98,7 +98,7 @@

 (h3 "Code Highlight")

-(p "Codes are highlighted by [google-code-prettify](http://code.google.com/p/google-code-prettify/).")
+(p "Code is highlighted using [google-code-prettify](http://code.google.com/p/google-code-prettify/).")

 #-CLJ
 #-CODE
@@ -117,7 +117,7 @@
 (h2 "Layout file")
 (h3 "Example")

-(p "Layout options is same as template options.")
+(p "Layout options are the same as template options.")

 #-CLJ
 ; @title  default title
@@ -128,7 +128,7 @@
 [:body contents]
 CLJ

-(h4 "Special variable")
+(h4 "Special variables")

 (ul [
      (p "`site`: Variable to access layout options.")


restrcuture

restrcuture

--- src/epicea/typed/core.clj
+++ src/epicea/typed/core.clj
@@ -57,12 +57,14 @@
                     :tag (constantly true)
                     :data ::sized-type))

-(spec/def ::sized-type (spec/or :double ::double
-                                :float ::float
-                                :long ::long
-                                :int ::int
-                                :bool ::bool
-                                :number ::number
+(spec/def ::primitive (spec/or :double ::double
+                               :float ::float
+                               :long ::long
+                               :int ::int
+                               :bool ::bool
+                               :number ::number))
+
+(spec/def ::sized-type (spec/or :primitive ::primitive
                                 :record ::record
                                 :union ::union
                                 :unspecified ::unspecified ;; <-- a primitive building block


Allow pipelined (non-throwing) parsing exceptions

--- src/taoensso/carmine/protocol.clj
+++ src/taoensso/carmine/protocol.clj
@@ -173,7 +173,8 @@
 (defn- get-parsed-reply! [^DataInputStream in parser]
   (if parser
     (let [{:keys [dummy-reply? raw?] :as m} (meta parser)]
-      (parser (when-not dummy-reply? (get-basic-reply! in raw?))))
+      (let [reply (when-not dummy-reply? (get-basic-reply! in raw?))]
+        (try (parser reply) (catch Exception e e))))
     (get-basic-reply! in)))

 (defn get-replies!


Small test cases for parallel-closures

Small test cases for parallel-closures

Signed-off-by: Daniel Borchmann <25857343a15bf1edafebc2912e82ecf775c585c1@mailbox.tu-dresden.de>

--- src/conexp/tests/base.clj
+++ src/conexp/tests/base.clj
@@ -354,6 +354,22 @@
          (seq [#{} #{1} #{2} #{2 1} #{3} #{3 1} #{3 2} #{3 2 1}])))
   (is (= (all-closed-sets [1 nil] identity)
          (seq [#{} #{nil} #{1} #{1 nil}]))))
+
+(defn clop-by-subsets [base subsets]
+  (fn [X]
+    (reduce intersection base (filter #(subset? X %) subsets))))
+
+(deftest test-parallel-closures
+  (dotimes [i 13]
+    (is (= (expt 2 (+ i 1))
+           (count (parallel-closures (set-of-range (+ i 2)) #(conj % 1))))))
+  (are [base subsets] (= (set (all-closed-sets base (clop-by-subsets base subsets)))
+                         (set (parallel-closures base (clop-by-subsets base subsets))))
+    #{1 2 3 4} [#{1 2} #{3 4}]
+    #{1 2 3 4} [#{1} #{2} #{3}]
+    #{1 2 3 5 7} [#{1 2 3} #{1 2 3 5} #{1 2 3 7}]))
+
+;;;

 (deftest test-subsets
   (is (= #{#{} #{1} #{2} #{1 2}}


Re-enable file store behavior checks.

Re-enable file store behavior checks.

--- test/blocks/store/file_test.clj
+++ test/blocks/store/file_test.clj
@@ -11,17 +11,6 @@
   []
   (io/file "target" "test" "tmp"
            (str "file-block-store." (System/currentTimeMillis))))
-
-
-(deftest conversion-tests
-  (testing "file->id"
-    (let [file->id @#'file/file->id]
-      (is (nil? (file->id nil nil))
-          "should return nil for nil files")
-      (is (nil? (file->id "foo/bar" (io/file "foo" "baz" "abc")))
-          "should return nil for non-child files")
-      (is (nil? (file->id "foo/bar" (io/file "foo" "bar" "1220" "ab" "0x" "123abc")))
-          "should return nil for non-hex files"))))

 #_
@@ -43,5 +32,6 @@
 (deftest ^:integration check-behavior
   (let [tmpdir (mk-tmpdir!)]
     (test-harness/check-store
-      #(doto (file-block-store tmpdir)
-         (block/erase!)))))
+      #(let [store (file-block-store tmpdir)]
+         @(block/erase! store)
+         store))))


Reinstate tests for processor module.

Reinstate tests for processor module.

They were deactivated by mistake.

--- clstreams/test/clstreams/processor_test.clj
+++ clstreams/test/clstreams/processor_test.clj
@@ -3,7 +3,7 @@
             [clstreams.processor :as sut]
             [clstreams.testutil.topology-driver :as drv]))

-(comment :update-me deftest test-transducing-processor
+(deftest test-transducing-processor
   (let [data [["a" "1"] ["b" "2"] ["c" "3"]]]
     (testing "can perform arbitrary reductions on its input"
       (let [state (atom 0)
@@ -41,7 +41,7 @@
         (is (= @ctx1 @ctx2))))))

-(comment :update-medeftest test-key-value-processor
+(deftest test-key-value-processor
   (let [data [["a" "1"] ["b" "2"] ["c" "3"]]]
     (is (= (drv/through-kstreams-processor
             (sut/key-value-processor


Fix test.

Fix test.

--- test/cli4clj/test/cli_tests.clj
+++ test/cli4clj/test/cli_tests.clj
@@ -194,7 +194,7 @@
 (test/deftest clojure-repl-stderr-div-zero-test
   (let [in-cmds ["(/ 1 0)"]
         out (cli-tests/test-cli-stderr clojure.main/repl in-cmds)]
-    (test/is (.startsWith out "Execution error (ArithmeticException)"))))
+    (test/is (.startsWith out "ArithmeticException Divide by zero"))))

 (test/deftest clojure-repl-stdout-no-op-no-prompt-test
   (let [in-cmds [""]


use are instead of is for valued anagrams

--- test/clj/scrabble/core_test.clj
+++ test/clj/scrabble/core_test.clj
@@ -74,7 +74,7 @@

 (t/deftest valued-anagrams-test
   (t/testing "valued-anagrams"
-    (t/is (= (scrabble/valued-anagrams "211e1" "friend") '(["fined" 14] ["fired" 13] ["fried" 13] ["finer" 13] ["infer" 10] ["diner" 9])) )))
+    (t/are [tiles word ans] (= (scrabble/valued-anagrams tiles word) ans) "211e1" "friend" '(["fined" 14] ["fired" 13] ["fried" 13] ["finer" 13] ["infer" 10] ["diner" 9]))))

 (t/deftest matches-test
   (t/testing "get the best possible placements"


Cleanup.

Cleanup.

--- src/gorilla_repl/core.clj
+++ src/gorilla_repl/core.clj
@@ -20,12 +20,6 @@
             [clojure.java.io :as io])
   (:gen-class))

-;; useful for debugging the nREPL requests
-(defn print-req
-  [handler]
-  (fn [request]
-    (println (:params request))
-    (handler request)))

 ;; a wrapper for JSON API calls
 (defn wrap-api-handler


Clean up syllabize cond branches

Clean up syllabize cond branches

--- src/hangul_utils/core.clj
+++ src/hangul_utils/core.clj
@@ -80,17 +80,17 @@
 (defn syllabize
   "Takes a string of Korean alphabets, and reconstructs Korean text."
   [s]
-  (let [[a s l]
+  (let [[acc syl limbo]
         (reduce
          (fn [[acc syl limbo] c]
            (cond
-             (and (empty? syl) (initial? c)) [acc [c] nil]
-             (and (= 1 (count syl)) (not limbo) (medial? c)) [acc (conj syl c) nil]
-             (and (= 1 (count syl)) (not limbo) (not (medial? c))) [(conj acc syl) [c] nil]
-             (and (not limbo) (final? c)) [acc syl c]
-             (and limbo (initial? c)) [(conj acc (conj syl limbo)) [c] nil]
-             (and limbo (medial? c)) [(conj acc syl) [limbo c] nil]
-             :else [(conj acc (conj syl limbo) [c]) [] nil]))
+             (and (empty? syl) (initial? c))     [acc [c] nil]
+             (and (= 1 (count syl)) (not limbo)) (if (medial? c) [acc (conj syl c) nil]
+                                                     [(conj acc syl) [c] nil])
+             (and (not limbo) (final? c))        [acc syl c]
+             (and limbo (initial? c))            [(conj acc (conj syl limbo)) [c] nil]
+             (and limbo (medial? c))             [(conj acc syl) [limbo c] nil]
+             :else                               [(conj acc (conj syl limbo) [c]) [] nil]))
          [[] [] nil]
          s)]
-    (construct-str (conj a (conj s l)))))
+    (construct-str (conj acc (conj syl limbo)))))


give paths a proper bounding box

give paths a proper bounding box

--- src-cljs/frontend/controllers/controls.cljs
+++ src-cljs/frontend/controllers/controls.cljs
@@ -468,7 +468,13 @@
                                  :layer/ry (Math/abs (- (:layer/start-y %)
                                                         (:layer/end-y %)))})
                               (when (= layer-type :layer.type/path)
-                                {:layer/path (svg/points->path (:points layer))})
+                                (let [xs (map :rx (:points layer))
+                                      ys (map :ry (:points layer))]
+                                  {:layer/path (svg/points->path (:points layer))
+                                   :layer/start-x (apply min xs)
+                                   :layer/end-x (apply max xs)
+                                   :layer/start-y (apply min ys)
+                                   :layer/end-y (apply max ys)}))
                               (when (= layer-type :layer.type/text)
                                 {:layer/end-x (+ (get-in layer [:layer/start-x])
                                                  (get-in layer [:bbox :width]))


Update REST call

Update REST call

--- src-cljs/frontend/controllers/controls.cljs
+++ src-cljs/frontend/controllers/controls.cljs
@@ -430,8 +430,8 @@
 (defmethod post-control-event! :stopped-building-project
   [target message {:keys [vcs-url project-id]} previous-state current-state]
   (let [api-ch (get-in current-state [:comms :api])]
-    (button-ajax :post
-                 (gstring/format "/api/v1/project/%s/stop-building" (vcs-url/project-name vcs-url))
+    (button-ajax :delete
+                 (gstring/format "/api/v1/project/%s/enable" (vcs-url/project-name vcs-url))
                  :stop-building-project
                  api-ch
                  :context {:project-id project-id}))


Quit tracking v2 opt in events

Quit tracking v2 opt in events

--- src-cljs/frontend/controllers/controls.cljs
+++ src-cljs/frontend/controllers/controls.cljs
@@ -1139,20 +1139,6 @@
             (put! (:errors comms) [:api-error api-result]))
           (api/get-project-settings project-name (:api comms))))))

-(defmethod post-control-event! :try-ui-v2-clicked
-  [target message _ state]
-  (feature/enable-in-cookie :ui-v2)
-  (track-and-redirect "Try UI V2 Clicked" {} js/location))
-
-(defmethod post-control-event! :disable-ui-v2-clicked
-  [target message _ state]
-  (feature/disable-in-cookie :ui-v2)
-  (track-and-redirect "Disable UI V2 Clicked" {} js/location))
-
-(defmethod post-control-event! :ui-v2-beta-feedback
-  [target message _ state]
-  (analytics/track "UI V2 Beta Feedback Clicked"))
-
 (defmethod post-control-event! :project-experiments-feedback-clicked
   [target message _ previous-state current-state]
   (support/raise-dialog (get-in current-state [:comms :errors])))


Update project-follow and project-unfollow API Calls

  Update project-follow and project-unfollow API calls to use `api-path` util

--- src-cljs/frontend/controllers/controls.cljs
+++ src-cljs/frontend/controllers/controls.cljs
@@ -456,7 +456,7 @@
         org-name (vcs-url/org-name vcs-url)
         repo-name (vcs-url/repo-name vcs-url)]
     (button-ajax :post
-                 (gstring/format "/api/v1/project/%s/follow" project)
+                 (api-path/project-follow (:vcs_type repo) project)
                  :follow-repo
                  api-ch
                  :params {:vcs-type (:vcs_type repo)}
@@ -478,9 +478,10 @@
         login (get-in current-state state/user-login-path)
         project (vcs-url/project-name vcs-url)
         org-name (vcs-url/org-name vcs-url)
-        repo-name (vcs-url/repo-name vcs-url)]
+        repo-name (vcs-url/repo-name vcs-url)
+        vcs-type (vcs-url/vcs-type vcs-url)]
     (button-ajax :post
-                 (gstring/format "/api/v1/project/%s/follow" project)
+                 (api-path/project-follow vcs-type project)
                  :follow-project
                  api-ch
                  :context {:project-id project-id})
@@ -499,7 +500,7 @@
         org-name (vcs-url/org-name vcs-url)
         repo-name (vcs-url/repo-name vcs-url)]
     (button-ajax :post
-                 (gstring/format "/api/v1/project/%s/unfollow" project)
+                 (api-path/project-unfollow (:vcs_type repo) project)
                  :unfollow-repo
                  api-ch
                  :params {:vcs-type (:vcs_type repo)}
@@ -518,7 +519,7 @@
         org-name (vcs-url/org-name vcs-url)
         repo-name (vcs-url/repo-name vcs-url)]
     (button-ajax :post
-                 (gstring/format "/api/v1/project/%s/unfollow" project)
+                 (api-path/project-unfollow (:vcs_type repo) project)
                  :unfollow-project
                  api-ch
                  :params {:vcs-type (:vcs_type repo)}


Add TODOs

Add TODOs

--- src-cljs/qcon/main.cljs
+++ src-cljs/qcon/main.cljs
@@ -163,6 +163,7 @@
 (def app-model
   (atom {:current-slide 8
          :slides
+         ;; TODO Add cardinal such that each slide has its own number to avoid react warning
          [{:title "core.async"
            :event "QCon 2014"
            :author "Malcolm Sparks"
@@ -199,13 +200,18 @@
            :custom go-block-slide
            :opts {:font-size "80pt" :circles 5}
            }
-          ;; Show result of race in alts! between a channel and a timeout
+
+          ;; TODO Play catch between go blocks
+
+          ;; TODO Show source code from cljs sources on disk - via cljs - use different namespaces
+
+          ;; TODO result of race in alts! between a channel and a timeout

           ;; Go blocks

           {:title "When?"}

-          {:title "Hello Ruben"}
+          ;; TODO Don't forget to mention Hecuba and Stentor (that they're free software)

           {:title "END?"}]}))


Lots of blocks.core refactoring.

Lots of blocks.core refactoring.

--- src/blocks/core.clj
+++ src/blocks/core.clj
@@ -1,12 +1,18 @@
-(ns blobble.core
-  "Blob record and storage protocol functions.
+(ns blocks.core
+  "Block record and storage protocol functions.

-  When blobs are returned from a blob store, they may include 'stat' metadata
-  about the blobs:
+  Blocks have the following two primary attributes:
+
+  - `:content`   read-only Java `ByteBuffer` with opaque content
+  - `:id`        `Multihash` with the digest identifying the content
+
+  Blocks may be given other attributes describing their content. When blocks
+  are returned from a block store, they may include 'stat' metadata about the
+  blocks:

   - `:stat/size`        content size in bytes
-  - `:stat/stored-at`   time blob was added to the store
-  - `:stat/origin`      resource location for the blob"
+  - `:stat/stored-at`   time block was added to the store
+  - `:stat/origin`      resource location for the block"
   (:refer-clojure :exclude [get list])
   (:require
     [byte-streams :as bytes]
@@ -16,120 +22,137 @@
     multihash.core.Multihash))

-;; ## Blob Record
+(defn- resolve-hash!
+  "Resolves an algorithm designator to a hash function. Throws an exception on
+  invalid names or error."
+  [algorithm]
+  (cond
+    (nil? algorithm)
+      (throw (IllegalArgumentException.
+               "Cannot find hash function without algorithm name"))

-;; Blobs have the following two primary attributes:
-;;
-;; - `:id`        `Multihash` with the digest identifying the content
-;; - `:content`   read-only Java `ByteBuffer` with opaque content
-;;
-;; Blobs may be given other attributes describing their content. This is used
-;; by blob stores to note storage-level 'stat' metadata, and in the data layer
-;; to hold deserialized values and type information.
-(defrecord Blob
+    (keyword? algorithm)
+      (if-let [hf (get multihash/functions algorithm)]
+        hf
+        (throw (IllegalArgumentException.
+                 (str "Cannot map algorithm name " algorithm
+                      " to a supported hash function"))))
+
+    (ifn? algorithm)
+      algorithm
+
+    :else
+      (throw (IllegalArgumentException.
+               (str "Hash algorithm must be keyword name or direct function, got: "
+                    (pr-str algorithm))))))
+
+
+
+;; ## Block Record
+
+; TODO: ideally, id and content should NOT be overwritable.
+(defrecord Block
   [^Multihash id
    ^ByteBuffer content])

-(defn empty-blob
-  "Constructs a new blob record with the given multihash identifier and no
+(defn empty-block
+  "Constructs a new block record with the given multihash identifier and no
   content."
   [id]
-  {:pre [(instance? Multihash id)]}
-  (Blob. id nil))
+  (when-not (instance? Multihash id)
+    (throw (IllegalArgumentException.
+             (str "Block identifier must be a Multihash, got: " (pr-str id)))))
+  (Block. id nil))

-(def ^:dynamic *hash-fn*
-  "Function to use to produce multihash values."
-  multihash/sha2-256)
+(defn size
+  "Determine the number of bytes stored in a block."
+  [block]
+  (if-let [content (:content block)]
+    (.capacity ^ByteBuffer content)
+    (:stat/size block)))

-(defmacro with-algorithm
-  "Executes body with the hash algorithm bound to the given function."
-  [fn-sym & body]
-  `(binding [*hash-fn* ~fn-sym]
-     ~@body))
-
-
-(defn identify
-  "Constructs a multihash for the given content."
-  [content]
-  (when content
-    (*hash-fn* content)))
-
-
-(defn validate!
-  "Checks that the identifier of a blob matches the actual digest of the
-  content. Throws an exception if the id does not match."
-  [blob]
-  (let [{:keys [id content]} blob]
-    (when-not (multihash/test id content)
-      (throw (IllegalStateException.
-               (str "Invalid blob with content " content
-                    " but id " id))))))
+(defn open
+  "Opens an input stream to read the content of the block. This is typically
+  preferable to directly accessing the content."
+  [block]
+  (when-let [content (:content block)]
+    ; TODO: should this create a separate ByteBuffer to avoid multi-thread headaches?
+    ; Need to look at how the input stream gets created.
+    (.rewind ^ByteBuffer content)
+    (bytes/to-input-stream content)))

 (defn read!
   "Reads data into memory from the given source and hashes it to identify the
-  blob. This can handle any source supported by the byte-streams library."
-  [source]
-  (let [content (bytes/to-byte-array source)]
-    (when-not (empty? content)
-      (Blob. (identify content)
-             (.asReadOnlyBuffer (ByteBuffer/wrap content))))))
+  block. This can handle any source supported by the byte-streams library.
+  Defaults to sha2-256 if no algorithm is specified."
+  ([source]
+   (read! source :sha2-256))
+  ([source algorithm]
+   (let [hash-fn (resolve-hash! algorithm)
+         content (bytes/to-byte-array source)]
+     (when-not (empty? content)
+       (Block. (hash-fn content)
+               (.asReadOnlyBuffer (ByteBuffer/wrap content)))))))

 (defn write!
-  "Writes blob data to a byte stream."
-  [blob sink]
-  (when-let [content (:content blob)]
+  "Writes block data to an output stream."
+  [block sink]
+  (when-let [content (open block)]
     (bytes/transfer content sink)))

-(defn open
-  "Opens an input stream to read the content of the blob."
-  [blob]
-  (when-let [content (:content blob)]
-    (.rewind ^ByteBuffer content)
-    (bytes/to-input-stream content)))
+(defn validate!
+  "Checks that the identifier of a block matches the actual digest of the
+  content. Throws an exception if the id does not match."
+  [block]
+  (let [{:keys [id content]} block]
+    (when-not (multihash/test id content)
+      (throw (IllegalStateException.
+               (str "Invalid block with content " content
+                    " but id " id))))))

 ;; ## Storage Interface

-(defprotocol BlobStore
+(defprotocol BlockStore
   "Protocol for content storage keyed by hash identifiers."

   (enumerate
     [store opts]
-    "Enumerates the ids of the stored blobs with some filtering options. The
+    "Enumerates the ids of the stored blocks with some filtering options. The
     'list' function provides a nicer wrapper around this protocol method.")

   (stat
     [store id]
-    "Returns a blob record with metadata but no content.")
+    "Returns a block record with metadata but no content.")

   (get*
     [store id]
-    "Loads content for a hash-id and returns a blob record. Returns nil if no
-    blob is stored. The blob should include stat metadata.")
+    "Loads content for a hash-id and returns a block record. Returns nil if no
+    block is stored. The block should include stat metadata.")

   (put!
-    [store blob]
-    "Saves a blob into the store. Returns the blob record, updated with stat
+    [store block]
+    "Saves a block into the store. Returns the block record, updated with stat
     metadata.")

   (delete!
     [store id]
-    "Removes a blob from the store.")
+    "Removes a block from the store.")

   (erase!!
     [store]
-    "Removes all blobs from the store."))
+    "Removes all blocks from the store."))

 (defn list
-  "Enumerates the stored blobs, returning a sequence of multihashes.
+  "Enumerates the stored blocks, returning a sequence of multihashes.
   See `select-ids` for the available query options."
   ([store]
    (enumerate store nil))
@@ -140,60 +163,32 @@

 (defn get
-  "Loads content for a multihash and returns a blob record. Returns nil if no
-  blob is stored. The blob should include stat metadata.
+  "Loads content for a multihash and returns a block record. Returns nil if no
+  block is stored. The block should include stat metadata.

   This function checks the digest of the loaded content against the requested multihash,
   and throws an exception if it does not match."
   [store id]
-  (when-not (instance? multihash.core.Multihash id)
+  (when-not (instance? Multihash id)
     (throw (IllegalArgumentException.
-             (str "Id value " (pr-str id) " is not a multihash."))))
-  (when-let [blob (get* store id)]
-    (validate! blob)
-    blob))
+             (str "Id value must be a multihash, got: " (pr-str id)))))
+  (when-let [block (get* store id)]
+    (validate! block)
+    block))

 (defn store!
-  "Stores content from a byte source in a blob store and returns the blob
+  "Stores content from a byte source in a block store and returns the block
   record. This method accepts any source which can be handled as a byte
   stream by the byte-streams library."
   [store source]
-  (when-let [blob (read! source)]
-    (put! store blob)))
-
-
-
-;; ## Utility Functions
-
-(defn select-ids
-  "Selects hash identifiers from a sequence based on input criteria.
-  Available options:
-
-  - `:encoder` function to encode multihashes with (default: `multihash/hex`)
-  - `:after`   start enumerating ids lexically following this string
-  - `:prefix`  only return ids starting with the given string
-  - `:limit`   limit the number of results returned"
-  [opts ids]
-  (let [{:keys [prefix limit]} opts
-        encoder (:encoder opts multihash/hex)
-        after (:after opts prefix)]
-    (cond->> ids
-      after  (drop-while #(pos? (compare after (encoder %))))
-      prefix (take-while #(.startsWith ^String (encoder %) prefix))
-      limit  (take limit))))
-
-
-(defn size
-  "Determine the number of bytes stored in a blob."
-  [blob]
-  (or
-    (when-let [content (:content blob)]
-      (.capacity ^ByteBuffer content))
-    (:stat/size blob)))
+  (when-let [block (read! source)]
+    (put! store block)))

 (defn scan-size
-  "Scans the blobs in a store to determine the total stored content size."
+  "Scans the blocks in a store to determine the total stored content size."
   [store]
-  (reduce + 0 (map (comp :stat/size (partial stat store)) (list store))))
+  (->> (list store)
+       (map (comp size (partial stat store)))
+       (reduce + 0N)))


Additional input handling functinos including mouse-wheel.

--- src/brevis/core.clj
+++ src/brevis/core.clj
@@ -147,12 +147,48 @@
           :terminated? true)
           )))

+(defn mouse-move
+  "Respond to a change in x,y position of the mouse."
+  [[[dx dy] [x y]] state]
+  #_(println x y)
+  state)
+
+(defn mouse-up
+  "Respond to a mouse button being released"
+  [[x y] button state]
+  #_(println button)
+  state)
+
+(defn mouse-click
+  "Respond to a click?"
+  [[x y] button state]
+  #_(println button)
+  state)
+
+(defn mouse-down
+  "Respond to a mouse button being pressed"
+  [[x y] button state]
+  #_(println button)
+  state)
+
+(defn mouse-wheel
+  "Respond to a mousewheel movement. dw is +/- depending on scroll-up or down."
+  [dw state]
+  #_(println dw)
+  state)
+
 ;; ## Start a brevis instance

 (defn start-gui [initialize update]
   "Start the simulation with a GUI."
   (app/start
-   {:reshape reshape, :init init, :mouse-drag mouse-drag, :key-press key-press, :update update, :display display}
+   {:reshape reshape, :init init, :mouse-drag mouse-drag, :key-press key-press, :update update, :display display
+    ;:mouse-move    (fn [[[dx dy] [x y]] state] (println )
+    ;:mouse-up       (fn [[x y] button state] (println button) state)
+    ;:mouse-click   (fn [[x y] button state] (println button) state)
+    ;:mouse-down    (fn [[x y] button state] (println button) state)
+    ;:mouse-wheel   (fn [dw state] (println dw) state)
+    }
    (merge {:rotate-mode :x :translate-mode :x
            :rot-x 0 :rot-y 0 :rot-z 90
            :shift-x 0 :shift-y 20 :shift-z 0;-30


use send-off since we're doing io

use send-off since we're doing io

--- src/cavm/loader.clj
+++ src/cavm/loader.clj
@@ -74,7 +74,7 @@
   [db detector docroot]
   (let [a (agent nil)]
     (fn [filename]
-      (send a (fn [n]
+      (send-off a (fn [n]
                 (try
                   (loader db detector docroot filename)
                   (catch Exception e (log-error e)))


♻ Use select-keys for validating the demo congregation response

Why:
- Will produce better error messages if the response is missing an
  expected key
- Will detect a mistyped key when expecting the value to be nil

--- test/territory_bro/api_test.clj
+++ test/territory_bro/api_test.clj
@@ -405,15 +405,12 @@
                            (merge session)
                            app)]
           (is (ok? response))
-          (is (= "demo" (:id (:body response)))
-              "replaces original ID")
-          (is (= "Demo Congregation" (:name (:body response)))
-              "replaces original name")
-          (is (= [] (:users (:body response)))
-              "may not view users")
-          (is (= {:viewCongregation true}
-                 (:permissions (:body response)))
-              "has read-only permissions")))
+          (is (= {:id "demo"
+                  :name "Demo Congregation"
+                  :users []
+                  :permissions {:viewCongregation true}}
+                 (select-keys (:body response) [:id :name :users :permissions]))
+              "returns an anonymized read-only congregation")))

       (testing "requires login"
         (let [response (-> (request :get (str "/api/congregation/demo"))


Attempt

Attempt

--- src/korhal/core.clj
+++ src/korhal/core.clj
@@ -12,9 +12,11 @@
  :constructors {[] []}
  :prefix "korhal-")

-(defn korhal-main [& args] (korhal.core.))
+(defn korhal-main [& args]
+  (let [ai (new korhal.core)]
+    (.start (jnibwapi.JNIBWAPI. ai))))

-(defn korhal-init [this] (.start (jnibwapi.JNIBWAPI. this)))
+(defn korhal-init [this] [[] "state"])

 (defn korhal-connected [this])
 (defn korhal-gameStarted [this])


removed unused version

removed unused version

--- main/src/dda/pallet/dda_managed_vm/infra.clj
+++ main/src/dda/pallet/dda_managed_vm/infra.clj
@@ -30,7 +30,6 @@
    [dda.pallet.dda-managed-vm.infra.java :as java]))

 (def facility :dda-managed-vm)
-(def version  [0 0 0])

 (def Bookmarks mozilla/Bookmarks)


Add substring

Add substring

Alias clojure.core/subs and use it everywhere instead of .substring

--- src/superstring/core.clj
+++ src/superstring/core.clj
@@ -32,6 +32,7 @@
           (vals (ns-publics namespace)))))

 (alias-ns clojure.string)
+(def substring clojure.core/subs)

 (defn- ^String slice-relative-to-end
   [s index length]
@@ -59,9 +60,9 @@
      (neg? (+ (.length s) index)) nil ; slice relative to end falls outside s
      (neg? index) (slice-relative-to-end s index length)
      (>= index (.length s)) nil
-     (> (- length index) (.length (.substring s index))) (.substring s index)
+     (> (- length index) (.length (substring s index))) (substring s index)
      :else (let [end (+ index length)]
-             (.substring s index end)))))
+             (substring s index end)))))

 (defn ^String ends-with?
   "Return s if s ends with suffix."
@@ -71,7 +72,7 @@
   ([^String s ^String suffix ignore-case]
    (if-not ignore-case
      (ends-with? s suffix)
-     (let [end (.substring s (max 0 (- (.length s) (.length suffix))))]
+     (let [end (substring s (max 0 (- (.length s) (.length suffix))))]
        (when (.equalsIgnoreCase end suffix)
          s)))))

@@ -85,7 +86,7 @@
   ([^String s ^String prefix ignore-case]
    (if-not ignore-case
      (starts-with? s prefix)
-     (let [beg (.substring s 0 (.length prefix))]
+     (let [beg (substring s 0 (.length prefix))]
        (when (.equalsIgnoreCase beg prefix)
          s)))))

@@ -97,8 +98,8 @@
   Applying chop to an empty string is a no-op."
   [^String s]
   (if (.endsWith s "\r\n")
-    (.substring s 0 (- (.length s) 2))
-    (.substring s 0 (max 0 (dec (.length s))))))
+    (substring s 0 (- (.length s) 2))
+    (substring s 0 (max 0 (dec (.length s))))))

 (defn ^String chomp
   "Return a new string with the given record separator removed from
@@ -108,13 +109,13 @@
   the end of s."
   ([^String s]
    (cond
-     (.endsWith s "\r\n") (.substring s 0 (- (.length s) 2))
-     (.endsWith s "\r") (.substring s 0 (dec (.length s)))
-     (.endsWith s "\n") (.substring s 0 (dec (.length s)))
+     (.endsWith s "\r\n") (substring s 0 (- (.length s) 2))
+     (.endsWith s "\r") (substring s 0 (dec (.length s)))
+     (.endsWith s "\n") (substring s 0 (dec (.length s)))
      :else s))
   ([^String s ^String separator]
    (if (.endsWith s separator)
-     (.substring s 0 (- (.length s) (.length separator)))
+     (substring s 0 (- (.length s) (.length separator)))
      s)))

 (defn ^String capitalize
@@ -124,7 +125,7 @@
   (case (.length s)
     0 ""
     1 (upper-case s)
-    (str (upper-case (.substring s 0 1)) (lower-case (.substring s 1)))) )
+    (str (upper-case (substring s 0 1)) (lower-case (substring s 1)))) )

 (defn ^String swap-case
   "Change lower case characters to upper case and vice versa."
@@ -144,7 +145,7 @@
         remaining (if (zero? full-lengths) (- width (.length s))
                       (rem missing (* full-lengths (.length padding))))]
     (str (apply str (repeat full-lengths padding))
-         (.substring padding 0 remaining))))
+         (substring padding 0 remaining))))

 (defn ^String pad-right
@@ -188,9 +189,9 @@
            full-lengths (Math/ceil (/ missing (.length padding)))
            p (gen-padding s padding width)
            lengths-before (Math/floor (/ full-lengths 2))]
-       (str (.substring p 0 (* (.length padding) lengths-before))
+       (str (substring p 0 (* (.length padding) lengths-before))
             s
-            (.substring p (* (.length padding) lengths-before)))))))
+            (substring p (* (.length padding) lengths-before)))))))

 (defn ^String chop-suffix
   "If s ends with suffix return a new string without the suffix.
@@ -204,7 +205,7 @@
     :post [(not (nil? %))]}
    (if (and (>= (.length s) (.length suffix))
             (ends-with? s suffix ignore-case))
-     (.substring s 0 (- (.length s) (.length suffix)))
+     (substring s 0 (- (.length s) (.length suffix)))
      s)))

 (defn ^String chop-prefix
@@ -219,7 +220,7 @@
     :post [(not (nil? %))]}
    (if (and (>= (.length s) (.length prefix))
             (starts-with? s prefix ignore-case))
-     (.substring s (.length prefix))
+     (substring s (.length prefix))
      s)))

 (defn- case-sensitive-contains
@@ -275,7 +276,7 @@
   [^String s len]
   {:pre [(not (nil? s)) (>= len 3)]}
   (if (> (.length s) (max 3 (- len 3)))
-    (str (.substring s 0 (- len 3)) "...")
+    (str (substring s 0 (- len 3)) "...")
     s))

 (defn- char-equal-ignore-case
@@ -343,7 +344,7 @@
    :post [(string? %)]}
   (let [first-char (first s)
         start (if (upper-exists? first-char) (upper-case first-char) first-char)]
-    (str start (lower-case (.substring s 1)))))
+    (str start (lower-case (substring s 1)))))

 (defn ^String upper-case?
   "Return s if s is all upper case.
@@ -594,7 +595,7 @@
           (if (> (aget ls i j) @z)
             (do
               (reset! z (aget ls i j))
-              (reset! ret #{(.substring s1 (- i @z) i)}))
+              (reset! ret #{(substring s1 (- i @z) i)}))
             (when (= (aget ls i j) @z)
-              (swap! ret conj (.substring s1 (- i @z) i)))))))
+              (swap! ret conj (substring s1 (- i @z) i)))))))
     @ret))


Fix problem with hang at bootstrap

Fix problem with hang at bootstrap

--- src/eventstore/handler.clj
+++ src/eventstore/handler.clj
@@ -65,12 +65,7 @@
                         #(json/read-str (first (:payload_s %)) :key-fn keyword)
                         (db/lazy-events riak-streams "streams" 0)))))

-(def ms (m/start-server!
-          #_(db/->DBDummy)
-          #_(mongo/mongo)
-          (filedb/->DBFile (clojure.java.io/resource "events.json"))
-          #_(riak/riak riak/s-bucket)))
-(def test-ds (:stm ms))
+(def test-ds (filedb/->DBFile (clojure.java.io/resource "events.json")))

 (defroutes app-routes
   (GET "/streams" []
@@ -100,6 +95,11 @@
 ;; In order to use http-kit, run `lein run` instead of `lein ring server`
 (defn -main [& args]
   #_(future (m/start-server!))
+  (def ms (m/start-server!
+            #_(db/->DBDummy)
+            #_(mongo/mongo)
+            (filedb/->DBFile (clojure.java.io/resource "events.json"))
+            #_(riak/riak riak/s-bucket)))
   (let [handler (reload/wrap-reload #'app)]
     (println run-server)
     (time (run-server handler {:port 3000}))))


Handle proportion locking on mouse resize.

--- src/uxbox/main/geom.cljs
+++ src/uxbox/main/geom.cljs
@@ -207,48 +207,64 @@
   "A specialized function for vertex movement
   for rect-like shapes."
   [shape vid {dx :x dy :y lock? :lock}]
-  (let [{:keys [x1 x2 y1 y2]} shape
-        dy (if lock? dx dy)]
-    (case vid
-      :top-left (assoc shape
-                       :x1 (min x2 (+ x1 dx))
-                       :y1 (min y2 (+ y1 dy)))
-      :top-right (assoc shape
-                        :x2 (max x1 (+ x2 dx))
-                        :y1 (min y2 (+ y1 dy)))
-      :bottom-left (assoc shape
-                          :x1 (min x2 (+ x1 dx))
-                          :y2 (max y1 (+ y2 dy)))
-      :bottom-right (assoc shape
-                           :x2 (max x1 (+ x2 dx))
-                           :y2 (max y1 (+ y2 dy)))
-      :top (assoc shape :y1 (min y2 (+ y1 dy)))
-      :right (assoc shape :x2 (max x1 (+ x2 dx)))
-      :bottom (assoc shape :y2 (max y1 (+ y2 dy)))
-      :left (assoc shape :x1 (min x2 (+ x1 dx))))))
+  (letfn [(handle-positioning [{:keys [x1 x2 y1 y2 proportion] :as shape}]
+            (case vid
+              :top-left (assoc shape
+                               :x1 (min x2 (+ x1 dx))
+                               :y1 (min y2 (+ y1 dy)))
+              :top-right (assoc shape
+                                :x2 (max x1 (+ x2 dx))
+                                :y1 (min y2 (+ y1 dy)))
+              :bottom-left (assoc shape
+                                  :x1 (min x2 (+ x1 dx))
+                                  :y2 (max y1 (+ y2 dy)))
+              :bottom-right (assoc shape
+                                   :x2 (max x1 (+ x2 dx))
+                                   :y2 (max y1 (+ y2 dy)))
+              :top (assoc shape :y1 (min y2 (+ y1 dy)))
+              :right (assoc shape :x2 (max x1 (+ x2 dx)))
+              :bottom (assoc shape :y2 (max y1 (+ y2 dy)))
+              :left (assoc shape :x1 (min x2 (+ x1 dx)))))
+
+          (handle-proportion [{:keys [y1 proportion proportion-lock] :as shape}]
+            (let [{:keys [width height]} (size shape)]
+              (if (or lock? proportion-lock)
+                (assoc shape :y2 (+ y1 (/ width proportion)))
+                shape)))]
+    (-> shape
+        (handle-positioning)
+        (handle-proportion))))

 (defn- move-circle-vertex
   "A specialized function for vertex movement
   for circle shapes."
-  [shape vid {dx :x dy :y lock :lock}]
-  (let [[dx dy] (if lock [dx dx] [dx dy])]
-    (case vid
-      :top-left (assoc shape
-                       :rx (max 0 (- (:rx shape) dx))
-                       :ry (max 0 (- (:ry shape) dy)))
-      :top-right (assoc shape
-                        :rx (max 0 (+ (:rx shape) dx))
-                        :ry (max 0 (- (:ry shape) dy)))
-      :bottom-left (assoc shape
-                          :rx (max 0 (- (:rx shape) dx))
-                          :ry (max 0 (+ (:ry shape) dy)))
-      :bottom-right (assoc shape
-                           :rx (max 0 (+ (:rx shape) dx))
-                           :ry (max 0 (+ (:ry shape) dy)))
-      :top (assoc shape :ry (max 0 (- (:ry shape) dy)))
-      :right (assoc shape :rx (max 0 (+ (:rx shape) dx)))
-      :bottom (assoc shape :ry (max 0 (+ (:ry shape) dy)))
-      :left (assoc shape :rx (max 0 (+ (:rx shape) dx))))))
+  [shape vid {dx :x dy :y lock? :lock}]
+  (letfn [(handle-positioning [shape]
+            (case vid
+              :top-left (assoc shape
+                               :rx (max 0 (- (:rx shape) dx))
+                               :ry (max 0 (- (:ry shape) dy)))
+              :top-right (assoc shape
+                                :rx (max 0 (+ (:rx shape) dx))
+                                :ry (max 0 (- (:ry shape) dy)))
+              :bottom-left (assoc shape
+                                  :rx (max 0 (- (:rx shape) dx))
+                                  :ry (max 0 (+ (:ry shape) dy)))
+              :bottom-right (assoc shape
+                                   :rx (max 0 (+ (:rx shape) dx))
+                                   :ry (max 0 (+ (:ry shape) dy)))
+              :top (assoc shape :ry (max 0 (- (:ry shape) dy)))
+              :right (assoc shape :rx (max 0 (+ (:rx shape) dx)))
+              :bottom (assoc shape :ry (max 0 (+ (:ry shape) dy)))
+              :left (assoc shape :rx (max 0 (+ (:rx shape) dx)))))
+          (handle-proportion [{:keys [rx proportion proportion-lock] :as shape}]
+            (let [{:keys [width height]} (size shape)]
+              (if (or lock? proportion-lock)
+                (assoc shape :ry (/ rx proportion))
+                shape)))]
+    (-> shape
+        (handle-positioning)
+        (handle-proportion))))

 ;; --- Paths


Fix Errors making it through exception handler

--- src/formlogic/handlers.clj
+++ src/formlogic/handlers.clj
@@ -37,7 +37,7 @@
   [handler]
   (fn [req]
     (try (handler req)
-         (catch Exception e
+         (catch Throwable e
            (do
              (log/error e "Unhandled exception in handler!")
              ;; We wrap exception and stack trace in response body. These will


Remove obsolete and unused test file

Remove obsolete and unused test file

--- test/comic_reader/core_test.clj
+++ test/comic_reader/core_test.clj
@@ -1,7 +0,0 @@
-(ns comic-reader.core-test
-  (:require [clojure.test :refer :all]
-            [comic-reader.core :refer :all]))
-
-(deftest a-test
-  (testing "FIXME, I fail."
-    (is (= 0 1))))


RR: pick appropriate style for view-by

RR: pick appropriate style for view-by

--- src/hatti/map/viewby.cljs
+++ src/hatti/map/viewby.cljs
@@ -154,11 +154,12 @@
         stops (mapv #(if (id-selected? %)
                        [% (id-color %)]
                        [% grey]) ids)
-        id_string (om/get-props owner [:dataset-info :id_string])]
+        id_string (om/get-props owner [:dataset-info :id_string])
+        style (om/get-state owner [:style])]
     (when (-> stops seq seq?)
       (map-utils/set-mapboxgl-paint-property
        (om/get-state owner :mapboxgl-map) id_string
-       (map-utils/get-style-properties :point :normal :stops stops))
+       (map-utils/get-style-properties style :normal :stops stops))
       (om/set-state! owner :stops stops))))

 (defn filter-answer-data-structures


using line-seq

using line-seq

--- src/hackerrank/eval_ex.clj
+++ src/hackerrank/eval_ex.clj
@@ -10,15 +10,12 @@

 (defn series-expansion-e-to-the-x
   [x]
-  (println (format "%.4f" (reduce + (map (partial nth-order-term x) (range 10))))))
+  (reduce + (map (partial nth-order-term x) (range 10))))
+
+;; using line-seq
+(defn -main
+  []
+  (let [lines (line-seq (java.io.BufferedReader. *in*))]
+    (mapv (comp println #(format "%.4f" %) series-expansion-e-to-the-x read-string) (rest lines))))

-;; can simplify (read-string (read-line)) to (read)
-(defn -main
-  []
-  (let [n (read-string (read-line))]
-    (dotimes [_ n]
-      (let [x (read-string (read-line))]
-        (series-expansion-e-to-the-x x)))))
-
-


logger at runtime

logger at runtime

--- src/clj/algorithms_clj/macro_initiation.clj
+++ src/clj/algorithms_clj/macro_initiation.clj
@@ -206,7 +206,8 @@
 ;; Example 4-b: Adding logs based on run time option (no overhead)
 ;; --------------------------------------------------------

-(def logger (atom println))
+(def default-logger (partial println "INFO:"))
+(def logger (atom default-logger))

 (defmacro defn-log-2
   [name bindings body]
@@ -222,11 +223,11 @@

 (defn test-add-log-2
   []
-  (reset! logger println)
+  (reset! logger default-logger)
   (println (add-log-2 1 2))
   (reset! logger nil)
   (println (add-log-2 1 2))
-  (reset! logger println))
+  (reset! logger default-logger))

 ;; --------------------------------------------------------
 ;; Example 4-b: Adding logs based on compile time option (no overhead)


WM: Register autoresize on re-rendering table

--- src/hatti/views/table.cljs
+++ src/hatti/views/table.cljs
@@ -202,7 +202,8 @@
                (.resizeCanvas grid)
                (.invalidateAllRows grid)
                (.render grid)
-               (init-sg-pager grid dataview))))))))
+               (init-sg-pager grid dataview)
+               (.registerPlugin grid (.AutoColumnSize js/Slick)))))))))

 ;; OM COMPONENTS


cleanup docker metadata outbound mapper

cleanup docker metadata outbound mapper

--- src/clj/swarmpit/docker/mapper/outbound.clj
+++ src/clj/swarmpit/docker/mapper/outbound.clj
@@ -153,27 +153,25 @@
         stack (:stack service)
         image-id (get-in service [:repository :imageId])
         distribution-id (get-in service [:distribution :id])
-        distribution-type (get-in service [:distribution :type])
-        metadata (volatile! {})]
-    (when (some? stack)
-      (vswap! metadata #(merge {:com.docker.stack.namespace stack
-                                :com.docker.stack.image     image} %)))
-    (when (some? autoredeploy)
-      (vswap! metadata #(merge {:swarmpit.service.deployment.autoredeploy (str autoredeploy)} %)))
-    (when (some? image-id)
-      (vswap! metadata #(merge {:swarmpit.service.repository.image.id image-id} %)))
-    (when (some? distribution-type)
-      (vswap! metadata #(merge {:swarmpit.service.distribution.id   distribution-id
-                                :swarmpit.service.distribution.type distribution-type} %)))
-    @metadata))
+        distribution-type (get-in service [:distribution :type])]
+    (merge {}
+           (when (some? stack)
+             {:com.docker.stack.namespace stack
+              :com.docker.stack.image     image})
+           (when (some? autoredeploy)
+             {:swarmpit.service.deployment.autoredeploy (str autoredeploy)})
+           (when (some? image-id)
+             {:swarmpit.service.repository.image.id image-id})
+           (when (some? distribution-type)
+             {:swarmpit.service.distribution.id   distribution-id
+              :swarmpit.service.distribution.type distribution-type}))))

 (defn ->service-container-metadata
   [service]
-  (let [stack (:stack service)
-        metadata (volatile! {})]
-    (when (some? stack)
-      (vswap! metadata #(merge {:com.docker.stack.namespace stack} %)))
-    @metadata))
+  (let [stack (:stack service)]
+    (merge {}
+           (when (some? stack)
+             {:com.docker.stack.namespace stack}))))

 (defn ->service
   [service image]


now we have list*, how cool right.

now we have list*, how cool right.

--- src/http/async/client.clj
+++ src/http/async/client.clj
@@ -40,17 +40,18 @@
      (binding [*ahc* c#]
        ~@body)))

-(defmacro gen-method [methods]
-  `(do
-     ~@(for [method methods]
-         (let [fn-name (symbol (.toUpperCase (name method)))
-               fn-doc (str "Here goes docs for " fn-name)]
-           `(defn ~fn-name ~fn-doc [#^String ~'url & {:as ~'options}]
-              (apply execute-request
-                     (apply prepare-request ~method ~'url (apply concat ~'options))
-                     (apply concat *default-callbacks*)))))))
+(defmacro gen-method [& methods]
+  (list* 'do
+     (map (fn [method#]
+            (let [fn-name (symbol (.toUpperCase (name method#)))
+                  fn-doc (str "Here goes docs for --- " fn-name)]
+              `(defn ~fn-name ~fn-doc [#^String ~'url & {:as ~'options}]
+                 (apply execute-request
+                        (apply prepare-request ~method# ~'url (apply concat ~'options))
+                        (apply concat *default-callbacks*)))))
+          methods)))

-(gen-method [:get :post :put :delete :head :options])
+(gen-method :get :post :put :delete :head :options)

 (defn request-stream
   "Consumes stream from given url.


add some type hints to avoid introspection

--- src/corpusmaker.clj
+++ src/corpusmaker.clj
@@ -17,6 +17,10 @@
      [redis])
   (:use
      [clojure.contrib.duck-streams :only (read-lines)]))
+
+;; Parsing big dumps can be really slow if the program spends time handling
+;; types dynamically
+(set! *warn-on-reflection* true)

 ;;
 ;; Utilities to parse DBPedia N-TRIPLES dump to load them in a redis DB to
@@ -102,6 +106,9 @@
 ; some <!-- wiki comment --> inside the text body
 (def *comment* #"<!--(.*?)-->")

+; some <ref /> inside the text body
+(def *ref* #"(<ref(.*?)/>|<ref(.*?)>(.*?)</ref>)")
+
 ; some {{wiki directive}} inside the text body
 (def *double-curly* #"\{\{(.+?)\}\}")

@@ -127,15 +134,23 @@

 (defn no-redirect?
   "Check that the page content does not forward to another article"
-  [page-markup]
+  [#^String page-markup]
   (-> page-markup .trim (.startsWith "#REDIRECT") not))
+
+(defn replace-all
+  "Replace all occurrences of a pattern in the given text"
+  [text #^java.util.regex.Pattern pattern replacement]
+  (-> pattern (.matcher text) (.replaceAll replacement)))
+
+(defn remove-all
+  "Replace all occurrences of a pattern in the given text by an empty string"
+  [text #^java.util.regex.Pattern pattern]
+  (replace-all text pattern ""))

 (defn clean-markup
   "Remove wiki markup that does not hold annotation data"
-  [page-markup]
-  (reduce #(-> %2 (.matcher %1) (.replaceAll ""))
-          page-markup
-          [*comment* *double-curly* *category*]))
+  [#^String page-markup]
+  (reduce remove-all page-markup [*comment* *double-curly* *category* *ref*]))

 (defn collect-text
   "collect wikimarkup payload of a dump in seqable xml"


Use planner instead of rules, as rules are non-wrapped configuration param, can't be used in resolution matching

--- src/io/cyanite/engine.clj
+++ src/io/cyanite/engine.clj
@@ -92,7 +92,7 @@
   Ingester
   (ingest! [this metric]
     (drift! drift (:time metric))
-    (doseq [resolution (fetch-resolutions state rules metric)]
+    (doseq [resolution (fetch-resolutions state planner metric)]
       (ingest! resolution metric)))
   Enqueuer
   (enqueue! [this metric]


Only create DLO metrics once per subdirectory

This was previously creating the metrics every time a message was
discarded or the DLO was stored.

--- src/com/puppetlabs/puppetdb/command/dlo.clj
+++ src/com/puppetlabs/puppetdb/command/dlo.clj
@@ -61,11 +61,12 @@
 (defn- create-metrics-for-dlo!
   "Creates the standard set of global metrics."
   [dir]
-  (swap! metrics assoc-in [:global :compression] (timer [ns-str "global" "compression"]))
-  (swap! metrics assoc-in [:global :compression-failures] (meter [ns-str "global" "compression-failures"] "failures/s"))
-  (swap! metrics assoc-in [:global :filesize] (gauge [ns-str "global" "filesize"] (FileUtils/sizeOf dir)))
-  (swap! metrics assoc-in [:global :messages] (gauge [ns-str "global" "messages"] (count (mapcat messages (subdirectories dir)))))
-  (swap! metrics assoc-in [:global :archives] (gauge [ns-str "global" "archives"] (count (mapcat archives (subdirectories dir))))))
+  (when-not (:global @metrics)
+    (swap! metrics assoc-in [:global :compression] (timer [ns-str "global" "compression"]))
+    (swap! metrics assoc-in [:global :compression-failures] (meter [ns-str "global" "compression-failures"] "failures/s"))
+    (swap! metrics assoc-in [:global :filesize] (gauge [ns-str "global" "filesize"] (FileUtils/sizeOf dir)))
+    (swap! metrics assoc-in [:global :messages] (gauge [ns-str "global" "messages"] (count (mapcat messages (subdirectories dir)))))
+    (swap! metrics assoc-in [:global :archives] (gauge [ns-str "global" "archives"] (count (mapcat archives (subdirectories dir)))))))

 (defn- create-metrics-for-subdir!
   "Creates the standard set of metrics for the given `subdir`, using its
@@ -73,12 +74,13 @@
   [subdir]
   (let [subdir-name (fs/base-name subdir)
         prefix [ns-str subdir-name]]
-    (swap! metrics assoc-in [subdir-name :compression] (timer (conj prefix "compression")))
-    (swap! metrics assoc-in [subdir-name :compression-failures] (meter (conj prefix "compression-failures") "failures/s"))
-    (swap! metrics assoc-in [subdir-name :filesize] (gauge (conj prefix "filesize") (FileUtils/sizeOf subdir)))
-    (swap! metrics assoc-in [subdir-name :messages] (gauge (conj prefix "messages") (count (messages subdir))))
-    (swap! metrics assoc-in [subdir-name :archives] (gauge (conj prefix "archives") (count (archives subdir))))
-    (swap! metrics assoc-in [subdir-name :last-archived] (gauge (conj prefix "archives") (last-archived subdir)))))
+    (when-not (get @metrics subdir-name)
+      (swap! metrics assoc-in [subdir-name :compression] (timer (conj prefix "compression")))
+      (swap! metrics assoc-in [subdir-name :compression-failures] (meter (conj prefix "compression-failures") "failures/s"))
+      (swap! metrics assoc-in [subdir-name :filesize] (gauge (conj prefix "filesize") (FileUtils/sizeOf subdir)))
+      (swap! metrics assoc-in [subdir-name :messages] (gauge (conj prefix "messages") (count (messages subdir))))
+      (swap! metrics assoc-in [subdir-name :archives] (gauge (conj prefix "archives") (count (archives subdir))))
+      (swap! metrics assoc-in [subdir-name :last-archived] (gauge (conj prefix "archives") (last-archived subdir))))))

 (defn- global-metric
   "Returns the global metric corresponding to `metric`."


Fix postgres query for numeric comparisons

This commit changes the regex that we are using for
numeric comparisons in postgres to a format that
is compatible with both 8.4 and 9.1.

--- src/com/puppetlabs/puppetdb/scf/storage.clj
+++ src/com/puppetlabs/puppetdb/scf/storage.clj
@@ -102,8 +102,8 @@

 (defmethod sql-as-numeric "PostgreSQL"
   [column]
-  (format (str "CASE WHEN %s~'^\\d+$' THEN %s::integer "
-               "WHEN %s~'^\\d+\\.\\d+$' THEN %s::float "
+  (format (str "CASE WHEN %s~E'^\\\\d+$' THEN %s::integer "
+               "WHEN %s~E'^\\\\d+\\\\.\\\\d+$' THEN %s::float "
                "ELSE NULL END")
           column column column column))


latest ClojureScript version

latest ClojureScript version

[org.clojure/clojurescript "0.0-3119"]

--- Clojure-Websockets/MainApp/project.clj
+++ Clojure-Websockets/MainApp/project.clj
@@ -20,7 +20,7 @@
                  [ring/ring-defaults "0.1.4"]
                  [clj-time "0.9.0"]
                  [pandect "0.5.1"]
-                 [org.clojure/clojurescript "0.0-2913"]
+                 [org.clojure/clojurescript "0.0-3119"]
                  [tailrecursion/cljs-priority-map "1.1.0"]
                  [org.clojure/data.priority-map "0.0.5"]
                  [reagent "0.5.0"]


Copy AOT core.async

Copy AOT core.async

--- ClojureScript/replete/script/build.clj
+++ ClojureScript/replete/script/build.clj
@@ -89,4 +89,13 @@
 (extract-analysis-cache "out/fipp/engine.cljc.cache.edn" "out/fipp/engine.cljc.cache.json")
 (extract-analysis-cache "out/fipp/visit.cljc.cache.edn" "out/fipp/visit.cljc.cache.json")

+(extract-analysis-cache "out/cljs/core/async.cljs.cache.edn" "out/cljs/core/async.cljs.cache.json")
+(extract-analysis-cache "out/cljs/core/async/impl/ioc_macros_runtime.cljc.cache.edn" "out/cljs/core/async/impl/ioc_macros_runtime.cljc.cache.json")
+(extract-analysis-cache "out/cljs/core/async/impl/protocols.cljs.cache.edn" "out/cljs/core/async/impl/protocols.cljs.cache.json")
+(extract-analysis-cache "out/cljs/core/async/impl/channels.cljs.cache.edn" "out/cljs/core/async/impl/channels.cljs.cache.json")
+(extract-analysis-cache "out/cljs/core/async/impl/dispatch.cljs.cache.edn" "out/cljs/core/async/impl/dispatch.cljs.cache.json")
+(extract-analysis-cache "out/cljs/core/async/impl/buffers.cljs.cache.edn" "out/cljs/core/async/impl/buffers.cljs.cache.json")
+(extract-analysis-cache "out/cljs/core/async/impl/timers.cljs.cache.edn" "out/cljs/core/async/impl/timers.cljs.cache.json")
+(extract-analysis-cache "out/cljs/core/async/impl/ioc_helpers.cljs.cache.edn" "out/cljs/core/async/impl/ioc_helpers.cljs.cache.json")
+
 (System/exit 0)


More cleanup

More cleanup

--- src/angelic/search/implicit/dash_astar.clj
+++ src/angelic/search/implicit/dash_astar.clj
@@ -166,18 +166,27 @@
   (and (empty? (get-children sp))
        (summary/solved? (summaries/summary sp))))

+(defn- connect-and-watch! [p c out-f child-f]
+  (summaries/connect! p c)
+  (when out-f (add-output-watcher! c out-f))
+  (add-child-watcher! c child-f))
+
+(defn- connect-and-watch-ts! [p c out-f]
+  (summaries/connect! p (sp-ts c))
+  (add-output-watcher! c out-f))

 (defmethod print-method angelic.search.implicit.dash_astar.Subproblem [sp o]
   (print-method (format "#<SP$%8h %s %s>" (System/identityHashCode sp) (sp-name sp)
                         (if (get-output-set sp) :OUT :STUB)) o))

-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;  Generic Trait  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;  Constructors  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 ;; Canonical SPs are Atomic and Pair; wrappers use TS of inner SP.
 (defn- canonicalize [sp] (ts-sp (sp-ts sp)))
 (defn- canonical? [sp] (identical? sp (ts-sp (sp-ts sp))))

+;; Summary-fn should take bound into account.
 (defn- make-subproblem [nm inp-set wrapped-ts eval!-fn ri-fn summary-fn]
  (let [                 ts-atom          (atom wrapped-ts)
        ^PubSubHub       output-ps        (make-pubsubhub)
@@ -249,40 +258,7 @@
       (when (canonical? s) (add-subsuming-sp! ret s))
       ret)))))

-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;  Utils  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-(defn- connect-and-watch! [p c out-f child-f]
-  (summaries/connect! p c)
-  (when out-f (add-output-watcher! c out-f))
-  (add-child-watcher! c child-f))
-
-(defn- connect-and-watch-ts! [p c out-f]
-  (summaries/connect! p (sp-ts c))
-  (add-output-watcher! c out-f))
-
-
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;  Constructors  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-
-(defn noeval [s] (throw (RuntimeException. (print-str s "not evaluable!"))))
-
-(defn make-wrapped-subproblem [nm inp-set prefix-set inner-sp output-wrap child-watch ri-fn]
-  (util/assert-is (contains? prefix-set (first (sp-name inner-sp))))
-  (let [ret (make-subproblem nm inp-set (sp-ts inner-sp) noeval ri-fn summaries/or-summary)]
-    (connect-and-watch! ret inner-sp
-      (fn [o] (set-output-set! ret (output-wrap o)))
-      (fn [inner-child] (child-watch ret inner-child)))
-    ret))
-
-;; Note: summary-fn should take subsuming-bound into account.
-(defn- make-simple-subproblem [nm inp-set ri-fn eval-fn summary-fn]
-  (make-subproblem nm inp-set nil eval-fn (fn [s ni] (if (= ni inp-set) s (ri-fn s ni))) summary-fn))
-
-;; Get a fresh subproblem with the given name and input.
 (defmulti get-subproblem (fn get-subproblem-dispatch [nm inp] (first nm)))
-
-

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;;;;;;;;;;;;;;;;;;;;;;;;;     Core Subproblems     ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -299,9 +275,8 @@
   (let [nm    (atomic-name fs)
         state (atom :ready) ;; set to out-set after first eval, then :go after second.
         sm-fn (atom #(summary/make-live-simple-summary (summaries/get-bound %) %))]
-    (make-simple-subproblem
-     nm inp-set
-     (fn [s ri] (assert (not *collect-equal-outputs*)) (get-subproblem nm  ri))
+    (make-subproblem
+     nm inp-set nil
      (fn evaluate! [s]
        (util/print-debug 1 "eval" nm (= :ready @state))
        (assert (not (= :go @state)))
@@ -327,7 +302,8 @@
                    (set-output-set! s out-set)
                    (schedule-decrease! s)))) ;; TODO?
            (do (reset! state :go) ;; Die
-               (summaries/add-bound! s Double/NEGATIVE_INFINITY)))))
+               (summaries/add-bound! s Double/NEGATIVE_INFINITY)))))
+     (fn [s ri] (assert (not *collect-equal-outputs*)) (if (= ri inp-set) s (get-subproblem nm  ri)))
      (fn summarize [s] (@sm-fn s)))))

 (defmethod get-subproblem :Atomic [[_ fs :as n] inp-set]
@@ -347,7 +323,6 @@
      (let [nm (pair-name (sp-name left-sp) right-name)
            right-sp (delay (right-sp-fn (get-output-set! left-sp)))
            right?-atom (atom false) ;; Expand on right
-           ri-fn    (fn [s ni] (make-pair-subproblem (refine-input left-sp ni) right-name #(refine-input @right-sp %)))
            ss (summaries/make-sum-summarizer nil)
            go-right! (fn [s]
                        (reset! right?-atom true)
@@ -357,8 +332,11 @@
                          (fn ignore-output [_] nil)
                          (fn right-child [right-child] (add-sp-child! s (make-pair-subproblem left-sp right-child) true)))
                        (summaries/summary-changed-local! ss))
-           ret (make-simple-subproblem nm (input-set left-sp) ri-fn
+           ret (make-subproblem nm (input-set left-sp) nil
                  (fn eval! [s] (schedule-decrease! s) (go-right! s)) ;; TODO: ??
+                 (fn [s ni] (if (= ni (input-set left-sp)) s
+                                (make-pair-subproblem (refine-input left-sp ni)
+                                                      right-name #(refine-input @right-sp %))))
                  (fn [s]
                    (or (and (not @right?-atom)
                             (solved-terminal? left-sp)
@@ -384,6 +362,16 @@
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;     Wrappers     ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+(defn make-wrapped-subproblem [nm inp-set prefix-set inner-sp output-wrap child-watch ri-fn]
+  (util/assert-is (contains? prefix-set (first (sp-name inner-sp))))
+  (let [ret (make-subproblem nm inp-set (sp-ts inner-sp)
+                             (fn [_] (throw (RuntimeException.)))
+                             ri-fn summaries/or-summary)]
+    (connect-and-watch! ret inner-sp
+      (fn [o] (set-output-set! ret (output-wrap o)))
+      (fn [inner-child] (child-watch ret inner-child)))
+    ret))

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;     Output Collection     ;;;;;;;;;;;;;;;;;;;;;;;;;;


plugin - update docstring

plugin - update docstring

--- plugin/src/leiningen/doo.clj
+++ plugin/src/leiningen/doo.clj
@@ -188,7 +188,7 @@
   - build-id: any of the ids under the :cljsbuild map in your project.clj
   - watch-mode: either auto (default) or once\n

-build-id is optional provided there is a corresponding default under :doo
+All arguments are optional provided there is a corresponding default under :doo
 in project.clj.\n")

 (defn ^{:doc help-string}


permutations.clj: added Resumable implementation for BacktrackingGenerator

--- clojure/org/gavrog/clojure/permutations.clj
+++ clojure/org/gavrog/clojure/permutations.clj
@@ -31,6 +31,19 @@
                            :siblings-left (rest siblings-left)}))))]
           (when (seq stack)
             (BacktrackingGenerator. gen-children extract desc stack))))
+  Resumable
+  (checkpoint [_] (rest (reverse (map :branch-nr stack))))
+  (resume [_ checkpoint]
+          (loop [todo checkpoint stack stack]
+            (if (seq todo)
+              (let [n (first todo)
+                    children (drop n (gen-children (:node (first stack))))
+                    stack (conj stack
+                                {:node (first children)
+                                 :branch-nr n
+                                 :siblings-left (rest children)})]
+                (recur (rest todo) stack))
+              (BacktrackingGenerator. gen-children extract desc stack))))
   Object
   (toString [_] (str desc)))