Thursday, January 20, 2011

Banshee "seek" function problem solved

Apparently my fav player has been refusing to let me use the 'seek' bar for some time now and I dodged looking for a solution too long now. After 2 minutes of research I found out that all I needed to do was to install the package gstreamer0.10-plugins-ugly and restart Banshee. Funny thing is I don't even remember uninstalling it in the first place (presuming that it was pre-installed).
Anyway.... another bug fix in my F1 Notebook

Saturday, January 15, 2011

Sunday, January 9, 2011

New features Java EE 6.0

I found a nice article on this topic here: http://www.javabeat.net/articles/99-new-features-in-java-ee-60-1.html

Thursday, January 6, 2011

Linux Subdirectories of Root directory [cheatsheet]

  • /bin - Common programs, shared by the system, the system administrator and the users.
  • /boot - The startup files and the kernel, vmlinuz. In some recent distributions also grub data. Grub is the GRand Unified Boot loader and is an attempt to get rid of the many different boot-loaders we know today.
  • /dev - Contains references to all the CPU peripheral hardware, which are represented as files with special properties.
  • /etc - Most important system configuration files are in /etc, this directory contains data similar to those in the Control Panel in Windows
  • /home - Home directories of the common users.
  • /initrd - (on some distributions) Information for booting. Do not remove!
  • /lib - Library files, includes files for all kinds of programs needed by the system and the users.
  • /lost+found - Every partition has a lost+found in its upper directory. Files that were saved during failures
    are here.

  • /misc - For miscellaneous purposes.
  • /mnt - Standard mount point for external file systems, e.g. a CD-ROM or a digital camera.
  • /net - Standard mount point for entire remote file systems
  • /opt - Typically contains extra and third party software
  • /proc - A virtual file system containing information about system resources. More information about the
    meaning of the files in proc is obtained by entering the command man proc in a terminal
    window. The file proc.txt discusses the virtual file system in detail.

  • /root - The administrative user's home directory. Mind the difference between /, the root directory and
    /root, the home directory of the root user.

  • /sbin - Programs for use by the system and the system administrator.
  • /tmp - Temporary space for use by the system, cleaned upon reboot, so don't use this for saving any work!
  • /usr - Programs, libraries, documentation etc. for all user-related programs.
  • /var - Storage for all variable files and temporary files created by users, such as log files, the mail
    queue, the print spooler area, space for temporary storage of files downloaded from the Internet,
    or to keep an image of a CD before burning it.

Wednesday, December 1, 2010

The Filter Pattern - Selective Iterators

The following code is from: http://www.erik-rasmussen.com/blog/2008/01/18/the-filter-pattern-java-conditional-abstraction-with-iterables/ 


import
java.util.Iterator;

import java.util.NoSuchElementException;


public abstract class Filter<T> {

  public abstract boolean passes(T object);


  public Iterator<T> filter(Iterator<T> iterator) {

    return new FilterIterator(iterator);

  }


  public Iterable<T> filter(Iterable<T> iterable) {

    return new Iterable<T>() {

      public Iterator<T> iterator() {

        return filter(iterable.iterator());

      }

    };

  }


  private class FilterIterator implements Iterator<T> {

    private Iterator<T> iterator;

    private T next;


    private FilterIterator(Iterator<T> iterator) {

      this.iterator = iterator;

      toNext();

    }


    public boolean hasNext() {

      return next != null;

    }


    public T next() {

      if (next == null)

        throw new NoSuchElementException();

      T returnValue = next;

      toNext();

      return returnValue;

    }


    public void remove() {

      throw new UnsupportedOperationException();

    }


    private void toNext() {

      next = null;

      while (iterator.hasNext()) {

        T item = iterator.next();

        if (item != null && passes(item)) {

          next = item;

          break;

        }

      }

    }

  }

}

Tuesday, November 30, 2010

A little insight on Java's 'type erasure' terminology

As everyone knows, generics have been introduced since Java 1.5 to enforce compile-time type-correctness. However, at run-time, all the type safety is removed via a process called 'type erasure'. So all typed Collections will have their type removed from the bytecode at runtime and explicit casts will be introduced when extracting elements from the Collections.  For example List<Double> list = new ArrayList<Double>();  will be translated at runtime to List list = new ArrayList(); . As a result of type erasure, type parameters cannot be determined at runtime. This change has been introduced in ordered to ensure pre-Java 5 code (you may call it 'legacy code') inter-operates peacefully with the newly introduced generics.

Monday, November 15, 2010

[Spring Framework] Constructor vs. Setter injection

Following are a number of paragraphs stripped from "Spring in Action, 2nd Edition" ,by Craig Walls, published by Manning Publications in 2007, which illustrate in a rather friendly manner the ups and downs when opting for a particular type of mutator: [This goes in my blog as a future reference]

