Wednesday, April 22, 2009

Installing ImageMagick / Imagick for PHP on Linux CentOS

This was tricky, so thought I'd post for peeps having problems.


1.yum install ImageMagick


2.yum install php-devel (if not installed)

NOTE: skipping step 2 leads to this problem..."ERROR: `phpize' failed".


3.yum install ImageMagick-devel

NOTE: skipping step 3 leads to this problem ... "ERROR: `/tmp/tmppccQA1/imagick-2.2.2/configure --with-imagick' failed"


4. WRONG: pecl install imagick

had problem : PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/modules/imagick.so' - /usr/lib/php/modules/imagick.so: undefined symbol: ClonePixelWand in Unknown on line 0


fixed by uninstalling : pecl uninstall imagick


4.RIGHT : pecl install imagick-2.2.1 (don't just run pecl install imagick, version 2.2.2 doesn't work)


5. echo "extension=imagick.so" > /etc/php.d/imagick.ini (might not be neccessary)


6. vi /etc/php.ini -> add extension=imagick.so


7. /etc/init.d/httpd restart


8.php -m | grep imagick (to check if loaded.)


AND finally it should work! Hope this helps!

Thursday, April 9, 2009

SQL: Distinct vs group by

...Okay, this isn't Java related, but I'm mostly doing PHP + SQL Server queries these days and I'm too lazy to make a new blog.


As I'm still a bit of a beginner when it comes to SQL (mostly just know basic selects and inserts... even my joins are rather rusty) I had a problem with select statement. Even though I wanted to get data cross-referenced from a bunch of tables, I only wanted data where the first column was unique.

"so this is a job for distinct, right?"

Wrong. This is really a job for group by, and this is why:


(quoted from "Jeff's SQL Server Blog") :

http://weblogs.sqlteam.com/jeffs/archive/2007/10/12/sql-distinct-group-by.aspx


I'm reproducing the text below because I hate it when links become outdated.


By The Way ... DISTINCT is not a function ...

Have you ever seen (or written) code like this:



select distinct(employeeID), salary

from salaryhist


That compiles and executes without returning any errors. I've seen that attempted many times over the years, and of course people think DISTINCT is "broken" and "not working" because they see multiple rows for each employeeID. "But I asked for only distinct employeeIDs!" they say.


Well, the DISTINCT has nothing to do with the EmployeeID column; it is not a function that accepts arguments! It is just a tag that you can put after the word SELECT to indicate that you want only distinct combinations of all columns in the result set returned.


That syntax is accepted because (employeeID) is just an expression, a reference to a column, which happens to be surrounded by parenthesis. For example, you could write:



select distinct (employeeID), (salary)
from salaryhist


or:


select (employeeID), (salary)
from salaryhist



or even:



select distinct ((employeeID)), ((salary))
from salaryhist



Nothing is indicating that DISTINCT should be "operating" on the employeeID column; it is just a column reference in the SELECT clause that happens to be surrounded by parenthesis.


So, remember:


DISTINCT always operates on all columns in the final result
DISTINCT is not a function that accepts a column as an argument
When you do want to return multiple columns in your result, but only have them be distinct for a subset of those columns, you would use GROUP BY. And, of course, you must specify how you'd like to summarize all non distinct/grouped columns for any others you'd like to return:



select employeeID, max(salary) as MaxSalary
from salaryhist
group by employeeID



Notice that now we are getting distinct EmployeeID values, and the max salary per EmployeeID. This will truly return exactly one row per EmployeeID, unlike the initial DISTINCT example. And, in this case, MAX() is indeed a function that accepts and acts upon an argument -- unlike DISTINCT!

Thursday, January 15, 2009

A hint

Sometimes you get to wondering when to make objects... or when to stick to a basic premade type and call some methods in your normal class to change them.

When you find yourself wanting to do something like...
myThing = doSomethingToMyThing(myThing); //if it's local or
myThing = doSomethingToMyThing(); //if it's global

you know you should really make that method belong to myThing's class, since all you want to do is change something about that object.
If there's no such handy method in the MyThing class, it may be time to make your own object extending it, and give it the method. It's the OO way!

cuz myThing.doSomething(); just looks cleaner, don't it?

Thursday, January 8, 2009

No join method?!

Wow, I was raised on perl so this came as a bit of a shock...

the opposite of split is... nothing

