How to remove Whitespace between String - Java

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 2 / 10)
Loading ... Loading ...

Today i play around with some funny and simple thing in Java, frankly i really do not know about it. I created following code like below

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll(" ", " AND ");			   
}

What i trying to do is remove all whitespace between a string. for example, user key in “Hello Google”, it will replace as “Hello AND Google”, ya this is correct if user only enter one space between word.

"Hello Google"  ---> "Hello AND Google"

But how about user key in many space in between? Haha.. For example

"Hello           Google"  ---> "Hello AND AND AND AND AND Google"

Above is not what i want, should i replace it as below?

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll(" ", " AND ");
     sText= sText.replaceAll("  ", " AND ");	
     sText= sText.replaceAll("   ", " AND ");	
     sText= sText.replaceAll("    ", " AND ");	
     sText= sText.replaceAll("     ", " AND ");				   
}

ya we can replace as many as we like, but this is not so effective and dynamic enough. Finally Regular Expression come to place and solve it.

if(StringUtils.hasLength(sText)
 {
     sText= sText.replaceAll("\\s+", " AND ");		   
}

Great , exactly what i want, Regular Expression ROCK!!!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • SphereIt
  • Reddit
  • Google
  • YahooMyWeb
  • Technorati
  • Spurl
  • Sphinn
  • Mixx
  • connotea
  • BlinkList

JavaScript Call Funtion After Page Load

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 2 / 10)
Loading ... Loading ...

Usually we can call a function during page on load with following two methods.

<body onload="happycode() ">

or

<script>
window.onload=happycode 
</script>

But how we can call a javascript function after a page load? I solved it by using a very simple method, it did exactly what i want and call after page and content loaded. Just add an onload function at the end of the body.

<html>
....
<body>
...
 
<script>
//call after page loaded
window.onload=happycode  
</script>
</body>
</html>
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • SphereIt
  • Reddit
  • Google
  • YahooMyWeb
  • Technorati
  • Spurl
  • Sphinn
  • Mixx
  • connotea
  • BlinkList

Javascript Highlight search result

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 1 / 10)
Loading ... Loading ...

Tedpavlic created a very easy to understand and useful client site javascript highlight.

Here i briefly describe how to use it, please visit website above for details

1)Include following code

<style>
<!-- 
    SPAN.searchword { background-color:yellow }
    // -->
</style>
<script src="http://links.tedpavlic.com/js/searchhi_slim.js" 
type="text/javascript" language="JavaScript"></script>

2) Call it localSearchHighlight(’searchstr’)

<script language="javascript">
window.onload=localSearchHighlight('search search')
</script>

3)Result

4)Simple, Done. Thanks Tedpavlic provided a good javascript highlight code.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • SphereIt
  • Reddit
  • Google
  • YahooMyWeb
  • Technorati
  • Spurl
  • Sphinn
  • Mixx
  • connotea
  • BlinkList

Java Decompiler Plugin For Eclipse

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 2 / 10)
Loading ... Loading ...

After integrated Java Decompiler (Jad) into Eclipse, when we click any java class file in eclipse, it will automatically decompile for us. This is very convenient and useful.

How to Integrated Java Decompiler with Eclipse

1) Download Jab and extract it
http://www.kpdus.com/jad.html

2) Download Jabclipse (net.sf.jadclipse_x.x.x.jar)
http://sourceforge.net/projects/jadclipse/

3) Copy Jabclipse(jadclipse_x.x.x.jar) to eclipse plugin folder

4) Restart Eclipse

5) Set Jadclipse Preference, Window –> Preference –> Java –> Jadclipse
Key in Jad path in Path to Decompiler field

6) Done, now we select any java class file, it will auto decompile it

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • SphereIt
  • Reddit
  • Google
  • YahooMyWeb
  • Technorati
  • Spurl
  • Sphinn
  • Mixx
  • connotea
  • BlinkList

How to copy Entire Directory in Linux

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 1 / 10)
Loading ... Loading ...

Command is simple, here i provide two samples to show how to copy entire directory in linux.

cp -r sourcedir targetdir

for instance,

1) Copy anything from current directory to /usr/local/download

cp -r * /usr/local/download

2) Copy whole directory (include content) /usr/local/fromdownload to target /usr/local/download

cp -r  /usr/local/fromdownload  /usr/local/download
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • SphereIt
  • Reddit
  • Google
  • YahooMyWeb
  • Technorati
  • Spurl
  • Sphinn
  • Mixx
  • connotea
  • BlinkList

