Always include optional session view model fields.

--- src/shale/sessions.clj
+++ src/shale/sessions.clj
@@ -25,13 +25,13 @@

 (def SessionView
   "A session, as presented to library users."
-  {(s/optional-key :id)          s/Str
-   (s/optional-key :session-id)  s/Str
-   (s/optional-key :tags)         [s/Str]
-   (s/optional-key :reserved)      s/Bool
-   (s/optional-key :current-url)   s/Str
-   (s/optional-key :browser-name)  s/Str
-   (s/optional-key :node)          NodeView})
+  {(s/required-key :id)            s/Str
+   (s/required-key :webdriver-id)  s/Str
+   (s/required-key :tags)         [s/Str]
+   (s/required-key :reserved)      s/Bool
+   (s/required-key :current-url)   s/Str
+   (s/required-key :browser-name)  s/Str
+   (s/required-key :node)          NodeView})

 (def TagChange
   "Add/remove a session/node tag"
@@ -510,10 +510,17 @@
             (or ids (model-ids SessionInRedis)))))
   true)

+(def view-model-defaults {:tags #{}
+                          :browser-name nil
+                          :reserved false
+                          :node {}
+                          :current-url nil
+                          :webdriver-id nil})
+
 (s/defn view-model :- SessionView [id :- s/Str]
   (if-let [m (->> (model SessionInRedis id)
                   keywordize-keys)]
-    (merge {:id id} m)))
+    (merge view-model-defaults {:id id} m)))

 (s/defn view-models :- [SessionView] []
   (with-car*


Cosmetic improvement to app main component.

--- src/uxbox/main/ui.cljs
+++ src/uxbox/main/ui.cljs
@@ -74,8 +74,16 @@

 ;; --- Main App (Component)

-(defn app-render
+(defn app-will-mount
   [own]
+  (when @st/auth-ref
+    (rs/emit! (udu/fetch-profile)))
+  own)
+
+(mx/defc app
+  {:will-mount app-will-mount
+   :mixins [mx/reactive]}
+  []
   (let [route (mx/react route-ref)
         auth (mx/react st/auth-ref)
         location (:id route)
@@ -101,19 +109,6 @@
         nil
         ))))

-(defn app-will-mount
-  [own]
-  (when @st/auth-ref
-    (rs/emit! (udu/fetch-profile)))
-  own)
-
-(def app
-  (mx/component
-   {:render app-render
-    :will-mount app-will-mount
-    :mixins [mx/reactive]
-    :name "app"}))
-
 ;; --- Routes

 (def routes
@@ -137,9 +132,6 @@

 (defn init
   []
-  (let [app-dom (gdom/getElement "app")
-        lightbox-dom (gdom/getElement "lightbox")
-        loader-dom (gdom/getElement "loader")]
-    (rum/mount (app) app-dom)
-    (rum/mount (lightbox) lightbox-dom)
-    (rum/mount (loader) loader-dom)))
+  (mx/mount (app) (dom/get-element "app"))
+  (mx/mount (lightbox) (dom/get-element "lightbox"))
+  (mx/mount (loader) (dom/get-element "loader")))


Improve optimise.functions/check-gradient

* Decompose most functionality into private functions, to make
  check-gradient less monolithic.
* Add many more :return options, and improve the logic used for
  formatting the output based on the value for :return.
* Improve the docstring.

--- cortex/src/cortex/optimise/functions.clj
+++ cortex/src/cortex/optimise/functions.clj
@@ -31,7 +31,7 @@
             [clojure.string :as str]
             [cortex.nn.protocols :as cp]
             [cortex.optimise.parameters]
-            [cortex.util :as util]))
+            [cortex.util :as util :refer [def-]]))

 ;;;; Protocol extensions

@@ -60,72 +60,168 @@

 ;;;; Gradient checker