"There are certain things that most people can agree upon: the fact that the sky
is blue, that Michael Jordan is the greatest player to touch a basketball, and that
Star Trek V should have never happened. And then there are those things that
should never be discussed in polite company, such as politics, religion, and the
eternal “tastes great/less filling” debates.
Likewise, the choice between constructor injection and setter injection stirs up
as much discourse as the arguments surrounding creamy versus crunchy peanut
butter. Both have their merits and their weaknesses. Which should you choose?

Those on the constructor-injection side of the debate will tell you that:
• Constructor injection enforces a strong dependency contract. In short, a
bean cannot be instantiated without being given all of its dependencies. It is
perfectly valid and ready to use upon instantiation. Of course, this assumes
that the bean’s constructor has all of the bean’s dependencies in its param-
eter list.

• Because all of the bean’s dependencies are set through its constructor,
there’s no need for superfluous setter methods. This helps keep the lines of
code at a minimum.

• By only allowing properties to be set through the constructor, you are, effec-
tively, making those properties immutable, preventing accidental change in
the course of application flow.

However, the setter injection-minded will be quick to respond with:
• If a bean has several dependencies, the constructor’s parameter list can be
quite lengthy.

• If there are several ways to construct a valid object, it can be hard to come
up with unique constructors, since constructor signatures vary only by the
number and type of parameters.

• If a constructor takes two or more parameters of the same type, it may be
difficult to determine what each parameter’s purpose is.

• Constructor injection does not lend itself readily to inheritance. A bean’s con-
structor will have to pass parameters to super() in order to set private
properties in the parent object.

Fortunately, Spring doesn’t take sides in this debate and will let you choose the
injection model that suits you best. In fact, you can even mix-and-match construc-
tor and setter injection in the same application... or even in the same bean."

Saturday, October 9, 2010

Simple Apache Lucene tutorial courtesy of "Java Code Geeks"

http://www.javacodegeeks.com/2010/05/introduction-to-apache-lucene-for-full.html

Thursday, September 16, 2010

Change the GRUB Menu Timeout on Ubuntu

When your Ubuntu system boots, you will see the GRUB menu if you hit the Esc key, or if you’ve enabled the menu to show by default.
The only issue with this is that the default timeout is only 3 seconds.
You may want to increase this amount… or you may even want to decrease
it. Either one is simple.


Open up the /boot/grub/menu.lst file in your favorite text editor. I’m using gedit:


sudo gedit /boot/grub/menu.lst



Now find the section that looks like this:


## timeout sec
# Set a timeout, in SEC seconds, before automatically booting the default entry
# (normally the first entry defined).
timeout 3



The timeout value is in seconds. Save the file, and when you reboot
you will have that many seconds to choose the menu item you want.

show the GRUB menu by default on Ubuntu

When Ubuntu boots, you normally briefly see a screen that says “GRUB loading. please wait… Press Esc to enter the menu…”


If you are hacking around your system and would prefer to always see
the GRUB menu (to enter command-line options, for instance), there’s an
easy fix.


Open up the /boot/grub/menu.lst file in your favorite text editor. I’m using gedit:


sudo gedit /boot/grub/menu.lst



Now find the section that looks like this:


## hiddenmenu
# Hides the menu by default (press ESC to see the menu)
hiddenmenu



Put a # before hiddenmenu to comment that line out:


## hiddenmenu
# Hides the menu by default (press ESC to see the menu)
#hiddenmenu



Save the file, and you should see the menu the next time you reboot.


SOURCE: www.howtogeek.com

Adding windows XP to grub menu after intalling this OS AFTER Ubuntu

So your dual booting windows and you want windows to appear in the grub screen at startup. Here's how you do it:



As root:

# nano /boot/grub/menu.lst



Add the following lines in wherever you would like the entry to show up:



title MS Windows XP

root (hd0,0) [note below]
*
savedefault

makeactive

chainloader +1



*(hd0,0) means /dev/hda1

*(hd0,1) means /dev/hda2

Wednesday, July 7, 2010

SCDJWS 5, web service design patterns notes


Web Service Design Patterns






The
design patterns related to Web Service help to enhance
maintainability of the solution or to minimize QoS impact associated
with building applications using web service frameworks. Web Services
based interaction might be expensive because of


  • operation
    is expensive in term of server-side processing
  • communication
    overhead (amount of data transfer/bandwidth)
  • encoding/decoding
    may be expensive

Application
designers should look for alternatives in this situation.


Asynchronous Interaction Pattern


Goals
of this pattern are:


  • decouple
    input and output.
  • deliver
    output from server to client.
  • Associate
    output message with corresponding input message

This
can be achieved with various application level designs to achieve the
above goals which are Server-side push, Client-side pull. JMS-based
and JAX-WS based which are described below.




Server-side
push


