Comparing the expressive power of Java with Ruby’s

I came across this programming exercise on GitHub.

Test 1: FizzBuzzBasic: Write some code that prints out the following for a contiguous range of numbers:

the number
‘fizz’ for numbers that are multiples of 3
‘buzz’ for numbers that are multiples of 5
‘fizzbuzz’ for numbers that are multiples of 15
e.g. if I run the program over a range from 1-20 I should get the following output:

#!console

1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz

The Java solution I’ve found at the same location is listed below.

package codingtests.fizzbuzz;

import com.google.common.base.Preconditions;

import java.io.PrintStream;
import java.util.*;
import java.util.function.IntFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FizzBuzzBasic {

    public static void main(String... arguments) {
        FizzBuzzBasic fb = new FizzBuzzBasic();
        fb.checkCommandLineArguments(arguments);
        fb.convertToFizzBuzzAndOut(Integer.valueOf(arguments[0]), System.out);
    }

    public void convertToFizzBuzzAndOut(int upperBound, PrintStream out){
        getFizzBuzzValuesForNumbers(1,upperBound).stream().forEach(out::println);
    }

    public void checkCommandLineArguments(String... arguments){
        Preconditions.checkArgument(arguments.length == 1, "Program must get exactly one argument");
        try{
            Integer.valueOf(arguments[0]);
        } catch (NumberFormatException ex){
            throw new IllegalArgumentException("Argument must be a valid number");
        }
    }

    public List<String> getFizzBuzzValuesForNumbers(int firstNumber, int lastNumber){
        return IntStream.range(firstNumber,lastNumber+1).mapToObj(this::convertNumberToFizzBuzz).collect(Collectors.toList());
    }

    public String convertNumberToFizzBuzz(int number){
        Preconditions.checkArgument(number > 0,"Number should be greater than 0!");

        if (number % 15 == 0) return "fizzbuzz";
        if (number % 3 == 0) return "fizz";
        if (number % 5 == 0) return "buzz";

        return String.valueOf(number);
    }

}

The Ruby solution I’ve came up with is cited below.

(1..20).lazy.map {|n| if (n % 15) == 0; 'fizzbuzz' elsif (n % 5) == 0; 'buzz' elsif (n % 3) == 0; 'fizz' else n end}.each {|x| print "#{x} "}

Expressing the solution in Ruby is easy and straightforward. It’s actually a one-liner. Easy to read and understand. The Java solution is way more verbose and obscure.

Comparing the expressive power of Java with Ruby’s

My 2×1,5V battery iPhone Charger

IMG_1526

Figure 1

Making things is fun! Making an iPhone charger which uses two 1,5V AA batteries is actually easy! At the heart of this small project, there is a DC-DC step-up (boost) converter.

The main part is packed in an IC and only a few external components are necessary to build it, to be able to pump a little charge into your iPhone when there are no wall sockets around.

The whole stuff can be bought as a kit from Adafruit, including all the necessary components and a PCB. If you are in the US and want to save yourself some trouble getting all the components by yourself, -especially the IC and the PCB- then you might want to consider buying the kit from Adafruit.

Adafruit MintyBoost Kit – v3.0

However if you live outside the US, the additional international shipping costs might render this idea not worth to follow.

To save costs, I’ve decided to build it myself from the parts. All the components were relatively easy to come by from local electrical stores expect the IC and the PCB. However thanks to the generosity of the European Linear Technology sales office in Munich I could get two samples of the LT1302 IC for FREE!!! (Big thanks goes to Torsten Lessnau!) After this the only remaining item was the PCB. I went for the easy solution, by choosing a perfboard (stripboard, prototyping PCB). I only had to cut a few copper strips and add some jumper wires to make a replacement PCB for the project.

The datasheet for the LT1302 can be found here.

The circuit diagram to build this project can be found here.

The part list (version 3.0) is here.

The fully assembled and working project can be seen in figure 1.

Thanks Adafruit! Thanks Linear Technology!

Happy Charging! 🙂

