{"size":321,"ext":"clj","lang":"Clojure","max_stars_count":1.0,"content":"(ns sound-flour.oscillators)\n\n(def buffer-len 8000)\n\n(def sample-rate 8000)\n\n(defn sine-wave [frequency amplitude]\n (let [data (->>\n (range buffer-len)\n (mapv #(* amplitude (Math\/sin (\/ (* 2 Math\/PI % frequency) sample-rate))))\n )]\n (fn [t] (data (mod t buffer-len)))))\n\n\n","avg_line_length":21.4,"max_line_length":90,"alphanum_fraction":0.53894081} {"size":5540,"ext":"clj","lang":"Clojure","max_stars_count":294.0,"content":"(defproject nasa-cmr\/cmr-metadata-db-app \"0.1.0-SNAPSHOT\"\n :description \"The metadata db is a micro-service that provides\n support for persisting metadata concepts.\"\n :url \"https:\/\/github.com\/nasa\/Common-Metadata-Repository\/tree\/master\/metadata-db-app\"\n :exclusions [[cheshire]\n [clj-http]\n [clj-time]\n [com.fasterxml.jackson.core\/jackson-core]\n [com.fasterxml.jackson.core\/jackson-databind]\n [org.clojure\/tools.reader]\n [org.slf4j\/slf4j-api]]\n :dependencies [[cheshire \"5.10.0\"]\n [clj-http \"3.11.0\"]\n [clj-time \"0.15.1\"]\n [com.fasterxml.jackson.core\/jackson-core \"2.12.1\"]\n [com.fasterxml.jackson.dataformat\/jackson-dataformat-cbor \"2.12.1\"]\n [compojure \"1.6.1\"]\n [drift \"1.5.3\"]\n [inflections \"0.13.0\"]\n [nasa-cmr\/cmr-acl-lib \"0.1.0-SNAPSHOT\"]\n [nasa-cmr\/cmr-common-app-lib \"0.1.0-SNAPSHOT\"]\n [nasa-cmr\/cmr-common-lib \"0.1.1-SNAPSHOT\"]\n [nasa-cmr\/cmr-message-queue-lib \"0.1.0-SNAPSHOT\"]\n [nasa-cmr\/cmr-oracle-lib \"0.1.0-SNAPSHOT\"]\n [org.clojure\/clojure \"1.10.0\"]\n [org.clojure\/tools.nrepl \"0.2.13\"]\n [org.clojure\/tools.reader \"1.3.2\"]\n [org.quartz-scheduler\/quartz \"2.3.1\"]\n [org.slf4j\/slf4j-api \"1.7.30\"]\n [ring\/ring-core \"1.9.2\"]\n [ring\/ring-json \"0.5.1\"]]\n :plugins [[drift \"1.5.3\"]\n [lein-exec \"0.3.7\"]\n [lein-shell \"0.5.0\"]\n [test2junit \"1.3.3\"]]\n :repl-options {:init-ns user}\n :jvm-opts ^:replace [\"-server\"\n \"-Dclojure.compiler.direct-linking=true\"]\n :test-paths [\"test\" \"int-test\"]\n :profiles {:security {:plugins [[com.livingsocial\/lein-dependency-check \"1.1.1\"]]\n :dependency-check {:output-format [:all]\n :suppression-file \"resources\/security\/suppression.xml\"}}\n :dev {:dependencies [[nasa-cmr\/cmr-mock-echo-app \"0.1.0-SNAPSHOT\"]\n [org.clojars.gjahad\/debug-repl \"0.3.3\"]\n [org.clojure\/tools.namespace \"0.2.11\"]\n [pjstadig\/humane-test-output \"0.9.0\"]\n [proto-repl \"0.3.1\"]]\n :jvm-opts ^:replace [\"-server\"]\n :source-paths [\"src\" \"dev\" \"test\" \"int-test\"]\n :injections [(require 'pjstadig.humane-test-output)\n (pjstadig.humane-test-output\/activate!)]}\n :uberjar {:main cmr.metadata-db.runner\n :aot :all}\n :static {}\n ;; This profile is used for linting and static analysis. To run for this\n ;; project, use `lein lint` from inside the project directory. To run for\n ;; all projects at the same time, use the same command but from the top-\n ;; level directory.\n :lint {:source-paths ^:replace [\"src\"]\n :test-paths ^:replace []\n :plugins [[jonase\/eastwood \"0.2.5\"]\n [lein-ancient \"0.6.15\"]\n [lein-bikeshed \"0.5.0\"]\n [lein-kibit \"0.1.6\"]]}\n ;; The following profile is overriden on the build server or in the user's\n ;; ~\/.lein\/profiles.clj file.\n :internal-repos {}\n :kaocha {:dependencies [[lambdaisland\/kaocha \"1.0.732\"]\n [lambdaisland\/kaocha-cloverage \"1.0.75\"]\n [lambdaisland\/kaocha-junit-xml \"0.0.76\"]]}}\n ;; Database migrations run by executing \"lein migrate\"\n :aliases {\"create-user\" [\"exec\" \"-p\" \".\/support\/create_user.clj\"]\n \"drop-user\" [\"exec\" \"-p\" \".\/support\/drop_user.clj\"]\n \"migrate\" [\"migrate\" \"-c\" \"config.mdb-migrate-config\/app-migrate-config\"]\n ;; Prints out documentation on configuration environment variables.\n \"env-config-docs\" [\"exec\" \"-ep\" \"(do (use 'cmr.common.config) (print-all-configs-docs) (shutdown-agents))\"]\n ;; Alias to test2junit for consistency with lein-test-out\n \"test-out\" [\"test2junit\"]\n\n ;; Kaocha test aliases\n ;; refer to tests.edn for test configuration\n \"kaocha\" [\"with-profile\" \"+kaocha\" \"run\" \"-m\" \"kaocha.runner\"]\n \"itest\" [\"kaocha\" \"--focus\" \":integration\"]\n \"utest\" [\"kaocha\" \"--focus\" \":unit\"]\n \"ci-test\" [\"kaocha\" \"--profile\" \":ci\"]\n \"ci-itest\" [\"itest\" \"--profile\" \":ci\"]\n \"ci-utest\" [\"utest\" \"--profile\" \":ci\"]\n\n ;; Linting aliases\n \"kibit\" [\"do\"\n [\"with-profile\" \"lint\" \"shell\" \"echo\" \"== Kibit ==\"]\n [\"with-profile\" \"lint\" \"kibit\"]]\n \"eastwood\" [\"with-profile\" \"lint\" \"eastwood\" \"{:namespaces [:source-paths]}\"]\n \"bikeshed\" [\"with-profile\" \"lint\" \"bikeshed\" \"--max-line-length=100\"]\n \"check-deps\" [\"with-profile\" \"lint\" \"ancient\" \":all\"]\n \"check-sec\" [\"with-profile\" \"security\" \"dependency-check\"]\n \"lint\" [\"do\" [\"check\"] [\"kibit\"] [\"eastwood\"]]\n ;; Placeholder for future docs and enabler of top-level alias\n \"generate-static\" [\"with-profile\" \"static\" \"shell\" \"echo\"]})\n","avg_line_length":55.4,"max_line_length":119,"alphanum_fraction":0.5055956679} {"size":6599,"ext":"clj","lang":"Clojure","max_stars_count":4.0,"content":"(set! *warn-on-reflection* true)\n(set! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :since \"2017-11-10\"\n :date \"2017-11-15\"\n :doc \"Common definitions for benchmark scripts.\" }\n \n taiga.scripts.quantiles.defs\n \n (:require [clojure.java.io :as io]\n [clojure.string :as s]\n [clojure.pprint :as pp]\n [zana.api :as z]\n [taiga.api :as taiga]\n [taiga.scripts.quantiles.deciles :as deciles]\n [taiga.scripts.quantiles.record :as record])\n \n (:import [java.util Map]\n [java.io File]\n [clojure.lang IFn IFn$OD]\n [taiga.ensemble MeanModel]))\n;;----------------------------------------------------------------\n(def ^:private nss (str *ns*))\n(def n (* 1 1 8 8 1024))\n(def nterms 128)\n;;----------------------------------------------------------------\n(def ^:private input-folder \n (io\/file \n (apply io\/file \"tst\" (butlast (s\/split nss #\"\\.\"))) \n \"in\"))\n\n(defn- input-file [prefix n suffix]\n (let [file (io\/file input-folder \n (str prefix \"-\" n \".\" suffix))]\n (io\/make-parents file) \n file))\n;;----------------------------------------------------------------\n(defn generate-data [^long n]\n (let [median (record\/make-pyramid-function 16.0)\n data (z\/seconds \n \"generate\"\n (z\/map (record\/generator median) \n (range (* 3 n)))) \n [mean measure test] (z\/seconds \n \"partition\" \n (z\/partition n data))]\n (z\/write-tsv-file\n record\/tsv-attributes \n mean \n (input-file \"mean\" (z\/count mean) \"tsv.gz\"))\n (z\/write-tsv-file\n record\/tsv-attributes \n measure \n (input-file \"measure\" (z\/count measure) \"tsv.gz\"))\n (z\/write-tsv-file\n record\/tsv-attributes \n test \n (input-file \"test\" (z\/count test) \"tsv.gz\"))\n {:data mean\n :empirical-distribution-data measure\n :test-data test}))\n;;----------------------------------------------------------------\n(def ^:private output-folder \n (io\/file \n (apply io\/file \"tst\" (butlast (s\/split nss #\"\\.\")))\n \"out\"))\n\n(defn- output-file [prefix options suffix]\n (let [file (io\/file output-folder \n (str prefix\n \"-\" (:n options (z\/count (:data options)))\n \"-\" (:nterms options) \n \"-\" (:mincount options)\n \"-\" (:mtry options)\n \".\" suffix))]\n (io\/make-parents file) \n file))\n;;----------------------------------------------------------------\n(defn- mean-regression-options ^Map [^long n]\n (let [predictors (dissoc record\/attributes \n :ground-truth :prediction)\n m (int (z\/count predictors))\n mtry (Math\/min m (int (Math\/round (Math\/sqrt m))))\n mincount 127\n options (taiga\/mean-regression-options\n {:n n\n :attributes record\/attributes\n :nterms nterms \n :mincount mincount \n :mtry mtry})]\n options))\n;;----------------------------------------------------------------\n(defn mean-regression ^MeanModel [^long n]\n (let [options (mean-regression-options n)\n data (record\/read-tsv-file \n (input-file \"mean\" n \"tsv.gz\"))\n mean-forest (taiga\/mean-regression (assoc options :data data))\n mean-forest-file (output-file \"mean\" options \"edn.gz\")]\n (io\/make-parents mean-forest-file)\n (taiga\/write-edn mean-forest mean-forest-file)\n mean-forest))\n;;----------------------------------------------------------------\n(defn- real-probability-measure-options ^Map [^long n]\n (let [options (mean-regression-options n)\n mean-forest-file (output-file \"mean\" options \"edn.gz\")\n mean-forest (taiga\/read-edn mean-forest-file)\n data (record\/read-tsv-file \n (input-file \"measure\" n \"tsv.gz\"))]\n (assoc options \n :mean-regression-forest mean-forest\n :empirical-distribution-data data)))\n;;----------------------------------------------------------------\n(defn real-probability-measure ^MeanModel [^long n]\n (let [options (real-probability-measure-options n)\n #_(pp\/pprint (z\/clojurize (:mean-regression-forest options)))\n measure-forest (taiga\/real-probability-measure options)\n measure-forest-file (output-file \n \"measure\" options \"edn.gz\")]\n (io\/make-parents measure-forest-file)\n (taiga\/write-edn measure-forest measure-forest-file)\n measure-forest))\n;;----------------------------------------------------------------\n(defn predict [^long n ^String prefix]\n (let [options (real-probability-measure-options n)\n measure-forest-file (output-file \n \"measure\" options \"edn.gz\")\n measure-forest (taiga\/read-edn measure-forest-file)\n predictors (dissoc record\/attributes \n :ground-truth :prediction)\n predict1 (fn predict1 [datum]\n (assoc \n datum \n :qhat (deciles\/make \n z\/quantile \n (measure-forest predictors datum))))\n predicted (z\/pmap \n runningpredict1 \n (record\/read-tsv-file \n (input-file prefix n \"tsv.gz\")))\n predicted-file (output-file prefix options \"tsv.gz\")]\n (record\/write-tsv-file predicted predicted-file)\n predicted))\n;;----------------------------------------------------------------\n(defn- decile-cost ^double [^IFn$OD y ^IFn deciles ^Iterable data]\n (let [it (z\/iterator data)]\n (loop [sum (double 0.0)]\n (if (.hasNext it)\n (let [datum (.next it)\n yi (.invokePrim y datum)\n qi (deciles datum)]\n (recur (+ sum (deciles\/cost yi qi))))\n sum))))\n;;----------------------------------------------------------------\n(defn relative-cost [^long n ^String prefix]\n (let [options (real-probability-measure-options n)\n predicted-file (output-file prefix options \"tsv.gz\")\n predicted (record\/read-tsv-file predicted-file)\n true-cost (decile-cost record\/y record\/ymu predicted)\n pred-cost (decile-cost record\/y record\/qhat predicted)]\n (println n prefix (float true-cost) (float pred-cost) \n (float (\/ pred-cost true-cost)))))\n;;----------------------------------------------------------------\n","avg_line_length":40.4846625767,"max_line_length":70,"alphanum_fraction":0.4873465677} {"size":333,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns blaze.db.impl.db-spec\n (:require\n [blaze.db.api-spec]\n [blaze.db.impl.batch-db-spec]\n [blaze.db.impl.codec-spec]\n [blaze.db.impl.db :as db]\n [blaze.db.impl.index-spec]\n [blaze.db.kv.spec]\n [clojure.spec.alpha :as s]))\n\n\n(s\/fdef db\/db\n :args (s\/cat :node :blaze.db\/node :t :blaze.db\/t)\n :ret :blaze.db\/db)\n","avg_line_length":22.2,"max_line_length":51,"alphanum_fraction":0.6126126126} {"size":1298,"ext":"cljc","lang":"Clojure","max_stars_count":60.0,"content":"(ns vimsical.subgraph.re-frame\n (:require\n [vimsical.subgraph :as sg]\n [re-frame.core :as re-frame]\n [re-frame.interop :as interop]))\n\n;; * Db helpers\n\n(defn- ref?\n [_ expr]\n (sg\/ref? (deref (re-frame\/subscribe [::sg\/id-attrs])) expr))\n\n(defn- get-ref\n [{:keys [db]} pattern lookup-ref]\n {:pre [(interop\/deref? db)]}\n (deref (interop\/make-reaction #(get @db lookup-ref))))\n\n(defn- skip?\n [expr]\n (-> expr meta ::sg\/skip boolean))\n\n;; * Subscription db parser\n\n(defn- parser\n [{:keys [parser db db-ref? pattern] :as context} result expr]\n {:pre [(interop\/deref? db)]}\n (letfn [(parse [] (sg\/parse-expr context result expr))\n (join? [expr] (= ::sg\/join (sg\/expr-type expr)))]\n (if (and (not (skip? expr))\n (or (db-ref? db expr)\n (join? expr)))\n (deref (interop\/make-reaction parse))\n (parse))))\n\n;; * Internal subscription\n\n(re-frame\/reg-sub\n ::sg\/id-attrs\n (fn [db _]\n (select-keys db [::sg\/id-attrs])))\n\n;; * API\n\n(defn pull\n [db pattern lookup-ref]\n {:pre [(interop\/deref? db)]}\n (interop\/make-reaction\n #(sg\/pull db pattern lookup-ref\n {:parser parser\n :db-ref? ref?\n :db-get-ref get-ref})))\n\n(defn raw-sub-handler\n [db [_ pattern lookup-ref]]\n (pull db pattern lookup-ref))\n","avg_line_length":23.1785714286,"max_line_length":63,"alphanum_fraction":0.5785824345} {"size":2289,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns ^{:doc \"Server-side base CityShelf view.\"\n :author \"Eric Weinstein \"}\n cityshelf.views.index\n (:use [hiccup.page :only (html5 include-css include-js)]\n [hiccup.element :only (javascript-tag)]))\n\n(defn index\n \"Provides the base CityShelf view.\"\n [title]\n (html5 {:lang \"en\"}\n [:head\n [:title title]\n (include-css \"css\/style.css\"\n \"\/\/maxcdn.bootstrapcdn.com\/font-awesome\/4.3.0\/css\/font-awesome.min.css\")\n [:link {:rel \"apple-touch-icon\" :href \"apple-touch-icon.png\/apple-touch-icon.png\"}]\n [:link {:rel \"apple-touch-icon\" :sizes \"57x57\" :href \"apple-touch-icon\/apple-touch-icon-57x57-precomposed.png\"}]\n [:link {:rel \"apple-touch-icon\" :sizes \"72x72\" :href \"apple-touch-icon\/apple-touch-icon-72x72-precomposed.png\"}]\n [:link {:rel \"apple-touch-icon\" :sizes \"114x114\" :href \"apple-touch-icon\/apple-touch-icon-114x114-precomposed.png\"}]\n [:link {:rel \"apple-touch-icon\" :sizes \"144x144\" :href \"apple-touch-icon\/apple-touch-icon-144x144-precomposed.png\"}]\n [:meta {:charset \"UTF-8\"}]\n [:meta {:name \"description\" :content \"CityShelf: Go Local for Books\"}]\n [:meta {:name \"keywords\" :content \"CityShelf, indie, bookstore, local, books\"}]\n [:meta {:name \"viewport\"\n :content \"user-scalable=no, width=device-width,\n height=device-height, initial-scale=1.0,\n maximum-scale=1.0, minimal-ui\"}]\n [:meta {:property \"og:image\" :content \"img\/cs_logo.svg\"}]]\n [:body\n [:div {:id \"app\"}]\n (include-js \"https:\/\/maps.googleapis.com\/maps\/api\/js?key=AIzaSyBmimHj60eXII2ZAc7VY1pzqs2ANJqdwZI\")\n (include-js \"js\/compiled\/cityshelf.js\")\n (javascript-tag\n \"(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n })(window,document,'script','\/\/www.google-analytics.com\/analytics.js','ga');\n\n ga('create', 'UA-56171518-1', 'auto');\n ga('send', 'pageview');\")]))\n","avg_line_length":57.225,"max_line_length":126,"alphanum_fraction":0.5915246833} {"size":831,"ext":"cljc","lang":"Clojure","max_stars_count":311.0,"content":"(ns schism.impl.vector-clock-test\n (:require #?(:clj [clojure.test :refer [deftest testing is]]\n :cljs [cljs.test :refer [deftest testing is]])\n [schism.impl.vector-clock :as vc]\n [schism.impl.protocols :as proto]\n [schism.node :as node]))\n\n\n(defrecord SimpleClocked [last-time vclock]\n proto\/Vclocked\n (get-clock [_] vclock)\n (with-clock [this new-clock]\n (assoc this :vclock new-clock)))\n\n(deftest update-clock-test\n (node\/initialize-node! :clock-test-node)\n (let [test (->SimpleClocked nil {})\n updated (vc\/update-clock time test\n (assoc test :last-time time))\n time (:last-time updated)]\n (is (= {:clock-test-node time} (proto\/get-clock updated)))\n (is #?(:clj (instance? java.util.Date time)\n :cljs true))))\n","avg_line_length":34.625,"max_line_length":62,"alphanum_fraction":0.5980746089} {"size":1750,"ext":"clj","lang":"Clojure","max_stars_count":282.0,"content":"(ns virgil.util\n \"Utilities for cross-tooling.\"\n (:import (javax.tools DiagnosticCollector Diagnostic$Kind)))\n\n(defn- println-err [& args]\n (binding [*err* *out*]\n (apply println args)))\n\n(defn- infer-print-function\n \"Infer the function to print the compilation event with depending on the\n environment (Leiningen, Boot).\"\n [^Diagnostic$Kind diagnostic-kind]\n (let [tool (or (try (require 'leiningen.core.main) :lein\n (catch Exception _))\n (try (require 'boot.util) :boot\n (catch Exception _)))\n err-fn (case tool\n :lein (resolve 'leiningen.core.main\/warn)\n :boot (resolve 'boot.util\/fail)\n println-err)\n warn-fn (case tool\n :lein (resolve 'leiningen.core.main\/warn)\n :boot (resolve 'boot.util\/warn)\n println-err)\n info-fn (case tool\n :lein (resolve 'leiningen.core.main\/info)\n :boot (resolve 'boot.util\/info)\n println-err)]\n (condp = diagnostic-kind\n Diagnostic$Kind\/ERROR err-fn\n Diagnostic$Kind\/WARNING warn-fn\n Diagnostic$Kind\/MANDATORY_WARNING warn-fn\n info-fn)))\n\n(defn print-diagnostics [^DiagnosticCollector diag-coll]\n (doseq [d (.getDiagnostics diag-coll)]\n (let [k (.getKind d)\n log (infer-print-function k)]\n (if (nil? (.getSource d))\n (log (format \"%s: %s\\n\"\n (.toString k)\n (.getMessage d nil)))\n (log (format \"%s: %s, line %d: %s\\n\"\n (.toString k)\n (.. d getSource getName)\n (.getLineNumber d)\n (.getMessage d nil)))))))\n","avg_line_length":36.4583333333,"max_line_length":74,"alphanum_fraction":0.536} {"size":204,"ext":"cljs","lang":"Clojure","max_stars_count":2.0,"content":"(ns fan-fiction.utils\n (:require [clojure.string :as str]))\n\n(defn kebab->camel-keyword [k]\n (let [[head & tail] (-> k name (str\/split #\"-\"))]\n (keyword (apply str head (map str\/capitalize tail)))))\n","avg_line_length":29.1428571429,"max_line_length":58,"alphanum_fraction":0.6225490196} {"size":2225,"ext":"clj","lang":"Clojure","max_stars_count":17.0,"content":"(ns salava.core.session\n (:require [clojure.pprint :refer [pprint]]\n [ring.util.http-response :refer [unauthorized forbidden]]\n [ring.middleware.cookies :refer [wrap-cookies]]\n [ring.middleware.session :refer [wrap-session]]\n [ring.middleware.session.cookie :refer [cookie-store]]\n [buddy.auth.backends :as backends]\n [buddy.auth.accessrules :refer [wrap-access-rules]]\n [buddy.auth.middleware :refer [wrap-authentication wrap-authorization]]))\n\n(def auth-backend\n ; By default responds with 401 or 403 if unauthorized\n (backends\/session))\n\n(defn wrap-session-expired [handler]\n (fn [request]\n (if (some-> request (get-in [:session :identity :expires]) (> (long (\/ (System\/currentTimeMillis) 1000))))\n (handler request)\n (handler (assoc-in request [:session :identity] nil)))))\n\n;;TODO allow other cookies in bearer token request\n(defn wrap-bearer-token [handler session-name]\n (fn [request]\n (if (or (get-in request [:headers \"cookie\"])\n (nil? (get-in request [:headers \"authorization\"])))\n (handler request)\n (let [token (last (re-find #\"(?i)^Bearer (.+)\" (get-in request [:headers \"authorization\"])))]\n (handler (assoc-in request [:headers \"cookie\"] (str session-name \"=\" token)))))))\n\n(defn wrap-app-session [routes config]\n (-> routes\n (wrap-authorization auth-backend)\n (wrap-authentication auth-backend)\n (wrap-session-expired)\n (wrap-session {:store (cookie-store {:key (get-in config [:session :secret])})\n :root (get-in config [:session :root])\n :cookie-name (get-in config [:session :name])\n :cookie-attrs {:http-only true\n :secure (get-in config [:session :secure])\n :max-age (get-in config [:session :max-age])}})\n (wrap-bearer-token (get-in config [:session :name]))))\n\n(defn access-error [req val]\n (unauthorized))\n\n(defn wrap-rule [handler rule]\n (-> handler\n (wrap-access-rules {:rules [{:pattern #\".*\"\n :handler rule}]\n :on-error access-error})))\n","avg_line_length":43.6274509804,"max_line_length":110,"alphanum_fraction":0.5887640449} {"size":409,"ext":"clj","lang":"Clojure","max_stars_count":3.0,"content":"(defproject incanter\/incanter-latex \"1.2.3\"\n :description \"Library for rendering LaTeX math equations using the jLateXMath library.\"\n :dependencies [[incanter\/incanter-charts \"1.2.3\"]\n [net.sf.alxa\/jlatexmath \"0.9.1-SNAPSHOT\"]]\n :dev-dependencies [[swank-clojure \"1.3.0-SNAPSHOT\"]\n [lein-clojars \"0.6.0\"]]\n :repositories {\"alxa-repo\" \"http:\/\/alxa.sourceforge.net\/m2\"})\n","avg_line_length":51.125,"max_line_length":89,"alphanum_fraction":0.6601466993} {"size":905,"ext":"clj","lang":"Clojure","max_stars_count":15.0,"content":"(defproject bcbio.variation.recall \"0.2.6\"\n :description \"Parallel merging, squaring off and ensemble calling for genomic variants.\"\n :url \"https:\/\/github.com\/chapmanb\/bcbio.variation.recall\"\n :license {:name \"MIT\" :url \"http:\/\/www.opensource.org\/licenses\/mit-license.html\"}\n :dependencies [[org.clojure\/clojure \"1.10.0\"]\n [org.clojure\/tools.cli \"0.4.1\"]\n [ordered \"1.3.2\"]\n [version-clj \"0.1.0\"]\n [de.kotka\/lazymap \"3.1.1\"]\n [bcbio.run \"0.0.6\"]\n [com.github.broadinstitute\/picard \"1.140\"]\n [com.github.samtools\/htsjdk \"1.140\"]]\n :plugins [[lein-midje \"3.2.1\"]]\n :profiles {:dev {:dependencies\n [[midje \"1.9.4\"]\n [io.aviso\/pretty \"0.1.36\"]]}\n :uberjar {:aot [bcbio.variation.recall.main]}}\n :main ^:skip-aot bcbio.variation.recall.main)\n","avg_line_length":47.6315789474,"max_line_length":90,"alphanum_fraction":0.564640884} {"size":5409,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(defproject player \"2.6.0\"\n :description \"asciinema player\"\n :url \"https:\/\/github.com\/asciinema\/asciinema-player\"\n :license {:name \"Apache 2.0\"\n :url \"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\"}\n\n :dependencies [[org.clojure\/clojure \"1.8.0\"]\n [org.clojure\/clojurescript \"1.9.671\"]\n [org.clojure\/core.async \"0.2.374\"]\n [reagent \"0.7.0\"]\n [devcards \"0.2.2\" :exclusions [cljsjs\/react cljsjs\/create-react-class cljsjs\/react-dom-server cljsjs\/react-dom]]\n [org.clojure\/test.check \"0.9.0\"]\n [org.clojure\/core.match \"0.3.0-alpha4\"]\n [prismatic\/schema \"1.1.6\"]]\n\n :plugins [[lein-cljsbuild \"1.1.5\"]\n [lein-figwheel \"0.5.14\"]\n [lein-less \"1.7.5\"]\n [lein-doo \"0.1.7\"]\n [lein-kibit \"0.1.3\"]]\n\n :min-lein-version \"2.5.3\"\n\n :clean-targets ^{:protect false} [\"resources\/public\/js\" \"target\" \"out\"]\n\n :source-paths [\"src\" \"vt\/src\"]\n :resource-paths [\"resources\" \"vt\/resources\"]\n\n :profiles {:dev {:dependencies [[com.cemerick\/piggieback \"0.2.1\"]\n [org.clojure\/tools.nrepl \"0.2.10\"]\n [environ \"1.0.1\"]\n [figwheel-sidecar \"0.5.0-1\"]]\n :plugins [[refactor-nrepl \"1.1.0\"]]\n :source-paths [\"dev\/clj\" \"dev\/cljs\"]}\n :repl {:plugins [[cider\/cider-nrepl \"0.10.0\"]]}}\n\n :repl-options {:nrepl-middleware [cemerick.piggieback\/wrap-cljs-repl]}\n\n :cljsbuild {:builds {:dev {:source-paths [\"src\" \"dev\/cljs\"]\n :figwheel {:on-jsload \"asciinema.player.dev\/reload\"}\n :compiler {:main \"asciinema.player.dev\"\n :asset-path \"js\/dev\"\n :output-to \"resources\/public\/js\/dev.js\"\n :output-dir \"resources\/public\/js\/dev\"\n :source-map true\n :foreign-libs [{:file \"public\/element.js\"\n :provides [\"asciinema.player.element\"]}\n {:file \"codepoint-polyfill.js\"\n :provides [\"asciinema.vt.codepoint-polyfill\"]}]\n :optimizations :none\n :pretty-print true}}\n :devcards {:source-paths [\"src\" \"dev\/cards\" ]\n :figwheel {:devcards true}\n :compiler {:main \"asciinema.player.cards\"\n :asset-path \"js\/devcards\"\n :output-to \"resources\/public\/js\/devcards.js\"\n :output-dir \"resources\/public\/js\/devcards\"\n :source-map-timestamp true\n :foreign-libs [{:file \"public\/element.js\"\n :provides [\"asciinema.player.element\"]}]\n :optimizations :none}}\n :test {:source-paths [\"src\" \"test\"]\n :compiler {:output-to \"resources\/public\/js\/test.js\"\n :source-map true\n :foreign-libs [{:file \"public\/element.js\"\n :provides [\"asciinema.player.element\"]}\n {:file \"codepoint-polyfill.js\"\n :provides [\"asciinema.vt.codepoint-polyfill\"]}]\n :optimizations :none\n :pretty-print false\n :main \"asciinema.player.runner\"}}\n :release {:source-paths [\"src\"]\n :compiler {:output-to \"resources\/public\/js\/asciinema-player.js\"\n :output-dir \"resources\/public\/js\/release\"\n :closure-defines {goog.DEBUG false}\n :preamble [\"license.js\" \"public\/CustomEvent.js\" \"public\/CustomElements.min.js\"]\n :foreign-libs [{:file \"public\/element.js\"\n :provides [\"asciinema.player.element\"]}\n {:file \"codepoint-polyfill.js\"\n :provides [\"asciinema.vt.codepoint-polyfill\"]}]\n :optimizations :advanced\n :elide-asserts true\n :source-map \"resources\/public\/js\/asciinema-player.js.map\"\n :pretty-print false}}}}\n\n :figwheel {:http-server-root \"public\"\n :server-port 3449\n :css-dirs [\"resources\/public\/css\"]}\n\n :less {:source-paths [\"src\/less\"]\n :target-path \"resources\/public\/css\"})\n","avg_line_length":58.7934782609,"max_line_length":129,"alphanum_fraction":0.4083934184} {"size":619,"ext":"cljs","lang":"Clojure","max_stars_count":3.0,"content":"(ns focus.core\n (:require\n [om.core :as om :include-macros true]\n [sablono.core :as html :refer [html] :include-macros true]))\n\n(enable-console-print!)\n\n(defn focus-input!\n [e owner]\n (.focus (om\/get-node owner \"my-input\"))\n (om\/set-state! owner :force-rerender! true))\n\n(defn focus\n [data owner]\n (reify\n om\/IRenderState\n (render-state [_ {:keys [selected-date] :as state}]\n (html\n [:div\n [:input.my-input {:type \"text\" :ref \"my-input\"}]\n [:button {:onClick #(focus-input! % owner)} \"Click me to focus!\"]]))))\n\n(om\/root focus {} {:target (.getElementById js\/document \"root\")})\n","avg_line_length":25.7916666667,"max_line_length":78,"alphanum_fraction":0.6138933764} {"size":2777,"ext":"clj","lang":"Clojure","max_stars_count":396.0,"content":"(ns chromex.app.appview-tag\n \"Use the appview tag to embed other Chrome Apps within your\n Chrome App. (see Usage).\n\n * available since Chrome 43\n * https:\/\/developer.chrome.com\/apps\/tags\/appview\"\n\n (:refer-clojure :only [defmacro defn apply declare meta let partial])\n (:require [chromex.wrapgen :refer [gen-wrap-helper]]\n [chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))\n\n(declare api-table)\n(declare gen-call)\n\n; -- functions --------------------------------------------------------------------------------------------------------------\n\n(defmacro connect\n \"Requests another app to be embedded.\n\n |app| - The extension id of the app to be embedded.\n |data| - Optional developer specified data that the app to be embedded can use when making an embedding decision.\n\n This function returns a core.async channel of type `promise-chan` which eventually receives a result value.\n Signature of the result value put on the channel is [success] where:\n\n |success| - True if the embedding request succeded.\n\n In case of an error the channel closes without receiving any value and relevant error object can be obtained via\n chromex.error\/get-last-error.\n\n https:\/\/developer.chrome.com\/apps\/tags\/appview#method-connect.\"\n ([app data] (gen-call :function ::connect &form app data))\n ([app] `(connect ~app :omit)))\n\n; -- convenience ------------------------------------------------------------------------------------------------------------\n\n(defmacro tap-all-events\n \"Taps all valid non-deprecated events in chromex.app.appview-tag namespace.\"\n [chan]\n (gen-tap-all-events-call api-table (meta &form) chan))\n\n; ---------------------------------------------------------------------------------------------------------------------------\n; -- API TABLE --------------------------------------------------------------------------------------------------------------\n; ---------------------------------------------------------------------------------------------------------------------------\n\n(def api-table\n {:namespace \"\",\n :since \"43\",\n :functions\n [{:id ::connect,\n :name \"connect\",\n :callback? true,\n :params\n [{:name \"app\", :type \"string\"}\n {:name \"data\", :optional? true, :type \"any\"}\n {:name \"callback\", :optional? true, :type :callback, :callback {:params [{:name \"success\", :type \"boolean\"}]}}]}]})\n\n; -- helpers ----------------------------------------------------------------------------------------------------------------\n\n; code generation for native API wrapper\n(defmacro gen-wrap [kind item-id config & args]\n (apply gen-wrap-helper api-table kind item-id config args))\n\n; code generation for API call-site\n(def gen-call (partial gen-call-helper api-table))","avg_line_length":42.7230769231,"max_line_length":125,"alphanum_fraction":0.5174648902} {"size":320,"ext":"clj","lang":"Clojure","max_stars_count":86.0,"content":";; Copyright \u00a9 2014 JUXT LTD.\n\n(ns modular.reactor\n (:require [com.stuartsierra.component :as component]\n [clojurewerkz.meltdown.reactor :as mr]))\n\n(defrecord Reactor []\n component\/Lifecycle\n (start [this]\n (assoc this :reactor (mr\/create)))\n (stop [this] this))\n\n(defn new-reactor\n []\n (->Reactor))\n","avg_line_length":20.0,"max_line_length":54,"alphanum_fraction":0.653125} {"size":1521,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":";; Copyright (c) 7theta. All rights reserved.\n;; The use and distribution terms for this software are covered by the\n;; MIT License (https:\/\/opensource.org\/licenses\/MIT) which can also be\n;; found in the LICENSE file at the root of this distribution.\n;;\n;; By using this software in any fashion, you are agreeing to be bound by\n;; the terms of this license.\n;; You must not remove this notice, or any others, from this software.\n\n(defproject com.7theta\/servo \"2.3.2\"\n :description \"A rehinkdb client library designed to integrate with signum\"\n :url \"https:\/\/github.com\/7theta\/servo\"\n :license {:name \"MIT License\"\n :url \"https:\/\/opensource.org\/licenses\/MIT\"}\n :dependencies [[org.clojure\/clojure \"1.10.3\"]\n\n [com.7theta\/signum \"4.2.1\"]\n [com.7theta\/tempus \"0.3.2\"]\n [com.7theta\/utilis \"1.12.2\"]\n\n [com.7theta\/aleph \"0.4.7-alpha9-1\"]\n [com.7theta\/gloss \"0.2.6-1\"]\n\n [metosin\/jsonista \"0.3.4\"]\n [inflections \"0.13.2\"]\n [metrics-clojure \"2.10.0\"]\n [integrant \"0.8.0\"]]\n :profiles {:dev {:global-vars {*warn-on-reflection* true}\n :dependencies [[org.clojure\/tools.namespace \"1.1.0\"]\n [integrant\/repl \"0.3.2\"]]\n :source-paths [\"dev\"]}}\n :clean-targets ^{:protect false} [\"out\" \"target\"]\n :prep-tasks [\"compile\"]\n :scm {:name \"git\"\n :url \"https:\/\/github.com\/7theta\/servo\"})\n","avg_line_length":42.25,"max_line_length":76,"alphanum_fraction":0.5785667324} {"size":256,"ext":"cljc","lang":"Clojure","max_stars_count":null,"content":"(ns four-clojure-problems.for-144)\n\n(def osilrate (fn [start & functions]\n (reductions (fn [result function]\n (function result))\n start\n (cycle functions))))\n","avg_line_length":32.0,"max_line_length":49,"alphanum_fraction":0.44140625} {"size":78,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"\n(def pos (atom [0 0]))\n(def vel (atom [1 1]))\n\n(reset! pos (map + @pos vel))\n","avg_line_length":13.0,"max_line_length":29,"alphanum_fraction":0.5256410256} {"size":592,"ext":"clj","lang":"Clojure","max_stars_count":1.0,"content":"(defproject xmlfmt-clj \"0.1.0-alpha.2\"\n :description \"xmlfmt-clj\"\n :dependencies [[org.clojure\/clojure \"1.10.0\"]]\n :plugins [[lein-ancient \"0.6.14\"]\n [lein-ring \"0.9.7\"]\n [lein-try \"0.4.3\"]\n [test2junit \"1.2.2\"]]\n :main xmlfmt-clj.main\n :scm {:name \"git\"\n :url \"https:\/\/github.com\/olecve\/xmlfmt-cl\"}\n :profiles {:uberjar {:aot :all}\n :dev {:dependencies [[org.clojure\/tools.namespace \"0.2.11\"]]\n :test2junit-output-dir \"target\/test-results\"\n :source-paths [\"dev\"]}})\n","avg_line_length":39.4666666667,"max_line_length":86,"alphanum_fraction":0.5219594595} {"size":8145,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns domain-specific-languages-clojure.crisp\n (:require [instaparse.core :as insta]))\n\n(deftype crisp-fn [env arg-list body])\n\n(defn crisp-fn? [x]\n (instance? crisp-fn x))\n\n(def self-evaling?\n (some-fn string? nil? number? boolean? fn?))\n\n(defn crisp-eval [env expr]\n (cond\n (self-evaling? expr)\n expr\n\n (symbol? expr)\n (if (contains? env expr)\n (get env expr)\n (throw (ex-info \"I could not find the symbol in the environment.\"\n {:symbol expr\n :environment env})))\n\n (seq? expr)\n (let [[op & args] expr]\n (case op\n if (let [[test then else] args]\n (if (crisp-eval env test)\n (crisp-eval env then)\n (crisp-eval env else)))\n quote (let [[quote-expr] args]\n quote-expr)\n do (last (map #(crisp-eval env %) args))\n let (let [[binding & body] args]\n (cond\n (empty? binding)\n (crisp-eval env (cons 'do body))\n\n (= 1 (count binding))\n (throw (ex-info \"Odd number of binding forms in let.\"\n {:bindings binding}))\n\n :else\n (let [[var val & rst] binding\n evaled-val (crisp-eval env val)]\n (crisp-eval (assoc env var evaled-val)\n (cons 'let (cons rst body))))))\n fn (let [[arg-list & body] args]\n (crisp-fn. env arg-list body))\n (let [[f & args] (map #(crisp-eval env %) expr)]\n (cond\n (ifn? f)\n (apply f args)\n\n (crisp-fn? f)\n (crisp-eval\n (merge (.-env f) (zipmap (.-arg-list f) args))\n (cons 'do (.-body f)))\n\n :else\n (throw (ex-info \"I don't know how to call this as a function.\"\n {:expression expr\n :evaled-value f}))))))\n\n :else\n (throw (ex-info \"I don't know how to evaluate this expression.\"\n {:expression expr}))))\n\n(defn crisp-compile* [expr static-env]\n (cond\n (self-evaling? expr)\n (fn [env]\n expr)\n\n (symbol? expr)\n (if (contains? static-env expr)\n (fn [env]\n (get env expr))\n (throw (ex-info \"I could not find the symbol in the environment.\"\n {:symbol expr\n :environment static-env})))\n\n (seq? expr)\n (let [[op & args] expr]\n (case op\n if (let [[testf thenf elsef]\n (map #(crisp-compile* % static-env) args)]\n (fn [env]\n (if (testf env)\n (thenf env)\n (elsef env))))\n quote (let [[quote-expr] args]\n (fn [env]\n quote-expr))\n do (let [bodyfs (doall (map #(crisp-compile* % static-env) args))]\n (fn [env]\n (last (map #(% env) bodyfs))))\n let (let [[binding & body] args]\n (cond\n (empty? binding)\n (crisp-compile* (cons 'do body) static-env)\n\n (= 1 (count binding))\n (throw (ex-info \"Odd number of binding forms in let.\"\n {:bindings binding}))\n\n :else\n (let [[var val & rst] binding\n valf (crisp-compile* val static-env)\n nextf (crisp-compile*\n (cons 'let (cons rst body))\n (conj static-env var))]\n (fn [env]\n (nextf (assoc env var (valf env)))))))\n fn (let [[arg-list & body] args]\n (if (empty? arg-list)\n (let [bodyf (crisp-compile* (cons 'do body)\n static-env)]\n (fn [env]\n (fn []\n (bodyf env))))\n (let [argname (first arg-list)\n nextf (crisp-compile*\n (cons 'fn (cons (rest arg-list)\n body))\n (conj static-env argname))]\n (fn [env]\n (fn [arg1 & args]\n (apply\n (nextf (assoc env argname arg1))\n args))))))\n (let [[ff & argfs] (doall (map #(crisp-compile* % static-env) expr))]\n (fn [env]\n (let [f (ff env)]\n (cond\n (ifn? f)\n (apply f (map #(% env) argfs))\n\n (crisp-fn? f)\n (crisp-eval\n (merge (.-env f) (zipmap (.-arg-list f) (map #(% env) argfs)))\n (cons 'do (.-body f)))\n\n :else\n (throw (ex-info \"I don't know how to call this as a function.\"\n {:expression expr\n :evaled-value f}))))))))\n\n :else\n (throw (ex-info \"I don't know how to evaluate this expression.\"\n {:expression expr}))))\n\n\n(defmacro crisp-compile [expr static-env]\n `(sut\/crisp-compile* '~expr '~static-env))\n\n(def parse\n (insta\/parser\n \"\n = WS STATEMENT*\n = IFTHENELSE | EXPRESSION SEMI | BLOCK | VARIABLEASSIGNMENT\n = LITERAL | VARIABLE | FUNCTIONDEFINITION | FUNCTIONCALL\n\n(* Statements *)\nIFTHENELSE = IF OPEN EXPRESSION CLOSE STATEMENT ELSE STATEMENT\nBLOCK = OPENCURLY STATEMENT* CLOSECURLY\nVARIABLEASSIGNMENT = LET BINDINGS BLOCK\n\n(* Expressions *)\nVARIABLE = #'[a-zA-Z][\\\\w]*' WS\n = NUMBER | STRING\nFUNCTIONDEFINITION = FUNCTION OPEN PARAMS CLOSE BLOCK\nFUNCTIONCALL = EXPRESSION OPEN ARGS CLOSE\n\n(* Literals *)\nNUMBER = #'\\\\d*[.]?\\\\d+' WS\nSTRING = <'\\\"'> #'[^\\\"]*' <'\\\"'> WS\n\n(* Lists *)\nBINDINGS = (VARIABLE EQUAL EXPRESSION COMMA)* VARIABLE EQUAL EXPRESSION\nPARAMS = WS | (VARIABLE COMMA)* VARIABLE\nARGS = WS | (EXPRESSION COMMA)* EXPRESSION\n\n(* Keywords *)\n = <\\\"if\\\"> WS\n = <\\\"else\\\"> WS\n = <\\\"let\\\"> WS\n = <\\\"function\\\"> WS\n\n(* Puncutation *)\n = <\\\";\\\"> WS\n = <\\\"(\\\"> WS\n = <\\\")\\\"> WS\n = <\\\"{\\\"> WS\n = <\\\"}\\\"> WS\n = <\\\"=\\\"> WS\n = <\\\",\\\"> WS\n\n(* Whitespace *)\n = <#'\\\\s*'>\n\n\"))\n\n(declare rparse rparse-number rparse-symbol rparse-string rparse-list\n gobble-whitespace)\n\n(defn rparse [s]\n (let [[c & cs :as s] (gobble-whitespace s)]\n (cond\n (empty? s)\n [nil nil]\n\n (Character\/isDigit c)\n (rparse-number s)\n\n (Character\/isLetter c)\n (rparse-symbol s)\n\n (= \\\" c)\n (rparse-string s)\n\n (= \\( c)\n (rparse-list s)\n\n :else\n (throw (ex-info \"I don't know how to parse this.\"\n {:string (apply str s)})))))\n\n(defn parse-number [s]\n (if (neg? (.indexOf s \".\"))\n (Integer\/parseInt s)\n (Double\/parseDouble s)))\n\n(defn rparse-number\n ([s]\n (rparse-number [] s))\n ([acc [c & cs :as s]]\n (cond\n (empty? s)\n [(parse-number (apply str acc)) cs]\n\n (or (Character\/isDigit c) (= \\. c))\n (recur (conj acc c) cs)\n\n :else\n [(parse-number (apply str acc)) s])))\n\n(defn symbol-char? [c]\n (or\n (Character\/isLetterOrDigit c)\n (= \\+ c)\n (= \\- c)\n (= \\? c)))\n\n(defn rparse-symbol\n ([s]\n (rparse-symbol [] s))\n ([acc [c & cs :as s]]\n (cond\n (empty? s)\n [(symbol (apply str acc)) cs]\n\n (symbol-char? c)\n (recur (conj acc c) cs)\n\n :else\n [(symbol (apply str acc)) s])))\n\n(defn rparse-string\n ([s]\n (rparse-string [] (rest s)))\n ([acc [c & cs :as s]]\n (cond\n (empty? s)\n (throw (ex-info \"Missing closing quotes.\"\n {:string (apply str s)}))\n\n (= \\\" c)\n [(apply str acc) cs]\n\n :else\n (recur (conj acc c) cs))))\n\n(defn rparse-list\n ([s]\n (rparse-list [] (rest s)))\n ([acc [c & cs :as s]]\n (cond\n (empty? s)\n (throw (ex-info \"Missing closing paren.\"\n {:string (apply str s)\n :acc acc}))\n\n (= \\) c)\n [(seq acc) cs]\n\n :else\n (let [[val rst] (rparse s)]\n (recur (conj acc val) rst)))))\n\n(defn gobble-whitespace [[c & cs :as s]]\n (cond\n (empty? s)\n s\n\n (Character\/isWhitespace c)\n (recur cs)\n\n :else\n s))\n","avg_line_length":26.1897106109,"max_line_length":80,"alphanum_fraction":0.4718232044} {"size":99,"ext":"clj","lang":"Clojure","max_stars_count":2.0,"content":"(ns velho-ds.server)\n\n(defn handler [request]\n {:status 200\n :body (slurp \"public\/index.html\")})","avg_line_length":19.8,"max_line_length":38,"alphanum_fraction":0.6666666667} {"size":629,"ext":"cljs","lang":"Clojure","max_stars_count":null,"content":"(ns chromex.app.i18n (:require-macros [chromex.app.i18n :refer [gen-wrap]])\n (:require [chromex.core]))\n\n; -- functions --------------------------------------------------------------------------------------------------------------\n\n(defn get-accept-languages* [config]\n (gen-wrap :function ::get-accept-languages config))\n\n(defn get-message* [config message-name substitutions]\n (gen-wrap :function ::get-message config message-name substitutions))\n\n(defn get-ui-language* [config]\n (gen-wrap :function ::get-ui-language config))\n\n(defn detect-language* [config text]\n (gen-wrap :function ::detect-language config text))\n\n","avg_line_length":34.9444444444,"max_line_length":125,"alphanum_fraction":0.5914149444} {"size":3717,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns metabase.events.revision\n (:require [clojure.core.async :as async]\n [clojure.tools.logging :as log]\n [metabase.events :as events]\n [metabase.models.card :refer [Card]]\n [metabase.models.dashboard :refer [Dashboard]]\n [metabase.models.metric :refer [Metric]]\n [metabase.models.revision :refer [push-revision!]]\n [metabase.models.segment :refer [Segment]]))\n\n(def ^:const revisions-topics\n \"The `Set` of event topics which are subscribed to for use in revision tracking.\"\n #{:card-create\n :card-update\n :dashboard-create\n :dashboard-update\n :dashboard-add-cards\n :dashboard-remove-cards\n :dashboard-reposition-cards\n :metric-create\n :metric-update\n :metric-delete\n :segment-create\n :segment-update\n :segment-delete})\n\n(defonce ^:private ^{:doc \"Channel for receiving event notifications we want to subscribe to for revision events.\"}\n revisions-channel\n (async\/chan))\n\n\n;;; ## ---------------------------------------- EVENT PROCESSING ----------------------------------------\n\n\n(defn process-revision-event!\n \"Handle processing for a single event notification received on the revisions-channel\"\n [revision-event]\n ;; try\/catch here to prevent individual topic processing exceptions from bubbling up. better to handle them here.\n (try\n (when-let [{topic :topic object :item} revision-event]\n (let [model (events\/topic->model topic)\n id (events\/object->model-id topic object)\n user-id (events\/object->user-id object)\n revision-message (:revision_message object)]\n ;; TODO: seems unnecessary to select each entity again, is there a reason we aren't using `object` directly?\n (case model\n \"card\" (push-revision! :entity Card,\n :id id,\n :object (Card id),\n :user-id user-id,\n :is-creation? (= :card-create topic)\n :message revision-message)\n \"dashboard\" (push-revision! :entity Dashboard,\n :id id,\n :object (Dashboard id),\n :user-id user-id,\n :is-creation? (= :dashboard-create topic)\n :message revision-message)\n \"metric\" (push-revision! :entity Metric,\n :id id,\n :object (Metric id),\n :user-id user-id,\n :is-creation? (= :metric-create topic)\n :message revision-message)\n \"segment\" (push-revision! :entity Segment,\n :id id,\n :object (Segment id),\n :user-id user-id,\n :is-creation? (= :segment-create topic)\n :message revision-message))))\n (catch Throwable e\n (log\/warn (format \"Failed to process revision event. %s\" (:topic revision-event)) e))))\n\n\n\n;;; ## ---------------------------------------- LIFECYLE ----------------------------------------\n\n(defmethod events\/init! ::Revisions\n [_]\n (events\/start-event-listener! revisions-topics revisions-channel process-revision-event!))\n","avg_line_length":45.8888888889,"max_line_length":116,"alphanum_fraction":0.4748453054} {"size":1453,"ext":"cljs","lang":"Clojure","max_stars_count":null,"content":"(ns hours.overtime\n (:require\n [clojure.string]\n [hours.calendar]))\n\n(defn format-balance [balance]\n (defn abs \"(abs n) is the absolute value of n\" [n]\n (if (neg? n)\n (- n)\n n))\n (defn hour [hours minutes]\n (if (= 0 hours)\n (if (= 0 minutes)\n \"0\"\n (clojure.string\/join \"\" [minutes \"m\"]))\n (if (= 0 minutes)\n (clojure.string\/join \"\" [hours \"h\"])\n (clojure.string\/join \"\" [hours \"h\" minutes]))))\n (defn sign [s]\n (cond\n (> balance 0) (clojure.string\/join \"\" [\"+\" s])\n (< balance 0) (clojure.string\/join \"\" [\"-\" s])\n :else s))\n (let [abs-balance (abs balance)\n hours (int (\/ abs-balance 60))\n minutes (- abs-balance (* hours 60))]\n (sign (hour hours minutes))))\n\n(defn parse-overtime [overtime]\n (let [r (re-matches #\"^([+-]?)(\\d{1,3})\" overtime)\n full (first r)\n sign (second r)\n digits (last r)]\n (cond\n (not r) 0\n (= (count digits) 3) (let [absolute (+ (* (js\/parseInt (subs digits 0 1)) 60) (js\/parseInt (subs digits 1)))]\n (if (= \"-\" sign)\n (- absolute)\n absolute))\n (= (count digits) 2) (js\/parseInt full)\n (= (count digits) 1) (* (js\/parseInt full) 60)\n )))\n\n(defn get-week-balance [get-day week]\n (let [week-days (hours.calendar\/days-of-week week)]\n (apply + (map #(parse-overtime (get-day %)) week-days))))\n","avg_line_length":30.914893617,"max_line_length":115,"alphanum_fraction":0.5037852719} {"size":970,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns clj-scraper.database\n (:use clojure.pprint)\n (:require [clojure.java.jdbc :as sql]))\n\n(def db\n {:classname \"org.sqlite.JDBC\"\n :subprotocol \"sqlite\"\n :subname \"db\/database.db\"\n })\n\n(defn create-db \n \"Drop the table then recreate it.\"\n []\n (sql\/execute! db [\"drop table if exists animals\"])\n (try \n (let [cs (sql\/create-table-ddl :animals\n [[:id :integer :primary :key :autoincrement]\n [:img :text]\n [:name :text]\n [:link :text]])]\n (sql\/execute! db [cs]))\n (catch Exception e (println e))))\n ; We should actual do something with that exception\n ; but this is just for fun. So... \u00af\\_(\u30c4)_\/\u00af\n\n\n(defn output-all-records\n [conn]\n (sql\/query conn \"select * from animals\"))\n\n(defn insert-record\n \"Insert a record into the animals table\"\n [record]\n (sql\/insert! db :animals record))","avg_line_length":28.5294117647,"max_line_length":80,"alphanum_fraction":0.5371134021} {"size":3535,"ext":"clj","lang":"Clojure","max_stars_count":2.0,"content":"(ns clojupyter.util\n (:require [cheshire.core :as cheshire]\n [clojure.string :as str]\n [clojure.pprint :as pp]\n [io.simplect.compose :refer [def- redefn]]\n [pandect.algo.sha256 :refer [sha256-hmac]]\n [clojupyter.log :as log]))\n\n(def- CHARSET \"UTF8\")\n\n(def json-str cheshire\/generate-string)\n\n(defn bytes->string\n [bytes]\n (String. bytes \"UTF-8\"))\n\n(defn string->bytes\n [v]\n (cond\n (= (type v) (Class\/forName \"[B\"))\n ,, v\n (string? v)\n ,, (.getBytes ^String v CHARSET)\n :else\n ,, (.getBytes (json-str v) CHARSET)))\n\n;;; ----------------------------------------------------------------------------------------------------\n;;; EXTERNAL\n;;; ----------------------------------------------------------------------------------------------------\n\n(def IDSMSG \"\")\n(def IDSMSG-BYTES (string->bytes IDSMSG))\n(def SEGMENT-ORDER [:envelope :delimiter :signature :header :parent-header :metadata :content])\n\n(defn code-empty?\n [s]\n (-> s str str\/trim count zero?))\n\n(defn code-hushed?\n [s]\n (-> s str str\/trimr (str\/ends-with? \";\")))\n\n(def delimiter-frame?\n \"Accepts a single argument which must be a byte-array, returns `true` the array represents the\n Jupyter 'delimiter' frame (consisting of the bytes of the text '' encoded as UTF-8);\n otherwise returns `false`.\"\n (let [delim ^bytes IDSMSG-BYTES\n n-delim (count delim)]\n (fn [^bytes other-byte-array]\n (if (= n-delim (count other-byte-array))\n (loop [idx 0]\n (cond\n (= idx n-delim)\n ,, true\n (= (aget delim idx) (aget other-byte-array idx))\n ,, (recur (inc idx))\n :else\n ,, false))\n false))))\n\n(defn uuid?\n [x]\n (boolean (re-find #\"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\" x)))\n\n(defmacro ^{:style\/indent :defn} define-simple-record-print\n [name format-fn]\n (if (symbol? name)\n (let [fmtfn (gensym \"fn-\")]\n `(let [~fmtfn ~format-fn]\n (defmethod print-method ~name\n [rec# w#]\n (.write w# (~fmtfn rec#)))\n (defmethod pp\/simple-dispatch ~name\n [rec#]\n (print (~fmtfn rec#)))))\n (throw (Exception. (str \"define-simple-record-print: invalid form\")))))\n\n\n(defn make-signer-checker\n [key]\n (let [mkchecker (fn mkchecker [signer]\n (fn [{:keys [header parent-header metadata content preframes]}]\n (let [payload-vec [header parent-header metadata content]\n signature (.-signature preframes)\n check-signature (signer payload-vec)]\n (log\/debug \"Checking message with key\" key)\n (or (= \"\" check-signature) ; When signer returns \"\" authentication and message signing is disabled.\n (= check-signature (bytes->string signature))))))\n signer\t(if (empty? key)\n (constantly \"\")\n (fn signer [payload-vec]\n ;; BUG: The signer fn should not generate its own strings from maps, but it should\n ;; check the strings it received from the channel.\n (sha256-hmac (apply str payload-vec) key)))]\n [signer (mkchecker signer)]))\n\n(redefn parse-json-str cheshire\/parse-string)\n\n(defn to-json-str\n \"Returns JSON representation (string) of `v`.\"\n [v]\n (let [repr (java.io.StringWriter.)]\n (cheshire\/generate-stream v repr)\n (str repr)))\n","avg_line_length":33.6666666667,"max_line_length":128,"alphanum_fraction":0.527864215} {"size":843,"ext":"clj","lang":"Clojure","max_stars_count":255.0,"content":"#!\/usr\/bin\/env bb\n\n(ns test-coverage\n (:require [helper.main :as main]\n [helper.shell :as shell]\n [lread.status-line :as status]))\n\n(defn generate-doc-tests []\n (status\/line :head \"Generating tests for code blocks in documents\")\n (shell\/command \"clojure -X:test-doc-blocks gen-tests\"))\n\n(defn run-clj-doc-tests []\n (status\/line :head \"Running unit and code block tests under Clojure for coverage report\")\n (shell\/command \"clojure\" \"-M:test-common:test-docs:kaocha\"\n \"--plugin\" \"cloverage\" \"--codecov\"\n \"--profile\" \"coverage\"\n \"--no-randomize\"\n \"--reporter\" \"documentation\"))\n\n(defn -main [& args]\n (when (main\/doc-arg-opt args)\n (generate-doc-tests)\n (run-clj-doc-tests))\n nil)\n\n(main\/when-invoked-as-script\n (apply -main *command-line-args*))\n","avg_line_length":30.1071428571,"max_line_length":91,"alphanum_fraction":0.6144721234} {"size":244,"ext":"cljs","lang":"Clojure","max_stars_count":87.0,"content":"(ns example.another-core-test\n (:require\n [cljs.test :refer-macros [deftest is testing]]\n [example.core :refer [hello-user]]\n [devcards.core :refer-macros [defcard-rg]]))\n\n(defcard-rg another-hello-user-test\n [hello-user true])\n","avg_line_length":27.1111111111,"max_line_length":51,"alphanum_fraction":0.6762295082} {"size":11320,"ext":"clj","lang":"Clojure","max_stars_count":1.0,"content":";; ## SQL\/query-related functions for events\n\n(ns com.puppetlabs.puppetdb.query.events\n (:require [puppetlabs.kitchensink.core :as kitchensink]\n [clojure.string :as string]\n [com.puppetlabs.cheshire :as json])\n (:use [com.puppetlabs.jdbc :only [underscores->dashes dashes->underscores valid-jdbc-query? add-limit-clause]]\n [com.puppetlabs.puppetdb.scf.storage-utils :only [db-serialize sql-regexp-match]]\n [com.puppetlabs.puppetdb.query :only [compile-term compile-and compile-or compile-not-v2 execute-query]]\n [clojure.core.match :only [match]]\n [clj-time.coerce :only [to-timestamp]]\n [com.puppetlabs.puppetdb.query.paging :only [validate-order-by!]]))\n\n(defn compile-resource-event-inequality\n \"Compile a timestamp inequality for a resource event query (> < >= <=).\n The `value` for comparison must be coercible to a timestamp via\n `clj-time.coerce\/to-timestamp` (e.g., an ISO-8601 compatible date-time string).\"\n [& [op path value :as args]]\n {:post [(map? %)\n (string? (:where %))]}\n (when-not (= (count args) 3)\n (throw (IllegalArgumentException. (format \"%s requires exactly two arguments, but %d were supplied\" op (dec (count args))))))\n\n (let [timestamp-fields {\"timestamp\" \"resource_events.timestamp\"\n \"run-start-time\" \"reports.start_time\"\n \"run-end-time\" \"reports.end_time\"\n \"report-receive-time\" \"reports.receive_time\"}]\n (match [path]\n [(field :guard (kitchensink\/keyset timestamp-fields))]\n (if-let [timestamp (to-timestamp value)]\n {:where (format \"%s %s ?\" (timestamp-fields field) op)\n :params [(to-timestamp value)]}\n (throw (IllegalArgumentException. (format \"'%s' is not a valid timestamp value\" value))))\n\n :else (throw (IllegalArgumentException.\n (str op \" operator does not support object '\" path \"' for resource events\"))))))\n\n(defn compile-resource-event-equality\n \"Compile an = predicate for resource event query. `path` represents the field to\n query against, and `value` is the value.\"\n [& [path value :as args]]\n {:post [(map? %)\n (string? (:where %))]}\n (when-not (= (count args) 2)\n (throw (IllegalArgumentException. (format \"= requires exactly two arguments, but %d were supplied\" (count args)))))\n (let [path (dashes->underscores path)]\n (match [path]\n [\"certname\"]\n {:where (format \"reports.certname = ?\")\n :params [value]}\n\n [\"latest_report?\"]\n {:where (format \"resource_events.report %s (SELECT latest_reports.report FROM latest_reports)\"\n (if value \"IN\" \"NOT IN\"))}\n\n [(field :guard #{\"report\" \"resource_type\" \"resource_title\" \"status\"})]\n {:where (format \"resource_events.%s = ?\" field)\n :params [value] }\n\n ;; these fields allow NULL, which causes a change in semantics when\n ;; wrapped in a NOT(...) clause, so we have to be very explicit\n ;; about the NULL case.\n [(field :guard #{\"property\" \"message\" \"file\" \"line\" \"containing_class\"})]\n (if-not (nil? value)\n {:where (format \"resource_events.%s = ? AND resource_events.%s IS NOT NULL\" field field)\n :params [value] }\n {:where (format \"resource_events.%s IS NULL\" field)\n :params nil })\n\n ;; these fields require special treatment for NULL (as described above),\n ;; plus a serialization step since the values can be complex data types\n [(field :guard #{\"old_value\" \"new_value\"})]\n {:where (format \"resource_events.%s = ? AND resource_events.%s IS NOT NULL\" field field)\n :params [(db-serialize value)] }\n\n :else (throw (IllegalArgumentException.\n (str path \" is not a queryable object for resource events\"))))))\n\n(defn compile-resource-event-regexp\n \"Compile an ~ predicate for resource event query. `path` represents the field\n to query against, and `pattern` is the regular expression to match.\"\n [& [path pattern :as args]]\n {:post [(map? %)\n (string? (:where %))]}\n (when-not (= (count args) 2)\n (throw (IllegalArgumentException. (format \"~ requires exactly two arguments, but %d were supplied\" (count args)))))\n (let [path (dashes->underscores path)]\n (match [path]\n [\"certname\"]\n {:where (sql-regexp-match \"reports.certname\")\n :params [pattern]}\n\n [(field :guard #{\"report\" \"resource_type\" \"resource_title\" \"status\"})]\n {:where (sql-regexp-match (format \"resource_events.%s\" field))\n :params [pattern] }\n\n ;; these fields allow NULL, which causes a change in semantics when\n ;; wrapped in a NOT(...) clause, so we have to be very explicit\n ;; about the NULL case.\n [(field :guard #{\"property\" \"message\" \"file\" \"line\" \"containing_class\"})]\n {:where (format \"%s AND resource_events.%s IS NOT NULL\"\n (sql-regexp-match (format \"resource_events.%s\" field))\n field)\n :params [pattern] }\n\n :else (throw (IllegalArgumentException.\n (str path \" is not a queryable object for resource events\"))))))\n\n(defn resource-event-ops\n \"Maps resource event query operators to the functions implementing them. Returns nil\n if the operator isn't known.\"\n [op]\n (let [op (string\/lower-case op)]\n (cond\n (= op \"=\") compile-resource-event-equality\n (= op \"and\") (partial compile-and resource-event-ops)\n (= op \"or\") (partial compile-or resource-event-ops)\n (= op \"not\") (partial compile-not-v2 resource-event-ops)\n (#{\">\" \"<\" \">=\" \"<=\"} op) (partial compile-resource-event-inequality op)\n (= op \"~\") compile-resource-event-regexp)))\n\n(def event-columns\n {\"certname\" [\"reports\"]\n \"configuration_version\" [\"reports\"]\n \"start_time\" [\"reports\" \"run_start_time\"]\n \"end_time\" [\"reports\" \"run_end_time\"]\n \"receive_time\" [\"reports\" \"report_receive_time\"]\n \"report\" [\"resource_events\"]\n \"status\" [\"resource_events\"]\n \"timestamp\" [\"resource_events\"]\n \"resource_type\" [\"resource_events\"]\n \"resource_title\" [\"resource_events\"]\n \"property\" [\"resource_events\"]\n \"new_value\" [\"resource_events\"]\n \"old_value\" [\"resource_events\"]\n \"message\" [\"resource_events\"]\n \"file\" [\"resource_events\"]\n \"line\" [\"resource_events\"]\n \"containment_path\" [\"resource_events\"]\n \"containing_class\" [\"resource_events\"]})\n\n;; This is the template for the SELECT statement that we use in the common case.\n(def default-select\n \"SELECT %s\n FROM resource_events\n JOIN reports ON resource_events.report = reports.hash\n WHERE %s\")\n\n\n;; This is the template for the SELECT statement that we use if we are filtering\n;; out duplicate events that occurred on the same resource (per node).\n(def distinct-select\n \"SELECT %s\n FROM resource_events\n JOIN reports ON resource_events.report = reports.hash\n JOIN (SELECT reports.certname,\n resource_events.resource_type,\n resource_events.resource_title,\n resource_events.property,\n MAX(resource_events.timestamp) AS timestamp\n FROM resource_events\n JOIN reports ON resource_events.report = reports.hash\n WHERE %s\n GROUP BY certname, resource_type, resource_title, property) latest_events\n ON reports.certname = latest_events.certname\n AND resource_events.resource_type = latest_events.resource_type\n AND resource_events.resource_title = latest_events.resource_title\n AND ((resource_events.property = latest_events.property) OR\n (resource_events.property IS NULL AND latest_events.property IS NULL))\n AND resource_events.timestamp = latest_events.timestamp\")\n\n(defn query->sql\n \"Compile a resource event `query` into an SQL expression.\"\n [query-options query]\n {:pre [(sequential? query)]\n :post [(valid-jdbc-query? %)]}\n (let [{:keys [where params]} (compile-term resource-event-ops query)\n select-template (if (:distinct-resources? query-options)\n distinct-select\n default-select)\n sql (format select-template\n (string\/join \", \"\n (map\n (fn [[column [table alias]]]\n (str table \".\" column\n (if alias (format \" AS %s\" alias) \"\")))\n event-columns))\n where)]\n (apply vector sql params)))\n\n(defn limited-query-resource-events\n \"Take a limit, paging-options map, a query, and its parameters,\n and return a map containing the results and metadata.\n\n The returned map will contain a key `:result`, whose value is vector of\n resource events which match the query. If the paging-options indicate\n that a total result count should also be returned, then the map will\n contain an additional key `:count`, whose value is an integer.\n\n Throws an exception if the query would return more than `limit` results.\n (A value of `0` for `limit` means that the query should not be limited.)\"\n [limit paging-options [query & params]]\n {:pre [(and (integer? limit) (>= limit 0))]\n :post [(or (zero? limit) (<= (count %) limit))\n (map? %)\n (contains? % :result)\n (sequential? (:result %))]}\n (validate-order-by! (map keyword (keys event-columns)) paging-options)\n (let [limited-query (add-limit-clause limit query)\n results (execute-query\n limit\n (apply vector limited-query params)\n paging-options)]\n (assoc results :result\n (map\n #(-> (kitchensink\/mapkeys underscores->dashes %)\n (update-in [:old-value] json\/parse-string)\n (update-in [:new-value] json\/parse-string))\n (:result results)))))\n\n(defn query-resource-events\n \"Take a paging-options map, a query, and its parameters, and return a map\n containing matching resource events and metadata. For more information about\n the return value, see `limited-query-resource-events`.\"\n [paging-options [sql & params]]\n {:pre [(string? sql)]}\n (limited-query-resource-events 0 paging-options (apply vector sql params)))\n\n(defn events-for-report-hash\n \"Given a particular report hash, this function returns all events for that\n given hash.\"\n [report-hash]\n {:pre [(string? report-hash)]\n :post [(vector? %)]}\n (let [query [\"=\" \"report\" report-hash]\n ;; we aren't actually supporting paging through this code path for now\n paging-options {}]\n (vec\n (->> query\n (query->sql nil)\n (query-resource-events paging-options)\n (:result)\n (map #(-> %\n (dissoc :run-start-time)\n (dissoc :run-end-time)\n (dissoc :report-receive-time)))))))\n","avg_line_length":45.8299595142,"max_line_length":129,"alphanum_fraction":0.6038869258} {"size":13521,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":";; Copyright \u00a9 2016-2018, JUXT LTD.\n\n(ns tick.ical\n (:require\n [clojure.set :as set]\n [clojure.string :as str]\n [clojure.java.io :as io]\n [clojure.spec.alpha :as s]\n [tick.core :as t]\n [tick.interval :as ival])\n (:import\n [java.time Instant LocalDate LocalDateTime ZonedDateTime ZoneId ZoneRegion]\n [java.time.format DateTimeFormatter]))\n\n;; Have considered wrapping ical4j. However, since ical4j does not\n;; use Java 8 time (as of the time of writing), any appeals to\n;; maturity\/stability are moot. Sometimes it's a bad idea to wrap a\n;; Java library simply because one exists (concurrency issues, etc.)\n\n(def CRLF \"\\r\\n\")\n\n(defn contentline\n \"Fold the given string value returning a sequence of strings up to\n 75 octets in length, as per RFC 5545 folding rules.\"\n [s]\n (let [limit 75]\n (loop [acc [] n 0]\n (if (>= (+ n limit) (count s))\n (conj acc (str\n (if (empty? acc) \"\" \" \")\n (subs s n)\n CRLF))\n (recur\n (conj acc (str\n (if (empty? acc) \"\" \" \")\n (subs s n (+ n limit))\n CRLF))\n (+ limit n))))))\n\n(defn print-cl\n \"Folding print, where long lines are folded as per RFC 5545 Section 4.1\"\n [& args]\n (doseq [line (contentline (apply str args))]\n (print line)))\n\n(defprotocol ICalendarValue\n (serialize-value [_] \"\"))\n\n(def DATE-TIME-FORM-1-PATTERN (DateTimeFormatter\/ofPattern \"YYYYMMdd'T'HHmmss\"))\n\n;; Only call with ZoneID of UTC otherwise produces invalid ICAL format\n(def DATE-TIME-FORM-2-PATTERN (DateTimeFormatter\/ofPattern \"YYYYMMdd'T'HHmmssX\"))\n\n(def DATE-TIME-FORM-3-PATTERN (DateTimeFormatter\/ofPattern \"YYYYMMdd'T'HHmmss\"))\n\n(extend-protocol ICalendarValue\n String\n (serialize-value [s] {:value s})\n Instant\n (serialize-value [i] {:value (.format (ZonedDateTime\/ofInstant i (ZoneId\/of \"UTC\")) DATE-TIME-FORM-2-PATTERN)})\n LocalDate\n (serialize-value [s] {:value (.format s DateTimeFormatter\/BASIC_ISO_DATE)})\n LocalDateTime\n (serialize-value [s] {:value (.format s DATE-TIME-FORM-1-PATTERN)})\n ZonedDateTime\n (serialize-value [s] {:value (.format s DATE-TIME-FORM-3-PATTERN)\n :params {:tzid (t\/zone s)}})\n ZoneRegion\n (serialize-value [zr] {:value (str zr)})\n clojure.lang.APersistentMap\n (serialize-value [s] s))\n\n(defprotocol ICalendarObject\n (property-values [obj prop-name]\n \"Return the properties of an ICalendarObject with the given\n name. Returns a sequence of values, since iCalendar properties may\n have multiple values.\")\n (property-value [obj prop-name]\n \"Return the first property value of an ICalendarObject.\"))\n\n(defprotocol IPrintable\n (print-object [_] \"Print as an iCalendar object\"))\n\n(defmacro wrap-with [c & body]\n `(do\n (print-cl \"BEGIN:\" ~c)\n ~@body\n (print-cl \"END:\" ~c)))\n\n(defn print-property [prop-name prop-value]\n (let [{:keys [params value]} (serialize-value prop-value)]\n (print-cl\n (str\/upper-case (name prop-name))\n (apply str (for [[k v] params]\n (str \";\" (str\/upper-case (name k)) \"=\" v)))\n \":\"\n value)))\n\n(defrecord Property [name value]\n IPrintable\n (print-object [_]\n (print-property name value)))\n\n(defrecord VEvent []\n t\/ITimeSpan\n (beginning [this] (t\/beginning (property-value this :dtstart)))\n ;; This might seem wrong but we use t\/beginning to convert a\n ;; date-time to the same date-time, and a date to midnight (the\n ;; start of that date). TODO: Is this explained in the RFC anywhere?\n (end [this] (t\/beginning (property-value this :dtend)))\n\n IPrintable\n (print-object [this]\n (wrap-with\n \"VEVENT\"\n (doseq [prop (:properties this)]\n (print-object prop))))\n\n ICalendarObject\n (property-values [this prop-name]\n (->> this\n :properties\n (filter #(= (:name %) (str\/upper-case (name prop-name))))\n (mapv :value)))\n (property-value [this prop-name]\n (first (property-values this prop-name)))\n\n t\/IConversion\n (inst [this] (t\/inst (property-value this :dtstart)))\n (instant [this] (t\/inst (property-value this :dtstart)))\n (offset-date-time [this] (t\/offset-date-time (property-value this :dtstart)))\n (zoned-date-time [this] (t\/zoned-date-time (property-value this :dtstart)))\n\n t\/IExtraction\n (time [this] (t\/time (property-value this :dtstart)))\n (date [this] (t\/date (property-value this :dtstart)))\n (date-time [this] (t\/date-time (property-value this :dtstart)))\n (nanosecond [this] (t\/nanosecond (property-value this :dtstart)))\n (microsecond [this] (t\/microsecond (property-value this :dtstart)))\n (millisecond [this] (t\/millisecond (property-value this :dtstart)))\n (second [this] (t\/second (property-value this :dtstart)))\n (minute [this] (t\/minute (property-value this :dtstart)))\n (hour [this] (t\/hour (property-value this :dtstart)))\n (day-of-week [this] (t\/day-of-week (property-value this :dtstart)))\n (day-of-month [this] (t\/day-of-month (property-value this :dtstart)))\n (month [this] (t\/month (property-value this :dtstart)))\n (year [this] (t\/year (property-value this :dtstart)))\n (year-month [this] (t\/year-month (property-value this :dtstart)))\n (zone [this] (t\/zone (property-value this :dtstart)))\n (zone-offset [this] (t\/zone-offset (property-value this :dtstart))))\n\n(defrecord VCalendar [subobjects]\n ;; TODO: Add t\/ITimeSpan\n IPrintable\n (print-object [this]\n (wrap-with\n \"VCALENDAR\"\n (doseq [obj subobjects]\n (print-object obj))))\n ICalendarObject\n (property-values [this prop-name]\n (->> this\n :properties\n (filter #(= (:name %) (str\/upper-case (name prop-name))))\n (mapv :value)))\n (property-value [this prop-name]\n (first (property-values this prop-name))))\n\n(comment\n ;; Form 1: DATE WITH LOCAL TIME\n (with-out-str\n (print-object\n (vcalendar\n (vevent \"Malcolm is on holiday!\"\n (t\/date \"2018-07-21\")\n (t\/date \"2018-07-31\")\n :description \"The content information associated with an iCalendar object is formatted using a syntax similar to that defined by [RFC 2425]. That is, the content information consists of CRLF-separated content lines.\"))))\n\n ;; Form 2: DATE WITH UTC TIME\n (with-out-str\n (print-object\n (vcalendar\n (vevent \"Malcolm is in a meeting!\"\n (t\/now)\n (t\/+ (t\/now) (t\/minutes 50))\n :description \"The content information associated with an iCalendar object is formatted using a syntax similar to that defined by [RFC 2425]. That is, the content information consists of CRLF-separated content lines.\"))))\n\n ;; Form 3: DATE WITH LOCAL TIME AND TIME ZONE REFERENCE\n (with-out-str\n (print-object\n (vcalendar\n (vevent\n \"Malcolm is in a meeting, in New York!\"\n (t\/at-zone (t\/at (t\/today) \"14:00\") \"America\/New_York\")\n (t\/at-zone (t\/at (t\/today) \"14:50\") \"America\/New_York\")\n :description \"The content information associated with an iCalendar object is formatted using a syntax similar to that defined by [RFC 2425]. That is, the content information consists of CRLF-separated content lines.\")))))\n\n\n;; Parsing with spec\n\n(s\/def ::contentline\n (s\/cat\n :name ::name\n :params (s\/*\n (s\/cat\n :semicolon #{\\;}\n :param ::param))\n :colon #{\\:}\n :value ::value))\n\n(defn char-range [from to]\n (map char (range (int from) (inc (int to)))))\n\n(def QSAFE-CHAR\n (set (concat [\\space \\t]\n [(char 0x21)]\n (char-range 0x23 0x7e))))\n\n(def SAFE-CHAR\n (set (concat [\\space \\t]\n [(char 0x21)]\n (char-range 0x23 0x2b)\n (char-range 0x2d 0x39)\n (char-range 0x3c 0x7e))))\n\n(def VALUE-CHAR\n (set (concat [\\space \\t]\n (char-range 0x21 0x7e))))\n;; TODO: Add NON-US-ASCII\n\n(def CONTROL\n (set (concat (char-range 0x00 0x08)\n (char-range 0x0a 0x1f)\n [0x7f])))\n\n(s\/def ::name\n (s\/alt :iana-token ::iana-token\n :x-name ::x-name))\n\n(def ALPHA-DIGIT\n (set\/union (set (char-range \\a \\z))\n (set (char-range \\A \\Z))\n (set (char-range \\0 \\9))))\n\n(s\/def ::iana-token\n (s\/+ (conj ALPHA-DIGIT \\-)))\n\n(s\/def ::x-name\n (s\/cat\n :prefix (s\/cat :x1 #{\\X}\n :x2 #{\\-})\n :vendorid (s\/? (s\/cat :vendorid ::vendorid\n :dash #{\\-}))\n :suffix (s\/+ (set \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890-\"))))\n\n(s\/def ::vendorid\n (s\/and\n (s\/+ (set \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890\"))\n #(= (count %) 3)))\n\n(s\/def ::param\n (s\/cat :param-name ::param-name\n :equals #{\\=}\n :param-value ::param-value\n :param-values (s\/* (s\/cat :comma #{,} :param-value ::param-value))))\n\n(s\/def ::param-name\n (s\/alt :iana-token ::iana-token :x-name ::x-name))\n\n(s\/def ::param-value\n (s\/alt :paramtext ::paramtext\n :quoted-string ::quoted-string))\n\n(s\/def ::paramtext (s\/* ::SAFE-CHAR))\n\n(s\/def ::value (s\/* ::VALUE-CHAR))\n\n(s\/def ::quoted-string\n (s\/cat\n :open-quote #{\\\"}\n :content (s\/* ::QSAFE-CHAR)\n :close-quote #{\\\"}))\n\n;; Any character except CONTROL and DQUOTE\n(s\/def ::QSAFE-CHAR (comp not (conj CONTROL \\\")))\n\n;; Any character except CONTROL, DQUOTE, \";\", \":\", \",\"\n(s\/def ::SAFE-CHAR (comp not (set\/union CONTROL #{\\\" \\; \\: \\,})))\n\n(s\/def ::VALUE-CHAR (comp not CONTROL))\n\n(defn unfolding-line-seq*\n [^java.io.BufferedReader rdr hold]\n (if-let [line (.readLine rdr)]\n (if (= (.charAt line 0) \\space)\n (recur rdr (conj hold line))\n (cons (str\/join hold) (lazy-seq (unfolding-line-seq* rdr [line]))))\n [(str\/join hold)]))\n\n(defn unfolding-line-seq [^java.io.BufferedReader rdr]\n (next (unfolding-line-seq* rdr [])))\n\n(defn extract-name-as-string [[k v]]\n (case k\n :iana-token (apply str v)\n :x-name (str \"X-\" (apply str (:suffix v)))\n (throw (ex-info \"Bad input\" {:k k}))))\n\n(defn extract-param-value-as-string [[k v]]\n (case k\n :paramtext (apply str v)\n :quoted-string (apply str (:content v))))\n\n(defn line->contentline [s]\n (let [m (s\/conform ::contentline (seq s))]\n (when-not (:name m) (throw (ex-info \"No name\" {:contentline s})))\n (let [str-value (-> m :value str\/join)]\n {:name (-> m :name extract-name-as-string)\n :params (->> m :params\n (map (juxt\n (comp extract-name-as-string :param-name :param)\n (comp extract-param-value-as-string :param-value :param)))\n (into {} ))\n ;; We set to the string, but properties may replace this with\n ;; another type\n :value str-value\n ;; We always retain the original string value\n :string-value str-value})))\n\n;; JCF tip\n;;(s\/conform (s\/and (s\/conformer seq) ::iana-token) \"foobar\")\n\n(defmulti add-contentline-to-model\n \"A reducing function that gives a parsed content-line to an\n accumulator that builds a model.\"\n (fn [acc cl] (:name cl)))\n\n(defn error [acc contentline message]\n (update acc :errors\n (fnil conj [])\n {:error message\n :lineno (:lineno contentline)}))\n\n(defn- instantiate [m]\n (case (:object m)\n \"VCALENDAR\" (map->VCalendar m)\n \"VEVENT\" (map->VEvent m)\n m))\n\n(defmethod add-contentline-to-model \"BEGIN\"\n [acc contentline]\n ;; BEGIN means place the current object in the stack, and start a\n ;; new one\n (cond-> acc\n (:curr-object acc) (update :stack (fnil conj []) (:curr-object acc))\n true (assoc :curr-object {:object (:value contentline)\n :lineno (:lineno contentline)})))\n\n(defmethod add-contentline-to-model \"END\"\n [acc contentline]\n ;; END means place the current object in the stack, and start a new\n ;; one\n (let [curr-object (instantiate (:curr-object acc))\n restore-object (some-> (:stack acc) last) ; check if nil, bad state\n restore-object (update restore-object :subobjects (fnil conj []) curr-object)]\n (-> acc\n (assoc :curr-object restore-object\n :stack (vec (butlast (:stack acc)))))))\n\n(defmulti coerce-to-value (fn [value-type value] value-type))\n(defmethod coerce-to-value \"DATE\" [_ value] (LocalDate\/parse value DateTimeFormatter\/BASIC_ISO_DATE))\n(defmethod coerce-to-value nil [_ value] value)\n\n(defn add-property [acc contentline]\n (update-in\n acc [:curr-object :properties] (fnil conj [])\n (map->Property\n (update contentline\n :value\n #(coerce-to-value (get-in contentline [:params \"VALUE\"]) %)))))\n\n(defmethod add-contentline-to-model :default\n [acc contentline]\n (add-property acc contentline))\n\n(defn parse-ical [^java.io.BufferedReader r]\n (->> r\n unfolding-line-seq\n (map line->contentline)\n (map-indexed (fn [n o] (assoc o :lineno (inc n))))\n (reduce add-contentline-to-model {})\n :curr-object\n :subobjects))\n\n(defn event?\n \"Determines whether or not the given map is an event\"\n [{:keys [object]}]\n (= object \"VEVENT\"))\n\n(defn events\n \"Given a vcalendar object, return only the events\"\n [vcalendar]\n (filter event? (:subobjects vcalendar)))\n\n(defn remove-events\n \"Given a vcalendar object, remove events that satisfy pred\"\n [vcalendar pred]\n (update vcalendar\n :subobjects\n (fn [subobjects]\n (->> subobjects\n (remove (every-pred event? pred))\n (into (empty subobjects))))))\n","avg_line_length":32.6594202899,"max_line_length":236,"alphanum_fraction":0.6144515938} {"size":1546,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns pricing-service.persistence.conversions\n (:require [korma.core :refer [raw]]\n [clojure.string :as s]\n [clj-time.core :as t])\n (:import (java.sql Time)\n (org.postgresql.util PGobject)\n (org.joda.time LocalTime)))\n\n(defn pgarray->keywords [arr]\n (mapv keyword (.getArray arr)))\n\n;; PG enums are PGObjects\n(defn kw->pgobject\n [kw type]\n (doto (PGobject.)\n (.setType type)\n (.setValue (name kw))))\n\n;; JDBC expects java.sql.Time for TIME fields, but we want to pass around Joda DateTimes\n;; in our app (or in this case LocalTime) and clj-time doesn't provide the coercion we need\n;; This looks hackish, but is the only solution I found that works without getting screwed\n;; by local TZ settings.\n;; See: http:\/\/stackoverflow.com\/questions\/9422753\/converting-joda-localtime-to-sql-time\/9422817#9422817\n(defn local-time->sql-time [time]\n (-> time\n .toDateTimeToday\n .getMillis\n Time.))\n\n(defn sql-time->local-time [time]\n (LocalTime\/fromDateFields time))\n\n(defn json-time->local-time [time-str]\n (t\/local-time (read-string (subs time-str 0 2)) (read-string (subs time-str 3 5))))\n\n;; Yes this is ugly, but inserting arrays of enum in PG can't be done in another way...\n(defn keywords->pgarray-of-enum [coll type]\n (raw (str \"'{\" (s\/join \",\" (mapv name coll)) \"}'::\" type \"[]\")))\n\n(defn modify\n \"Return record with field modified by fn if field exists, otherwise return record\"\n [record field fn]\n (if (field record)\n (assoc record field (fn (field record)))\n record))","avg_line_length":34.3555555556,"max_line_length":104,"alphanum_fraction":0.6714100906} {"size":946,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(defproject identity \"0.1.0-SNAPSHOT\"\n :description \"FIXME: write description\"\n :url \"http:\/\/example.com\/FIXME\"\n :min-lein-version \"2.0.0\"\n :dependencies [[org.clojure\/clojure \"1.10.0\"]\n [compojure \"1.6.1\"]\n [ring\/ring \"1.8.0\"]\n [ring\/ring-json \"0.5.0\"]\n [ring\/ring-defaults \"0.3.2\"]\n [org.clojure\/java.jdbc \"0.7.11\"]\n [org.clojure\/tools.logging \"0.6.0\"]\n [ch.qos.logback\/logback-classic \"1.2.3\"]\n [common-lib \"0.1.2\"]\n [mysql\/mysql-connector-java \"8.0.19\"]\n [http-kit \"2.1.16\"]]\n :plugins [[lein-ring \"0.12.5\"]]\n :ring {:handler identity.handler\/app}\n :profiles\n {:dev {:dependencies [[javax.servlet\/servlet-api \"2.5\"]\n [ring\/ring-mock \"0.3.2\"]\n [com.h2database\/h2 \"1.4.200\"]]}}\n :main identity.handler\n :aot [identity.handler])\n","avg_line_length":39.4166666667,"max_line_length":57,"alphanum_fraction":0.5105708245} {"size":365,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(defproject brainfuck \"0.1.0-SNAPSHOT\"\n :description \"FIXME: write description\"\n :url \"http:\/\/example.com\/FIXME\"\n :license {:name \"Eclipse Public License\"\n :url \"http:\/\/www.eclipse.org\/legal\/epl-v10.html\"}\n :dependencies [[org.clojure\/clojure \"1.8.0\"]]\n :main ^:skip-aot brainfuck.core\n :target-path \"target\/%s\"\n :profiles {:uberjar {:aot :all}})\n","avg_line_length":36.5,"max_line_length":61,"alphanum_fraction":0.6684931507} {"size":3614,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(defproject tech.gojek\/ziggurat \"2.8.0\"\n :description \"A stream processing framework to build stateless applications on kafka\"\n :url \"https:\/\/github.com\/gojektech\/ziggurat\"\n :license {:name \"Apache License, Version 2.0\"\n :url \"https:\/\/www.apache.org\/licenses\/LICENSE-2.0\"}\n :dependencies [[bidi \"2.1.4\"]\n [camel-snake-kebab \"0.4.0\"]\n [cheshire \"5.8.1\"]\n [clonfig \"0.2.0\"]\n [clj-http \"3.7.0\"]\n [com.cemerick\/url \"0.1.1\"]\n [com.datadoghq\/java-dogstatsd-client \"2.4\"]\n [com.fasterxml.jackson.core\/jackson-databind \"2.9.3\"]\n [com.novemberain\/langohr \"5.0.0\"]\n [com.taoensso\/carmine \"2.17.0\"]\n [io.dropwizard.metrics5\/metrics-core \"5.0.0-rc2\" :scope \"compile\"]\n [medley \"0.8.4\"]\n [mount \"0.1.10\"]\n [org.apache.httpcomponents\/fluent-hc \"4.5.4\"]\n [org.apache.kafka\/kafka-streams \"1.1.1\" :exclusions [org.slf4j\/slf4j-log4j12 log4j]]\n [org.apache.logging.log4j\/log4j-core \"2.7\"]\n [org.apache.logging.log4j\/log4j-slf4j-impl \"2.7\"]\n [org.clojure\/clojure \"1.10.0\"]\n [org.clojure\/data.json \"0.2.6\"]\n [org.clojure\/tools.logging \"0.3.1\"]\n [org.clojure\/tools.nrepl \"0.2.12\"]\n [org.flatland\/protobuf \"0.8.1\"]\n [prismatic\/schema \"1.1.9\"]\n [ring\/ring \"1.6.3\"]\n [ring\/ring-core \"1.6.3\"]\n [ring\/ring-defaults \"0.3.1\"]\n [ring\/ring-jetty-adapter \"1.6.3\"]\n [ring\/ring-json \"0.4.0\"]\n [ring-logger \"0.7.7\"]\n [tech.gojek\/sentry-clj.async \"1.0.0\"]\n [yleisradio\/new-reliquary \"1.0.0\"]]\n :java-source-paths [\"src\/com\"]\n :aliases {\"test-all\" [\"with-profile\" \"default:+1.8:+1.9\" \"test\"]\n \"code-coverage\" [\"with-profile\" \"test\" \"cloverage\" \"--output\" \"coverage\" \"--coveralls\"]}\n :profiles {:uberjar {:aot :all\n :global-vars {*warn-on-reflection* true}}\n :test {:jvm-opts [\"-Dlog4j.configurationFile=resources\/log4j2.test.xml\"]\n :dependencies [[com.google.protobuf\/protobuf-java \"3.5.1\"]\n [io.confluent\/kafka-schema-registry \"4.1.1\"]\n [junit\/junit \"4.12\"]\n [org.apache.kafka\/kafka-streams \"1.1.1\" :classifier \"test\" :exclusions [org.slf4j\/slf4j-log4j12 log4j]]\n [org.apache.kafka\/kafka-clients \"1.1.1\" :classifier \"test\"]\n [org.apache.kafka\/kafka_2.11 \"1.1.1\" :classifier \"test\"]]\n :plugins [[lein-cloverage \"1.0.13\"]]\n :repositories [[\"confluent-repo\" \"https:\/\/packages.confluent.io\/maven\/\"]]}\n :dev {:plugins [[jonase\/eastwood \"0.2.6\"]\n [lein-cljfmt \"0.6.3\"]\n [lein-cloverage \"1.0.13\"]\n [lein-githooks \"0.1.0\"]\n [lein-kibit \"0.1.6\"]]\n :githooks {:auto-install true\n :pre-commit [\"lein cljfmt check && lein kibit\"]\n :pre-push [\"lein test\"]}}\n :1.9 {:dependencies [[org.clojure\/clojure \"1.9.0\"]]}\n :1.8 {:dependencies [[org.clojure\/clojure \"1.8.0\"]]}})\n","avg_line_length":59.2459016393,"max_line_length":141,"alphanum_fraction":0.4709463199} {"size":2340,"ext":"clj","lang":"Clojure","max_stars_count":15.0,"content":"(ns wfl.unit.modules.xx-test\n (:require [clojure.test :refer [deftest is]]\n [wfl.module.xx :as xx]))\n\n(def ^:private output-url \"gs:\/\/fake-output-bucket\/\")\n\n(deftest test-make-inputs-from-cram\n (let [sample \"gs:\/\/fake-input-bucket\/folder\/sample.cram\"\n inputs (xx\/make-inputs-to-save output-url {:input_cram sample})]\n (is (= sample (:input_cram inputs)))\n (is (= \"sample\" (:sample_name inputs)))\n (is (= \"sample\" (:base_file_name inputs)))\n (is (= \"sample\" (:final_gvcf_base_name inputs)))\n (is (= (str output-url \"folder\") (:destination_cloud_path inputs)))))\n\n(deftest test-make-inputs-from-bam\n (let [sample \"gs:\/\/fake-input-bucket\/folder\/sample.bam\"\n inputs (xx\/make-inputs-to-save output-url {:input_bam sample})]\n (is (= sample (:input_bam inputs)))\n (is (= \"sample\" (:sample_name inputs)))\n (is (= \"sample\" (:base_file_name inputs)))\n (is (= \"sample\" (:final_gvcf_base_name inputs)))\n (is (= (str output-url \"folder\") (:destination_cloud_path inputs)))))\n\n(deftest test-specifying-destination_cloud_path\n (let [destination \"gs:\/\/some-bucket\/in-the-middle\/of-nowhere.out\"\n inputs (xx\/make-inputs-to-save output-url\n {:input_bam \"gs:\/\/fake-input-bucket\/sample.bam\"\n :destination_cloud_path destination})]\n (is (= destination (:destination_cloud_path inputs)))))\n\n(deftest test-specifying-sample_name\n (let [name \"geoff\"\n inputs (xx\/make-inputs-to-save output-url\n {:input_bam \"gs:\/\/fake-input-bucket\/sample.bam\"\n :sample_name name})]\n (is (= name (:sample_name inputs)))))\n\n(deftest test-specifying-arbitrary-workflow-inputs\n (is (:arbitrary\n (xx\/make-inputs-to-save output-url\n {:input_bam \"gs:\/\/fake-input-bucket\/sample.bam\"\n :arbitrary \"hai\"}))))\n\n(deftest test-invalid-input-gs-url-throws\n (is (thrown? Exception\n (xx\/make-inputs-to-save\n output-url\n {:input_cram \"https:\/\/domain\/sample.cram\"})))\n (is (thrown? Exception\n (xx\/make-inputs-to-save\n output-url\n {:input_cram \"https:\/\/domain\/sample.cram\"}))))\n","avg_line_length":43.3333333333,"max_line_length":104,"alphanum_fraction":0.5799145299} {"size":419,"ext":"clj","lang":"Clojure","max_stars_count":2.0,"content":" (ns instruments\n (:use [overtone.core]))\n\n(definst bell [freq 440 attack 0 sustain 1 release 1]\n (let [fund freq\n overt1 (* 2.3 freq)\n overt2 (* 3.1 freq)]\n (pan2 (* (env-gen (lin attack 0 sustain 1 release 1))\n (+ (* (sin-osc fund) 1)\n (* (sin-osc overt1) 0.5)\n (* (sin-osc overt2) 0.2))))))\n","avg_line_length":34.9166666667,"max_line_length":67,"alphanum_fraction":0.4272076372} {"size":4809,"ext":"cljc","lang":"Clojure","max_stars_count":1.0,"content":"(ns ^:no-doc zprint.redef\n #?@(:clj [(:import (java.util.concurrent.locks ReentrantLock))]))\n\n;;\n;; # Function switch support\n;;\n;; ztype is an atom containing a vector with two elements:\n;;\n;; A keyword:\n;;\n;; :zipper\n;; :structure\n;; :none\n;;\n;; An integer, representing the number of invocations of zprint\n;; running at one time.\n;;\n;; All of this is to manage the zfns without using the binding\n;; function, and it requires ^:dyanmic, which costs performance.\n;;\n\n#?(:clj (def ztype (atom [:none 0])))\n#?(:clj (def ztype-lock (ReentrantLock.)))\n#?(:clj (def zlock-enable (atom true)))\n\n#?(:clj\n (defmacro zlocking\n \"Emulates locking macro, but doesn't use synchronized block\n because that interacts badly with graalvm. Executes exprs\n in an implicit do, while locking x. Will release the lock\n on x in all circumstances. Only does locking if the global\n zlock-enable is true, because graalvm will compile with the\n following code, but will throw an exception since it is\n unable to find the unlock method.\"\n [^ReentrantLock x & body]\n `(let [lockee# ~x]\n (try (if @zlock-enable (. lockee# (lock)))\n ~@body\n (if @zlock-enable (. lockee# (unlock)))\n (catch Exception e#\n (if @zlock-enable (. lockee# (unlock)))\n (throw e#))))))\n#?(:clj\n (defn remove-locking\n \"Removes the locking on the ztype-lock because graalvm doesn't seem\n to be able to figure out how it works and operate correctly.\"\n []\n (reset! zlock-enable false)))\n\n;#?(:clj (def ztype-history (atom [])))\n\n#?(:clj (defn bind-vars\n \"Change the root binding of all of the vars in the binding-map.\"\n [binding-map]\n (doseq [[the-var var-value] binding-map]\n (.bindRoot ^clojure.lang.Var the-var var-value))))\n\n; Note that this is always and only called by do-redef-vars,\n; a macro in macros.cljc\n#?(:clj\n (defn redef-vars\n \"Redefine all of the traversal functions for zippers or structures, \n then call the function of no arguments passed in.\"\n [the-type binding-map body-fn]\n (zlocking\n ztype-lock\n (let [[current-type the-count :as current-ztype] @ztype]\n #_(swap! ztype-history conj [:in the-type current-type the-count])\n (if (= current-type the-type)\n ; We are already using the right functions, indicate\n ; that another zprint is using them.\n (reset! ztype [current-type (inc the-count)])\n ; We are not currently using the right functions, see\n ; if we can change to use them?\n (if (zero? the-count)\n ; Nobody else is using them, so we can change them.\n (do #_(swap! ztype-history conj\n [:change current-type the-type the-count])\n (bind-vars binding-map)\n (reset! ztype [the-type 1]))\n ; Somebody else is using them, we cannot use them\n (throw\n (Exception. (str \"Attempted to run zprint with type: \"\n the-type\n \" when \"\n the-count\n \" invocations were already running with type \"\n current-type\n \" ! \")))))))\n ;\n ; There is a doall below because we must ensure that all of the\n ; calls to any of the redefed vars take place before we reduce the\n ; reference count of the number of users of those redefed vars.\n ; Otherwise the redefed vars could get reset to some other value,\n ; which would then not work well if you then evaluated the lazy\n ; sequence expecting the previous fn mappings to be in place.\n ;\n (try (doall (body-fn))\n (finally\n (zlocking\n ztype-lock\n (let [[current-type the-count] @ztype]\n #_(swap! ztype-history conj\n [:out the-type current-type the-count])\n (if (= current-type the-type)\n ; Note that we never put the original values back, as they\n ; might be fine for the next call, saving us the trouble\n ; of setting them again. We do, of course, decrement the\n ; count.\n (reset! ztype [current-type (dec the-count)])\n (throw (Exception.\n (str \"Internal Error: when attempting to reduce\"\n \" count of invocations using: \" the-type\n \", the type was: \" current-type))))))))))\n","avg_line_length":41.8173913043,"max_line_length":80,"alphanum_fraction":0.5508421709} {"size":19276,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns cmr.umm-spec.umm-to-xml-mappings.iso19115-2\n \"Defines mappings from UMM records into ISO19115-2 XML.\"\n (:require\n [clj-time.format :as f]\n [clojure.string :as str]\n [cmr.common.util :as util]\n [cmr.common.xml.gen :refer :all]\n [cmr.umm-spec.date-util :as date-util]\n [cmr.umm-spec.iso-keywords :as kws]\n [cmr.umm-spec.iso19115-2-util :as iso]\n [cmr.umm-spec.location-keywords :as lk]\n [cmr.umm-spec.umm-to-xml-mappings.iso19115-2.additional-attribute :as aa]\n [cmr.umm-spec.umm-to-xml-mappings.iso19115-2.data-contact :as data-contact]\n [cmr.umm-spec.umm-to-xml-mappings.iso-shared.distributions-related-url :as sdru]\n [cmr.umm-spec.umm-to-xml-mappings.iso19115-2.metadata-association :as ma]\n [cmr.umm-spec.umm-to-xml-mappings.iso19115-2.platform :as platform]\n [cmr.umm-spec.umm-to-xml-mappings.iso19115-2.spatial :as spatial]\n [cmr.umm-spec.umm-to-xml-mappings.iso19115-2.tiling-system :as tiling]\n [cmr.umm-spec.util :as su :refer [char-string]]))\n\n(def iso19115-2-xml-namespaces\n {:xmlns:xs \"http:\/\/www.w3.org\/2001\/XMLSchema\"\n :xmlns:gmx \"http:\/\/www.isotc211.org\/2005\/gmx\"\n :xmlns:gss \"http:\/\/www.isotc211.org\/2005\/gss\"\n :xmlns:gco \"http:\/\/www.isotc211.org\/2005\/gco\"\n :xmlns:xsi \"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n :xmlns:gmd \"http:\/\/www.isotc211.org\/2005\/gmd\"\n :xmlns:gmi \"http:\/\/www.isotc211.org\/2005\/gmi\"\n :xmlns:gml \"http:\/\/www.opengis.net\/gml\/3.2\"\n :xmlns:xlink \"http:\/\/www.w3.org\/1999\/xlink\"\n :xmlns:eos \"http:\/\/earthdata.nasa.gov\/schema\/eos\"\n :xmlns:srv \"http:\/\/www.isotc211.org\/2005\/srv\"\n :xmlns:gts \"http:\/\/www.isotc211.org\/2005\/gts\"\n :xmlns:swe \"http:\/\/schemas.opengis.net\/sweCommon\/2.0\/\"\n :xmlns:gsr \"http:\/\/www.isotc211.org\/2005\/gsr\"})\n\n(def iso-topic-categories\n #{\"farming\"\n \"biota\"\n \"boundaries\"\n \"climatologyMeteorologyAtmosphere\"\n \"economy\"\n \"elevation\"\n \"environment\"\n \"geoscientificInformation\"\n \"health\"\n \"imageryBaseMapsEarthCover\"\n \"intelligenceMilitary\"\n \"inlandWaters\"\n \"location\"\n \"oceans\"\n \"planningCadastre\"\n \"society\"\n \"structure\"\n \"transportation\"\n \"utilitiesCommunication\"})\n\n(defn- generate-data-dates\n \"Returns ISO XML elements for the DataDates of given UMM collection.\"\n [c]\n ;; Use a default value if none present in the UMM record\n (let [dates (or (:DataDates c) [{:Type \"CREATE\" :Date date-util\/default-date-value}])]\n (for [date dates\n :let [type-code (get iso\/iso-date-type-codes (:Type date))\n date-value (or (:Date date) date-util\/default-date-value)]]\n [:gmd:date\n [:gmd:CI_Date\n [:gmd:date\n [:gco:DateTime date-value]]\n [:gmd:dateType\n [:gmd:CI_DateTypeCode {:codeList (str (:ngdc iso\/code-lists) \"#CI_DateTypeCode\")\n :codeListValue type-code} type-code]]]])))\n\n(defn- generate-datestamp\n \"Return the ISO datestamp from metadata dates. Use update date if available, then creation date\n if available, or a default if neither are populated.\"\n [c]\n (when-let [datestamp (or (date-util\/metadata-update-date c)\n (date-util\/metadata-create-date c)\n date-util\/parsed-default-date)]\n [:gmd:dateStamp\n [:gco:DateTime (f\/unparse (f\/formatters :date-time) datestamp)]]))\n\n(defn- generate-metadata-dates\n \"Returns ISO datestamp and XML elements for Metadata Dates of the given UMM collection.\n ParentEntity, rule, and source are required under MD_ExtendedElementInformation, but are just\n populated with empty since they are not needed for the Metadata Dates\"\n [c]\n (for [date (:MetadataDates c)]\n [:gmd:metadataExtensionInfo\n [:gmd:MD_MetadataExtensionInformation\n [:gmd:extendedElementInformation\n [:gmd:MD_ExtendedElementInformation\n [:gmd:name\n [:gco:CharacterString (iso\/get-iso-metadata-type-name (:Type date))]]\n [:gmd:definition\n [:gco:CharacterString (get iso\/iso-metadata-type-definitions (:Type date))]]\n [:gmd:dataType\n [:gmd:MD_DatatypeCode\n {:codeList \"\"\n :codeListValue \"\"} \"Date\"]]\n [:gmd:domainValue\n [:gco:CharacterString (f\/unparse (f\/formatters :date-time) (:Date date))]]\n [:gmd:parentEntity\n [:gco:CharacterString \"\"]]\n [:gmd:rule\n [:gco:CharacterString \"\"]]\n [:gmd:source\n [:gmd:CI_ResponsibleParty\n [:gmd:role\n [:gmd:CI_RoleCode\n {:codeList \"\"\n :codeListValue \"\"} \"Role\"]]]]]]]]))\n\n(defn iso-topic-value->sanitized-iso-topic-category\n \"Ensures an uncontrolled IsoTopicCategory value is on the schema-defined list or substitues a\n default value.\"\n [category-value]\n (get iso-topic-categories category-value \"location\"))\n\n(def attribute-data-type-code-list\n \"http:\/\/earthdata.nasa.gov\/metadata\/resources\/Codelists.xml#EOS_AdditionalAttributeDataTypeCode\")\n\n(defn- generate-projects-keywords\n \"Returns the content generator instructions for descriptive keywords of the given projects.\"\n [projects]\n (let [project-keywords (map iso\/generate-title projects)]\n (kws\/generate-iso19115-descriptive-keywords \"project\" project-keywords)))\n\n(defn- generate-projects\n [projects]\n (for [proj projects]\n (let [{short-name :ShortName} proj]\n [:gmi:operation\n [:gmi:MI_Operation\n [:gmi:description\n (char-string (iso\/generate-title proj))]\n [:gmi:identifier\n [:gmd:MD_Identifier\n [:gmd:code\n (char-string short-name)]]]\n [:gmi:status \"\"]\n [:gmi:parentOperation {:gco:nilReason \"inapplicable\"}]]])))\n\n(defn- generate-publication-references\n [pub-refs]\n (for [pub-ref pub-refs\n ;; Title and PublicationDate are required fields in ISO\n :when (and (:Title pub-ref) (:PublicationDate pub-ref))]\n [:gmd:aggregationInfo\n [:gmd:MD_AggregateInformation\n [:gmd:aggregateDataSetName\n [:gmd:CI_Citation\n [:gmd:title (char-string (:Title pub-ref))]\n (when (:PublicationDate pub-ref)\n [:gmd:date\n [:gmd:CI_Date\n [:gmd:date\n [:gco:Date (second (re-matches #\"(\\d\\d\\d\\d-\\d\\d-\\d\\d)T.*\" (str (:PublicationDate pub-ref))))]]\n [:gmd:dateType\n [:gmd:CI_DateTypeCode\n {:codeList (str (:iso iso\/code-lists) \"#CI_DateTypeCode\")\n :codeListValue \"publication\"} \"publication\"]]]])\n [:gmd:edition (char-string (:Edition pub-ref))]\n (when (:DOI pub-ref)\n [:gmd:identifier\n [:gmd:MD_Identifier\n [:gmd:code (char-string (get-in pub-ref [:DOI :DOI]))]\n [:gmd:description (char-string \"DOI\")]]])\n [:gmd:citedResponsibleParty\n [:gmd:CI_ResponsibleParty\n [:gmd:organisationName (char-string (:Author pub-ref))]\n [:gmd:role\n [:gmd:CI_RoleCode\n {:codeList (str (:ngdc iso\/code-lists) \"#CI_RoleCode\")\n :codeListValue \"author\"} \"author\"]]]]\n [:gmd:citedResponsibleParty\n [:gmd:CI_ResponsibleParty\n [:gmd:organisationName (char-string (:Publisher pub-ref))]\n [:gmd:role\n [:gmd:CI_RoleCode\n {:codeList (str (:ngdc iso\/code-lists) \"#CI_RoleCode\")\n :codeListValue \"publisher\"} \"publication\"]]]]\n (when-let [online-resource (:OnlineResource pub-ref)]\n [:gmd:citedResponsibleParty\n [:gmd:CI_ResponsibleParty\n [:gmd:contactInfo\n [:gmd:CI_Contact\n [:gmd:onlineResource\n [:gmd:CI_OnlineResource\n [:gmd:linkage\n [:gmd:URL (:Linkage online-resource)]]\n [:gmd:protocol (char-string (:Protocol online-resource))]\n [:gmd:applicationProfile (char-string (:ApplicationProfile online-resource))]\n [:gmd:name (char-string (:Name online-resource))]\n [:gmd:description (char-string (str (:Description online-resource) \" PublicationReference:\"))]\n [:gmd:function\n [:gmd:CI_OnLineFunctionCode\n {:codeList (str (:iso iso\/code-lists) \"#CI_OnLineFunctionCode\")\n :codeListValue \"\"} (:Function online-resource)]]]]]]\n [:gmd:role\n [:gmd:CI_RoleCode\n {:codeList (str (:ngdc iso\/code-lists) \"#CI_RoleCode\")\n :codeListValue \"resourceProvider\"} \"resourceProvider\"]]]])\n [:gmd:series\n [:gmd:CI_Series\n [:gmd:name (char-string (:Series pub-ref))]\n [:gmd:issueIdentification (char-string (:Issue pub-ref))]\n [:gmd:page (char-string (:Pages pub-ref))]]]\n [:gmd:otherCitationDetails (char-string (:OtherReferenceDetails pub-ref))]\n [:gmd:ISBN (char-string (:ISBN pub-ref))]]]\n [:gmd:associationType\n [:gmd:DS_AssociationTypeCode\n {:codeList (str (:ngdc iso\/code-lists) \"#DS_AssociationTypeCode\")\n :codeListValue \"Input Collection\"} \"Input Collection\"]]]]))\n\n(defn extent-description-string\n \"Returns the ISO extent description string (a \\\"key=value,key=value\\\" string) for the given UMM-C\n collection record.\"\n [c]\n (let [vsd (first (-> c :SpatialExtent :VerticalSpatialDomains))\n temporal (first (:TemporalExtents c))\n m {\"VerticalSpatialDomainType\" (:Type vsd)\n \"VerticalSpatialDomainValue\" (:Value vsd)\n \"SpatialCoverageType\" (-> c :SpatialExtent :SpatialCoverageType)\n \"SpatialGranuleSpatialRepresentation\" (-> c :SpatialExtent :GranuleSpatialRepresentation)\n \"Temporal Range Type\" (:TemporalRangeType temporal)}]\n (str\/join \",\" (for [[k v] m\n :when (some? v)]\n (str k \"=\" (str\/replace v #\"[,=]\" \"\"))))))\n\n(defn- generate-user-constraints\n \"Returns the constraints appropriate for the given metadata.\"\n [c]\n (let [description (get-in c [:AccessConstraints :Description])\n value (get-in c [:AccessConstraints :Value])\n use-constraints (:UseConstraints c)]\n [:gmd:resourceConstraints\n (when (or description value use-constraints)\n [:gmd:MD_LegalConstraints\n (when use-constraints\n [:gmd:useLimitation (char-string (:UseConstraints c))])\n (when description\n [:gmd:useLimitation\n [:gco:CharacterString (str \"Restriction Comment: \" description)]])\n (when value\n [:gmd:otherConstraints\n [:gco:CharacterString (str \"Restriction Flag:\" value)]])])]))\n\n\n(defn umm-c-to-iso19115-2-xml\n \"Returns the generated ISO19115-2 xml from UMM collection record c.\"\n [c]\n (let [platforms (platform\/platforms-with-id (:Platforms c))\n {additional-attributes :AdditionalAttributes\n abstract :Abstract\n version-description :VersionDescription} c]\n (xml\n [:gmi:MI_Metadata\n iso19115-2-xml-namespaces\n [:gmd:fileIdentifier (char-string (:EntryTitle c))]\n [:gmd:language (char-string \"eng\")]\n [:gmd:characterSet\n [:gmd:MD_CharacterSetCode {:codeList (str (:ngdc iso\/code-lists) \"#MD_CharacterSetCode\")\n :codeListValue \"utf8\"} \"utf8\"]]\n [:gmd:hierarchyLevel\n [:gmd:MD_ScopeCode {:codeList (str (:ngdc iso\/code-lists) \"#MD_ScopeCode\")\n :codeListValue \"series\"} \"series\"]]\n (if-let [archive-centers (data-contact\/generate-archive-centers (:DataCenters c))]\n archive-centers\n [:gmd:contact {:gco:nilReason \"missing\"}])\n (generate-datestamp c)\n [:gmd:metadataStandardName (char-string \"ISO 19115-2 Geographic Information - Metadata Part 2 Extensions for imagery and gridded data\")]\n [:gmd:metadataStandardVersion (char-string \"ISO 19115-2:2009(E)\")]\n (spatial\/coordinate-system-element c)\n (generate-metadata-dates c)\n [:gmd:identificationInfo\n [:gmd:MD_DataIdentification\n [:gmd:citation\n [:gmd:CI_Citation\n [:gmd:title (char-string (:EntryTitle c))]\n (generate-data-dates c)\n [:gmd:edition (char-string (:Version c))]\n [:gmd:identifier\n [:gmd:MD_Identifier\n [:gmd:code (char-string (:ShortName c))]\n [:gmd:version (char-string (:Version c))]]]\n (when-let [doi (:DOI c)]\n [:gmd:identifier\n [:gmd:MD_Identifier\n (when-let [authority (:Authority doi)]\n [:gmd:authority\n [:gmd:CI_Citation\n [:gmd:title [:gco:CharacterString \"\"]]\n [:gmd:date \"\"]\n [:gmd:citedResponsibleParty\n [:gmd:CI_ResponsibleParty\n [:gmd:organisationName [:gco:CharacterString authority]]\n [:gmd:role\n [:gmd:CI_RoleCode {:codeList \"http:\/\/www.isotc211.org\/2005\/resources\/Codelist\/gmxCodelists.xml#CI_RoleCode\"\n :codeListValue \"\"} \"authority\"]]]]]])\n [:gmd:code [:gco:CharacterString (:DOI doi)]]\n [:gmd:codeSpace [:gco:CharacterString \"gov.nasa.esdis.umm.doi\"]]\n [:gmd:description [:gco:CharacterString \"DOI\"]]]])]]\n [:gmd:abstract (char-string (if (or abstract version-description)\n (str abstract iso\/version-description-separator version-description)\n su\/not-provided))]\n [:gmd:purpose {:gco:nilReason \"missing\"} (char-string (:Purpose c))]\n [:gmd:status\n (when-let [collection-progress (:CollectionProgress c)]\n [:gmd:MD_ProgressCode\n {:codeList (str (:ngdc iso\/code-lists) \"#MD_ProgressCode\")\n :codeListValue (str\/lower-case collection-progress)}\n collection-progress])]\n (data-contact\/generate-data-centers (:DataCenters c))\n (data-contact\/generate-data-center-contact-persons (:DataCenters c))\n (data-contact\/generate-data-center-contact-groups (:DataCenters c))\n (data-contact\/generate-contact-persons (:ContactPersons c))\n (data-contact\/generate-contact-groups (:ContactGroups c))\n (sdru\/generate-browse-urls c)\n (generate-projects-keywords (:Projects c))\n (kws\/generate-iso19115-descriptive-keywords\n \"theme\" (map kws\/science-keyword->iso-keyword-string (:ScienceKeywords c)))\n (kws\/generate-iso19115-descriptive-keywords \"place\"\n (lk\/location-keywords->spatial-keywords\n (:LocationKeywords c)))\n (kws\/generate-iso19115-descriptive-keywords \"temporal\" (:TemporalKeywords c))\n (kws\/generate-iso19115-descriptive-keywords nil (:AncillaryKeywords c))\n (platform\/generate-platform-keywords platforms)\n (platform\/generate-instrument-keywords platforms)\n (generate-user-constraints c)\n (ma\/generate-non-source-metadata-associations c)\n (generate-publication-references (:PublicationReferences c))\n (sdru\/generate-publication-related-urls c)\n [:gmd:language (char-string (or (:DataLanguage c) \"eng\"))]\n (for [topic-category (:ISOTopicCategories c)]\n [:gmd:topicCategory\n [:gmd:MD_TopicCategoryCode (iso-topic-value->sanitized-iso-topic-category topic-category)]])\n [:gmd:extent\n [:gmd:EX_Extent {:id \"boundingExtent\"}\n [:gmd:description\n [:gco:CharacterString (extent-description-string c)]]\n (tiling\/tiling-system-elements c)\n (spatial\/spatial-extent-elements c)\n (spatial\/generate-orbit-parameters c)\n (for [temporal (:TemporalExtents c)\n rdt (:RangeDateTimes temporal)]\n [:gmd:temporalElement\n [:gmd:EX_TemporalExtent\n [:gmd:extent\n [:gml:TimePeriod {:gml:id (su\/generate-id)}\n [:gml:beginPosition (:BeginningDateTime rdt)]\n (if (:EndsAtPresentFlag temporal)\n [:gml:endPosition {:indeterminatePosition \"now\"}]\n [:gml:endPosition (su\/nil-to-empty-string (:EndingDateTime rdt))])]]]])\n (for [temporal (:TemporalExtents c)\n date (:SingleDateTimes temporal)]\n [:gmd:temporalElement\n [:gmd:EX_TemporalExtent\n [:gmd:extent\n [:gml:TimeInstant {:gml:id (su\/generate-id)}\n [:gml:timePosition date]]]]])]]\n [:gmd:processingLevel\n [:gmd:MD_Identifier\n [:gmd:code (char-string (-> c :ProcessingLevel :Id))]\n [:gmd:description (char-string (-> c :ProcessingLevel :ProcessingLevelDescription))]]]]]\n (sdru\/generate-service-related-url (:RelatedUrls c))\n (aa\/generate-content-info-additional-attributes additional-attributes)\n [:gmd:contentInfo\n [:gmd:MD_ImageDescription\n [:gmd:attributeDescription \"\"]\n [:gmd:contentType \"\"]\n [:gmd:processingLevelCode\n [:gmd:MD_Identifier\n [:gmd:code (char-string (-> c :ProcessingLevel :Id))]\n [:gmd:description (char-string (-> c :ProcessingLevel :ProcessingLevelDescription))]]]]]\n (let [related-url-distributions (sdru\/generate-distributions c)\n data-center-distributors (data-contact\/generate-distributors (:DataCenters c))]\n (when (or related-url-distributions data-center-distributors)\n [:gmd:distributionInfo\n [:gmd:MD_Distribution\n related-url-distributions\n data-center-distributors]]))\n [:gmd:dataQualityInfo\n [:gmd:DQ_DataQuality\n [:gmd:scope\n [:gmd:DQ_Scope\n [:gmd:level\n [:gmd:MD_ScopeCode\n {:codeList (str (:ngdc iso\/code-lists) \"#MD_ScopeCode\")\n :codeListValue \"series\"}\n \"series\"]]]]\n [:gmd:report\n [:gmd:DQ_AccuracyOfATimeMeasurement\n [:gmd:measureIdentification\n [:gmd:MD_Identifier\n [:gmd:code\n (char-string \"PrecisionOfSeconds\")]]]\n [:gmd:result\n [:gmd:DQ_QuantitativeResult\n [:gmd:valueUnit \"\"]\n [:gmd:value\n [:gco:Record {:xsi:type \"gco:Real_PropertyType\"}\n [:gco:Real (:PrecisionOfSeconds (first (:TemporalExtents c)))]]]]]]]\n (when-let [quality (:Quality c)]\n [:gmd:report\n [:gmd:DQ_QuantitativeAttributeAccuracy\n [:gmd:evaluationMethodDescription (char-string quality)]\n [:gmd:result {:gco:nilReason \"missing\"}]]])\n [:gmd:lineage\n [:gmd:LI_Lineage\n (aa\/generate-data-quality-info-additional-attributes additional-attributes)\n (when-let [processing-centers (data-contact\/generate-processing-centers (:DataCenters c))]\n [:gmd:processStep\n [:gmd:LI_ProcessStep\n [:gmd:description {:gco:nilReason \"missing\"}]\n processing-centers]])\n (ma\/generate-source-metadata-associations c)]]]]\n [:gmi:acquisitionInformation\n [:gmi:MI_AcquisitionInformation\n (platform\/generate-instruments platforms)\n (generate-projects (:Projects c))\n (platform\/generate-platforms platforms)]]])))\n","avg_line_length":45.4622641509,"max_line_length":143,"alphanum_fraction":0.6089437643} {"size":3096,"ext":"clj","lang":"Clojure","max_stars_count":2.0,"content":";; Copyright (c) Cognitect, Inc.\n;; All rights reserved.\n\n(require '[jsonista.core :as json]\n '[cognitect.aws.client.api :as aws]\n '[cognitect.aws.credentials :as credentials])\n\n(def iam (aws\/client {:api :iam}))\n\n(->> (aws\/invoke iam {:op :ListRoles}) :Roles (map :RoleName))\n\n;; who am I?\n(aws\/invoke iam {:op :GetUser})\n\n(def me (:User *1))\n\n;; make a role to use for this example\n(aws\/invoke iam {:op :CreateRole\n :request {:RoleName \"aws-api-example-role\"\n :AssumeRolePolicyDocument\n (json\/write-value-as-string\n {\"Version\" \"2012-10-17\",\n \"Statement\" [ {\"Effect\" \"Allow\"\n \"Principal\" {\"AWS\" [(:Arn me)]}\n \"Action\" [\"sts:AssumeRole\"]}]})}})\n\n(def new-role (:Role *1))\n\n;; make a policy to use for this example\n(aws\/invoke iam {:op :CreatePolicy\n :request {:PolicyName \"IAMGetMe\"\n :PolicyDocument\n (json\/write-value-as-string\n {\"Version\" \"2012-10-17\",\n \"Statement\" [ {\"Effect\" \"Allow\"\n \"Action\" [\"iam:GetUser\"]\n \"Resource\" [(:Arn me)]}]})}})\n\n(def policy (:Policy *1))\n\n;; attach the new policy to the new role\n(aws\/invoke iam {:op :AttachRolePolicy :request {:RoleName (:RoleName new-role)\n :PolicyArn (:Arn policy)}})\n\n;; make a credentials provider that can assume a role\n(defn assumed-role-credentials-provider [role-arn session-name refresh-every-n-seconds]\n (let [sts (aws\/client {:api :sts})]\n (credentials\/auto-refreshing-credentials\n (reify credentials\/CredentialsProvider\n (fetch [_]\n (when-let [creds (:Credentials\n (aws\/invoke sts\n {:op :AssumeRole\n :request {:RoleArn role-arn\n :RoleSessionName session-name}}))]\n {:aws\/access-key-id (:AccessKeyId creds)\n :aws\/secret-access-key (:SecretAccessKey creds)\n :aws\/session-token (:SessionToken creds)\n ::credentials\/ttl refresh-every-n-seconds}))))))\n\n(def provider (assumed-role-credentials-provider (:Arn new-role) \"example-session\" 600))\n\n;; make a client using the assumed role credentials provider\n(def iam-with-assumed-role (aws\/client {:api :iam :credentials-provider provider}))\n\n;; use it!\n(aws\/invoke iam-with-assumed-role {:op :GetUser :request {:UserName (:UserName me)}})\n\n;; clean up\n(credentials\/stop provider)\n(aws\/invoke iam {:op :DetachRolePolicy :request {:RoleName (:RoleName new-role) :PolicyArn (:Arn policy)}})\n(aws\/invoke iam {:op :DeletePolicy :request {:PolicyArn (:Arn policy)}})\n(aws\/invoke iam {:op :DeleteRole :request {:RoleName \"aws-api-example-role\"}})\n","avg_line_length":41.8378378378,"max_line_length":107,"alphanum_fraction":0.5313307494} {"size":711,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns cljfx.fx.radio-menu-item\n \"Part of a public API\"\n (:require [cljfx.composite :as composite]\n [cljfx.lifecycle :as lifecycle]\n [cljfx.fx.menu-item :as fx.menu-item]\n [cljfx.coerce :as coerce])\n (:import [javafx.scene.control RadioMenuItem]))\n\n(set! *warn-on-reflection* true)\n\n(def props\n (merge\n fx.menu-item\/props\n (composite\/props RadioMenuItem\n ;; overrides\n :style-class [:list lifecycle\/scalar :coerce coerce\/style-class\n :default [\"radio-menu-item\" \"menu-item\"]]\n ;; definitions\n :selected [:setter lifecycle\/scalar :default false])))\n\n(def lifecycle\n (composite\/describe RadioMenuItem\n :ctor []\n :props props))\n","avg_line_length":28.44,"max_line_length":69,"alphanum_fraction":0.6357243319} {"size":7440,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns flow.command.initialise-authorisation-attempt-test\n (:require [flow.core :refer :all]\n [flow.entity.authorisation :as authorisation]\n [flow.entity.user :as user]\n [flow.domain.user-management :as user-management]\n [flow.helpers :as h]\n [clojure.test :refer :all]))\n\n\n(defn setup\n []\n (h\/create-test-user! \"success+2@simulator.amazonses.com\")\n (h\/delete-test-user! \"success+2@simulator.amazonses.com\")\n (h\/create-test-user! \"success+3@simulator.amazonses.com\")\n (h\/create-test-user! \"success+4@simulator.amazonses.com\")\n (h\/create-test-user! \"success+5@simulator.amazonses.com\")\n (h\/create-test-user! \"success+6@simulator.amazonses.com\"))\n\n(defn fixture [test]\n (h\/ensure-empty-table)\n (setup)\n (test)\n (h\/ensure-empty-table))\n\n(use-fixtures :each fixture)\n\n\n(deftest test-initialise-authorisation-attempt\n\n (testing \"The handler negotiates the initialise-authorisation-attempt command when the\n command is being made for a non-existent user.\"\n (let [request (h\/request\n {:session :unauthorised\n :command {:initialise-authorisation-attempt\n {:user\/email-address \"success+1@simulator.amazonses.com\"}}})\n user-id (user\/id \"success+1@simulator.amazonses.com\")\n user (user\/fetch user-id)\n authorisations (h\/find-test-authorisations user-id)\n {:keys [status headers body] :as response} (handler request)\n user' (user\/fetch user-id)\n authorisations' (h\/find-test-authorisations user-id)]\n (is (= 200 status))\n (is (= {:users {}\n :authorisations {}\n :metadata {}\n :session {:current-user-id nil}}\n (h\/decode :transit body)))\n (is (= nil user user'))\n (is (empty? authorisations))\n (is (empty? authorisations'))))\n\n (testing \"The handler negotiates the initialise-authorisation-attempt command when the\n command is being made for an existing user who has prevously been deleted.\"\n (let [request (h\/request\n {:session :unauthorised\n :command {:initialise-authorisation-attempt\n {:user\/email-address \"success+2@simulator.amazonses.com\"}}})\n user-id (user\/id \"success+2@simulator.amazonses.com\")\n user (user\/fetch user-id)\n authorisations (h\/find-test-authorisations user-id)\n {:keys [status headers body] :as response} (handler request)\n user' (user\/fetch user-id)\n authorisations' (h\/find-test-authorisations user-id)]\n (is (= 200 status))\n (is (= {:users {}\n :authorisations {}\n :metadata {}\n :session {:current-user-id nil}}\n (h\/decode :transit body)))\n (is (= user user'))\n (is (empty? authorisations))\n (is (empty? authorisations'))))\n\n (testing \"The handler negotiates the initialise-authorisation-attempt command when the command\n is being made for an existing user and no session is provided.\"\n (let [request (h\/request\n {:command {:initialise-authorisation-attempt\n {:user\/email-address \"success+3@simulator.amazonses.com\"}}})\n user-id (user\/id \"success+3@simulator.amazonses.com\")\n user (user\/fetch user-id)\n authorisations (h\/find-test-authorisations user-id)\n {:keys [status headers body] :as response} (handler request)\n user' (user\/fetch user-id)\n authorisations' (h\/find-test-authorisations user-id)]\n (is (= 200 status))\n (is (= {:users {}\n :authorisations {}\n :metadata {}\n :session {:current-user-id nil}}\n (h\/decode :transit body)))\n (is (= user user'))\n (is (= 0 (count authorisations)))\n (is (= 1 (count authorisations')))))\n\n (testing \"The handler negotiates the initialise-authorisation-attempt command when the command\n is being made for an existing user and an unauthorised session is provided.\"\n (let [request (h\/request\n {:session :unauthorised\n :command {:initialise-authorisation-attempt\n {:user\/email-address \"success+4@simulator.amazonses.com\"}}})\n user-id (user\/id \"success+4@simulator.amazonses.com\")\n user (user\/fetch user-id)\n authorisations (h\/find-test-authorisations user-id)\n {:keys [status headers body] :as response} (handler request)\n user' (user\/fetch user-id)\n authorisations' (h\/find-test-authorisations user-id)]\n (is (= 200 status))\n (is (= {:users {}\n :authorisations {}\n :metadata {}\n :session {:current-user-id nil}}\n (h\/decode :transit body)))\n (is (= user user'))\n (is (= 0 (count authorisations)))\n (is (= 1 (count authorisations')))))\n\n (testing \"The handler negotiates the initialise-authorisation-attempt command when the command\n is being made for an existing user and an authorised session is provided, where the\n authorised user happens to be the same user upon whom the authorisation attempt is\n being initialised.\"\n (let [request (h\/request\n {:session \"success+5@simulator.amazonses.com\"\n :command {:initialise-authorisation-attempt\n {:user\/email-address \"success+5@simulator.amazonses.com\"}}})\n user-id (user\/id \"success+5@simulator.amazonses.com\")\n user (user\/fetch user-id)\n authorisations (h\/find-test-authorisations user-id)\n {:keys [status headers body] :as response} (handler request)\n user' (user\/fetch user-id)\n authorisations' (h\/find-test-authorisations user-id)]\n (is (= 200 status))\n (is (= {:users {}\n :authorisations {}\n :metadata {}\n :session {:current-user-id user-id}}\n (h\/decode :transit body)))\n (is (= user user'))\n (is (= 0 (count authorisations)))\n (is (= 1 (count authorisations')))))\n\n (testing \"The handler negotiates the initialise-authorisation-attempt command when the command\n is being made for an existing user and an authorised session is provided, where the\n authorised user is distinct from the user upon whom the authorisation attempt is\n being initialised.\"\n (let [request (h\/request\n {:session \"success+5@simulator.amazonses.com\"\n :command {:initialise-authorisation-attempt\n {:user\/email-address \"success+6@simulator.amazonses.com\"}}})\n user-id (user\/id \"success+6@simulator.amazonses.com\")\n user (user\/fetch user-id)\n authorisations (h\/find-test-authorisations user-id)\n {:keys [status headers body] :as response} (handler request)\n user' (user\/fetch user-id)\n authorisations' (h\/find-test-authorisations user-id)]\n (is (= 200 status))\n (is (= {:users {}\n :authorisations {}\n :metadata {}\n :session {:current-user-id (user\/id \"success+5@simulator.amazonses.com\")}}\n (h\/decode :transit body)))\n (is (= user user'))\n (is (= 0 (count authorisations)))\n (is (= 1 (count authorisations'))))) )\n","avg_line_length":45.3658536585,"max_line_length":96,"alphanum_fraction":0.5934139785} {"size":2316,"ext":"clj","lang":"Clojure","max_stars_count":1.0,"content":"(defproject com.caioaao\/clj-liftbridge \"0.1.0-alpha2-SNAPSHOT\"\n :description \"liftbridge client library\"\n :url \"https:\/\/github.com\/caioaao\/clj-liftbridge\"\n :scm \"https:\/\/github.com\/caioaao\/clj-liftbridge\"\n :min-lein-version \"2.0.0\"\n :manifest {\"GIT_COMMIT\" ~(System\/getenv \"GIT_COMMIT\")\n \"BUILD_NUMBER\" ~(System\/getenv \"BUILD_NUMBER\")}\n :license {:name \"Apache License Version 2.0\"\n :url \"http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\"}\n :source-paths [\"src\/main\/clojure\"]\n :java-source-paths [\"src\/main\/java\"\n \"src\/gen\/java\"]\n :resource-paths [\"resources\/main\"]\n :dependencies [[org.clojure\/clojure \"1.10.0\"]\n [org.clojure\/core.async \"0.6.532\"]\n [com.google.protobuf\/protobuf-java \"3.11.0\"]\n [io.grpc\/grpc-protobuf \"1.26.0\"]\n [io.grpc\/grpc-stub \"1.26.0\"]]\n :profiles {:dev {:source-paths [\"src\/main\/clojure\" \"src\/dev\/clojure\"]\n :test-paths [\"src\/test\/clojure\"]\n :resource-paths [\"resources\/dev\"]\n :repl-options {:init-ns user}\n :dependencies [[hashp \"0.1.0\"]\n [orchestra \"2018.12.06-2\"]\n [org.clojure\/tools.namespace \"0.3.1\"]\n [less-awful-ssl \"1.0.4\"]\n [io.grpc\/grpc-netty \"1.26.0\"]\n [nubank\/matcher-combinators \"1.2.7\" ]\n [nubank\/state-flow \"2.0.5\"]]\n :plugins [[lein-cljfmt \"0.6.1\"]]}\n :kaocha {:dependencies [[lambdaisland\/kaocha \"0.0-565\"]]}}\n :release-tasks [[\"deploy\" \"clojars\"]\n #_[\"change\" \"version\"\n \"leiningen.release\/bump-version\" \"alpha\"]\n #_[\"vcs\" \"commit\"]\n #_[\"vcs\" \"push\"]]\n :deploy-repositories [[\"clojars\" {:url \"https:\/\/clojars.org\/repo\"\n :sign-releases false\n :username :env\/clojars_username\n :password :env\/clojars_password}]]\n\n :aliases {\"kaocha\" [\"with-profile\" \"+dev,+kaocha\" \"run\" \"-m\" \"kaocha.runner\"]})\n","avg_line_length":53.8604651163,"max_line_length":81,"alphanum_fraction":0.4831606218} {"size":295,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns voxxed-2017-clojure.env\n (:require [clojure.tools.logging :as log]))\n\n(def defaults\n {:init\n (fn []\n (log\/info \"\\n-=[voxxed-2017-clojure started successfully]=-\"))\n :stop\n (fn []\n (log\/info \"\\n-=[voxxed-2017-clojure has shut down successfully]=-\"))\n :middleware identity})\n","avg_line_length":24.5833333333,"max_line_length":73,"alphanum_fraction":0.6305084746} {"size":3095,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns day12\n (:require [clojure.string :as s]))\n\n(def example-input (slurp \"day12input_eg.txt\"))\n\n(defn edge-lookup [input]\n (reduce (fn [lookup edge]\n (if (lookup (first edge))\n (update lookup (first edge) conj (second edge))\n (assoc lookup (first edge) [(second edge)])))\n {}\n (mapcat (fn [line]\n [(s\/split line #\"-\")\n (reverse (s\/split line #\"-\"))])\n (s\/split input #\"\\n\"))))\n\n(defn extend-path [lookup path]\n (if (= \"end\" (last path))\n [path]\n (map (fn [new-step]\n (conj path new-step))\n (lookup (last path)))))\n\n(defn extend-paths [lookup paths]\n (mapcat (partial extend-path lookup) paths))\n\n(defn is-lower? [x]\n (= (s\/lower-case x) x))\n\n(comment\n (is-lower? \"A\"))\n\n(defn repeated-small-cave [path]\n (->> path\n frequencies\n (filter #(and (> (val %) 1)\n (is-lower? (key %))))\n count\n pos?))\n\n(comment\n (repeated-small-cave [\"a\" \"B\" \"aa\"]))\n\n(defn remove-invalid-paths [paths]\n (->> paths\n (remove repeated-small-cave)\n distinct))\n\n(defn all-ended? [paths]\n (= 0 (->> paths\n (filter #(not= \"end\" (last %)))\n count)))\n\n(comment\n (remove-invalid-paths [[\"a\" \"a\"] [\"a\" \"b\"] [\"a\" \"B\" \"B\"] [\"a\" \"B\" \"B\"]])\n (all-ended? [[\"a\" \"end\"] [\"B\" \"end\"]])\n (all-ended? [[\"a\" \"end\"] [\"B\" \"a\"]]))\n\n(defn part1 [input]\n (count\n (let [lookup (edge-lookup input)]\n (loop [paths [[\"start\"]]]\n (if (all-ended? paths)\n paths\n (recur (->> paths\n (extend-paths lookup)\n remove-invalid-paths)))))))\n\n(comment\n (part1 example-input)\n (part1 (slurp \"day12input_eg2.txt\"))\n (part1 (slurp \"day12input_eg3.txt\"))\n (part1 (slurp \"day12input.txt\")))\n\n;;part 2\n\n(defn repeated-small-cave2 [path]\n (or\n (->> path\n frequencies\n (filter #(and (> (val %) 1)\n (is-lower? (key %))))\n count\n (#(> % 1)))\n (->> path\n frequencies\n (filter #(and (> (val %) 2)\n (is-lower? (key %))))\n count\n pos?)))\n\n(comment\n (repeated-small-cave2 [\"a\" \"B\" \"aa\" \"a\" \"a\"])\n (repeated-small-cave2 [\"a\" \"B\" \"aa\" \"a\" \"b\"])\n (repeated-small-cave2 [\"a\" \"B\" \"aa\" \"a\" \"aa\"]))\n\n(defn repeated-cave [path cave]\n (->> path\n (filter #(= % cave))\n count\n (#(> % 1))))\n\n(defn repeated-start-end [path]\n (or (repeated-cave path \"start\")\n (repeated-cave path \"end\")))\n\n(defn remove-invalid-paths2 [paths]\n (->> paths\n (remove repeated-small-cave2)\n (remove repeated-start-end)\n distinct))\n\n(defn part2 [input]\n (count\n (let [lookup (edge-lookup input)]\n (loop [paths [[\"start\"]]]\n (if (all-ended? paths)\n paths\n (recur (->> paths\n (extend-paths lookup)\n remove-invalid-paths2)))))))\n\n(comment\n (part2 example-input)\n (part2 (slurp \"day12input_eg2.txt\"))\n (part2 (slurp \"day12input_eg3.txt\"))\n (part2 (slurp \"day12input.txt\")))\n\n","avg_line_length":23.992248062,"max_line_length":74,"alphanum_fraction":0.4959612278} {"size":3838,"ext":"clj","lang":"Clojure","max_stars_count":8.0,"content":"(ns clj-record.associations-test\n (:require\n [clj-record.test-model.manufacturer :as manufacturer]\n [clj-record.test-model.product :as product]\n [clj-record.test-model.person :as person]\n [clj-record.test-model.thing-one :as thing-one])\n (:use clojure.test\n clj-record.test-helper))\n\n\n(defdbtest belongs-to-creates-find-function\n (let [humedai (manufacturer\/create (valid-manufacturer-with {:name \"Humedai Automotive\"}))\n s3000xi (product\/create {:name \"S-3000xi\" :manufacturer_id (:id humedai)})]\n (is (= humedai (product\/find-manufacturer s3000xi)))))\n\n(defdbtest has-many-creates-a-find-function\n (let [humedai (manufacturer\/create (valid-manufacturer-with {:name \"Humedai Automotive\"}))\n s3000xi (product\/create {:name \"S-3000xi\" :manufacturer_id (:id humedai)})\n s3000xl (product\/create {:name \"S-3000xl\" :manufacturer_id (:id humedai)})]\n (is (= [s3000xi s3000xl] (manufacturer\/find-products humedai)))))\n\n(defdbtest has-many-creates-a-destroy-function\n (let [humedai (manufacturer\/create (valid-manufacturer-with {:name \"Humedai Automotive\"}))\n s3000xi (product\/create {:name \"S-3000xi\" :manufacturer_id (:id humedai)})\n s3000xl (product\/create {:name \"S-3000xl\" :manufacturer_id (:id humedai)})]\n (manufacturer\/destroy-products humedai)\n (is (empty? (manufacturer\/find-products humedai)))))\n\n(defdbtest belongs-to-custom-fk-and-model\n (let [mother-rec (person\/create {:name \"mom\"})\n father-rec (person\/create {:name \"dad\"})\n kid-rec (person\/create {:name \"kid\" :mother_id (:id mother-rec) :father_person_id (:id father-rec)})]\n (is (= mother-rec (person\/find-mother kid-rec)))\n (is (= father-rec (person\/find-father kid-rec)))))\n\n(defdbtest has-many-custom-fk-and-model\n (let [person-rec (person\/create {:name \"phred\"})\n thing-rec1 (thing-one\/create {:name \"one\" :owner_person_id (:id person-rec)})\n thing-rec2 (thing-one\/create {:name \"two\" :owner_person_id (:id person-rec)})]\n (is (= [thing-rec1 thing-rec2] (person\/find-things person-rec)))))\n\n(comment\n(defdbtest find-records-can-do-eager-fetching-of-has-many-association\n (let [manu1 (manufacturer\/create (valid-manufacturer-with {:name \"manu1\" :grade 99}))\n prod1 (product\/create {:name \"prod1\" :manufacturer_id (:id manu1)})\n prod2 (product\/create {:name \"prod2\" :manufacturer_id (:id manu1)})\n manu2 (manufacturer\/create (valid-manufacturer-with {:name \"manu2\" :grade 99}))\n prod3 (product\/create {:name \"prod3\" :manufacturer_id (:id manu2)})\n prod4 (product\/create {:name \"prod4\" :manufacturer_id (:id manu2)})]\n (let [[eager-manu1 eager-manu2] (manufacturer\/find-records {:grade 99} {:include [:products]})]\n (is (= \"manu1\" (:name eager-manu1)))\n (is (= \"manu2\" (:name eager-manu2)))\n (is (= [prod1 prod2] (:products eager-manu1)))\n (is (= [prod3 prod4] (:products eager-manu2))))))\n)\n\n\n;This is very primitive implementation of eager fetch\n(defdbtest find-records-can-do-eager-fetching-of-has-many-association\n (let [manu1 (manufacturer\/create (valid-manufacturer-with {:name \"manu1\" :grade 99}))\n prod1 (product\/create {:name \"prod1\" :manufacturer_id (:id manu1)})\n prod2 (product\/create {:name \"prod2\" :manufacturer_id (:id manu1)})\n manu2 (manufacturer\/create (valid-manufacturer-with {:name \"manu2\" :grade 99}))\n prod3 (product\/create {:name \"prod3\" :manufacturer_id (:id manu2)})\n prod4 (product\/create {:name \"prod4\" :manufacturer_id (:id manu2)})]\n (let [[eager-manu1 eager-manu2] (manufacturer\/eager-fetch-products (manufacturer\/find-records {:grade 99}))]\n (is (= \"manu1\" (:name eager-manu1)))\n (is (= \"manu2\" (:name eager-manu2)))\n (is (= [prod1 prod2] (:products eager-manu1)))\n (is (= [prod3 prod4] (:products eager-manu2))))))\n","avg_line_length":54.0563380282,"max_line_length":112,"alphanum_fraction":0.672746222} {"size":5480,"ext":"clj","lang":"Clojure","max_stars_count":29.0,"content":"(ns acceptance.util\n (:require [push.core :as push]\n [push.type.definitions.interval :as iv]\n [push.type.definitions.complex :as complex]\n [push.type.definitions.quoted :as qc])\n (:use [midje.sweet])\n )\n\n\n;; literal generators\n\n(defn some-boolean\n []\n (rand-nth [true false]))\n\n\n(defn some-long\n \"returns a random long selected from [-max\/2,max\/2]\"\n [i]\n (-' (rand-int i) (\/ i 2)))\n\n\n(defn some-double\n \"returns a random double selected from [-max\/2,max\/2]\"\n [i]\n (-' (rand i) (\/ i 2)))\n\n\n(defn some-rational\n \"returns a random rational composed of numerator `some-long` and a positive random integer in [1,range]\"\n [i]\n (\/ (some-long i) (inc (rand-int i))))\n\n\n(defn some-bigint\n \"returns a random BigInt based on `(some-long range)`\"\n [i]\n (bigint (some-long i)))\n\n\n(defn some-bigdec\n \"returns a random BigDecimal based on `(some-double range)`\"\n [i]\n (bigdec (some-double i)))\n\n\n(defn some-ascii\n \"returns a random character in the range [33,125]\"\n []\n (char (+ 33 (rand-int (- 126 33)))))\n\n\n(defn some-string\n \"returns a random string of length i, by assembling characters picked with `(some-ascii)`\"\n [i]\n (clojure.string\/join\n (take i\n (repeatedly #(char (+ 33 (rand-int (- 126 33))))))))\n\n\n(defn vector-of-stuff\n \"constructs a vector of a given length by calling a function with the given argument repeatedly; for example, `(vector-of-stuff some-long 3 10)` will produce a 10-element vector of numbers from the range [-1,1]\"\n [f i j]\n (into [] (take j (repeatedly #(f i)))))\n\n\n(defn some-instruction\n \"given an interpreter instance, it randomly selects one if the defined instructions from its keys\"\n [interpreter]\n (rand-nth (push\/known-instructions interpreter)))\n\n\n(defn some-interval\n \"given a range, produces an Interval record using `(some-long)` and `(some-double)` for the range\"\n [i]\n (iv\/make-interval (some-long i) (some-double i)))\n\n\n(def all-the-variable-names\n (map keyword\n (map str (map char (range 97 123)))))\n\n(defn some-ref\n \"given an interpreter instance, it randomly selects one if the defined bindings, plus one from an additional collection of keywords\"\n [interpreter extra-bindings]\n (rand-nth\n (concat\n (keys (:bindings interpreter))\n all-the-variable-names)))\n\n\n\n;; code generation\n\n(declare some-codeblock)\n\n(defn some-item\n [scale erc-prob interpreter]\n (if (< (rand) erc-prob)\n (rand-nth [\n (some-boolean)\n (some-long scale)\n (some-long (* 10 scale))\n (some-long (* 1000 scale))\n (some-double scale)\n (some-double (* 10 scale))\n (some-double (* 1000 scale))\n (some-rational (* 100 scale))\n (some-bigint (* 10000 scale))\n (some-bigdec (* 10000 scale))\n (complex\/complexify\n (some-long scale) (some-rational scale))\n (some-ascii)\n (some-string scale)\n (some-interval (* 100 scale))\n (vector-of-stuff some-long (* 10 scale) (rand-int scale))\n (vector-of-stuff some-double (* 10 scale) (rand-int scale))\n (some-codeblock (max 1 (dec scale)) erc-prob interpreter)\n (qc\/push-quote (some-codeblock (max 1 (dec scale)) erc-prob interpreter))\n ])\n (if (< erc-prob (rand))\n (some-instruction interpreter)\n (some-ref interpreter all-the-variable-names)\n )))\n\n\n(defn some-codeblock\n [scale erc-prob interpreter]\n (repeatedly\n (max 1 (rand-int scale))\n #(some-item (max 1 (rand-int scale)) erc-prob interpreter)\n ))\n\n\n(defn some-program\n [prog-size scale erc-prob interpreter]\n (into []\n (take\n prog-size\n (repeatedly #(some-item scale erc-prob interpreter))\n )))\n\n\n(defn some-bindings\n [how-many scale erc-prob interpreter]\n (zipmap\n (take how-many all-the-variable-names)\n (repeatedly #(list (some-item scale erc-prob interpreter)))\n ))\n\n\n(defn preloaded-stacks\n [how-many scale erc-prob interpreter]\n {\n :boolean (repeatedly how-many some-boolean)\n :booleans (repeatedly how-many\n #(into []\n (repeatedly (rand-int how-many) some-boolean)))\n :char (repeatedly how-many some-ascii)\n :chars (repeatedly how-many\n #(into []\n (repeatedly (rand-int how-many) some-ascii)))\n :code (repeatedly how-many\n #(some-codeblock (max 1 (dec how-many)) erc-prob interpreter))\n :complex (repeatedly how-many\n #(complex\/complexify (some-long scale) (some-rational scale)))\n :complexes (repeatedly how-many\n (fn []\n (into [] (repeatedly (inc (rand-int how-many))\n #(complex\/complexify (some-rational scale)\n (some-double scale))))))\n :ref (repeatedly how-many\n #(some-ref interpreter all-the-variable-names))\n ; ; :refs '()\n :scalar (repeatedly how-many #(some-long (* 10 scale)))\n :scalars (repeatedly how-many\n (fn [] (into [] (repeatedly (rand-int how-many)\n #(some-long (* 10 scale))))))\n ; :set '()\n :string (repeatedly how-many #(some-string scale))\n :strings (repeatedly how-many\n (fn [] (into [] (repeatedly (rand-int how-many) #(some-string scale)))))\n :vector (repeatedly how-many\n (fn []\n (into []\n (repeatedly 3\n #(some-codeblock 2 erc-prob interpreter)))))\n }\n )\n\n;\n; (println (str (preloaded-stacks (push\/interpreter :bindings {:x 9 :y 99}) 20 10 4\/5)))\n","avg_line_length":28.3937823834,"max_line_length":213,"alphanum_fraction":0.6111313869} {"size":6223,"ext":"clj","lang":"Clojure","max_stars_count":62.0,"content":"(ns dl4clj.datasets.api.iterators\n (:import [org.deeplearning4j.datasets.datavec\n RecordReaderDataSetIterator\n SequenceRecordReaderDataSetIterator]\n [org.nd4j.linalg.dataset.api.iterator DataSetIterator])\n (:require [clojure.core.match :refer [match]]\n [dl4clj.utils :refer [obj-or-code? eval-if-code]]))\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;; getters\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defn current-batch\n \"return index of the current batch\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.batch ~iter))\n :else\n (.batch iter)))\n\n(defn get-batch-size\n \"return the batch size\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.batch ~iter))\n :else\n (.batch iter)))\n\n(defn get-current-cursor\n \"The current cursor if applicable\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.cursor ~iter))\n :else\n (.cursor iter)))\n\n(defn get-pre-processor\n \"Returns preprocessors, if defined\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.getPreProcessor ~iter))\n :else\n (.getPreProcessor iter)))\n\n(defn get-input-columns\n \"Input columns for the dataset\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.inputColumns ~iter))\n :else\n (.inputColumns iter)))\n\n(defn next-n-examples!\n \"Like the standard next method but allows a customizable number of examples returned\"\n [& {:keys [iter n as-code?]\n :or {as-code? true}\n :as opts}]\n (match [opts]\n [{:iter (_ :guard seq?)\n :n (:or (_ :guard number?)\n (_ :guard seq?))}]\n (obj-or-code? as-code? `(.next ~iter ~n))\n [{:iter _\n :n _}]\n (let [[iter-obj some-n] (eval-if-code [iter seq?]\n [n seq? number?])]\n (.next iter-obj some-n))))\n\n(defn next-example!\n \"returns the next example in an iterator\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.next ~iter))\n :else\n (.next iter)))\n\n(defn get-num-examples\n \"Total number of examples in the dataset\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.numExamples ~iter))\n :else\n (.numExamples iter)))\n\n(defn get-total-examples\n \"Total examples in the iterator\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.totalExamples ~iter))\n :else\n (.totalExamples iter)))\n\n(defn get-total-outcomes\n \"The number of labels for the dataset\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.totalOutcomes ~iter))\n :else\n (.totalOutcomes iter)))\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;; misc\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defn load-from-meta-data\n [& {:keys [iter meta-data as-code?]\n :or {as-code? true}\n :as opts}]\n (match [opts]\n [{:iter (_ :guard seq?)\n :meta-data (_ :guard seq?)}]\n (obj-or-code? as-code? `(.loadFromMetaData ~iter ~meta-data))\n :else\n (let [[iter-obj md-obj] (eval-if-code [iter seq?]\n [meta-data seq?])]\n (.loadFromMetaData iter-obj md-obj))))\n\n(defn remove-data!\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(doto ~iter .remove))\n :else\n (doto iter .remove)))\n\n(defn async-supported?\n \"Does this DataSetIterator support asynchronous prefetching of multiple DataSet objects?\n Most DataSetIterators do, but in some cases it may not make sense to wrap\n this iterator in an iterator that does asynchronous prefetching.\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.asyncSupported ~iter))\n :else\n (.asyncSupported iter)))\n\n(defn reset-supported?\n \"Is resetting supported by this DataSetIterator?\n Many DataSetIterators do support resetting, but some don't\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.resetSupported ~iter))\n :else\n (.resetSupported iter)))\n\n(defn reset-iter!\n \"Resets the iterator back to the beginning\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(doto ~iter .reset))\n :else\n (doto iter .reset)))\n\n(defn has-next?\n \"checks to see if there is anymore data in the iterator\"\n [iter & {:keys [as-code?]\n :or {as-code? true}}]\n (match [iter]\n [(_ :guard seq?)]\n (obj-or-code? as-code? `(.hasNext ~iter))\n :else\n (.hasNext iter)))\n\n(defn set-pre-processor!\n \"Set a pre processor\"\n [& {:keys [iter pre-processor as-code?]\n :or {as-code? true}\n :as opts}]\n (match [opts]\n [{:iter (_ :guard seq?)\n :pre-processor (_ :guard seq?)}]\n (obj-or-code? as-code? `(doto ~iter (.setPreProcessor ~pre-processor)))\n :else\n (let [[iter-obj pp-obj] (eval-if-code [iter seq?] [pre-processor seq?])]\n (doto (if (has-next? iter-obj)\n iter-obj\n (reset-iter! iter-obj))\n (.setPreProcessor pp-obj)))))\n","avg_line_length":30.6551724138,"max_line_length":90,"alphanum_fraction":0.5028121485} {"size":27153,"ext":"clj","lang":"Clojure","max_stars_count":1.0,"content":"{\"ClusterName\" \"5d5892d3-1f74-4ccf-91af-548dfc9767aa\",\n \"OrgID\" 11789772,\n \"Version\" 1,\n \"Report\"\n {\"fingerprints\" [],\n \"info\" [],\n \"pass\" [],\n \"reports\"\n [{\"component\" \"ccx_rules_ocp.ocs.operator_phase_check.report\",\n \"details\" {\"error_key\" \"ERROR_KEY\", \"type\" \"rule\"},\n \"key\" \"ERROR_KEY\",\n \"links\" {},\n \"rule_id\" \"foo_check|ERROR_KEY\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\" \"ccx_rules_ocp.ocs.pvc_phase_check.report\",\n \"details\" {\"error_key\" \"ERROR_KEY\", \"type\" \"rule\"},\n \"key\" \"ERROR_KEY\",\n \"links\" {},\n \"rule_id\" \"foo_check|ERROR_KEY\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\" \"ccx_rules_ocp.ocs.ceph_check_mon_clock_skew.report\",\n \"details\" {\"error_key\" \"ERROR_KEY\", \"type\" \"rule\"},\n \"key\" \"ERROR_KEY\",\n \"links\" {},\n \"rule_id\" \"foo_check|ERROR_KEY\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\" \"ccx_rules_ocp.ocs.check_pods_scc.report\",\n \"details\" {\"error_key\" \"ERROR_KEY\", \"type\" \"rule\"},\n \"key\" \"ERROR_KEY\",\n \"links\" {},\n \"rule_id\" \"foo_check|ERROR_KEY\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\" \"ccx_rules_ocp.ocs.check_ocs_version.report\",\n \"details\" {\"error_key\" \"ERROR_KEY\", \"type\" \"rule\"},\n \"key\" \"ERROR_KEY\",\n \"links\" {},\n \"rule_id\" \"foo_check|ERROR_KEY\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\"\n \"ccx_rules_ocp.external.rules.nodes_requirements_check.report\",\n \"details\"\n {\"error_key\" \"NODES_MINIMUM_REQUIREMENTS_NOT_MET\",\n \"link\"\n \"https:\/\/docs.openshift.com\/container-platform\/4.1\/installing\/installing_bare_metal\/installing-bare-metal.html#minimum-resource-requirements_installing-bare-metal\",\n \"nodes\"\n [{\"memory\" 8.16, \"memory_req\" 16, \"name\" \"foo1\", \"role\" \"master\"}],\n \"type\" \"rule\"},\n \"key\" \"NODES_MINIMUM_REQUIREMENTS_NOT_MET\",\n \"links\"\n {\"docs\"\n [\"https:\/\/docs.openshift.com\/container-platform\/4.1\/installing\/installing_bare_metal\/installing-bare-metal.html#minimum-resource-requirements_installing-bare-metal\"]},\n \"rule_id\" \"nodes_requirements_check|NODES_MINIMUM_REQUIREMENTS_NOT_MET\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\" \"ccx_rules_ocp.external.bug_rules.bug_1766907.report\",\n \"details\" {\"error_key\" \"BUGZILLA_BUG_1766907\", \"type\" \"rule\"},\n \"key\" \"BUGZILLA_BUG_1766907\",\n \"links\" {\"bz\" [\"https:\/\/bugzilla.redhat.com\/show_bug.cgi?id=1766907\"],\n \"doc\" [],\n \"kcs\" [\"https:\/\/access.redhat.com\/solutions\/4631541\"]},\n \"rule_id\" \"bug_1766907|BUGZILLA_BUG_1766907\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\"\n \"ccx_rules_ocp.external.rules.nodes_kubelet_version_check.report\",\n \"details\"\n {\"error_key\" \"NODE_KUBELET_VERSION\",\n \"kcs_link\" \"https:\/\/access.redhat.com\/solutions\/4602641\",\n \"nodes_with_different_version\"\n [{\"Kubelet Version\" \"v1.14.6+0a21dd3b3\",\n \"Node\" \"oc1\",\n \"role\" \"worker\"} {\"Kubelet Version\" \"v1.14.6+0a21dd3b3\",\n \"Node\" \"oc2\",\n \"role\" \"worker\"} {\"Kubelet Version\" \"v1.14.6+d39ad8449\",\n \"Node\" \"oc3\",\n \"role\" \"worker\"}],\n \"type\" \"rule\"},\n \"key\" \"NODE_KUBELET_VERSION\",\n \"links\" {\"kcs\" [\"https:\/\/access.redhat.com\/solutions\/4602641\"]},\n \"rule_id\" \"nodes_kubelet_version_check|NODE_KUBELET_VERSION\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\"\n \"ccx_rules_ocp.external.rules.samples_op_failed_image_import_check.report\",\n \"details\"\n {\"error_key\" \"SAMPLES_FAILED_IMAGE_IMPORT_ERR\",\n \"info\"\n {\"condition\" \"Degraded\",\n \"lastTransitionTime\" \"2020-03-19T08:32:53Z\",\n \"message\"\n \"Samples installed at 4.2.0, with image import failures for these imagestreams: php \",\n \"name\" \"openshift-samples\",\n \"reason\" \"FailedImageImports\"},\n \"kcs\" \"https:\/\/access.redhat.com\/solutions\/4563171\",\n \"type\" \"rule\"},\n \"key\" \"SAMPLES_FAILED_IMAGE_IMPORT_ERR\",\n \"links\" {\"kcs\" [\"https:\/\/access.redhat.com\/solutions\/4563171\"]},\n \"rule_id\"\n \"samples_op_failed_image_import_check|SAMPLES_FAILED_IMAGE_IMPORT_ERR\",\n \"tags\" [],\n \"type\" \"rule\"} {\"component\"\n \"ccx_rules_ocp.external.rules.cluster_wide_proxy_auth_check.report\",\n \"details\"\n {\"error_key\" \"AUTH_OPERATOR_PROXY_ERROR\",\n \"kcs\" \"https:\/\/access.redhat.com\/solutions\/4569191\",\n \"op\"\n {\"available\" {\"last_trans_time\" \"2020-03-31T08:39:51Z\",\n \"message\" nil,\n \"reason\" \"NoData\",\n \"status\" nil},\n \"degraded\"\n {\"last_trans_time\" \"2020-03-31T08:42:33Z\",\n \"message\"\n \"WellKnownEndpointDegraded: failed to GET well-known https:\/\/10.237.112.145:6443\/.well-known\/oauth-authorization-server: Tunnel or SSL Forbidden\",\n \"reason\" \"WellKnownEndpointDegradedError\",\n \"status\" true},\n \"name\" \"authentication\",\n \"progressing\" {\"last_trans_time\" \"2020-03-31T08:39:51Z\",\n \"message\" nil,\n \"reason\" \"NoData\",\n \"status\" nil},\n \"upgradeable\" {\"last_trans_time\" \"2020-03-31T08:39:51Z\",\n \"message\" nil,\n \"reason\" \"AsExpected\",\n \"status\" true},\n \"version\" nil},\n \"type\" \"rule\"},\n \"key\" \"AUTH_OPERATOR_PROXY_ERROR\",\n \"links\" {\"kcs\" [\"https:\/\/access.redhat.com\/solutions\/4569191\"]},\n \"rule_id\" \"cluster_wide_proxy_auth_check|AUTH_OPERATOR_PROXY_ERROR\",\n \"tags\" [],\n \"type\" \"rule\"}],\n \"skips\"\n [{\"details\" \"All: ['ccx_ocp_core.specs.must_gather.DeploymentsMG'] Any: \",\n \"reason\" \"MISSING_REQUIREMENTS\",\n \"rule_fqdn\" \"ccx_rules_ocp.external.bug_rules.bug_1801300.report\",\n \"type\" \"skip\"} {\"details\" \"All: ['ccx_ocp_core.specs.must_gather.DeploymentsMG'] Any: \",\n \"reason\" \"MISSING_REQUIREMENTS\",\n \"rule_fqdn\" \"ccx_rules_ocp.external.bug_rules.bug_1802248.report\",\n \"type\" \"skip\"} {\"details\"\n \"All: ['ccx_rules_ocp.common.conditions.image_registry.DegradedImageRegistryOperator', 'ccx_rules_ocp.common.conditions.image_registry.ImageRegistryPod', 'ccx_rules_ocp.common.conditions.image_registry.ImageRegistryPersistentVolumeClaim'] Any: \",\n \"reason\" \"MISSING_REQUIREMENTS\",\n \"rule_fqdn\"\n \"ccx_rules_ocp.external.rules.image_registry_pv_no_access.report\",\n \"type\" \"skip\"} {\"details\"\n \"All: ['ccx_rules_ocp.common.conditions.image_registry.DegradedImageRegistryOperator', 'ccx_rules_ocp.common.conditions.image_registry.ImageRegistryPod', 'ccx_rules_ocp.common.conditions.image_registry.ImageRegistryPersistentVolumeClaim'] Any: \",\n \"reason\" \"MISSING_REQUIREMENTS\",\n \"rule_fqdn\"\n \"ccx_rules_ocp.external.rules.image_registry_pv_low_capacity.report\",\n \"type\" \"skip\"} {\"details\"\n \"All: ['ccx_rules_ocp.common.conditions.image_registry.DegradedImageRegistryOperator', 'ccx_rules_ocp.common.conditions.image_registry.ImageRegistryPod', 'ccx_rules_ocp.common.conditions.image_registry.isImageRegistryPodEmptyDirVolume', 'ccx_rules_ocp.common.conditions.image_registry.isImageRegistryPodPersistentVolume'] Any: \",\n \"reason\" \"MISSING_REQUIREMENTS\",\n \"rule_fqdn\"\n \"ccx_rules_ocp.external.rules.image_registry_no_volume_set_check.report\",\n \"type\" \"skip\"} {\"details\"\n \"All: ['ccx_rules_ocp.common.conditions.image_registry.DegradedImageRegistryOperator', 'ccx_rules_ocp.common.conditions.image_registry.ImageRegistryPod', 'ccx_rules_ocp.common.conditions.image_registry.ImageRegistryPersistentVolumeClaim'] Any: \",\n \"reason\" \"MISSING_REQUIREMENTS\",\n \"rule_fqdn\"\n \"ccx_rules_ocp.external.rules.image_registry_pv_not_bound.report\",\n \"type\" \"skip\"}],\n \"system\" {\"hostname\" nil, \"metadata\" {}}}}\n","avg_line_length":170.7735849057,"max_line_length":433,"alphanum_fraction":0.1855411925} {"size":705,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns advent.2020.test-day8\n (:require [clojure.test :refer :all]\n [advent.2020.day8 :as d]))\n\n(def ^:private example [\"nop +0\"\n \"acc +1\"\n \"jmp +4\"\n \"acc +3\"\n \"jmp -3\"\n \"acc -99\"\n \"acc +1\"\n \"jmp -4\"\n \"acc +6\"])\n\n(deftest puzzle1\n (testing \"Examples\"\n (is (= 5 (d\/puzzle1 example))))\n\n (testing \"Actual input\"\n (is (= 2003 (d\/puzzle1 d\/puzzle-input)))))\n\n(deftest puzzle2\n (testing \"Examples\"\n (is (= 8 (d\/puzzle2 example))))\n\n (testing \"Actual input\"\n (is (= 1984 (d\/puzzle2 d\/puzzle-input)))))\n","avg_line_length":25.1785714286,"max_line_length":46,"alphanum_fraction":0.4241134752} {"size":1689,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns hxgm30.httpd.app.routes.rest.core\n (:require\n [hxgm30.httpd.app.handler.core :as core-handler]\n [taoensso.timbre :as log]))\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;; REST API Routes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defn admin-api\n [httpd-component]\n [[\"\/api\/health\" {\n :get (core-handler\/health httpd-component)\n :options core-handler\/ok}]\n [\"\/api\/ping\" {\n :get {:handler core-handler\/ping\n :roles #{:admin}}\n :post {:handler core-handler\/ping\n :roles #{:admin}}\n :options core-handler\/ok}]])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;; Testing Routes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(def testing\n [[\"\/api\/testing\/401\" {:get (core-handler\/status :unauthorized)}]\n [\"\/api\/testing\/403\" {:get (core-handler\/status :forbidden)}]\n [\"\/api\/testing\/404\" {:get (core-handler\/status :not-found)}]\n [\"\/api\/testing\/405\" {:get (core-handler\/status :method-not-allowed)}]\n [\"\/api\/testing\/500\" {:get (core-handler\/status :internal-server-error)}]\n [\"\/api\/testing\/503\" {:get (core-handler\/status :service-unavailable)}]])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;; Assembled Routes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defn all\n [httpd-component api-version]\n (concat\n (admin-api httpd-component)\n testing))\n","avg_line_length":39.2790697674,"max_line_length":77,"alphanum_fraction":0.4014209591} {"size":1219,"ext":"clj","lang":"Clojure","max_stars_count":2.0,"content":";;\n;; Licensed to the Apache Software Foundation (ASF) under one or more\n;; contributor license agreements. See the NOTICE file distributed with\n;; this work for additional information regarding copyright ownership.\n;; The ASF licenses this file to You under the Apache License, Version 2.0\n;; (the \"License\"); you may not use this file except in compliance with\n;; the License. You may obtain a copy of the License at\n;;\n;; http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n;;\n;; Unless required by applicable law or agreed to in writing, software\n;; distributed under the License is distributed on an \"AS IS\" BASIS,\n;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n;; See the License for the specific language governing permissions and\n;; limitations under the License.\n;;\n\n(ns org.apache.clojure-mxnet.lr-scheduler\n (:import (org.apache.mxnet FactorScheduler)))\n\n\n(defn factor-scheduler\n \"Assume the weight has been updated by n times, then the learning rate will\n be base_lr * factor^^(floor(n\/step))\n - step int, schedule learning rate after n updates\n - factor number, the factor for reducing the learning rate\"\n [step factor]\n (new FactorScheduler (int step) (float factor)))\n","avg_line_length":42.0344827586,"max_line_length":77,"alphanum_fraction":0.7489745693} {"size":597,"ext":"clj","lang":"Clojure","max_stars_count":22.0,"content":"(ns cartus.null-test\n (:require\n [clojure.test :refer :all]\n\n [cartus.test-support.definitions :as defs]\n\n [cartus.null :as cartus-null]))\n\n(deftest logs-to-null-logger-at-level-without-failure\n (doseq [{:keys [without-opts]} defs\/level-defs]\n (let [{:keys [log-fn]} without-opts\n logger (cartus-null\/logger)\n type ::some.event\n context {:some \"context\"}\n\n result (atom nil)]\n (try\n (log-fn logger type context)\n (reset! result :success)\n (catch Throwable t\n (reset! result t)))\n\n (is (= :success @result)))))\n","avg_line_length":24.875,"max_line_length":53,"alphanum_fraction":0.5845896147} {"size":1440,"ext":"cljc","lang":"Clojure","max_stars_count":null,"content":"(ns girouette.tw.interactivity)\n\n(def components\n [{:id :appearance\n :rules \"\n appearance = 'appearance-none'\n \"\n :garden (fn [_]\n {:appearance \"none\"})}\n\n\n {:id :cursor\n :rules \"\n cursor = <'cursor-'> ('auto' | 'default' | 'pointer' | 'wait' |\n 'text' | 'move' | 'not-allowed')\n \"\n :garden (fn [{[type] :component-data}]\n {:cursor type})}\n\n\n {:id :outline\n :rules \"\n outline = <'outline-'> ('none' | 'white' | 'black')\n \"\n :garden (fn [{[type] :component-data}]\n {:outline ({\"none\" \"2px solid transparent\"\n \"white\" \"2px dotted white\"\n \"black\" \"2px dotted black\"} type)\n :outline-offset \"2px\"})}\n\n\n {:id :pointer-events\n :rules \"\n pointer-events = <'pointer-events-'> ('none' | 'auto')\n \"\n :garden (fn [{[type] :component-data}]\n {:pointer-events type})}\n\n\n {:id :resize\n :rules \"\n resize = <'resize'> (<'-'> ('none' | 'x' | 'y'))?\n \"\n :garden (fn [{[type] :component-data}]\n {:resize ({\"none\" \"none\"\n \"x\" \"horizontal\"\n \"y\" \"vertical\"\n nil \"both\"} type)})}\n\n\n {:id :user-select\n :rules \"\n user-select = <'select-'> ('none' | 'text' | 'all' | 'auto')\n \"\n :garden (fn [{[type] :component-data}]\n {:user-select type})}])\n","avg_line_length":25.2631578947,"max_line_length":67,"alphanum_fraction":0.4458333333} {"size":2629,"ext":"clj","lang":"Clojure","max_stars_count":84.0,"content":"(ns alda.lisp.parts-test\n (:require [clojure.test :refer :all]\n [clojure.pprint :refer :all]\n [alda.test-helpers :refer (get-instrument)]\n [alda.lisp :refer :all]\n [alda.parser :refer :all]))\n\n(deftest part-tests\n (score*)\n (testing \"a part:\"\n (part* \"piano\/trumpet 'trumpiano'\")\n (testing \"starts at offset 0\"\n (is (zero? (:offset (:current-offset (get-instrument \"piano\")))))\n (is (zero? (:offset (:current-offset (get-instrument \"trumpet\"))))))\n (testing \"starts at the :start marker\"\n (is (= :start (:current-marker (get-instrument \"piano\"))))\n (is (= :start (:current-marker (get-instrument \"trumpet\")))))\n (testing \"has the instruments that it has\"\n (is (= 2 (count *current-instruments*)))\n (is (some #(re-find #\"^piano-\" %) *current-instruments*))\n (is (some #(re-find #\"^trumpet-\" %) *current-instruments*)))\n (testing \"sets a nickname if applicable\"\n (is (contains? *nicknames* \"trumpiano\"))\n (let [trumpiano (*nicknames* \"trumpiano\")]\n (is (= (count trumpiano) 2))\n (is (some #(re-find #\"^piano-\" %) trumpiano))\n (is (some #(re-find #\"^trumpet-\" %) trumpiano))))\n (note (pitch :d) (duration (note-length 2 {:dots 1})))\n (def piano-offset (-> (get-instrument \"piano\") :current-offset))\n (def trumpet-offset (-> (get-instrument \"trumpet\") :current-offset))\n (testing \"instruments from a group can be separated at will\"\n (part* \"piano\")\n (is (= 1 (count *current-instruments*)))\n (is (re-find #\"^piano-\" (first *current-instruments*)))\n (is (= piano-offset (-> (get-instrument \"piano\") :current-offset)))\n (chord (note (pitch :a))\n (note (pitch :c :sharp))\n (note (pitch :e)))\n (alter-var-root #'piano-offset\n (constantly (-> (get-instrument \"piano\") :current-offset)))\n\n (part* \"trumpet\")\n (is (= 1 (count *current-instruments*)))\n (is (re-find #\"^trumpet-\" (first *current-instruments*)))\n (is (= trumpet-offset (-> (get-instrument \"trumpet\") :current-offset)))\n (note (pitch :d))\n (note (pitch :e))\n (note (pitch :f :sharp))\n (alter-var-root #'trumpet-offset\n (constantly (-> (get-instrument \"trumpet\") :current-offset)))\n (is (= piano-offset (-> (get-instrument \"piano\") :current-offset))))\n (testing \"referencing a nickname\"\n (part* \"trumpiano\")\n (is (= 2 (count *current-instruments*)))\n (is (some #(re-find #\"^piano-\" %) *current-instruments*))\n (is (some #(re-find #\"^trumpet-\" %) *current-instruments*)))))\n\n","avg_line_length":45.3275862069,"max_line_length":83,"alphanum_fraction":0.5717002663} {"size":12692,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns puppetlabs.services.jruby.jruby-puppet-service-test\n (:require [clojure.test :refer :all]\n [puppetlabs.services.protocols.jruby-puppet :as jruby-protocol]\n [puppetlabs.services.jruby.jruby-puppet-testutils :as jruby-testutils]\n [puppetlabs.kitchensink.core :as ks]\n [puppetlabs.trapperkeeper.app :as app]\n [puppetlabs.services.jruby.jruby-puppet-core :as jruby-puppet-core]\n [puppetlabs.trapperkeeper.testutils.bootstrap :as bootstrap]\n [me.raynes.fs :as fs]\n [schema.test :as schema-test]))\n\n(use-fixtures :once schema-test\/validate-schemas)\n\n(defn jruby-service-test-config\n [pool-size]\n (jruby-testutils\/jruby-puppet-tk-config\n (jruby-testutils\/jruby-puppet-config {:max-active-instances pool-size})))\n\n(deftest facter-jar-loaded-during-init\n (testing (str \"facter jar found from the ruby load path is properly \"\n \"loaded into the system classpath\")\n (let [temp-dir (ks\/temp-dir)\n facter-jar (-> temp-dir\n (fs\/file jruby-puppet-core\/facter-jar)\n (ks\/absolute-path))\n config (assoc-in (jruby-service-test-config 1)\n [:jruby-puppet :ruby-load-path]\n (into [] (cons (ks\/absolute-path temp-dir)\n jruby-testutils\/ruby-load-path)))]\n (fs\/touch facter-jar)\n (bootstrap\/with-app-with-config\n app\n (jruby-testutils\/jruby-service-and-dependencies-with-mocking config)\n config\n (is (true? (some #(= facter-jar (.getFile %))\n (.getURLs (ClassLoader\/getSystemClassLoader)))))))))\n\n(deftest environment-class-info-tags\n (testing \"environment-class-info-tags cache has proper data\"\n ;; This test uses a mock JRubyPoolManagerService. Where these tests are\n ;; largely about validating the content of the environment cache, whose\n ;; implementation lives in Clojure, having \"real\" JRuby instances running\n ;; in the application stack does not seem essential for these tests.\n ;;\n ;; There are related tests in other namespaces which do use real JRubyPuppet\n ;; instances:\n ;;\n ;; * puppetlabs.services.jruby.class-info-test - Makes direct calls on a\n ;; \"real\" JRubyPuppet to validate that the environment class content\n ;; matches the manifest content on disk.\n ;;\n ;; * puppetlabs.services.master.environment-classes-int-test - Stands up\n ;; a full application stack and makes calls to the \"environment_classes\"\n ;; HTTP endpoint which exercise both the Clojure-level environment class\n ;; cache and \"real\" JRubyPuppet instances for doing class info parsing.\n (let [config (jruby-service-test-config 1)]\n (bootstrap\/with-app-with-config\n app\n (jruby-testutils\/jruby-service-and-dependencies-with-mocking config)\n config\n (let [service (app\/get-service app :JRubyPuppetService)\n production-cache-id-before-first-update\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\")]\n (testing \"when environment not previously loaded to cache\"\n (is (nil? (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\")))\n (is (= 1 production-cache-id-before-first-update)))\n (testing \"when environment info first set to cache\"\n (jruby-protocol\/set-environment-class-info-tag!\n service\n \"production\"\n \"1234prod\"\n production-cache-id-before-first-update)\n (is (= \"1234prod\" (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\")))\n (is (nil? (jruby-protocol\/get-environment-class-info-tag\n service\n \"test\")))\n (jruby-protocol\/set-environment-class-info-tag!\n service\n \"test\"\n \"1234test\"\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"test\"))\n (is (= \"1234prod\" (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\")))\n (is (= \"1234test\" (jruby-protocol\/get-environment-class-info-tag\n service\n \"test\"))))\n (let [production-cache-id-after-first-update\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\")\n test-cache-id-after-first-update\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"test\")]\n (testing \"when environment info reset in the cache\"\n (is (= 2 production-cache-id-after-first-update))\n (is (= 2 test-cache-id-after-first-update))\n (jruby-protocol\/set-environment-class-info-tag!\n service\n \"production\"\n \"5678prod\"\n production-cache-id-after-first-update)\n (is (= \"5678prod\" (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\")))\n (is (= \"1234test\" (jruby-protocol\/get-environment-class-info-tag\n service\n \"test\")))\n (is (= test-cache-id-after-first-update\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"test\")))\n (testing \"and environment expired between get and corresponding set\"\n (let [production-cache-id-before-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\")\n _ (jruby-protocol\/mark-environment-expired! service\n \"production\")\n production-cache-id-after-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\")]\n (is (not= production-cache-id-after-first-update\n production-cache-id-before-marked-expired))\n (is (not= production-cache-id-before-marked-expired\n production-cache-id-after-marked-expired))\n (is (= nil (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\"))\n (str \"Tag was unexpectedly non-nil, however, it should have \"\n \"been because of the prior call to \"\n \"`mark-environment-expired`\"))\n (jruby-protocol\/set-environment-class-info-tag!\n service\n \"production\"\n \"89abprod\"\n production-cache-id-before-marked-expired)\n (is (= nil (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\"))\n (str \"Tag should not have been changed by the prior set \"\n \"since the environment was marked expired after the \"\n \"cache was read for \"\n \"`production-cache-id-before-marked-expired`\"))\n (is (= production-cache-id-after-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\"))\n (str \"Cache id should not have been changed by the prior \"\n \"set since the environment was marked expired after \"\n \"cache was read for \"\n \"`production-cache-id-before-marked-expired`\")))))\n (testing \"when an individual environment is marked expired\"\n (let [production-cache-id-before-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\")]\n (jruby-protocol\/mark-environment-expired! service \"production\")\n (is (nil? (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\")))\n (is (not= production-cache-id-before-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\"))))\n (is (= \"1234test\" (jruby-protocol\/get-environment-class-info-tag\n service\n \"test\")))\n (is (= test-cache-id-after-first-update\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"test\"))))\n (testing \"when all environments are marked expired\"\n (let [production-cache-id-before-set-tag\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\")]\n (jruby-protocol\/set-environment-class-info-tag!\n service\n \"production\"\n \"8910prod\"\n production-cache-id-before-set-tag)\n (is (= \"8910prod\" (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\"))))\n (let [production-cache-id-before-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\")]\n (jruby-protocol\/mark-all-environments-expired! service)\n (is (nil? (jruby-protocol\/get-environment-class-info-tag\n service\n \"production\")))\n (is (not= production-cache-id-before-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"production\")))\n (is (nil? (jruby-protocol\/get-environment-class-info-tag service\n \"test\")))\n (is (not= test-cache-id-after-first-update\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"test\")))))\n (testing (str \"when all environments expired between get and set \"\n \"for environment that did not previously exist\")\n (let [staging-cache-id-before-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"staging\")\n _ (jruby-protocol\/mark-all-environments-expired! service)\n staging-cache-id-after-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"staging\")]\n (jruby-protocol\/set-environment-class-info-tag!\n service\n \"staging\"\n \"1234staging\"\n staging-cache-id-before-marked-expired)\n (is (= nil (jruby-protocol\/get-environment-class-info-tag\n service\n \"staging\"))\n (str \"Tag should not have been changed by the prior set \"\n \"since the environment was marked expired after the \"\n \"`staging-cache-id-before-marked-expired` was read\"))\n (is (= staging-cache-id-after-marked-expired\n (jruby-protocol\/get-environment-class-info-cache-generation-id!\n service\n \"staging\"))\n (str \"Cache id should not have been changed by the prior \"\n \"set since the environment was marked expired after the \"\n \"`staging-cache-id-before-marked-expired` was \"\n \"read\"))))))))))\n","avg_line_length":52.0163934426,"max_line_length":88,"alphanum_fraction":0.5256066814} {"size":1307,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":";; Copyright 2014-2015 Red Hat, Inc, and individual contributors.\n;;\n;; Licensed under the Apache License, Version 2.0 (the \"License\");\n;; you may not use this file except in compliance with the License.\n;; You may obtain a copy of the License at\n;;\n;; http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n;;\n;; Unless required by applicable law or agreed to in writing, software\n;; distributed under the License is distributed on an \"AS IS\" BASIS,\n;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n;; See the License for the specific language governing permissions and\n;; limitations under the License.\n\n(ns immutant.scheduling.quartz\n \"Utilities specific to [Quartz](http:\/\/quartz-scheduler.org\/).\"\n (:require [immutant.scheduling.internal :as int])\n (:import org.projectodd.wunderboss.scheduling.QuartzScheduling))\n\n(defn quartz-scheduler\n \"Returns the internal Quartz scheduler instance for the given options.\n\n `opts` should be the same scheduler options passed\n to [[immutant.scheduling\/schedule]] (currently just :num-threads).\"\n [opts]\n (let [^QuartzScheduling quartz-scheduler (-> (merge int\/create-defaults opts)\n int\/scheduler\n (doto .start))]\n (.scheduler quartz-scheduler)))\n","avg_line_length":43.5666666667,"max_line_length":79,"alphanum_fraction":0.6977811783} {"size":2332,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns cmr.opendap.site.data\n \"The functions of this namespace are specifically responsible for generating\n data structures to be consumed by site page templates.\n\n Of special note: this namespace and its sibling `page` namespace are only\n ever meant to be used in the `cmr.search.site` namespace, particularly in\n support of creating site routes for access in a browser.\n\n Under no circumstances should `cmr.search.site.data` be accessed from outside\n this context; the data functions defined herein are specifically for use\n in page templates, structured explicitly for their needs.\")\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;; Data Utility Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(def default-title \"CMR OPeNDAP\")\n\n(def default-partner-guide\n \"Data for templates that display a link to Partner Guides. Clients should\n overrirde these keys in their own base static and base page maps if they\n need to use different values.\"\n {:partner-url \"https:\/\/wiki.earthdata.nasa.gov\/display\/CMR\/CMR+Client+Partner+User+Guide\"\n :partner-text \"Client Partner's Guide\"})\n\n(defn base-static\n \"Data that all static pages have in common.\n\n Note that static pages don't have any context.\"\n []\n (merge default-partner-guide\n {:base-url \"\"\n :app-title default-title}))\n\n(defn base-dynamic\n \"Data that all pages have in common.\n\n Note that dynamic pages need to provide the base-url.\"\n ([]\n (base-dynamic {}))\n ([data]\n (merge default-partner-guide\n {:app-title default-title}\n data)))\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;; Page Data Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n(defmulti base-page\n \"Data that all app pages have in common.\n\n The `:cli` variant uses a special constructed context (see\n `static.StaticContext`).\n\n The default variant is the original, designed to work with the regular\n request context which contains the state of a running CMR.\"\n :execution-context)\n\n(defmethod base-page :cli\n [data]\n (base-static data))\n\n(defmethod base-page :default\n [data]\n (base-dynamic data))\n","avg_line_length":34.8059701493,"max_line_length":91,"alphanum_fraction":0.5977701544} {"size":1845,"ext":"clj","lang":"Clojure","max_stars_count":141.0,"content":"(ns kit.edge.db.postgres\n (:require\n [cheshire.core :as cheshire]\n [next.jdbc]\n [next.jdbc.prepare :as prepare]\n [next.jdbc.result-set :as result-set])\n (:import\n [clojure.lang IPersistentMap]\n [java.sql Array PreparedStatement Timestamp]\n [java.time Instant LocalDate LocalDateTime]\n [org.postgresql.util PGobject]))\n\n(def ->json cheshire\/generate-string)\n(def <-json #(cheshire\/parse-string % true))\n\n(defn ->pgobject\n \"Transforms Clojure data to a PGobject that contains the data as\n JSON. PGObject type defaults to `jsonb` but can be changed via\n metadata key `:pgtype`\"\n [x]\n (let [pgtype (or (:pgtype (meta x) \"jsonb\"))]\n (doto (PGobject.)\n (.setType pgtype)\n (.setValue (->json x)))))\n\n(defn <-pgobject\n \"Transform PGobject containing `json` or `jsonb` value to Clojure data\"\n [^PGobject v]\n (let [type (.getType v)\n value (.getValue v)]\n (if (#{\"jsonb\" \"json\"} type)\n (when value\n (with-meta (<-json value) {:pgtype type}))\n value)))\n\n(extend-protocol result-set\/ReadableColumn\n Array\n (read-column-by-label [^Array v _] (vec (.getArray v)))\n (read-column-by-index [^Array v _2 _3] (vec (.getArray v)))\n\n PGobject\n (read-column-by-label [^PGobject v _] (<-pgobject v))\n (read-column-by-index [^PGobject v _2 _3] (<-pgobject v)))\n\n(extend-protocol prepare\/SettableParameter\n Instant\n (set-parameter [^Instant v ^PreparedStatement ps ^long i]\n (.setTimestamp ps i (Timestamp\/from v)))\n\n LocalDate\n (set-parameter [^LocalDate v ^PreparedStatement ps ^long i]\n (.setTimestamp ps i (Timestamp\/valueOf (.atStartOfDay v))))\n\n LocalDateTime\n (set-parameter [^LocalDateTime v ^PreparedStatement ps ^long i]\n (.setTimestamp ps i (Timestamp\/valueOf v)))\n\n IPersistentMap\n (set-parameter [m ^PreparedStatement s i]\n (.setObject s i (->pgobject m))))","avg_line_length":30.75,"max_line_length":73,"alphanum_fraction":0.6693766938} {"size":4078,"ext":"cljs","lang":"Clojure","max_stars_count":2.0,"content":"(ns sharetribe.flex-cli.process-util\n (:require [clojure.set :as set]\n [chalk]\n [form-data :as FormData]\n [sharetribe.flex-cli.io-util :as io-util]\n [sharetribe.flex-cli.api.client :as api.client]\n [sharetribe.flex-cli.exception :as exception]))\n\n(def error-arrow (.bold.red chalk \"\\u203A\"))\n\n(defn- error-report\n \"Given an error description map, format it as an error report string\n (a multi line string).\"\n [total index error]\n (let [{:keys [loc msg]} error\n {:keys [row col]} loc\n header (if loc\n (str (inc index) \"\/\" total\n \" [at line \" row \", column \" col \"]\"\n \":\\n\")\n (str (inc index) \"\/\" total\n \":\\n\"))]\n (str \"\\n\" error-arrow \" \" header msg \"\\n\")))\n\n(defn- template-error-report [total index error]\n (let [{:keys [template-name reason evidence line column template-part]} error]\n (error-report\n total\n index\n {:msg (str \"Error in \" (.bold chalk (name template-name))\n \" template \" (name template-part)\n \". Reason: \" reason\n \"\\n\\n\" evidence)\n :loc {:row line\n :col column}})))\n\n(defn- format-invalid-templates-error [data]\n (let [errors (-> (api.client\/api-error data) :details :render-errors)\n total-errors (count errors)]\n (concat\n [:span\n \"The process contains invalid email templates. Found \"\n (str total-errors) \" invalid \" (if (= 1 total-errors) \"template\" \"templates\") \".\"\n :line]\n (map-indexed (partial template-error-report total-errors) errors))))\n\n(defn format-invalid-template-error [data]\n (let [error (-> (api.client\/api-error data) :details :render-error)]\n (template-error-report 1 0 error)))\n\n(defn- format-process-exists-error [data]\n [:span error-arrow\n \" Process already exists: \"\n (-> data api.client\/api-error :details :process-name name)])\n\n(defmethod exception\/format-exception :process.util\/new-process-api-call-failed [_ _ data]\n (case (:code (api.client\/api-error data))\n :invalid-templates (format-invalid-templates-error data)\n :tx-process-already-exists (format-process-exists-error data)\n (api.client\/default-error-format data)))\n\n(defmethod exception\/format-exception :process.util\/missing-templates [_ _ {:keys [notifications]}]\n [:span\n (map (fn [{:keys [name template]}]\n [:span error-arrow\n \" Template \" (.bold chalk (clojure.core\/name template))\n \" not found for notification \" (.bold chalk (clojure.core\/name name))\n :line])\n notifications)])\n\n(defn ensure-process-dir! [path]\n (when-not (io-util\/process-dir? path)\n (exception\/throw! :command\/invalid-args\n {:command :push\n :errors [\"--path should be a process directory\"]})))\n\n(defn ensure-templates! [tx-process templates]\n (let [process-tmpl-names (->> tx-process :notifications (map :template) set)\n template-names (set (map :name templates))\n extra-tmpls (set\/difference template-names process-tmpl-names)\n missing-templates (remove (fn [n]\n (contains? template-names (:template n)))\n (:notifications tx-process))]\n (doseq [t extra-tmpls]\n (io-util\/ppd-err [:span\n (.bold.yellow chalk \"Warning: \")\n \"template exists but is not used in the process: \"\n (.bold chalk (name t))]))\n (when (seq missing-templates)\n (exception\/throw! :process.util\/missing-templates {:notifications missing-templates}))))\n\n(defn to-multipart-form-data [{:keys [name definition templates]}]\n (reduce\n (fn [form-data tmpl]\n (doto form-data\n (.append (str \"template-html-\" (clojure.core\/name (:name tmpl))) (:html tmpl))\n (.append (str \"template-subject-\" (clojure.core\/name (:name tmpl))) (:subject tmpl))))\n (doto (FormData.)\n (.append \"name\" name)\n (.append \"definition\" definition))\n templates))\n","avg_line_length":39.9803921569,"max_line_length":99,"alphanum_fraction":0.5948994605} {"size":2300,"ext":"cljc","lang":"Clojure","max_stars_count":896.0,"content":"(ns cats.monad.identity-spec\n #?@(:cljs\n [(:require [cljs.test :as t]\n [clojure.test.check]\n [clojure.test.check.generators :as gen]\n [clojure.test.check.properties :as prop :include-macros true]\n [cats.labs.test :as lt]\n [cats.builtin :as b]\n [cats.monad.identity :as id]\n [cats.context :as ctx :include-macros true]\n [cats.core :as m :include-macros true])\n (:require-macros [clojure.test.check.clojure-test :refer (defspec)])])\n #?(:clj\n (:require [clojure.test :as t]\n [clojure.test.check.clojure-test :refer [defspec]]\n [clojure.test.check :as tc]\n [clojure.test.check.generators :as gen]\n [clojure.test.check.properties :as prop]\n [cats.labs.test :as lt]\n [cats.builtin :as b]\n [cats.monad.identity :as id]\n [cats.context :as ctx]\n [cats.core :as m])))\n\n(t\/deftest basic-operations-test\n (t\/is (= 1 @(id\/identity 1))))\n\n(def id-gen\n (gen\/fmap id\/identity gen\/any))\n\n(defspec identity-first-functor-law 10\n (lt\/first-functor-law {:gen id-gen}))\n\n(defspec identity-second-functor-law 10\n (lt\/second-functor-law\n {:gen id-gen\n :f str\n :g count}))\n\n(defspec identity-applicative-identity 10\n (lt\/applicative-identity-law\n {:ctx id\/context\n :gen id-gen}))\n\n(defspec identity-applicative-homomorphism 10\n (lt\/applicative-homomorphism\n {:ctx id\/context\n :gen gen\/any\n :f str}))\n\n(defspec identity-applicative-interchange 10\n (lt\/applicative-interchange\n {:ctx id\/context\n :gen gen\/int\n :appf (id\/identity inc)}))\n\n(defspec identity-applicative-composition 10\n (lt\/applicative-composition\n {:ctx id\/context\n :gen gen\/int\n :appf (id\/identity inc)\n :appg (id\/identity dec)}))\n\n(defspec identity-first-monad-law 10\n (lt\/first-monad-law\n {:ctx id\/context\n :mf (comp id\/identity str)}))\n\n(defspec identity-second-monad-law 10\n (lt\/second-monad-law {:ctx id\/context}))\n\n(defspec identity-third-monad-law 10\n (lt\/third-monad-law\n {:ctx id\/context\n :f (comp id\/identity str)\n :g (comp id\/identity count)}))\n\n(t\/deftest predicate-test\n (t\/is (id\/identity 1)))\n","avg_line_length":28.75,"max_line_length":78,"alphanum_fraction":0.6008695652} {"size":302,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns libby.dev-middleware\n (:require [ring.middleware.reload :refer [wrap-reload]]\n [selmer.middleware :refer [wrap-error-page]]\n [prone.middleware :refer [wrap-exceptions]]))\n\n(defn wrap-dev [handler]\n (-> handler\n wrap-reload\n wrap-error-page\n wrap-exceptions))\n","avg_line_length":27.4545454545,"max_line_length":57,"alphanum_fraction":0.6357615894} {"size":392,"ext":"clj","lang":"Clojure","max_stars_count":67.0,"content":"(defn series-step [x]\n (reduce * (repeat x (bigint x))))\n\n(defn only-last-10-digits [x]\n (->> x\n str\n vec\n (take-last 10)\n (apply str)\n bigint))\n\n(defn sum-series [x] \n (transduce \n (map (comp only-last-10-digits\n series-step))\n +\n (range 1 (inc x))))\n\n(defn solve []\n (->> 1000 sum-series only-last-10-digits str))\n\n(println (solve))\n","avg_line_length":17.0434782609,"max_line_length":48,"alphanum_fraction":0.5255102041} {"size":12051,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns crux.node\n (:require [clojure.java.io :as io]\n [clojure.spec.alpha :as s]\n [clojure.tools.logging :as log]\n [com.stuartsierra.dependency :as dep]\n [crux.backup :as backup]\n [crux.codec :as c]\n [crux.config :as cc]\n [crux.db :as db]\n [crux.index :as idx]\n [crux.io :as cio]\n [crux.kv :as kv]\n crux.object-store\n [crux.query :as q]\n [crux.status :as status]\n [crux.tx :as tx])\n (:import [crux.api ICruxAPI ICruxAsyncIngestAPI]\n java.io.Closeable\n [java.util.concurrent Executors ThreadFactory]\n java.util.concurrent.locks.StampedLock))\n\n(s\/check-asserts (if-let [check-asserts (System\/getProperty \"clojure.spec.compile-asserts\")]\n (Boolean\/parseBoolean check-asserts)\n true))\n\n(defrecord CruxVersion [version revision]\n status\/Status\n (status-map [this]\n {:crux.version\/version version\n :crux.version\/revision revision}))\n\n(def crux-version\n (memoize\n (fn []\n (when-let [pom-file (io\/resource \"META-INF\/maven\/juxt\/crux-core\/pom.properties\")]\n (with-open [in (io\/reader pom-file)]\n (let [{:strs [version\n revision]} (cio\/load-properties in)]\n (->CruxVersion version revision)))))))\n\n(defn- ensure-node-open [{:keys [closed?]}]\n (when @closed?\n (throw (IllegalStateException. \"Crux node is closed\"))))\n\n(defrecord CruxNode [kv-store tx-log indexer object-store options close-fn status-fn closed? ^StampedLock lock]\n ICruxAPI\n (db [this]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (let [tx-time (:crux.tx\/tx-time (db\/read-index-meta indexer :crux.tx\/latest-completed-tx))]\n (q\/db kv-store object-store tx-time tx-time))))\n\n (db [this valid-time]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (let [transact-time (:crux.tx\/tx-time (db\/read-index-meta indexer :crux.tx\/latest-completed-tx))]\n (.db this valid-time transact-time))))\n\n (db [this valid-time transact-time]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (q\/db kv-store object-store valid-time transact-time)))\n\n (document [this content-hash]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (with-open [snapshot (kv\/new-snapshot kv-store)]\n (db\/get-single-object object-store snapshot (c\/new-id content-hash)))))\n\n (documents [this content-hash-set]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (with-open [snapshot (kv\/new-snapshot kv-store)]\n (db\/get-objects object-store snapshot (map c\/new-id content-hash-set)))))\n\n (history [this eid]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (with-open [snapshot (kv\/new-snapshot kv-store)]\n (mapv c\/entity-tx->edn (idx\/entity-history snapshot eid)))))\n\n (historyRange [this eid valid-time-start transaction-time-start valid-time-end transaction-time-end]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (with-open [snapshot (kv\/new-snapshot kv-store)]\n (->> (idx\/entity-history-range snapshot eid valid-time-start transaction-time-start valid-time-end transaction-time-end)\n (mapv c\/entity-tx->edn)\n (sort-by (juxt :crux.db\/valid-time :crux.tx\/tx-time))))))\n\n (status [this]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (status-fn)))\n\n (attributeStats [this]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (idx\/read-meta kv-store :crux.kv\/stats)))\n\n (submitTx [this tx-ops]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n @(db\/submit-tx tx-log tx-ops)))\n\n (hasSubmittedTxUpdatedEntity [this submitted-tx eid]\n (.hasSubmittedTxCorrectedEntity this submitted-tx (:crux.tx\/tx-time submitted-tx) eid))\n\n (hasSubmittedTxCorrectedEntity [this submitted-tx valid-time eid]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (tx\/await-tx indexer submitted-tx (:crux.tx-log\/await-tx-timeout options))\n (q\/submitted-tx-updated-entity? kv-store object-store submitted-tx valid-time eid)))\n\n (newTxLogContext [this]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (db\/new-tx-log-context tx-log)))\n\n (txLog [this tx-log-context from-tx-id with-ops?]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (for [{:keys [crux.tx\/tx-id\n crux.tx.event\/tx-events] :as tx-log-entry} (db\/tx-log tx-log tx-log-context from-tx-id)\n :when (with-open [snapshot (kv\/new-snapshot kv-store)]\n (nil? (kv\/get-value snapshot (c\/encode-failed-tx-id-key-to nil tx-id))))]\n (if with-ops?\n (-> tx-log-entry\n (dissoc :crux.tx.event\/tx-events)\n (assoc :crux.api\/tx-ops\n (with-open [snapshot (kv\/new-snapshot kv-store)]\n (->> tx-events\n (mapv #(tx\/tx-event->tx-op % snapshot object-store))))))\n tx-log-entry))))\n\n (sync [this timeout]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (-> (tx\/await-no-consumer-lag indexer (or (and timeout (.toMillis timeout))\n (:crux.tx-log\/await-tx-timeout options)))\n :crux.tx\/tx-time)))\n\n (sync [this tx-time timeout]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (-> (tx\/await-tx-time indexer tx-time (or (and timeout (.toMillis timeout))\n (:crux.tx-log\/await-tx-timeout options)))\n :crux.tx\/tx-time)))\n\n ICruxAsyncIngestAPI\n (submitTxAsync [this tx-ops]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (db\/submit-tx tx-log tx-ops)))\n\n backup\/INodeBackup\n (write-checkpoint [this {:keys [crux.backup\/checkpoint-directory] :as opts}]\n (cio\/with-read-lock lock\n (ensure-node-open this)\n (kv\/backup kv-store (io\/file checkpoint-directory \"kv-store\"))\n\n (when (satisfies? tx-log backup\/INodeBackup)\n (backup\/write-checkpoint tx-log opts))))\n\n Closeable\n (close [_]\n (cio\/with-write-lock lock\n (when (and (not @closed?) close-fn) (close-fn))\n (reset! closed? true))))\n\n(defn install-uncaught-exception-handler! []\n (when-not (Thread\/getDefaultUncaughtExceptionHandler)\n (Thread\/setDefaultUncaughtExceptionHandler\n (reify Thread$UncaughtExceptionHandler\n (uncaughtException [_ thread throwable]\n (log\/error throwable \"Uncaught exception:\"))))))\n\n(defn- start-kv-indexer [{::keys [kv-store tx-log object-store]} _]\n (tx\/->KvIndexer kv-store tx-log object-store\n (Executors\/newSingleThreadExecutor\n (reify ThreadFactory\n (newThread [_ r]\n (doto (Thread. r)\n (.setName \"crux.tx.update-stats-thread\")))))))\n\n(s\/def ::topology-id\n (fn [id]\n (and (or (string? id) (keyword? id) (symbol? id))\n (namespace (symbol id)))))\n\n(s\/def ::start-fn ifn?)\n(s\/def ::deps (s\/coll-of keyword?))\n(s\/def ::args (s\/map-of keyword?\n (s\/keys :req [:crux.config\/type]\n :req-un [:crux.config\/doc]\n :opt-un [:crux.config\/default\n :crux.config\/required?])))\n\n(defn- resolve-topology-id [id]\n (s\/assert ::topology-id id)\n (-> id symbol requiring-resolve var-get))\n\n(s\/def ::module (s\/and (s\/and (s\/or :module-id ::topology-id :module map?)\n (s\/conformer\n (fn [[m-or-id s]]\n (if (= :module-id m-or-id)\n (resolve-topology-id s) s))))\n (s\/keys :req-un [::start-fn]\n :opt-un [::deps ::args])))\n\n(defn- start-order [system]\n (let [g (reduce-kv (fn [g k m]\n (let [m (s\/conform ::module m)]\n (reduce (fn [g d] (dep\/depend g k d)) g (:deps m))))\n (dep\/graph)\n system)\n dep-order (dep\/topo-sort g)\n dep-order (->> (keys system)\n (remove #(contains? (set dep-order) %))\n (into dep-order))]\n dep-order))\n\n(defn- parse-opts [args options]\n (into {}\n (for [[k {:keys [crux.config\/type default required?]}] args\n :let [[validate-fn parse-fn] (s\/conform :crux.config\/type type)\n v (some-> (get options k) parse-fn)\n v (if (nil? v) default v)]]\n (do\n (when (and required? (not v))\n (throw (IllegalArgumentException. (format \"Arg %s required\" k))))\n (when (and v (not (validate-fn v)))\n (throw (IllegalArgumentException. (format \"Arg %s invalid\" k))))\n [k v]))))\n\n(defn start-module [m started options]\n (s\/assert ::module m)\n (let [{:keys [start-fn deps spec args]} (s\/conform ::module m)\n deps (select-keys started deps)\n options (merge options (parse-opts args options))]\n (start-fn deps options)))\n\n(s\/def ::topology-map (s\/map-of keyword? ::module))\n\n(defn start-modules [topology options]\n (s\/assert ::topology-map topology)\n (let [started-order (atom [])\n started (atom {})\n started-modules (try\n (into {}\n (for [k (start-order topology)]\n (let [m (topology k)\n _ (assert m (str \"Could not find module \" k))\n m (start-module m @started options)]\n (swap! started-order conj m)\n (swap! started assoc k m)\n [k m])))\n (catch Throwable t\n (doseq [c (reverse @started-order)]\n (when (instance? Closeable c)\n (cio\/try-close c)))\n (throw t)))]\n [started-modules (fn []\n (doseq [m (reverse @started-order)\n :when (instance? Closeable m)]\n (cio\/try-close m)))]))\n\n(def base-topology {::kv-store 'crux.kv.rocksdb\/kv\n ::object-store 'crux.object-store\/kv-object-store\n ::indexer {:start-fn start-kv-indexer\n :deps [::kv-store ::tx-log ::object-store]}})\n\n(defn options->topology [{:keys [crux.node\/topology] :as options}]\n (when-not topology\n (throw (IllegalArgumentException. \"Please specify :crux.node\/topology\")))\n (let [topology (if (map? topology) topology (resolve-topology-id topology))\n topology-overrides (select-keys options (keys topology))\n topology (merge topology (zipmap (keys topology-overrides)\n (map resolve-topology-id (vals topology-overrides))))]\n (s\/assert ::topology-map topology)\n topology))\n\n(def node-args\n {:crux.tx-log\/await-tx-timeout\n {:doc \"Default timeout in milliseconds for waiting.\"\n :default 10000\n :crux.config\/type :crux.config\/nat-int}})\n\n(defn start ^crux.api.ICruxAPI [options]\n (let [options (into {} options)\n topology (options->topology options)\n [modules close-fn] (start-modules topology options)\n {::keys [kv-store tx-log indexer object-store]} modules\n status-fn (fn [] (apply merge (map status\/status-map (cons (crux-version) (vals modules)))))\n node-opts (parse-opts node-args options)]\n (map->CruxNode {:close-fn close-fn\n :status-fn status-fn\n :options node-opts\n :kv-store kv-store\n :tx-log tx-log\n :indexer indexer\n :object-store object-store\n :closed? (atom false)\n :lock (StampedLock.)})))\n","avg_line_length":39.6414473684,"max_line_length":128,"alphanum_fraction":0.5552236329} {"size":10973,"ext":"clj","lang":"Clojure","max_stars_count":922.0,"content":"(\r\n\r\n \"intersect\"\r\n [(dim :number :grain #(> (:grain %) 1)) (dim :number)] ; grain 1 are taken care of by specific rule\r\n (compose-numbers %1 %2)\r\n\r\n \"intersect (with and)\"\r\n [(dim :number :grain #(> (:grain %) 1)) #\"(?i)i|a\" (dim :number)] ; grain 1 are taken care of by specific rule\r\n (compose-numbers %1 %3)\r\n\r\n ;;\r\n ;; Integers\r\n ;;\r\n\r\n \"zero\"\r\n #\"(?i)(zero|nic)\"\r\n {:dim :number :integer true :value 0 :grain 1}\r\n\r\n \"one\"\r\n #\"(?i)jed(en|nego|nemu|nym|nej|n(a|\u0105))\"\r\n {:dim :number :integer true :value 1 :grain 1}\r\n\r\n \"two\"\r\n #\"(?i)dw(a|(o|\u00f3)(ch|m)|oma|iema|ie)\"\r\n {:dim :number :integer true :value 2 :grain 1}\r\n\r\n \"three\"\r\n #\"(?i)trz(y|ema|ech)\"\r\n {:dim :number :integer true :value 3 :grain 1}\r\n\r\n \"four\"\r\n #\"(?i)czter(ej|y|ech|em|ema)\"\r\n {:dim :number :integer true :value 4 :grain 1}\r\n\r\n \"five\"\r\n #\"(?i)pi(e|\u0119)(c|\u0107)(iu|oma|u)?\"\r\n {:dim :number :integer true :value 5 :grain 1}\r\n\r\n \"six\"\r\n #\"(?i)sze(s|\u015b)(c|\u0107)(iu|oma|u)?\"\r\n {:dim :number :integer true :value 6 :grain 1}\r\n\r\n \"seven\"\r\n #\"(?i)sied(miu|em|mioma)\"\r\n {:dim :number :integer true :value 7 :grain 1}\r\n\r\n \"eight\"\r\n #\"(?i)o(s|\u015b)(iem|miu|mioma)\"\r\n {:dim :number :integer true :value 8 :grain 1}\r\n\r\n \"nine\"\r\n #\"(?i)dziewi(e|\u0119)(\u0107|c)(iu|ioma)?\"\r\n {:dim :number :integer true :value 9 :grain 1}\r\n\r\n \"ten\"\r\n #\"(?i)dzisi(e|\u0119)(\u0107|c)(iu|ioma)?\"\r\n {:dim :number :integer true :value 10 :grain 1}\r\n\r\n \"eleven\"\r\n #\"(?i)jedena(stu|(s|\u015b)cie|stoma)\"\r\n {:dim :number :integer true :value 11 :grain 1}\r\n\r\n \"twelve\"\r\n #\"(?i)dwunast(u|oma)|dwana(\u015b|s)cie\"\r\n {:dim :number :integer true :value 12 :grain 1}\r\n\r\n \"thirteen\"\r\n #\"(?i)trzyna(\u015b|s)(tu|cie|toma)\"\r\n {:dim :number :integer true :value 13 :grain 1}\r\n\r\n \"fourteen\"\r\n #\"(?i)czterna(s|\u015b)(tu|cie|toma)\"\r\n {:dim :number :integer true :value 14 :grain 1}\r\n\r\n \"fifteen\"\r\n #\"(?i)pi\u0119tna(s|\u015b)(ta|tu|cie|toma)\"\r\n {:dim :number :integer true :value 15 :grain 1}\r\n\r\n \"sixteen\"\r\n #\"(?i)szesna(s|\u015b)(tu|cie|toma)\"\r\n {:dim :number :integer true :value 16 :grain 1}\r\n\r\n \"seventeen\"\r\n #\"(?i)siedemna(s|\u015b)(tu|cie|toma)\"\r\n {:dim :number :integer true :value 17 :grain 1}\r\n\r\n \"eighteen\"\r\n #\"(?i)osiemna(s|\u015b)(tu|cie|toma)\"\r\n {:dim :number :integer true :value 18 :grain 1}\r\n\r\n \"nineteen\"\r\n #\"(?i)dziewietna(s|\u015b)(tu|cie|toma)\"\r\n {:dim :number :integer true :value 19 :grain 1}\r\n\r\n \"single\"\r\n #\"(?i)pojedynczy\"\r\n {:dim :number :integer true :value 1 :grain 1}\r\n\r\n \"a pair\"\r\n #\"(?i)para?\"\r\n {:dim :number :integer true :value 2 :grain 1}\r\n\r\n \"dozen\"\r\n #\"(?i)tuzin\"\r\n {:dim :number :integer true :value 12 :grain 1 :grouping true} ;;restrict composition and prevent \"2 12\"\r\n\r\n \"number 100\"\r\n #\"(?i)(sto|setki)\"\r\n {:dim :number :integer true :value 100 :grain 2}\r\n\r\n \"number 200\"\r\n #\"(?i)(dwie(\u015bcie| setki))\"\r\n {:dim :number :integer true :value 200 :grain 2}\r\n\r\n \"number 300\"\r\n #\"(?i)(trzy(sta| setki))\"\r\n {:dim :number :integer true :value 300 :grain 2}\r\n\r\n \"number 400\"\r\n #\"(?i)(cztery(sta| setki))\"\r\n {:dim :number :integer true :value 400 :grain 2}\r\n\r\n \"number 500\"\r\n #\"(?i)(pi\u0119\u0107(set| setek))\"\r\n {:dim :number :integer true :value 500 :grain 2}\r\n\r\n \"number 600\"\r\n #\"(?i)(sze\u015b\u0107(set| setek))\"\r\n {:dim :number :integer true :value 600 :grain 2}\r\n\r\n \"number 700\"\r\n #\"(?i)(siedem(set| setek))\"\r\n {:dim :number :integer true :value 700 :grain 2}\r\n\r\n \"number 800\"\r\n #\"(?i)(osiem(set| setek))\"\r\n {:dim :number :integer true :value 800 :grain 2}\r\n\r\n \"number 900\"\r\n #\"(?i)(dziewi\u0119\u0107(set| setek))\"\r\n {:dim :number :integer true :value 900 :grain 2}\r\n\r\n \"thousand\"\r\n #\"(?i)ty(s|\u015b)i(a|\u0105|\u0119)c(e|y)?\"\r\n {:dim :number :integer true :value 1000 :grain 3}\r\n\r\n \"million\"\r\n #\"(?i)milion(y|\u00f3w)?\"\r\n {:dim :number :integer true :value 1000000 :grain 6}\r\n\r\n \"couple\"\r\n #\"pare\"\r\n {:dim :number :integer true :value 2}\r\n\r\n \"a few\" ; TODO set assumption\r\n #\"kilk(a|u)\"\r\n {:dim :number :integer true :precision :approximate :value 3}\r\n\r\n \"twenty\"\r\n #\"(?i)dwadzie(\u015b|s)cia|dwudziest(u|oma)\"\r\n {:dim :number :integer true :value 20 :grain 1}\r\n\r\n \"thirty\"\r\n #\"(?i)trzydzie\u015bci|trzydziest(u|oma)\"\r\n {:dim :number :integer true :value 30 :grain 1}\r\n\r\n \"thirty\"\n #\"(?i)trzydzie\u015bci|trzydziest(u|oma)\"\r\n {:dim :number :integer true :value 30 :grain 1}\r\n\r\n \"fou?rty\"\n #\"(?i)czterdzie\u015bci|czterdziest(u|oma)\"\r\n {:dim :number :integer true :value 40 :grain 1}\r\n\r\n \"fifty\"\r\n #\"(?i)pi\u0119\u0107dziesi\u0105t|pi\u0119\u0107dziesi\u0119ci(u|oma)\"\r\n {:dim :number :integer true :value 50 :grain 1}\r\n\r\n \"sixty\"\r\n #\"(?i)sze\u015b\u0107dziesi\u0105t|sze\u015b\u0107dziesi\u0119ci(u|oma)\"\r\n {:dim :number :integer true :value 60 :grain 1}\r\n\r\n \"integer (20..90)\"\r\n #\"(?i)(twenty|thirty|fou?rty|fifty|sixty|seventy|eighty|ninety)\"\r\n {:dim :number\r\n :integer true\r\n :value (get {\"dwadzie\u015bcia\" 20 \"trzydzie\u015bci\" 30 \"czterdzie\u015bci\" 40 \"pi\u0119\u0107dziesi\u0105t\" 50 \"sze\u015b\u0107dziesi\u0105t\" 60\r\n \"siedemdziesi\u0105t\" 70 \"osiemdziesi\u0105t\" 80 \"dziewi\u0119\u0107dziesi\u0105t\" 90}\r\n (-> %1 :groups first .toLowerCase))\r\n :grain 1}\r\n\r\n \"integer 21..99\"\r\n [(integer 10 90 #(#{20 30 40 50 60 70 80 90} (:value %))) (integer 1 9)]\r\n {:dim :number\r\n :integer true\r\n :value (+ (:value %1) (:value %2))}\r\n\r\n \"integer (numeric)\"\r\n #\"(\\d{1,18})\"\r\n {:dim :number\r\n :integer true\r\n :value (Long\/parseLong (first (:groups %1)))}\r\n\r\n \"integer with thousands separator ,\"\r\n #\"(\\d{1,3}(,\\d\\d\\d){1,5})\"\r\n {:dim :number\r\n :integer true\r\n :value (-> (:groups %1)\r\n first\r\n (clojure.string\/replace #\",\" \"\")\r\n Long\/parseLong)}\r\n\r\n ; composition\r\n \"special composition for missing hundreds like in one twenty two\"\r\n [(integer 1 9) (integer 10 99)] ; grain 1 are taken care of by specific rule\r\n {:dim :number\r\n :integer true\r\n :value (+ (* (:value %1) 100) (:value %2))\r\n :grain 1}\r\n\r\n\r\n \"number dozen\"\r\n [(integer 1 10) (dim :number #(:grouping %))]\r\n {:dim :number\r\n :integer true\r\n :value (* (:value %1) (:value %2))\r\n :grain (:grain %2)}\r\n\r\n\r\n \"number thousands\"\r\n [(integer 1 999) (integer 1000 1000)]\r\n {:dim :number\r\n :integer true\r\n :value (* (:value %1) (:value %2))\r\n :grain (:grain %2)}\r\n\r\n \"number millions\"\r\n [(integer 1 99) (integer 1000000 1000000)]\r\n {:dim :number\r\n :integer true\r\n :value (* (:value %1) (:value %2))\r\n :grain (:grain %2)}\r\n\r\n ;;\r\n ;; Decimals\r\n ;;\r\n\r\n \"decimal number\"\r\n #\"(\\d*\\.\\d+)\"\r\n {:dim :number\r\n :value (Double\/parseDouble (first (:groups %1)))}\r\n\r\n \"number dot number\"\r\n [(dim :number #(not (:number-prefixed %))) #\"(?i)dot|point\" (dim :number #(not (:number-suffixed %)))]\r\n {:dim :number\r\n :value (+ (* 0.1 (:value %3)) (:value %1))}\r\n\r\n\r\n \"decimal with thousands separator\"\r\n #\"(\\d+(,\\d\\d\\d)+\\.\\d+)\"\r\n {:dim :number\r\n :value (-> (:groups %1)\r\n first\r\n (clojure.string\/replace #\",\" \"\")\r\n Double\/parseDouble)}\r\n\r\n ;; negative number\r\n \"numbers prefix with -, negative or minus\"\r\n [#\"(?i)-|minus\\s?|negative\\s?\" (dim :number #(not (:number-prefixed %)))]\r\n (let [multiplier -1\r\n value (* (:value %2) multiplier)\r\n int? (zero? (mod value 1)) ; often true, but we could have 1.1111K\r\n value (if int? (long value) value)] ; cleaner if we have the right type\r\n (assoc %2 :value value\r\n :integer int?\r\n :number-prefixed true)) ; prevent \"- -3km\" to be 3 billions\r\n\r\n\r\n ;; suffixes\r\n\r\n ; note that we check for a space-like char after the M, K or G\r\n ; to avoid matching 3 Mandarins\r\n \"numbers suffixes (K, M, G)\"\r\n [(dim :number #(not (:number-suffixed %))) #\"(?i)([kmg])(?=[\\W\\$\u20ac]|$)\"]\r\n (let [multiplier (get {\"k\" 1000 \"m\" 1000000 \"g\" 1000000000}\r\n (-> %2 :groups first .toLowerCase))\r\n value (* (:value %1) multiplier)\r\n int? (zero? (mod value 1)) ; often true, but we could have 1.1111K\r\n value (if int? (long value) value)] ; cleaner if we have the right type\r\n (assoc %1 :value value\r\n :integer int?\r\n :number-suffixed true)) ; prevent \"3km\" to be 3 billions\r\n\r\n ;;\r\n ;; Ordinal numbers\r\n ;; TODO: optimize\/streamline?\r\n\r\n \"first ordinal\"\r\n #\"(?i)pierw?sz(y|ego|emu|m|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 1}\r\n\r\n \"second ordinal\"\r\n #\"(?i)drugi?(ego|emu|m|(a|\u0105)|ej)?\"\r\n {:dim :ordinal\r\n :value 2}\r\n\r\n \"third ordinal\"\r\n #\"(?i)trzeci(ego|ch|emu|m|mi|ej|(a|\u0105))?\"\r\n {:dim :ordinal\r\n :value 3}\r\n\r\n \"fourth ordinal\"\r\n #\"(?i)czwart(y|ego|emu|ym|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 4}\r\n\r\n \"fifth ordinal\"\r\n #\"(?i)pi(a|\u0105)t(y|ego|emu|m|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 5}\r\n\r\n \"sixth ordinal\"\r\n #\"(?i)sz(o|\u00f3)st(y|ego|emu|m|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 6}\r\n\r\n \"seventh ordinal\"\r\n #\"(?i)si(o|\u00f3)dm(y|ego|emu|m|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 7}\r\n\r\n \"8th ordinal\"\r\n ;;case insensitivity doesn't apply to polish chars, hence the \u00d3\r\n #\"(?i)(o|\u00f3|\u00d3)sm(y|ego|emu|m|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 8}\r\n\r\n \"9th ordinal\"\r\n #\"(?i)dziewi(a|\u0105)t(ym|y|ego|em|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 9}\r\n\r\n \"10th ordinal\"\r\n #\"(?i)dziesi(a|\u0105)t(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 10}\r\n\r\n \"11th ordinal\"\r\n #\"(?i)jedenast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 11}\r\n\r\n \"12th ordinal\"\r\n #\"(?i)dwunast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 12}\r\n\r\n \"13th ordinal\"\r\n #\"(?i)trzynast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 13}\r\n\r\n \"14th ordinal\"\r\n #\"(?i)czternast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 14}\r\n\r\n \"15th ordinal\"\r\n #\"(?i)pi(e|\u0119)tnast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 15}\r\n\r\n \"16th ordinal\"\r\n #\"(?i)szesnast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 16}\r\n\r\n \"17th ordinal\"\r\n #\"(?i)siedemnast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 17}\r\n\r\n \"18th ordinal\"\r\n #\"(?i)osiemnast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 18}\r\n\r\n \"19th ordinal\"\r\n #\"(?i)dziewi(\u0119|e)tnast(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 19}\r\n\r\n \"20th ordinal\"\r\n #\"(?i)dwudziest(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 20}\r\n\r\n \"21st ordinal no space\"\r\n #\"(?i)dwudziest(ym|y|ego|emu|(a|\u0105)|ej)pierw?sz(y|ego|emu|m|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 21}\r\n\r\n \"22nd ordinal no space\"\r\n #\"(?i)dwudziest(ym|y|ego|emu|(a|\u0105)|ej)drugi?(ego|emu|m|(a|\u0105)|ej)?\"\r\n {:dim :ordinal\r\n :value 22}\r\n\r\n \"23rd ordinal no space\"\r\n #\"(?i)dwudziest(ym|y|ego|emu|(a|\u0105)|ej)trzeci(ego|ch|emu|m|mi|ej|(a|\u0105))?\"\r\n {:dim :ordinal\r\n :value 23}\r\n\r\n \"24th ordinal no space\"\r\n #\"(?i)dwudziest(ym|y|ego|emu|(a|\u0105)|ej)czwart(y|ego|emu|ym|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 24}\r\n\r\n \"21-29th ordinal\" ;;FIX WON'T HANDLE THE WHITESPACE CASE\r\n [#\"(?i)dwudziest(ym|y|ego|emu|(a|\u0105)|ej)( |-)?\"(dim :ordinal)]\r\n {:dim :ordinal :value (+ 20 (get %2 :value))}\r\n\r\n \"30th ordinal\"\r\n #\"(?i)trzydziest(ym|y|ego|emu|(a|\u0105)|ej)\"\r\n {:dim :ordinal\r\n :value 30}\r\n\r\n \"31-39th ordinal\"\r\n [#\"(?i)trzydziest(ym|y|ego|emu|(a|\u0105)|ej)( |-)?\"(dim :ordinal)]\r\n {:dim :ordinal :value (+ 30 (get %2 :value))}\r\n\r\n \"ordinal (digits)\"\r\n #\"0*(\\d+)( |-)?(szy|sza|szym|ego|go|szego|gi(ego|ej)?|st(a|y|ej)|t(ej|y|ego)|ci(ego)?)\"\r\n {:dim :ordinal\r\n :value (read-string (first (:groups %1)))} ; read-string not the safest\r\n\r\n\r\n )\r\n","avg_line_length":24.9954441913,"max_line_length":112,"alphanum_fraction":0.5646587077} {"size":11783,"ext":"cljs","lang":"Clojure","max_stars_count":null,"content":"(ns re-demo.datepicker\n (:require\n [goog.date.Date]\n [reagent.core :as reagent]\n [reagent.ratom :refer-macros [reaction]]\n [cljs-time.core :refer [today days minus plus day-of-week before?]]\n [cljs-time.coerce :refer [to-local-date]]\n [cljs-time.format :refer [formatter unparse]]\n [re-com.core :refer [h-box v-box box gap single-dropdown datepicker datepicker-dropdown checkbox label title p button md-icon-button]]\n [re-com.datepicker :refer [iso8601->date datepicker-dropdown-args-desc]]\n [re-com.validate :refer [date-like?]]\n [re-com.util :refer [now->utc]]\n [re-demo.utils :refer [panel-title title2 args-table github-hyperlink status-text]]))\n\n\n(def ^:private days-map\n {:Su \"S\" :Mo \"M\" :Tu \"T\" :We \"W\" :Th \"T\" :Fr \"F\" :Sa \"S\"})\n\n\n(defn- toggle-inclusion!\n \"convenience function to include\/exclude member from\"\n [set-atom member]\n (reset! set-atom\n (if (contains? @set-atom member)\n (disj @set-atom member)\n (conj @set-atom member))))\n\n(defn- checkbox-for-day\n [day enabled-days]\n [v-box\n :align :center\n :children [[label\n :style {:font-size \"smaller\"}\n :label (day days-map)]\n [checkbox\n :model (@enabled-days day)\n :on-change #(toggle-inclusion! enabled-days day)]]])\n\n(defn- parameters-with\n \"Toggle controls for some parameters.\"\n [content enabled-days disabled? show-today? show-weeks?]\n [v-box\n :gap \"15px\"\n :align :start\n :children [[gap :size \"20px\"]\n [title :level :level3 :label \"Parameters\"]\n [h-box\n :gap \"20px\"\n :align :start\n :children [[checkbox\n :label [box :align :start :child [:code \":disabled?\"]]\n :model disabled?\n :on-change #(reset! disabled? %)]\n [checkbox\n :label [box :align :start :child [:code \":show-today?\"]]\n :model show-today?\n :on-change #(reset! show-today? %)]\n [checkbox\n :label [box :align :start :child [:code \":show-weeks?\"]]\n :model show-weeks?\n :on-change #(reset! show-weeks? %)]]]\n [h-box\n :gap \"2px\"\n :align :center\n :children [[checkbox-for-day :Su enabled-days]\n [checkbox-for-day :Mo enabled-days]\n [checkbox-for-day :Tu enabled-days]\n [checkbox-for-day :We enabled-days]\n [checkbox-for-day :Th enabled-days]\n [checkbox-for-day :Fr enabled-days]\n [checkbox-for-day :Sa enabled-days]\n [gap :size \"5px\"]\n [box :align :start :child [:code \":selectable-fn\"]]]]\n [:span [:code \"e.g. (fn [date] (#{1 2 3 4 5 6 7} (day-of-week date)))\"]]\n content]])\n\n\n(defn- date->string\n [date]\n (if (date-like? date)\n (unparse (formatter \"dd MMM, yyyy\") date)\n \"no date\"))\n\n\n(defn- show-variant\n [variation]\n (let [model1 (reagent\/atom #_nil #_(today) (now->utc)) ;; Test 3 valid data types\n model2 (reagent\/atom #_nil #_(plus (today) (days 120)) (plus (now->utc) (days 120))) ;; (today) = goog.date.Date, (now->utc) = goog.date.UtcDateTime\n model3 (reagent\/atom nil)\n disabled? (reagent\/atom false)\n show-today? (reagent\/atom true)\n show-weeks? (reagent\/atom false)\n enabled-days (reagent\/atom (-> days-map keys set))\n as-days (reaction (-> (map #(% {:Su 7 :Sa 6 :Fr 5 :Th 4 :We 3 :Tu 2 :Mo 1}) @enabled-days) set))\n selectable-pred (fn [date] (@as-days (day-of-week date))) ; Simply allow selection based on day of week.\n label-style {:font-style \"italic\" :font-size \"smaller\" :color \"#777\"}]\n (case variation\n :inline [(fn inline-fn\n []\n [parameters-with\n [h-box\n :gap \"20px\"\n :align :start\n :children [[v-box\n :gap \"5px\"\n :children [[label\n :style label-style\n :label [:span \" :maximum - \" (date->string @model2) [:br] \":start-of-week - Sunday\"]]\n [datepicker\n :model model1\n :maximum model2\n :disabled? disabled?\n :show-today? @show-today?\n :show-weeks? @show-weeks?\n :selectable-fn selectable-pred\n :on-change #(do #_(js\/console.log \"model1:\" %) (reset! model1 %))]\n [label :style label-style :label (str \"selected: \" (date->string @model1))]\n [h-box\n :gap \"6px\"\n :margin \"10px 0px 0px 0px\"\n :align :center\n :children [[label :style label-style :label \"Change model:\"]\n [md-icon-button\n :md-icon-name \"zmdi-arrow-left\"\n :size :smaller\n :disabled? (not (date-like? @model1))\n :on-click #(when (date-like? @model1)\n (reset! model1 (minus @model1 (days 1))))]\n [md-icon-button\n :md-icon-name \"zmdi-arrow-right\"\n :size :smaller\n :disabled? (if (and (date-like? @model1) (date-like? @model2))\n (not (before? (to-local-date @model1)\n (to-local-date @model2)))\n true)\n :on-click #(when (date-like? @model1)\n (reset! model1 (plus @model1 (days 1))))]\n [button\n :label \"Reset\"\n :class \"btn btn-default\"\n :style {:padding \"1px 4px\"}\n :on-click #(reset! model1 nil)]]]]]\n\n [v-box\n :gap \"5px\"\n :children [[label\n :style label-style\n :label [:span \":minimum - \" (date->string @model1) [:br] \":start-of-week - Monday\"]]\n [datepicker\n :start-of-week 0\n :model model2\n :minimum model1\n :show-today? @show-today?\n :show-weeks? @show-weeks?\n :selectable-fn selectable-pred\n :disabled? disabled?\n :on-change #(do #_(js\/console.log \"model2\" %) (reset! model2 %))]\n [label :style label-style :label (str \"selected: \" (date->string @model2))]]]]]\n enabled-days\n disabled?\n show-today?\n show-weeks?])]\n :dropdown [(fn dropdown-fn\n []\n [parameters-with\n [h-box\n :size \"auto\"\n :align :start\n :children [[gap :size \"120px\"]\n [datepicker-dropdown\n :model model3\n :show-today? @show-today?\n :show-weeks? @show-weeks?\n :selectable-fn selectable-pred\n :placeholder \"Select a date\"\n :format \"dd MMM, yyyy\"\n :disabled? disabled?\n :on-change #(reset! model3 %)]]]\n enabled-days\n disabled?\n show-today?\n show-weeks?])])))\n\n\n(def variations ^:private\n [{:id :inline :label \"Inline\"}\n {:id :dropdown :label \"Dropdown\"}])\n\n\n(defn datepicker-examples\n []\n (let [selected-variation (reagent\/atom :inline)]\n (fn examples-fn []\n [v-box\n :size \"auto\"\n :gap \"10px\"\n :children [[panel-title \"Date Components\"\n \"src\/re_com\/datepicker.cljs\"\n \"src\/re_demo\/datepicker.cljs\"]\n [h-box\n :gap \"100px\"\n :children [[v-box\n :gap \"10px\"\n :width \"450px\"\n :children [[title2 \"[datepicker ... ] & [datepicker-dropdown ... ]\" {:font-size \"24px\"}]\n [status-text \"Stable\"]\n [p \"An inline or popover date picker component.\"]\n [args-table datepicker-dropdown-args-desc]]]\n [v-box\n :gap \"10px\"\n :size \"auto\"\n :children [[title2 \"Demo\"]\n [h-box\n :gap \"10px\"\n :align :center\n :children [[label :label \"Select a demo\"]\n [single-dropdown\n :choices variations\n :model selected-variation\n :width \"200px\"\n :on-change #(reset! selected-variation %)]]]\n [show-variant @selected-variation]]]]]]])))\n\n\n;; core holds a reference to panel, so need one level of indirection to get figwheel updates\n(defn panel\n []\n [datepicker-examples])\n","avg_line_length":51.4541484716,"max_line_length":170,"alphanum_fraction":0.3628956972} {"size":14102,"ext":"clj","lang":"Clojure","max_stars_count":14.0,"content":"(ns puppetlabs.stockpile.queue\n (:refer-clojure :exclude [reduce])\n (:require\n [puppetlabs.i18n.core :refer [trs]])\n (:import\n [clojure.lang BigInt]\n [java.io ByteArrayInputStream File FileOutputStream InputStream]\n [java.nio.file AtomicMoveNotSupportedException DirectoryStream\n FileSystemException NoSuchFileException Path Paths]\n [java.nio.channels FileChannel]\n [java.nio.file FileAlreadyExistsException Files OpenOption StandardCopyOption]\n [java.nio.file.attribute FileAttribute]\n [java.util.concurrent.atomic AtomicLong]))\n\n;; Queue structure:\n;; - qdir\/stockpile\n;; - qdir\/q\/INTEGER # message\n;; - qdir\/q\/INTEGER-ENCODED_METADATA # message\n;; - qdir\/q\/tmp-BLARG # pending message\n\n(defn- basename [^Path path]\n (.getName path (dec (.getNameCount path))))\n\n(defn ^Path path-get [^String s & more-strings]\n (Paths\/get s (into-array String more-strings)))\n\n(defn- parse-integer [x]\n (try\n (Long\/parseLong x)\n (catch NumberFormatException ex\n nil)))\n\n(defprotocol AsPath\n (as-path ^Path [x]))\n\n(extend-protocol AsPath\n Path\n (as-path [x] x)\n String\n (as-path [x] (path-get x))\n File\n (as-path [x] (.toPath x)))\n\n(defprotocol Entry\n (entry-id [entry])\n (entry-meta [entry]))\n\n(defrecord MetaEntry [id metadata]\n Entry\n (entry-id [this] id)\n (entry-meta [this] metadata))\n\n(extend-protocol Entry\n Long\n (entry-id [this] this)\n (entry-meta [this] nil))\n\n(defn- create-tmp-file [parent]\n ;; Don't change the prefix\/suffix here casually. Other\n ;; code below assumes, for example, that a temporary file will never\n ;; be named \"stockpile\".\n (Files\/createTempFile (as-path parent) \"tmp-\" \"\"\n (into-array FileAttribute [])))\n\n(defn fsync [x metadata?]\n (with-open [fc (FileChannel\/open (as-path x)\n (into-array OpenOption []))]\n (.force fc metadata?)))\n\n(def ^:private copt-atomic StandardCopyOption\/ATOMIC_MOVE)\n(def ^:private copt-replace StandardCopyOption\/REPLACE_EXISTING)\n(def ^:private copts-type (class (into-array StandardCopyOption [])))\n\n(defn ^copts-type copts [opts]\n (into-array StandardCopyOption opts))\n\n(defn- atomic-move [src dest]\n (Files\/move (as-path src) (as-path dest)\n (copts [copt-atomic])))\n\n(defn- rename-durably\n \"If possible, atomically renames src to dest (each of which may be a\n File, Path, or String). If dest already exists, on some platforms\n the replacement will succeed, and on others it will throw an\n IOException. The rename may also fail with\n AtomicMoveNotSupportedException (perhaps if src and dest are on\n different filesystems). See java.nio.file.Files\/move for additional\n information. fsyncs the dest parent directory to make the final\n rename durable unless sync-parent? is false (presumably the caller\n will ensure the sync).\"\n [src dest sync-parent?]\n (atomic-move src dest)\n (when sync-parent?\n (fsync (.getParent (as-path dest)) true)))\n\n(defn- delete-if-exists [path]\n ;; Solely exists for error handling tests\n (Files\/deleteIfExists path))\n\n(defn- write-stream [^InputStream stream ^Path dest]\n ;; Solely exists for error handling tests\n (Files\/copy stream dest (copts [copt-replace])))\n\n(defn- qpath ^Path [{:keys [^Path directory] :as q}]\n (.resolve directory \"q\"))\n\n(defn- queue-entry-path\n [q id metadata]\n (let [^Path parent (qpath q)\n ^String entry-name (apply str id (when metadata [\"-\" metadata]))]\n (.resolve parent entry-name)))\n\n(defn- entry-path\n [q entry]\n (queue-entry-path q (entry-id entry) (entry-meta entry)))\n\n(defn- filename->entry\n \"Returns an entry if name can be parsed as such, i.e. either as\n an integer or integer-metadata, nil otherwise.\"\n [^String name]\n (let [dash (.indexOf name (int \\-))]\n (if (= -1 dash)\n (parse-integer name)\n ;; Perhaps it has metadata\n (when-let [id (parse-integer (subs name 0 dash))]\n (->MetaEntry id (subs name (inc dash)))))))\n\n(defrecord Stockpile [directory next-likely-id])\n\n(defn- reduce-paths\n [f val ^DirectoryStream dirstream]\n (with-open [_ dirstream]\n (clojure.core\/reduce f val (-> dirstream .iterator iterator-seq))))\n\n(defn- plausible-prefix?\n [s]\n (-> #\"^[0-9](?:-.)?+\" (.matcher s) .find))\n\n\n;;; Stable, public interface\n\n(defn entry [id metadata]\n (let [id (if (integer? id)\n (long id)\n (throw\n (IllegalArgumentException.\n (trs \"id is not an integer: {0}\" id))))]\n (cond\n (nil? metadata) id\n\n (not (string? metadata))\n (throw\n (IllegalArgumentException.\n (trs \"metadata is not a string: {0}\" (pr-str metadata))))\n\n :else (->MetaEntry id metadata))))\n\n(defn next-likely-id\n \"Returns a likely id for the next message stored in the q. No\n subsequent entry ids will be less than this value.\"\n [{^AtomicLong next :next-likely-id :as q}]\n (.get next))\n\n(defn create\n \"Creates a new queue in directory, which must not exist, and returns\n the queue. If an exception is thrown, the directory named may or\n may not exist and may or may not be empty.\"\n [directory]\n (let [top (as-path directory)\n q (.resolve top \"q\")]\n (Files\/createDirectory top (into-array FileAttribute []))\n (Files\/createDirectory q (into-array FileAttribute []))\n ;; This sentinel is last - indicates the queue is *ready*\n (let [tmp (create-tmp-file top)]\n (with-open [out (FileOutputStream. (.toFile tmp))]\n (.write out (.getBytes \"0 stockpile\" \"UTF-8\")))\n (fsync tmp false)\n (rename-durably tmp (.resolve top \"stockpile\") false))\n (fsync top true)\n (->Stockpile top (AtomicLong. 0))))\n\n(defn open\n \"Opens the queue in directory, and returns it. Expects only\n stockpile created files in the directory, and currently deletes any\n existing file in the queue whose name starts with \\\"tmp-\\\".\"\n [directory]\n (let [top (as-path directory)\n q (.resolve top \"q\")]\n (let [info-file (.resolve top \"stockpile\")\n info (String. (Files\/readAllBytes info-file) \"UTF-8\")]\n (when-not (= \"0 stockpile\" info)\n (throw (IllegalStateException.\n (trs \"Invalid queue token {0} found in {1}\"\n (pr-str info)\n (pr-str (str info-file)))))))\n (let [max-id (reduce-paths (fn [result ^Path p]\n (let [name (str (basename p))]\n (cond\n (.startsWith name \"tmp-\")\n (do (Files\/deleteIfExists p) result)\n\n (plausible-prefix? name)\n (max result (-> name\n filename->entry\n entry-id))\n \n :else\n result)))\n 0\n (Files\/newDirectoryStream q))]\n (->Stockpile top (AtomicLong. (inc max-id))))))\n\n(defn reduce\n \"Calls (f reduction entry) for each existing entry as-per reduce,\n with val as the initial reduction, and returns the result. The\n ordering of the calls is unspecified, as is the effect of concurrent\n discards. The reduction may be escaped by throwing a unique\n exception (cf. slingshot). For example: (reduce \\\"foo\\\" conj []).\"\n [q f val]\n (reduce-paths (fn [result ^Path p]\n (let [name (-> p basename str)]\n (if-not (plausible-prefix? name)\n result\n (f result (filename->entry name)))))\n val\n (Files\/newDirectoryStream (qpath q))))\n\n(defn store\n \"Atomically and durably enqueues the content of stream, and returns\n an entry that can be used to refer to the content later. An ex-info\n exception of {:kind ::unable-to-commit :stream-data path} may be\n thrown if store was able to read the data from the stream, but\n unable to make it durable. If any other exception is thrown, the\n state of the stream is unknown. The :stream-data value will be a\n path to a file containing all of the data that was in the stream.\n Among other things, it's possible that ::unable-to-commit indicates\n the metadata was incompatible with the underlying filesystem (it was\n too long, couldn't be encoded, etc.). That's because the current\n implementation records the metadata in a file name corresponding to\n the entry, and may use up to 20 (Unicode Basic Latin block)\n characters of that file name for internal purposes. The remainder\n of the filename is available for the metadata, but the maximum\n length of that remainder depends on the platform and target\n filesystem. Many common filesystems now allow a file name to be up\n to 255 characters or bytes, and at least on Linux, the JVM converts\n the Unicode string path to a filesystem path using an encoding that\n depends on the locale, often choosing UTF-8. So assuming a UTF-8\n encoding and a 255 byte maximum path length (e.g. ext4), after\n subtracting the 20 (UTF-8 encoded Basic Latin block) bytes reserved\n for internal use, there may be up to 235 bytes available for the\n metadata. Of course how many Unicode characters that will allow\n depends on their size when converted to UTF-8. Whenever there's an\n error, it's possible that the attempt to clean up may fail and leave\n behind a temporary file. In that case create throws an ex-info\n exception of {:kind ::path-cleanup-failure-after-error :path\n p :exception ex} with the exception produced by the original failure\n as the cause. To handle that possibility, callers may want to\n structure invocations with a nested try like this:\n (try\n (try+\n (stock\/create ...)\n (catch [:kind ::path-cleanup-failure-after-error]\n {:keys [path exception]}\n ;; Perhaps log or try to clean up the path more aggressively\n (throw (:cause &throw-context)))\n (catch SomeExceptionThatCausedCreateToFail\n ;; Reached for this exception whether or not there was a\n ;; cleanup failure\n ...)\n ...)\n Additionally, among other exceptions, the current implementation may\n throw any documented by java.nio.file.Files\/move for an ATOMIC_MOVE\n within the same directory.\"\n ([q stream] (store q stream nil))\n ([q ^ByteArrayInputStream stream metadata]\n (let [^AtomicLong next (:next-likely-id q)\n qd (qpath q)]\n (let [^Path tmp-dest (create-tmp-file qd)]\n ;; It might be possible to optimize some cases with\n ;; transferFrom\/transferTo eventually.\n (try\n (write-stream stream tmp-dest)\n (catch Exception ex\n (try\n (delete-if-exists tmp-dest)\n (catch Exception del-ex\n (throw\n (ex-info (trs \"unable to delete temp file {0} after error\"\n (pr-str (str tmp-dest)))\n {:kind ::path-cleanup-failure-after-error\n :path tmp-dest\n :exception del-ex}\n ex))))\n (throw ex)))\n (try\n (fsync tmp-dest false)\n (loop []\n (let [id (.getAndIncrement next)\n target (queue-entry-path q id metadata)\n ;; Can't recur from catch\n moved? (try\n (rename-durably tmp-dest target true)\n true\n (catch FileAlreadyExistsException ex\n false))]\n (if moved?\n (entry id metadata)\n (recur))))\n (catch Exception ex\n (throw (ex-info (trs \"unable to commit; leaving stream data in {0}\"\n (pr-str (str tmp-dest)))\n {:kind ::unable-to-commit\n :stream-data tmp-dest}\n ex))))))))\n\n(defn stream\n \"Returns an unbuffered stream of the entry's data. Throws an\n ex-info exception of {:kind ::no-such-entry :entry e :source s} if\n the requested entry does not exist. Currently the :source will\n always be a Path.\"\n [q entry]\n (let [path (entry-path q entry)]\n (try\n (Files\/newInputStream path (make-array OpenOption 0))\n (catch NoSuchFileException ex\n (let [m (entry-meta entry)\n id (entry-id entry)]\n (throw (ex-info (trs \"No file found for entry {0} at {1}\"\n (if-not m id (pr-str [id m]))\n (pr-str (str path)))\n {:kind ::no-such-entry :entry entry :source path}\n ex)))))))\n\n(defn discard\n \"Atomically and durably discards the entry (returned by store) from\n the queue. The discarded data will be placed at the destination\n path (durably if possible), when one is provided. This should be\n much more efficient, and likely safer if the destination is at least\n on the same filesystem as the queue. The results of calling this\n more than once for a given entry are undefined.\"\n ;; Not entirely certain the queue parent dir syncs are necessary *if*\n ;; everyone guarantees that you either see the file or not, and if\n ;; we're OK with the possibility of spurious redelivery.\n ([q entry]\n (Files\/deleteIfExists (entry-path q entry))\n (fsync (qpath q) true))\n ([q entry destination]\n (let [^Path src (entry-path q entry)\n ^Path destination (as-path destination)\n moved? (try\n (Files\/move src destination (copts [copt-atomic]))\n true\n (catch UnsupportedOperationException ex\n false)\n (catch AtomicMoveNotSupportedException ex\n false))]\n (when-not moved?\n (Files\/copy src destination (copts [copt-replace]))\n (Files\/delete src))\n (fsync (.getParent destination) true)\n (fsync (qpath q) true))))\n","avg_line_length":38.955801105,"max_line_length":81,"alphanum_fraction":0.6114735499} {"size":1546,"ext":"cljs","lang":"Clojure","max_stars_count":null,"content":"(ns example.core\n (:require [reagent.core :as reagent :refer [atom]]\n [secretary.core :as secretary :include-macros true]\n [goog.events :as events]\n [goog.history.EventType :as EventType])\n (:import goog.History))\n\n;; -------------------------\n;; State\n(defonce app-state (atom {:text \"Hello, this is: \"}))\n\n(defn get-state [k & [default]]\n (clojure.core\/get @app-state k default))\n\n(defn put! [k v]\n (swap! app-state assoc k v))\n\n;; -------------------------\n;; Views\n\n(defmulti page identity)\n\n(defmethod page :page1 [_]\n [:div [:h2 (get-state :text) \"Page 1\"]\n [:div [:a {:href \"#\/page2\"} \"go to page 2\"]]])\n\n(defmethod page :page2 [_]\n [:div [:h2 (get-state :text) \"Page 2\"]\n [:div [:a {:href \"#\/\"} \"go to page 1\"]]])\n\n(defmethod page :default [_]\n [:div \"Invalid\/Unknown route\"])\n\n(defn main-page []\n [:div [page (get-state :current-page)]])\n\n;; -------------------------\n;; Routes\n(secretary\/set-config! :prefix \"#\")\n\n(secretary\/defroute \"\/\" []\n (put! :current-page :page1))\n\n(secretary\/defroute \"\/page2\" []\n (put! :current-page :page2))\n\n;; -------------------------\n;; Initialize app\n(defn init! []\n (reagent\/render-component [main-page] (.getElementById js\/document \"app\")))\n\n;; -------------------------\n;; History\n(defn hook-browser-navigation! []\n (doto (History.)\n (events\/listen\n EventType\/NAVIGATE\n (fn [event]\n (secretary\/dispatch! (.-token event))))\n (.setEnabled true)))\n;; need to run this after routes have been defined\n(hook-browser-navigation!)\n","avg_line_length":24.5396825397,"max_line_length":77,"alphanum_fraction":0.5595084088} {"size":5202,"ext":"clj","lang":"Clojure","max_stars_count":14.0,"content":"; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distribution terms for this software are covered by the\n; Eclipse Public License 1.0 (http:\/\/opensource.org\/licenses\/eclipse-1.0.php)\n; which can be found in the file epl-v10.html at the root of this distribution.\n; By using this software in any fashion, you are agreeing to be bound by\n; the terms of this license.\n; You must not remove this notice, or any other, from this software.\n\n(ns \n ^{:author \"Chris Houser, Stuart Halloway\",\n :doc \"Conveniently launch a sub-process providing its stdin and\ncollecting its stdout\"}\n clojure.java.shell\n (:use [clojure.java.io :only (as-file copy)])\n (:import (java.io ByteArrayOutputStream StringWriter)\n (java.nio.charset Charset)))\n\n(def ^:dynamic *sh-dir* nil)\n(def ^:dynamic *sh-env* nil)\n\n(defmacro with-sh-dir\n \"Sets the directory for use with sh, see sh for details.\"\n {:added \"1.2\"}\n [dir & forms]\n `(binding [*sh-dir* ~dir]\n ~@forms))\n\n(defmacro with-sh-env\n \"Sets the environment for use with sh, see sh for details.\"\n {:added \"1.2\"}\n [env & forms]\n `(binding [*sh-env* ~env]\n ~@forms))\n \n(defn- aconcat\n \"Concatenates arrays of given type.\"\n [type & xs]\n (let [target (make-array type (apply + (map count xs)))]\n (loop [i 0 idx 0]\n (when-let [a (nth xs i nil)]\n (System\/arraycopy a 0 target idx (count a))\n (recur (inc i) (+ idx (count a)))))\n target))\n\n(defn- parse-args\n [args]\n (let [default-encoding \"UTF-8\" ;; see sh doc string\n default-opts {:out-enc default-encoding :in-enc default-encoding :dir *sh-dir* :env *sh-env*}\n [cmd opts] (split-with string? args)]\n [cmd (merge default-opts (apply hash-map opts))]))\n\n(defn- ^\"[Ljava.lang.String;\" as-env-strings \n \"Helper so that callers can pass a Clojure map for the :env to sh.\"\n [arg]\n (cond\n (nil? arg) nil\n (map? arg) (into-array String (map (fn [[k v]] (str (name k) \"=\" v)) arg))\n true arg))\n\n(defn- stream-to-bytes\n [in]\n (with-open [bout (ByteArrayOutputStream.)]\n (copy in bout)\n (.toByteArray bout)))\n\n(defn- stream-to-string\n ([in] (stream-to-string in (.name (Charset\/defaultCharset))))\n ([in enc]\n (with-open [bout (StringWriter.)]\n (copy in bout :encoding enc)\n (.toString bout))))\n\n(defn- stream-to-enc\n [stream enc]\n (if (= enc :bytes)\n (stream-to-bytes stream)\n (stream-to-string stream enc)))\n\n(defn sh\n \"Passes the given strings to Runtime.exec() to launch a sub-process.\n\n Options are\n\n :in may be given followed by any legal input source for\n clojure.java.io\/copy, e.g. InputStream, Reader, File, byte[],\n or String, to be fed to the sub-process's stdin.\n :in-enc option may be given followed by a String, used as a character\n encoding name (for example \\\"UTF-8\\\" or \\\"ISO-8859-1\\\") to\n convert the input string specified by the :in option to the\n sub-process's stdin. Defaults to UTF-8.\n If the :in option provides a byte array, then the bytes are passed\n unencoded, and this option is ignored.\n :out-enc option may be given followed by :bytes or a String. If a\n String is given, it will be used as a character encoding\n name (for example \\\"UTF-8\\\" or \\\"ISO-8859-1\\\") to convert\n the sub-process's stdout to a String which is returned.\n If :bytes is given, the sub-process's stdout will be stored\n in a byte array and returned. Defaults to UTF-8.\n :env override the process env with a map (or the underlying Java\n String[] if you are a masochist).\n :dir override the process dir with a String or java.io.File.\n\n You can bind :env or :dir for multiple operations using with-sh-env\n and with-sh-dir.\n\n sh returns a map of\n :exit => sub-process's exit code\n :out => sub-process's stdout (as byte[] or String)\n :err => sub-process's stderr (String via platform default encoding)\"\n {:added \"1.2\"}\n [& args]\n (let [[cmd opts] (parse-args args)\n proc (.exec (Runtime\/getRuntime) \n ^\"[Ljava.lang.String;\" (into-array cmd)\n (as-env-strings (:env opts))\n (as-file (:dir opts)))\n {:keys [in in-enc out-enc]} opts]\n (if in\n (future\n (with-open [os (.getOutputStream proc)]\n (copy in os :encoding in-enc)))\n (.close (.getOutputStream proc)))\n (with-open [stdout (.getInputStream proc)\n stderr (.getErrorStream proc)]\n (let [out (future (stream-to-enc stdout out-enc))\n err (future (stream-to-string stderr))\n exit-code (.waitFor proc)]\n {:exit exit-code :out @out :err @err}))))\n\n(comment\n\n(println (sh \"ls\" \"-l\"))\n(println (sh \"ls\" \"-l\" \"\/no-such-thing\"))\n(println (sh \"sed\" \"s\/[aeiou]\/oo\/g\" :in \"hello there\\n\"))\n(println (sh \"sed\" \"s\/[aeiou]\/oo\/g\" :in (java.io.StringReader. \"hello there\\n\")))\n(println (sh \"cat\" :in \"x\\u25bax\\n\"))\n(println (sh \"echo\" \"x\\u25bax\"))\n(println (sh \"echo\" \"x\\u25bax\" :out-enc \"ISO-8859-1\")) ; reads 4 single-byte chars\n(println (sh \"cat\" \"myimage.png\" :out-enc :bytes)) ; reads binary file into bytes[]\n(println (sh \"cmd\" \"\/c dir 1>&2\"))\n\n)\n","avg_line_length":36.3776223776,"max_line_length":101,"alphanum_fraction":0.6257208766} {"size":649,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns dev.codecarver.domain.entities.article\n (:require [validateur.validation :refer [validation-set\n presence-of\n length-of]])\n (:require [dev.codecarver.domain.util.util :as util]))\n\n(defrecord Article [id title body created updated url repository-url publish? article-id])\n\n(def ^:private validator (validation-set\n (presence-of :title)\n (presence-of :body)\n (length-of :title :within (range 10 51))))\n\n(defn validate [options]\n (util\/validate (merge options {:validator validator})))\n","avg_line_length":40.5625,"max_line_length":90,"alphanum_fraction":0.5577812018} {"size":400,"ext":"clj","lang":"Clojure","max_stars_count":1.0,"content":"(ns girajira.infra.events.datetime-test\n (:require [midje.sweet :refer :all]\n [girajira.infra.events.datetime :refer :all]\n [clj-time.core :as clj-time]))\n\n(facts \"when calculating today's date\"\n (fact \"it returns a string representation of today's date\"\n (today) => \"2018-12-01T14:00:00.000\"\n (provided\n (clj-time\/now) => (clj-time\/date-time 2018 12 01 14 0 0))))\n","avg_line_length":36.3636363636,"max_line_length":65,"alphanum_fraction":0.6425} {"size":258,"ext":"clj","lang":"Clojure","max_stars_count":null,"content":"(ns achord.routes\n (:use [compojure.core :only [defroutes]])\n (:require [compojure.route :as route]\n [achord.routers.index :as index]))\n\n(defroutes all-routes\n index\/routes\n (route\/not-found \"

Page not found.<\/p>\")) ;; all other, return 404\n","avg_line_length":28.6666666667,"max_line_length":70,"alphanum_fraction":0.6550387597} {"size":13382,"ext":"cljc","lang":"Clojure","max_stars_count":null,"content":"(ns hyjinks.core\n (:require [clojure.string :refer [escape split join capitalize lower-case trim index-of]]\n [hyjinks.macros #?(:clj :refer :cljs :refer-macros) [deftag deftags extend-type-ifn defrecord-ifn]]))\n\n;; Forward definitions to resolve circular references\n\n(declare tag?)\n(declare extend-tag)\n\n;; General helpers\n\n(defn- prune-map [m]\n (let [rem? #(or (nil? %) (= \"\" %) (and (coll? %) (empty? %)))]\n (apply dissoc m (map first (filter (comp rem? second) m)))))\n\n(defn- str-join [& items] (join (flatten items)))\n\n(defn- interposep [sep pred [x & [y :as more] :as coll]]\n (cond\n (empty? coll) (empty coll)\n (= 1 (count coll)) coll\n (pred x y) (concat [x sep] (interposep sep pred more))\n :else (concat [x] (interposep sep pred more))))\n\n(defn- str-join-extra-spaces [& items]\n (->> items\n flatten\n (interposep \" \" #(not (or (tag? %1) (tag? %2))))\n (apply str)))\n\n(defn- starts-with [prefix s] (= prefix (subs s 0 (#?(:clj .length :cljs .-length) prefix))))\n\n(def ^{:private true} escape-chars {\n \\< \"<\"\n \\> \">\"\n \\& \"&\"\n \\\" \""\"\n \\' \"'\"})\n\n(defn- html-escape [x]\n (if (string? x)\n (escape x escape-chars)\n x))\n\n(defn- split-selector [s]\n (if (not= s \"\")\n (let [i (index-of s \".\" 1)\n j (index-of s \"#\" 1)\n k (cond\n (not (or i j)) nil\n (not i) j\n (not j) i\n (< j i) j\n (< i j) i)]\n (if k\n (cons (subs s 0 k) (split-selector (subs s k)))\n (cons s nil)))))\n\n(defn- parse-selector [selector]\n (let [selector-parts (split-selector (name selector))\n tag-name (first (filter #(not (or (starts-with \"#\" %) (starts-with \".\" %))) selector-parts))\n id-clause (first (filter (partial starts-with \"#\") selector-parts))\n class-clauses (filter (partial starts-with \".\") selector-parts)]\n {:tag-name (or tag-name \"div\")\n :id (if id-clause (subs id-clause 1))\n :class-names (mapv #(subs % 1) class-clauses)}))\n\n(defn tag->string\n \"Serializes a tag and its children into an HTML string.\"\n [{:keys [tag-name attrs css r-opts items]}]\n (let [{css-class :class} attrs\n attrs (if (sequential? css-class) (assoc attrs :class (join \" \" css-class)) attrs)\n attrs+css (if (empty? css) attrs (assoc attrs :style (str css)))\n escape-child (if (:no-escape r-opts) identity html-escape)\n child-join (if (:pad-children r-opts) str-join-extra-spaces str-join)]\n (str-join\n (if (= tag-name \"html\") \"\")\n \"<\" tag-name attrs+css\n (if (:void-element r-opts)\n \">\"\n [\">\" (child-join (map escape-child items)) \"<\/\" tag-name \">\"]))))\n\n(defn tag->hiccup\n \"Translates a tag to the nested-vector representation used by hiccup.\"\n [{:keys [tag-name attrs css r-opts items]}]\n (let [{css-class :class} attrs\n attrs (if (sequential? css-class) (assoc attrs :class (join \" \" css-class)) attrs)\n attrs+css (if (empty? css) attrs (assoc attrs :style (str css)))\n escape-child (if (:no-escape r-opts) identity html-escape)\n child-join (if (:pad-children r-opts) str-join-extra-spaces str-join)]\n (vec\n (concat\n (if (empty? attrs+css)\n [(keyword tag-name)]\n [(keyword tag-name) (into {} attrs+css)])\n (map #(if (tag? %) (tag->hiccup %) %) items)))))\n\n;; Core types\n\n(defrecord Literal [s]\n #?(:clj java.lang.Object :cljs Object)\n (toString [_] s))\n\n(defrecord Comment [content]\n #?(:clj java.lang.Object :cljs Object)\n (toString [_] (str \"\")))\n\n(defrecord RenderOptions []\n #?(:clj java.lang.Object :cljs Object)\n (toString [this]\n (str-join (filter (fn [[k v]] (if v [k v])) this))))\n\n(defrecord Attrs []\n #?(:clj java.lang.Object :cljs Object)\n (toString [this]\n (str-join (map (fn [[k v]] [\" \" (name k) \"=\\\"\" (html-escape v) \"\\\"\"]) this)))\n #?@(:clj [\n clojure.lang.IFn\n (invoke [this] this)\n (invoke [this t] (extend-tag t this))\n (applyTo [this args] (extend-tag (first args) this))]))\n\n(defrecord Css []\n #?(:clj java.lang.Object :cljs Object)\n (toString [this]\n (str-join (map (fn [[k v]] [\"; \" (name k) \": \" v]) this) \";\"))\n #?@(:clj [\n clojure.lang.IFn\n (invoke [this] this)\n (invoke [this t] (extend-tag t this))\n (applyTo [this args] ((first args) this))]))\n\n(#?(:clj defrecord-ifn :cljs defrecord) Tag [tag-name attrs css items r-opts]\n #?(:clj java.lang.Object :cljs Object)\n (toString [this] (tag->string this)))\n\n(do #?@(\n :cljs\n [(extend-type Attrs\n cljs.core\/IFn\n (-invoke\n ([this] this)\n ([this t] (extend-tag t this))))\n (extend-type Css\n cljs.core\/IFn\n (-invoke\n ([this] this)\n ([this t] (extend-tag t this))))\n (extend-type-ifn Tag)]))\n\n;; Builder functions\n\n(defn literal?\n \"Checks if argument is a Literal and will be passed\n through rendering without being escaped or encoded.\"\n [x]\n (instance? Literal x))\n\n(defn comment?\n \"Checks if argument is an HTML Comment.\"\n [x]\n (instance? Comment x))\n\n(defn tag?\n \"Checks if argument is a Tag.\"\n [x]\n (instance? Tag x))\n\n(defn css?\n \"Checks if argument is a collection of CSS attributes.\"\n [x]\n (instance? Css x))\n\n(defn attrs?\n \"Checks if argument is a collection of HTML attributes.\"\n [x]\n (instance? Attrs x))\n\n(defn r-opts?\n \"Checks if argument is a collection of Rendering Options.\"\n [x]\n (instance? RenderOptions x))\n\n(defn- attrs-or-map? [x] (or (attrs? x) (and (map? x) (not (record? x)))))\n\n(defn- child-item? [x] (not (or (attrs-or-map? x) (css? x) (r-opts? x) (nil? x) (= \"\" x))))\n\n(defn- join-class-names [x]\n (if (sequential? x)\n (->> x\n (filter identity)\n (map trim)\n (join \" \"))\n x))\n\n(defn- merge-attrs [xs ys]\n (let [m (merge xs ys)\n cs0 (join-class-names (:class xs))\n cs1 (join-class-names (:class ys))]\n (assoc m :class\n (if (and cs0 cs1)\n (str cs0 \" \" cs1)\n (join-class-names (:class m))))))\n\n(defn- extend-attrs [attrs more] (prune-map (reduce merge-attrs attrs more)))\n\n(defn- extend-css [css more] (prune-map (apply merge css more)))\n\n(defn- extend-r-opts [r-opts more] (prune-map (apply merge r-opts more)))\n\n(defn- extend-items [items more] (vec (flatten (concat items more))))\n\n(defn attrs\n \"Creates a new collection of HTML Attributes from the given\n sequence of key-values.\"\n [& {:as key-vals}]\n (extend-attrs (Attrs.) key-vals))\n\n(defn css\n \"Creates a new collection of CSS Attributes from the given\n sequence of key-values.\"\n [& {:as key-vals}]\n (extend-css (Css.) key-vals))\n\n(defn- r-opts [& {:as key-vals}] (extend-r-opts (RenderOptions.) key-vals))\n\n(defn tag\n \"Creates a new Tag with the given child tags, HTML Attributes,\n CSS Attributes and Rendering Options. Tag name argument can\n use CSS selector syntax to provide an id and CSS class names\n in addition to a tag name.\"\n [selector & stuff]\n (let [stuff (flatten stuff)\n {:keys [tag-name id class-names]} (parse-selector selector)\n attrs (extend-attrs\n (Attrs.)\n (conj\n (filter attrs-or-map? stuff)\n (if id {:id id})\n (if (seq class-names) {:class class-names})))\n css (extend-css (Css.) (filter css? stuff))\n r-opts (extend-r-opts (RenderOptions.) (filter r-opts? stuff))\n items (extend-items [] (filter child-item? stuff))]\n (Tag. tag-name attrs css items r-opts)))\n\n(defn extend-tag\n \"Merges a tag with additional child tags, HTML Attributes,\n CSS Attributes and Rendering Options.\"\n [{:keys [tag-name attrs css r-opts items] :as t} & stuff]\n (let [stuff (flatten stuff)]\n (if (empty? stuff)\n t\n (let [attrs (extend-attrs attrs (filter attrs-or-map? stuff))\n css (extend-css css (filter css? stuff))\n r-opts (extend-r-opts r-opts (filter r-opts? stuff))\n items (extend-items items (filter child-item? stuff))]\n (Tag. tag-name attrs css items r-opts)))))\n\n(defn literal\n \"Creates a new Literal that will be passed through rendering without\n being escaped or encoded. It adds no additional space between arguments.\"\n [& content]\n (Literal. (str-join content)))\n\n;; Declaring rendering options\n\n(def void-element\n \"Indicates that this tag cannot have children and will\n be rendered ending with \/> instead of a closing tag.\"\n (r-opts :void-element true))\n\n(def no-escape\n \"Prevents (tag->string) from escaping HTML sensitive\n chars in content. Used by