Yay! Got 10 out of 10 in Week 6: Collections in Scala course at Coursera

scala-logoThank you, thank you, Coursera, Martin Odersky and his team, Michał, Thomas, and whoever has helped me to learn so much and at long last sorted the assignment out! I could score 10 out of 10 in Week 6: Collections in the course Functional Programming Principles in Scala at Coursera.

coursera-scala-week6-results

I can finally go to bed without worrying I couldn’t finish the assignment on time! I was tearing my hair out trying to get the job finished on time and I even asked people around about additional tips as it seemed I might’ve not found the solution.

After almost a week of very intensive labours, my dear friend Michał Fijołek sent me a hint – the thread sentenceAnagrams Suggestions on the course’s discussion forum in which I found missing pieces to the puzzle! Without the hint I would certainly not have sorted it out, but fortunately I was close. When I followed the advices given in the very first email in the thread, I reorganized my code and all of a sudden the very first test run finished without any errors! I couldn’t believe my eyes. I thought they’re deceiving me.

When I submitted the code, the time the result took to show up lasted forever. The result was available after a very, very, very long 2 minutes and 10 out of 10 was the most amazing end of the day. Just a day before the final submission date I passed the tests! All of them!

Thanks Michał and Thomas Otani (who wrote the email in the golden thread)! You made my day and I’m very grateful.

On to Week 7: Lazy Evaluation.

Languages Leave a comment

If in Scala, pattern matching might not always be elegant

I like simple solutions and I usually very easily adapt behaviors that reflect similar approach. I quickly learnt pattern matching as a way to destructure collections and sequences in Scala. So quickly that I almost forgot about the plain old if expression. Too bad, Jacek!

I’ve just noticed that once I got used to pattern matching in Scala I kept writing applications as follows:

list match {
    case Nil => // do something with an empty collection
    case head :: tail =>
        // do something with a non-empty collection when destructuring is of help
}

It struck me when I went as far as to use pattern matching for a check of emptiness vs non-emptiness yet I didn’t want to have the list to be destructured.

list match {
    case Nil => // do something with an empty collection
    case _ => // do something with a non-empty collection
}

Notice the last case expression with a catch-all _ wildcard. It was ridiculous to use pattern matching when the if expression was all I actually needed. That’s why I believe that pattern matching might not always be the most elegant approach and the plain, old if expression might be better.

if (list.isEmpty) // do something with an empty collection
else // do something else with a non-empty collection

It’s much more elegant for me. Hopefully, it’s a more idiomatic code, too. Is it?

You may be asking yourself, when do I care about the case of an empty list and don’t bother about destructuring? I’d love hearing your thoughts about it before I share mine. Go ahead and teach me a bit of Scala!

Languages 11 Comments

Huffman Coding for 10 ends up 6 due to late submission in Functional Scala at Coursera

My schedule didn’t work out well for the past weeks. I simply couldn’t spare much time for a few self-learning activities and so I couldn’t submit the programming assignment for Huffman Coding (Week 4: Types and Pattern Matching) in the course Functional Programming Principles in Scala at Coursera earlier.

1,5 days later I scored the maximum – 10 out of 10, but with the penalty of 20% less a day after the due date I ultimately ended up with 6.

coursera-week4-results

What the course has learnt me is more valuable than the score itself, tough. I’m getting used to Scala’s tools like Scala’s REPL and sbt, and at the end of the week at Coursera my working environment was Sublime Text 2 and a terminal that looked as follows.

coursera-week4-sbt-test-repl-git-terminals

I’ve got the upper window for sbt ~test, the middle for Scala REPL and finally the bottom for git. It worked so well that I have just upgraded IntelliJ IDEA to 12.1.2 in the meantime even though I promised myself to use IDEA more often.

I also submitted the question Idiomatic search of value in a list of element-value pairs in Scala at StackOverflow and got 5 points more.

Languages Leave a comment

When in Scala REPL, :paste might be your better friend (than :load)

I’ve been following Odersky’s Functional Programming Principles in Scala at Coursera and when I’ve been asked to tackle a programming problem I ended up with the following:

sealed trait A {
  def show: String = this match {
    case AA(n) => "AA(%s)".format(n)
    case a @ _ => "Wish I knew how to show " + a
  }
}
case class AA(n: Integer) extends A

Since I’ve been writing the application in Sublime Text 2 and copying and pasting it to Scala REPL, the only result I’ve been getting were the following errors:

$ scala
Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> sealed trait A {
     |   def show: String = this match {
     |     case AA(n) => "AA(%s)".format(n)
     |     case a @ _ => "Wish I knew how to show " + a
     |   }
     | }
