Friday, December 23, 2011

JS: Word Count using Javascript

I just made a word counter using Javascript. Started it of as a jsfiddle attempt out of boredom. Thought it will help me count the words in assignments. blah. I have also made the source code available in github.

The counter is a simple javascript function, but have used jQuery selectors for simplicity and easiness. Initially my aim was to just get the count of words in the textarea by splitting the spaces and adding 1. But that approach is not accurate, when there are multiple spaces between words. So I used regular expression for replacing multiple spaces with a single space: /\s+/gi.

counter = function() {
    var value = $('#text').val();

    if (value.length == 0) {
        $('#wordCount').html(0);
        $('#totalChars').html(0);
        $('#charCount').html(0);
        $('#charCountNoSpace').html(0);
        return;
    }

    var regex = /\s+/gi;
    var wordCount = value.trim().replace(regex, ' ').split(' ').length;
    var totalChars = value.length;
    var charCount = value.trim().length;
    var charCountNoSpace = value.replace(regex, '').length;

    $('#wordCount').html(wordCount);
    $('#totalChars').html(totalChars);
    $('#charCount').html(charCount);
    $('#charCountNoSpace').html(charCountNoSpace);
};

The results are set in <span> elements as follows:
    0
    0
    0
    0

Now attach the counter function to change, keydown, keypress, keyup, blur and focus events of the textarea, to make sure the function called on every change.

$(document).ready(function() {    
    $('#text').change(counter);
    $('#text').keydown(counter);
    $('#text').keypress(counter);
    $('#text').keyup(counter);
    $('#text').blur(counter);
    $('#text').focus(counter);
});

This can be accessed in the following links

1. Word Counter using javascript

2. Source code for word counter using javascript

3. jsFiddle for word counter using javascript


Please report any bugs, issues or suggestions in github or just comment here.

Share it if you liked!

Wednesday, December 21, 2011

Oracle SQL to calculate value based on previous row value

Oracle database allows you to use SQL to calculate value based on the values of the previous row in a query result set. Use LAG and LEAD analytic function to calculate based on previous rows values.

Usage:
Both functions have the same usage, as shown below.
LAG (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)

Description:
value_expression - Can be a column or a built-in function, except for other analytic functions.
offset - The number of rows preceeding/following the current row, from which the data is to be retrieved. The default value is 1.
default - The value returned if the offset is outside the scope of the window. The default value is NULL.

Example:

select salary,lag(salary+300,1,0) over (order by salary) as new_sal,lag(salary+200,2,0) over (order by salary) as new_sal2 from employees;


   

Java: Marshalling in Java

Marshalling is a technique that can be easily understood and utilized efficiently. IT is the process of converting a POJO(Plain Old Java Object) in memory into a format that can be written to disk or send via network, usually in text formats like xml or json. The reverse of this technique is called unmarshalling.

Difference between Marshalling and Serialization:

Marshalling is similar to Serialization in practice but the difference is that, Marshalling also saves the code of an object in addition to its state.

Example

In the following example to explain marshalling, standard JAXB(Java Architecture for XML Binding) is used. For marshalling an object using JAXB, it must have annotation for the root element - @XmlRootElement
 
package blog.warfox.tutorials.marshalling;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * Student class for Marshalling demo example
 * @author warfox
 */
@XmlRootElement(name="student")

public class Student {

     private String name;
     private int rollNo;
     private double marks;
     private int rank;

     public String getName() {
          return this.name;
     }

     public void setName(String name) {
          this.name = name;
     }

     public int getRollNo() {
          return this.rollNo;
     }

     public void setRollNo(int rollNo) {
          this.rollNo = rollNo;
     }

     public double getMarks() {
          return this.marks;
     }

     public void setMarks(double marks) {
          this.marks = marks;
     }

     public int getRank() {
          return this.rank;
     }

     public void setRank(int rank) {
          this.rank = rank;
     }
}


Marshaller class which does the marshalling job

An instance of student is created and given for marshalling.
package blog.warfox.tutorials.marshalling;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class MyMarshaller {

     public static String marshall(Object object) throws JAXBException {

        JAXBContext context = JAXBContext.newInstance(object.getClass());
        
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        StringWriter writer = new StringWriter();
        m.marshal(object, writer);

        return writer.toString();
    }

    public static void main(String[] args) throws JAXBException {

        Student student = new Student();
        student.setName("Name");
        student.setRollNo(1);
        student.setMarks(99.99);
        student.setRank(1);
  
        System.out.println(marshall(student));
   }
}

Output:


    99.99
    Name
    1
    1



In the above example, JAXB has automatically copied the xml tags from the property names of Student class. We can set our own tag names by using JAXB's @XmlElement annotation on the access method as follows.

