Monday, June 17, 2013

Demspter-Shafter theory application

Dempster-Shafer theory in decision making
Let us define
A= “not crowed at all”
B= “normal”
C=“ very crowed”
Then whole Environment E={A,B,C}. 


Vehicle       Message content      Message reputation score

V1                    C                                0.6       
V2                    C                                0.8      
V3                    A                                0.7      
(1) considering V1and V2(@ here means Unknown)
                                m1({C})=0.6           m1({@})=0.4
 m2({C})=0.8        {C}  0.48                 {C}   0.32
 m2({@})=0.2       {C}   0.12                {@}   0.08
Thus  m1+m2({C})=0.48+0.32+0.12=0.92         m1+m2({@})=0.08         

(2)  take V3 into consideration
                                       m1+m2 ({C})=0.92           m1+m2 ({@})=0.08
 m3({A})=0.7               NULL  0.644                          {A}   0.056
 m3({@})=0.3                {C}  0.276                             {@} 0.024
Which means m1+m2+m3({NULL})=0.644,  m1+m2+m3({A})=0.056
                        m1+m2+m3({C})=0.276,  m1+m2+m3({@})=0.024

(3) standardization because of Empty set
Because the m1+m2+m3({NULL})=0.644 should be 0, so after standard process:
m1+m2+m3({A})=0.056/(1-0.644)=0.157
m1+m2+m3({C})=0.276/(1-0.644)=0.775
m1+m2+m3({@})= 0.024/(1-0.644)=0.068
So, confidence interval :
A=[0.157, 0.157+0.068]=[0.157,0.225]
C=[0.775, 0.775+0.068]=[0.775,0.843]

Bad case for Dempster-Shafer theory
two doctor and one patient
1st doctor diagnoses the patient was attacted by tumor with 0.9 propability, and cancer with 0.1;
2nd doctor diagnoses the patient was attacted by concussion with 0.9 propability, and cancer with 0.1;
thus
                                                     m1({tumor})=0.9                  m1({cancer})=0.1
 m2({concussion})=0.9                {NULL}  0.81                   {NULL}   0.09
 m2({cancer})=0.1                       {NULL}   0.09                  {cancer}   0.01

=>    m1+m2({NULL})=0.81+0.09+0.09=0.99         m1+m2({tumor})=0.01  
       
       K= m1+m2({NULL})=0.99
       after standardization:
       m1+m2({tumor})=0.01/(1-K)=1
      Which would be greatly contrary with our intuition.
       So, when K is equal or very close to 1, we should just cancle the standardization

Saturday, June 15, 2013

shared folder between virtualbox and host

1. Create a folder on host like this:
    F:\Shared
2.On VirtualBox Manager:
   Settings-Shared Folders-Add shared folder
   Folder Path: select the one you create above
   Folder Name: use the default one
   tick "Auto-mount"  and "Make permanent" and then save it.
3.Open terminal on Ubuntu on VirtualBox:
   sudo mount -t vboxsf Shared zhiguang/Win_Lin/
   # zhiguang/Win_Lin/ is the corresponding folder for Shared, you should create it before running this command

   then once you put files in  F:\Shared, you can share and edit them in zhiguang/Win_Lin/ immediately.
  

"The system is running in low-graphics mode" for Ubuntu on VM VirtualBox

When I installed Ubuntu Desktop 12.04 LTS into VirtualBox, it prompts "The system is running in low-graphics mode". I tried 6 soutions which solved the problem for other people but not me. Although I do not the exactly intrinsic reason, the following command finally served me well:

sudo apt-get update
sudo apt-get upgrade
sudo reboot
I hope it can also help you.

Tuesday, June 11, 2013

Full screen for ubuntu on VM VirtualBox

I have VM VirtualBox on Win 7, and Ubuntu on VM VirtualBox. By default, the ubuntu could not be displayed as fullscreen. But there is way to make it seem as the ubuntu os is directly installed on your PC hardisk.

1. Installing Guest Additions for full screen

   [Device]--->[Install Guest Addtions]

2. After some configure by the machine, you can open the Guest Additions folder which should be on your Desktop in Ubuntu with name like this: VBOXADDITIONS_#

3. Open terminal, and cd into this folder VBOXADDITIONS_# by:

cd  /media
cd  VBOXADDITIONS_#
sudo sh VboxLinuxAdditions.run

4. Restart the ubuntu.
you can see the ubuntu is enlarged filling up the whole VirtualBox. However the VirtualBox window frame still exists, you can implement the real full screen by HOST+F,  which would make  the VirtualBox window frame  disappear. Another  HOST+F will bring the window frame back again. By default in Ubuntu, the HOST key is the Right Ctrl

Monday, June 3, 2013

ANSI C (2)

12. recursion
#include <stdio.h>

void binary_to_ascii( unsigned int value)

{

   unsigned int quotient;

   quotient=value/10;

   if(quotient!=0)

      binary_to_ascii(quotient);//recursion

   putchar(value%10+'0');



}



value=4267  quotient=?

value=4267  quotient=426

value=426  quotient=42

value=42  quotient=4

value=4  quotient=0

value=42  quotient=4

value=426 quotient=42

value=4267  quotient=426


13.variable parameter

#include <stdarg.h>

float average(int n_values,...)

{

  va_list var_arg;

  int count;

 float sum=0;



 var_start(var_arg,n_values);

for(count=0; count<n_values;count+=1)

{

   sum+=va_arg(var_arg, int);

}

va_end(var_arg);

return sum/n_values;

}


14. array
//(1)

int array[10];

2[array]  ==  *(2+(array)) ==array[2];



//(2)

int array[10], a;

for(a=0;a<10;a=a+1)

     array[a]=0;



int array[10], *ap;

for(ap=array; ap<array+10;ap++)  // more efficient here than array

   *ap=0;

// when   accessing the array elements by a fixed increment,  using pointer would more efficient than that of array index;



//(3)

#include <stdio.h>

#include <stdlib.h>

void my_parameter1(char string[]);

void my_parameter2(char *string);

int main()

