Archive

Archive for January, 2011

Javascript 101 Week 1 Assignment

January 29, 2011 8 comments

As I blogged previously, I am starting to learn Javascript via P2PU.org/Mozilla School of Webcraft. Here are my answers to the first week’s assignment.

Questions

The alliance of Netscape and Sun Microsystems did not use Java in the browser, because it was not suitable for that purpose. Why do you think Java was not suitable to be embedded in a browser?

I don’t think Java is suitable for embedding in a browser for a few reasons. Firstly, while the Just in time compiler does a great job at optimizing code that runs over and over again, there is a big cost to starting up the JVM, as it must load dozens if not hundreds of class files.

Furthermore, developing web applications in Java would be very slow for the developer too, as the code would have to be compiled into bytecodes before it could be run. Webapps written in Java have this problem already; if all the client side scripting were done in Java, this would be unbearable.

Furthermore, Java is not a good scripting language because it is too verbose, and the strict type checking is often overkill for simple scripts.

We are advised to provide a radix, because Javascript stops parsing at the first nondigit number. If the number starts with 0, this makes Javascript believe the number is octal and that any character other than 0-7 is invalid. Thus parseInt(“09”) == 0.

What is a type, and why do you think types are useful in writing programs?

A type indicates the ‘flavor’ of a variable, i.e. what the ‘tentacle’ grasps (using the terminology of the Eloquent Javascript course. Types are very useful for ensuring that the operations we invoke on variables make sense. For instance, it makes sense to invoke the times binary operand on two numerical values, but it doesn’t make sense to invoke it on two Strings, or a String and a number.

Why do we lose precision when performing operations with decimal numbers in Javascript? Can you think of a few implications of why this would be a problem?

All numbers in Javascript are stored as doubles (64 bit floating point numbers), which have a finite precision. Certain numbers cannot be exactly represented in this format, such as 0.1 (it has a nonterminating binary representation, and thus cannot be exactly represented in a finite number of digits). This means we have to be very careful when working with numbers, because our intuitive sense is wrong.

.1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 = 0.9999999999999999

Do you understand why the following operation produces the given result 115 * 4 – 4 + 88 / 2 = 500

Yes – order of operations matters. * and / have higher precedence over +. If you want to change this, use parentheses to explicitly show the order you want.

What does typeof 4.5 do, and why does typeof (typeof 4.5) return “string” 

Typeof returns a string representation of the type of the argument. typeof (typeof 4.5) returns string, because typeof returns the string “number”. The piece in parentheses is executed first, with that result becoming the argument to the outer typeof call.

Exercises

2.1

(4 >= 6 || "grass" != "green") &&
   !(12 * 2 == 144 && true)

(false || true) && !(24 == 144 && true)
(false || true) && !(false && true)
(true) && !(false)
(true) && (true)
true

2.2

function while_exponent(val, exp) {
    var product = 1;
    var counter = 0;
    while (counter < exp) {
        prduct *= val;
        counter++;
    }
    return product;
}

2.3

function while_triangle(n_lines) {
    var line_counter = 1;
    while (line_counter <= n_lines) {
        var string = ""
        var inner_counter = 0;
        while (inner_counter < line_counter) {
            string += "#"
            inner_counter++;
        }
        print(string)
        line_counter++;
    }
}

2.4

function exponent(val, exp) {
  product = 1;
  for (var i = 0; i < exp; i++) {
    product *= val;
  }
  return product;
}

exponent(2, 10) == 1024

function triangle(lines) {
  for (var i = 1; i <= lines; i++) {
    var string = ""
    for (var j = 0; j < i; j++) {
      string += "#"
    }
    print(string);
  }
}
triangle(10);
#
##
###
####
#####
######
#######
########
#########
##########

2.5

var result = Number(prompt("What's the value of 2+2?"));
if (result == 4) {
    alert("Excellent");
}
else if (result == 3 || result == 5) {
    alert("Almost");
}
else {
    alert("Idiot.");
}

2.6

while (true) {
    var result = Number(prompt("What's the value of 2+2?"));
    if (result == 4) {
        alert("Excellent");
        break;
    }
    else if (result == 3 || result == 5) {
        alert("Almost");
    }
    else {
        alert("Idiot.");
    }
}

2.

var name = prompt("What's your name?") || "Guest";

This is an example of using the OR binary op to return the second operand if the first is a Falsey value (e.g. the empty string). This allows you to provide sensible defaults

We can use the && as a guard against null values. For instance, if we want to invoke a method on an object, but not if it’s null, we could do

var result = X && X.someMethod()

since the && will only evaluate the second operand if the first is not a Falsey value (e.g. null), we are safe from executing undefined methods.

 

/*#p2pu-Jan2011-javascript101*/

Java annoyances

January 28, 2011 Leave a comment
Having had Java as the programming language of the vast majority of my undergraduate courses, as well as the language I program in every day, I am most comfortable and fluent in it.  When I return to Java after using different languages such as AWKPython, or Ruby, I’m always left with a bitter taste in my mouth.  There are some things Java just makes way too hard, verbose, and painful to accomplish.  It’s for that reason that I’m learning Scala, what could be (simplistically) described as a cleaned up, more succint version of Java.

Asymmetry in standard libraries

Symmetry is an important feature of a library; it basically means that methods come in pairs.  For instance, you’d expect that a class with a read method has a write method, or one with a set method has a get method.  (That’s not always the case, certainly, but API writers often strive for symmetry.  See Practical API Design: Confessions of a Java Framework Architect) As another example, there’s both a method to convert from an array to a list (Arrays.asList) and there is a method to go the other direction (List.toArray()).  Unfortunately, not all of the Java library APIs adhere to this convention.  The one that bothers me the most is in the String library.  There is a String split method that breaks a String up around a given regular expression, but no corresponding method to reconstitute a String from a collection of other String objects, with a specified separator between them.  This leads to code like the following to comma separate a collection of strings:
String[] strings = ...;
StringBuilder b = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
 b.append(strings[i]);
 if (i != strings.length -1) {
 b.append(",");
 }
}
System.out.println(b.toString());
This whole mess could be replaced with one line of Python code
print(",".join(strings))
or in Scala:
println(strings.mkString(","))
It’s pretty sad that you have to either write that ugly mess, or turn to something like Apache StringUtils.

