(ns riemann.victorops-test
  (:use riemann.victorops
        clojure.test)
  (:require [riemann.logging :as logging]))

(def api-key (System/getenv "VICTOROPS_API_KEY"))
(def routing-key (System/getenv "VICTOROPS_ROUTING_KEY"))

(when-not api-key
  (println "export VICTOROPS_API_KEY=\"...\" to run these tests."))

(when-not routing-key
  (println "export VICTOROPS_ROUTING_KEY=\"...\" to run these tests."))

(logging/init)

(deftest ^:victorops ^:integration test-info
  (let [vo (victorops api-key routing-key)]
    ((:info vo) {:host "localhost"
                :service "victorops info notification"
                :metric 42
                :state "info"})))

(deftest ^:victorops ^:integration test-recovery
  (let [vo (victorops api-key routing-key)]
    ((:recovery vo) {:host "localhost"
                    :service "victorops recovery notification"
                    :metric 0.5
                    :state "ok"})))

(deftest ^:victorops ^:integration test-warning
  (let [vo (victorops api-key routing-key)]
    ((:warning vo) {:host "localhost"
                    :service "victorops warning notification"
                    :metric 0.5
                    :state "warning"})))

(deftest ^:victorops ^:integration test-critical
  (let [vo (victorops api-key routing-key)]
    ((:critical vo) {:host "localhost"
                    :service "victorops critical notification"
                    :metric 0.5
                    :state "critical"})))

Add an integration test for victorops

Add an integration test for victorops


(ns migrations.046-add-primary-keys-to-providers-and-work-tables
  "Adds primary keys to three database tables."
  (:require [config.mdb-migrate-helper :as h]))

(defn up
  "Migrates the database up to version 46."
  []
  (println "migrations.046-add-primary-keys-to-providers-and-work-tables up...")
  (h/sql "alter table providers drop constraint unique_provider_id")
  (h/sql "alter table providers add constraint providers_pk primary key (provider_id)")
  (h/sql (str "alter table sync_delete_work add constraint sync_delete_work_pk "
              "primary key (concept_id, revision_id)"))
  (h/sql (str "alter table get_concepts_work_area add constraint get_concepts_work_area_pk "
              "primary key (concept_id, revision_id)")))

(defn down
  "Migrates the database down from version 46."
  []
  (println "migrations.046-add-primary-keys-to-providers-and-work-tables down...")
  (h/sql "alter table providers drop constraint providers_pk")
  (h/sql (str "alter table providers add constraint unique_provider_id unique(provider_id) "
              "using index (create unique index provider_id_index on providers(provider_id))"))
  (h/sql "alter table sync_delete_work drop constraint sync_delete_work_pk")
  (h/sql "alter table get_concepts_work_area drop constraint get_concepts_work_area_pk"))

CMR-3050: Add primary keys to three metadata_db tables


(ns futura.executor-tests
  (:require [clojure.core.async :as a]
            [clojure.test :refer :all]
            [clojure.java.io :as io]
            [clojure.pprint :refer [pprint]]
            [futura.executor :as exec]))

