This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Thứ Ba, 20 tháng 12, 2016

13 Study Tips

Our brain can potentially memorize 2.5 petabytes of information, which is roughly the equivalent of 3 million hours of YouTube videos. In order to use some of that staggering capacity a little more effectively when you study, here are some tips that are based on widely accepted research by neuroscientists and learning experts.



Thứ Ba, 15 tháng 11, 2016

Nạp chồng phương thức - Overloading method

Nạp chồng phương thức - Overloading method

Khái niệm

Tương tự như khái niệm nạp chồng phương thức trong C++, trong java, nạp chồng phương thức (overloading method) là hiện tượng nhiều phương thức có cùng tên, tuy nhiên số lượng tham số hoặc kiểu của tham số trong các phương thức này là khác nhau.
Chú ý: Các phương thức có cùng tên, cùng danh sách tham số, tuy nhiên, kiểu trả về khác nhau không được xem là hiện tượng overload.

Tác dụng và cơ chế của overload

Sử dụng overload trong một chương trình nhằm tăng khả năng đọc của chương trình.
Trình biên dịch sẽ dựa vào tham số được truyền vào phương thức mà quyết định xem sẽ gọi phương thức nào trong danh sách phương thức overload.

Overload với tham số kiểu cơ bản

Theo định nghĩa thì chúng ta có 2 cách để tạo ra hiện tượng overload:
  • Thay đổi số lượng tham số
  • Thay đổi kiểu dữ liệu của tham số

Thay đổi số lượng tham số

Đây là trường hợp khá đơn giản và dễ nhận biết nhất của hiện tượng overload. Các bạn có thể tham khảo đoạn mã nguồn dưới đây:
  1. public class stdio {
  2. private String author;
  3. private static final String address = "stdio.vn";
  4. stdio(){
  5. author = "Kevin La";
  6. }
  7. stdio(String author_name){
  8. author = author_name;
  9. }
  10. public static void main(String [] args){
  11. //Call no arguments constructor
  12. stdio obj = new stdio();
  13. System.out.println(obj.author);
  14. //Call constructor has a argument
  15. stdio obj1 = new stdio("Alice");
  16. System.out.println(obj1.author);
  17. }
  18. }
Trong đoạn mã nguồn trên, tôi đã thực hiện overload constructor của lớp stdio với 1 constructor không có tham số và 1 constructor có chứa 1 tham số.

Thay đổi kiểu dữ liệu của tham số

Khi có cùng số lượng tham số, trình biên dịch sẽ dựa vào kiểu của đối số được truyền vào phương thức, sau đó đối chiếu với kiểu dữ liệu của tham số của phương thức để chọn ra phương thức thích hợp nhất.
Ví dụ:
  1. public class Calculation {
  2. void add(int param1, int param2){
  3. System.out.println(param1 + param2);
  4. }
  5. void add(float param1, float param2){
  6. System.out.println(param1 + param2);
  7. }
  8. public static void main(String [] args){
  9. Calculation obj = new Calculation();
  10. obj.add(10, 10);
  11. obj.add(10.5f, 10.24f);
  12. }
  13. }
Tại dòng số 10, trình biên dịch sẽ gọi phương thức add ở dòng thứ 2 để thực thi do cả 2 tham số truyền vào đều là kiểu int. Giải thích tương tự với dòng số 11.
Tuy nhiên, ở một khía cạnh khác, tôi muốn đề cập tới hiện tượng ép kiểu và lớp bao trong java được sử dụng như thế nào trong nạp chồng phương thức.
Quan sát ví dụ dưới đây:
  1. public class TestOverload {
  2. void method(Integer param){
  3. System.out.println("_Integer invoked");
  4. }
  5. void method(long param){
  6. System.out.println("_long invoked");
  7. }
  8. public static void main(String [] args){
  9. Calculation obj = new Calculation();
  10. obj.add(10);
  11. }
  12. }
Kết quả là:
  1. _long invoked