{

    char arr[]="zhiguang";

    char *arr1="zhiguang";

    printf("%d\n",sizeof(arr));//9--array: 'z'  'h' ... 'g','\0'

    printf("%d\n",strlen(arr));//8--array:  'z'  'h' ... 'g'

    printf("%d\n",sizeof(arr1));//4--pointer size

    printf("%d\n",strlen(arr1));//8-- the content length the pointer points to

    my_parameter1(arr);//4--pointer size, it is not 9, because it only pass the array as pointer in fact

    my_parameter1(arr1);//4--pointer size

    my_parameter2(arr);//4--pointer size

    my_parameter2(arr1);//4--pointer size

    return 0;

}

void my_parameter1(char string[])

{

   printf("%d\n",sizeof(string));

}

void my_parameter2(char *string)

{

   printf("%d\n",sizeof(string));

}



//(4)

    char arr[]="zhiguang";

    char *arr1="zhiguang";//constant

    arr[2]='w';// ok

    arr1[2]='w';//error, because it is constant

    *(arr1+2)='w';//error, because it is constant



//(5)

int matrix[3][10];

matrix;//pointer, points to the first whole row, 10 elements

matrix+1;//pointer, points to the second whole row, 10 elements

*(matrix+1);// it is an array, also the points to the first element in second row;

*(matrix+1)+5;//pointer, points to matrix[1][5]

*(*(matrix+1)+5);//value, content of matrix[1][5]

*(matrix[1]+5);//value, content of matrix[1][5]

matrix[4,3]==matrix[3];//because of ','



//(6)

int vector[10], *vp=vector;//ok

int matrix[3][10], *mp=matrix;//error;

int (*p)[10]=matrix;//ok, p is a pointer first, points to an array with 10 elements;

int *pi=&matrix[0][0];//ok

int *pi=matrix[0];//ok



//(7)

// if the parameter mat is 2-D array, you can declare the function as:

void fun(int (*mat)[10]);//ok

void fun(mat[][10]);//ok

//however, the following is wrong

void func2(int **mat);//error



//(8)

char  *keyword[5];// an array, each element is a pointer;

char const *keyword[]={"do","for","while"};

// the best way to determine the length of this array is:

sizeof(keyword)/sizeof(keyword[0]);



//(9)
void function0(int);
void function1(int);
void function2(int);
int main(void)
{
   void (*f[3])(int) = {function0,function1,function2};
//f is first an array, each element is a pointer, pointing to a func with an int parameter
   return 0;
}


15. string
//strlen returns an unsigned in, so

if(strlen(x)>strlen(y)) //always right

if(strlen(x)-strlen(y)>=0) //sometimes, error

if(strlen(x)>=10)//always right

if(strlen(x)-10>=0) //sometimes, error


16. void *
//any type pointer could be converted to void*, and that is why

void  *memcpy(void *dst, void const *src, size_t length);

void  *memmove(void *dst, void const *src, size_t length);

void  *memcmp(void *a, void const *b, size_t length);

//...


17. structure
//(1)

struct{

   int a;

   int b;

}x;



struct SIMPLE{

   int a;

   int b;

};

struct SIMPLE x;



typedef struct {

   int a;

   int b;

} Simple;

Simple x;



//(2)

typedef struct{

    int a;

    struct SELF_REF3 *b;//error, there is no SELF_REF3 yet;

    int c;

} SELF_REF3; 



typedef struct SELF_REF3_TAG{

    int a;

    struct SELF_REF3_TAG *b;//OK, there is SELF_REF3_TAG already;

    int c;

} SELF_REF3_TAG; 



//(3)

// the following is error

struct A{

struct B *partner;

};

struct B{

struct A *partner;

}

//the following is correct

struct B;// declare first, even if it is not complete

struct A{

struct B *partner;

};

struct B{

struct A *partner;


18. memory
//(1)

void *malloc(size_t size);

void free(void *pointer);

// if malloc failed, it would return an NULL



//(2)

int *pi;

pi=malloc(25*sizeof(int));

if(pi==NULL)

{

   printf("out of memory!\n");

   exit(1);

}



//(3)

// the pointer passed to free must be generated by malloc, calloc, or realloc, not others;



//(4)

// simplest way of memory leak

for(int i=0; i<10;i++)

    int *p=malloc(25*sizeof(int));

Sunday, June 2, 2013

ANSI C (1)

1. logically delete the command
# if 0

   statements

#endif

2. exit
exit(EXIT_SUCCESS);// stdlib.h

exit(EXIT_FAILURE);// stdlib.h

3.array variable as parameter
array variable, as function parameter, will pass the reference to the function, other kinds of variables will pass the values to the function
4.NUL  NULL
NUL=='\0' ;// the ASCII character 

NULL==0; // the pointer

5. read
#define MAX_INPUT 1000

char input[MAX_INPUT];

int ch;

while(gets(input)!=NULL)//read the line

{

}

while((ch=getchar())!=EOF&&ch!='\n')//read the character 

{

}

6. standard structure
#include <stdlib.h>

int main(void)

{

   return 0;

}

7.typedef  define
typedef char   *ptr_to_char;

define  p_ptr_to_char char*;

8 const pointer
int const *pci ; // you can modify pci, but not *pci

int *const pci;  // you can modify *pci, but not pci;

9 switch
switch(command)

{

  case 'A':

      add_entry();

      break;

  case 'B':

      delete_entry();

     // break;

  case 'C':

      edit_entry();

      break;

}

if command=='B', then delete_entry()  and  edit_entry() would be implemented, because there is no 'break' for case'B'. So pay attention to all the 'break'.
10 sizeof
it is an operator, not function
sizeof(int); // return the length by bytes

sizeof x;

11. pointer to string
//  string length

#include <stdlib.h>

size_t strlen(char *string)

{

   int length=0;

   while(*string++ !='\0')

          length+=1;

   return length;

}


// find the char in strings

#include <stdio.h>

#include<assert.h>

#define TRUE 1

#define FALSE 0

int find_char(char **strings, char value)

{

   assert(strings!=NULL)



   while(*strings !=NULL)

  {

       while(**strings!='\0') 

       {

            if(*(*strings)++==value)

                return TRUE;

       }

       strings++;

  }

   return FALSE;

}



Thursday, May 30, 2013

Java basic

1. in one .java file, there could be as many class as you wish, but there should be at most 1 public class, and this class name should be the same with the file name.

// B.java

class A

{
}

public class B

{
}

class C

{
}

2. for boolean, there are only true and false, no -1, 0,1
in C++, you can write like this:

while(1)

{
}

but in Java, while(1) is wrong, and you can only use:
while (true)

{
}


3. define array
//-1

int num[];

num=new int[3]; //ok;

int num[]=new int[3];//ok

int num[]={1,2,3};//ok

int num[]=new int[]{1,2,3};//ok

int num[]=new int[3]{1,2,3};//error

int num[3]; //error



//-2

int [][] num;

num=new int[2][];

num[0]=new int[3]; //3 elements

num[1]=new int[4]; //4 elements



4. for loop
for(int i=0; i<5; i++)

{
   int a=i; //ok

}

int b=i;// error, i is not defined out of the for loop

5. print hex number
  int hx=0xffffffff;
  int hc=hx<<2;
  System.out.println(Integer.toHexString(hc));
6. default value
int   0;

char '\0'

boolean false

object  null

7.  same name for parameter and member
class Point

{
    int x,y;