+(defn random-point
+  "Generates a random point within dist of center."
+  [center dist]
+  ;; If we just naively generated a uniform random number for each dimension,
+  ;; most of our vectors would have at least one near-zero coordinate. This would
+  ;; cause pathological behavior with some (pathological) objective functions.
+  ;; To avoid this, we first generate a random unit vector on the
+  ;; param-count-dimensional hypersphere, and then rescale it randomly.
+  ;; See http://math.stackexchange.com/a/44701/160658 for information on generating
+  ;; random unit vectors.
+  (->> (repeatedly (m/ecount center) util/rand-gaussian)
+    (m/array :vectorz)
+    (m/normalise)
+    ;; Not using (rand dist) allows for dist to be a vector.
+    (* dist (rand))
+    (+ (m/array :vectorz center))))
+
+(defn numerical-gradient
+  "Calculates the approximate value of the ith component of the gradient of a function
+  at the parameter vector x, using the symmetric different quotient formula. See
+  https://en.wikipedia.org/wiki/Numerical_differentiation for information on this
+  technique."
+  [function x i h]
+  (/ (- (value function (m/mset x i (+ (m/mget x i) h)))
+        (value function (m/mset x i (- (m/mget x i) h))))
+     2 h))
+
+(defn- error->rating
+  "Converts a relative error to an integer rating, as described in check-gradient."
+  [error]
+  (long (util/clamp 0
+                    (- (Math/floor (Math/log10 error)))
+                    20)))
+
+(defn- rating->class
+  "Converts a rating to a rating class, as described in check-gradient."
+  [rating]
+  (condp > rating
+    2 :very-bad
+    4 :bad
+    7 :maybe-okay
+    :all-good))
+
+(defn- rating->class-str
+  "Like rating->class, but returns a printable string."
+  [rating]
+  (condp > rating
+    2 "very bad"
+    4 "bad"
+    7 "maybe okay"
+    "all good"))
+
+(defn- print-ratings
+  "Prints a frequency map for the ratings of the errors, in a readable format."
+  [errors]
+  (println "  Count  Rating")
+  (println "-------  ------")
+  (doseq [[rating cnt] (->> errors
+                         (map error->rating)
+                         frequencies
+                         sort)]
+    (util/sprintf "%7d %s%-6d (%s)%n"
+                  cnt
+                  (case rating
+                    0
+                    "≤"
+                    20
+                    "≥"
+                    " ")
+                  rating
+                  (rating->class-str rating))))
+
+(def- class-values
+  "Used for sorting the classes from least desirable to most desirable in print-classes."
+  ;; This is extremely inelegant, but easy to understand. Feel free to improve the
+  ;; implementation of print-classes so that this map is unnecessary.
+  {"very bad" 0
+   "bad" 1
+   "maybe okay" 2
+   "all good" 3})
+
+(defn- print-classes
+  "Prints a frequency map for the rating classes of the errors, in a readable format."
+  [errors]
+  (println "  Count  Class     ")
+  (println "-------  ----------")
+  (doseq [[cls cnt] (->> errors
+                      (map error->rating)
+                      (map rating->class-str)
+                      frequencies
+                      (sort-by #(get class-values (key %))))]
+    (util/sprintf "%7d  %-10s%n" cnt cls)))
+
 (defn check-gradient
-  "Runs a gradient check. The first argument is the function, and param-count is the number
-  of entries in the parameter vector. Since functions can be variable-arity, passing param-count
-  is required. The gradient is computed at a number of points (given by points, which
-  defaults to 100) centered at center (defaults to [0, 0, ..., 0]) and with a maximum
-  spread of dist (defaults to 1). At each point, the numerical gradient is computed
-  using the difference quotient (f(x + h) - f(x - h)) / (2h) for each dimension. The
-  relative error is computed for each dimension at each point (or, if :dims is provided,
-  that many dimensions, chosen randomly), and each error is
-  transformed by #(- (Math/floor (Math/log10 %))). Typically, this scale will place
-  errors on a scale from 0-20; errors outside this range are clamped to it. If :print
-  is falsy, then the list of relative errors is returned; otherwise (default), a
-  user-friendly frequency listing is printed and nil is returned. The groupings used to
-  categorize relative errors are as follows:
-    error > 1e-2          (very bad)
-    1e-2 ≥ error > 1e-4   (bad)
-    1e-4 ≥ error > 1e-7   (maybe okay)
-    1e-7 ≥ error          (all good)
-  The techniques used in this function are described at:
-  http://cs231n.github.io/neural-networks-3/"
-  [function param-count & {:keys [center dist points h print dims]
-                           :or {dist 1 points 100 h 1e-5 print true dims param-count}}]
-  (let [center (m/array :vectorz (or center (repeat param-count 0)))
+  "Checks if the analytic gradient of a function agrees with its numeric gradient, i.e. the
+  :gradient is implemented correctly. The first argument is the function, and param-count is
+  the number of entries in the parameter vector. Since functions can be variable-arity, passing
+  param-count is always required.
+
+  The analytic gradient is computed at a number of points (given by points, which defaults to
+  100) centered at center (defaults to [0, 0, ..., 0]) and with a maximum spread of dist
+  (defaults to 1). At each point, the numerical gradient is computed for each dimension (or, if
+  dims is provided, that many dimensions, chosen randomly) using the symmetric difference
+  quotient, and the relative errors per dimension are determined.
+
+  Relative errors can be automatically rated and classified to make them more human-readable.
+  The rating for a relative error is given by rating = clamp(0, -floor(log10(relative error)), 20),
+  and classes are defined by the following table:
+
+           error > 1e-2   (very bad)     rating < 2
+    1e-2 ≥ error > 1e-4   (bad)          2 ≤ rating < 4
+    1e-4 ≥ error > 1e-7   (maybe okay)   4 ≤ rating < 7
+    1e-7 ≥ error          (all good)     7 ≤ rating
+
+  The format of the results is determined by the return parameter (defaults to :print), according
+  to the following listing:
+
+  :errors - return list of relative errors
+  :rating-list - return list of ratings
+  :average-rating - return the average rating
+  :ratings - return frequency map of ratings
+  :print - print frequency table of ratings
+  :class-list - return list of classes
+  :classes - return freqency map of classes
+  :print-classes - print frequency table of classes
+
+  See http://cs231n.github.io/neural-networks-3/ for more information about the techniques used in
+  this function."
+  [function param-count & {:keys [center dist points h return dims]
+                           :or {dist 1 points 100 h 1e-5 return :print dims param-count}}]
+  (let [;; This vector is converted to a Vectorz vector by the random-point function,
+        ;; so no need to do it twice.
+        center (or center (repeat param-count 0))
         errors (mapcat (fn [x]
                          (->> (gradient function x)
                            (map-indexed vector)
                            shuffle
                            (take dims)
-                           (map (fn [[i grad-component :as pair]]
+                           (map (fn [[i grad-component]]
                                   (util/relative-error
-                                    (/ (- (value function (m/mset x i (+ (m/mget x i) h)))
-                                          (value function (m/mset x i (- (m/mget x i) h))))
-                                       2 h)
+                                    (numerical-gradient function x i h)
                                     grad-component)))))
-                       (repeatedly points
-                                   (fn []
-                                     (* dist
-                                        (m/array
-                                          :vectorz
-                                          (repeatedly param-count rand))))))]
-    (if print
-      (do
-        (println "  Count  Rating")
-        (println "-------  ------")
-        (doseq [[rating cnt] (->> errors
-                               (map (fn [error]
-                                      (long (util/clamp 0
-                                                        (- (Math/floor (Math/log10 error)))
-                                                        20))))
-                               frequencies
-                               sort)]
-          (util/sprintf "%7d %s%-6d (%s)%n"
-                        cnt
-                        (case rating
-                          0
-                          "≤"
-                          20
-                          "≥"
-                          " ")
-                        rating
-                        (condp > rating
-                          2 "very bad"
-                          4 "bad"
-                          7 "maybe okay"
-                          "all good"))))
-      errors)))
+                       (repeatedly points #(random-point center dist)))]
+    (case return
+      :errors errors
+      :rating-list (map error->rating errors)
+      :average-rating (->> errors
+                        (map error->rating)
+                        (apply util/avg))
+      :ratings (->> errors
+                 (map error->rating)
+                 frequencies)
+      :print (print-ratings errors)
+      :class-list (->> errors
+                    (map error->rating)
+                    (map rating->class))
+      :classes (->> errors
+                 (map error->rating)
+                 (map rating->class)
+                 frequencies)
+      :print-classes (print-classes errors)
+      (throw (IllegalArgumentException. (str "invalid value for :return (" return ")"))))))

 ;;;; Sample functions


Update content.cljs

Update content.cljs

--- src/prais2/content.cljs
+++ src/prais2/content.cljs
@@ -21,7 +21,7 @@
          (Header. "Longitude"                    false      false    0   0
                   "")
          (Header. "Number of Operations"        true       true     95   50
-                  "The number of heart operations carried out on under-16s at each hospital during the 3 years April 2011 to March 2014")
+                  "The number of heart operations carried out on under-16s at each hospital during the 3 years April 2011 to March 2014. Operations that occur within 30 days of each other are treated as a single operation.")
          (Header. "Number of Deaths"            false       true    75   50
                   "The number of operations where the child  died within 30 days of their operation, from any cause")
          (Header. "Number of Survivors"         false       true    85   50


Remove gradient check comments from sample fns

These should no longer be necessary since we have actual tests for the
sample functions.

--- cortex/src/cortex/optimise/functions.clj
+++ cortex/src/cortex/optimise/functions.clj
@@ -404,9 +404,7 @@
                          (Math/sqrt (inc i)))))))})

 (def sum-of-different-powers
-  "-1 ≤ x ≤ 1
-  performs poorly on gradient check, but appears to
-  be implemented correctly"
+  "-1 ≤ x ≤ 1"
   {:value (fn [args]
             (m/esum
               (m/emap-indexed (fn [[i] xi]
@@ -461,9 +459,7 @@

 (defn michalewicz
   "0 ≤ x ≤ π
-  requires parameter m
-  performs poorly on gradient check, but appears to
-  be implemented correctly"
+  requires parameter m"
   [m]
   {:value (fn [args]
             (- (m/esum


Circle to CircleCI

Circle to CircleCI

--- frontend/components/language_landing.cljs
+++ frontend/components/language_landing.cljs
@@ -154,7 +154,7 @@
              [:div.languages-cta-step
               [:div.step-number]
               [:div
-               "Run one of your " (:language template) " projects on Circle"]]
+               "Run one of your " (:language template) " projects on CircleCI"]]
              [:div.languages-cta-step
               [:div.step-number]
               [:div


+;; TODO

+;; TODO

--- src/babel/italiano/morphology.cljc
+++ src/babel/italiano/morphology.cljc
@@ -241,6 +241,7 @@

 ;; TODO: this is an overly huge method that needs to be rewritten to be easier to understand and maintain.
 ;; TODO: use replace patterns instead (as with French)
+;; TODO: split into morphology/verb function, morphology/noun function, etc.
 (defn get-string-1 [word]
   (if (seq? word)
     (map (string/join " " #(get-string-1 %))


make it possible to interrupt an acquisition

git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@10784 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd


don't use .startsWith, since it's only in ES6 now

--- src/chat/client/views/message.cljs
+++ src/chat/client/views/message.cljs
@@ -62,6 +62,11 @@
         (re-replace (type-info :pattern) text (type-info :replace)))
       text-or-node)))

+; TODO: clojure 1.8 should implement this
+(defn starts-with? [s prefix]
+  ; not using .startsWith because it's only supported in ES6
+  (= 0 (.indexOf s prefix)))
+
 (defn make-delimited-processor
   "Make a new transducer to process the stream of words"
   [{:keys [delimiter result-fn]}]
@@ -78,7 +83,7 @@
            (cond
              ; TODO: handle starting code block with delimiter not at beginning of word
              ; start
-             (and (= @state ::start) (.startsWith input delimiter))
+             (and (= @state ::start) (starts-with? input delimiter))
              (cond
                (and (not= input delimiter) (.endsWith input delimiter))
                (xf result (result-fn (.slice input (count delimiter) (- (.-length input) (count delimiter)))))


Copy over om web impl to ios

Copy over om web impl to ios

--- src/qttt/ui/om_ios.cljs
+++ src/qttt/ui/om_ios.cljs
@@ -1,22 +1,126 @@
 (ns qttt.ui.om-ios
   (:require [qttt.ui.pre-om]
             [om.core :as om]
-            [om.dom :as dom]))
+            [om.dom :as d]
+            [qttt.game :as game]))

 ;; Reset js/React back as the form above loads in an different React
 (set! js/React (js/require "react-native/Libraries/react-native/react-native"))

-(defn widget [data owner]
+(def css-transition-group (js/React.createFactory js/React.addons.CSSTransitionGroup))
+
+(defn class-name
+  "Return a class name string given multiple CSS classes. Nil classes are filtered out."
+  [& classes]
+  (apply str (interpose " " (filter identity classes))))
+
+(defn mark
+  "Return a Om DOM node for a player's mark"
+  [{:keys [player turn focus collapsing]}]
+  (let [icon (if (= 0 player) "fa-plus" "fa-circle-o")
+        player-class (if (= 0 player) "player-x" "player-o")]
+    (d/span #js {:key (str player)
+                 :className (class-name "mark" player-class (when focus "highlight")
+                                        (when collapsing "shake") (when collapsing "shake-constant"))}
+            (d/span #js {:className (class-name "fa" icon)})
+            (d/span #js {:className "turn"} turn))))
+
+(defn entanglement
+  "Om component for an individual entanglement"
+  [e owner]
+  (let [[_ cell _ subcell] (om/path e)
+        game-cursor (om/root-cursor (om/state e))]
+    (reify
+      om/IRender
+      (render [this]
+        (d/td #js {:className (class-name (if (empty? e) "empty-mark" "spooky-mark"))
+                   :onClick (fn [evt]
+                              (om/transact! game-cursor
+                                            #(game/play (game/unspeculate %) cell subcell)))
+                   :onMouseEnter (fn [evt]
+                                   (om/transact! game-cursor
+                                                 #(game/speculate % cell subcell)))
+                   :onMouseLeave (fn [evt]
+                                   (om/transact! game-cursor game/unspeculate))}
+              (css-transition-group #js {:transitionName "mark-transition"}
+                                    (when-not (empty? e) (mark e))))))))
+
+(defn superposition
+  "Om component for a quantum cell"
+  [cell owner]
   (reify
     om/IRender
     (render [this]
-      (js/React.createElement js/React.View
-          (clj->js {:style {:flexDirection "row",
-                            :margin 40 :backgroundColor "#EEFFEE"
-                            :justifyContent "center"}})
-        (js/React.createElement js/React.Text
-            (clj->js {:style {:flex 1,
-                              :justifyContent "center"}})
-            (:text data))))))
+      (d/td #js {:className (class-name "superposition")}
+            (apply d/table nil
+                   (map (fn [row]
+                          (apply d/tr nil
+                                 (map (fn [idx]
+                                        ;; Make sure were have a valid cursor
+                                        (let [e (get-in cell [:entanglements idx]
+                                                        (get-in (assoc-in cell [:entanglements idx] {})
+                                                                [:entanglements idx]))]
+                                          (om/build entanglement e)))
+                                      row)))
+                        (partition 3 (range 9))))))))

-(om/root widget {:text "Hello from ClojureScript!"} {:target 1})
+(defn classical
+  "Om component for a classical cell"
+  [cell owner]
+  (reify
+    om/IRender
+    (render [this]
+      (d/td #js {:className "classical"}
+            (mark (:classical cell))))))
+
+(defn cell
+  "Om component for a square"
+  [cell owner]
+  (if (:classical cell)
+    (classical cell owner)
+    (superposition cell owner)))
+
+(defn instructions [game owner]
+  (reify
+    om/IRender
+    (render [this]
+      (let [[player phase] (game/instructions game)
+            player-classes (if (zero? player)
+                             ["player-x" "fa-plus"]
+                             ["player-o" "fa-circle-o"])]
+        (d/div #js {:className "instructions"}
+               (d/span #js {:className (apply class-name "mark" "fa" player-classes)})
+               (str "'s turn: " phase))))))
+
+(defn board [game owner]
+  (reify
+    om/IRender
+    (render [this]
+      (d/div #js {:className "board-container"}
+             (om/build instructions game)
+             (apply d/table #js {:className "board"}
+                    (map (fn [row]
+                           (apply d/tr nil
+                                  (map (fn [idx]
+                                         (om/build cell
+                                                   (get-in game [:board idx]))) row)))
+                         (partition 3 (range 9))))
+             (d/div #js {:className "repo-link"}
+                    (d/a #js {:href "http://github.com/levand/qttt"}
+                         "http://github.com/levand/qttt"))))))
+
+(defn screen [game owner]
+  (reify
+    om/IRender
+    (render [this]
+      (d/div #js {:className "play-area"}
+             (om/build board game)))))
+
+
+(defn ^:export main
+  []
+  (let [game-state (atom game/new-game)]
+    (om/root
+      screen
+      game-state
+      {:target 1})))


Coments

Coments

--- src/clj/algorithms_clj/huffman.clj
+++ src/clj/algorithms_clj/huffman.clj
@@ -92,7 +92,8 @@
               result)))
         ))))

-(defn decode
+(defn decode ;; TODO - The transducer could be used to do pipe-line parallelism
+  "Decode a stream of inputs, provided the huffman tree as first parameter"
   [huffman-tree inputs]
   (transduce (huffman-xf huffman-tree) conj [] inputs))


the exception message lied about the class name

--- src/clj/runbld/hosting/aws_ec2.clj
+++ src/clj/runbld/hosting/aws_ec2.clj
@@ -27,7 +27,7 @@
                  {:socket-timeout 500 :conn-timeout 500}))
       (catch java.net.SocketTimeoutException _)
       (catch org.apache.http.conn.ConnectTimeoutException _)
-      (catch org.apache.http.conn.NoHttpResponseException _)
+      (catch org.apache.http.NoHttpResponseException _)
       (catch java.net.ConnectException _)
       ;; Non-AWS Windows
       (catch java.net.SocketException _)


Fix pull data WB

Fix pull data WB

--- src/clj_simple_chart/bp/wb_raw.clj
+++ src/clj_simple_chart/bp/wb_raw.clj
@@ -20,16 +20,15 @@
        (mapv #(reduce merge {} %))
        (reduce (fn [o v] (assoc o (get v "alpha-3") (get v "alpha-2"))) {})))

-(def country-name (keyword "Country Name"))
-(def country-code (keyword "Country Code"))
+(def country-name-kw (keyword "Country Name"))
+(def country-code-kw (keyword "Country Code"))

 (defn parse-country-record [prop c]
-  (let [country (get c country-name)
-        country-code (get c country-code)]
+  (let [country (get c country-name-kw)
+        country-code (get c country-code-kw)]
     (reduce (fn [o [k v]]
-              (if (or (= k country)
-                      (= k (keyword "Country"))
-                      (= k country-code)
+              (if (or (= k country-name-kw)
+                      (= k country-code-kw)
                       (zero? (count (name k))))
                 o
                 (let [year-value (read-string (name k))
@@ -42,11 +41,10 @@

 (defn parse-url [indicator prop]
   (let [resp (cached-get (str "http://api.worldbank.org/countries/all/indicators/" indicator "?format=csv"))
-        expected-columns [country-code country-name]
+        expected-columns [country-code country-name-kw "1990" "2015"]
         csv-map (csv/csv-map (:body resp))]
     (spit (str "./data/wb/" indicator ".csv") (csv/debomify (:body resp)))
     (test/is (= 200 (:status resp)))
-    (println (:columns csv-map))
     (->> csv-map
          (csv/assert-columns expected-columns)
          (:data)


Generalize webm integration to video integration

--- src/cljs/openslack/views/text.cljs
+++ src/cljs/openslack/views/text.cljs
@@ -74,9 +74,9 @@
    [:video {:src url
             :controls true}]])

-(def webm-regex #"https?://.*\.webm")
-
-(register-enricher! webm-regex make-video-message)
+(def video-regex #"https?://.*\.(?:webm|mp4|ogv)")
+
+(register-enricher! video-regex make-video-message)

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


refactor modal routes

refactor modal routes

--- src/cljs/salava/page/ui/modal.cljs
+++ src/cljs/salava/page/ui/modal.cljs
@@ -4,7 +4,7 @@
             [markdown.core :refer [md->html]]
             [salava.core.ui.ajax-utils :as ajax]
             [salava.core.i18n :refer [t]]
-            [salava.core.ui.helper :refer [navigate-to path-for]]
+            [salava.core.ui.helper :refer [navigate-to path-for collect-plugin-modal-routes]]
             [salava.badge.ui.helper :as bh]
             [salava.core.time :refer [date-from-unix-time]]
             [salava.file.icons :refer [file-icon]]
@@ -13,9 +13,7 @@
             [reagent.session :as session]
             [salava.core.ui.error :as err]
             [salava.core.ui.modal :refer [set-new-view]]
-            [salava.page.ui.helper :refer [badge-block html-block file-block heading-block tag-block]]
-            [salava.page.ui.edit :as edit]
-            ))
+            [salava.page.ui.helper :refer [badge-block html-block file-block heading-block tag-block]]))

@@ -69,15 +67,15 @@

 (defn init-data [page-id state]
   (ajax/GET
-     (path-for (str "/obpv1/page/view/" page-id) true)
-     {:handler (fn [data]
+    (path-for (str "/obpv1/page/view/" page-id) true)
+    {:handler (fn [data]

-                 (reset! state (assoc data
-                                      :page-id page-id
-                                      :show-link-or-embed-code nil
-                                      :permission "success"
-                                      :badge-small-view false)))}
-     (fn [] (swap! state assoc :permission "error"))))
+                (reset! state (assoc data
+                                :page-id page-id
+                                :show-link-or-embed-code nil
+                                :permission "success"
+                                :badge-small-view false)))}
+    (fn [] (swap! state assoc :permission "error"))))

 (defn handler [params]
@@ -101,5 +99,5 @@
     ))

 (def ^:export modalroutes
-  {:page {:view handler
-          :block-type edit/contenttype}})
+  {:page (merge {:view handler}
+                (collect-plugin-modal-routes [:page ] ["edit"]))})


Getting close to finishing the new HTTP protocol middleware

--- src/clojure/picard/http/server.clj
+++ src/clojure/picard/http/server.clj
@@ -1,5 +1,8 @@
 (ns picard.http.server
   (:use picard.http.core))
+
+;; TODO:
+;; * Count the bytes in the request body

 (declare
  handle-request
@@ -7,8 +10,13 @@
  awaiting-100-continue
  waiting-for-response)

+(defrecord ConnectionState
+    [upstream])
+
 (defrecord ExchangeState
     [connection
+     upstream
+     downstream
      next-up-fn
      next-dn-fn
      keepalive?
@@ -17,9 +25,11 @@
      responded?])

 (defn- initial-exchange-state
-  [conn]
+  [conn downstream]
   (ExchangeState.
    conn
+   nil
+   downstream
    handle-request
    handle-response
    true
@@ -29,20 +39,76 @@

 (defn- awaiting-100-continue?
   [current-state]
-  `(= awaiting-100-continue (.next-up-fn ~current-state)))
+  (= awaiting-100-continue (.next-up-fn current-state)))

 (defn- awaiting-response?
   [current-state]
-  `(= waiting-for-response (.next-up-fn ~current-state)))
-
-(defn- finalize-exchange
-  [state current-state])
+  (= waiting-for-response (.next-up-fn current-state)))
+
+(defn- exchange-finished?
+  [current-state]
+  (and (.responded? current-state)
+       (or (awaiting-response? current-state)
+           (awaiting-100-continue? current-state))))
+
+(defn- maybe-finalize-exchange
+  [current-state]
+  (when (exchange-finished? current-state)
+    (let [conn     (.conn current-state)
+          upstream (.upstream current-state)]
+
+      ;; The current exchange is complete, so remove it from
+      ;; the connection state.
+      (swap! conn #(dissoc % :upstream))
+
+      ;; Send an upstream event that indicates the HTTP exchange
+      ;; is complete.
+      (upstream :done nil))))
+
+(defn- maybe-close-connection
+  [current-state]
+  (when-not (.keepalive? current-state)
+    ((.downstream current-state) :close nil)))

 (defn- stream-or-finalize-response
-  [])
+  [state evt chunk current-state]
+  (when-not (= :body evt)
+    (throw (Exception. "Expecting a :body event")))
+
+  (swap-then!
+   state
+   (fn [current-state]
+     (if chunk
+       (let [bytes-sent     (.bytes-to-send current-state)
+             bytes-expected (.bytes-expected current-state)
+             bytes-to-send  (+ bytes-sent (chunk-size chunk))
+             responded?     (= bytes-expected bytes-to-send)]
+         (assoc current-state
+           :bytes-to-send bytes-to-send
+           :responded?    responded?
+           :next-dn-fn    (when-not responded? stream-or-finalize-request)))
+       ;; This is the final chunk
+       ;; TODO: Check that the content-length is correct
+       (assoc current-state
+         :responded? true
+         :next-dn-fn nil)))
+   (fn [current-state]
+     (let [responded? (.responded? current-state)
+           chunked?   (.chunked? current-state)
+           downstream (.downstream current-state)]
+       ;; It only makes sense to check if the exchange needs to be finalized
+       ;; when the response is complete.
+       (when responded?
+         (maybe-finalize-exchange current-state))
+
+       (cond
+        chunk    (downstream :message (chunk->netty-chunk chunk))
+        chunked? (downstream :message HttpChunk/LAST_CHUNK))
+
+       (maybe-close-connection current-state)))))

 (defn- handle-response
-  [state next-up evt val current-state]
+  [state evt val current-state]
   (when-not (= :response evt)
     (throw (Exception. "Expecting a :response event")))

@@ -89,43 +155,46 @@
                                      (= (hdrs "transfer-encoding") "chunked")
                                      (not (status-expects-body? status))))))))
      (fn [current-state]
-       (throw (Exception. "Not implemented"))))))
+       (let [downstream (.downstream current-state)
+             message    (response->netty-response status hdrs body)]
+         (maybe-finalize-exchange current-state)
+         (downstream :message message)
+         (maybe-close-connection current-state))))))

 (defn- waiting-for-response
   [_ _ _ _ _]
   (throw (Exception. "Not expecting a message right now.")))

 (defn- stream-or-finalize-request
-  [state next-up evt val current-state]
-  ;; TODO: Handle the case when (not= :body evt)
+  [state evt val current-state]
   (let [chunk (normalize-chunk val)]
     (if chunk
-      (next-up :body chunk)
+      ((.upstream current-state) :body chunk)
       (swap-then!
        state
        #(assoc % :next-up-fn waiting-for-response)
        (fn [current-state]
-         (next-up :body nil)
-         (finalize-exchange state current-state))))))
+         (maybe-finalize-exchange current-state)
+         ((.upstream current-state) :body nil)
+         (maybe-close-connection current-state))))))

 (defn- awaiting-100-continue
-  [state next-up evt val current-state]
+  [state evt val current-state]
   (swap-then!
    state
    #(assoc % :next-up-fn stream-or-finalize-request)
-   #(stream-or-finalize-request state next-up evt val %)))
+   #(stream-or-finalize-request state evt val %)))

 (defn- handle-request
-  [state next-up _ [hdrs body :as request] _]
+  [state _ [hdrs body :as request] _]
   (let [keepalive?   (keepalive-request? request)
         expects-100? (expecting-100? request)
         head?        (= "HEAD" (request :request-method))
         chunked?     (= :chunked body)
-        next-up-fn
-        (cond
-         (not chunked?)  waiting-for-response
-         expects-100?    awaiting-100-continue
-         :else           stream-request-body)]
+        next-up-fn   (cond
+                      (not chunked?)  waiting-for-response
+                      expects-100?    awaiting-100-continue
+                      :else           stream-request-body)]

     (swap-then!
      state
@@ -134,32 +203,33 @@
         :head?      head?
         :next-up-fn next-up-fn)
      (fn [current-state]
-       (next-up :request request)
-       (finalize-exchange state current-state)))))
+       (maybe-finalize-exchange current-state)
+       ((.upstream current-state) :request request)
+       (maybe-close-connection current-state)))))

 (defn- mk-downstream-fn
-  [state next-dn]
+  [state]
   (fn [evt val]
     (if (#{:response :body} evt)
       (let [current-state @state]
-        ((.next-dn-fn current-state) state next-dn evt val current-state))
+        ((.next-dn-fn current-state) state evt val current-state))
       (next-dn evt val))))

 (defn- exchange
   [app dn conn]
-  (let [state   (atom (initial-exchange-state conn))
-        next-up (app (mk-downstream-fn state dn))]
+  (let [state   (atom (initial-exchange-state conn dn))
+        next-up (app (mk-downstream-fn state))]
+    ;; Track the upstream
+    (swap! state #(assoc % :upstream next-up))
+
     ;; The exchange event handler only processes events
     ;; related to the current HTTP exchange and will pass
     ;; on all other events.
     (fn [evt val]
       (if (#{:request :body} evt)
         (let [current-state @state]
-          ((.next-up-fn current-state) state next-up evt val current-state))
+          ((.next-up-fn current-state) state evt val current-state))
         (next-up evt val)))))
-
-(defrecord ConnectionState
-    [upstream])

 (defn- throw-http-pipelining-exception
   []
@@ -186,8 +256,12 @@
                (swap! state #(assoc % :upstream next-up))
                (next-up evt val)))

+           (= :close evt)
+           (when next-up
+             (throw (IOException. "Connection reset by peer")))
+
            next-up
            (next-up evt val)

-           :else
+           (not (#{:open :close} evt))
            (throw (Exception. "Not expecting a message right now."))))))))


