Ed's Big Plans

Computing for Science and Awesome

Archive for the ‘Java’ tag

Exposing MATLAB data with JFrame & JTextArea

without comments

Today, I’ll describe my first foray into MATLAB. My task is simple — there’s already a GUI developed as a toolbox. The user inputs a bunch of data, and it crunches it away and provides a graph and displays a dialogue box about the moments of the data. The issue here is that we’d like to know more about the data — particularly, we’d like to retrieve the ordered pairs corresponding to each of the plotted points in the graph.

In this exercise, I’ll show you how to use JFrame & JTextArea to display the coordinates of a graph in an already existing MATLAB GUI toolbox or plugin.

The reason why I’ve decided on this approach rather than outputting directly to the MATLAB console is because I eventually want to add additional functions to reshape and reformat the text, and also to save the text that appears in its own window using additional Java swing components. But that’s a story for another day.

The Quick How-To … ( 3 steps )

Choose the toolbox or plugin you’d like to modify and open up its “.m” file. This is where you’ll want to add your custom code. There are three parts to this exercise — first, we need to get a few classes from Java; then, we need to store the data we want to display; finally, we make the display appear.

In this example, I’ll import the bare minimal amount of Java classes — you can extend this functionality by adding more swing classes if you like. I’ve arbitrarily prefixed my Java variables above with the prefix “expose”.

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane; // Scrollbars -- optional.
exposeReport = JFrame('Data Report');
exposeTa = JTextArea(24, 80);
exposeScroll = JScrollPane(exposeTa);
exposeScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
exposePane = exposeReport.getContentPane();
exposePane.add(exposeScroll);
exposeReport.pack();

I’m not exactly sure why MATLAB doesn’t include scrollbars automatically.

Of the above, there are only two variables which we’ll need to refer to again later — “exposeReport” and “exposePane”.

The next step is to use your JTextArea as an output terminal. Just append strings to it as the graph is being built — you’ll have to look at your specific plugin to figure out the logic behind the graph — in general, you’ll be looking for a for-loop and a function that alters the graph.

// Look for a 'for' loop with a line that adds data to the graph.
// Here, I've used the variable SomeX for a point's x-coordinate,
// and SomeY for a point's y-coordinate.
exposeTa.append(sprintf('%d\t%d\n', SomeX, SomeY));

The loop spins around and incrementally adds all of the points. Note that I’ve used “%d” as a conversion to numbers expressed in base-ten (including floating point values). This is different from the conversion character in C where “%d” indicates only integers.

We add the final code after the loop exits. This next code makes your data report window visible — just as you’d expect from Java.

exposeReport.setVisible(1);

I opted to put this line after the code that reveals the toolbox’s original summary window — this causes my report to appear on top.

That’s all there is to it! Enjoy 😀

MATLAB from a CS student perspective

MATLAB has always been a bit of an oddball language for me. It’s dynamically typed but also exposes Java’s classes if you ask nicely. It’s C-looking and provides functions that the C-programmer would be happy accepting such as strcat and sprintf, but again — putting on the dynamic spin by returning the constructed string rather than modifying the contents of a buffer. All in all, the design choices do a good job of making MATLAB do what it’s intended to do; it gives scientists and engineers a way to succinctly express math to a machine without having to take too many computer science courses.

Eddie Ma

July 11th, 2011 at 1:18 am

The Right Tool (Why I chose Java to do RSA)

without comments

Brief: I learned something valuable last week when working on this RSA encryption/decryption assignment for my Computer Security class. It’s important to be versatile when doing computer science — we must ensure we always use the most efficient tool. If we aren’t versatile, we risk taking tremendous amounts of time trying to reimplement something that already exists elsewhere.

So, what tool is the right tool to quickly throw together RSA encryption?

It turns out that Java does an excellent job. Its BigInteger class has all the ingredients you’ll ever need.

// This function generates a new probable prime ...
BigInteger p = BigInteger.probablePrime(bits, random);

// This function performs modulus inverse ...
BigInteger d = e.modInverse(phi_n);

// These functions can be used to check your work ...
BigInteger one = d.multiply(e).mod(phi_n);
BigInteger one = p.gcd(q);

// This function is at the heart of RSA ...
BigInteger C = M.modPow(d, n);

Before I looked at the Java documentation, I had plans to do this with Python and some of my classmates had plans with MATLAB. It’s not that these are inherently bad technologies — they’re just not the right tool.

As much as I have gripes with Java, I’ve got to say that this made me and a lot of my class very happy 😀

Eddie Ma

February 24th, 2011 at 6:26 pm

Posted in Pure Programming

Tagged with , ,

Generic Functions in C# and Java

without comments