My 2×1,5V battery iPhone Charger

Domain Specific Language Demo in Ruby

Fun with Ruby and Domain Specific Languages

Domain Specific Languages (DSLs) are great, because they enable you to express your ideas in a language which draws it’s vocabulary and structure from the business domain you are concerned with.

DSLs makes it easy to communicate with stakeholders and others with knowledge of the business domain. Also it’s much more natural and easier to solve problems in such a DSL for programmers if available, compared to a general purpose low-level programming language.

DSLs are often split up to external end internal DSLs. In this post I’m trying to show some meta-programming capabilities of Ruby. Here I build a simple internal DSL, on top of Ruby, using Ruby as the host language.

Please note that some sources may refer to internal DSLs as embedded DSLs. Don’t be confused, they both mean the same.

The domain in this post is the building of XML markup from structured DSL code.

Imagine you need to generate XML markup like this:

<person type="Villain" role="President">
  <name>
    <first>Coriolanus</first>
    <last>Snow</last>
  </name>
  <address>
    <street>Presidential Residence</street>
    <city>The Capitol</city>
    <country>Panem</country>
  </address>
  <empty/>
  <withattribsonly key="value" other="other"/>
</person>

Using code-editors and IDEs, it’s not a big deal today, since they aid entering structured data like XML and they can offer tag-closing and autocomplete features and more. Hence you can generate them by entering the XML by hand.

Also, you can opt for writing a small program in a general-purpose programming language to transform some structured data into XML markup, but that assumes that you already have the structured data available to you in some other format. By using a low-level general-purpose programming language you’ll have some performance gain, but coding the tool in that language will be tedious and cumbersome.

A third option could be to use an existing tool/library to perform the transformation for you. With this you could save the time and effort implementing such a tool by yourself.

BUT there’s a forth option, which is the most FUN option in my opinion. Since Ruby is a dynamic, high-level programming language with amazing meta-programming features, it’s so easy to write an internal DSL in Ruby, just to make the XML markup generating happen.

Take a look at the following little DSL for describing structured data:

to_xml do
  person type: 'Villain', role: 'President' do
    name do
      first 'Coriolanus'
      last 'Snow'
    end
    address do
      street 'Presidential Residence'
      city 'The Capitol'
      country 'Panem'
    end
    empty
    withattribsonly key: 'value', other: 'other'
  end
end

If you were looking careful, you probably discovered, that it’s the same structured data as the above in XML markup.

That’s it!

You can find all the source for this little demo below.