Simplify component listener for scenes

Simplify component listener for scenes

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

--- src/conexp/contrib/draw/scenes.clj
+++ src/conexp/contrib/draw/scenes.clj
@@ -8,8 +8,8 @@

 (ns conexp.contrib.draw.scenes
   (:use conexp.base)
+  (:use [seesaw.core :only (listen)])
   (:import [java.awt Color]
-           [java.awt.event ComponentListener]
            [java.io File]
            [java.awt.image BufferedImage]
            [javax.imageio ImageIO]
@@ -140,12 +140,9 @@
       (.shouldWorldExtentFitViewport false)
       (.setStyle default-scene-style)
       (add-scene-hook :image-changed))
-    (.addComponentListener (scene-canvas scn)
-                           (proxy [ComponentListener] []
-                             (componentResized [comp-evt]
-                               (call-scene-hook scn :image-changed))
-                             (componentHidden [comp-evt])
-                             (componentShown  [comp-evt])))
+    (listen (scene-canvas scn) :component-resized
+            (fn [_]
+              (call-scene-hook scn :image-changed)))
     scn))

 ;; methods on scenes


Remove ancient commented-out streams for matching (service x), etc

--- src/riemann/streams.clj
+++ src/riemann/streams.clj
@@ -853,13 +853,6 @@
       (call-rescue event children)
       true)))