    void func1(int x, int y)

   {

      x=x; //parameter to parameter, not what we want

      y=y; //parameter to parameter, not what we want

   }

  

    void func2(int x, int y)

   {

      this.x=x; //parameter x to member x

      this.y=y; //parameter y to member y

   }



}
8. call another construction method
 class Point

{
    int x,y;

    Point(int a, int b)

  {

     x=a;

     y=b;

  }



  Point()

 {

    this(3,4);// call another construct method, and should be the first statement

 }

}

9. static
static methods could call static methods and access the static variable, could not call the non-static methods or access variable;
while  non-static methods  could call static methods and access to static variable.
10.. final variable

In most cases, the final variable should be initialized when it is defined.
class Point

{

    final double PI=3.1415926;

}



one exception:

class Point

{

    final double PI;

    Point()

  {

     PI=3.1415926; 

  }

}

however, if the final variable is also static, you must initialize it when defining it:
static final double PI=3.1415926;

11. call parent method

public class MyAnimal
{
   MyAnimal()
  {
       System.out.println("I am Animal! without parameter");
  }

     MyAnimal(int param)
  {
       System.out.println("I am Animal! with parameter");
  }

}


 class MyFish extends MyAnimal
{

      public MyFish()
   {
      // in this place, super()is called even if you do not write it;

     // so if there is no MyAnimal() at all, error would happen.

     // in that case, you could use  super(0) if  MyAnimal(int param) is defined

     // or you could redifine the MyAnimal() 

      System.out.println("I am fish! without parameter");
   }

    public MyFish(int param)
   {
      //in this place, still super(),not super(0), is called even if you do not write it;

     // to call MyAnimal(int param), should write super(0) in this place

     // 0 represents the parameter, you can use anyone you like
      System.out.println("I am fish! with parameter!");
 
 } 

    public void breathe()
    {
          super. breathe(); // use this call  parent  breathe();

          System.out.println("Fish breathe!");

    }

}
12. polymorphic

class Parent
{
    void fun1()
  {
     System.out.println(" Parent 1");
  }
   void fun2()
  {
     System.out.println(" Parent 2");
  }
}

class Child extends Parent
{
  
   void fun1()
  {
     System.out.println(" Child 1");
  } 
  public static void main(String[] args)
 {
       Child cd=new Child();
       Parent pt=cd;//Ok
       pt.fun1();    // result: Child 1, because of new Child();
       pt.fun2();    // result: Parent 2, because Child dose not override fun2()

       Parent pt1=new Parent();//Ok
       Child cd1=pt1;//error, can not convert from Parent to Child
 }
}


Wednesday, May 29, 2013

read and write file in Java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Read_Write {

 public static void main(String[] arg) throws IOException{
 String fileName = "data/input/tweet_2012_06";
 BufferedReader in = new BufferedReader(new FileReader(fileName));
 String str;

 FileWriter fstream = new FileWriter("data/output_tweet_2012_06.txt");
 BufferedWriter out = new BufferedWriter(fstream);

 int counter = 0;
 while ((str = in.readLine())!= null){
  System.out.println(counter+"  " + str);
  out.write(str);
  counter++;

 }
    System.out.println("counter is "+counter);
  out.close();
 in.close();
 }
}

SendMessage from modaless dialog to the view in SDI without document/view structure support--another method

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to send the "view" a message

you can realize it like this:

1. in ChildView.cpp
#include "ModalLessDlg.h"

void CChildView::OnModalLess() // show the modalless dialog
{

    CModalLessDlg* instance = new CModalLessDlg(this);
    instance->Create(CModalLessDlg::IDD,this);
    instance->PARENT = this;  
    instance->ShowWindow(1);

}


2. in ModalLessDlg.h

#include "ChildView.h"



public:

CChildView *PARENT;



3. in ChildView.h

public:

void     setDisplayText(CString src);

private:

CString   displayText;


4. in ChildView.cpp

CChildView::CChildView(): displayText(_T("zhiguang"))
{
}



void CChildView::setDisplayText(CString src)
{
    displayText=src;
    Invalidate(TRUE);
}



void CChildView::OnPaint() // show different results of image 
{


  CPaintDC dc(this); // device context for painting   
  CRect rect;
  GetClientRect (&rect);
  dc.DrawText (displayText, -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER);

}



5. in ModalLessDlg.cpp

void CModalLessDlg::OnBegin() // 
{

  CString str_sent="OnBegin is running!";
  PARENT->setDisplayText(str_sent);
}




that is all.

it is using ChildView as one parameter to construct the modaless dialog, then you can easily use the ChildView and its members to change the client area.



Tuesday, May 28, 2013

SendMessage from modaless dialog to the view in SDI without document/view structure support

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to send a text to the "view"

you can realize it like this:

1. in MainFrm.h, there is one protected variable:

protected: CChildView   m_wndView;


change it as public variable:

public: CChildView   m_wndView;


2. in ModalLessDlg.cpp:

#define WM_MY_DOSOME (WM_USER+1)


3. in ModalLessDlg.cpp:

void CModalLessDlg::OnBegin() // 
{
 // TODO: start
    
  CMainFrame   *pFrame=(CMainFrame*)(AfxGetApp()->m_pMainWnd); 
  char buf[]="I LOVE YOU";
 (pFrame->m_wndView).SendMessage(WM_MY_DOSOME,(WPARAM)buf,0);

}


4. In ChildView.h, add the following:

afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);//before DECLARE_MESSAGE_MAP()