Different treatment of primitives and objects

It is a lot harder to deal with variable length collections of primitive types than it should be.  This is because you cannot create collections out of things that are not objects.  You can create them out of the boxed primitive type wrappers, but then you have to iterate through and convert back into the primitive types.

In other words, you can create a List<Double> but you cannot create a List<double>.  This leads to code like the following:
// Need a double[] but don't know how long it's going to be
List<Double> doubles = new LinkedList<Double>();
for (...) {
 doubles.append(theComputedValue);
}
// Option 1: Use for loop and iterate over Double list, converting to primitive values through
// auto unboxing
// Bad: leads to O(n^2) running time with LinkedList
double[] doubleArray = new double[doubles.size()];
for (int i = 0; i < doubleArray.length; i++) {
 doubleArray[i] = doubles.get(i);
}
// Option 2: Use enhanced for loop syntax (described below), along with
// additional index variable.
// Better performance but extraneous index value hanging around
int index = 0;
// Automatic unboxing
for (double d : doubles) {
 doubleArray[index++] = d;
}
...
b[index] // Oops
As I blogged about previously, there is a library called Apache Commons Primitives that can be used for variable sized lists for primitive types, but it is a shame one has to turn to third party libraries for such a common task.

Patchwork iteration support

Java 5 introduced the “Enhanced for loop” syntax which allows you to replace
Collection<String> strings = new ArrayList<String>();
Iterator<String> it = strings.iterator();
while (it.hasNext()) {
 String theString = it.next();
}
with the much simpler
for (String s : strings) {
 // deal with the String
}
Here’s the rub: this syntax is supported for arrays and Iterable objects.  But guess what?  Iterators are not Iterable.  Why is this a problem?  Well, you might want to return read-only iterators to your data.  If you do this, the client code cannot use the enhanced for loop syntax, and is stuck with the earlier hasNext() code.  If you want to use the enhanced for loop syntax to work for Iterators, you need to introduce a wrapper around the Iterator which implements the Iterable interface.  From the previously linked blog post:
class IterableIterator<T> implements  Iterable<T> {
    private Iterator<T> iter;
    public IterableIterator(Iterator<T> iter) {
        this.iter = iter;
    }
    // Fulfill the Iterable interface
    public Iterator<T> iterator() {
        return iter;
    }
}
I hope this strikes you as inelegant as well.
Furthermore, arrays are not iterable either, despite the fact that you can use the enhanced for loop syntax with them.
What this all boils down to is that there’s no great way to accept an Iterable collection of objects.  If you accept an Iterable<E>, you close yourself off to arrays and iterators.  You’d have to convert the arrays to a suitable collection type by using the Arrays.asList method.  It would be great if we could treat arrays, collections, etc., agnostically when all we want to do is iterate over their elements.

