Groovy, Grails and Responsive Web Design Stack Overflow

I’ve taken inspiration from Stephen Moretti and his CFOverflow twitter account and started twitter accounts for Groovy, Grails and Responsive Web Design that post the latest questions on each topic from Stack Overflow. For Groovy it posts the latest questions tagged Groovy and the same goes for Grails. I originally set these up as just one feed, but the questions coming in to the two feeds don’t really overlap as much as I thought they might so I decided to split them into two accounts.

For the Responsive Web Design account the latest Stack Overflow posts tagged “media queries” or “responsive design” are posted.

Stephen said he added some filters to prevent duplicates from posting, but I haven’t done that yet. If duplicates start showing up in the feeds I will take a look at the filters.

If anyone thinks other feeds should be added to these accounts let me know and I can get them added. Any feedback at all in appreciated

Groovy questions
Grails questions
Responsive Web Design questions

Registration for Iowa Code Camp is now open!

Registration for Iowa Code Camp is now open. The event is completely free for anyone who wants to attend and includes breakfast and lunch onsite and also an after party hosted by Robert Half Technology.

The event is Saturday, May 9th from 8 am to 5:30 pm at the Hotel Kirkwood in Cedar Rapids. There will be 5 blocks of sessions with 7 sessions going on at a time, so you’re sure to find something you want to attend during each time slot.

There are 100, 200 and even a few 300 level sessions covering topics such as Agile methodologies, DevOps, Ember, Git, Go, Kafka, R and Responsive Web Design. If you attended Iowa Code Camp last November in Ankeny there are many speakers who presented that are presenting again this year on different topics.

I’m speaking at Iowa Code Camp!

I’m happy to announce I’ve been selected to speak at Iowa Code Camp, May 9, 2015 at The Hotel Kirkwood in Cedar Rapids. If you’re interested in attending the cost is absolutely free for anyone wanting to attend and registration will be open shortly. I’ll have a follow up post once registration is open.

I will be speaking about Responsible Responsive Web Design. In the 75 minute talk I’ll be covering what responsive design is and how to build a website using it. I’ll also cover how to design a responsive website responsibly – How you can delivery a consistent user experience to users on small and large screen devices and how to decrease your website’s page size quickly and effectively to make your website load fast even on slow internet connections. Lastly, I’ll cover how to use the newest HTML5 specifications even on browsers that do not have native support.

A big thanks goes out to Scott Jehl, who wrote the book Responsible Responsive Design that inspired this talk.

Checking an HTML page for duplicate IDs using JavaScript

A couple years back I wrote a post about Checking an HTML page for duplicate IDs using jQuery. A pretty useful tool when you need to ensure IDs on a page are unique. The downside to that code was that it required jQuery and the app I’m currently working with does not use jQuery, so I modifed the existing code to write a pure JavaScript solution that does the same thing.

var allElements = document.getElementsByTagName("*");
var allIds = {};
var found = false;
for (var i = 0, n = allElements.length; i < n; ++i) {
  var id = allElements[i].id;
  if (id) {
    if (allIds[id] === undefined) {
      allIds[id] = 1;
    } else {
      found = true;
      console.warn('Duplicate ID #' + id);
    }
  }
}
if (!found) {
  console.log('No duplicate IDs found');
}

All you need to do is create a new bookmark with the following as the URL

javascript: (function() {var allElements = document.getElementsByTagName('*');var allIds = {};var found = false;for (var i = 0, n = allElements.length; i < n; ++i) {var id = allElements[i].id;if (id) {if (allIds[id] === undefined) {allIds[id] = 1;} else {found = true;console.warn('Duplicate ID #' + id);}}}if (!found) {console.log('No duplicate IDs found');}})();

Or you can simply drag the bookmarklet below onto your bookmark toolbar

Duplicate ID Checker

Update: Ryan Guill let me know he wrote something similar and he’s saved it as a Gist. It’s interesting seeing the different approaches to accomplish the same thing.

Firefox Open Pop Ups as Tabs

