Javascript: Week Numbers in a Month

February 11, 2014 Leave a comment

Used to find the week numbers in a Month.

For example,

Jan, 2014 –  5-weeks (W), such as W1, W2, W3, W4, W5
Feb, 2014 –  5-weeks (W), such as W5, W6, W7, W8, W9
..
Nov, 2014 –  6-weeks(W), such as W44, W45, W46, W47, W48, W49

Example Program:

<script>

function weekNumbersRangeInMonth(month, year){

	year = year || new Date().getFullYear();
	var yearStart = new Date(year,0,1);	// 1st Jan of the Year

	var first_day_of_month = new Date(year, month, 1);
	var first_week_number = Math.ceil(( ( (first_day_of_month - yearStart) / 86400000) +yearStart.getDay()+ 1)/7);

	var last_day_of_month = new Date(year, month+1, 0);	// Last date of the Month
	var last_week_number = Math.ceil(( ( (last_day_of_month - yearStart) / 86400000) +yearStart.getDay()+ 1)/7);

	return  [first_week_number, last_week_number];
}

//
var month_jan = 0;	//Jan - Dec (0-11)
var year_2014 = 2014;

var week_no_arr = weekNumbersRangeInMonth(month_jan, year_2014);

for(var index = week_no_arr[0]; index<=week_no_arr[1]; index++){
	console.log("Week-" + index);
}
</script>

/*OUTPUT*/
Week-1
Week-2
Week-3
Week-4
Week-5 
Categories: JavaScript Tags: , , , , , , , , ,

Java: Generating Alphanumeric Random String

December 20, 2013 Leave a comment

Random String Generation, This may be use for the random password generation.

Long.toHexString(Double.doubleToLongBits(Math.random()));

Example Program:

public class RandomString {

	public static void main(String[] args) {

		for (int i = 0; i < 5; i++) {

			String randomString = Long.toHexString(Double.
					doubleToLongBits(Math.random()));
			System.out.println(randomString);
		}
	}
}

/*OUTPUT*/

3fe4d054c004b70b
3fe25d41e5136cd3
3fe1f0e3f337342b
3f95be11d3c95b40
3fe00a0282fa651b
Categories: Java Tags: , , , , , , ,

ORACLE : DROP ALL TABLES & SEQUENCE

December 17, 2013 Leave a comment

The below query is used to drop all the tables and sequence from the Oracle DB.

BEGIN

FOR c IN (SELECT table_name FROM user_tables) LOOP
EXECUTE IMMEDIATE (‘DROP TABLE ‘ || c.table_name || ‘ CASCADE CONSTRAINTS’);
END LOOP;

FOR s IN (SELECT sequence_name FROM user_sequences) LOOP
EXECUTE IMMEDIATE (‘DROP SEQUENCE ‘ || s.sequence_name);
END LOOP;

END;

Categories: DB Tags: , , , , , , , , ,

Java: Shortest Common Superstring Algorithm

May 18, 2013 Leave a comment

Shortest Common Superstring

The shortest common superstring of 2 strings S1 and S2 is a string S with the minimum number of characters which contains both S1 and S2 as a sequence of consecutive characters. For instance, the shortest common superstring of “alba” and “bacau” is “albacau”.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class ShortestCommonSuperstringAlgorithm {

	private void createSuperString(Set<String> subStrings) {
		int totalStrings = subStrings.size();
		String[] match = new String[totalStrings];
		int i = 0;

		for(String superString : subStrings) {

			Set<String> temp = new HashSet<String>(subStrings);
			String maxSuperString = superString;
			while(temp.size() > 1) {

				String subString = "";
				String nextMaxSuperString = maxSuperString;

				for(String nextString : temp) {

					if(!nextString.equals(nextMaxSuperString)) {

						String superTemp = getSuperString(maxSuperString, nextString);
						if (nextMaxSuperString.equals(maxSuperString) || nextMaxSuperString.length() > superTemp.length()) {
							nextMaxSuperString = superTemp;
							subString = nextString;
						}
					}
				}

				temp.remove(maxSuperString);
				temp.remove(subString);
				maxSuperString = nextMaxSuperString;
				temp.add(maxSuperString);
			}

			match[i] = maxSuperString;
			//System.out.println(match[i]);
			i++;
		}

		String bestAns = match[0];

		for(i = 1; i < match.length; i++) {
			if(bestAns.length() > match[i].length()) {
				bestAns = match[i];
			}
		}

		System.out.println("Shortest Common Super String => " + bestAns);
		System.out.println("With a Length of             => " + bestAns.length());

	}

	private String getSuperString(String superString, String someString) {
		String result = superString;

		int endIndex = someString.length() - 1;

		while(endIndex > 0 && !superString.endsWith(someString.substring(0, endIndex)))	{
			endIndex--;
		}

		if(endIndex > 0) {
			result += someString.substring(endIndex);
		}
		else {
			result += someString;
		}

		return result;
	}

	public static void main(String arg[]) {

		Set<String> fragments = new HashSet<String>();
		ShortestCommonSuperstringAlgorithm superStringCreator = new ShortestCommonSuperstringAlgorithm();

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input = "";
		int noOfFragments = 0;		// noOfFragments = m 

		// read input string, no. of fragments and their length

		try{
			System.out.println("Enter the no of Fragments : ");
			noOfFragments = Integer.parseInt(br.readLine());

			int size = 1;
			do{
				System.out.println(size + ". Fragment String : ");
				input = br.readLine();
				fragments.add(input);
				size++;
			}while(size<=noOfFragments);

		}catch(Exception ex){
			System.out.println("Please give correct Inputs.");
			ex.printStackTrace();
			return;
		}

		// find the shortest super string
		superStringCreator.createSuperString(fragments);
	}
}