Lack of type inference for constructors with generics

Yes, we all know we should program to an interface rather than to a specific implementation; doing so will allow our code to be much more flexible and easily changed later.  Furthermore, we also know we should use generics for our collections rather than raw collections of objects; this allows us to catch typing errors before they occur.  So in other words

// BAD: Raw hashmap and programming to the implementation!
HashMap b = new HashMap();
// Good
Map<String, Integer> wordCounts = new HashMap<String, Integer>();
In fact, this lack of type inference is one reason why Joshua Bloch suggests that static factory methods can be better that constructors – it is possible to have a static factory method that can infer the correct types and instantiate the object, without making you explicitly repeat the type parameters.  For instance, Google Guava provides many static methods to instantiate maps:
Map<String, Integer> wordCounts = Maps.newHashMap();
Fortunately, the problem of having to repeat type parameters twice for constructors is being fixed in JDK 7 with something called the Diamond Operator.  It will allow you to replace
Map<String, Integer> wordCounts = new HashMap<String, Integer>();
with
Map<String, Integer> wordCounts = new HashMap<>();
This improvement to the language can’t come fast enough.

Conclusion

I use Java on a daily basis for about 90% of the work I need to do.  I’m comfortable with it, I understand its syntax, it’s fast, it’s powerful.  After being exposed to languages like python and scala, certain issues in Java stand out in stark contrast, and thus I’ve enumerated a few of the reasons that Java annoys me on a daily basis.  Fortunately excellent libraries exist to correct many of the annoyances, but it’s painful to have to use them to do such basic things as joining a list of Strings with a given separator character, or creating a variable sized list of primitive types. Fortunately Java continues to evolve, and at least some of my irritations will be fixed in JDK 7.
Post in the comments if you have better workarounds than those that I’ve suggested, you have other languages that make these tasks easy and would like to highlight them, or any other reason you can think of.

WorkFlowy – free minimalist list webapp

January 25, 2011 Leave a comment
Today’s post is about WorkFlowy, a great, free web application for creating and managing lists. It is the best tool for organizing TODOs and random thoughts out of anything I’ve found. 

First, let me describe the two main problems I have with todo/note taking software I’ve tried previously.  Secondly I’ll show how WorkFlowy alleviates these problems.

TODO: fix these problems!

There have certainly been other TODO list applications that I have used in the past, but they usually suffer from at least one of the following problems:

