(ns mdr2.failjure
  (:require [failjure.core :as fail]))

(defrecord AnnotatedFailure [message data]
  fail/HasFailed
  (failed? [self] true)
  (message [self] (:message self)))

Add support for an annotated failure

Add support for an annotated failure

that contains extra data aside from the error message


;
; Chapter 1.1 - Notes
;

; defining a function
(defn square [x]
  (* x x))

; using the function as a building block in other functions
(defn sum-of-squares [x y]
  (+ (square x) (square y)))

; once again, using functions as building blocks
(defn f [x]
  (sum-of-squares (* x 2) (+ x 10)))

; expressing conditional with `cond`
(defn abs [x]
  (cond
    (> x 0) x
    (< x 0) (- x)
    (= x 0) 0))

; conditional with `cond` + `else`
(defn abs [x]
  (cond
    (< x 0) (- x)
    :else x))

; conditional with `if`
(defn abs [x]
  (if (< x 0)
    (- x)
    x))

; using logical `and`
(defn between [n x y]
  (and (> n x) (< n y)))

; using logical `or`
(defn gte [x y]
  (or (> x y) (= x y)))

; using `not`
(defn lte [x y]
  (not (> x y)))

;
; Chapter 1.1 - Exercises
;

; Ex 1.1:
; What are the results of each expression?

; 10

; (+ 5 3 4)

; (- 9 1)

; (/ 6 2)

; (+ (* 2 4) (- 4 6))

; (define a 3)
; (define b (+ a 1))
; (+ a b (* a b))

; (= a b)

; (if (and (> b a) (< b (* a b)))
;  b
;  a)

; (cond ((= a 4) 6)
;  ((= b 4) (+ 6 7 a))
;  (else 25))

; (+ 2 (if (> b a) b a))

; (* (cond ((> a b) a)
;  ((< a b) b)
;  (else -1))
;  (+ a 1))

; Ex 1.2:
; Translate the following expression into prefix form:
; (5 + 4 + (2 - (3 - (6 + 0.8)))) / (3 * (6 - 2) * (2 - 7))

; Ex 1.3:
; Define a procedure that takes three numbers as arguments
; and returns the sum of the squares of the two larger numbers.

Add initial SICP chapter 1 notes file

Add initial SICP chapter 1 notes file


(ns doctopus.doctopus.tentacle-test
  (:require [clojure.test :refer :all]
            [doctopus.doctopus.tentacle :refer :all]
            [me.raynes.fs :as fs]))

(def one-tentacle)

Add a tentacle test ns

Add a tentacle test ns


(ns main)

(defn main []
  (let [a (Integer/parseInt (read-line))
        b (Integer/parseInt (read-line))]
    (* a b)))

(println "PROD =" (main))

Solve Simple Product in clojure

Solve Simple Product in clojure


(ns circle.backend.action.rvm
  "actions for dealing with RVM during builds"
  (:require [circle.backend.action :as action])
  (:use [circle.backend.build :only (checkout-dir)])
  (:require [circle.sh :as sh])
  (:use [circle.backend.action.bash :only (remote-bash-build bash)]))

(defn trust []
  (action/action
   :name "rvm trust"
   :act-fn (fn [build]
             (let [dir (checkout-dir build)]
               (remote-bash-build build (sh/q (rvm rvmrc trust ~dir)))))))

Add missing file, RVM actions

Add missing file, RVM actions


(ns clara.rules.testfacts
  "This namespace exists primary for testing purposes, working around the fact that we cannot AOT compile test classes. This should be moved to the tests once a workaround for this is solved.")

;; Reflection against records requires them to be compiled AOT, so we temporarily
;; place them here as leiningen won't AOT compile test resources.
(defrecord Temperature [temperature location])
(defrecord WindSpeed [windspeed location])
(defrecord Cold [temperature])
(defrecord ColdAndWindy [temperature windspeed])
(defrecord LousyWeather [])

;; Test facts for chained rules.
(defrecord First [])
(defrecord Second [])
(defrecord Third [])
(defrecord Fourth [])

Add test facts to ClojureScript

Add test facts to ClojureScript


(ns parkour.toolbox-test
  (:require [clojure.test :refer :all]
            [clojure.string :as str]
            [clojure.java.io :as io]
            [clojure.core.reducers :as r]
            [parkour (conf :as conf) (fs :as fs) (cstep :as cstep)
             ,       (wrapper :as w) (mapreduce :as mr) (toolbox :as ptb)
             ,       (reducers :as pr) (graph :as pg)]
            [parkour.io (text :as text)]
            [parkour.util :refer [ignore-errors returning]]
            [parkour.test-helpers :as th])
  (:import [org.apache.hadoop.io Text NullWritable]
           [org.apache.hadoop.mapreduce Job Partitioner]))

