Exemple #1
1
void lcd_value_int(uint8_t var)
{
    char temp[10];
    itoa(var,temp,10);
    lcd_puts(temp);
}
const char* module_name(uint8_t index, char* buf)
{
    return itoa(index, buf, 10);
}
Exemple #3
0
int main(void)
{
    char buffer[7];
    int  num=134;
    unsigned char i;
    
    
    DDRD &=~ (1 << PD2);        /* Pin PD2 input              */
    PORTD |= (1 << PD2);        /* Pin PD2 pull-up enabled    */


    /* initialize display, cursor off */
    lcd_init(LCD_DISP_ON_CURSOR_BLINK);

    for (;;) {                           /* loop forever */
        /* 
         * Test 1:  write text to display
         */

        /* clear display and home cursor */
        lcd_clrscr();
        
        /* put string to display (line 1) with linefeed */
        lcd_puts("LCD Test Line 1\n");

        /* cursor is now on second line, write second line */
        lcd_puts("Line 2");
        
        /* move cursor to position 8 on line 2 */
        lcd_gotoxy(7,1);  
        
        /* write single char to display */
        lcd_putc(':');
        
        /* wait until push button PD2 (INT0) is pressed */
        wait_until_key_pressed();
        
        
        /*
         * Test 2: use lcd_command() to turn on cursor
         */
        
        /* turn on cursor */
        lcd_command(LCD_DISP_ON_CURSOR);

        /* put string */
        lcd_puts( "CurOn");
        
        /* wait until push button PD2 (INT0) is pressed */
        wait_until_key_pressed();


        /*
         * Test 3: display shift
         */
        
        lcd_clrscr();     /* clear display home cursor */

        /* put string from program memory to display */
        lcd_puts_P( "Line 1 longer than 14 characters\n" );
        lcd_puts_P( "Line 2 longer than 14 characters" );
        
        /* move BOTH lines one position to the left */
        lcd_command(LCD_MOVE_DISP_LEFT);
        
        /* wait until push button PD2 (INT0) is pressed */
        wait_until_key_pressed();

        /* turn off cursor */
        lcd_command(LCD_DISP_ON);
        
        
        /*
         *   Test: Display integer values
         */
        
        lcd_clrscr();   /* clear display home cursor */
        
        /* convert interger into string */
        itoa( num , buffer, 10);
        
        /* put converted string to display */
        lcd_puts(buffer);
        
        /* wait until push button PD2 (INT0) is pressed */
        wait_until_key_pressed();
        
        
        /*
         *  Test: Display userdefined characters
         */

       lcd_clrscr();   /* clear display home cursor */
       
       lcd_puts("Copyright: ");
       
       /*
        * load two userdefined characters from program memory
        * into LCD controller CG RAM location 0 and 1
        */
       lcd_command(_BV(LCD_CGRAM));  /* set CG RAM start address 0 */
       for(i=0; i<16; i++)
       {
           lcd_data(pgm_read_byte_near(&copyRightChar[i]));
       }
       
       /* move cursor to position 0 on line 2 */
       /* Note: this switched back to DD RAM adresses */
       lcd_gotoxy(0,1);
       
       /* display user defined (c), built using two user defined chars */
       lcd_putc(0);
       lcd_putc(1);
       

       /* wait until push button PD2 (INT0) is pressed */
       wait_until_key_pressed();
              
    }
}
void uart_send_int(unsigned char port,int val)
{
	itoa(val,uart_send_buffer,10);
	uart_send_string(port,uart_send_buffer);
}
Exemple #5
0
/*===========================================================================*
 *		            sef_cb_init_fresh                                *
 *===========================================================================*/