1) They require too much information about each item
When I’m jotting things down, I rarely care about prioritizing it, giving it a due date, assigning it a label, tag, etc.  A lot of organization software hits you over the head with all the different ways to categorize your items; this really can slow you down when you’re just trying to brainstorm in a lightweight manner.  I found Evernote to suffer from this problem.
2) They force you into a flat mode of thinking
When I’m trying to right down all the thoughts in my head related to a given project or task, they often are deeply hierarchical.  I write down task A, which really consists of subtasks A.1 and A.2, where A.2 in turn consists of tasks A.2.i, A.2.ii, and A.2.iii.  I want whatever software I jot down notes with to reflect this way that I think, and it ties into the previous point.  I’d much rather indicate that a task depends on a different task by nesting it beneath another task, rather than manually annotating it with a label.
(Here’s a visual representation of the nested list I described earlier:)
  • A
    • A.1
    • A.2
      • A.2.i
      • A.2.ii
      • A.2.iii
I found Things, a todo manager on Mac to suffer from this problem.  It just didn’t fit into the way I like to jot things down in a nested relationship.

WorkFlowy

With respect to #1, WorkFlowy is as barebones as you can get.  There are no labels, tags, colors, due dates, etc.  All you do is enter plain text.  If you need all those bells and whistles, then WorkFlowy might not be for you.  But if all you want is an online repository for your random thoughts, I have not found anything better.

Workflow is also excellent at managing deeply hierarchical information, as I described in number two.  It supports the standard tab/shift+tab combo to indent/unindent items.

Indent text with the tab key

Here you see all the top level notes that I have.

Top level lists

Top level lists

By clicking the plus sign to the left of the node, I can expand the subtree that’s rooted at that node.  This allows me to selectively hide/reveal pieces of my lists.

After the chores node has been expanded

The ability to expand/collapse subtrees is nothing new, though it is an extremely useful UI feature (and one that I desperately wish were in Google Tasks).  Workflowy adds an additional way of showing / hiding information, which I’ve never seen before and I wish was copied everywhere.  If you click on the node itself rather than the plus sign to the left of it, you jump to that node in the tree, hiding all siblings and ancestors of that node.  Conceptually, you “zoom in” on that part of your list, ignoring all the distractions of the other lists
Zoom in

Zoom in

You are always able to work your way up the list (backing out of the subtree you entered) through the intelligent use of breadcrumbs that appear at the top of your view.

Breadcrumbs allow you to back out of your current location

This is an extremely effective UI technique, as it allows you to create arbitrarily complex and nested hierarchies but focus on only a small piece of it at any one time.  This allows you to switch between nested and essentially flat views of your data at will, simply by zooming into the relevant portion of the tree and by collapsing the children nodes whose detail you don’t care about.

Conclusion

Workflowy is an extremely lightweight, barebones web application for managing your notes and todo items.  Workflowy encourages you to get down the information as easily and as quickly as possible, and makes it easy to rearrange the data and selectively view the portions you want to see.  It features a unique UI feature for zooming into subtrees of your lists, while providing breadcrumbs to back your way out of your current position.
While I do like the minimalism of the application, there are certain features that I wish were present.  For instance, it would be nice if links were automatically parsed from the plaintext.  Overall, I find Workflowy an indispensable part of my toolkit.

Scala – type inferencing gotchas

January 24, 2011 6 comments
I’ve written previously about Scala; today I’m going to write about a potential ‘gotcha’ of Scala’s type inferencing.  Type inferencing means that instead of writing
int x = 100;

as we would in Java, you can instead write

val x = 100
and the compiler is smart enough to figure out that you mean an integer.  Let’s look at one case in which the use of implicit typing came back to bite me.

The setup

I was writing a routine that calculates the ‘average’ color of an image (where we define the average color as the color formed by the average red, blue, and green components of all the pixels in the image).  A first pass might look like this:
def calculateAverageColor(image:BufferedImage):Color = {
    var redSum = 0
    var greenSum = 0
    var blueSum = 0

    // calculate the sum of each channel here

    val red = (redSum / numPixels)
    val green = (greenSum / numPixels)
    val blue = (blueSum / numPixels)

    new Color(red, green, blue)
}
(I’m leaving off the actual summation algorithm, as it’s not important to illustrate how the problem manifests itself.)
This code is almost right, but it has a problem.  Can you guess what it is?

Problem #1

