Tuesday, November 26, 2013

Query to find and replace a specific word in SQL Database without affecting the data along with it

update table
set column_name = replace(column_name,'TextToBeReplaced','TextToBeReplacedBy')

Mysqladmin Commands in Linux

mysqladmin is a command-line utility the comes with MySQL server and it is used by Database Administrators to perform some basic MySQL tasks easily such as setting root password, changing root password, monitoring mysql processes, reloading privileges, checking server status etc.

1.To set MySQL Root password:
# mysqladmin -u root password YOURNEWPASSWORD
 
2.to Change MySQL Root password?
#mysqladmin -u root -p123456 password 'xyz123'
 
3.To check MySQL Server is running?
# mysqladmin -u root -p ping
 
4.To Check which MySQL version I am running?
# mysqladmin -u root -p version
 
5.To Find out current Status of MySQL server?
#mysqladmin -u root -ptmppassword status 

6.To check status of all MySQL Server Variable’s and value’s?
# mysqladmin -u root -p extended-status
 
7.To see all MySQL server Variables and Values?
# mysqladmin  -u root -p variables
 
8.To check all the running Process of MySQL server?
#mysqladmin -u root -p processlist
 
9.To create a Database in MySQL server?
# mysqladmin -u root -p create databasename
 
10.To drop a Database in MySQL server?
# mysqladmin -u root -p drop databasename
 
11.To reload/refresh MySQL Privileges?
# mysqladmin -u root -p reload;
# mysqladmin -u root -p refresh;
 
The reload command tells the server to reload the grant tables. The refresh command
 flushes all tables and reopens the log files.
 
12.To shutdown MySQL server Safely?
#mysqladmin -u root -p shutdown 

other commands:
# /etc/init.d/mysqld stop
# /etc/init.d/mysqld start
 
13.Some useful MySQL Flush commands
 
# mysqladmin -u root -p flush-hosts
# mysqladmin -u root -p flush-tables
# mysqladmin -u root -p flush-threads
# mysqladmin -u root -p flush-logs
# mysqladmin -u root -p flush-privileges
# mysqladmin -u root -p flush-status
 
 
14.To kill Sleeping MySQL Client Process?
to see: # mysqladmin -u root -p processlist
 
Run the following id with process id: 
# mysqladmin -u root -p kill 5 

15.To run multiple mysqladmin commands together?
#mysqladmin  -u root -p processlist status version 

16.To Connect remote mysql server:
# mysqladmin  -h 172.16.25.126 -u root -p
 
 
17.To execute command on remote MySQL server:
# mysqladmin  -h 172.16.25.126 -u root -p status
 
 
18.To start/stop MySQL replication on a slave server?
# mysqladmin  -u root -p start-slave
# mysqladmin  -u root -p stop-slave
 
19.To store MySQL server Debug Information to logs?
# mysqladmin  -u root -p debug
 
20.To view mysqladmin options and usage:
# mysqladmin --help 
 
 
 
Source 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Thursday, November 21, 2013

To get autorefresh resultset of Sql query

The following query does not full fill the requirements as it does not auto refresh 
the results. Each time it updates the screen with the new resultset.
 
 
 
 
SELECT GETDATE()              --your query to run
raiserror('',0,1) with nowait --to flush the buffer
waitfor delay '00:00:10'      --pause for 10 seconds
GO 5                          --loop 5 times
 
 
The above query will run  5 times, pausing for 10 seconds between each run.

Copy an existing MySQL table to a new table

To make a copy of the table tableOriginal which is in a different database called production into a new table called tableDuplicate in the currently selected database, use these two commands:

CREATE TABLE tableDuplicate LIKE production.tableOriginal ; 

INSERT into tableDuplicate SELECT * FROM production.tableOriginal ;

The first command creates the new table recipes_new by duplicating the structure of the existing table. The second command copies the data from old to new.

Tuesday, November 19, 2013

Set Java_Home and Path System variable in Windows

Stage 1. Locate the JRE Installation Directory

If you already know the installation path for the Java Runtime Environment, go to Stage 2 below. Otherwise, find the installation path by following these instructions:
  1. If you didn't change the installation path for the Java Runtime Environment during installation, it will be in a directory under C:\Program Files\Java. Using Explorer, open the directory C:\Program Files\Java.
  2. Inside that path will be one or more subdirectories such as C:\Program Files\Java\jre6