Approach
1: Client supplies the address of a web service dedicated to
process specific response to the request, as part of request and the
server contacts the dedicated web service to reply to the query back
to the client.


Approach
2: Client supplies address of a generic web service that can be
invoked to supply the result of operation back to client, along with
unique token to identify this request, The server later invokes this
generic web service to deliver an answer to this client the server
uses the same token as part of response message to identify the
response to client. WS-Addressing defines a way to create these
tokens portably.




Client-side
pull


Client
issues a request along with a unique token to server, the server
accepts the request, allowing client to continue processing. server
process each request to obtain response and stores all responses
indexed by tokens supplied by client in each request in a data
structure accessible as a new Response web service. Each client
queries the new web service for answer to earlier requests using the
same token. Enough storage required on server side to store all
response, until the client retrieves it. For reliability the storage
might need to be persistence. Increases network overhead as client
may poll periodically for it's response.




JMS
based


Non-portable
web service solution, uses JMS as message transport instead of HTTP.
Both Client-side pull and Server-side push can be implemented using
JMS. In case of Client-side pull the client uses multiple requests
first being a JMS message and the subsequent ones being synchronous
and portable.




JAX-WS
based


JAX-WS
introduces Dispatch<T> and Provider<T> interfaces to
describe client and server side of the interaction. On client side it
introduced the ability to indicate whether the interaction is
synchronous or asynchronous, whether it's Client-side pull or
Server-side push or one way.

interface
Dispatch<T>{ // client-side
 
T invoke(T
msg);
 
Response<T>
invokeAsync(T msg);
 
Future<?>
invokeAsync(T msg, AsyncHandler<T> h);
 
void
invikeOneWay(T msg);

}



interface
Provider<T>{ // server-side
 
T invoke(T msg,
Map<String, Object> context);
}

Example

MessagingAPIMessage
request = new MessagingAPIMessage( "sayHello", "Tracy"
);

MessagingAPIMessage
response = MessagingAPIMessage) port.invoke( request );

System.out.println("Response:
" + response.getResult());

AsyncHandler<Object>
responseHandler = new AsyncHandler<Object>() {
 
public void
handleResponse(Response<Object> resp){
  
try {
    
MessagingAPIMessage
result = (MessagingAPIMessage) response.get();
   
 
System.out.println(
"Response: " + result.getResult() );
  
} catch(
Exception e ) {  
}
 
}
};
port.invokeAsync(
request, responseHandler );



Advantages:
More responsive application, JAX-WS provides transparent
implementation

Disadvantages: Other
than JAX-WS requires more complex designs

JMS Bridge


The
Characteristics of JMS Bridge pattern are as follow:


  • Keep
    different subsystems using their own JMS implementation
  • Introduce
    a client which can relay messages from one JMS implementation to
    next
  • the
    JMS clients should be implemented as Web Services

Advantages:
No need to develop vendor specific to bridge two underlying
middle-ware vendor. It's vendor and JMS independent.

Disadvantage:
Overhead XML encoding/transmission and decoding

Web Service Cache


Cache
can be introduced at two places which will be transparent to client
(as Endpoint Handlers). The overhead is reduced by short-circuiting
requests that do not need to be executed.


Advantages:
Reduce communication and processing overhead

Disadvantage:
Increased memory
footprint, application must realize when to invalidate or refresh
cache.

Web Service Broker


Can
be used implement some services as Web Service and still address the
concerns that web services don't address like transaction
propagation. Web Service broker is introduced as a middle-man between
the client and the remote service in which the client is interested.
Can be implemented as a state-full session bean.


Advantage:
Simpler client design

Disadvantage:
Complex to implement (not guaranteed)

Web Service Logger


A
common approach to introduce logging into the design of an
application involves the application of Decorator pattern as follows:



  • An additional object is
    introduced as a wrapper around the actual service provider.
  • The logging functionality is
    captured in the wrapper.

Sunday, May 16, 2010

SQLalchemy tweak

If you've been ripping your hair off trying to figure out the "BoundMetaData is not defined" error in SQLAlchemy, the answer is to switch "BoundMetaData" with simply "MetaData", as the first one appears to have been deprecated. The Python code should look like this:

from sqlalchemy import *<br /><br />db = create_engine('sqlite:///MyDb.db')<br />metadata = MetaData(db)<br />

Useful SQLAlchemy links:
http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html
http://www.sqlalchemy.org/docs/05/ormtutorial.html

Wednesday, April 14, 2010

basic xml-rpc communication between a python server and c# client

Setting up the python server

import calendar, SimpleXMLRPCServer

#The server object
class Calendar:
    def getMonth(self, year, month):
        return calendar.month(year, month)

    def getYear(self, year):
        return calendar.calendar(year)


calendar_object = Calendar()
server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8888))
server.register_instance(calendar_object)