5. in ChildView.cpp, add the following:

BEGIN_MESSAGE_MAP(CChildView, CWnd)
 // ...
    ON_MESSAGE(WM_MY_DOSOME,OnMyMessage)  //only need to add this line

 //...
END_MESSAGE_MAP()



//then realize the response function:

LRESULT CChildView::OnMyMessage(WPARAM iParam1,LPARAM iParam2)
{
   
 char *buf=(char *)iParam1; 
 CString str;
 str.Format("%s",buf);
 MessageBox(str);
 return 0L;

}


the function is only a test to see whether you can receive the text or not, you can also show it in the client area of the view through Invalidate() again in this OnMyMessage function.



modaless dialog refresh the view in SDI without document/view structure support

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to refresh the "view"

you can realize this like this:

1. in MainFrm.h, there is one protected variable:

protected: CChildView   m_wndView;

change it as public variable:

public: CChildView   m_wndView;

2. add one public variable for the ChildView.h:

public: int dlg_fresh;

initialize it in ChildView.cpp:

CChildView::CChildView()
{
 dlg_fresh=0;
}

3. in the response function of modalless dialog button, write like this:

//ModalLessDlg.cpp 

void CModalLessDlg::OnBegin() // stard the thread
{
 CMainFrame   *pFrame=(CMainFrame*)(AfxGetApp()->m_pMainWnd); // get the mainframe
 (pFrame->m_wndView).dlg_fresh=1; //set the flag
 (pFrame->m_wndView).Invalidate(); // refresh the view in the ChildView

}

4. in the ChildView.cpp, implement the OnPaint() like this:

//ChildView.cpp

void CChildView::OnPaint()
{
 CPaintDC dc(this); // device context for painting
 CRect rect;
 GetClientRect (&rect);
 if(dlg_fresh==0)
 {
  dc.DrawText (_T ("it is not the modaless dlg refreshing!"), -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER); 
 }
 else
 {
    dc.DrawText (_T ("it is the modaless dlg refreshing!"), -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER); 
       dlg_fresh=0;
 }
}


Monday, May 27, 2013

kernel event object and thread in MFC

one button to create the kernel event object and worker thread, and the other button to signal the event and terminate the thread.



UINT __cdecl MyThreadProc(LPVOID lpParameter) // thread generation function
{
   CEvent* pEvent = (CEvent*)(lpParameter);
   VERIFY(pEvent != NULL);
   // Wait for the event to be signaled
   ::WaitForSingleObject(pEvent->m_hObject, INFINITE);
   // Terminate the thread
   ::AfxEndThread(0, FALSE);
   return 0L;
}


void CModalLessDlg::OnBnClickedButton1() // start the thread
{
 // TODO: start
   pEvent = new CEvent(FALSE, FALSE);
   // Create a thread that will wait on the event
   //CWinThread* pThread;
   pThread = ::AfxBeginThread(&MyThreadProc, pEvent, 0, 0, CREATE_SUSPENDED, NULL);
   pThread->m_bAutoDelete = FALSE;
   pThread->ResumeThread();
  
   // show the status of thread
   CString st1="Thread started";
   SetDlgItemText(IDC_EDIT1, st1);
}


void CModalLessDlg::OnBnClickedButton2() // setevent and terminate the thread
{

    pEvent->SetEvent();
   // Wait for the thread to consume the event and return
    ::WaitForSingleObject(pThread->m_hThread, INFINITE);
    delete pThread;
    delete pEvent;
 // show the status of thread
    CString st2="Thread Terminated!";
    SetDlgItemText(IDC_EDIT1, st2);
}

edge detection based on sobel operator in MFC