package blog.warfox.tutorials.marshalling;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Student class for Marshalling demo example
 * @author warfox
 *
 */
@XmlRootElement(name="student")
public class Student {

   private String name;

   private int rollNo;

   private double marks;

   private int rank;

   @XmlElement(name="student-name") 
   public String getName() {
      return this.name;
   }

   public void setName(String name) {
     this.name = name;
   }

   @XmlElement(name="student-rollno")
   public int getRollNo() {
     return this.rollNo;
   }

   public void setRollNo(int rollNo) {
     this.rollNo = rollNo;
   }

   @XmlElement(name="student-marks")
   public double getMarks() {
     return this.marks;
   }

   public void setMarks(double marks) {
     this.marks = marks;
   }

   @XmlElement(name="student-rank")
   public int getRank() {
     return this.rank;
   }

   public void setRank(int rank) {
    this.rank = rank;
   }
}

Output:

    99.99
    Name
    1
    1


Share this tutorial if it helped you.

Wednesday, September 7, 2011

Windows batch script to create directory auto file name DDMONYYYY with the help of javascript

In the previous post I had shown a windows batch script for creating directories with name of format DDMMYYYY. In this post I will show you how to create directories of format DDMONYYYY. I did a lot of research on web to figure this out. Here is the script, it looks a little bit complex.

:: Auto directory date batch (DDMONYYYY format)
:: In Win32, use WSH/JS to create directory in format DDMONYYYY,
:: using temporary javascript and batch files.
:: JS file is used for for getting MON
:: @author Deepu Mohan Puthrote www.deepumohan.com
@echo off
:: Declare function fnMonthLookUp
echo function fnMonthLookUp () {} > tmpDate.js
:: Create array on fnMonthLookUp
echo fnMonthLookUp['1'] = 'JAN'; >> tmpDate.js
echo fnMonthLookUp['2'] = 'FEB'; >> tmpDate.js
echo fnMonthLookUp['3'] = 'MAR'; >> tmpDate.js
echo fnMonthLookUp['4'] = 'APR'; >> tmpDate.js
echo fnMonthLookUp['5'] = 'MAY'; >> tmpDate.js
echo fnMonthLookUp['6'] = 'JUN'; >> tmpDate.js
echo fnMonthLookUp['7'] = 'JUL'; >> tmpDate.js
echo fnMonthLookUp['8'] = 'AUG'; >> tmpDate.js
echo fnMonthLookUp['9'] = 'SEP'; >> tmpDate.js
echo fnMonthLookUp['10'] = 'OCT'; >> tmpDate.js
echo fnMonthLookUp['11'] = 'NOV'; >> tmpDate.js
echo fnMonthLookUp['12'] = 'DEC'; >> tmpDate.js
:: Get Date
echo var D = new Date(); >> tmpDate.js
echo var dd = D.getDate(); >> tmpDate.js
echo var mm = D.getMonth()+1; >> tmpDate.js
echo var yyyy = D.getFullYear(); >> tmpDate.js
echo var mon = fnMonthLookUp[mm]; >> tmpDate.js
echo var date = dd + mon + yyyy; >> tmpDate.js
echo WScript.Echo('mkdir '+date); >>tmpDate.js

cscript //nologo tmpDate.js > tmpDate.bat
del tmpDate.js
call tmpDate
del tmpDate.bat


Copy and paste this code into a file with extension bat and save it into a path where you want to create the directory. Please do share your comments.

You can also download the batch file from here. You can safely download it, it is hosted is safe server of HostGator.

The above script creates a tempDate.js and tempDate.bat file. Windows can run javascript file using the command cscript. Output of this javascript file is taken to tmpDate.bat file.
A sample javascript file generated by the above code is given below.

function fnMonthLookUp () {} 
fnMonthLookUp['1'] = 'JAN'; 
fnMonthLookUp['2'] = 'FEB'; 
fnMonthLookUp['3'] = 'MAR'; 
fnMonthLookUp['4'] = 'APR'; 
fnMonthLookUp['5'] = 'MAY'; 
fnMonthLookUp['6'] = 'JUN'; 
fnMonthLookUp['7'] = 'JUL'; 
fnMonthLookUp['8'] = 'AUG'; 
fnMonthLookUp['9'] = 'SEP'; 
fnMonthLookUp['10'] = 'OCT'; 
fnMonthLookUp['11'] = 'NOV'; 
fnMonthLookUp['12'] = 'DEC'; 
var D = new Date(); 
var dd = D.getDate(); 
var mm = D.getMonth()+1; 
var yyyy = D.getFullYear(); 
var mon = fnMonthLookUp[mm]; 
var date = dd + mon + yyyy; 
WScript.Echo('mkdir '+date); 

