Wednesday, February 29, 2012

Computer Programming


Oracle SQL


JavaBeans
JSP
Java
HTML
CSS
postgreSQL 
Javascript
C#
PHP

Tuesday, February 28, 2012

Oracle SQL

index

SQL: Structured Query Language
DML: Data Manipulation Language
DDL:  Data Definition Language

/* multiline comment */
-- one line comment

Query:  an operation that retrieves data from one or more tables or views. A query nested within another SQL statement is called a subquery.

A schema is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema.

Tables are the basic unit of data storage in an Oracle database. Data is stored in rows and columns. You define a table with a table name (such as employees) and set of columns. You give each column a column name (such as employee_id, last_name, and job_id), a datatype (such as VARCHAR2, DATE, or NUMBER), and a width. The width can be predetermined by the datatype, as in DATE. If columns are of the NUMBER datatype, define precision and scale instead of width.
A datatype is either scalar or nonscalar. A scalar type contains an atomic value, whereas a nonscalar (sometimes called a "collection") contains a set of values.
A large object (LOB) is a special form of scalar datatype representing a large scalar value of binary or character data.
--------------------
datatype
CHAR: fixed-length character string
NCHAR: Fixed-length Unicode-only
NVARCHAR2: Variable-length Unicode-only
Do not use the VARCHAR datatype.

NUMBER: number from 1.0 x 10^-130 to but not including 1.0 x 10^126.
NUMBER(p,s)
p: is the precision, or the maximum number of significant decimal digits, where the most significant digit is the left-most nonzero digit, and the least significant digit is the right-most known digit.
s: is the scale,or the number of digits from the decimal point to the least significant digit.
---------------------
CREATE TABLE test (col1 NUMBER(5,2), col2 FLOAT(5));
INSERT INTO test VALUES (123.45, 123.45);
----------------
Floating-point numbers can have a decimal point anywhere from the first to the last digit or can have no decimal point at all.
----------------
TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of DATE datatype.
----------
DUAL: Dummy table

