Convert explode-element-name to take a string, not a keyword

--- src/main/clojure/cascade/internal/viewbuilder.clj
+++ src/main/clojure/cascade/internal/viewbuilder.clj
@@ -35,19 +35,18 @@
       (pr-str any))))))

 (defn explode-element-name
-  "Explodes an element name keyword into a seq of three-element vectors. Each vector
+  "Explodes an element name string into a seq of three-element vectors. Each vector
   consists of the portion of the name prior to the match, the match character, and
-  the match term. :div.alpha#beta would split to [[\"div\" \".\" \"alpha\"] [\"div.alpha\" \"#\" \"beta\"]]."
-  [element-name]
-  (let [name-str (name element-name)]
-    ; match sequences of word characters prefixed with '.' or '#' within the overall name
-    (loop [matcher (re-matcher #"([.#])([\w-]+)" name-str)
-           result []]
-      (if (.find matcher)
-        (recur matcher (conj result [(.substring name-str 0 (.start matcher))
-                                     (.group matcher 1)
-                                     (.group matcher 2)]))
-        result))))
+  the match term. div.alpha#beta would split to [[\"div\" \".\" \"alpha\"] [\"div.alpha\" \"#\" \"beta\"]]."
+  [^String element-name]
+  ; match sequences of word characters prefixed with '.' or '#' within the overall name
+  (loop [matcher (re-matcher #"([.#])([\w-]+)" element-name)
+         result []]
+    (if (.find matcher)
+      (recur matcher (conj result [(.substring element-name 0 (.start matcher))
+                                   (.group matcher 1)
+                                   (.group matcher 2)]))
+      result)))

 (defn extract-attributes
   [exploded match key attributes]
@@ -66,7 +65,7 @@
   a keyword if there is only a single value. The attributes map may be nil if the
   element-name is simple."
   [element-name]
-  (let [exploded (explode-element-name element-name)]
+  (let [exploded (explode-element-name (name element-name))]
     (if (empty? exploded)
       [element-name nil]
       (let [simple-element-name (keyword (get-in exploded [0 0]))
@@ -74,72 +73,72 @@
             attributes (->> {} (extract "." :class) (extract "#" :id))]
         [simple-element-name attributes]))))

-(defn combine
-  "Given the results of rendering (where each step provides a render result), combine the results
-into a single sequence of DOM nodes. Each of the render results should be a DOM node,
-or a collection of DOM nodes (or a nested collection of DOM nodes, etc.). Strings are also allowed,
-which are converted into :text DOM nodes."
-  [& render-results]
-  (loop [output (transient [])
-         queue render-results]
-    (let [current (first queue)
-          remainder (next queue)]
-      (cond
-        (nil? current) (if (empty? remainder) (persistent! output) (recur output remainder))
-        (sequential? current) (recur output (concat current remainder))
-        :otherwise (recur (conj! output (convert-render-result current)) remainder)))))
+        (defn combine
+          "Given the results of rendering (where each step provides a render result), combine the results
+    into a single sequence of DOM nodes. Each of the render results should be a DOM node,
+    or a collection of DOM nodes (or a nested collection of DOM nodes, etc.). Strings are also allowed,
+    which are converted into :text DOM nodes."
+          [& render-results]
+          (loop [output (transient [])
+                 queue render-results]
+            (let [current (first queue)
+                  remainder (next queue)]
+              (cond
+                (nil? current) (if (empty? remainder) (persistent! output) (recur output remainder))
+                (sequential? current) (recur output (concat current remainder))
+                :otherwise (recur (conj! output (convert-render-result current)) remainder)))))

-(with-monad parser-m
-  (declare parse-embedded-template)
+        (with-monad parser-m
+          (declare parse-embedded-template)

-  (def parse-text
-    (domonad [text match-string]
-      ; The encode-string occurs just once, at macro expansion time
-      `(raw-node ~(encode-string text))))
+          (def parse-text
+            (domonad [text match-string]
+              ; The encode-string occurs just once, at macro expansion time
+              `(raw-node ~(encode-string text))))

-  (def parse-name
-    ; An attribute or element name is either a keyword or a form that yields a keyword.
-    (match-first match-keyword))
+          (def parse-name
+            ; An attribute or element name is either a keyword or a form that yields a keyword.
+            (match-first match-keyword))

-  (def parse-body
-    (domonad [body match-vector]
-      (parse-embedded-template body)))
+          (def parse-body
+            (domonad [body match-vector]
+              (parse-embedded-template body)))

-  (def parse-entity
-    (domonad [entity-name match-keyword :when (.startsWith (name entity-name) "&")]
-      `(raw-node ~(str (name entity-name) ";"))))
+          (def parse-entity
+            (domonad [entity-name match-keyword :when (.startsWith (name entity-name) "&")]
+              `(raw-node ~(str (name entity-name) ";"))))

-  (def parse-element
-    (domonad [name parse-name
-              attributes (optional match-map)
-              body (optional parse-body)]
-      (let [[factored-element-name implicit-attributes] (factor-element-name name)
-            assembled-attributes (merge implicit-attributes attributes)]
-        `(element-node ~factored-element-name ~assembled-attributes ~body))))
+          (def parse-element
+            (domonad [name parse-name
+                      attributes (optional match-map)
+                      body (optional parse-body)]
+              (let [[factored-element-name implicit-attributes] (factor-element-name name)
+                    assembled-attributes (merge implicit-attributes attributes)]
+                `(element-node ~factored-element-name ~assembled-attributes ~body))))

-  ; Accept a single form that will act as a renderer, returning a render
-  ; result, which will be combined with other render results via the
-  ; parse-forms parser. This form may be a symbol or a list (a function call).
-  (def parse-form
-    (domonad [form match-form]
-      form))
+          ; Accept a single form that will act as a renderer, returning a render
+          ; result, which will be combined with other render results via the
+          ; parse-forms parser. This form may be a symbol or a list (a function call).
+          (def parse-form
+            (domonad [form match-form]
+              form))

-  (def parse-single-form
-    (match-first parse-text parse-entity parse-element parse-form))
+          (def parse-single-form
+            (match-first parse-text parse-entity parse-element parse-form))

-  (def parse-forms
-    (domonad [forms (none-or-more parse-single-form)]
-      ; Evaluation order means that the DOM tree is effectively constructed bottom-to-top
-      ; (because combine is not lazy).
-      ; This may be be relevent in terms of ordering of CSS stylesheets & JavaScript libraries,
-      ; since that information is "collected on the side" (in an atom) and therefore not
-      ; purely functional. Perhaps there's a monadic approach that will allow the construction
-      ; of the DOM tree and the collection of CSS/JS data to occur in a stricly functional way?
-      `(combine ~@forms)))
-  ) ; with-monad parser-m
+          (def parse-forms
+            (domonad [forms (none-or-more parse-single-form)]
+              ; Evaluation order means that the DOM tree is effectively constructed bottom-to-top
+              ; (because combine is not lazy).
+              ; This may be be relevent in terms of ordering of CSS stylesheets & JavaScript libraries,
+              ; since that information is "collected on the side" (in an atom) and therefore not
+              ; purely functional. Perhaps there's a monadic approach that will allow the construction
+              ; of the DOM tree and the collection of CSS/JS data to occur in a stricly functional way?
+              `(combine ~@forms)))
+          ) ; with-monad parser-m

-(defn parse-embedded-template
-  "Used as part of (defview) or (template) to convert the a form, the embedded template, into
+        (defn parse-embedded-template
+          "Used as part of (defview) or (template) to convert the a form, the embedded template, into
 a new list of forms that constructs the structure layed out by the template."
-  [forms]
-  (run-parse parse-forms forms "embedded template forms"))+          [forms]
+          (run-parse parse-forms forms "embedded template forms"))


Makes log in logging-exception-handler be INFO level (#1396)

--- scheduler/src/cook/rest/api.clj
+++ scheduler/src/cook/rest/api.clj
@@ -2956,12 +2956,12 @@
       in-str)))

 (defn- logging-exception-handler
-  "Wraps `base-handler` with an additional `log/error` call which logs the request and exception"
+  "Wraps `base-handler` with an additional `log/info` call which logs the request and exception"
   [base-handler]
   (fn logging-exception-handler [ex data req]
-    (log/error ex "Error when processing request"
-               (-> (dissoc req ::c-mw/options :body :ctrl :request-time :servlet-request :ssl-client-cert)
-                   (update-in [:headers] (fn [headers] (pc/map-vals (fn [value] (truncate value 80)) headers)))))
+    (log/info ex "Error when processing request"
+              (-> (dissoc req ::c-mw/options :body :ctrl :request-time :servlet-request :ssl-client-cert)
+                  (update-in [:headers] (fn [headers] (pc/map-vals (fn [value] (truncate value 80)) headers)))))
     (base-handler ex data req)))

 ;;


server - add ring reload

server - add ring reload

--- src/osmium/core.clj
+++ src/osmium/core.clj
@@ -4,6 +4,7 @@
             [clojure.edn :as edn]
             [clojure.java.io :as io]
             [com.stuartsierra.component :as component]
+            [ring.middleware.reload :refer [wrap-reload]]
             [ring.middleware.params :as params]
             [ring.middleware.edn :refer [wrap-edn-params]]
             [ring.util.response :as response]
@@ -23,6 +24,7 @@
 (def app-handler
   (-> main-routes
       wrap-edn-params
+      wrap-reload
       handler/site))

 (defn start-jetty [handler port]


forgot to add entry point body in the queue

--- src/crawler/crawl.clj
+++ src/crawler/crawl.clj
@@ -792,7 +792,10 @@
                                       extract
                                       stop?
                                       []
-                                      {}
+                                      {entry-point {:body (:body body)
+                                                    :url entry-point
+                                                    :src-url nil
+                                                    :src-text nil}}
                                       (if (leaf? {:anchor-text nil
                                                   :src-url     nil
                                                   :body        (:body body)})


convolute try/let

convolute try/let

--- src/rester/core.clj
+++ src/rester/core.clj
@@ -137,12 +137,12 @@
 (defn -main
   "Give me a CSV with API rest cases and I will verify them"
   [& args]
-  (let [opts (apply hash-map (map-indexed #(if (even? %1) (subs %2 1) %2) (rest args)))
-        _ (println "running with arguments:" opts)
-        xml-report (str "target/" (str/replace (first args) #"\.csv" "-results.xml"))
-        results (test-all (load-tests-from (first args) opts))]
-    (try
+  (try
+    (let [opts (apply hash-map (map-indexed #(if (even? %1) (subs %2 1) %2) (rest args)))
+          _ (println "running with arguments:" opts)
+          xml-report (str "target/" (str/replace (first args) #"\.csv" "-results.xml"))
+          results (test-all (load-tests-from (first args) opts))]
       ((juxt #(junit-report xml-report %) print-test-results) results)
-      (System/exit (:total-failures results))
-      (finally
-        (shutdown-agents)))))
+      (System/exit (:total-failures results)))
+    (finally
+      (shutdown-agents))))


removed commented code

removed commented code

--- src/selmer/tags.clj
+++ src/selmer/tags.clj
@@ -24,7 +24,7 @@
        (apply concat)
        (split-with (partial not= "in"))))

-(defn for-handler [args #_[^String id _ ^String items] tag-content render rdr]
+(defn for-handler [args tag-content render rdr]
   (let [content (tag-content rdr :for :empty :endfor)
         for-content (get-in content [:for :content])
         empty-content (get-in content [:empty :content])


rolled back arg exception

rolled back arg exception

--- src/selmer/util.clj
+++ src/selmer/util.clj
@@ -47,13 +47,8 @@
 (def ^:dynamic ^Pattern   *endblock-pattern* nil)

 (defn check-tag-args [args]
-  (cond
-    (or (.contains args "= ") (.contains args " ="))
-    (exception "there shouldn't be spaces near `=` in param assign statement: " args)
-
-    (odd? (count (filter #{\"} args)))
-    (exception "malformed tag arguments in " args)
-    :else args))
+  (if (even? (count (filter #{\"} args)))
+    args (exception "malformed tag arguments in " args)))

 (defn read-tag-info [rdr]
   (let [buf (StringBuilder.)


added game state check\change

added game state check\change

--- src/ttt/handler.clj
+++ src/ttt/handler.clj
@@ -10,7 +10,7 @@

 (cheshire.generate/add-encoder org.bson.types.ObjectId cheshire.generate/encode-str)

-(def empty-field [0,0,0,0,0,0,0,0,0])
+(def empty-field 0)

 (defn generate
   "generates a unique token for the game"
@@ -22,6 +22,7 @@
   [error]
   (case error
     :wrong-turn (generate-string {:error "wrong turn"})
+    :occupied-cell (generate-string {:error "the cell is already occupied"})
     :invalid-state (generate-string {:error "invalid state"})
     :not-found (generate-string {:error "resource not found"})
     (generate-string {:error "unknown error"})))
@@ -42,7 +43,7 @@
     (let [{type "type" password "password"} body]
       (case type
         0 (generate-string
-                  (mc/insert-and-return db coll {:token (generate) :type type :field empty-field :state :first-player-turn}))
+            (mc/insert-and-return db coll {:token (generate) :type type :field1 empty-field :field2 empty-field :state :first-player-turn}))
         1 "shared key"
         "asd Bad request")))

@@ -50,24 +51,69 @@
     "Returns a status of a game by id"
     [id]
     (generate-string
-        (mc/find-one db coll {:token id} [:token :state :field]) false))
+        (mc/find-one db coll {:token id} [:token :state :field1 :field2]) false))
+
+  (defn win? [field]
+    (cond
+      (= (bit-and field 7) 7) true
+      (= (bit-and field 56) 56) true
+      (= (bit-and field 448) 448) true
+      (= (bit-and field 292) 292) true
+      (= (bit-and field 146) 146) true
+      (= (bit-and field 73) 73) true
+      (= (bit-and field 273) 273) true
+      (= (bit-and field 84) 84) true
+      :else false))
+
+  (defn tie? [field1 field2]
+    (= (bit-or field1 field2) 511))
+
+  (defn get-state [current-state field1 field2]
+    (if (win? field1)
+      :first-player-wins
+      (if (win? field2)
+        :second-player-wins
+        (if (tie? field1 field2)
+          :tie
+          (if (= current-state "first-player-turn")
+            :second-player-turn
+            :first-player-turn)))))
+
+  (defn add-and-check [position game]
+    (let [field1 (get game :field1)
+          field2 (get game :field2)
+          state (get game :state)
+          pos-mask (bit-shift-left 1 position)]
+      (cond
+        (= (bit-and (bit-or field1 field2) pos-mask) 0)
+        (case state
+          "first-player-turn" (generate-string
+                                (mc/save-and-return db coll
+                                  (assoc game
+                                    :state (get-state state (bit-or field1 pos-mask) field2)
+                                    :field1 (bit-or field1 pos-mask))))
+          "second-player-turn" (generate-string
+                                 (mc/save-and-return db coll
+                                   (assoc game
+                                     :state (get-state state field1 (bit-or field2 pos-mask))
+                                     :field2 (bit-or field2 pos-mask)))))
+          :else (fail :occupied-cell))))

   (defn make-turn
     "Make a turn"
     [id, body]
     (let [game (mc/find-one-as-map db coll {:token id})
-          {state :state field :field token :token} game
+          {state :state field1 :field1 field2 :field2 token :token} game
           {player "player" position "position"} body]
-      (prn player)
       (case state
         "first-player-turn" (cond
-                               (= player 1) (generate-string (mc/save-and-return db coll (assoc game :state :second-player-turn)))
+                               (= player 1) (add-and-check position game)
                                :else (fail :wrong-turn))
         "second-player-turn" (cond
-                               (= player 2) (generate-string (mc/save-and-return db coll (assoc game :state :first-player-turn)))
+                               (= player 2) (add-and-check position game)
                                :else (fail :wrong-turn))
-        "first-player-won" (generate-string game)
-        "second-player-won" (generate-string game)
+        "first-player-wins" (generate-string game)
+        "second-player-wins" (generate-string game)
         "tie" (generate-string game)
         (fail :invalid-state)))))


Remove unused list-contains? function

Remove unused list-contains? function

--- src/vdquil/util.clj
+++ src/vdquil/util.clj
@@ -4,9 +4,3 @@
 (defn hex-to-rgb [hex]
   (map (comp #(Integer/parseInt % 16) (partial apply str))
        (partition 2 (.replace hex "#" ""))))
-
-;; Substitute for contains? for lists
-(defn in?
-  "true if seq contains elm"
-  [seq elm]
-  (some #(= elm %) seq))


CMR-1297 Adds a :pre check.

CMR-1297 Adds a :pre check.

--- search-app/src/cmr/search/results_handlers/atom_results_handler.clj
+++ search-app/src/cmr/search/results_handlers/atom_results_handler.clj
@@ -464,4 +464,5 @@

 (defmethod qs/single-result->response :atom
   [context query results]
+  {:pre [(<= (count (:items results)) 1)]}
   (qs/search-results->response context query results))


Remove printwritter impl.

Remove printwritter impl.

--- src/decimal/core.cljs
+++ src/decimal/core.cljs
@@ -755,11 +755,6 @@
     (let [t *decimal*]
       (t. v)))

-  cljs.core/IPrintWithWriter
-  (-pr-writer [mv writer _]
-    (cljs.core/-write writer "#decimal ")
-    (cljs.core/-write writer (.toString mv)))
-
   cljs.core/IDeref
   (-deref [v]
     (.toNumber v))


Add translations for tooltip

Add translations for tooltip

--- src/discuss/core.cljs
+++ src/discuss/core.cljs
@@ -27,7 +27,7 @@
 (om/root sidebar/view lib/app-state
          {:target (.getElementById js/document (lib/prefix-name "sidebar"))})

-(om/root tooltip/view {}
+(om/root tooltip/view lib/app-state
          {:target (.getElementById js/document (lib/prefix-name "tooltip"))})

 (om/root contribute/view {}


Added config functions for extra logging.

--- src/dragon/config.clj
+++ src/dragon/config.clj
@@ -107,6 +107,30 @@
   [system]
   (components/get-config system :cli :log-nss))

+(defn repl
+  [system]
+  (components/get-config system :repl))
+
+(defn repl-log-level
+  [system]
+  (components/get-config system :repl :log-level))
+
+(defn repl-log-nss
+  [system]
+  (components/get-config system :repl :log-nss))
+
+(defn app
+  [system]
+  (components/get-config system :app))
+
+(defn app-log-level
+  [system]
+  (components/get-config system :app :log-level))
+
+(defn app-log-nss
+  [system]
+  (components/get-config system :app :log-nss))
+
 (defn templating
   [system]
   (components/get-config system :templating))


I think this assertion is too strict for grouping.

--- src/onyx/scheduling/percentage_task_scheduler.clj
+++ src/onyx/scheduling/percentage_task_scheduler.clj
@@ -50,9 +50,7 @@

 (defn percentage-balanced-taskload
   [replica job candidate-tasks n-peers]
-  {:post [(>= n-peers 0)
-;;          (= n-peers (reduce + (map :allocation (vals %))))
-          ]}
+  {:post [(>= n-peers 0)]}
   (let [sorted-tasks (tasks-by-pct replica job candidate-tasks)
         allocations (largest-remainder-allocations replica sorted-tasks n-peers job)
         oversaturated (filter (fn [{:keys [task allocation]}]


Remove label

Remove label

--- src/status_im/ui/screens/multiaccounts/recover/views.cljs
+++ src/status_im/ui/screens/multiaccounts/recover/views.cljs
@@ -32,9 +32,7 @@
       {:style {:color       colors/gray
                :text-align  :center
                :line-height 22}}
-      (i18n/label :t/custom-seed-phrase-text-1)
-      [{:style {:color colors/black}}
-       (i18n/label :t/custom-seed-phrase-text-2)]]]
+      (i18n/label :t/custom-seed-phrase-text-1)]]
     [react/view {:margin-vertical 24
                  :align-items     :center}
      [button/button {:on-press            #(re-frame/dispatch [:hide-popover])


Finished todos of new-execute-request.

Finished todos of new-execute-request.

--- src/async/http/client/request.clj
+++ src/async/http/client/request.clj
@@ -260,40 +260,34 @@
               :done    (promise)
               :error   (promise)}]
     (.executeRequest
-     *ahc*
-     req
+     *ahc* req
      (proxy [AsyncHandler] []
-       (onStatusReceived
-        [#^HttpResponseStatus e]
-        (let [[result action] (status resp (convert-status-to-map e))]
-          (deliver (:status resp) result)
-          (convert-action action)))
-       (onHeadersReceived
-        [#^HttpResponseHeaders e]
-        (let [[result action] (headers resp (convert-headers-to-map e))]
-          (deliver (:headers resp) result)
-         (convert-action action)))
-       (onBodyPartReceived
-        [#^HttpResponseBodyPart e]
-        (when-let [bytes (.getBodyPartBytes e)]
-          (let [length (alength bytes)
-                baos (ByteArrayOutputStream. length)]
-            (.write baos bytes 0 alength)
-            (let [[result action] (part resp baos)
-                  body (:body resp)]
-              (if-not (delivered? body)
-                (deliver body result))
-              (convert-action action)))))
-       (onCompleted
-        []
-        ;; TODO this is wrong, no call to completed
-        (deliver (:done resp) true))
-       (onThrowable
-        [#^Throwable t]
-        (do
-          (print-cause-trace t)
-          ;; TODO this needs to deliver as well
-          (error resp t)))))
+       (onStatusReceived [#^HttpResponseStatus e]
+                         (let [[result action] (status resp (convert-status-to-map e))]
+                           (deliver (:status resp) result)
+                           (convert-action action)))
+       (onHeadersReceived [#^HttpResponseHeaders e]
+                          (let [[result action] (headers resp (convert-headers-to-map e))]
+                            (deliver (:headers resp) result)
+                            (convert-action action)))
+       (onBodyPartReceived [#^HttpResponseBodyPart e]
+                           (when-let [bytes (.getBodyPartBytes e)]
+                             (let [length (alength bytes)
+                                   baos (ByteArrayOutputStream. length)]
+                               (.write baos bytes 0 alength)
+                               (let [[result action] (part resp baos)
+                                     body (:body resp)]
+                                 (if-not (delivered? body)
+                                   (deliver body result))
+                                 (convert-action action)))))
+       (onCompleted []
+                    (do
+                      (completed resp)
+                      (deliver (:done resp) true)))
+       (onThrowable [#^Throwable t]
+                    (do
+                      (print-cause-trace t)
+                      (deliver (:error resp) (error resp t))))))
     ^{:started (System/currentTimeMillis)}
     resp))


Only scale if width/height is positive

Only scale if width/height is positive

Fixes: #11728
Signed-off-by: Andrea Maria Piana <39e16ece3c2d27e1889178b15ddb376e524032f8@gmail.com>

--- src/status_im/ui/screens/chat/message/styles.cljs
+++ src/status_im/ui/screens/chat/message/styles.cljs
@@ -130,7 +130,8 @@
        :height (* aspect-ratio max-width)})))

 (defn link-preview-image [outgoing {:keys [height width] :as dimensions}]
-  (merge (if (and height width)
+  (merge (if (and (pos? height)
+                  (pos? width))
            (scale-dimensions dimensions)
            {:height 170})
          {:overflow                   :hidden


Refactored create-job and update-job to use the proper job template

--- src/emender_jenkins/jenkins_api.clj
+++ src/emender_jenkins/jenkins_api.clj
@@ -149,11 +149,15 @@
         :trust-store      "keystore"
         :trust-store-pass "changeit"}))

+(defn get-template
+    [metadata]
+    (slurp (if metadata "data/template.xml" "data/template_with_metadata.xml")))
+
 (defn create-job
-    [jenkins-url jenkins-auth include-jenkins-reply? job-name git-repo branch]
+    [jenkins-url jenkins-auth include-jenkins-reply? job-name git-repo branch metadata]
     (log-operation job-name git-repo branch "create")
-    (let [template (slurp "data/template.xml")
-          config   (update-template template git-repo branch)
+    (let [template (get-template metadata)
+          config   (update-template template git-repo branch metadata)
           url      (str (update-jenkins-url jenkins-url jenkins-auth) "createItem?name=" (.replaceAll job-name " " "%20"))]
           (println "URL to use: " url)
           (try
@@ -164,10 +168,10 @@
                   (error-response-structure job-name "create" e)))))

 (defn update-job
-    [jenkins-url jenkins-auth include-jenkins-reply? job-name git-repo branch]
+    [jenkins-url jenkins-auth include-jenkins-reply? job-name git-repo branch metadata]
     (log-operation job-name git-repo branch "update")
-    (let [template (slurp "data/template.xml")
-          config   (update-template template git-repo branch)
+    (let [template (get-template metadata)
+          config   (update-template template git-repo branch metadata)
           url      (str (job-name->url (update-jenkins-url jenkins-url jenkins-auth) job-name) "/config.xml")]
           (println "URL to use: " url)
           (try


more general pattern-matching for tokenization

--- src/babel/francais/morphology.clj
+++ src/babel/francais/morphology.clj
@@ -516,44 +516,65 @@
                 )]
     suffix))

+;; used for parsing: TODO: unify with generation
+(def pattern-to-structure
+  {
+   #"^(\S+)ée$" [{:replace-with "er"
+                  :structure {:synsem {:infl :past-p
+                                       :subcat {:1 {:agr {:number :sing
+                                                          :gender :fem}}}}}}]
+   #"^(\S+)ées$" [{:replace-with "er"
+                   :structure {:synsem {:infl :past-p
+                                        :subcat {:1 {:agr {:number :plur
+                                                           :gender :fem}}}}}}]
+   #"^(\S+)é$" [{:replace-with "er"
+                 :structure {:synsem {:infl :past-p
+                                      :subcat {:1 {:agr {:number :sing
+                                                         :gender :masc}}}}}}]
+   #"^(\S+)és$" [{:replace-with "er"
+                  :structure {:synsem {:infl :past-p
+                                       :subcat {:1 {:agr {:number :plur
+                                                          :gender :masc}}}}}}]
+
+   ;; -er and -ir type verbs
+   #"^(\S+)e$" [{:replace-with "er"
+                 :structure {:synsem {:subcat {:1 {:agr {:number :sing
+                                                         :person :1st}}}
+                                      :infl :present}}}
+                {:replace-with "ir"
+                 :structure {:synsem {:subcat {:1 {:agr {:number :sing
+                                                         :person :1st}}}
+                                      :infl :present}}}]
+   }
+  )
+
+(defn find-structure-from-pattern [patterns surface-form]
+  (if (not (empty? patterns))
+    (if (re-find (first patterns) surface-form)
+      (map (fn [each]
+             (merge {:pattern (first patterns)}
+                    each))
+           (get pattern-to-structure (first patterns)))
+      (find-structure-from-pattern (rest patterns) surface-form))))
+
 (defn analyze [surface-form lexicon]
   "return the map incorporating the lexical information about a surface form.
    The function tries to analyze the surface form into a lexical form, and then
    looks up the hypothesized lexeme using lookup-fn."
-  (cond
-
-   (= surface-form "allées")
-   (concat
-    (map (fn [lexeme]
-           (unifyc
-            lexeme
-            {:synsem {:subcat {:1 {:agr {:number :plur
-                                         :gender :fem}}}}}))
-         (get lexicon "aller"))
-    (get lexicon surface-form))
-
-   (re-find #"e$" surface-form)
-   (concat
-
-    ;; -er type verb
-    (map (fn [lexeme]
-           (unifyc
-            lexeme
-            {:synsem {:subcat {:1 {:agr {:number :sing
-                                         :person :1st}}}
-                      :infl :present}}))
-         (get lexicon (string/replace surface-form #"(e)$" "$1r")))
-
-    ;; -ir type verb
-    (map (fn [lexeme]
-           (unifyc
-            lexeme
-            {:synsem {:subcat {:1 {:agr {:number :sing
-                                         :person :1st}}}
-                      :infl :present}}))
-         (get lexicon (string/replace surface-form #"(e)$" "ir")))
-
-    (get lexicon surface-form))
-
-   true
-   (get lexicon surface-form)))
+  (let [matches (find-structure-from-pattern (keys pattern-to-structure)
+                                             surface-form)]
+    (cond
+     (not (empty? matches))
+     (concat
+      (mapcat (fn [match]
+                (map (fn [lexeme]
+                       (unifyc
+                        lexeme
+                        (:structure match)))
+                     (get lexicon (str (string/replace surface-form (:pattern match) "$1") (:replace-with match)))))
+              matches)
+      (get lexicon surface-form))
+
+     true
+     (get lexicon surface-form))))
+


Improve the help doc string

Improve the help doc string

--- src/afrey/boot_asset_fingerprint.clj
+++ src/afrey/boot_asset_fingerprint.clj
@@ -21,7 +21,13 @@
   (or (-> path io/file .getParent) ""))

 (core/deftask asset-fingerprint
-  "Fingerprint files in a pod"
+  "Replace asset references with a URL query-parameter based on the hash contents.
+
+  The main purpose of doing this is for cache-busting static assets
+  that were deployed with a far-future expiration date. See the Ruby
+  on Rails Asset Pipeline guide, segment \"What is Fingerprinting and
+  Why Should I Care\" for a detailed explanation of why you want to do this.
+  (http://guides.rubyonrails.org/asset_pipeline.html#what-is-fingerprinting-and-why-should-i-care-questionmark) "
   [s skip            bool  "Skips file fingerprinting and replaces each asset url with bare"
    e extensions  EXT  [str] "Add a file extension to indicate the files to process for asset references."
    _ asset-host HOST str   "Host to prefix all asset urls with"


list missing packages

list missing packages

--- src/clj/ikea_clojure_cup/pack.clj
+++ src/clj/ikea_clojure_cup/pack.clj
@@ -7,13 +7,19 @@
   (def sample-param
     {:bins [{:id "car" :depth 5 :weight 5 :height 5}]
      :packages [{:id "11" :depth 10 :weight 10 :height 10}
-                {:id "22" :depth 20 :weight 2 :height 20}]}))
+                {:id "22" :depth 2 :weight 2 :height 2}]}))

 (defn bin->string [{:keys [id depth weight height]}]
   (format "%s:0:%sx%sx%s" id depth weight height))

 (defn package->string [{:keys [id depth weight height]}]
   (format "%s:0:0:%sx%sx%s" id depth weight height))
+
+(defn get-missing [requested-packages packing-details]
+  (let [all (map :id requested-packages)
+        packed (set (map :id (-> packing-details first :items)))
+        missing (set (remove packed all))]
+  (filter #(missing (:id %)) requested-packages)))

 (defn pack [{:keys [bins packages]}]
   (let [bins (cs/join "," (map bin->string bins))
@@ -22,18 +28,23 @@
         response (http-kit/post url)
         packing-details (json/read-str (:body @response) :key-fn keyword)
         requested-items-count (count packages)
-        items-count (-> packing-details first :items count)]
-    {:result (cond
-              (= items-count 0) :no
-              (= items-count requested-items-count) :yes
-              (not= items-count requested-items-count) :partial)
-     :details packing-details}))
+        items-count (-> packing-details first :items count)
+        result (cond
+                (= items-count 0) :no
+                (= items-count requested-items-count) :yes
+                (not= items-count requested-items-count) :partial)]
+    (merge {:result result
+            :details packing-details}
+           (when (= :partial result)
+             {:missing (get-missing packages packing-details)}))))

 (comment
   (pack sample-param)
+  (def res-partial [{:curr_weight 0, :weight_limit 0, :item_count 1, :size_2 5, :size "5 x 5 x 5", :size_1 5, :id "0", :size_3 5, :items [{:constraints 0, :y_origin_in_bin -1.5, :x_origin_in_bin -1.5, :sp_size_3 2, :size_2 2, :sp_size_2 2, :sp_size "2 x 2 x 2", :weight 0, :size_1 2, :orig_size "2 x 2 x 2", :id "22", :size_3 2, :z_origin_in_bin 1.5, :sp_size_1 2}]}])

   (def res-yes [{:curr_weight 0, :weight_limit 0, :item_count 1, :size_2 5, :size "5 x 5 x 5", :size_1 5, :id "0", :size_3 5, :items [{:constraints 0, :y_origin_in_bin -1.5, :x_origin_in_bin -1.5, :sp_size_3 2, :size_2 2, :sp_size_2 2, :sp_size "2 x 2 x 2", :weight 0, :size_1 2, :orig_size "2 x 2 x 2", :id "22", :size_3 2, :z_origin_in_bin 1.5, :sp_size_1 2}]}])
+

   (def resp-preview (let [response (http-kit/post "http://www.packit4me.com/api/call/preview?bins=0:50:5x5x5&items=0:0:15:1x1x1&binId=0")]


old websocket client rmeoved in favor of chord

--- src/cljs/hellhound/websocket.cljs
+++ src/cljs/hellhound/websocket.cljs
@@ -2,66 +2,4 @@
   "In order to connect to the HellHound's websocket server
   you need to use functions provided by this ns."
   (:require
-   [cljs.core.async        :as async]
    [hellhound.logger       :as log]))
-
-(defn handle-connection-error
-  []
-  (log/error "Couldn't connect to remote server."))
-
-(defn on-close
-  []
-  (log/info "Socket closed!"))
-
-(defn on-recv
-  [packet packer chan]
-  (if-not (satisfies? IPacker packer)
-    (throw "The provided packer does not satisfies IPacker protocol."))
-
-  (let [data (unpack packer packet)]
-    (log/debug "DATA RECV:")
-    (log/debug data)
-    (async/put! chan data)))
-
-(defn create-recv-channel
-  []
-  (async/chan 100))
-
-(defn create-send-channel
-  []
-  (async/chan 100))
-
-(defn set-channels!
-  [connection packer]
-
-  (let [recv-channel (create-recv-channel)
-        send-channel (create-send-channel)]
-
-    (set! (.-onmessage connection) #(on-recv % packer recv-channel))
-    (set! (.-onclose   connection) on-close)
-
-    {:connection   connection
-     packer        packer
-     :recv-channel recv-channel
-     :send-channel send-channel}))
-
-
-
-
-
-(defn create-json-packer
-  []
-  (JsonPacker.))
-
-(defn connect!
-  "Connect to remote websocket server"
-  ([url]
-   (connect! url {}))
-
-  ([url {:keys [packer]
-         :as options
-         :or {packer  (create-json-packer)}}]
-
-   (if-let [conn (js/WebSocket. url)]
-     (set-channels! conn packer)
-     (handle-connection-error))))


cond-button refactoring

cond-button refactoring

--- src/cljs/netrunner/gameboard.cljs
+++ src/cljs/netrunner/gameboard.cljs
@@ -239,11 +239,11 @@
      [:div.panel.blue-shade.identity
       (om/build card-view (:identity cursor))]])))

-(defn cond-button [text cond command args]
+(defn cond-button [text cond f]
   (sab/html
    (if cond
      [:button.disabled text]
-     [:button {:on-click #(send-command command args)} text])))
+     [:button {:on-click f} text])))

 (defn gameboard [{:keys [side gameid] :as cursor} owner]
   (reify
@@ -274,13 +274,15 @@
                (when (:keep me)
                  [:div
                   (when (= side :runner)
-                    (cond-button "Remove Tag" (or (< (:click me) 1) (< (:credit me) 2) (< (:tag me) 1)) "remove-tag"))
+                    (cond-button "Remove Tag"
+                                 (or (< (:click me) 1) (< (:credit me) 2) (< (:tag me) 1))
+                                 #(send-command "remove-tag")))
                   (when (= side :runner)
-                    (cond-button "Run" (< (:click me) 1) "run" {:server :hq}))
+                    (cond-button "Run" (< (:click me) 1) #(send-command "run")))
                   (when (= side :corp)
-                    (cond-button "Purge" (< (:click me) 3) "purge"))
-                  (cond-button "Draw" (< (:click me) 1) "draw")
-                  (cond-button "Take Credit" (< (:click me) 1) "credit")])]
+                    (cond-button "Purge" (< (:click me) 3) #(send-command "purge")))
+                  (cond-button "Draw" (< (:click me) 1) #(send-command "draw"))
+                  (cond-button "Take Credit" (< (:click me) 1) #(send-command "credit"))])]

               [:div.leftpane
                [:div


Fix server ordering to be numeric

Fix server ordering to be numeric

remote->num is an integer, and we use that to sort in get-remotes and
remote-list

--- src/cljs/netrunner/gameboard.cljs
+++ src/cljs/netrunner/gameboard.cljs
@@ -252,7 +252,7 @@
                          )))) ": ")))

 (defn remote->num [server]
-  (-> server str (clojure.string/split #":remote") last))
+  (-> server str (clojure.string/split #":remote") last js/parseInt))

 (defn remote->name [server]
   (let [num (remote->num server)]
@@ -261,10 +261,10 @@
 (defn get-remotes [servers]
  (->> servers
      (filter #(not (#{:hq :rd :archives} (first %))))
-     (sort-by #(remote->name (first %)))))
+     (sort-by #(remote->num (first %)))))

 (defn remote-list [remotes]
-  (->> remotes (map #(remote->name (first %))) sort))
+  (->> remotes (map #(remote->name (first %))) (sort-by #(remote->num (first %)))))

 (defn card-view [{:keys [zone code type abilities counter advance-counter advancementcost current-cost subtype
                          advanceable rezzed strength current-strength title remotes selected hosted


Bootstrap gridize things a bit more

Bootstrap gridize things a bit more

Fixes inability to click deployment selection dropdown (need to make
the dropdown 100% width now.

--- src/cljs/onyx_dashboard/core.cljs
+++ src/cljs/onyx_dashboard/core.cljs
@@ -114,8 +114,7 @@
   (render-state [_ _] (dom/div (:input data)))
   (did-mount [_]
              (let [editor (.edit js/ace (om/get-node owner))]
-               (.setOptions editor
-                            (clj->js {:maxLines 15}))
+               (.setOptions editor (clj->js {:maxLines 15}))
                (.setMode (.getSession editor) "ace/mode/clojure")
                (.setHighlightActiveLine editor false)
                (.setHighlightGutterLine editor false)
@@ -124,18 +123,17 @@

 (defcomponent select-deployment [{:keys [deployments deployment]} owner]
   (render [_]
-          (dom/div
-            (b/toolbar {}
-                       (apply (partial b/dropdown {:bs-style "primary"
-                                                   :style {:width left-bar-width}
-                                                   :title (or (:id deployment) "Deployments")})
-                              (for [[id info] (reverse (sort-by (comp :created-at val)
-                                                                deployments))]
-                                (b/menu-item {:key id
-                                              :on-select (fn [_]
-                                                           ;(stop-tracking! id)
-                                                           (start-tracking! id))}
-                                             id)))))))
+          (b/toolbar {:style {:width "100%"}}
+                     (apply (partial b/dropdown {:bs-style "primary"
+                                                 :style {:width "100%"}
+                                                 :title (or (:id deployment) "Select Deployment")})
+                            (for [[id info] (reverse (sort-by (comp :created-at val)
+                                                              deployments))]
+                              (b/menu-item {:key id
+                                            :on-select (fn [_]
+                                                         ;(stop-tracking! id)
+                                                         (start-tracking! id))}
+                                           id))))))

 (defn is-job-entry? [job-id entry]
   (if-let [entry-job-id (if (= (:fn entry) :submit-job)
@@ -202,9 +200,10 @@
             (if-let [job (and selected-job jobs (jobs selected-job))]
               (dom/div
                (p/panel
-                {:header (om/build section-header {:text "Catalog"
-                                          :visible (:job visible)
-                                          :type :job} {})}
+                 {:header (om/build section-header
+                                    {:text "Catalog"
+                                     :visible (:job visible)
+                                     :type :job} {})}
                 (if (:job visible)
                   (om/build clojure-block {:input (:pretty-catalog job)})))

@@ -240,26 +239,27 @@
                           (recur)))))

   (render-state [_ {:keys [api-chan]}]
-                (dom/div
-                 (g/grid {}
-                         (r/page-header
-                          {}
-                          "Onyx Dashboard")
-                         (g/row
-                          {}
-                          (g/col
-                           {:xs 6 :md 4}
-                           (dom/aside {}
-                                      (dom/nav {:class "left-nav-deployment" :style {:width left-bar-width :position "fixed"}}
-                                               (om/build select-deployment app {})
-                                               (om/build job-selector deployment {}))))
-                          (g/col
-                           {:xs 12 :md 11 :md-push 1}
-                           (dom/div {:style {:margin-left left-bar-width}}
-                                    (om/build job-info {:deployment deployment
-                                                        :visible visible} {})
-                                    (om/build log-entries-table {:entries (deployment->latest-log-entries deployment)
-                                                                 :visible (:log-entries visible)} {}))))))))
+                #_(dom/div
+                  {:class "grids-examples"}
+                  (g/grid {}
+                          (g/row {:class "show-grid"}
+                                 (g/col {:xs 12 :md 8}
+                                        (dom/div {} "Who (g/col {:xs 12 :md 8})"))
+                                 (g/col {:xs 6 :md 4}
+                                        (dom/div {} "What (g/col {:xs 6 :md 4})")))))
+                (dom/div {:class "grids-examples"} ;(r/page-header {} "Onyx Dashboard")
+                         (g/grid {}
+                                 (g/row {}
+                                        (g/col {:xs 6 :md 4}
+                                               (dom/div {:class "left-nav-deployment"}
+                                                        (om/build select-deployment app {}))
+                                               (dom/div {}
+                                                        (om/build job-selector deployment {})))
+                                        (g/col {:xs 12 :md 8 :md-push 1 }
+                                               (dom/div (om/build job-info {:deployment deployment
+                                                                            :visible visible} {})
+                                                        (om/build log-entries-table {:entries (deployment->latest-log-entries deployment)
+                                                                                :visible (:log-entries visible)} {}))))))))

 (defn main []
   (om/root


Set default font size

Set default font size

--- src/clojure/nightcode/editors.clj
+++ src/clojure/nightcode/editors.clj
@@ -18,7 +18,7 @@
            [org.fife.ui.rtextarea RTextScrollPane SearchContext SearchEngine]))

 (def editors (atom (flatland/ordered-map)))
-(def font-size (atom (utils/read-pref :font-size)))
+(def font-size (atom (utils/read-pref :font-size 14)))
 (def paredit-enabled? (atom (utils/read-pref :enable-paredit true)))
 (def tabs (atom nil))


(SERVER-297) Remove duplicate entries at the head of $LOAD_PATH

Without this patch there are duplicate entries for the system ruby
library paths at the head of the $LOAD_PATH.  This behavior exists to
prevent accidentally loading libraries from the OS MRI copy of Ruby and
was necessary back when puppetserver loaded puppet code from the OS ruby
library paths.

This is no longer necessary as puppet code is isolated in PC1 and exists
outside of any Ruby library paths.  This patch addresses the problem by
removing the duplicate entries from the head of the LOAD_PATH restoring
the default behavior of JRuby.

--- src/clj/puppetlabs/services/jruby/jruby_puppet_internal.clj
+++ src/clj/puppetlabs/services/jruby/jruby_puppet_internal.clj
@@ -78,25 +78,17 @@

 (schema/defn ^:always-validate managed-load-path :- [schema/Str]
   "Return a list of ruby LOAD_PATH directories built from the
-  user-configurable ruby-load-path setting of the jruby-puppet configuration
-  section and prepending specific JRuby directories necessary for third party
-  extensions extensions.  See SERVER-297 and SERVER-538 for more info."
-  [ruby-load-path :- [schema/Str]
-   jruby-home :- schema/Str]
-  (->> ruby-load-path
-    (cons ruby-code-dir)
-    (cons (str jruby-home "/lib/ruby/1.9"))
-    (cons (str jruby-home "/lib/ruby/shared"))
-    (cons (str jruby-home "/lib/ruby/1.9/site_ruby"))))
+  user-configurable ruby-load-path setting of the jruby-puppet configuration."
+  [ruby-load-path :- [schema/Str]]
+  (cons ruby-code-dir ruby-load-path))

 (defn prep-scripting-container
   [scripting-container ruby-load-path gem-home]
-  (let [jruby-home (.getHomeDirectory scripting-container)]
-    (doto scripting-container
-      (.setLoadPaths (managed-load-path ruby-load-path jruby-home))
-      (.setCompatVersion (CompatVersion/RUBY1_9))
-      (.setCompileMode RubyInstanceConfig$CompileMode/OFF)
-      (.setEnvironment (managed-environment (get-system-env) gem-home)))))
+  (doto scripting-container
+    (.setLoadPaths (managed-load-path ruby-load-path))
+    (.setCompatVersion (CompatVersion/RUBY1_9))
+    (.setCompileMode RubyInstanceConfig$CompileMode/OFF)
+    (.setEnvironment (managed-environment (get-system-env) gem-home))))

 (defn empty-scripting-container
   "Creates a clean instance of `org.jruby.embed.ScriptingContainer` with no code loaded."
@@ -295,7 +287,6 @@
   use `create-scripting-container` instead of `new-main`."
   [config :- jruby-schemas/JRubyPuppetConfig]
   (let [jruby-config (RubyInstanceConfig.)
-        jruby-home   (.getJRubyHome jruby-config)
         {:keys [ruby-load-path gem-home]} config]
     (doto jruby-config
       (.setEnvironment (managed-environment (get-system-env) gem-home))


Expose trace details on d3-tree output

Expose trace details on d3-tree output

--- src/com/wsscode/pathom/trace.cljc
+++ src/com/wsscode/pathom/trace.cljc
@@ -111,7 +111,7 @@
                 x
                 (range count)))

-            (:com.wsscode.pathom.parser/async-return :com.wsscode.pathom.parser/skip-wait-key
+            (:com.wsscode.pathom.parser/async-return :com.wsscode.pathom.parser/skip-wait-key :com.wsscode.pathom.parser/call-read
               :com.wsscode.pathom.parser/skip-resolved-key :com.wsscode.pathom.parser/external-wait-key)
             (update-in x [:response ::children key ::details] (fnil conj []) (select-keys row [::event ::relative-timestamp]))

@@ -169,15 +169,15 @@
                         :keys  [key]}]
   (cond-> {:start    relative-timestamp
            :duration (or duration 0)
-           :details  (mapv (fn [{::keys                           [relative-timestamp duration event]
-                                 :com.wsscode.pathom.connect/keys [plan sym input-data]}]
-                             (cond-> {:event    (name event)
-                                      :duration (or duration 0)
-                                      :start    relative-timestamp}
-                               plan (assoc :plan plan)
-                               sym (assoc :sym sym)
-                               (= event :com.wsscode.pathom.connect/call-resolver)
-                               (assoc :input input-data))) details)}
+           :details  (mapv (fn [{::keys [relative-timestamp duration event]
+                                 :as    row}]
+                             (let [details (->> (dissoc row ::relative-timestamp ::timestamp ::duration ::event)
+                                                (into {} (map (fn [[k v]] [(keyword (name k)) v]))))]
+                               (merge {:event    (name event)
+                                       :duration (or duration 0)
+                                       :start    relative-timestamp}
+                                      details)))
+                       details)}
     key (assoc :name (str key))
     children (assoc :children
                     (into [] (map (comp compute-d3-tree second) children)))))


Return not found from trace plugin (actual results comes later from plugin)

--- src/com/wsscode/pathom/trace.cljc
+++ src/com/wsscode/pathom/trace.cljc
@@ -215,4 +215,4 @@
    :com.wsscode.pathom.connect/register
    [{:com.wsscode.pathom.connect/sym     `trace
      :com.wsscode.pathom.connect/output  [:com.wsscode.pathom/trace]
-     :com.wsscode.pathom.connect/resolve (fn [env _])}]})
+     :com.wsscode.pathom.connect/resolve (fn [env _] :com.wsscode.pathom.core/not-found)}]})


Add ability for admins to make user admin via card

--- src/braid/client/ui/views/pills.cljs
+++ src/braid/client/ui/views/pills.cljs
@@ -85,6 +85,7 @@
   (let [user (subscribe [:user user-id])
         open-group-id (subscribe [:open-group-id])
         admin? (subscribe [:user-is-group-admin? user-id] [open-group-id])
+        viewer-admin? (subscribe [:current-user-is-group-admin?] [open-group-id])
         user-status (subscribe [:user-status user-id])]
     (fn [user-id]
       [:div.card
@@ -106,7 +107,13 @@
        [:div.actions
         ; [:a.pm "PM"]
         ; [:a.mute "Mute"]
-        [search-button-view (str "@" (@user :nickname))]]])))
+        [search-button-view (str "@" (@user :nickname))]
+        (when (and @viewer-admin? (not @admin?))
+          ; TODO: make this not ugly
+          [:button.make-admin
+           {:on-click (fn [_] (dispatch [:make-admin {:group-id @open-group-id
+                                                      :user-id user-id}]))}
+           "Make Admin"])]])))

 (defn user-pill-view
   [user-id]


proofreading

proofreading

--- Clojure-Websockets/MainApp/src/cljs/birdwatch/ui/util.cljs
+++ Clojure-Websockets/MainApp/src/cljs/birdwatch/ui/util.cljs
@@ -29,7 +29,7 @@
   (str "" text ""))

 (defn- url-replacer
-  "Replace URL occurences in tweet texts with HTML (including links)."
+  "Replaces URL occurrences in tweet texts with HTML (including links)."
   [acc entity]
   (s/replace acc (:url entity) (a-blank (:url entity) (:display_url entity))))

@@ -48,7 +48,7 @@
     (s/replace acc f-screen-name (a-blank (str twitter-url screen-name) f-screen-name))))

 (defn- reducer
-  "Generic reducer, allows calling specified function for each item in provided collection."
+  "Generic reducer, allows calling specified function for each item in the collection."
   [text coll fun]
   (reduce fun text coll))

@@ -65,7 +65,7 @@
           (s/replace , "RT " "RT ")))))

 (defn entity-count
-  "Gets count of specified entity from either tweet, or, when exists, original (retweeted) tweet."
+  "Gets count of specified entity from either tweet or, if exists, original (retweeted) tweet."
   [tweet state k s]
   (let [rt-id (if (contains? tweet :retweeted_status)
                 (:id_str (:retweeted_status tweet))


No scheduling for dates before today, rather than times before now

--- src/get_here/core.clj
+++ src/get_here/core.clj
@@ -18,7 +18,7 @@
             [clj-time.coerce :as c]
             [clj-time.core :as t])
   (:import [java.util Date]
-           [java.time ZonedDateTime Instant ZoneId DayOfWeek]
+           [java.time ZonedDateTime Instant ZoneId LocalDate DayOfWeek]
            [java.time.temporal ChronoUnit]))

 (defn epoch-seconds->date [epoch-seconds]
@@ -108,6 +108,14 @@
                        (seconds->duration))}
      :route route}))

+(defn date-before-today? [date]
+  {:pre [(instance? java.util.Date date)]}
+  (.. date
+      (toInstant)
+      (atZone (ZoneId/of "America/New_York"))
+      (toLocalDate)
+      (isBefore (LocalDate/now (ZoneId/of "America/New_York")))))
+
 (defroutes routes
   (GET "/" []
     (response/resource-response "static/index.html"))
@@ -134,9 +142,7 @@
       {:status 400, :body {:code 1, :reason "Value provided for :arrive-by must be a Date."}}

       :else
-      (if (.. arrive-by
-              (toInstant)
-              (isBefore (Instant/now)))
+      (if (date-before-today? arrive-by)
         {:status 200, :body {:code 2 :reason "No route available"}}
         (let [{:keys [status body] :as response} @(google-transit-directions
                                                    "Pennsylvania Station, New York, NY"


Added to-map.

Added to-map.

--- src/clj/elephantdb/keyval/domain.clj
+++ src/clj/elephantdb/keyval/domain.clj
@@ -24,6 +24,13 @@
     (u/with-read-lock (.rwLock domain)
       (.get shard key))))

+(defn to-map
+  "Returns a persistent map containing all kv pairs in the supplied
+  domain."
+  [domain]
+  (into {} (for [^KeyValDocument doc (seq domain)]
+             [(.key doc) (.value doc)])))
+
 (defn index-keys
   "For the supplied domain and sequence of keys, returns a sequence of
   maps with the following keys:


add transactions/change-date

add transactions/change-date

--- src/cljc/clj_money/transactions.cljc
+++ src/cljc/clj_money/transactions.cljc
@@ -157,3 +157,9 @@
   (->> (dates/ranges start-date (dates/period interval-type interval-count))
        (take-while #(apply t/overlaps? start-date end-date %))
        (map #(summarize-period % items))))
+
+(defn change-date
+  [trx new-date]
+  (-> trx
+      (rename-keys {:transaction-date :original-transaction-date})
+      (assoc :transaction-date new-date)))


[REFACTOR] Correct indentation

[REFACTOR] Correct indentation

Signed-off-by: Pang Yan Han <22594c345857f664c61cd411f607c4d40a9d4af9@gmail.com>

--- src/cljs/cljs_nusmods/timetable.cljs
+++ src/cljs/cljs_nusmods/timetable.cljs
@@ -1489,7 +1489,7 @@

    NOTE: This function should only be called once."
   [urlHash]
-  (let [moduleUrlHashArray                (.split urlHash "&")
+  (let [moduleUrlHashArray (.split urlHash "&")

         ; for modules with lessons
         modWithLessonRegex
@@ -1526,8 +1526,7 @@
         moduleInfoFinal
         (get-module-info-from-url-hash-module-info modWithLessonExistent)

-        moduleCodes
-        (distinct (map #(:moduleCode %1) moduleInfoFinal))]
+        moduleCodes        (distinct (map #(:moduleCode %1) moduleInfoFinal))]

     (.log js/console (str "modWithLessonExistent = " (.stringify js/JSON (clj->js modWithLessonExistent))))
     (.log js/console (str "moduleInfoFinal = " (.stringify js/JSON (clj->js moduleInfoFinal))))


[REFACTOR] Use destructuring for hash

[REFACTOR] Use destructuring for hash

Signed-off-by: Pang Yan Han <22594c345857f664c61cd411f607c4d40a9d4af9@gmail.com>

--- src/cljs/cljs_nusmods/timetable.cljs
+++ src/cljs/cljs_nusmods/timetable.cljs
@@ -610,10 +610,10 @@
   (let [ttDay (timetable-get-day day)]
     (:rowIndex
       (reduce
-        (fn [result ttRow]
+        (fn [{:keys [foundFreeRow] :as result} ttRow]
           (cond
-            (:foundFreeRow result) result
-            (zero? (count ttRow))  (assoc result :foundFreeRow true)
+            foundFreeRow          result
+            (zero? (count ttRow)) (assoc result :foundFreeRow true)

             (empty?
               ; Find any existing lessons which overlap with our new lesson.


Submit is a button

Submit is a button

--- src/cljs/gc_api_browser/url_bar.cljs
+++ src/cljs/gc_api_browser/url_bar.cljs
@@ -8,10 +8,10 @@
             [gc-api-browser.dom-utils :refer [clearfix]]))

 (defn submit [cursor owner]
-  (dom/div #js {:className ""
-                :onClick   #(async/put! (om/get-state owner :submit-chan)
-                                        (select-keys cursor [:url :method :body :headers]))}
-           "Send"))
+  (dom/button #js {:className ""
+                   :onClick #(async/put! (om/get-state owner :submit-chan)
+                                         (select-keys cursor [:url :method :body :headers]))}
+              "Send"))

 (defn edit-url [{:keys [url] :as cursor}]
   (dom/div nil


fix display results

fix display results

--- src/clojure/zensols/cisql/export.clj
+++ src/clojure/zensols/cisql/export.clj
@@ -53,7 +53,7 @@
     (let [data (->> data
                     (map (fn [row]
                            (map #(get row %) header))))]
-     (dis/display-results data :columns header :title title))
+      (dis/display-results data :column-names header :title title))
     (print-table header data)))

 (defn export-query-to-function


deref recording atom before querying

deref recording atom before querying

--- src/com/billpiel/mem_tracer/core.clj
+++ src/com/billpiel/mem_tracer/core.clj
@@ -124,7 +124,7 @@

 (defmacro q
 "Queries the active trace recording."
- [& body] `(q/q (q/trace->zipper recording)
+ [& body] `(q/q (q/trace->zipper @recording)
                            ~@body))

 ;; === END Query functions


reorder funcs

reorder funcs

--- src/shelver/goodreads.clj
+++ src/shelver/goodreads.clj
@@ -11,17 +11,17 @@
   (get-shelves [this page])
   (get-shelf-books [this shelf]))

+(defn- api-helper [request-method url params]
+  (let [request-fn (case request-method
+                     :GET clj-http/get)]
+    (-> (request-fn url {:query-params params})
+        (#(assoc % :parsed (->> (:body %) java.io.StringReader. xml/parse))))))
+
 (defn- oauth-api-helper [oauth-client access-token request-method url params]
   (let [credentials (oauth/credentials oauth-client access-token request-method url params)
         request-fn (case request-method
                      :GET clj-http/get)]
     (-> (request-fn url {:query-params credentials})
-        (#(assoc % :parsed (->> (:body %) java.io.StringReader. xml/parse))))))
-
-(defn- api-helper [request-method url params]
-  (let [request-fn (case request-method
-                     :GET clj-http/get)]
-    (-> (request-fn url {:query-params params})
         (#(assoc % :parsed (->> (:body %) java.io.StringReader. xml/parse))))))

 (defn shelf-name [shelf]


Exercise 2.3

Exercise 2.3

--- src/sicp/chapter2/1_2.clj
+++ src/sicp/chapter2/1_2.clj
@@ -1,5 +1,6 @@
 (ns sicp.chapter2.1-2
-  (:require [sicp.chapter1.1-7 :refer [average]]
+  (:require [sicp.chapter1.1-6 :refer [abs]]
+            [sicp.chapter1.1-7 :refer [average]]
             [sicp.chapter1.2-5 :refer [gcd]]
             [sicp.common.list :refer :all]))

@@ -47,4 +48,26 @@
   (printf "(%s,%s)%n" (x-point p) (y-point p)))

 ;; Exercise 2.3
-;; TODO
+(defn make-rectangle [p1 p2]
+  (kons p1 p2))
+
+(defn width [rect]
+  (let [p1 (car rect)
+        p1-x (x-point p1)
+        p2 (cdr rect)
+        p2-x (x-point p2)]
+    (abs (- p2-x p1-x))))
+
+(defn height [rect]
+  (let [p1 (car rect)
+        p1-y (y-point p1)
+        p2 (cdr rect)
+        p2-y (y-point p2)]
+    (abs (- p2-y p1-y))))
+
+(defn perimeter [rect]
+  (+ (* 2 (width rect))
+     (* 2 (height rect))))
+
+(defn area [rect]
+  (* (width rect) (height rect)))


actually fix tests

actually fix tests

--- src/test/om_css/tests.clj
+++ src/test/om_css/tests.clj
@@ -311,7 +311,7 @@

 (defcomponent SimpleDefcomponent [props children]
   [:.inline {:display "inline"}]
-  (dom/div {:class :inline}))
+  (dom/div {:class :inline} "inline div"))

 (deftest test-om-css-cellophane
   (testing "cellophane & defui"


upsert test data in the past

upsert test data in the past

--- src/er_cassandra/model/util/test.clj
+++ src/er_cassandra/model/util/test.clj
@@ -91,7 +91,10 @@
   ([entity instance-stream]
    (upsert-instance-stream entity instance-stream {}))
   ([entity instance-stream opts]
-   @(m/upsert-buffered *model-session* entity instance-stream opts)))
+   @(m/upsert-buffered *model-session*
+                       entity
+                       instance-stream
+                       (ts/past-timestamp-opt opts))))

 (defn sync-consume-stream
   "synchronously consume a stream"


No need to use delay

No need to use delay

--- src/net/sekao/nightcode/projects.clj
+++ src/net/sekao/nightcode/projects.clj
@@ -100,9 +100,9 @@
       (getPath []
         path)
       (getPane [state-atom]
-        (let [pane (get-in @state-atom [:panes path] (delay (file-pane)))]
+        (let [pane (or (get-in @state-atom [:panes path]) (file-pane))]
           (swap! state-atom update :panes assoc path pane)
-          @pane)))))
+          pane)))))

 (defn home-node []
   (let [path "**Home**"
@@ -115,9 +115,9 @@
       (getPath []
         path)
       (getPane [state-atom]
-        (let [pane (get-in @state-atom [:panes path] (delay (home-pane)))]
+        (let [pane (or (get-in @state-atom [:panes path]) (home-pane))]
           (swap! state-atom update :panes assoc path pane)
-          @pane)))))
+          pane)))))

 (defn root-node [state]
   (let [project-files (->> (:project-set state)


Set bind addr.

Set bind addr.

--- src/onyx_benchmark/submit_linear.clj
+++ src/onyx_benchmark/submit_linear.clj
@@ -32,6 +32,10 @@
   (let [batch-size (Integer/parseInt batch-size)
         max-pending (Integer/parseInt max-pending)
         peer-config (read-string (slurp peer-config-file))
+        peer-config (merge
+                     {:onyx.messaging/bind-addr
+                      (slurp "http://169.254.169.254/latest/meta-data/local-ipv4")}
+                     peer-config)
         job-config (read-string (slurp job-config-file))
         catalog [{:onyx/name :in
                   :onyx/plugin :onyx.plugin.bench-plugin/generator


procfiles/altcrawl.clj: start work to call Ruby scrapers

--- src/org/altlaw/jobs/pre/altcrawl.clj
+++ src/org/altlaw/jobs/pre/altcrawl.clj
@@ -5,24 +5,91 @@
             [clojure.contrib.walk :as walk])
   (:use clojure.contrib.json.read
         org.altlaw.util.log)
-  (:import (org.apache.commons.codec.binary Base64)))
+  (:import (org.apache.commons.codec.binary Base64)
+           (javax.script ScriptContext ScriptEngine ScriptEngineManager)
+           (java.io StringReader)))

 (hadoop/setup-mapreduce)

-(declare *reporter*)
+(declare *reporter* *raw-input*)

 (defn counter [group name]
   (.incrCounter *reporter* group name 1))

-(def *docid-map* (ref {}))
+(def *ruby* nil)
+
+(def *ruby-context* nil)
+
+(def *docid-map* nil)

 (defn get-docid [uri]
-  (get @*docid-map* uri))
+  (get *docid-map* uri))

 (defn- decode-response-body [download]
   (assoc download :response_body_bytes
          (Base64/decodeBase64
           (.getBytes (:response_body_base64 download) "UTF-8"))))
+
+
+;; DIAGRAM OF CONTROL FLOW
+;;
+;; status-code-dispatch
+;;  |                |
+;;  |               warn
+;;  |
+;; mime-type-dispatch----------------------
+;;  |                   |                 |
+;;  |                   |                 |
+;; handle-html         handle-pdf        warn
+;;  |       |           |      |
+;;  |      warn         |     request Docid
+;;  |                   |
+;; scraper-dispatch    convert-pdf
+;;  |
+;; (for each case found)
+;;  |
+;;  |
+;; handle-scraped
+;;  |
+
+
+
+
+;; Step 3 (for HTML): Run scrapers
+
+(defn handle-scraped [record]
+  [101 (pr-str record)])
+
+(defn handle-scraper-output [output]
+  (filter identity
+          (map (fn [line]
+                 (when (seq (.trim line))
+                   (handle-scraped (read-json-string line))))
+               (.split output "\n"))))
+
+(defn run-scrapers [download]
+  (handle-scraper-output
+   (with-out-str
+     (.setWriter *ruby-context* *out*)
+     (.setReader *ruby-context* (StringReader. *raw-input*))
+     (.eval *ruby* "$runner.parse_all_from_stream($stdin)"))))
+
+
+;;; Step 4 (for PDFs): convert to HTML
+
+(defn convert-pdf [docid download]
+  (debug "converting PDF to HTML for " (:request_uri download)))
+
+;;; Step 3 (for PDFs): dispatch on presence of Docid
+
+(defn handle-pdf [download]
+  (if-let [docid (get-docid (:request_uri download))]
+    (do (debug "handle-pdf got docid " docid " for " (:request_uri download))
+        (counter "PDF files" "with docid")
+        (convert-pdf docid download))
+    (do (warn "handle-pdf found no docid for " (:request_uri download))
+        (counter "PDF files" "no docid"))))
+

 ;;; Step 2: dispatch on MIME type of the download

@@ -32,11 +99,13 @@

 (defmethod mime-type-dispatch "application/pdf" [download]
   (counter "MIME types" "PDF")
-  (debug "mime-type-dispatch got PDF from " (:request_uri download)))
+  (debug "mime-type-dispatch got PDF from " (:request_uri download))
+  (handle-pdf download))

 (defmethod mime-type-dispatch "text/html" [download]
   (counter "MIME types" "HTML")
-  (debug "mime-type-dispatch got HTML from " (:request_uri download)))
+  (debug "mime-type-dispatch got HTML from " (:request_uri download))
+  (run-scrapers download))

 (defmethod mime-type-dispatch :default [download]
   (counter "MIME types" "unknown")
@@ -61,20 +130,31 @@

 ;;; MAPPER METHODS

+(defn load-jruby []
+  (alter-var-root #'*ruby*
+                  (fn [_] (.getEngineByName (ScriptEngineManager.) "jruby")))
+  (alter-var-root #'*ruby-context*
+                  (fn [_] (.getContext *ruby*)))
+  (.eval *ruby* (str "require 'org/altlaw/extract/scrape/run_scraper'"))
+  (.eval *ruby* (str "$runner = RunScraper.new")))
+
 (defn mapper-configure [this job]
   (let [cached (DistributedCache/getLocalCacheFiles job)
         path (first (filter #(= (.getName %) "docids.tsv.gz") cached))]
     (when (nil? path) (throw (RuntimeException. "No docid.tsv.gz in DistributedCache.")))
     (info "Loading docid map from " path)
-    (dosync (ref-set *docid-map* (tsv/load-tsv-map (str path))))))
+    (alter-var-root #'*docid-map*
+                    (fn [_] (tsv/load-tsv-map (str path))))
+    (load-jruby)))

 (defn mapper-map [this wkey wvalue output reporter]
     (let [input (walk/keywordize-keys (read-json-string (str wvalue)))]
       (debug "Called map with file position " wkey
              " and value " (logstr input))
-      (binding [*reporter* reporter]
+      (binding [*reporter* reporter
+                *raw-input* (str wvalue)]
         (doseq [[key value] (my-map input)]
-          (.collect output (Text. key) (Text. value))))))
+          (.collect output (Text. (str key)) (Text. value))))))


(maint) use (atom {} :validator (fn [v]))

Here in order to further schema-check the state of a broker we
attach a validator function to the atoms used to track the :connections
and :uri-map.  If the validator raises or doesn't return truthy the
atom will not be updated.

--- src/puppetlabs/cthun/broker/core.clj
+++ src/puppetlabs/cthun/broker/core.clj
@@ -15,7 +15,7 @@
             [puppetlabs.puppetdb.mq :as mq]
             [schema.core :as s]
             [slingshot.slingshot :refer [throw+ try+]])
-  (:import (clojure.lang IFn)))
+  (:import (clojure.lang IFn Atom)))

 (def Connection
   "The state of a websocket in the connections map"
@@ -26,6 +26,14 @@
 (def Websocket
   "Schema for a websocket session"
   Object)
+
+(def UriMap
+  "Mapping of Uri to Websocket, for sending"
+  {message/Uri Websocket})
+
+(def Connections
+  "Mapping of Websocket session to Connection state"
+  {Websocket Connection})

 (def Broker
   {:activemq-broker    Object
@@ -33,11 +41,8 @@
    :record-client      IFn
    :find-clients       IFn
    :authorized         IFn
-   ;; TODO(richardc) watch for a solution for an atom containing a
-   ;; structure - https://github.com/Prismatic/schema/issues/186
-   ;; until then, s/Any it is.
-   :uri-map            s/Any #_(s/atom {message/Uri Websocket})
-   :connections        s/Any #_(s/atom {Websocket Connection})
+   :uri-map            Atom ;; atom with schema UriMap. will be checked with :validator
+   :connections        Atom ;; atom with schema Connections. will be checked with :validator
    :metrics-registry   Object
    :metrics            {s/Keyword Object}})

@@ -417,8 +422,8 @@
                               :authorized         authorized
                               :metrics            {}
                               :metrics-registry   (get-metrics-registry)
-                              :connections        (atom {})
-                              :uri-map            (atom {})}
+                              :connections        (atom {} :validator (partial s/validate Connections))
+                              :uri-map            (atom {} :validator (partial s/validate UriMap))}
           metrics            (build-and-register-metrics broker)
           broker             (assoc broker :metrics metrics)
           activemq-consumers (subscribe-to-queues broker accept-consumers delivery-consumers)


add jdbc

add jdbc

--- src/luffer/models.clj
+++ src/luffer/models.clj
@@ -12,7 +12,7 @@
                      ;:password (System/getenv "PG_PASSWORD")
                      ;:user (System/getenv "PG_USER")}))

-(defdb db (postgres {:connection-uri (System/getenv "PG_URL")}))
+(defdb db (postgres {:connection-uri (str "jdbc:" (System/getenv "PG_URL"))}))

 (declare plays users tracks shows tours venues api_clients)


fix ws out rate metric and remove ws latency metric

http-kit's send does not provide a way to measure output latency so
we should not send this metric. But we can measure the websocket
server out rate.

--- src/riemann/transport/websockets.clj
+++ src/riemann/transport/websockets.clj
@@ -47,7 +47,9 @@
                                  (when (pred event)
                                    ;; http-kit's send does not provide a way
                                    ;; to measure output latency
-                                   (http/send! ch (event-to-json event))))
+                                   (measure-latency
+                                    (:out stats)
+                                    (http/send! ch (event-to-json event)))))
                                true)]
       (info "New websocket subscription to" topic ":" query)

@@ -215,10 +217,6 @@

                          ; Latencies
                          (map (fn [[q latency]]
-                                {:service (str svc " out latency " q)
-                                 :metric latency})
-                              (:latencies out))
-                         (map (fn [[q latency]]
                                 {:service (str svc " in latency " q)
                                  :metric latency})
                               (:latencies in)))


fix websocket listening address

fix websocket listening address

--- src/riemann/transport/websockets.clj
+++ src/riemann/transport/websockets.clj
@@ -183,7 +183,7 @@
           (locking this
             (when-not @server
               (reset! server (http/run-server (ws-handler core stats)
-                                              {:host host
+                                              {:ip host
                                                :port port}))
               (info "Websockets server" host port "online"))))


exclude ensure

exclude ensure

--- src/main/clojure/cljs/env/macros.clj
+++ src/main/clojure/cljs/env/macros.clj
@@ -7,7 +7,7 @@
 ;   You must not remove this notice, or any other, from this software.

 (ns cljs.env.macros
-  (:refer-clojure :exclude [binding])
+  (:refer-clojure :exclude [binding ensure])
   (:require [cljs.core :refer [binding]]))

 (defmacro with-compiler-env


Create a DNA lexicon.

Create a DNA lexicon.

--- src/kolmogorov_music/kolmogorov.clj
+++ src/kolmogorov_music/kolmogorov.clj
@@ -37,10 +37,6 @@
   (random? (->> 66 char (repeat 14) (take 3))) => true)

-(def ascii
-  (->> (range 32 127)
-       (map char)))
-
 (defn kleene* [elements]
   (letfn [(expand [strings] (for [s strings e elements] (conj s e)))]
     (->>
@@ -48,14 +44,28 @@
       expand
       (cons []))))

-(defn lexicon []
-  (->> ascii
+(defn babel []
+  (let [ascii (->> (range 32 127) (map char))]
+    (->> ascii
+       kleene*
+       (map (partial apply str)))))
+
+(fact "We can construct all strings as a lazy sequence."
+  (->> (babel) (take 5)) => ["" " " "!" "\"" "#"]
+  (nth (babel) 364645) => "GEB")
+
+(defn dna []
+  (->> "GATC"
        kleene*
        (map (partial apply str))))

-(fact "We can construct all strings as a lazy sequence."
-  (->> (lexicon) (take 5)) => ["" " " "!" "\"" "#"]
-  (nth (lexicon) 364645) => "GEB")
+(fact "We can construct all genes as a lazy sequence."
+  (->> (dna) (take 5)) => ["" "G" "A" "T" "C"]
+  (nth (dna) 364645) => "GGGCTCGAGG")
+
+(fact "Lexicons aren't very random."
+  (randomness (take 1000 (babel))) => #(< % 1/100)
+  (randomness (take 1000 (dna))) => #(< % 1/100))

 (defn complexity
@@ -67,7 +77,7 @@
   "Calculate the shortest string that is more complicated than itself."
   []
   (let [its-own-source (repl/source-fn 'enterprise)]
-    (->> (lexicon)
+    (->> (babel)
          (drop-while (fn [s] (<= (complexity s) (value-length its-own-source))))
          first)))


Reallocate peers.

Reallocate peers.

--- src/onyx/scheduling/common_job_scheduler.clj
+++ src/onyx/scheduling/common_job_scheduler.clj
@@ -39,6 +39,57 @@
         active? (partial at-least-one-active? replica)]
     (every? identity (map #(active? (get-in replica [:allocations job %])) tasks))))

+(defn current-job-allocations [replica]
+  (into {}
+        (map (fn [j]
+               {j (apply + (map count (vals (get-in replica [:allocations j]))))})
+             (:jobs replica))))
+
+(defn current-task-allocations [replica]
+  (into
+   {}
+   (map (fn [j]
+          {j (into {} (map (fn [[t a]] {t (count a)}) (get-in replica [:allocations j])))})
+        (:jobs replica))))
+
+(defn job->task-claims [replica job-offers]
+  (reduce-kv
+   (fn [all j claim]
+     (assoc all j (cts/task-claim-n-peers replica j claim)))
+   {}
+   job-offers))
+
+(defn reallocate-peers [origin-replica displaced-peers max-utilization]
+  (loop [peer-pool displaced-peers
+         replica origin-replica]
+    (let [candidate-jobs (filter identity
+                                 (mapcat
+                                  (fn [job]
+                                    (let [current (get (current-task-allocations replica) job)
+                                          desired (cts/task-distribute-peer-count replica job (get max-utilization job))
+                                          tasks (get-in replica [:tasks job])]
+                                      (map
+                                       (fn [t]
+                                         (when (< (get current t) (get desired t))
+                                           [job t]))
+                                       tasks)))
+                                  (:jobs replica)))]
+      (if (and (seq peer-pool) (seq candidate-jobs))
+        (recur (rest peer-pool)
+               (update-in replica [:allocations
+                                   (ffirst candidate-jobs)
+                                   (second (first candidate-jobs))]
+                          conj (first peer-pool)))
+        replica))))
+
+(defn find-displaced-peers [replica max-util]
+  (mapcat
+   (fn [job]
+     (let [overflow (- (get current-allocations-c job) (get max-util job))]
+       (when (pos? overflow)
+         (cts/drop-peers replica job overflow))))
+   (:jobs replica)))
+
 (defmulti select-job
   (fn [{:keys [args]} replica]
     (:job-scheduler replica)))
@@ -206,14 +257,33 @@
 (def task-distribution-pt (cts/task-distribute-peer-count replica-pt :j2 (:j2 max-utilization-pt)))

-
-
-
-;; x - Function to map job id -> N peers
-;; x - Function to take the difference between capacity and usage
-;; x - Function to redisperse extra peers
-;; x - Function to map task id -> N peers
-;; - Function to figure out which peers go to which tasks and jobs
-;; - Function to update the replica
-;; - Function per peer to start or not start new task
-
+(def replica-c {:job-scheduler :onyx.job-scheduler/percentage
+                :jobs [:j1 :j2]
+                :tasks {:j1 [:t1 :t2 :t3]
+                        :j2 [:t4 :t5 :t6]}
+                :task-schedulers {:j1 :onyx.task-scheduler/balanced
+                                  :j2 :onyx.task-scheduler/balanced}
+                :saturation {:j1 3 :j2 Double/POSITIVE_INFINITY}
+                :peers [:p1 :p2 :p3 :p4 :p5 :p6 :p7 :p8 :p9 :p10]
+                :percentages {:j1 40 :j2 60}
+                :allocations {:j1 {:t1 [] :t2 [] :t3 []}
+                              :j2 {:t4 [:p1 :p2 :p3 :p4]
+                                   :t5 [:p5 :p6 :p7]
+                                   :t6 [:p8 :p9 :p10]}}})
+
+(def job-offers-c (job-offer-n-peers replica-c))
+
+(def job-claims-c (job->task-claims replica-c job-offers-c))
+
+(def spare-peers-c (apply + (vals (merge-with - job-offers-c job-claims-c))))
+
+(def max-utilization-c (claim-spare-peers replica-c job-claims-c spare-peers-c))
+
+(def task-distribution-c (cts/task-distribute-peer-count replica-c :j2 (:j2 max-utilization-c)))
+
+(def current-job-allocations-c (current-job-allocations replica-c))
+
+(def current-task-allocations-c (current-task-allocations replica-c))
+
+(def peers-to-displace (find-displaced-peers replica-c max-utilization-c))
+


calculate monthday and monthweek and use it in our pulse scheduling task.

--- src/metabase/task/send_pulses.clj
+++ src/metabase/task/send_pulses.clj
@@ -6,6 +6,7 @@
                                     [triggers :as triggers])
             [clojurewerkz.quartzite.schedule.cron :as cron]
             [clj-time.core :as time]
+            [clj-time.predicates :as timepr]
             [metabase.db :as db]
             [metabase.driver :as driver]
             [metabase.email :as email]
@@ -29,6 +30,22 @@
 (defonce ^:private send-pulses-job (atom nil))
 (defonce ^:private send-pulses-trigger (atom nil))

+(defn- monthday [dt]
+  (cond
+    (timepr/first-day-of-month? dt) :first
+    (timepr/last-day-of-month? dt)  :last
+    (= 15 (time/day dt))            :mid
+    :else                           :other))
+
+(defn- monthweek [dt]
+  (let [curr-day-of-month  (time/day dt)
+        last-of-month      (time/day (time/last-day-of-the-month dt))
+        start-of-last-week (- last-of-month 7)]
+    (cond
+      (> 8 curr-day-of-month)                  :first
+      (< start-of-last-week curr-day-of-month) :last
+      :else                                    :other)))
+
 ;; triggers the sending of all pulses which are scheduled to run in the current hour
 (jobs/defjob SendPulses
   [ctx]
@@ -40,8 +57,10 @@
         curr-hour          (time/hour now)
         curr-weekday       (->> (time/day-of-week now)
                                 (get pulse-channel/days-of-week)
-                                :id)]
-    (send-pulses curr-hour curr-weekday :other :other)))
+                                :id)
+        curr-monthday      (monthday now)
+        curr-monthweek     (monthweek now)]
+    (send-pulses curr-hour curr-weekday curr-monthday curr-monthweek)))

 (defn- task-init []
   ;; build our job


Fix embed-field

Fix embed-field

--- src/main/resources/sandbox-init.clj
+++ src/main/resources/sandbox-init.clj
@@ -19,7 +19,7 @@
   (defn delete-self [] (.set k9.sandbox/*delete-self* true))

   ;; Embed utilities
-  (defn embed-field [embed t d i] (.field embed (com.tterrag.k9.util.EmbedCreator$EmbedField. t d i)))
+  (defn embed-field [embed t d i] (.field embed t d i))

   (defn embed-create [title desc & fields]
     (let [builder (com.tterrag.k9.util.EmbedCreator/builder)]


Don't need to bind channel

Don't need to bind channel

--- src/musicbox/one.cljs
+++ src/musicbox/one.cljs
@@ -107,7 +107,7 @@

    (loop [instrument instrument]
      (draw draw-ctx instrument)
-     (let [[touch-data c] (alts! [c-touch-start c-touch-end])
+     (let [[touch-data _] (alts! [c-touch-start c-touch-end])
            touches (touch-data->touches touch-data)]

        (recur (update-size (reduce fire-event-on-instrument instrument touches)


Finally accomplished the first problem using clojure

--- hackerrank/functional_programming/clojure/reversing_list.clj
+++ hackerrank/functional_programming/clojure/reversing_list.clj
@@ -1,14 +1,13 @@
 #!/usr/local/bin env clj
 (def example (int 35231))
+(def example2 (int 1051986650))

-(defn digitize
-  ; Given a non-negative integer, return an array containing a list of independent digits in reverse order
-  [example]
-  (loop [x 1234]
-    (when (> x 0 )
-      (print (str (mod x 10) " "))
-      (recur (quot x 10)))))
-(println (digitize example) (str "Hello" ))
+(defn digitize [n]
+  (loop [results []
+         x n]
+    (let [results (conj results (mod x 10))]
+      (if (>= x 10)
+        (recur results (quot x 10))
+        results))))

-
-
+(println (digitize example))


adding some more default arg strings

adding some more default arg strings

--- src/overtone/sc/ugen/defaults.clj
+++ src/overtone/sc/ugen/defaults.clj
@@ -24,7 +24,15 @@
 (def NO-ARG-DOC-FOUND "-")

 (def DEFAULT-ARG-DOCS
-  {"bufnum" "The index of the buffer to use."})
+  {"bufnum" "A buffer or buffer index value."
+   "freq" "frequency in hz (cycles per second)"
+   "freq1" "frequency in hz (cycles per second)"
+   "freq2" "frequency in hz (cycles per second)"
+   "freq3" "frequency in hz (cycles per second)"
+   "phase" "the start point within a cycle"
+   "loop" "a boolean switch to turn on looping"
+   "in" "the input signal"
+   })

 (def DOC-WIDTH 60)


Fix resizing bug

Fix resizing bug

--- src/zaffre/glterminal.clj
+++ src/zaffre/glterminal.clj
@@ -16,7 +16,9 @@
     (java.nio FloatBuffer ByteBuffer)
     (java.nio.charset Charset)
     (org.lwjgl.opengl GL GLUtil GL11 GL12 GL13 GL14 GL15 GL20 GL30 GL32)
-    (org.lwjgl.glfw GLFW GLFWVidMode GLFWVidMode$Buffer GLFWImage GLFWImage$Buffer GLFWErrorCallback GLFWCharCallback GLFWKeyCallback GLFWMouseButtonCallback GLFWCursorPosCallback)
+    (org.lwjgl.glfw GLFW GLFWVidMode GLFWVidMode$Buffer GLFWImage GLFWImage$Buffer
+      GLFWErrorCallback GLFWCharCallback GLFWKeyCallback GLFWMouseButtonCallback
+      GLFWCursorPosCallback GLFWFramebufferSizeCallback)
     (org.lwjgl.system Platform)
     (org.joml Matrix4f Vector3f)
     (java.io File FileInputStream FileOutputStream)
@@ -1140,6 +1142,18 @@
                                              {:type :mouse-enter :col col :row row :group-id group-id})
                                            entered-locations)
                                       false))))
+        framebuffer-size-callback
+                              (proxy [GLFWFramebufferSizeCallback] []
+                                (invoke [window framebuffer-width framebuffer-height]
+                                  (let [^ByteBuffer bbnil nil]
+                                    (with-gl-context gl-lock window capabilities
+                                      (log/info "Changing size of fbo" fbo-texture)
+                                      (log/info "framebuffer size changed" screen-width screen-height framebuffer-width framebuffer-height)
+                                      (GL11/glBindTexture GL11/GL_TEXTURE_2D fbo-texture)
+                                      (GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 GL11/GL_RGB (int framebuffer-width) (int framebuffer-height) 0 GL11/GL_RGBA GL11/GL_UNSIGNED_BYTE bbnil)
+                                      (GL11/glBindTexture GL11/GL_TEXTURE_2D 0)
+                                      (reset! framebuffer-size [framebuffer-width framebuffer-height])))))
+
         gl                 {:p-matrix-buffer (ortho-matrix-buffer framebuffer-width framebuffer-height)
                             :mv-matrix-buffer (position-matrix-buffer [(- (/ framebuffer-width 2)) (- (/ framebuffer-height 2)) -1.0 0.0]
                                                                       [framebuffer-width framebuffer-height 1.0])
@@ -1227,6 +1241,7 @@
         (GLFW/glfwSetCharCallback window char-callback)
         (GLFW/glfwSetMouseButtonCallback window mouse-button-callback)
         (GLFW/glfwSetCursorPosCallback window cursor-pos-callback)
+        (GLFW/glfwSetFramebufferSizeCallback window framebuffer-size-callback)
         (future
           ;; Wait for main thread loop to start
           (.await latch)
@@ -1295,10 +1310,11 @@
                         (GLFW/glfwSetWindowSize window width height)
                         (GLFW/glfwSetWindowPos window (quot (- (.width primary-video-mode) screen-width) 2)
                                                       (quot (- (.height primary-video-mode) screen-height) 2))
-                        (let [[framebuffer-width framebuffer-height :as fb-size] (glfw-framebuffer-size window)
+                        #_(let [[framebuffer-width framebuffer-height :as fb-size] (glfw-framebuffer-size window)
                               ^ByteBuffer bbnil nil]
                           (reset! framebuffer-size fb-size)
                           (log/info "Changing size of fbo" fbo-texture)
+                          (log/info "window size changed" width height screen-width screen-height framebuffer-width framebuffer-height)
                           (GL11/glBindTexture GL11/GL_TEXTURE_2D fbo-texture)
                           (GL11/glTexImage2D GL11/GL_TEXTURE_2D 0 GL11/GL_RGB (int framebuffer-width) (int framebuffer-height) 0 GL11/GL_RGBA GL11/GL_UNSIGNED_BYTE bbnil)
                           (GL11/glBindTexture GL11/GL_TEXTURE_2D 0))))


(PDB-4807) noisy-future: be noisy about Throwables too

--- src/puppetlabs/puppetdb/utils.clj
+++ src/puppetlabs/puppetdb/utils.clj
@@ -441,7 +441,7 @@
   `(future
      (try
        ~@body
-       (catch Exception ex#
+       (catch Throwable ex#
          (binding [*out* *err*]
            (println ex#))
          (throw ex#)))))


security: fallback to default key if a specific host key is not found

This is convenient for tests since we can provide example configuration
that will work without modifications.

--- src/org/spootnik/fleet/security.clj
+++ src/org/spootnik/fleet/security.clj
@@ -22,7 +22,9 @@
                                  {:pem pem :path ca-priv})))]
     (reify AuthStore
       (verify [this host input sig]
-        (let [path (format "%s/%s.%s" certdir host suffix)
+        (let [candidate (format "%s/%s.%s" certdir host suffix)
+              path (if (.exists (io/file candidate)) candidate
+                       (format "%s/_default.%s" certdir suffix))
               pem (.readObject (PEMReader. (io/reader path)))
               public (cond
                       (instance? java.security.PublicKey pem)


bugfix: long was passed to pegdown instead of int

--- src/notehub/views.clj
+++ src/notehub/views.clj
@@ -12,7 +12,7 @@
 (def get-message (get-map "messages"))

 (def md-processor
-  (PegDownProcessor. (bit-and-not Extensions/ALL Extensions/HARDWRAPS)))
+  (PegDownProcessor. (int (bit-and-not Extensions/ALL Extensions/HARDWRAPS))))

 (defn md-to-html [md-text]
   (.markdownToHtml md-processor md-text))


Use record constructor fn instead of java constructor

--- src/rdf-common/grafter/rdf/io.clj
+++ src/rdf-common/grafter/rdf/io.clj
@@ -3,6 +3,7 @@
   any Linked Data format supported by Sesame."
   (:require [clojure.java.io :as io]
             [grafter.rdf.protocols :as pr]
+            [grafter.rdf.protocols :refer [->Quad]]
             [clojure.tools.logging :as log]
             [me.raynes.fs :as fs]
             [pantomime.media :as mime]
@@ -322,11 +323,11 @@
   ;; TODO fix this to work properly with object & context.
   ;; context should return either nil or a URI
   ;; object should be converted to a clojure type.
-  (Quad. (str (.getSubject st))
-         (str (.getPredicate st))
-         (sesame-rdf-type->type (.getObject st))
-         (when-let [graph (.getContext st)]
-           (sesame-rdf-type->type graph))))
+  (->Quad (str (.getSubject st))
+          (str (.getPredicate st))
+          (sesame-rdf-type->type (.getObject st))
+          (when-let [graph (.getContext st)]
+            (sesame-rdf-type->type graph))))

 (defn filename->rdf-format
   "Given a filename we attempt to return an appropriate RDFFormat


Add support for MS Windows newlines.  (Closes #177)

--- src/pamela/parser.clj
+++ src/pamela/parser.clj
@@ -109,7 +109,7 @@
 (defn build-parser [& [ebnf-filename]]
   (let [ebnf-filename (or ebnf-filename "pamela.ebnf")
         ebnf (slurp (resource (str "public/" ebnf-filename)))
-        whitespace (insta/parser "whitespace = #'([,\\s]+|;.*\\n)+'")
+        whitespace (insta/parser "whitespace = #'([,\\s]+|;.*\\s)+'")
         parser (insta/parser ebnf
                  :input-format :ebnf
                  :auto-whitespace whitespace)]


update help

update help

--- src/panpan/hestia.clj
+++ src/panpan/hestia.clj
@@ -74,7 +74,7 @@
     (fn [& _] "8256158"))) ; }}}

 (defn hestia-handler
-  "^(.+?)\\s*(を)?(開始|始める|はじめる) - toggl開始
+  "^(.+?)\\s*(を)?(開始|始め|はじめ)     - toggl開始
    ^(再開|さいかい)                     - toggl再開
    ^(終了|終わった|おわった|おわた)     - toggl停止
    ^(神様|神さま).*違(い|う)            - toggl削除


Add some more TXT records so autodiscovery works.

--- src/pepa/printing.clj
+++ src/pepa/printing.clj
@@ -1,8 +1,10 @@
 (ns pepa.printing
   (:require [com.stuartsierra.component :as component]
             [lpd.server :as lpd]
-            [lpd.protocol :as lpd-protocol])
-  (:import [javax.jmdns JmDNS ServiceInfo]))
+            [lpd.protocol :as lpd-protocol]
+            [pepa.log :as log])
+  (:import [javax.jmdns JmDNS ServiceInfo]
+           [java.net InetAddress]))

 (defn ^:private job-handler [config]
   (reify
@@ -16,33 +18,44 @@
                           :handler (job-handler config))))

 (defn ^:private service-info [config]
-  (ServiceInfo/create "_printer._tcp.local."
-                      "LPD Server"
-                      (:port config)
-                      10
-                      10
-                      {"pdl" "application/pdf,application/postscript"
-                       "rq" "some-queue"}))
+  (let [name "Pepa DMS Printer"]
+    (ServiceInfo/create "_printer._tcp.local."
+                        name
+                        (:port config)
+                        10
+                        10
+                        true
+                        {"pdl" "application/pdf,application/postscript"
+                         "rp" "documents"
+                         "txtvers" "1"
+                         "qtotal" "1"
+                         "ty" name})))

 (defrecord LPDPrinter [config mdns server]
   component/Lifecycle
-  (start [component]
+  (start [lpd]
     (let [lpd-config (get-in config [:printing :lpd])]
       (if (:enable lpd-config)
         (do
-          (println ";; Starting LPD Server")
+          (assert (< 0 (:port lpd-config) 65535))
+          (log/info lpd "Starting LPD Server")
           (let [server (-> (lpd-server lpd-config)
                            (lpd/start-server))
-                jmdns (JmDNS/create)]
+                ;; TODO: Use IP from config?
+                ip (InetAddress/getByName "moritz-x230")
+                jmdns (JmDNS/create ip nil)]
             (.registerService jmdns (service-info lpd-config))
-            (assoc component
+            (assoc lpd
                    :mdns jmdns
                    :server server)))
-        component)))
-  (stop [component]
-    (lpd/stop-server (:server component))
-    (.close (:mdns component))
-    (assoc component
+        lpd)))
+  (stop [lpd]
+    (log/info lpd "Stopping LPD Server")
+    (when-let [server (:server lpd)]
+      (lpd/stop-server server))
+    (when-let [mdns (:mdns lpd)]
+      (.close mdns))
+    (assoc lpd
            :mdns nil
            :server nil)))


Fix condition in init-port

Fix condition in init-port

--- src/pericles/gpio.clj
+++ src/pericles/gpio.clj
@@ -10,7 +10,9 @@
   (and (not (:debug? cfg)) (not (nil? @port))))

 (defn init-port
-  "Initializes GPIO port." [] (if (port-available?)
+  "Initializes GPIO port."
+  []
+  (if-not (:debug? cfg)
     (let [port-num (:gpio-port cfg)
           new-port {:num port-num
                     :port (gpio/open-port port-num :direction :out)}
@@ -22,7 +24,7 @@
 (defn destroy-port
   "Closes GPIO port."
   []
-  (if (port-available?)
+  (if-not (:debug? cfg)
     (when-let [old-port (reset! port nil)]
       (gpio/close! (:port old-port))
       (log/debugf "Closed GPIO port %d." (:num old-port)))))


Remove unnecessary require

Remove unnecessary require

--- src/play_clj/repl.clj
+++ src/play_clj/repl.clj
@@ -1,6 +1,5 @@
 (ns play-clj.repl
-  (:require [clojure.pprint :refer :all]
-            [play-clj.core :refer :all]))
+  (:require [play-clj.core :refer :all]))

 (defn entities
   "Returns the entities in `screen-object`, optionally filtered by a supplied


Execute the factory synchronously instead of async.

--- src/promesa/core.cljc
+++ src/promesa/core.cljc
@@ -191,10 +191,10 @@
        (let [p (CompletableFuture.)
              reject #(.completeExceptionally p %)
              resolve #(.complete p %)]
-         (submit #(try
-                    (func resolve reject)
-                    (catch Throwable e
-                      (reject e))))
+         (try
+           (func resolve reject)
+           (catch Throwable e
+             (reject e)))
          p))

      Throwable


commit @duckinator's minimum-unambiguous-path fn, per #16

--- src/pronouns/util.clj
+++ src/pronouns/util.clj
@@ -43,3 +43,13 @@
           acc2 (conj acc pair)]
       (if (empty? todo) (reverse acc2)
           (recur acc2 row next (rest todo))))))
+
+(defn minimum-unambiguous-path
+  ([pronouns-table sections] (minimum-unambiguous-path pronouns-table sections 1))
+  ([pronouns-table sections number-of-sections]
+    (let [sections-subset (take number-of-sections sections)
+          results (filter (fn [pronouns] (= (take number-of-sections pronouns) sections-subset)) pronouns-table)]
+      (case (count results)
+        0 nil
+        1 (clojure.string/join "/" sections-subset)
+        (recur pronouns-table sections (+ number-of-sections 1))))))


Fix many issues of image rendering on workspace.

--- src/uxbox/main/ui/shapes/image.cljs
+++ src/uxbox/main/ui/shapes/image.cljs
@@ -29,16 +29,17 @@

 (defn- will-mount
   [own]
-  (let [{:keys [image-id]} (first (:rum/args own))]
-    (rs/emit! (udi/fetch-image image-id))
+  (let [{:keys [image]} (first (:rum/args own))]
+    (println (:rum/args own))
+    (rs/emit! (udi/fetch-image image))
     own))

 (mx/defcs image-component
   {:mixins [mx/static mx/reactive]
    :will-mount will-mount}
-  [own {:keys [id image-id] :as shape}]
+  [own {:keys [id image] :as shape}]
   (let [selected (mx/react common/selected-ref)
-        image (mx/react (image-ref image-id))
+        image (mx/react (image-ref image))
         selected? (contains? selected id)
         local (:rum/local own)
         on-mouse-down #(common/on-mouse-down % shape selected)]
@@ -61,13 +62,3 @@
         attrs (-> (attrs/extract-style-attrs shape)
                   (merge props size))]
     [:image attrs]))
-
-;; --- Image SVG
-
-(mx/defc image-svg
-  {:mixins [mx/static]}
-  [{:keys [data id view-box] :as shape}]
-  (let [key (str "image-svg-" id)
-        view-box (apply str (interpose " " view-box))
-        props {:view-box view-box :id key :key key}]
-    [:svg props data]))


Use hash of config instead of connection in slack adapter

--- src/yetibot/core/adapters/slack.clj
+++ src/yetibot/core/adapters/slack.clj
@@ -38,7 +38,9 @@
   (-> @*conn* :start :self))

 (defn determine-config-from-chat-source-hash []
-    (get @hash-to-conn (:conn-hash *chat-source*)))
+  (log/info "*conn* not set; find using" *chat-source*)
+  (log/info (keys @hash-to-conn))
+  (get @hash-to-conn (:conn-hash *chat-source*)))

 (defn slack-config []
   ; if *config* is not bound, it's probably an API call, which will pass a :hash
@@ -55,7 +57,8 @@

 (def adapter :slack)

-(defn chat-source [channel] {:adapter adapter :room channel :conn-hash (hash *conn*)})
+(defn chat-source [channel] {:adapter adapter :room channel
+                             :conn-hash (hash *config*)})

 (defn send-msg [msg]
   (slack-chat/post-message (slack-config) *target* msg
@@ -232,7 +235,7 @@
                                           :manual_presence_change on-manual-presence-change
                                           :message on-message
                                           :hello on-hello))
-            (swap! hash-to-conn conj {(hash *conn*) *conn*})
+            (swap! hash-to-conn conj {(hash *config*) *conn*})
             (reset-users-from-conn)))
         configs))))