Tại dòng số 10, khi truyền 10 là một đối số kiểu int, trình biên dịch sẽ kiểm tra xem có phương thức add nào có tham số là kiểu int hay không, tuy nhiên, trình biên dịch không tìm thấy. Thay vào đó, nó tìm thấy 2 phương thức add có tham số là lớp bao của kiểu int là Integer (dòng số 2) và một kiểu rộng hơn kiểu int là long (dòng số 5). Khi ấy, trình biên dịch sẽ ưu tiên gọi phương thức có tham số có kiểu rộng hơn đối số truyền vào thay vì phương thức có tham số là lớp bao của đối số truyền vào.

Overload và quan hệ kế thừa

Nhắc tới quan hệ kế thừa, chúng ta thường đề cập tới mối quan hệ IS-A. Nói cách khác, một đối tượng thuộc lớp con cũng là một đối tượng thuộc lớp cha. Vì thế, khi thực hiện overload phương thức ta hoàn toàn có thể truyền một đối tượng thuộc lớp con vào một phương thức trong danh sách phương thức overload có tham số mang kiểu dữ liệu của lớp cha.
Quan sát ví dụ sau đây:
  1. class Animal{
  2. }
  3. class Dog extends Animal{
  4. }
  5. public class Test_Animal {
  6. void eat(Animal animal){
  7. System.out.println("Animal eats everything");
  8. }
  9. void eat(Dog dog){
  10. System.out.println("Dogs eat meat");
  11. }
  12. public static void main(String [] args){
  13. Test_Animal obj = new Test_Animal();
  14. Animal animal = new Animal();
  15. Dog dog = new Dog();
  16. Animal animal_obj = new Dog();
  17. obj.eat(animal);
  18. obj.eat(dog);
  19. obj.eat(animal_obj);
  20. }
  21. }
Kết quả:
  1. Animal eats everything
  2. Dogs eat meat
  3. Animal eats everything
Kết quả của 2 dòng đầu tiên hoàn toàn dễ hiểu. Tuy nhiên, kết quả của dòng thứ 3 có thể gây lăn tăn cho bạn đọc. Tôi sẽ giải thích điều này như sau:
Hãy quan sát dòng code số 19 và 23.
  • Tại dòng số 19, ta khởi tạo một đối tượng lớp Dog và gán cho một tham chiếu kiểu Animal (hãy nhớ rằng lớp Dog kế thừa từ Animal). Nói cách khác, ta sử dụng một tham chiếu kiểu Animal tham chiếu tới một đối tượng kiểu Dog.
  • Như vậy, tại dòng 23, khi gọi phương thức eat() theo logic thông thường, thì phương thức eat có tham số kiểu Dog sẽ được gọi, nhưng ở đây, trình biên dịch lại gọi phương thức eat có tham số kiểu Animal. Đó là do, tham chiếu animal_obj chỉ xác định được đối tượng nó tham chiếu thực sự tới là đối tượng nào tại quá trình runtime, điều đó đồng nghĩa với, trong khi biên dịch (compile) animal_obj chưa hề biết đối tượng nó thực sự tham chiếu tới trên heap và trình biên dịch chỉ biết về animal_obj có kiểu dữ liệu là Animal. Trong khi đó, việc quyết định chọn phương thức trong danh sách phương thức overload lại được trình biên dịch quyết định trong quá trình compile. Vì thế, trình biên dịch sẽ quyết định phương thức overload được gọi dựa vào kiểu dữ liệu của tham chiếu (Animal), không phải dựa vào kiểu dữ liệu của đối tượng được tham chiếu trỏ tới (Dog).

Chủ Nhật, 30 tháng 10, 2016

change image upload file when have a exists image

html:

<input id="profile-image-upload" class="hidden" type="file">
<div id="profile-image">click here to change profile image</div>


css:

input.hidden {
    position: absolute;
    left: -9999px;
}

#profile-image {
    cursor: pointer;
    background: #8adffb;
  width: 80px;
    height: 80px;
}


js:


$(function() {
    $('#profile-image').on('click', function() {
        $('#profile-image-upload').click();
    });
});

         


https://jsfiddle.net/ksnvphu/vq2u91w6/1/

Thứ Bảy, 29 tháng 10, 2016

How to Convert String to StringBuffer in Java and reverse

How to Convert String to StringBuffer in Java.

String str = "Hello";
StringBuffer sb = new StringBuffer();
sb.append(str);



How to Convert StringBuffer to String in Java

String sb = new StringBuffer();

String str = sb.toString();

Thứ Bảy, 22 tháng 10, 2016

Auto Comment in Eclipse

Class:
- Path: windown/preference/java/code style/code templates/types
/​**
 * ${file_name}
 *
 * version 1.0
 *
 * Date: ${date}
 *
 * copyright
 *
 * Modification Logs:
 * DATE                 AUTHOR          DESCRIPTION
 * -----------------------------------------------------------------------
 * ${date}              PhuNV3              Create
 */​

Method:
- Path: windown/preference/java/code style/code templates/methods



/**
 * @parame ${return_type}
 * @return ${return_type}
 * @throw ${return_type}
 */

Thứ Hai, 10 tháng 10, 2016

Using a Stored Procedure with Output Parameters



A SQL Server stored procedure that you can call is one that returns one or more OUT parameters, which are parameters that the stored procedure uses to return data back to the calling application. The Microsoft SQL Server 2005 JDBC Driver provides the SQLServerCallableStatement class, which you can use to call this kind of stored procedure and process the data that it returns.
When you call this kind of stored procedure by using the JDBC driver, you must use the call SQL escape sequence together with the prepareCallmethod of the SQLServerConnection class. The syntax for the call escape sequence with OUT parameters is the following:
{call procedure-name[([parameter][,[parameter]]...)]}
NoteNote:
For more information about the SQL escape sequences, see Using SQL Escape Sequences.
When you construct the call escape sequence, specify the OUT parameters by using the ? (question mark) character. This character acts as a placeholder for the parameter values that will be returned from the stored procedure. To specify a value for an OUT parameter, you must specify the data type of each parameter by using the registerOutParameter method of the SQLServerCallableStatement class before you run the stored procedure.
The value that you specify for the OUT parameter in the registerOutParameter method must be one of the JDBC data types contained in java.sql.Types, which in turn maps to one of the native SQL Server data types. For more information about the JDBC and SQL Server data types, seeUnderstanding the JDBC Driver Data Types.
When you pass a value to the registerOutParameter method for an OUT parameter, you must specify not only the data type to be used for the parameter, but also the parameter's ordinal placement or the parameter's name in the stored procedure. For example, if your stored procedure contains a single OUT parameter, its ordinal value will be 1; if the stored procedure contains two parameters, the first ordinal value will be 1, and the second ordinal value will be 2.
NoteNote:
The JDBC driver does not support the use of CURSOR, SQLVARIANT, TABLE, and TIMESTAMP SQL Server data types as OUT parameters.
As an example, create the following stored procedure in the SQL Server 2005 AdventureWorks sample database:
CREATE PROCEDURE GetImmediateManager
   @employeeID INT,
   @managerID INT OUTPUT
AS
BEGIN
   SELECT @managerID = ManagerID 
   FROM HumanResources.Employee 
   WHERE EmployeeID = @employeeID
END
This stored procedure returns a single OUT parameter (managerID), which is an integer, based on the specified IN parameter (employeeID), which is also an integer. The value that is returned in the OUT parameter is the ManagerID based on the EmployeeID that is contained in the HumanResources.Employee table.
In the following example, an open connection to the AdventureWorks sample database is passed in to the function, and the execute method is used to call the GetImmediateManager stored procedure:
public static void executeStoredProcedure(Connection con) {
   try {
      CallableStatement cstmt = con.prepareCall("{call dbo.GetImmediateManager(?, ?)}");
      cstmt.setInt(1, 5);
      cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
      cstmt.execute();
      System.out.println("MANAGER ID: " + cstmt.getInt(2));
   }
   catch (Exception e) {
      e.printStackTrace();
   }
}
This example uses the ordinal positions to identify the parameters. Alternatively, you can identify a parameter by using its name instead of its ordinal position. The following code example modifies the previous example to demonstrate how to use named parameters in a Java application. Note that parameter names correspond to the parameter names in the stored procedure's definition:
public static void executeStoredProcedure(Connection con) {
   try {
      CallableStatement cstmt = con.prepareCall("{call dbo.GetImmediateManager(?, ?)}");
      cstmt.setInt("employeeID", 5);
      cstmt.registerOutParameter("managerID", java.sql.Types.INTEGER);
      cstmt.execute();
      System.out.println("MANAGER ID: " + cstmt.getInt("managerID"));
      cstmt.close();
   }
   catch (Exception e) {
      e.printStackTrace();
   }
}
NoteNote:
These examples use the execute method of the SQLServerCallableStatement class to run the stored procedure. This is used because the stored procedure did not also return a result set. If it did, the executeQuery method would be used.
Stored procedures can return update counts and multiple result sets. The Microsoft SQL Server 2005 JDBC Driver follows the JDBC 3.0 specification, which states that multiple result sets and update counts should be retrieved before the OUT parameters are retrieved. That is, the application should retrieve all of the ResultSet objects and update counts before retrieving the OUT parameters by using the CallableStatement.getter methods. Otherwise, the ResultSet objects and update counts that have not already been retrieved will be lost when the OUT parameters are retrieved. For more information about update counts and multiple result sets, see Using a Stored Procedure with an Update Count and Using Multiple Result Sets.