SELECT TO_DATE('2005', 'YYYY') FROM DUAL;
SELECT 1+1 FROM DUAL;
SELECT SYSDATE  FROM DUAL;
SELECT USER FROM DUAL;
-------------
literal: fixed data value
text literals: 'Hello'
-----------
INSERT INTO my_table VALUES (1, SYSDATE);
INSERT INTO my_table VALUES (2, TRUNC(SYSDATE));
SELECT * FROM my_table
WHERE datecol = TO_DATE('03-OCT-02','DD-MON-YY');
SELECT * FROM my_table
WHERE datecol > TO_DATE('02-OCT-02', 'DD-MON-YY');
-----------
SYSDATE:  returns the current date and time set for the operating system on which the database resides.
-----------
TRUNC(date,fmt): returns date with the time portion of the day truncated to the unit specified by the format model fmt.
SELECT TRUNC(TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR')  "New Year"  FROM DUAL;
--------------------
Datetime Literals

DATE '1998-12-25'
TO_DATE('98-DEC-25 17:30','YY-MON-DD HH24:MI')
---------------
SELECT * FROM my_table WHERE datecol = DATE '2002-10-03';
SELECT * FROM my_table WHERE TRUNC(datecol) = DATE '2002-10-03';
INSERT INTO my_table VALUES
   (3, TO_DATE('3-OCT-2002','DD-MON-YYYY'));
INSERT INTO my_table VALUES (4, '03-OCT-02');
INSERT INTO my_table VALUES (5, TRUNC(SYSDATE));
SELECT TIMESTAMP '1999-10-29 01:30:00' AT TIME ZONE 'US/Pacific' FROM DUAL;
--------------
IS NULL
IS NOT NULL
SELECT last_name FROM employees
WHERE commission_pct IS NULL ORDER BY last_name;
---------------
sequence is a schema object that can generate unique sequential values. These values are often used for primary and unique keys. You can refer to sequence values in SQL statements with these pseudocolumns:
CURRVAL: Returns the current value of a sequence
NEXTVAL: Increments the sequence and returns the next value
You must qualify CURRVAL and NEXTVAL with the name of the sequence:
sequence.CURRVAL
sequence.NEXTVAL
To refer to the current or next value of a sequence in the schema of another user, you must have been granted either SELECT object privilege on the sequence or SELECT ANY SEQUENCE system privilege, and you must qualify the sequence with the schema containing it:
schema.sequence.CURRVAL
schema.sequence.NEXTVAL
To refer to the value of a sequence on a remote database, you must qualify the sequence with a complete or partial name of a database link:
schema.sequence.CURRVAL@dblink
schema.sequence.NEXTVAL@dblink
-----------
SELECT employees_seq.nextval FROM DUAL;
INSERT INTO employees
VALUES (employees_seq.nextval, 'John', 'Doe', 'jdoe', '555-1212', TO_DATE(SYSDATE), 'PU_CLERK', 2500, null, null,30);
INSERT INTO orders (order_id, order_date, customer_id) VALUES (orders_seq.nextval, TO_DATE(SYSDATE), 106);
INSERT INTO order_items (order_id, line_item_id, product_id) VALUES (orders_seq.currval, 1, 2359);
------------
ROWNUM: a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.
You can use ROWNUM to limit the number of rows returned by a query, as in this example:
SELECT * FROM employees WHERE ROWNUM < 11;
SELECT * FROM
(SELECT * FROM employees ORDER BY employee_id)
WHERE ROWNUM < 11;
---------------
SELECT * FROM order_items WHERE quantity = -1
 ORDER BY order_id, line_item_id, product_id;
SELECT * FROM employees WHERE -salary < 0
  ORDER BY employee_id;
--------------
SELECT hire_date  FROM employees
WHERE SYSDATE - hire_date  > 365
ORDER BY hire_date;
-------------------
SELECT 'Name is ' || last_name
FROM employees ORDER BY last_name;
------------
NVL lets you replace null (returned as a blank) with a string in the results of a query. If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1.

SELECT last_name,
NVL(TO_CHAR(commission_pct), 'Not Applicable')
"COMMISSION"  FROM employees
WHERE last_name LIKE 'B%' ORDER BY last_name;
-------------------
TO_CHAR function converts a DATETIME, number, or NTEXT expression to a TEXT expression in a specified format. This function is typically used to format output data.
SHOW TO_CHAR(SYSDATE, 'Month DD, YYYY HH24:MI:SS')
November  30, 2000 10:01:29

--calculates the average of the maximum salaries of all the departments
SELECT AVG(MAX(salary)) FROM employees GROUP BY department_id;
SELECT COUNT(*) "Total" FROM employees;
SELECT COUNT(*) "Allstars" FROM employees
   WHERE commission_pct > 0;
SELECT COUNT(commission_pct) "Count" FROM employees;
SELECT COUNT(DISTINCT manager_id) "Managers" FROM employees;
-------------
partition: smaller and more manageable pieces of very large tables and indexes
---------------
INSERT INTO employee (empno, ename, job)
VALUES (emp_sequence.NEXTVAL, 'SMITH', 'CLERK');
--------------
INSERT INTO personal_info
values('bart','simpson',12345,$45000)
SELECT * FROM personal_info
SELECT last_name FROM personal_info
SELECT * FROM personal_info WHERE salary > $50000
UPDATE personal_info SET salary = salary * 1.03
UPDATE personal_info SET salary = salary + $5000
WHERE employee_id = 12345
DELETE FROM personal_info WHERE employee_id = 12345
--------------
SELECT last_name, salary + NVL(commission_pct, 0),
   job_id, e.department_id
  FROM employees e, departments d
  WHERE e.department_id = d.department_id
    AND salary + NVL(commission_pct,0) >
   (SELECT salary + NVL(commission_pct,0)
      FROM employees
      WHERE last_name = 'Pataballa');



SELECT last_name,
salary + NVL(commission_pct, 0),
job_id, e.department_id
FROM employees e,departments d
WHERE e.department_id = d.department_id
AND salary + NVL(commission_pct, 0) >
  (SELECT salary + NVL(commission_pct,0)
  FROM employees  WHERE last_name = 'Pataballa');
-------------
SELECT last_name  FROM employees WHERE last_name
LIKE '%A\_B%' ESCAPE '\'
ORDER BY last_name;

x [NOT] LIKE y [ESCAPE 'z']
%:  zero or more characters except null.
_:  single character

SELECT salary FROM employees
WHERE last_name LIKE 'R%' ORDER BY salary;

SELECT salary FROM employees
WHERE 'SM%' LIKE last_name ORDER BY salary;
----------------
ESCAPE Clause Example The following example searches for employees with the pattern A_B in their name:

SELECT last_name  FROM employees
WHERE last_name LIKE '%A\_B%' ESCAPE '\'
ORDER BY last_name;
The ESCAPE clause identifies the backslash (\) as the escape character. In the pattern, the escape character precedes the underscore (_). This causes Oracle to interpret the underscore literally, rather than as a special pattern matching character.
---------------------
SELECT * FROM employees
WHERE salary BETWEEN 2000 AND 3000
ORDER BY employee_id;
-------------
EXISTS: TRUE if a subquery returns at least one row.

SELECT department_id FROM departments d
WHERE EXISTS
  (SELECT * FROM employees e
    WHERE d.department_id
    = e.department_id)
   ORDER BY department_id;
---------------
SELECT * FROM employees
WHERE job_id IN ('PU_CLERK','SH_CLERK')
ORDER BY employee_id;

SELECT * FROM employees WHERE salary IN
  (SELECT salary FROM employees
   WHERE department_id =30)
ORDER BY employee_id;

SELECT * FROM employees WHERE salary NOT IN
  (SELECT salary  FROM employees
   WHERE department_id = 30)
ORDER BY employee_id;

SELECT * FROM employees WHERE job_id NOT IN
  ('PU_CLERK', 'SH_CLERK')
ORDER BY employee_id;
----------------
SELECT * FROM persons p
WHERE VALUE(p) IS OF TYPE (employee_t);

SELECT * FROM persons p
WHERE VALUE(p) IS OF (ONLY part_time_emp_t);
-------------------
integrity constraints: rules for each column.

NOT NULL: prohibits a database value from being null.
unique: prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null.
primary key: combines a NOT NULL constraint and a unique constraint.
foreign key: requires values in one table to match values in another table.
check constraint: requires a value in the database to comply with a specified condition.
--------------------------
you must match datatype (using the TO_CHAR function) when columns do not exist in one or the other table:

SELECT location_id, department_name "Department",
TO_CHAR(NULL) "Warehouse"  FROM departments

UNION

SELECT location_id, TO_CHAR(NULL) "Department", warehouse_name FROM warehouses;
--------------------------
--UNION returns only distinct rows
SELECT product_id FROM order_items
UNION
SELECT product_id FROM inventories
ORDER BY product_id;

--UNION ALL does not eliminate duplicate rows
SELECT location_id  FROM locations
UNION ALL
SELECT location_id  FROM departments
ORDER BY location_id;
--------------------
SELECT product_id FROM inventories
INTERSECT
SELECT product_id FROM order_items
ORDER BY product_id;
---------------
SELECT product_id FROM inventories
MINUS
SELECT product_id FROM order_items
ORDER BY product_id;
-------------------
Join is a query that combines rows from two or more tables, views, or materialized views. It is done whenever multiple tables appear in the FROM clause of the query.
-----------------------
SELECT last_name, job_id, departments.department_id, department_name
FROM employees, departments
WHERE
 employees.department_id =
 departments.department_id
ORDER BY last_name, job_id;
-----------------
SELECT last_name, job_id, departments.department_id, department_name
FROM employees, departments
WHERE
employees.department_id =
     departments.department_id
  AND job_id = 'SA_MAN'
ORDER BY last_name;
-------------------
SELECT last_name, department_id FROM employees
WHERE department_id =
     (SELECT department_id FROM employees
      WHERE last_name = 'Lorentz')
ORDER BY last_name, department_id;
--------------------
UPDATE employees SET salary = salary * 1.1
WHERE employee_id IN
  (SELECT employee_id FROM job_history);
-------------------------
CREATE TABLE new_departments (department_id, department_name, location_id) AS
   SELECT department_id, department_name,
   location_id  FROM departments;
----------------------
SELECT
e1.last_name || ' works for ' || e2.last_name
   "Employees and Their Managers"
FROM employees e1, employees e2
WHERE e1.manager_id = e2.employee_id
      AND e1.last_name LIKE 'R%'
ORDER BY e1.last_name;
---------------------




The left outer join returns all departments, including those without any employees.

recommended syntax:

SELECT d.department_id, e.last_name
FROM departments d LEFT OUTER JOIN employees e
   ON d.department_id = e.department_id
ORDER BY d.department_id, e.last_name;

traditional syntax:

SELECT d.department_id, e.last_name
FROM departments d, employees e
WHERE d.department_id = e.department_id(+)
ORDER BY d.department_id, e.last_name;
--------------------
UPDATE employees SET commission_pct = NULL
WHERE job_id = 'SH_CLERK';

UPDATE employees SET  job_id = 'SA_MAN',
  salary = salary + 1000, department_id = 120
WHERE first_name||' '||last_name = 'Douglas Grant';

UPDATE employees@remote SET salary = salary * 1.1
WHERE last_name = 'Baer';
------------------------
UPDATE employees a SET

 department_id =
 (SELECT department_id FROM departments
 WHERE location_id = '2100'),

 (salary, commission_pct) =
 (SELECT 1.1*AVG(salary), 1.5*AVG(commission_pct)
 FROM employees b
 WHERE a.department_id = b.department_id)

WHERE department_id IN
  (SELECT department_id FROM departments
  WHERE location_id = 2900 OR location_id = 2700);
---------------------

Monday, February 27, 2012

JSP

index



JSP: JavaServer Pages
Java Servlet
BEA WebLogic Application Server (JSP capable web-server)
----------------------
hello.jsp
<HTML><BODY>
Hello!  The time is now  <%= new java.util.Date() %>
</BODY></HTML>
------------------------
<HTML><BODY>
<%
// This is a scriptlet.  Notice that the "date"
// variable we declare here is available in the
// embedded expression later on.
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>

Hello!  The time is now <%= date %>
</BODY></HTML>
------------------------
<HTML><BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>

Hello!  The time is now

<%
// This scriptlet generates HTML output
out.println( String.valueOf( date ));
%>
</BODY></HTML>
-----------------------
<HTML><BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>

Hello!  The time is now

<%
out.println( date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost());
%>
</BODY></HTML>
---------------------
<TABLE BORDER=2>
<% for ( int i = 0; i < n; i++ ) { %>
<TR> <TD> Number </TD> <TD> <%= i+1 %> </TD> </TR>
<% } %>
</TABLE>
-----------------------
<% if ( hello ) { %>
<P>Hello, world
<% } else { %>
<P>Goodbye, world
<% } %>
-----------------------
<%@ page import="java.util.*" %>
<HTML><BODY>
<%
System.out.println( "Evaluating date now" );
Date date = new Date();
%>
Hello!  The time is now <%= date %>
</BODY></HTML>
-----------------------
<HTML> <BODY>
Going to include hello.jsp...<BR>
<%@ include file="hello.jsp" %>
</BODY> </HTML>
-------------------
<%@ page import="java.util.*" %>
<HTML><BODY>
<%!
Date theDate = new Date();
Date getDate(){
  System.out.println( "In getDate() method" );
  return theDate;
}
%>
Hello!  The time is now <%= getDate() %>
</BODY></HTML>
-----------------------
<HTML> <BODY>
Going to include hello.jsp...<BR>
<jsp:include page="hello.jsp"/>
</BODY></HTML>
-------------------
A session is an object associated with a visitor.  Data can be put in the session and retrieved from it, much like a Hashtable.  A different set of data is kept for each visitor to the site.
--------------
<HTML><BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name?
<INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY></HTML>
-----------------------
SaveName.jsp
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
<HTML><BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY></HTML>
---------------------
NextPage.jsp
<HTML><BODY>
Hello, <%= session.getAttribute( "theName" ) %>
</BODY></HTML>


---------------------
GetName.html
<HTML><BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name?
<INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address?
<INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age?
<INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY></HTML>
------------------------
package user;

public class UserData
{
String username;
public void setUsername(String value){username = value;}
public String getUsername(){return username;}

String email;
public void setEmail(String value){email=value;}
public String getEmail(){return email;}

int age;
public void setAge(int value){age=value;}
public int getAge(){return age;}

}//class UserData
--------------------
SaveName.jsp
<jsp:useBean id="user" class="user.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>

<HTML><BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY></HTML>
------------------------
NextPage.jsp
<jsp:useBean id="user" class="user.UserData" scope="session"/>
<HTML><BODY>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</BODY></HTML>
------------------------
tld tag library description
------------------
GetName.jsp
<%@ taglib prefix="blx" uri="/blx.tld" %>
<jsp:useBean id="user" class="user.UserData" scope="session"/>

<HTML><BODY>

<blx:getProperty name="user" property="*">

<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>

</blx:getProperty>

</BODY></HTML>
-------------------
<jsp:forward>
Forwards a client request to an HTML file, JSP file, or servlet for processing.

JSP Syntax
<jsp:forward page="{ relativeURL | <%= expression %> }" />

Examples
<jsp:forward page="/servlet/login" />
----------------
SaveName.jsp
<%@ taglib prefix="blx" uri="/blx.tld" %>

<%!
boolean haveError;
StringBuffer errors;

public void errorHandler
( String field, String value, Exception ex )
{
haveError = true;
if ( errors == null ) errors = new StringBuffer();
else errors.append( "<P>" );

errors.append
( "<P>Value for field \"" + field + "\" is invalid." );
if ( ex instanceof java.lang.NumberFormatException )
 errors.append( " The value must be a number." );
}//errorHandler
%>

<%
// Variables must be initialized outside declaration!
haveError = false;
errors = null;
%>

<HTML><BODY>

<jsp:useBean id="user" class="user.UserData" scope="session"/>
<blx:setProperty name="user" property="*" onError="errorHandler"/>
<%
if (haveError){
  out.println( errors.toString());
  pageContext.include("GetName.jsp");
} else
   pageContext.forward("NextPage.jsp");
%>

</BODY></HTML>
-------------------
<%
if (haveError){
request.setAttribute("errors",errors.toString());
pageContext.forward("GetName.jsp");
} else pageContext.forward( "NextPage.jsp" );
%>
----------------
GetName.jsp
<jsp:useBean id="user" class="user.UserData" scope="session"/>
<HTML><BODY>

<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name?
<INPUT TYPE=TEXT NAME=username SIZE=20
  VALUE="<%= user.getUsername() %>"><BR>
What's your e-mail address?
<INPUT TYPE=TEXT NAME=email SIZE=20
  VALUE="<%= user.getEmail() %>"><BR>
What's your age?
<INPUT TYPE=TEXT NAME=age SIZE=4
  VALUE=<%= user.getAge() %>>
<P><INPUT TYPE=SUBMIT>
</FORM>

</BODY></HTML>
---------------------
<FORM METHOD=POST ACTION=j_security_check>

The target j_security_check is provided by the application server, and does not need to be coded.

The form must contain two <INPUT> fields, named j_username and j_password respectively for the username and password.  Typically, the username field will be a TEXT input field, and the password field will be a PASSWORD input field.
------------------
Output Comment
Generates a comment that is sent to the client in the viewable page source.

JSP Syntax
<!--    comment [ <%= expression %> ] -->

Example 1
<!-- This file displays the user login screen -->

Displays in the page source:
<!-- This file displays the user login screen -->

Example 2
<!-- This page was loaded on
<%= (new java.util.Date()).toLocaleString() %> -->

Displays in the page source:
<!-- This page was loaded on January 1, 2000 -->
---------------
Hidden Comment
Documents the JSP page but is not sent to the client.

JSP Syntax
<%-- comment --%>

Examples
<%@ page language="java" %>
<html><head><title>A Comment Test</title></head><body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body></html>
-----------------------
Declaration
Declares a variable or method.
JSP Syntax
<%! declaration; [ declaration; ]+ ... %>

Examples
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

You must declare the variable or method before you use it in the JSP file.
---------------
Expression
JSP Syntax   <%= expression %>

Examples
The map file has <font color="blue"> <%= map.size() %> </font> entries.
Good guess, but nope. Try <b> <%= numguess.getHint() %> </b>.

Description
An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.
You cannot use a semicolon to end an expression.
---------------------
Scriptlet: contains a code fragment.

JSP Syntax
<% code fragment %>

Examples
<%
String name = null;
if (request.getParameter("name") == null) {
%>

<%@ include file="error.html" %>

<%
} else {
foo.setName(request.getParameter("name"));
if (foo.getName().equalsIgnoreCase("integra"))
name = "acura";
if (name.equalsIgnoreCase( "acura" )) {
%>

Description
A scriptlet can contain any number of language statements, variable or method declarations, or expressions.
You can use any of the implicit objects or any object declared with a <jsp:useBean> element.
Any text, HTML tags, or JSP elements you write must be outside the scriptlet.
Scriptlets are executed at request time, when the JSP container processes the client request. If the scriptlet produces output, the output is stored in the out object.
---------------
Include Directive
Includes a static file in a JSP file.

JSP Syntax
<%@ include file="relativeURL" %>

Examples

include.jsp:
<html>
<body bgcolor="white">
<font color="blue">
The current date and time are
<%@ include file="date.jsp" %>
</font>
</body> </html>

date.jsp:
<%@ page import="java.util.*" %>
<%= (new java.util.Date() ).toLocaleString() %>

Displays in the page:
The current date and time are
Aug 30, 1999 2:38:40
---------------
Page Directive
Defines attributes that apply to an entire JSP page.

JSP Syntax
<%@ page
[ language="java" ]
[ extends="package.class" ]
[ import= "{ package.class | package.* }, ..." ]
[ session="true|false" ]
[ buffer="none|8kb|sizekb" ]
[ autoFlush="true|false" ]
[ isThreadSafe="true|false" ]
[ info="text" ]
[ errorPage="relativeURL" ]
[ contentType="mimeType [ ;charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ]
[ isErrorPage="true|false" ]
%>

Examples
<%@ page import="java.util.*, java.lang.*" %>
<%@ page buffer="5kb" autoFlush="false" %>
<%@ page errorPage="error.jsp" %>
---------------
You can use the <%@ page %> directive more than once in a translation unit, but you can only use each attribute, except import, once.

language="java"
The scripting language used in scriptlets, declarations, and expressions in the JSP file and any included files. In this release, the only allowed value is java.

extends="package.class"
The fully qualified name of the superclass of the Java class file this JSP file will be compiled to. Use this attribute cautiously, as it can limit the JSP container's ability to provide a specialized superclass that improves the quality of the compiled file.

import="{package.class | package.* }, ..."
A comma-separated list of Java packages that the JSP file should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP file. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP file.
The following packages are implicitly imported, so you don't need to specify them with the import attribute:
java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*
You must place the import attribute before the element that calls the imported class.

session="true | false"
Whether the client must join an HTTP session in order to use the JSP page. If the value is true, the session object refers to the current or new session.
If the value is false, you cannot use the session object or a <jsp:useBean> element with scope=session in the JSP file.
The default value is true.

buffer="none | 8kb | sizekb"
The buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client Web browser. The default value is 8kb. If you specify a buffer size, the output is buffered with at least the size you specified.

autoFlush="true | false"
Whether the buffered output should be flushed automatically when the buffer is full. If set to true (the default value), the buffer will be flushed. If set to false, an exception will be raised when the buffer overflows. You cannot set autoFlush to false when buffer is set to none.

isThreadSafe="true | false"
Whether thread safety is implemented in the JSP file. The default value is true, which means that the JSP container can send multiple, concurrent client requests to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page.

info="text"
A text string that is incorporated verbatim into the compiled JSP page. You can later retrieve the string with the Servlet.getServletInfo() method.

errorPage="relativeURL"
A pathname to a JSP file that this JSP file sends exceptions to. If the pathname begins with a /, the path is relative to the JSP application's document root directory and is resolved by the Web server. If not, the pathname is relative to the current JSP file.

isErrorPage="true | false"
Whether the JSP file displays an error page. If set to true, you can use the exception object in the JSP file. If set to false (the default value), you cannot use the exception object in the JSP file.

contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"
The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

Tip
If you need to include a long list of packages or classes in more than one JSP file, you can create a separate JSP file with a <%@ page %> directive that contains the import list and include that file in the main JSP file.
------------------

Sunday, February 26, 2012

C#






index  
C# Version 4.0

// Hello1.cs
public class Hello1
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, World!");
   }
}

public Access is not restricted.
protected Access is limited to the containing class or types derived from the containing class.
internal Access is limited to the current assembly.
protected internal Access is limited to the current assembly or types derived from the containing class.
private Access is limited to the containing type.

static Declare a member that belongs to the type itself rather than to a specific object.
void  method does not return a value
Main method is the entry point of your program. It is declared inside a class or struct. It must be static. It can either have a void or int return type.  The Main method can be declared without parameters or with parameters. The latter form allows your program to read command-line arguments.
Source file file extension .cs
assembly: executable or library file
applications: file extension .exe (executable)
libraries: file extension dll (no Main method)

// Hello2.cs
using System;

public class Hello2
{
   public static void Main()
   {
      Console.WriteLine("Hello, World!");
   }
}

// Hello3.cs
// arguments: A B C D
using System;

public class Hello3
{
   public static void Main(string[] args)
   {
      Console.WriteLine("Hello, World!");
      Console.WriteLine("You entered the following {0} command line arguments:",
         args.Length );
      for (int i=0; i < args.Length; i++)     
         Console.WriteLine("{0}", args[i]);
     
   }
}

// Hello4.cs
using System;
public class Hello4
{
   public static int Main(string[] args)
   {
      Console.WriteLine("Hello, World!");
      return 0;
   }
}

System is a namespace
Namespaces contain types and other namespaces
Console is a class in the System namespace

<Namespace>.<Class>.<Method>(parameters);


using System;
namespace Acme.Collections
{
   public class Stack
   {
      Entry top;

      public void Push(object data) {
         top = new Entry(top, data);
      }

      public object Pop() {
         if (top == null) throw new InvalidOperationException();
         object result = top.data;
         top = top.next;
         return result;
      }

      class Entry
      {
         public Entry next;
         public object data;

         public Entry(Entry next, object data) {
            this.next = next;
            this.data = data;
         }
      }
   }
}

using System;
class Test
{
   static void Main() {
      int i = 123;
      object o = i;        // Boxing
      int j = (int)o;      // Unboxing
   }
}

static void Main(string[] args)
{
   if (args.Length == 0)
      Console.WriteLine("a");  
   else
      Console.WriteLine("b");  
}

static void Main(string[] args)
{
   int n = args.Length;
   switch (n) {
      case 0:
         Console.WriteLine("No arguments");
         break;
      case 1:
         Console.WriteLine("One argument");
         break;
      default:
         Console.WriteLine("{0} arguments", n);
         break;
      }
   }
}


Saturday, February 25, 2012

JavaScript

index  



<html><body>
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
</body></html> 
-----------------------
<p id = "demo">This is a paragraph </p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
// the browser will replace the content of the HTML element with id = "demo", with the current date
//JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created
</script>
--------------------------
<head> <script type="text/javascript">
function displayDate()
{ document.getElementById("demo").innerHTML=Date(); }
</script> </head>
<body>
<button type = "button" onclick = "displayDate()">
Display Date</button>
<p id = "demo"></p>
</body>
It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
--------------------------
JavaScript can be placed in external JS file.
a.html
<html><head>
<script type ="text/javascript" src="javascript.js"></script>
</head><body>
<button type = "button" onclick = "displayDate()">Display Date </button>
<p  id = "demo"></p>
</body></html>
javascript.js
function displayDate()
{ document.getElementById("demo").innerHTML = Date(); }
-----------------------------
<html><head></head><body>
bbbbbbbbbbbbbb
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
</script> 
aaaaaaaaaaaa
</body></html>
-----------------------
<script type="text/javascript">
/*
multiline
comments
*/
// one-line comment
</script> 
-----------------------
var x = 5;
var carname = "Volvo";
-----------------------
A variable declared with var inside a function is LOCAL (valid only inside the function) 
A variable declared without var is GLOBAL (valid in the entire web page) 
function displayDate() { 
var x;  // LOCAL
y;     //GLOBAL
x = 1;
y = "aaa";
}
-----------------------
x += y // same as x = x + y;
txt1 = "What a very";
txt2 = "nice day";
txt3 = txt1 + txt2;
-----------------------
If you add a number and a string, the result will be a string!
x = 5 + "5";
document.write(x); // 55
x = "6" + 6;
document.write(x); // 66
-----------------------
age = "17"; // string is interpreted as number!!
if (age < 18)   document.write("Too young");
else  document.write("adult");
----------------------------
&& and      || or      ! not 
----------------------------
greeting = (visitor=="PRES") ? "Dear President " : "Dear ";
if (visitor == "PRES")
 greeting = "Dear President ";
else
 greeting = "Dear ";
----------------------------
var d = new Date();
var time = d.getHours();
if (time < 12) 
 document.write("<b>Good morning</b>");
else if (time < 18)
 document.write("<b>Good afternoon</b>");
else
 document.write("<b>Good evening</b>");
----------------------------
var d = new Date();
var theDay = d.getDay(); //returns the day of the week (from 0 to 6)
switch (theDay) {
case 5:
  document.write("Friday");  break;
case 6:
  document.write("Saturday"); break;
case 0:
  document.write("Sunday"); break;
default:
  document.write("Outro dia");
}
----------------------------
POPUP
alert("sometext"); //OK 
var r = confirm("sometext"); //OK cancel
if (r == true) OK else cancel
var name = prompt("enter your name","Harry Potter");
if (name != null && name != "")
-------------------------
onblur an element loses focus
onchange an element change
onclick mouse click
ondblclick mouse double-click
onerror An error occurs when loading
onfocus an element gets focus
onmousedown mouse button is pressed
onmousemove mouse pointer moves
onmouseout mouse pointer moves out of an element
onmouseover mouse pointer moves over an element
onmouseup mouse button is released
onkeydown a key is pressed
onkeypress a key is pressed and released
onkeyup a key is released
onselect an element is selected 
onload A page or image is finished loading 
onresize A window or frame is resized 
onselect Text is selected 
onunload The user exits the page 
-------------------------
<html><head><script type="text/javascript">
function product(a,b) { return a * b; }
</script></head><body><script type="text/javascript">
document.write(product(4,4));
</script></body></html>
-------------------------
for (i = 0; i <= 5; i++) 
{  document.write("The number is " + i + "<br />"); }
-------------------------
var i = 0;
while (i <= 5) {
  document.write("The number is " + i + "<br />");
  i++;
}
-------------------------
var i = 0;
do {
  document.write("The number is " + i + "<br />");
  i++;
} while (i <= 5);
-------------------------
for (i = 0; i <= 10; i++) {
  if (i == 3) break;
  document.write("The number is " + i + "<br />");
}
-------------------------
var person = { 
firstName : "John",
Surname : "Doe",
age : 25   }; 
for (x in person) document.write(person[x] + " ");
-------------------------
<html><head><script type="text/javascript">
function isKeyPressed(event) {
if (event.altKey)  alert("ALT key");
else            alert("No ALT key");
}
</script></head>
<body onmousedown = "isKeyPressed(event)" >
<p> Click somewhere in the document. An alert box will tell you if you pressed the ALT key or not.
</p>
</body></html> 
-------------------------
<html><head><script type="text/javascript">
var txt = "";
function message()
{
try {  adddlert("Welcome guest!");  } 
catch( err ) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.description + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);  }
}
</script></head>
<body>
<input type = "button" value = "View message" onclick = "message()" />
</body></html>
-----------------------------
var x = prompt("Enter a number between 0 and 10:","");
try { 
  if(x > 10)        throw "Err1";
  else if(x < 0)     throw "Err2";
  else if(isNaN(x))  throw "Err3";
} catch( er ) {
  if(er == "Err1") alert("Error! The value is too high");
  if(er == "Err2") alert("Error! The value is too low");
  if(er == "Err3") alert("Error! The value is not a number");
}
-----------------------------
\' single quote 
\" double quote 
\\ backslash 
\n new line 
\r carriage return 
\t tab 
\b backspace 
\f form feed 
-----------------------------
var txt = "Hello World!";
document.write(txt.length);
document.write(txt.toUpperCase());
-----------------------------
http://www.w3schools.com/jsref/jsref_obj_string.asp
http://www.w3schools.com/jsref/jsref_obj_date.asp
http://www.w3schools.com/jsref/jsref_obj_math.asp
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
-----------------------------
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)  alert("Today is before 14th January 2100");
else        alert("Today is after 14th January 2100");
-----------------------------
ARRAY
var myCars = new Array(); 
// regular array (add an optional integerargument to control array's size)
myCars[0]="Saab"; 
myCars[1]="Volvo";
myCars[2]="BMW";
var myCars = new Array("Saab","Volvo","BMW");
var myCars = ["Saab","Volvo","BMW"]; 
-----------------------------
var myBoolean = new Boolean();
-----------------------------
var x = Math.PI;
var y = Math.sqrt(16);
document.write(Math.round(4.7));
document.write(Math.random());
-----------------------------
REGULAR EXPRESSIONS
new RegExp("regexp","i")
/regexp/i 
<html><head></head><body><script type="text/javascript">
var patt1 = new RegExp("e");
document.write(patt1.test("The best things in life are free")); //true
document.write(patt1.exec("The best things in life are free"));//e
</script></body></html>
-----------------------------
<div id = "example"></div>
<script type="text/javascript">
txt="<p>Browser CodeName: "   
+ navigator.appCodeName + "</p>";
txt += "<p>Browser Name: " 
+ navigator.appName + "</p>";
txt +="<p>Browser Version: "
+ navigator.appVersion + "</p>";
txt += "<p>Cookies Enabled: "
+ navigator.cookieEnabled + "</p>";
txt += "<p>Platform: " 
+ navigator.platform + "</p>";
txt+="<p>User-agent header:"
+navigator.userAgent+ "</p>";
document.getElementById("example").innerHTML=txt;
-----------------------------
<html><head><script type="text/javascript">
function validateForm()
{
var x = document.forms["myForm"]["fname"].value
if (x == null || x == "")
{
  alert("First name must be filled out");
  return false;
}
}
</script></head><body>
<form name="myForm" action="someURL" onsubmit = "return validateForm()" 
method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body></html>
-----------------------------
<html><head><script type="text/javascript">
function validateForm() {
var x = document.forms["myForm"]["email"].value
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length){
  alert("Not a valid e-mail address");
  return false; } }