(deftest iexecutor-tests
  (let [p (promise)]
    (exec/execute #(deliver p true))
    (is (deref p 1000 false)))

  (let [p (promise)]
    (exec/execute exec/*default* #(deliver p true))
    (is (deref p 1000 false))))

(deftest iexecutor-service-tests
  (let [p (exec/submit (fn []
                         (a/<!! (a/timeout 500))
                         true))]
    (is (deref p 1000 false)))
  (let [submit (partial exec/submit exec/*default*)
        p (submit (fn []
                    (a/<!! (a/timeout 500))
                    true))]
    (is (deref p 1000 false))))

Add tests for executor api.

Add tests for executor api.


(ns chazel.ids
  (:import (com.hazelcast.core HazelcastInstance IdGenerator)
           (com.hazelcast.flakeidgen FlakeIdGenerator)))

(defn safe-generator
  ^FlakeIdGenerator
  [^HazelcastInstance hz ^String gname]
  (.getFlakeIdGenerator hz gname))

(defn unsafe-generator ;; DEPRECATED
  ^IdGenerator
  [^HazelcastInstance hz ^String gname]
  (.getIdGenerator hz gname))

(defn new-id!
  "Given a hazelcast instance <hz> and IdGenerator name,
  returns a new ID. Uniqueness is controlled by the last
  argument and default to true. If you choose to pass false
  be aware that the underlying generator has been deprecated."
  (^long [hz]
   (new-id! hz "IDS" true))
  (^long [hz generator-name]
   (new-id! hz generator-name true))
  (^long [^HazelcastInstance hz generator-name flake?]
   (if flake?
     (.newId (safe-generator hz generator-name))
     (.newId (unsafe-generator hz generator-name)))))

(defn parse-flake-id
  "Parses a FlakeId into its 3 constituent parts."
  [^long n]
  (let [binary (Long/toBinaryString n)
        ts   (-> (subs binary 0 41)   ;; 41 bits - timestamp
                 (BigInteger. 2))
        sequ (-> (subs binary 41 47)  ;; 6 bits - sequence number
                 (BigInteger. 2))
        node (-> (subs binary 47 63)  ;; 16 bits - nodeID
                 (BigInteger. 2))]
    {:millis-since-1-1-2018 (long ts)
     :seq-no  (long sequ)
     :node-id (long node)}))

Add new namespace for id generation

Add new namespace for id generation


(ns comic-reader.database
  (:require [com.stuartsierra.component :as component]
            [datomic.api :as d]))

(def uri "datomic:dev://localhost:4334/comics")

(defrecord Database [uri conn]
  component/Lifecycle

  (start [component]
    (println "Comic-Reader: Connecting to database...")
    (let [uri (:uri component)
          do-seeds? (d/create-database uri)
          conn (d/connect uri)]
      ;; Conform database to schemas here

      ;; Add seeds if database was newly created
      ;; (when do-seeds?
      ;;   @(d/transact conn (seed/data)))
      (assoc component :conn conn)))

  (stop [component]
    (println "Comic-Reader: Disconnecting from database...")
    (dissoc component :conn)))

(defn new-database []
  (map->Database {}))

(defn get-conn [database]
  (or (:conn database)
      (when-let [uri (:uri database)]
        (d/connect uri))))

Add a basic datomic component

Add a basic datomic component


(ns vault.store-test
  (:require [clojure.test :refer :all]
            [vault.blob :as blob]
            [vault.store :refer :all]))

(deftest blob-containment
  (let [blobref (blob/hash-content :sha1 "foo bar")]
    (is (false? (contains-blob? (reify BlobStore (stat [this blobref] nil)) blobref)))
    (is (true? (contains-blob? (reify BlobStore (stat [this blobref] {:size 1})) blobref)))))

(deftest blobref-selection
  (let [a (blob/make-blobref :md5 "37b51d194a7513e45b56f6524f2d51f2")
        b (blob/make-blobref :md5 "73fcffa4b7f6bb68e44cf984c85f6e88")
        c (blob/make-blobref :md5 "73fe285cedef654fccc4a4d818db4cc2")
        d (blob/make-blobref :md5 "acbd18db4cc2f85cedef654fccc4a4d8")
        e (blob/make-blobref :md5 "c3c23db5285662ef7172373df0003206")
        blobrefs [a b c d e]]
    (are [brs opts] (= brs (select-blobrefs opts blobrefs))
         blobrefs {}
         [c d e]  {:start "md5:73fd2"}
         [b c]    {:prefix "md5:73"}
         [a b]    {:count 2})))

Add tests for ns vault.store.

Add tests for ns vault.store.


{:nodes
 {:comp
  {:name "calc-tnseq-fitness",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:comp [:prn1]}}

Add compare flow for tnseq

Add compare flow for tnseq


(ns io.cyanite.engine-test
  (:require [io.cyanite.engine          :as e]
            [com.stuartsierra.component :as component]
            [clojure.test               :refer :all]
            [io.cyanite.test-helper     :refer :all]))

(deftest engine-test
  (with-config
    {:engine (component/using (e/map->Engine {:rules {"default" ["5s:1h"]}}) [:drift
                                                                              :queues
                                                                              :writer])}
    (let [engine    (:engine *system*)
          clock     (:clock *system*)
          writer    (:writer *system*)
          base-time 1454877020]
      (doseq [i (range 0 6)]
        (set-time! clock (* (+ base-time i) 1000))
        (e/accept! engine {:path "a.b.c" :metric i :time (+ base-time i)}))

      (let [[res] @writer]
        (is (= "a.b.c" (:path res)))
        (is (= 2.0 (:mean res)))
        (is (= 10 (:sum res)))
        (is (= 4 (:max res)))
        (is (= 0 (:min res)))
        (is (= base-time (:time res)))))))

Implement initial simplistic engine test


(ns clojars.main
  (:require [clojars.scp]
            [ring.adapter.jetty :refer [run-jetty]]
            [clojars.web :refer [clojars-app]]
            [clojars.promote :as promote]
            [clojars.config :refer [config configure]]
            [clojure.tools.nrepl.server :as nrepl])
  (:import com.martiansoftware.nailgun.NGServer
           java.net.InetAddress)
  (:gen-class))

(defn start-jetty []
  (when-let [port (:port config)]
    (println "clojars-web: starting jetty on" (str "http://" (:bind config) ":" port))
    (run-jetty #'clojars-app {:host (:bind config)
                            :port port
                            :join? false})))

(defn start-nailgun []
  (when-let [port (:nailgun-port config)]
    (println "clojars-web: starting nailgun on" (str (:nailgun-bind config) ":" port))
    (.run (NGServer. (InetAddress/getByName (:nailgun-bin config)) port))))

(defn -main [& args]
  (configure args)
  (start-jetty)
  (nrepl/start-server :port (:nrepl-port config) :bind "127.0.0.1")
  (start-nailgun))

; (defonce server (run-jetty #'clojars-app {:port 8080 :join? false}))

(ns clojars.main
  (:require [clojars.scp]
            [ring.adapter.jetty :refer [run-jetty]]
            [clojars.web :refer [clojars-app]]
            [clojars.promote :as promote]
            [clojars.config :refer [config configure]]
            [clojure.tools.nrepl.server :as nrepl])
  (:import com.martiansoftware.nailgun.NGServer
           java.net.InetAddress)
  (:gen-class))

(defn start-jetty []
  (when-let [port (:port config)]
    (println "clojars-web: starting jetty on" (str "http://" (:bind config) ":" port))
    (run-jetty #'clojars-app {:host (:bind config)
                            :port port
                            :join? false})))

(defn start-nailgun []
  (when-let [port (:nailgun-port config)]
    (println "clojars-web: starting nailgun on" (str (:nailgun-bind config) ":" port))
    (.run (NGServer. (InetAddress/getByName (:nailgun-bin config)) port))))

(defn -main [& args]
  (alter-var-root #'*read-eval* (constantly false))
  (configure args)
  (start-jetty)
  (nrepl/start-server :port (:nrepl-port config) :bind "127.0.0.1")
  (start-nailgun))

; (defonce server (run-jetty #'clojars-app {:port 8080 :join? false}))

Work around dangerous default behaviour of Clojure.


(ns grade-school)

(defn grade []  ;; <- arglist goes here
    ;; your code goes here
)

(defn add []  ;; <- arglist goes here
    ;; your code goes here
)

(defn sorted []  ;; <- arglist goes here
    ;; your code goes here
)

Add stub for grade-school exercise

Add stub for grade-school exercise


(ns mdr2.pipeline1
  (:use [clojure.java.shell :only [sh]])
  (:require [clojure.string :as s]))

(defn validate [file]
  (sh "daisy-pipeline"
      "/usr/lib/daisy-pipeline/scripts/verify/ConfigurableValidator.taskScript"
      (str "--validatorInputFile=" file)
      ;; make sure it has to be a DTBook file
      "--validatorRequireInputType=Dtbook document"
      ;; make sure files with a missing DOCTYPE declaration do not validate
      "--validatorInputDelegates=org.daisy.util.fileset.validation.delegate.impl.NoDocTypeDeclarationDelegate"))

(defn audio-encoder [dtb output-dir bitrate]
  (apply sh "daisy-pipeline"
         "/usr/lib/daisy-pipeline/scripts/modify_improve/dtb/DTBAudioEncoder.taskScript"
         (map (fn [[k v]] (format "--%s=%s" (name k) v))
              {:input dtb :output output-dir :bitrate bitrate})))

(defn filter-output [lines]
  (map #(s/trim (s/replace % "[ERROR, Validator]" ""))
       (filter #(re-matches #"^\[ERROR, Validator\].*" %)
               (s/split-lines lines))))

Add code to interface with DAISY pipeline


(ns test-compile
  (:use [clojure.test]
        [clojure.contrib.java-utils :only [delete-file-recursively file]]
        [clojure.contrib.shell-out :only [with-sh-dir sh]]))

(deftest test-compile
  (delete-file-recursively (file "sample" "classes" "nom") true)
  (with-sh-dir "sample"
    (sh "lein" "compile"))
  (is (.exists (file "sample" "classes" "nom" "nom" "nom.class"))))

Add a test for the compile task.

Add a test for the compile task.


(ns clojure-walkthrough.cjia.ch06_xx
  (:require [clojure.data.json :as json]
            [clojure.xml :as xml-core])
  (:gen-class))

;; 6.4.1: creating refs
(def all-users (ref {}))

(deref all-users) ;; {}

@all-users ;; {}

all-users ;; #ref[{:status :ready, :val {}} 0x7c93b91f]

;; 6.4.2: mutating refs with ref-set
;(ref-set all-users {}) ; IllegalStateException

(dosync
 (ref-set all-users {})) ;; {}

;; Alter: (alter ref function & args)

(defn new-user [id login monthly-budget]
  {:id id
   :login login
   :monthly-budget monthly-budget
   :total-expensives 0})

;; Let's add something to this user
(defn add-new-user [login budget-amount]
  (dosync
   (let [current-number (count @all-users)
         user (new-user (inc current-number) login budget-amount)]
     (alter all-users assoc login user))))

(add-new-user "amit" 100000) ;; {"amit" {:id 2, :login "amit", :monthly-budget 100000, :total-expensives 0}}

(add-new-user "deepthi" 200000) ;; {"amit" {:id 2, :login "amit", :monthly-budget 100000, :total-expensives 0}, "deepthi" {:id 3, :login "deepthi", :monthly-budget 200000, :total-expensives 0}}

;; 6.5 Agents
(def total-cpu-time (agent 0))

(deref total-cpu-time) ;; 0

@total-cpu-time ;; 0

;; Mutating agents
; (send the-agent the-function & more-args)

(send total-cpu-time + 700) ;; #agent[{:status :ready, :val 1400} 0x76768bd0]

(deref total-cpu-time) ;; 700

;; Send off: (send-off the-agent the-function & more-args)

;; 6.5.3: Working with agents
; await and wait-for: (await & the-agents)

;; Agent errors
(def bad-agent (agent 10))

;(send bad-agent / 0) ;; divided by zero

(deref bad-agent)  ;; 10

;(send bad-agent / 2) ;; still get arror

(agent-error bad-agent)

(let [e (agent-error bad-agent)
      st (.getStackTrace e)]
  (println (.getMessage e))
  (println (clojure.string/join "\n" st)))

(clear-agent-errors bad-agent) ;; agent is now ready for more actions

Add examples from chapter 6

Add examples from chapter 6


(ns grafter.sequences-test
  (:require [clojure.test :refer :all]
            [grafter.sequences :refer :all]))

(deftest column-names-seq-test
  (testing "iterates alphabet repeatedly like it's numeric"
    (is  (= ["A" "B" "AA" "AB" "BA" "BB" "AAA" "AAB"]
            (take 8 (column-names-seq "AB"))))))

Test for column name generator.

Test for column name generator.


(ns re-demo.utils
  (:require [re-com.core     :refer [title]]
            [reagent.core    :as    reagent]))

(def panel-title-style {
    :font-family "Ubuntu"
    :font-weight "300"
    ;; :font-style  "bold"
    :font-size   "24px"
    :color       "#FF6522"    ;; orange
    :margin-top  "7px"
   })

(defn panel-title
  "The text shown at the top of each Tab Panel"
  [text]
  [title
    :label      text
    :underline? false
    :style      panel-title-style
    ])

(defn component-title
  "Used when you want a notes title like [something ... ]"
  [component-name style]
  [title
   :h          :h4   ;; [:h4 .. ]
   :label      component-name
   :style      (merge style {:color "#555"})
   :underline? false
   ])

Add utilities for showing titles

Add utilities for showing titles


(ns caesium.byte-bufs-benchmark
  (:require [caesium.crypto.secretbox :as sb]
            [caesium.crypto.secretbox-test :as st]
            [caesium.byte-bufs :as bb]
            [criterium.core :refer [bench]]
            [clojure.test :refer [deftest]]))

(defn secretbox-easy-wrap-byte-array
  [m n k]
  (let [c (byte-array (+ sb/macbytes (bb/buflen m)))]
    (sb/secretbox-easy-to-buf!
     (bb/->indirect-byte-buf c)
     (bb/->indirect-byte-buf m)
     (bb/->indirect-byte-buf n)
     (bb/->indirect-byte-buf k))
    c))

(defn secretbox-easy-unwrap-byte-buf
  [m n k]
  (let [c (bb/alloc (+ sb/macbytes (bb/buflen m)))]
    (sb/secretbox-easy-to-buf!
     c
     (bb/->indirect-byte-buf m)
     (bb/->indirect-byte-buf n)
     (bb/->indirect-byte-buf k))
    (bb/->bytes c)))

(deftest ^:benchmark wrap-byte-array
  (bench (secretbox-easy-wrap-byte-array st/ptext st/n0 st/secret-key)))

(deftest ^:benchmark unwrap-byte-buf
  (bench (secretbox-easy-unwrap-byte-buf st/ptext st/n0 st/secret-key)))

Add benchmarks for different byte buf strategies


Add test case for cljam.cigar

Add test case for cljam.cigar


(ns icecap.handlers.http-test
  (:require [clojure.core.async :as a]
            [manifold.deferred :as d]
            [icecap.handlers.core :refer [execute]]
            [icecap.handlers.http]
            [aleph.http :as h]
            [clojure.test :refer :all]))

(def step
  {:type :http :url "http://www.example.com"})

(def fake-response
  {})

(defn fake-request
  [_]
  (d/success-deferred fake-response))

(deftest execute-tests
  (with-redefs
    [h/request fake-request]
    (is (let [ch (execute step)
              [result] (a/<!! (a/into [] ch))]
          (= result fake-response)))))

Write a basic unit test for the http handler

Refs #14.


(ns koeeoadi.emacs-helpers)

(defn plist-to-map [plist]
  (let [plist-to-map' (fn [x]
                        (if (coll? x)
                          (into {} (mapv #(into [] %) (partition 2 2 x)))
                          x))]
    (vec (reverse (mapv plist-to-map' plist)))))

Move emacs helpers to clj folder

Move emacs helpers to clj folder


{:dev
 {:dependencies [[org.clojure/tools.namespace "0.2.11"]
                 [criterium "0.4.3"]]
  :source-paths ["dev"]
  :codeina {:sources ["src"]
            :reader :clojure
            :target "doc/dist/latest/api"
            :src-uri "http://github.com/funcool/cats/blob/master/"
            :src-uri-prefix "#L"}
  :plugins [[funcool/codeina "0.3.0-SNAPSHOT"]
            [lein-ancient "0.6.7" :exclusions [org.clojure/tools.reader]]]}
 :bench
 [:dev
  {:main ^:skip-aot benchmarks
   :jvm-opts ^:replace []}]}

{:dev
 {:dependencies [[org.clojure/tools.namespace "0.2.11"]
                 [criterium "0.4.3"]]
  :source-paths ["dev"]
  :codeina {:sources ["src"]
            :reader :clojure
            :target "doc/dist/latest/api"
            :src-uri "http://github.com/funcool/cats/blob/master/"
            :src-uri-prefix "#L"}
  :plugins [[funcool/codeina "0.3.0"]
            [lein-ancient "0.6.7" :exclusions [org.clojure/tools.reader]]]}
 :bench
 [:dev
  {:main ^:skip-aot benchmarks
   :jvm-opts ^:replace []}]}

Update codeina plugin version to 0.3.0.

Update codeina plugin version to 0.3.0.


;; Copyright 2015 Andrey Antukh <niwi@niwi.nz>
;;
;; 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 continuo.util.codecs
  (:require [taoensso.nippy :as nippy]))

(defn data->bytes
  "Serialize a clojure data into a binary format."
  [data]
  (nippy/freeze data))

(defn bytes->data
  "Deserialize bytes into clojure data structures."
  [input]
  (nippy/thaw input))

Add lightweight abstraction for data encoding with nippy.


(ns ^{:doc "JUnit formatter for Midje that keeps original stdout output."}
  midje.emission.plugins.junit.with-default
  (:require [midje.emission.plugins.junit :as junit]
            [midje.emission.plugins.default :as default]
            [midje.emission.state :as state]))

(defn merge-functions [oldf newf]
  (fn [& args]
    (apply oldf args)
    (apply newf args)))

(def emission-map (merge-with merge-functions
                              default/emission-map
                              junit/emission-map))

(state/install-emission-map emission-map)

Add a 'junit-with-default' emission plugin.

It creates both the junit reports and the default stdout.


(ns figwheel-sidecar.components.css-watcher
  (:require
   [figwheel-sidecar.components.file-system-watcher :as fsw]
   [figwheel-sidecar.utils :as utils]
   [figwheel-sidecar.components.figwheel-server :as fig]))

(defn make-css-file [path]
  { :file (utils/remove-root-path path)
    :type :css } )

(defn send-css-files [figwheel-server files]
  (fig/send-message figwheel-server
                    ::fig/broadcast
                    { :msg-name :css-files-changed
                      :files files}))

(defn handle-css-notification [watcher files]
  (when-let [changed-css-files (not-empty (filter #(.endsWith % ".css") (map str files)))]
    (let [figwheel-server (:figwheel-server watcher)
          sendable-files (map #(make-css-file %) changed-css-files)]
      (send-css-files figwheel-server sendable-files)
      (doseq [f sendable-files]
        (println "sending changed CSS file:" (:file f))))))

(defn css-watcher [{:keys [watch-paths] :as options}]
  (fsw/map->FileSystemWatcher (merge {:watcher-name "CSS Watcher"
                                      :notification-handler #'handle-css-notification} options)))

(ns figwheel-sidecar.components.css-watcher
  (:require
   [figwheel-sidecar.components.file-system-watcher :as fsw]
   [figwheel-sidecar.utils :as utils]
   [figwheel-sidecar.components.figwheel-server :as fig]))

(defn make-css-file [path]
  { :file (utils/remove-root-path path)
    :type :css } )

(defn send-css-files [figwheel-server files]
  (fig/send-message figwheel-server
                    ::fig/broadcast
                    { :msg-name :css-files-changed
                      :files files}))

(defn handle-css-notification [watcher files]
  (when-let [changed-css-files (not-empty (filter #(.endsWith % ".css") (map str files)))]
    (let [figwheel-server (:figwheel-server watcher)
          sendable-files (map #(make-css-file %) changed-css-files)]
      (send-css-files figwheel-server sendable-files)
      (doseq [f sendable-files]
        (println "sending changed CSS file:" (:file f))))))

(defn css-watcher [{:keys [watch-paths] :as options}]
  (fsw/file-system-watcher (merge {:watcher-name "CSS Watcher"
                                   :notification-handler #'handle-css-notification} options)))

Create FileSystemWatcher with constructor fn


(ns refactor-nrepl.find-unbound
  (:require [clojure.set :as set]
            [clojure.tools.analyzer.ast :refer [nodes]]
            [refactor-nrepl
             [analyzer :refer [ns-ast]]
             [util :refer :all]]))

(defn find-unbound-vars [{:keys [file line column]}]
  {:pre [(number? line)
         (number? column)
         (not-empty file)]}
  (throw-unless-clj-file file)
  (let [content (slurp file)
        ast (ns-ast content)
        sexp (get-enclosing-sexp content (dec line) column)
        selected-sexp-node (->> ast
                                (top-level-form-index line column)
                                (nth ast)
                                nodes
                                (filter (partial node-at-loc? line column))
                                (filter (partial node-for-sexp? sexp))
                                last)]
    (into '() (set/intersection (->> selected-sexp-node :env :locals keys set)
                                (->> selected-sexp-node
                                     nodes
                                     (filter #(= :local (:op %)))
                                     (map :form)
                                     set)))))

(ns refactor-nrepl.find-unbound
  (:require [clojure.set :as set]
            [clojure.tools.analyzer.ast :refer [nodes]]
            [refactor-nrepl
             [analyzer :refer [ns-ast]]
             [util :refer :all]]))

(defn find-unbound-vars [{:keys [file line column]}]
  {:pre [(number? line)
         (number? column)
         (not-empty file)]}
  (throw-unless-clj-file file)
  (let [content (slurp file)
        ast (ns-ast content)
        sexp (get-enclosing-sexp content (dec line) (dec column))
        selected-sexp-node (->> ast
                                (top-level-form-index line column)
                                (nth ast)
                                nodes
                                (filter (partial node-at-loc? line column))
                                (filter (partial node-for-sexp? sexp))
                                last)]
    (into '() (set/intersection (->> selected-sexp-node :env :locals keys set)
                                (->> selected-sexp-node
                                     nodes
                                     (filter #(= :local (:op %)))
                                     (map :form)
                                     set)))))

Fix off by one error in find-unbound

Fix off by one error in find-unbound

Input to find-unbound is indexed from 1 1, get-enclosing-sexp is indexed
from 0 0.


(defproject finagle-clojure "0.1.0"
  :description "A light wrapper around Finagle for Clojure"
  :url "https://github.com/twitter/finagle-clojure"
  :license {:name "Apache License, Version 2.0"
            :url "https://www.apache.org/licenses/LICENSE-2.0"}
  :dependencies [[finagle-clojure/core "0.1.0"]
                 [finagle-clojure/thrift "0.1.0"]]
  :plugins [[lein-sub "0.3.0"]
            [codox "0.8.10"]
            [lein-midje "3.1.3"]]
  :sub ["core" "thrift"]
  :codox {:sources ["core/src" "thrift/src"]
          :defaults {:doc/format :markdown}
          :output-dir "doc/codox"
          :src-dir-uri "http://github.com/samn/finagle-clojure/blob/v0.1.0"
          :src-linenum-anchor-prefix "L"})

(defproject finagle-clojure "0.1.0"
  :description "A light wrapper around Finagle for Clojure"
  :url "https://github.com/twitter/finagle-clojure"
  :license {:name "Apache License, Version 2.0"
            :url "https://www.apache.org/licenses/LICENSE-2.0"}
  :dependencies [[finagle-clojure/core "0.1.0"]
                 [finagle-clojure/thrift "0.1.0"]]
  :plugins [[lein-sub "0.3.0"]
            [codox "0.8.10"]
            [lein-midje "3.1.3"]]
  :sub ["core" "thrift"]
  :codox {:sources ["core/src" "thrift/src"]
          :defaults {:doc/format :markdown}
          :output-dir "doc/codox"
          :src-dir-uri "http://github.com/samn/finagle-clojure/blob/v0.1.0/"
          :src-linenum-anchor-prefix "L"})

Fix codox src-dir-uri for 0.1.0

Fix codox src-dir-uri for 0.1.0


(ns berry.formatting)

(defn- indent-with
[character width]
  (apply str (repeat width character)))

(def tab (partial indent-with "\t"))

(def space (partial indent-with " "))

(defn indent
[text {apply-indentation :indent-style
  indent-size :indent-size
  level :level}]
(let [width (* indent-size level)]
    (str (apply-indentation width) text)))

Create functions for handling indentation.


(ns main)

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

(println "SOMA =" (main))

Solve Simple Sum in clojure

Solve Simple Sum in clojure


(ns uxbox.repo
  "A main interface for access to remote resources."
  (:refer-clojure :exclude [do])
  (:require [postal.client :as ps]
            [beicon.core :as rx]))

(def ^:private ^:const +client+
  "https://test.uxbox.io")

(defn novelty
  [type data]
  (rx/from-promise
   (ps/novelty +client+ type data)))

(defn query
  ([type]
   (rx/from-promise
    (ps/query +client+ type)))
  ([type data]
   (rx/from-promise
    (ps/query +client+ type data))))

(defmulti -do
  (fn [type data] type))

(defn do
  "Perform a side effectfull action accesing
  remote remote resources."
  ([type]
   (-do type nil))
  ([type data]
   (-do type data)))

;; (defmethod do :login
;;   [type data]
;;   (rx/from-promise
;;    (ps/novelty :login data)))

(defmethod -do :login
  [type data]
  (->> (rx/of {:fullname "Cirilla Fiona"
               :photo "/images/favicon.png"
               :username "cirilla"
               :email "cirilla@uxbox.io"})
       (rx/delay 100)))

Add initial approach for client-server communication.


(ns jungerer.io-test
  (:require [clojure.test :refer :all]
            [clojure.java.io :as io]
            [jungerer.graph :as g]
            [jungerer.io :refer :all]))

(def sample-pairs-f (io/resource "sample.pairs"))

(deftest load-pairs!-test
  (testing "returns nil if loading is succeeded"
    (is (nil? (load-pairs! sample-pairs-f (g/directed-graph))))))

Add a test for jungerer.io/load-pairs!

Add a test for jungerer.io/load-pairs!


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

(deftest permuted-byte-types-test
  (is (= '[[^long ^{size_t {}} crypto_secretbox_keybytes []]]
         (#'b/permuted-byte-types
          '[^long ^{size_t {}} crypto_secretbox_keybytes []]))))

Test that we can correctly permute byte types


(ns useful.string-test
  (:use useful.string clojure.test))

(deftest to-camel
  (are [in out] (= out (camelize in))
       "the-string" "theString"
       "this-is-real" "thisIsReal"
       "untouched" "untouched"))

(deftest from-camel
  (are [in dashed underscored] (= [dashed underscored]
                                  ((juxt dasherize underscore) in))
       "setSize"          "set-size"         "set_size"
       "theURL"           "the-url"          "the_url"
       "ClassName"        "class-name"       "class_name"
       "LOUD_CONSTANT"    "loud-constant"    "loud_constant"
       "the_CRAZY_train"  "the-crazy-train"  "the_crazy_train"
       "with-dashes"      "with-dashes"      "with_dashes"
       "with_underscores" "with-underscores" "with_underscores"))

Add tests for dasherize & co

Add tests for dasherize & co


(ns postal.core-tests
  (:require [cljs.test :as t]
            [cats.core :as m]
            [promesa.core :as p]
            [beicon.core :as s]
            [postal.core :as pc]
            [postal.socket :as ps]))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defn to-promise
  [ob]
  {:pre [(s/observable? ob)]}
  (let [s (s/take 1 ob)]
    (p/promise (fn [resolve reject]
                 (s/subscribe s #(resolve %) #(reject %) (constantly nil))))))

(defn send-handshake
  ([sock]
   (send-handshake sock :hello))
  ([sock type]
   (let [busin (:busin sock)
         busout (:busout sock)
         result-frame (case type
                        :error {:cmd :error :data {:message "Unexpected"}}
                        :hello {:cmd :hello})]
     (m/mlet [hello-frame (to-promise busout)
              :let [hello-frame (pc/frame-decode hello-frame)]]

       (assert (= (:cmd hello-frame) :hello))
       (s/push! busin {:type :socket/message
                       :payload(pc/frame-encode result-frame)})))))

(defn make-client
  []
  (let [busin (s/bus)
        busout (s/bus)
        sock (ps/fake-websocket busin busout)
        client (pc/client sock)]
    [busin busout sock client]))

(t/deftest error-on-handshake-test
  (t/async done
    (let [[busin busout sock client] (make-client)]
      (m/mlet [_ (send-handshake sock :error)]
        (t/is (pc/closed? client))
        (done))
      (s/push! busin {:type :socket/open}))))

(t/deftest query-frame-success-test
  (t/async done
    (let [[busin busout sock client] (make-client)]
      (m/mlet [frame (send-handshake sock)
               result (pc/query client "/foobar")]
        (t/is (= (:data result) "foobar"))
        (done))

      (s/push! busin {:type :socket/open})
      (m/mlet [frame (to-promise busout)
               :let [frame (pc/frame-decode frame)]]
        (s/push! busin {:type :socket/message
                        :payload (pc/frame-encode
                                  {:cmd :response
                                   :id (:id frame)
                                   :data "foobar"})}))
      )))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initial Setup & Entry Point
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(enable-console-print!)

(defmethod t/report [:cljs.test/default :end-run-tests]
  [m]
  (if (t/successful? m)
    (set! (.-exitCode js/process) 0)
    (set! (.-exitCode js/process) 1)))

(set! *main-cli-fn* #(t/run-tests))

Add two initial tests for handshake and query response.


(ns riemann.slack-test
  (:use riemann.slack
        clojure.test)
  (:require [riemann.logging :as logging]))

(def api-key (System/getenv "SLACK_API_KEY"))
(def room (System/getenv "SLACK_ALERT_ROOM"))
(def account (System/getenv "SLACK_ALERT_ACCOUNT"))
(def user "Riemann_Slack_Test")

(when-not api-key
  (println "export SLACK_API_KEY=\"...\" to run these tests."))

(when-not room
  (println "export SLACK_ALERT_ROOM=\"...\" to run these tests."))

(when-not account
  (println "export SLACK_ALERT_ACCOUNT=\"...\" to run these tests."))

(logging/init)

(deftest ^:slack test_event
  (let [slack_connect (slack account api-key user room)]
    (slack_connect {:host "localhost"
         :service "good event test"
         :description "Testing slack.com alerts from riemann"
         :metric 42
         :state "ok"})))

(ns riemann.slack-test
  (:use riemann.slack
        clojure.test)
  (:require [riemann.logging :as logging]))

(def api-key (System/getenv "SLACK_API_KEY"))
(def room (System/getenv "SLACK_ALERT_ROOM"))
(def account (System/getenv "SLACK_ALERT_ACCOUNT"))
(def user "Riemann_Slack_Test")

(when-not api-key
  (println "export SLACK_API_KEY=\"...\" to run these tests."))

(when-not room
  (println "export SLACK_ALERT_ROOM=\"...\" to run these tests."))

(when-not account
  (println "export SLACK_ALERT_ACCOUNT=\"...\" to run these tests."))

(logging/init)

(deftest ^:slack ^:integration test_event
  (let [slack_connect (slack account api-key user room)]
    (slack_connect {:host "localhost"
                    :service "good event test"
                    :description "Testing slack.com alerts from riemann"
                    :metric 42
                    :state "ok"})))

Mark slack tests as integration

Mark slack tests as integration


(ns clj-gatling.perf-test
  (:require [clj-gatling.core :as gatling])
  (:gen-class))

(defn- create-scenario [url]
  {:name "Test scenario"
   :requests [{:name "Request" :http url}]})

(defn run-simulation [url users]
  (gatling/run-simulation [(create-scenario url)] users {:root "tmp"}))

Add manual performance test to be run from REPL


(ns cmr.bootstrap.migrations.002-update-quartz-to-2-2-2
  (:require [clojure.java.jdbc :as j]
            [config.migrate-config :as config]))

(defn up
  "Migrates the database up to version 2. Adds a column needed for Quartz 2.2.0 and higher."
  []
  (println "migrations.002-update-quartz-to-2-2-2 up...")
  (j/db-do-commands (config/db)
                    "ALTER TABLE QRTZ_FIRED_TRIGGERS ADD SCHED_TIME NUMBER(13) DEFAULT 0 NOT NULL"))

(defn down
  "Migrates the database down from version 2."
  []
  (println "migrations.002-update-quartz-to-2-2-2 down...")
  (j/db-do-commands (config/db) "ALTER TABLE QRTZ_FIRED_TRIGGERS DROP COLUMN SCHED_TIME"))

Add bootstrap quartz table migration

CMR-2173: Add bootstrap quartz table migration


(ns bejeweled-bot.solver)
(use 'bejeweled-bot.gems)

(defn solve
  "puikula"
  [gem-array]
  (map-indexed
  (fn [colIdx col]
    (map-indexed
      (fn [rowIdx item]
        (check-matches colIdx rowIdx item))
      col))
  gem-array))

(defn check-matches [x y gem-type]
  ())

(def testArray
  [[:ruby        :opal     :ruby       :diamond    :topaz    :amethyst   :sapphire :sapphire]
   [:ruby        :diamond  :amethyst   :diamond    :opal     :smaragdine :sapphire :smaragdine]
   [:topaz       :sapphire :smaragdine :topaz      :opal     :diamond    :amethyst :ruby]
   [:sapphire    :opal     :sapphire   :topaz      :sapphire :smaragdine :ruby     :ruby]
   [:amethyst    :opal     :diamond    :sapphire   :amethyst :ruby       :opal     :opal]
   [:topaz       :opal     :amethyst   :smaragdine :amethyst :topaz      :sapphire :amethyst]
   [:smaragdine  :opal     :opal       :opal       :sapphire :ruby       :amethyst :sapphire]
   [:amethyst    :opal     :diamond    :amethyst   :diamond  :topaz      :opal     :opal]])

(solve testArray)

Add basic structure and an example field


(ns scrabble-score)

(defn score-letter [] ;; <- Arglist goes here
      ;; your code goes here
      )

(defn score-word [] ;; <- Arglist goes here
  ;; your code goes here
  )

Add stub for scrabble score

Add stub for scrabble score


(ns braid.base.server.cqrs-fx
  "Namespace that collects common CQRS command fx"
  (:require
    [braid.base.server.socket :as socket]
    [braid.core.server.sync-helpers :as helpers]
    [braid.core.server.db :as db]))

(def run-txns! db/run-txns! )

(def chsk-send! socket/chsk-send!)

(def group-broadcast! helpers/broadcast-group-change)

Add namespace for common command fx

Add namespace for common command fx


(ns dataframe.pipeline-test
  (:require [dataframe.core :refer :all]
            [expectations :refer [expect]]))

(expect (frame {:a [1 2 3]
                :b [10 20 30]
                :c [6 7 8]
                :d [16 27 38]})
        (with-> (frame {:a [1 2 3] :b [10 20 30]})
                (assoc-col :c (add $a 5))
                (assoc-col :d (add $b $c))))

(expect (frame {:c [3 6] :b [2 4] :a [1 2]} [:x :y])
        (let [df (frame [[:x {:a 1 :b 2}]
                         [:y {:a 2 :b 4}]
                         [:z {:a 3 :b 8}]])]
          (with-> df
                  (select (lte $a 2))
                  (assoc-col :c (add $a $b))
                  (sort-rows :c :b))))

Add test for complicated pipelines

Add test for complicated pipelines


(ns desdemona.query-test
  (:require
   [desdemona.query :as q]
   [clojure.test :refer [deftest is]]))

(deftest query-tests
  (is (= [{:ip "10.0.0.1"}]
         (q/query '(== (:ip entry) "10.0.0.1")
                  [{:ip "10.0.0.1"}]))))

Write the simplest test I can think of

Write the simplest test I can think of


{:nodes
 {:ph0
  {:name "wgseq-phase0",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:ph0 [:prn1]}}

Add job flow for wgset phase 0 processing


(ns photon.default-projs
  (:require [serializable.fn :as sfn]
            [photon.streams :as streams]))

(def stream-fn
  (sfn/fn [p n]
    (merge-with
     #(assoc %1 :total-events (+ (:total-events %1)
                                 (:total-events %2)))
     p
     {(:stream-name n)
      {:total-events 1}})))

(def default-projections
  [{:projection-name "__streams__"
    :stream-name "__all__"
    :language :clojure
    :reduction (pr-str stream-fn)
    :initial-value {}}])

(defn init-default-projs! [stm]
  (dorun (map #(apply streams/register-query!
                      stm
                      (vals
                       (select-keys % [:projection-name
                                       :stream-name :language
                                       :reduction :initial-value])))
              default-projections)))

Create file for default projections

Create file for default projections


{:nodes
 {:ph0
  {:name "tnseq-phase0-d",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:ph0 [:prn1]}}

Add phase-0d after all - manually made sample fqs can make use of this


(ns inet.data.dns.psl
  "Functions for interfacing with Mozilla Public Suffix List format files."
  (:refer-clojure :exclude [load])
  (:require [clojure.string :as str]
            [clojure.java.io :as io]
            [inet.data.dns :as dns])
  (:import [java.io Reader]))

(def ^:dynamic *default-psl-url*
  "URL of the default Mozilla Public Suffix List file."
  (str "http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/"
       "effective_tld_names.dat?raw=1"))

(defn load
  "Load a Mozilla Public Suffix List format file from the Reader `source`."
  [^Reader source]
  (letfn [(prefix? [^String s1 ^String s2] (.startsWith s2 s1))
          (ignorable? [s] (or (empty? s) (prefix? "//" s)))
          (convert [entry n rule]
            (let [prefix (-> entry (subs n) dns/domain)]
              [prefix rule]))
          (parse [entry]
            (condp prefix? entry
              "*." (convert entry 2 :wildcard)
              "!"  (convert entry 1 :exception)
                   (convert entry 0 :normal)))
          (step [[prefixes rules] entry]
            (let [[prefix rule] (parse entry)]
              [(conj prefixes prefix) (assoc rules prefix rule)]))]
    (->> (line-seq source) (map str/trim) (remove ignorable?)
         (reduce step [(dns/domain-set) {}]))))

(def ^:private memo-load
  (memoize
   (fn [url]
     (with-open [source (io/reader url)]
       (load source)))))

(defn lookup
  "Determine the E2LD of `domain` as specified by the PSL loaded in `psl`.
Uses the default PSL loaded from `*default-psl-url*` if `psl` is not provided."
  ([dom] (lookup (memo-load *default-psl-url*) dom))
  ([psl dom]
     (let [dom (dns/domain dom), [prefixes rules] psl]
       (when-let [prefix (->> dom (get prefixes) first)]
         (case (get rules prefix)
           :exception prefix
           :normal    (dns/domain-next dom prefix)
           :wildcard  (second (dns/domain-ancestors dom prefix)))))))

Add namespace for PSL loading and lookup.


(ns ^:figwheel-always randometer.core
    (:require
              [reagent.core :as reagent :refer [atom]]))

(enable-console-print!)

(println "Edits to this text should show up in your developer console.")

;; define your app data so that it doesn't get over-written on reload

(defonce app-state (atom {:text "Hello world!"}))

(defn hello-world []
  [:h1 (:text @app-state)])

(reagent/render-component [hello-world]
                          (. js/document (getElementById "app")))

(defn on-js-reload []
  ;; optionally touch your app-state to force rerendering depending on
  ;; your application
  ;; (swap! app-state update-in [:__figwheel_counter] inc)
)

(ns ^:figwheel-always randometer.core
    (:require
              [reagent.core :as reagent :refer [atom]]))

(enable-console-print!)

(def size [24 6])

(defn show-trial [x]
  (if x "●" "○"))

(defn trial []
  (> 0.5 (rand)))

(defn biased-trial [propensity]
  (> propensity (rand)))

(defn muted-trial [propensity memory]
  (if (> propensity (rand))
    (not memory)
    memory))

(defn biased-generator [n p]
  (repeatedly n #(biased-trial p)))

(defn muted-generator [n p]
  (letfn [(helper [previous]
            (lazy-seq
             (cons previous
                   (helper (muted-trial p previous)))))]
    (take n (helper (trial)))))

(defn puzzle [generator propensity]
  (partition (first size) (generator (apply * size) propensity)))

(defn shuffle-boards [boards]
  (zipmap (range) (shuffle (range (count boards)))))

;; define your app data so that it doesn't get over-written on reload

(defonce app-state (atom {:text "Hello world!"}))

(defn hello-world []
  [:h1 (:text @app-state)])

(reagent/render-component [hello-world]
                          (. js/document (getElementById "app")))

(defn on-js-reload []
  ;; optionally touch your app-state to force rerendering depending on
  ;; your application
  ;; (swap! app-state update-in [:__figwheel_counter] inc)
)

Implement the utility functions for generating puzzles


(ns mnist.core-simplified
    (:require
        [clojure.core.matrix :as mat]
        [cortex.optimise :as opt]
        [thinktopic.datasets.mnist :as mnist]
        [cortex.network :as net]))

(defn- mnist-labels
    [class-labels]
    (let [n-labels (count class-labels)
          labels (mat/zero-array [n-labels 10])]
        (doseq [i (range n-labels)]
            (mat/mset! labels i (nth class-labels i) 1.0))
        labels))

(defn train [network training-data training-labels]
    (let [n-epochs 1
          learning-rate 0.3
          momentum 0.1
          batch-size 10
          loss-fn (opt/quadratic-loss)
          optimizer (net/sgd-optimizer network loss-fn learning-rate momentum)]
        (net/train-network optimizer n-epochs batch-size training-data training-labels)))

(defn evaluate [network test-data test-labels]
    (let [[results score] (net/evaluate network test-data test-labels)
          label-count (count test-data)
          score-percent (float (/ score label-count))]
        (println (format "Score: %f [%d of %d]" score-percent score label-count))))

(defn run-experiment []
    (let [training-data  (map #(vec [%]) @mnist/data-store)
          training-labels (mnist-labels @mnist/label-store)
          test-data  (map #(vec [%]) @mnist/test-data-store)
          test-labels (mnist-labels @mnist/test-label-store)

          input-width (last (mat/shape training-data))
          output-width (last (mat/shape training-labels))
          hidden-layer-size 30

          network (net/sequential-network
                      [(net/linear-layer :n-inputs input-width :n-outputs hidden-layer-size)
                       (net/sigmoid-activation hidden-layer-size)
                       (net/linear-layer :n-inputs hidden-layer-size :n-outputs output-width)])]

        (println "Training...")
        (train network training-data training-labels)
        (println "Testing...")
        (evaluate network test-data test-labels)))

(defn -main []
    (run-experiment))

[examples/mnist] Add a more simplified version of mnist looking much like the scrabble example.


(ns riemann.mailgun-test
  (:require [riemann.mailgun :as mailgun]
            [clj-http.client :as client]
            [clojure.test :refer [deftest testing is are]]))

(defn- mock-post [result-atom email event]
  (with-redefs [client/post (fn [url opts]
                              (reset! result-atom
                                      (merge (:form-params opts)
                                             {:url url
                                              :basic-auth (:basic-auth opts)})))]
    (email event)))

(deftest mailgun-test
  (let [result-atom (atom {})
        sandbox "mail.relay"
        service-key "testkey"
        recipient "somedude@somewhere.com"
        default-body-result "At Wed Dec 31 16:02:03 PST 1969\ntest host testservice  (17)\nTags: []\nCustom Attributes: {}\n\n"
        default-subject-result "test host testservice"
        event {:service "testservice"
               :host "test host"
               :time 123
               :metric 17}
        mailer (mailgun/mailgun {:sandbox sandbox
                                 :service-key service-key})
        email (mailer recipient)]

    (testing "ensure the data posted to mailgun matches expectations"
      (mock-post result-atom email event)
      (are [key result] (= result (key @result-atom))
           :url (str "https://api.mailgun.net/v2/" sandbox "/messages")
           :basic-auth ["api" service-key]
           :from (str "Riemann <riemann@" sandbox ">")
           :to (list recipient)
           :subject default-subject-result
           :text default-body-result))

    (testing "ensure message overrides are used"
      (let [body-formatter-result "this is the body"
            body-formatter (fn [_] body-formatter-result)
            subject-formatter-result "this is the subject"
            subject-formatter (fn [_] subject-formatter-result)
            from-override "my-override@xanadu"
            mailer (mailgun/mailgun {:sandbox sandbox
                                     :service-key service-key}
                                    {:subject subject-formatter
                                     :body body-formatter
                                     :from from-override})
            email (mailer recipient)]
        (mock-post result-atom email event)
        (are [rkey result] (= result (rkey @result-atom))
           :subject subject-formatter-result
           :text body-formatter-result
           :from from-override)))

    (testing "ensure mailgun options are split out when given only one map"
      (let [from-override "my-override@xanadu"
            mailer (mailgun/mailgun {:sandbox sandbox
                                     :service-key service-key
                                     :from from-override})
            email (mailer recipient)]
        (mock-post result-atom email event)
        (is (= (:from @result-atom)
               from-override))))))

Add unit tests for mailgun output

Add unit tests for mailgun output


(ns in.co.sdslabs.slack-lens.lib.slack-rtm
  (:require [clj-slack.rtm :as rtm]
            [aleph.http :as http]
            [manifold.stream :as s]))

(defn- get-connection-map
  [url token]
  {:api-url url
   :token token})

(defn- get-rtm-ws-url
  [url token]
  (-> (get-connection-map url token)
      rtm/start
      :url))

(defn- get-rtm-ws-connection
  [url]
  (if-let [socket (try
                    @(http/websocket-client url)
                    (catch Exception e
                      nil))]
    socket
    nil))

(defn connect
  [url token]
  (let [ws-url (get-rtm-ws-url url token)
        conn (get-rtm-ws-connection ws-url)]
    @(s/take! conn)
    conn))

Add initial code for slack-rtm lib

Add initial code for slack-rtm lib


; This is the main interface to exntending core.matrix's protocols

(ns gpu.matrix
  (:require [clojure.core.matrix.protocols :as mp])
  (:import gpu.matrix.NDArray))

(extend-protocol mp/PImplementation
  NDArray
  (implementation-key [m] :gpu-matrix)
  (meta-info [m] {})
  (construct-matrix [m data]
    ; TODO
    (let [ndims (mp/dimensionality data)]
      ))
  (new-vector [m length]
    ; TODO
    )
  (new-matrix [m rows columns]
    ; TODO
    )
  (new-matrix-nd [m shape]
    ; TODO
    )
  (supports-dimensionality? [m dimensions]
    true))

Add simple wireframe for clojure protocol extensions


{:nodes
 {:ph1
  {:name "rnaseq-star-phase1",
   :type "tool",
   :args []}
  :prn1 {:type "func",
         :name "prn"}},
 :edges
 {:ph1 [:prn1]}}

Add STAR capable job flow

Add STAR capable job flow


;; Note: replace ch03-xx the right number
(ns clojure-walkthrough.cjia.ch05-xx
  (:require [clojure.data.json :as json]
            [clojure.xml :as xml-core])
  (:gen-class))

;; import java
(import 'java.util.Date 'java.text.SimpleDateFormat)

;; import more than one at a time from the same package
;; in this case from 'java.util'
(import '[java.util Date Set]) ;; java.util.Set

;; The recommended way is to to import into a namespace like
(ns clojure-walkthrough.cjia.ch05-xx
  (:import (java.util Set Date))
  (:import (java.text SimpleDateFormat)))

;; Now we can use them
(def sdf (new SimpleDateFormat "yyyy-MM-dd"))

;; Or alternatively, Clojure allow us to write something like
(def sdf (SimpleDateFormat. "yyyy-MM-dd"))

(defn date-from-date-string [date-string]
  (let [sdf (SimpleDateFormat. "yyyy-MM-dd")]
    (.parse sdf date-string)))

(date-from-date-string "2016-01-30") ;; #inst "2016-01-29T13:00:00.000-00:00"

;; Static Methods
(Long/parseLong "12321") ;; 12321

;; calling with (Classname/staticMethod args*)

;; Static Fields
(import '(java.util Calendar)) ;; java.util.Calendar

(Calendar/JANUARY) ;; 0

(Calendar/FEBRUARY) ;; 1

;; 5.1.4 Macros and the dot special form

(. System getenv "PATH")
(. System (getenv "PATH"))

;; Use of Java instance object
(import '(java.util Random)) ;; java.util.Random

(def rnd (Random.)) ;; #'clojure-walkthrough.cjia.ch05-xx/rnd

(. rnd (nextInt 10)) ;; 3 ;; result will vary
(. rnd (nextInt 10)) ;; 6 ;; result will vary

Add examples from chapter 5

Add examples from chapter 5


(ns roman-to-decimal.core)
(use ['clojure.string :only '(split)])

;;; This is a fairly messy implementation, since I have almost 0 expirence with
;;; clojure. Please forgive me then, and please leave a note if you have tips or
;;; comments.

(defn roman-to-decimal [roman]
  ;; Converts roman numbers represented as strings into decimal numbers

  (defn iter [acc decimal i]
    (if (= i (count decimal))
      acc
      (let [n (nth decimal i)
            nxt-i (+ i 1)
            nxt (nth decimal nxt-i 0)]

      (if (> nxt n)
        (iter (- acc n) decimal nxt-i)
        (iter (+ acc n) decimal nxt-i)))))

  (let [roman-map {"I" 1, "V" 5, "X" 10, "L" 50, "C" 100, "D" 500, "M" 1000}
        decimal (map roman-map (rest (split roman #"")))]
    (iter 0 decimal 0)))

Add naive clojure implementation - without validation.


;; 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 buddy.core.padding-tests
  (:require [clojure.test :refer :all]
            [buddy.core.codecs :as codecs]
            [buddy.core.bytes :as bytes]
            [buddy.core.padding :as padding]))

(deftest pkcs7-padding
  (let [data (byte-array 10)]
    (bytes/fill data 2)
    (padding/pad! data 6)

    (is (padding/padded? data))
    (is (= (padding/count data) 4))

    (padding/unpad! data)
    (is (= 4 (padding/count data :zerobyte)))))

(deftest tbc-padding
  (let [data (byte-array 10)]
    (bytes/fill data 2)
    (padding/pad! data 6 :tbc)

    (is (padding/padded? data :tbc))
    (is (= (padding/count data :tbc) 4))

    (padding/unpad! data :tbc)
    (is (= 4 (padding/count data :zerobyte)))))

(deftest zerobyte-padding
  (let [data (byte-array 10)]
    (bytes/fill data 2)
    (padding/pad! data 6 :zerobyte)

    (is (padding/padded? data :zerobyte))
    (is (= (padding/count data :zerobyte) 4))

    (padding/unpad! data :zerobyte)
    (is (= 4 (padding/count data :zerobyte)))))

Add tests for padding implementation.

Add tests for padding implementation.


(ns riemann.campfire
  "Forwards events to Campfire"
  (:use [clojure.string :only [join]])
  (:require [clj-campfire.core :as cf]))

(defn cf-settings
  "Setup settings for campfire. Required information is your api-token, ssl connection
  true or false, and your campfire sub-domain."
  [token ssl sub-domain]
  {:api-token token, :ssl ssl, :sub-domain sub-domain})

(defn room
  "Sets up the room to send events too. Pass in the settings created with cf-settings
  and the room name"
  [settings room-name]
  (cf/room-by-name settings room-name))

(defn campfire
  "Creates an adaptor to forward events to campfire.
  TODO: write more here once the event formatting is better.
  TODO: tests
  Tested with:
  (streams
    (by [:host, :service]
      (let [camp (campfire \"token\", true, \"sub-domain\", \"room\")]
        camp)))"
  [token ssl sub-domain room-name]
  (fn [e]
   (let [string (str (join " " ["HOST:" (str (:host e)) "SERVICE:" (str (:service e)) "STATE:" (str (:state e)) "DESC:" (str (:description e))]))]
   (cf/message (room (cf-settings token ssl sub-domain) room-name) string))))

(ns riemann.campfire
  "Forwards events to Campfire"
  (:use [clojure.string :only [join]])
  (:require [clj-campfire.core :as cf]))

(defn cf-settings
  "Setup settings for campfire. Required information is your api-token, ssl connection
  true or false, and your campfire sub-domain."
  [token ssl sub-domain]
  {:api-token token, :ssl ssl, :sub-domain sub-domain})

(defn room
  "Sets up the room to send events too. Pass in the settings created with cf-settings
  and the room name"
  [settings room-name]
  (cf/room-by-name settings room-name))

(defn format_string
  [e]
  (str (join " " ["HOST:" (str (:host e)) "SERVICE:" (str (:service e)) "STATE:" (str (:state e)) "DESC:" (str (:description e))]))
  )

(defn campfire
  "Creates an adaptor to forward events to campfire.
  TODO: write more here once the event formatting is better.
  TODO: tests
  Tested with:
  (streams
    (by [:host, :service]
      (let [camp (campfire \"token\", true, \"sub-domain\", \"room\")]
        camp)))"
  [token ssl sub-domain room-name]
  (fn [e]
   (let [string (str (join " " ["HOST:" (str (:host e)) "SERVICE:" (str (:service e)) "STATE:" (str (:state e)) "DESC:" (str (:description e))]))]
   (cf/message (room (cf-settings token ssl sub-domain) room-name) string))))

Add a string formatting function

Add a string formatting function


(ns bzzz.state-test
  (:use clojure.test
        [bzzz.state :as state])
  (:import (java.util HashMap Map))
  (:import (bzzz.java.query TermPayloadClojureScoreQuery)))

(defn ro-get-in [k & [default]]
  (get-in TermPayloadClojureScoreQuery/EXPR_GLOBAL_STATE_RO k default))

(defn ro-get-in-equals-to [k target]
  (is (= (ro-get-in k) target)
      (str "Global State: " TermPayloadClojureScoreQuery/EXPR_GLOBAL_STATE_RO)))

(deftest test-state
  (testing "cleanup the global RO state leaves no key behind"
    (TermPayloadClojureScoreQuery/replace_expr_global_state_ro
      (new java.util.HashMap))
    (is (= TermPayloadClojureScoreQuery/EXPR_GLOBAL_STATE_RO {})))

  (testing "merge overwrites keys with their values"
    (state/ro-merge { :foo 1, :bar 2 })
    (is (= (ro-get-in [:foo]) 1))
    (is (= (ro-get-in [:bar]) 2)))

  (testing "deep-merge keeps nested keys untouched"
    (state/ro-deep-merge { :foo { :bar 1 }})
    (state/ro-deep-merge { :foo { :baz 2 }})
    (is (= (ro-get-in [:foo :bar]) 1) (str "Wrong nested key " TermPayloadClojureScoreQuery/EXPR_GLOBAL_STATE_RO))
    (is (= (ro-get-in [:foo :baz]) 2) (str "Wrong nested key " TermPayloadClojureScoreQuery/EXPR_GLOBAL_STATE_RO))

    (testing "while always the value associated if the key exists"
      (state/ro-deep-merge { :foo { :baz 3 }})
      (is (= (ro-get-in [:foo :baz]) 3) (str "Wrong nested key " TermPayloadClojureScoreQuery/EXPR_GLOBAL_STATE_RO))))

  (testing "rename changes the key name"
    (let [test-data {:foo 1, :bar 2, :baz 3}]
      (state/ro-merge { :before-key test-data })
      (is (= (ro-get-in [:before-key]) test-data))
      (state/ro-rename-key :before-key :after-key)
      (is (= (ro-get-in [:after-key]) test-data))

      (testing "and makes sure the old key doesn't exist anymore"
        (is (nil? (ro-get-in [:before-key])))))))

Add very simple tests for bzzz.state

Add very simple tests for bzzz.state


(ns hatnik.web.client.project-list
  (:require goog.net.XhrIo
            [om.core :as om :include-macros true]
            [om.dom :as dom :include-macros true]
            [hatnik.web.client.components :as widget]))

(def app-state
  (atom {:num 0
         :projects []}))

(defn click-handler []
  (swap! app-state
         assoc :num
         (+ 1 (:num @app-state))))

(defn project-list-widget [data owner]
  (reify
    om/IRender
    (render [this]
      (widget/accordion-panel
       :header "FOO project"
       :body (dom/p nil "Foo project is good.")
       :body-id "iFooProject"))))

(om/root project-list-widget app-state
         {:target (. js/document (getElementById "iProjectList"))})

Add template for project list.

Add template for project list.


(ns goya.components.bresenham)

;; =============================================================================
;; Bresenham line drawing algorithm
;; Stolen from:
;;   http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm#Clojure

(defn bresenham [x0 y0 x1 y1]
  (let [len-x (js/Math.abs (- x0 x1))
        len-y (js/Math.abs (- y0 y1))
        is-steep (> len-y len-x)]
    (let [[x0 y0 x1 y1] (if is-steep [y0 x0 y1 x1] [x0 y0 x1 y1])]
      (let [[x0 y0 x1 y1] (if (> x0 x1) [x1 y1 x0 y0] [x0 y0 x1 y1])]
        (let [delta-x (- x1 x0)
              delta-y (js/Math.abs (- y0 y1))
              y-step (if (< y0 y1) 1 -1)]
          (loop [x x0
                 y y0
                 error (js/Math.floor delta-x 2)
                 pixels (if is-steep [[y x]] [[x y]])]
            (if (>= x x1)
              pixels
              (if (< error delta-y)
                (recur (inc x)
                       (+ y y-step)
                       (+ error (- delta-x delta-y))
                       (if is-steep (conj pixels [y x]) (conj pixels [x y])))
                (recur (inc x)
                       y
                       (- error delta-y)
                       (if is-steep (conj pixels [y x]) (conj pixels [x y]))
                       )))))))))

Introduce Bresenham routine for line-segment drawing


(ns beehive.exploration
  (:import (net.uncontended.precipice Failable)))

(def thing
  (gen-class
    :name clojure.examples.impl
    :extends Enum
    :prefix "test-"
    :methods []))

Add work exploring the usage of enums

Add work exploring the usage of enums


; https://www.hackerrank.com/challenges/a-very-big-sum
(use '[clojure.string :only (split triml)])

(let [n_t (read-line)
      n (Integer/parseInt n_t)
      arr_temp (read-line)
      arr_t (split arr_temp #"\s+")
      arr (map #(Integer/parseInt %) arr_t)]
  (println(reduce + arr)))

Resolve a very big sum.

Resolve a very big sum.


(ns cmr.message-queue.test.queue.queue-broker-wrapper-test
  "Functions for testing the queue broker wrapper we use for testing."
  (:require
    [clojure.test :refer :all]
    [cmr.common.lifecycle :as lifecycle]
    [cmr.message-queue.queue.memory-queue :as memory-queue]
    [cmr.message-queue.queue.queue-protocol :as queue-protocol]
    [cmr.message-queue.test.queue-broker-wrapper :as queue-broker-wrapper]))

(def queue-name "test-queue")

(def queue-config
  "Message queue configuration for the test."
  {:queues [queue-name]
   :exchanges ["test-exchange"]
   :queues-to-exchanges {"test-queue" ["test-exchange"]}})

(defn- retry-handler
  "A handler that forces a retry"
  [& args]
  (throw (Exception. "force retry")))

(defn- get-number-of-retries
  "Returns the number of times a message was retried."
  [message message-history]
  (let [relevant-messages (->> message-history
                               (keep #(first (:messages %)))
                               (filter #(= (:name message) (:name %))))
        retry-counts (keep :retry-count relevant-messages)]
    (apply max 0 retry-counts)))

(defn- get-final-state
  "Returns the final state of a message."
  [message-history]
  (-> message-history last :action :message :state))

(deftest retries-exhausted-test
  (let [queue-broker (memory-queue/create-memory-queue-broker queue-config)
        queue-wrapper (lifecycle/start
                        (queue-broker-wrapper/create-queue-broker-wrapper queue-broker) nil)
        message {:name "test-retries"}]
    ;; Add a listener that will always return a failure when processing a message
    (queue-protocol/subscribe queue-wrapper queue-name retry-handler)
    (queue-protocol/publish-to-queue queue-wrapper queue-name message)
    (queue-broker-wrapper/wait-for-terminal-states queue-wrapper)
    (let [message-history (queue-broker-wrapper/get-message-queue-history queue-wrapper queue-name)
          number-of-retries (get-number-of-retries message message-history)
          final-state (get-final-state message-history)]
      (is (= 5 number-of-retries))
      (is (= :failure final-state)))
    (lifecycle/stop queue-wrapper nil)))

CMR-4621: Add a test to verify the queue broker wrapper moves messages to a failed state after all retries are exhausted.


(ns main)

(defn main []
  (let [_ (read-line)
        a (Double/parseDouble (read-line))
        b (Double/parseDouble (read-line))]
    (format "%.2f" (+ a (* b 0.15)))))

(printf "TOTAL = R$ %s%n" (main))

Solve Salary with Bonus in clj

Solve Salary with Bonus in clj


(ns cortex.layers_test
  "Tests for behaviour of standard layer implementations"
  (:use [clojure.test])
  (:use [cortex.core])
  (:require [clojure.core.matrix :as m]
            [cortex.layers :as layers]
            [cortex.util :as util]
            [clojure.test.check :as sc]
            [clojure.test.check.generators :as gen]
            [clojure.test.check.properties :as prop]
            [clojure.test.check.clojure-test :refer (defspec)]))

Add test namespace for layers with generative testing


(ns clojure-rest.store)

(defmacro def-multi-reducer
  [name reducer-map]
 `(def ~name
    (clojure-rest.store/multi-reducer ~reducer-map)
  ))

Add macros to help define a multi-reducer


(ns rook.middleware-spec
  (:use
    speclj.core
    io.aviso.rook))

(def terminal-handler identity)

(defn wrap-with-gnip
  [handler metadata]
  (if-let [value (:gnip metadata)]
    (fn [request]
      (handler (assoc request :gnip value)))))

(defn wrap-with-plug
  [handler metadata tag]
  (if (:plug metadata)
    (fn [request]
      (-> request
          (update-in [:plug] (fnil conj []) tag)
          handler))))

(def request {:uri "/"})

(describe "io.aviso.rook/middleware->"

  (it "can wrap a handler with a middleware"
      (let [middleware (middleware-> wrap-with-gnip)
            handler' (middleware terminal-handler {:gnip :gnop})]
        (should-not-be-same terminal-handler handler')
        (should= {:uri "/" :gnip :gnop}
                 (handler' request))))

  (it "leaves a handler alone if middleware returns nil"
      (let [middleware (middleware-> wrap-with-gnip)
            handler' (middleware terminal-handler {})]
        (should-be-same terminal-handler handler')
        (should= request
                 (handler' request))))

  (it "can pass parameters to the middleware"
      (let [middleware (middleware->
                         (wrap-with-plug :alpha)
                         (wrap-with-plug :beta)
                         (wrap-with-plug :gamma))
            handler' (middleware terminal-handler {:plug true})]
        (should= {:uri "/" :plug [:gamma :beta :alpha]}
                 (handler' request)))))

(run-specs)

Add some tests for middleware->

Add some tests for middleware->


(ns subman.migrations
  "Migration which should be run manually from repl."
  (:require [monger.collection :as mc]
            [clojurewerkz.elastisch.rest.document :as esd]
            [environ.core :refer [env]]
            [clj-di.core :refer [get-dep]]
            [subman.handlers :refer [init-models]]
            [subman.models :refer [get-raw-db get-total-count]]))

(defn from-index-to-raw-db!
  []
  (init-models)
  (let [raw-db (get-raw-db)
        total-count (get-total-count)
        limit 1000]
    (loop [offset 0]
      (let [subtitles (esd/search (get-dep :db-connection)
                                  (env :index-name) "subtitle"
                                  :from offset
                                  :size limit)]
        (doseq [item (->> subtitles :hits :hits (map :_source))]
          (mc/insert raw-db "subtitle" item))
        (when-not (> (+ offset limit) total-count)
          (println "Moved:" offset)
          (recur (+ offset limit)))))))

Add migration for moving indexed documents to raw db


(ns no.knowit.clojure_functional.order-service
  (:use [clojure.test])
  (:import no.knowit.java_functional.product.Product)
  (:import [no.knowit.java_functional.order TrainJourney Order])
  (:import [org.joda.time DateTime]))

(defn create-order [train-journey]
  (do (Thread/sleep 200)
    (new Order train-journey 123.0)))

(defn create-order-coll [itinerary-coll]
  (map create-order itinerary-coll))

(defn create-order-coll-par [itinerary-coll]
  (pmap create-order itinerary-coll))

(defn create-itineraries []
  (let [from "OSLO S"
        to "BERGEN"
        departure-time (new DateTime)]
  (repeatedly 5
    #(new TrainJourney from to departure-time
       (.plusHours departure-time 2)))))

(deftest test-creating-orders
  (let [itineraries (create-itineraries)
        start (System/currentTimeMillis)
        result (doall (create-order-coll-par itineraries))
        stop (- (System/currentTimeMillis) start)]
    (is (= 5 (count result)))
    (is (< stop 400))))

(run-tests)

Test for resembling Java OrderServiceTest. Using map and pmap.


(ns clj-libssh2.test-libssh2
  (:require [clojure.test :refer :all]
            [clj-libssh2.libssh2 :as libssh2]))

(deftest check-libssh2-version-is-ok
  "This shoudln't change by surprise!"
  (is (= "1.6.0" (libssh2/version))))

Add a basic test to ensure libssh2 is JNA-ed properly.


(ns forecast.repository.location-forecast
  (:require [clj-http.client :as client]
            [cheshire.core :refer [parse-string]]
            [clojure.string :refer [split]]
            [clojure.walk :refer [keywordize-keys]]
            )
  (:import [java.util Calendar]))

(defonce locations (atom {}))
(defn clear-locations [] (reset! locations {}))

(defn api
  []
  (or (System/getenv "WEATHER_API") (throw "Must set WEATHER_API envrionment variable")))

(defn tomorrow
  []
  (.format (java.text.SimpleDateFormat. "yyyy-MM-dd")
           (java.util.Date. (+ (* 1 86400 1000) (.getTime (java.util.Date.))))
           ))
;; (tomorrow)

(defn force-location->forecast
  [location]
  (try
    (let [url (str "http://api.openweathermap.org/data/2.5/forecast?units=imperial&lat=" (:latitude location) "&lon=" (:longitude location) "&APPID=" (api))
          response (client/get url {:accept :json :socket-timeout 1000 :conn-timeout 1000})
          day (re-pattern (str (tomorrow) ".*"))
          ]
      (if (= (:status response) 200)
        (->>
         (keywordize-keys (parse-string (:body response)))
         :list
         (filter #(re-matches day (:dt_txt %)))
         (map #(-> % :main :temp_max))
         (apply max)
         )
        {:error (str "error response for location (" (:status response) ")")}
        ))
    (catch Exception e {:error (str e)})))
;; (prn (force-location->forecast {:latitude 37.386 :longitude -122.0838}))
;; (prn (location->forecast {:latitude 37.386 :longitude -122.0838}))

(defn location->forecast
  [location]
  (if-let [forecast (@locations location)]
    forecast
    (let [forecast (force-location->forecast location)]
      (swap! locations assoc location forecast)
      forecast)))

;; (clear-locations)
;; (prn (force-location->forecast {:latitude 37.386 :longitude -122.0838}))

Add forecast lookup for a location.

Add forecast lookup for a location.

Uses open weather map.


(ns circle.ruby
  (:import javax.script.ScriptEngine)
  (:import javax.script.ScriptEngineManager)
  (:import org.jruby.embed.ScriptingContainer)
  (:import org.jruby.RubySymbol))

(def engine
  (->
   (ScriptEngineManager.)
   (.getEngineByName "jruby")))

(defn eval-ruby
  "Eval a ruby string."
  [s]
  (-> engine
      (.eval s)))

(defn ruby
  "Returns the org.jruby.Ruby object"
  []
  (-> (ScriptingContainer.)
      (.getProvider)
      (.getRuntime)))

(defn intern-keyword
  "Given a java string, return a ruby keyword"
  [s]
  (RubySymbol/newSymbol (ruby) s))

Add a ns for working with Ruby from Clojure


(ns datasplash.pubsub
  (:require [datasplash.core :refer :all])
  (:import (com.google.cloud.dataflow.sdk.io PubsubIO$Read PubsubIO$Write)
           (com.google.cloud.dataflow.sdk.values PBegin)
           (com.google.cloud.dataflow.sdk Pipeline)))

(defn read-from-pubsub
  "Create an unbounded PCollection from a pubsub stream"
  [topic options p]
  (-> p
      (cond-> (instance? Pipeline p) (PBegin/in))
      (apply-transform (PubsubIO$Read/subscription topic) {} options)))

(defn write-to-pubsub
  "Write the contents of an unbounded PCollection to to a pubsub stream"
  [topic options pcoll]
  (-> pcoll
      (apply-transform (PubsubIO$Write/topic topic) {} options)))

; Example
;(def read-subscription "projects/my-project/subscriptions/my-subscription")
;(def write-transformed-topic "projects/my-project/topics/my-transformed-topic")
;(def read-transformed-subscription "projects/my-project/subscriptions/my-transformed-subscription")
;
;(defn stream-interactions-from-pubsub
;  [pipeline]
;  (->> pipeline
;       (read-from-pubsub read-subscription {:name "read-interactions-from-pubsub"})
;       (ds/map (fn [message]
;                 (do
;                   (log/info (str "Got message:\n" message))
;                   message)) {:name "log-message"})
;       (write-to-pubsub write-transformed-topic {:name "write-forwarded-interactions-to-pubsub"})))
;
;(defn stream-forwarded-interactions-from-pubsub
;  [pipeline]
;  (->> pipeline
;       (read-from-pubsub read-transformed-subscription {:name "read-transformed-interactions-from-pubsub"})
;       (ds/map (fn [message]
;                 (do
;                   (log/info (str "Got transformed message:\n" message))
;                   message)) {:name "log-transformed-message"})))

Add PubsubIO source and sink

Add PubsubIO source and sink


(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