Monday, March 22, 2010

Scala: desugaring

This post is composed of the info on scala source desugaring originating from this thread. I was afraid the information would be lost forever so, after a fight with markdown and pandoc I produced this:

Desugaring of scala types
Source typeType
Int => IntFunction1[Int, Int]
(Int, Int, Int) => IntFunction3[Int, Int, Int, Int]
(String, Int)Tuple2[String, Int]
String <:< Test<:<[String, Test]
Desugaring of scala values
Source valueDesugaredType
nullNullNull
()()Unit
11Int
2.0f2.0fFloat
3.03.0Double
"hello""hello"String
'dSymbol("d")Symbol
(5,6)Tuple2(5,6)Tuple2[Int, Int]
(7,8,9)Tuple3(7,8,9)Tuple3[Int, Int, Int]

Now lets get down to functions (first line - source, second - desugared, optional third - type):
Anonymous Function1
x: Int => x * 1

new Function1[Int, Int] {
    def apply(x: Int): Int = x * 1
}
Anonymous Function2
(_: Int) * (_: Int)

(x1: Int, x2: Int) => x1 * x2

Type: Function2[Int, Int, Int]
Partial function explicitly typed as a Function1
{ case x: Int => x }: (Any => Int)

new Function1[Any, Int] {
   def apply(x: Any) = x match { case x: Int => x}
}
Partial function
{ case x: Int => x }: PartialFunction[Any, Int]

new PartialFunction[Any, Int] {
   def apply(x: Any) = x match { case x: Int => x}
   def isDefinedAt(x: Any) = x match { case x: Int => true; case _ => false}
}
XML Syntax
<a:b><c></c></a:b>

new xml.Elem("a", "b", null, xml.TopScope,
new xml.Elem(null, "c", null, xml.TopScope))

Type: xml.Elem 
 
 
Thanks to:
  • David Flemstrom
  • Johannes Rudolph
  • Jason Zaugg

Thursday, March 11, 2010

Installing Arch Linux on a notebook

I finally got around installing a linux distro on my new notebook. After carefully choosing the easiest and the lightest one, I chose arch. Of all distributions arch linux has one of the best wikis available, an awesome package manager and an active community.

Installation

The installation process is smooth. If you only have the wireless available (no eth), don't forget to choose wireless_tools package from base-devel, as you won't be able to configure wireless without it.

Setting up wireless

Refer to wireless wiki, network wiki for a DHCP setup:

ifconfig wlan0 up # activate the kernel interface
iwconfig wlan0 essid "MyEssid" key 1234567890 #WEP encrypted
dhcpcd wlan0

Add this to /etc/rc.conf under the NETWORKING:

wlan0="dhcp"
INTERFACES=(wlan0)
Network profiles

When you'll get tired of setting up connection manually every time you start up your box and think about putting the ifconfig stuff in a start up script - don't do that. The standard way to set up a network is through the netcfg utility/daemon. You need to set up a profile which will reside in /etc/network.d and add the net-profiles daemon

DAEMONS=(syslog-ng !network hal netfs net-profiles crond pcm)

and the network profile name (under NETWORKING)

NETWORKS=(profile-in-rc.d/network)

to you rc.conf (note that I have disabled the network daemon for some reason, not really sure why though). To be honest, I could not get netcfg to successfully connect using my profile for the first week. It fixed itself after a system update some time later.

Tips
  • If you ever need to restart network do: /etc/rc.d/network restart

Setting up X

Refer to xorg wiki:

pacman -S xorg
pacman -S nvidia # if you have an nvidia card
nvidia-xconfig # creates an /etc/X11/xorg.conf
pacman -S acpid # ([power management](http://wiki.archlinux.org/index.php/Acpid))

add hal and dbus to DAEMONS in /etc/rc.conf and you're good to go.

Tips
  • When I tried to run X for the first time - I would get locked out and had to hard-reboot the box. However, it wasn't really dead as I figured out later. If you ever get into what looks like a lock out, try ctrl+alt+F1/2/.. which will bring up another TTY screen.

Setting up WM

I chose xmonad (arch wiki). The process is fairly straightforward, just proceed as described in wiki. The only problem I have encountered was the freetype lib which wasn't installed. Easily fixed by

pacman -Ss freetype && pacman -S extras/libxft
Tips
  • If you get a blank screen and your /var/Xorg.0.log is empty - probably xmonad has started without errors. It's a minimal window manager, so don't expect much eye candy. Use Meta+S+Enter to open a terminal and read a wiki from there.

  • If you ever run into troubles while upgrading or installing any graphical packages look here.

  • If you find yourself staring at your keyboard, unable to figure out what to press in order to switch to another window/desktop or open another console - use this vi-style reference.

  • You also might want to have a status bar. There are two competitors currently: xmobar and dzen, latter being more feature-rich and sophisticated. That's why I chose the former one. Its setup is straightforward as: pacman -S xmobar and following the xmonad guide on adding a statusbar.

  • xmonad 0.9.1 has a problem with playing HTML5 video tags in full screen.

Setting up sound

Sound is managed by ALSA. I don't know what it is for sure, so I'll leave it to your imagination. To get it up and running you need

pacman -S alsa-utils
alsaconf
aplay  /usr/share/sounds/alsa/Front\_Center.wav

