Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Remove another rvm/trust missed in the merge | (ns circle.backend.build.template
(:require [circle.backend.action.load-balancer :as lb])
(:refer-clojure :exclude [find])
(:use [circle.backend.action.nodes :only (start-nodes stop-nodes)])
(:require [circle.backend.action.tag :as tag])
(:use [circle.util.except :only (throw-if-not assert!)])
(:use [circle.backend.action.vcs :only (checkout)])
(:require [circle.backend.action.rvm :as rvm]))
(defn build-templates []
;;; defn, solely so this file doesn't need to be reloaded when reloading action fns.
{:build {:prefix [start-nodes
tag/tag-revision
checkout
rvm/rvm-use]
:suffix [stop-nodes]}
:deploy {:prefix [start-nodes
tag/tag-revision
checkout
rvm/trust]
:suffix [lb/add-instances
lb/wait-for-healthy
lb/shutdown-remove-old-revisions]}
:staging {:prefix [start-nodes
tag/tag-revision
checkout]
:suffix []}
:empty {:prefix []
:suffix []}})
(defn find [name]
(get (build-templates) (keyword name)))
(defn find! [name]
(assert! (find name) "could not find template %s" name))
(defn apply-template [template-name actions]
(let [template (find! template-name)
before (map #(apply % []) (-> template :prefix))
after (map #(apply % []) (-> template :suffix))]
(concat before actions after))) | (ns circle.backend.build.template
(:require [circle.backend.action.load-balancer :as lb])
(:refer-clojure :exclude [find])
(:use [circle.backend.action.nodes :only (start-nodes stop-nodes)])
(:require [circle.backend.action.tag :as tag])
(:use [circle.util.except :only (throw-if-not assert!)])
(:use [circle.backend.action.vcs :only (checkout)])
(:require [circle.backend.action.rvm :as rvm]))
(defn build-templates []
;;; defn, solely so this file doesn't need to be reloaded when reloading action fns.
{:build {:prefix [start-nodes
tag/tag-revision
checkout
rvm/rvm-use]
:suffix [stop-nodes]}
:deploy {:prefix [start-nodes
tag/tag-revision
checkout]
:suffix [lb/add-instances
lb/wait-for-healthy
lb/shutdown-remove-old-revisions]}
:staging {:prefix [start-nodes
tag/tag-revision
checkout]
:suffix []}
:empty {:prefix []
:suffix []}})
(defn find [name]
(get (build-templates) (keyword name)))
(defn find! [name]
(assert! (find name) "could not find template %s" name))
(defn apply-template [template-name actions]
(let [template (find! template-name)
before (map #(apply % []) (-> template :prefix))
after (map #(apply % []) (-> template :suffix))]
(concat before actions after))) |
Enable golf leagues for everyone | {:wrap-reload false
:db-host "localhost"
:db-user nil
:db-pwd nil
:host "smtp.googlemail.com"
:user "team@4clojure.com"
:problem-submission false
:advanced-user-count 50
:pass ""}
| {:wrap-reload false
:db-host "localhost"
:db-user nil
:db-pwd nil
:host "smtp.googlemail.com"
:user "team@4clojure.com"
:problem-submission false
:advanced-user-count 50
:pass ""
:golfing-active true}
|
Switch to using Storm 0.9.5 in quickstart | (defproject {{ project_name }} "0.0.1-SNAPSHOT"
:source-paths ["topologies"]
:resource-paths ["_resources"]
:target-path "_build"
:min-lein-version "2.0.0"
:jvm-opts ["-client"]
:dependencies [[org.apache.storm/storm-core "0.9.4"]
[com.parsely/streamparse "0.0.4-SNAPSHOT"]
]
:jar-exclusions [#"log4j\.properties" #"backtype" #"trident" #"META-INF" #"meta-inf" #"\.yaml"]
:uberjar-exclusions [#"log4j\.properties" #"backtype" #"trident" #"META-INF" #"meta-inf" #"\.yaml"]
)
| (defproject {{ project_name }} "0.0.1-SNAPSHOT"
:source-paths ["topologies"]
:resource-paths ["_resources"]
:target-path "_build"
:min-lein-version "2.0.0"
:jvm-opts ["-client"]
:dependencies [[org.apache.storm/storm-core "0.9.5"]
[com.parsely/streamparse "0.0.4-SNAPSHOT"]
]
:jar-exclusions [#"log4j\.properties" #"backtype" #"trident" #"META-INF" #"meta-inf" #"\.yaml"]
:uberjar-exclusions [#"log4j\.properties" #"backtype" #"trident" #"META-INF" #"meta-inf" #"\.yaml"]
)
|
Add lein CIDER nREPL plugin | {:user {:plugins [[jonase/eastwood "0.2.0"]
[lein-kibit "0.0.8"]]}}
| {:user {:plugins [[jonase/eastwood "0.2.0"]
[lein-kibit "0.0.8"]
[cider/cider-nrepl "0.8.1"]]}}
|
Fix test failure caused by missed rename | (ns logback-riemann-appender.core-test
(:require
[clojure.test :refer :all]
[clojure.tools.logging :as log])
(:import
[com.github.kyleburton.logback RiemannAppender]))
(deftest test-logging
(is (= 0 (.get RiemannAppender/timesCalled)))
(log/infof "log at info level")
(is (= 1 (.get RiemannAppender/timesCalled)))
(log/fatalf "log at fatal level")
(is (= 2 (.get RiemannAppender/timesCalled)))
(let [ex (RuntimeException. "Test Error")]
(log/fatalf ex "log with exception: %s" ex))
(is (= 3 (.get RiemannAppender/timesCalled))))
(comment
(defn testfnkrb []
(let [ex (RuntimeException. "Test exception for logging, what stacktrace do we get?")]
(log/infof ex "Testing Stacktrace: %s" ex)))
(dotimes [ii 20]
(log/info "test from clojure"))
(let [ex (RuntimeException. "Test exception for logging, what stacktrace do we get?")]
(log/infof ex "Testing Stacktrace: %s" ex))
(testfnkrb)
) | (ns logback-riemann-appender.core-test
(:require
[clojure.test :refer :all]
[clojure.tools.logging :as log])
(:import
[com.walmartlabs.logback RiemannAppender]))
(deftest test-logging
(is (= 0 (.get RiemannAppender/timesCalled)))
(log/infof "log at info level")
(is (= 1 (.get RiemannAppender/timesCalled)))
(log/fatalf "log at fatal level")
(is (= 2 (.get RiemannAppender/timesCalled)))
(let [ex (RuntimeException. "Test Error")]
(log/fatalf ex "log with exception: %s" ex))
(is (= 3 (.get RiemannAppender/timesCalled))))
(comment
(defn testfnkrb []
(let [ex (RuntimeException. "Test exception for logging, what stacktrace do we get?")]
(log/infof ex "Testing Stacktrace: %s" ex)))
(dotimes [ii 20]
(log/info "test from clojure"))
(let [ex (RuntimeException. "Test exception for logging, what stacktrace do we get?")]
(log/infof ex "Testing Stacktrace: %s" ex))
(testfnkrb)
) |
Add a simple dsl query test | (ns desdemona.query-test
(:require
[desdemona.query :as q]
[clojure.test :refer [deftest is]]))
(def dsl->logic
@#'desdemona.query/dsl->logic)
(deftest dsl->logic-tests
(is (= '(l/featurec x {:ip "10.0.0.1"})
(dsl->logic '(= (:ip x) "10.0.0.1")))))
(deftest logic-query-tests
(is (= []
(q/run-logic-query 'l/fail
[{:ip "10.0.0.1"}])))
(is (= [[{:ip "10.0.0.1"}]]
(q/run-logic-query '(l/featurec x {:ip "10.0.0.1"})
[{:ip "10.0.0.1"}]))))
| (ns desdemona.query-test
(:require
[desdemona.query :as q]
[clojure.test :refer [deftest is]]))
(def dsl->logic
@#'desdemona.query/dsl->logic)
(deftest dsl->logic-tests
(is (= '(l/featurec x {:ip "10.0.0.1"})
(dsl->logic '(= (:ip x) "10.0.0.1")))))
(deftest dsl-query-tests
(is (= []
(q/run-dsl-query '(= (:ip x) "10.0.0.1")
[{:ip "10.0.0.1"}]))))
(deftest logic-query-tests
(is (= []
(q/run-logic-query 'l/fail
[{:ip "10.0.0.1"}])))
(is (= [[{:ip "10.0.0.1"}]]
(q/run-logic-query '(l/featurec x {:ip "10.0.0.1"})
[{:ip "10.0.0.1"}]))))
|
Remove checking for dir when creating core cache file | (ns cljs-utils.caching
(:require [clojure.java.io :as io]
[cognitect.transit :as transit])
(:import [java.io ByteArrayOutputStream]))
(def out-dir "resources/public/js-cache/")
(def filename "core.cljs.cache.aot.json")
(defn mkdirp [path]
(let [dir (java.io.File. path)]
(if (.exists dir)
true
(.mkdirs dir))))
(defn dump-core-analysis-cache
[out-path]
(let [cache (read-string
(slurp (io/resource "cljs/core.cljs.cache.aot.edn")))
out (ByteArrayOutputStream. 1000000)
writer (transit/writer out :json)]
(transit/write writer cache)
(spit (io/file out-path) (.toString out))))
(defn -main
[& args]
(println "Starting dump...")
(mkdirp out-dir)
(dump-core-analysis-cache (str out-dir filename))
(println "End."))
| (ns cljs-utils.caching
(:require [clojure.java.io :as io]
[cognitect.transit :as transit])
(:import [java.io ByteArrayOutputStream]))
(def out-dir "resources/public/js-cache/")
(def filename "core.cljs.cache.aot.json")
(defn dump-core-analysis-cache
[out-path]
(let [cache (read-string
(slurp (io/resource "cljs/core.cljs.cache.aot.edn")))
out (ByteArrayOutputStream. 1000000)
writer (transit/writer out :json)]
(transit/write writer cache)
(spit (io/file out-path) (.toString out))))
(defn -main
[& args]
(println "Starting dump...")
(dump-core-analysis-cache (str out-dir filename))
(println "End."))
|
Update to Clojure 1.3 - seems to work fine. | ; :mode=clojure:
(defproject spraff "1.0.0-SNAPSHOT"
:description "IRC bot."
:dependencies [
[org.clojure/clojure "1.2.1"]
[irclj "0.4.1-SNAPSHOT"]
]
:dev-dependencies [
[marginalia "0.5.1"]]
:main spraff.core)
| ; :mode=clojure:
(defproject spraff "1.0.0-SNAPSHOT"
:description "IRC bot."
:dependencies [
[org.clojure/clojure "1.3.0"]
[irclj "0.4.1-SNAPSHOT"]
]
:main spraff.core)
|
Fix bug in creation of date | (ns clj-applenewsapi.crypto
(:require [pandect.algo.sha256 :refer [sha256-hmac]]
[clojure.data.codec.base64 :refer [encode decode]]
[clj-time.format :as tf]
[clj-time.core :as t]))
(defn now []
(tf/unparse (tf/formatter "Y-m-d'T'H:m:s'Z'") (t/now)))
(defn canonical [method url t]
(str method url t))
(defn signature [c-url secret]
(->> secret
(.getBytes)
(decode)
(sha256-hmac c-url)
(.getBytes)
(encode)
(String.)))
| (ns clj-applenewsapi.crypto
(:require [pandect.algo.sha256 :refer [sha256-hmac]]
[clojure.data.codec.base64 :refer [encode decode]]
[clj-time.format :as tf]
[clj-time.core :as t]))
(defn now []
(tf/unparse (tf/formatter "YYYY-MM-dd'T'HH:mm:ss'Z'") (t/now)))
(defn canonical [method url t]
(str method url t))
(defn signature [c-url secret]
(->> secret
(.getBytes)
(decode)
(sha256-hmac c-url)
(.getBytes)
(encode)
(String.)))
|
Revert "Use the sonatype repo, now that the patches are in" | (defproject reply "0.1.0-SNAPSHOT"
:description "REPL-y: A fitter, happier, more productive REPL for Clojure."
:dependencies [[org.clojure/clojure "1.3.0"]
[net.sf.jline/jline "2.6-SNAPSHOT"]
[clojure-complete "0.1.4"]]
:dev-dependencies [[midje "1.3-alpha4"]
[lein-midje "[1.0.0,)"]]
:aot [reply.reader.jline.JlineInputReader]
:repositories {"sonatype"
{:url "http://oss.sonatype.org/content/repositories/snapshots"}}
:java-source-path "src")
| (defproject reply "0.1.0-SNAPSHOT"
:description "REPL-y: A fitter, happier, more productive REPL for Clojure."
:dependencies [[org.clojure/clojure "1.3.0"]
[org.clojars.trptcolin/jline "2.6-SNAPSHOT"]
[clojure-complete "0.1.4"]]
:dev-dependencies [[midje "1.3-alpha4"]
[lein-midje "[1.0.0,)"]]
:aot [reply.reader.jline.JlineInputReader]
:java-source-path "src")
|
Test the case of already being stopped. | (ns klangmeister.test.processing
(:require [cljs.test :refer-macros [deftest is]]
[klangmeister.processing :as processing]
[klangmeister.framework :as framework]
[klangmeister.actions :as action]))
(def ignore! (constantly nil))
(deftest stopping
(is
(=
(framework/process (action/->Stop :foo) ignore! {:foo {:looping? true}})
{:foo {:looping? false}})))
| (ns klangmeister.test.processing
(:require [cljs.test :refer-macros [deftest testing is]]
[klangmeister.processing :as processing]
[klangmeister.framework :as framework]
[klangmeister.actions :as action]))
(def ignore! (constantly nil))
(deftest stopping
(testing
(is
(=
(framework/process (action/->Stop :foo) ignore! {:foo {:looping? true}})
{:foo {:looping? false}}))
(is
(=
(framework/process (action/->Stop :foo) ignore! {:foo {:looping? false}})
{:foo {:looping? false}}))))
|
Make it easier to run queries at REPL | (ns bgg-graphql-proxy.main
(:require
[io.pedestal.http :as http]
[bgg-graphql-proxy.schema :refer [bgg-schema]]
[bgg-graphql-proxy.server :refer [pedestal-server]]))
(defn stop-server
[server]
(http/stop server)
nil)
(defn start-server
"Creates and starts Pedestal server, ready to handle Graphql (and Graphiql) requests."
[]
(-> (bgg-schema)
pedestal-server
http/start))
| (ns bgg-graphql-proxy.main
(:require
[io.pedestal.http :as http]
[com.walmartlabs.graphql :refer [execute]]
[bgg-graphql-proxy.schema :refer [bgg-schema]]
[bgg-graphql-proxy.server :refer [pedestal-server]]))
(defn stop-server
[server]
(http/stop server)
nil)
(defn start-server
"Creates and starts Pedestal server, ready to handle Graphql (and Graphiql) requests."
[]
(-> (bgg-schema)
pedestal-server
http/start))
|
Remove aot compilation to prevent code refresh errors | (defproject potoo "0.1.0-SNAPSHOT"
:description "A mini twitter clone backend using clojure and datomic"
:url "https://github.com/kongeor/potoo"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
[com.datomic/datomic-free "0.9.5344"]
[com.stuartsierra/component "0.3.1"]
[ring/ring "1.4.0"]
[ring/ring-json "0.4.0"]
[bidi "1.25.0"]
[com.taoensso/timbre "4.2.1"]]
:source-paths ["src/clj"]
:main potoo.system
:aot [potoo.system]
:min-lein-version "2.0.0")
| (defproject potoo "0.1.0-SNAPSHOT"
:description "A mini twitter clone backend using clojure and datomic"
:url "https://github.com/kongeor/potoo"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
[com.datomic/datomic-free "0.9.5344"]
[com.stuartsierra/component "0.3.1"]
[ring/ring "1.4.0"]
[ring/ring-json "0.4.0"]
[bidi "1.25.0"]
[com.taoensso/timbre "4.2.1"]]
:source-paths ["src/clj"]
:main potoo.system
:min-lein-version "2.0.0")
|
Prepare for next release cycle. | (defproject onyx-app/lein-template "0.9.7.0-alpha19"
:description "Onyx Leiningen application template"
:url "https://github.com/onyx-platform/onyx-template"
:license {:name "MIT License"
:url "http://choosealicense.com/licenses/mit/#"}
:repositories {"snapshots" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}
"releases" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}}
:plugins [[lein-set-version "0.4.1"]]
:profiles {:dev {:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}}
:eval-in-leiningen true)
| (defproject onyx-app/lein-template "0.9.7.0-SNAPSHOT"
:description "Onyx Leiningen application template"
:url "https://github.com/onyx-platform/onyx-template"
:license {:name "MIT License"
:url "http://choosealicense.com/licenses/mit/#"}
:repositories {"snapshots" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}
"releases" {:url "https://clojars.org/repo"
:username :env
:password :env
:sign-releases false}}
:plugins [[lein-set-version "0.4.1"]]
:profiles {:dev {:plugins [[lein-set-version "0.4.1"]
[lein-update-dependency "0.1.2"]
[lein-pprint "1.1.1"]]}}
:eval-in-leiningen true)
|
Add an alternate duration detection function | (ns mdr2.dtb
"Functions to query DAISY Talking Books"
(:require [clojure.data.xml :as xml]
[clojure.java.io :refer [file]])
(:import javax.sound.sampled.AudioSystem))
(defn file-audio-length
"Get the length of the audio in seconds for a given audio file"
[file]
;; see http://stackoverflow.com/questions/3009908/how-do-i-get-a-sound-files-total-time-in-java
(let [stream (AudioSystem/getAudioInputStream file)
format (.getFormat stream)
frameRate (.getFrameRate format)
frames (.getFrameLength stream)
durationInSeconds (/ frames frameRate)]
durationInSeconds))
(defn wav-file? [file]
(and (.isFile file)
(.endsWith (.getName file) ".wav")))
(defn audio-length [dtb]
(let [audio-files (filter wav-file? (file-seq (file dtb)))]
(reduce + (map file-audio-length audio-files))))
| (ns mdr2.dtb
"Functions to query DAISY Talking Books"
(:require [clojure.data.xml :as xml]
[clojure.java.io :refer [file]]
[clojure.java.shell :refer [sh]]
[clojure.string :refer [trim-newline]])
(:import javax.sound.sampled.AudioSystem))
(defn file-audio-length
"Get the length of the audio in seconds for a given audio file"
[file]
;; see http://stackoverflow.com/questions/3009908/how-do-i-get-a-sound-files-total-time-in-java
(let [stream (AudioSystem/getAudioInputStream file)
format (.getFormat stream)
frameRate (.getFrameRate format)
frames (.getFrameLength stream)
durationInSeconds (/ frames frameRate)]
durationInSeconds))
;; admitedly this is kinda hackish but the "Java-way" using
;; AudioSystem et al doesn't seem to work inside immutant
;; see https://issues.jboss.org/browse/IMMUTANT-457
;; (defn file-audio-length [file]
;; (-> (sh "soxi" "-D" (.getPath file))
;; :out
;; trim-newline
;; Double/parseDouble))
(defn wav-file? [file]
(and (.isFile file)
(.endsWith (.getName file) ".wav")))
(defn audio-length [dtb]
(let [audio-files (filter wav-file? (file-seq (file dtb)))]
(reduce + (map file-audio-length audio-files))))
|
Add `set-checked!` function for ListViews | (ns neko.ui.listview
"Contains utilities to work with ListView."
(:import android.util.SparseBooleanArray))
(defn get-checked
"Returns a vector of indices for items being checked in a ListView.
The two-argument version additionally takes a sequnce of data
elements of the ListView (usually the data provided to the adapter)
and returns the vector of only those elements that are checked. "
([lv]
(let [bool-array (.getCheckedItemPositions lv)
count (.getCount lv)]
(loop [i 0, result []]
(if (= i count)
result
(if (.get bool-array i)
(recur (inc i) (conj result i))
(recur (inc i) result))))))
([lv items]
(let [bool-array (.getCheckedItemPositions lv)
count (.getCount lv)]
(loop [i 0, [curr & rest] items, result []]
(if (= i count)
result
(if (.get bool-array i)
(recur (inc i) rest (conj result curr))
(recur (inc i) rest result)))))))
| (ns neko.ui.listview
"Contains utilities to work with ListView."
(:import android.util.SparseBooleanArray))
(defn get-checked
"Returns a vector of indices for items being checked in a ListView.
The two-argument version additionally takes a sequnce of data
elements of the ListView (usually the data provided to the adapter)
and returns the vector of only those elements that are checked. "
([lv]
(let [bool-array (.getCheckedItemPositions lv)
count (.getCount lv)]
(loop [i 0, result []]
(if (= i count)
result
(if (.get bool-array i)
(recur (inc i) (conj result i))
(recur (inc i) result))))))
([lv items]
(let [bool-array (.getCheckedItemPositions lv)
count (.getCount lv)]
(loop [i 0, [curr & rest] items, result []]
(if (= i count)
result
(if (.get bool-array i)
(recur (inc i) rest (conj result curr))
(recur (inc i) rest result)))))))
(defn set-checked!
"Given a sequence of numbers checks the respective ListView
elements."
[lv checked-ids]
(doseq [i checked-ids]
(.setItemChecked lv i true)))
|
Load clojure.repl when started as interactive repl | ;; Copyright (c) Daniel Borchmann. All rights reserved.
;; 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 LICENSE 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.
(use 'clojure.tools.cli)
;;
(defn- run-repl []
(clojure.main/repl :init #(use 'conexp.main)))
(let [options (cli *command-line-args*
(optional ["--load" "Load a given script"]))]
(when (options :load)
(use 'conexp.main)
(load-file (options :load)))
(when-not (or (options :load))
(clojure.main/repl :init #(use 'conexp.main))))
;;
nil
| ;; Copyright (c) Daniel Borchmann. All rights reserved.
;; 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 LICENSE 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.
(use 'clojure.tools.cli)
;;
(defn- run-repl []
(clojure.main/repl :init #(use 'conexp.main)))
(let [options (cli *command-line-args*
(optional ["--load" "Load a given script"]))]
(when (options :load)
(use 'conexp.main)
(load-file (options :load)))
(when-not (or (options :load))
(clojure.main/repl :init #(do (use 'conexp.main) (use 'clojure.repl)))))
;;
nil
|
Add 10 days to test claim expiration | (ns obb-api.core.auth
"Handles auth tokens"
(:require [environ.core :refer [env]]
[clj-jwt.core :refer :all]
[clj-time.core :refer [now plus days]]))
(def ^:private secret (or (env :obb-jwt-secret) "test"))
(defn- build-claim
"Build a claim to sign"
[user]
{:iss user
:exp (plus (now) (days -1))
:iat (now)})
(defn token-for
"Creates a token for a given user"
[args]
(-> (build-claim (args :user))
jwt
(sign :HS256 secret)
to-str))
(defn parse
"Verifies a given token"
[token]
(-> token str->jwt))
(defn valid?
"Checks if a token is valid"
[token]
(if token
(verify token secret)
false))
(defn username
"Gets the username of the given token"
[token]
(get-in token [:claims :iss]))
| (ns obb-api.core.auth
"Handles auth tokens"
(:require [environ.core :refer [env]]
[clj-jwt.core :refer :all]
[clj-time.core :refer [now plus days]]))
(def ^:private secret (or (env :obb-jwt-secret) "test"))
(defn- build-claim
"Build a claim to sign"
[user]
{:iss user
:exp (plus (now) (days 10))
:iat (now)})
(defn token-for
"Creates a token for a given user"
[args]
(-> (build-claim (args :user))
jwt
(sign :HS256 secret)
to-str))
(defn parse
"Verifies a given token"
[token]
(-> token str->jwt))
(defn valid?
"Checks if a token is valid"
[token]
(if token
(verify token secret)
false))
(defn username
"Gets the username of the given token"
[token]
(get-in token [:claims :iss]))
|
Use ":use" instead of ":require" | (ns funnel-front.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[funnel-front.components.home.main :as home]
[funnel-front.stores.main-store :as store]))
(enable-console-print!)
(om/root
home/main-comp
store/app-state
{:target (. js/document (getElementById "app"))})
| (ns funnel-front.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true])
(:use [funnel-front.components.home.main :only [main-comp]]
[funnel-front.stores.main-store :only [app-state]]))
(enable-console-print!)
(om/root
main-comp
app-state
{:target (. js/document (getElementById "app"))})
|
Fix the printing of the result. | (ns leipzig-live.views
(:require
[leipzig-live.actions :as action]))
(defn home-page [handle! state]
[:div [:h1 "Welcome to Leipzig Live!"]
[:div [:input {:type "text"
:value (:text state)
:on-change #(-> % .-target .-value action/->Refresh handle!)}]
[:button {:on-click (fn [_] (handle! (action/->Play)))} "Play!"]]
[:div
(-> state :music print)]])
| (ns leipzig-live.views
(:require
[leipzig-live.actions :as action]))
(defn home-page [handle! state]
[:div [:h1 "Welcome to Leipzig Live!"]
[:div [:input {:type "text"
:value (:text state)
:on-change #(-> % .-target .-value action/->Refresh handle!)}]
[:button {:on-click (fn [_] (handle! (action/->Play)))} "Play!"]]
[:div
(-> state :music print-str)]])
|
Include selections for auto reloading | (ns cruncher.core
(:require [om.next :as om :refer-macros [defui]]
[om.dom :as dom :include-macros true]
[goog.dom :as gdom]
[cruncher.data.pokemon]
[cruncher.communication.auth]
[cruncher.utils.extensions]
[cruncher.utils.lib :as lib]
[cruncher.shredder.main]
[cruncher.views :as views]
[om.next :as om]))
(enable-console-print!)
(om/add-root! lib/reconciler views/Main (gdom/getElement "cruncher-main"))
(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 cruncher.core
(:require [om.next :as om :refer-macros [defui]]
[om.dom :as dom :include-macros true]
[goog.dom :as gdom]
[cruncher.data.pokemon]
[cruncher.communication.auth]
[cruncher.utils.extensions]
[cruncher.utils.lib :as lib]
[cruncher.selections]
[cruncher.shredder.main]
[cruncher.views :as views]
[om.next :as om]))
(enable-console-print!)
(om/add-root! lib/reconciler views/Main (gdom/getElement "cruncher-main"))
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
|
Change name to match clojure style | (ns fault.service
(:import (fault ServiceExecutor)
(fault.circuit CircuitBreaker BreakerConfig BreakerConfig$BreakerConfigBuilder)
(clojure.lang ILookup)))
(set! *warn-on-reflection* true)
(deftype CLJBreaker [^CircuitBreaker breaker]
ILookup
(valAt [this key] (.valAt this key nil))
(valAt [_ key default]
(case key
:open? (.isOpen breaker)
:config (let [^BreakerConfig config (.getBreakerConfig breaker)]
{:time-period-in-millis (.timePeriodInMillis config)
:failure-threshold (.failureThreshold config)
:time-to-pause-millis (.timeToPauseMillis config)})
default)))
(defn swap-breaker-config
[{:keys [circuit-breaker]}
{:keys [time-period-in-millis failure-threshold time-to-pause-millis]}]
(.setBreakerConfig
^CircuitBreaker circuit-breaker
^BreakerConfig (doto (BreakerConfig$BreakerConfigBuilder.)
(.timePeriodInMillis time-period-in-millis)
(.failureThreshold failure-threshold)
(.timeToPauseMillis time-to-pause-millis)
(.build))))
(defn service-executor [pool-size]
(let [executor (ServiceExecutor. pool-size)]
{:service executor
:metrics (.getActionMetrics executor)
:circuit-breaker (.getCircuitBreaker executor)}))
| (ns fault.service
(:import (fault ServiceExecutor)
(fault.circuit CircuitBreaker BreakerConfig BreakerConfig$BreakerConfigBuilder)
(clojure.lang ILookup)))
(set! *warn-on-reflection* true)
(deftype CLJBreaker [^CircuitBreaker breaker]
ILookup
(valAt [this key] (.valAt this key nil))
(valAt [_ key default]
(case key
:open? (.isOpen breaker)
:config (let [^BreakerConfig config (.getBreakerConfig breaker)]
{:time-period-in-millis (.timePeriodInMillis config)
:failure-threshold (.failureThreshold config)
:time-to-pause-millis (.timeToPauseMillis config)})
default)))
(defn swap-breaker-config!
[{:keys [circuit-breaker]}
{:keys [time-period-in-millis failure-threshold time-to-pause-millis]}]
(.setBreakerConfig
^CircuitBreaker circuit-breaker
^BreakerConfig (doto (BreakerConfig$BreakerConfigBuilder.)
(.timePeriodInMillis time-period-in-millis)
(.failureThreshold failure-threshold)
(.timeToPauseMillis time-to-pause-millis)
(.build))))
(defn service-executor [pool-size]
(let [executor (ServiceExecutor. pool-size)]
{:service executor
:metrics (.getActionMetrics executor)
:circuit-breaker (.getCircuitBreaker executor)}))
|
Add more paths to :clean-targets for simple example | (defproject simple "0.10.10-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"
:exclusions [com.google.javascript/closure-compiler-unshaded
org.clojure/google-closure-library]]
[thheller/shadow-cljs "2.8.51"]
[reagent "0.8.1"]
[re-frame "0.10.9"]]
:plugins [[lein-shadow "0.1.5"]]
:clean-targets ^{:protect false} ["resources/public/js"]
:shadow-cljs {:nrepl {:port 8777}
:builds {:client {:target :browser
:output-dir "resources/public/js"
:modules {:client {:init-fn simple.core/run}}
:devtools {:http-root "resources/public"
:http-port 8280}}}})
| (defproject simple "0.10.10-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"
:exclusions [com.google.javascript/closure-compiler-unshaded
org.clojure/google-closure-library]]
[thheller/shadow-cljs "2.8.51"]
[reagent "0.8.1"]
[re-frame "0.10.9"]]
:plugins [[lein-shadow "0.1.5"]]
:clean-targets ^{:protect false} [:target-path
".shadow-cljs"
"shadow-cljs.edn"
"package.json"
"package-lock.json"
"resources/public/js"]
:shadow-cljs {:nrepl {:port 8777}
:builds {:client {:target :browser
:output-dir "resources/public/js"
:modules {:client {:init-fn simple.core/run}}
:devtools {:http-root "resources/public"
:http-port 8280}}}})
|
Change the fixture to do a full pave-and-re-bootstrap before and after ever set of tests. | (ns doctopus.test-database
(:require [clojure.test :refer :all]
[doctopus.configuration :refer [server-config]]
[doctopus.db :refer :all]
[doctopus.db.schema :refer :all]
[korma.db :refer [defdb postgres]]
[clojure.test :refer :all]
[doctopus
[db :refer :all]]
[doctopus.db.schema :refer :all]
[clojure.test :refer :all]
[clojure.test :refer :all]
[doctopus
[db :refer :all]]
[doctopus.db.schema :refer :all]))
(defdb test-db (postgres
(select-keys (get-in (server-config) [:database :test])
[:db :user :password :host :port])))
(defn- truncate!
[table-name]
(let [sql-string (format "TRUNCATE %s CASCADE" table-name)]
(do-sql-with-logging! sql-string :test)))
(defn database-fixture
[f]
(bootstrap :test)
(f)
(doseq [n (keys table-name->schema)] (truncate! n)))
| (ns doctopus.test-database
(:require [clojure.test :refer :all]
[doctopus.configuration :refer [server-config]]
[doctopus.db :refer :all]
[doctopus.db.schema :refer :all]
[korma.db :refer [defdb postgres]]
[clojure.test :refer :all]
[doctopus
[db :refer :all]]
[doctopus.db.schema :refer :all]
[clojure.test :refer :all]
[clojure.test :refer :all]
[doctopus
[db :refer :all]]
[doctopus.db.schema :refer :all]))
(defdb test-db (postgres
(select-keys (get-in (server-config) [:database :test])
[:db :user :password :host :port])))
(defn- truncate!
[table-name]
(let [sql-string (format "TRUNCATE %s CASCADE" table-name)]
(do-sql-with-logging! sql-string :test)))
(defn obliterate!
[]
(do-sql-with-logging! "DROP SCHEMA public CASCADE" :test)
(do-sql-with-logging! "CREATE SCHEMA public" :test))
(defn database-fixture
[f]
(bootstrap :test)
(f)
(obliterate!))
|
Fix bug not reporting time correctly for videos over one hour | (ns qcast.util
(:require [clojure.string :refer [split]]))
;;; Interface
;; Core
(defn parse-int [s]
(when (string? s)
(Long/parseLong s)))
;; Time
(defn interspaced
"Repeatedly execute task-fn following a t ms sleep. If arg is given, pass arg
to the initial execution and its result to subsequent executions. This is
usually best wrapped in a Future."
([t task-fn]
(loop []
(task-fn)
(Thread/sleep t)
(recur)))
([t task-fn arg]
(loop [_arg arg]
(let [res (task-fn _arg)]
(Thread/sleep t)
(recur res)))))
(defn seconds
([] (seconds 1))
([n] (* n 1000)))
(defn minutes
([] (minutes 1))
([n] (* n (seconds 60))))
(defn hours
([] (hours 1))
([n] (* n (minutes 60))))
(defn days
([] (days 1))
([n] (* n (hours 24))))
(defn interval->sec [s]
(let [units (map parse-int (split s #":"))]
(+ (* (first units) 60)
(second units))))
| (ns qcast.util
(:require [clojure.string :refer [split]]))
;;; Interface
;; Core
(defn parse-int [s]
(when (string? s)
(Long/parseLong s)))
;; Time
(defn interspaced
"Repeatedly execute task-fn following a t ms sleep. If arg is given, pass arg
to the initial execution and its result to subsequent executions. This is
usually best wrapped in a Future."
([t task-fn]
(loop []
(task-fn)
(Thread/sleep t)
(recur)))
([t task-fn arg]
(loop [_arg arg]
(let [res (task-fn _arg)]
(Thread/sleep t)
(recur res)))))
(defn seconds
([] (seconds 1))
([n] (* n 1000)))
(defn minutes
([] (minutes 1))
([n] (* n (seconds 60))))
(defn hours
([] (hours 1))
([n] (* n (minutes 60))))
(defn days
([] (days 1))
([n] (* n (hours 24))))
(defn interval->sec [s]
(->> (split s #":")
(map parse-int)
reverse
(map * (iterate (partial * 60) 1))
(reduce +)))
|
Enable treating warnings as errors and list acceptable warnings | (ns status-im.utils.build
(:require [cljs.analyzer :as analyzer]))
(defn warning-handler [warning-type env extra]
(when (warning-type analyzer/*cljs-warnings*)
(when-let [s (analyzer/error-message warning-type extra)]
(binding [*out* *err*]
(println (analyzer/message env (str "\u001B[31mWARNING\u001B[0m: " s))))
;; TODO Do not enable yet as our current reagent version generates warnings
#_(System/exit 1)))) | (ns status-im.utils.build
(:require [cljs.analyzer :as analyzer]))
;; Some warnings are unavoidable due to dependencies. For example, reagent 0.6.0
;; has a warning in its util.cljs namespace. Adjust this as is necessary and
;; unavoidable warnings arise.
(def acceptable-warning?
#{
"Protocol IFn implements method -invoke with variadic signature (&)" ;; reagent 0.6.0 reagent/impl/util.cljs:61
})
(defn nil-acceptable-warning [s]
(when-not (acceptable-warning? s)
s))
(defn warning-handler [warning-type env extra]
(when (warning-type analyzer/*cljs-warnings*)
(when-let [s (nil-acceptable-warning (analyzer/error-message warning-type extra))]
(binding [*out* *err*]
(println (analyzer/message env (str "\u001B[31mWARNING\u001B[0m: " s))))
(System/exit 1))))
|
Add a missing test description | (ns magician.string-test
(:require [clojure.test :refer :all]
[magician.string :refer :all]))
(deftest palindrome?-test
(is (palindrome? ""))
(is (palindrome? "a"))
(is (palindrome? "deed"))
(is (palindrome? "racecar"))
(is (not (palindrome? "cats")))
(is (not (palindrome? "no"))))
| (ns magician.string-test
(:require [clojure.test :refer :all]
[magician.string :refer :all]))
(deftest palindrome?-test
"determines if it is a palindrome"
(is (palindrome? ""))
(is (palindrome? "a"))
(is (palindrome? "deed"))
(is (palindrome? "racecar"))
(is (not (palindrome? "cats")))
(is (not (palindrome? "no"))))
|
Change cards so that its not an atom | (ns decktouch.card-data)
(defonce cards (atom [
{:name "Bile Blight"
:mana-cost [:B :B]}
{:name "Seeker of the Way"
:mana-cost [:1 :W]}
{:name "Magma Jet"
:mana-cost [:1 :R]}])) | (ns decktouch.card-data)
(def cards [
{:name "Bile Blight"
:mana-cost [:B :B]}
{:name "Seeker of the Way"
:mana-cost [:1 :W]}
{:name "Magma Jet"
:mana-cost [:1 :R]}]) |
Remove usage of potemkin (for cljs compatibility). | (ns bytebuf.core
(:refer-clojure :exclude [read byte float double short long bytes])
(:require [bytebuf.spec :as spec]
[bytebuf.buffer :as buffer]
[bytebuf.proto :as proto]
[potemkin.namespaces :refer [import-vars]]))
(import-vars
[bytebuf.spec
compose-type
spec
string
string*
int32
int64
short
integer
long
float
double
byte
bytes
bool]
[bytebuf.buffer
allocate]
[bytebuf.proto
size])
(defn write!
"Write data into buffer following the specified
spec instance."
([buff data spec]
(write! buff data spec {}))
([buff data spec {:keys [offset] :or {offset 0}}]
(locking buff
(spec/write spec buff offset data))))
(defn read*
"Read data from buffer following the specified spec
instance. This method returns a vector of readed data
and the data itself.
If you need only data, use `read` function."
([buff spec]
(read* buff spec {}))
([buff spec {:keys [offset] :or {offset 0}}]
(locking buff
(spec/read spec buff offset))))
(defn read
"Read data from buffer following the specified
spec instance. This function is a friend of `read*`
and it returns only the readed data."
[& args]
(second (apply read* args)))
| (ns bytebuf.core
(:refer-clojure :exclude [read byte float double short long bytes])
(:require [bytebuf.spec :as spec]
[bytebuf.buffer :as buffer]
[bytebuf.proto :as proto]))
(def compose-type spec/compose-type)
(def spec spec/spec)
;; (def string spec/string)
;; (def string* spec/string*)
(def int32 spec/int32)
(def int64 spec/int64)
(def short spec/short)
(def integer spec/integer)
(def long spec/long)
(def float spec/float)
(def double spec/double)
(def byte spec/byte)
(def bytes spec/bytes)
(def bool spec/bool)
(def allocate buffer/allocate)
(def size proto/size)
(defn write!
"Write data into buffer following the specified
spec instance."
([buff data spec]
(write! buff data spec {}))
([buff data spec {:keys [offset] :or {offset 0}}]
(locking buff
(spec/write spec buff offset data))))
(defn read*
"Read data from buffer following the specified spec
instance. This method returns a vector of readed data
and the data itself.
If you need only data, use `read` function."
([buff spec]
(read* buff spec {}))
([buff spec {:keys [offset] :or {offset 0}}]
(locking buff
(spec/read spec buff offset))))
(defn read
"Read data from buffer following the specified
spec instance. This function is a friend of `read*`
and it returns only the readed data."
[& args]
(second (apply read* args)))
|
Improve schema dependency on old Clojure | (defproject icecap "0.1.0-SNAPSHOT"
:description "A secure capability URL system"
:url "https://github.com/lvh/icecap"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
;; Handlers
[org.clojure/core.async "0.1.338.0-5c5012-alpha"]
[http-kit "2.1.16"]
;; Schemata
[prismatic/schema "0.2.6"]
[schema-contrib "0.1.3"]
[cddr/integrity "0.2.0-SNAPSHOT"]
;; REST API
;; http-kit already required as part of handlers
[ring/ring-defaults "0.1.1"]
[ring-middleware-format "0.4.0"]
[compojure "1.1.8"]]
:main ^:skip-aot icecap.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| (defproject icecap "0.1.0-SNAPSHOT"
:description "A secure capability URL system"
:url "https://github.com/lvh/icecap"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
;; Handlers
[org.clojure/core.async "0.1.338.0-5c5012-alpha"]
[http-kit "2.1.16"]
;; Schemata
[prismatic/schema "0.2.6"]
[schema-contrib "0.1.3"]
[cddr/integrity "0.2.0-20140823.193326-1" :exclusions [org.clojure/clojure]]
;; REST API
;; http-kit already required as part of handlers
[ring/ring-defaults "0.1.1"]
[ring-middleware-format "0.4.0"]
[compojure "1.1.8"]]
:main ^:skip-aot icecap.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
|
Allow the content type to be multi-valued. | (ns dragon.blog.content.core
(:require [dragon.blog.content.rfc5322 :as rfc5322]
[dragon.event.system.core :as event]
[dragon.event.tag :as tag]
[trifl.fs :as fs]))
(defn parse
[system file-obj]
(event/publish system tag/read-source-pre {:file file-obj})
(let [file-type (fs/extension file-obj)
content (slurp file-obj)]
(event/publish system tag/read-source-post {:file file-obj})
(assoc
(case file-type
:rfc5322 (rfc5322/parse system content)
:default {:raw-data content
:error :parser-not-found})
:file-type file-type)))
| (ns dragon.blog.content.core
(:require [clojure.string :as string]
[dragon.blog.content.rfc5322 :as rfc5322]
[dragon.event.system.core :as event]
[dragon.event.tag :as tag]
[taoensso.timbre :as log]
[trifl.fs :as fs]))
(defn parse-content-type
[content-type]
(let [types (string/split content-type #",")
parts (count types)]
(if (= 1 parts)
(keyword content-type)
(map (comp keyword string/trim) types))))
(defn file-extension-dispatch
[system content extension]
(case extension
:rfc5322 (rfc5322/parse system content)
:default {:raw-data content
:error :parser-not-found}))
(defn parse
[system file-obj]
(event/publish system tag/read-source-pre {:file file-obj})
(let [extension (fs/extension file-obj)
content (slurp file-obj)]
(event/publish system tag/read-source-post {:file file-obj})
(-> extension
((partial file-extension-dispatch system content))
(update-in [:content-type] parse-content-type)
(assoc :file-type extension))))
|
Correct fetching functions to account for column name changes | (ns verbose-spoon.model.core
(:require [verbose-spoon.model.queries :as q]))
(defn fetch-major-list []
(map :major_name (q/major-query)))
(defn fetch-category-list []
(map :category_name (q/category-query)))
(defn fetch-designation-list []
(map :designation_name (q/designation-query)))
;; name is wrong
(defn key-is-category [[k v]]
(when (re-matches #"category" k) v))
(defn insert-course [{:keys [coursenum coursename instructor designation numstudents] :as params}]
(let [categories (map key-is-category params)]
(q/insert-course-query coursenum coursename instructor designation numstudents)
(dorun (map (partial q/insert-course-is-category-query coursename) categories))))
| (ns verbose-spoon.model.core
(:require [verbose-spoon.model.queries :as q]))
(defn fetch-major-list []
(map :major_name (q/major-query)))
(defn fetch-category-list []
(map :name (q/category-query)))
(defn fetch-designation-list []
(map :name (q/designation-query)))
;; name is wrong
(defn key-is-category [[k v]]
(when (re-matches #"category" k) v))
(defn insert-course [{:keys [coursenum coursename instructor designation numstudents] :as params}]
(let [categories (map key-is-category params)]
(q/insert-course-query coursenum coursename instructor designation numstudents)
(dorun (map (partial q/insert-course-is-category-query coursename) categories))))
|
Fix typo in <meta> tag in doc layout | ; @title default title
; @format html5
[:head
[:meta {:charset (:charset site)}]
[:meta {:name "viewport"
:content "width=device-width, initiali-scale=1.0, user-scalable=yes"}]
[:title
(if (= (:title site) "home")
(:site-title site)
(str (:site-title site) " - " (:title site)))]
[:link {:rel "shortcut icon"
:href "/favicon.ico"}]
[:link {:href "/atom.xml"
:rel "alternate"
:title (:title site)
:type "application/atom-xml"}]
(css ["/css/prettify.css" (:css site ())])
(css {:media "only screen and (max-device-width:480px)"} (:device-css site))]
; /head
[:body
; github ribbon
(github-ribbon "https://github.com/liquidz/misaki")
(container
contents
[:footer {:class "footer"}
[:p (link (str "@" (:twitter site)) (str "http://twitter.com/" (:twitter site)))
" 2013"]
[:p (link (img "misaki banner" "/img/misaki_banner.svg") "https://github.com/liquidz/misaki")]])
; /container
(js ["/js/prettify.js"
"/js/lang-clj.js"
(:js site ())])]
; /body
| ; @title default title
; @format html5
[:head
[:meta {:charset (:charset site)}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1.0, user-scalable=yes"}]
[:title
(if (= (:title site) "home")
(:site-title site)
(str (:site-title site) " - " (:title site)))]
[:link {:rel "shortcut icon"
:href "/favicon.ico"}]
[:link {:href "/atom.xml"
:rel "alternate"
:title (:title site)
:type "application/atom-xml"}]
(css ["/css/prettify.css" (:css site ())])
(css {:media "only screen and (max-device-width:480px)"} (:device-css site))]
; /head
[:body
; github ribbon
(github-ribbon "https://github.com/liquidz/misaki")
(container
contents
[:footer {:class "footer"}
[:p (link (str "@" (:twitter site)) (str "http://twitter.com/" (:twitter site)))
" 2013"]
[:p (link (img "misaki banner" "/img/misaki_banner.svg") "https://github.com/liquidz/misaki")]])
; /container
(js ["/js/prettify.js"
"/js/lang-clj.js"
(:js site ())])]
; /body
|
Use new service to identify the king. | (ns made-merits.routes.leaderboard
(:require [made-merits.layout :as layout]
[compojure.core :refer [defroutes GET POST]]
[ring.util.http-response :as response]
[made-merits.db.core :as db]
[clojure.java.io :as io]))
(defn leaderboard []
(layout/render
"leaderboard.html" {:meritted_users (db/get-meritted-users)}))
(defroutes leaderboard-routes
(GET "/" [] (leaderboard)))
| (ns made-merits.routes.leaderboard
(:require [made-merits.layout :as layout]
[compojure.core :refer [defroutes GET POST]]
[ring.util.http-response :as response]
[made-merits.service.winner-calculator :as winner-calculator]
[made-merits.db.core :as db]
[clojure.java.io :as io]))
(defn meritted-users
[]
(winner-calculator/with-winner (db/get-meritted-users)))
(defn leaderboard []
(layout/render
"leaderboard.html" {:meritted_users (meritted-users)}))
(defroutes leaderboard-routes
(GET "/" [] (leaderboard)))
|
Remove .shadow-cljs cache from :clean-targets in todomvc example | (defproject todomvc-re-frame "0.10.10-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"
:exclusions [com.google.javascript/closure-compiler-unshaded
org.clojure/google-closure-library]]
[thheller/shadow-cljs "2.8.52"]
[reagent "0.8.1"]
[re-frame "0.10.9"]
[binaryage/devtools "0.9.10"]
[clj-commons/secretary "1.2.4"]
[day8.re-frame/tracing "0.5.3"]]
:plugins [[lein-shadow "0.1.5"]]
:clean-targets ^{:protect false} [:target-path
".shadow-cljs"
"shadow-cljs.edn"
"package.json"
"package-lock.json"
"resources/public/js"]
:shadow-cljs {:nrepl {:port 8777}
:builds {:client {:target :browser
:output-dir "resources/public/js"
:modules {:client {:init-fn todomvc.core/main}}
:devtools {:http-root "resources/public"
:http-port 8280}}}}
:aliases {"dev-auto" ["shadow" "watch" "client"]})
| (defproject todomvc-re-frame "0.10.10-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"
:exclusions [com.google.javascript/closure-compiler-unshaded
org.clojure/google-closure-library]]
[thheller/shadow-cljs "2.8.52"]
[reagent "0.8.1"]
[re-frame "0.10.9"]
[binaryage/devtools "0.9.10"]
[clj-commons/secretary "1.2.4"]
[day8.re-frame/tracing "0.5.3"]]
:plugins [[lein-shadow "0.1.5"]]
:clean-targets ^{:protect false} [:target-path
"shadow-cljs.edn"
"package.json"
"package-lock.json"
"resources/public/js"]
:shadow-cljs {:nrepl {:port 8777}
:builds {:client {:target :browser
:output-dir "resources/public/js"
:modules {:client {:init-fn todomvc.core/main}}
:devtools {:http-root "resources/public"
:http-port 8280}}}}
:aliases {"dev-auto" ["shadow" "watch" "client"]})
|
Add slamhound to lein plugins | {:user {:plugins [[lein-difftest "1.3.8"]
[lein-marginalia "0.7.1"]
[lein-pprint "1.1.1"]
[lein-swank "1.4.4"]]
:search-page-size 30}}
| {:user {:plugins [[lein-difftest "1.3.8"]
[lein-marginalia "0.7.1"]
[lein-pprint "1.1.1"]
[slamhound "1.3.1"]
[lein-swank "1.4.4"]]
:search-page-size 30}}
|
Change card list to a vector | (ns decktouch.card-data
(:require [reagent.core :as reagent :refer [atom]]
[ajax.core :refer [POST]]
[cljs.core.async :refer [chan >! <!]])
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn get-card-list-from-storage []
"Get the list of cards from localStorage, or [] if it is empty"
(let [key "card-list"
list (.getItem js/localStorage key)]
(if (undefined? list)
[]
(map (fn [n] {"name" n}) (js->clj (.parse js/JSON list))))))
(def card-list (atom (get-card-list-from-storage)))
(defn <lookup-card-data [card-name]
(let [c (chan)]
(POST "/data/card" {:handler #(go (>! c %))
:params {:card-name card-name}
:format :raw
:error-handler (fn [{:keys [status status-text]}]
(.log js/console
(str "Error: " status " "
status-text)))})
c))
(defn add-card-to-list! [card-name]
(do
(swap! card-list conj {"name" card-name})
(go
(let [response (<! (<lookup-card-data card-name))]
(.log js/console response))))) | (ns decktouch.card-data
(:require [reagent.core :as reagent :refer [atom]]
[ajax.core :refer [POST]]
[cljs.core.async :refer [chan >! <!]])
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn get-card-list-from-storage []
"Get the list of cards from localStorage, or [] if it is empty"
(let [key "card-list"
list (.getItem js/localStorage key)]
(if (undefined? list)
[]
(map (fn [n] {"name" n}) (js->clj (.parse js/JSON list))))))
;; This collection is a vector of maps of strings to strings
;; [ {"a" "z"} ]
(def card-list (atom (into [] (get-card-list-from-storage))))
(defn <lookup-card-data [card-name]
(let [c (chan)]
(POST "/data/card" {:handler #(go (>! c %))
:params {:card-name card-name}
:format :raw
:error-handler (fn [{:keys [status status-text]}]
(.log js/console
(str "Error: " status " "
status-text)))})
c))
(defn add-card-to-list! [card-name]
(do
(swap! card-list conj {"name" card-name})
(go
(let [response (<! (<lookup-card-data card-name))]
(.log js/console response))))) |
Remove view if no map or reduce function is found | (ns joiner.design
(:use com.ashafa.clutch)
(:use joiner.core)
(:use joiner.resource))
(defn- load-view [path]
(let [loader-fn (fn[sum value]
(let [file-content (load-resource (str path value ".js"))]
(if (nil? file-content)
sum
(assoc sum (keyword value) file-content))))]
(reduce loader-fn {} ["map" "reduce"])))
(defn update-view [database design-doc view-name]
"Create or update a new view based on the resources found at
design-doc/view-name/[map.js reduce.js]"
(with-db database database
(save-view design-doc (keyword view-name)
(load-view (str design-doc "/views/" view-name "/")))))
| (ns joiner.design
(:use com.ashafa.clutch)
(:use joiner.core)
(:use joiner.resource))
(defn- load-view [path]
(let [loader-fn (fn[sum value]
(let [file-content (load-resource (str path value ".js"))]
(if (nil? file-content)
sum
(assoc sum (keyword value) file-content))))]
(reduce loader-fn {} ["map" "reduce"])))
(defn- remove-view [database design-doc view-name]
(with-db database
(let [doc (get-document (str "_design/" design-doc))
views (:views doc)]
(update-document (assoc doc :views (dissoc views (keyword view-name)))))))
(defn update-view [database design-doc view-name]
"Create or update a new view based on the resources found at
design-doc/view-name/[map.js reduce.js]"
(let [mapreduce (load-view (str design-doc "/views/" view-name "/"))]
(if (empty? mapreduce)
(remove-view database design-doc view-name)
(with-db database database
(save-view design-doc (keyword view-name) mapreduce)))))
|
Remove confusing stack trace when loading props | (ns photon.config
(:require [clojure.tools.logging :as log]))
(defn load-props
"Receives a path and loads the Java properties for the file represented by the path inside the classpath (typically, a resource)."
[resource-name]
(do
(let [f (java.io.File. "./config.properties")
config-file (if (.exists f)
(clojure.java.io/file f)
(clojure.java.io/resource (str resource-name ".properties")))
io (clojure.java.io/input-stream config-file)
prop (java.util.Properties.)]
(log/info "opening resource" config-file)
(.load prop io)
(into {} (for [[k v] prop]
[(keyword k) v])))))
(def default-config {:amqp.url "amqp://localhost"
:microservice.name "photon"
:mongodb.host "localhost"
:riak.default_bucket "rxriak-events-v1"
:riak.node.1 "riak1.node.com"
:riak.node.2 "riak2.node.com"
:riak.node.3 "riak3.node.com"})
(def config (try
(let [props (load-props "config")]
(log/info "Properties" (pr-str props))
(merge default-config props))
(catch Exception e
(log/error "Configuration was not loaded due to " e)
(.printStackTrace e)
default-config)))
| (ns photon.config
(:require [clojure.tools.logging :as log]))
(defn load-props
"Receives a path and loads the Java properties for the file represented by the path inside the classpath (typically, a resource)."
[resource-name]
(do
(let [f (java.io.File. "./config.properties")
config-file (if (.exists f)
(clojure.java.io/file f)
(clojure.java.io/resource (str resource-name ".properties")))
io (clojure.java.io/input-stream config-file)
prop (java.util.Properties.)]
(log/info "opening resource" config-file)
(.load prop io)
(into {} (for [[k v] prop]
[(keyword k) v])))))
(def default-config {:amqp.url "amqp://localhost"
:microservice.name "photon"
:mongodb.host "localhost"
:riak.default_bucket "rxriak-events-v1"
:riak.node.1 "riak1.node.com"
:riak.node.2 "riak2.node.com"
:riak.node.3 "riak3.node.com"})
(def config (try
(let [props (load-props "config")]
(log/info "Properties" (pr-str props))
(merge default-config props))
(catch Exception e
(log/error "Falling back to default config. Configuration was not loaded due to " e)
default-config)))
|
Split out transducers based on results. | (ns cmr.client.http.impl
(:require
[cljs-http.client :as http]
[cljs.core.async :as async]
[cmr.client.common.util :as util])
(:refer-clojure :exclude [get])
(:require-macros [cljs.core.async.macros :refer [go go-loop]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utility Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn make-channel
[client]
(if (get-in client [:parent-client-options :return-body?])
(async/promise-chan (map :body))
(async/promise-chan)))
(defn get-default-options
[client]
{:with-credentials? false})
(defn make-http-options
[client call-options]
(merge (get-default-options client)
{:channel (make-channel client)}
(:http-options client)
call-options))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord HTTPClientData [
parent-client-options
http-options])
(defn get
[this url options]
(http/get url (make-http-options this options)))
| (ns cmr.client.http.impl
(:require
[cljs-http.client :as http]
[cljs.core.async :as async]
[cmr.client.common.util :as util])
(:refer-clojure :exclude [get])
(:require-macros [cljs.core.async.macros :refer [go go-loop]]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utility Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def result-xducer
(map clj->js))
(def result-body-xducer
(map (comp clj->js :body)))
(defn make-channel
[client]
(if (get-in client [:parent-client-options :return-body?])
(async/promise-chan result-body-xducer)
(async/promise-chan result-xducer)))
(defn get-default-options
[client]
{:with-credentials? false
:headers {"Accept" "application/json"}})
(defn make-http-options
[client call-options]
(merge (get-default-options client)
{:channel (make-channel client)}
(:http-options client)
call-options))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord HTTPClientData [
parent-client-options
http-options])
(defn get
[this url options]
(http/get url (make-http-options this options)))
|
Use refer all instead of :use | (ns grafter.rdf.ontologies.rdf
"Some convenience terms for the RDF and RDFS vocabularies."
(:use grafter.rdf.ontologies.util))
(def rdf (prefixer "http://www.w3.org/1999/02/22-rdf-syntax-ns#"))
(def rdfs (prefixer "http://www.w3.org/2000/01/rdf-schema#"))
(def rdf:a (rdf "type"))
(def rdf:Property (rdf "Property"))
(def rdfs:subPropertyOf (rdfs "subPropertyOf"))
(def rdfs:Class (rdfs "Class"))
(def rdfs:subClassOf (rdfs "subClassOf"))
(def rdfs:label (rdfs "label"))
(def rdfs:comment (rdfs "comment"))
(def rdfs:isDefinedBy (rdfs "isDefinedBy"))
(def rdfs:range (rdfs "range"))
(def rdfs:domain (rdfs "domain"))
| (ns grafter.rdf.ontologies.rdf
"Some convenience terms for the RDF and RDFS vocabularies."
(:require grafter.rdf.ontologies.util :refer :all))
(def rdf (prefixer "http://www.w3.org/1999/02/22-rdf-syntax-ns#"))
(def rdfs (prefixer "http://www.w3.org/2000/01/rdf-schema#"))
(def rdf:a (rdf "type"))
(def rdf:Property (rdf "Property"))
(def rdfs:subPropertyOf (rdfs "subPropertyOf"))
(def rdfs:Class (rdfs "Class"))
(def rdfs:subClassOf (rdfs "subClassOf"))
(def rdfs:label (rdfs "label"))
(def rdfs:comment (rdfs "comment"))
(def rdfs:isDefinedBy (rdfs "isDefinedBy"))
(def rdfs:range (rdfs "range"))
(def rdfs:domain (rdfs "domain"))
|
Call force-update-all on file saved | (ns cglossa.dev
(:require [cglossa.core :as core]
[figwheel.client :as figwheel :include-macros true]
[cljs.core.async :refer [put!]]
[weasel.repl :as weasel]))
(enable-console-print!)
(figwheel/watch-and-reload
:websocket-url "ws://localhost:3449/figwheel-ws"
:jsload-callback (fn [] (core/main)))
(weasel/connect "ws://localhost:9001" :verbose true)
(core/main)
| (ns cglossa.dev
(:require [cglossa.core :as core]
[reagent.core :refer [force-update-all]]
[figwheel.client :as figwheel :include-macros true]
[cljs.core.async :refer [put!]]
[weasel.repl :as weasel]))
(enable-console-print!)
(figwheel/watch-and-reload
:websocket-url "ws://localhost:3449/figwheel-ws"
:jsload-callback (fn [] (force-update-all)))
(weasel/connect "ws://localhost:9001" :verbose true)
(core/main)
|
Test the web site bodies more. | (ns circle.web.test-web
(:require circle.init)
(:require [clj-http.client :as http])
(:require [clj-http.core :as core])
(:use midje.sweet))
(circle.init/init)
(def site "http://localhost:8080")
(fact "/ returns 200"
(let [response (http/get site)]
response => (contains {:status 200 :body #"Sign up"})))
(fact "posting works"
(let [post-request {:form-params {:email "mytest@test.com" :contact true}}
post-response (http/post site post-request)
get-request {:cookies (post-response :cookies)
:url (get-in post-response [:headers "location"])}
get-response (http/get site get-request)]
post-response => (contains {:status 302})
(:headers post-response) => (contains {"location" "/"})
get-response => (contains {:status 200 :body #"Thanks"}))) | (ns circle.web.test-web
(:require circle.init)
(:require [clj-http.client :as http])
(:require [clj-http.core :as core])
(:use midje.sweet))
(circle.init/init)
(def site "http://localhost:8080")
(fact "/ returns 200"
(let [response (http/get site)
body (response :body)]
response => (contains {:status 200})
body => #"Sign up"
body => #"Continuous Integration made easy"
body => #"form"
body =not=> #"Thanks"
))
(fact "posting works"
(let [post-request {:form-params {:email "mytest@test.com" :contact true}}
post-response (http/post site post-request)
get-request {:cookies (post-response :cookies)
:url (get-in post-response [:headers "location"])}
get-response (http/get site get-request)
body (get-response :body)]
post-response => (contains {:status 302})
(:headers post-response) => (contains {"location" "/"})
get-response => (contains {:status 200})
body => #"Thanks"
body =not=> #"form")) |
Add Om components for building a list of available sidekiqs | (ns ^:figwheel-always sidequarter-frontend.core
(:require[om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]))
(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!"}))
(om/root
(fn [data owner]
(reify om/IRender
(render [_]
(dom/h1 nil (:text data)))))
app-state
{:target (. 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 sidequarter-frontend.core
(:require-macros [cljs.core.async.macros :refer [go]])
(:require[om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[cljs.core.async :refer [<!]]
[sidequarter-frontend.api :as api]))
(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 {}))
(defn sidekiq-view [data owner]
(om/component
(dom/div #js {:className "sidekiq" :id (data :id)}
(dom/h3 nil (data :namespace))
(dom/p nil (data :application))
(dom/p nil (data :redis_url)))))
(defn sidekiq-list [data owner]
(om/component
(apply dom/div #js {:className "sidekiq-list"}
(om/build-all sidekiq-view (:sidekiqs data)))))
(defn sidekiq-box [data owner]
(reify
om/IWillMount
(will-mount [_]
(om/transact! data [:sidekiqs] (fn [] []))
(go
(let [response ((<! (api/get-sidekiqs)) :body)]
(om/update! data [:sidekiqs] (:sidekiqs response)))))
om/IRender
(render [_]
(dom/h1 nil "Sidekiqs")
(om/build sidekiq-list data))))
(om/root
(fn [data owner]
(reify om/IRender
(render [_]
(dom/div nil (om/build sidekiq-box data)))))
app-state
{:target (. 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)
)
|
Make fixtures register a macro and register by var instead of fn. | (ns incise.once.fixtures.core
(:require [incise.load :refer [load-once-fixtures]]
[taoensso.timbre :refer [spy]]))
(defonce fixtures (atom {}))
(defn register
"Register a fixture for once with the given rank. Rank should be a number. The
higher the number the later the fixture is executed. (A fixture with rank 0
would be the first thing to execute.)"
[fixture & [rank]]
(swap! fixtures assoc fixture (or rank 750)))
(defn- generate-thunk [thunk fixture]
(fn [] (fixture thunk)))
(defn run-fixtures []
(reset! fixtures {})
(load-once-fixtures)
((->> @fixtures
(spy :trace)
(sort-by (comp - val))
(map key)
(reduce generate-thunk (fn [])))))
| (ns incise.once.fixtures.core
(:require [incise.load :refer [load-once-fixtures]]
[taoensso.timbre :refer [spy]]))
(defonce fixtures (atom {}))
(defmacro register
"Register a fixture for once with the given rank. Rank should be a number. The
higher the number the later the fixture is executed. (A fixture with rank 0
would be the first thing to execute.)"
[fixture & [rank]]
`(swap! fixtures assoc (var ~fixture) (or ~rank 750)))
(defn- generate-thunk [thunk fixture]
(fn [] (fixture thunk)))
(defn run-fixtures []
(reset! fixtures {})
(load-once-fixtures)
((->> @fixtures
(spy :trace)
(sort-by (comp - val))
(map key)
(reduce generate-thunk (fn [])))))
|
Add implementation for bytes[] on SecretKey protocol. | ;; Copyright 2013 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.keys
(:require [buddy.core.codecs :refer [str->bytes]]))
(defprotocol SecretKey
(key->bytes [key] "Normalize key to byte array")
(key->str [key] "Normalize key String"))
(extend-protocol SecretKey
String
(key->bytes [key] (str->bytes key))
(key->str [key] key))
| ;; Copyright 2013 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.keys
(:require [buddy.core.codecs :refer [str->bytes bytes->hex]]))
(defprotocol SecretKey
(key->bytes [key] "Normalize key to byte array")
(key->str [key] "Normalize key String"))
(extend-protocol SecretKey
(Class/forName "[B")
(key->bytes [it] it)
(key->str [it] (bytes->hex it))
String
(key->bytes [key] (str->bytes key))
(key->str [key] key))
|
Move docstring to proper location | (ns com.puppetlabs.cmdb.query.population
(:use [com.puppetlabs.jdbc :only [query-to-vec]]))
(defn correlate-exported-resources
[]
"Fetch a map of {exported-resource [#{exporting-nodes} #{collecting-nodes}]},
to correlate the nodes exporting and collecting resources."
(query-to-vec (str "SELECT DISTINCT exporters.type, exporters.title, "
"(SELECT certname FROM certname_catalogs WHERE catalog=exporters.catalog) AS exporter, "
"(SELECT certname FROM certname_catalogs WHERE catalog=collectors.catalog) AS collector "
"FROM catalog_resources exporters, catalog_resources collectors "
"WHERE exporters.resource=collectors.resource AND exporters.exported=true AND collectors.exported=false "
"ORDER BY exporters.type, exporters.title, exporter, collector ASC")))
| (ns com.puppetlabs.cmdb.query.population
(:use [com.puppetlabs.jdbc :only [query-to-vec]]))
(defn correlate-exported-resources
"Fetch a map of {exported-resource [#{exporting-nodes} #{collecting-nodes}]},
to correlate the nodes exporting and collecting resources."
[]
(query-to-vec (str "SELECT DISTINCT exporters.type, exporters.title, "
"(SELECT certname FROM certname_catalogs WHERE catalog=exporters.catalog) AS exporter, "
"(SELECT certname FROM certname_catalogs WHERE catalog=collectors.catalog) AS collector "
"FROM catalog_resources exporters, catalog_resources collectors "
"WHERE exporters.resource=collectors.resource AND exporters.exported=true AND collectors.exported=false "
"ORDER BY exporters.type, exporters.title, exporter, collector ASC")))
|
Convert requests-state to a plain hash rather than a record | (ns parbench.requests-state)
(defrecord RequestsState [requests concurrency grid])
(defn create-blank [requests concurrency url-generator]
"Creates a blank representation of request state"
(let [grid (for [row (range concurrency)]
(for [col (range requests)]
(ref {:y row :x col
:url (url-generator col row)
:state :untried
:status nil
:runtime nil}) ))]()
(RequestsState. requests concurrency grid )))
(defn stats [requests-state]
"Returns a mapping of RequestsState http states states to counts"
(reduce
(fn [stats request]
(let [r @request
state (:state r)
status (:status r)
statuses (:statuses stats)]
(assoc stats
:total (inc (stats :total 0))
state (inc (stats state 0))
:statuses (assoc statuses status (inc (statuses status 0)))
:progress (if (not= state :untried)
(inc (stats :progress 0))
(stats :progress 0)))))
{:statuses {}}
(flatten (:grid requests-state))))
| (ns parbench.requests-state)
(defn create-blank [requests concurrency url-generator]
"Creates a blank representation of request state"
(let [grid (for [row (range concurrency)]
(for [col (range requests)]
(ref {:y row :x col
:url (url-generator col row)
:state :untried
:status nil
:runtime nil}) ))]()
{:requests requests :concurrency concurrency
:grid grid}))
(defn stats [requests-state]
"Returns a mapping of RequestsState http states states to counts"
(reduce
(fn [stats request]
(let [r @request
state (:state r)
status (:status r)
statuses (:statuses stats)]
(assoc stats
:total (inc (stats :total 0))
state (inc (stats state 0))
:statuses (assoc statuses status (inc (statuses status 0)))
:progress (if (not= state :untried)
(inc (stats :progress 0))
(stats :progress 0)))))
{:statuses {}}
(flatten (:grid requests-state))))
|
Copy format function from backend | (ns frontend.models.test
(:require [clojure.string :as string]
[frontend.state :as state]
[frontend.utils :as utils :include-macros true]
[goog.string :as gstring]
goog.string.format))
(defn source [test]
(or (:source_type test)
;; TODO: this can be removed once source_type is fully deployed
(:source test)))
(defmulti format-test-name source)
(defmethod format-test-name :default [test]
(:name test))
(defmethod format-test-name "lein-test" [test]
(str (:classname test) "/" (:name test)))
(defmethod format-test-name "cucumber" [test]
(if (string/blank? (:name test))
(:classname test)
(:name test)))
(defn pretty-source [source]
(case source
"cucumber" "Cucumber"
"rspec" "RSpec"
source))
(defn failed? [test]
(not= "success" (:result test)))
| (ns frontend.models.test
(:require [clojure.string :as string]
[frontend.state :as state]
[frontend.utils :as utils :include-macros true]
[goog.string :as gstring]
goog.string.format))
(defn source [test]
(or (:source_type test)
;; TODO: this can be removed once source_type is fully deployed
(:source test)))
(defmulti format-test-name source)
(defmethod format-test-name :default [test]
(->> [[(:name test)] [(:classname test) (:file test)]]
(map (fn [s] (some #(when-not (string/blank? %) %) s)))
(filter identity)
(string/join " - in ")))
(defmethod format-test-name "lein-test" [test]
(str (:classname test) "/" (:name test)))
(defmethod format-test-name "cucumber" [test]
(if (string/blank? (:name test))
(:classname test)
(:name test)))
(defn pretty-source [source]
(case source
"cucumber" "Cucumber"
"rspec" "RSpec"
source))
(defn failed? [test]
(not= "success" (:result test)))
|
Define query function for running SQL queries | (ns cglossa.db)
| (ns cglossa.db
(:require [clojure.string :as str]
[clojurewerkz.ogre.core :as q])
(:import (com.tinkerpop.blueprints.impls.orient OrientGraphFactory)
(com.orientechnologies.orient.core.sql OCommandSQL)))
(defn get-graph
([] (get-graph true))
([transactional?]
(let [factory (OrientGraphFactory. "remote:localhost/Glossa" "admin" "admin")]
(if transactional? (.getTx factory) (.getNoTx factory)))))
(defn query
"Takes an SQL query and optionally a map of parameters, runs it against the
OrientDB database, and returns the query result as a seq. The params argument
is a hash map with the following optional keys:
* targets: A vertex ID, or a sequence of such IDs, to use as the target in the
SQL query (e.g. '#12:1' or ['#12:1' '#12:2']), replacing the placeholder #TARGET
or #TARGETS (e.g. 'select from #TARGETS').
* strings: Map with strings that will be interpolated into the SQL query, replacing
placeholders with the same name preceded by an ampersand. Restricted to
letters, numbers and underscore to avoid SQL injection. Use only in those
cases where OrientDB does not support 'real' SQL parameters (such as in the
specification of attribute values on edges and vertices, e.g. in()[name = &name],
with {:name 'John'} given as the value of the strings key).
* sql-params: parameters (positioned or named) that will replace question marks
in the SQL query through OrientDB's normal parameterization process.
A full example:
(query \"select out('&out') from #TARGETS where code = ?\"
{:targets [\"#12:0\" \"#12:1\"]
:sql-params [\"bokmal\"]
:strings {:out \"HasMetadataCategory\"}})"
([sql]
(query sql {}))
([sql params]
(let [graph (get-graph)
targets (if (:targets params)
(-> (:targets params) vector flatten vec)
[])
_ (doseq [target targets] (assert (re-matches #"#\d+:\d+" target)
(str "Invalid target: " target)))
strings (:strings params)
_ (assert (or (nil? strings) (map? strings))
"String params should be provided in a map")
_ (doseq [s (vals strings)] (assert (not (re-find #"[\W]" s))
(str "Invalid string param: " s)))
sql-params (into-array (:sql-params params))
sql* (-> sql
(str/replace #"\&(\w+)" #(get strings (keyword (second %))))
(str/replace #"#TARGETS?" (str "[" (str/join ", " targets) "]")))
cmd (OCommandSQL. sql*)
]
(seq (.. graph (command cmd) (execute sql-params))))))
|
Use the correct location for getting CSS | (ns day8.re-frame.trace.styles
(:require-macros [day8.re-frame.trace.macros :as macros]))
(def panel-styles (macros/slurp-macro "day8/re_frame/css/main.css"))
| (ns day8.re-frame.trace.styles
(:require-macros [day8.re-frame.trace.macros :as macros]))
(def panel-styles (macros/slurp-macro "day8/re_frame/trace/main.css"))
|
Stop horsing around, part 2. | (ns lcmap.clownfish.state
(:require [cheshire.core :as json]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[lcmap.clownfish.config :refer [config]]
[mount.core :refer [defstate] :as mount]
[org.httpkit.client :as http]))
(defmulti retrieve (fn [url]
(if (str/starts-with?
(str/lower-case url) "http")
:http
:local)))
(defmethod retrieve :http [url]
(-> @(http/request {:url url
:method :get
:headers {"Accept" "application/json"}})
(:body)))
(defmethod retrieve :local [url]
(-> url io/resource slurp (json/decode true)))
(defstate tile-specs
;:start {:tile_x 10 :tile_y 10 :shift_x 0 :shift_y 0})
:start (let [url (get-in config [:state :tile-specs-url])]
(log/debug "Loading tile-specs")
(try
(retrieve url)
(catch Exception e
(log/errorf e "Could not load tile-specs from: %s" url)
(throw e)))))
| (ns lcmap.clownfish.state
(:require [cheshire.core :as json]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.logging :as log]
[lcmap.clownfish.config :refer [config]]
[mount.core :refer [defstate] :as mount]
[org.httpkit.client :as http]))
(defmulti retrieve (fn [url]
(if (str/starts-with?
(str/lower-case url) "http")
:http
:local)))
(defmethod retrieve :http [url]
(-> @(http/request {:url url
:method :get
:headers {"Accept" "application/json"}})
(:body)))
(defmethod retrieve :local [url]
(-> url io/resource slurp))
(defstate tile-specs
;:start {:tile_x 10 :tile_y 10 :shift_x 0 :shift_y 0})
:start (let [url (get-in config [:state :tile-specs-url])]
(log/debug "Loading tile-specs")
(try
(-> url retrieve (json/decode true))
(catch Exception e
(log/errorf e "Could not load tile-specs from: %s" url)
(throw e)))))
|
Allow only admins access to list of registered users | (ns time-tracker.users.handlers
(:require [ring.util.response :as res]
[time-tracker.users.db :as users-db]
[time-tracker.invited-users.db :as invited-users-db]
[time-tracker.web.util :as web-util]))
;; /users/me/
(defn retrieve
[{:keys [credentials]} connection]
(if-let [user-profile (users-db/retrieve connection
(:sub credentials))]
(res/response user-profile)
web-util/error-not-found))
;; /users/
(defn list-all
[request connection]
(res/response (users-db/retrieve-all connection)))
| (ns time-tracker.users.handlers
(:require [ring.util.response :as res]
[time-tracker.users.db :as users-db]
[time-tracker.invited-users.db :as invited-users-db]
[time-tracker.web.util :as web-util]))
;; /users/me/
(defn retrieve
[{:keys [credentials]} connection]
(if-let [user-profile (users-db/retrieve connection
(:sub credentials))]
(res/response user-profile)
web-util/error-not-found))
;; /users/
(defn list-all
[{:keys [credentials] :as request} connection]
(let [google-id (:sub credentials)]
(if (users-db/has-user-role? google-id connection ["admin"])
(res/response (users-db/retrieve-all connection))
web-util/error-forbidden)))
|
Make alpha/beta/etc versions incompatible with each other. | (ns onyx.peer.log-version)
(def version "0.10.0-SNAPSHOT")
(defn check-compatible-log-versions! [cluster-version]
(when-not (or (re-find #"-" version)
(= version cluster-version))
(throw (ex-info "Incompatible versions of the Onyx cluster coordination log.
A new, distinct, :onyx/tenancy-id should be supplied when upgrading or downgrading Onyx."
{:cluster-version cluster-version
:peer-version version}))))
| (ns onyx.peer.log-version)
(def version "0.10.0-SNAPSHOT")
(defn check-compatible-log-versions! [cluster-version]
(when-not (or (re-find #"-SNAPSHOT" version)
(= version cluster-version))
(throw (ex-info "Incompatible versions of the Onyx cluster coordination log.
A new, distinct, :onyx/tenancy-id should be supplied when upgrading or downgrading Onyx."
{:cluster-version cluster-version
:peer-version version}))))
|
Add multiple varities to handle html fragments | (ns datemo.arb
(:require [clojure.pprint :refer [pprint]])
(:use hickory.core))
(defn html->hiccup [html]
(as-hiccup (parse html)))
(defn hiccup->arb [hiccup]
(if (string? (first hiccup))
(first hiccup)
(let [[tag attrs & rest] (first hiccup)
rest-count (count rest)]
(if (or (= 0 rest-count) (and (= 1 rest-count) (string? (first rest))))
[:arb {:original-tag tag} (first rest)]
(loop [arb [:arb {:original-tag tag}]
forms rest]
(if (= 1 (count forms))
(conj arb (hiccup->arb forms))
(recur (conj arb (hiccup->arb (list (first forms))))
(next forms))))))))
(defn html->arb [html]
(hiccup->arb (html->hiccup html)))
| (ns datemo.arb
(:require [clojure.pprint :refer [pprint]])
(:use hickory.core))
(defn html->hiccup
([html] (as-hiccup (parse html)))
([html as-fragment]
(if (false? as-fragment)
(html->hiccup html)
(map as-hiccup (parse-fragment html)))))
(defn hiccup->arb [hiccup]
(if (string? (first hiccup))
(first hiccup)
(let [[tag attrs & rest] (first hiccup)
rest-count (count rest)]
(if (or (= 0 rest-count) (and (= 1 rest-count) (string? (first rest))))
[:arb {:original-tag tag} (first rest)]
(loop [arb [:arb {:original-tag tag}]
forms rest]
(if (= 1 (count forms))
(conj arb (hiccup->arb forms))
(recur (conj arb (hiccup->arb (list (first forms))))
(next forms))))))))
(defn html->arb
([html] (html->arb html false))
([html as-fragment]
(if (false? as-fragment)
(hiccup->arb (html->hiccup html)))
(hiccup->arb (html->hiccup html as-fragment))))
(defn arb->tx [arb]
arb)
|
Fix defalias to support docstrings | (ns clojurewerkz.cassaforte.ns-utils)
(defmacro defalias ^:private [sym v]
`(intern *ns* (with-meta ~sym (meta ~sym)) (deref ~v)))
(defn alias-ns
"Alias all the vars from namespace to the curent namespace"
[ns-name]
(require ns-name)
(doseq [[n v] (ns-publics (the-ns ns-name))]
(defalias n v)))
| (ns clojurewerkz.cassaforte.ns-utils)
(defn defalias
"Create a var with the supplied name in the current namespace, having the same
metadata and root-binding as the supplied var."
[name ^clojure.lang.Var var]
(apply intern *ns* (with-meta name (merge (meta var)
(meta name)))
(when (.hasRoot var) [@var])))
(defn alias-ns
"Alias all the vars from namespace to the curent namespace"
[ns-name]
(require ns-name)
(doseq [[n v] (ns-publics (the-ns ns-name))]
(defalias n v)))
|
Update Jetty dependency to 9.4.36.v20210114 | (defproject ring/ring-jetty-adapter "1.9.0"
:description "Ring Jetty adapter."
:url "https://github.com/ring-clojure/ring"
:scm {:dir ".."}
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.7.0"]
[ring/ring-core "1.9.0"]
[ring/ring-servlet "1.9.0"]
[org.eclipse.jetty/jetty-server "9.4.31.v20200723"]]
:aliases {"test-all" ["with-profile" "default:+1.8:+1.9:+1.10" "test"]}
:profiles
{:dev {:dependencies [[clj-http "3.10.0"]
[less-awful-ssl "1.0.6"]]
:jvm-opts ["-Dorg.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT=500"]}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]}
:1.10 {:dependencies [[org.clojure/clojure "1.10.2"]]}})
| (defproject ring/ring-jetty-adapter "1.9.0"
:description "Ring Jetty adapter."
:url "https://github.com/ring-clojure/ring"
:scm {:dir ".."}
:license {:name "The MIT License"
:url "http://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.7.0"]
[ring/ring-core "1.9.0"]
[ring/ring-servlet "1.9.0"]
[org.eclipse.jetty/jetty-server "9.4.36.v20210114"]]
:aliases {"test-all" ["with-profile" "default:+1.8:+1.9:+1.10" "test"]}
:profiles
{:dev {:dependencies [[clj-http "3.10.0"]
[less-awful-ssl "1.0.6"]]
:jvm-opts ["-Dorg.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT=500"]}
:1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]}
:1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]}
:1.10 {:dependencies [[org.clojure/clojure "1.10.2"]]}})
|
Stop adding maintainer label per Docker recs | (ns docker-clojure.dockerfile
(:require
[clojure.java.shell :refer [sh]]
[clojure.string :as str]
[docker-clojure.dockerfile.boot :as boot]
[docker-clojure.dockerfile.lein :as lein]
[docker-clojure.dockerfile.tools-deps :as tools-deps]))
(defn build-dir [{:keys [base-image build-tool]}]
(str/join "/" ["target"
(str/replace base-image ":" "-")
build-tool]))
(defn contents [{:keys [maintainer build-tool] :as variant}]
(str/join "\n"
(concat [(format "FROM %s" (:base-image variant))
(format "LABEL maintainer=\"%s\"" maintainer)
""]
(case build-tool
"boot" (boot/contents variant)
"lein" (lein/contents variant)
"tools-deps" (tools-deps/contents variant)))))
(defn write-file [dir file variant]
(let [{:keys [exit err]} (sh "mkdir" "-p" dir)]
(if (zero? exit)
(spit (str/join "/" [dir file])
(contents variant))
(throw (ex-info (str "Error creating directory " dir)
{:error err})))))
(defn clean-all []
(sh "sh" "-c" "rm -rf target/*"))
| (ns docker-clojure.dockerfile
(:require
[clojure.java.shell :refer [sh]]
[clojure.string :as str]
[docker-clojure.dockerfile.boot :as boot]
[docker-clojure.dockerfile.lein :as lein]
[docker-clojure.dockerfile.tools-deps :as tools-deps]))
(defn build-dir [{:keys [base-image build-tool]}]
(str/join "/" ["target"
(str/replace base-image ":" "-")
build-tool]))
(defn contents [{:keys [maintainer build-tool] :as variant}]
(str/join "\n"
(concat [(format "FROM %s" (:base-image variant))
""]
(case build-tool
"boot" (boot/contents variant)
"lein" (lein/contents variant)
"tools-deps" (tools-deps/contents variant)))))
(defn write-file [dir file variant]
(let [{:keys [exit err]} (sh "mkdir" "-p" dir)]
(if (zero? exit)
(spit (str/join "/" [dir file])
(contents variant))
(throw (ex-info (str "Error creating directory " dir)
{:error err})))))
(defn clean-all []
(sh "sh" "-c" "rm -rf target/*"))
|
Fix division to round to at least 2 decimal places | (ns warreq.kea.calc.math
(:require [clojure.math.numeric-tower :refer [expt]]
[warreq.kea.calc.util :as u]
[neko.notify :refer [toast]])
(:import java.math.BigDecimal))
(defn rpn
"Evaluate an expression composed in Reverse Polish Notation and return the
result. `rpn` may optionally take a stack as a separate parameter, which may
contain a partially resolved expression."
([e]
(rpn e '()))
([e s]
(if (empty? e)
(first s)
(if (number? (first e))
(recur (rest e)
(conj s (first e)))
(recur (rest e)
(conj (drop 2 s) (eval (conj (reverse (take 2 s)) (first e)))))))))
(defn floating-division [x y]
(if (not= ^BigDecimal y BigDecimal/ZERO)
(.divide ^BigDecimal x ^BigDecimal y java.math.RoundingMode/HALF_UP)
(do (u/vibrate! 500)
(toast "Cannot divide by 0."))))
(defn op-alias [op]
(case op
"^" expt
"÷" floating-division
"×" *
(resolve (symbol op))))
| (ns warreq.kea.calc.math
(:require [clojure.math.numeric-tower :refer [expt]]
[warreq.kea.calc.util :as u]
[neko.notify :refer [toast]])
(:import java.math.BigDecimal))
(defn rpn
"Evaluate an expression composed in Reverse Polish Notation and return the
result. `rpn` may optionally take a stack as a separate parameter, which may
contain a partially resolved expression."
([e]
(rpn e '()))
([e s]
(if (empty? e)
(first s)
(if (number? (first e))
(recur (rest e)
(conj s (first e)))
(recur (rest e)
(conj (drop 2 s) (eval (conj (reverse (take 2 s)) (first e)))))))))
(defn floating-division [x y]
(if (not= ^BigDecimal y BigDecimal/ZERO)
(.divide ^BigDecimal x ^BigDecimal y 2 java.math.RoundingMode/HALF_EVEN)
(do (u/vibrate! 500)
(toast "Cannot divide by 0."))))
(defn op-alias [op]
(case op
"^" expt
"÷" floating-division
"×" *
(resolve (symbol op))))
|
Fix async require on async cljs | (ns com.wsscode.common.async-cljs)
(defmacro if-cljs
[then else]
(if (:ns &env) then else))
(defmacro go-catch [& body]
`(async/go
(try
~@body
(catch :default e# e#))))
(defmacro <!p [promise]
`(consumer-pair (cljs.core.async/<! (promise->chan ~promise))))
(defmacro <? [ch]
`(throw-err (cljs.core.async/<! ~ch)))
(defmacro <?maybe [x]
`(let [res# ~x]
(if (chan? res#) (<? res#) res#)))
(defmacro <!maybe [x]
`(let [res# ~x]
(if (chan? res#) (cljs.core.async/<! res#) res#)))
(defmacro let-chan
"Handles a possible channel on value."
[[name value] & body]
`(let [res# ~value]
(if (chan? res#)
(go-catch
(let [~name (<? res#)]
~@body))
(let [~name res#]
~@body))))
(defmacro go-promise [& body]
`(let [ch# (cljs.core.async/promise-chan)]
(async/go
(let [res# (try
~@body
(catch :default e# e#))]
(cljs.core.async/put! ch# res#)))
ch#))
| (ns com.wsscode.common.async-cljs
(:require [cljs.core.async :as async]))
(defmacro if-cljs
[then else]
(if (:ns &env) then else))
(defmacro go-catch [& body]
`(async/go
(try
~@body
(catch :default e# e#))))
(defmacro <!p [promise]
`(consumer-pair (cljs.core.async/<! (promise->chan ~promise))))
(defmacro <? [ch]
`(throw-err (cljs.core.async/<! ~ch)))
(defmacro <?maybe [x]
`(let [res# ~x]
(if (chan? res#) (<? res#) res#)))
(defmacro <!maybe [x]
`(let [res# ~x]
(if (chan? res#) (cljs.core.async/<! res#) res#)))
(defmacro let-chan
"Handles a possible channel on value."
[[name value] & body]
`(let [res# ~value]
(if (chan? res#)
(go-catch
(let [~name (<? res#)]
~@body))
(let [~name res#]
~@body))))
(defmacro go-promise [& body]
`(let [ch# (cljs.core.async/promise-chan)]
(async/go
(let [res# (try
~@body
(catch :default e# e#))]
(cljs.core.async/put! ch# res#)))
ch#))
|
Enable pretty hooks for logging | (ns user
(:use
clojure.repl
io.aviso.repl
speclj.config))
(install-pretty-exceptions)
(alter-var-root #'default-config assoc :color true :reporters ["documentation"])
| (ns user
(:use
clojure.repl
io.aviso.repl
io.aviso.logging
speclj.config))
(install-pretty-exceptions)
(install-pretty-logging)
(install-uncaught-exception-handler)
(alter-var-root #'default-config assoc :color true :reporters ["documentation"])
|
Reduce code duplication by using a partial function. | (ns berry.parsing.context-handler)
(def begin {
:start-line 1
:start-column 1
:current-line 1
:current-column 1
:offset 0})
(defn ++
[{current-column :current-column
offset :offset
:as context}]
(merge context {
:current-column (inc current-column)
:offset (inc offset)}))
(defn --
[{current-column :current-column
offset :offset
:as context}]
(merge context {
:current-column (dec current-column)
:offset (dec offset)}))
| (ns berry.parsing.context-handler)
(def begin {
:start-line 1
:start-column 1
:current-line 1
:current-column 1
:offset 0})
(defn- apply-to
[transform {current-column :current-column
offset :offset
:as context}]
(assoc context
:current-column (transform current-column)
:offset (transform offset)))
(def ++ (partial apply-to inc))
(def -- (partial apply-to dec))
|
Add ability to create tabs. | (ns nightweb.core
(:use splendid.jfx
nightweb.page)
(:import javafx.scene.layout.VBox
javafx.scene.layout.HBox
javafx.scene.control.TabPane
javafx.scene.control.Tab
javafx.scene.web.WebView
javafx.scene.layout.Priority
javafx.scene.control.Button
javafx.scene.control.TextField
javafx.geometry.Insets
net.i2p.router.Router)
(:gen-class))
(defn start-browser
"Launch the JavaFX browser (non-blocking)."
[]
(jfx (let [window (VBox.)
tab-view (VBox.)
nav-bar (HBox.)
back-btn (Button. "<-")
for-btn (Button. "->")
reload-btn (Button. "Reload")
url-field (TextField.)
tab-bar (TabPane.)
main-tab (Tab. "Main Page")
add-tab (Tab. "+")
web-view (WebView.)]
(.setPadding nav-bar (Insets. 4))
(.setSpacing nav-bar 2)
(add nav-bar [back-btn for-btn reload-btn url-field])
(HBox/setHgrow url-field Priority/ALWAYS)
(add tab-view [nav-bar web-view])
(.setClosable add-tab false)
(.setContent main-tab tab-view)
(.add (.getTabs tab-bar) main-tab)
(.add (.getTabs tab-bar) add-tab)
(.load (.getEngine web-view) "http://localhost:8080")
(VBox/setVgrow tab-bar Priority/ALWAYS)
(add window [tab-bar])
(show window))))
(defn start-router
"Launch the router (blocking)."
[]
(Router/main nil))
(defn -main
"Launch everything."
[& args]
(start-web-server)
(start-browser)
(comment (start-router)))
| (ns nightweb.core
(:use nightweb.page
nightweb.browser)
(:import net.i2p.router.Router)
(:gen-class))
(defn start-router
"Launch the router (blocking)."
[]
(Router/main nil))
(defn -main
"Launch everything."
[& args]
(start-web-server)
(start-browser)
(comment (start-router)))
|
Remove debug message from update-cb-info in devcards | (ns cards.util
(:require [om.dom :as dom]))
(defn update-cb-info [tag state & params]
(println "update-cb-info" tag state params)
(swap! state (fn [state] (-> state
(update-in [:callbacks tag :counter] inc)
(assoc-in [:callbacks tag :params] params)))))
(defn render-cb-info [tag state label]
(let [{:keys [counter params]} (get-in @state [:callbacks tag])]
(dom/div #js {:style #js {:marginTop "1rem"}}
(dom/strong nil "Callback info: " label)
(dom/div nil (str "Triggered " (or counter 0) " times"))
(dom/div nil "Parameters: " (dom/code nil (str params))))))
| (ns cards.util
(:require [om.dom :as dom]))
(defn update-cb-info [tag state & params]
(swap! state (fn [state] (-> state
(update-in [:callbacks tag :counter] inc)
(assoc-in [:callbacks tag :params] params)))))
(defn render-cb-info [tag state label]
(let [{:keys [counter params]} (get-in @state [:callbacks tag])]
(dom/div #js {:style #js {:marginTop "1rem"}}
(dom/strong nil "Callback info: " label)
(dom/div nil (str "Triggered " (or counter 0) " times"))
(dom/div nil "Parameters: " (dom/code nil (str params))))))
|
Convert date into iso date | (use '[clojure.string :only (split-lines split join capitalize)])
(defn read-tabular-file [filename]
(let [data (slurp filename)
lines (split-lines data)
split-by-tab #(split % #"\t")]
(map split-by-tab lines)))
(defn nameify [s]
(let [words (split s #" ")
word-names (map capitalize words)]
(join " " word-names)))
(defn convert-player [country data]
(let [shirt (data 0)]
{
:id (str country "_" shirt)
:country (nameify country)
:name (nameify (data 1))
:shirt_number shirt
:date_of_birth (data 2)
:position (data 3)
:club (data 4)
:height (data 5)
}))
(def raw (read-tabular-file "2010/brazil.data"))
(println (convert-player "brazil" (first raw)))
| (use '[clojure.string :only (split-lines split join capitalize)])
(defn read-tabular-file [filename]
(let [data (slurp filename)
lines (split-lines data)
split-by-tab #(split % #"\t")]
(map split-by-tab lines)))
(defn nameify [s]
(let [words (split s #" ")
word-names (map capitalize words)]
(join " " word-names)))
(defn iso-date [s]
(let [[day month year] (split s #"/")]
(format "%s-%s-%s" year month day)))
(defn convert-player [country data]
(let [shirt (data 0)]
{
:id (str country "_" shirt)
:country (nameify country)
:name (nameify (data 1))
:shirt_number shirt
:date_of_birth (iso-date (data 2))
:position (data 3)
:club (data 4)
:height (data 5)
}))
(def raw (read-tabular-file "2010/brazil.data"))
(println (convert-player "brazil" (first raw)))
|
Use snapshot version of cider-nrepl | {:user {:signing {:gpg-key "8ED1CE42"}
:dependencies [[alembic "0.2.1"]
[clj-stacktrace "0.2.7"]
[criterium "0.4.2"]
[org.clojure/tools.namespace "0.2.5"]
[slamhound "1.5.3"]
[spyscope "0.1.4"]]
:plugins [[cider/cider-nrepl "0.7.0"]
[codox "0.6.6"]
[jonase/eastwood "0.1.4"]
[lein-ancient "0.5.5" :exclusions [commons-codec]]
[lein-cljsbuild "1.0.3"]
[lein-clojars "0.9.1"]
[lein-cloverage "1.0.2"]
[lein-difftest "2.0.0"]
[lein-kibit "0.0.8"]
[lein-marginalia "0.7.1"]
[lein-pprint "1.1.1"]
[lein-swank "1.4.4"]]
:injections [(require
'[alembic.still :refer [distill]]
'[clojure.repl :refer [source]]
'[clojure.tools.namespace.repl :as repl]
'[criterium.core :refer [bench quick-bench]]
'spyscope.core)]
:aliases {"slamhound" ["run" "-m" "slam.hound"]}
:search-page-size 50}}
| {:user {:signing {:gpg-key "8ED1CE42"}
:dependencies [[alembic "0.2.1"]
[clj-stacktrace "0.2.7"]
[criterium "0.4.2"]
[org.clojure/tools.namespace "0.2.5"]
[slamhound "1.5.3"]
[spyscope "0.1.4"]]
:plugins [[cider/cider-nrepl "0.8.0-SNAPSHOT"]
[codox "0.6.6"]
[jonase/eastwood "0.1.4"]
[lein-ancient "0.5.5" :exclusions [commons-codec]]
[lein-cljsbuild "1.0.3"]
[lein-clojars "0.9.1"]
[lein-cloverage "1.0.2"]
[lein-difftest "2.0.0"]
[lein-kibit "0.0.8"]
[lein-marginalia "0.7.1"]
[lein-pprint "1.1.1"]
[lein-swank "1.4.4"]]
:injections [(require
'[alembic.still :refer [distill]]
'[clojure.repl :refer [source]]
'[clojure.tools.namespace.repl :as repl]
'[criterium.core :refer [bench quick-bench]]
'spyscope.core)]
:aliases {"slamhound" ["run" "-m" "slam.hound"]}
:search-page-size 50}}
|
Add some pretty print configuration for lein | {:user {:ultra {:color-scheme :solarized_dark
:stacktraces true}
:plugins [[lein-try "0.4.3"]
[lein-ancient "0.6.10-SNAPSHOT"]
[lein-kibit "0.1.2"]
[jonase/eastwood "0.2.3"]
;[venantius/ultra "0.5.0"]
]}}
| {:user {:ultra {:color-scheme :solarized_dark
:stacktraces true
:repl true
:java true
:tests true}
:plugins [[lein-try "0.4.3"]
[lein-ancient "0.6.10-SNAPSHOT"]
[lein-kibit "0.1.2"]
[jonase/eastwood "0.2.3"]
;[venantius/ultra "0.5.1"]
]
:repl-options {:init (set! *print-length* 42)}
}}
|
Use print-cause-trace instead of print-stack-trace. | (ns incise.watcher
(:require [taoensso.timbre :refer [error]]
[clojure.stacktrace :refer [print-stack-trace]]
[watchtower.core :refer [watcher rate file-filter extensions
on-change]]))
(defn log-exceptions [func]
"Log (i.e. print) exceptions received from the given function."
(let [out *out*
err *err*]
(fn [& args]
(binding [*out* out
*err* err]
(try
(apply func args)
(catch Exception e
(error (with-out-str (print-stack-trace e)))))))))
(defn per-change [change-fn]
(fn [files]
(doseq [file files]
(change-fn file))))
(defn watch
[change-fn]
(watcher ["resources/posts/" "resources/pages/"]
(rate 300)
(on-change (-> change-fn
per-change
log-exceptions))))
(def watching nil)
(defn start-watching [& args]
(alter-var-root #'watching (fn [& _] (apply watch args))))
(defn stop-watching []
(when watching
(future-cancel watching)))
| (ns incise.watcher
(:require [taoensso.timbre :refer [error]]
[clojure.stacktrace :refer [print-cause-trace]]
[watchtower.core :refer [watcher rate file-filter extensions
on-change]]))
(defn log-exceptions [func]
"Log (i.e. print) exceptions received from the given function."
(let [out *out*
err *err*]
(fn [& args]
(binding [*out* out
*err* err]
(try
(apply func args)
(catch Exception e
(error (with-out-str (print-cause-trace e)))))))))
(defn per-change [change-fn]
(fn [files]
(doseq [file files]
(change-fn file))))
(defn watch
[change-fn]
(watcher ["resources/posts/" "resources/pages/"]
(rate 300)
(on-change (-> change-fn
per-change
log-exceptions))))
(def watching nil)
(defn start-watching [& args]
(alter-var-root #'watching (fn [& _] (apply watch args))))
(defn stop-watching []
(when watching
(future-cancel watching)))
|
Use idiomatic clojure for str/starts-with? | (ns com.wsscode.pathom.test
(:require [com.wsscode.pathom.core :as p]))
(defn self-reader [{:keys [ast query] :as env}]
(if query
(p/join env)
(name (:key ast))))
#?(:clj
(defn sleep-reader [{:keys [ast query] :as env}]
(if-let [time (p/ident-value env)]
(do
(Thread/sleep time)
(if query
(p/join env)
(name (first (:key ast)))))
::p/continue)))
(defn repeat-reader [env]
(if-let [key (p/ident-key env)]
(if (some-> (name key) (.startsWith "repeat."))
(p/join-seq env (map (constantly {}) (range (p/ident-value env))))
::p/continue)
::p/continue))
| (ns com.wsscode.pathom.test
(:require [com.wsscode.pathom.core :as p]
[clojure.string :as str]))
(defn self-reader [{:keys [ast query] :as env}]
(if query
(p/join env)
(name (:key ast))))
#?(:clj
(defn sleep-reader [{:keys [ast query] :as env}]
(if-let [time (p/ident-value env)]
(do
(Thread/sleep time)
(if query
(p/join env)
(name (first (:key ast)))))
::p/continue)))
(defn repeat-reader [env]
(if-let [key (p/ident-key env)]
(if (some-> (name key) (str/starts-with? "repeat."))
(p/join-seq env (map (constantly {}) (range (p/ident-value env))))
::p/continue)
::p/continue))
|
Remove created-at from daily report | (ns servisne-info.tasks.daily-report
(:require [servisne-info.logging :as l]
[servisne-info.notifications :refer [send-daily-report-email]]
[servisne-info.repository :as repo]
[servisne-info.tasks.task-definition :refer [deftask]]))
(defn- format-event-data [event]
(l/format-data (dissoc event :_id)))
(defn send-daily-report []
(let [events (repo/find-events-for-yesterday)]
(send-daily-report-email (map format-event-data events))))
(def send-daily-report-task
(deftask "send daily report"
(send-daily-report)))
| (ns servisne-info.tasks.daily-report
(:require [servisne-info.logging :as l]
[servisne-info.notifications :refer [send-daily-report-email]]
[servisne-info.repository :as repo]
[servisne-info.tasks.task-definition :refer [deftask]]))
(defn- format-event-data [event]
(l/format-data (dissoc event :_id :created-at)))
(defn send-daily-report []
(let [events (repo/find-events-for-yesterday)]
(send-daily-report-email (map format-event-data events))))
(def send-daily-report-task
(deftask "send daily report"
(send-daily-report)))
|
Make results more readible in dark theme | (ns planck.themes
(:require [planck.from.io.aviso.ansi :as ansi]))
(def ^:private colorize-fn-dumb identity)
(def ^:private colorize-off-dumb "")
(def ^:private dumb
{:results-fn colorize-fn-dumb
:ex-msg-fn colorize-fn-dumb
:ex-stack-fn colorize-fn-dumb
:err-font colorize-off-dumb
:verbose-font colorize-off-dumb
:reset-font colorize-off-dumb})
(def ^:private theme-ansi-base
{:reset-font ansi/reset-font})
(def ^:private light
(merge theme-ansi-base
{:results-fn ansi/blue
:ex-msg-fn ansi/bold-red
:ex-stack-fn ansi/green
:err-font ansi/red-font
:verbose-font ansi/white-font}))
(def ^:private dark
(merge theme-ansi-base
{:results-fn ansi/blue
:ex-msg-fn ansi/bold-red
:ex-stack-fn ansi/green
:err-font ansi/red-font
:verbose-font ansi/white-font}))
(def ^:private themes
{:plain dumb
:light light
:dark dark})
(defn get-theme
[theme-id]
(get themes theme-id dumb))
| (ns planck.themes
(:require [planck.from.io.aviso.ansi :as ansi]))
(def ^:private colorize-fn-dumb identity)
(def ^:private colorize-off-dumb "")
(def ^:private dumb
{:results-fn colorize-fn-dumb
:ex-msg-fn colorize-fn-dumb
:ex-stack-fn colorize-fn-dumb
:err-font colorize-off-dumb
:verbose-font colorize-off-dumb
:reset-font colorize-off-dumb})
(def ^:private theme-ansi-base
{:reset-font ansi/reset-font})
(def ^:private light
(merge theme-ansi-base
{:results-fn ansi/blue
:ex-msg-fn ansi/bold-red
:ex-stack-fn ansi/green
:err-font ansi/red-font
:verbose-font ansi/white-font}))
(def ^:private dark
(merge theme-ansi-base
{:results-fn ansi/bold-blue
:ex-msg-fn ansi/bold-red
:ex-stack-fn ansi/green
:err-font ansi/red-font
:verbose-font ansi/white-font}))
(def ^:private themes
{:plain dumb
:light light
:dark dark})
(defn get-theme
[theme-id]
(get themes theme-id dumb))
|
Set :externs value for :advanced compilation. | (defproject {{name}} "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
[quil "2.2.0-SNAPSHOT"]
[org.clojure/clojurescript "0.0-2268"]]
:plugins [[lein-cljsbuild "1.0.3"]]
:hooks [leiningen.cljsbuild]
:cljsbuild
{:builds [{:source-paths ["src"]
:compiler
{:output-to "web/js/main.js"
:optimizations :whitespace
:pretty-print true}}]}) | (defproject {{name}} "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
[quil "2.2.0-SNAPSHOT"]
[org.clojure/clojurescript "0.0-2268"]]
:plugins [[lein-cljsbuild "1.0.3"]]
:hooks [leiningen.cljsbuild]
:cljsbuild
{:builds [{:source-paths ["src"]
:compiler
{:output-to "web/js/main.js"
:externs ["externs/processing-externs.js"]
:optimizations :whitespace
:pretty-print true}}]}) |
Use port 5600, as before | (ns ^{:clojure.tools.namespace.repl/load false}
nrepl
(:require
[clojure.tools.nrepl.server :as nrepl.server]
[cider.nrepl]
[cemerick.piggieback]
[refactor-nrepl.middleware :as refactor.nrepl]))
(defn start-nrepl
[]
(let [server
(nrepl.server/start-server
:handler
(apply nrepl.server/default-handler
(conj (map #'cider.nrepl/resolve-or-fail cider.nrepl/cider-middleware)
#'refactor.nrepl/wrap-refactor
#'cemerick.piggieback/wrap-cljs-repl
)))]
(spit ".nrepl-port" (:port server))
(println "nREPL port:" (:port server))
server))
(def server (start-nrepl))
| (ns ^{:clojure.tools.namespace.repl/load false}
nrepl
(:require
[clojure.tools.nrepl.server :as nrepl.server]
[cider.nrepl]
[cemerick.piggieback]
[refactor-nrepl.middleware :as refactor.nrepl]))
(defn start-nrepl
[opts]
(let [server
(nrepl.server/start-server
:port (:port opts)
:handler
(apply nrepl.server/default-handler
(conj (map #'cider.nrepl/resolve-or-fail cider.nrepl/cider-middleware)
#'refactor.nrepl/wrap-refactor
#'cemerick.piggieback/wrap-cljs-repl
)))]
(spit ".nrepl-port" (:port server))
(println "nREPL port:" (:port server))
server))
(def server (start-nrepl {:port 5600}))
|
Fix a bug in `lines->numbers`. | (ns advent2017.core)
(defn read-puzzle
([name]
(read-puzzle name identity))
([name xform]
(-> (clojure.java.io/file (str "../2017/" name))
(slurp)
xform)))
(defn enumerate [xs]
(map vector (range) xs))
(defn ->lines [s]
(clojure.string/split s #"\n"))
(defn ->words [s]
(clojure.string/split s #"\s+"))
(defn ->numbers [xs]
(map #(Integer/parseInt %) xs))
(def lines->numbers (partial map words->numbers))
(defn csv->numbers [s]
(->numbers (clojure.string/split s #",")))
(defn manhattan-distance
([[x2 y2]]
(manhattan-distance [0 0] [x2 y2]))
([[x1 y1] [x2 y2]]
(+ (Math/abs (- x1 x2))
(Math/abs (- y1 y2)))))
(defn bfs-lazy [tree pred f]
((fn step [queue]
(lazy-seq
(when (seq queue)
(let [[[node & children] depth] (peek queue)
xs (step (into (pop queue)
(map vector children (repeat (inc depth)))))]
(if (pred node depth children)
(cons (f node depth children) xs)
xs)))))
(conj clojure.lang.PersistentQueue/EMPTY [tree 0])))
| (ns advent2017.core)
(defn read-puzzle
([name]
(read-puzzle name identity))
([name xform]
(-> (clojure.java.io/file (str "../2017/" name))
(slurp)
xform)))
(defn enumerate [xs]
(map vector (range) xs))
(defn ->lines [s]
(clojure.string/split s #"\n"))
(defn ->words [s]
(clojure.string/split s #"\s+"))
(defn ->numbers [xs]
(map #(Integer/parseInt %) xs))
(def lines->numbers (comp (partial map (comp ->numbers ->words))
->lines))
(defn csv->numbers [s]
(->numbers (clojure.string/split s #",")))
(defn manhattan-distance
([[x2 y2]]
(manhattan-distance [0 0] [x2 y2]))
([[x1 y1] [x2 y2]]
(+ (Math/abs (- x1 x2))
(Math/abs (- y1 y2)))))
(defn bfs-lazy [tree pred f]
((fn step [queue]
(lazy-seq
(when (seq queue)
(let [[[node & children] depth] (peek queue)
xs (step (into (pop queue)
(map vector children (repeat (inc depth)))))]
(if (pred node depth children)
(cons (f node depth children) xs)
xs)))))
(conj clojure.lang.PersistentQueue/EMPTY [tree 0])))
|
Use `defonce` instead of `def` | (ns {{ns-name}}.routes
(:require
[bidi.bidi :as bidi]
[pushy.core :as pushy]
[re-frame.core :as re-frame]
[{{ns-name}}.events :as events]))
(defmulti panels identity)
(defmethod panels :default [] [:div "No panel found for this route."])
(def routes
(atom
["/" {"" :home
"about" :about}]))
(defn parse
[url]
(bidi/match-route @routes url))
(defn url-for
[& args]
(apply bidi/path-for (into [@routes] args)))
(defn dispatch
[route]
(let [panel (keyword (str (name (:handler route)) "-panel"))]
(re-frame/dispatch [::events/set-active-panel panel])))
(def history
(pushy/pushy dispatch parse))
(defn navigate!
[handler]
(pushy/set-token! history (url-for handler)))
(defn start!
[]
(pushy/start! history))
(re-frame/reg-fx
:navigate
(fn [handler]
(navigate! handler)))
| (ns {{ns-name}}.routes
(:require
[bidi.bidi :as bidi]
[pushy.core :as pushy]
[re-frame.core :as re-frame]
[{{ns-name}}.events :as events]))
(defmulti panels identity)
(defmethod panels :default [] [:div "No panel found for this route."])
(def routes
(atom
["/" {"" :home
"about" :about}]))
(defn parse
[url]
(bidi/match-route @routes url))
(defn url-for
[& args]
(apply bidi/path-for (into [@routes] args)))
(defn dispatch
[route]
(let [panel (keyword (str (name (:handler route)) "-panel"))]
(re-frame/dispatch [::events/set-active-panel panel])))
(defonce history
(pushy/pushy dispatch parse))
(defn navigate!
[handler]
(pushy/set-token! history (url-for handler)))
(defn start!
[]
(pushy/start! history))
(re-frame/reg-fx
:navigate
(fn [handler]
(navigate! handler)))
|
Add messaging to notify-join test. Switch defs to let | (ns onyx.log.notify-join-cluster-test
(:require [onyx.extensions :as extensions]
[onyx.log.entry :refer [create-log-entry]]
[midje.sweet :refer :all]))
(def entry (create-log-entry :notify-join-cluster {:observer :d :subject :a}))
(def f (partial extensions/apply-log-entry entry))
(def rep-diff (partial extensions/replica-diff entry))
(def rep-reactions (partial extensions/reactions entry))
(def old-replica {:pairs {:a :b :b :c :c :a} :prepared {:a :d} :peers [:a :b :c]})
(let [new-replica (f old-replica)
diff (rep-diff old-replica new-replica)
reactions (rep-reactions old-replica new-replica diff {:id :d})]
(fact diff => {:observer :d :subject :b :accepted-joiner :d :accepted-observer :a})
(fact reactions => [{:fn :accept-join-cluster :args diff :immediate? true}])
(fact (rep-reactions old-replica new-replica diff {:id :a}) => nil)
(fact (rep-reactions old-replica new-replica diff {:id :b}) => nil)
(fact (rep-reactions old-replica new-replica diff {:id :c}) => nil))
| (ns onyx.log.notify-join-cluster-test
(:require [onyx.extensions :as extensions]
[onyx.log.entry :refer [create-log-entry]]
[onyx.messaging.aeron :as aeron]
[com.stuartsierra.component :as component]
[midje.sweet :refer :all]))
(def peer-config
(:peer-config (read-string (slurp (clojure.java.io/resource "test-config.edn")))))
(def messaging
(aeron/aeron {:opts peer-config}))
(component/start messaging)
(try
(let [entry (create-log-entry :notify-join-cluster {:observer :d :subject :a})
f (partial extensions/apply-log-entry entry)
rep-diff (partial extensions/replica-diff entry)
rep-reactions (partial extensions/reactions entry)
old-replica {:pairs {:a :b :b :c :c :a} :prepared {:a :d} :peers [:a :b :c]}
new-replica (f old-replica)
diff (rep-diff old-replica new-replica)
reactions (rep-reactions old-replica new-replica diff {:id :d :messenger messaging})]
(fact diff => {:observer :d :subject :b :accepted-joiner :d :accepted-observer :a})
(fact reactions => [{:fn :accept-join-cluster :args diff :immediate? true :site-resources {:aeron/port 40201}}])
(fact (rep-reactions old-replica new-replica diff {:id :a}) => nil)
(fact (rep-reactions old-replica new-replica diff {:id :b}) => nil)
(fact (rep-reactions old-replica new-replica diff {:id :c}) => nil))
(finally
(component/stop messaging)))
|
Fix and change obj-select(v) functions, now more keyword-y | (ns lo-cash.core
(:require [clojure.browser.repl :as repl]))
(defn -main []
(.log js/console "connecting...")
(repl/connect "http://localhost:9000/repl"))
(defn obj-select
"Selects the given keys from a JS object and returns a keywordized map"
[obj [& keys]]
(into {}
(map #([(keyword %) (aget obj %)])
keys)))
(defn obj-selectv
"Selects the given keys from a JS object and returns a vector of their values"
[obj [& keys]]
(mapv #(aget obj %) keys))
| (ns lo-cash.core
(:require [clojure.browser.repl :as repl]))
(defn -main []
(.log js/console "connecting...")
(repl/connect "http://localhost:9000/repl"))
(defn obj-select
"Selects the given keys from a JS object and returns a keywordized map"
[obj & keys]
(into {}
(map (fn [k]
[(keyword k) (aget obj (name k))])
keys)))
(defn obj-selectv
"Selects the given keys from a JS object and returns a vector of their values"
[obj & keys]
(mapv #(aget obj (name %)) keys))
|
Add unwrap function to be used for arguments. | (ns guangyin.internal.types
(:import (guangyin.internal.types ObjectWrapper TemporalAmountWrapper
TemporalAccessorWrapper TemporalWrapper)))
(defmethod print-method ObjectWrapper
[obj writer]
(print-method @obj writer))
(defn wrapped-instance?
[^Class c x]
(or (instance? c x) ; FIXME This should be removed
(and (instance? ObjectWrapper x)
(instance? c @x))))
(defmacro wrap-object
[& body]
`(ObjectWrapper. (do ~@body)))
(defmacro wrap-temporal-accessor
[keymap & body]
`(TemporalAccessorWrapper. ~keymap (do ~@body)))
(defmacro wrap-temporal
[keymap & body]
`(TemporalWrapper. ~keymap (do ~@body)))
(defmacro wrap-temporal-amount
[keymap & body]
`(TemporalAmountWrapper. ~keymap (do ~@body)))
| (ns guangyin.internal.types
(:import (guangyin.internal.types ObjectWrapper TemporalAmountWrapper
TemporalAccessorWrapper TemporalWrapper)))
(defmethod print-method ObjectWrapper
[obj writer]
(print-method @obj writer))
(defn wrapped-instance?
[^Class c x]
(or (instance? c x) ; FIXME This should be removed
(and (instance? ObjectWrapper x)
(instance? c @x))))
(defn unwrap
[x]
(if (instance? ObjectWrapper x) @x x))
(defmacro wrap-object
[& body]
`(ObjectWrapper. (do ~@body)))
(defmacro wrap-temporal-accessor
[keymap & body]
`(TemporalAccessorWrapper. ~keymap (do ~@body)))
(defmacro wrap-temporal
[keymap & body]
`(TemporalWrapper. ~keymap (do ~@body)))
(defmacro wrap-temporal-amount
[keymap & body]
`(TemporalAmountWrapper. ~keymap (do ~@body)))
|
Test that the value remains unchanged when there's an error. | (ns klangmeister.test.processing
(:require [cljs.test :refer-macros [deftest testing is]]
[klangmeister.processing :as processing]
[klangmeister.framework :as framework]
[klangmeister.compile.eval :as eval]
[klangmeister.actions :as action]))
(def ignore! (constantly nil))
(deftest stopping
(testing
(is
(=
(framework/process (action/->Stop :foo) ignore! {:foo {:looping? true}})
{:foo {:looping? false}}))
(is
(=
(framework/process (action/->Stop :foo) ignore! {:foo {:looping? false}})
{:foo {:looping? false}}))))
(deftest refreshing
(testing
(is
(=
(framework/process (action/->Refresh "(phrase [1] [69])" :foo) ignore! {})
{:foo {:value [{:time 0 :pitch 69 :duration 1}] :text "(phrase [1] [69])" :error nil}}))
(is
((comp :error :foo)
(framework/process (action/->Refresh "(phrase [1] [6" :foo) ignore! {})))))
| (ns klangmeister.test.processing
(:require [cljs.test :refer-macros [deftest testing is]]
[klangmeister.processing :as processing]
[klangmeister.framework :as framework]
[klangmeister.compile.eval :as eval]
[klangmeister.actions :as action]))
(def ignore! (constantly nil))
(deftest stopping
(testing
(is
(=
(framework/process (action/->Stop :foo) ignore! {:foo {:looping? true}})
{:foo {:looping? false}}))
(is
(=
(framework/process (action/->Stop :foo) ignore! {:foo {:looping? false}})
{:foo {:looping? false}}))))
(deftest refreshing
(testing
(is
(=
(framework/process (action/->Refresh "(phrase [1] [69])" :foo) ignore! {})
{:foo {:value [{:time 0 :pitch 69 :duration 1}] :text "(phrase [1] [69])" :error nil}}))
(is
((comp :error :foo)
(framework/process (action/->Refresh "(phrase [1] [6" :foo) ignore! {})))
(is
(=
(-> (framework/process (action/->Refresh "(phrase [1] [6" :foo) ignore! {:foo {:value [{:time 0 :pitch 69 :duration 1}]}})
:foo
:value)
[{:time 0 :pitch 69 :duration 1}]))))
|
Rename tf-corpus variable to term-frequency-corpus. | (ns analyze-data.tf-idf.inverse-document-frequency)
(defn document-frequency
"Return a map from term to number of documents it appears in."
[tf-corpus]
(let [count-term (fn [m term] (assoc m term (inc (get m term 0))))
term-keys (mapcat keys tf-corpus)]
(reduce count-term {} term-keys)))
(defn calc-inverse-document-frequency
"Calculate inverse document frequency.
num-documents: the total number of documents
num-documents-with-term: the number of documents containing the term we are
calculating for"
[num-documents num-documents-with-term]
(Math/log (/ num-documents num-documents-with-term)))
(defn inverse-document-frequency
"Given
tf-corpus: a sequence of term-frequency maps where each one represents a
single document
Return a map from term to its inverse document frequency (as defined at
https://en.wikipedia.org/wiki/Tf–idf#Inverse_document_frequency_2)."
[tf-corpus]
(let [num-documents (count tf-corpus)
document-frequencies (document-frequency tf-corpus)
assoc-idf (fn [m term num-documents-with-term]
(assoc m
term
(calc-inverse-document-frequency
num-documents
num-documents-with-term)))]
(reduce-kv assoc-idf {} document-frequencies)))
| (ns analyze-data.tf-idf.inverse-document-frequency)
(defn document-frequency
"Return a map from term to number of documents it appears in."
[term-frequency-corpus]
(let [count-term (fn [m term] (assoc m term (inc (get m term 0))))
term-keys (mapcat keys term-frequency-corpus)]
(reduce count-term {} term-keys)))
(defn calc-inverse-document-frequency
"Calculate inverse document frequency.
num-documents: the total number of documents
num-documents-with-term: the number of documents containing the term we are
calculating for"
[num-documents num-documents-with-term]
(Math/log (/ num-documents num-documents-with-term)))
(defn inverse-document-frequency
"Given
term-frequency-corpus: a sequence of term-frequency maps where each one
represents a single document
Return a map from term to its inverse document frequency (as defined at
https://en.wikipedia.org/wiki/Tf–idf#Inverse_document_frequency_2)."
[term-frequency-corpus]
(let [num-documents (count term-frequency-corpus)
document-frequencies (document-frequency term-frequency-corpus)
assoc-idf (fn [m term num-documents-with-term]
(assoc m
term
(calc-inverse-document-frequency
num-documents
num-documents-with-term)))]
(reduce-kv assoc-idf {} document-frequencies)))
|
Print output to console when running with debug flags | (ns whitman.core
(:require [whitman.config :as config]
[whitman.crawler :as crawler]
[whitman.db :as db]
[whitman.writer :as writer])
(:gen-class))
(defn exit [code msg]
(binding [*out* *err*]
(do (println msg)
(System/exit code))))
(defn do-crawl [cfg writer]
(let [users (crawler/records cfg)
docs (map #(crawler/sample-docs cfg %) users)]
(doseq [d docs] (writer/write writer cfg (:query d) (:insert d)))))
(defn writer [args]
:db)
(defn -main [& args]
(if (< (count args) 1)
(exit 1 "No configuration file specified")
(do-crawl (config/read-config (last args)) (writer args))))
| (ns whitman.core
(:require [whitman.config :as config]
[whitman.crawler :as crawler]
[whitman.db :as db]
[whitman.writer :as writer])
(:gen-class))
(defn exit [code msg]
(binding [*out* *err*]
(do (println msg)
(System/exit code))))
(defn do-crawl [cfg writer]
(let [users (crawler/records cfg)
docs (map #(crawler/sample-docs cfg %) users)]
(doseq [d docs] (writer/write writer cfg (:query d) (:insert d)))))
(defn writer [args]
(case (nth args 0)
"-d" :console
"--debug" :console
:db))
(defn -main [& args]
(if (< (count args) 1)
(exit 1 "No configuration file specified")
(do-crawl (config/read-config (last args)) (writer args))))
|
Test what the nonce is | (ns caesium.magicnonce.secretbox-test
(:require [caesium.magicnonce.secretbox :as ms]
[caesium.crypto.secretbox :as s]
[caesium.crypto.secretbox-test :as st]
[clojure.test :refer [deftest is]]
[caesium.util :as u]))
(deftest xor-test
(let [one (byte-array [1 0 1])
two (byte-array [0 1 0])
out (byte-array [0 0 0])]
(is (identical? (#'ms/xor! out one two) out))
(is (u/array-eq (byte-array [1 1 1]) out)))
(let [one (byte-array [1 0 1])
two (byte-array [0 1 0])]
(is (identical? (#'ms/xor-inplace! one two) one))
(is (u/array-eq (byte-array [1 1 1]) one))))
(deftest secretbox-pfx-test
(let [nonce (byte-array (range s/noncebytes))
ctext (ms/secretbox-pfx st/ptext nonce st/secret-key)]
(is (= (+ s/noncebytes
(alength ^bytes st/ptext)
s/macbytes)
(alength ^bytes ctext)))))
| (ns caesium.magicnonce.secretbox-test
(:require [caesium.magicnonce.secretbox :as ms]
[caesium.crypto.secretbox :as s]
[caesium.crypto.secretbox-test :as st]
[clojure.test :refer [deftest is]]
[caesium.util :as u]))
(deftest xor-test
(let [one (byte-array [1 0 1])
two (byte-array [0 1 0])
out (byte-array [0 0 0])]
(is (identical? (#'ms/xor! out one two) out))
(is (u/array-eq (byte-array [1 1 1]) out)))
(let [one (byte-array [1 0 1])
two (byte-array [0 1 0])]
(is (identical? (#'ms/xor-inplace! one two) one))
(is (u/array-eq (byte-array [1 1 1]) one))))
(deftest secretbox-pfx-test
(let [nonce (byte-array (range s/noncebytes))
ctext (ms/secretbox-pfx st/ptext nonce st/secret-key)]
(is (= (+ s/noncebytes
(alength ^bytes st/ptext)
s/macbytes)
(alength ^bytes ctext)))
(is (= (range s/noncebytes)
(take s/noncebytes ctext)))))
|
Use more clojure idomatic _last_ function. | (ns bob (:require [clojure.string :as str]))
(defn response-for [x]
(cond
(str/blank? x) "Fine, be that way."
(= (str/upper-case x) x) "Woah, chill out!"
(= \? (get x (- (count x) 1))) "Sure."
:else "Whatever."
)
) | (ns bob (:require [clojure.string :as str]))
(defn response-for [x]
(cond
(str/blank? x) "Fine, be that way."
(= (str/upper-case x) x) "Woah, chill out!"
(= \? (last x)) "Sure."
:else "Whatever."
)
) |
Bump version number to 0.1.1 | (defproject io.nervous/fink-nottle "0.1.0"
:description "Asynchronous Clojure client for the Amazon SNS service"
:url "https://github.com/nervous-systems/fink-nottle"
:license {:name "Unlicense" :url "http://unlicense.org/UNLICENSE"}
:scm {:name "git" :url "https://github.com/nervous-systems/fink-nottle"}
:deploy-repositories [["clojars" {:creds :gpg}]]
:signing {:gpg-key "moe@nervous.io"}
:global-vars {*warn-on-reflection* true}
:source-paths ["src" "test"]
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/core.async "0.1.346.0-17112a-alpha"]
[org.clojure/data.codec "0.1.0"]
[io.nervous/eulalie "0.3.2"]
[io.nervous/glossop "0.1.0"]
[prismatic/plumbing "0.4.1"]
[cheshire "5.5.0"]]
:exclusions [[org.clojure/clojure]])
| (defproject io.nervous/fink-nottle "0.1.1"
:description "Asynchronous Clojure client for the Amazon SNS service"
:url "https://github.com/nervous-systems/fink-nottle"
:license {:name "Unlicense" :url "http://unlicense.org/UNLICENSE"}
:scm {:name "git" :url "https://github.com/nervous-systems/fink-nottle"}
:deploy-repositories [["clojars" {:creds :gpg}]]
:signing {:gpg-key "moe@nervous.io"}
:global-vars {*warn-on-reflection* true}
:source-paths ["src" "test"]
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/core.async "0.1.346.0-17112a-alpha"]
[org.clojure/data.codec "0.1.0"]
[io.nervous/eulalie "0.3.2"]
[io.nervous/glossop "0.1.0"]
[prismatic/plumbing "0.4.1"]
[cheshire "5.5.0"]]
:exclusions [[org.clojure/clojure]])
|
Move lein-midje into dev plugins | (defproject basex "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:java-source-paths ["src/main/java"]
:source-paths ["src/main/clojure"]
:dependencies [[org.clojure/clojure "1.5.1"] ]
:profiles { :dev { :repositories { "BaseX Maven Repository" "http://files.basex.org/maven" }
:dependencies [[org.basex/basex "7.8.2"]
[midje "1.5.1"]
[lein-midje "3.0.0"]
[me.raynes/fs "1.4.4"]]}})
| (defproject basex "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:java-source-paths ["src/main/java"]
:source-paths ["src/main/clojure"]
:dependencies [[org.clojure/clojure "1.5.1"] ]
:profiles { :dev { :repositories { "BaseX Maven Repository" "http://files.basex.org/maven" }
:plugins [[lein-midje "3.0.0"]]
:dependencies [[org.basex/basex "7.8.2"]
[midje "1.5.1"]
[me.raynes/fs "1.4.4"]]}})
|
Set clojure version to the las stable: 1.6.0 | (defproject suricatta "0.1.0-SNAPSHOT"
:description "High level sql toolkit for clojure (backed by jooq library)"
:url "http://example.com/FIXME"
:license {:name "Apache 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.txt"}
:dependencies [[org.clojure/clojure "1.7.0-alpha2"]
[org.jooq/jooq "3.4.2"]
[clojure.jdbc "0.3.0-SNAPSHOT"]
[postgresql "9.3-1101.jdbc41"]
[com.h2database/h2 "1.3.176"]])
| (defproject suricatta "0.1.0-SNAPSHOT"
:description "High level sql toolkit for clojure (backed by jooq library)"
:url "http://example.com/FIXME"
:license {:name "Apache 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.txt"}
:dependencies [[org.clojure/clojure "1.6.0"]
[org.jooq/jooq "3.4.2"]
[clojure.jdbc "0.3.0-SNAPSHOT"]
[postgresql "9.3-1101.jdbc41"]
[com.h2database/h2 "1.3.176"]])
|
Simplify location of data dir | (ns nightmod.utils
(:require [clojure.java.io :as io])
(:import [java.text SimpleDateFormat]))
(def ^:const properties-file ".properties")
(def main-dir (atom nil))
(def project-dir (atom nil))
(def error (atom nil))
(defn get-data-dir
[]
(let [home-dir (System/getProperty "user.home")
app-name "Nightmod"
app-name-lower (clojure.string/lower-case app-name)
osx-dir (io/file home-dir "Library" "Application Support" app-name)
win-dir (io/file home-dir "AppData" "Roaming" app-name)]
(.getCanonicalPath
(cond
(.exists (.getParentFile osx-dir)) osx-dir
(.exists (.getParentFile win-dir)) win-dir
:else (if-let [config-dir (System/getenv "XDG_CONFIG_HOME")]
(io/file config-dir app-name-lower)
(io/file home-dir ".config" app-name-lower))))))
(defn format-date
[unix-time]
(.format (SimpleDateFormat. "yyyy.MM.dd HH:mm:ss") unix-time))
(defn new-project!
[template]
(let [project-name (str (System/currentTimeMillis))
project-file (io/file @main-dir project-name)]
(.mkdirs project-file)
(doseq [f (-> (io/resource template) io/file .listFiles)]
(io/copy f (io/file project-file (.getName f))))
(.getCanonicalPath project-file)))
| (ns nightmod.utils
(:require [clojure.java.io :as io])
(:import [java.text SimpleDateFormat]))
(def ^:const properties-file ".properties")
(def main-dir (atom nil))
(def project-dir (atom nil))
(def error (atom nil))
(defn get-data-dir
[]
(.getCanonicalPath (io/file (System/getProperty "user.home") "nightmod")))
(defn format-date
[unix-time]
(.format (SimpleDateFormat. "yyyy.MM.dd HH:mm:ss") unix-time))
(defn new-project!
[template]
(let [project-name (str (System/currentTimeMillis))
project-file (io/file @main-dir project-name)]
(.mkdirs project-file)
(doseq [f (-> (io/resource template) io/file .listFiles)]
(io/copy f (io/file project-file (.getName f))))
(.getCanonicalPath project-file)))
|
Add macro to DRY up exception handling in channel code. | (ns frontend.utils)
(defmacro inspect
"prints the expression '<name> is <value>', and returns the value"
[value]
`(do
(let [name# (quote ~value)
result# ~value]
(print (pr-str name#) "is" (pr-str result#))
result#)))
(defmacro timing
"Evaluates expr and prints the label and the time it took.
Returns the value of expr."
{:added "1.0"}
[label expr]
`(let [global-start# (or (aget js/window "__global_time")
(aset js/window "__global_time" (.getTime (js/Date.))))
start# (.getTime (js/Date.))
ret# ~expr
global-time# (- (.getTime (js/Date.)) global-start#)]
(aset js/window "__global_time" (.getTime (js/Date.)))
(prn (str ~label " elapsed time: " (- (.getTime (js/Date.)) start#) " ms, " global-time# " ms since last"))
ret#))
| (ns frontend.utils)
(defmacro inspect
"prints the expression '<name> is <value>', and returns the value"
[value]
`(do
(let [name# (quote ~value)
result# ~value]
(print (pr-str name#) "is" (pr-str result#))
result#)))
(defmacro timing
"Evaluates expr and prints the label and the time it took.
Returns the value of expr."
{:added "1.0"}
[label expr]
`(let [global-start# (or (aget js/window "__global_time")
(aset js/window "__global_time" (.getTime (js/Date.))))
start# (.getTime (js/Date.))
ret# ~expr
global-time# (- (.getTime (js/Date.)) global-start#)]
(aset js/window "__global_time" (.getTime (js/Date.)))
(prn (str ~label " elapsed time: " (- (.getTime (js/Date.)) start#) " ms, " global-time# " ms since last"))
ret#))
(defmacro swallow-errors
"wraps errors in a try/catch statement, logging issues to the console
and optionally rethrowing them if configured to do so."
[action]
`(try ~action
(catch js/Error e#
(merror e#)
(when (:rethrow-errors? initial-query-map)
(js* "debugger;")
(throw e#)))))
|
Make the REPL work with literals. | (ns leipzig-live.core
(:require [reagent.core :as reagent :refer [atom]]
[reagent.session :as session]
[secretary.core :as secretary :include-macros true]
[accountant.core :as accountant]
[cljs.js :as cljs]))
;; -------------------------
;; Model
(defonce music (atom "7"))
;; -------------------------
;; Behaviour
(defonce compiler-state (cljs/empty-state))
(defn evaluate
[expr-str]
(cljs/eval-str
compiler-state
expr-str
nil
{:eval cljs/js-eval}
#(print-str expr-str " evaluates to " %)))
;; -------------------------
;; Views
(defn home-page []
[:div [:h1 "Welcome to Leipzig Live!"]
[:div [:input {:type "text"
:value (-> music deref print-str)
:on-change #(reset! music (-> % .-target .-value))}]]
[:div
(evaluate @music)]])
(defn current-page []
[:div [(session/get :current-page)]])
;; -------------------------
;; Routes
(secretary/defroute "/" []
(session/put! :current-page #'home-page))
;; -------------------------
;; Initialize app
(defn mount-root []
(reagent/render [current-page] (.getElementById js/document "app")))
(defn init! []
(accountant/configure-navigation!)
(accountant/dispatch-current!)
(mount-root))
| (ns leipzig-live.core
(:require [reagent.core :as reagent :refer [atom]]
[reagent.session :as session]
[secretary.core :as secretary :include-macros true]
[accountant.core :as accountant]
[cljs.js :as cljs]))
;; -------------------------
;; Model
(defonce music (atom ""))
;; -------------------------
;; Behaviour
(defn identify
"Hack to make literal values still evaluate."
[expr-str]
(str "(identity " expr-str ")"))
(defonce compiler-state (cljs/empty-state))
(defn evaluate
[expr-str]
(cljs/eval-str
compiler-state
(identify expr-str)
nil
{:eval cljs/js-eval}
#(:value %)))
;; -------------------------
;; Views
(defn home-page []
[:div [:h1 "Welcome to Leipzig Live!"]
[:div [:input {:type "text"
:value (-> music deref print-str)
:on-change #(reset! music (-> % .-target .-value))}]]
[:div
(evaluate @music)]])
(defn current-page []
[:div [(session/get :current-page)]])
;; -------------------------
;; Routes
(secretary/defroute "/" []
(session/put! :current-page #'home-page))
;; -------------------------
;; Initialize app
(defn mount-root []
(reagent/render [current-page] (.getElementById js/document "app")))
(defn init! []
(accountant/configure-navigation!)
(accountant/dispatch-current!)
(mount-root))
|
Test web socket connection works | (ns dasha.core)
(defn log
[data]
(.log js/console (str data)))
(log "test")
| (ns dasha.core
(:require-macros
[cljs.core.async.macros :as asyncm :refer (go go-loop)])
(:require
;; <other stuff>
[cljs.core.async :as async :refer (<! >! put! chan)]
[taoensso.sente :as sente :refer (cb-success?)]))
(defn log
[data]
(.log js/console (str data)))
(defn route-receive
[[event data]]
(log (str "received " event " with data: " data))
)
(defn route-event
[[event-id data :as all]]
(case event-id
:chsk/state (log (str "first open: " (:first-open? data)))
:chsk/recv (route-receive data)
(log (str "undefined event: " all))))
(let [{:keys [chsk ch-recv send-fn state]}
(sente/make-channel-socket! "/chsk" ; Note the same path as before
{:type :auto ; e/o #{:auto :ajax :ws}
})]
(def chsk chsk)
(def ch-chsk ch-recv) ; ChannelSocket's receive channel
(def chsk-send! send-fn) ; ChannelSocket's send API fn
(def chsk-state state) ; Watchable, read-only atom
(go
(while true
(route-event (:event (<! ch-recv)))))
)
|
Throw an exception instead of segfaulting | (ns tensorflow-clj.core
(:gen-class))
(def ^:dynamic graph nil)
(defmacro with-graph [& body]
`(binding [graph (org.tensorflow.Graph.)]
(try
~@body
(finally
(.close graph)))))
(defn- build-op [op-type op-name attr-map]
(let [ob (.opBuilder graph op-type (name op-name))]
(doseq [[attr-name attr-value] attr-map]
(.setAttr ob attr-name attr-value))
(-> ob (.build) (.output 0))))
(defn tensor [value]
(org.tensorflow.Tensor/create value))
(defn constant [name value]
(let [t (tensor value)]
(build-op "Const" name {"dtype" (.dataType t) "value" t})))
(defn variable [name]
(build-op "Variable" name
{"dtype" org.tensorflow.DataType/DOUBLE
"shape" (org.tensorflow.Shape/scalar)}))
(defn run-and-fetch [name]
(with-open [sess (org.tensorflow.Session. graph)]
(-> sess (.runner)
(.fetch (name name))
(.run))))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
| (ns tensorflow-clj.core
(:gen-class))
(def ^:dynamic graph nil)
(defmacro with-graph [& body]
`(binding [graph (org.tensorflow.Graph.)]
(try
~@body
(finally
(.close graph)))))
(defn- build-op [op-type op-name attr-map]
(let [ob (.opBuilder graph op-type (name op-name))]
(doseq [[attr-name attr-value] attr-map]
(.setAttr ob attr-name attr-value))
(-> ob (.build) (.output 0))))
(defn tensor [value]
(org.tensorflow.Tensor/create value))
(defn constant [name value]
(let [t (tensor value)]
(build-op "Const" name {"dtype" (.dataType t) "value" t})))
(defn variable [name]
(build-op "Variable" name
{"dtype" org.tensorflow.DataType/DOUBLE
"shape" (org.tensorflow.Shape/scalar)}))
(defn run-and-fetch [name]
(with-open [sess (org.tensorflow.Session. graph)]
(let [runner (.runner sess)]
(print (-> runner
(.feed (name name) (tensor 234.0))
(.fetch (name name))
(.run)
(.get 0)
(.toString))))))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
|
Make sure only return on final done, not just eoi! |
{:name "aggregate"
:path ""
:func (let [result (volatile! [])]
(fn[data]
(if (pg/eoi? data)
@result
(do
(vswap! result (fn[resval] (conj resval data)))
(pg/need)))))
:description "Streaming aggregation. Takes a stream of data and constructs a vector containing all data. This is mostly for aggregating result maps of upstream nodes. Similar to eager seqs in that all data will be used at once. BE CAREFUL."
}
|
{:name "aggregate"
:path ""
:func (let [result (volatile! [])]
(fn[data]
(if (and (pg/eoi? data) (pg/done? data))
@result
(do
(vswap! result (fn[resval] (conj resval data)))
(pg/need)))))
:description "Streaming aggregation. Takes a stream of data and constructs a vector containing all data. This is mostly for aggregating result maps of upstream nodes. Similar to eager seqs in that all data will be used at once. BE CAREFUL."
}
|
Update to ClojureScript 0.0-2665. Also update simple-brepl and Weasel to compatible versions. | (defproject shrimp "0.1.0-SNAPSHOT"
:description "Demo project for Goby."
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2511"]
[org.clojure/core.async "0.1.346.0-17112a-alpha"]
[goby "0.1.0"]
[weasel "0.4.2"]]
:plugins [[lein-cljsbuild "1.0.3"]
[jarohen/simple-brepl "0.1.2"]]
:source-paths ["src"]
:brepl {:ip "127.0.0.1"}
:cljsbuild {:builds {:dev
{:source-paths ["src"
"dev-src"]
:compiler {:output-to "js/main.js"
:optimizations :whitespace
:static-fns false
:externs ["externs.js"]
:pretty-print true}}
:rel
{:source-paths ["src"
"rel-src"]
:compiler {:output-to "js/main.js"
:optimizations :advanced
:static-fns true
:externs ["externs.js"]
:pretty-print false
:pseudo-names false}}}})
| (defproject shrimp "0.1.0-SNAPSHOT"
:description "Demo project for Goby."
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2665"]
[org.clojure/core.async "0.1.346.0-17112a-alpha"]
[goby "0.1.0"]
[weasel "0.5.0"]]
:plugins [[lein-cljsbuild "1.0.3"]
[jarohen/simple-brepl "0.2.1"]]
:source-paths ["src"]
:brepl {:ip "127.0.0.1"}
:cljsbuild {:builds {:dev
{:source-paths ["src"
"dev-src"]
:compiler {:output-to "js/main.js"
:optimizations :whitespace
:static-fns false
:externs ["externs.js"]
:pretty-print true}}
:rel
{:source-paths ["src"
"rel-src"]
:compiler {:output-to "js/main.js"
:optimizations :advanced
:static-fns true
:externs ["externs.js"]
:pretty-print false
:pseudo-names false}}}})
|
Raise the log level to info | (ns circle.logging
(:import (org.apache.log4j Logger
BasicConfigurator
EnhancedPatternLayout
Level
ConsoleAppender
SimpleLayout)
(org.apache.log4j.spi RootLogger))
(:import (org.apache.log4j.rolling TimeBasedRollingPolicy
RollingFileAppender))
(:import org.apache.commons.logging.LogFactory))
(defn set-level [logger level]
(. (Logger/getLogger logger) (setLevel level)))
(defn init []
(let [rolling-policy (doto (TimeBasedRollingPolicy.)
(.setActiveFileName "circle.log" )
(.setFileNamePattern "circle-%d{yyyy-MM-dd}.log.gz")
(.activateOptions))
layout (EnhancedPatternLayout. "%p [%d] %t - %c - %m%n")
rolling-log-appender (doto (RollingFileAppender.)
(.setRollingPolicy rolling-policy)
(.setLayout layout)
(.activateOptions))]
(doto (Logger/getRootLogger)
(.removeAllAppenders)
(.addAppender rolling-log-appender)
(.addAppender (ConsoleAppender. layout))))
(. (Logger/getRootLogger) (setLevel Level/DEBUG))
(set-level "jclouds.wire" Level/OFF)
(set-level "jclouds.headers" Level/OFF)
(set-level "jclouds.signature" Level/OFF))
| (ns circle.logging
(:import (org.apache.log4j Logger
BasicConfigurator
EnhancedPatternLayout
Level
ConsoleAppender
SimpleLayout)
(org.apache.log4j.spi RootLogger))
(:import (org.apache.log4j.rolling TimeBasedRollingPolicy
RollingFileAppender))
(:import org.apache.commons.logging.LogFactory))
(defn set-level [logger level]
(. (Logger/getLogger logger) (setLevel level)))
(defn init []
(let [rolling-policy (doto (TimeBasedRollingPolicy.)
(.setActiveFileName "circle.log" )
(.setFileNamePattern "circle-%d{yyyy-MM-dd}.log.gz")
(.activateOptions))
layout (EnhancedPatternLayout. "%p [%d] %t - %c - %m%n")
rolling-log-appender (doto (RollingFileAppender.)
(.setRollingPolicy rolling-policy)
(.setLayout layout)
(.activateOptions))]
(doto (Logger/getRootLogger)
(.removeAllAppenders)
(.addAppender rolling-log-appender)
(.addAppender (ConsoleAppender. layout))))
(. (Logger/getRootLogger) (setLevel Level/INFO))
(set-level "jclouds.wire" Level/OFF)
(set-level "jclouds.headers" Level/OFF)
(set-level "jclouds.signature" Level/OFF))
|
Add fns to highlight text passages | (ns discuss.texts.lib
(:require [cljs.spec.alpha :as s]
[clojure.string :as string]
[discuss.translations :refer [translate] :rename {translate t}]))
(defn join-with-and
"Join collection of strings with `and`."
[col]
(string/join (str " <i>" (t :common :and) "</i> ") col))
(s/fdef join-with-and
:args (s/cat :col (s/coll-of string?))
:ret string?)
| (ns discuss.texts.lib
(:require [cljs.spec.alpha :as s]
[clojure.string :as string]
[goog.string :refer [format]]
[goog.string.format]
[discuss.translations :refer [translate] :rename {translate t}]))
(defn join-with-and
"Join collection of strings with `and`."
[col]
(string/join (str " <i>" (t :common :and) "</i> ") col))
(s/fdef join-with-and
:args (s/cat :col (s/coll-of string?))
:ret string?)
;; -----------------------------------------------------------------------------
;; Highlight strings with html classes
(defn highlight-premise [premise]
(format "<span class=\"text-info\">%s</span>" premise))
(defn highlight-conclusion [premise]
(format "<span class=\"text-warning\">%s</span>" premise))
(defn highlight-undercut [premise]
(format "<span class=\"text-primary\">%s</span>" premise))
|
Add repl options since :main is bad w/ classnames | (let [dev-deps '[[speclj "2.3.0"]]]
(defproject reply "0.2.0-SNAPSHOT"
:description "REPL-y: A fitter, happier, more productive REPL for Clojure."
:dependencies [[org.clojure/clojure "1.4.0"]
[jline/jline "2.10"]
[org.thnetos/cd-client "0.3.6"]
[clj-stacktrace "0.2.4"]
[org.clojure/tools.nrepl "0.2.1"]
[org.clojure/tools.cli "0.2.1"]
[com.cemerick/drawbridge "0.0.6"]
[trptcolin/versioneer "0.1.0"]
[clojure-complete "0.2.2"]
[org.clojars.trptcolin/sjacket "0.1.0.3"
:exclusions [org.clojure/clojure]]]
:profiles {:dev {:dependencies ~dev-deps}}
:dev-dependencies ~dev-deps
:plugins ~dev-deps
:aot [reply.reader.jline.JlineInputReader]
:source-path "src/clj"
:java-source-path "src/java"
:test-path "spec"
:source-paths ["src/clj"]
:java-source-paths ["src/java"]
:test-paths ["spec"]
:main ^{:skip-aot true} reply.ReplyMain))
| (let [dev-deps '[[speclj "2.3.0"]]]
(defproject reply "0.2.0-SNAPSHOT"
:description "REPL-y: A fitter, happier, more productive REPL for Clojure."
:dependencies [[org.clojure/clojure "1.4.0"]
[jline/jline "2.10"]
[org.thnetos/cd-client "0.3.6"]
[clj-stacktrace "0.2.4"]
[org.clojure/tools.nrepl "0.2.1"]
[org.clojure/tools.cli "0.2.1"]
[com.cemerick/drawbridge "0.0.6"]
[trptcolin/versioneer "0.1.0"]
[clojure-complete "0.2.2"]
[org.clojars.trptcolin/sjacket "0.1.0.3"
:exclusions [org.clojure/clojure]]]
:profiles {:dev {:dependencies ~dev-deps}}
:dev-dependencies ~dev-deps
:plugins ~dev-deps
:aot [reply.reader.jline.JlineInputReader]
:source-path "src/clj"
:java-source-path "src/java"
:test-path "spec"
:source-paths ["src/clj"]
:java-source-paths ["src/java"]
:test-paths ["spec"]
:repl-options {:init-ns user}
:main ^{:skip-aot true} reply.ReplyMain))
|
Set buddy-core dependency to 0.5.0. | (defproject buddy/buddy-sign "0.5.0-SNAPSHOT"
:description "High level message signing"
:url "https://github.com/funcool/buddy-sign"
:license {:name "BSD (2-Clause)"
:url "http://opensource.org/licenses/BSD-2-Clause"}
:dependencies [[org.clojure/clojure "1.6.0"]
[com.taoensso/nippy "2.8.0"]
[buddy/buddy-core "0.5.0-SNAPSHOT"]
[slingshot "0.12.2"]
[cats "0.4.0"]
[clj-time "0.9.0"]
[cheshire "5.4.0"]]
:source-paths ["src"]
:javac-options ["-target" "1.7" "-source" "1.7" "-Xlint:-options"]
:test-paths ["test"])
| (defproject buddy/buddy-sign "0.5.0-SNAPSHOT"
:description "High level message signing"
:url "https://github.com/funcool/buddy-sign"
:license {:name "BSD (2-Clause)"
:url "http://opensource.org/licenses/BSD-2-Clause"}
:dependencies [[org.clojure/clojure "1.6.0"]
[com.taoensso/nippy "2.8.0"]
[buddy/buddy-core "0.5.0"]
[slingshot "0.12.2"]
[cats "0.4.0"]
[clj-time "0.9.0"]
[cheshire "5.4.0"]]
:source-paths ["src"]
:javac-options ["-target" "1.7" "-source" "1.7" "-Xlint:-options"]
:test-paths ["test"])
|
Set 0.11.3-SNAPSHOT version of catacumba. | (defproject uxbox-backend "0.1.0-SNAPSHOT"
:description "UXBox backend."
:url "http://uxbox.github.io"
:license {:name "MPL 2.0" :url "https://www.mozilla.org/en-US/MPL/2.0/"}
:source-paths ["src"]
:javac-options ["-target" "1.8" "-source" "1.8" "-Xlint:-options"]
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]
:dependencies [[org.clojure/clojure "1.8.0" :scope "provided"]
[org.slf4j/slf4j-simple "1.7.18"]
[bouncer "1.0.0"]
[mount "0.1.10"]
[environ "1.0.2"]
[buddy/buddy-sign "0.9.0"]
[buddy/buddy-hashers "0.11.0"]
[com.github.spullara.mustache.java/compiler "0.9.1"]
[org.postgresql/postgresql "9.4.1208" :scope "provided"]
[niwinz/migrante "0.1.0"]
[funcool/suricatta "0.8.1"]
[funcool/promesa "0.8.1"]
[hikari-cp "1.6.1"]
[funcool/catacumba "0.11.2"]])
| (defproject uxbox-backend "0.1.0-SNAPSHOT"
:description "UXBox backend."
:url "http://uxbox.github.io"
:license {:name "MPL 2.0" :url "https://www.mozilla.org/en-US/MPL/2.0/"}
:source-paths ["src"]
:javac-options ["-target" "1.8" "-source" "1.8" "-Xlint:-options"]
:jvm-opts ["-Dclojure.compiler.direct-linking=true"]
:dependencies [[org.clojure/clojure "1.8.0" :scope "provided"]
[org.slf4j/slf4j-simple "1.7.18"]
[bouncer "1.0.0"]
[mount "0.1.10"]
[environ "1.0.2"]
[buddy/buddy-sign "0.9.0"]
[buddy/buddy-hashers "0.11.0"]
[com.github.spullara.mustache.java/compiler "0.9.1"]
[org.postgresql/postgresql "9.4.1208" :scope "provided"]
[niwinz/migrante "0.1.0"]
[funcool/suricatta "0.8.1"]
[funcool/promesa "0.8.1"]
[hikari-cp "1.6.1"]
[funcool/catacumba "0.11.3-SNAPSHOT"]])
|
Bump plumbing dep and test on Clojure 1.6 | (defproject prismatic/fnhouse "0.1.0-SNAPSHOT"
:description "Transform lightly-annotated functions into a full-fledged web service"
:license {:name "Eclipse Public License - v 1.0"
:url "http://www.eclipse.org/legal/epl-v10.html"
:distribution :repo}
:url "https://github.com/Prismatic/fnhouse"
:dependencies [[prismatic/plumbing "0.2.1"]]
:profiles {:dev {:dependencies [[org.clojure/clojure "1.5.1"]]
:warn-on-reflection true}
:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]}}
:lein-release {:deploy-via :shell
:shell ["lein" "deploy" "clojars"]}
:aliases {"all" ["with-profile" "dev:dev,1.4"]})
| (defproject prismatic/fnhouse "0.1.0-SNAPSHOT"
:description "Transform lightly-annotated functions into a full-fledged web service"
:license {:name "Eclipse Public License - v 1.0"
:url "http://www.eclipse.org/legal/epl-v10.html"
:distribution :repo}
:url "https://github.com/Prismatic/fnhouse"
:dependencies [[prismatic/plumbing "0.2.2"]]
:profiles {:dev {:dependencies [[org.clojure/clojure "1.5.1"]]
:warn-on-reflection true}
:1.6 {:dependencies [[org.clojure/clojure "1.6.0-RC1"]]}}
:aliases {"all" ["with-profile" "dev:dev,1.6"]}
:lein-release {:deploy-via :shell
:shell ["lein" "deploy" "clojars"]})
|
Enable console print for easier browser debugging | (ns {{name}}.core
(:require-macros [retro-fever.macros :refer [game]])
(:require [retro-fever.core :as core]
[retro-fever.input :as input]
[retro-fever.sprite :as sprite]
[retro-fever.asset :as asset]))
(defonce game-state (atom {})) ; Atom to store the game state
(defn update-fn []) ; Update function called on each iteration in the game loop
(defn render-fn [context]) ; Render function called on each iteration in the game loop
(defn load-resources []) ; Function to load all the game resources
(defn setup []) ; Function to setup initial game state
(defn ^:export init [] ; The entry point into the game from the HTML page
(.log js/console "Launching game")
(core/init-canvas "game-canvas" 640 480) ; Initialize canvas on HTML page
(input/init) ; Initialize input devices
(load-resources) ; Load game resources, such as images and animations
(core/setup setup) ; Setup the initial game state
(game core/game-loop update-fn render-fn 60) ; Create and start the game loop
)
| (ns {{name}}.core
(:require-macros [retro-fever.macros :refer [game]])
(:require [retro-fever.core :as core]
[retro-fever.input :as input]
[retro-fever.sprite :as sprite]
[retro-fever.asset :as asset]))
(enable-console-print!)
(defonce game-state (atom {})) ; Atom to store the game state
(defn update-fn []) ; Update function called on each iteration in the game loop
(defn render-fn [context]) ; Render function called on each iteration in the game loop
(defn load-resources []) ; Function to load all the game resources
(defn setup []) ; Function to setup initial game state
(defn ^:export init [] ; The entry point into the game from the HTML page
(.log js/console "Launching game")
(core/init-canvas "game-canvas" 640 480) ; Initialize canvas on HTML page
(input/init) ; Initialize input devices
(load-resources) ; Load game resources, such as images and animations
(core/setup setup) ; Setup the initial game state
(game core/game-loop update-fn render-fn 60) ; Create and start the game loop
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.