/*Output:*/

Enter the no of Fragments :
5
1. Fragment String :
abdul
2. Fragment String :
apple
3. Fragment String :
mango
4. Fragment String :
orange
5. Fragment String :
banana
Shortest Common Super String => bananapplemangorangeabdul
With a Length of => 25

References:

https://github.com/rajanmalhotra/Code-Samples/blob/master/ComputationalBiology/ShortestCommonSuperstring.java

http://en.wikipedia.org/wiki/Shortest_common_supersequence

http://www8.cs.umu.se/kurser/TDBAfl/VT06/algorithms/BOOK/BOOK5/NODE209.HTM

PHP: String Replace All

March 14, 2013 Leave a comment

In PHP str_replace() is used to replace the strings, It also support to replace multiple string.

The below example code is used to replace the multiple string/char in a string.

In the code $delimiters array() is used to set the multiple delimiters.

$str_in = '[wel.co/me]';
$delimiters = array('[', ']', '.', '/');
$str_out = str_replace($delimiters, "", $str_in);
print($str_out);

// INPUT
 [wel.co/me]
// OUTPUT
 welcome

Referance:
http://php.net/manual/en/function.str-replace.php

Categories: PHP Tags: , , ,

J2EE: HttpSession getSession(boolean create)

October 16, 2012 Leave a comment

– Returns the current HttpSession associated with this request or, if there is no current Session and create is true, returns a new Session.

– If create is false and the request has no valid HttpSession, this method returns null.

– To make sure the session is properly maintained, you must call this method before the response is committed.

 

Parameters : true – to create a new Session for this request if necessary; false to return null if there’s no current Session

Returns : The HttpSession associated with this request or null if create is false and the request has no valid Session.

 

request.getSession(true) : This method will check whether Session already existed for the request or not. If it existed then it will return the already existed Session. If Session is not already existed for this request then this method will create a new Session and return that new Session.

request.getSession(false) : This method will check whether Session already existed for the request or not. If it existed then it will return the already existed Session. If Session is not already existed for this request then this method will return NULL, that means this method says that the request does not have a Session previously.

request.getSession() : Returns the current Session associated with this request, or if the request does not have a Session, creates one. Its by default work as request.getSession(true).

Why those 3 different methods are available means, It is not always a good idea to create a new Session. If we don’t want to create a new Session then we should use getSession(false).

Categories: Java

JSF: Injecting Managed Beans

July 20, 2012 Leave a comment

JSF managed beans don’t have a rich set of controls for dependency injection, but there is a basic mechanism—the @ManagedProperty annotation.
Suppose you have a UserBean with name user that contains information about the current user.

Here is how you can inject it into a field of another bean:

@ManagedBean
@SessionScoped
public class EditBean implements Serializable {
	
	@ManagedProperty(value="#{user}")
	private UserBean currentUser;
	
	public void setCurrentUser(UserBean newValue) { 
		currentUser = newValue; 
	}
}

Note that you annotate the currentUser field, but you must supply a setCurrentUser method.
When an EditBean instance is constructed, the value expression #{user} is evaluated, and the result is passed to the setCurrentUser method.

Categories: Java, JSF Tags: ,