Thursday 31 October 2013

Joda Time - handling of end of February when DateTime.plusMonths() is called

Overheard a colleague at work with an issue re: February and got
curious enough to see what Joda-Time does in handling this scenario:

// if current date is 31st, how will joda-time handle setting month to february?
dt = new DateTime();
println "now: " + dt.toString();
futureDt = dt.plusMonths(4);
println "4 mos in future: " + futureDt.toString();

OUTPUT

now: 2013-10-31T15:29:53.628+11:00
4 mos in future: 2014-02-28T15:29:53.628+11:00

Nice.

The Groovy Shell functionality within IntelliJ IDEA makes quick
playing around like this a breeze!

Friday 25 October 2013

Phatch - Photo Batch Processor

Found myself having to generate different resolutions of images.
Originally planned to use ImageMagick from a ruby script but came
across something quicker and easier - Phatch on Linux.

http://photobatch.wikidot.com/

(TO UPDATE THIS POST)

Thursday 4 July 2013

Building strings in javascript

Instead of StringBuilder, we use an array and just append to the end of array.

http://trephine.org/t/index.php?title=Efficient_JavaScript_string_building


http://dev.opera.com/articles/view/efficient-javascript/?page=2#primitiveoperator

/**
* Constructs an html string from any number of lists of data items.
*/
function buildList( /* list1, list2, ... */ ) {
var buf = [ "<ul>\n" ];
for (var i=0; i<arguments.length; i++) {
var list = arguments[i];
for (var j=0; j<list.length; j++) {
buf[buf.length] = "<li>"; // append <li> tags and
buf[buf.length] = list[j]; // item to array buffer, utilizing
buf[buf.length] = "</li>\n"; // primitive array assignment
}
}
buf[buf.length] = "</ul>";
return buf.join('');
}

Wednesday 19 June 2013

Workaround for Ubuntu 12 bug with Chrome - can't rearrange tabs

I have started using OneTab plugin to do this, where I would collapse
all tabs into a OneTab page, then rearrange them, but this would also
work:

https://bugs.launchpad.net/ubuntu/+source/unity-2d/+bug/935713/comments/11

"Two workarounds for this:

To move tabs left or right in a single window you can use
Ctrl+Shift+PgUp and Ctrl+Shift+PgDown.

To move tabs between two Chromium windows you need to set the
destination window to be "Always on top". Then dragging a tab from the
source window to the destination would actually allow the tab to be
inserted in the destination window, as expected."

Monday 10 June 2013

From an ex-friends' post on St Augustine.

"That is why the Philippines is one of, if not the most blest people
in this earth by God. Suffering is strongest in Love and it works both
ways, for God and us his people. That is the reason why life in the
Philippines is always difficult. No man or anybody is meant to make it
otherwise, because God harvests millions of souls from our country. He
gives our people suffering as a divine gift in purifying souls that is
a requirement for us to enter the kingdom of God. He loves us so much
that suffering is His blessing so that we will always love Him back
above all else, and never look elsewhere."


I can't believe it. This is from a guy named after a leader of the
Russian Revolution. What happened? What made him give up, to accept
that suffering is our lot in life and is a blessing? What twisted
logic! What kind of insecure 5-year old god is this, to make people
suffer so that they pay more attention to him? Accept your situation,
don't try to make it better, suffering makes you better for the
afterlife. Holy shit.


Oh wait, Sherlock. What if there is no afterlife? What if this is all
we have? What then? No second chances, no upgrades to first-class at
journey's end. What have you done with your life if all you did is
suffer, hoping that you get a better deal in the next one?

Monday 27 May 2013

JQuery: Toggle display of a div

Javascript:

// show 'more-attributes' for ad if user clicks 'Show attributes' link
$('.show-hide-attributes').live('click', function () {
var $this = $(this);
$(this).closest('.meta-attrbt').find('.more-attributes').slideToggle(0,
function () {
$this.text($(this).is(':visible') ? "Hide attributes" :
"Show attributes");
});

return false;
});


HTML

<dd class="p-ads-dd meta-attrbt">
<a class="show-hide-attributes" href="#">Show attributes</a>
<div style="display: none;" class="more-attributes">
<p>Attribute 1: This is a detail</p>
<p>Attribute 2: This is another detail</p>
<p>Areas of expertise: Expertise 1</p>
<p>Areas of expertise: Expertise 2</p>
</div>

</dd>


JSFiddle:

http://jsfiddle.net/25QC7/



Attach function to click event of .show-hide-attributes

We are using classes ('more-attributes', 'show-hide-attributes)
because there are multiple instances of these on the page.

We are using .find() to attach the slideToggle() because there are
multiple rows containing these attributes. Each set of attributes is
specific to a single record.

Added function to slideToggle() so that label changes from 'Show
attributes' if attribute div is hidden, to 'Hide attributes' if the
div is displayed.

Tuesday 14 May 2013

Java: Anti-pattern - make your method names as terse as possible.

Just came across a mock class used in unit tests that has:


cr()

b()

Of course there was no doco on the method names.

Took me a while to realise this was:

create()

build()


So why the fuck did they have to make them that short? Probably
because they were using vi.

Thursday 9 May 2013

IntelliJ: recommended vmoptions settings to improve performance

Currently using these settings

-Xms512m
-Xmx2048m
-XX:MaxPermSize=512m
-XX:ReservedCodeCacheSize=256m
-XX:+UseCodeCacheFlushing
-XX:+UseConcMarkSweepGC
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true

If that doesn't work, I'll try and update bin/idea64.vmoptions to:

-server
-Xms1024m
-Xmx1024m
-XX:NewSize=128m
-XX:MaxNewSize=128m
-XX:PermSize=256m
-XX:MaxPermSize=256m
-XX:+UseParNewGC
-XX:ParallelGCThreads=4
-XX:MaxTenuringThreshold=1
-XX:SurvivorRatio=8
-XX:+UseCodeCacheFlushing
-XX:+UseConcMarkSweepGC
-XX:+AggressiveOpts
-XX:+CMSClassUnloadingEnabled
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:+CMSParallelRemarkEnabled
-XX:CMSInitiatingOccupancyFraction=65
-XX:+CMSScavengeBeforeRemark
-XX:+UseCMSInitiatingOccupancyOnly
-XX:ReservedCodeCacheSize=64m
-XX:-TraceClassUnloading
-ea
-Dsun.io.useCanonCaches=false



REF: http://p7h.blogspot.com.au/2012/12/intellij-idea-tuning-parameters.html

Monday 6 May 2013

UNIX: Copy a file to multiple subdirectories

I have a directory tree and in each of the lowest level directories, I
have a file called "attributes"

I've updated the contents of one of them, and want to copy it to the
other directories.

1. Find the files
find . -name attributes > target_directories.log

2. Edit "target_directories.log" and remove the "attributes" so it is
a list of subdirectories.

./building_trades/carpentry/attributes
./building_trades/concreting_paving/attributes
./party_catering/attributes

becomes

./building_trades/carpentry/
./building_trades/concreting_paving/
./party_catering/

Do this in vi using:

:%s/search_string/replacement_string/g

:%s/\/attributes/\//g

We have to use the / in our search and replace, as doing

:%s/attributes//g

didn't seem to work

The "\" has to be there to escape the "/" character

3. Copy our updated file to other subdirectories:

cat target_directories.log |xargs -n 1 cp attributes

Friday 3 May 2013

Unix: replacing a block of text in multiple files

I was trying to do this in IntelliJ using Structural Search but this
function doesn't seem to work on non-recogised files (ie, java/ xml/
etc).. I just wanted to replace the contents of a plain text file with
a larger block of text.

Ended up doing this manually but if I wanted to fiddle, perhaps this
approach using sed would have been the right way to go:

http://stackoverflow.com/questions/6524896/unix-easiest-way-of-recursively-replacing-a-block-of-multi-line-text

Thursday 2 May 2013

JQuery: disable options on a 2nd select box, when a specific selection is chosen in 1st select box

Backing up this JSFiddle I was playing around with at:

http://jsfiddle.net/hatft/3/


Scenario:

* User has selectboxes to enter "Opening hours", starting time and
closing times using two select boxes.

* When user selects "Closed" in first selectbox, the 2nd select box
must not allow the user to choose any times, and must have "-" as the
value.

* When user changes from "Closed" to some other value, the 2nd select
box must work as normal, allowing user to choose anything

Strictly speaking, we would probably want to do more validation so that:

- closing time is mandatory when start time is selected
- closing time is not earlier than starting time


HTML:

<h3 class="margin-bottom10">Your opening hours</h3>

<table>
<tbody>
<tr class="opening-hours-mon-fri display_none">
<td>Monday</td>
<td>
<select id="postad-monFrom" name="openhrs_mon_from">
<option>Please select</option>
<option value="closed">Closed</option>
<option value="0:00am">0:00am</option>
<option value="0:30am">0:30am</option>
<option value="1:00am">1:00am</option>
</select>
<!--<label for="postad-monTo">to</label>-->to
<select id="postad-monTo"
name="attributeMap[appliance_phone_repair.openhrs_mon_to_s]">
<option></option>
<option value="-">-</option>
<option value="0:00am">0:00am</option>
<option value="0:30am">0:30am</option>
<option value="1:00am">1:00am</option>
</select>
</td>
</tr>
<tr class="opening-hours-mon-fri">
<td>
<label for="postad-tuesFrom">Tuesday</label>
</td>
<td>
<select id="postad-tuesFrom"
name="attributeMap[appliance_phone_repair.openhrs_tues_from_s]">
<option>Select time</option>
<option value="closed">Closed</option>
<option value="0:00am">0:00am</option>
<option value="0:30am">0:30am</option>
<option value="1:00am">1:00am</option>
</select>

<label for="postad-tuesTo">to</label>

<select id="postad-tuesTo"
name="attributeMap[appliance_phone_repair.openhrs_tues_to_s]">
<option></option>
<option value="-">-</option>
<option value="0:00am">0:00am</option>
<option value="0:30am">0:30am</option>
<option value="1:00am">1:00am</option>
</select>
</td>
</tr>
</tbody>
</table>



JAVASCRIPT (uses jQuery 1.6.4)


// TEST SELECTORS BY CHANGING BKGROUND COLOR
//$('[class^="opening-hours-"]').css("background-color", "red");
$('[class^="opening-hours-"]').find('select[id$="From"]').css("background-color",
"yellow");

/*

TIL:

1. You need to use .nextAll() instead of .next()

next() ONLY WORKS IF THE SELECT BOX IS THE NEXT ELEMENT.

IF THERE IS ANYTHING IN BETWEEN, LIKE A <label>, then this won't work.

the earlier version of this only works because "to" was not inside a label

2. When "Closed" is chosen, set the "to" selectbox to "-" and don't
allow any other choices

- set disabled attribute on the options that were not selected
- when value of "From" selectbox is NOT "Closed", then remove disabled
attribute on the "To" options


*/


$('[class^="opening-hours-"]').find('select[id$="From"]').change(function () {
if ($(this).val() == 'closed') {
/*
DOES NOT WORK BECAUSE .next() only gets the
immediately following element.
*/
var $toSelect = $(this).nextAll('select[id$="To"]');
$toSelect.css("background-color", "red");
$toSelect.val('-');
$toSelect.find(':not(:selected)').attr('disabled','disabled');
} else {
$(this).nextAll('select[id$="To"]').find(':not(:selected)').removeAttr('disabled');
$(this).nextAll('select[id$="To"]').css("background-color", "white");


}
});

OSX: Opening a terminal from finder

I've used the shortcut in Windows XP to open a cmd window from
explorer. However, I haven't used it in OSX before. Finally got around
to getting it working. Apparently it's now built in to Lion, but my
imac is still on Snow Leopard.

Google brought me here:

http://stackoverflow.com/a/3487098/204255

and then this:

http://jameslow.com/2010/04/22/openterminalhere-and-anthere/

I downloaded the zip file, opened it, then dragged the file to the top
portion of finder, along with the other icons.

Wednesday 1 May 2013

HTML5 custom data attributes are case sensitive, and potentially confusing. Just stick to lower-case.

I have a form where the user can enter the hours that a business is
open, and with a pair of select boxes for each day of the week (ie,
"From" and "To" select box with times of the day)

Now I wanted to set this up so that the first time the user sees the
form, it already has default values of 9-5pm for Monday to Friday, and
10-4pm on Saturday and Sunday.

The model class we have has a variable called editMode() that
indicates whether the form is displaying an existing record or a new
record. I planned to use this to toggle the javascript code so it only
sets the values for "opening hours" if the record is not coming from
the database.

I was trying to access some data attributes I had set up as:

<div id="editModeStatus" data-isEditMode="${model.editMode}" ></div>

with jQuery code:

if (!$('#editModeStatus').data('isEditMode')) {
alert('editMode?' + $('#editModeStatus').data('iseditmode'));

And in the alert message, I would get:

editMode? undefined

and changing that code to:

alert('editMode?' + $('#editModeStatus').data('iseditmode'));

gave me

editMode? false

--when it should have been true, because that's the value that was
displaying in the HTML:

<div id="editModeStatus" data-iseditmode="false" ></div>

Googling on "data attribute case sensitive" brought me a couple of
posts discussing the case-sensitivity of html5 data attributes, and
how DATA ATTRIBUTES CAN ONLY BE LOWER-CASE UNLESS THERE IS A HYPHEN
PRECEDING THE UPPER-CASE CHARACTER

Not something I'm likely to remember immediately, so to simplify
things, I'd rather just use lower case in both the HTML and
Javascript.


REF:

http://blog.benpowell.co.uk/2012/03/warning-html5-data-attribute-is-case.html

Tuesday 23 April 2013

Java, Spring: creating error messages in Spring - reject() vs rejectValue()

When to use errors.reject() or errors.rejectValue()??

"The difference between rejectValue and reject is that rejectValue
always has to be about a field, hence it is a FieldError. The reject
method generates global errors."

Be careful with your calls because .reject() and rejectValue() both
have two string parameters. If your call is meant to be for
.rejectValue() but call .reject() instead, it will not break but also
won't work!


REF:
http://forum.springsource.org/archive/index.php/t-34649.html


From

org/springframework/spring-context/3.0.5.RELEASE/spring-context-3.0.5.RELEASE-sources.jar!/org/springframework/validation/Errors.java

Errors.java


/**
* Register a field error for the specified field of the current object
* (respecting the current nested path, if any), using the given error
* description.
* <p>The field name may be <code>null</code> or empty String to indicate
* the current object itself rather than a field of it. This may result
* in a corresponding field error within the nested object graph or a
* global error if the current object is the top object.
* @param field the field name (may be <code>null</code> or empty String)
* @param errorCode error code, interpretable as a message key
* @see #getNestedPath()
*/
void rejectValue(String field, String errorCode);




/**
* Register a global error for the entire target object,
* using the given error description.
* @param errorCode error code, interpretable as a message key
*/
void reject(String errorCode);

/**
* Register a global error for the entire target object,
* using the given error description.
* @param errorCode error code, interpretable as a message key
* @param defaultMessage fallback default message
*/
void reject(String errorCode, String defaultMessage);

Friday 19 April 2013

Getting size of a map in JSTL (it's different in JSP2.1 and JSP 2.2)

Surprised to discover that this doesn't cause problems in JSP

<c:out value="${priceMap.lenght}"/>

tried fixing it to

${priceMap.size}

then realised it gets converted to getSize() and so changed to

${priceMap.size()}

and then get a JSP exception:

org.apache.jasper.JasperException: /WEB-INF/jsp/postform.jsp(31,22)
The function getSize must be used with a prefix when a default
namespace is not specified

I was wondering why, then realised that this works in JSP 2.2
(released in 2009) but not in JSP 2.1 (released 2006)

In JSP 2.1 you must use:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<c:out value="${fn:length(priceMap)}" />

Tuesday 16 April 2013

IntelliJ IDEA: More keyboard shortcuts that don't work in Xubuntu 12.04

Just discovered a few more IntelliJ IDEA keyboard shortcuts that don't
work in Xubuntu 12.04 because of conflicts with OS default keyboard
mappings.

To fix these, go into:

Settings -> Settings Manager -> Window Manager -> Keyboard (tab)

Then remove the mappings for these key combinations:

Alt-F8 - Evaluate Expression

Ctrl-F1 to Ctrl-F12 - these are mainly for moving to different
Workspace. See the image for the replacement mapping I set - I
replaced them with Ctrl-Shift-Windows-Alt-F1-F4. I've left mappings
for Workspace 5-12 as empty because I dont' think I'll need more than
4 workspaces.

Alt-Insert - Generate
Alt-Delete - Safe Delete

IntelliJ IDEA: On Xubuntu 12.04, Ctrl-F12 (File structure popup) doesn't work. Here's how to fix it.

THE PROBLEM:

I use Ctrl-F12 a *lot* in IntelliJ IDEA, so it was annoying when I
started work on a new desktop with Xubuntu and found that it wasn't
working anymore. The IDEA settings were all there, but it wasn't
getting picked up.

Contacted support and found out the problem is due to conflict with
Xubuntu default keyboard mappings.

Xubuntu maps Ctrl+<function key> to Switch Workspaces.


THE SOLUTION:

Just go into Settings -> Settings Manager -> Window Manager -> Keyboard (tab)

Go down to Action = Workspace 12 and remove the keyboard mapping.

In the unlikely event you *do* need to move between 12 workspaces,
just map that to another combo, or change the IntelliJ mapping to
something similar like Windows + F12.

Monday 15 April 2013

Depending on the Java Matcher method you use, your regex may not get what you want

We had a system that you could configure with regexes to parse
incoming data. One of them was a pattern to look at a user's email,
and was configured like:

@domain\.com

And it wasn't matching the values we had, even though the values were
of the form:


somebody@domain.com

someone.else@domain.com


Then I found that the code we used to find a match was:

pattern.matcher(value).matches();

Now the javadoc for matches() says:

"Attempts to match the entire region against the pattern."

So if you look at the ENTIRE string, then

somebody@domain.com

would never match

If you use Matcher.find(), then it just looks at any substring that
matches the pattern, and so this would succeed.

The fix was to change the regex to


.*@domain\.com

YES, it also means that invalid username values would be matched, but
we have other filters that would check if the entire string was of
valid email format. All we care about is the domain, for this bit of
functionality.


REF: http://stackoverflow.com/questions/4450045/difference-between-matches-and-find-in-java-regex

Thursday 11 April 2013

Unix: how to display line numbers in less command

run "less"
then type ":"
then type "-N"
enter RETURN

Unix: Count the number of delimiters for each line in a huge file

Found this here:

http://ubuntuforums.org/showthread.php?t=301479

*THIS* is the one to use:

awk 'BEGIN { FS = ";" } ; { print NF-1 }' <million_lines.csv>

note that this outputs to console, so pipe to file for easier use
(add this at the end: > output_file)

example:

input file is "addresses.txt" and i want to

awk 'BEGIN { FS = "\t" } ; { print NF-1 }' addresses.txt > tab_count.txt


The other approach using echo |tr|wc is really really slow.


Note to self: learn awk and sed!

Java: In a static method, how do we load a file from a jar in classpath

Task: inside a static method, load a file contained in a jar that is
in our classpath.


First approach:

static void loadFromClasspath(String filename)
InputStream in = MyClass.class.getClassLoader().getResourceAsStream(filename);

// test
System.out.println("file found?" + in.available());

in.close()



main()
MyClass.loadFromClasspath("/this/is/a/package/file.txt");


-- was getting NPE on call to in.available


Second approach:

changed one line to

InputStream in = MyClass.class.getResourceAsStream(filename);

WORKS!


Warning:

Trying

MyClass.loadFromClasspath("file.txt");

does *not* work

Saturday 23 March 2013

So it's "class war" when it offends the rich, but not when it's against poor people?

http://www.theaustralian.com.au/opinion/columnists/for-labors-sake-julia-gillard-must-drop-the-words-that-divide/story-e6frg75f-1226603796481

So precioussss. Precious miners. They digs for the precious. Please
Mistress Julia, don't hurt them.

Belittling big business is "class war". What about belittling asylum
seekers and those on the dole?

Shanahan accuses Gillard of "gender war", while ignoring non-stop
sexist abuse and hate speech from Liberal allies such as Alan Jones.
Good on ya, disingenuous twat.

Wednesday 9 January 2013

jQuery code to implement "email this page" functionality

Some pages on our site have a "Print this page" link which opens a popup window where the user can email the content to someone else using a form.

Our implementation uses jQuery to:
1. copy the content from the window that opened the popup, using window.opener.document
2. filter the contents of the copied content
3. put it in the textarea

This javascript needs to be located on the poup page.

<script type='text/javascript'>
$(function () {
    // get the content based on id of the div -- ie, id="main-content-wrapper"
    // call .clone() so that subsequent .remove() calls do not affect the original window.opener.document
  var content = $('#main-content-wrapper', window.opener.document).clone();

// remove the elements that we don't want displayed in our form
  $('ul.page-tools', content).remove();
    $('ul.breadcrumbs', content).remove();
    $('p.return', content).remove();
// paste the content into a textarea input field with id="emailContent"
// calling .children() because the content we have has lots of intervening divs
  // in your case this may not be needed, so just use content.html()
    $("#emailContent").html(content.children().html());


})
</script>

Btw, our implementation uses CKEditor javascript library so the emailContent textarea will display the content as HTML.