Pages

2011-01-12

Generate a random number from a range


      public int getRandomNumberFromRange(int Min, int Max) {
            Random rn = new Random();
            int Delta = Max - Min + 1;
            int Offset = rn.nextInt() % Delta;
            int RandVal = Min + Offset;
            if (RandVal == 0)
                  return Min;
            return (RandVal > 0) ? RandVal : (RandVal * -1);
      }

That's it!

Create md5 hash of a string

     public String getMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

That's it!

Get Epoch from time stamp string



      public long getEpochFromBFTimeStamp(String TimeStamp) {
            try {
                  return (new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss'.0'")
                             .parse(TimeStamp).getTime() / 1000);
            } catch (ParseException e) {
                  return -1;
            }
      }


That's it!

Get UTC Time stamp from epoch

      String UTC_TIMEZONE = "UTC"; 
      String m_DateFormat = "yyyy-MM-dd HH:mm:ss";
      public String getUtcTimeStampFromEpoch(long epoch) {
           
             SimpleDateFormat df = new java.text.SimpleDateFormat(m_DateFormat);
             df.setTimeZone(TimeZone.getTimeZone(UTC_TIMEZONE));
             return     df.format(new java.util.Date(epoch * 1000));
      }



That's it!

Stop a Java thread properly

public class myThread extends Thread {
      // define a volatile Boolean as a trigger for thread stop
      private volatile boolean stop = false;

     
      @Override
      public void run() {
            while(!stop) {
                 
                  //do some reoccurring task here

                  ....
 

                  //wait
                  try {
                        new Thread();
                        Thread.sleep(1000);
                  } catch (InterruptedException e) {
                        stop = true;
                  }
            }
      }
      public void destroy() {
            stop=true;
            interrupt();
      }
}

Run the thread and stop it using the destroy() method.

That's it!

Pattern matching in Groovy script

def BlackListPattern ="I am a text to match"
pattern = ~BlackListPattern

matcher = pattern.matcher(LineToMatchAgainst);

if(matcher.getCount()>0) {
    // There's a match!!!
}

That's it!

Get last insert ID in Firebird

Firebird 2 introduces RETURNING clause for INSERT statements, so you can get the inserted value in a single go, just like with MySQL and some other database systems:

INSERT INTO t1 (...) values (...) returning pk;

PK
===========
32
 

That's it!

Run a script only on the last day of month

Sometimes you want to run a script as a cron job, though on the last day of the month, which is not supported by cron. So add the following code on the top of the script and set the cronjob to be run on daily basis:

#!/bin/bash

TODAY=`/bin/date +%d`
TOMORROW=`/bin/date +%d -d "1 day"`

# See if tomorrow's day is less than today's
if ! [ $TOMORROW -lt $TODAY ]

then
     # It's not the last day of the month, exiting...
     exit 0
fi

# Proceed with normal code to be run on the last day of the month here:
....


That's it!

Get previous month in Java Script

JavaScript - get previous month:

new Date(new Date().getFullYear(), new Date().getMonth() - 1, new Date().getDay()).toDateString()

That's it!

Run a scheduled job every 15 minutes in Windows

schtasks /Create /TN "Kill Pathetic Processes" /SC MINUTE /MO 15 /TR "C:\WIN\system32\cscript.exe C:\killEmAll.vbs"

Reformat Date column in Oracle SQL Query to a time stamp

 Reformat Date column in Oracle SQL Query to a time stamp

Assume you have a date column but you want to see the time as well, then you need to reformat the column:

Use instead SELECT SOME_DATE_COLUMN the following:

SELECT to_char(SOME_DATE_COLUMN,'DD/MM/YYYY HH24:MI:SS') as SOME_DATE_COLUMN_FORMATTED


That's it!

How to prevent a computer from running a user logon script