(deftest test-by-p
  (th/with-config
    (let [job (mr/job), klass (mr/partitioner! job #'ptb/by-p #'pr/nth1)
          p ^Partitioner (w/new-instance job klass)
          np 10, modn #(mod % np), ->part #(.getPartition p % nil np)
          records (map #(-> [(gensym) %]) (range 100))]
      (is (= (->> records (group-by (comp modn pr/nth1)) vals set)
             (->> records (group-by ->part) vals set))))))

(deftest test-nth0-p
  (th/with-config
    (let [job (mr/job), klass (mr/partitioner! job #'ptb/nth0-p)
          p ^Partitioner (w/new-instance job klass)
          np 10, modn #(mod % np), ->part #(.getPartition p % nil np)
          records (map #(-> [% (gensym)]) (range 100))]
      (is (= (->> records (group-by (comp modn pr/nth0)) vals set)
             (->> records (group-by ->part) vals set))))))

(defn words-m
  {::mr/sink-as :keys}
  [coll] (r/mapcat #(str/split % #"\s+") coll))

(deftest test-identity-t
  (th/with-config
    (is (= #{"apple" "banana" "carrot"}
           (-> (pg/input (text/dseq (io/resource "word-count-input.txt")))
               (pg/map #'words-m)
               (pg/partition [Text NullWritable])
               (pg/combine #'ptb/identity-t :keygroups :keys)
               (pg/output (text/dsink))
               (pg/fexecute (conf/ig) `test-identity-t)
               (->> (into #{})))))))

Add tests for parkour.toolbox functions.


(ns storemi.js
  (:require
    [clj-rhino :as js]
    [clojure.walk :refer [keywordize-keys]]))

(def parser-scope
  (doto (js/new-safe-scope)
    (js/eval (slurp "resources/public/js/underscore-min.js"))
    (js/eval (slurp "resources/public/js/parser.js"))))

(defn parse-script [script]
  (let [sc (js/new-scope nil parser-scope)]
    (js/set! sc "script" script)
    (-> (js/eval sc "parseScript(script)")
        js/from-js)))

(def react-scope
  (let [scripts ["resources/public/js/underscore-min.js"
                 "resources/public/js/react.min.js"
                 "resources/public/js/parser.js"
                 "resources/public/js/react/story-ui.react.js"]
        scope (js/new-scope)]
    (js/eval scope "var global = this")
    (doseq [s scripts]
      (js/eval scope (slurp s)))
    scope))

(defn render-story-component [data]
  (let [sc (js/new-scope nil react-scope)]
    (js/set! sc "data" (js/to-js data sc))
    (-> (js/eval sc "React.renderComponentToString(Story({data: data}))")
        )))

Add file that interfaces with javascript files


global
    daemon
    maxconn 256

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

frontend http
    bind *:9999
    <% (doseq [[{name :name regex :regex}] services]
      %>acl <%= name %>-regex path_reg <%= regex %>
    use_backend <%= name %>-backends if <%= name %>-regex
    <%) %> <% (doseq [[{name :name} outs] services]
        %>
backend <%= name %>-backends
    balance roundrobin
    <% (doseq [[idx out] (map-indexed vector outs)]
        %>server <%= (str name "-" idx) %> <%= out %> maxconn 32
    <%
       )
%><%) %>

Add template for routing / load balancing


(ns scrape-trs.summitpost.core
  (:require [scrape-trs.summitpost
             [extract-pager-urls :refer [extract-all-pager-urls]]
             [extract-result-urls :refer [extract-result-urls]]
             [extract-trip-report :refer [extract-trip-report]]])
  (:import scrape_trs.protocol.ScrapeTripReport))

(def base-url "http://www.summitpost.org")

(deftype SPScrapeTripReport []

  ScrapeTripReport

  (extract-pager-urls
    [this list-page]
    (extract-all-pager-urls base-url list-page))

  (extract-trip-report-urls
    [this list-page]
    (extract-result-urls base-url list-page))

  (extract-trip-report
    [this trip-report-url trip-report-page]
    (extract-trip-report trip-report-url trip-report-page)))

Add SPScrapeTripReport which implements ScrapeTripReport protocol.


;; https://github.com/technomancy/leiningen/issues/747#issuecomment-8024136
(swap! leiningen.core.project/default-profiles
       update-in [:base] assoc :repositories
       [["clojars" {:url "https://clojars.org/repo/"}]])

Prepare a workaround for the Leiningen 2 Preview 9 provisioning issue


(ns migrations.053-remove-provider-services-tables
  (:require [clojure.java.jdbc :as j]
            [config.migrate-config :as config]
            [config.mdb-migrate-helper :as h]
            [cmr.metadata-db.data.oracle.concept-tables :as ct]))

(defn up
  "Migrates the database up to version 53."
  []
  (println "migrations.053-remove-provider-services-tables up...")
  (doseq [provider (h/get-regular-providers)
          :let [t (ct/get-table-name provider :service)
                sequence-name (str t "_seq")]]
    (h/sql (format "drop table %s" t))
    (h/sql (format "drop sequence %s" sequence-name)))
  (h/sql "drop table small_prov_services")
  (h/sql "drop sequence small_prov_services_seq"))

(def create-service-sql
  "CREATE TABLE small_prov_services (
    id NUMBER,
    concept_id VARCHAR(255) NOT NULL,
    native_id VARCHAR(1030) NOT NULL,
    metadata BLOB NOT NULL,
    format VARCHAR(255) NOT NULL,
    revision_id INTEGER DEFAULT 1 NOT NULL,
    revision_date TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP NOT NULL,
    deleted INTEGER DEFAULT 0 NOT NULL,
    entry_id VARCHAR(255) NOT NULL,
    entry_title VARCHAR(1030) NOT NULL,
    delete_time TIMESTAMP WITH TIME ZONE,
    user_id VARCHAR(30) NULL,
    provider_id VARCHAR(255) NOT NULL,
    CONSTRAINT small_prov_services_pk PRIMARY KEY (id),
    CONSTRAINT small_prov_services_con_rev
      UNIQUE (provider_id, native_id, revision_id)
      USING INDEX (create unique index small_prov_services_ucr_i
                          ON small_prov_services(provider_id, native_id, revision_id)),
    CONSTRAINT small_prov_services_cid_rev
      UNIQUE (concept_id, revision_id)
      USING INDEX (create unique index small_prov_services_cri
                          ON small_prov_services(concept_id, revision_id)))")

(defn down
  "Migrates the database down from version 53."
  []
  (println "migrations.053-remove-provider-services-tables down...")
  (doseq [provider (h/get-regular-providers)]
    (ct/create-concept-table (config/db) provider :service)
    (ct/create-concept-table-id-sequence (config/db) provider :service))
  (h/sql create-service-sql)
  (h/sql "CREATE SEQUENCE small_prov_services_seq"))

CMR-4176: Add migration to remove provider specific services tables and sequences.


;; Copyright (c) 2013-2015 Andrey Antukh <niwi@niwi.be>
;;
;; Licensed under the Apache License, Version 2.0 (the "License")
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;;     http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.

(ns buddy.core.mac.proto
  "Hash-based Message Authentication Codes
  low level protocol definition.")

(defprotocol IMac
  (^:private update [_ bytes offset length] "Update bytes in a current instance.")
  (^:private end [_] "Return the computed mac and reset the engine."))

(defn update!
  ([engine input]
   (update engine input 0 (count input)))
  ([engine input offset]
   (update engine input offset (count input)))
  ([engine input offset length]
   (update engine input offset length)))

(defn end!
  [engine]
  (end engine))

Add generic mac engine abstraction for low level but clojure idiomatic access to mac.


(ns discuss.lib.views
  (:require [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]))

(defn fa-icon
  "Wrapper for font-awesome icons."
  ([class]
   (dom/i #js {:className (str "fa " class)}))
  ([class f]
   (dom/i #js {:className (str "pointer fa " class)
               :onClick   f})))

(defn logo
  "If no function is provided, show logo as is. Else bind function to onClick-event and add
   pointer-class."
  ([]
   (fa-icon "fa-comments"))
  ([f]
   (fa-icon "fa-comments" f)))

(defn safe-html
  "Creates DOM element with interpreted HTML."
  [string]
  (dom/span #js {:dangerouslySetInnerHTML #js {:__html string}}))

(defn commit-target-value
  "Set local state of view, parse the value of the target of val."
  [key val owner]
  (om/set-state! owner key (.. val -target -value)))

(defn display
  "Toggle display view."
  [show]
  (if show
    #js {}
    #js {:display "none"}))

(defn toggle-show [show] (if show false true))

Create separate namespace for multiple libs


(ns berry.converters.to-member
  (:require [berry.formatting :refer [indent]]))

(declare colon transform-name)

(defn to-member
  [[name value] options to-json]
  (let [{prettify? :prettify?} options
        name (transform-name name options)
        value (to-json value options to-json)]
    (str name
         (colon prettify?)
         value)))

(defn- colon
  [prettify?]
  (if prettify?
    " : "
    ":"))

(defn- transform-name
  [name options]
  (let [{prettify? :prettify?} options]
    (if prettify?
      (indent name options)
      name)))

Add function for transforming a seq with a name and a value into a JSON member


; Copyright © 2015, JUXT LTD.

(ns yada.walk
  (:require
   [clojure.walk :refer [postwalk]])
  (:import [yada.handler Handler]
           [yada.resource Resource]))

;; Functions to update inner routes

(defn update-routes [routes f & args]
  (postwalk
   (fn [x]
     (if (or
          (instance? Handler x)
          (instance? Resource x))
       (apply f x args)
       x))
   routes))

(defn merge-options [m routes]
  (update-routes routes
                 (fn [{:keys [handler args]}]
                   (merge handler m))))

(defn basic-auth [realm auth-fn routes]
  (merge-options
   {:security {:type :basic :realm realm}
    :authorization auth-fn}
   routes))

; Copyright © 2015, JUXT LTD.

(ns yada.walk
  (:require
   [clojure.walk :refer [postwalk]])
  (:import [yada.handler Handler]
           [yada.resource Resource]))

;; Functions to update inner routes

(defn update-routes [routes f & args]
  (postwalk
   (fn [x]
     (if (or
          (instance? Handler x)
          (instance? Resource x))
       (apply f x args)
       x))
   routes))

(defn merge-options [m routes]
  (update-routes routes
                 (fn [{:keys [handler args]}]
                   (merge handler m))))

#_(defn basic-auth [routes realm authn-fn authorization ]
  (merge-options
   {:access-control
    {realm {:authentication-schemes
            [{:scheme "Basic"
              :verify authn-fn}]
            :authorization {:methods {:get "secret/view"}}}}}
   routes))

Comment out basic auth - no need for fn here


(ns test-deploy
  (:use [leiningen.deploy] :reload)
  (:use [clojure.test]
        [clojure.java.io :only [file]]
        [leiningen.core :only [read-project defproject]]
        [leiningen.util.file]))

(def test-project (read-project "test_projects/sample/project.clj"))

(deftest test-deploy
  (delete-file-recursively "/tmp/lein-repo" :silently)
  (deploy test-project "file:///tmp/lein-repo")
  (let [dir (file "/tmp/lein-repo/nomnomnom/nomnomnom/0.5.0-SNAPSHOT/")
        files (.list dir)
        year (+ 1900 (.getYear (java.util.Date.)))]
    (is (seq files))
    ;; TODO: this is vulnerable to the y3k bug!
    (is (seq (filter #(re-find #"nomnomnom-0.5.0-2\d{7}\." %) files)))))

Add test for deploy task.

Add test for deploy task.


{:nodes
 {:ph2
  {:name "tnseq-phase2b",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:ph2 [:prn1]}}

Add ability to run aggregation separate from std phase-2 run


(ns desdemona.ui.core-test
  (:require
   [desdemona.ui.core :as c]
   [cljs.test :as t :refer-macros [deftest testing is are]]))

(deftest add-tests
  (is (= (c/add 1 2) 3)))

Add a stupid ideally-failing core test

Add a stupid ideally-failing core test


{:user {:ultra {:color-scheme :solarized_dark
                :stacktraces  true}
        :plugins [[lein-try "0.4.3"]
                  [lein-ancient "0.6.10-SNAPSHOT"]
                  [lein-kibit "0.1.2"]
                  [jonase/eastwood "0.2.3"]
                  ;[venantius/ultra "0.5.0"]
                 ]}}

Add lein file in clojure config folder

Add lein file in clojure config folder


(ns org.playasophy.wonderdome.input.gamepad-test
  (:require
    [clojure.core.async :as async :refer [<!]]
    [clojure.test :refer :all]
    [com.stuartsierra.component :as component]
    [org.playasophy.wonderdome.input.gamepad :as gamepad]))

(defn gamepad-test
  "Creates and starts a gamepad input component attached to a channel and reader
  which will print events received to the console."
  []
  (let [channel (async/chan (async/dropping-buffer 5))
        input (gamepad/snes channel)]
    (async/go-loop []
      (prn (<! channel))
      (recur))
    (component/start input)))

Add testing harness function to gamepad-test ns.


(disable-warning
 {:linter :suspicious-expression
  ;; specifically, those detected in function suspicious-macro-invocations
  :if-inside-macroexpansion-of #{'defun.core/defun}
  :within-depth 12
  :reason "defun creates calls to and with only 1 argument."})

Add missing Eastwood config file.

Add missing Eastwood config file.


(ns audio-utils.triggered-chunker
  (:require [audio-utils.util :refer [aatom aswap! << >>]]
            [audio-utils.worker :as w]))

(defprotocol ITriggeredChunker
  (process-samples [this samples])
  (deliver-chunks [this])
  (reset-chunks [this])
  (trigger [this capture?]))

(defrecord TriggeredChunker [next chunks capturing?]
  w/IWorkerAudioNode
  (connect [this destination]
    (reset! next destination))

  (disconnect [this]
    (reset! next nil))

  (process-audio [this data]
    (when (<< capturing?)
      (js/console.log "TRIGGERED CHUNKER: PROCESS AUDIO"
                      data
                      (<< capturing?))
      (let [n-channels (count data)
            n-samples  (count (first data))]
        (dotimes [n n-samples]
          (let [samples (mapv #(nth % n) data)]
            (process-samples this samples))))))

  ITriggeredChunker
  (process-samples [this samples]
    (dotimes [channel (count samples)]
      (let [sample (samples channel)]
        (aswap! chunks update channel conj sample))))

  (deliver-chunks [this]
    (some-> @next (w/process-audio (<< chunks))))

  (reset-chunks [this]
    (let [n-channels   (count (<< chunks))
          empty-chunks (into [] (repeat n-channels []))]
      (>> chunks empty-chunks)))

  (trigger [this capture?]
    (js/console.log "TRIGGERED CHUNKER: TRIGGER: capture?" capture?)
    (when-not capture?
      (deliver-chunks this)
      (reset-chunks this))
    (>> capturing? capture?)))

(defn triggered-chunker
  []
  (map->TriggeredChunker {:next       (atom nil)
                          :chunks     (aatom [])
                          :capturing? (aatom false)}))

Add an audio chunker that yields chunks whenever it is triggered


(ns clojure-walkthrough.cjia.ch09-xx
  (:import [java.text SimpleDateFormat]))

(defn new-expense [date-string dollars cents category merchant-name]
  {:date (.parse (SimpleDateFormat. "yyyy-MM-dd") date-string)
   :amount-dollars dollars
   :amount-cents cents
   :category category
   :merchant-name merchant-name})

(defn total-cents [e]
  (-> (:amount-dollars e)
      (* 10)
      (+ (:amount-cents e))))

;; Adding some functions
(defn total-amount
  ([expenses-list]
   (total-amount (constantly true) expenses-list))
  ([pred expenses-list]
   (->> expenses-list
        (filter pred)
        (map total-cents)
        (apply +))))

(defn is-category? [e some-category]
  (= (:category e) some-category))

(defn category-is [category]
  #(is-category? % category))

;; Let's test it in the new namespaces
(ns clojure-walkthrough.cjia.ch09-xx-test
  (:require [clojure-walkthrough.cjia.ch09-xx :refer :all]
            [clojure.test :refer :all]))

;; (defn clj-expenses [(new-expense "2009-8-20" 21 95 "books" "Amazon.com")
;;                     (new-expense "2009-8-21" 72 43 "food"  "Mollie-Stones")
;;                     (new-expense "2009-8-22" 315 71 "car-rental" "Avis")
;;                     (new-expense "2009-8-23" 15 68  "books" "Borders")])

Add first example from chapter 9

Add first example from chapter 9


(ns audio-utils.mp3-encoder
  (:require [cljsjs.lamejs]
            [audio-utils.worker :as w]))

(defrecord MP3Encoder [bit-rate sample-rate next]
  w/IWorkerAudioNode
  (connect [this destination]
    (reset! next destination))

  (disconnect [this]
    (reset! next nil))

  (process-audio [this data]
    (let [int-data (mapv (fn [samples]
                           (into-array (map #(* 32768 %) samples)))
                         data)
          encoder  (js/lamejs.Mp3Encoder. 2 sample-rate bit-rate)
          encoded  #js []]
      (doto encoded
        (.push (apply (aget encoder "encodeBuffer") int-data))
        (.push (.flush encoder)))
      (some-> @next (w/process-audio encoded)))))

(defn mp3-encoder
  [{:keys [bit-rate
           sample-rate]
    :or   {bit-rate    128
           sample-rate 44100}}]
  (map->MP3Encoder {:bit-rate    bit-rate
                    :sample-rate sample-rate
                    :next        (atom nil)}))

Add MP3 encoder implementation for worker audio pipelines

An important part of this is to translate float sample vectors to
integer arrays for encoding since that's what lamejs expects as its
input.


(ns clj-gatling.simulation-test
  (:use clojure.test)
  (:require [clj-gatling.simulation :as simulation]))

(defn run-request [id] "OK")

(def scenario
  {:name "Test scenario"
   :requests [{:name "Request1" :fn run-request}
              {:name "Request2" :fn run-request}]})

(defn get-result [requests request-name]
  (:result (first (filter #(= request-name (:name %)) requests))))

(deftest simulation-returns-result-when-run-with-one-user
  (let [result (first (simulation/run-simulation scenario 1))]
    (is (= "Test scenario" (:name result)))
    (is (= "OK" (get-result (:requests result) "Request1")))
    (is (= "OK" (get-result (:requests result) "Request2")))))

Add simple test for simulation run

Add simple test for simulation run


(ns overtone.examples.instruments.pitch-controller
  (:use overtone.live))

;; Fire off this synth and connect an instrument/mic.
;; The pitch will be detected and used to control the saw waves

(defsynth pitch-controlled-saws
  [out-bus 0]
  (let [p   (pitch (sound-in) )
        p   (/ p 4)
        p   (lag p 1)]
    (out out-bus (saw [p (+ p (* p 0.01))]))))

;;(pitch-controlled-saws)
;;(stop)

Add simple mic/input pitch-controlled synth example


(ns clojuredocs.main
  (:require [ring.adapter.jetty :as jetty]
            [aleph.http :as ah]
            [clojuredocs.env :as env]
            [clojuredocs.entry :as entry]
            [somnium.congomongo :as mon]))

(mon/set-connection!
  (mon/make-connection (env/str :mongo-url)))

(mon/add-index! :examples [:ns :name :library-url])
(mon/add-index! :vars [:ns :name :library-url])

(defn start-http-server [entry-point opts]
  (ah/start-http-server
    (ah/wrap-ring-handler
      (fn [r]
        (let [resp (entry-point r)]
          (if (:status resp)
            resp
            (assoc resp :status 200)))))
    opts))

(defn -main []
  (let [port (env/int :port 8080)]
    (start-http-server
      (var entry/routes)
      {:port port :join? false})
    (println (format "Server running on port %d" port))))

(ns clojuredocs.main
  (:require [ring.adapter.jetty :as jetty]
            [aleph.http :as ah]
            [somnium.congomongo :as mon]
            [clojuredocs.env :as env]
            [clojuredocs.entry :as entry]
            [clojuredocs.config :as config]))

(mon/set-connection!
  (mon/make-connection (env/str :mongo-url)))

(mon/add-index! :examples [:ns :name :library-url])
(mon/add-index! :vars [:ns :name :library-url])

(defn start-http-server [entry-point opts]
  (ah/start-http-server
    (ah/wrap-ring-handler
      (fn [r]
        (let [resp (entry-point r)]
          (if (:status resp)
            resp
            (assoc resp :status 200)))))
    opts))

(defn valid-env-or-exit []
  (let [res (->> [(env/int :port)                  "Port missing"
                  (:client-id config/gh-creds)     "GH client ID missing"
                  (:client-secret config/gh-creds) "GH client secret missing"
                  config/base-url                  "base url missing"]
                 (partition 2)
                 (map #(when (nil? (first %))
                         (println " !" (second %))
                         true))
                 (reduce #(or %1 %2)))]
    (when res
      (println)
      (println " ! Missing required config vars, exiting.")
      (println)
      #_(System/exit 1))))

(defn -main []
  (valid-env-or-exit)
  (let [port (env/int :port 8080)]
    (start-http-server
      (var entry/routes)
      {:port port :join? false})
    (println (format "Server running on port %d" port))))

Exit if all config vars not found

Exit if all config vars not found


{
 :name "tnseq-phase1",
 :path  "",

 :graph {:bt1 {:type "tool"
               :path "bowtie2"
               :args ["-p" "16" "--very-sensitive" "-x" "#1" "-U" "#2"]
               }
         :bt2 {:type "tool"
               :path "bowtie2"
               :args ["-f" "-N" "1" "--reorder"
                      "--no-unal" "--no-head"
                      "-p" "8"
                      "-x" "#1" "-U" "#3"]
               }
         :mmap {:type "func"
                :name "make-maps"
                :args ["#4"]}
         :st1 {:type :tool
               :path "samtools"
               :args ["view" "-b"]}
         :st2 {:type :tool
               :path "samtools"
               :args ["sort" "--threads" "8"]}
         :st3 {:type :tool
               :path "samtools"
               :args ["index" "-" "#6"]}
         :cl1 {:type "func"
               :name "write-bam"
               :args ["#5"]}
         :edges {:bt2 [:mmap]
                 :bt1 [:st1] :st1 [:st2] :st2 [:cl1 :st3]}}

 ;; instructional data used in /help
 :description "Process collapsed fastas from bowtie alignment, to bam conversion and map file making, to bam sort, to bam indexing, to bam write - all via streaming connections."
 }

Add support for Aerobio map file generation from streaming SAM


(ns circle.backend.aws-iam
  "fns for working with AWS Identity & Access Management"
  (:use [circle.aws-credentials :only (aws-credentials)])
  (:import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient
           com.amazonaws.services.identitymanagement.model.UploadServerCertificateRequest
           com.amazonaws.services.identitymanagement.model.GetServerCertificateRequest))

(defmacro with-iam-client
  [client & body]
  `(let [~client (AmazonIdentityManagementClient. aws-credentials)]
     ~@body))

(defn upload-certificate
  "Uploads an SSL certificate. cert is the certificate public key, it
  begins with ---BEGIN CERTIFICATE---. priv key begins with --BEGIN
  RSA PRIVATE KEY--- "
  [{:keys [name certificate private-key]}]
  (with-iam-client client
    (let [result (.uploadServerCertificate client (UploadServerCertificateRequest. name certificate private-key))]
      (.getServerCertificateMetadata result))))

(defn get-certificate [name]
  (with-iam-client client
    (-> client (.getServerCertificate (GetServerCertificateRequest. name)) (.getServerCertificate) (bean) (update-in [:serverCertificateMetadata] bean))))

Add missing file that should have been committed months ago. Adds fns for uploading SSL certificates to AWS, useful for creating SSL load balancers at the repl


(ns org.spootnik.cyanite.path
  "Implements a path store which tracks metric names. The
   default implementation provides lucene based implementations"
  (:require [clucy.core                  :as search]
            [clojure.tools.logging       :refer [error info debug]]))

(defprotocol Pathstore
  "The pathstore provides a way to insert paths and later look them up"
  (register [this tenant path])
  (search [this tenant path]))

(defn lucene-pathstore
  [index]
  (reify Pathstore
    (register [this tenant path]
      (search/add index {:tenant tenant :path path}))
    (search [this tenant path]
      (let [query (format "tenant:'%s' path:'%s'" tenant path)]
        (->> (loop [init []
                    page 0]
               (let [paths (map :path (search/search index query 1000000
                                                     :page page
                                                     :results-per-page 100))]

                 (if (< (count paths) 100)
                   (concat init paths)
                   (recur (concat init paths) (inc page))))))))))

(defn lucene-memory-pathstore
  [_]
  (lucene-pathstore (search/memory-index)))

(defn lucene-file-pathstore
  [{:keys [path]}]
  (lucene-pathstore (search/disk-index path)))

Add a metric name index protocol and implementation

This is based on lucene and provides both an in-memory
and on-disk implementation


(ns vip.data-processor.validation.v5-test
  (:require  [clojure.test :refer :all]
             [vip.data-processor.pipeline :as pipeline]
             [vip.data-processor.db.postgres :as psql]
             [vip.data-processor.validation.xml :as xml]
             [vip.data-processor.test-helpers :refer :all]
             [vip.data-processor.validation.v5 :as v5]))

(use-fixtures :once setup-postgres)
(use-fixtures :each with-clean-postgres)

(deftest ^:postgres full-good-v5-test
  (let [ctx {:input (xml-input "v5_sample_feed.xml")
             :pipeline (concat [psql/start-run
                                xml/load-xml-ltree]
                               v5/validations)}
        out-ctx (pipeline/run-pipeline ctx)]
    (assert-no-problems out-ctx [])))

Test the v5 sample feed against all validaitons


(ns app-macros.view-test
  (:require [cljs.test :refer-macros [deftest is]]
            [om.next :as om]
            [app-macros.view :refer-macros [defview]]))

(defview MinimalView)

(deftest minimal-view-works
  (and (is (not (nil? MinimalView)))
       (is (not (nil? minimal-view)))))

(defview MinimalViewWithKeyfn
  (keyfn [{:keys [foo]}] (str foo "-baz")))

(deftest minimal-view-with-key-fn-works
  (and (is (not (nil? MinimalViewWithKeyfn)))
       (is (not (nil? minimal-view-with-keyfn)))
       (is (not (nil? minimal-view-with-keyfn-keyfn)))
       (is (= "bar-baz" (minimal-view-with-keyfn-keyfn {:foo "bar"})))))

(defview ViewWithQuery
  (query [this]
    [:foo :bar]))

(deftest view-with-query-works
  (is (= [:foo :bar] (om/get-query ViewWithQuery))))

(defview ViewWithProps
  [user [name email]]
  (ident [this props] [:user/by-name name])
  (get-name [this] name)
  (get-email [this] email))

(comment
  (deftest view-with-props-works
    (let [view (view-with-props {:user/name "Jeff"
                                 :user/email "jeff@jeff.org"})]
      (println (.-prototype (type view)))
      (println (.-om$isComponent view))
      (and (is (= "Jeff" (.get-name view)))
           (is (= "jeff@jeff.org" (.get-email view))))))

  (cljs.pprint/pprint
   (macroexpand-1
    '(defview ViewWithProps
       [user [name email]]
       (ident [this props] [:user/by-name name])
       (get-name [this] name)
       (get-email [this] email)))))

Add a few basic tests for the defview macro


(ns snippets.color.setting
  (:require [quil.snippet :refer [defsnippet]]
            [quil.core :refer :all]))

(defsnippet background-s {}
  (background 255 0 0)
  (let [gr (create-graphics 100 100)]
    (with-graphics gr
      (background 120))
    (image gr 0 0)

    (with-graphics gr
      (background 70 120))
    (image gr 70 70)

    (with-graphics gr
      (background 0 255 255))
    (image gr 140 140)

    (with-graphics gr
      (background 0 0 255 120))
    (image gr 210 210)))

(defsnippet background-image-s {}
  (let [gr (create-graphics (width) (height))]
    (with-graphics gr
      (background 0 120 120)
      (ellipse 250 250 300 300))

    (background-image gr)))

(defsnippet fill-s {}
  (background 0 0 255)

  (fill 120)
  (rect 0 0 100 100)

  (fill 80 120)
  (rect 70 70 100 100)

  (fill 0 255 0)
  (rect 140 140 100 100)

  (fill 255 0 0 120)
  (rect 210 210 100 100))

(defsnippet no-fill-s {}
  (background 255)

  (stroke 0)
  (fill 120)
  (rect 0 0 100 100)

  (no-fill)
  (rect 70 70 100 100))

(defsnippet no-stroke-s {}
  (background 255)

  (fill 120)
  (stroke 0)
  (rect 0 0 100 100)

  (no-stroke)
  (rect 70 70 100 100))

(defsnippet stroke-s {}
  (background 255)
  (stroke-weight 10)

  (stroke 120)
  (rect 0 0 100 100)

  (stroke 80 120)
  (rect 70 70 100 100)

  (stroke 0 255 0)
  (rect 140 140 100 100)

  (stroke 255 0 0 120)
  (rect 210 210 100 100))

Add Color - Setting snippets.

Add Color - Setting snippets.


(ns main
  (:require [clojure.string :as str]))

(defn main []
  (loop [line (read-line)]
    (when line
      (let [[a b c] (str/split line #" ")
            a' (Integer/parseInt a)
            b' (Integer/parseInt b)
            c' (Integer/parseInt c)
            result (/ (+ (+ (Math/abs (- a' b')) b') a') 2)
            result (/ (+ (+ (Math/abs (- c' result)) result) c') 2)]
        (printf "%d eh o maior%n" result))
      (recur (read-line)))))

(main)

Solve The Greatest in clojure

Solve The Greatest in clojure


(ns onyx.static.pretty-print
  #?(:clj (:require [io.aviso.ansi :as a])))

(def bold
  #?(:clj a/bold
     :cljs identity))

(def magenta
  #?(:clj a/magenta
     :cljs identity))

(def blue
  #?(:clj a/blue
     :cljs identity))

(def bold-red
  #?(:clj a/bold-red
     :cljs identity))

(def bold-green
  #?(:clj a/bold-green
     :cljs identity))

Add missing pretty print file.

Add missing pretty print file.


{:nodes
 {:ph2
  {:name "tnseq-phase2",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:ph2 [:prn1]}}

Add job flow for phase 2 tnseq

Add job flow for phase 2 tnseq


(ns onyx.state-extensions)

(defmulti initialise-log
  (fn [log-type event]
    log-type))

(defmulti close-log
  (fn [log]
    (type log)))

;; For onyx to implement
;; We can implement log storage for Kafka and maybe ZK (if small data is used and we gc)
(defmulti store-log-entries
  "Store state update [op k v] entries in a log"
  (fn [log event entries]
    (type log)))

(defmulti playback-log-entries
  "Read state update [op k v] entries from log"
  (fn [log event state apply-fn]
    (type log)))

(defmulti store-seen-ids
  "Store seen ids in a log. Ideally these will be timestamped for auto expiry"
  (fn [log event seen-ids]
    (type log)))

(defmulti playback-seen-ids
  "Read seen ids from a log"
  (fn [log event bucket-state apply-fn]
    (type log)))

Add state extensions State extensions are for a log type to implement for storage and playback of state commands


(ns cmr.common.background-jobs
  "Namespace for creating simple background jobs that run at a specified interval in a thread.
  For more complex requirements see the cmr.common.jobs namespace which use Quartz."
  (:require [cmr.common.lifecycle :as lifecycle]))

(defrecord BackgroundJob
  [
   ;; The job-function to run
   job-fn

   ;; The interval (in seconds) to run the job
   job-interval-secs

   ;; A reference to the thread to run the background job
   thread-ref]

  lifecycle/Lifecycle

  (start
    [this system]
    (when thread-ref (.interrupt thread-ref))
    (let [thread (Thread.
                   (fn []
                     (try
                      (while (not (.isInterrupted (Thread/currentThread)))
                        (job-fn)
                        (Thread/sleep (* 1000 job-interval-secs)))
                      (catch InterruptedException _))))
          ;; Have to set the thread reference before starting the thread otherwise interrupt fails
          updated-this (assoc this :thread-ref thread)]
      (.start (:thread-ref updated-this))
      updated-this))

  (stop
    [this system]
    (when thread-ref (.interrupt thread-ref))
    (assoc this :thread-ref nil)))

(defn create-background-job
  "Creates a background job using the provided job-fn and how often to run the job in seconds."
  [job-fn job-interval-secs]
  (->BackgroundJob job-fn job-interval-secs nil))

(comment
  (def counter (atom 1))
  (def job (create-background-job #(swap! counter inc) 0.1))
  (def job (lifecycle/start job nil))
  (def job (lifecycle/stop job nil))
  @counter)

CMR-3525: Add new simple background jobs namespace for running jobs


(ns newsfeed.integration.api
  (:require [midje.sweet :refer :all]
            [peridot.core :as p]
            [clojure.data.json :as json]
            [newsfeed.core :as nf]
            [newsfeed.api :as api]))

(facts "about 'api'"
       (let [app (p/session nf/app)]
         (fact "returns 200 on /ping"
               (get-in (p/request app "/ping") [:response :status]) => 200)
         (fact "returns 403 when no token given"
               (get-in (p/request app "/api") [:response :status]) => 403)
         (fact "returns 403 when invalid token given"
               (get-in (p/request app "/api" :headers {"X-Auth-Token" "invalid"}) [:response :status]) => 403)
         (fact "returns 404 when valid token given but invalid route"
               (get-in (p/request app "/api/404" :headers {"X-Auth-Token" "valid"}) [:response :status]) => 404
               (provided (contains? nf/tokens "valid") => true))
         (fact "returns 200 on /api/feeds when valid token given"
               (get-in (p/request app "/api/feeds" :headers {"X-Auth-Token" "valid"}) [:response :status]) => 200
               (provided (contains? nf/tokens "valid") => true
                         (api/get-feeds anything) => '()))))

Add integration tests for newsfeed service


; Eli Bendersky [http://eli.thegreenplace.net]
; This code is in the public domain.
(ns expression.protocols)

(defrecord Constant [value])
(defrecord BinaryPlus [lhs rhs])

(defprotocol Evaluatable
  (evaluate [this]))

(defprotocol Stringable
  (stringify [this]))

(extend-type Constant
  Evaluatable
    (evaluate [this] (:value this))
  Stringable
    (stringify [this] (str (:value this))))

(extend-type BinaryPlus
  Evaluatable
    (evaluate [this] (+ (evaluate (:lhs this)) (evaluate (:rhs this))))
  Stringable
    (stringify [this]
      (clojure.string/join " + " [(stringify (:lhs this))
                                  (stringify (:rhs this))])))

; Also have an alternative to use extend-protocol here...
; the core is 'extend' - a true matrix of type/op

(def c1 (Constant. 1.1))
(def c2 (Constant. 2.2))
(def p1 (BinaryPlus. c1 c2))
(def p2 (BinaryPlus. p1 c2))

(evaluate p2)
(stringify p2)

; "Adding" a new data type - the built-in double type and showing how to extend
; all protocols for it.
(extend-type java.lang.Double
  Evaluatable
    (evaluate [this] this)
  Stringable
    (stringify [this] (str this)))

(def f1 11.5)
(def p3 (BinaryPlus. c1 f1))

(evaluate p3)
(stringify p3)

Add a basic working example in Clojure

Add a basic working example in Clojure


;; Copyright 2015 Andrey Antukh <niwi@niwi.be>
;;
;; Licensed under the Apache License, Version 2.0 (the "License")
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;;     http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.

(ns bytebuf.core-tests
  (:require [clojure.test :refer :all]
            [bytebuf.core :as buf]))

(deftest allocate
  (testing "Allocate heap buffer."
    (let [buffer (buf/allocate 16)]
      (is (not (.isDirect buffer)))))

  (testing "Allocate direct buffer"
    (let [buffer (buf/allocate 16 {:type :direct})]
      (is (.isDirect buffer))))
)

Add test directory with initial tests.

Add test directory with initial tests.


(ns radicalzephyr.boot-junit
  {:boot/export-tasks true}
  (:require [boot.core :as core])
  (:import org.junit.runner.JUnitCore))

(deftask junit
  "Run the jUnit test runner."
  []
  (with-pre-wrap fileset
    (let [result (JUnitCore/runClasses
                  (into-array [#_ (magic goes here to find all test classes)]))]
      (when (> (.getFailureCount result) 0)
        (throw (ex-info "There were some test failures." {:result result}))))
    fileset))

Add the stub of the junit task

Add the stub of the junit task


(ns discuss.find
  (:require [clojure.walk :refer [keywordize-keys]]
            [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]
            [discuss.communication :as com]
            [discuss.lib :as lib]))

(def data (atom {}))

(defn statement-handler
  "Called when received a response in the search."
  [response]
  (let [res (lib/json->clj response)
        values (:values res)
        error (:error res)]
    (if (pos? (count error))
      (lib/error-msg! error)
      (do
        (lib/no-error!)
        (swap! data assoc :foo (keywordize-keys res))
        (println res)
        (println values)
        (println (get "values" res))
        ))))

(defn statement
  "Find related statements to given keywords."
  [keywords]
  (com/ajax-get "api/get/statements/1/3/a" {} statement-handler))

(defn item-view []
  (reify om/IRender
    (render [_]
      (dom/div nil "One element"))))

(defn view []
  (reify om/IRender
    (render [_]
      (dom/h4 nil "Hello World!"))))

Prepare statement query to dbas

Prepare statement query to dbas


{:nodes
 {:ph2
  {:name "tnseq-final-aggregate",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:ph2 [:prn1]}}

Add super(aka global or final) aggregation job flow


;;   Copyright (c) Reid McKenzie, Rich Hickey & contributors. The use
;;   and distribution terms for this software are covered by the
;;   Eclipse Public License 1.0
;;   (http://opensource.org/licenses/eclipse-1.0.php) which can be
;;   found in the file epl-v10.html at the root of this distribution.
;;   By using this software in any fashion, you are agreeing to be
;;   bound by the terms of this license.  You must not remove this
;;   notice, or any other, from this software.

(ns oxcart.passes.emit-clj
  {:doc "Implements an ast to source return emitter designed to be run
         after other transformations for verification of output."
   :added "0.0.4"
   :author "Reid McKenzie"}
  (:require [clojure.tools.analyzer.passes.jvm.emit-form :as emit]
            [oxcart.passes.util :as util]))

(defn emit-clojure
  "λ Whole-AST → options → (Seq Form)

  Uses tools.analyzer.jvm to emit Clojure code from a whole program
  AST. Inteded for use in debugging and verifying output, as well as
  for rebuilding and re-analyzing programs in between syntax level
  passes.

  options:
    At present there are no options accepted by this pass."
  [{:keys [modules] :as whole-ast} options]
  (->> whole-ast
       util/whole-ast->forms
       (map emit/emit-form)))

Add AST to form emission pass

Add AST to form emission pass


(ns vip.data-processor.db.sqlite-test
  (:require [vip.data-processor.db.sqlite :as sqlite]
            [clojure.test :refer :all]
            [vip.data-processor.validation.data-spec.v3-0 :as v3-0]))

(deftest column-names-test
  (let [db (sqlite/temp-db "column-names-test" "3.0")]
    (is (= ["state_id" "early_vote_site_id"]
           (sqlite/column-names (-> db :tables :state-early-vote-sites))))))

Add a test for sqlite/column-names

Add a test for sqlite/column-names

The upcoming korma update broke the original version of this fn, so I added a test first.


(ns main
  (:require [clojure.string :as string]))

(def notas [10000.0 5000.0 2000.0 1000.0 500.0 200.0])
(def coins [100.0 50.0 25.0 10.0 5.0 1.0])

(defn print-result [value currencies currency-type]
  (println (str (string/upper-case currency-type) "S:"))
  (loop [value value
         [currency & remaining-currencies] currencies]
    (let [quantity (quot value currency)]
      (printf
       "%.0f %s(s) de R$ %.2f%n"
       quantity
       currency-type
       (with-precision 2 (/ currency 100.0))))
    (if (seq remaining-currencies)
      (recur (mod value currency) remaining-currencies)
      (mod value currency))))

(defn main []
  (loop [line (read-line)]
    (when line
      (let [value (-> line
                      (Double/parseDouble))]
            (-> (* value 100)
                (print-result notas "nota")
                (print-result coins "moeda"))
        (recur (read-line))))))

(main)

Solve Banknotes and Coins in clojure

Solve Banknotes and Coins in clojure


(ns desdemona.cli-test
  (:require
   [desdemona.launcher.aeron-media-driver :as aeron]
   [clojure.test :refer [deftest testing is]])
  (:import
   [java.io StringWriter]))

(def fake-block-forever!
  (constantly ::blocked-forever))

(defn fake-exit
  [status]
  [::exited status])

(defmacro with-fake-launcher-side-effects
  "Runs body with a fake exit, block-forever! and stdout.

  This assumes you're using com.gfredericks.system-slash-exit, because
  it's _way_ easier to mock out than the alternative.

  Returns [body-value stdout]. If it would have blocked forever, body-value
  will be ::blocked-forever. If it would have exited, body-value will
  be [::exited status]."
  [& body]
  `(with-redefs [com.gfredericks.system-slash-exit/exit fake-exit
                 desdemona.launcher.utils/block-forever! fake-block-forever!]
     (let [stdout# (StringWriter.)]
       (binding [*out* stdout#]
         (let [result# ~@body]
           [result# (str stdout#)])))))

(deftest aeron-main-tests
  "Tests for the aeron-media-driver main."
  (testing "usage"
    (let [[result stdout] (with-fake-launcher-side-effects
                            (aeron/-main "--help"))]
      (is (= result 0))
      (is (= stdout nil)))))

Add basic test structure + failing test

Add basic test structure + failing test


(ns konserve.konserve-test
  (:require [cljs.test :refer [run-tests]]
            [konserve.filestore-test]
            [konserve.serializers-test]))

(run-tests 'konserve.filestore-test
           'konserve.serializers-test)

Add cljs konserve main test.

Add cljs konserve main test.


(ns doctopus.files.predicates
  "We've got a loooot of filtering to do.

  Like, a lot.")

(defmulti is-type?
  "Returns true if the type of the file matches the type given."
  (fn [fobj regex] (class fobj)))

(defmethod is-type? java.lang.String
  [file-string type-regex]
  (if (re-find type-regex file-string)
    true
    false))

(defmethod is-type? java.io.File
  [file-handle type-regex]
  (is-type? (.getPath file-handle) type-regex))

(defn markdown?
  "returns true only for type files."
  [file-handle]
  (is-type? file-handle #"(?i)md|markdown|mdown$"
            ))

(defn restructured-text?
  "returns true only for type files."
  [file-handle]
  (is-type? #"(?i)rst|rest$" (.getPath file-handle)
            ))

Move the predicate functions in to their own ns -- it seems likely that we'll wind up with a bunch of these. Also, remove the note about expecting a java.io.File from the docstrings -- our schmancy multimethod `is-type` obviates that.


{:user {:plugins [[lein-try "0.4.1"]
                  [lein-pprint "1.1.1"]
                  [cider/cider-nrepl "0.7.0"]]}}

Add leiningen `:user` profile file

Add leiningen `:user` profile file


(ns main)

(defn main []
  (let [h (-> (read-line) (Double/parseDouble))
        s (-> (read-line) (Double/parseDouble))]
    (printf "%.3f%n" (/ (* h s) 12))))

(main)

Solve Fuel Spent in clojure

Solve Fuel Spent in clojure


;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) 2016 Andrey Antukh <niwi@niwi.nz>

(ns uxbox.util.dom.files
  "A interop helpers for work with files."
  (:require [beicon.core :as rx]
            [cuerdas.core :as str]))

(defn- read-as-dataurl
  [file]
  (rx/create
   (fn [sick]
     (let [fr (js/FileReader.)]
       (aset fr "onload" #(sick (rx/end (.-result fr))))
       (.readAsDataURL fr file))
     (constantly nil))))

(defn- retrieve-image-size
  [data]
  (println "data:" data)
  (rx/create
   (fn [sick]
     (let [img (js/Image.)]
       (aset img "onload" #(sick (rx/end [(.-width img) (.-height img)])))
       (set! (.-src img) data))
     (constantly nil))))

(defn get-image-size
  "Get the real image size."
  [file]
  (->> (read-as-dataurl file)
       (rx/flat-map retrieve-image-size)))

Add utils for work with dom file like objects.


(ns subman.t-routes
  (:require [midje.sweet :refer [fact => truthy]]
            [subman.routes :as routes]))

(fact "routes should be ok"
      routes/main-routes => truthy)

Add simple test for routes

Add simple test for routes


;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) 2016 Andrey Antukh <niwi@niwi.nz>

(ns uxbox.images
  "Image postprocessing."
  (:require [storages.core :as st]
            [uxbox.media :as media]
            [uxbox.util.paths :as paths]
            [uxbox.util.images :as images]
            [uxbox.util.data :refer (dissoc-in)]))

(defn make-thumbnail
  [path {:keys [size format quality] :as cfg}]
  (let [parent (paths/parent path)
        [filename ext] (paths/split-ext path)

        suffix-parts [(nth size 0) (nth size 1) quality format]
        final-name (apply str filename "-" (interpose "." suffix-parts))
        final-path (paths/path parent final-name)

        images-storage media/images-storage
        thumbs-storage media/thumbnails-storage]
    (if @(st/exists? thumbs-storage final-path)
      (str (st/public-url thumbs-storage final-path))
      (let [datapath @(st/lookup images-storage path)
            content (images/thumbnail datapath cfg)
            path @(st/save thumbs-storage final-path content)]
        (str (st/public-url thumbs-storage path))))))

(defn populate-thumbnail
  [entry {:keys [src dst] :as cfg}]
  (let [src (if (vector? src) src [src])
        dst (if (vector? dst) dst [dst])]
    (assoc-in entry dst
              (make-thumbnail (get-in entry src) cfg))))

(defn populate-thumbnails
  [entry & settings]
  (reduce populate-thumbnail entry settings))

(defn populate-urls
  [entry storage src dst]
  (let [src (if (vector? src) src [src])
        dst (if (vector? dst) dst [dst])
        value (get-in entry src)
        url (str (st/public-url storage value))]
    (-> entry
        (dissoc-in src)
        (assoc-in dst url))))

Add the ability to populate objects with thumbnails and url resolved paths.


;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) 2016 Andrey Antukh <niwi@niwi.nz>

(ns uxbox.util.mixins
  (:require [rum.core :as rum]
            [sablono.compiler :as s]))

(defn- parse-defc
  [args]
  (loop [r {}
         s 0
         v (first args)
         n (rest args)]
    (case s
      0 (if (symbol? v)
          (recur (assoc r :name v) (inc s) (first n) (rest n))
          (throw (ex-info "Invalid" {})))
      1 (if (string? v)
          (recur (assoc r :doc v) (inc s) (first n) (rest n))
          (recur r (inc s) v n))
      2 (if (map? v)
          (if-let [mixins (:mixins v)]
            (let [spec (dissoc v :mixins)
                  mixins (if (empty? spec)
                           mixins
                           (conj mixins spec))]
              (recur (assoc r :mixins mixins) (inc s) (first n) (rest n)))
            (recur (assoc r :mixins [v]) (inc s) (first n) (rest n)))
          (recur r (inc s) v n))
      3 (let [sym (:name r)
              func `(fn ~sym ~v ~(s/compile-html `(do ~@n)))]
          [func (:doc r) (:mixins r) sym]))))

(defmacro defc
  [& args]
  (let [[render doc mixins cname] (parse-defc args)]
    `(def ~cname ~doc (rum/build-defc ~render ~mixins ~(str cname)))))

Add own defc macro for more easy define components with less boilerplate.


(ns clj-gatling.core-test
  (:require [clojure.test :refer :all]
            [clj-gatling.test-helpers :refer :all]
            [clj-containment-matchers.clojure-test :refer :all]
            [clj-gatling.core :refer [run run-simulation]]
            [clj-async-test.core :refer :all]
            [clojure.core.async :refer [go <! <!! timeout]]
            [clj-time.core :as time]))

(use-fixtures :once setup-error-file-path)

(def legacy-scenario
  {:name "Test scenario"
   :context {}
   :requests [{:name "Request1" :fn successful-request}
              {:name "Request2" :fn failing-request}]})

(def simulation
  {:name "Test simulation"
   :scenarios [{:name "Test scenario"
                :steps [(step "Step1" true)
                        (step "Step2" false)]}]})

(deftest legacy-simulation-returns-summary
  (let [summary (run-simulation [legacy-scenario] 1 {})]
    (is (= {:ok 1 :ko 1} summary))))

(deftest simulation-returns-summary
  (let [summary (run simulation {:concurrency 1})]
    (is (= {:ok 1 :ko 1} summary))))

Add smoke tests for core entrypoint functionss


;; See: https://clojuredocs.org/clojure.test/deftest
(ns cjapplied.ch08)
(use 'clojure.test)

(deftest addition
  (is (= 4 (+ 2 2)))
  (is (= 7 (+ 3 4))))

(deftest subtraction
  (is (= 1 (- 4 3)))
  (is (= 3 (- 7 4))))

;; composing tests
(deftest arithmetic
  (addition)
  (subtraction))

(deftest test-range
  (is (= '(0 1 2 3 4) (range 5))))

(run-tests 'cjapplied.ch08)
;; {:test 6, :pass 9, :fail 0, :error 0, :type :summary}

(run-all-tests) ;;
{:test 9, :pass 10, :fail 1, :error 1, :type :summary}

Add sample from Clojure Applied

Add sample from Clojure Applied


(ns parse-names.core
  (:require [parse-names.vendor :as v]))

(defn parse-name [name]
  (let [name-obj (v/parse name)]
    (->> {:first-name (.-firstName name-obj)
          :last-name (.-lastName name-obj)
          :leading-initial (.-salutation name-obj)
          :suffix (.-suffix name-obj)
          :middle-name (.-initials name-obj)}
         (filter (fn [[k v]] (not (empty? v))))
         (into {}))))

Add cljs wrapper on vendor

Add cljs wrapper on vendor


(ns doctopus.web-test
  (:require [clojure.edn :as edn]
            [clojure.java.io :as io]
            [clojure.test :refer :all]
            [compojure.core :refer [context]]
            [doctopus.configuration :refer [docs-uri-prefix]]
            [doctopus.db :as db]
            [doctopus.doctopus.head :as h]
            [doctopus.doctopus :refer [->Doctopus load-routes bootstrap-heads]]
            [doctopus.doctopus.tentacle :as t]
            [doctopus.test-database :refer [schema-only-fixture]]
            [doctopus.test-utilities :as utils]
            [doctopus.web :as web]))

(use-fixtures :once schema-only-fixture)

(def test-map-props
  (h/parse-tentacle-config-map
   (edn/read-string (slurp (io/resource "test/heads/test/doctopus-test.edn")))))

(def one-head (h/map->Head {:name "test"}))
(def one-tentacle (t/map->Tentacle test-map-props))
(def stunt-doctopus (->Doctopus {} {}))

(deftest document-routes-test
  (db/save-head! one-head)
  (db/save-tentacle! one-tentacle)
  (db/create-mapping! one-head one-tentacle)
  (bootstrap-heads stunt-doctopus)
  (testing "Doctopus document routes"
    (let [ctx-str (str "/" docs-uri-prefix)
          routes (context ctx-str [] (load-routes stunt-doctopus))
          response (utils/fake-request routes :get "/docs/doctopus-test/index.html")]
      (is (utils/truthy? (:body response)))
      (is (= "text/html" ((:headers response) "Content-Type")))
      (is (= 200 (:status response))))))

(deftest routes-test
  (testing "Tests against base, unwrapped doctopus-routes"
    (let [routes (web/create-application web/doctopus-routes)
          requester (partial utils/fake-request routes)]
      (is (= 200 (:status (requester :get "/"))))
      (is (= 200 (:status (requester :get "/index.html"))))
      (is (= 200 (:status (requester :get "/heads"))))
      (is (= 200 (:status (requester :get "/heads/doctopus-test"))))
      (is (= 200 (:status (requester :get "/add-head"))))
      (is (= 200 (:status (requester :get "/add-tentacle"))))
      ;; These two 403. Huh. Not... perfectly sure what to do.
      ;; (is (= 200 (:status (requester :post "/add-tentacle"))))
      ;; (is (= 200 (:status (requester :post "/add-head"))))
      )))

Add web NS tests, mostly for routes

Add web NS tests, mostly for routes


(ns user
  (:require [clojars
             [config :as config]
             [errors :as errors]
             [system :as system]]
            [clojars.db.migrate :as migrate]
            [clojure.java.io :as io]
            [clojure.tools.namespace.repl :refer [refresh]]
            [eftest.runner :as eftest]
            [meta-merge.core :refer [meta-merge]]
            [reloaded.repl :refer [system init stop go clear]]))

(def dev-env
  {:app {:middleware []}})

(defn new-system []
  (refresh)
  (config/configure [])
  (assoc (system/new-system (meta-merge config/config dev-env))
         :error-reporter (errors/->StdOutReporter)))

(ns-unmap *ns* 'test)

(defn reset []
  (if system
    (do (clear)
        (go))
    (refresh)))

(defn test [& tests]
  (let [tests (if (empty? tests)
                  (eftest/find-tests "test")
                  tests)]
        (eftest/run-tests tests {:report eftest.report.pretty/report
                                 :multithread? false})))

(when (io/resource "local.clj")
  (load "local"))

(defn migrate []
  (migrate/migrate (:db config/config)))

;; TODO: function to setup fake data (from clojars.dev.setup?)

(reloaded.repl/set-init! new-system)

(ns user
  (:require [clojars
             [cloudfiles :as cf]
             [config :as config]
             [errors :as errors]
             [system :as system]]
            [clojars.db.migrate :as migrate]
            [clojure.java.io :as io]
            [clojure.tools.namespace.repl :refer [refresh]]
            [eftest.runner :as eftest]
            [meta-merge.core :refer [meta-merge]]
            [reloaded.repl :refer [system init stop go clear]]))

(def dev-env
  {:app {:middleware []}})

(defn new-system []
  (refresh)
  (config/configure [])
  (assoc (system/new-system (meta-merge config/config dev-env))
    :error-reporter (errors/->StdOutReporter)
    :cloudfiles (cf/connect "" "" "dev" "transient")))

(ns-unmap *ns* 'test)

(defn reset []
  (if system
    (do (clear)
        (go))
    (refresh)))

(defn test [& tests]
  (let [tests (if (empty? tests)
                  (eftest/find-tests "test")
                  tests)]
        (eftest/run-tests tests {:report eftest.report.pretty/report
                                 :multithread? false})))

(when (io/resource "local.clj")
  (load "local"))

(defn migrate []
  (migrate/migrate (:db config/config)))

;; TODO: function to setup fake data (from clojars.dev.setup?)

(reloaded.repl/set-init! new-system)

Add in-memory cloudfiles connection to the dev system


(ns subman.t-search
  (:require-macros [purnam.test.sweet :refer [facts fact]])
  (:require [reagent.core :refer [atom]]
            [subman.helpers :refer [truthy]]
            [subman.search :as search]))

(facts "should create search request"
       (fact "with query"
             (search/create-search-request "test") => "/api/search/?query=test")
       (fact "with query and lang"
             (search/create-search-request
              "test :lang ru") => "/api/search/?query=test&lang=ru"))

(fact "watch to query should be ok"
      (search/watch-to-query (atom "")
                             (atom [])
                             (atom 0)) => truthy)

Add simple tests for search

Add simple tests for search


; Use refs to create a vector of accounts in memory. Create debit and credit functions to change the balance of an account.
(def accounts (ref [0 0 0]))

(defn balance
  [accounts index]
  (nth @accounts index))

(defn debit
  [accounts index amount]
  (dosync (alter accounts assoc index (- (balance accounts index) amount))))

(defn credit
  [accounts index amount]
  (dosync (alter accounts assoc index (+ (balance accounts index) amount))))

Add clojure day 3 basic

Add clojure day 3 basic


(ns decktouch.mtg-card-master
  (:require [clojure.data.json :as json]))

(def mtg-cards (json/read-str (slurp "resources/AllCards.json")))

(def card-names (keys mtg-cards))

(defn match
  "Returns true if query is a substring in string"
  [query string]
  (some? (re-matches (re-pattern (str "(?i)" query ".*"))
                    string)))

(defn get-cards-matching-query
  "Return a list of maps of strings of card names that match the query for the card input autocomplete"
  [query]
  (let [match-query (partial match query)]
      (map (fn [thing] {:cardName thing})
        (filter match-query card-names))))

Add mtg card master namespace

Add mtg card master namespace


(ns cljam.io.vcf.reader-test
  (:require [clojure.test :refer [deftest is]]
            [cljam.io.vcf.reader :as vcf-reader]))

(deftest parse-structured-line-test
  (is (= {:id "ID", :description "\"This\" is a description",
          :note "You can use \" in string fields by escaping it with \\"}
       (#'vcf-reader/parse-structured-line "ID=ID,Description=\"\\\"This\\\" is a description\",Note=\"You can use \\\" in string fields by escaping it with \\\\\"")))
  (is (thrown-with-msg? RuntimeException
                        #"Unexpected end of string field"
                        (#'vcf-reader/parse-structured-line "x=\"unbalanced double quote")))
  (is (thrown-with-msg? RuntimeException
                        #"Either '\\' or '\"' was expected immediately after '\\', but got 'x'"
                        (#'vcf-reader/parse-structured-line "x=\"unknown \\x escape sequence\""))))

Add tests for character escaping for VCF string fields


Add test case for cljam.cigar

Add test case for cljam.cigar


(defproject cryogen "0.1.0"
            :description "Simple static site generator"
            :url "https://github.com/lacarmen/cryogen"
            :license {:name "Eclipse Public License"
                      :url "http://www.eclipse.org/legal/epl-v10.html"}
            :dependencies [[org.clojure/clojure "1.6.0"]
                           [ring/ring-devel "1.3.2"]
                           [compojure "1.3.1"]
                           [ring-server "0.3.1"]
                           [cryogen-core "0.1.8"]]
            :plugins [[lein-ring "0.8.13"]]
            :main cryogen.core
            :ring {:init cryogen.server/init
                   :handler cryogen.server/handler})

(defproject cryogen "0.1.0"
            :description "Simple static site generator"
            :url "https://github.com/lacarmen/cryogen"
            :license {:name "Eclipse Public License"
                      :url "http://www.eclipse.org/legal/epl-v10.html"}
            :dependencies [[org.clojure/clojure "1.6.0"]
                           [ring/ring-devel "1.3.2"]
                           [compojure "1.3.1"]
                           [ring-server "0.3.1"]
                           [cryogen-core "0.1.9"]]
            :plugins [[lein-ring "0.8.13"]]
            :main cryogen.core
            :ring {:init cryogen.server/init
                   :handler cryogen.server/handler})

Update cryogen-core dependency to 0.1.9.


(ns scraper.core
  (:require [clojure.string :as str]))

(def url "https://docs.google.com/spreadsheets/d/1XMCStIcX-UkJF2YYmco7mnoSec8I8Vg_1wSSAVR7L00/export?format=csv")

(def input (slurp url))
(def entries (str/split input #"\n"))
(def an-entry (-> (str/split input #"\n")
                  (get 2)))

;; Helpers
;; =======
(defn- unicode-bool
  "Returns true if val is a unicode checkmark"
  [val]
  (= "✔" val))

(defn- update-fields
  "Applies f to each value of fields"
  [coll f fields]
  (reduce #(update %1 %2 f) coll fields))

;; Entry parsing
;; ===========
(defn split-entry
  "Splits the entry in an array of values"
  [csv-line]
  (drop 1 (str/split csv-line #",")))

(defn pedal
  "Builds a pedal hash-map from the values array"
  [values]
  (zipmap [:brand :model :distributor :isolator :adapter :comment] values))

(defn parse-boolean-fields
  "Updates :distributor, :isolator and :adapter to be proper booleans"
  [entry]
  (update-fields entry unicode-bool [:distributor :isolator :adapter]))

;; Parsing all the data
(defn parse-entries
  "Transforms all entries into pedals"
  [entries]
  (map #(-> (str/trim %)
            split-entry
            pedal
            parse-boolean-fields)
       entries))

(defn write-to-file
  "Writes the output to the data.cljs file"
  [entries]
  (spit
   "./gigrig/src/gigrig/data.cljs"
   (with-out-str
     (println "(ns gigrig.data)")
     (println "(defonce data")
     (pr entries)
     (println ")"))))

(defn -main []
  (-> (slurp url)
      (str/split #"\n")
      (#(drop 2 %))
      parse-entries
      write-to-file))

Write scraper for pedals db

Write scraper for pedals db


(ns doctopus.files-test
  (:require [doctopus.files :refer :all]
            [clojure.test :refer :all]))

(deftest test-truncate-str
  (testing "Can we truncate one path by removing another path from the front?"
    (let [fq "/foo/bar/baz/bing/bang/document.markdown"
          remove-str "/foo/bar/baz/bing/"
          result (truncate-str fq remove-str)]
      (is (= result "bang/document.markdown")))))

Add our first test oh boy!

Add our first test oh boy!


(ns grafter.rdf.ontologies.ons-geography
  (:require [grafter.rdf.ontologies.util :refer :all]))

(def statistical-entity (prefixer "http://statistics.data.gov.uk/def/statistical-entity#"))
(def statistical-entity:name                 (statistical-entity "name"))
(def statistical-entity:abbreviation         (statistical-entity "abbreviation"))
(def statistical-entity:owner                (statistical-entity "owner"))
(def statistical-entity:coverage             (statistical-entity "coverage"))
(def statistical-entity:relatedentity        (statistical-entity "relatedentity"))
(def statistical-entity:status               (statistical-entity "status"))
(def statistical-entity:liveinstances        (statistical-entity "liveinstances"))
(def statistical-entity:archivedinstances    (statistical-entity "archivedinstances"))
(def statistical-entity:coverage             (statistical-entity "coverage"))
(def statistical-entity:firstcode            (statistical-entity "firstcode"))
(def statistical-entity:lastcode             (statistical-entity "lastcode"))
(def statistical-entity:reservedcode         (statistical-entity "reservedcode"))
(def statistical-entity:introduced           (statistical-entity "introduced"))
(def statistical-entity:lastinstancechange   (statistical-entity "lastinstancechange"))
(def statistical-entity:code                 (statistical-entity "code"))
(def statistical-entity:crossborderinstances (statistical-entity "crossborderinstances"))

(def statistical-geography (prefixer "http://statistics.data.gov.uk/def/statistical-geography#"))
(def statistical-geography:officialname      (statistical-entity "officialname"))
(def statistical-geography:status            (statistical-entity "status"))

(def boundary-change (prefixer "http://statistics.data.gov.uk/def/boundary-change/"))
(def boundary-change:operativedate           (boundary-change "operativedate"))
(def boundary-change:originatingChangeOrder  (boundary-change "originatingChangeOrder"))
(def boundary-change:terminateddate          (boundary-change "terminateddate"))
(def boundary-change:changeOrderTitle        (boundary-change "changeOrderTitle"))

Add Vocabulary (prefixers) for ONS/ Statistical Geography


(ns caesium.randombytes-test
  (:require [caesium.randombytes :as r]
            [clojure.test :refer [deftest is]]))

(deftest randombytes-tests
  (let [some-bytes (r/randombytes 10)]
    (is (= 10 (alength some-bytes)))))

Add a simple test for randombytes

Add a simple test for randombytes


(ns ^:figwheel-load word-finder.actions.call-server
  (:require [ajax.core :refer [GET]]))

(def server "http://localhost:8080/api/words/")

;;FIXME: the string interpolation can be easily broken.
(defn find-words [input-string callback]
  (GET (str server "find" "?find=" input-string)
      {:handler       callback
       :error-handler #(println "ERROR" %)}))

(defn find-anagrams [input-string callback]
  (GET (str server "anagrams" "?find=" input-string)
      {:handler       callback
       :error-handler #(println "ERROR!" %)}))

(defn find-sub-anagrams [input-string callback]
  (GET (str server "sub-anagrams" "?find=" input-string)
      {:handler callback}))

(ns ^:figwheel-load word-finder.actions.call-server
  (:require [ajax.core :refer [GET]]))

(def server "http://localhost:8080/api/words/")

(defn find-words
  "Call the server-side find-words, returning JSON"
  [input-string callback]
  (GET (str server "find")
      {:params        {:find input-string}
       :format        :json
       :handler       callback
       :error-handler #(println "ERROR" %)}))

(defn find-anagrams
  "Call the server-side find-anangrams, returning JSON"
  [input-string callback]
  (GET (str server "anagrams")
      {:params        {:find input-string}
       :format        :json
       :handler       callback
       :error-handler #(println "ERROR!" %)}))

(defn find-sub-anagrams
  "Call the server-side find-sub-anagrams, returning JSON"
  [input-string callback]
  (GET (str server "sub-anagrams")
      {:params        {:find input-string}
       :format        :json
       :handler       callback
       :error-handler #(println "ERROR!" %)}))

Fix the cljs server calls to use ajax.core :params

Instead of doing poor string interpolation, just use the library.


(ns hydrofoil.expectations.model
  (:require [expectations :refer :all]
            [hydrofoil.model :refer :all]
            [hydrofoil.core :refer :all]
            [hydrofoil.evolution :refer :all]))

;;; --------- Utils Tests ------------

Add Utils test file, don't have anything to put in it yet.


(ns clj-diff.test.performance
  (:use [clj-diff.core])
  (:use [clj-diff.performance] :reload)
  (:use [clojure.test]))

(deftest mutate-test
  (let [a "abcdefghijklmnopqrstuvwxyz"
        changes #(count (flatten (map rest (:+ %))))
        largest-group #(apply max (map count (map rest (:+ %))))]
    (is (<= (changes (diff a (mutate a 1 1)))
           1))
    (is (<= (changes (diff a (mutate a 2 1)))
            2))
    (is (<= (changes (diff a (mutate a 5 1)))
            5))
    (is (<= (changes (diff a (mutate a 5 5)))
            5))
    (is (<= (largest-group (diff a (mutate a 5 5)))
            5))
    (is (<= (changes (diff a (mutate a 10 5)))
            10))
    (is (<= (largest-group (diff a (mutate a 10 5)))
            5))))

Add unit test for mutate and update the charts.


(ns circle.admin.ebs
  (:require [org.jclouds.ec2.ebs2 :as ebs])
  (:require [circle.backend.ec2 :as ec2])
  (:use [circle.utils.except :only (throw-if-not)])
  (:use [circle.aws-credentials :only (jclouds-compute)]))

(defn default-volume [instance-id]
  (let [inst (ec2/instance instance-id)
        devices (map bean (-> inst :blockDeviceMappings))
        root-dev (-> inst :rootDeviceName)
        dev (first (filter #(not= root-dev (:deviceName %)) devices))]
    (-> dev :ebs (bean) :volumeId)))

(defn volume-from-id
  "returns a Volume from the id"
  [vol-id]
  (->>
   jclouds-compute
   (ebs/volumes)
   (filter #(= vol-id (.getId %)))
   (first)))

(defn take-snapshot
  "Create a snapshot of an EBS volume.
  ec2-id - and AWS instance id
  description -

  Options:
  vol-id - the vol-id. If not specified, uses the first non-root device.
   "
  [ec2-id description & {:keys [vol-id]}]
  (ebs/create-snapshot jclouds-compute (volume-from-id (or vol-id (default-volume ec2-id))) description))

(defn latest-snapshot
  "Returns the snapshot-id with matching description"
  [description]
  (->>
   (ebs/snapshots jclouds-compute :owner "self")
   (map bean)
   (filter #(= description (:description %)))
   (sort-by :startTime)
   (last)
   :id))

Add functions for interacting with EBS snapshots


(ns clojure-walkthrough.cjia.ch07-xx)
; 7.1: Macro basic

; 7.1.1: Textual substitution

(def a-ref (ref 0))

(dosync
 (ref-set a-ref 1)) ; 1

;; You could implement this using the macros like
; (syn-set a-ref 1)

(defmacro sync-set [r v]
  (list 'dosync
        (list 'ref-set r v)))

(sync-set a-ref 1) ;; 1

Add macro example from section 7.1

Add macro example from section 7.1


(ns cljs-nlp.stats.levenshtein
  (:use [clojure.string :only [blanks?]]))

(defn create-element
  [char1 char2 previous-row current-row idx]
  (if (= char1 char2)
    (previous-row (- idx 1))
    (+ 1 (min
      (previous-row (- idx 1))
      (previous-row idx)
      (last current-row)))))

(defn create-row
  [char1 str2 previous-row current-row]
  (let [char2 (first str2)
        idx (count current-row)]
    (if (= (count current-row) (count previous-row))
      current-row
      (recur
        char1
        (rest str2)
        previous-row
        (conj current-row (create-element char1 char2 previous-row current-row idx))))))

(defn levenshtein
  "Calculate the edit distance between two strings."
  ([str1 str2]
    (let [initial-row (vec (range (inc (count str2))))]
      (levenshtein 1 initial-row str1 str2)))
  ([row-no previous-row str1 str2]
    (let [next-row (create-row (first str1) str2 previous-row [row-no])
          rest-str1 (subs str1 1)]
      (if (blank? rest-str1)
        (last next-row)
        (recur (inc row-no) next-row rest-str1 str2)))))

Add ability to calculate edit distance.

Add ability to calculate edit distance.


(defproject onyx-app/lein-template "0.10.0.0-beta10"
  :description "Onyx Leiningen application template"
  :url "https://github.com/onyx-platform/onyx-template"
  :license {:name "MIT License"
            :url "http://choosealicense.com/licenses/mit/#"}
  :repositories {"snapshots" {:url "https://clojars.org/repo"
                              :username :env
                              :password :env
                              :sign-releases false}
                 "releases" {:url "https://clojars.org/repo"
                             :username :env
                             :password :env
                             :sign-releases false}}
  :plugins [[lein-set-version "0.4.1"]]
  :profiles {:dev {:plugins [[lein-set-version "0.4.1"]
                             [lein-update-dependency "0.1.2"]
                             [lein-pprint "1.1.1"]]}}
  :eval-in-leiningen true)

(defproject onyx-app/lein-template "0.10.0.0-SNAPSHOT"
  :description "Onyx Leiningen application template"
  :url "https://github.com/onyx-platform/onyx-template"
  :license {:name "MIT License"
            :url "http://choosealicense.com/licenses/mit/#"}
  :repositories {"snapshots" {:url "https://clojars.org/repo"
                              :username :env
                              :password :env
                              :sign-releases false}
                 "releases" {:url "https://clojars.org/repo"
                             :username :env
                             :password :env
                             :sign-releases false}}
  :plugins [[lein-set-version "0.4.1"]]
  :profiles {:dev {:plugins [[lein-set-version "0.4.1"]
                             [lein-update-dependency "0.1.2"]
                             [lein-pprint "1.1.1"]]}}
  :eval-in-leiningen true)

Prepare for next release cycle.

Prepare for next release cycle.


(ns grimoire.api.web-test
  (:require [grimoire.api :as api]
            [grimoire.things :as t]
            [grimoire.util :refer [succeed? result]]
            [grimoire.api.web.read]
            [clojure.test :refer :all]))

(def test-config
  {:datastore
   {:mode :web
    :host "http://127.0.0.1:3000"}}) ;; test against local Grimoire instance

;; Listing tests
;;------------------------------------------------------------------------------

(deftest list-groups-test
  (let [?res (-> test-config
                api/list-groups)]
    (is (succeed? ?res))
    (doseq [?g (result ?res)]
      (is (t/isa? :group ?g)))))

(deftest list-artifacts-test
  (let [g    (t/->Group "org.clojure")
        ?res (-> test-config
                (api/list-artifacts g))]
    (is (succeed? ?res))
    (doseq [?a (result ?res)]
      (is (t/isa? :artifact ?a)))))

(deftest list-versions-test
  (let [g    (t/->Group "org.clojure")
        a    (t/->Artifact g "clojure")
        ?res (-> test-config
                (api/list-versions a))]
    (is (succeed? ?res))
    (doseq [?v (result ?res)]
      (is (t/isa? :version ?v)))))

(deftest list-ns-test
  (let [v    (t/->Version "org.clojure" "clojure" "1.6.0")
        ?res (-> test-config
                (api/list-namespaces v))]
    (is (succeed? ?res))
    (doseq [?ns (result ?res)]
      (is (t/isa? :namespace ?ns)))))

(deftest list-prior-versions-test
  (let [ns   (t/->Ns "org.clojure" "clojure" "1.6.0" "clojure.core")
        ?res (-> test-config
                (api/thing->prior-versions ns))]
    (is (succeed? ?res))
    (is (= #{"1.6.0" "1.5.0" "1.4.0"}
           (->> ?res result (map (comp :name :parent)) set)))))

(deftest list-def-test
  (let [ns   (t/->Ns "org.clojure" "clojure" "1.6.0" "clojure.core")
        ?res (-> test-config
                (api/list-defs ns))]
    (is (succeed? ?res))
    (let [defs (->> ?res result (map :name) set)]
      (doseq [d ["for" "def" "let" "catch"]]
        (is (defs d))))))

Add tests of the Grimoire web API

Add tests of the Grimoire web API


(ns pathfinder.analyze.clojure-test
  (:use midje.sweet
        pathfinder.analyze.analyzer
        pathfinder.analyze.clojure))

(facts "about heuristic analysis"
       (fact "should keep the source"
             (analyze (->CljHeuristicAnalyzer) "foo" {}) => (contains {:source "foo"}))
       (fact "should keep the metadata"
             (analyze (->CljHeuristicAnalyzer) "foo" {:a :b}) => (contains {:meta {:a :b}}))
       (fact "should extract definitions"
             (:definitions (analyze (->CljHeuristicAnalyzer) "(defn foo [] 3)" {}))
             => (contains (contains {:name "foo"})))
       (fact "should extract definitions, namespaced"
             (:definitions (analyze (->CljHeuristicAnalyzer) "(ns test) (defn foo [] 3)" {}))
             => (contains (contains {:name "test/foo"}))))

Add tests for current clj heuristic analyzer


(ns com.nomistech.clojure-the-language.protocols-and-records-test
  (:require [midje.sweet :refer :all]))

;;;; ___________________________________________________________________________
;;;; ---- `defrecord` and what it gives you ----

(defrecord MyRecord [x y])

(fact "Simple constructor"
  (MyRecord. 1 2)
  => {:x 1 :y 2})

(fact "Constructor using metadata"
  (-> (MyRecord. 1 2 {:m-1 1 :m-2 2} nil)
      meta)
  => {:m-1 1 :m-2 2})

(fact "Constructor using extension data"
  (-> (MyRecord. 1 2 nil {:e-1 1 :e-2 2})
      :e-1)
  => 1)

(fact "->xxx factory function"
  (->MyRecord 1 2)
  => (MyRecord. 1 2))

(fact "map->xxx factory function"
  (map->MyRecord {:x 1 :y 2})
  => (MyRecord. 1 2))

;;;; ___________________________________________________________________________

Add protocols and records stuff.

Add protocols and records stuff.


(ns lazytest.reified-tests
  (:use (lazytest expect testable runnable-test)))

(def t1 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect= 1 2)))))))))

(def t2 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect= 1 1)))))))))

(def t3 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect-instance java.lang.String :a)))))))))

(def t4 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect-not= 1 1)))))))))

(def t5 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect= (/ 1 0) 0)))))))))

(def t6 (reify Testable
	       (get-tests [this]
			  (list
			   (reify RunnableTest
				  (run-tests [this]
					     (list
					      (try-expectations this
								(expect (< 1 0))))))))))

Add reified-tests example source for testing at the REPL


(ns clojure-walkthrough.cjia.ch10-xx
  (:require [clojure.test :refer :all]
            [clojure-walkthrough.cjia.ch10-date-operations :refer :all]))

(deftest test-simple-data-parsing
  (let [d (date "2009-01-22")]
    (is (= (day-from d) 22))))

Add place holder for cjia

Add place holder for cjia


(ns main
  (:require [clojure.string :as str]))

(defn main []
  (let [[x1 y1] (-> (read-line) (str/split #" "))
        [x2 y2] (-> (read-line) (str/split #" "))
        [x1' y1' x2' y2'] (map #(Double/parseDouble %) [x1 y1 x2 y2])]
    (printf "%.4f%n" (Math/sqrt (+ (Math/pow (- x2' x1') 2) (Math/pow (- y2' y1') 2))))))

(main)

Solve Distance Between Two Points in clojure


(ns main)

(defn main []
  (let [a (Double/parseDouble (read-line))
        b (Double/parseDouble (read-line))]
    (format "%.5f" (/ (+ (* a 3.5) (* b 7.5)) 11.0))))

(println "MEDIA =" (main))

Solve Average 1 in clojure

Solve Average 1 in clojure


(ns workflo.macros.entity-test
  (:require [clojure.spec :as s]
            [clojure.test :refer [deftest is]]
            [workflo.macros.entity :as e :refer [defentity]]))

(deftest minimal-defentity
  (is (= '(do
            (def macros-user-schema map?)
            (def macros-user-definition
              {:schema pod/macros-user-schema}))
         (macroexpand-1 `(defentity macros/user
                           (~'schema ~'map?))))))

(deftest defentity-with-validation
  (is (= '(do
            (def macros-user-validation
              (s/keys :req [:foo/bar]
                      :opt [:bar/baz]))
            (def macros-user-schema map?)
            (def macros-user-definition
              {:schema pod/macros-user-schema
               :validation pod/macros-user-validation}))
         (macroexpand-1 `(defentity macros/user
                           (~'validation
                             (~'s/keys :req [:foo/bar]
                                       :opt [:bar/baz]))
                           (~'schema ~'map?))))))

(deftest defentity-with-auth
  (is (= '(do
            (defn macros-user-auth
              [{:keys [foo bar]}]
              (println foo bar))
            (def macros-user-auth-query
              '[{:name foo :type :property}
                {:name bar :type :property}])
            (def macros-user-schema map?)
            (def macros-user-definition
              {:auth pod/macros-user-auth
               :auth-query pod/macros-user-auth-query
               :schema pod/macros-user-schema}))
         (macroexpand-1 `(defentity macros/user
                           ~'(auth [foo bar]
                             (println foo bar))
                           ~'(schema map?))))))

(deftest defentity-with-auth-and-validation
  (is (= '(do
            (defn macros-user-auth
              [{:keys [foo bar]}]
              (println foo bar))
            (def macros-user-auth-query
              '[{:name foo :type :property}
                {:name bar :type :property}])
            (def macros-user-validation
              (s/keys :req-un [::foo ::bar]))
            (def macros-user-schema map?)
            (def macros-user-definition
              {:auth pod/macros-user-auth
               :auth-query pod/macros-user-auth-query
               :validation pod/macros-user-validation
               :schema pod/macros-user-schema}))
         (macroexpand-1 `(defentity macros/user
                           ~'(auth [foo bar]
                                   (println foo bar))
                           ~'(validation
                               (s/keys :req-un [::foo ::bar]))
                           ~'(schema map?))))))

Add code generation tests for the defentity macro


(ns server.name-bazaar.utils
  (:require
    [cljs.core.async :refer [<! go]]
    [cljs.test :refer-macros [async]]
    [cljs-time.coerce :refer [from-long]]
    [cljs-web3-next.eth :as web3-eth]
    [cljs-web3-next.evm :as web3-evm]
    [cljs-web3-next.helpers :as web3-helpers]
    [district.server.web3 :refer [web3]]
    [district.shared.async-helpers :refer [promise->]]
    [mount.core :as mount]
    [taoensso.timbre :as log]))

(def snapshot-id (atom ""))

(def namehash (aget (js/require "eth-ens-namehash") "hash"))
(def sha3 (comp (partial str "0x") (aget (js/require "js-sha3") "keccak_256")))

(defn now []
  (promise-> (web3-eth/get-block-number @web3)
             #(web3-eth/get-block @web3 % false)
             (fn [block]
               (let [block (web3-helpers/js->cljkk block)]
                 (from-long (* (:timestamp block) 1000))))))

(defn before-test []
  (async done
    (go
      (-> (mount/with-args
            {:web3            {:url        "ws://127.0.0.1:8549"
                               :on-online  #(log/warn "Ethereum node went online")
                               :on-offline #(log/warn "Ethereum node went offline")}
             :smart-contracts {:contracts-build-path "./resources/public/contracts-build/"
                               :contracts-var        #'name-bazaar.shared.smart-contracts/smart-contracts
                               :auto-mining?         true}})
          (mount/only [#'district.server.web3
                       #'district.server.smart-contracts/smart-contracts])
          (mount/start))
      (let [id (<! (web3-evm/snapshot @web3))]
        (swap! snapshot-id (fn [_] id)))
      (done))))

(defn after-test []
  (async done
    (go
      ;; we'd like to use cljs-web3-next.evm/revert here, but it's broken now as:
      ;; 1. evm_revert doesn't accept 0 arguments even if it should:
      ;;    https://github.com/trufflesuite/ganache-cli/issues/672
      ;; 2. evm_revert is a non-standard method not explicitly supported in web3js
      ;; 3. there's a validator expecting by default any non-standard method to have 0 args
      ;; so we need to go more low level
      (js-invoke (aget @web3 "currentProvider")
                 "send"
                 (clj->js {:jsonrpc "2.0",
                           :method "evm_revert",
                           :params [@snapshot-id],
                           :id 1})
                 (fn [err _]
                   (if err (throw (js/Error. "Error evm_revert-ing to snapshot" err)))
                   (mount/stop)
                   (js/setTimeout #(done) 500))))))

Use snapshots to clear chain before test

Before, deployer was used to clear test blockchain state
before each test. Deployer is now gone, replaced with
truffle. I found it much faster to use ganache snapshotting
before / after each test, than to call truffle migrate.