In a lot of cases this code will work fine.  But if you have an extremely high resolution image, or you have an overexposed image (where many of the pixels are near white, implying a high red, green, and blue value), any of the individual sums can overflow, if the sum exceeds the max value that an integer can hold.  Due to the way binary numbers are implemented (“Twos complement”), this results in a negative number.
scala> java.lang.Integer.MAX_VALUE
res0: Int = 2147483647

scala> java.lang.Integer.MAX_VALUE+1
res2: Int = -2147483648

If this happens, then we end up trying to construct a color with negative red, green, or blue values; this will result in an IllegalArgumentException.

The easiest way to fix this is to use a bigger datatype to store the running sum; let’s use a Long instead.  This allows us a maximum value of 9223372036854775807; that should be plenty big to store whatever running total we have.
def calculateAverageColor(image:BufferedImage):Color = {
     // Declare the sums as longs so we don't have to worry about overflow
     var redSum:Long = 0
     var greenSum:Long = 0
     var blueSum:Long = 0

     // calculate the sum of each channel

     val red = (redSum / numPixels)
     val green = (greenSum / numPixels)
     val blue = (blueSum / numPixels)

     new Color(red, green, blue)
}
This code looks OK at a cursory glance; if you actual use it, you will quickly get an exception:
java.lang.IllegalArgumentException: Color parameter outside of expected range: Red, Green, Blue

Problem #2

At this point, you might start debugging the process by printing out the values of red, green, and blue.  Sure enough they’ll be in the range [0, 255], just as you need for the Color constructor.  What is going on?

There are two related problems.  The first is that the type of red, green, and blue are not integers, due to the Long value in the computation.  The compiler sees the Long and (correctly) infers that the type of red, green, and blue must be Long.

This wouldn’t be a problem, except that there is no Color constructor that takes in Long arguments.  Yet the code compiles fine.  Why?
Well, it’s because of the implicit widening conversions present in the Java language.  These (usually) make our lives as programmers much easier.  If a method is defined to take in an integer and we pass it a short instead, the short is implicitly converted to an integer with no extra effort on our part.  This is done automatically because there is no danger of truncation; because the type that is implicitly converted to is larger (wider), it can always hold the value of the smaller type.
According to the Sun specification,


The following 19 specific conversions on primitive types are called the widening primitive conversions:

     

  • byte to shortintlongfloat, or double
  • short to intlongfloat, or double
  • char to intlongfloat, or double
  • int to longfloat, or double
  • long to float or double
  • float to double

The implicit conversion that tripped me up was that longs are implicitly promoted to float.  The reason the method compiled, even though there is no constructor that takes long r,g,b arguments, is because there is a constructor that takes float arguments, and the longs were automatically converted to floats!  See the Color documentation for more. Unlike the integer constructor, which takes RGB values in the range [0,255], the float constructor takes RGB values in the range [0,1].
The solution is to convert the longs back into ints, via a cast.  In Java this would be accomplished with
long redSum = ...;
int averageRed = (int) (redSum/numPixels);
In Scala you instead must do
val redSum:Long = ...
val averageRed:Int = (redSum/numPixels).asInstanceOf[Int]
The fixed code as a whole thus looks like
	var redSum:Long = 0
	var greenSum:Long = 0
	var blueSum:Long = 0

	// calculate the sum of each channel

	val red:Int = (redSum / numPixels).asInstanceOf[Int]
	val green:Int = (greenSum / numPixels).asInstanceOf[Int]
	val blue:Int = (blueSum / numPixels).asInstanceOf[Int]

	new Color(red, green, blue)

Conclusion

One of the nice things about Scala is that you do not need to explicitly declare the types of your variables.  In one sequence of unfortunate events, the variables that looked like ints were in fact longs, leading to an implicit conversion to the float primitive type, which in turn caused the incorrect constructor to be invoked, and an IllegalArgumentException.  Hopefully you can avoid doing something so foolish as a result of reading this post.

NetBeans Platform – how to register a class as a provider of multiple services