void CChildView::OnEdge() // edge detection based on Sobel operators
{

 {
 int operx[3][3]={-1,0,1,-2,0,2,-1,0,1};//Sobel operators
 int opery[3][3]={1,2,1,0,0,0,-1,-2,-1};//Sobel operators
 int i,j;
 int p=0;
 int smx=0,smy=0;
 //CImage img_tem;
 //img_tem.Create(img_width,img_hight,24,0);
 for(i=0;i<img_hight;i++)
 {
  for(j=0;j<img_width;j++)
  {
   COLORREF cf = MyRGB(0,0,0);
   img_final.SetPixel(j,i,cf); //img_final is a member of this class, this is to reset it to zeros
         
  }
 }

 for(i=0;i<img_hight-2;i++)
 {
  for(j=0;j<img_width-2;j++)
  {
            smx=0;
   smy=0;
   for (int m=0; m<3; m++)
   {
      for (int n=0; n<3; n++)
      {  
      COLORREF rgb=img_new.GetPixel(j+n,i+m);
         int p=MyGetRValue(rgb);
                  smx=smx+p*operx[m][n];
                  smy=smy+p*opery[m][n];
      }
   }
   float G=smx*smx+smy*smy;
   int GD=(int)sqrt(G);
           
   if(GD>100) // threshold to determine whether it is an edge
   {
         COLORREF cf = MyRGB(255,255,255);
         img_final.SetPixel(j+1,i+1,cf);
 
   }
  }
 }
  
   Invalidate(); //call the OnPaint to show the result

}


basic image processing in MFC

Everybody knows that MFC+OpenCV is very convenient for image processing. But how about only using MFC? Most of the operation for image processing is based on bitmap in previous MFC version, say VC++6.0.

In VS2008, there is already CImage class, which could greatly facilitate the image processing.
 (1) get basic info of one image
  #include <atlimage.h>
  ...
  CImage img; //image object
  img.Load(FilePathName); // load a local image
  img_hight=img.GetHeight();//get hight
  img_width=img.GetWidth();//get width
  img_bits=img.GetBPP();//get bit counts for each pixel, say 8,24,32...
  COLORREF rgb=img.GetPixel(10,10);// get the pixel color
 

  CImage img_new; //another image object
  img_new.Create(img_width, img_hight, 24, 0);//create a image with the same size
  img.SetPixel(10,10,rgb);// set the pixel color

(2) get the r,g,b value from the COLORREF value:

#define MyGetRValue(rgb) ((BYTE)(rgb))
#define MyGetGValue(rgb) ((BYTE)(((WORD)(rgb)) >> 8))
#define MyGetBValue(rgb) ((BYTE)((rgb)>>16))

 COLORREF rgb=img.GetPixel(j,i);
 int r = MyGetRValue(rgb);
 int g=MyGetGValue(rgb);
 int b=MyGetBValue(rgb);

(3) convert the 24bit color image into gray image:

 #define MyRGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)))

 BYTE cl = (BYTE)(0.299 * r + 0.587 * g + 0.114 * b);
 int clr=(int)cl;
 COLORREF cf = MyRGB(clr,clr,clr);
  img_gray.SetPixel(j,i,cf);


 
 

Sunday, May 26, 2013

read and write .ini file in MFC

Sometimes we need to configure the controls on the dialog based on the .ini and we may also need to save the final control values on the dialog to the same file in MFC, we can do that like this:

user.ini
[initialize]                   ;section name
m_listbox=0               ;key and int value       
name=zhiguang          ;key and string value


(1) example to initialize the controls on the dialog

BOOL CModalDlg::OnInitDialog() // read values from the .ini file
{
 
  CDialog::OnInitDialog();
  CString  iniFilePath;
  iniFilePath=".//ini//user.ini";
  // read ini for listbox
  int  list_pos; 
  list_pos=GetPrivateProfileInt("initialize","m_listbox",0,iniFilePath);
  m_listbox.AddString(_T("MIT"));
  m_listbox.AddString(_T("I.PAC"));
  m_listbox.AddString(_T("CASEM"));
  m_listbox.AddString(_T("Genric Power"));
  m_listbox.SetCurSel(list_pos);
 
  // read ini for edit
  CString  str_edit; 
  GetPrivateProfileString("initialize","IDC_EDIT1","",str_edit.GetBuffer(MAX_PATH),MAX_PATH,iniFilePath);
  SetDlgItemText(IDC_EDIT1, str_edit);

  // read ini for checkbox
  int  check_val; 
  check_val=GetPrivateProfileInt("initialize","m_check",0,iniFilePath);
  m_check.SetCheck(check_val);
 
  // read ini for radio
  int  radio_val; 
  radio_val=GetPrivateProfileInt("initialize","IDC_RADIO1",0,iniFilePath);
  if(radio_val==1)
  ((CButton *)GetDlgItem(IDC_RADIO1))->SetCheck(TRUE);
  else
  ((CButton *)GetDlgItem(IDC_RADIO2))->SetCheck(TRUE);

  return TRUE;
}


(2) example to update the control values on the dialog back to the same .ini file.

void CModalDlg::OnBnClickedOk() //save the values to the .ini file
{
 CString  iniFilePath;
    iniFilePath=".//ini//user.ini";
 //write ini for listbox
 int list_pos=m_listbox.GetCurSel();
 CString str_pos;
 str_pos.Format("%d",list_pos);
 WritePrivateProfileString("initialize","m_listbox",str_pos,iniFilePath);
 //write ini for editbox
 CString str_edit;
 GetDlgItemText(IDC_EDIT1, str_edit);
 WritePrivateProfileString("initialize","IDC_EDIT1",str_edit,iniFilePath);
   // read ini for checkbox
    int  check_val; 
    check_val=m_check.GetCheck();
 CString str_check;
 str_check.Format("%d",check_val);
 WritePrivateProfileString("initialize","m_check",str_check,iniFilePath);
   // read ini for radio button
    int  radio_val; 
    radio_val=((CButton *)GetDlgItem(IDC_RADIO1))->GetCheck();
 CString str_radio;
 str_radio.Format("%d",radio_val);
 WritePrivateProfileString("initialize","IDC_RADIO1",str_radio,iniFilePath);

 OnOK();
}


To read the file, we have  GetPrivateProfileString and GetPrivateProfileInt for String and Int values, to write the file , we only have WritePrivateProfileString, so we should convert the format of the value into CString first before writing

modal and modalless dialog in MFC

For both cases, you should create one dialog template, which could be done in the resource explorer

Modal Dialog
1. then create one class ModalDlg for modal dialog using this dialog template, and the CModalDlg.cpp and CModalDlg.h would be generated.

2. in the file where you want to show the modal dialog, first include the "ModalDlg.h", then in this file, you could use the following code :

void CChildView::OnModal() // show the modal dialog
{
 CModalDlg dlg;
 dlg.DoModal();
}


ModalLess Dialog

1. then create one class ModalLessDlg for modalless dialog using this dialog template, and the CModalLessDlg.cpp and CModalLessDlg.h would be generated.

2. in the file where you want to show the modalless dialog, first include the "ModalLessDlg.h", then in this file, you could use the following code :

void CChildView::OnModalLess() // show the modalless dialog
{
 CModalLessDlg *lsdlg=new CModalLessDlg;
 lsdlg->Create(IDD_DIALOG2,NULL);//IDD_DIALOG2 is the ID of dialog template you created
 lsdlg->ShowWindow(SW_SHOW);

 }


For both dialogs, if you want to initialize some parameters for all the controls on them, you can do that by overriding the  BOOL CModalDlg::OnInitDialog(){}  or  BOOL CModalLessDlg::OnInitDialog() {}





Saturday, April 13, 2013

reserved keywords in mysql

today,  I created 3 mysql tables for my facebook app, to save user "status" "comment" "like" infomation.

I did not think too much before i created the 3 tables with name: status, comment, like respectively.
then, I found I could insert content into status and comment table while always failed the like table .

/*php code*/
mysql_query("INSERT INTO like (object_id,user_id,type) VALUES ('$comment_id', '$like_user_id','comment')");//error

I did know the 'like' is one mysql reserved keyword, however, i did not think that way at that very moment

then when I changed the table name from 'like' to 'likes', then it works.
/*php code*/
mysql_query("INSERT INTO likes (object_id,user_id,type) VALUES ('$comment_id', '$like_user_id','comment')");//correct //or mysql_query("INSERT INTO my_like (object_id,user_id,type) VALUES ('$comment_id', '$like_user_id','comment')");//correct
Here is the official mysql reserved keyword.
http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html

however, I think it's safe to name your table or column as: my_xxx.

Tuesday, April 9, 2013

facebook fql format

pay attention to the "+" in the fql


 // 1.
 $access_token="XXX";
 $url0 = "https://graph.facebook.com/"
    . "fql?q=SELECT+message,time,status_id+FROM+status+WHERE+uid=10000+"
    . "AND+time>=1365481000+AND+time<=1365483292+LIMIT+0,1"
    . "&access_token=" . $access_token;

 $res0 = json_decode(file_get_contents($url0));


//2.

$url1 = "https://graph.facebook.com/"
                   . "fql?q=SELECT+fromid,time,text,object_id+FROM+comment+WHERE+object_id+"
                   ."IN+(SELECT+status_id+FROM+status+WHERE+uid=$uid)+"
                   ."AND+time>=$tm1+AND+time<=$tm2"
                   . "&access_token=" . $access_token;
$res1 = json_decode(file_get_contents($url1));

get realtime update of user infomation using facebook app

you can configure the framework according to the official document at:

http://developers.facebook.com/docs/reference/api/realtime/

if succeed, you can get the infomation like:

{ "object": "user", "entry":
    [    
         { "uid": 1335845740,      
           "changed_fields":
               [ "status" ],
           "time": 1365483292 }
   ]
}

It means the user(whose id is 1335845740 ) updated his status (most likely to post a new status).

what I want to say is, the 'time' 1365483292 you got is not exactly correct.

I use fql to crawl the status data and get the status created date is around 1365483292, but not exactly the same, say 1365483291. However, for some other times, they are  same.

So, if you got the update info as above, you should pay attention that "time" infomation.
if you still want to use this "time" info to crawl some latest data, you'd better use:


WHERE time BETWEEN $time-1 AND $time  // or something similar 

issue on inserting text or varchar values on mysql

when we insert text or varchar values into tables on mysql, we usually use the following format

mysql_query("INSERT INTO user (userid, name, gender) VALUES ('$user_id', '$user_name', '$user_gender'");

instead of

mysql_query("INSERT INTO user (userid, name, gender) VALUES ($user_id, $user_name, $user_gender");


yes, the difference is '$user_name' and  $user_name.

the advantage of former is that:
if your name is zhiguang cao (yes, there is one blank space between given name and surname )

when you insert  $user_name, it will be considered as two items: zhiguang  and cao respectively, and thus the result would not be correct generally.

while if you insert '$user_name', it will be considered as one item: 'zhiguang cao' would be one item instead of two.

I took me hours to find this problem although it seems not a big deal. thanks chenbo's help!

Thursday, April 4, 2013

tranverse files under one directory using C++ on ubuntu

#include <string>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include </usr/include/i386-linux-gnu/sys/types.h>
#include </usr/include/i386-linux-gnu/sys/stat.h>
#include <dirent.h>
#include <errno.h>
using namespace std;
int main(void)
{
   DIR *dp;
   int n=0;
   int len=0;
   struct dirent *dirp;
   string str0;
   dp=opendir("/home/HSS/topic_modeling/topic_1/");

   while((dirp=readdir(dp))!=NULL)
   {  
      str0=string(dirp->d_name);
      len=str0.size();
      if( len>4)
// for txt files and this will filter out the '.' and '..' file
      {
            // do what you want to do !
      }
   }
return 0;
}

windows+apache+mysql+php(WAMP) for 64 bits

1. widows:
      we process this on 64 bit windows 7:
2. apache:
     I chooose: httpd-2.4.4-win64.zip
     create one folder:   C:/apache64,  unzip the file to that directory, and thus we can access httpd.conf file by :

   C:/apache64/conf/httpd.conf .
  
   modify this file:

   ServerRoot "C:/apache64"
   ServerName localhost:80
  DocumentRoot "D:\CZG\PHP_WEB"
  <Directory "D:\CZG\PHP_WEB">
   DirectoryIndex index.html index.htm index.php
   ScriptAlias /cgi-bin/ "C:/apache64/cgi-bin/"

 thus, when you input: http://localhost in your broswer, it will redirct you to D:\CZG\PHP_WEB

add your apache to system path by:
add  C:/apache64/bin/ to the path variable of your system.

then you can use the following on your cmd:
httpd.exe -k install
httpd.exe -k start


finally  you open bin folder and double click the ApacheMonitor.exe file.
If you input: http://localhost in your broswer now, it will display: it works!

when you run into problems with this, such as : the requested operation has failed.
you can using the following command line to check the reason:
httpd.exe -w -n "Apache2" -k start
it will give the specific error

3. php:
i choose: php-5.4.3-Win32-VC9-x64.zip
and unzip it to:  C:/php .
then in C:/apache64/conf/httpd.conf to add this or make it effective


LoadModule php5_module "C:/php/php5apache2_4.dll"   // for this case, is 2_4 not 2_2
AddType application/x-httpd-php .php
 # configure the path to php.ini
PHPIniDir "C:/php"

then rename the file php.ini-development to php.ini, and add or  make the following effective
extension_dir = "C:/php/ext/"
allow_url_fopen = Off
extension=php_gd2.dll
extension=php_mysql.dll;
extension=php_zip.dll
Set sendmail from e-mail address:
sendmail_from =xxx@gmail.com

Some settings for MySQL:  
mysql.default_port = 3306
mysql.default_host = localhost


Some settings for session:
session.save_path = "C:/my_session" 
//to same sesssion file and creat one folder like C:/my_session

4.mysql:

i choose: mysql-essential-5.1.68-winx64.msi
install it by defauly, and do not forget the user name and passwork during the installing process
i choose username: root, password: 1234(anyone you like, as long as you can remeber)

then in the D:\CZG\PHP_WEB, create one test.php with the following content:

<?php
$con = mysql_connect("localhost:3306","root","1234"); if (!$con)   {   die("Could not connect: " . mysql_error());   }   else   {     echo "it is connected to database!";   } mysql_close($con);
?>

then run it @ http://localhost/test.php

in my case, I can user localhost:3306 or 127.0.0.1:3306   but when I remove :3306, it dose not work.
i know the port for mysql is 3306, but I am sure, for my previous 32 bit version configuration, it dose not need to add the port in the php code. 

one more thing: for windows 7, the database would be by default stored in:

C:\ProgramData\MySQL\MySQL Server 5.1\data

you can modify this directory at:

C:\Program Files\MySQL\MySQL Server 5.1\my.ini
datadir="C:/ProgramData/MySQL/MySQL Server 5.1/Data/"


5. workbench

to better visualize the mysql  database, I installed workbench:mysql-workbench-gpl-5.2.42-win32.msi.
for first time, it needs the same user name and password, then you can see the table contents of your database like using excel.



using filezilla for amazon ubuntu server

when you create ubuntu instance on amazon ec2, you will get user name(say, root or ec2-user) and one .pem file
then in your local ubuntu, you can access the server by:
chmod 400 xxx.pem    #make this file publicly visible
ssh -i xxx.pem ec2-user@xxx.xxx.xxx.xxx
# xxx.xxx.xxx.xxx  is the ip address amazon assigned to you
thus you can access the ubuntu server on amazon.
however, for transfering files between local machine and server, we usually use filezilla.
the default internet access directory is  /var/www/html  however, the general user do not have rights to upload files directly to this folder, so we can:
sudo chmod 777  /var/www/html 
thus we can use filezilla to transfer files directly to that folder.
after installing filezilla, we should configure first:
1)open the site manager->new site. then we name it as something you like, and for host, input the ip address, for port:input 22, for protocol: choose SFTP-SSH file...    for logon type: normal   for user: input your user name
2)edit-> settings->connection->SFTP, press: add keyfile. thus select your pem file, and  will convert it to ppk file.
after that, back to step 1), press "connect", then your local machine would connect to your amazon ubuntu server. You can now use mouse to drag files from your local machine to the server and vice versa.

