Archive for the 'programming' Category

Reading/Printing a file

A friend of mine at work, also bitten by the functional bug, has been hacking on some Scala.

He showed me some code yesterday and I thought it might be fun to convert it. I am not going to post his code, as that would be presumptuous, but I have mine to show.

The goal is to read up a file, and then print that file prepending each line with the number of characters in that line, as well as padding the beginning so that everything lines up.

The usual caveats about my newbness.

; Get the name of the document from the cli
(def arg (first *command-line-args*))

; Convert the doc to a vector
(def lines (vec (.split (slurp arg) "\n")))

; Takes a string, and finds out how long
; the length, of the length is
(defn length-of-length[s]
(.length (str (.length s))))

; Returns the longest element from a collection
(defn get-longest-line[lines]
(reduce (fn [x y]
(if (>(.length x)(.length y))
x y))lines))

; Repeat s string t times.
(defn pad[s t]
(take t (repeat s)))

; Find the maximum width of a line from the doc
(def max-width (length-of-length (get-longest-line lines)))

; Take the vector of the file, iterate over the lines and
; print each one prepended with the number of characters that
; appear in that line
(doseq [line lines]
(let [num-spaces (- max-width (length-of-length line))]
(println (apply str " " (pad " " num-spaces)) (.length line) " | " line)))

Tip of the hat to ‘Chousuke’ in #clojure for the clue on ‘apply’.

Example


$ java -cp /opt/clojure/clojure.jar clojure.main scala.clj test.txt
50 | This is a text file with lines that vary in length
0 |
13 | ^^ Blank line
34 | Some other text that is mid length
9 | Oh hai!!!

Thanks for playing!

Dwarf Name Generator

The local ruby group sends out the Ruby Quiz (with some regularity). This week it was to create a Dwarf Name Generator.

I thought of a fairly simple solution in Clojure pretty quickly, but then it took me a while to implement it. Anyway, here is what I came up with.


; Create a couple of Maps with keys being Integers
(def firstnames {1 "Danby" 2 "Tamreil" 3 "Vash" 4 "Gobu"})
(def lastnames {1 "Dongledorp" 2 "Floopydoo" 3 "Goran" 4 "Zypher"})

; Return a random Integer with a value > 0 but < = the upper bounds
(defn randomize [upper]
(let [randy (. Math round(* (. Math random) upper))]
(if (= randy 0)
(int (+ 1 randy))
(int randy))))

; Since Maps, can be used as Functions that take a key as an argument
; pass those to println
(println (firstnames (randomize (.size firstnames))) (lastnames (randomize (.size lastnames))))

The reason it took me so long is that initially I wasn't casting 'randy' to a Java Integer, and using it as a argument to a Map (which causes the Map to act as a function) was causing the Map to not find it while looking it up. After a bit of head scratching, I asked in #clojure.

Obviously, if I were a linguist, I would have created a lot of maps with just parts of names in them (I am sure that is called something), and then randomized that further, but I am not, and since the underlying mechanics would be more or less the same, I left it as is.

Happy hacking!

Clojure/Java Interop

Hello again.

I picked up the book Programming Clojure and have made my way through the first two chapters which were great.

Last night I started the 3rd chapter, on Java Interoperability.

I was hoping to toss together a single Java class that I could then try to rewrite in Clojure to help me learn. Following is what I came up with. (Note, I am not a Java ninja by any stretch so beware).

This is not intended as any sort of comparison of the languages per se. It’s simply, “Given X, I had to do Y to get the same functionality”.

My idea was to find a Java library for parsing rss and then parse out the rss for this site, prining the Title of the Post, as well as the link (this is the lieberry I used).

First the Java:

And next the Clojure:

While I am not sure the Clojure code is as succinct as it could be since I am still pretty new, I do like the looks of it. I agree with the notion that it’s an expressive language, and that one can do quite a bit with a minimum of fuss. I think that practically the syntax is idiomatic, I am not entirely sold on the dot form, and dot dot macro. I don’t think they are as visually appealing as would be a symbol in this context. But they do make sense.

Happy learning!

n00b

I am a total Clojure n00b. But I am having a lot of fun learning it. It’s not like anything else I have learned to date.

I hadn’t really done much with it, other than watch presentations, mess around in the REPL, and with the help of Hexmode, get Clojure working with Slime in Emacs.

Yesterday and this morning during stolen minutes of solitude, I have been trying to get it to talk to a MySQL DB. Mostly, because I’d love to get to a point where I can, you know, actually do something with it :)

So this, for my fellow newbs that stumble here via google, is what I did.

For the purposes of demonstration, I created a 1 table db and gave it some lame data.

