Public Vars

Back

nth (clj)

(source)

function

(nth coll index) (nth coll index not-found)
Returns the value at the index. get returns nil if index out of bounds, nth throws an exception unless not-found is supplied. nth also works for strings, Java arrays, regex Matchers and Lists, and, in O(n) time, for sequences.

Examples

clojure
(deftest division
  (is (= clojure.core// /))
  (binding [*ns* *ns*]
    (eval '(do (ns foo
                 (:require [clojure.core :as bar])
                 (:use [clojure.test]))
               (is (= clojure.core// bar//))))))

(deftest Instants
  (testing "Instants are read as java.util.Date by default"
    (is (= java.util.Date (class #inst "2010-11-12T13:14:15.666"))))
  (let [s "#inst \"2010-11-12T13:14:15.666-06:00\""]
    (binding [*data-readers* {'inst read-instant-date}]
      (testing "read-instant-date produces java.util.Date"
        (is (= java.util.Date (class (read-string s)))))
      (testing "java.util.Date instants round-trips"
        (is (= (-> s read-string)
               (-> s read-string pr-str read-string))))
      (testing "java.util.Date instants round-trip throughout the year"
        (doseq [month (range 1 13) day (range 1 29) hour (range 1 23)]
          (let [s (format "#inst \"2010-%02d-%02dT%02d:14:15.666-06:00\"" month day hour)]
            (is (= (-> s read-string)
                   (-> s read-string pr-str read-string))))))
      (testing "java.util.Date handling DST in time zones"
        (let [dtz (TimeZone/getDefault)]
          (try
            ;; A timezone with DST in effect during 2010-11-12
            (TimeZone/setDefault (TimeZone/getTimeZone "Australia/Sydney"))
            (is (= (-> s read-string)
                   (-> s read-string pr-str read-string)))
            (finally (TimeZone/setDefault dtz)))))
      (testing "java.util.Date should always print in UTC"
        (let [d (read-string s)
              pstr (print-str d)
              len (.length pstr)]
          (is (= (subs pstr (- len 7)) "-00:00\"")))))
    (binding [*data-readers* {'inst read-instant-calendar}]
      (testing "read-instant-calendar produces java.util.Calendar"
        (is (instance? java.util.Calendar (read-string s))))
      (testing "java.util.Calendar round-trips"
        (is (= (-> s read-string)
               (-> s read-string pr-str read-string))))
      (testing "java.util.Calendar remembers timezone in literal"
        (is (= "#inst \"2010-11-12T13:14:15.666-06:00\""
               (-> s read-string pr-str)))
        (is (= (-> s read-string)
               (-> s read-string pr-str read-string))))
      (testing "java.util.Calendar preserves milliseconds"
        (is (= 666 (-> s read-string
                       (.get java.util.Calendar/MILLISECOND)))))))
  (let [s "#inst \"2010-11-12T13:14:15.123456789\""
        s2 "#inst \"2010-11-12T13:14:15.123\""
        s3 "#inst \"2010-11-12T13:14:15.123456789123\""]
    (binding [*data-readers* {'inst read-instant-timestamp}]
      (testing "read-instant-timestamp produces java.sql.Timestamp"
        (is (= java.sql.Timestamp (class (read-string s)))))
      (testing "java.sql.Timestamp preserves nanoseconds"
        (is (= 123456789 (-> s read-string .getNanos)))
        (is (= 123456789 (-> s read-string pr-str read-string .getNanos)))
        ;; truncate at nanos for s3
        (is (= 123456789 (-> s3 read-string pr-str read-string .getNanos))))
      (testing "java.sql.Timestamp should compare nanos"
        (is (= (read-string s) (read-string s3)))
        (is (not= (read-string s) (read-string s2)))))
    (binding [*data-readers* {'inst read-instant-date}]
      (testing "read-instant-date should truncate at milliseconds"
        (is (= (read-string s) (read-string s2) (read-string s3))))))
  (let [s "#inst \"2010-11-12T03:14:15.123+05:00\""
        s2 "#inst \"2010-11-11T22:14:15.123Z\""]
    (binding [*data-readers* {'inst read-instant-date}]
      (testing "read-instant-date should convert to UTC"
        (is (= (read-string s) (read-string s2)))))
    (binding [*data-readers* {'inst read-instant-timestamp}]
      (testing "read-instant-timestamp should convert to UTC"
        (is (= (read-string s) (read-string s2)))))
    (binding [*data-readers* {'inst read-instant-calendar}]
      (testing "read-instant-calendar should preserve timezone"
        (is (not= (read-string s) (read-string s2)))))))
hoplon/hoplon
(ns hoplon.binding
  (:refer-clojure :exclude [binding bound-fn])
  (:require [clojure.core  :as clj]
            [cljs.analyzer :as a]))

(defmacro binding
  "See clojure.core/binding."
  [bindings & body]
  (let [env           (assoc &env :ns (a/get-namespace a/*cljs-ns*))
        value-exprs   (take-nth 2 (rest bindings))
        bind-syms     (map #(:name (a/resolve-existing-var env %)) (take-nth 2 bindings))
        bind-syms'    (map (partial list 'quote) bind-syms)
        set-syms      (repeatedly (count bind-syms) gensym)
        setfn         (fn [x y]
                        {:push! `(fn []
                                   (let [z# ~x]
                                     (set! ~x ~y)
                                     (fn [] (set! ~x z#))))})
        thunkmaps     (map setfn bind-syms set-syms)]
    (a/confirm-bindings env bind-syms)
    `(let [~@(interleave set-syms value-exprs)]
       (hoplon.binding/push-thread-bindings ~(zipmap bind-syms' thunkmaps))
       (try ~@body (finally (hoplon.binding/pop-thread-bindings))))))
mikera/core.matrix
   WARNING: because they lack efficient indexed access, sequences will perform badly for most
   array operations. In general they should be converted to other implementations before use."
  (:require [clojure.core.matrix.protocols :as mp]
            [clojure.core.matrix.implementations :as imp]
    #?(:clj [clojure.core.matrix.macros :refer [scalar-coerce error]]))
  #?(:clj (:import [clojure.lang ISeq])
     :cljs (:require-macros [clojure.core.matrix.macros :refer [scalar-coerce error]])))

(extend-protocol mp/PIndexedAccess
  ISeq
    (get-1d [m x]
      (scalar-coerce (nth m x)))
    (get-2d [m x y]
      (let [row (nth m x)]
        (mp/get-1d row y)))
    (get-nd [m indexes]
      (if-let [indexes (seq indexes)]
        (if-let [next-indexes (next indexes)]
          (let [mv (nth m (first indexes))]
            (mp/get-nd mv next-indexes))
          (nth m (first indexes)))
        m ;; TODO: figure out if this is a good return value? should it be an error?
        )))

(extend-protocol mp/PSliceView
  ISeq
    (get-major-slice-view [m i]
      (nth m i)))
PrecursorApp/precursor
(ns pc.http.routes.api
  (:require [cemerick.url :as url]
            [cheshire.core :as json]
            [clojure.core.memoize :as memo]
            [clojure.string :as str]
            [clojure.tools.reader.edn :as edn]
            [crypto.equality :as crypto]
            [defpage.core :as defpage :refer (defpage)]
            [pc.auth :as auth]
            [pc.crm :as crm]
            [pc.datomic :as pcd]
            [pc.early-access]
            [pc.http.doc :as doc-http]
            [pc.http.team :as team-http]
            [pc.http.handlers.custom-domain :as custom-domain]
            [pc.models.chat-bot :as chat-bot-model]
            [pc.models.doc :as doc-model]
            [pc.models.flag :as flag-model]
            [pc.models.team :as team-model]
            [pc.profile :as profile]
            [ring.middleware.anti-forgery :as csrf]
            [slingshot.slingshot :refer (try+ throw+)]))

(defpage new [:post "/api/v1/document/new"] [req]
  (let [params (some-> req :body slurp edn/read-string)
        read-only? (:read-only params)
        doc-name (:document/name params)]
    (if-not (:subdomain req)
      (let [cust-uuid (get-in req [:auth :cust :cust/uuid])
            intro-layers? (:intro-layers? params)
            doc (doc-model/create-public-doc!
                 (merge {:document/chat-bot (rand-nth chat-bot-model/chat-bots)}
                        (when cust-uuid {:document/creator cust-uuid})
                        (when read-only? {:document/privacy :document.privacy/read-only})
                        (when doc-name {:document/name doc-name})))]
        (when intro-layers?
          (doc-http/add-intro-layers doc))
        {:status 200 :body (pr-str {:document (doc-model/read-api doc)})})
      (if (and (:team req)
               (auth/logged-in? req)
               (auth/has-team-permission? (pcd/default-db) (:team req) (:auth req) :admin))
        (let [doc (doc-model/create-team-doc!
                   (:team req)
                   (merge {:document/chat-bot (rand-nth chat-bot-model/chat-bots)}
                          (when-let [cust-uuid (get-in req [:cust :cust/uuid])]
                            {:document/creator cust-uuid})
                          (when read-only?
                            {:document/privacy :document.privacy/read-only})
                          (when doc-name
                            {:document/name doc-name})))]
          {:status 200 :body (pr-str {:document (doc-model/read-api doc)})})
        {:status 400 :body (pr-str {:error :unauthorized-to-team
                                    :redirect-url (str (url/map->URL {:host (profile/hostname)
                                                                      :protocol (if (profile/force-ssl?)
                                                                                  "https"
                                                                                  (name (:scheme req)))
                                                                      :port (if (profile/force-ssl?)
                                                                              (profile/https-port)
                                                                              (profile/http-port))
                                                                      :path "/new"
                                                                      :query (:query-string req)}))
                                    :msg "You're unauthorized to make documents in this subdomain. Please request access."})}))))
typedclojure/typedclojure
(ns ^:no-doc typed.ann.clojure
  "Type annotations for the base Clojure distribution."
  #?(:cljs (:require-macros [typed.ann-macros.clojure :as macros]))
  (:require [clojure.core :as cc]
            [typed.clojure :as t]
            #?(:clj [typed.ann-macros.clojure :as macros])
            #?(:clj typed.ann.clojure.jvm) ;; jvm annotations
            #?(:clj clojure.core.typed))
  #?(:clj
     (:import (clojure.lang PersistentHashSet PersistentList
                            APersistentMap #_IPersistentCollection
                            #_ITransientSet
                            IRef)
              (java.util Comparator Collection))))

#?(:cljs (do
(t/ann-protocol cljs.core/Fn)
(t/ann-protocol cljs.core/IFn)
(t/ann-protocol cljs.core/ICloneable
                -clone [cljs.core/ICloneable :-> t/Any])
(t/ann-protocol [[x :variance :covariant]]
                cljs.core/IIterable
                ;; TODO
                -iterator [(cljs.core/IIterable x) :-> t/Any #_Object])
(t/ann-protocol cljs.core/ICounted
                -count [cljs.core/ICounted :-> t/Num])
(t/ann-protocol cljs.core/IEmptyableCollection
                ;; :/ TFn param on protocol?
                -empty [cljs.core/IEmptyableCollection :-> t/Any])
(t/ann-protocol cljs.core/ICollection
                -conj [cljs.core/ICollection t/Any :-> cljs.core/ICollection])
(t/ann-protocol [[x :variance :covariant]] cljs.core/IIndexed
                -nth (t/All [y]
                            [(cljs.core/IIndexed x) t/JSnumber (t/? y) :-> (t/U x y)]))
(t/ann-protocol cljs.core/ASeq)
(t/ann-protocol [[x :variance :covariant
                  ;;FIXME causes mystery error
                  ;:< t/AnyNilableNonEmptySeq
                  ]]
                cljs.core/ISeqable)
(t/ann-protocol [[x :variance :covariant]] cljs.core/ISeq
                -first [(cljs.core/ISeq x) :-> (t/Nilable x)]
                -rest [(cljs.core/ISeq x) :-> (cljs.core/ISeq x)])
;cljs.core/INext [[x :variance :covariant]]
(t/ann-protocol [[v :variance :covariant]] cljs.core/ILookup)
(t/ann-protocol [[k :variance :covariant]
                 [v :variance :covariant]]
                cljs.core/IAssociative
                -contains-key [(cljs.core/IAssociative k v) t/Any :-> t/Bool]
                -assoc (t/All [k1 v1] [(cljs.core/IAssociative k v) k1 v1 :->
                                       (cljs.core/IAssociative (t/U k k1) (t/U v v1))]))
(t/ann-protocol cljs.core/IMap
                -dissoc [cljs.core/IMap t/Any :-> cljs.core/IMap])
(t/ann-protocol [[k :variance :covariant]
                 [v :variance :covariant]]
                cljs.core/IMapEntry
                -key [(cljs.core/IMapEntry k v) :-> k]
                -val [(cljs.core/IMapEntry k v) :-> v])
(t/ann-protocol cljs.core/ISet
                -disjoin (t/All [s] [s t/Any :-> s]))
(t/ann-protocol [[x :variance :covariant]]
                cljs.core/IStack
                -peek [(cljs.core/IStack x) :-> (t/U nil x)]
                -pop [(cljs.core/IStack x) :-> (cljs.core/IStack x)])
(t/ann-protocol [[x :variance :covariant]]
                cljs.core/IVector
                -assoc-n (t/All [x1] [(cljs.core/IVector x) t/Num x1
                                      :-> (cljs.core/IVector (t/U x x1))]))
(t/ann-protocol [[x :variance :covariant]]
                cljs.core/IDeref
                -deref [(cljs.core/IDeref x) :-> x])
(t/ann-protocol [[x :variance :covariant]]
                cljs.core/IDerefWithTimeout
                -deref-with-timeout [(cljs.core/IDerefWithTimeout x) :-> x])
(t/ann-protocol cljs.core/IMeta
                -meta [cljs.core/IMeta :-> (t/Nilable (t/Map t/Any t/Any))])
(t/ann-protocol cljs.core/IWithMeta
                -with-meta [cljs.core/IWithMeta (t/Nilable (t/Map t/Any t/Any)) :-> cljs.core/IWithMeta])
;TODO
;cljs.core/IReduce [[]]
(t/ann-protocol cljs.core/IKVReduce ;;TODO
                -kv-reduce [cljs.core/IKVReduce [t/Any t/Any t/Any :-> t/Any] :-> t/Any])
(t/ann-protocol cljs.core/IList)
(t/ann-protocol cljs.core/IEquiv
                -equiv [cljs.core/IEquiv t/Any :-> t/Bool])
(t/ann-protocol cljs.core/IHash
                -hash [cljs.core/IHash :-> t/Num])
(t/ann-protocol cljs.core/ISequential)
(t/ann-protocol cljs.core/IRecord)
(t/ann-protocol [[x :variance :covariant]]
                cljs.core/IReversible
                -rseq [(cljs.core/IReversible x) :-> (t/NilableNonEmptySeq x)])
(t/ann-protocol [[k :variance :covariant]
                 [v :variance :covariant]] cljs.core/IFind
                -find [(cljs.core/IFind k v) t/Any :-> (t/Nilable (cljs.core/IMapEntry k v))]
                )
(t/ann-protocol [[x :variance :invariant]]
                cljs.core/ISorted
                -sorted-seq [(cljs.core/ISorted x) t/Bool :-> (t/Nilable (t/ASeq x))]
                ;; second arg => comparable?
                -sorted-seq-from [(cljs.core/ISorted x) t/Any t/Bool :-> (t/Nilable (t/ASeq x))]
                -entry-key [(cljs.core/ISorted x) t/Any :-> t/Any]
                -comparator [(cljs.core/ISorted x) :-> [x x :-> t/Num]])
(t/ann-protocol cljs.core/IPending)
;cljs.core/IWriter [[]]
;cljs.core/IPrintWithWriter [[]]
;    ;TODO
;;cljs.core/IWatchable [[]]
;    ;cljs.core/IEditableCollection [[]]
;    ;cljs.core/ITransientCollection [[]]
;    ;cljs.core/ITransientAssociative [[]]
;    ;cljs.core/ITransientMap [[]]
;    ;cljs.core/ITransientVector [[]]
;    ;cljs.core/ITransientSet [[]]
(t/ann-protocol [[x :variance :invariant]]
                cljs.core/IComparable)
;    ;cljs.core/IChunk [[]]
;    ;cljs.core/IChunkedSeq [[]]
;    ;cljs.core/IChunkedNext [[]]
(t/ann-protocol cljs.core/INamed
                -named [cljs.core/INamed :-> t/Str]
                -namespace [cljs.core/INamed :-> (t/Nilable t/Str)])
(t/ann-protocol [[x :variance :invariant]]
                cljs.core/IVolatile
                -vreset! (t/All [x] [(cljs.core/IVolatile x) x :-> x]))

cc/nthrest (t/All [x] [(t/Seqable x) t/AnyInteger :-> (t/ASeq x)])

cc/first (t/All [x] (t/IFn [(t/HSequential [x t/Any :*]) :-> x
                            :object {:id 0 :path [(Nth 0)]}]
                           [(t/EmptySeqable x) :-> nil]
                           [(t/NonEmptySeqable x) :-> x]
                           [(t/Seqable x) :-> (t/Option x)]))
cc/second (t/All [x] (t/IFn [(t/HSequential [t/Any x t/Any :*]) :-> x
                             :object {:id 0 :path [(Nth 1)]}]
                            [(t/Option (t/I (t/Seqable x) (t/CountRange 0 1))) :-> nil]
                            [(t/I (t/Seqable x) (t/CountRange 2)) :-> x]
                            [(t/Seqable x) :-> (t/Option x)]))
cc/ffirst (t/All [x] [(t/Seqable (t/Seqable x)) :-> (t/Nilable x)])
cc/nfirst (t/All [x] [(t/Seqable (t/Seqable x)) :-> (t/NilableNonEmptyASeq x)])
cc/group-by (t/All [x y] [[x :-> y] (t/Seqable x) :-> (t/Map y (t/NonEmptyAVec x))])
cc/fnext (t/All [x] [(t/Seqable x) :-> (t/Option x)])
cc/nnext (t/All [x] [(t/Seqable x) :-> (t/NilableNonEmptyASeq x)])
cc/nthnext (t/All [x] (t/IFn [nil t/AnyInteger :-> nil]
                             [(t/Seqable x) t/AnyInteger :-> (t/NilableNonEmptyASeq x)]))
cc/rest (t/All [x] [(t/Seqable x) :-> (t/ASeq x)])
cc/last (t/All [x] (t/IFn [(t/NonEmptySeqable x) :-> x]
                          [(t/Seqable x) :-> (t/U nil x)]))
cc/butlast (t/All [x] [(t/Seqable x) :-> (t/NilableNonEmptyASeq x)])
cc/next (t/All [x] (t/IFn [(t/Option (t/Coll x)) :-> (t/NilableNonEmptyASeq x)
                           :filters {:then (& (is (t/CountRange 2) 0)
                                              (! nil 0))
                                     :else (| (is (t/CountRange 0 1) 0)
                                              (is nil 0))}]
                          [(t/Seqable x) :-> (t/NilableNonEmptyASeq x)]))

cc/take-nth (t/All [x] [t/AnyInteger (t/Seqable x) :-> (t/ASeq x)])

cc/eval [t/Any :-> t/Any]
cc/rand-nth (t/All [x] [(t/U (t/Indexed x) (t/SequentialSeqable x)) :-> x])
cloudkj/lambda-ml
(ns lambda-ml.factorization-test
  (:require [clojure.test :refer :all]
            [clojure.core.matrix :refer :all]
            [lambda-ml.factorization :refer :all]))

(deftest test-factorization
  (let [data [[1 2 3] [4 5 6]]
        [w h] (-> (factorizations data 2)
                  (nth 200))]
    (is (< (cost data (mmul w h)) 1E-6))))