<console>:9: error: not found: value AA
           case AA(n) => "AA(%s)".format(n)
                ^
<console>:9: error: not found: value n
           case AA(n) => "AA(%s)".format(n)
                                         ^

scala> case class AA(n: Integer) extends A
<console>:7: error: not found: type A
       case class AA(n: Integer) extends A
                                         ^

:load A.scala didn’t work either.

scala> :load A.scala
Loading A.scala...
<console>:9: error: not found: value AA
           case AA(n) => "AA(%s)".format(n)
                ^
<console>:9: error: not found: value n
           case AA(n) => "AA(%s)".format(n)
                                         ^
<console>:7: error: not found: type A
       case class AA(n: Integer) extends A
                                         ^
<console>:8: error: not found: value AA
              println(AA(1).show)
                      ^

When I defined an empty trait A first so I could get passed the error, I got another.

scala> sealed trait A
defined trait A

scala> case class AA(n: Integer) extends A
defined class AA

scala> sealed trait A {
     |   def show: String = this match {
     |     case AA(n) => "AA(%s)".format(n)
     |     case a @ _ => "Wish I knew how to show " + a
     |   }
     | }
<console>:12: error: constructor cannot be instantiated to expected type;
 found   : AA
 required: A
           case AA(n) => "AA(%s)".format(n)
                ^
<console>:12: error: not found: value n
           case AA(n) => "AA(%s)".format(n)
                                         ^