If you can't hear the pleasant voice, consult the oracle.

Setting up touchpad

See Touchpad Synaptics. According to the wiki, you only need to

pacman  -S xf86-input-synaptics

However, it didn't work for me without a restart.

General Tips
  • If shutdown doesn't shut down - use poweroff. In my case shutdown didn't work, no matter what I tried: all of the shutdown options, apci modes, e.t.c. After a search through arch forums (which resulted in zero topics matching the symptoms I've been having) and a dozen tries I just gave up and tried the poweroff which worked like a charm.

Applications

Arch is a lean distro, it even has it's user selected "Lean and Mean of the Year" list of applications found somewhere in the forums section.

File manager

Definitely vifm. However, installing vifm is not as straightforward as other packages as it isn't yet in the official arch repo (as of 2010-02-16). First you need to get the 'arch build system' (abs)

pacman -S abs

then the base-devel group

pacman -S base-devel

create a directory for unofficial package builds and get the package

mkdir ~/builds && cd ~/builds && wget http://aur.archlinux.org/packages/vifm-git/vifm-git.tar.gz

build the package

tar -xvf vifm-git.tar.gz && cd PKGBUILD && makepkg -s

install the resulting tar

pacman -U [the tar.gz file built by makepkg]

Tuesday, November 17, 2009

Random bits: xor in the enterprise

You rarely find useful applications of xor (or any other bitwise operator for that matter) in everyday enterprise software development. Sure, they are widely used when implementing non-trivial algorithms... hell, even the trivial ones if they aren't concerned with the calculation of a total gross premium after a second endorsement on a rainy evening.
Anyway, I was pleasantly surprised after I found this little method:

void process(SomeData first, SomeData second) {
if (first == null && second == null) {
doWhenBothNull();
} else if (first != null ^ second != null) {
doWhenOneNull();
} else {
doWhenBothNonNull();
}
}

Of course this code could have been rewritten without using xor and wouldn't loose in readability; of course, the whole algorithm could have been rewritten so that these checks wouldn't even take place.
This post isn't about maintainability or good practices. It is about the small things that make our work worthwile.

Friday, July 3, 2009

Completely random: 1

According to the official source, Mavens pom.xml got its name from "Project Object Model". Although, in my opinion, "Property Of Maven" would have explained it clearlier.

Thursday, June 11, 2009

Codes vs Numbers

Spending hours in search for a bug in domain logic, when all that's wrong is the leading zero which gets truncated during string->int conversion: priceless.

Thursday, March 19, 2009

Unordered collections

Suppose we have domain classes with fields of type Collection. We also need to implement equals on these classes, which can be easily done using org.apache.commons.lang.builder.EqualsBuilder.
However, the EqualsBuilder is not smart enough to treat our data as an unordered collection (unordered is the lowest common denominator when the implemented interface is a Collection and not a List). This means that we should wrap our collections into UnorderedCollection
when comparing, which can be done like so:

public static <T, E extends T> Collection<T> asCollection(final Collection<E> ts) {
return new UnorderedCollection<T>() {

@Override
public Iterator<T> iterator() {
return new UnmodifiableIterator<T>() {
private Iterator<E> iterator = ts.iterator();

public boolean hasNext() {
return iterator.hasNext();
}

public T next() {
return iterator.next();
}

};
}

@Override
public int size() {
return ts.size();
}

@Override
public String toString() {
return ts.toString();
}
};
}


private static abstract class UnorderedCollection<T> extends AbstractCollection<T> {
/**
* Taken from {@link AbstractSet#equals} implementation.
* <p>
* <b>Important!</b> not associative when compared with ordered
* {@link Collection} (such as {@link List}).
* </p><p>
* E.g.
* <code>CollectionUtils.asCollection().equals(new ArrayList()) == true</code>

* but
* <code>(new ArrayList()).equals(CollectionUtils.asCollection()) != true</code>

*
* @see java.lang.Object#equals(java.lang.Object)
* @see java.util.collection.AbstractSet#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object o) {
if (o == this) {
return true;
}

if (!(o instanceof Collection)) {
return false;
}
Collection c = (Collection) o;
if (c.size() != size()) {
return false;
}
try {
return containsAll(c);
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
}
}

The implementation of equals was adopted from AbstractSet as the comments state.

private static abstract class UnmodifiableIterator<T> implements Iterator<T> {
public void remove() {
throw new UnsupportedOperationException(
"Collection was created using CollectionUtils#asCollection which does not support element removal.");
}
}

This way we can wrap any Collection with an UnorderedCollection and enjoy the equality between
Arrays.asList(1, 2, 3)

and
Arrays.asList(3, 2, 1)

Monday, March 9, 2009

Java web apps in Tomcat

Put as little external libraries as you can into $TOMCAT/commons/lib or $TOMCAT/shared/lib. When time to update comes each shared dependency has a chance of crippling your efforts by breaking seemingly independent applications. In general, you shouldn't add any libraries to aforementioned folders. If your applications must share some of their dependencies - set up a simlink outside of the Tomcat. This way you will have a guarantee that there will be no issues related to the Tomcats classloader.

If you want to maintain j2ee 1.4 compatibility and avoid problems with dependencies on jsp/jstl libraries (dreaded NoClassDefFoundError: Class not found javax/el/ValueExpression) I suggest you use this configuration:

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>