We have an application at work that was built for IE 5.5, so this may have made sense at some point, but it opens up 3 new windows before you actually get to the useful part of the application. In Chrome you can right click on the title bar and choose “Show as Tab”, but Firefox doesn’t have that option. Thankfully there’s an about:config setting you can change to force all pop ups to render into a tab rather than a new window.

If you’re not familiar with about:config simply type about:config into the address bar and hit go, just like it’s a normal url. You will likely get a warning about “voiding your warranty”. Click “I’ll be careful, I promise!” and the search for newwindow. You will see an entry with a Preference Name of “browser.link.open_newwindow.restriction” and a value of 2. Change that value to 0 and all pop ups will open as tabs.

newwindow

Adding the stack trace to a Java Server Page error page

I’ve recently been switched to a Java project and one of the most frustrating parts of the application (other than barely knowing Java) is the error page would only show a “An error as occurred” message and not the actual stack trace. In production this is a perfectly valid scenario, but when developing having to go back to RAD and scroll through the console to find the error message was wasting a lot of time, so after a decent amount of googling I found a way to dump the stack trace to the page.

The code ended up looking like this. In the message board post they used exception instead of error, but hopefully you get the point.

<jsp:useBean id="error" scope="request" class="java.lang.Throwable" />
  <%
    Object billingError = request.getSession().getAttribute(RequestParamConstants.UNKNOWN_BILLING_ERROR);
    error = (Throwable)billingError;
  %>
  <%@page isErrorPage="true" import="java.io.*"%>
  <pre>
    <%
      error.printStackTrace(new PrintWriter(out));
    %>
  </pre>

A while after implementing this I ran into an error where the first line was about 400 characters long, so I had to scroll way over to the right. This is because by default the pre tag does not wrap, so I added this simple css fix which allows the pre tag to wrap

pre { white-space: pre-wrap;}

Using an if statement to conditionally run a target in Hudson

We’re running a horribly outdated version of Hudson at work (2.2.1), so this may not be relevant for people using a version of Hudson updated in the past 4 years. I was trying to conditionally run a block of code in a Hudson build and thought by setting parameters in the Ant build properties I could turn off running unit tests (based on looking at other build XML files).

I had this code in my Ant build properties

do.test=false

This didn’t work, so I echoed the value into the console and it was correctly registering at false, but the tests were still being ran.

 <echo message="Do test? ${do.test}" />
  <target name="test" depends="compile" description="execute unit and functional tests" if="do.test">
    <cobertura-instrument todir="${temp.dir}/instrumented-classes" datafile="${temp.dir}/cobertura.ser">
    </cobertura-instrument>
  </target>

After quite a while trying to find an answer through Google I found out if there’s a parameter called do.test with ANY value then that is a true statement and the block will run. My solution was to rename the parameter to _do.test. You could obviously also delete the parameter, but once I had resolved my build issue I was going to turn the tests back on.

Converting roman numerals to numbers using Groovy/Grails

I wrote up a post last week about my experience converting roman numerals to numbers using ColdFusion and I promised a follow up doing the same thing in Grails.

I did learn an interesting tidbit about Grails, the maximum numbers of tests you can have in a where clause is 999. Not a big deal as this is a somewhat contrived example, but something to note nonetheless. Without further ado here is my code, once again this assumes you have entered a valid roman numeral and I’ve tested the accuracy up to 2000.

class RomanService {
  Integer romanToDecimal(String romanNumber) {
    Integer newNumber = 0, previousNumber = 0
    Map romanToNumberMapping = [M:1000, D:500, C:100, L:50, X:10, V:5, I:1]
    for (Integer oneChar = romanNumber.length() - 1; oneChar >= 0; oneChar--) {
      String oneLetter = romanNumber.charAt(oneChar)
      newNumber = processNumber(romanToNumberMapping[oneLetter], previousNumber, newNumber)
      previousNumber = romanToNumberMapping[oneLetter]
    }
    return newNumber 
  }

  Integer processNumber(Integer currentNumber, Integer previousNumber, Integer newNumber) {
    return previousNumber > currentNumber ? newNumber - currentNumber : newNumber + currentNumber
  }
}