Now, I’ve been facing two issues :( I’ve been fooled by

error: constructor cannot be instantiated to expected type

and spent hours googling to figure out what was wrong.

Right before I submitted a question on StackOverflow, I remembered :paste to paste an entire application so it’s compiled as a single compilation unit. That was that!

scala> :paste
// Entering paste mode (ctrl-D to finish)

sealed trait A {
  def show: String = this match {
    case AA(n) => "AA(%s)".format(n)
    case a @ _ => "Wish I knew how to show " + a
  }
}
case class AA(n: Integer) extends A

// Exiting paste mode, now interpreting.

defined trait A
defined class AA

It looks I might need a bit more support from tools than what I got from Sublime Text 2 and Scala REPL as I’m simply still in my infancy of developing applications in Scala. Lesson learnt.

Languages 1 Comment

10 out of 10 in Week 3: Data and Abstraction in Scala course at Coursera

scala-logoI can’t explain how happy I am! At long last I could score 10.00 out of 10.00 in the part Object-Oriented Sets (Week 3: Data and Abstraction) in the course Functional Programming Principles in Scala at Coursera. It took me almost 3 weeks of a very intensive mental exercise to finally make it and I’m pretty sure I wouldn’t have achieved it without the tests that were part of the assignment and many more I wrote myself.

The exercise has therefore proved to me that the idea of writing tests is the only viable approach to tackle programming assignments.

I used to think that writing standalone applications could replace tests. It had been working fine for my self-study exercises, but didn’t work for the exercises at Coursera. Since they were part of the assignment it’d have been weird not to leverage their existence that eventually led me to writing even more. I enjoyed the activity so much.

coursera-week3-results

Before I could see the above result, I submitted four other solutions with the maximum score of 9.94. I used git to keep the sources under control and compare the previous submissions that also helped a lot – when I wasn’t satisfied with the results I simply checked out another version and started over.

What I found very productive was to have sbt console open with ~test. When I saved a test or a class it automatically fired up the tests and gave me a result. It was so much easier than re-executing sbt test or test in the sbt console every change.

All in all, git, ScalaTest, sbt’s ~test and many late-night hours of rewriting the code and reading the discussions on the course’s forum made the score of 10 out of 10 achievable. It was painful mental-wise, but the final result did make my day.

I’m yet to submit the other exercise Huffman Coding of Week 4: Types and Pattern Matching by Sun 28 Apr 2013 11:59 PM CEST +0200 to score high. It’s certainly not an easy task given I’ve got 2 days left. It’s gonna be tough. Wish me luck.

Languages Leave a comment

git init, add and commit or checkout for programming assignments (at Coursera and beyond)

The project I’m assigned to requires the team to migrate an application to IBM Business Process Manager Advanced V8 platform. It takes time to make that happened and I’ve been struggling with reverting unnecessary changes during the migration. The process of introducing a change, testing it, reverting or reviewing the list of already-made changes has been complicated enough not to mention the application itself.

What the refreshing feeling it was when I began using git for change management system. Many may have experienced it as well, and guess I’d had to figure it out myself (= all were already riding their bicycles, and yet I was reinventing the wheel).

It happened just a couple of days ago, but am wholeheartedly into using it every time and everywhere.

I’m doing the course Functional Programming Principles in Scala at Coursera and as the idea to version the course assignments struck me, I knew I should be using git again. When I don’t need a change (= it doesn’t work as expected) I simply revert it without relying on Ctrl-Z or similar.

jacek:~/sandbox/scala-coursera
$ unzip objsets.zip
Archive:  objsets.zip
   creating: objsets/
   ...
jacek:~/sandbox/scala-coursera
$ cd objsets
jacek:~/sandbox/scala-coursera/objsets
$ git init .
Initialized empty Git repository in /Users/jacek/sandbox/scala-coursera/objsets/.git/
jacek:~/sandbox/scala-coursera/objsets
$ git add .
jacek:~/sandbox/scala-coursera/objsets
$ git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#     new file:   .classpath
#     new file:   .project
#     new file:   .settings/org.scala-ide.sdt.core.prefs
#     new file:   build.sbt
...
jacek:~/sandbox/scala-coursera/objsets
$ git commit -m 'Initial commit'
[master (root-commit) 8e5f0fe] Initial commit
 26 files changed, 2903 insertions(+)
 create mode 100644 .classpath
 create mode 100644 .project
 create mode 100644 .settings/org.scala-ide.sdt.core.prefs
 create mode 100644 build.sbt
...
jacek:~/sandbox/scala-coursera/objsets
$ git status
# On branch master
nothing to commit (working directory clean)

It takes so little that I git every assignment I’m in. Very useful and certainly no-brainer anymore.

Tools 1 Comment

IntelliJ IDEA 12.1 on Java 7 on Mac OS X still experimental?

With Java 8 coming and Java 6 unsupported it’s quite surprising to find out that Java 7 is still not yet on a par with the mentioned versions for many tools.

I’ve been a passive user of IntelliJ IDEA for quite some time now, and I remember I made a few attempts to become more active with its use. But it’s quite recently when I decided to fully embrace the IDE as the IDE of my choice.

With the support of WebSphere Liberty Profile, Scala, Maven and many others, I’m into the IDE for April and perhaps for the months to come. I do think I should have made that happened long before, though.

I’m on Mac OS X 10.8.3 and Oracle has just released Java™ SE Development Kit 7, Update 21 (JDK 7u21). In the meantime, I came across the blog entry Setting up for scala development on Android where I read about developing Android applications in Scala with OpenJDK 7.

I fired up IntelliJ IDEA 12.1 to find out it still uses Java 6.

With the thread IDEA on JDK 7 – now that Mac OS X is officially supported I learnt that it’s possible to run IDEA with Java 7, but it should still be considered, well, experimental.

I changed /Applications/IntelliJ\ IDEA\ 12.app/Contents/Info.plist so it contained “JVMVersion” => “1.7*” (use plutil -p to inspect the settings).

It did use Java 7, but the flickering appears and it’s barely possible to display the About IntelliJ IDEA popup window – it shows up and almost instantaneously disappears.

about-intellij-idea-java-7

Any tips how to improve the situation? Are there use cases where IDEA with Java 7 should not be used at all?

Tools 2 Comments

Implementing RESTful services with JAX-RS and WebSphere 8.5 Liberty Profile

“At long last” one could say as exploring the JAX-RS (The Java API for RESTful Web Services) support in WebSphere Application Server V8.5 Liberty Profile (WLP) has been on the TODO list of mine for so long.

In the forum WASdev there was a thread about Multipath form data and variable-length input forms with Strings and Files that encouraged me to give the task a whirl and play with the JAX-RS implementation in WLP (the latest refresh as of March).

Read it yourself in the article Implementing RESTful services with JAX-RS and WebSphere 8.5 Liberty Profile and let me know your thoughts.

Java EE, WebSphere , Leave a comment

Deploying Play Framework applications onto WebSphere Liberty Profile

For the past couple of days I’ve been looking into developing enterprise applications in Scala with WebSphere Liberty Profile as the runtime environment (aka application server).

It’s worked fine so far as you can read in two articles of mine:

With so much success (it shouldn’t come as a surprise that at the beginning of a long journey every step is a great success) I’ve been thinking about something a bit more complex that would really demonstrate a production-ready support for Scala in WebSphere Liberty Profile. And all of a sudden a challenge came along – developing Play 2.1 applications with WebSphere Liberty Profile. That was it!

But hey, no built-in support for deploying Play applications onto Java EE application servers?! How could that be? I can understand the point that it’s so much easier to have a hosted runtime environment inside the framework (so it’s just play run to have your application up and running quickly), but there are some valid reasons to deploy the applications onto a full-blown Java EE application server.

You may want to read README in WAR Plugin for Play framework 2.x to find out some of the reasons for “Why choosing WAR packaging when native Play 2 is a better deployment model (features and performances)?”

Speaking of WAR Plugin for Play framework 2.x, that’s the approach people (tend to) recommend when there’s a need to deploy Play applications onto Java EE application servers.

In Server compatibility I couldn’t find any version of WebSphere Application Server and as a matter of fact there was the following sentence: “The plugin may work on others containers, such as Weblogic or Websphere (not tested yet).”

I wore my “entrepreneur” hat and my mission began.

It took a few minutes to have the plugin set up for my simple Play project and dropping the result of play war to the dropins directory of a WebSphere Liberty Profile server was all it took to have the application up and running.

Play's Welcome Page in WebSphere Liberty Profile

No need to do much – play war and cp target/helloplay-1.0-SNAPSHOT.war ~/apps/wlp.next.BETA/usr/servers/defaultServer/dropins did the trick. Easy.

What worried me though was that the page didn’t resemble the look of the page when executed with play run.

Play's Welcome Page in play run

It was way after midnight when I noticed it and was a bit tired to figure it out. Since the exercise was supposed to be quick and easy, I jotted down my findings and scheduled another session with the environment early morning.

That turned out a very productive decision!

After a quarter of self-learning how the sample application worked (created with play new helloplay) the most important piece turned out the app/views/index.scala.html.

@(message: String)

@main("Welcome to Play 2.1") {

    @play20.welcome(message, style = "Java")

}

Note the line @play20.welcome(message, style = "Java"). The page’s source is in welcome.scala.html and what drew my attention was the following line:

@play.api.Play.maybeApplication.filterNot(_.mode != play.api.Mode.Dev).map { _ =>

I knew I nailed it down. When running the application with play run the following was printed out to the console:

[info] play - Application started (Dev)

When the application got started in WebSphere Liberty Profile there was the following line in the logs:

[info] play - Application started (Prod)

That made the difference in the welcome pages. Easy, isn’t it?

BTW, I have not managed to find out how to change Prod to Dev environment for a Play application deployed onto WebSphere Liberty Profile. Anyone?

Frameworks, Languages, WebSphere , , Leave a comment

New article about Scala and WebSphere Liberty Profile and niceties of latest updates

Hot on the heels of my new article Scala as Shared Library for Java EE applications in WebSphere 8.5 Liberty Profile about Scala as the language for developing Java EE enterprise applications with the Scala jars shared amongst applications using the Shared Library feature of WebSphere 8.5 Liberty Profile, the teams behind WebSphere Liberty Profile and Scala IDE decided almost simultaneously to release updates to their products.

Luckily, it hasn’t taken long to update the development environment and the article itself. You can appreciate how simple the article became with the latest and greatest of WebSphere Liberty Profile, WebSphere Developer Tools and Scala IDE. I think it will take a bit longer before I switch the environment to some other fancy setup, if any.

Let me know how the article Scala as Shared Library for Java EE applications in WebSphere 8.5 Liberty Profile reads and where it needs further improvements.

I’m a strong believer that such contributions should rather be recorded as screencasts not described as an article, but before drawing conclusions I’d love hearing your thoughts on the matter. I’d appreciate.

To be honest, the article was my first attempt at using the Download and Install feature of WDT where you can download WebSphere Liberty Profile from Internet and install it to whatever directory you wish. Read and see it in the article’s Registering WebSphere Liberty Profile in Eclipse.

When I updated the tools I no longer meant to download WLP myself, but hand it over to WDT to do it for me instead. I clicked the Download or install a new runtime environment link, selected Download and install a new runtime environment from option with IBM WebSphere Application Server V8.5.Next Beta Liberty Profile download site chosen and then all of a sudden a popup window showed up that I had never seen before.

wdt-beta-liberty-profile-extended-download-site-add-on

I clicked Click to Install and then the Next > button to be presented with the familiar window to select the folder to install the runtime environment, but what was different that instead of one – wlp-developers-runtime-8.5.next.beta.jar – there were two jars – wlp-developers-extended-8.5.next.beta.jar and the other.

wdt-beta-liberty-profile-installation-folder-for-betas

What do I need the wlp-developers-extended-8.5.next.beta.jar for? Does “the more the better” apply here? I’ll see in…81.5 MBs.

In the meantime I’ll read New and Noteworthy in the WebSphere Application Server, WebSphere Developer Tools, and Rational Application Developer Betas.

Java EE, Languages, Tools, WebSphere , , Leave a comment