January 24, 2011 4 comments
In NetBeans Platform, there is an annotation called ‘ServiceProvider‘, which allows you to declare that your class provides a certain service (i.e., implements a given interface).   This ties directly into the previously blogged about topic of Lookups, as the class thus annotated is added to the global, default lookup.  Recall that a lookup is a nice wrapper around a Map<Class<E>, Collection<? extends E>>, and allows modules to decouple themselves from the service they request from the actual concrete implementation that they receive.  (A much more in-depth discussion can be found on the Dev FAQ section on lookups).

The issue I ran into is that the documentation is not very clear how you can register your class as providing more than one service (again, implementing more than one interface).  For instance, say I have two interfaces I want a class to fulfill:

public interface Foo {
    public String getFoo();
}

public interface Bar {
    public String getBar();
}

public class FooBar implements Foo, Bar {
    public String getFoo() { return "foo"; }

    public String getBar() { return "bar"; }
}
Since you cannot annotate a class twice, the naive solution fails:
// This is a mistake; you can't declare two annotations like this
@ServiceProvider(service=Foo.class)
@ServiceProvider(service=Bar.class)
public class FooBar implements Foo, Bar {
The correct solution is to use the ServiceProviders annotation, which allows you to provide a list of @ServiceProvider declarations.
@ServiceProviders(value={
    @ServiceProvider(service=Foo.class),
    @ServiceProvider(service=Bar.class)}
)
Now you can find the FooBar instance via either defined interface.

NetBeans – Reformat text

January 13, 2011 Leave a comment

The NetBeans IDE has a great shortcut for reformatting sourcecode.  Simply hit ⌃⇧F (ctrl shift f), and all the sourcecode in the current file will be reformatted.  This is a great feature, and I only stumbled upon it through a StackOverflow search.

Before reformatting. This is how the code looked on StackOverflow

After running the algorithm. Note how much more readable it is

(Sourcecode taken from this stackoverflow post)

The other time it’s useful is when working on a project where someone is using very large tab settings (e.g. 8 spaces per tab instead of 4).  This can make it very difficult to read.  By invoking this command, you’ll put the code into a much more readable format.

P2PU – World of Webcraft

January 13, 2011 1 comment
P2PU (Peer 2 Peer University) is a “grassroots open education project that organizes learning outside of institutional walls and gives learners recognition for their achievements. ”  In particular, they are offering a series of free online classes for web development; you can see the full list at http://p2pu.org/webcraft.  Once you sign up for an account, you can apply to take part in any of the courses offered.  Due to the limited number of slots, you must complete some rudimentary tasks to prove that you are going to be involved in the class, in order to apply for admission. 

I signed up for the Javascript 101 course and was asked to watch a 30 minute introductory video, write a short blog post, and then write a simple javascript program that did some addition and displayed the result as an alert in the browser.  Pretty simple stuff, but it weeds out those who are not willing to do some work on their own and would just slow down the class.

I also applied for, and was accepted into, the Introduction to Ruby and Rails course.  Longtime readers of this blog might remember that I have dabbled in Rails before, and had an initially favorable impression.  But like any skill, you must use your knowledge or it quickly fades away.  I’m basically back to square one with Ruby/Rails due to not having used it in the past year, so I’m looking forward to the added impetus of a class to get me to learn it.

Given that the vast majority of my programming has been on desktop / mobile client applications, I am excited to learn some web programming languages and techniques.  Technology changes quickly, and I can all but guarantee my expertise in Java Swing is not going to count for much in a few years.

I’ll be sure to write about my impressions as I go through the course; in the meantime, I urge you to sign up for these courses before they fill up.

Code Complete 2nd Edition e-book – $20

January 12, 2011 Leave a comment

Hi all,

I’ve slowly been transitioning all of my tech book purchases to e-book formats, particularly due to O’Reilly’s daily e-book deal tweets (follow @oreilly if interested; they seemed to be posted less frequently recently, but there are some good deals once in awhile).

Anyways, today’s deal of the day is Code Complete 2nd Edition, which is $20 with discount code DDC2E. I got this as a paperback for Christmas a few years ago and literally read it cover to cover in a week or so. It’s great stuff, and a must read for any programmer. I’m half tempted to buy it again, as it’s a lot more convenient to have a digital version than a 1.5 inch thick tome.

Reset windowing system in NetBeans Platform

January 5, 2011 3 comments
One of the benefits of building programs on top of NetBeans Platform is the powerful windowing and docking framework it provides out of the box.  Part of this functionality is persistence; when a user closes a NetBeans Platform application, the state of all the windows is saved.  The next time the application is started, the windowing state is restored.  This is why the NetBeans IDE (which is built on the NetBeans Platform) remembers which files you had loaded and how you had your windows arranged.
During development, it is sometimes beneficial to do a ‘factory reset’ and reset the windows back to the way they would look when the application is launched for the first time. For instance, you may have inadvertently closed some windows you wanted to have open, or you opened some windows that you wanted closed and don’t feel like manually restoring each window’s open/closed state. Or perhaps you moved some of the windows in a position that made sense for testing part of the application, but now you want to test another part that requires the original windowing setup.

Clean and build

There are two main ways to do this.  The easiest way is to do a full clean and build of the project (right click on the top level project node in NetBeans and choose Clean and build)

This works fine, but it has the drawback of.. cleaning and rebuilding the project.  This can take a long time for complex projects, and is a bit overkill if all you want to do is reset the windowing system.

Remove Windows2Local

The second way of accomplishing this is to remove a folder named “Windows2Local”.  If the root of your NetBeans Platform project is located at /path/to/Foo, then the folder to remove is /path/to/Foo/build/testuserdir/config/Windows2Local
You can delete the folder any way you see fit; I usually do a
rm -rf /path/to/Foo/build/testuserdir/config/Windows2Local
from the terminal.
This folder contains the saved information about the window placement and sizes; by removing it, you force NetBeans to recreate it when the application restarts.
This method is much faster, as nothing needs to be recompiled.  It is my preferred way of resetting the windowing system back to its default state when developing NetBeans Platform applications.

NetBeans Platform – ModuleInstall ClassNotFoundException

January 3, 2011 Leave a comment

In the NetBeans Platform, you can create an ModuleInstall class which handles the lifecycle of your module, and provides methods you can override to handle when your module is loaded and unloaded.  The standard way of creating this class is to use the wizard that NetBeans provides for this purpose, accessible by right clicking on the project and choosing New -> Other -> Module Development -> Module Installer

If you decide that you do not want to use the ModuleInstall mechanism any longer (the NetBeans Platform folks suggest you do NOT use it, as it will increase the startup time of the application), you might think you can just delete the Installer.java file that the wizard created.  Unfortunately, that’s not the case.  When you run the project you’ll get an exception like the following

org.netbeans.InvalidException:  
StandardModule:net.developmentality.moduleexample jarFile: ...
  java.lang.ClassNotFoundException:  net.developmentality.moduleexample.Installer starting from  ModuleCL@482...

The problem is that the wizard modified the manifest.mf file as well, and you need to manually clean up the file before your project will work again.

Open the manifest.mf file and you’ll see a line in the file like the following:

OpenIDE-Module-Install: net/developmentality/moduleexample/Installer.class

delete that line, and rebuild.  You should be ready to go.
In general, you need to be very careful about using any of the wizards that NetBeans provides.  They are extremely useful, but they end up changing XML files that you will need to manually edit later if you decide to refactor.  For instance, if you create an Action instance using the New Action Wizard, the action will be registered in the layer.xml file.  If you rename the action using the refactor command, the entries in the xml file are NOT modified, and you will get an exception at runtime unless you remember to edit that file.
Fortunately, the wizards are smart enough to at least tell you which files they are modifying.  It’s just a matter of remembering this further down the road when you need to refactor, move, or delete files.  Look for the modified files section in the wizard dialog: