Archive

Archive for the ‘coding’ Category

Find the maximum for an Iterable of Comparable

    public static <T extends Comparable<T>> T getMaximum(Iterable<T> values) {
        
        T max = null;

        for (T value : values) {
            if (max == null || max.compareTo(value) < 0) {
                max = value;
            }
        }
        return max;
    }

Categories: coding, java

Iterate in reverse order over a list in Java

April 26, 2012 2 comments

Sometimes we want to iterate in reverse order over a list in Java – without (re)sorting the list. Code example:

    for (T item : backwards(list)) {
        // do something
    }

Here is a backwards() method that does this for you (maybe put this code into a util class and use a static import):

    public static <T> Iterable<T> backwards(final List<T> list) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return backwardsIterator(list);
            }
        };
    }

    private static <T> Iterator<T> backwardsIterator(List<T> list) {
        final ListIterator<T> iter = list.listIterator(list.size());
        return new Iterator<T>() {
            @Override
            public boolean hasNext() {
                return iter.hasPrevious();
            }

            @Override
            public T next() {
                return iter.previous();
            }

            @Override
            public void remove() {
                iter.remove();
            }
        };
    }

Categories: coding, java

Record and share shell activity via shelr.tv

April 22, 2012 Leave a comment

Terminal

Shelr.tv allows Unix/Linux command line users to record something interesting from their terminal and share it to followers.

It is a bit like YouTube for plain text shellcasts. A great feature is that you can copy and paste everything you see.

A nice intro with interesting comments from one of the core developers can be found on linuxaria.com.

A Debian package has been proposed through the Debian “package mentor” system.

Categories: bash, debian, mac os, opensuse

Move JPGs from camera to year/month folder using bash, exif and gphotofs

April 12, 2012 Leave a comment

Prerequisites:

  • Install the gphotofs and exif packages.
  • Make sure you have the folders $HOME/devices/camera (camera mount point) and $HOME/media/photos (base folder for photo folders) or edit the script below to use different locations.
  • Verify that your camera mounts fine using gphotofs and that it internally stores JPGs in a subfolder of “DCIM”.

Save this script as /usr/local/bin/copy-cam-jpgs.sh:

#! /bin/sh

mountpoint=$HOME/devices/camera
targetfolder=$HOME/media/photos

# check availability of cmdline tools
type gphotofs exif fusermount || exit

# mount camera if necessary
if ! mount|grep "$mountpoint"; then 
  gphotofs "$mountpoint"
fi