post on user's timeline by app

<?php
  session_start();
  require_once('AppInfo.php');
  require_once('utils.php');
  require_once('sdk/src/facebook.php');
  
  $facebook = new Facebook(array(
   'appId'  => 'APP_ID',
   'secret' => 'APP_SECRET',
  ));

$app_token="XXXXXX"; //long life access_token should be better
 $attachment = array
 (
 "access_token"=>"$app_token",
 "message" => "Interesting App",
 "name" => "MyApp",
 "caption" => "About MyApp",
 "link" => "http://facebook.com/",  //your own url
 "description" => "Awesome App",
 "scope" => "publish_stream"
 );
 
 $result = $facebook->api("/USER_ID/feed","POST",$attachment);
print_r($result );
 ?>

send request from app to user using javascript


<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:fb="https://www.facebook.com/2008/fbml">
  <head>
    <title>MyNTU Request</title>
  </head>
  <body>
    <div id="fb-root"></div>

    <script src="http://connect.facebook.net/en_US/all.js"></script>

    <script>

      FB.init({
        appId  : 'xxxxxxxxxxx',    //your app id
        frictionlessRequests: true
      });
  
      FB.ui({method: 'apprequests',
          message: 'My Great Request',
          to: 'xxxxxx'                    //user id you want to send to
        }, requestCallback);
      function requestCallback(response) {
        // Handle callback heres
      }
    </script>
  </body>