How to building PostgreSQL libpq Programs

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 4 / 10)
Loading ... Loading ...

Create and compile a program with PostgreSQL libpq is not so straightforward. I created a sample program like “testlibpq.c” in PostgreSQL documentation to test it.

When i compile it, i hit following error

libpq-fe.h: No such file or directory
PGconn’ undeclared (first use in this function)

1
2
3
4
5
6
7
8
9
10
11
12
13
mkyong@mkyong-desktop:~/Desktop/index$ gcc -o test.o test.c
test.c:8:22: error: libpq-fe.h: No such file or directory
test.c:11: error: expected ‘)’ before ‘*’ token
test.c: In function ‘main’:
test.c:21: error: ‘PGconn’ undeclared (first use in this function)
test.c:21: error: (Each undeclared identifier is reported only once
test.c:21: error: for each function it appears in.)
test.c:21: error: ‘conn’ undeclared (first use in this function)
test.c:22: error: ‘PGresult’ undeclared (first use in this function)
test.c:22: error: ‘res’ undeclared (first use in this function)
test.c:41: error: ‘CONNECTION_OK’ undeclared (first use in this function)
test.c:57: error: ‘PGRES_COMMAND_OK’ undeclared (first use in this function)
test.c:83: error: ‘PGRES_TUPLES_OK’ undeclared (first use in this function)

It do need to include -I/usr/include/postgresql/ in order to compile it, please check your database or Linux administrator, or just type “pg_config –includedir” to find out where is PostgreSQL include file located.

However I still hit error like follwing

undefined reference to `PQfinish’
undefined reference to `PQconnectdb’

1
2
3
4
5
6
7
8
9
10
11
12
13
mkyong@mkyong-desktop:~/Desktop/index$ gcc -I/usr/include/postgresql/  -o test.o test.c
/tmp/ccoOJzAT.o: In function `exit_nicely':
test.c:(.text+0xd): undefined reference to `PQfinish'
/tmp/ccoOJzAT.o: In function `main':
test.c:(.text+0x57): undefined reference to `PQconnectdb'
test.c:(.text+0x65): undefined reference to `PQstatus'
test.c:(.text+0x74): undefined reference to `PQerrorMessage'
test.c:(.text+0xac): undefined reference to `PQexec'
test.c:(.text+0xba): undefined reference to `PQresultStatus'
test.c:(.text+0xca): undefined reference to `PQerrorMessage'
test.c:(.text+0xef): undefined reference to `PQclear'
test.c:(.text+0x105): undefined reference to `PQclear'
test.c:(.text+0x118): undefined reference to `PQexec'

Library is missing. Include PostgreSQL library pathwith -L/usr/lib/postgresql/8.3/lib/, this all PostgreSQL configuration information can get it from “pg_config”.

But I still hit the same error again

undefined reference to `PQfinish’
undefined reference to `PQconnectdb”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mkyong@mkyong-desktop:~/Desktop/index$ gcc -I/usr/include/postgresql/ -L/usr/lib/postgresql/8.3/lib/ -o test.o test.c
/tmp/ccgWnRJg.o: In function `exit_nicely':
test.c:(.text+0xd): undefined reference to `PQfinish'
/tmp/ccgWnRJg.o: In function `main':
test.c:(.text+0x57): undefined reference to `PQconnectdb'
test.c:(.text+0x65): undefined reference to `PQstatus'
test.c:(.text+0x74): undefined reference to `PQerrorMessage'
test.c:(.text+0xac): undefined reference to `PQexec'
test.c:(.text+0xba): undefined reference to `PQresultStatus'
test.c:(.text+0xca): undefined reference to `PQerrorMessage'
test.c:(.text+0xef): undefined reference to `PQclear'
test.c:(.text+0x105): undefined reference to `PQclear'
test.c:(.text+0x118): undefined reference to `PQexec'
test.c:(.text+0x126): undefined reference to `PQresultStatus'
test.c:(.text+0x136): undefined reference to `PQerrorMessage'
test.c:(.text+0x15b): undefined reference to `PQclear'
test.c:(.text+0x171): undefined reference to `PQclear'

It do need to specified exactly library with -lpq to include libpg library, correct command is like following

gcc -I/usr/include/postgresql/ -L/usr/lib/postgresql/8.3/lib/ -lpq -o test.o test.c