Chủ Nhật, 9 tháng 10, 2016

How to get return value in function sql by Java



Function in sql server
create function checkFunc(
 @MaSP varchar(10)
)
returns int
AS
BEGIN
 declare @kq int
 IF EXISTS(SELECT * FROM SANPHAM WHERE MaSP=@MaSP) set @kq=2
 ELSE 
  BEGIN
   set @kq = 0
  END
 return @kq
END
//execute
select dbo.checkFunc('sp02') 

How to get data by resultset in java

public int checkSanPham() {
  sql = "select dbo.checkFunc(?)";
  connection = connectDB.getConnect();
  int kq = 0;
  try {
   ps = connection.prepareStatement(sql);
   ps.setString(1, "sp02");
   rs = ps.executeQuery();
   if(rs.next()){
    System.out.println(rs.getInt(1));
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    rs.close();
    ps.close();
    connection.close();
   } catch (Exception e2) {
   }
  }
  
  return kq;
 }


SQL.

How to use CallableStatement 

store-proceduce in sql

 
create proc sp_insert 
 @MaSP varchar(10),
 @TenSP varchar(50),
 @MaLoaiSP varchar(10),
 @GiaBan int,
 @SoLuong int
AS
BEGIN 
 --kiem tra Ma loai san pham co ton tai trong bang LOAISP
 IF EXISTS(SELECT TOP 1 MaLoaiSP FROM LOAISP WHERE MaLoaiSP = @MaLoaiSP)
  BEGIN
   -- Kiem tra neu k ton tai ma san pham thi cho insert
   IF NOT EXISTS(SELECT TOP 1 MaSP FROM SANPHAM WHERE MaSP = @MaSP)
    BEGIN
     INSERT INTO SANPHAM (MaSP,TenSP,MaLoaiSP,GiaBan,SoLuong) VALUES(@MaSP, @TenSP, @MaLoaiSP, @GiaBan, @SoLuong)
    END
   ELSE
    BEGIN
     print ('Trung khoa chinh')
    END
  END
 ELSE
  BEGIN
   print ('MaLoaiSP khong ton tai')
  END
END

--execute
exec sp_insert 'sp09','kaka','type001','10','10'

Insert method in Java
public void themSanPham(String maSP, String tenSP, String maLoaiSP,
   String giaBan, String soLuong) {
  sql = "{call sp_insert(?,?,?,?,?)}";
  connection = connectDB.getConnect();
  CallableStatement cs = null;
  try {
   cs = connection.prepareCall(sql);
   cs.setString(1, maSP);
   cs.setString(2, tenSP);
   cs.setString(3, maLoaiSP);
   cs.setInt(4, Integer.valueOf(giaBan));
   cs.setInt(5, Integer.valueOf(soLuong));
   int i = cs.executeUpdate();
   System.out.println(i);
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    cs.close();
    connection.close();
   } catch (Exception e2) {
   }
  }
  
 }

Khi update, or insert data by store-procedure thì khi update, insert thành công thì nó sẽ trả về giá trị 1, fail thì trả về -1. ta lấy giá trị này để xác định là thành công hay chưa.
                        int i = cs.executeUpdate();

System.out.println(i);