# - No explicit support for xml processing instructions
# - No explicit support for comments
# - Lacks support for escaping xml entities
# - No support for a predefined offset to start the indentation form
# - Fixed, non-configurable 2 space indentation
# ...
class SimpleBuilder < BasicObject
  def method_missing(name, *args, &block)
    @level ||= 0
    @target ||= ::STDOUT
    attrs, text = _split_args_to_attrs_and_text args
    if block
      ::Kernel.fail ::ArgumentError, 'Cannot have text content when sub-structure is given' unless text.nil?
      _indent
      _start_tag name, attrs
      _newline
      begin
        @level += 2
        block.call(self)
      ensure
        @level -= 2
        _indent
        _end_tag name
        _newline
      end
    elsif text.nil?
      _indent
      _start_tag name, attrs, true
      _newline
    else
      _indent
      _start_tag name, attrs
      @target << text
      _end_tag name
      _newline
    end
  end

  private

  def _start_tag(name, attrs, close = false)
    @target << "<#{name}"
    attrs.each do |k, v|
      @target << %( #{k}="#{v}")
    end if attrs
    @target << '/' if close
    @target << '>'
  end

  def _end_tag(name)
    @target << "</#{name}>"
  end

  def _newline
    @target << "\n"
  end

  def _indent
    return if @level == 0
    @target << ' ' * @level
  end

  def _split_args_to_attrs_and_text(args)
    attrs, text = nil, nil
    args.each do |arg|
      case arg
      when ::Hash
        attrs ||= {}
        attrs.merge!(arg)
      else
        text ||= ''
        text << arg.to_s
      end
    end
    [attrs, text]
  end
end

def to_xml(&block)
  sb = SimpleBuilder.new
  sb.instance_exec(&block)
end

Please note that this is a simplified solution lacking some important features which could be essential in a real production system -some of them were mentioned in the implementation as comments above-, but these features could be added later and the goal of this demo was only to show how easy it is to write an internal DSL in Ruby.

This code above was based on Builder which is a Ruby Gem available for all of us and is written by Jim Weirich. You may wish to see that too for a more elaborate solution.

References

  1. Embedded DSL
  2. Ruby
  3. Builder by Jim Weirich
Domain Specific Language Demo in Ruby

My Emacs Settings

“GNU Emacs is an extensible, customizable text editor—and more.” as they introduce it to the readers on the official site of GNU Emacs.

Actually it’s an old thing still in use today. But it’s no wonder so many people like it even now, since it’s flexible, configurable and extensible. It’s built around some powerful core ideas about buffers, editing and so, and provides a LISP dialect the Emacs Lisp to it’s users to extend and configure it’s features. It’s worth to mention, that the modern versions of GNU Emacs comes with a package system, and there are package repositories containing tons of useful packages to choose form.

Side note. The fact Emacs Lisp is a dynamically scoped language might surprise you, since almost all modern programming languages are statically scoped today. Before you would throw a rock on it, you would like to consider that there are cases when it can come in handy. Eg. You can make other parts of the code behave temporary different, without the need to pass arguments around all the way down in the call stack. The dynamic binding is the default in Emacs, but you may opt for lexical binding if needed on a per file basis.

;; -*- lexical-binding: t -*-

(defun make-adder (x)
  (lambda (y) (+ x y)))

To me it’s a versatile platform for doing many text related operations. Starting from source code editing, through project- and file management, to actually testing REST APIs interactively in a minimalist and easy to use style.

There are many awesome repositories on GitHub hosting Emacs settings and configuration for individuals. There were some attempts to provide a minimalistic, standard common ground with enhancements compared to the bare setup a freshly installed Emacs comes with, that fits everyone. Actually it’s a difficult task to do, since what fits all? Probably the most well known example is Technomancy’s Better Defaults for Emacs.

Based on these influencing examples by Technomancy, Magnars and Bodil, I assembled my minimalistic version that fits me well.

I find hosting my Emacs settings on GitHub to be a good idea, because when I move to a new machine, I only need to install Emacs and check out the repo and start Emacs up. And that’s all. All the packages I need are automatically downloaded and installed during the first start.

For my personal Emacs setup, I didn’t like the idea to depend on external, non-standard libraries to be able to install external and non-standard packages. One reason is that these libraries can be installed and updated through the package system and I didn’t like the git submodule binding for this.

Therefore I choose Bodil’s approach to use exclusively pure core Emacs Lisp code to perform this “bootstrapping”.

;; Install packages if not present
(dolist (pkg '(flx
	       flx-ido
	       flycheck
	       markdown-mode
	       paredit
	       projectile
	       restclient))
  (install-package-if-not-installed pkg))

I must also mention that on a Mac, it’s a bit tricky to setup properly to have the user environment settings from the shell right. But don’t worry. It’s not a big deal really. There is a package to the rescue.