Stage 2. Set the JAVA_HOME Variable

Once you have identified the JRE installation path:
  1. Right-click the My Computer icon on your desktop and select Properties.
  2. Click the Advanced tab.
  3. Click the Environment Variables button.
  4. Under System Variables, click New.
  5. Enter the variable name as JAVA_HOME.
  6. Enter the variable value as the installation path for the Java Development Kit.
    • If your Java installation directory has a space in its path name, you should use the shortened path name (e.g. C:\Progra~1\Java\jre6) in the environment variable instead.
      Icon
      Note for Windows users on 64-bit systems
      Progra~1 = 'Program Files'Progra~2 = 'Program Files(x86)'
  7. Click OK.
  8. Click Apply Changes.
  9. Close any command window which was open before you made these changes, and open a new command window. There is no way to reload environment variables from an active command prompt. If the changes do not take effect even after reopening the command window, restart Windows.




You can run Java applications just fine without setting the PATH environment variable. Or, you can optionally set it as a convenience.
Set the PATH environment variable if you want to be able to conveniently run the executables (javac.exe, java.exe, javadoc.exe, and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:
C:\Java\jdk1.7.0\bin\javac MyClass.java
The PATH environment variable is a series of directories separated by semicolons (;). Microsoft Windows looks for programs in the PATH directories in order, from left to right. You should have only one bin directory for the JDK in the path at a time (those following the first are ignored), so if one is already present, you can update that particular entry.
The following is an example of a PATH environment variable:
C:\Java\jdk1.7.0\bin;C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem
It is useful to set the PATH environment variable permanently so it will persist after rebooting. To make a permanent change to the PATH variable, use the System icon in the Control Panel. The precise procedure varies depending on the version of Windows:
Windows XP
  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Windows Vista:
  1. From the desktop, right click the My Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced tab (Advanced system settings link in Vista).
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Windows 7:
  1. From the desktop, right click the Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced system settings link.
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.

For Details

Friday, October 25, 2013

Rank of languages

 
Classification of programming languages ​​for "August 2013" according  TIOBE


Tuesday, October 22, 2013

Making a JSF/Primefaces Field required based on condition

JSF required attribute based on condition for jsf or primeface component required="true" then

required="#{not empty bean.value1}" />
or
 required="#{bean.value1 != ' '}" />
or
 required="#{bean.value1 = = ' '}" />
or
if bean.vale is boolean

 required="#{bean.value3?true:false}" />
conditinal expression you can use

MySQL stored procedure vs function

The most general difference between procedures and functions is that they are invoked differently and for different purposes:
  1. A procedure does not return a value. Instead, it is invoked with a CALL statement to perform an operation such as modifying a table or processing retrieved records.
  2. A function is invoked within an expression and returns a single value directly to the caller to be used in the expression.
  3. You cannot invoke a function with a CALL statement, nor can you invoke a procedure in an expression.
You can't mix in stored procedures with ordinary SQL, whilst with stored function you can.
e.g. SELECT get_foo(myColumn) FROM mytable is not valid if get_foo() is a procedure, but you can do that if get_foo() is a function. The price is that functions have more limitations than a procedure.
 
Syntax for routine creation differs somewhat for procedures and functions:
  1. Procedure parameters can be defined as input-only, output-only, or both. This means that a procedure can pass values back to the caller by using output parameters. These values can be accessed in statements that follow the CALL statement. Functions have only input parameters. As a result, although both procedures and functions can have parameters, procedure parameter declaration differs from that for functions.
  2. Functions return value, so there must be a RETURNS clause in a function definition to indicate the data type of the return value. Also, there must be at least one RETURN statement within the function body to return a value to the caller. RETURNS and RETURN do not appear in procedure definitions.
    • To invoke a stored procedure, use the CALL statement. To invoke a stored function, refer to it in an expression. The function returns a value during expression evaluation.
    • A procedure is invoked using a CALL statement, and can only pass back values using output variables. A function can be called from inside a statement just like any other function (that is, by invoking the function's name), and can return a scalar value.
    • Specifying a parameter as IN, OUT, or INOUT is valid only for a PROCEDURE. For a FUNCTION, parameters are always regarded as IN parameters.
    If no keyword is given before a parameter name, it is an IN parameter by default. Parameters for stored functions are not preceded by IN, OUT, or INOUT. All function parameters are treated as IN parameters.

    To define a stored procedure or function, use CREATE PROCEDURE or CREATE FUNCTION respectively:
    CREATE PROCEDURE proc_name ([parameters])
     [characteristics]
     routine_body
    
    
    CREATE FUNCTION func_name ([parameters])
     RETURNS data_type       // diffrent
     [characteristics]
     routine_body
    A MySQL extension for stored procedure (not functions) is that a procedure can generate a result set, or even multiple result sets, which the caller processes the same way as the result of a SELECT statement. However, the contents of such result sets cannot be used directly in expression.
    Stored routines are associated with a particular database, just like tables or views. When you drop a database, any stored routines in the database are also dropped.
    Stored procedures and functions do not share the same namespace. It is possible to have a procedure and a function with the same name in a database.
    In Stored procedures dynamic SQL can be used but not in functions or triggers.
    SQL prepared statements (PREPARE, EXECUTE, DEALLOCATE PREPARE) can be used in stored procedures, but not stored functions or triggers. Thus, stored functions and triggers cannot use Dynamic SQL (where you construct statements as strings and then execute them). (Dynamic SQL in MySQL stored routines)

    Some more interesting differences between FUNCTION and STORED PROCEDURE:
  3. Stored procedure is precompiled execution plan where as functions are not. Function Parsed and compiled at runtime. Stored procedures, Stored as a pseudo-code in database i.e. compiled form.
  4. Stored procedure has the security and reduces the network traffic and also we can call stored procedure in any no. of applications at a time. reference
  5. Functions are normally used for computations where as procedures are normally used for executing business logic.
  6. Functions Cannot affect the state of database (Statements that do explicit or implicit commit or rollback are disallowed in function) Whereas Stored procedures Can affect the state of database using commit etc.
    refrence: J.1. Restrictions on Stored Routines and Triggers
  7. Functions can't use FLUSH statements whereas Stored procedures can do.
  8. Stored functions cannot be recursive Whereas Stored procedures can be. Note: Recursive stored procedures are disabled by default, but can be enabled on the server by setting the max_sp_recursion_depth server system variable to a nonzero value. See Section 5.2.3, “System Variables”, for more information.
  9. Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger. Good Example: How to Update same table on deletion in MYSQL?
Note: that although some restrictions normally apply to stored functions and triggers but not to stored procedures, those restrictions do apply to stored procedures if they are invoked from within a stored function or trigger. For example, although you can use FLUSH in a stored procedure, such a stored procedure cannot be called from a stored function or trigger. 

Tuesday, October 1, 2013

How to Get CodeIgniter Support for PHP in NetBeans?

To supports CodeIgniter in my favourite IDE Netbeans there is a NetBeans plugin under the Project Kenai
This plugin will allow us to create CodeIgniter projects right from NetBeans’ Create New PHP Project Wizard, also it’ll provide full auto-completion while you’re coding.
In this post I’ll explain how to get this plugin to work. First you should make sure that you have at least NetBeans 7.0 installed on your machine. Also go ahead and download the latest version of CodeIgniter (currently v 2.1.4).
1. From NetBeans go to Tools menu, then choose Plugins, and then select the Settings tab.
2. Click on the Add button on the window appeared from the last step.
3. Type any name you find appropriate, and for the URL paste one of these links depending on your NetBeans version, and click Ok.
4. Go to the Available Plugins tab, and search for CodeIgniter, two plugins should appear (Framework and Framework Repository), check both of them and click Install.
5. Go to Tools menu, and choose Settings. Then go to PHP tab. You should find a new tab for CodeIgniter, switch to it.
6. Under Base Files click Add type an appropriate name in the name field (I used CodeIgniter 2.1.4), and browse to the CodeIgniter’s zip file you downloaded earlier. Finally hit the Ok button.
7. Now restart NetBeans, and once it’s restarted try to create a new PHP project via the File menu.
8. Go through the few steps of creating a new project, and at the final step under PHP Frameworks you should find CodeIgniter there, check it and hit Finish.
Create New PHP Project Wizard

There you have it! You can now start coding with CodeIgniter like a ninja!

Wednesday, September 18, 2013

To show Image in jasper report from BLOB field of MySql Database

Normally we save image in the blob field of mySql database table. To get that image  in the report page of jasper report we need to follow some steps.

1.set your field class type:    java.io.InputStream
2.Write Image Expression :     JRImageLoader.loadImage((byte [ ] )
                               (JRLoader.loadBytes($F{ImageData})))
                                ImageData is the Blob field in the table.
3.Image Expression Class :      java.awt.Image
4.add the following include

  
 

Installing JAVA(JDK) from rpm file in linux


  1. Become root by running su and entering the super-user password.
  2. Change to the directory in which you want to install. Type:
    cd <directory path name>
    For example, to install the software in the /usr/java/ directory, Type:
    cd /usr/java

  3. Uninstall any earlier installations of the Java packages. rpm -e <package_name>
  4. Install the package.
    rpm -ivh jre-7u7-linux-x64.rpm

    To upgrade a package:
    rpm -Uvh jre-7u7-linux-x64.rpm

  5. Delete the .rpm file if you want to save disk space.
  6. Exit the root shell. No need to reboot.


    Link

Command to Reset $JAVA_HOME in linux

Some times we need to change the $JAVA_HOME i our linux environment.

Goto Terminal and open either of the following files using an editor of your choice (vim, nano, etc):

# nano /etc/profile
or
# nano /root/.bash_profile 

(Instead of root you can also change your normal username.)

Then

#export JAVA_HOME=/home/user/jdk1.7.0_02/
#export PATH=$PATH:$JAVA_HOME/bin


After executing this command just execute the below command to check the current home:


#java -version

Wednesday, August 14, 2013

Java Code to send SMS through SMPP

Java Code to send sms using smpp:

import java.io.IOException;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUException;
import org.jsmpp.bean.Alphabet;
import org.jsmpp.bean.BindType;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.GeneralDataCoding;
import org.jsmpp.bean.MessageClass;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.SMSCDeliveryReceipt;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.BindParameter;
import org.jsmpp.session.SMPPSession;

/**
 *
 * @author paul.pronabananda
 */
public class SMS {

    private String serverAddress = "xxx.xx.xxx.xx"; (ip address of smpp server)
    private int port = xxxx; (port no to connect)
    private String systemID = "paul";  (user id to establish connection)
    private String systemType = "paul";
    private String password = "paul";
    private TypeOfNumber sourceTON = TypeOfNumber.valueOf((byte) 5);
    private TypeOfNumber destinationTON = TypeOfNumber.valueOf((byte) 1);
    private NumberingPlanIndicator sourceNPI;
    private NumberingPlanIndicator destinationNPI;
//    private String fromNumber = "01732444471";
    private String prefixToNumber = "88";
//    private String toNumber = "01553466667";// private TimeFormatter tF = new AbsoluteTimeFormatter();

    public void sendTextMessage(String MSISDN,String fromNumber,String msgBody) {
        sourceNPI = NumberingPlanIndicator.valueOf((byte) 9);
        destinationNPI = NumberingPlanIndicator.valueOf((byte) 1);

        BindParameter bindParam;
        bindParam = new BindParameter(BindType.BIND_TX, systemID, password, systemType, sourceTON, sourceNPI, null);
        SMPPSession smppSession = null;
        try {
            // smpp session is created using the bindparam and the smsc ip address/port
            smppSession = new SMPPSession();
            smppSession.unbindAndClose();
            smppSession.connectAndBind(serverAddress, port, bindParam);
        } catch (IOException e1) {
            System.err.println("Problem to create Session");
            e1.printStackTrace();
        }

      //  String msgBody = "This is a Test Message";

        String messageID = "";
        try {
            messageID = smppSession.submitShortMessage("CMT", sourceTON, sourceNPI, fromNumber,
                    destinationTON, destinationNPI, prefixToNumber + MSISDN,
                    new ESMClass(), (byte) 0, (byte) 0, null, null,
                    new RegisteredDelivery(SMSCDeliveryReceipt.DEFAULT), (byte) 1,
                    new GeneralDataCoding(false, true, MessageClass.CLASS1, Alphabet.ALPHA_DEFAULT), (byte) 0,
                    msgBody.getBytes());
        } catch (PDUException e) {
            //    log.error("Thread[" + nThreadNo + "] -> Failed [" + toNumber+"] : "+"Invalid PDU parameter",e);
            System.err.println("Invalid PDU parameter");
            e.printStackTrace();
        } catch (ResponseTimeoutException e) {
            //    log.error("Thread[" + nThreadNo + "] -> Failed [" + toNumber+"] : "+"Response timeout",e);
            System.err.println("Response timeout");
            e.printStackTrace();
        } catch (InvalidResponseException e) {
            //    log.error("Thread[" + nThreadNo + "] -> Failed [" + toNumber+"] : "+"Receive invalid respose",e);
            System.err.println("Receive invalid respose");
            e.printStackTrace();
        } catch (NegativeResponseException e) {
            //  log.error("Thread[" + nThreadNo + "] -> Failed [" + toNumber+"] : "+"Receive negative response",e);
            System.err.println("Receive negative response");
            e.printStackTrace();
        } catch (IOException e) {
            //   log.error("Thread[" + nThreadNo + "] -> Failed [" + toNumber+"] : "+"IO error occur",e);
            System.err.println("IO error occur");
            e.printStackTrace();
        } catch (Exception e) {
            //   log.error("Thread[" + nThreadNo + "] -> Failed [" + toNumber+"] : "+"Unknown error occur",e);
            System.err.println("Unknown error occur");
            e.printStackTrace();
        } finally {
            System.out.print(messageID);
        }

    }
}

Wednesday, February 6, 2013

Selecting the JVM framework

For various reason all the time we are confused to choose the perfect framework for various reason. Some times for benefits of application development and most of the time for the purpose of career. Recently from a web search, I havea pdf consisting some information regarding this issue. Here is the snapshot of that note.

Some factors for choosing frame work:
  • Request, Component or RIA Framework
  • Ease of Development
  • Project Community
  • Project Future and Roadmap
  • Maintenance
  • Technical Features
Types of application we need to develop:
  • High-traffic, internet facing, infinite scalability
  • Intranet-based, behind the firewall, few users
  • Products, to be maintained for 5-10 years
  • Legacy Backend
  • Others?
Actually the framework should be choose depending on the requirements in project:



»Request Based Frameworks -----------Struts 2, Spring MVC, Rails, Stripes

»Component Based Frameworks.-----------JSF, Tapestry, GWT

»Rich Internet Applications -------------Flex

»One Size Fits All -------------Grails

Generically we may map framework depending on project as:

»High-traffic, internet facing, infinite scalability:
       -------- Request-based frameworks
»Intranet-based, behind the firewall, few users:
       --------Component-based frameworks
»Products, to be maintained for 5-10 years:
       --------Largest Community, Most Vendor Support
»Legacy Backend:
       --------- Same Language as backend

At this time many points should be checked before choosing framework:
1. Developer Productivity
2. Developer Perception
3. Learning Curve
4. Project Health
5. Developer Availability
6. Job Trends

7. Templating
8. Components
9. Ajax
10.Plugins or Add-Ons
11. Scalability
12.Testing Support

13.i18n and l10n
14.Validation
15. Multi-language Support (Groovy / Scala)
16.Quality of Documentation/Tutorials
17.Books Published
18.REST Support (client and server)
19.Mobile / iPhone Support
20.Degree of Risk

The following matrix shows the ratings:


Matrix Result:


  • Spring MVC (17)
  • GWT (17)
  • Ruby on Rails (17)
  • Grails (16.5)
  • Wicket (14.5)
  • Struts 2 (14.5)
--------------------------
Spring MVC
-------------------------
Pros
  • – Easy Configuration with Annotations and Conventions
  • – Integrates with many view options seamlessly: JSP/JSTL, Tiles, FreeMarker, Excel, PDF, JSON
  • Excellent REST Support
Cons
  • – Instant reload not built-in, need JRebel or Spring Roo
  • – No open development process, need to be SpringSource
  • – Ajax requires 3rd-party library (can be a good thing!)

--------------------------
GWT
--------------------------
Pros
  • Write Java => Produces Optimized JavaScript
  • Easy to learn and develop with standard Java Tools
  • Vibrant Community
Cons
  • You have to know Java
  • Slow to compile, difficult to test
  • More like a JSP Tag Library than a web framework

-----------------------
Ruby On Rails
----------------------
Pros
  • Easy to learn and understand for Web Developers
  • Lots and lots of documentation
  • Passionate Community
Cons
  • Slightly less performant by default
  • Dynamic language means more tests
  • Development Tools and Debugging

---------------------
Grails
--------------------
Pros
  • Easy dynamic language transition for Java Developers
  • Groovy
  • Plugins for all types of applications
Cons
  • Groovy learning targets Java Developers
  • Stack traces are horrendous
  • Knowledge of underlying frameworks not required, but helpful
---------------------
Wicket
---------------------
Pros
  • Great for Java Developers
  • Tight binding between pages and views
  • Active community - support from creators
Cons
  • No Jobs or Developers
  • Stateful by default
  • HTML Templates live next to Java code by default





Monday, February 4, 2013

MVC in Sturts 2 and the flow of execution.

At first check  MVC funda

Suppose we want to create a application to show greetings for an interaction in by user. For this purpose, we can provide a page for initial interaction by the user. Suppose this page is index.jsp. This page contains a link by clicking which the user is able to get greetings from application. to so so we need to make following arrangements:


  1. Create a class to store the welcome message (the model)
  2. Create a server page to present the message (the view)
  3. Create an Action class to control the interaction between the user, the model, and the view (the controller)
  4. Create a mapping (struts.xml) to couple the Action class and view




How the code works here:
A browser sends to the web server a request for the URL 


  1. User send request by clicking on the link and in the link it is depicted which action will be implemented.
  2. The container receives from the web server a request for the depicted resource grettings.action. According to the settings loaded from the web.xml, the container finds that all requests are being routed to org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter, including the *.action requests. The StrutsPrepareAndExecuteFilter is the entry point into the framework.
  3. The framework looks for an action mapping named (i.e)"greetings", and it finds that this mapping corresponds to the class . The framework instantiates the Action and calls the Action's required method.
  4. The method creates the GreetingProvider (model) object and returns SUCCESS(feedback strings). The framework checks the action mapping to see what page to load if SUCCESS is returned. The framework tells the container to render as the response to the request, the resource welcome.jsp.
  5. As the page welcome.jsp is being processed, and the tag merges into the response the value of the required attributes.
  6. A pure HTML response is sent back to the browser.




Friday, February 1, 2013

MVC- Model View Controller

All the time we hear about it and the term itself made an image in mind. But still there is some fog in it. Recently i have got three definition regarding this three layers, and after that i am able to remove the fog about it:

MVC means Model-View-Controller where model is responsible for business logic, view handles the user interaction with application and controller decides the flow of application.
  • Model – A class which supplies the data needed for the application. 
  • View – A view element which displays the data.It displays the message returned by the Model class.
  • Controller – A controller class which will respond to user URL request. The controller will coordinate the actions of Model and the View. 


1) User sends the request using view which reaches to the controller on the server.
2) Controller decides the respective model and delivers the control to particular model.
3) As a result of business processing, model changes its state.
4) Depending on the state change of model, control redirects the flow to the view.
Main advantage of this architecture is the separation of data layer, presentation layer and pure business logic.

Sunday, January 6, 2013

Problem to parse int in JavaScript

we face problem when try to:
parseInt('08') returns 0

The leading zero in the string tells the Javascript engine that it is an octal number. Because 8 and 9 are not valid numbers in octal, parseInt returns 0. This is expected behaviour because they are not valid octal integers and parseInt returns 0 because the first valid number encountered is a zero.
The solution

After a quick bit of research when I had this problem, I discovered the parseInt function has an optional 'radix' parameter which specifies the base to use. By passing 10 as the base it solves the leading 0 issue, for example:
 alert( parseInt('08', 10) );

will show the number 8 in an alert dialog, whereas:
 alert( parseInt('08') );

would display 0.
Conclusion

To be on the safe side it's probably always a good idea to pass the radix parameter to the parseInt function to ensure the values returned are what you expect them to be, especially if they might contain leading zeroes.