-; Shortcuts for match
-;(defn description [value & children] (apply match :description value children))
-;(defn host [value & children] (apply match :host value children))
-;(defn metric [value & children] (apply match :metric value children))
-;(defn service [value & children] (apply match :service value children))
-;(defn state [value & children] (apply match :state value children))
-;(defn time [value & children] (apply match :time value children))

 (defn tagged-all
   "Passes on events where all tags are present.


Fix Eastwood. Thanks Eastwood!

Fix Eastwood. Thanks Eastwood!

--- src/open_company/resources/section.clj
+++ src/open_company/resources/section.clj
@@ -3,7 +3,6 @@
             [clj-time.format :as format]
             [clojure.walk :refer (keywordize-keys)]
             [defun.core :refer (defun defun-)]
-            [open-company.config :as c]
             [open-company.resources.common :as common]
             [open-company.resources.company :as company]))


add docstrings for default vars

add docstrings for default vars

--- src/overtone/sc/machinery/defaults.clj
+++ src/overtone/sc/machinery/defaults.clj
@@ -1,44 +1,70 @@
 (ns overtone.sc.machinery.defaults
   (:require [overtone.at-at :as at-at]))

-;; ## SCSynth limits
-(def MAX-NODES 4000)
-(def MAX-BUFFERS 4000)
-(def MAX-SDEFS 2000)
-(def MAX-AUDIO-BUS 1000)
-(def MAX-CONTROL-BUS 4000)
+(def MAX-NODES
+  "Maximum number of executing nodes allowed in the server"
+  4000)

-;;Number of audio busses to reserve. These busses won't be available to users
-;;via overtone.sc.bus/audio-bus
-(def AUDIO-BUS-RESERVE-COUNT 50)
+(def MAX-BUFFERS
+  "Maximum number of audio buffers allowed in the server"
+  4000)

+(def MAX-SDEFS
+  "Maximum number of SynthDefs allowed in the server"
+  2000)

-(def SERVER-HOST "127.0.0.1")
-(def SERVER-PORT nil) ; nil means a random port
-(def N-RETRIES 20)
+(def MAX-AUDIO-BUS
+  "Maximum number of audio busses allowed in the server"
+  1000)

-;; Max number of milliseconds to wait for a reply from the server
-(def REPLY-TIMEOUT 500)
+(def MAX-CONTROL-BUS
+  "Maximum number of control busses allowed in the server"
+  4000)

-;;Max number of samples supported in a UDP OSC message
-(def MAX-OSC-SAMPLES 8192)
+(def AUDIO-BUS-RESERVE-COUNT
+  "Number of audio busses to reserve. These busses won't be available to users
+  via overtone.sc.bus/audio-bus"
+  50)

-;id of root group in node tree on server
-(def ROOT-GROUP 0)
+(def SERVER-PORT
+  "Default port number used when booting external server. If nil, a random port is used"
+  nil)

-;;make an at-at pool for all default scheduling
-(def SC-POOL (at-at/mk-pool))
+(def N-RETRIES
+  "Number of times to attempt to connect to an externally booted server"
+  50)

-(def SC-PATHS {:linux ["scsynth"]
-               :windows ["C:/Program Files/SuperCollider/scsynth.exe"
-                         "D:/Program Files/SuperCollider/scsynth.exe"
-                         "E:/Program Files/SuperCollider/scsynth.exe"
-                         "C:/Program Files (x86)/SuperCollider/scsynth.exe"
-                         "D:/Program Files (x86)/SuperCollider/scsynth.exe"
-                         "E:/Program Files (x86)/SuperCollider/scsynth.exe"]
+(def REPLY-TIMEOUT
+  "Max number of milliseconds to wait for a reply from the server"
+  500)

-               :mac  ["/Applications/SuperCollider/scsynth"] })
+(def MAX-OSC-SAMPLES
+  "Max number of samples supported in a UDP OSC message"
+  8192)

-(def SC-ARGS  {:linux []
-               :windows []
-               :mac   ["-U" "/Applications/SuperCollider/plugins"] })
+(def ROOT-GROUP
+  "ID of root group in node tree on server"
+  0)
+
+(def SC-POOL
+  "make an at-at pool for all default scheduling"
+  (at-at/mk-pool))
+
+(def SC-PATHS
+  "Default system paths to an externally installed SuperCollider server for
+  various operating systems."
+  {:linux ["scsynth"]
+   :windows ["C:/Program Files/SuperCollider/scsynth.exe"
+             "D:/Program Files/SuperCollider/scsynth.exe"
+             "E:/Program Files/SuperCollider/scsynth.exe"
+             "C:/Program Files (x86)/SuperCollider/scsynth.exe"
+             "D:/Program Files (x86)/SuperCollider/scsynth.exe"
+             "E:/Program Files (x86)/SuperCollider/scsynth.exe"]
+   :mac  ["/Applications/SuperCollider/scsynth"] })
+
+(def SC-ARGS
+  "Extra arguments required to correctly boot an external SuperCollider server
+  for various operating systems."
+  {:linux []
+   :windows []
+   :mac   ["-U" "/Applications/SuperCollider/plugins"]})


fix redirect from custom subdomain

fix redirect from custom subdomain

--- src/pc/http/handlers/custom_domain.clj
+++ src/pc/http/handlers/custom_domain.clj
@@ -23,7 +23,9 @@
   {:status 302
    :headers {"Location" (str (url/map->URL {:host (profile/hostname)
                                             :protocol (name (:scheme req))
-                                            :port (:server-port req)
+                                            :port (if (profile/force-ssl?)
+                                                    (profile/https-port)
+                                                    (profile/http-port))
                                             :path (:uri req)
                                             :query (:query-string req)}))}
    :body ""})