>>> Attached: ( Main.java — in Java | Main.cs — in C# ) <<<

Updated: (1) Made code more readable. (2) Removed unnecessary package (Java) and namespace (C#) and added a function that returns a generic type as well. (3) Attached compilable demo source code in separate files.

The most fun and productive concept in object oriented programming is generics — for me anyway. In C, one could deploy generics hazardously with code that casts the contents of memory addresses with a putative struct. The first field gives away what that chunk of memory is supposed to be at run time (usually, it’s a typdef int or an enum). I still do that when it’s called for, but it’s quite delicate and often leads to insidious bugs that don’t crash immediately. At least one would know what code to suspect when crashes do happen.

In C# and Java, two languages that derive from C — we find full safe support of generics. Generic classes (the things that collections are made of) are interesting, and I’m sure most who have used either of these languages have already played with them and have found them useful. One of the things that don’t receive a healthy dose of spotlight is Generic Functions (“Generic Methods” if you like).

I’ll compare two segments of code, one in C# and one in Java that do exactly the same thing — demonstrate two trivial functions printArrayList() and getElement(). The function printArrayList() prints out the contents of an ArrayList (Java) or a List (C#). The function getElement() retrieves an element from a list. This shows how single generic functions can operate on collections, each with a different defined type without the need for unsafe casting. The only assumption the code makes is that each object in a list implements the toString() method (needed for the printing function).

Note naming convention: In Java, methods are just members of an object, so they are named in lowercase. In C#, methods are capitalized. We will refer to methods by the Java convention here to keep things consistent.

Setting Up in Main…

Let’s declare and fill a few lists for this demonstration. Three generic list objects, cow, dog and elephant are constructed in a for loop. Each gets ten elements. Each list contains objects of a particular type; cow contains integers, dog contains doubles and elephant contains strings.

Java Code C# Code
ArrayList<Integer> cow = new ArrayList();
ArrayList<Double> dog = new ArrayList();
ArrayList<String> elephant = new ArrayList();
List<int> cow = new List();
List<double> dog = new List();
List<string> elephant = new List();

Notice that Java does not autobox the type in the angel brackets so you can’t give it the primitives int and double. In C#, this is allowed plus string is also a primitive. Remember: In both Java and C#, primitives are emulated — they are first class objects that are only different from other objects in that they are pass-by-value rather than pass-by-reference.

Appending ten items to each list. Shown below is the Java version — in C#, change “add()” to “Add()”.

for(int i = 0; i < 10; i ++) {
    cow.add(3 * i);
    dog.add(0.25 * i);
    if(i % 2 == 0)
        elephant.add("Even");
    else
        elephant.add("Odd");
}

The below is the code we want to make work — We’ll call printArrayList() to print out all of the elements in each list, then we’ll call getElement() to return a specific element from each list. Notice that this is the Java version below — in C#, we capitalize method names and use Console.Writeline() instead of System.out.println().

System.out.println("== Generic List Printer ==");

printArrayList(cow);
printArrayList(dog);
printArrayList(elephant);

System.out.println();

System.out.println("== Generic Element Accessing ==");

int    cow_at_7      = getElement(cow, 7);
double dog_at_2      = getElement(dog, 2);
String elephant_at_4 = getElement(elephant, 4);

System.out.println("Cow at 7      = " + cow_at_7);
System.out.println("Dog at 2      = " + dog_at_2);
System.out.println("Elephant at 4 = " + elephant_at_4);

Note that in C#, we may use the keyword “var” instead of typing out the types for cow_at_7, dog_at_2, and elephant_at_4 — the compiler infers the type for us. This is different from unsafely casting with “Object”, as the compiler infers the narrowest possible type and substitutes in that correct type.

Onto the methods …

Below is the Java version of printArrayList().

static <A> void printArrayList(ArrayList<A> animalList) {
    for(A a : animalList)
        System.out.print(a + "\t");
    System.out.println();
}

Below is the C# version of PrintArrayList().

static void PrintArrayList<A>(List<A> animalList) {
    foreach(A a in animalList)
        Console.Write(a + "\t");
    Console.WriteLine();
}

Notice that printArrayList() is a method that specifies a generic type <A>, but only in its argument list. In Java, <A> appears before the function’s type and in C#, this appears after the function name. In this case, it’s obvious what we would do if we have functions that return specific types — we just substitute the type where the keyword “void” is. So what happens when we want to return the generic type? That’s what getElement() will demonstrate.

Below is the Java version of getElement().

static <A> A getElement(ArrayList<A> what, int which) {
    return what.get(which);

Below is the C# version of GetElement().

static A GetElement<A>(List<A> what, int which) {
    return what[which];

Yes, these are both trivial functions, as you could have easily called ArrayList.get() in Java and List[] in C# respectively — but it does the job in this demonstration. In the Java version, the generic type <A> is placed before the type of the function, A. Don’t let that confuse you, just recall how we specified the return type when it wasn’t the generic type. In C#, we place the generic type <A> after the function name just as before.

Below is the output you should expect if you run the main function.

C# Output

== Generic List Printer ==
0	3	6	9	12	15	18	21	24	27
0	0.25	0.5	0.75	1	1.25	1.5	1.75	2	2.25
Even	Odd	Even	Odd	Even	Odd	Even	Odd	Even	Odd	

== Generic Element Accessing ==
Cow at 7      = 21
Dog at 2      = 0.5
Elephant at 4 = Even

The Java output is the same, except the values that are doubles are always printed with a trailing “.0” even if it is numerically equal to an integer.

Eddie Ma

January 29th, 2010 at 11:41 am

Java Classpaths are Evil

with 2 comments

While working with Phylogenetic Analysis Library (PAL) for an alignment problem, I ran into the problem of having to specify classpaths to a jar file… it should have be straight forward enough…

Java classpaths are a pain.

Here are a few observations I’ve made about how to specify them in the command line.

  • an Item can either be a directory that contains .class and .java files OR
  • an Item can be a .jar file.
  • to specify more than one Item.jar in Unix, use:
javac -classpath .:Item1.jar:Item2.jar
  • note that you cannot put a space between the colons
  • note that you must include an extra Item ‘.’ to specify the current working directory
  • note that in Windows, you must use ‘;’ instead of ‘:’
  • note that after compiling with javac, the same -classpath and its arguments must then be applied with java

Nuisance? Yes! Necessary Evil? No!

In the compiled Java class, there certainly could have been some metadata implemented that is a copy of the last known classpath string… why is there a disparity between the symbols used in Unix and Windows? … Why aren’t spaces allowed? Why does one have to specify the current working directory?

Evil.

A side effect of not being able to put spaces in between the colons of several paths is that one can’t just put a backslash in to negate a newline– you would need to have the next path start at the very beginning of the next line which is just ugly.

Eddie Ma

November 23rd, 2009 at 12:28 pm

Posted in Pure Programming

Tagged with ,