As you can see a javascript array is created that holds index for each month. Next we create a new Date object using javascript function new Date(). From the date object get the date, month and year. Next we get the MON format of month from the javascript array already created. Now in date variable we have the date in the required format. WScript.Echo() command will give the output. And the output will be mkdir DDMONYYYY. This output is taken into the tmpDate.bat file. Then the tmpDate.js file is deleted and tmpDate.bat file is executed using the call command.

In the next post I shall give an improved version.

For those who are new to windows batch files, visit this site by Microsoft. You can also get these very good books from Amazon.com.
   

Windows batch script to create directory name DDMMYYYY

Many times I had to create directories with date as name for different purposes. I made this batch script to make that task easy. This is handy to keep all work of a particular day in its own folder. The following batch script will create directory of name format DDMMYYYY in the current path.

:: Auto directory date batch (MMDDYYYY format)
:: First parses month, day, and year into mm , dd, yyyy formats and then combines to be DDMMYYYY
:: Setups %date% variable
:: @author Deepu Mohan Puthrote www.deepumohan.com
@echo off
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%dd%%mm%%yyyy%
echo New folder name %date%
MKDIR %date%

Copy and paste this code into a file with extension bat and save it into a path where you want to create the directory. Double click on the batch file to create the current day's directory.

You can also download the batch file from here. You can safely download it, it is hosted in safe server of HostGator.
In the next post I will post the batch script for creating directory names with DDMONYYYY format. It will be pretty advanced which uses temporary javascipt and batch file. See the post here.

For those who are new to windows batch files, visit this site by Microsoft. You can also get these very good books from Amazon.com.

   

Sunday, August 21, 2011

Cancel html form submission when using jQuery.submit()

Most web developers might have come across this scenario - cancel the form submission after it is fired. This happens when form validation is fired on the submit event of form element. You may have to cancel the submission based on the validation.

This post is on how to cancel an html form submission when using jQuery. The following 4 code snippets does the same the job. This can be used to prevent submit event being fired based on some validation.

1. Cancel using event.preventDefault() method.
$('form').submit(submit_handler1);

function submit_handler1(event) {
  event.preventDefault();
}

2. Cancel by returning false from the submit handler.
$('form').submit(submit_handler2);

function submit_handler2() {
 return false;
}

3. Cancel by returning false from the submit handler.
$('form').submit(submit_handler3);

submit_handler3 = function () {
 return false;
}

4. Cancel by returning false from the submit handler.
$('form').submit(submit_handler4);

$.submit_handler4 = function () {
 return false;
}

In these examples I have used a submit handler function. It is always better to write submit handler function separately, for code maintainability. Here examples 2, 3 and 4 are same only difference is in the way submit handler function is attached to the submit event.

To learn/improve jQuery skills, buy one of these book from Amazon.com.

Monday, April 18, 2011

How to get html color code from an image using MS Paint

This is a quick tutorial for getting html color codes using MS Paint. The idea is to get RGB codes from MS Paint and then convert the RGB color code values to hexadecimal values. This tutorial is best suited for Windows 7 operators.

Follow the instructions:

1. Open the image in ms paint.



2. Use color picker to select the color on image for which you want the html code for.
    (Circled in red)

3. Now that I have selected blue color note that 'Color 1' changes to blue. You should make sure the color you have selected and that shown in 'Color 1' are same.


4. Now we are ready to get the RGB code of the selected color.
    Click on the 'Edit Color's button to get the color palette.



5. That's it! Now we got the RGB values of the selected color.
   RGB(14,149,255) = the blue color we want.

6. To get the html color code convert each value to its hexadecimal notation. For those lazy people like me there are a lot of RGB to HTML converters available. The first result I got from Google is http://easycalculation.com/rgb-coder.php

7. Now for those who really want to convert RGB to html color code on their on, read the rest. Open Calculator. (Windows + R, calc)

8. Press Alt+3 or select 'Programmer' mode.

9. Now calculator must have expanded with some extra features. Radio button for 'Dec' is selected by default.


10. Type in each of the RGB values and select Hex for converting to hexadecimal value.
  • 14 will be converted to E
  • 149 will be converted to 95
  • 255 will be converted to FF
So RGB(14,149,255) ---> #0E95FF.
Note that html color code is either 6 digits or 3 digits. So if you get single digit hexadecimal just add a zero on left.

Fiddle here: http://jsfiddle.net/deepumohanp/9AA33/

Share this tutorial if it helped.
And feel free to tell your opinions in comments. I read them to improve.

Related Posts Plugin for WordPress, Blogger...