cd $mountpoint/*/DCIM/*

for jpg in *.JPG; do
  year_month=$(exif --tag=0x9003 -m $jpg \
         | cut -f1,2 -d: \
         | tr ':' '/')
  folder="$targetfolder/$year_month"
  mkdir -p "$folder"
  mv -v "$jpg" "$folder"
done

cd
fusermount -u $mountpoint

Make it executable like this:

chmod ugo+x /usr/local/bin/copy-cam-jpgs.sh

Then plug in your digital photo camera and run “copy-cam-jpgs.sh“. It will move all JPGs from the camera to $target_folder/yyyy/mm where yyyy is the 4 digit year and mm is the two digit month of the date the photo was taken (as per EXIF data in the JPG).

Categories: bash, coding, debian, opensuse

Export HTML table as CSV file using JQuery

April 9, 2012 Leave a comment

Put this code into a script section into a common HTML head include file:

$(document).ready(function() {

  $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to spreadsheet");
    $button.insertAfter($table);

    $button.click(function() {
      var csv = $table.table2CSV({delivery:'value'});
      window.location.href = 'data:text/csv;charset=UTF-8,'
                            + encodeURIComponent(csv);
    });
  });
})

Note:

  • Requires JQuery and table2CSV (i.e. put script references before the script above)
  • “table” selector is a JQuery selector and can be adjusted to suit your needs
  • Only works in browsers with full “Data URI” support (Firefox, Chrome, Opera) but not in IE (which only supports this for images)
  • For full browser compatibility you would have to use a slightly different approach that requires a server side script (e.g. a Java Servlet) to “echo” the CSV. Maybe I will blog about that in another post.
Categories: javascript

Backup/restore XFCE desktop icons

March 8, 2012 Leave a comment

Sometimes the XFCE desktop icons get messed up, for example by games that temporarily change the screen resolution to 800×600.

A solution to this problem has been mentioned here. It suggests using “sudo chattr +i” to lock the config file where XFCE stores the icon positions.

Alternatively (and without the repeated need for sudo and chattr) you can also backup and restore the ~/.config/xfce4/desktop/icons* file(s) like this:

Create a script /usr/local/bin/save-xfce-desktop-icons.sh like this:

#! /bin/sh
mkdir -p ~/.config/xfce4/desktop.bak
cp -f ~/.config/xfce4/desktop/icons* ~/.config/xfce4/desktop.bak

Create another script /usr/local/bin/load-xfce-desktop-icons.sh like this:

#! /bin/sh
cp -f ~/.config/xfce4/desktop.bak/icons* ~/.config/xfce4/desktop

Make the scripts executable like this

sudo chmod ugo+x /usr/local/bin/save-xfce-desktop-icons.sh
sudo chmod ugo+x /usr/local/bin/load-xfce-desktop-icons.sh

Then in the XFCE start menu, go to “Settings” – “Keyboard” – “Application Shortcuts” and configure 2 keyboard shortcuts:

Command Shortcut
save-xfce-desktop-icons.sh <Control><ALT>S
load-xfce-desktop-icons.sh <Control><ALT>L

Then you will be able to backup and restore your icons like this:

  • Backup: Press F5 then <Control><ALT>S then F5
  • Restore: Press F5 then <Control><ALT>L then F5

The F5 is necessary to synchronize what you see on the screen with the content of ~/.config/xfce4/desktop/icons*.

Categories: bash, coding, debian, foss, opensuse

Shell script to generate index.html (directory listing)

February 17, 2012 Leave a comment

A simple shell script – let’s call it index-html.sh – to turn a list of file names into html links:

#!/bin/sh

echo '<html><body>'
sed 's/^.*/<a href="&">&<\/a><br\/>/'
echo '</body></html>'

Example use:

ls | index-html.sh > index.html

Categories: bash, foss

Job trends – Programming languages

January 10, 2012 Leave a comment

TIOBE index and trends

According to the current TIOBE index, Objective-C market share is growing the fastest. This is the native programming language of Apple devices like iPhone, iPad and iMac.

Indeed.com job ad trends

Absolute volume: Java is still leading the pack (as of 2011/2012).

php, perl, java, ruby, python, scala, c++, cobol, c# Job Trends graph

Relative growth: Look at Scala and Ruby …

php, perl, java, ruby, python, scala, c++, cobol, c# Job Trends graph

Categories: coding, java, mac os

Maven integration (m2e) for Eclipse 3.7.x (Indigo)

January 2, 2012 Leave a comment

Sonatype’s Maven integration for Eclipse (m2e) has been migrated to eclipse.org and is now available from the default update site for Indigo.

This means that you no longer have to add any Sonatype update sites as mentioned on the old (now outdated) m2eclipse site.

In particular, this also means that the old “m2e-extras” update site is obsolete for Eclipse 3.7.x and later. Things like WTP integration or Subclipse integration are now available as “m2e connectors” through Window – Preferences – Maven – Discovery.

All of this is very poorly (or not at all) documented on the new m2e home page and some people had problems with these changes.

Categories: java

Programming principles for Java methods

January 1, 2012 Leave a comment

Topics I want to cover in the future about Java methods:

  • Minimalistic coding style [1] [2] [3] [4]
  • “Fail early” (or “fail fast”) principle [1] [2]
  • “Return early” principle [1] [2] [3]
  • Object creation methods (to allow final)
  • Type generic methods (process a T vs create a T)
  • Functional style: stateless static methods vs interfaces
  • Javadoc: On interface not implementation
  • Method naming guidelines
  • Strategy parameters (often anonymous interface implementations)
  • Exception handling methods (try-catch-finally, throwing exceptions)
  • How to avoid setter/getter madness
  • Method chaining API style (static factory method, builder methods)
Categories: java
Follow

Get every new post delivered to your Inbox.