boo. shame on you, Sun.

Thursday, June 12, 2008

mysterious smells

One of our problems at this company is the need to write, re-write, and edit a huge amount of the code base really fast. Since we have demos, releases and branches coming up in a few weeks (less now that I'm going to be going back to Japan soon), there is a feeling of muted urgency.


The good news: we're pretty good at doing what is needed very quickly.

The bad news: our code is starting to smell.


What do I mean by smell? A 'code smell' is a term I just learned the other day. Basically it's a combination of less-than-optimum coding practices, usually introduced by a lack of refactoring, or using procedural programming techniques (because they're more intuitive/easier to implement) when in the long run the code would be much easier to maintain and understand using object oriented principles.


Here is a list stolen from http://wiki.java.net/bin/view/People/SmellsToRefactorings
(which in turn was summarized from the classic book "Refactoring" by Kent beck.)















































SmellDescriptionRefactorings
Comments Should only be used to clarify "why" not "what".

Can quickly become verbose and reduce code clarity.
Extract Method

Rename Method

Introduce Assertion

Long Method The longer the method the harder it is to see what it’s doing.
Extract Method

Replace Temp with Query

Introduce Parameter Object

Preserve Whole Object

Replace Method with Method Object

Long Parameter List Don't pass in everything the method needs; pass in enough so that the method can get to everything it needs.
Replace Parameter with Method

Preserve Whole Object

Introduce Parameter Object

Duplicated Code
Extract Method

Pull Up Field

Form Template Method

Substitue Algorithm

Large Class A class that is trying to do too much can usually be identified by looking at how many instance variables it has. When a class has too many instance variables, duplicated code cannot be far behind.
Extract Class

Extract Subclass

Type Embedded in Name Avoid redundancy in naming. Prefer schedule.add(course) to schedule.addCourse(course)
Rename Method

Uncommunicative Name Choose names that communicate intent (pick the best name for the time, change it later if necessary).
Rename Method

Inconsistent Names Use names consistently.
Rename Method

Dead Code A variable, parameter, method, code fragment, class, etc is not used anywhere (perhaps other than in tests). Delete the code.
Speculative Generality Don't over-generalize your code in an attempt to predict future needs.
If you have abstract classes that aren't doing much use Collapse Hierarchy

Remove unnecessary delegation with Inline Class

Methods with unused parameters - Remove Parameter

Methods named with odd abstract names should be brought down to earth with Rename Method



There are more on that site, and even more in the book. I should really buy it. But it might just sit on the shelf like my 'Design Patterns' book. Oh well, at least my coworker found use for it and has been semi-permanently borrowing it.
But I digress.

Friday, May 16, 2008

Perly Java

So, if you have even a tiny bit of Java experience you know about the normal format of the if/then/else control flow.

if(something that might be true){
do this;
}else{
do that;
}

or alternatively,
if(something that might be true){
do this;
}else if(something else that might be true){
do that;
}else{
do the alternative.
}

Of course there are a number of ways to make these statements shorter, like ommitting closing curly braces if the 'do this' operation is one line, etc.
These shorter ways are a little harder to read, but make the code a little more compact which can be a good thing.
But there is an even SHORTER way! If you just have a simple if/then/else statement, nothing fancy, just one operation for the if and the else, then you can get it down to one line.

To make this even more cryptic, it is not even necessary to use the words 'if' or 'else' in there at all: in place of if is '?' and in place of else is ':'.
So the above code fragment would look like this:

(something that might be true)?do this:do that;

This is getting suspiciously like Perl, if you ask me. Java heresy! ;)

Friday, May 2, 2008

Singletons: I finally get it

When I was trying to make a map for a servlet that is created long before I can pass stuff to it, I realized I need a way to make a map of user's input from the GUI, give it to the servlet, and read that map from the server side. But it can't just be any old instantiation of a map object. It has to be the ONE instance that I actually put stuff in, so I know where to point on the server side from the servlet's data processing methods.

I had heard about singletons, and in fact had to study about them before. But I studied them in a kind of abstract way and never really had to use them - until now.