;; Are we on a mac?
(defvar is-mac (equal system-type 'darwin)
  "Boolean indicating if we are on a mac")

;; Setup environment variables from the user's shell.
(when is-mac
  (install-package-if-not-installed 'exec-path-from-shell)
  (exec-path-from-shell-initialize))

I like the idea to have the customisation in a separate file. Therefore I put the following code in my init.el file.

;; Keep emacs Custom-settings in separate file
(setq custom-file (expand-file-name "custom.el" user-emacs-directory))
(load custom-file)

Then it’s in a separate file, the custom.el.

(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(js-indent-level 2)
 '(projectile-find-dir-includes-top-level t)
 '(projectile-switch-project-action (quote projectile-find-dir))
 '(scheme-program-name "guile"))
(custom-set-faces
 ;; custom-set-faces was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 )

Are you considering using GNU Emacs?

Pros

  • Powerful and productive environment for text related tasks
  • No need to move your hand between the keyboard and the mouse all the time
  • Many packages for tons of tasks
  • You can modify, bend, and extend it to serve your needs best

Cons

  • Hard to learn all the funny keystrokes
  • It can be hard to learn LISP
  • Steep learning curve

GNU Emacs is an extensible text editor and can be customised to meet individual needs.

To see the the complete code to my Emacs settings, visit my GithHub repo!

My Emacs Settings

Combining ExtJS with Clojure Compojure

Back in 2013, I was working on an R&D project to create a proof of concept on combining the Sencha ExtJS frontend with a Clojure Compojure backend, having a RESTful API in-between.

With this loosely-coupled architecture and way more productive server-side development approach -using Clojure instead of Java- I could demonstrate an alternative to the previous, heavy-weight J2EE backend-based old-school application.

I did have an easy job working on this, since Michael Jakl already posted an example using Compojure for REST API with an in-memory RDBMS.

Also Sencha provided an example on using their REST proxy.

All the remaining work was to blend the parts and to write a unit test for the server side.

The server side code looks like this:

(ns users.handler
  (:import com.mchange.v2.c3p0.ComboPooledDataSource)
  (:use compojure.core)
  (:use ring.util.response)
  (:require [compojure.handler :as handler]
            [compojure.route :as route]
            [ring.util.response :as response]
            [ring.middleware.json :as middleware]
            [clojure.java.jdbc :as sql]))

(def db-config
  {:classname "org.h2.Driver"
   :subprotocol "h2"
   :subname "mem:users"
   :user ""
   :password ""})

(defn pool [config]
  (let [cpds (doto (ComboPooledDataSource.)
               (.setDriverClass (:classname config))
               (.setJdbcUrl (str "jdbc:" (:subprotocol config) ":" (:subname config)))
               (.setUser (:user config))
               (.setPassword (:password config))
               (.setMaxPoolSize 1)
               (.setMinPoolSize 1))]
    {:datasource cpds}))

(def pooled-db (delay (pool db-config)))

(defn db-connection [] @pooled-db)

(sql/with-connection (db-connection)
                                        ;(sql/drop-table :users)
  (sql/create-table :users
                    [:id :int "PRIMARY KEY AUTO_INCREMENT"]
                    [:email "varchar(128)"]
                    [:first "varchar(64)"]
                    [:last "varchar(64)"]))

(defn wrap-ext-store
  "Put the data and message into a map used by the ExtJS REST Store/Proxy"
  [data message]
  {:success true :message message :data data})

(defn get-all-users []
  (response
   (sql/with-connection (db-connection)
     (sql/with-query-results results
       ["select * from users"]
       (-> (into [] results) (wrap-ext-store "Loaded data"))))))

(defn raw-get-user [id]
  (sql/with-connection (db-connection)
    (sql/with-query-results results
      ["select * from users where id = ?" id]
      (cond (empty? results) {:status 404}
            :else (first results)))))

(defn get-user [id]
  (response (-> raw-get-user(id) (wrap-ext-store (str "Feched User " id)))))

(defn create-new-user [user]
  (response
   (sql/with-connection (db-connection)
     (let [usr (dissoc user :id)
           id (first (vals (sql/insert-record :users usr)))]
       (-> (raw-get-user id) (wrap-ext-store "Created new User"))))))

(defn update-user [id user]
  (sql/with-connection (db-connection)
    (let [usr (assoc user "id" id)]
      (sql/update-values :users ["id = ?" id] usr)))
  (response (-> (raw-get-user id) (wrap-ext-store (str "Updated User " id)))))

(defn delete-user [id]
  (sql/with-connection (db-connection)
    (sql/delete-rows :users ["id = ?" id]))
  (response (-> [] (wrap-ext-store (str "Destroyed User " id)))))

(defroutes app-routes
  (GET "/" [] (response/resource-response "index.html" {:root "public"}))
  (context "/users" [] (defroutes users-routes
                         (GET "/" [] (get-all-users))
                         (POST "/" {body :body} (create-new-user body))
                         (context "/:id" [id] (defroutes users-routes
                                                (GET "/" [] (get-user id))
                                                (PUT "/" {body :body} (update-user id body))
                                                (DELETE "/" [] (delete-user id))))))
  (route/resources "/")
  (route/not-found "<h1>Not Found</h1>"))

(def app
  (-> (handler/site app-routes)
      (middleware/wrap-json-body)
      (middleware/wrap-json-response)))

And the whole project can be found on GitHub.

 

Combining ExtJS with Clojure Compojure

Week number vs. Erlang/OTP

Some years ago I had to find out what is the current week number for some reason.

Of course there are common tools like Office/Calendar applications and also the Web for your aid. You can look it up easily. Also there are support for it in many programming language libraries.

However, that time I was working on some Erlang research and found that it’s standard library did lack support for determining week numbers. Then I decided to add it since it did sound like a fun little project and a nice experience in Open Source project contribution.

So I began by researching how to determine week numbers. I found that there are different kind of “week numbers” used by different parts of the World. I found that it’s the ISO Week Number I was looking for.

Then I read the well made contribution description/guideline by Ericsson and based on that I made my contribution to Erlang/OTP with the source, documentation and tests.

The contribution was accepted and is part of the Erlang/OTP now. It serves the needs of people developing Erlang applications and wanting to use the Week Number for some reason.

The code in Erlang looks like this:

%%
%% Calculates the iso week number for the current date.
%%
-spec iso_week_number() -> yearweeknum().
iso_week_number() ->
    {Date, _} = local_time(),
    iso_week_number(Date).


%%
%% Calculates the iso week number for the given date.
%%
-spec iso_week_number(Date) -> yearweeknum() when
      Date :: date().
iso_week_number({Year, Month, Day}) ->
    D = date_to_gregorian_days({Year, Month, Day}),
    W01_1_Year = gregorian_days_of_iso_w01_1(Year),
    W01_1_NextYear = gregorian_days_of_iso_w01_1(Year + 1),
    if W01_1_Year =< D andalso D < W01_1_NextYear ->
	    % Current Year Week 01..52(,53)
	    {Year, (D - W01_1_Year) div 7 + 1};
	D < W01_1_Year ->
	    % Previous Year 52 or 53
	    PWN = case day_of_the_week(Year - 1, 1, 1) of
		4 -> 53;
		_ -> case day_of_the_week(Year - 1, 12, 31) of
			4 -> 53;
			_ -> 52
		     end
		end,
	    {Year - 1, PWN};
	W01_1_NextYear =< D ->
	    % Next Year, Week 01
	    {Year + 1, 1}
    end.

References

Week number vs. Erlang/OTP

My Ruby configuration for tinkering

I don’t want the Gem documentation to be built locally on my system, I refer to the online documentation instead.

Setting this up is actually easy.

Put this in a file called .gemrc in your home directory:

gem: --no-document

I like to use the REPL in Ruby (IRB) to tinker with it, and enjoy the dynamic properties of the language.

Unfortunately out of the box IRB lacks such extremely useful tools like code completion, pretty print and automatic indentation.

The interesting thing is that, IRB can be equipped with such tools right out of the box, but it’s not equipped with any by default. Maybe that’s because they didn’t wanted to enforce one particular setting over others, and wanted to leave it up to the user which one to use.

To automate the setup for each and every IRB session, put the following code in a file called .irbrc in your home directory:

require 'irb/completion'
require 'pp'
IRB.conf[:AUTO_INDENT]=true

Let me mention an alternative to IRB with lots of useful tools like the above and more. Pry – An IRB alternative and runtime developer console

My Ruby configuration for tinkering