This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2018-03-20
Channels
- # bangalore-clj (1)
- # beginners (145)
- # boot (8)
- # braid-chat (2)
- # capetown (2)
- # cider (27)
- # cljs-dev (232)
- # cljsrn (30)
- # clojure (223)
- # clojure-boston (1)
- # clojure-dusseldorf (2)
- # clojure-greece (1)
- # clojure-italy (21)
- # clojure-russia (16)
- # clojure-sanfrancisco (13)
- # clojure-spec (33)
- # clojure-uk (56)
- # clojurescript (165)
- # core-async (16)
- # core-logic (5)
- # cursive (14)
- # data-science (2)
- # datavis (2)
- # datomic (49)
- # duct (15)
- # editors (5)
- # emacs (6)
- # fulcro (11)
- # graphql (11)
- # hoplon (8)
- # jobs (4)
- # jobs-discuss (82)
- # jobs-rus (7)
- # leiningen (4)
- # luminus (5)
- # off-topic (90)
- # om (7)
- # om-next (1)
- # parinfer (67)
- # pedestal (34)
- # portkey (46)
- # re-frame (12)
- # reagent (4)
- # reitit (3)
- # remote-jobs (1)
- # ring-swagger (8)
- # shadow-cljs (13)
- # spacemacs (18)
- # specter (6)
- # sql (5)
- # tools-deps (4)
- # unrepl (40)
- # yada (26)
the asker specified using a particular libary (Joda-Time) but the only library you need nowadays (since 2014) is baked into the JVM (the java.time.* package) You don't even need a "clojure library" to wrap it. But you have to get comfy calling Java objects (really not very different than Ruby or Python)
one way to do it is like so:
(import (java.time LocalDate DayOfWeek))
(let [starting-at (LocalDate/of 2018 3 1)
days (iterate #(.plusDays % 1) starting-at)
mondays (filter (fn [day]
(= DayOfWeek/MONDAY (.getDayOfWeek day)))
days)]
(str (nth mondays 2)))
I was just writing it up using clj-time
(since the OP asked about Joda Time) and, yeah, I was arriving at the same solution 🙂
(! 770)-> clj -Sdeps '{:deps {clj-time {:mvn/version "RELEASE"}}}'
Clojure 1.9.0
user=> (require '[clj-time.core :as t] '[clj-time.predicates :as p])
nil
user=> (nth (->> (t/date-time 2018 3 1) (iterate #(t/plus % (t/days 1))) (filter p/monday?)) 2)
#object[org.joda.time.DateTime 0x771158fb "2018-03-19T00:00:00.000Z"]
user=> (str *1)
"2018-03-19T00:00:00.000Z"
Or using clojure.java-time
(a very thin wrapper for Java Time):
(! 772)-> clj -Sdeps '{:deps {clojure.java-time {:mvn/version "RELEASE"}}}'
Clojure 1.9.0
user=> (require '[java-time :as jt])
nil
user=> (nth (->> (jt/local-date-time 2018 3 1) (iterate #(jt/plus % (jt/days 1))) (filter jt/monday?)) 2)
#object[java.time.LocalDateTime 0x1983b48a "2018-03-19T00:00"]
user=> (str *1)
"2018-03-19T00:00"
@seancorfield I'm mildly surprised that jt/local-date-time
takes a 3-argument constructor that only specifies date and not any time.
hey guys
so, I am trying to remove every new line from a file that I reading using slurp
..the way I am trying to remove the new lines is like this:
(print (apply str (filter #(not (#{\newline} %)) string)))
it words for a small string, but for some reason when I try it over the whole file, it returns something weird, which is pretty much a line in te middle kind of
can anyone see something weird about this function?
@brnbraga95 Since slurp
gives you the entire file as a string, a simple string replacement would be a lot more efficient than converting the data to a sequence, filtering it, and squashing it back into a string.
@brnbraga95 So I agree with @seancorfield that something like (.replace string "\n" "") is the way to go, but I'm also not sure why your aren't getting the result you're expecting from your original way. Is it possible there is a carriage return or some other odd character in the file?
it could be that, I indeed changed my approach to read line by line, so that I can work with large files as well
Hi all, can anyone explain to me why commute
is called twice? I understand the difference between alter
and commute
but I don’t know why commute
is called at the beginning and at commit point
When you use commute
you state that "changes may have been made by other transactions to any Refs that have been commuted by this transaction". The second call is to ensure that a proper updated value is commited if the other transaction updated it while your transaction was running. Otherwise you might get only one update applied although there were two updates actually. alter
will solve this situation by retrying the whole transaction whereas commute
relies on "commutatitivy" of the update fn and can give you better performance.
this can help: https://clojure.org/reference/refs And maybe this: https://stackoverflow.com/questions/4999281/ref-set-vs-commute-vs-alter
@U06BE1L6T but what does commute
do with the first value? I dont get why the 2nd commute alone isn’t sufficient
what does clojure do with the result of the 1st commute
? I looked into the java source and didn’t get it…
I'm not an expert, but I believe that's because you actually want to access the updated value inside your transaction 🙂
:thinking_face: that would imply that the value I write may not be the value that is set?
I'm having some troubles using boot. I've used this guide https://lionfacelemonface.wordpress.com/2015/01/17/boot-getting-started-with-clojure-in-10-minutes/
when I tried to run boot build
it said jar has been created, yet I see no jars in my directory
@mailmeupinside not a boot guy myself, but have you looked itno ./target/
dir?
@mailmeupinside boot doesn't write any files by default unless you run the target
task afterwards
I have another problem now 😄
(clojure.string/split "foo bar" #" ") ; works
(clojure.string/split ["foo bar" "x y"] #" ") ; obviously doesn't
(apply clojure.string/split ["foo bar" "x y"] #" ") ; also doesn't but I don't know why
apply
is for taking the arguments from a collection and applying a function to them, like (apply + [1 2])
=> (map (fn [s] (clojure.string/split s #" ")) ["foo bar" "x y"])
(["foo" "bar"] ["x" "y"])
=> (mapcat (fn [s] (clojure.string/split s #" ")) ["foo bar" "x y"])
("foo" "bar" "x" "y")
Is there anything like NCruch or Wallaby.js for Clojure? I know there is 'Lein auto test' but is there a plugin were the results appearing withing the editor next to the line with a Green tick or Red cross?
Cursive will do this if you’re using clojure.test
Thanks! Might need to starting using Cursive. Does Cursive have inline evaluation? Does it update the inline evaluation and test as you type?
you can eval expressions in your editor and send them to your repl if that’s what you mean
Could anyone give me a hand finding discrepancy with clob in jdbc? When I run the same query against h2 and posrgresql I get two different results:
(jdbc/query db ["SELECT bar FROM foo"])
for postgre returns:
({:bar "fapfap"})
and for h2 returns:
({:bar #object[org.h2.jdbc.JdbcClob 0x7844d931 "clob7: 'fapfap'"]})
Why is that?
I’d expect same thing to be returned in both cases. If it’s driver specific, how exactly clob is actually accessed in clojure.java.jdbc?
Tried reading code, but struggling to find the right spot, where it is actually read from ResultSet
, somewhere around:
https://github.com/clojure/java.jdbc/blob/master/src/main/clojure/clojure/java/jdbc.clj#L1092
Thanks!For reference, I solved it by passing :read-columns
that supports org.h2.jdbc.JdbcClob
, based pretty much on internal implementation:
https://github.com/clojure/java.jdbc/blob/master/src/main/clojure/clojure/java/jdbc.clj#L442
Actually you can do less than that, and just extend the protocol:
(extend-protocol jdbc/IResultSetReadColumn
JdbcClob
(result-set-read-column [x _2 _3] (slurp (.getCharacterStream x))))
hey, how do I map three levels deep? 😅 I have something like [[["foo" "bar"]]]
and I have to map over foo
and bar
it is a case of “iterate the most highly nested collection”, or “iterate through the first of the first item”?
((["abcde" "fghij"]) (["abcde" "ecdab"] ["xyz" "ers" "sew"]))
would be a sample seq from my code
I have to do something for every string
Specter can help:
user=> a
((["abcde" "fghij"]) (["abcde" "ecdab"] ["xyz" "ers" "sew"]))
user=> (transform [ALL ALL ALL] count a)
(([5 5]) ([5 5] [3 3 3]))
I think something like specter is going to be necessary if I want it to be any readable
specter is never a necessity, and only sometimes a convenience
Obligatory: “Perhaps you should revisit the data structure?” not-very-helpful suggestion 🙂
also, in this case the answer can't be easier
given (def a '((["abcde" "fghij"]) (["abcde" "ecdab"] ["xyz" "ers" "sew"])))
you just (flatten a)
... try (map count (flatten a))
Does anybody know of a library for CLJ/CLJS that has the same intention as How to Design Program's https://docs.racket-lang.org/teachpack/2htdpimage.html ?
It's a bit old, but clojurebridge used to do a turtle graphics sort of thing: https://github.com/ClojureBridge/welcometoclojurebridge/blob/master/outline/TURTLE.md
Seems to be really interesting but too different from htdp2/image. I wanted something to draw that included a lot of ready functions like star
and polygon
with overlays. The idea is not to follow the book with Clojure rather than Racket but to play here and there with how it would look like in the Clojure world.
Thank you though!
Sure! It wouldn't surprise me if there is other things out there -- certainly you could do it all with Java interop -- but probably not what you are looking for.
@U9H7B8P7X I just remembered there is a Clojure/ClojureScript library for compiling Processing/p5.js and although it has a focus on animation, I guess it will do what I need http://quil.info/api 🎉
Alright, this is it: https://www.maria.cloud/intro
@joelsanchez that can be said about anything that isn't assembly
specter isn't always better in terms of readability, which can't be said when comparing C to assembly
in this example, flatten
vs transform [ALL ALL ALL]
that's true, yep
Hi there, does anyone know how I can change javascripts this
from cljs? (goog.object/set this "value" "foobar")
does not work...
there's this-as
and (js-this)
, you choose
(this-as this
(goog.object/set this "value" "foobar"))
(goog.object/set (js-this) "value" "foobar")
bear in mind that function literals and partial
won't retain this
context
It's a bit old, but clojurebridge used to do a turtle graphics sort of thing: https://github.com/ClojureBridge/welcometoclojurebridge/blob/master/outline/TURTLE.md
Any tips or example projects for building real-time systems with Clojure and PostgreSQL? I am looking to build a realtime app with Clojure and Postgresql using NOTIFY, LISTEN, and UNLISTEN with triggers. I am using the driver here: https://github.com/alaisi/postgres-async-driver
Not answering your question but this might be interesting: the myth of asynchronous JDBC: http://mikemainguy.blogspot.cz/2015/05/the-myth-of-asynchronous-jdbc.html
I'm trying out postgres now, replacing an atom with the database. It's a bank emulation, doing transactions. With the atom, I could easily handle 10.000 transactions a second, now it's down to about 100. I'm using the same library, and some pointers from http://lacinia.readthedocs.io/en/latest/tutorial/database-1.html
What's the idiomatic way to extract content from deep inside a json object? e.g. { 'results': [ { 'entries': [ { 'features': [ 'a', 'b' ] }, { 'features': ['c', 'd'] ] } ] }
<- I'd like to extract 'a', 'b', 'c' and 'd'
(->> (get-in data ["results" 0 "entries"]) (mapcat (fn [entry] (get entry "features")))) => ("a" "b" "c" "d")
@greg316 - thanks - what if there were multiple elements in results? e.g. i didn't want just index 0 or results?
(->> (get data "results") (mapcat (fn [result] (mapcat (fn [entry] (get entry "features")) (get result "entries"))))
sorry, but new to this, but by 'more pipelining' do you mean extract some of the nested calls to their own functions?
what do you typically use to construct a data structure? reduce? I want to create a map that would have a letter as a key and how many these letters I've found as a value
Check out the source code of frequencies
@mailmeupinside if you weren't aware, you can do so by typing (source frequencies)
into a repl
the rest of the functions in clojure.repl are handy too: https://clojuredocs.org/clojure.repl 🙂
although maybe the frequencies
function does what you want (it is implemented with reduce
)?
(defn un-frequencies-helper [a-map a-seq]
(if (empty? a-map)
(reverse a-seq)
(let [fst-key ((first a-map) 0)
fst-val ((first a-map) 1)]
(if (<= fst-val 1)
(un-frequencies-helper (rest a-map) (cons fst-val a-seq))
(un-frequencies-helper (assoc a-map fst-key (dec fst-val))))
(un-frequencies-helper a-map (cons fst-key a-seq)))))
(un-frequencies {:a 3 :b 2 "^_^" 1})
clojure.lang.ArityException: Wrong number of args (1) passed to: recursion/un-frequencies-helper
@lum you're only passing one argument to un-frequencies-helper
here: (un-frequencies-helper (assoc a-map fst-key (dec fst-val)))
hey guys, I am to print a persistentArrayMap like this: (doseq [[k v] j] (print k))
but I am gettin UnsupportedOperationException nth not supported on this type: PersistentArrayMap clojure.lang.RT.nthFrom (RT.java:983)
which I guess means I cant iterate over this kind of data, does anyone know a workaround?
@brnbraga95 call seq
on the map.
(although I would have expected doseq
to do that for you)
Yes, it does. Just confirmed that. @brnbraga95 can you share a bit more code? What you've written works if j
is a hash map literal...
boot.user=> (doseq [[k v] {:a 1 :b 2}] (println k))
:a
:b
nil
boot.user=> (type {:a 1 :b 2})
clojure.lang.PersistentArrayMap
you are totally right. apparently what I got was something called lazySeq
that is wrapping some persistentArrayMaps
what I am trying to achieve is am array of jobs ids, types and urgences, which are the values of the persistentMaps
, at this point I no longer care for key, which are always new_jobs
Ah, you had a sequence of maps... So you want to produce a sequence of vectors? Like ([<uuid> bills-questions true] [...] [...])
?
Ideally I would like to have something like:
[
"690de6bc-163c-4345-bf6f-25dd0c58e864": {
"type": "bills-questions",
"urgent": false
}
]
Since you're starting with a sequence and you want to produce a sequence of the same length, where each element is just a transformation of the original sequence, you want to call map
and pass a transformation function:
(map some-function jobs)
where some-function
takes a job hash map and produces a vector containing just the values of :id
, :type
, and :urgent
...That's not a valid data structure -- did you want to produce a hash map, indexed by the job ID? (not a vector)
yes, but I also want to be able to iterate over it, because I want to find workers for those jobs
but I want the smallest payload
If you want to go from a sequence of hash maps to a (new) hash map, then you want reduce
.
that is why I am trying to map over and make it a simpler data structure
does not reduce "reduces" it to a single value?
ooh I got you
(reduce (fn [m job] (assoc m ...)) {} jobs)
That will produce a hash map from the jobs
. What you assoc
into it will be the job ID (as the key) and then a hash map of just the keys you want (as the value).
Is that enough to get you going in the right direction?
yes it is, just to make sure. m
is my current hash map (the accumalted), job
is the current job I am iterating and {}
is a starting hash map
is that correct?
Actually you can do less than that, and just extend the protocol:
(extend-protocol jdbc/IResultSetReadColumn
JdbcClob
(result-set-read-column [x _2 _3] (slurp (.getCharacterStream x))))