minor bug fix (#166)

minor bug fix (#166)

--- src/cortex/compute/cpu/backend.clj
+++ src/cortex/compute/cpu/backend.clj
@@ -44,9 +44,9 @@

 (defn backend
-  [& {:keys [datatype driver device stream]
-      :or [datatype :double]}]
-  (let [driver (or driver (cpu-drv/driver))
+  [& {:keys [datatype driver device stream]}]
+  (let [datatype (or datatype :double)
+        driver (or driver (cpu-drv/driver))
         device (or device (drv/default-device driver))]
     (drv/unsafe-with-compute-device
      device


Improve messages

Improve messages

--- src/inviteyoself/routes/invite.clj
+++ src/inviteyoself/routes/invite.clj
@@ -15,7 +15,7 @@

 (defn ensure-unique-email [email]
   (if (not (invite/unique? email))
-    (throw+ "You've already submitted an invite recently!")
+    (throw+ "邀請函在路上了，請靜待片刻")
     email))

 (defform invite-form {}


better implementation of Field count

better implementation of Field count

--- src/metabase/driver/mongo/query_processor.clj
+++ src/metabase/driver/mongo/query_processor.clj
@@ -133,16 +133,27 @@
              {$project {"_id" false, "avg" true}}))

 (defaggregation ["count" field-id]
-  (aggregate {$match {(field-id->kw field-id) {$exists true}}}
-             {$group {"_id" nil
-                      "count" {$sum 1}}}
-             {$project {"_id" false, "count" true}}))
+  `[{:count (mc/count ^DBApiLayer *mongo-connection* ~*collection-name*
+                      (merge ~*constraints*
+                             {(field-id->kw field-id) {$exists true}}))}])

 (defaggregation ["distinct" field-id]
   (aggregate {$group {"_id" (field-id->$string field-id)}}
              {$group {"_id" nil
                       "count" {$sum 1}}}
              {$project {"_id" false, "count" true}}))
+
+(defn u []
+  (with-mongo-connection [^DBApiLayer conn (sel :one Database :name "Strider")]
+    (binding [*collection-name* "venues"]
+      (eval (aggregate {$match {:atlas_id {$exists true}}}
+                       {$group {"_id" nil
+                                "count" {$sum 1}}}
+                       {$project {"_id" false, "count" true}})))))
+
+(defn x []
+  (with-mongo-connection [^DBApiLayer conn (sel :one Database :name "Strider")]
+    ))

 (defaggregation ["stddev" field-id]
   nil) ; TODO


Fix reflection warning

Fix reflection warning

--- src/metabase/driver/mongo/query_processor.clj
+++ src/metabase/driver/mongo/query_processor.clj
@@ -391,7 +391,7 @@
 (def ^:private fn-name->decoder
   {:ISODate (fn [arg]
               (DateTime. arg))
-   :ObjectId (fn [arg]
+   :ObjectId (fn [^String arg]
                (ObjectId. arg))})

 (defn- form->encoded-fn-name


Removed reference to missing file

Removed reference to missing file


preprocess-multipart updates  * Returns proper fragment drop list for correct metrics calculations

--- src/ais/resilient_decoder.clj
+++ src/ais/resilient_decoder.clj
@@ -153,7 +153,7 @@
                (= (m_fc (first frags)) (count frags)))
         (sort-by m_fn frags)))))

-(defn complete-multipart?
+(defn- complete-multipart?
   "Determines if an input sequence of message fragments is monotonic -- using fragment
   numbers as indicies.  If this is true and the sequence cardinality matches n, it connotes
   the sequence is a complete multipart message.  Useful if sequence doesn't have group tags.
@@ -169,33 +169,38 @@
     (for [match (find-matches! frag-groups unpaired-frags)]
       match)))

-(defn- _decode? [include-types line]
-  (if (= (m_fn line) 1)
-    (contains? include-types (m_type line)) true))
-
-(defn- preprocess-multipart [line include-types unpaired-frags in-ch out-ch]
-  (let [remaining (filter (partial _decode? include-types) (consume (- (m_fc line) 1) in-ch))
-        lines (conj remaining line)
-        groups (group-fragments lines)
-        notag (groups :notag)]
-    (doseq [msg (groups :single)] ; frag reordering can mix single msgs in multipart sequence
-      (async/>!! out-ch [msg]))
-    (if-let [frag (first notag)]
-      ;; ASSUMPTION: multipart fragments are either tagged or untagged and not both in an input stream.
+(defn- -forward [source include-types out-ch]
+  (loop [msgs source
+         acc []]
+    (if-let [msg-frags (first msgs)]
+      (if (contains? include-types (m_type (first msg-frags)))
+        (do
+          (async/>!! out-ch msg-frags)
+          (recur (rest msgs) acc))
+        (recur (rest msgs) (concat acc msg-frags)))
+      acc)))
+
+(defn- -forward-multipart [include-types unpaired-frags groups out-ch]
+  (let [notag (groups :notag)]
+    (if-let [lead-frag (first notag)]
+      ;; ASSUMPTION: multipart fragments are either tagged or untagged (and not both) in an input stream.
       ;; In either case, determine if input fragment sequence forms a complete message.  In tagged
       ;; case, we can search for unmatched fragments in cache to form complete message.  In untagged
       ;; case, no searches can be done; As such, if current fragment sequence doesn't form a complete
-      ;; message they cannot be used as possible matches for subsequent fragment sequences.
-      (if (and (> (count notag) 0) (complete-multipart? (m_fc frag) notag) (contains? include-types (m_type frag)))
+      ;; message they cannot be used as possible matches for subsequent fragment sequences due to ordering
+      ;; ambiguity
+      (if (and (complete-multipart? (m_fc lead-frag) notag) (contains? include-types (m_type lead-frag)))
         (do
           (async/>!! out-ch notag)
-          {:notag []})
-        {:notag notag})
-      (do
-        (doseq [msg (parse-multipart (dissoc groups :notag :single) unpaired-frags)]
-          (if (contains? include-types (m_type (first msg)))
-            (async/>!! out-ch msg)))
-        {:notag notag}))))
+          [])
+        notag)
+      (-forward (parse-multipart (dissoc groups :notag :single) unpaired-frags) include-types out-ch))))
+
+(defn- preprocess-multipart [line include-types unpaired-frags in-ch out-ch]
+  (let [remaining (consume (- (m_fc line) 1) in-ch)
+        groups (group-fragments (conj remaining line))]
+    {:drop (concat (-forward (map vector (groups :single)) include-types out-ch)
+                   (-forward-multipart include-types unpaired-frags groups out-ch))}))

 (defn- log-metrics [dropped invalid]
   (logging/info (format "count.invalid.total=%d" invalid))
@@ -220,9 +225,15 @@
 ;;;   Writes decoded messages to disk.
 ;;;

+;; TODO: Optimize decoding when multipart messages aren't in include-list.
+;; Don't pass thru multipart fragments.
+(defn- -decode? [include-types line]
+  (if (= (m_fn line) 1)
+    (contains? include-types (m_type line)) true))
+
 (defn- filter-stream [include-types in-ch]
   (let [out-ch (async/chan buffer-size)
-        decode? (partial _decode? include-types)
+        decode? (partial -decode? include-types)
         unpaired-frags (atom {})]
     (async/thread
       (loop [dropped 0
@@ -235,16 +246,16 @@
                   (do
                     (async/>!! out-ch [line])
                     (recur dropped invalid))
-                  (let [groups (preprocess-multipart line include-types unpaired-frags in-ch out-ch)]
-                    (recur (+ dropped (count (groups :notag))) invalid)))
-                (let [groups (preprocess-multipart line include-types unpaired-frags in-ch out-ch)]
-                  (recur (+ dropped (count (groups :notag))) invalid)))
+                  (let [ret (preprocess-multipart line include-types unpaired-frags in-ch out-ch)]
+                    (recur (+ dropped (count (ret :drop))) invalid)))
+                (let [ret (preprocess-multipart line include-types unpaired-frags in-ch out-ch)]
+                  (recur (+ dropped (count (ret :drop))) invalid)))
               (recur (inc dropped) invalid))
             (do
               (logging/debug (format "Invalid message syntax: %s" line))
               (recur dropped (inc invalid))))
           (do
-            (log-metrics dropped invalid)
+            (log-metrics (+ dropped (count @unpaired-frags)) invalid)
             (async/close! out-ch)))))
     out-ch))


Gut most of the Swagger tests

Gut most of the Swagger tests

--- spec/rook/swagger_spec.clj
+++ spec/rook/swagger_spec.clj
@@ -1,8 +1,7 @@
 (ns rook.swagger-spec
-  (:import [java.util UUID Date]
-           [javax.servlet.http HttpServletResponse])
   (:use io.aviso.rook
         speclj.core
+        clojure.repl
         clojure.template
         clojure.pprint)
   (:require [io.aviso.rook.dispatcher :as d]
@@ -13,9 +12,10 @@
             [qbits.jet.server :as jet]
             [clojure.tools.logging :as l]))

-#_ (defn- swagger-data [options & ns-specs]
-  (let [[_ routing-table] (d/construct-namespace-handler options ns-specs)]
-    (rs/construct-swagger routing-table)))
+(defn- swagger-object
+  [rook-options swagger-options & ns-specs]
+  (let [[_ routing-table] (d/construct-namespace-handler rook-options ns-specs)]
+    (rs/construct-swagger-object swagger-options routing-table)))

 (defn get*
   [path]
@@ -41,57 +41,17 @@
   data)

 (def expected-swagger-data
-  {"/hotels"
-   {:description "The Hotels Resource."
-    :routes      [{:method :get
-                   :uri    "/hotels"
-                   :metadata
-                           {:summary          "Returns a list of all hotels, with control over sort order."
-                            :return           200
-                            :responseMessages [{:code          200
-                                                :message       ""
-                                                :responseModel [{:id         UUID
-                                                                 :created_at Date
-                                                                 :updated_at Date
-                                                                 :name       String}]}]
-                            :parameters       []}}
-                  {:method :get
-                   :uri    "/hotels/{id}"
-                   :metadata
-                           {:summary          "Returns a single hotel, if found."
-                            :return           200
-                            :responseMessages [{:code          200
-                                                :message       ""
-                                                :responseModel {:id         UUID
-                                                                :created_at Date
-                                                                :updated_at Date
-                                                                :name       String}}
-                                               {:code          404
-                                                :message       ""
-                                                :responseModel nil}]
-                            :parameters       [{:type  :path
-                                                :model {:id String}}]}}]}
-   "/hotels/{hotel-id}/rooms"
-   {:description "A set of rooms within a specific hotel."
-    :routes      [{:method :post
-                   :uri    "/hotels/{hotel-id}/rooms"
-                   :metadata
-                           {:summary          "No endpoint description provided."
-                            :return           nil
-                            :responseMessages ()
-                            :parameters
-                                              [{:type  :path
-                                                :model {:hotel-id String}}]}}]}})
+  {})

-#_ (describe "io.aviso.rook.swagger"
+(describe "io.aviso.rook.swagger"

   (it "can construct swagger data"
-      (let [data (swagger-data nil
-                               ["hotels" 'hotels
-                                [[:hotel-id "rooms"] 'rooms]])]
-        (should= expected-swagger-data data)))
+      (let [data (swagger-object nil nil
+                                 ["hotels" 'hotels
+                                  [[:hotel-id "rooms"] 'rooms]])]
+        #_ (should= expected-swagger-data data)))

-  (context "end-to-end (synchronous)"
+  #_ (context "end-to-end (synchronous)"

     (with-all handler (-> (rook/namespace-handler {:swagger true}
                                                   ["hotels" 'hotels
@@ -99,8 +59,8 @@
                           rook/wrap-with-standard-middleware))

     (with-all server (jet/run-jetty {:ring-handler @handler
-                                     :join? false
-                                     :port 8192}))
+                                     :join?        false
+                                     :port         8192}))

     (it "can start the server"
         (should-not-be-nil @server))


SER-753 refactor image retrieval

SER-753 refactor image retrieval

--- src/vignette/storage/static_assets.clj
+++ src/vignette/storage/static_assets.clj
@@ -22,10 +22,14 @@
     (fs/file-exists? to))
   (->response-object [this] (file-stream this)))

-(defn create-async-response-stored-object [static-image-get]
-  (let [static-image-response @static-image-get]
-    (if (-> static-image-response :status (= 200))
-      (->AsyncResponseStoredObject static-image-response))))
+(defn first-available [image-urls]
+  (if-let [url (first image-urls)]
+    (let [response @(http/get url {:as :stream})]
+      (let [status (:status response)]
+        (if (= 200 status)
+          (->AsyncResponseStoredObject response)
+          (if (= 451 status)
+            (first-available (rest image-urls))))))))

 (defrecord StaticImageStorage [static-image-url] ImageStorageProtocol
   (save-thumbnail [_ _ _] nil)
@@ -33,14 +37,9 @@
   (save-original [_ _ _] nil)

   (get-original [_ original-map]
-    (if-let [uuid (:uuid original-map)]
-      (let [response @(http/get (static-image-url uuid) {:as :stream})]
-        (let [status (:status response)]
-          (if (= 200 status)
-            (->AsyncResponseStoredObject response)
-            (if (= 451 status)
-              (if-let [pid (:blocked-placeholder original-map)]
-                (create-async-response-stored-object (http/get (static-image-url pid) {:as :stream})))))))))
+    (let [uuid (:uuid original-map)
+          pid (:blocked-placeholder original-map)]
+      (first-available (map static-image-url (remove nil? [uuid pid])))))

   (original-exists? [_ image-map] nil
     (if-let [uuid (:uuid image-map)]


up version

up version

--- kafka-clj/project.clj
+++ kafka-clj/project.clj
@@ -1,4 +1,4 @@
-(defproject kafka-clj "2.0.3"
+(defproject kafka-clj "2.0.4"
   :description "fast kafka library implemented in clojure"
   :url "https://github.com/gerritjvv/kafka-fast"
   :license {:name "Eclipse Public License"


Add a decode message benchmark

Add a decode message benchmark

--- benchmarks/mavlink/parse.clj
+++ benchmarks/mavlink/parse.clj
@@ -1,29 +0,0 @@
-(ns mavlink.parse
-  (:require [clojure.java.io :as io]
-            [mavlink.core :as mavlink])
-  (:use perforate.core))
-
-(defgoal parse-goal "Load MAVLink XML's and create a parser")
-
-(defcase parse-goal :one-file
-  []
-  (mavlink/parse {:xml-sources [{:xml-file "common.xml"
-                                 :xml-source (-> "test/resources/common.xml" io/input-stream)}]
-                  :descriptions true}))
-
-(defcase parse-goal :one-file-no-description
-  []
-  (mavlink/parse {:xml-sources [{:xml-file "common.xml"
-                                 :xml-source (-> "test/resources/common.xml" io/input-stream)}]
-                  :descriptions true}))
-
-(defcase parse-goal :multiple-files
-  []
-  (mavlink/parse {:xml-sources [{:xml-file "test-include.xml"
-                                 :xml-source (-> "test/resources/test-include.xml" io/input-stream)}
-                                {:xml-file "common.xml"
-                                 :xml-source (-> "test/resources/common.xml" io/input-stream)}
-                                {:xml-file "uAvionix.xml"
-                                 :xml-source (-> "test/resources/uAvionix.xml" io/input-stream)}
-                                ]
-                  :descriptions true}))


improve performance

improve performance

--- src/babel/francais/writer.clj
+++ src/babel/francais/writer.clj
@@ -50,7 +50,8 @@
             (fn [verb]
               (log/trace (str "verb: " (strip-refs verb)))
               (let [root-form (get-in verb [:français :français])
-                    essere (get-in verb [:synsem :essere])]
+                    essere (get-in verb [:synsem :essere])
+                    medium (medium)]
                 (log/info (str "generating with verb: '" root-form "'"))
                 (.size (map (fn [tense]
                               (let [spec (unify {:root {:français {:français root-form}}}
@@ -76,7 +77,7 @@
                                                                 (process [{:fill-one-language
                                                                            {:count 1
                                                                             :spec spec
-                                                                            :model (medium)
+                                                                            :model medium
                                                                             }}]
                                                                          "fr")
                                                                 ;; TODO: move this to *before*


5 min delay for finish msg

5 min delay for finish msg

--- src/clj/mokkameister/brew.clj
+++ src/clj/mokkameister/brew.clj
@@ -71,6 +71,6 @@

 (defn start-brewing! [in-brew]
   (let [brew     (persist-brew! in-brew)
-        delay-ms (* (:brew-time brew) 60 50)]
+        delay-ms (* (:brew-time brew) 60 1000)]
     (notify-start! brew)
     (delayed! delay-ms (finish-brewing! brew))))


gallery stats

gallery stats

--- src/clj/salava/gallery/db.clj
+++ src/clj/salava/gallery/db.clj
@@ -6,7 +6,7 @@
             [salava.core.util :refer [get-db md->html]]
             [salava.core.countries :refer [all-countries sort-countries]]
             [salava.page.main :as p]
-            [salava.social.db :as so]
+            ;[salava.social.db :as so]
             [clojure.set :refer [subset?]]
             [clojure.string :as string]
             [schema.core :as schema]
@@ -358,3 +358,8 @@
   (let [badge-content (select-common-badge-content {:id badge-content-id} (into {:result-set-fn first} (get-db ctx)))]
     (rename-keys badge-content {:image_file :image :name :title})))

+(defn gallery-stats [ctx]
+  {:profiles (gallery-profiles-count {} (into {:result-set-fn first :row-fn :profiles_count}(get-db ctx)))
+   :pages (gallery-pages-count {} (into {:result-set-fn first :row-fn :pages_count}(get-db ctx)))
+   :badges (gallery-badges-count {} (into {:result-set-fn first :row-fn :badges_count}(get-db ctx)))})
+


Updated dev for use with Redis.

Updated dev for use with Redis.

--- dev-resources/src/dragon/dev.clj
+++ dev-resources/src/dragon/dev.clj
@@ -1,5 +1,5 @@
 (ns dragon.dev
-  "Dragon development namespace
+  "Dragon development namespace.

   This namespace is particularly useful when doing active development on depedent
   blog applications."
@@ -17,6 +17,7 @@
             [dragon.blog.content.rfc5322 :as rfc5322]
             [dragon.blog.generator :as generator]
             [dragon.cli.core :as cli]
+            [dragon.data.sources.redis :as redis-db]
             [dragon.components.core :as component-api]
             [dragon.components.system :as components]
             [dragon.config :as config]
@@ -24,11 +25,14 @@
             [dragon.util :as util]
             [markdown.core :as md]
             [selmer.parser :as selmer]
+            [taoensso.carmine :as car :refer [wcar]]
             [taoensso.timbre :as log]
             [trifl.core :refer [->int]]
             [trifl.java :refer [show-methods]]))

-(logger/set-level! '[dragon clojang] :debug)
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;   State & Transition Vars   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 (def state :stopped)
 (def system nil)
@@ -38,6 +42,20 @@
 (def invalid-start-transitions #{:started :running})
 (def invalid-stop-transitions #{:stopped})
 (def invalid-run-transitions #{:running})
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;   Initial Setup & Utility Functions   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+(logger/set-level! '[dragon clojang] :debug)
+
+(defn redis
+  [& args]
+  (apply redis-db/cmd (concat [system] args)))
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;   State Management   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 (defn init
   ([]
@@ -100,6 +118,10 @@
       (alter-var-root #'state (fn [_] :running))))
   state)

+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;   Reloading Management   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
 (defn -refresh
   ([]
     (repl/refresh))
@@ -119,6 +141,8 @@
   (deinit)
   (refresh :after 'dragon.dev/run))

-;;; Aliases
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;   Aliases   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 (def reload #'reset)


routing: renamed 'user' event into 'api' event

--- examples/_common/middleware/routing.cljs
+++ examples/_common/middleware/routing.cljs
@@ -7,22 +7,22 @@

 ;;;;;;;;;;;;;;;;;;;;;;;;; History object deals with browser url bar
 (defprotocol HistoryProtocol
-  (listen [this on-browser-event on-user-event]
+  (listen [this on-browser-event on-api-event]
           "Starts calling back on history events. There are 2 types of events:
-            1) 'user' - initiated via this API;
+            1) 'api' - initiated via this API;
             2) 'browser' - e.g. changing hash in url bar or clicking forward/back buttons.
           Fires the initial browser callback. Returns a function which stops listening.")
   (token [this] "Return current token.")
-  (replace-token [this token] "Replace token firing user event.")
-  (set-token [this token] "Push token firing user event."))
+  (replace-token [this token] "Replace token firing API event.")
+  (set-token [this token] "Push token firing API event."))

 (defrecord History [-goog-history]
   HistoryProtocol
   (listen
-    [this on-browser-event on-user-event]
+    [this on-browser-event on-api-event]
     (let [key (goog.events/listen -goog-history EventType/NAVIGATE
                                   #((if (.-isNavigation %) on-browser-event
-                                                           on-user-event)
+                                                           on-api-event)
                                     (.-token %)))]
       (on-browser-event (token this))
       #(goog.events/unlistenByKey key)))
@@ -79,7 +79,7 @@
                (reset! unlisten
                        (listen history
                                #(dispatch-signal [::-on-browser-event %])
-                               #(dispatch-signal [::-on-user-event %])))
+                               #(dispatch-signal [::-on-api-event %])))

                (let [token (reaction (::token @model))]
                  (run!
@@ -96,7 +96,7 @@
                (dispatch-action [::-set-token token])
                (dispatch-signal [::on-navigate token]))

-             [::-on-user-event token]
+             [::-on-api-event token]
              (dispatch-action [::-set-token token])

              :else


Remove empty groups.

Remove empty groups.

--- src/uxbox/data/workspace.cljs
+++ src/uxbox/data/workspace.cljs
@@ -156,6 +156,17 @@
             (as-> (get-in state [:pages-by-id page :shapes]) $
               (into [] (remove #(= % id) $))
               (assoc-in state [:pages-by-id page :shapes] $)))
+
+          (clear-empty-groups [state {:keys [group] :as :shape}]
+            (if-let [group' (get-in state [:shapes-by-id group])]
+              (if (empty? (:items group'))
+                (as-> state $
+                  (dissoc-from-page $ group')
+                  (dissoc-from-group $ group')
+                  (dissoc-from-index $ group')
+                  (clear-empty-groups $ group'))
+                state)
+              state))

           (dissoc-from-index [state shape]
             (case (:type shape)
@@ -171,7 +182,8 @@
           (as-> state $
             (dissoc-from-page $ shape)
             (dissoc-from-group $ shape)
-            (dissoc-from-index $ shape)))))))
+            (dissoc-from-index $ shape)
+            (clear-empty-groups $ shape)))))))

 (defn move-shape
   "Mark a shape selected for drawing in the canvas."


Fix fips portion of output filename

Fix fips portion of output filename

"51" should be formatted as "51", not "00051"

--- src/vip/data_processor/s3.clj
+++ src/vip/data_processor/s3.clj
@@ -40,7 +40,7 @@
 (defn format-fips [fips]
   (cond
     (nil? fips) "XX"
-    (< (count fips) 2) (format "%02d" (Integer/parseInt fips))
+    (< (count fips) 3) (format "%02d" (Integer/parseInt fips))
     (< (count fips) 5) (format "%05d" (Integer/parseInt fips))
     :else fips))


Clean up the .nrepl-port file after exit

When the system exits, remove the .nrepl-port file as it is no longer
required.

-=david=-

--- lib/edge.dev.nrepl/src/edge/dev/nrepl.clj
+++ lib/edge.dev.nrepl/src/edge/dev/nrepl.clj
@@ -1,6 +1,7 @@
 (ns ^{:clojure.tools.namespace.repl/load false} edge.dev.nrepl
   (:require
    [nrepl.server]
+   [clojure.java.io :as io]
    [cider.nrepl]
    [refactor-nrepl.middleware :as refactor.nrepl]
    [io.aviso.ansi]))
@@ -25,7 +26,10 @@
                    (conj #'refactor.nrepl/wrap-refactor)
                    piggieback
                    (conj piggieback))))]
-    (spit ".nrepl-port" (:port server))
+    (let [port (:port server)
+          port-file (io/file ".nrepl-port")]
+      (.deleteOnExit port-file)
+      (spit port-file port))
     (println (io.aviso.ansi/yellow (str "[Edge] nREPL client can be connected to port " (:port server))))
     server))


fix for connection being closed occasionally

--- iwaswhere-web/src/clj/iwaswhere_web/store.clj
+++ iwaswhere-web/src/clj/iwaswhere_web/store.clj
@@ -32,7 +32,7 @@
   [{:keys [current-state msg-payload msg-meta]}]
   (let [sente-uid (:sente-uid msg-meta)
         query (update-in msg-payload [:not-tags] (fn [not-tags] (set (map #(s/replace % #"~" "") not-tags))))
-        new-state (assoc-in current-state [:client-queries sente-uid] query)]
+        new-state (update-in current-state [:client-queries sente-uid] merge query)]
     {:new-state new-state
      :send-to-self [:state/publish-current {:sente-uid sente-uid}]}))


Add transfer-rdf-list-links-with-nil to connect rdf:List members to nil where appropriate

--- resources/rules/post_identifier_merge/step_b_ontology_to_ice/step_b/link_bio_with_nil.clj
+++ resources/rules/post_identifier_merge/step_b_ontology_to_ice/step_b/link_bio_with_nil.clj
@@ -1,8 +1,11 @@
-`{:name "link-bio-with-nil"
-  :description "This link-bio-with-properties rule requires both
-  things being linked to be 'bioentities' and thus this rule excludes
-  links within RDF lists that connect to rdf:nil. This rule fills in
-  those missing links."
-  :head ((?/bio ?/p rdf/nil))
-  :body ((?/c obo/IAO_0000219 ?/bio)
-         (?/c ?/p rdf/nil))}+`{:name "transfer-rdf-list-links-with-nil"
+  :description "This rule transfers links to rdf:nil from list members to bio world. These links are
+  predominantly '?x rdf:rest rdf/nil'."
+  :head ((?/bio_list_member ?/p rdf/nil))
+  :sparql-string "select ?bio_list_member ?p {
+  ?list_record rdf:type ccp:IAO_EXT_0000317 .
+  ?list_record obo:IAO_0000219 ?list_member .
+  ?list_member ?p rdf:nil .
+  ?list_record obo:IAO_0000219 ?bio_list_member .
+  filter (?list_member != ?bio_list_member)
+  }"}


Updated tools.reader version (fixes #93)

--- ring-core/project.clj
+++ ring-core/project.clj
@@ -4,7 +4,7 @@
   :license {:name "The MIT License"
             :url "http://opensource.org/licenses/MIT"}
   :dependencies [[org.clojure/clojure "1.3.0"]
-                 [org.clojure/tools.reader "0.7.3"]
+                 [org.clojure/tools.reader "0.8.1"]
                  [ring/ring-codec "1.0.0"]
                  [commons-io "2.4"]
                  [commons-fileupload "1.3"]


Correct typos and removes unnecessary `as-element`

--- examples/react-mde/src/example/core.cljs
+++ examples/react-mde/src/example/core.cljs
@@ -1,9 +1,9 @@
 (ns example.core
-  "This example shows how to use the `react-mde` library, which privdes a markdown editor as
+  "This example shows how to use the `react-mde` library, which provides a markdown editor as
   a React component.
   The integration is not straightforward because we need to provide a custom `textarea`
-  component to `ReactMde`, so we can have the cursor positining fixes needed by reagent. BUT
-  we must make sure that `ReactMde` sees a ref to the true `textarea` component, and not reagents
+  component to `ReactMde` so we can have the cursor positining fixes needed by reagent. BUT
+  we must make sure that `ReactMde` sees a ref to the true `textarea` component, and not reagent's
   wrapper."
   (:require [reagent.core :as r]
             [reagent.dom :as rdom]
@@ -50,13 +50,10 @@
   "Renders a ReactMde component with a custom textarea, but without `forwardRef`"
   []
   (let [state (r/atom {:value "Initial Value!" :tab "write"})
-        textarea (r/create-class
-                  {:reagent-render
-                   (fn [props]
-                     (r/as-element [:textarea props]))})]
+        textarea (r/create-class {:reagent-render (fn [props] [:textarea props])})]
     (fn []
       [:div {:style common-style}
-       [:h3 "Without custom textarea, but no forwardRef"]
+       [:h3 "With custom textarea but no forwardRef"]
        [:i "Cursor behaves fine, but the functionalities from the toolbar are broken."]
        [:> ReactMde {:value (:value @state)
                      :on-change #(swap! state assoc :value %)


Upgrade dependencies in deps.cljs

Upgrade dependencies in deps.cljs


working on moves for hexapod

working on moves for hexapod

--- src/strangeloop_dance_party/hexapod.clj
+++ src/strangeloop_dance_party/hexapod.clj
@@ -77,10 +77,10 @@
 (defn send-command-from-queue []
   (do (println "command queue is " @command-queue)
       (let [command (or (first @command-queue) default-command)]
-        (println "Sending ..." command)
+       ; (println "Sending ..." command)
         (reset! command-queue (rest @command-queue))
         (send-robot command)
-        (Thread/sleep 50))))
+        (Thread/sleep 33))))

 (defn add-command [command]
   (swap! command-queue conj command))
@@ -151,17 +151,79 @@
 (defn start-communicator []
   (send robot-agent (fn [_]
                       (while @talk-on?
-                        (send-command-from-queue)
-                        (Thread/sleep 300)))))
+                        (send-command-from-queue)))))

 ;;; moves for the beat and amplitude

+;;; need to be in translate-mode
+
 (defn up-down [amplitude]
   "maps a set of moves through a range with an amplitude from 0-1
    -- if a move set is being peformed then don't send it"
-  (let [num-moves (int (+ (* amplitude 190) 10))]
-    (map #(move % CENTER CENTER CENTER) (range 10 200 100))
-    ))
+  (assert (and (pos? amplitude) (>= 1 amplitude)) )
+  (let [num-moves (int  (* amplitude 10))
+        move-range (conj (vec (range 10 200 num-moves)) 200)]
+    (println "num moves " num-moves " move-range " move-range)
+    (map #(move % CENTER CENTER CENTER) move-range)))
+
+
+(defn twist-right-left [amplitude]
+  "maps a set of moves through a range with an amplitude from 0-1
+   -- if a move set is being peformed then don't send it"
+  (assert (and (pos? amplitude) (>= 1 amplitude)) )
+  (let [num-moves (int  (* amplitude 10))
+        move-range (conj (vec (range 10 200 num-moves)) 200)]
+    (println "num moves " num-moves " move-range " move-range)
+    (map #(move CENTER % CENTER CENTER) move-range)))
+
+(defn shift-forward-backwards [amplitude]
+  "maps a set of moves through a range with an amplitude from 0-1
+   -- if a move set is being peformed then don't send it"
+  (assert (and (pos? amplitude) (>= 1 amplitude)) )
+  (let [num-moves (int  (* amplitude 10))
+        move-range (conj (vec (range 10 200 num-moves)) 200)]
+    (println "num moves " num-moves " move-range " move-range)
+    (map #(move CENTER CENTER % CENTER) move-range)))
+
+(defn shift-left-right [amplitude]
+  "maps a set of moves through a range with an amplitude from 0-1
+   -- if a move set is being peformed then don't send it"
+  (assert (and (pos? amplitude) (>= 1 amplitude)) )
+  (let [num-moves (int  (* amplitude 10))
+        move-range (conj (vec (range 10 200 num-moves)) 200)]
+    (println "num moves " num-moves " move-range " move-range)
+    (map #(move CENTER CENTER CENTER %) move-range)))
+
+
+(defn wave1 [amplitude]
+  "maps a set of moves through a range with an amplitude from 0-1
+   -- if a move set is being peformed then don't send it"
+  (assert (and (pos? amplitude) (>= 1 amplitude)) )
+  (let [num-moves (int  (* amplitude 10))
+        move-range (conj (vec (range 10 200 num-moves)) 200)]
+    (println "num moves " num-moves " move-range " move-range)
+    (map #(move % % CENTER CENTER) move-range)))
+
+(defn wave2 [amplitude]
+  "maps a set of moves through a range with an amplitude from 0-1
+   -- if a move set is being peformed then don't send it"
+  (assert (and (pos? amplitude) (>= 1 amplitude)) )
+  (let [num-moves (int  (* amplitude 10))
+        move-range (conj (vec (range 10 200 num-moves)) 200)]
+    (println "num moves " num-moves " move-range " move-range)
+    (map #(move % CENTER % CENTER) move-range)))
+
+
+(defn wave3 [amplitude]
+  "maps a set of moves through a range with an amplitude from 0-1
+   -- if a move set is being peformed then don't send it"
+  (assert (and (pos? amplitude) (>= 1 amplitude)) )
+  (let [num-moves (int  (* amplitude 10))
+        move-range (conj (vec (range 10 200 num-moves)) 200)]
+    (println "num moves " num-moves " move-range " move-range)
+    (map #(move % CENTER % CENTER) move-range)))
+
+;;;;

 (agent-errors robot-agent)
 (comment
@@ -184,10 +246,21 @@
   (sit-up)
   (change-mode :translate-mode)

+  (up-down 0.5)
+  (twist-right-left 0.5)
+  (shift-forward-backwards 0.5)
+  (shift-left-right 0.5)
+  (wave1 0.5)
+  (wave2 0.5)
+  (wave3 0.5)
+
+
+
   ;; up down  range between 10 and 200 safter
   ;; 20 is slow mave through range
   ;; 100 is faster move through the range
-  (map #(move % CENTER CENTER CENTER) (range 10 200 20))
+  (map #(move % CENTER CENTER CENTER) (range 10 200 10))
+  (map #(move % CENTER CENTER CENTER) (reverse (range 10 200 20)))

   ;; up down
   (map #(move % CENTER CENTER CENTER) (range 10 200 100))


Refactor image storage layout.

Refactor image storage layout.

--- src/uxbox/main/ui/dashboard/images.cljs
+++ src/uxbox/main/ui/dashboard/images.cljs
@@ -57,19 +57,22 @@
   (-> (l/in [:dashboard :images])
       (l/derive st/state)))

-(def ^:private collections-map-ref
-  (-> (comp (l/key :image-colls-by-id)
-            (ul/merge library/+image-collections-by-id+))
+(def ^:private collections-ref
+  (-> (l/key :image-colls-by-id)
       (l/derive st/state)))

-(def ^:private collections-ref
-  (-> (l/lens vals)
-      (l/derive collections-map-ref)))
-
-(defn- focus-collection
-  [id]
-  (-> (l/key id)
-      (l/derive collections-map-ref)))
+(def ^:private images-ref
+  (-> (l/key :images-by-id)
+      (l/derive st/state)))
+
+;; (def ^:private collections-ref
+;;   (-> (l/lens vals)
+;;       (l/derive collections-map-ref)))
+
+;; (defn- focus-collection
+;;   [id]
+;;   (-> (l/key id)
+;;       (l/derive collections-map-ref)))

 ;; --- Page Title

@@ -131,7 +134,7 @@
             (let [type (:type collection)
                   id (:id collection)]
               (rs/emit! (di/select-collection type id))))]
-    (let [images (count (:images collection))]
+    (let [images (count (:images collection []))]
       [:li {:on-click on-click
             :class-name (when selected? "current")}
        [:span.element-title (:name collection)]
@@ -140,10 +143,10 @@

 (mx/defc nav-section
   {:mixins [mx/static mx/reactive]}
-  [type selected]
+  [type selected colls]
   (let [own? (= type :own)
         builtin? (= type :builtin)
-        collections (cond->> (mx/react collections-ref)
+        collections (cond->> (vals colls)
                       own? (filter #(= :own (:type %)))
                       builtin? (filter #(= :builtin (:type %)))
                       own? (sort-by :id))]
@@ -160,17 +163,16 @@
            (mx/with-key key)))]))

 (mx/defc nav
-  {:mixins [mx/static mx/reactive]}
-  []
-  (let [dashboard (mx/react dashboard-ref)
-        collections (mx/react collections-ref)
-        selected (:id dashboard)
-        type (:type dashboard)
-        own? (= type :own)
+  {:mixins [mx/static]}
+  [{:keys [type id] :as state} colls]
+  (let [own? (= type :own)
         builtin? (= type :builtin)]
     (letfn [(select-tab [type]
-              (let [xf (filter #(= type (:type %)))
-                    colls (sequence xf collections)]
+              (let [xf (comp
+                        (map second)
+                        (filter #(= type (:type %))))
+                    colls (into [] xf colls)
+                    colls (sort-by :id colls)]
                 (if-let [item (first colls)]
                   (rs/emit! (di/select-collection type (:id item)))
                   (rs/emit! (di/select-collection type)))))]
@@ -183,7 +185,7 @@
          [:li {:class-name (when own? "current")
                :on-click (partial select-tab :own)}
           "YOUR LIBRARIES"]]
-        (nav-section type selected)]])))
+        (nav-section type id colls)]])))

 ;; --- Grid

@@ -248,13 +250,14 @@
      [:span (:name image)]]))

 (mx/defc grid
-  {:mixins [mx/static]}
-  [state selected {:keys [id type images] :as coll}]
-  (let [own? (= type :own)
+  {:mixins [mx/static mx/reactive]}
+  [{:keys [id type  selected] :as state}]
+  (let [filtering (:filter state)
         ordering (:order state)
-        filtering (:filter state)
-        images (->> images
-                    (remove nil?)
+        own? (= type :own)
+        images (rum/react images-ref)
+        images (->> (vals images)
+                    (filter #(= id (:collection %)))
                     (filter-images-by filtering)
                     (sort-images-by ordering))]
     [:div.dashboard-grid-content
@@ -269,23 +272,22 @@

 (mx/defc content
   {:mixins [mx/static]}
-  [state coll]
-  (let [selected (:selected state)
-        coll-type (:type coll)
-        own? (= coll-type :own)]
+  [{:keys [type id selected] :as state} coll]
+  (let [own? (= type :own)]
     (when coll
       [:section.dashboard-grid.library
        (page-title coll)
-       (grid state selected coll)
-       (when (and (seq selected))
+       (grid state)
+       (when (seq selected)
          (grid-options coll))])))

 ;; --- Menu

 (mx/defc menu
-  {:mixins [mx/static]}
-  [state coll]
-  (let [ordering (:order state :name)
+  {:mixins [mx/static mx/reactive]}
+  [coll]
+  (let [state (mx/react dashboard-ref)
+        ordering (:order state :name)
         filtering (:filter state "")
         icount (count (:images coll))]
     (letfn [(on-term-change [event]
@@ -346,13 +348,13 @@
   {:will-mount images-page-will-mount
    :did-remount images-page-did-remount
    :mixins [mx/static mx/reactive]}
-  [type id]
+  [_ _]
   (let [state (mx/react dashboard-ref)
-        coll-id (:id state)
-        coll (mx/react (focus-collection coll-id))]
+        colls (mx/react collections-ref)
+        coll (get colls (:id state))]
     [:main.dashboard-main
      (header)
      [:section.dashboard-content
-      (nav)
-      (menu state coll)
+      (nav state colls)
+      (menu coll)
       (content state coll)]]))


Sort image collections by name instead by id.

--- src/uxbox/main/ui/dashboard/images.cljs
+++ src/uxbox/main/ui/dashboard/images.cljs
@@ -149,7 +149,7 @@
         collections (cond->> (vals colls)
                       own? (filter #(= :own (:type %)))
                       builtin? (filter #(= :builtin (:type %)))
-                      own? (sort-by :id))]
+                      own? (sort-by :name))]
     [:ul.library-elements
      (when own?
        [:li
@@ -171,8 +171,8 @@
               (let [xf (comp
                         (map second)
                         (filter #(= type (:type %))))
-                    colls (into [] xf colls)
-                    colls (sort-by :id colls)]
+                    colls (->> (into [] xf colls)
+                               (sort-by :name))]
                 (if-let [item (first colls)]
                   (rs/emit! (di/select-collection type (:id item)))
                   (rs/emit! (di/select-collection type)))))]


Fix errors

Fix errors

--- src/org/spootnik/cyanite/store.clj
+++ src/org/spootnik/cyanite/store.clj
@@ -208,14 +208,14 @@
                             (doall (map #(future
                                            (->> (alia/execute
                                                  session fetch!
-                                                 {:values [% tenant (int rollup)
+                                                 {:values [[%] tenant (int rollup)
                                                            (int period)
                                                            from to]
                                                   :fetch-size Integer/MAX_VALUE})
                                                 (map detect-aggregate)
-                                                (seq))
-                                           paths)))]
-                        (map deref futures)))]
+                                                (seq)))
+                                           paths))]
+                        (remove nil? (reduce concat (map deref futures)))))]
           (let [min-point  (:time (first data))
                 max-point  (-> to (quot rollup) (* rollup))
                 nil-points (->> (range min-point (inc max-point) rollup)


Don't create tag until *after* pushing to repo (fixes adzerk/bootlaces#6)

--- boot/core/src/boot/task/built_in.clj
+++ boot/core/src/boot/task/built_in.clj
@@ -624,9 +624,9 @@
                       (format "scm tag in pom doesn't match (%s, %s)" t ensure-tag))
               (assert (or (not ensure-version) (= v ensure-version))
                       (format "jar version doesn't match project version (%s, %s)" v ensure-version))
+              (util/info "Deploying %s...\n" (.getName f))
+              (pod/with-call-worker
+                (boot.aether/deploy ~(core/get-env) ~[repo r] ~(.getPath f) ~artifact-map))
               (when tag
                 (util/info "Creating tag %s...\n" v)
-                (git/tag v "release"))
-              (util/info "Deploying %s...\n" (.getName f))
-              (pod/with-call-worker
-                (boot.aether/deploy ~(core/get-env) ~[repo r] ~(.getPath f) ~artifact-map)))))))))
+                (git/tag v "release")))))))))


Use mapcat over flatten map

Use mapcat over flatten map

--- src/tile_game/board.clj
+++ src/tile_game/board.clj
@@ -79,7 +79,7 @@
 (defn dijkstra-map [dmap coords seen cost]
   (if (empty? (set/difference coords seen))
     dmap
-    (let [costs (flatten (map #(list (coords->index dmap %) cost) coords))
+    (let [costs (mapcat #(list (coords->index dmap %) cost) coords)
           edges (reduce set/union #{}
                         (map #(set (adjacent-coords dmap %)) coords))
           next (set/difference edges seen)]


Load Config by filename and load default all in place

--- src/toggler/handler.clj
+++ src/toggler/handler.clj
@@ -10,6 +10,9 @@

 (defn read-default-config []
   (decode (slurp (io/resource "config.json")) true))
+
+(defn read-custom-config [filename]
+  (decode (slurp (str "custom-config/" filename ".json")) true))

 (def cfg (atom (read-default-config)))

@@ -28,14 +31,14 @@
    (swap! cfg assoc component-name component-toggles))
   ([component setting newval]
   (let [toggle-map (get @cfg (keyword component))]
-    (swap! cfg assoc-in [(keyword component)] (assoc toggle-map (keyword setting) newval))))
-  )
+    (swap! cfg assoc-in [(keyword component)] (assoc toggle-map (keyword setting) newval)))))

 (defn reload-config [config]
   (reset! cfg config))

-(defn reset-cfg []
-  (reload-config (read-default-config)))
+(defn reset-cfg
+  ([] (reload-config (read-default-config)))
+  ([filename] (reload-config (read-custom-config filename))))

 (defn backup-config []
   (spit
@@ -137,11 +140,19 @@
   :post! (fn [_] (saveconfig filename))
   :handle-ok (encode {:filename filename}) )

+(defresource load-config-from-file [filename]
+ :allowed-methods [:post]
+  :available-media-types ["application/json"]
+  :post! (fn [_] (reset-cfg filename))
+  :handle-ok (encode {:filename filename}) )
+
 (defroutes app-routes
   (GET "/" [] status)
   (PUT "/reconfigure" {body :body} (let [bodydecoded (decode (slurp body) true)]
                                      (reconfigure bodydecoded)))
   (PUT "/reset" [] reset-config)
+  (POST "/reset" {body :body} (let [bodydecoded (decode (slurp body) true)]
+                               (load-config-from-file (get bodydecoded :filename))))
   (PUT "/save" [] save-config)
   (POST "/save" {body :body} (let [bodydecoded (decode (slurp body) true)]
                                (save-config-to-file (get bodydecoded :filename))))


improve test

improve test

--- test/clj/com/rpl/specter/core_test.clj
+++ test/clj/com/rpl/specter/core_test.clj
@@ -135,12 +135,13 @@

 (defspec transform-last-compound
   (for-all+
-   [v (gen/such-that #(some odd? %) (gen/vector gen/int))]
-   (let [v2 (transform [(filterer odd?) LAST] inc v)
+   [pred (gen/elements [odd? even?])
+    v (gen/such-that #(some pred %) (gen/vector gen/int))]
+   (let [v2 (transform [(filterer pred) LAST] inc v)
          differing-elems (differing-elements v v2)]
      (and (= (count v2) (count v))
           (= (count differing-elems) 1)
-          (every? even? (drop (first differing-elems) v2))
+          (every? (complement pred) (drop (first differing-elems) v2))
           ))))

 ;; max sizes prevent too much data from being generated and keeps test from taking forever


simplify test

simplify test

--- test/clj/lambdacd/steps/shell_test.clj
+++ test/clj/lambdacd/steps/shell_test.clj
@@ -63,8 +63,4 @@
               :out    ""
               :status :killed}
              (bash (some-ctx is-killed) "/"
-                   "echo foo"
-                   "sleep .5"
-                   "echo bar"
-                   "sleep 5"
-                   "echo this-is-after-more-than-five-seconds-and-shouldnt-appear-in-output"))))))+                   "echo foo"))))))


CMR-1280: Updates ISO MENDS spatial code to prefer seq over empty?

--- umm-lib/src/cmr/umm/iso_mends/spatial.clj
+++ umm-lib/src/cmr/umm/iso_mends/spatial.clj
@@ -161,7 +161,7 @@
     (gmd-poly
      (x/element :gml:Polygon {:gml:id (gen-id)}
                 (x/element :gml:exterior {} (gml-linear-ring (:points exterior)))
-                (when-not (empty? interior)
+                (when (seq interior)
                   (map #(x/element :gml:interior {} (gml-linear-ring (:points %))) interior))))))

 (defmethod geometry->iso-geom cmr.spatial.mbr.Mbr


CMR-3194: Remove commented out debug line

--- system-int-test/test/cmr/system_int_test/search/facets/collection_facets_v2_search_test.clj
+++ system-int-test/test/cmr/system_int_test/search/facets/collection_facets_v2_search_test.clj
@@ -143,7 +143,6 @@
           (is (< (index "default-p0") (index "Terra"))))))

     (testing "Science keywords are sorted alphabetically"
-      ; (println "Response is" response)
       (let [response (search-and-return-v2-facets
                       {:science-keywords-h {:0 {:topic "Popular"}}})
             science-keywords (-> (:children response) first :children)]


Set target-path to maintain compatibility with lein 2.3

--- boot-classloader/project.clj
+++ boot-classloader/project.clj
@@ -7,5 +7,5 @@
                  [org.springframework/spring-core "1.2.2"]
                  [com.cemerick/pomegranate        "0.2.0" :exclusions [org.clojure/clojure]]]
   :main ^:skip-aot tailrecursion.boot-classloader
-  :target-path "target/%s"
+  :target-path "target" ; force target-path to maintain 2.3 compatibility
   :profiles {:uberjar {:aot :all}})


remove react include. not needed

remove react include. not needed

--- env/dev/clj/load_test_om/dev.clj
+++ env/dev/clj/load_test_om/dev.clj
@@ -14,7 +14,6 @@
   (comp
      (set-attr :class "is-dev")
      (prepend (html [:script {:type "text/javascript" :src "/js/out/goog/base.js"}]))
-     (prepend (html [:script {:type "text/javascript" :src "/react/react.js"}]))
      (append  (html [:script {:type "text/javascript"} "goog.require('load_test_om.main')"]))))

 (defn browser-repl []


Trigger progress bar

Trigger progress bar

--- frontend/src/cruncher/shredder/main.cljs
+++ frontend/src/cruncher/shredder/main.cljs
@@ -4,23 +4,25 @@
             [cruncher.utils.lib :as lib]
             [cruncher.config :as config]
             [cruncher.communication.utils :as clib]
-            [cruncher.communication.main :as com]))
+            [cruncher.communication.main :as com]
+            [cruncher.communication.progress :as progress]))

 (defn success-handler
   "React on response after sending a new statement. Reset atom and call newly received url."
   [response]
-  (let [res (com/process-response response)]
-    (lib/info! "Converted Pokemon to bonbons. Jeah!")
-    (com/route :get-all-pokemon)))
+  (lib/update-progress-status! {:status "finished", :to_delete 1, :deleted 1})
+  (com/route :get-all-pokemon))

 (defn power-on
   "Crunch 'em all!"
-  []
+  [this]
   (let [url (:crunch-selected-pokemon config/api)
         selected-pokemon (vec (map #(.. % -value) (filter #(.. % -checked) (gdom/getElementsByClass "poketable-checkbox"))))]
     (when (pos? (count selected-pokemon))
       (when (js/confirm "Do you really want to send away the selected Pokemon?\nYou won't get them back!\n\nConsider your decision.")
         (lib/loading!)
+        (lib/update-progress-status! {:status "ok", :to_delete (count selected-pokemon), :deleted 0})
+        (progress/query-status this)
         (POST (clib/make-url url)
               {:body            (clib/clj->json {:ids selected-pokemon
                                                  :safe 1})