r00t.gr

Programming and more

How to find how many days are there between dates

I was writting a car rental application for some customer, when i came across this problem. Fortunatelly I found the  solution easier that I thought. You have to love google!

So here is the solution: Takes into account leap years and it’s tested and it works great.

 

 

	function dateDiff($start, $end) 
	{
		$start_ts = strtotime($start);
		$end_ts = strtotime($end);
		$diff = $end_ts - $start_ts;
		$start_array = explode("-", $start);
		$start_year = $start_array[0];
 
		$end_array = explode("-", $end);
		$end_year = $end_array[0];
 
		$years = $end_year-$start_year;
		if (($years%4) == 0) 
		{
			$extra_days = ((($end_year-$start_year)/4)-1);
		} 
		else 
		{
			$extra_days = ((($end_year-$start_year)/4));
		}
		$extra_days = round($extra_days);
 
		return round($diff / 86400)+$extra_days+1;
	}
echo dateDiff("2006-04-05", "2006-04-01");

The format of the dates is: yyyy-mm-dd

Thanks

Google Tasks Desktop Application

http://www.jashsayani.com/my-softwares/ go here and click on google tasks and install the application. This program uses adobe air.

How to recursive browse a directory with java

import java.io.*;
import java.util.*;
 
class aloxa
{
	public static void main(String args[])
	{
		try
		{
			traverse(new File("thomson"));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	static public void traverse( File file )
	{
	   // Print the name of the entry
	   System.out.println( file ) ;
	   // Check if it is a directory
	   if( file.isDirectory() )
	   {
	      // Get a list of all the entries in the directory
			String entries[] = file.list() ;
			// Ensure that the list is not null
			if( entries != null )
			{
				// Loop over all the entries
				for( String entry : entries )
				{
					// Recursive call to traverse
					traverse( new File(file,entry) ) ;
				}
			}
		}
	}
}

How to disable fn lock on acer gateway NV55S and other laptops

I have a new laptop, Acer Cateway NV55S. Great laptop, but I had one problem. I couldn’t use the F keys without pressing the FN button. This was very irritating because I use F-Keys a lot.

First round of googling revealed nothing, then I contacted gateway support, (that was no help either).

Then I found this link: http://h10025.www1.hp.com/ewfrf/wc/document?cc=dk&lc=da&dlc=da&docname=c02035108

The process to do this is a little different in Acer gateway, but the option is there. You have to change some values in the computer BIOS (Reboot, F2 to get int BIOS, Action keys mode).

Some other knowledge I gathered googling:

Disable FN LOCK for all laptops:

Dell = Fn + F4
Compaq = Fn + ScrLk
Lenovo = FN + Num Lock
IBM Thinkpad – Shift + Scroll Lock Num

Others:
Fn + F11
Ctrl + F11
Fn + Num Lock
Fn + Shift + Num Lock

Simple way to get md5 from string in java

You will see a lot of crazy shit when searching for this. I you want something simple, get this function to get md5 from string in java:

	static String md5(String text)
	{
		try
		{
			MessageDigest m=MessageDigest.getInstance("MD5");
			m.update(text.getBytes(),0,text.length());
			return new BigInteger(1,m.digest()).toString(16);			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return "";		
	}

Thanks for visiting

How to log cron crontab output in linux

Question: I created a backup.sh shell script and added it to my crontab to execute it daily. How do I verify whether the backup cron script job ran successfully? Also, I have several echo statements inside my backup.sh shell script. How do I save the output of my script to a log file when it is executed as a cron job?

Answer: Let us say that you’ve added the backup.sh to your crontab as shown below to execute it at midnight every day.

$ crontab -e
59 23 * * * /home/john/bin/backup.sh

To verify whether the this job got executed successfully or not, check the /var/log/cron file, which contains information about all the cron jobs that gets executed in your system. As you see from the following output, john’s cron job got executed succesfully.

$ tail /var/log/cron
Oct  8 22:00:00 dev-db crond[18340]: (root) CMD (/bin/sh /home/root/bin/system_check &)
Oct  8 23:00:00 dev-db crond[20348]: (oracle) CMD (/bin/sh /home/oracle/bin/cleanup.sh &)
Oct  8 23:59:00 dev-db crond[20399]: (john) CMD (/bin/sh /home/john/bin/backup.sh &)

Cron log contains the following information:

Timestamp – The date and time when the cron job was executed
Hostname – The hostname of the server (For example, dev-db)
The cron deamon name and the PID. For example, crond[20399]
Username – The username under which this cron job got executed. For example, john.
CMD – Anything following this is the real command that got executed at that time.

If there are any echo statements inside the backup.sh, you might want to log those into a file. In general, if the backup.sh cron script throws any output (including errors), you might want to log those to a log file. To do this, modify the crontab entry and add the output and error redirection as shown below.

$ crontab -e
59 23 * * * /home/john/bin/backup.sh > /home/john/logs/backup.log 2>&1

In the above:

> /home/john/logs/backup.log indicates that the standard output of the backup.sh script will be redirected to the backup.log file.
2>&1 indicates that the standard error (2>) is redirected to the same file descriptor that is pointed by standard output (&1).
So, both standard output and error will be redirected to /home/john/logs/backup.log

Create Random String in java.

Useful in many many cases.
Here is the code:

import java.security.SecureRandom;
import java.math.BigInteger;
 
final class randomstring
{
 
  static private SecureRandom rnd= new SecureRandom();
 
  static public String nextRandomString(int size)
  {
    return new BigInteger(130, rnd).toString(size);
  }
  public static void main(String args[])
  {
    System.out.println(nextRandomString(15));
 
    System.out.println(nextRandomString(32));
  }
 
}

Ban ip with iptables plus bash script

To ban an ip with iptables:

iptables -A INPUT -s 195.195.195.195 -j DROP
service iptables save
service iptables restart

if you want to do that with bash here is a simple script that asks you for theip to ban then bans it:

iptables -A INPUT -s 195.195.195.195 -j DROP
echo -n "Enter the ip [ENTER]: "
read ip
iptables -A INPUT -s $ip -j DROP
service iptables save
service iptables restart

Thanks for visiting.

How to Stop URLConnection from following redirection (Prevent Location: header).

This was very hard for me to find in Google. I almost spend 5 minutes instead of the usual 32 seconds to find the answer.

So here it is:

 

// Disable automatic redirects for all HTTP requests
HttpURLConnection.setFollowRedirects(false);
 
// Disable automatic redirects for a particular connection
try {
    // Create a URLConnection object for a URL
    URL url = new URL("http://hostname:80");
    URLConnection conn = url.openConnection();
 
    // Disable automatic redirects just for this connection
    HttpURLConnection httpConn = (HttpURLConnection)conn;
    httpConn.setInstanceFollowRedirects(false);
 
    // Send the request to the server
    conn.connect();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

How to build and sent a POST request with java

This is very useful at many times, if you want to emulate a post request from a browser. I use it all the time, it’s very useful, so i put it here for you to see:

 

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
 
    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
 
    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

If you don’t know exactly what to post, you can use live http headers addon for firefox. Just install the addon, open it (tools menu), fill the form you want to emulate, then click submit on the website you want to emulate the post

 

post request with java

If you click copy this is what you get: email=contact%email.gr&password=password&login=Sign+In

This is all the post data you need. Just delete:

String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8"); data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

And put:

String data = "email=contact%email.gr&password=password&login=Sign+In";