June 29, 2012

Java Varargs - Unlimited parameters to a Java method

When you cannot decide the number of parameters you need for a method, varargs becomes the solution. Earlier, if we couldn't determine such, we had to use a collection as a parameter to help with this scenario. But varargs simplifies this.

Varargs does use an array underneath, but using varargs syntax hides the process.

public static String format(String pattern,
                                Object... arguments);

Example :

If you need to write a file name extension filter for a number of extensions, you can use this method of defining the method.

public FileNameExtensionFilter(String description, String... extensions) {

Read more on varargs at :
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

JFileChooser - Useful Tips

Set Starting Directory
JFileChooser fileSaver = new JFileChooser();
String cpath = "C:/MWork/Test1/script/";
File f1 = new File(cpath);
fileSaver.setCurrentDirectory(f1);

File Filter
FileNameExtensionFilter filter = new FileNameExtensionFilter("eXtensible Markup Language file (*.xml) ", "xml");
fileSaver .setFileFilter(filter);

Default File Save Name
jFileChooser.setSelectedFile(new File("untitled.xml"));

June 22, 2012

Get Frame of a Component


In order to find the frame that contains a component, it is necessary to walk up the component's parents until the frame is encountered. SwingUtilities.getRoot() is a convenience method that finds the frame.

This example implements an action that finds and hides the frame of the component that triggered the action. See also Creating a JButton Component.

// Create an action
Action action = new AbstractAction("Action Label") {
  
    // This method is called when the action is triggered
    public void actionPerformed(ActionEvent evt) {
        
        Component c = (Component)evt.getSource();

        // Get the frame
        Component frame = SwingUtilities.getRoot(c);

        // Hide the frame
        frame.setVisible(false);
    }
};

http://www.exampledepot.com/egs/javax.swing/frame_FrameFind.html

June 21, 2012

XML Editor for Eclipse




Edit:
Make sure you go to Open With -> XML Editor to make XML Editor the default for that XML

June 19, 2012

Focus to newly added JComponent in Frame

int h = (int) pnlPrerequisites.getBounds().getHeight();
Component frame = SwingUtilities.getRoot(pnlPrerequisites);
System.out.println(h + "=" + frame.getHeight());
if (h > frame.getHeight()) {
    scrollPnlPre.setViewportView(p);
    // scrollPnlPre.getViewport().setView(p);
}

Problem : this removes the scroll

June 18, 2012

Get the string that matches the regex

If you want to get the string that matches the regex pattern you have defined, you might have noticed there isn't any direct method. As a solution a simple code as below can be used.

I wanted to read the number within the brackets in str.
(Note: The numbers always appear within brackets)
String str = "CLor (23)";
String search = "\\(\\d*\\)";
Pattern pattern = Pattern.compile(search);
Matcher matcher = pattern.matcher(str);
boolean matchFound = matcher.find();
if (matchFound) {
   int start = matcher.start();
   int end = matcher.end();
   String num = str.substring(start + 1, end - 1);
   System.out.println(num);
}

Above, in substring method I used
(start + 1, end -1)
because I needed to omit the brackets. If the whole string that matches the regex was needed method needs to have parameters
(start,end)

May 25, 2012

JTextBox Select all on Click

Following code will select all the content from the text box at click on it, if the textbox content is "<comment>".

Use focus listener - JTextArea does not have ActionListener like JTextField

public static JScrollPane getCommentBox() {

    final JTextArea txtComment = new JTextArea();
    txtComment.setText("<comments>");
    txtComment.setForeground(Color.GRAY);
    txtComment.setColumns(50);
    txtComment.setRows(3);

    FocusListener fl = new FocusListener() {
    
       @Override
       public void focusLost(FocusEvent arg0) {
          System.out.println("not typing....");
       }

       @Override
       public void focusGained(FocusEvent arg0) {
          if (txtComment.getText().equals(Constants.COMMENTS)) {
              txtComment.selectAll();
              txtComment.setForeground(Color.BLACK);
          }
       }
    };

    txtComment.addFocusListener(fl);
    JScrollPane jScrollPane1 = new JScrollPane();
    jScrollPane1.setViewportView(txtComment);

    return jScrollPane1;
}

Fixed size text area with scroll

JTextArea txtArea = new JTextArea();
txtArea.setColumns(50);
txtArea.setRows(2);
JScrollPane jScrollPane1 = new JScrollPane();
jScrollPane1.setViewportView(txtArea);

May 15, 2012

ArrayList and Array Conversions

ArrayList to Array Conversion :
List<T> list = new ArrayList<T>();
T[] array = list.toArray(new T[list.size()]);

Array to ArrayList Conversion : 
String[] array = {"a", "b", "c"};
List list = Arrays.asList(array);

Here the list is immutable. So if you want to be able to modify this list, create the list as below :
List list = new ArrayList(Arrays.asList(array));

February 5, 2012

No. of Spanning Trees for a Complete Graph with Constraints

For a graph with v vertices, the spanning tree contains (v-1) edges. Also the number of spanning trees can be given by vv-2 (Cayleys, 1889). Using this formula, lets determine a relationship between number of constraints and the number of spanning trees. Consider the following complete graph with 4 vertices. The colored edges will be the constraints (compulsory edges) we will consider.


According to Cayleys formula there has to be 44-2=16 spanning trees for the graph and each spanning tree contains (4-1) = 3 edges. The image below shows all the spanning trees.




According to the spanning trees, lets consider the number of spanning trees when constraints are present.


# ConstraintsConstraints# Spanning trees
0No constraint16
1Blue8
1Red8
1Green8
2Blue, Red3
2Blue, Green4
2Red, Green3
3Red, Green, Blue1

Conclusion:

According to the above numbers, although there is a relationship when one constraint is present (Vv-2/2), there is no such linear relationship when two or more constraints are present. If the two compulsory edges are adjacent then the number of spanning tree is lesser. When the number of constraints equals the number of edges in spanning tree, only one spanning tree exists.

January 20, 2012

Apps not working after google 2-step verification enabling

Pidgin was not working after I activated 2-step verification for my google account.

Solution : generate application specific password from https://accounts.google.com/IssuedAuthSubTokens#accesscodes

Backup to a .sql file and Restore from .sql database file (MySQL)


Backup

From above link :-
In your command, you can't have a space between -p and the password. Also, mysqldump has to be run on the command line, not in a mysql shell.

Try this on your command line

mysqldump -u username -ppassword databasename > backup.sql

Restore
  • Go to the folder with the backup.sql file from console
  • Start MySQL server
  • Type in source backup.sql
Reference

November 27, 2011

Fixing ConcurrentModificationException

Here I am discussing the instances where, iterating over a collection throws the ConcurrentModificationException. As mentioned in the API documentation, the reason here is, "it is not generally permissible for one thread to modify a Collection while another thread is iterating over it."

Following is a code segment which can throw this exception.
Iterator itr = purchased_products.iterator();
while (itr.hasNext()) {
  if (itr.next().getProduct_id() == product_id) {
    Purchase p = itr.next();
    purchased_products.remove(p);
  }
}

There are a number of different solutions provided in forums. Almost all of them are provided as tweaks to iteration which is already happening.If you need to keep using the iterator, solution here will not work.

This solution gives up the iterator. This is a simple code which we all have being through, but may have missed out for situation as this. I found this by referring the remove method in java.util.ArrayList.

for (int index = 0; index < size; index++)
  if (elementData[index] == null) {
  fastRemove(index);

As in the above code segment from remove(Object o) method, I too used a for loop to find the index of the item to be removed and then called upon the remove(int index) method to remove the element. This will not result in any such errors and is efficient than using iterator. But it will highly depend on your requirement.

So the revision for the above code segment given earlier would be as,
for (int index = 0; index < purchased_products.size(); index++) {
  if (product_id == purchased_products.get(index).getProduct_id()) {
    purchased_products.remove(index);
    index--;
  }
}

November 23, 2011

SqlFairy

"sqlfairy" is a pretty cool software which helps you in instantly visualizing any huge sql database, when all you have is it's schema.

You just have to do a quick installation with sudo apt-get install sqlfairy and you are all good to go.

Just refer some tutorials are available from :

November 21, 2011

Eclipse block comment problem

Eclipse by default formats the block comments when you save changes of a file. It is additional trouble when you need to uncomment.

To solve this problem,

  • Go to Windows->Preferences->Java->Code Style->Formatter->Edit->Comments 
  • Uncheck Enable block comment formatting
  • Click on Apply

November 20, 2011

Git Reference Sheet

Git Repository

It contains a set of 'commit objects' and 'heads' which are references to those commit objects. Commit objects are a set of files that reflect the state of project at any given time. They also include references to parent commit objects. Head is a reference to a commit object. a head has a name. By default, every repository has a head called "master". A repository can contain many heads but at any given time, one head is selected as the "current head" which is always named as "HEAD".

(In simple terms, HEAD is the current branch. But there are exceptions to this. Another definition is to refer to HEAD as a reference to the last commit in the current checked out branch.)

Delete

delete a remote branch
git push git@github.com:....git :mahee2

delete a branch

git branch -d mahee

Push

Push is done when you want to push the work you have done upstream for sharing purposes.

General command is git push [remote-name] [branch-name]

If you want to push your master branch to origin server, run git push origin master

example : git push git@github.com:charithsoori/Cart-beta.git mahee

The real scene behind above commands are a little explanatory. when you give a command as git push origin mahee it means, to take the local branch named 'mahee' and push it to the remote 'mahee' branch. git push origin mahee:mahee does the same. (Take my local 'mahee' and make it remote 'mahee'). If it is a different branch in remote (e.g. test) just give the command as git push origin mahee:test

if above push doesn't work due to not having a common ancestor and you get the following error :-

To git@github.com:.....git
! [rejected]        mahee -> mahee (non-fast-forward)
error: failed to push some refs to 'git@github.com:charithsoori/Cart-beta.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.


Do force push using
git push --force
or
git push git@github.com:.....git mahee --force (untested)

Actually force is not a very good option and is not encouraged. if a simple git pull and then pushing doesn't work, then you might have to use force.

Fetch

to pull any new work since clone or last fetch

git fetch origin

here "origin" refers to the remote repository when a clone is taken. The fetch will pull all the data from the remote project which isn't currently available. after this fetch, references to all branches are available and it is possible to merge branches or inspect them at will. Fetch only pulls data to local repository. It does not do any merging or modification to current work. Those should be done manually.

Pull

git pull

If a branch is set to track a remote branch, you can use pull to automatically pull and merge a remote branch to the current branch.

When to fetch and when to pull?

http://longair.net/blog/2009/04/16/git-fetch-and-merge/

Merge

git merge local mahee

merges local and mahee branches to local.

also, another method to do this merging is to checkout to local and then call on git merge mahee

Conflicting merge

git checkout branch1
git fetch origin branch2
git merge FETCH_HEAD

Auto-merging ......
CONFLICT (content): Merge conflict in ...........
Removing ..........
Auto-merging .........
CONFLICT (content): ..........
Automatic merge failed; fix conflicts and then commit the result.

when above output is received you can use a mergetool and perform merging in a little bit of a manual way.


git mergetool
merge tool candidates: opendiff kdiff3 tkdiff xxdiff meld tortoisemerge gvimdiff diffuse ecmerge p4merge araxis emerge vimdiff
Merging:
.........
.........

Normal merge conflict for '....':
{local}: modified
{remote}: modified
Hit return to start merge resolution tool (kdiff3):

Normal merge conflict for '.........':
{local}: modified
{remote}: modified
Hit return to start merge resolution tool (kdiff3):


References

September 11, 2011