#Go into the main listener loop
print "Listening on port 8888"
server.serve_forever()



Setting up the C# client

1. Download the helping DLL's from http://xml-rpc.net/
2. Create a proxy interface: 


using System;
using CookComputing.XmlRpc;

namespace XMLRPCclient
{
   
    [XmlRpcUrl("http://127.0.0.1:8888/")]       
    public interface IClientCalendarProxy : IXmlRpcProxy
    {
        [XmlRpcMethod("getMonth")]
        string getMonth(int p1, int p2);

    }
}



3. Init & run your client using the upper defined proxy interface (make sure the URL points to the port of the web service)

using System;
using CookComputing.XmlRpc;

namespace XMLRPCclient
{

    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
           
           

            IClientCalendarProxy proxy = XmlRpcProxyGen.Create<IClientCalendarProxy>();


            string ret = proxy.getMonth(2002,8);
            Console.WriteLine(ret);

        }
    }
}



Useful links:

Sunday, March 21, 2010

[windows] deleting winrar temporary data

If you've ever been in the situation where you have to unzip a large archive and you cancel the unzipping process midway, you will find that upon cancellation, the temporary winrar files will not be erased so you will find yourself losing 6,7 Gb of space just like that. To fix this, go to "Run" and type %temp% - this is the temporary folder on your computer, so just go on and delete all the unused stale data (such as winrar temporary files).

Friday, March 19, 2010

Many-To-Many self reference in Java Persistence API

    Think of the following scenario: you need a many-to-many relationship between a table and itself... how can you accomplish that with JPA annotations ?
    Suppose we have a table Tasks in the database which is mapped to an Entity named Task. A task entry should have a list of parent tasks (prerequisite tasks if you want) and a list of child tasks (tasks which upon the current task's completion would enable them to start). The Task entity class would look a little something like this:

@Entity
@Table (name = "Tasks" , schema = "ProjectManagement" )
public class Task implements Serializable {

// Mandatory @Id PK field

//constructors (including a no-arg constructor)

//fields

// getters and setters


@ManyToMany
@JoinTable ( name = "parent_child_task" ,
                    joinColumns = @JoinColumn ( name = "child_id" , referencedColumnName = "id" ),
                    inverseJoinColumns = @JoinColumn ( name = "parent_id" , referencedColumnName = "id" ))
private List<Task> prerequisiteTasks = new ArrayList<Task>();

@ManyToMany (mappedBy = "prerequisiteTasks" )
private List<Task> childTasks = new ArrayList<Task>();

//.... more

}

Hope this makes sense

Wednesday, March 17, 2010

Operations allowed in EJB 3.0 session beans

  • Operations Allowed in the Methods of a Stateful Session Bean






  • Operations Allowed in the Methods of a Stateless Session Bean





SOURCE: EJB 3.0 specification



Tuesday, March 16, 2010

Bulk Update and Delete Operations in EJB 3.0 JPQL

Bulk update and delete operations apply to entities of a single entity class (together with its subclasses, if any). Only one entity abstract schema type may be specified in the FROM or UPDATE clause.

The syntax of these operations is as follows:
update_statement ::= update_clause [where_clause]
update_clause ::= UPDATE abstract_schema_name [[AS] identification_variable]
                            SET update_item {, update_item}*
update_item ::= [identification_variable.]{state_field | single_valued_association_field} =
                            new_value
new_value ::=
          simple_arithmetic_expression |
          string_primary |
          datetime_primary |
          boolean_primary |
          enum_primary
          simple_entity_expression |
          NULL
delete_statement ::= delete_clause [where_clause]
delete_clause ::= DELETE FROM abstract_schema_name [[AS] identification_variable]

  • A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.
  • The new_value specified for an update operation must be compatible in type with the state-field to which it is assigned.
  • Bulk update maps directly to a database update operation, bypassing optimistic locking checks. Portable applications must manually update the value of the version column, if desired, and/or manually validate the value of the version column.
  • The persistence context is not synchronized with the result of the bulk update or delete.

Caution should be used when executing bulk update or delete operations because they may result in
inconsistencies between the database and the entities in the active persistence context. In general, bulk update and delete operations should only be performed within a separate transaction or at the beginning of a transaction (before entities have been accessed whose state might be affected by such operations)
.

SOURCE: EJB 3.0 Persistence Specification, pages 104-105


Saturday, March 6, 2010

Installing XAMPP on 64 bit Ubuntu

Installing and securing XAMPP:
http://www.codetorment.com/2009/10/20/guide-install-xampp-on-ubuntu/

Basic installing:
http://sadhas.wordpress.com/2009/10/01/install-xampp-in-ubuntu/

Similar topic:
http://azimyasin.wordpress.com/2007/11/13/running-xampp-in-64-bit-machine/