Done, compile without error.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • SphereIt
  • Reddit
  • Google
  • YahooMyWeb
  • Technorati
  • Spurl
  • Sphinn
  • Mixx
  • connotea
  • BlinkList

Calculate program execute time / time elapsed in C

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 4 / 10)
Loading ... Loading ...

Here i shared a simple method to calculate program execute time or time elapsed in C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*calculate program execute time */
#include <time.h>
#include <stdio.h>
 
int main(int argc, char *argv[]) {
   time_t start, stop;
   clock_t ticks; long count;
 
   time(&start);
   // Do stuff
   int i=0;
 
   while(i<50000)
   {
	printf("Work work %d\n", i);
        i++;
        ticks = clock();
 
   }
 
   time(&stop);
 
   printf("Used %0.2f seconds of CPU time. \n", (double)ticks/CLOCKS_PER_SEC);
   printf("Finished in about %.0f seconds. \n", difftime(stop, start));
   return 0;
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • SphereIt
  • Reddit
  • Google
  • YahooMyWeb
  • Technorati
  • Spurl
  • Sphinn
  • Mixx
  • connotea
  • BlinkList

Open Browser in Java windows or Linux

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 6 / 10)
Loading ... Loading ...

Today i found a very useful java code, it can open browser from java application in windows or Linux.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.mkyong;
 
public class StartBrowser {
 
	public static void main(String args[])
	{
		String url = "http://www.google.com";
		String os = System.getProperty("os.name").toLowerCase();
	    Runtime rt = Runtime.getRuntime();
	    try{
	        if (os.indexOf( "win" ) >= 0) {
	        	// this doesn't support showing urls in the form of "page.html#nameLink" 
	            rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
	        } else if (os.indexOf( "mac" ) >= 0) {
	            rt.exec( "open " + url);
	        } else if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0) {
	        	// Do a best guess on unix until we get a platform independent way
	        	// Build a list of browsers to try, in this order.
	        	String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
	        			"netscape","opera","links","lynx"};
 
	        	// Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
	        	StringBuffer cmd = new StringBuffer();
	        	for (int i=0; i<browsers.length; i++)
	        		cmd.append( (i==0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
 
	        	rt.exec(new String[] { "sh", "-c", cmd.toString() });
	        } else {
	        	return;
	        }
	    }catch (Exception e){
	    	return;
	    }
	    return;	
 
	}
 
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • SphereIt
  • Reddit
  • Google
  • YahooMyWeb
  • Technorati
  • Spurl
  • Sphinn
  • Mixx
  • connotea
  • BlinkList

How to handle unknow size user input in C

1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (1 votes, average: 5 / 10)
Loading ... Loading ...

Here i shared two basic methods to handle user input in C.

1) scanf - this method is easy get attack by buffer overflow, try input some characters more than what you declare to experience buffer overflow

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    char bStr[80];
    printf("\nEnter a very very very long String value:");
    scanf("%s", bStr);
    printf("\nLong String value:%s \n\n",bStr);
    return 0;
}

2) fgets - this method can protect buffer overflow by limit the character user input

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    char bStr[80];
    printf("\nEnter a very very very long String value:");
    fgets ( bStr, 80, stdin );    
    printf("\nLong String value:%s \n\n",bStr);
    return 0;
}

However above two methods only can handle normal user input, how about i want to handle user input with 1000 or even more characters? Yes we can declare like “char bStr[1000]” or even more larger size, but this is not so dynamic and flexible enough. However we can use dynamic memory management in C to solve above problem, we can dynamic increase memory size with realloc() function.

First let see what above scanf() buffer overflow look like, just input more than what you declare and see the result below.

Buffer Overflow is not what we want. Here i share a dynamic memory allocation(realloc) in C to handle user input in unknown size.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    unsigned int len_max = 128;
    unsigned int current_size = 0;
 
    char *pStr = malloc(len_max);
    current_size = len_max;
 
    printf("\nEnter a very very very long String value:");
 
    if(pStr != NULL)
    {
	int c = EOF;
	unsigned int i =0;
        //accept user input until hit enter or end of file
	while (( c = getchar() ) != '\n' && c != EOF)
	{
		pStr[i++]=(char)c;
 
		//if i reached maximize size then realloc size
		if(i == current_size)
		{
                        current_size = i+len_max;
			pStr = realloc(pStr, current_size);
		}
	}
 
	pStr[i] = '\0'