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

(ns oxcart.passes
  {:doc "Implements a naive pass manager and dependency system."
   :author "Reid McKenzie"
   :added  "0.0.6"})

;; Whole-ASTs are maps of this structure:
;;   {:modules #{symbol}
;;    :passes  (Option #{Var})
;;    ∀ m ∈ Modules m → Module
;;   }
;;
;; Where a Module is at least
;;   {:forms (Vec AST)}
;;
;; The rationale for this structure is that loading is done in the
;; refernce JVM Clojure implementation on a per-module basis where
;; modules are defined to be single files but compilation and
;; evaluation occur sequentially over forms in order of
;; occurrance. Grouping forms from the same namespace together into a
;; module is pretty obvious choice, as is storing forms in file/load
;; order.

;; Passes are then functions from Whole-ASTs to Whole-ASTs. For user
;; "friendliness" each pass shall also take an options argument which
;; may change the behavior of the pass by enabling or disabling a
;; given transformation or logging output.
;;
;; As it is considered good practice for passes to be composed to
;; achieve some result rather than being monolithic, passes are
;; expected to depend on other passes, especially when a given
;; transformation requires previous enabling analysis. To assist this
;; pattern, when a non-transforming pass completes, it is expected to
;; conj it's identifier into the :passes set. Other passes may then
;; elect not to re-run analyses on which they depend if they have
;; already been run.

(defn record-pass
  [whole-ast pass]
  (update-in whole-ast [:passes] conj pass))

(defn require-pass
  [whole-ast pass options]
  (if (contains? (:passes whole-ast) pass)
    whole-ast
    (pass whole-ast options)))

(defn do-passes
  [ast options & passes]
  (reduce #(require-pass %1 %2 options)
          ast passes))

;; To enable this pattern however, transforming passes are required to
;; clobber the :passes key replacing it with #{}. This indicates to
;; subsequent passes that while information may exist in the program
;; AST it is likely stale and should (must) be re-analyzed before use.

(defn clobber-passes
  [ast]
  (assoc ast :passes #{}))

Add docs of the whole-ast structure & helpers


(ns frereth-cp.client.cookie-test
  "Test out pieces involved in client cookie handling"
  (:require [clojure.test :refer (deftest is testing)]))

(deftest url-comparison
  (testing "Distinct addresses"
    (let [ca (java.net.InetAddress/getByName "www.google.ca")
          com (java.net.InetAddress/getByName "www.google.com")]
      (is (not= ca com))))
  (testing "Multiple domains at same address"
    (let [www (java.net.InetAddress/getByName "www.frereth.com")
          beta (java.net.InetAddress/getByName "beta.frereth.com")]
      (is (= beta www)))))

Add cookie-test from several commits back

I copied a comment test into here several days ago.


(ns discuss.components.search.statements
  (:require [clojure.walk :refer [keywordize-keys]]
            [goog.crypt.base64 :as b64]
            [om.next :as om :refer-macros [defui]]
            [sablono.core :as html :refer-macros [html]]
            [ajax.core :refer [GET POST]]
            [discuss.specs :as specs]
            [discuss.utils.views :as vlib]
            [cljs.spec.alpha :as s]))

(defn- search-results
  "Handler which is called with the results from ElasticSearch. Extract statements
  from response and write it to the app-state."
  [this response]
  (let [results (-> response keywordize-keys :hits :hits)
        data (mapv :_source results)
        statements (filter (partial s/valid? ::specs/statement) data)]
    (om/transact! this `[(search/results {:results ~statements})])))

(defn search
  "Make a GET request and search in ElasticSearch for the requested data."
  [this query]
  (GET "http://localhost:9200/_search"
       {:handler (partial search-results this)
        :headers {"Authorization" (str "Basic " (b64/encodeString "elastic:changeme"))}
        :params {:q (str query "*")}}))

(defui Result
  Object
  (render [this]
          (let [statement (om/props this)
                {:keys [author content aggregate-id]} statement]
            (when-not (empty? content)
              (html [:div.bs-callout.bs-callout-info
                     [:span.badge.pull-right aggregate-id]
                     [:p (vlib/safe-html content)]
                     [:p (str "Author: " author)]])))))
(def result (om/factory Result))

(defui ^:once SearchQuery
  static om/IQuery
  (query [this] [:search/results])
  Object
  (render [this]
          (let [{:keys [search/results]} (om/props this)]
            (html [:div
                   [:form
                    [:div.form-group
                     [:label "Search for Statements"]
                     [:input.form-control {:type "text"
                                           :on-change #(search this (.. % -target -value))}]]]
                   [:div
                    [:h4 "Results"]
                    [:div.results (map #(result %) results)]]]))))
(def search-query (om/factory SearchQuery))

Add form to query argweb's ElasticSearch


(ns onyx.doc-test
  (:require [taoensso.timbre :refer [info] :as timbre]
            [clojure.test :refer [deftest is testing]]
            [onyx.static.default-vals :refer [defaults]]
            [onyx.information-model :refer [model]]))

(deftest missing-documentation-test
  (is (empty? (remove (apply merge (map :model (vals model)))
                      (keys defaults)))))

Test for missing documentation on defaults


(ns clojars.maven
  (:require [clojure.java.io :as io])
  (:import org.apache.maven.model.io.xpp3.MavenXpp3Reader))

(defn model-to-map [model]
  {:name (.getArtifactId model)
   :group (.getGroupId model)
   :version (.getVersion model)
   :description (.getDescription model)
   :homepage (.getUrl model)
   :authors (vec (map #(.getName %) (.getContributors model)))
   ;; TODO: doesn't appear to be used anywhere?
   :dependencies (vec (mapcat (fn [d] [(symbol (.getGroupId d)
                                               (.getArtifactId d))
                                       (.getVersion d)])
                              (.getDependencies model)))})

(defn read-pom
  "Reads a pom file returning a maven Model object."
  [file]
  (with-open [reader (io/reader file)]
    (.read (MavenXpp3Reader.) reader)))

(def pom-to-map (comp model-to-map read-pom))

(ns clojars.maven
  (:require [clojure.java.io :as io])
  (:import org.apache.maven.model.io.xpp3.MavenXpp3Reader))

(defn model-to-map [model]
  {:name (.getArtifactId model)
   :group (.getGroupId model)
   :version (.getVersion model)
   :description (.getDescription model)
   :homepage (.getUrl model)
   :url (.getUrl model)
   :licenses (.getLicenses model)
   :scm (.getScm model)
   :authors (vec (map #(.getName %) (.getContributors model)))
   ;; TODO: doesn't appear to be used anywhere?
   :dependencies (vec (mapcat (fn [d] [(symbol (.getGroupId d)
                                               (.getArtifactId d))
                                       (.getVersion d)])
                              (.getDependencies model)))})

(defn read-pom
  "Reads a pom file returning a maven Model object."
  [file]
  (with-open [reader (io/reader file)]
    (.read (MavenXpp3Reader.) reader)))

(def pom-to-map (comp model-to-map read-pom))

Add a few more fields to pom-to-map.

Add a few more fields to pom-to-map.


(ns yada.resources.classpath-resource
  (:require
   [clojure.java.io :as io]
   [clojure.string :as str]
   [yada.resource :refer [resource]]
   [yada.protocols :refer [as-resource]]))

(defn new-classpath-resource
  "Create a new classpath resource that resolves requests with
   path info in the active classpath, relative to root-path.

   Optionally takes an options map with the following keys:

   * index-files - a collection of files to try if the path info
                   ends with /

   Example:

      (new-classpath-resource \"public\")

   would resolve index.html to public/index.html inside
   the active classpath (e.g. of the JAR that serves the resource).

   If used with bidi, the following route

     [\"\" (yada (new-classpath-resource
                \"public\" {:index-files [\"index.html\"]}))]

   can be used to serve all files in public/ and fall back to
   index.html for URL paths like / or foo/."
  ([root-path]
   (new-classpath-resource root-path nil))
  ([root-path {:keys [index-files]}]
   (resource
    {:path-info?   true
     :methods      {}
     :sub-resource
     (fn [ctx]
       (let [path-info (-> ctx :request :path-info)
             path      (str/replace path-info #"^/" "")
             files     (if (= (last path-info) \/)
                         (map #(io/file root-path path %) index-files)
                         (list (io/file root-path path)))
             res       (first (sequence (comp (map #(.getPath %))
                                              (map io/resource)
                                              (drop-while nil?))
                                        files))]
         (as-resource res)))})))

Add a classpath-resource to serve files from classpath

For directories, i.e., requests with path infos that end with a /,
classpath resources will lazily try all index files specified via
the :index-files key in the optional options map.


(ns doctopus.storage.impls.temp-fs-test
  (:require [clojure.set :as set]
            [clojure.test :refer :all]
            [doctopus.files :as files]
            [doctopus.storage.impls.temp-fs :refer :all]
            [doctopus.test-utilities :as utils]
            [me.raynes.fs :as fs]))

(def test-pairs (files/read-html "resources/test/html"))
(def test-key (str (utils/make-today) "-doctopus-testing"))

(defn- thing-count
  "Brute-force counts the files in a dir"
  [dir]
  (count (apply set/union (map #(nth % 2) (fs/walk vector dir)))))

(deftest temp-fs-test
  (let [initial-count (thing-count (fs/file "resources/test/html"))]
    (testing "Can we save to the permanent filesystem?"
      (save-fn test-key test-pairs)
      (print initial-count)
      (binding [fs/*cwd* @temp-dir]
        (is (= initial-count (thing-count (fs/file test-key))))))
    (testing "Can we load from the permanent filesystem?"
      (is (= initial-count (count (load-fn test-key)))))
    (testing "Can we remove from the permanent filesystem?"
      (remove-fn test-key)
      (is (false? (fs/exists? (fs/file test-key)))))))

Add a temp FS test. A little cursory, but works and Is There at All


(ns implementation.firm-check-failures
  (:use midje.sweet
        midje.test-util))

; The namespace of the test should appear in test failure report
(capturing-failure-output
  (fact (+ 1 1) => 4)
  (fact
    @fact-output => #"implementation.firm-check-failures"))

Check the namespace appears in the fact output.


(ns circle.backend.nodes.circle-artifact
  (:require
   pallet.core
   pallet.phase
   [pallet.action.user :as user]
   [pallet.action.directory :as directory]
   [pallet.action.package :as package]
   [pallet.crate.java :as java]
   [pallet.action.remote-file :as remote-file]
   [pallet.action.service :as service]
   [pallet.crate.automated-admin-user :as automated-admin-user]
   [pallet.crate.git :as git]
   [pallet.crate.ssh-key :as ssh-key]
   [pallet.thread-expr :as thread-expr]))

(def circle-artifact-group
  (pallet.core/group-spec
   "circle"
   :circle-node-spec {:ami "ami-e913dd80"
                      :availability-zone "us-east-1a"
                      :instance-type "t1.micro"
                      :keypair-name "www"
                      :security-groups ["artifacts-server"]
                      :username "ubuntu"
                      :public-key (slurp "www.id_rsa.pub")
                      :private-key (slurp "www.id_rsa")}))

Add node definition for the artifacts server


(ns ruuvi.util-test
  (:require
    [ruuvi.util :refer :all]
    [midje.sweet :refer :all]
    )
  )

(fact
  "process-id returns process id"
  (let [pid (process-id)]
    pid => #(> % 0)
    ))

Add unit test for util.clj

Add unit test for util.clj


(ns workflo.macros.entity.datascript
  (:require [datascript.core :as d]
            [workflo.macros.entity.schema :as es]))

(defn attr-schema
  [attr-opts]
  (reduce (fn [opts opt]
            (cond-> opts
              (= :ref opt)
              (assoc :db/valueType :db.type/ref)
              (= :many opt)
              (assoc :db/cardinality :db.cardinality/many)
              (= :unique-value opt)
              (assoc :db/unique :db.unique/value)
              (= :unique-identity opt)
              (assoc :db/unique :db.unique/identity)))
          {} attr-opts))

(defn entity-schema
  "Returns the DataScript schema for an entity."
  [entity]
  (reduce (fn [schema [attr-name attr-opts]]
            (let [aschema (attr-schema attr-opts)]
              (cond-> schema
                (not (empty? aschema))
                (assoc attr-name aschema))))
          {}
          (es/entity-schema entity)))

Add DataScript schema generation for entities


(ns clojure.cfbt.ch05)

(defn wisdom
  [words]
  (str words ", Daniel-san"))

(wisdom "Always bathe on Friday") ;; "Always bathe on Friday, Daniel-san"

;; non-pure functional
(defn year-end-evaluation
  []
  (if (> (rand) 0.5)
    ("You get a raise!"
     "Better luck next year!")))

(defn analysis [text]
  (str "Character count: " (count text)))

(defn analyze-file
  [filename]
  (analysis (slurp filename)))

(analyze-file "project.clj") ;; "Character count: 659"

;; side-effect-free example

(def great-baby-name "Rosanthony")

(let [great-baby-name "Bloodthunder"]
  great-baby-name) ;; "Bloodthunder"

great-baby-name ;;  "Rosanthony"

(defn sum
  ([vals] (sum vals 0))
  ([vals accumulating-total]
   (if (empty? vals)
     accumulating-total
     (sum (rest vals) (+ (first vals) accumulating-total)))))

(sum [39 5 1]) ;; 45
(sum [39 5 1] 0) ;; 45
(sum [5 1] 39) ;; 45
(sum [] 45) ;; 45

;; Using recur
(defn sum
  ([vals]
   (sum vals 0))
  ([vals accumulating-total]
   (if (empty? vals)
     accumulating-total
     (recur (rest vals) (+ (first vals) accumulating-total)))))

(sum [39 5 1]) ;; 45
(sum [5 1] 39) ;; 45

(require '[clojure.string :as s])
(defn clean
  [text]
  (s/replace (s/trim text) #"lol" "LOL"))

(clean "My boa constrictor is so sassy lol!  ") ;; "My boa constrictor is so sassy LOL!"

;; Use comp
((comp inc *) 2 3) ;; 7

(def character
  {:name "Smooches McCutes"
   :attributes {:intelligence 10
                :strength 4
                :dexterity 5}})

(def c-int (comp :intelligence :attributes))
(def c-str (comp :strength     :attributes))
(def c-dex (comp :dexterity    :attributes))

(c-int character) ;; 10
(c-str character) ;; 4
(c-dex character) ;; 5

Add more examples from chapter 5

Add more examples from chapter 5


;; Copyright 2015 TWO SIGMA OPEN SOURCE, LLC
;;
;; 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 satellite.recipes-test
  (use satellite.recipes
       clojure.test))

(deftest test-exceeds-threshold?

  (testing "Excessive value returns true"
    (is (exceeds-threshold? {:metric 5} {:metric 2} 2)))

  (testing "Sufficiently low ratio returns false"
    (is (not (exceeds-threshold? {:metric 3} {:metric 2} 2))))

  (testing "Positive divisor and zero dividend returns true"
    (is (exceeds-threshold? {:metric 3} {:metric 0} 2)))

  (testing "Zero divisor and zero dividend returns false"
    (is (not (exceeds-threshold? {:metric 0} {:metric 0} 2)))))

(deftest test-fold-blackhole-thresholds

  (def settings {:blackhole-fails-to-starts-threshold 0.75
                 :blackhole-fails-to-finishes-threshold 3})

  (testing "critical state when too many failures "
    (is (= "critical"
           (:state (fold-blackhole-thresholds settings
                                              [{:metric 8} {:metric 10} {:metric 2}])))))

  (testing "ok state when few failures"
    (is (= "ok"
           (:state (fold-blackhole-thresholds settings
                                              [{:metric 1} {:metric 10} {:metric 2}])))))

  (testing "ok state when only fails per start exceeeded"
    (is (= "ok"
           (:state (fold-blackhole-thresholds settings
                                              [{:metric 8} {:metric 10} {:metric 9}])))))

  (testing "ok state when only fails per finish exceeeded"
    (is (= "ok"
           (:state (fold-blackhole-thresholds settings
                                              [{:metric 8} {:metric 20} {:metric 2}])))))

  )

satellite-master: Introduce unit tests for satellite.recipes.


(ns uncomplicate.neanderthal.clblast-cpu-test
  (:require [midje.sweet :refer :all]
            [uncomplicate.commons.core :refer [with-release]]
            [uncomplicate.clojurecl
             [core :refer [*command-queue* with-platform platforms devices with-queue with-context context]]
             [legacy :refer [command-queue-1]]]
            [uncomplicate.neanderthal
             [core :refer [tr]]
             [opencl :refer [with-engine *opencl-factory*]]
             [block-test :as block-test]
             [real-test :as real-test]
             [device-test :as device-test]
             [math-test :as math-test]]
            [uncomplicate.neanderthal.internal.device.clblast :refer [clblast-float clblast-double]]))

(defn test-blas-clblast [factory]
  (real-test/test-imin factory)
  (real-test/test-imax factory)
  (real-test/test-ge-trans! factory)
  (real-test/test-ge-sum factory))

(defn test-lapack-clblast [factory]
  (real-test/test-tr-trs factory tr)
  (real-test/test-tr-sv factory tr))

(with-release [dev (first (devices (first (platforms)) :cpu))
               ctx (context [dev])
               queue (command-queue-1 ctx dev)]

  (with-engine clblast-float queue
    (block-test/test-all *opencl-factory*)
    (real-test/test-blas *opencl-factory*)
    (test-blas-clblast *opencl-factory*)
    (test-lapack-clblast *opencl-factory*)
    (device-test/test-all *opencl-factory*)
    (math-test/test-all-device *opencl-factory*))

  (with-engine clblast-double queue
    (block-test/test-all *opencl-factory*)
    (real-test/test-blas *opencl-factory*)
    (test-blas-clblast *opencl-factory*)
    (test-lapack-clblast *opencl-factory*)
    (device-test/test-all *opencl-factory*)
    (math-test/test-all-device *opencl-factory*)))

Test clblast engine on CPU.

Test clblast engine on CPU.


{
 :name "make-map",
 :path "",
 :func (let [ot (volatile! nil)
             leftover (volatile! "")
             m {0 "+", 16 "-"}]
         (fn [map-file rec]
           (when (nil? (deref ot))
             (infof "make-maps: Opening %s" map-file)
             (vswap! ot (fn[_ f] (aio/open-file f :out)) map-file))
           (if (pg/eoi? rec)
             (if (pg/done? rec)
               (do
                 (infof "Closing stream %s" ot)
                 (pg/close-stream (deref ot))
                 (str "Finished writing " map-file))
               ;;Else
               (infof "End input stream: %s, REC: %s" (type rec) rec))
             (let [instg (str (deref leftover) (String. rec))
                   eolnl? (= \newline (austr/get instg (dec (count instg))))
                   lines (str/split instg #"\n")
                   [lines lo] (if (not eolnl?)
                                [(butlast lines) (last lines)]
                                [lines ""])
                   ot (deref ot)]
               (vswap! leftover (fn[_] lo))
               (doseq [line lines]
                 (let [rec (str/split line #"\t")
                       l (str/join
                          "\t"
                          [(-> (rec 0) (str/split #"-") second)
                           (-> (rec 1) Integer/parseInt m)
                           (-> (rec 3) Integer/parseInt dec)
                           (count (rec 9))])]
                   (.write ot l)
                   (.newLine ot)))))))

 :description "Take streaming SAM records (generated from bowtie from a _collapsed_ input file), pull out collapse count, strand info, position, and sq length, assemble with tabs and write resulting line to file map-file. This map-file will be used as input for calc_fitness operation."
}

Add map file generation service

Add map file generation service


(ns cglossa.seeds
  (:require [datomic.api :refer [delete-database create-database transact connect tempid db]]
            [datomic-schema.schema :refer [part schema fields generate-parts generate-schema]]
            [cglossa.server :as server]
            [cglossa.data-import.shared :as data-import]))

(defn dbschema []
  [(schema corpus
           (fields
             [name :string]
             [short-name :string :indexed]))

   (schema search
           (fields
             [corpus :ref :one]
             [queries :string :many]))])

(defn import-corpora []
  (data-import/tsv->tx-data "resources/data/corpora.tsv" "corpus"))

(defn seed []
  (let [url server/db-uri
        conn (connect url)]
    (transact conn (generate-schema tempid (dbschema)))
    (transact conn (import-corpora))))

Add code for seeding database

Add code for seeding database


(ns mofficer.service.user-config-resource-test
  (:use [midje.sweet])
  (:require [mofficer.infrastructure.datastructures.either]
            [cheshire.core :as ches]
            [mofficer.domain.business.user-config-business :as user-config-business]
            [mofficer.service.user-config-resource :as user-config-resource])
  (:import [mofficer.infrastructure.datastructures.either Either]))

(def user-config-test {:emailHost "http://www.gmail.com"
                       :emailPort 123
                       :senderUsername "senderUsername"
                       :senderPassword "senderPwd"
                       :senderEmail "sender@domain.com"
                       :senderId "senderId"})

(def user-config-test-as-json (ches/generate-string user-config-test))

(defn get-request-map [http-method uri body]
  {:request-method http-method
   :uri uri
   :body body})

(facts "About the user config resource:"

       (fact "Make a POST over /user-configs answer 201 if the user was created."
             (user-config-resource/user-config-api (get-request-map :post "/user-configs" user-config-test-as-json)) => (contains {:status 201 :body user-config-test})
             (provided (user-config-business/create-user-config anything) => (Either. nil user-config-test)))

       (fact "Make a POST over /user-configs answer 500 if the user couldn't be created."
             (user-config-resource/user-config-api (get-request-map :post "/user-configs" user-config-test-as-json)) => (contains {:status 500})
             (provided (user-config-business/create-user-config anything) => (Either. anything nil)))

       (fact "Make a GET over /user-configs/:sender-username returns the user-config with the same username."
             (user-config-resource/user-config-api (get-request-map :get "/user-configs/senderUsername" nil)) => (contains {:status 200 :body user-config-test})
             (provided (user-config-business/get-user-config-by-username "senderUsername") => user-config-test))

       (fact "Make a GET over /user-configs/:sender-username returns nil if the user-config with the same username does not exist."
             (user-config-resource/user-config-api (get-request-map :get "/user-configs/unknownUsername" nil)) => (contains {:status 200 :body nil})
             (provided (user-config-business/get-user-config-by-username "unknownUsername") => nil)))

Add tests for the user config API (the routes located in user_config_resource.clj).


(ns grimoire.util-test
  (:require [grimoire.util :as util]
            [clojure.test :refer :all]
            [clojure.test.check.clojure-test :refer [defspec]]
            [clojure.test.check :as tc]
            [clojure.test.check.generators :as gen]
            [clojure.test.check.properties :as prop]))

(defspec munge-unmunge-is-isomorphism 1000
  (prop/for-all [s gen/string]
    (= s (-> s util/munge util/demunge))))

Use generative testing of (· demunge munge)


(ns apio.concurrency.core
  (import (java.util.concurrent ForkJoinPool)))

;; TODO: initialize forkjoin pool in dynamic context
;; using dynamic loaded configuration.
(def *thread-pool* (ForkJoinPool.))

Add namespace for concurrency primitives.


(ns doctopus.storage.storage-impls.permanent-fs-test
  (:require [clojure.test :refer :all]
            [doctopus.files :as files]
            [doctopus.storage.storage-impls.permanent-fs :refer :all]
            [me.raynes.fs :as fs]))

(def test-vec (files/read-html "resources/test/html"))

(deftest permanent-fs-test
  (testing "Can we save to the permanent filesystem?"
    (save-fn ))
  (testing "Can we load from the permanent filesystem?")
  (testing "Can we remove from the permanent filesystem?"))

Add a test for the permanent fs

Add a test for the permanent fs


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

(defonce app-state (atom))

(enable-console-print!)

(defn draw-cells []
  (let [context (.getContext (.getElementById js/document "canvas") "2d")]
    (doseq [n (take 10 (repeatedly 1)) ]
      (.fillRect context (* n 15) (* n 15) 10 10))))

(defn main []
  (draw-cells))

Add a basic drawing cell function

Add a basic drawing cell function


(ns worker.main-test
  (:use clojure.test
        worker.main))

(deftest init-test
  (is (= nil (init "http://github.com/peritus/geocommit" "github.com/peritus/geocommit"))))

Add a simple test for init

Add a simple test for init


(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


{: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