Here is a great great understandable explanation from "Using the Singleton Pattern"
by Budi Kurniawan (http://www.onjava.com/pub/a/onjava/2003/08/27/singleton.html).


How do you write a Singleton class? Simple: create a public static method that is solely responsible for creating the single instance of the class. This also means that the client of the class should not be able to invoke the Singleton class's constructor, either. Because the absence of a constructor will make the compiler create a no-argument public constructor, a class applying the Singleton pattern has a private or protected constructor. Because the constructor is private or protected, there is no way a client can create an instance of that class by calling its constructor. The constructor is not accessible from outside of the class!


If the only constructor cannot be accessed, how do we get an instance of that class? The answer lies in a static method in the class. As mentioned above, a Singleton class will have a static method that calls the constructor to create an instance of the class and return this instance to the caller of the static method. But isn't the constructor private? That's right. However, remember that the static method is also in the same class; therefore, it has access to all members of the class, including the private members of the class.


You might ask the following question: "You can't create an instance of a class by calling its constructor, so how do you call the static method (responsible for creating the single instance of the class) without having the class instance?" Note, though, that static members of a class can be invoked without having an instance of that class. To limit the number of instances to one, the static method has to check if an instance has been created before. If it has, it simply returns a reference to the previous created instance. If it has not, it calls the constructor to create one. It's as simple as that.



So to get my map, I create a singleton class to hold my data, create a static getInstance method, and instantiate it from the GUI with my data mapping. Then on the server, I call the getInstance method (which will pass me back the ONE object with my map), and voila!

Friday, March 28, 2008

Do-it-yourself equals and hash code methods

Usually you can depend on the Java Object uberclass to provide your class with adequate .equals (to determine two objects's equality) and hashCode() (to index your object within a hash).
But sometimes, you just need a little more. You can override these methods and give your own classes more specific instructions about what to do when they are being tested for equality or being indexed. I still have much to learn about this, but found a tasty looking link for further, later perusal.
http://www.geocities.com/technofundo/tech/java/equalhash.html

Friday, March 14, 2008

Data Facades

One of the signs you're moving from basic programming to more advanced stuff:
the use of Data Facades. I noticed this in some of the newer parts of our code base, where it's being refactored by a more competent programmer than I! :)
Here's a little blurb on it from the MSDN site:

"Consider using a data facade to wrap the most relevant data needed by the client. You can develop a wrapper object, with a coarse-grained interface, to encapsulate and coordinate the functionality of one or more objects that have not been designed for efficient remote access. It provides clients with single interface functionality for multiple business objects."

What does that mean? Say my server-side code has a few queries that have very little difference between them. Instead of making if/else statements to differentiate them, create a *DataFacade class for each of these states. These in turn should all implement an interface that has methods for getting a part of the query. The *DataFacade classes will in turn have the specifics for their method bodies.

Tuesday, January 22, 2008

GWT - UIServiceAsync timing

I've been working a lot with GWT (google web toolkit), and have been using the user interface 'client side' , tying in to the back end. (server side). This introduces a few problems, especially with database calls. GWT translates Java into Javascript for you, but it doesn't try to generate javascript for the code you keep hidden away on the server side (thank goodness, especially since GWT currently only supports Java 1.4!)
So how does it know when the calls to the server side are complete?


Using AsyncCallbacks. These have onSuccess and onFailure methods you write yourself, which tell your UI side what to do when your server side calls have finished.


I have found that the timing of these prove to be a pain. Your client side code, like the tide and time, waits for no man. It will merrily march on, after you have made a call to get some data from the database for instance, and not care whether or not it has completed to run the next line. So you can't really depend on the feedback from the server side on the next line, your data might very well be null.
..or the line after that. or the next one.

So how do you make sure that darn query's output can be properly shown to the user?


the answer lies in the onSuccess method.
You make a structure to contain whatever you need on the UI side, and draw itself (as empty for now, or with a 'loading, please wait' message) to the screen.
Then, pass that container to the Async call. In the onSuccess method, you tell it to write the output to that container and draw itself again.


This way the user will always see something, and you won't get null Pointer exceptions.

Wednesday, January 2, 2008

comparing objects with nulls

When trying to test an object to see if it's null or not (for good error handling purposes), it's good to know: a null object's .equal method doesn't measure up to a null. ie, you can't do this:



String s = null;
String r = null;

possiblySetMyString(r);

if(s.equals(null)){
System.out.println("string not set");
throw new RuntimeException();
}else{
System.out.println(s);
}

public void possiblySetMyString(String t){
s = t;
}



Nope! That won't work. you can't check if a string 'equals' null with the object's .equals method , because it's going to try to compare various String parameters to a null. Instead, replace the s.equals(null) with s==null.
Note: use == to check for primatives (int, char, bool, null etc), and use .equals to compare two objects. If you're comparing two different types, better convert before comparing.

Friday, November 30, 2007

Assignment does not give a copy.

In my naive assuption, I believed that the statement


myMethod Report(Report report){
Report copyofreport = report;
return copyofreport;
}


would give me a new object, an instance of the class Report.

It kind of worked, but introduced a subtle bug. I tried calling this method multiple times, thinking I could get an array of identical reports- but when I did something to my first report, all of the 'copies' I had made were similarly affected, even though I hadn't touched them.

What this actually did was make an array of references that all pointed to my original object, report. when I changed one, the references all reflected the same change.

solution: to make a new, identical object, there's a handy interface called cloneable. implement cloneable, override the method if necessary, and then call .clone().



// public class Report implements Cloneable;
ReportmyMethod Report(Report report){
Report copyofreport = report.clone();
return copyofreport;
}



Much better.
This only creates a 'shallow copy' though, so if there are any inner objects in the cloneable class, the objects will have the same reference. This really only matters if you're going to change the inner objects, but it's good to be aware of.

Wednesday, November 21, 2007

exceptions?

As a still relatively new Java programmer, I'm still having trouble deciding whether or not to throw Exceptions in parts of my code that can go wrong.
This site is a great reference for what to do and what to avoid.


http://today.java.net/pub/a/today/2006/04/06/exception-handling-antipatterns.html



The most useful part: Antipatterns: what you really *shouldn't* do, and why. Here's an excerpt:


catch (NoSuchMethodException e) {
LOG.error("Blah", e);
throw e;
}


"This is one of the most annoying error-handling antipatterns. Either log the exception, or throw it, but never do both. Logging and throwing results in multiple log messages for a single problem in the code, and makes life hell for the support engineer who is trying to dig through the logs."

So true!!

I gotta get a me whole book of antipatterns....

Tuesday, November 20, 2007

Dude, where's my method?

So I was creating a new method in a class. This method the same name, but different signature of an existing method, but it took in different arguments. I finished writing the method bodies, and went back to the class that called my new method.


Oddly, I got the error:

"The method getExchangeDelayPlot(ReportOptions) in the type ExchangeDelaysDAO is not applicable for the arguments (ReportRequest)".


Me: .".what are you talking about, stupid eclipse. I made the method getExchangeDelayPlot(ReportRequest), and saved it, and got no compiler errors. are you blind or something?"


Of course, my IDE was not blind. (isn't that always the case).

What I missed: Although I had added the method to the concrete class (ExchangeDelaysDAOImpl), I was trying to call the method its parent abstract class above this. I had forgotten to add the empty method signature of the new method to the abstract class.


Lesson 1: look carefully at the *type* in the error message.

Lesson 2: remember class hierarchies: remember to add method signatures to any abstract classes or interfaces you're trying to call your methods from.

Wednesday, November 14, 2007

The trouble with arrays

I've always had trouble with arrays. Either I forget to initialize 'em, or worry about hardcoding the upper limit of values they can take... they're a pain.

names = new String[100]; //why 100? it's a magic number! boo!


So I think it's time to work with dynamic arrays. In Java 5.0 and beyond there is a class called
ArrayList
, which is similar to an array, but has no upper limit (hardcoded, anyways). Plus it's dynamic.

but what if I want to sort my strings? I need them in alphabetical order sometimes.
alphabetical sorts are easy peasy with arrays:

java.util.Arrays.sort(array);

There is no ArrayList.sort() method. Luckily, it's a type of Collection, and Collections do have sort methods.


import java.util.ArrayList;
import java.util.Collections;
...
Collections.sort( myArrayList );

Ta-da!

Tuesday, November 13, 2007

Cannot make a static reference to the non-static method

ComponentMap cm = GenericRDSFactory.getRDSComponents(rr);


(where GenericRDSFactory is a different class): gives the error

"Cannot make a static reference to the non-static method":

The static keyword just means that the method or attribute belongs to that class.

The solution: instantiate the class first, then invoke the methods from the new object.

GenericRDSFactory factory = new GenericRDSFactory();

ComponentMap cm = factory.getRDSComponents(rr);