$ mysqladmin -uroot create hack
$ echo "CREATE TABLE hack(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY);" | mysql -u root hack
$ for i in $(seq 4);do echo "use hack; INSERT INTO hack VALUES()" | mysql -u root hack;done

I can assure you the following code, is likely not best practices, but I have to start somewhere. So I whipped this together by looking at the test.clj for the clojure.contrib.sql library on github (Open Source rocks like that). And a lot of googling. The comments are there for your benefit.

(comment Import the Clojure Contrib SQL Library)
(require '[clojure.contrib.sql :as ccsql])

(comment Set up the connection string)
(def db { :classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//localhost/hack"
:user "root"
:create true })

(comment Define a function that does a SELECT * on whatever table you pass in)
(defn get-star
"Print all the rows in the table"
[table]
(ccsql/with-connection db
(ccsql/with-query-results res
[(str "SELECT * FROM " table)]
(doseq [rec res]
(println rec)))))

(comment Execute that function)
(get-star "hack")

Then to run that code, you have to add the mysql Driver jar to your classpath. (Obviously, manually doing all this won’t scale, and after a jar or two, you’ll want to build an executable jar of your own and adopt a build process, but for the purposes of demonstration, this is fine. In fact, I have my clojure script in /bin, so I don’t actually call this this way…but whatever)


$ java -cp "/opt/clojure/clojure.jar:/opt/clojure/clojure-contrib.jar:/opt/jars/mysql-connector-java-5.1.8-bin.jar" clojure.main test.clj
{:id 1}
{:id 2}
{:id 3}
{:id 4}

Ruby Hoedown

Signed up yesterday for the Ruby Hoedown, in Nashville.

Some friends and I (and a dude named Larry) are going to be heading down there in late August. Should be a blast.



I like postgres.

I really do. So after spending a pretty frustrating day trying to get a development environment in windows set up, I finally got to the part where I was going to put postgres on the machine.

Easy I thought. Those guys do good work. And they are cool enough to autogen you a password.

Um. wtf.

Javascript logging

In preparing for my talk this Sunday at CPOSC I have been playing around obviously with various commands, wrapper methods and utility function for jQuery.

This morning I was going through my feeds when I stumbled upon, Blackbird. It’s an open source Javascript logger.

It’s a nice companion to Firebug. I can add it to my page, and then toss some logging statements in my code. With a hit of F2, I can then see the logger.

For example I was testing the grep utility function. Previously I just tossed this in the Fireboug console, which works fine, but this way I can set up a whole bunch of code, and then look at the log as it happens in my page. Leet.

log.info( $.grep([1, 2, 3], function(n){return n < 3}, true) );

I know OpenThought has a logging component to it. Which has been around for a while. I am a little curious why no one had done this before now.

Is there already a way to do logging in Firebug?

Need to stop forgetting this

Create or append to array (Ruby):

(array ||= []) < < 1

Netbeans: Not as crappy as you might expect.

Over the last 3 days I have been using netbeans for RoR development. Honestly I expected to hate it. I figured I would use it for a few days, then crawl back to Emacs begging her to take me back with promises that I wouldn’t stray again.

Here is the truth. I don’t hate it. In fact, I kind of like it.

I like all the integration with Subversion (which we use at work) and Mercurial (which I use at home). I like the Rails integration. It has intellisense type functionality (though with a dynamic language is often unwieldy). The syntax highlighting (while having a white background) is nice.

One of my big complaints however was a lack of really good keybindings. I was missing my C-a, C-e and C-k. A quick google later and I realized you can switch to Emacs keybindings. Sweet. So I have done that.

I hate to say it, but overall I am pretty happy with Netbeans. If you are doing RoR development, and are chronically dissatisfied with software as I am, give it a shot.

My only complaint so far (and this might be fixable) is that tab navigation is chronological and not spatial (or serial you might call it). It’s like using Alt-Tab to cycle through windows versus using virtual desktops to navigate. I have to look into that further.

Use a specific Rails version during project creation

If you do any amount of Rails programming, at some point you end up with various versions of Rails installed on your system. Generally this is fine as Rails keeps what version should be used in it’s environment.rb file.

However when you are creating a new project, the system rails command will use the most recent gem installed.

Also usually fine unless you know the latest version breaks something you want to use. Andy had mentioned to me before that it was possible to specify the version Rails should use on the command line when generating the initial project. However I forgot what it was. Lately I have been on a code reading kick so I decided to start at the start and see if I could remember what he had told me.

Well it didn’t take long. The 3rd line of actual code in the system `rails` command is:


if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then

You can see, if you specify:

rails _2.0.2_ project_name

And that particular Rails version is correct and installed, it will use that version. Thanks to Andy for pointing that out.

Next Page »