On the whole it’s really not much different than the ColdFusion version, semicolons are optional in most places (pretty much anything that’s not a for loop) and you can strongly type the return values, although that’s definitely not a requirement. I wrote the example above exactly how I’d write it for a project, but also wanted to point out some of what I’m doing isn’t really required.

One interesting thing about Groovy and not one I’m terribly fond of is if you don’t have a return statement the last piece of code executed is returned, so newNumber doesn’t need a return statement in the romanToDecimal function and in processNumber the only line is returned. I’ve left the return statements off in the code below, but it’s not something I’d normally do, it saves .1 seconds of typing to not type it and can make the code confusing in my opinion. I also left off the types of variables, but my opinion is the same as not typing out return, it doesn’t save much time to not declare the type and it can cause some unnecesary confusion especially when it’s left off in the arguments.

class RomanService {
  def romanToDecimal(romanNumber) {
    def newNumber = 0, previousNumber = 0
    def romanToNumberMapping = [M:1000, D:500, C:100, L:50, X:10, V:5, I:1]
    for (def oneChar = romanNumber.length() - 1; oneChar >= 0; oneChar--) {
      def oneLetter = romanNumber.charAt(oneChar)
      newNumber = processNumber(romanToNumberMapping[oneLetter], previousNumber, newNumber)
      previousNumber = romanToNumberMapping[oneLetter]
    }
    newNumber
  }

  def processNumber(currentNumber, previousNumber, newNumber) {
    previousNumber > currentNumber ? newNumber - currentNumber : newNumber + currentNumber
  }
}

I’ve attached my test case as an external file given the size

Converting roman numerals to numbers using ColdFusion

I recently worked on a project that required translating roman numerals to the numerical counterpart, this needed to work for anything from 1-2000. I wrote my own using TDD and eventually came up with this

component {
  public function romanToDecimal(romanNumber) {
    var newNumber = 0;
    var previousNumber = 0;
    var romanToNumberMapping = {M:1000, D:500, C:100, L:50, X:10, V:5, I:1};
    var romanNumeral = ucase(romanNumber);
    for (var oneChar = romanNumeral.length() - 1; oneChar >= 0; oneChar--) {
      var oneLetter = romanNumeral.charAt(oneChar);
      if (previousNumber > romanToNumberMapping[oneLetter]) {
        newNumber-=romanToNumberMapping[oneLetter];
      } else {
        newNumber+=romanToNumberMapping[oneLetter];
      }
      previousNumber = romanToNumberMapping[oneLetter];
    }
    return newNumber;
  }
}

It’s simple enough that you should be able to add each roman numeral and it’s number into the mapping and this should theoretically work for any roman numeral, but I only tested up to 2000. This assumes that you have entered a valid roman numeral that can be translated to 1-2000.

The tests are written in MXUnit, so it’s a lot of repetition. I’ll be following up with a groovy example using spock that should have a much cleaner looking test. I’ve attached the test file and additionally have submitted this to cflib for approval.

You can download the test here if you’re so inclined.

Enabling multiple cursors based on a selection in Sublime Text

I was writing a bunch of unit tests for a roman numeral translator function that I’m working on and I was copy/pasting the number and roman numeral from a few websites to validate my function was correction. My plan is to write a test for the first 5000 roman numerals, but using ctrl+d to make 5000 selections and format the selection correctly was going to take quite a while and I knew there had to be a better way.

I googled around for a while and eventually found this Stack Overflow answer. You can enable multiple cursors by making a selection and then pressing ctrl+shift+l (l as in Linux). The cursors will be automatically placed at the end of the line, but you can use ctrl+shift+left arrow key (windows command) to move word by word through your selection.

This option is also available from the Sublime menu by going to Selection > Split into Lines, where it will also tell you the shortcut if you’re not using Windows.

Keep in mind, once you’re past a couple hundred selections Sublime can be very slow even on a fast computer, so be patient if you’re enabling hundreds of cursors.