</script></head><body>
<form name = "myForm" action="someURL" onsubmit = "return validateForm();" method = "post">
Email: <input type="text" name="email">
<input type = "submit" value="Submit">
</form> 
</body></html>
-----------------------------
<html><head><script type="text/javascript">
function timeMsg(){
  var t = setTimeout("alertMsg()",3000);
}
function alertMsg() {
  alert("Hello");
}
</script></head><body>
<form>
<input type = "button" 
value = "Display alert box in 3 seconds"
onclick = "timeMsg()" />
</form>
</body></html>
-----------------------------
<html><head><script type="text/javascript">
var c = 0;
var t;
var timer_is_on = 0;
function timedCount(){
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout("timedCount()",1000);
}
function doTimer(){
if (!timer_is_on)
  {
  timer_is_on = 1;
  timedCount();
  }
}
</script></head><body>
<form>
<input type = "button" value = "Start count!" onclick="doTimer()">
<input type = "text" id="txt" />
</form>
</body></html>
-----------------------------
<html><head><script type="text/javascript">
var c = 0;
var t;
var timer_is_on = 0;
function timedCount(){
document.getElementById('txt').value=c;
c = c + 1;
t = setTimeout("timedCount()",1000);
}
function doTimer(){
if (!timer_is_on)
  {
  timer_is_on = 1;
  timedCount();
  }
}
function stopCount()
{
clearTimeout(t);
timer_is_on = 0;
}
</script></head><body>
<form>
<input type = "button" value="Start count!" onclick = "doTimer()">
<input type = "text" id="txt">
<input type = "button" value="Stop count!" onclick = "stopCount()">
</form>
</body></html>
----------------
person = new Object();
person.firstname = "John";
person.lastname = "Doe";
person.age = 30;
person.eyecolor = "blue";
document.write(person.firstname);
--------------------------
person= {firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
document.write(person.firstname);
--------------------------
x.innerHTML - the text value of x
x.nodeName - the name of x
x.nodeValue - the value of x
x.parentNode - the parent ode of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x
-------------------------------------------------
x.getElementById(id) - get the element with a specified id
x.getElementsByTagName(name) - get all elements with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x
-------------------------------------------------
<html><body>
<p id = "intro">Hello World!</p>
<script type="text/javascript">
txt = document.getElementById("intro").innerHTML;
document.write("<p>The text from the intro paragraph: " + txt + "</p>");
</script></body></html>
------------------------------------
<html><body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
txt= document.getElementById("intro").childNodes[0].nodeValue;
document.write("<p>The text from the intro paragraph: " + txt + "</p>");
</script>
</body></html>
------------------------------------
<html><body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
<script type="text/javascript">
x = document.getElementsByTagName("p");
document.write("Text of first paragraph: " + x[0].innerHTML); //Hello World! 
</script>
</body></html>
-----------------------------
<html><body>
<p>Hello World!</p>
<div id = "main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>
<script type="text/javascript">
x = document.getElementById("main").getElementsByTagName("p");
document.write("First paragraph inside the div: " + x[0].innerHTML);
//The DOM is very useful.
</script>
</body></html>
-------------------------------------------------
<html><body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<script type="text/javascript">
x = document.getElementsByTagName("p");
document.write("Text of second paragraph: " + x[1].innerHTML);
</script>
</body></html>
-------------------------------------------------
<html><body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
x = document.getElementById("intro");
document.write(x.firstChild.nodeValue);
//Hello World!
</script>
</body></html>
-------------------------------------
<html><body>
<script type="text/javascript">
document.body.bgColor="lavender";
</script>
</body></html> 
-------------------------------------
<html><body>
<p id="p1">Hello World!</p>
<script type="text/javascript">
document.getElementById("p1").innerHTML="New text!";
</script>
</body></html> 
--------------------------------------------------
<html><body>
<input type="button"
onclick = "document.body.bgColor = 'lavender'; "
value = "Change background color"  />
</body></html>
--------------------------------------------------
<html><head><script type="text/javascript">
function ChangeText(){
document.getElementById("p1").innerHTML = "New text!";}
</script></head><body>
<p id="p1">Hello world!</p>
<input type="button" 
onclick = "ChangeText()" value = "Change text" />
</body></html> 
--------------------------------------------------
<html><head><script type="text/javascript">
function ChangeBackground(){
document.body.style.backgroundColor="lavender";}
</script></head><body>
<input type="button" 
onclick = "ChangeBackground()"
value = "Change background color" />
</body></html> 
--------------------------------------------------
<html><head><script type="text/javascript">
function ChangeStyle(){
document.getElementById("p1").style.color="blue";
document.getElementById("p1").style.fontFamily="Arial";}
</script></head><body>
<p id = "p1">Hello world!</p>
<input type = "button" onclick = "ChangeStyle()" value = "Change style" />
</body></html> 
--------------------------------------------------
<html><head>
<script type="text/javascript">
function getEventType(event)
{
  alert(event.bubbles);
}
</script></head>
<body onmousedown = "getEventType(event)">
<p>Click somewhere in the document.
An alert box will tell if the
event is a bubbling event.</p>
</body></html> 
--------------------------------------
<html><head>
<script type="text/javascript">
function show_coords(event)
{
  var x = event.clientX
  var y = event.clientY
  alert("X coords: " + x + ", Y coords: " + y)
}
</script>
</head>
<body onmousedown = "show_coords(event)">
<p>Click in the document. An alert box will alert
the x and y coordinates of the mouse pointer.</p>
</body></html> 
--------------------------------------------------