PRIVATE int sef_cb_init_fresh(int type, sef_init_info_t *info)
{
/* Initialize the process manager. 
 * Memory use info is collected from the boot monitor, the kernel, and
 * all processes compiled into the system image. Initially this information
 * is put into an array mem_chunks. Elements of mem_chunks are struct memory,
 * and hold base, size pairs in units of clicks. This array is small, there
 * should be no more than 8 chunks. After the array of chunks has been built
 * the contents are used to initialize the hole list. Space for the hole list
 * is reserved as an array with twice as many elements as the maximum number
 * of processes allowed. It is managed as a linked list, and elements of the
 * array are struct hole, which, in addition to storage for a base and size in 
 * click units also contain space for a link, a pointer to another element.
*/
  int s;
  static struct boot_image image[NR_BOOT_PROCS];
  register struct boot_image *ip;
  static char core_sigs[] = { SIGQUIT, SIGILL, SIGTRAP, SIGABRT,
				SIGEMT, SIGFPE, SIGBUS, SIGSEGV };
  static char ign_sigs[] = { SIGCHLD, SIGWINCH, SIGCONT };
  static char noign_sigs[] = { SIGILL, SIGTRAP, SIGEMT, SIGFPE, 
				SIGBUS, SIGSEGV };
  register struct mproc *rmp;
  register char *sig_ptr;
  message mess;

  /* Initialize process table, including timers. */
  for (rmp=&mproc[0]; rmp<&mproc[NR_PROCS]; rmp++) {
	tmr_inittimer(&rmp->mp_timer);
  }

  /* Build the set of signals which cause core dumps, and the set of signals
   * that are by default ignored.
   */
  sigemptyset(&core_sset);
  for (sig_ptr = core_sigs; sig_ptr < core_sigs+sizeof(core_sigs); sig_ptr++)
	sigaddset(&core_sset, *sig_ptr);
  sigemptyset(&ign_sset);
  for (sig_ptr = ign_sigs; sig_ptr < ign_sigs+sizeof(ign_sigs); sig_ptr++)
	sigaddset(&ign_sset, *sig_ptr);
  sigemptyset(&noign_sset);
  for (sig_ptr = noign_sigs; sig_ptr < noign_sigs+sizeof(noign_sigs); sig_ptr++)
	sigaddset(&noign_sset, *sig_ptr);

  /* Obtain a copy of the boot monitor parameters and the kernel info struct.  
   * Parse the list of free memory chunks. This list is what the boot monitor 
   * reported, but it must be corrected for the kernel and system processes.
   */
  if ((s=sys_getmonparams(monitor_params, sizeof(monitor_params))) != OK)
      panic("get monitor params failed: %d", s);
  if ((s=sys_getkinfo(&kinfo)) != OK)
      panic("get kernel info failed: %d", s);

  /* Initialize PM's process table. Request a copy of the system image table 
   * that is defined at the kernel level to see which slots to fill in.
   */
  if (OK != (s=sys_getimage(image))) 
  	panic("couldn't get image table: %d", s);
  procs_in_use = 0;				/* start populating table */
  for (ip = &image[0]; ip < &image[NR_BOOT_PROCS]; ip++) {
  	if (ip->proc_nr >= 0) {			/* task have negative nrs */
  		procs_in_use += 1;		/* found user process */

		/* Set process details found in the image table. */
		rmp = &mproc[ip->proc_nr];	
  		strncpy(rmp->mp_name, ip->proc_name, PROC_NAME_LEN); 
		rmp->mp_nice = get_nice_value(ip->priority);
  		sigemptyset(&rmp->mp_ignore);	
  		sigemptyset(&rmp->mp_sigmask);
  		sigemptyset(&rmp->mp_catch);
		if (ip->proc_nr == INIT_PROC_NR) {	/* user process */
  			/* INIT is root, we make it father of itself. This is
  			 * not really OK, INIT should have no father, i.e.
  			 * a father with pid NO_PID. But PM currently assumes 
  			 * that mp_parent always points to a valid slot number.
  			 */
  			rmp->mp_parent = INIT_PROC_NR;
  			rmp->mp_procgrp = rmp->mp_pid = INIT_PID;
			rmp->mp_flags |= IN_USE; 
		}
		else {					/* system process */
  			if(ip->proc_nr == RS_PROC_NR) {
  				rmp->mp_parent = INIT_PROC_NR;
  			}
  			else {
  				rmp->mp_parent = RS_PROC_NR;
  			}
  			rmp->mp_pid = get_free_pid();
			rmp->mp_flags |= IN_USE | PRIV_PROC;
		}

		/* Get kernel endpoint identifier. */
		rmp->mp_endpoint = ip->endpoint;

		/* Set scheduling info */
		rmp->mp_scheduler = KERNEL;

		/* Tell FS about this system process. */
		mess.m_type = PM_INIT;
		mess.PM_SLOT = ip->proc_nr;
		mess.PM_PID = rmp->mp_pid;
		mess.PM_PROC = rmp->mp_endpoint;
  		if (OK != (s=send(FS_PROC_NR, &mess)))
			panic("can't sync up with FS: %d", s);
  	}
  }

  /* Tell FS that no more system processes follow and synchronize. */
  mess.PR_ENDPT = NONE;
  if (sendrec(FS_PROC_NR, &mess) != OK || mess.m_type != OK)
	panic("can't sync up with FS");

#if (CHIP == INTEL)
        uts_val.machine[0] = 'i';
        strcpy(uts_val.machine + 1, itoa(getprocessor()));
#endif  

 system_hz = sys_hz();

 /* Map out our own text and data. This is normally done in crtso.o
  * but PM is an exception - we don't get to talk to VM so early on.
  * That's why we override munmap() and munmap_text() in utility.c.
  *
  * _minix_unmapzero() is the same code in crtso.o that normally does
  * it on startup. It's best that it's there as crtso.o knows exactly
  * what the ranges are of the filler data.
  */
  unmap_ok = 1;
  _minix_unmapzero();

  return(OK);
}
Exemple #6
0
//响应时间事件
void CFaceProcess::OnTimer(UINT nIDEvent){
	//AfxMessageBox("In OnTimer()");
	 CString     temp="";
 	 const char  *pszStr="";
	 int         match=0;
switch(nIDEvent){
	//定时器1的相应处理部分
   case timer:
	if(m_Video){
		if( !cvGrabFrame( m_Video))
			return ;
		m_GrabFrame = cvRetrieveFrame(m_Video );
		if( !m_GrabFrame)
			return ;
		if( !m_SaveFrame)
			m_SaveFrame = cvCreateImage( cvSize(m_GrabFrame->width,m_GrabFrame->height),
			IPL_DEPTH_8U, m_GrabFrame->nChannels );
		if( m_GrabFrame->origin == IPL_ORIGIN_TL )
			cvCopy( m_GrabFrame, m_SaveFrame, 0 );
		else
			cvFlip( m_GrabFrame, m_SaveFrame, 0 );
//		m_GrabFrame=cvQueryFrame(m_Video);
// 		if(m_GrabFrame->origin==0)
//		m_GrabFrame->origin=1;
        /**************对获取的帧进行人脸检测处理并且显示*****************/
		faceDetector.detect_and_draw(m_SaveFrame);
        //m_GrabFrame=faceDetector.getSrcImage();
	    m_CvvImage.CopyOf(m_SaveFrame,1);
	    m_CvvImage.DrawToHDC(hDC,&rect);
		//cvReleaseImage(&m_SaveFrame);
	 }
//	return;
	/************************************************************************/
	/* 获得b_Process状态                                                             */
	/************************************************************************/
	if(m_Video && b_flagProcess==true)
		b_Process=1;
	else if(m_Video && b_flagProcess==false)
		b_Process=2;
	else
		b_Process=0;
	/************************************************************************/
	/* 根据b_Process状态动态设置控件有效性                                                            */
	/************************************************************************/
     if(b_Process==1)//此时可以关摄像头、保存图片
	 {
		 GetDlgItem(ID_CLOSE_CAPTURE)->EnableWindow(true);//使控件有效
		 GetDlgItem(IDC_SAVE_PIC)->EnableWindow(true);    //使控件有效
	 }
	 else if(b_Process==2)//此时可以人脸识别、匹配率显示,不能保存图片
	 {
		//更新状态
		GetDlgItem(ID_CLOSE_CAPTURE)->EnableWindow(true); //使控件有效
		GetDlgItem(IDC_RECOGNISE)->EnableWindow(true);    //使控件有效
        GetDlgItem(IDC_SAVE_PIC)->EnableWindow(false);    //使控件wu效   
	   /******此时可保存供人脸识别用的图片**************************
		//  每次保存五张
		//  定时器而负责定时训练图片,并更新匹配率
		//  保存图片不断覆盖以前的图片
	   ****************************/		
		if((count % 5)==0)
		           count=1;
		 pszStr = testFileName[count].GetBuffer(testFileName[count].GetLength());
		 m_snap=cvCreateImage(cvGetSize(m_SaveFrame),m_SaveFrame->depth,m_SaveFrame->nChannels);
		 cvCopy(m_SaveFrame,m_snap,NULL);
		 //m_snap->origin=1;//等于0保存倒立图向
		 //检测人脸并保存测试图片
		//AfxMessageBox(CString(pszStr)+CString(itoa(count,chEdit,10)));
	    try{
		  if(faceDetector.detect_and_draw(m_snap)){
		     faceImage=faceDetector.getFaceImage();
			 if(faceImage){
			    //faceImage->origin=1;
		     //化简图片
			    if(faceSimplifier.Simplify(faceImage)){
				   faceGray=faceSimplifier.getFaceImage();
				   //faceGray->origin=1;//等于0保存倒立图向
				   cvSaveImage(pszStr,faceGray);	//把图像写入文件
				 //AfxMessageBox(CString(pszStr)+CString(itoa(count,chEdit,10))+"t1");
				   count++;
				}
			}// if(faceImage)
		  }
		}catch(...)  //重要,避免检测不到人脸时的异常终止
		{ /* AfxMessageBox("保存图片失败!!");*/	return ; }
	 }else //b_Process==0)  //此时只可以进行打开摄像头操或者退出
	 {
		 GetDlgItem(IDC_STATIC_OTHER)->EnableWindow(FALSE);//使控件无效
		 GetDlgItem(IDC_SAVE_PIC)->EnableWindow(FALSE);//使控件无效
		 GetDlgItem(IDC_RECOGNISE)->EnableWindow(FALSE);//使控件无效
		 GetDlgItem(ID_CLOSE_CAPTURE)->EnableWindow(FALSE);//使控件无效
	 }
	/************************************************************************/
	/* 显示属性   需要随时更新的在次显示,更新慢的在慢定时器facetimer中更新*/
	/************************************************************************/
	   m_fameCount++;
	//	m_vieoProtery=cvGetCaptureProperty(m_Video,CV_CAP_PROP_FRAME_COUNT);
	  itoa(m_fameCount,chEdit,10);
	  SetDlgItemText(IDC_STATIC_FRAME_COUNT,chEdit);
	break;
		//定时器2的相应处理部分
    case faceTimer:
	   //****************//人脸识别
	 correct=correct+faceRecognitor.recognize();
	 totalTest+=5;
	 matchPercent=float(correct)/totalTest;
	 match=int(matchPercent*100);
	/************************************************************************/
	/* 显示属性   需要随时更新的在次显示,更新慢的在慢定时器facetimer中更新*/
	/************************************************************************/	
    //匹配率的更新
	 itoa(match,chEdit,10);
	 temp=" "+CString(chEdit)+" %";
	 SetDlgItemText(IDC_STATIC_CORRECT,temp);
	 GetDlgItem(IDC_STATIC_CORRECT)->EnableWindow(TRUE);//使控件有效
	//根据匹配判断是否可以进入下一步
	 if(matchPercent>0.75 && totalTest>20)
        GetDlgItem(IDC_OK)->EnableWindow(TRUE);//使控件有效
	//其他更新
	 m_vieoProtery=cvGetCaptureProperty(m_Video,CV_CAP_PROP_POS_MSEC);
	 itoa(m_vieoProtery,chEdit,10);
	 SetDlgItemText(IDC_STATIC_OTHER,chEdit);
	 m_vieoProtery=cvGetCaptureProperty(m_Video,CV_CAP_PROP_FRAME_WIDTH);
	 itoa(m_vieoProtery,chEdit,10);
	 SetDlgItemText(IDC_STATIC_Width,chEdit);
	 m_vieoProtery=cvGetCaptureProperty(m_Video,CV_CAP_PROP_FRAME_HEIGHT);
	 itoa(m_vieoProtery,chEdit,10);
	 SetDlgItemText(IDC_STATIC_HEIGHT,chEdit);
     m_vieoProtery=cvGetCaptureProperty(m_Video,CV_CAP_PROP_FPS);
	 itoa(m_vieoProtery,chEdit,10);
	 SetDlgItemText(IDC_STATIC_FPS,chEdit);
   break;
   default:
	       break;
	}
	//调用基类时间
	CDialog::OnTimer(nIDEvent);
}
Exemple #7
0
void main()
{
	int sss,q,ll,gd=DETECT,p,gm,area,a=(450-(50*5)),d,cat=77,ch,dh,eh,t1,t2,t12,t22,len,cc,hh;
	char *str,*str1,*tim;
	initgraph(&gd,&gm,"");
	p=1;
	front();
	dr:
	viewport();
	q=menu();
	if(q==3)
	{
	     arun:	hh=help();
		if(hh==1)
		{
			how();
			goto arun;
		}
		if(hh==2)
		{
			select();
			goto arun;
		}
		if(hh==3)
		{
			credit();
			goto arun;
		}
		if(hh==4)
		{
			design();
			goto arun;
		}
		if(hh==5)
			goto dr;
	}
	if(q==2)
	{
	 rr:
		ll=sivakumar();
	       if(ll==1)
	       {
			p=m2();

			goto rr;
	       }
	       if(ll==2)
	       {
			a=speed();
			viewport();
			goto rr;
	       }
	       if(ll==3)
	       {
			topscore();
			goto rr;
		}
	       if(ll==4)
		    goto dr;
	}
	if(q==4)
		exit(0);
      if(q==1)
      {
	names();
	hide();
	viewport();
	x[0]=85;
	x[1]=70;
	x[2]=55;
	x[3]=40;
	y[0]=y[1]=y[2]=y[3]=35;
	setcolor(4);
	rectangle(24,19,626,396);
	ra();
	setcolor(15);
	setfillstyle(1,10);
	bar(32,32,43,43);
	area=imagesize(30,30,45,45);
	buff=malloc(area);
	getimage(30,30,45,45,buff);
	putimage(30,30,buff,XOR_PUT);
	setpos(0,0);
	setfillstyle(1,0);
	bar(100,100,500,350);
	prakash(p);
	level=p;
	putimage(40,35,buff,XOR_PUT);
	putimage(55,35,buff,XOR_PUT);
	putimage(70,35,buff,XOR_PUT);
	putimage(85,35,buff,XOR_PUT);
	textcolor(GREEN+BLINK);
	len=0;
	status("Game Play: Arrow keys       Menu: Esc         Pause (or) Play: Others key");
	while(1)
	{

	sss=getpixel(5,5);
	if(sss!=0);
	{
		setfillstyle(SOLID_FILL,0);
		bar(0,0,15,15);
	}
		if(((i-4)%11==0)&&(bon==0)&&(len!=(i-4)))
		{
			len=(i-4);
			gettime(&t);
			bonous();
				bon=1;
			t1=t.ti_sec;
			cc=10;
		}
		gettime(&t);
		if((t1!=t.ti_sec)&&(bon==1))
		{
			cc--;
			t1=t.ti_sec;
			itoa(cc,tim,10);
			setfillstyle(SOLID_FILL,0);
			bar(470,0,530,18);
			outtextxy(500,0,tim);

		}
		if((cc==0)&&(bon==1))
		{
			putimage(xc1,yc1,f2,XOR_PUT);
			bar(470,0,530,18);
			bon=0;
		}
		gotoxy(68,1);
		setcolor(6);
	       itoa(score,str,10);
	       setfillstyle(1,0);
	       settextstyle(3,0,1);
	       if(strcmp(str,str1)!=0)
	       {    bar(80,400,350,450);
		    outtextxy(100,420,"Score : ");
		    outtextxy(180,420,str);
		    strcpy(str1,str);
	       }
		if(kbhit())
		{
		       //	ch=getch();
			dh=getch();
			cat=dh;
		}
		else
		{
			arrange(x,y,i);
			if(set==0)
				food();
			if(cat!=dupli)
				cat=lock(cat,dupli);
			switch(cat)
			{
				case 72:
					     if(y[1]==20)
						  y[0]=380;
					     else
						  y[0]=y[1]-15;
					     x[0]=x[1];
					     d=getpixel(x[0]+8,y[0]+8);
					     if((d==10)||(d==14))
						doctor();
					     if((d==4)&&(bon==1))
					     {
						i++;
						sound(1000);
						delay(90);
						nosound();
						bon=0;
						score+=(cc*10);
					       putimage(xc1,yc1,f2,XOR_PUT);
					       putimage(x[0],y[0],buff,XOR_PUT);
					       putimage(x[i],y[i],buff,XOR_PUT);
					       setfillstyle(SOLID_FILL,0);
						bar(470,0,530,18);
					     }
					     else if(d==15)
					     {
						i++;
						set=0;
						sound(800);
						delay(40);
						score+=bb;
						nosound();
						putimage(x[0],y[0],buff,XOR_PUT);
					     }
					     else
					     {
						 putimage(x[0],y[0],buff,XOR_PUT);
						 putimage(x[i-1],y[i-1],buff,XOR_PUT);
					     }
						delay(a);
				     break;
				case 80:
				     if(y[1]==380)
					  y[0]=20;
				     else
					  y[0]=y[1]+15;
				     x[0]=x[1];
				      d=getpixel(x[0]+8,y[0]+8);
				      if((d==10)||(d==14))
					doctor();
					     if((d==4)&&(bon==1))
					     {
						i++;
						sound(1000);
						delay(90);
						nosound();
						bon=0;
						score+=(cc*10);
					       putimage(xc1,yc1,f2,XOR_PUT);
					       putimage(x[0],y[0],buff,XOR_PUT);
					       putimage(x[i],y[i],buff,XOR_PUT);
					       setfillstyle(SOLID_FILL,0);
						bar(470,0,530,18);
					     }
				      else if(d==15)
					     {
						i++;
						score+=bb;
						sound(800);
						delay(40);
						set=0;
						nosound();
						putimage(x[0],y[0],buff,XOR_PUT);
					     }
				       else
				      {
					     putimage(x[0],y[0],buff,XOR_PUT);
					     putimage(x[i-1],y[i-1],buff,XOR_PUT);
				      }
				     delay(a);
				     break;
				case 75:
				     if(x[1]==25)
					  x[0]=610;
				     else
					  x[0]=x[1]-15;
				     y[0]=y[1];
				     d=getpixel(x[0]+8,y[0]+8);
					if((d==10)||(d==14))
						doctor();
					     if((d==4)&&(bon==1))
					     {
						i++;
						sound(1000);
						delay(90);
						nosound();
						bon=0;
						score+=(cc*10);
					       putimage(xc1,yc1,f2,XOR_PUT);
					       putimage(x[0],y[0],buff,XOR_PUT);
					       putimage(x[i],y[i],buff,XOR_PUT);
					       setfillstyle(SOLID_FILL,0);
						bar(470,0,530,18);
					     }
					else if(d==15)
					  {
						i++;
						sound(800);
						delay(40);
						set=0;
						nosound();
						score+=bb;
						putimage(x[0],y[0],buff,XOR_PUT);
					  }
					  else
					  {
					     putimage(x[0],y[0],buff,XOR_PUT);
					     putimage(x[i-1],y[i-1],buff,XOR_PUT);
					  }
				      delay(a);
				 break;
				case 77:
				     if(x[1]==610)
					  x[0]=25;
				     else
					  x[0]=x[1]+15;
				     y[0]=y[1];
				     d=getpixel(x[0]+8,y[0]+8);
				      if((d==10)||(d==14))
					doctor();
					    if((d==4)&&(bon==1))
					     {
						i++;
						sound(1000);
						delay(90);
						nosound();
						bon=0;
						score+=(cc*10);
					       putimage(xc1,yc1,f2,XOR_PUT);
					       putimage(x[0],y[0],buff,XOR_PUT);
					       putimage(x[i],y[i],buff,XOR_PUT);
					       setfillstyle(SOLID_FILL,0);
						bar(470,0,530,18);
					     }
					else if(d==15)
					    {
						i++;
						set=0;
						sound(800);
						delay(40);
						score+=bb;
						nosound();
						putimage(x[0],y[0],buff,XOR_PUT);
					     }
					     else
					     {
						     putimage(x[0],y[0],buff,XOR_PUT);
						     putimage(x[i-1],y[i-1],buff,XOR_PUT);
					     }
				       delay(a);
					break;
				case 27:
					goto dx;
				//	break;
			}
			dupli=cat;
		}
    }
     }
     dx:
     call();
}
byte ESP8266_Simple::sendHttpRequest( unsigned long serverIpAddress, int port,  char *requestPathAndResponseBuffer, int bufferLength, char *httpHost, int bodyResponseOnlyFromLine, int *httpResponseCode )
{  
  byte responseCode;
  char cmdBuffer[64];    
  memset(cmdBuffer,0,sizeof(cmdBuffer));
  
  // Build up the command string
  //  AT+CIPSTART="TCP","[IP]",[PORT]
  strncpy_P(cmdBuffer, PSTR("AT+CIPSTART=\"TCP\",\""), sizeof(cmdBuffer));        // Command itself with opening quote for IP
  this->ipConvertDatatypeFromTo(serverIpAddress, cmdBuffer+strlen(cmdBuffer));  // the IP address
  strcpy(cmdBuffer+strlen(cmdBuffer),"\",");                                    // closing quote for IP
  itoa(port,cmdBuffer+strlen(cmdBuffer), 10);                                   // port  
  
  responseCode = this->sendCommand(cmdBuffer);
  if(responseCode != ESP8266_OK) return responseCode;
  
  // Create the data command
  memset(cmdBuffer,0,sizeof(cmdBuffer));
  strcpy_P(cmdBuffer, PSTR("AT+CIPSEND="));
  //                          "GET "                                       "\r\n"
  int httpRequestDataLength =   4  + strlen(requestPathAndResponseBuffer) + 2;
  if(httpHost)
  {
    //                        " HTTP/1.0\r\nHost: "                        "\r\n"
    httpRequestDataLength +=          17            + strlen(httpHost)     + 2;
  }
  
  itoa(httpRequestDataLength, cmdBuffer+strlen(cmdBuffer), 10); // Add 2 bytes for the trailing CRLF sequence that sendCommand will append
  
  responseCode = this->sendCommand(cmdBuffer);
  if(responseCode != ESP8266_OK)
  {
    // Close response
    this->sendCommand(F("AT+CIPCLOSE"));
    return responseCode;
  }
  
  memset(cmdBuffer,0,sizeof(cmdBuffer));  
  if(httpHost)
  {
    // NOTE!  If you specify HTTP/1.1, then Apache+PHP insist on sending chunked transfers
    //        this means that you'll get chunk lengths in your stream
    //        chunk lengths are hexadecimal integers specifying the chunk length given 
    //        before that chunk, eg your stream looks like
    //            [http response headers which include Transfer-Encoding: chunked]
    //            [blank line]
    //            [chunk length]
    //            [blank line]
    //            [data bytes (chunk length of)]
    //            etc...
    //        which would be a pain to parse, so we will just use HTTP/1.0, which works 
    //        well enough for our purposes and does not include any stupid chunking, yay.
    strcpy_P(cmdBuffer, PSTR(" HTTP/1.0\r\nHost: "));   
  }
  
  const char *builtUpCommand[] = {
    "GET ",
    requestPathAndResponseBuffer,
    cmdBuffer,
    httpHost,
    "\r\n" // The sendCommand will include another \r\n for us indicating end of headers
  };
  
  responseCode = this->sendCommand((const char **)builtUpCommand, httpHost ? 5 : 2, NULL, 0, 1); 
  if(responseCode != ESP8266_OK)
  {
    this->sendCommand(F("AT+CIPCLOSE"));
    return responseCode;
  }
  
  if(httpHost)
  {
    int httpResponseCodeBuffer;
    this->readIPD(requestPathAndResponseBuffer,bufferLength,bodyResponseOnlyFromLine, &httpResponseCodeBuffer);
    
    if(httpResponseCode)
    {
      *httpResponseCode = httpResponseCodeBuffer;
    }
  }
  else
  {
    this->readIPD(requestPathAndResponseBuffer,bufferLength,bodyResponseOnlyFromLine);
  }
  
  if(this->unlinkConnection() != ESP8266_OK)
  {
    this->reset();
  }
  this->sendCommand(F("AT+CIPSTATUS"));
  return ESP8266_OK;    
}
Exemple #9
0
//*****************************************************************************
//
//! Gets the current time from the selected SNTP server
//!
//! \brief  This function obtains the NTP time from the server.
//!
//! \param  GmtDiffHr is the GMT Time Zone difference in hours
//! \param  GmtDiffMins is the GMT Time Zone difference in minutes
//!
//! \return 0 : success, -ve : failure
//!
//*****************************************************************************
long GetSNTPTime(unsigned char ucGmtDiffHr, unsigned char ucGmtDiffMins)
{

/*
                            NTP Packet Header:

       0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9  0  1
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |LI | VN  |Mode |    Stratum    |     Poll      |   Precision    |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                          Root  Delay                           |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                       Root  Dispersion                         |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                     Reference Identifier                       |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                    Reference Timestamp (64)                    |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                    Originate Timestamp (64)                    |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                     Receive Timestamp (64)                     |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                     Transmit Timestamp (64)                    |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                 Key Identifier (optional) (32)                 |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      |                                                                |
      |                                                                |
      |                 Message Digest (optional) (128)                |
      |                                                                |
      |                                                                |
      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

*/
    char cDataBuf[48];
    long lRetVal = 0;
    int iAddrSize;

    //
    // Send a query to the NTP server to get the NTP time
    //
    memset(cDataBuf, 0, sizeof(cDataBuf));
    cDataBuf[0] = '\x1b';

    sAddr.sa_family = AF_INET;
    // the source port
    sAddr.sa_data[0] = 0x00;
    sAddr.sa_data[1] = 0x7B;    // UDP port number for NTP is 123
    sAddr.sa_data[2] = (char)((g_sAppData.ulDestinationIP>>24)&0xff);
    sAddr.sa_data[3] = (char)((g_sAppData.ulDestinationIP>>16)&0xff);
    sAddr.sa_data[4] = (char)((g_sAppData.ulDestinationIP>>8)&0xff);
    sAddr.sa_data[5] = (char)(g_sAppData.ulDestinationIP&0xff);

    lRetVal = sl_SendTo(g_sAppData.iSockID, cDataBuf, sizeof(cDataBuf), 0, &sAddr, sizeof(sAddr));
    if (lRetVal != sizeof(cDataBuf))
    {
        // could not send SNTP request
        hourSet = 25; // This will ensure we try to fetch time again
        //ASSERT_ON_ERROR(SERVER_GET_TIME_FAILED);
    }

    //
    // Wait to receive the NTP time from the server
    //
    sLocalAddr.sin_family = SL_AF_INET;
    sLocalAddr.sin_port = 0;
    sLocalAddr.sin_addr.s_addr = 0;
    if(g_sAppData.ulElapsedSec == 0)
    {
        lRetVal = sl_Bind(g_sAppData.iSockID, (SlSockAddr_t *)&sLocalAddr, sizeof(SlSockAddrIn_t));
    }

    iAddrSize = sizeof(SlSockAddrIn_t);

    lRetVal = sl_RecvFrom(g_sAppData.iSockID, cDataBuf, sizeof(cDataBuf), 0, (SlSockAddr_t *)&sLocalAddr, (SlSocklen_t*)&iAddrSize);
    ASSERT_ON_ERROR(lRetVal);

    //
    // Confirm that the MODE is 4 --> server
    //
    if ((cDataBuf[0] & 0x7) != 4)    // expect only server response
    {
        hourSet = 25; // This will ensure we try to fetch time again
        //ASSERT_ON_ERROR(SERVER_GET_TIME_FAILED);  // MODE is not server, abort
    }
    else
    {
        unsigned char iIndex;

        //
        // Getting the data from the Transmit Timestamp (seconds) field
        // This is the time at which the reply departed the
        // server for the client
        //
        g_sAppData.ulElapsedSec = cDataBuf[40];
        g_sAppData.ulElapsedSec <<= 8;
        g_sAppData.ulElapsedSec += cDataBuf[41];
        g_sAppData.ulElapsedSec <<= 8;
        g_sAppData.ulElapsedSec += cDataBuf[42];
        g_sAppData.ulElapsedSec <<= 8;
        g_sAppData.ulElapsedSec += cDataBuf[43];

        //
        // seconds are relative to 0h on 1 January 1900
        //
        g_sAppData.ulElapsedSec -= TIME2013;

        //
        // in order to correct the timezone
        //
        g_sAppData.ulElapsedSec += (ucGmtDiffHr * SEC_IN_HOUR);
        g_sAppData.ulElapsedSec += (ucGmtDiffMins * SEC_IN_MIN);

        g_sAppData.pcCCPtr = &g_sAppData.acTimeStore[0];

        //
        // day, number of days since beginning of 2013
        //
        g_sAppData.isGeneralVar = g_sAppData.ulElapsedSec/SEC_IN_DAY;
        memcpy(g_sAppData.pcCCPtr, g_acDaysOfWeek2013[g_sAppData.isGeneralVar%7], 3);
        g_sAppData.pcCCPtr += 3;
        *g_sAppData.pcCCPtr++ = '\x20';

        //
        // month
        //
        g_sAppData.isGeneralVar %= 365;
        for (iIndex = 0; iIndex < 12; iIndex++)
        {
            g_sAppData.isGeneralVar -= g_acNumOfDaysPerMonth[iIndex];
            if (g_sAppData.isGeneralVar < 0)
                    break;
        }
        if(iIndex == 12)
        {
            iIndex = 0;
        }
        memcpy(g_sAppData.pcCCPtr, g_acMonthOfYear[iIndex], 3);
        g_sAppData.pcCCPtr += 3;
        *g_sAppData.pcCCPtr++ = '\x20';

        // Set the Month Value
        dateTime.sl_tm_mon = iIndex + 1;

        //
        // date
        // restore the day in current month
        //
        g_sAppData.isGeneralVar += g_acNumOfDaysPerMonth[iIndex];
        g_sAppData.uisCCLen = itoa(g_sAppData.isGeneralVar + 1, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;
        *g_sAppData.pcCCPtr++ = '\x20';

        // Set the Date
        dateTime.sl_tm_day = g_sAppData.isGeneralVar + 1;

        //
        // time
        //
        g_sAppData.ulGeneralVar = g_sAppData.ulElapsedSec%SEC_IN_DAY;

        // number of seconds per hour
        g_sAppData.ulGeneralVar1 = g_sAppData.ulGeneralVar%SEC_IN_HOUR;

        // number of hours
        g_sAppData.ulGeneralVar /= SEC_IN_HOUR;
        g_sAppData.uisCCLen = itoa(g_sAppData.ulGeneralVar, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;
        *g_sAppData.pcCCPtr++ = ':';

        // Set the hour
        dateTime.sl_tm_hour = g_sAppData.ulGeneralVar;

        // number of minutes per hour
        g_sAppData.ulGeneralVar = g_sAppData.ulGeneralVar1/SEC_IN_MIN;

        // Set the minutes
        dateTime.sl_tm_min = g_sAppData.ulGeneralVar;

        // number of seconds per minute
        g_sAppData.ulGeneralVar1 %= SEC_IN_MIN;
        g_sAppData.uisCCLen = itoa(g_sAppData.ulGeneralVar, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;
        *g_sAppData.pcCCPtr++ = ':';
        g_sAppData.uisCCLen = itoa(g_sAppData.ulGeneralVar1, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;
        *g_sAppData.pcCCPtr++ = '\x20';

        //Set the seconds
        dateTime.sl_tm_sec = g_sAppData.ulGeneralVar1;

        //
        // year
        // number of days since beginning of 2013
        //
        g_sAppData.ulGeneralVar = g_sAppData.ulElapsedSec/SEC_IN_DAY;
        g_sAppData.ulGeneralVar /= 365;
        g_sAppData.uisCCLen = itoa(YEAR2013 + g_sAppData.ulGeneralVar, g_sAppData.pcCCPtr);
        g_sAppData.pcCCPtr += g_sAppData.uisCCLen;

        *g_sAppData.pcCCPtr++ = '\0';

        //Set the year
        dateTime.sl_tm_year = 2013 + g_sAppData.ulGeneralVar;

        CLI_Write("Response from server: ");
        CLI_Write((unsigned char *)g_acSNTPserver);
        CLI_Write("\n\r");
        CLI_Write((unsigned char *)g_sAppData.acTimeStore);
        CLI_Write("\n\r\n\r");

        //Set time of the device for certificate verification.
        lRetVal = setDeviceTimeDate();
        if(lRetVal < 0)
        {
            CLI_Write("Unable to set time in the device.\n\r");
            return lRetVal;
        }
    }

    return SUCCESS;
}
Exemple #10
0
int Settings::ParseSettings(char *filename, int argc_, char **argv_){
	int i;
	char numbuf[50];
	string temp,temp1;
	string cfgfile_name; // ss5
	    
	argc=argc_;
	argv=argv_;

	// Take name of config file from args. If not given then
	// FindSetting() handles "MAIN/cfgfile as special case // ss5
	FindSetting(&cfgfile_name, "MAIN","cfgfile", "fragistics.conf");
	
	//cfgfile = new ConfigFile(filename);
	cfgfile = new ConfigFile(cfgfile_name.c_str()); // ss5

	//settings

	
	//HTML
	FindSetting(&text_color, "HTML","text_color", "#c0c0c0");
	FindSetting(&link_color, "HTML","link_color", "#0000ff");
	FindSetting(&vlink_color, "HTML","vlink_color", "#ff0000");
	FindSetting(&alink_color, "HTML","alink_color", "#00ff00");
	FindSetting(&text_color, "HTML","text_color", "#c0c0c0");
	FindSetting(&bg_color, "HTML","bg_color", "#000000");
	FindSetting(&bg_image, "HTML","bg_image", "");

	FindSetting(&namecolors[0], "HTML","name0", "black");
	FindSetting(&namecolors[1], "HTML","name1", "red");
	FindSetting(&namecolors[2], "HTML","name2", "green");
	FindSetting(&namecolors[3], "HTML","name3", "yellow");
	FindSetting(&namecolors[4], "HTML","name4", "blue");
	FindSetting(&namecolors[5], "HTML","name5", "cyan");
	FindSetting(&namecolors[6], "HTML","name6", "magenta");
	FindSetting(&namecolors[7], "HTML","name7", "white");
	FindSetting(&namecolors[8], "HTML","name8", "white");
	FindSetting(&namecolors[9], "HTML","name9", "white");

	
	//KILL TABLES
	if(FindSetting(&temp, "KILL TABLES","hilite_levels", "4")==false){
		temp="4";
		cfgfile->AddValue("KILL TABLES","hilite_level0", "100");
		cfgfile->AddValue("KILL TABLES","hilite_color0", "#00ff00");

		cfgfile->AddValue("KILL TABLES","hilite_level1", "90");
		cfgfile->AddValue("KILL TABLES","hilite_color1", "#d0d000");

		cfgfile->AddValue("KILL TABLES","hilite_level2", "75");
		cfgfile->AddValue("KILL TABLES","hilite_color2", "#d07000");

		cfgfile->AddValue("KILL TABLES","hilite_level3", "50");
		cfgfile->AddValue("KILL TABLES","hilite_color3", "#804020");
	}
	hilite_levels=atoi(temp.c_str());
	if(hilite_levels>=KILLTABLE_MAXHILITE){
		hilite_levels=KILLTABLE_MAXHILITE-1;
		itoa(hilite_levels,numbuf,10);
		cfgfile->AddValue("KILL TABLES","hilite_levels", numbuf);
	}
	//loop to get colors/percents
	for(i=0;i<hilite_levels;i++){
		itoa(i,numbuf,10);
		temp1="hilite_level";
		temp1+=numbuf;
		FindSetting(&temp, "KILL TABLES",temp1.c_str(), "101");
		hilite_percents[i]=atoi(temp.c_str());
		temp1="hilite_color";
		temp1+=numbuf;
		FindSetting(&hilite_colors[i], "KILL TABLES",temp1.c_str(), "white");
	}
	FindSetting(&temp, "KILL TABLES","hilite_minhilite", "2");
	hilite_minhilite=atoi(temp.c_str());
	//columncolors
	FindSetting(&killtable_column[0], "KILL TABLES","column0", "#202020");
	FindSetting(&killtable_column[1], "KILL TABLES","column1", "#404040");
	FindSetting(&killtable_column[2], "KILL TABLES","column2", "#606060");


	//MAIN settings
	FindSetting(&temp, "MAIN","limit_overall_killtables", "1");
	main_overall_killtable=atoi(temp.c_str());
	FindSetting(&temp, "MAIN","players_min_time", "900");
	players_min_time=atoi(temp.c_str());
	FindSetting(&temp, "MAIN","players_min_games", "2");
	players_min_games=atoi(temp.c_str());
	FindSetting(&temp, "MAIN","players_min_kills", "20");
	players_min_kills=atoi(temp.c_str());
	FindSetting(&time_format, "MAIN","time_format", "%X %x");
	FindSetting(&temp, "MAIN","use_cust_rank", "0");
	use_cust_rank=atoi(temp.c_str());
	FindSetting(&temp, "MAIN","cust_rank_start", "10000");
	cust_rank_start=atoi(temp.c_str());
	FindSetting(&cust_rank_template, "MAIN","cust_rank_template", "custrank.htmlt");
	FindSetting(&srcpath, "MAIN","src_path", ".\\templates");
	FindSetting(&destpath, "MAIN","dest_path", ".\\output");
	FindSetting(&dbpath, "MAIN","db_path", ".\\database");
	FindSetting(&temp, "MAIN","use_db", "1");
	use_db=atoi(temp.c_str());
	


	//GAME settings
	FindSetting(&temp, "GAME","min_players", "2");
	game_minplayers=atoi(temp.c_str());
	FindSetting(&temp, "GAME","min_time", "21");
	game_mintime=atoi(temp.c_str());
	FindSetting(&temp, "GAME","min_kills", "10");
	game_minkills=atoi(temp.c_str());
	FindSetting(&temp, "GAME","game_complete", "2");
	game_complete=atoi(temp.c_str());
	FindSetting(&temp, "GAME","game_last_placed", "3");
	game_placed=atoi(temp.c_str());


	//LOGS settings
	FindSetting(&temp, "LOGS","number_of_logs", "-1");
	logs_number=atoi(temp.c_str());
	if(logs_number<=0 || logs_number>1000){				//yes, I know 1000 is arbitrary, but will anyone ever need more that that?
		cfgfile->AddValue("LOGS","number_of_logs", "1");
		cfgfile->AddValue("LOGS","logpath0", "games.log");
		cfgfile->AddValue("LOGS","logtype0", "0");
		logs_number=1;
	}
	logs_paths = new string[logs_number];
	logs_type = new int[logs_number];
	for(i=0;i<logs_number;i++){
		itoa(i,numbuf,10);
		temp1="logpath";
		temp1+=numbuf;
		FindSetting(&logs_paths[i], "LOGS",temp1.c_str(), "games.log");
		temp1="logtype";
		temp1+=numbuf;
		FindSetting(&temp, "LOGS",temp1.c_str(), "0");
		logs_type[i]=atoi(temp.c_str());
	}

	//TEMPLATES settings
	FindSetting(&temp, "TEMPLATES","main_templates_number", "-1");
	main_number=atoi(temp.c_str());
	if(main_number<0 || main_number>1000){				//yes, I know 1000 is arbitrary, but will anyone ever need more that that?
		cfgfile->AddValue("TEMPLATES","main_templates_number", "1");
		cfgfile->AddValue("TEMPLATES","main_template0", "stats");
		main_number=1;
	}
	main_templates = new string[main_number];
	for(i=0;i<main_number;i++){
		itoa(i,numbuf,10);
		temp1="main_template";
		temp1+=numbuf;
		FindSetting(&main_templates[i], "TEMPLATES",temp1.c_str(), "stats");
	}
	FindSetting(&temp, "TEMPLATES","game_templates_number", "-1");
	game_number=atoi(temp.c_str());
	if(game_number<0 || game_number>1000){				//yes, I know 1000 is arbitrary, but will anyone ever need more that that?
		cfgfile->AddValue("TEMPLATES","game_templates_number", "1");
		cfgfile->AddValue("TEMPLATES","game_template0", "game");
		game_number=1;
	}
	game_templates = new string[game_number];
	for(i=0;i<game_number;i++){
		itoa(i,numbuf,10);
		temp1="game_template";
		temp1+=numbuf;
		FindSetting(&game_templates[i], "TEMPLATES",temp1.c_str(), "game");
	}
	FindSetting(&lastgame_template, "TEMPLATES","lastgame_template", "lastgame");
	FindSetting(&gamelist_template, "TEMPLATES","gamelist_template", "gamelist");
	FindSetting(&gamelistloop_template, "TEMPLATES","gamelist_loop_template", "gamelistloop");
	FindSetting(&player_template, "TEMPLATES","player_template", "player");
	FindSetting(&temp, "TEMPLATES","map_templates_number", "-1");
	map_number=atoi(temp.c_str());
	if(map_number<0 || map_number>1000){				//yes, I know 1000 is arbitrary, but will anyone ever need more that that?
		cfgfile->AddValue("TEMPLATES","map_templates_number", "1");
		cfgfile->AddValue("TEMPLATES","map_template0", "map");
		map_number=1;
	}
	map_templates = new string[map_number];
	for(i=0;i<map_number;i++){
		itoa(i,numbuf,10);
		temp1="map_template";
		temp1+=numbuf;
		FindSetting(&map_templates[i], "TEMPLATES",temp1.c_str(), "map");
	}

	return true;
}
Exemple #11
0
int
main(int argc, char **argv)
{
	struct passwd *pw;
	struct group *gptr;
	char *arg, *cp;
	char buf[MAXPATHLEN];
	int i, f, ch;
	struct stat stb;

	/*
	 * Simulate setuid daemon w/ PRIV_END called.
	 * We don't want lpr to actually be setuid daemon since that
	 * requires that the lpr binary be owned by user daemon, which
	 * is potentially unsafe.
	 */
	if ((pw = getpwuid(DEFUID)) == NULL)
		errx(1, "daemon uid (%u) not in password file", DEFUID);
	effective_uid = pw->pw_uid;
	real_uid = getuid();
	effective_gid = pw->pw_gid;
	real_gid = getgid();
	setresgid(real_gid, real_gid, effective_gid);
	setresuid(real_uid, real_uid, effective_uid);

	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, cleanup);
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, cleanup);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
		signal(SIGQUIT, cleanup);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, cleanup);

	gethostname(host, sizeof (host));
	openlog("lpr", 0, LOG_LPR);

	while ((ch = getopt(argc, argv,
	    ":#:1:2:3:4:C:J:P:T:U:cdfghi:lmnpqrstvw:")) != -1) {
		switch (ch) {

		case '#':		/* n copies */
			if (isdigit(*optarg)) {
				i = atoi(optarg);
				if (i > 0)
					ncopies = i;
			}

		case '4':		/* troff fonts */
		case '3':
		case '2':
		case '1':
			fonts[ch - '1'] = optarg;
			break;

		case 'C':		/* classification spec */
			hdr++;
			class = optarg;
			break;

		case 'J':		/* job name */
			hdr++;
			jobname = optarg;
			break;

		case 'P':		/* specifiy printer name */
			printer = optarg;
			break;

		case 'T':		/* pr's title line */
			title = optarg;
			break;

		case 'U':		/* user name */
			hdr++;
			person = optarg;
			break;

		case 'c':		/* print cifplot output */
		case 'd':		/* print tex output (dvi files) */
		case 'g':		/* print graph(1G) output */
		case 'l':		/* literal output */
		case 'n':		/* print ditroff output */
		case 'p':		/* print using ``pr'' */
		case 't':		/* print troff output (cat files) */
		case 'v':		/* print vplot output */
			format = ch;
			break;

		case 'f':		/* print fortran output */
			format = 'r';
			break;

		case 'h':		/* toggle want of header page */
			hdr = !hdr;
			break;

		case 'i':		/* indent output */
			iflag++;
			indent = atoi(optarg);
			if (indent < 0)
				indent = 8;
			break;

		case 'm':		/* send mail when done */
			mailflg++;
			break;

		case 'q':		/* just q job */
			qflag++;
			break;

		case 'r':		/* remove file when done */
			rflag++;
			break;

		case 's':		/* try to link files */
			sflag++;
			break;

		case 'w':		/* versatec page width */
			width = optarg;
			break;

		case ':':               /* catch "missing argument" error */
			if (optopt == 'i') {
				iflag++; /* -i without args is valid */
				indent = 8;
			} else
				usage();
			break;

		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;
	if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;
	chkprinter(printer);
	if (SC && ncopies > 1)
		errx(1, "multiple copies are not allowed");
	if (MC > 0 && ncopies > MC)
		errx(1, "only %ld copies are allowed", MC);
	/*
	 * Get the identity of the person doing the lpr using the same
	 * algorithm as lprm. 
	 */
	if (real_uid != DU || person == NULL) {
		if ((pw = getpwuid(real_uid)) == NULL)
			errx(1, "Who are you?");
		if ((person = strdup(pw->pw_name)) == NULL)
			err(1, NULL);
	}
	/*
	 * Check for restricted group access.
	 */
	if (RG != NULL && real_uid != DU) {
		if ((gptr = getgrnam(RG)) == NULL)
			errx(1, "Restricted group specified incorrectly");
		if (gptr->gr_gid != getgid()) {
			while (*gptr->gr_mem != NULL) {
				if ((strcmp(person, *gptr->gr_mem)) == 0)
					break;
				gptr->gr_mem++;
			}
			if (*gptr->gr_mem == NULL)
				errx(1, "Not a member of the restricted group");
		}
	}
	/*
	 * Check to make sure queuing is enabled if real_uid is not root.
	 */
	(void)snprintf(buf, sizeof(buf), "%s/%s", SD, LO);
	if (real_uid && stat(buf, &stb) == 0 && (stb.st_mode & 010))
		errx(1, "Printer queue is disabled");
	/*
	 * Initialize the control file.
	 */
	mktemps();
	tfd = nfile(tfname);
	card('H', host);
	card('P', person);
	if (hdr) {
		if (jobname == NULL) {
			if (argc == 0)
				jobname = "stdin";
			else
				jobname = (arg = strrchr(argv[0], '/')) ?
				    arg + 1 : argv[0];
		}
		card('J', jobname);
		card('C', class);
		if (!SH)
			card('L', person);
	}
	if (iflag)
		card('I', itoa(indent));
	if (mailflg)
		card('M', person);
	if (format == 't' || format == 'n' || format == 'd')
		for (i = 0; i < 4; i++)
			if (fonts[i] != NULL)
				card('1'+i, fonts[i]);
	if (width != NULL)
		card('W', width);

	/*
	 * Read the files and spool them.
	 */
	if (argc == 0)
		copy(0, " ");
	else while (argc--) {
		if (argv[0][0] == '-' && argv[0][1] == '\0') {
			/* use stdin */
			copy(0, " ");
			argv++;
			continue;
		}
		if ((f = test(arg = *argv++)) < 0)
			continue;	/* file unreasonable */

		if (sflag && (cp = linked(arg)) != NULL) {
			(void)snprintf(buf, sizeof(buf), "%d %d",
			    statb.st_dev, statb.st_ino);
			card('S', buf);
			if (format == 'p')
				card('T', title ? title : arg);
			for (i = 0; i < ncopies; i++)
				card(format, &dfname[inchar-2]);
			card('U', &dfname[inchar-2]);
			if (f)
				card('U', cp);
			card('N', arg);
			dfname[inchar]++;
			nact++;
			continue;
		}
		if (sflag)
			warnx("%s: not linked, copying instead", arg);
		if ((i = safe_open(arg, O_RDONLY, 0)) < 0)
			warn("%s", arg);
		else {
			copy(i, arg);
			(void)close(i);
			if (f && unlink(arg) < 0)
				warnx("%s: not removed", arg);
		}
	}

	if (nact) {
		(void)close(tfd);
		tfname[inchar]--;
		/*
		 * Touch the control file to fix position in the queue.
		 */
		PRIV_START;
		if ((tfd = safe_open(tfname, O_RDWR|O_NOFOLLOW, 0)) >= 0) {
			char c;

			if (read(tfd, &c, 1) == 1 &&
			    lseek(tfd, (off_t)0, SEEK_SET) == 0 &&
			    write(tfd, &c, 1) != 1) {
				warn("%s", tfname);
				tfname[inchar]++;
				cleanup(0);
			}
			(void)close(tfd);
		}
		if (link(tfname, cfname) < 0) {
			warn("cannot rename %s", cfname);
			tfname[inchar]++;
			cleanup(0);
		}
		unlink(tfname);
		PRIV_END;
		if (qflag)		/* just q things up */
			exit(0);
		if (!startdaemon(printer))
			printf("jobs queued, but cannot start daemon.\n");
		exit(0);
	}
	cleanup(0);
	return (1);
	/* NOTREACHED */
}
Exemple #12
0
void CToxOptionsNodeList::OnInitDialog()
{
	m_nodes.SetExtendedListViewStyle(LVS_EX_SUBITEMIMAGES | LVS_EX_FULLROWSELECT | LVS_EX_LABELTIP);

	HIMAGELIST hImageList = m_nodes.CreateImageList(LVSIL_SMALL);
	HICON icon = Skin_LoadIcon(SKINICON_OTHER_TYPING);
	ImageList_AddIcon(hImageList, icon); IcoLib_ReleaseIcon(icon);
	icon = Skin_LoadIcon(SKINICON_OTHER_DELETE);
	ImageList_AddIcon(hImageList, icon); IcoLib_ReleaseIcon(icon);

	m_nodes.AddColumn(0, _T("IPv4"), 100);
	m_nodes.AddColumn(1, _T("IPv6"), 100);
	m_nodes.AddColumn(2, TranslateT("Port"), 50);
	m_nodes.AddColumn(3, TranslateT("Public key"), 130);
	m_nodes.AddColumn(4, _T(""), 32 - GetSystemMetrics(SM_CXVSCROLL));
	m_nodes.AddColumn(5, _T(""), 32 - GetSystemMetrics(SM_CXVSCROLL));

	m_nodes.EnableGroupView(TRUE);
	m_nodes.AddGroup(0, TranslateT("Common nodes"));
	m_nodes.AddGroup(1, TranslateT("User nodes"));

	////////////////////////////////////////

	int iItem = -1;

	if (CToxProto::IsFileExists((TCHAR*)VARST(_T(TOX_INI_PATH))))
	{
		char fileName[MAX_PATH];
		mir_strcpy(fileName, VARS(TOX_INI_PATH));

		char *section, sections[MAX_PATH], value[MAX_PATH];
		GetPrivateProfileSectionNamesA(sections, _countof(sections), fileName);
		section = sections;
		while (*section != NULL)
		{
			if (strstr(section, TOX_SETTINGS_NODE_PREFIX) == section)
			{
				GetPrivateProfileStringA(section, "IPv4", NULL, value, _countof(value), fileName);
				iItem = m_nodes.AddItem(mir_a2t(value), -1, NULL, 0);

				GetPrivateProfileStringA(section, "IPv6", NULL, value, _countof(value), fileName);
				m_nodes.SetItem(iItem, 1, mir_a2t(value));

				GetPrivateProfileStringA(section, "Port", NULL, value, _countof(value), fileName);
				m_nodes.SetItem(iItem, 2, mir_a2t(value));

				GetPrivateProfileStringA(section, "PubKey", NULL, value, _countof(value), fileName);
				m_nodes.SetItem(iItem, 3, mir_a2t(value));
			}
			section += mir_strlen(section) + 1;
		}
	}

	char module[MAX_PATH], setting[MAX_PATH];
	mir_snprintf(module, "%s_Nodes", m_proto->m_szModuleName);
	int nodeCount = db_get_w(NULL, module, TOX_SETTINGS_NODE_COUNT, 0);
	for (int i = 0; i < nodeCount; i++)
	{
		mir_snprintf(setting, TOX_SETTINGS_NODE_IPV4, i);
		ptrT value(db_get_tsa(NULL, module, setting));
		iItem = m_nodes.AddItem(value, -1, NULL, 1);

		mir_snprintf(setting, TOX_SETTINGS_NODE_IPV6, i);
		value = db_get_tsa(NULL, module, setting);
		m_nodes.SetItem(iItem, 1, value);

		mir_snprintf(setting, TOX_SETTINGS_NODE_PORT, i);
		int port = db_get_w(NULL, module, setting, 0);
		if (port > 0)
		{
			char portNum[10];
			itoa(port, portNum, 10);
			m_nodes.SetItem(iItem, 2, mir_a2t(portNum));
		}

		mir_snprintf(setting, TOX_SETTINGS_NODE_PKEY, i);
		value = db_get_tsa(NULL, module, setting);
		m_nodes.SetItem(iItem, 3, value);

		m_nodes.SetItem(iItem, 4, _T(""), 0);
		m_nodes.SetItem(iItem, 5, _T(""), 1);
	}
}
Exemple #13
0
/* modify by Suttipong Kanakakorn Tue  08-29-1989  23:53:53 */
void printing(void)
{
    extern int blankskip();
    extern int pic_print;
    int i,j   ;
    int printquit;
    char st[5] ;
    char s[500] ;
    char p[500] ;
    char scol   ;
    if (graphicprint==YES)        /* if print in graphic mode */
       initializebufferandfont(); /* allocate graphic buffer and load font */
    scol=7;
    dispstrhgc("¡ÓÅѧ¾ÔÁ¾ì COPY·Õè :     ",10-scol,12,0);
    dispstrhgc("  ˹éÒ·Õè :     ",30-scol,12,0);
    dispstrhgc("  ºÃ÷Ѵ·Õè :     ",43-scol,12,0);
    dispstrhgc("  ËÂØ´ªÑèǤÃÒÇ <P> àÅÔ¡¾ÔÁ¾ì <Q>",58-scol,12,BOLDATTR);
    printquit = NO;
    PrinterInitialize();                     /* initialize printer */
    PrinterMasterSelectMode(0);              /*  Set to 10 Cpi */
    for (i=1; i<=copytoprint; i++) {
        linespace = find_line_space();
        PrinterSetFormLenghtInch(pagelength);
        seekbeginline();
        /*
        itoa(i,st,10);
        dispstrhgc("     ",25 - scol,12,0);
        dispstrhgc(st,30 - strlen(st) - scol,12,2);
        */
        dispprintf(25 - scol, 12 ,2, "%5d", i);
        curpage = pagenumberoffset;
        /*
        itoa(curpage,st,10);
        dispstrhgc("     ",38 - scol ,12,0);
        dispstrhgc(st,43 - strlen(st) - scol ,12,2);
        */
        dispprintf(38 - scol, 12, 0, "%5d", curpage);
        curline = 0;
        pic_print = NO;
        while ((fgets(s,500,fp) != NULL) && (printquit==NO)) {
            strfilter(s,0x8d);         /* delete 0x8d */
            strcpy(p,s);
            j=0;
            while ((p[j]<32) && (p[j]!=NULL)) j++;
            if (p[j] == '.') {    /* -to allow free format.       */
                dotcommand(&p[j]); /* do dotcommand then read next */
                if (newpage == YES) {  /* page break dotcmd (.pa ,.cp) found */
                    newpage = NO;      /* reset pagebreak status */
                    /*
                    PrinterSkipLine(((29+1)-(locpagetitle!=0)-(locheading!=0)
                                   -(locfooting!=0)-curline)*2 );
                    */
                    skip_line((userlineperpage+1) - curline);
                    curline = 0   ;
                    printtitle(footing,locfooting);
                    PrinterFormFeed();
                    if (curpage >= pageend-pagebegin+pagenumberoffset) break;
                    pagewait(0);  /* finish each page */
                    curpage++     ;
                    /*
                    itoa(curpage,st,10);
                    dispstrhgc("     ",38 - scol ,12,0);
                    dispstrhgc(st,43 - strlen(st) - scol ,12,2);
                    */
                    dispprintf(38 - scol, 12, 0, "%5d", curpage);
                }
	    } else {  /* Not dot commands */
                if (mailmergeflag == YES) {
                    mailmerge(s,p);
                    strcpy(s,p);
                }
                if (stdcode == NO) {
                    contostd(s);   /* convert from ku to so-mo-or */
                }
                marginset(s);      /* set left-right margin */
                if  (curline == 0)  {
                    printtitle(heading,locheading);
                    sprintf(p,pageformat,curpage);
                    printtitle(p,locpagetitle);
                    curline++;     /* begin curline = 1  */
                }
                /*
                itoa(curline,st,10);
                dispstrhgc("     ",53 - scol ,12,0);
                dispstrhgc(st,58 - strlen(st) - scol ,12,2);
                dispstrhgc(blankline,2,13,0);
                */
                dispprintf(53 - scol, 12, 0, "%5d", curline);
		dispprintf(2, 13, NORMALATTR, "%77s", " ");  /* Clear Line */
		dispprintf(2, 13, 0, "%-77.77s", s);         /* Disp CurLine */
/*
                dispstrhgc(extbarprinting ? "*":"-",1,1,REVERSEATTR);
*/
                preprinterloadline(s);
                curline++;
                if (curline > userlineperpage) {
                    curline = 0   ;
                    printtitle(footing,locfooting);
                    PrinterFormFeed();
                    if (curpage >= pageend-pagebegin+pagenumberoffset)
                        break;
                    pagewait(0);  /* finish each page */
                    curpage++     ;
                    itoa(curpage,st,10);
                    dispstrhgc("     ",38 - scol ,12,0);
                    dispstrhgc(st,43 - strlen(st) - scol ,12,2);
                }
                linewait(&printquit);
            }  /* end case of non-dotcommand  */
        }     /* end while */
        if (curline != 0) {
            /*
            PrinterSkipLine(((29+1)-(locpagetitle!=0)-(locheading!=0)
                          -(locfooting!=0)-curline) *2 ); /* skip to bottom */
            */
            skip_line((userlineperpage+1) - curline);
            printtitle(footing,locfooting);
            PrinterFormFeed();
        }
        fseek(fp,0L,SEEK_SET);  /* rewind file pointer */
        if (printquit==YES) break; /* exit for loop */
        pagewait(1);  /* finish each copy */
    }
Exemple #14
0
// This is the menu item draw callback where you specify what each item should look like
static void menu_draw_row_callback(GContext* ctx, const Layer *cell_layer, MenuIndex *cell_index, void *data) {
  snprintf(yup, 2, "%c", all_answers[cell_index->row*2+1]);
  menu_cell_basic_draw(ctx, cell_layer, itoa(all_answers[cell_index->row*2]), yup, NULL);
}
void vmsHttpFlvTrafficAnalyzer5::LogMainCall (int iCall, LPCSTR pszHtmlPageUrl, LPCSTR pszFrameUrl, LPCSTR pszSwfUrl, LPCSTR pszFlashVars, vector <string> &vOtherSwfUrls, vector <string> &vOtherFlashVars, const vmsWinSockHttpDlgTree *pDlgTree, HTTPDLGTREEITEM pWebPage, HTTPDLGTREEITEM pFrame)
{
	TCHAR tszFile [MAX_PATH] = _T ("");
	GetTempPath (MAX_PATH, tszFile);
	_tcscat (tszFile, _T ("\\fdmflvsniff\\onDownloadIt-"));
	
	_stprintf (tszFile + _tcslen (tszFile), _T ("%03d.html"), iCall);

	HANDLE hFile = CreateFile (tszFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	assert (hFile != INVALID_HANDLE_VALUE);
	if (hFile == INVALID_HANDLE_VALUE)
		return;

	char szTmp [100] = "";

	string strHtml = "<html><body><h3>vmsHttpFlvTrafficAnalyzer5 onGetItButtonClicked</h3>"; 

	strHtml += "<b>Web page URL:</b><br>"; 
	strHtml += pszHtmlPageUrl ? pszHtmlPageUrl : "";
	assert (pWebPage != NULL);
	if (pWebPage)
	{
		strHtml += "<br>[<a href="; strHtml += itoa (pWebPage->spDlg->nID, szTmp, 16);
		strHtml += "-tree.html>tree</a>][<a href=webfiles\\";
		strHtml += szTmp; strHtml += ".txt>file</a>]";
	}
	strHtml += "<br><br>";

	strHtml += "<b>Frame URL:</b><br>";
	strHtml += pszFrameUrl && *pszFrameUrl && strcmp (pszHtmlPageUrl, pszFrameUrl) ? pszFrameUrl : "Not specified (none)";
	if (pFrame && pFrame != pWebPage)
	{
		strHtml += "<br>[<a href="; strHtml += itoa (pFrame->spDlg->nID, szTmp, 16);
		strHtml += "-tree.html>tree</a>][<a href=webfiles\\";
		strHtml += szTmp; strHtml += ".txt>file</a>]";
	}
	strHtml += "<br><br>";

	strHtml += "<b>Target SWF URL:</b><br>";
	strHtml += pszSwfUrl && *pszSwfUrl ? pszSwfUrl : "";
	strHtml += "<br><br>";

	strHtml += "<b>Target SWF FlashVars:</b><br>";
	strHtml += pszFlashVars ? pszFlashVars : "";
	strHtml += "<br><br>";

	assert (vOtherSwfUrls.size () == vOtherFlashVars.size ());

	if (vOtherSwfUrls.size () != vOtherFlashVars.size ())
		strHtml += "<b>ARGS ERROR: vOtherSwfUrls.size () != vOtherFlashVars.size ()</b><br><br>";
	else for (size_t i = 0; i < vOtherSwfUrls.size (); i++)
	{
		char sz [10] = ""; itoa (i, sz, 10);

		strHtml += "<b>Other SWF #"; strHtml += sz; strHtml += " URL:</b><br>";
		strHtml += vOtherSwfUrls [i].c_str ();
		strHtml += "<br><br>";
		
		strHtml += "<b>Other SWF #"; strHtml += sz; strHtml += " FlashVars:</b><br>";
		strHtml += vOtherFlashVars [i].c_str ();
		strHtml += "<br><br>";
	}
	
	DWORD dw = 0;
	WriteFile (hFile, strHtml.c_str (), strHtml.length (), &dw, NULL);

	CloseHandle (hFile);
}
Exemple #16
0
Text::Text(int i) {
	string = (char*)malloc(sizeof(int));
	itoa(i, string, 10);
}
byte ESP8266_Simple::serveHttpRequest()
{
  if(!this->espSerial->available()) return ESP8266_OK; // Nothing to do

  char cmdBuffer[64];
  char hdrBuffer[45];     
  
  char dataBuffer[this->httpServerMaxBufferSize];
  int  requestLength;
  byte responseCode;
  unsigned long  httpStatusCodeAndType;
  int  muxChannel = -1; // This will be set by readIPD(), we need to start with -1
                        // to indicate we will accept any channel, we will get
                        // packet data for whatever channel is first off the block
                        // any inter-mingled packet data from other channels is discarded
                        // for best results, only issue one request at a time!
  
  memset(dataBuffer,0,sizeof(dataBuffer));
  
  if((requestLength = this->readIPD(dataBuffer,sizeof(dataBuffer),-1,NULL,&muxChannel)))
  {
    // Call the handler, note we reserve the last byte of the data buffer
    // it will always be null for safety
    if(this->httpServerRequestHandler)
    {
      httpStatusCodeAndType = (*(this->httpServerRequestHandler))(dataBuffer,sizeof(dataBuffer)-1);
    }
    else
    {      
      httpStatusCodeAndType = this->httpServerRequestHandler_Builtin(dataBuffer, sizeof(dataBuffer)-1);
    }
    
    // Ensure that the last byte of the buffer is null for safety
    dataBuffer[sizeof(dataBuffer)-1] = 0;
    
    // Clear header and command buffer
    memset(hdrBuffer, 0, sizeof(hdrBuffer));
    memset(cmdBuffer,0,sizeof(cmdBuffer));
    
    // If it's not a raw response, make some headers
    if(!(httpStatusCodeAndType & ESP8266_RAW))
    {
      strncpy_P(hdrBuffer, PSTR("HTTP/1.0 "), sizeof(hdrBuffer)-1);
      itoa( httpStatusCodeAndType & 0x00FFFFFF,hdrBuffer+strlen(hdrBuffer), 10);
      strncpy_P(hdrBuffer+strlen(hdrBuffer), PSTR("\r\nContent-type: "), sizeof(hdrBuffer)-strlen(hdrBuffer)-1);
      
      switch(httpStatusCodeAndType & 0xFF000000)
      {
        case ESP8266_HTML:
          strncpy_P(hdrBuffer+strlen(hdrBuffer), PSTR("text/html"), sizeof(hdrBuffer)-strlen(hdrBuffer)-1);
          break;
          
        case ESP8266_TEXT:
          strncpy_P(hdrBuffer+strlen(hdrBuffer), PSTR("text/plain"), sizeof(hdrBuffer)-strlen(hdrBuffer)-1);
          break;          

      }
      strncpy_P(hdrBuffer+strlen(hdrBuffer), PSTR("\r\n\r\n"), sizeof(hdrBuffer)-strlen(hdrBuffer)-1);
    }
    
    // Create the send command which specifies the mux channel and data length    
    strncpy_P(cmdBuffer,PSTR("AT+CIPSEND="),sizeof(cmdBuffer));
    itoa(muxChannel,cmdBuffer+strlen(cmdBuffer),10); // With Mux
    cmdBuffer[strlen(cmdBuffer)]=',';
    itoa(strlen(hdrBuffer)+min(sizeof(dataBuffer)-1,strlen(dataBuffer)), cmdBuffer+strlen(cmdBuffer),10);
    
    if((responseCode = this->sendCommand(cmdBuffer)) != ESP8266_OK) 
    {
      return responseCode;
    }
    
    this->espSerial->print(hdrBuffer);
    this->espSerial->print(dataBuffer);
    
    memset(cmdBuffer,0,sizeof(cmdBuffer));
    strncpy_P(cmdBuffer, PSTR("AT+CIPCLOSE="), sizeof(cmdBuffer)-1);
    itoa(muxChannel, cmdBuffer+strlen(cmdBuffer),10);
    if((responseCode = this->sendCommand(cmdBuffer)) != ESP8266_OK)
    {
      return responseCode;
    }      
  }
  
  return ESP8266_OK;
}
void CFlashMenuObject::UpdateSingleplayerDifficulties()
{
	if(!m_apFlashMenuScreens[MENUSCREEN_FRONTENDSTART])
		return;

	if(!m_pPlayerProfileManager)
		return;

	IPlayerProfile *pProfile = m_pPlayerProfileManager->GetCurrentProfile(m_pPlayerProfileManager->GetCurrentUser());
	if(!pProfile)
		return;

	string sGeneralPath = "Singleplayer.Difficulty";
	int iDifficulties = 8;
/*	for(int i=0; i<EDifficulty_END; ++i)
	{
		string sPath = sGeneralPath;
		char c[5];
		itoa(i, c, 10);
		sPath.append(c);
		sPath.append(".available");

		TFlowInputData data;
		pProfile->GetAttribute(sPath, data, false);
		bool bDone = false;
		data.GetValueWithConversion(bDone);
		if(bDone)
		{
			iDifficulties += i*2;
		}
	}
*/
	int iDifficultiesDone = 0;
	for(int i=0; i<EDifficulty_END; ++i)
	{
		string sPath = sGeneralPath;
		char c[5];
		itoa(i, c, 10);
		sPath.append(c);
		sPath.append(".done");

		TFlowInputData data;
		pProfile->GetAttribute(sPath, data, false);
		bool bDone = false;
		data.GetValueWithConversion(bDone);
		if(bDone)
		{
			iDifficultiesDone += std::max(i*2,1);
		}
	}

	TFlowInputData data;
	pProfile->GetAttribute("Singleplayer.LastSelectedDifficulty", data, false);
	int iDiff = 2;
	data.GetValueWithConversion(iDiff);

	if(iDiff<=0)
	{
		iDiff = 2;
	}

	m_apFlashMenuScreens[MENUSCREEN_FRONTENDSTART]->Invoke("Root.MainMenu.SinglePlayer.enableDifficulties", iDifficulties);
	m_apFlashMenuScreens[MENUSCREEN_FRONTENDSTART]->Invoke("Root.MainMenu.SinglePlayer.enableDifficultiesStats", iDifficultiesDone);
	m_apFlashMenuScreens[MENUSCREEN_FRONTENDSTART]->Invoke("Root.MainMenu.SinglePlayer.selectDifficulty", iDiff);
}
Exemple #19
0
id0_int_t DebugKeys (void)
{
    id0_boolean_t esc;
    id0_int_t level,i;

#if 0
    if (Keyboard[sc_A])
    {
        id0_char_t levelstr[50];
        id0_unsigned_t org_tile,org_mapon,msgnum;
        id0_boolean_t newmsg=true,newlevel=false;

        VW_FixRefreshBuffer ();
        CenterWindow (16,3);
        US_Print("\n");
        US_CPrint("Message Test");
        VW_UpdateScreen();

        org_mapon = mapon;
        msgnum = (org_tile = *(mapsegs[0]+farmapylookup[player->tiley]+player->tilex))-NAMESTART;
        while (1)
        {
            // Get outta' here
            //
            if (Keyboard[sc_Escape])
            {
                while (Keyboard[sc_Escape])
                {
                    BE_ST_ShortSleep();
                }
                break;
            }

            // Move to previous message
            //
            if (Keyboard[sc_UpArrow])
            {
                if (msgnum)
                {
                    msgnum--;
                    newmsg = true;
                }
            }

            // Move to next message
            //
            if (Keyboard[sc_DownArrow])
            {
                if (msgnum < 24)
                {
                    msgnum++;
                    newmsg = true;
                }
            }

            // Move to previous level
            //
            if (Keyboard[sc_LeftArrow])
            {
                if (mapon)
                {
                    MM_SetPurge(&grsegs[LEVEL1TEXT+mapon],3);
                    mapon--;
                    newlevel = true;
                }
            }

            // Move to next level
            //
            if (Keyboard[sc_RightArrow])
            {
                if (mapon < LASTMAP-2)
                {
                    MM_SetPurge(&grsegs[LEVEL1TEXT+mapon],3);
                    mapon++;
                    newlevel = true;
                }
            }

            // Load new level text
            //
            if (newlevel)
            {
                CA_CacheGrChunk(LEVEL1TEXT+mapon);
                ScanText();
                newmsg = true;
                newlevel=false;
            }

            // Display new message text
            //
            if (newmsg)
            {
                *(mapsegs[0]+farmapylookup[player->tiley]+player->tilex) = msgnum+NAMESTART;
                DrawText(true);
                strcpy(levelstr,"Level: ");
                itoa(mapon,levelstr+strlen(levelstr),10);
                strcat(levelstr,"  Msg: ");
                itoa(msgnum,levelstr+strlen(levelstr),10);
                DisplaySMsg(levelstr,NULL);
                newmsg = false;

                if (Keyboard[sc_UpArrow] || Keyboard[sc_DownArrow] || Keyboard[sc_LeftArrow] || Keyboard[sc_RightArrow])
                    VW_WaitVBL(6);
            }

            BE_ST_ShortSleep();
        }
// Restore game
//
        MM_SetPurge(&grsegs[LEVEL1TEXT+mapon],3);
        mapon = org_mapon;
        CA_CacheGrChunk(LEVEL1TEXT+mapon);
        ScanText();
        *(mapsegs[0]+farmapylookup[player->tiley]+player->tilex) = org_tile;
        DrawText(true);
        status_flag = 0;
    }
#endif

    if (Keyboard[sc_T])
    {
        VW_FixRefreshBuffer ();
        CenterWindow (16,4);

        US_Print("Tics      :");
        US_PrintUnsigned (tics);
        US_Print("\nReal Tics :");
        US_PrintUnsigned(realtics);
        VW_UpdateScreen();
        IN_Ack ();
    }

    if (Keyboard[sc_V])
    {
        displayofs = bufferofs = screenloc[screenpage];
        CenterWindow (20,5);
        US_CPrint(refkeen_compat_gelib_c4_debug_str_with_gamename);
        //US_CPrint("\n"GAMENAME);
        US_CPrint(VERSION);
        US_CPrint(REVISION);
        VW_UpdateScreen();
        IN_Ack ();
    }

    if (Keyboard[sc_Q])			// Q = Insta-Quit!
        Quit("Insta-Quit!");

    if (Keyboard[sc_Z])		// Z = freeze Time
    {
        if (FreezeTime)
            FreezeTime = 1;		// Allow refresh to dec to zero..
        else
            StopTime();

        IN_Ack();
        return 1;
    }

//	if (Keyboard[sc_E])
//		FaceDoor((player->x>>16l)+1,(player->y>>16l));
//		FaceAngle(90);

#if 0
    if (Keyboard[sc_B])		// B = border color
    {
        CenterWindow(24,3);
        PrintY+=6;
        US_Print(" Border color (0-15):");
        VW_UpdateScreen();
        esc = !US_LineInput (px,py,str,NULL,true,2,0);
        if (!esc)
        {
            level = atoi (str);
            if (level>=0 && level<=15)
                VW_ColorBorder (level);
        }
        return 1;
    }
#endif

#if 0
    if (Keyboard[sc_C])		// C = count objects
    {
        CountObjects();
        return 1;
    }


    if (Keyboard[sc_D])		// D = start / end demo record
    {
        if (DemoMode == demo_Off)
            StartDemoRecord ();
        else if (DemoMode == demo_Record)
        {
            EndDemoRecord ();
            playstate = ex_completed;
        }
        return 1;
    }
#endif

#if 0
    if (Keyboard[sc_E])		// E = quit level
    {
        if (tedlevel)
            TEDDeath();
        playstate = ex_warped;
        gamestate.mapon++;
    }
#endif

#if 0
    if (Keyboard[sc_F])		// F = facing spot
    {
        CenterWindow (12,4);
        US_Print ("X:");
        US_PrintUnsigned (player->x);
        US_Print ("Y:");
        US_PrintUnsigned (player->y);
        US_Print ("A:");
        US_PrintUnsigned (player->angle);
        VW_UpdateScreen();
        IN_Ack();
        return 1;
    }
#endif

    if (Keyboard[sc_G])		// G = god mode
    {
        CenterWindow (12,2);
        if (godmode)
            US_PrintCentered ("God mode OFF");
        else
            US_PrintCentered ("God mode ON");
        VW_UpdateScreen();
        IN_Ack();
        godmode ^= 1;
        return 1;
    }

#if 0
    if (Keyboard[sc_H])		// H = hurt self
    {
        TakeDamage (5);
    }
#endif

    if (Keyboard[sc_I])			// I = item cheat
    {
        extern id0_boolean_t redraw_gems;

        CenterWindow (12,3);
        US_PrintCentered ("Free items!");
        VW_UpdateScreen();
        for (i=0; i<4; i++)
        {
            GiveBolt ();
            GiveNuke ();
            GivePotion ();
//			if (!gamestate.keys[i])
            GiveKey (i);
            gamestate.gems[i] = GEM_DELAY_TIME;
        }
        gamestate.gems[4] = GEM_DELAY_TIME;
        redraw_gems = true;
        for (i=0; i<8; i++)
            GiveScroll (i,false);

        IN_Ack ();
        return 1;
    }

    if (Keyboard[sc_M])			// M = memory info
    {
        DebugMemory();
        return 1;
    }

#if DEBUG_OVERHEAD
    if (Keyboard[sc_O])			// O = overhead
    {
        ViewMap();
        return 1;
    }
#endif

#if 0
    if (Keyboard[sc_P])			// P = pause with no screen disruptioon
    {
        PicturePause ();
        return 1;
    }
#endif

#if 0
    if (Keyboard[sc_S])	// S = slow motion
    {
        singlestep^=1;
        CenterWindow (18,3);
        if (singlestep)
            US_PrintCentered ("Slow motion ON");
        else
            US_PrintCentered ("Slow motion OFF");
        VW_UpdateScreen();
        IN_Ack ();
        return 1;
    }
#endif

#if 0
    if (Keyboard[sc_V])			// V = extra VBLs
    {
        CenterWindow(30,3);
        PrintY+=6;
        US_Print("  Add how many extra VBLs(0-8):");
        VW_UpdateScreen();
        esc = !US_LineInput (px,py,str,NULL,true,2,0);
        if (!esc)
        {
            level = atoi (str);
            if (level>=0 && level<=8)
                extravbls = level;
        }
        return 1;
    }
#endif

    if (Keyboard[sc_W])	// W = warp to level
    {
        CenterWindow(26,3);
        PrintY+=6;
        US_Print("  Warp to which level(0-18):");
        VW_UpdateScreen();
        esc = !US_LineInput (px,py,str,NULL,true,2,0);
        if (!esc)
        {
            level = atoi (str);
            if (level>=0 && level<=LASTMAP-1)
            {
                gamestate.mapon = level;
                playstate = ex_warped;
                lasttext = -1;
            }
        }
        return 1;
    }

#if 0
    if (Keyboard[sc_X])			// X = item cheat
    {
        CenterWindow (12,3);
        US_PrintCentered ("Extra stuff!");
        VW_UpdateScreen();
        for (i=0; i<4; i++)
        {
            GiveBolt ();
            GiveNuke ();
            GivePotion ();
        }
        IN_Ack ();
        return 1;
    }
#endif

    if (LastScan >= sc_1 && LastScan <= sc_8)	// free scrolls
    {
        GiveScroll (LastScan-sc_1,false);
        IN_ClearKeysDown ();
    }

    return 0;
}
// *************************************************************************************************
// @fn          display_altitude
// @brief       Display routine. Supports display in meters and feet. 
// @param       u8 line         LINE1
//              u8 update       DISPLAY_LINE_UPDATE_FULL, DISPLAY_LINE_UPDATE_PARTIAL, DISPLAY_LINE_CLEAR
// @return      none
// *************************************************************************************************
void display_altitude(u8 line, u8 update)
{
    u8 * str;
    s16 ft;
    
    // redraw whole screen
    if (update == DISPLAY_LINE_UPDATE_FULL) 
    {
        // Enable pressure measurement
        sAlt.state = MENU_ITEM_VISIBLE;

        // Start measurement
        start_altitude_measurement();
        
        // Display altitude
        display_altitude(LINE1, DISPLAY_LINE_UPDATE_PARTIAL);
    }
    else if (update == DISPLAY_LINE_UPDATE_PARTIAL)
    {
        // Update display only while measurement is active
        if (sAlt.timeout > 0)
        {
            // Altitude view
            if (PressDisplay == DISPLAY_DEFAULT_VIEW)
            {
                display_symbol(LCD_SEG_L1_DP1, SEG_OFF);
                if (sys.flag.use_metric_units)
                {
                    // Display "m" symbol
                    display_symbol(LCD_UNIT_L1_M, SEG_ON);
                    // Display altitude in xxxx m format, allow 3 leading blank digits
                    if (sAlt.altitude >= 0)
                    {
                        str = itoa(sAlt.altitude, 4, 3);
                        display_symbol(LCD_SYMB_ARROW_UP, SEG_ON);
                        display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
                    }
                    else
                    {
                        str = itoa(sAlt.altitude*(-1), 4, 3);
                        display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
                        display_symbol(LCD_SYMB_ARROW_DOWN, SEG_ON);
                    }
                }
                else
                {
                    // Display "ft" symbol
                    display_symbol(LCD_UNIT_L1_FT, SEG_ON);                 
                    
                    // Convert from meters to feet
                    ft = convert_m_to_ft(sAlt.altitude);
                    
                    // Limit to 9999ft (3047m)
                    if (ft > 9999) ft = 9999;
                    
                    // Display altitude in xxxx ft format, allow 3 leading blank digits
                    if (ft >= 0)
                    {
                        str = itoa(ft, 4, 3);
                        display_symbol(LCD_SYMB_ARROW_UP, SEG_ON);
                        display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
                    }
                    else
                    {
                        str = itoa(ft*(-1), 4, 3);
                        display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
                        display_symbol(LCD_SYMB_ARROW_DOWN, SEG_ON);
                    }               
                }
            }
            // Pressure view, unit: milliBar = hectoPascal
            else if (PressDisplay == DISPLAY_ALTERNATIVE_VIEW)
            {
                display_symbol(LCD_SEG_L1_DP1, SEG_OFF);
                display_symbol(LCD_UNIT_L1_M, SEG_OFF);
                display_symbol(LCD_UNIT_L1_FT, SEG_OFF);
                display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
                display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
                str = itoa(AmbientPressure, 4, 3);
            }
            // Pressure view, unit: PSI (Pound-force per square inch absolute) 1mbar = 0.01450377 PSI
            else  // DISPLAY_ALTERNATIVE_VIEW_2
            {
                str = itoa((u32)AmbientPressure * 10000L / 6895L, 4, 3);
                display_symbol(LCD_SEG_L1_DP1, SEG_ON);
            }
            display_chars(LCD_SEG_L1_3_0, str, SEG_ON);
        }
    }
    else if (update == DISPLAY_LINE_CLEAR)
    {
        // Disable pressure measurement
        sAlt.state = MENU_ITEM_NOT_VISIBLE;

        // Stop measurement
        stop_altitude_measurement();
        
        // Clean up function-specific segments before leaving function
        display_symbol(LCD_SEG_L1_DP1, SEG_OFF);
        display_symbol(LCD_UNIT_L1_M, SEG_OFF);
        display_symbol(LCD_UNIT_L1_FT, SEG_OFF);
        display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
        display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
    }
}
Exemple #21
0
int speed()
{
int a,dd,xxx=99+(50*4),ii,count;
char *stt;
	setpos(0,0);
	viewport();
	count=zzz;
	xxx=99+(count*4);
	settextstyle(3,0,3);
	setcolor(14);
	outtextxy(100,100,"Speed Level");
	status("  Increment : [->]           Decrement : [<-]         Accept : [Enter key]");
	rectangle(99,249,500,276);
	setfillstyle(SOLID_FILL,4);
	bar(100,250,xxx,275);
	goto df;
   cd: while(1)
	{
		if(kbhit())
		{
		      dd=getch();
		      switch(dd)
		      {
			case 77:
				if(count==100)
				     continue;
				count++;
				for(ii=0;ii<=3;ii++)
				{
					setcolor(4);
					xxx++;
					line(xxx,250,xxx,275);
				}
				break;
			case 75:
				if(count==0)
					continue;
					count--;
				for(ii=0;ii<=3;ii++)
				{
					setcolor(0);
					line(xxx,250,xxx,275);
					xxx--;
				}
				break;
			case 13:
				zzz=count;
				bb=(count/10)+1;
				a=450-(count*4);
				return a;
			}
		    df:	settextstyle(3,0,3);
			 itoa(count,stt,10);

			setfillstyle(SOLID_FILL,0);
			bar(200,180,300,240);
			setcolor(2);
			outtextxy(240,200,stt);
			goto cd;
		}

	}
       //	getch();
}
Exemple #22
0
static char *
exec_instr( pInstr s ) {
    pCell tc, tc2;
    char buffer[16];

    switch (s->opcode) {
    case SET:
	/* operand must be a string */
	tc = temp_pop();
	switch (tc->type) {
	case mu:
            fprintf(stderr, "exec_inst/SET: warning - unhandled case mu\n" );
            break;
	case string_t:
	    var_put(s->operand.contents.s, tc->contents.s);
	    break;
	case int_t:
	    var_put_int(s->operand.contents.s, tc->contents.i);
	    break;
	}
	break;
    case EMIT:
	tc = temp_pop();
	switch (tc->type) {
	case mu:
            fprintf(stderr, "exec_inst/EMIT: warning - unhandled case mu\n" );
            break;
	case string_t:
	    return tc->contents.s;
	case int_t:
	    sprintf(buffer, "%i", tc->contents.i);
	    return strdup(buffer);
	}
    case PUSHV:
	{
	    struct var *v = var_lookup(vars, s->operand.contents.s);
	    if (v == 0) {
		fprintf(stderr,
			"attempted to use unknown variable \"%s\" in expression.\n",
			s->operand.contents.s);
		push_str("(NULL)");
	    } else {
		switch (v->type) {
	        case mu:
                    fprintf(stderr, "exec_inst/PUSHV: warning - unhandled case mu\n" );
                    break;
		case string_t:
		    push_str(strdup(v->value.s));
		    break;
		case int_t:
		    push_int(v->value.i);
		    break;
		}
	    }
	}
	break;
    case INVOKE:
	{
	    pRule r = rule_find(rule_base, s->operand.contents.s);
	    if (r) {
		push_str(resolve_rule(rule_base, r));
	    } else {
		fprintf(stderr,
			"attempted to invoke non-existent rule \"%s\" in expression.\n",
			s->operand.contents.s);
		push_str(NULL);
	    }
	}
	break;
    case PUSH:
	switch (s->operand.type) {
	case mu:
            fprintf(stderr, "exec_inst/PUSH: warning - unhandled case mu\n" );
            break;
	case string_t:
	    push_str(strdup(s->operand.contents.s));
	    break;
	case int_t:
	    push_int(s->operand.contents.i);
	    break;
	}
	break;
    case ADD:
	tc = temp_pop();
	tc2 = temp_pop();
	if ((tc->type == int_t) && (tc2->type == int_t)) {
	    push_int(tc->contents.i + tc2->contents.i);
	} else {
	    char *s0, *s1;
	    /* string concatenation */
	    s0 = ((tc->type ==
		   int_t) ? itoa(tc->contents.i) : (tc->contents.s));
	    s1 = ((tc2->type ==
		   int_t) ? itoa(tc2->contents.i) : (tc2->contents.s));
	    push_str(concat(s1, s0));
	    free(s0);
	    free(s1);
	}
	break;
    case SUB:
	tc = temp_pop();
	tc2 = temp_pop();
	if ((tc->type == int_t) && (tc2->type == int_t)) {
	    push_int(tc2->contents.i + tc->contents.i);
	}
	break;
    case MUL:
	tc = temp_pop();
	tc2 = temp_pop();
	if ((tc->type == int_t) && (tc2->type == int_t)) {
	    push_int(tc->contents.i * tc2->contents.i);
	}
	break;
    case DIV:
	tc = temp_pop();
	tc2 = temp_pop();
	if ((tc->type == int_t) && (tc2->type == int_t)) {
	    push_int(tc2->contents.i / tc->contents.i);
	}
	break;
    case MOD:
	tc = temp_pop();
	tc2 = temp_pop();
	if ((tc->type == int_t) && (tc2->type == int_t)) {
	    push_int(tc2->contents.i % tc->contents.i);
	}
	break;
    case RANDOM:
	tc2 = temp_pop();
	tc = temp_pop();
	if ((tc->type == int_t) && (tc2->type == int_t)) {
	    push_int((random() % (tc2->contents.i - tc->contents.i + 1))
		     + tc->contents.i);
	}
	break;
    case LESSER:
	tc2 = temp_pop();
	tc = temp_pop();
	if ((tc->type == int_t) && (tc2->type == int_t)) {
	    push_int(min(tc->contents.i, tc2->contents.i));
	}
	break;
    case GREATER:
	tc2 = temp_pop();
	tc = temp_pop();
	if ((tc->type == int_t) && (tc2->type == int_t)) {
	    push_int(max(tc->contents.i, tc2->contents.i));
	}
	break;
    }
    return NULL;
}
Exemple #23
0
std::string EQEmuConfig::GetByName(const std::string &var_name) const
{
	if (var_name == "ShortName") {
		return (ShortName);
	}
	if (var_name == "LongName") {
		return (LongName);
	}
	if (var_name == "WorldAddress") {
		return (WorldAddress);
	}
	if (var_name == "LoginHost") {
		return (LoginHost);
	}
	if (var_name == "LoginAccount") {
		return (LoginAccount);
	}
	if (var_name == "LoginPassword") {
		return (LoginPassword);
	}
	if (var_name == "LoginPort") {
		return (itoa(LoginPort));
	}
	if (var_name == "Locked") {
		return (Locked ? "true" : "false");
	}
	if (var_name == "WorldTCPPort") {
		return (itoa(WorldTCPPort));
	}
	if (var_name == "WorldIP") {
		return (WorldIP);
	}
	if (var_name == "TelnetEnabled") {
		return (TelnetEnabled ? "true" : "false");
	}
	if (var_name == "WorldHTTPPort") {
		return (itoa(WorldHTTPPort));
	}
	if (var_name == "WorldHTTPMimeFile") {
		return (WorldHTTPMimeFile);
	}
	if (var_name == "WorldHTTPEnabled") {
		return (WorldHTTPEnabled ? "true" : "false");
	}
	if (var_name == "ChatHost") {
		return (ChatHost);
	}
	if (var_name == "ChatPort") {
		return (itoa(ChatPort));
	}
	if (var_name == "MailHost") {
		return (MailHost);
	}
	if (var_name == "MailPort") {
		return (itoa(MailPort));
	}
	if (var_name == "DatabaseHost") {
		return (DatabaseHost);
	}
	if (var_name == "DatabaseUsername") {
		return (DatabaseUsername);
	}
	if (var_name == "DatabasePassword") {
		return (DatabasePassword);
	}
	if (var_name == "DatabaseDB") {
		return (DatabaseDB);
	}
	if (var_name == "DatabasePort") {
		return (itoa(DatabasePort));
	}
	if (var_name == "QSDatabaseHost") {
		return (QSDatabaseHost);
	}
	if (var_name == "QSDatabaseUsername") {
		return (QSDatabaseUsername);
	}
	if (var_name == "QSDatabasePassword") {
		return (QSDatabasePassword);
	}
	if (var_name == "QSDatabaseDB") {
		return (QSDatabaseDB);
	}
	if (var_name == "QSDatabasePort") {
		return (itoa(QSDatabasePort));
	}
	if (var_name == "SpellsFile") {
		return (SpellsFile);
	}
	if (var_name == "OpCodesFile") {
		return (OpCodesFile);
	}
	if (var_name == "MapDir") {
		return (MapDir);
	}
	if (var_name == "QuestDir") {
		return (QuestDir);
	}
	if (var_name == "PluginDir") {
		return (PluginDir);
	}
	if (var_name == "LogPrefix") {
		return (LogPrefix);
	}
	if (var_name == "LogSuffix") {
		return (LogSuffix);
	}
	if (var_name == "ZoneExe") {
		return (ZoneExe);
	}
	if (var_name == "ZonePortLow") {
		return (itoa(ZonePortLow));
	}
	if (var_name == "ZonePortHigh") {
		return (itoa(ZonePortHigh));
	}
	if (var_name == "DefaultStatus") {
		return (itoa(DefaultStatus));
	}
//	if(var_name == "DynamicCount")
//		return(itoa(DynamicCount));
	return ("");
}
Exemple #24
0
double CScript::LocalVar(const char* CmdStr, char* retStr)
{
    // 取第一个参数: 变量名字符串, 该脚本系统仅支持数组下标为$var变量,不支持[]嵌套
    // 如 $Var[$Var1],#strVar[$Var1];
    char* firstVarName = (char*)CmdStr;

    // 先循环到第一个参数处
    long cmdStrLen = strlen(CmdStr);
    long tCurPos = 0;
    while(*firstVarName != '(' && tCurPos < cmdStrLen && *firstVarName != '\0')
    {
        tCurPos++;
        firstVarName++;
    }

    if(*firstVarName == '(') // 跳过'('
        firstVarName++;

    if(firstVarName)
    {
        char MainVarName[1024];  // 变量
        char InnVarName[1024];   // 下标变量

        // 分解字符串第一个参数及下标
        long tempPos = 0;
        char* tMainPtr = MainVarName;
        char* tInnPtr = InnVarName;
        CheckParamStringForArray(firstVarName, cmdStrLen-tCurPos, &tMainPtr, 1024, &tInnPtr, 1024, tempPos);

        // 读取字符串值
        if(MainVarName[0] == '#') // 字符串
        {
            char* strValue = NULL;
            strValue = GetStringParam(CmdStr, 1);

            if(m_pVariableList && strValue)
            {
                if(InnVarName[0] == '\0') // 不是数组变量
                {
                    if(strValue[0] != '#') // 第二个参数不是变量
                        m_pVariableList->AddVar(MainVarName, strValue);
                    else
                    {
                        char* str2ndValue = (char*)m_pVariableList->GetVarValue(strValue);
                        if(str2ndValue)
                            m_pVariableList->AddVar(MainVarName, str2ndValue);
                    }
                }
                else// 是数组变量
                {
                    int lArray = 0;
                    if(InnVarName[0] == '$') // 下标是普通变量而非数组变量
                    {
                        lArray = GetScriptVarValue((CMoveShape*)p_SrcShape, InnVarName, 0);
                    }
                    else if(InnVarName[0] != '$' && InnVarName[0] != '#') // 下标是常量
                    {
                        lArray = atoi(InnVarName);
                    }

                    // 去掉'[' ']'
                    for(int i=0; i < lArray; i++)
                    {
                        char tNum[32];
                        char name[1024];
                        strcpy_s(name, 1024, MainVarName);
                        itoa(i, tNum, 10);
                        strcat(name, tNum);
                        m_pVariableList->AddVar(name, strValue);
                    }
                }
            }

            M_FREE( strValue, sizeof(char)*MAX_VAR_LEN );
        }
        else if(MainVarName[0] == '$') // 第一个参数是数字变量
        {
            double value = GetIntParam(CmdStr, 1);

            if(m_pVariableList && (value != ERROR_CODE) )
            {
                if(InnVarName[0] == '\0') // 不是数组变量
                {
                    m_pVariableList->AddVar(MainVarName, value);
                }
                else // 是数组变量
                {
                    int lArray = 0;
                    if(InnVarName[0] == '$') // 下标是普通变量
                    {
                        lArray = GetScriptVarValue((CMoveShape*)p_SrcShape, InnVarName, 0);

                    }
                    else if(InnVarName[0] != '$' && InnVarName[0] != '#') // 下标是常量
                    {
                        lArray = atoi(InnVarName);
                    }

                    // 去掉'[' ']'
                    m_pVariableList->AddVar(MainVarName, lArray, value);
                }
            }
        }

        else if(MainVarName[0] == '@') // 定义GUID
        {
            double value = GetIntParam(CmdStr, 1);

            if(m_pVariableList && (value != ERROR_CODE) )
            {
                if(InnVarName[0] == '\0') // 不是数组变量
                {
                    m_pVariableList->AddGuid(MainVarName, NULL_GUID);
                }
                else // 是数组变量
                {
                    int lArray = 0;
                    if(InnVarName[0] == '$') // 下标是普通变量
                    {
                        lArray = GetScriptVarValue((CMoveShape*)p_SrcShape, InnVarName, 0);
                    }
                    else if(InnVarName[0] != '$' && InnVarName[0] != '#') // 下标是常量
                    {
                        lArray = atoi(InnVarName);
                    }

                    // 去掉'[' ']'
                    for(int i=0; i < lArray; i++)
                    {
                        char tNum[32];
                        char name[1024];
                        strcpy_s(name, 1024, MainVarName);
                        itoa(i, tNum, 10);
                        strcat(name, tNum);
                        m_pVariableList->AddGuid(name, NULL_GUID);
                    }
                }
            }
        }

        //	SAFE_DELETE_ARRAY(firstVarName);
    }
    return 1;
}
UBool
ResourceBundleTest::testTag(const char* frag,
                            UBool in_Root,
                            UBool in_te,
                            UBool in_te_IN)
{
    int32_t failOrig = fail;

    // Make array from input params

    UBool is_in[] = { in_Root, in_te, in_te_IN };

    const char* NAME[] = { "ROOT", "TE", "TE_IN" };

    // Now try to load the desired items

    char tag[100];
    UnicodeString action;

    int32_t i,j,actual_bundle;
//    int32_t row,col;
    int32_t index;
    UErrorCode status = U_ZERO_ERROR;
    const char* testdatapath;
    testdatapath=loadTestData(status);
    if(U_FAILURE(status))
    {
        dataerrln("Could not load testdata.dat %s " + UnicodeString(u_errorName(status)));
        return FALSE;
    }

    for (i=0; i<bundles_count; ++i)
    {
        action = "Constructor for ";
        action += param[i].name;

        status = U_ZERO_ERROR;
        ResourceBundle theBundle( testdatapath, *param[i].locale, status);
        //ResourceBundle theBundle( "c:\\icu\\icu\\source\\test\\testdata\\testdata", *param[i].locale, status);
        CONFIRM_UErrorCode(status, param[i].expected_constructor_status, action);

        if(i == 5)
          actual_bundle = 0; /* ne -> default */
        else if(i == 3)
          actual_bundle = 1; /* te_NE -> te */
        else if(i == 4)
          actual_bundle = 2; /* te_IN_NE -> te_IN */
        else
          actual_bundle = i;


        UErrorCode expected_resource_status = U_MISSING_RESOURCE_ERROR;
        for (j=e_te_IN; j>=e_Root; --j)
        {
            if (is_in[j] && param[i].inherits[j])
            {
                if(j == actual_bundle) /* it's in the same bundle OR it's a nonexistent=default bundle (5) */
                  expected_resource_status = U_ZERO_ERROR;
                else if(j == 0)
                  expected_resource_status = U_USING_DEFAULT_WARNING;
                else
                  expected_resource_status = U_USING_FALLBACK_WARNING;
                
                break;
            }
        }

        UErrorCode expected_status;

        UnicodeString base;
        for (j=param[i].where; j>=0; --j)
        {
            if (is_in[j])
            {
                base = NAME[j];
                break;
            }
        }

        //--------------------------------------------------------------------------
        // string

        uprv_strcpy(tag, "string_");
        uprv_strcat(tag, frag);

        action = param[i].name;
        action += ".getString(";
        action += tag;
        action += ")";


        status = U_ZERO_ERROR;

        UnicodeString string(theBundle.getStringEx(tag, status));

        if(U_FAILURE(status)) {
            string.setTo(TRUE, kErrorUChars, kErrorLength);
        }

        CONFIRM_UErrorCode(status, expected_resource_status, action);

        UnicodeString expected_string(kErrorUChars);
        if (U_SUCCESS(status)) {
            expected_string = base;
        }

        CONFIRM_EQ(string, expected_string, action);

        //--------------------------------------------------------------------------
        // array

        uprv_strcpy(tag, "array_");
        uprv_strcat(tag, frag);

        action = param[i].name;
        action += ".get(";
        action += tag;
        action += ")";

        status = U_ZERO_ERROR;
        ResourceBundle arrayBundle(theBundle.get(tag, status));
        CONFIRM_UErrorCode(status, expected_resource_status, action);
        int32_t count = arrayBundle.getSize();

        if (U_SUCCESS(status))
        {
            CONFIRM_GE(count, 1, action);

            for (j=0; j < count; ++j)
            {
                char buf[32];
                UnicodeString value(arrayBundle.getStringEx(j, status));
                expected_string = base;
                expected_string += itoa(j,buf);
                CONFIRM_EQ(value, expected_string, action);
            }

            action = param[i].name;
            action += ".getStringEx(";
            action += tag;
            action += ")";

            for (j=0; j<100; ++j)
            {
                index = count ? (randi(count * 3) - count) : (randi(200) - 100);
                status = U_ZERO_ERROR;
                string = kErrorUChars;
                UnicodeString t(arrayBundle.getStringEx(index, status));
                expected_status = (index >= 0 && index < count) ? expected_resource_status : U_MISSING_RESOURCE_ERROR;
                CONFIRM_UErrorCode(status, expected_status, action);

                if (U_SUCCESS(status))
                {
                    char buf[32];
                    expected_string = base;
                    expected_string += itoa(index,buf);
                }
                else
                {
                    expected_string = kErrorUChars;
                }
                CONFIRM_EQ(string, expected_string, action);
            }
        }
        else if (status != expected_resource_status)
        {
            record_fail("Error getting " + (UnicodeString)tag);
            return (UBool)(failOrig != fail);
        }

    }

    return (UBool)(failOrig != fail);
}
Exemple #26
0
void uart::sendInt(const int16_t i)
{
    char itoa_tmp[7];
    itoa (i, itoa_tmp, 10);
    sendString(itoa_tmp);
}
Exemple #27
0
static void testPutInsideValue(int value,int base){
    char tmp[35];
    memset(tmp,0,35);
    itoa(value,tmp,35,base);
    testPutChar(0xb8000+120, tmp, strlen(tmp));
}
Exemple #28
0
void uart::sendInt(const uint8_t i)
{
    char itoa_tmp[4];
    itoa (i, itoa_tmp, 10);
    sendString(itoa_tmp);
}
Exemple #29
0
/**
 * main render function
 */
void render() {
	counter++;
	if(counter >= 36000){
		counter = 0;
	}
	//Typical render pass
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// update dimensions
	enable_2d();

	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	glPushMatrix();

		// if in portrait mode
		if (oriention_side_up > 0)
		{
			glVertexPointer(2, GL_FLOAT, 0, verticesH);
			glTexCoordPointer(2, GL_FLOAT, 0, tex_coordH);
		}
		// if in landscape mode
		else
		{
			glVertexPointer(2, GL_FLOAT, 0, vertices);
			glTexCoordPointer(2, GL_FLOAT, 0, tex_coord);
		}

		//portrait or landscape?
		glBindTexture(GL_TEXTURE_2D, oriention_side_up>0?backgroundH:background);
		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

	glPopMatrix();

	pp = points.begin();

	while (pp != points.end()) {

		if (pp->visible) {
			// draw touchpoint
			glPushMatrix();
				glTranslatef(pp->getX(), (oriention_side_up>0?1024:600) - pp->getY(), 0);
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				glVertexPointer(2, GL_FLOAT, 0, verticesTouchpoint);
				glTexCoordPointer(2, GL_FLOAT, 0, tex_coord_touchpoint);
				glBindTexture(GL_TEXTURE_2D, touchpoint);
				glPushMatrix();
					glRotatef((float) ((float)(pp->startRotation) + (float) counter / 0.25f), 0, 0, 1);
					glPushMatrix();
						glTranslatef(-60, -60, 0);
						glColor4f(pp->r,pp->g,pp->b,1);
						glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
					glPopMatrix();
				glPopMatrix();
			glPopMatrix();

			// draw touchpoint number
			glPushMatrix();
				glColor4f(0.3f,0.3f,0.3f,1.0f);
				char buffer [33];
				itoa (pp->id+1,buffer,10);
				glTranslatef(pp->getX()+50,(oriention_side_up>0?1024:600)-pp->getY()+50,0);
				glPushMatrix();
					bbutil_render_text(font,buffer,0,0);
				glPopMatrix();
			glPopMatrix();

		}
		pp++;
	}

	glColor4f(1.0f,1.0f,1.0f,1.0f);

	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	glDisableClientState(GL_VERTEX_ARRAY);

	//Use utility code to update the screen
	bbutil_swap();
}
void CUnitTable::Init() {
	// get the unitdefs and stick them in the unitTypes[] array
	numOfUnits = ai->cb->GetNumUnitDefs();
	unitList = new const UnitDef*[numOfUnits];
	ai->cb->GetUnitDefList(unitList);

	// one more than needed because [0] is a dummy object (so
	// UnitDef->id can be used to adress that unit in array)
	unitTypes = new UnitType[numOfUnits + 1];

	// add units to UnitTable
	for (int i = 1; i <= numOfUnits; i++) {
		unitTypes[i].def = unitList[i - 1];
		// side has not been assigned - will be done later
		unitTypes[i].category = -1;

		// GetUnitDefList() filled our unitList
		// partially with null UnitDef*'s (bad,
		// nothing much to do if this happens)
		assert(unitTypes[i].def != 0x0);

		// get build options
		for (map<int, string>::const_iterator j = unitTypes[i].def->buildOptions.begin(); j != unitTypes[i].def->buildOptions.end(); j++) {
			const char* buildOptionName = j->second.c_str();
			const UnitDef* buildOptionDef = ai->cb->GetUnitDef(buildOptionName);
			unitTypes[i].canBuildList.push_back(buildOptionDef->id);
		}
	}

	// now set sides and create buildtree for each
	// note: this skips Lua commanders completely!
	for (int s = 0; s < numOfSides; s++) {
		// set side of start unit (eg. commander) and continue recursively
		int unitDefID = startUnits[s];
		unitTypes[unitDefID].sides.insert(s);

		CalcBuildTree(unitDefID, s);
	}

	// add unit to different groups
	for (int i = 1; i <= numOfUnits; i++) {
		UnitType* me = &unitTypes[i];

		// KLOOTNOTE: this is a hack to make KAIK recognize Lua
		// commanders ((which are unreachable from the starting
		// units in the mod hierarchy and so will be skipped by
		// CalcBuildTree(), meaning me->sides stays empty)) as
		// builders, but the ground_builders[side] list for this
		// unit might not exist (and will never actually contain
		// this unitDef ID)
		if (/* me->def->isCommander && */ me->def->buildOptions.size() > 0) {
			me->category = CAT_BUILDER;
		}

		for (std::set<int>::iterator it = me->sides.begin(); it != me->sides.end(); it++) {
			int mySide = *it;
			int UnitCost = int(me->def->metalCost * METAL2ENERGY + me->def->energyCost);
			me->TargetCategories.resize(me->def->weapons.size());

			if (me->def->filename.find(".lua") != std::string::npos) {
				// can't parse these without a Lua parser
				for (unsigned int w = 0; w != me->def->weapons.size(); w++) {
					me->TargetCategories[w] = "";
				}
			} else {
				CSunParser attackerParser(ai);
				attackerParser.LoadVirtualFile(me->def->filename.c_str());

				for (unsigned int w = 0; w != me->def->weapons.size(); w++) {
					char weaponnumber[10] = "";
					itoa(w, weaponnumber, 10);
					attackerParser.GetDef(me->TargetCategories[w], "-1", string("UNITINFO\\OnlyTargetCategory") + string(weaponnumber));
				}
			}


			me->DPSvsUnit.resize(numOfUnits + 1);

			// calculate this unit type's DPS against all other unit types
			for (int v = 1; v <= numOfUnits; v++) {
				me->DPSvsUnit[v] = GetDPSvsUnit(me->def, unitTypes[v].def);
			}

			// speed > 0 means we are mobile, minWaterDepth <= 0 means we
			// are allergic to water and cannot be in it (positive values
			// are inverted internally)
			if (me->def->speed > 0.0f /* && me->def->minWaterDepth <= 0 */) {
				if (me->def->buildOptions.size() > 0) {
					ground_builders[mySide].push_back(i);
					me->category = CAT_BUILDER;
				}
				else if (!me->def->weapons.empty() && !me->def->weapons.begin()->def->stockpile) {
					ground_attackers[mySide].push_back(i);
					me->category = CAT_G_ATTACK;
				}
			}



			else if (!me->def->canfly) {
				if (true /* me->def->minWaterDepth <= 0 */) {
					if (me->def->buildOptions.size() >= 1 && me->def->builder) {
						if ((((me->def)->TEDClassString) == "PLANT") || (((me->def)->speed) > 0.0f)) {
							me->isHub = false;
						} else {
							me->isHub = true;
						}

						ground_factories[mySide].push_back(i);
						me->category = CAT_FACTORY;
					}
					else {
						const WeaponDef* weapon = (me->def->weapons.empty())? 0: me->def->weapons.begin()->def;

						if (weapon && !weapon->stockpile && me->def->extractsMetal == 0.0f) {
							// we don't want armed extractors to be seen as general-purpose defense
							if (!weapon->waterweapon) {
								// filter out depth-charge launchers etc
								ground_defences[mySide].push_back(i);
								me->category = CAT_DEFENCE;
							}
						}

						if (me->def->stockpileWeaponDef) {
							if (me->def->stockpileWeaponDef->targetable) {
								// nuke
								nuke_silos[mySide].push_back(i);
								me->category = CAT_NUKE;
							}
							if (me->def->stockpileWeaponDef->interceptor) {
								// anti-nuke, not implemented yet
							}
						}

						if (me->def->shieldWeaponDef && me->def->shieldWeaponDef->isShield) {
							// shield, not implemented yet
							// me->category = CAT_SHIELD;
						}

						if (me->def->makesMetal) {
							metal_makers[mySide].push_back(i);
							me->category = CAT_MMAKER;
						}
						if (me->def->extractsMetal > 0.0f) {
							metal_extractors[mySide].push_back(i);
							me->category = CAT_MEX;
						}
						if (((me->def->energyMake - me->def->energyUpkeep) / UnitCost) > 0.002 || me->def->tidalGenerator || me->def->windGenerator) {
							if (/* me->def->minWaterDepth <= 0 && */ !me->def->needGeo) {
								// filter tidals and geothermals
								ground_energy[mySide].push_back(i);
								me->category = CAT_ENERGY;
							}
						}
						if (me->def->energyStorage / UnitCost > 0.2) {
							energy_storages[mySide].push_back(i);
							me->category = CAT_ESTOR;
						}
						if (me->def->metalStorage / UnitCost > 0.1) {
							metal_storages[mySide].push_back(i);
							me->category = CAT_MSTOR;
						}
					}
				}
			}
		}
	}

	ReadModConfig();
	// dump generated unit table to file
	DebugPrint();
}