</html>

send request from app to user using php


<?php

  $app_id = "YOUR_APP_ID";
  $app_secret = "YOUR_APP_SECRET";
  $token_url = "https://graph.facebook.com/oauth/access_token?" .
    "client_id=" . $app_id .
    "&client_secret=" . $app_secret .
    "&grant_type=client_credentials";
  $app_access= file_get_contents($token_url);
  $app_access_token = json_decode($app_access, true);
  $user_id ="USER_ID";
  $apprequest_url ="https://graph.facebook.com/" .
    $user_id .
    "/apprequests?message='INSERT_UT8_STRING_MSG'" .
    "&data='INSERT_STRING_DATA'&"  .  
    $app_access_token . "&method=post";
  $result = file_get_contents($apprequest_url);
  $obj = json_decode($result, true);
  print_r($app_access_token);
  print_r($obj);
  
?>

Tuesday, April 2, 2013

get user realtime update for your app

First, you should go to your app setting page in facebook developer home page.

when you reach the app setting panel or dashboard,

choose  Settings-Realtime Updates

then in the dashboard, you can
1) in fields: input some the field you like, such as hometown_location
2) in callback: input your app url
    if your app url is http://myapp.com
    and your file to preocess the realtime update is  update.php
    then you should input: http://myapp.com/update.php
  
3) in verify token, you should input one string you like, e.g.: myfacebookapp123

save the changes.

Then you should prepare the update.php file on your server, you could copy the following code to your update.php file

<?php

  $verify_token = myfacebookapp123';
  if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['hub_mode'])
    && $_GET['hub_mode'] == 'subscribe' && isset($_GET['hub_verify_token'])
    && $_GET['hub_verify_token'] == $verify_token) 
 {
      echo $_GET['hub_challenge'];
   } else if ($_SERVER['REQUEST_METHOD'] == 'POST')
   {
    $post_body = file_get_contents('php://input');
    $obj = json_decode($post_body, true);
    $myFile = "testFile.txt";
    $fh = fopen($myFile, 'a+') or die("can't open file");
    $stringData = "Something updates, pls go to get it!\n";
    fwrite($fh, $stringData);
    fclose($fh);
  }
?>

Now you can go to facebook and modify one user's(who has authened your app before) hometown. after 1-2 minutes, your server could generate one testFile.txt with "Something updates, pls go to get it!" This post dose not analyze the content in  $obj . it is something like this:
  /*
  {
  "object": "user",
  "entry": [
    {
      "uid": 1335845740,
      "changed_fields": [
        "name",
        "picture"
      ],
      "time": 232323
    }, {
      "uid": 1234,
      "changed_fields": [
        "friends"
      ],
      "time": 232325
    }
  ]
}
  */

you can try to get them respectively use php. One thing we should pay attention to is that: through realtime update, we can only get the which filed has been updated, such as hometown. but we do not know what is the user's latest howntown unless we write codes to crawl that data.

get the access token and extend its lifetime for your app

1. the basic idea is : use your 'state' get 'code', then use 'code' get 'access_token', finally use current access_token to get the 60-day long access-token. thus, even the user is not logged into  facebook, you can still access his data:

<?php 
  
   $app_id = "YOUR_APP_ID";
   $app_secret = "APP_SECRET";
   $my_url = "YOUR_URL";
   session_start();
  
   $code = $_REQUEST["code"];
   if(empty($code)) {
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
     $dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . $_SESSION['state'] . "&scope=user_birthday,user_hometown, read_stream, friends_likes, email, user_status, publish_stream, status_update,offline_access";
     header("Location: " . $dialog_url);
  }
  
   if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;
     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     $_SESSION['access_token'] = $params['access_token'];
     $graph_url = "https://graph.facebook.com/me/feed?access_token="
       . $params['access_token'];
     $user = json_decode(file_get_contents($graph_url),TRUE);//get all the data related with 'feed'
  echo "</br>";
  echo "<h3>Your infomation are:</h3>";
  echo "</br>";
  print_r($user);
  echo "</br>";
  echo "</br>";
   }
   else {
     echo("The state does not match. You may be a victim of CSRF.");
   }

 ?>


2. use the short-term token to get the 60-day access token

<?php
 $my_token_url="https://graph.facebook.com/oauth/access_token
    grant_type=fb_exchange_token&          
    client_id=YOUR_APP_ID&
    client_secret=YOUR_APP_SECRET&
    fb_exchange_token=YOUR_CURRENT_ACCESS_TOKEN";

 header("Location: " . $my_token_url);

?>

If your current token is not expired yet, you are likely to get the same token but with longer life(60 days) you can also see how long it will last every time you refresh the page.

redirect out of iFrame

In that case, you should use:
echo "<script>self.parent.location.href = 'YOUR_URL'</script>";
instead of

echo "<script>location.href = 'YOUR_URL'</script>";

But first, you should realize that you are located in one iFrame then.

all the 'scope' options in facebook app development

our app always ask for user permission, but you should type the correct offcial permission in the scope parameter. e.g

    function authUser() {
        
        FB.login(checkLoginStatus, {scope:'user_hometown, read_stream, friends_likes, email, user_status, publish_stream, status_update,offline_access'});
      }
    

if you want get the user's hometowm permission, you should type user_hometown instead of just hometown, otherwise you can never get this permission.
all below is all the latest scope options supported by facebook
   /*
   Supported scopes: ads_management create_event create_note email export_stream friends_about_me friends_activities friends_birthday 

   friends_checkins friends_education_history friends_events friends_games_activity friends_groups friends_hometown friends_interests 

   friends_likes friends_location friends_notes friends_online_presence friends_photo_video_tags friends_photos friends_questions 

   friends_relationship_details friends_relationships friends_religion_politics friends_status friends_subscriptions friends_videos 

   friends_website friends_work_history manage_friendlists manage_notifications manage_pages offline_access photo_upload publish_actions 

   publish_checkins publish_stream read_friendlists read_insights read_mailbox read_page_mailboxes read_requests read_stream rsvp_event share_item sms 

   status_update user_about_me user_activities user_birthday user_checkins user_education_history user_events user_games_activity user_groups user_hometown 

   user_interests user_likes user_location user_notes user_online_presence user_photo_video_tags user_photos user_questions user_relationship_details user_relationships
 
   user_religion_politics user_status user_subscriptions user_videos user_website user_work_history video_upload xmpp_login
   */
  

user login using FB for facebook app development

All you need to do is to replace the Uppercase Variables with your own real parameter. If the user dose not log into facebook, then it will redirect the user to the facebook login page; if the user user has loged into facebook but not authened your required permission, then it will prompt the user permission pannel. if the uer has loged into facebook and authened all your permission, it would direcly redirect the user into your app;




 
  
    YOUR_APP_NAME
  
  
   
    

Standard C++

1. <string> is the C++ version for string type, <cstring> is the C++ version for string in C, <string.h>is the C version;

2.
 
   // In C, it is correct: 
         int *pr=NULL;
   // in C++, it is correct:
         int *pr=0;
   // if you want keep
          int *pr=NULL;
   //in C++ code, you should  #include<cstdlib>
3.  // 1)
 
            int a=10;
            int b=20;
            int const  *pt=&a; // same as: const int  *pt=&a ;
            *pt=11;  //error
             pt=&b;  // correct
      //2) 
 
            int a=10;
            int b=20;
            int *const  pt=&a;
            *pt=11;  //correct
             pt=&b;  // error
4. conversion between string and char
 
      //1)
          char * ch="caozhiguang";
          string str(ch); // from char to string;
           string str=ch; // same with above
      //2)
           string str("caozhiguang");
           char *ch;
           ch=str.c_str(); // from string to char;
5. avoid repeating include, also a  better file framework(at least for me)
 
    //Zhiguang.h
    #include <string>
    using namespace std;
    #ifndef  ZHIGUANG_H
    #define ZHIGUANG_H
       Class Zhiguang
       {
             public:
                     Zhiguang();
                     Zhiguang(string the_name, string the_addr);
                     string getinfo();
             private:
                     string name;
                     string address;
                     static double salary;
        }
    #endif

  //Zhiguang.cpp
  //you'd better initialize the static var in this file
  #include  "Zhiguang.h"
  salary=3500; //initialize the static var;
  Zhiguang::Zhiguang() { }
  Zhiguang::Zhiguang(string the_name, string the_addr)  { }
  string Zhiguang::getinfo(){    }

  //main.cpp
  #include "Zhiguang.h" // no need to include the cpp file
  using namespace std;
  int main()
  {
     Zhiguang zg;
    // do whatever you want
   }

6.  create one object for the class

 
   //1)  
         Zhiguang zg;
         zg.name;
         zg.address;
         zg.getinfo();
   //2) 
         Zhiguang zg=Zhiguang();
         zg.name;
         zg.address;
         zg.getinfo();

   //3)
         Zhiguang *zg=new Zhiguang();
         zg->name;
         zg->address;
         zg->getinfo();

7. default constructor needed to initialize members of built-in type

 
    Zhiguang() : name("zhiguang"), address("Singapore"){  }

   Note: for the real initialize order, it would be based on the declaration order in the class declaration.
   e.g:  
 
                private:
                     string address;
                     string name;
            in this case, the default constructor would initialize the address first even it is listed in the second  place in the constructor.

8.  1) if the member method is const, it means it can not change the object's member variable;
     2) for const member, there should be keyword const both in declaration and definition;
     3) the const object can only use its const member, while non-const object can access both const and non-const members;
     4) for non-const member method, this could not be changed while *this could;
          for const member method,  both this and *this could not be changed.