Example #1
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    double *a, *diag, *c, *V, *U;
    double *sub_diag, *hyp_diag;
    double **d, **rhs, b;
    int N, i, step, dims, j; /*can be replaced with mxGetM*/
    int tid, nthreads;

    if( 0 == nlhs || nrhs < 5)
        mexErrMsgTxt("not enough input arguments");
    plhs[0] =prhs[0];

    U= mxGetPr(plhs[0]);
    sub_diag= mxGetPr(prhs[1]);
    diag= mxGetPr(prhs[2]);
    hyp_diag= mxGetPr(prhs[3]);
    V= mxGetPr(prhs[4]);

    N= mxGetM( prhs[0] );

    d= (double *)mxMalloc(N*sizeof(double));
    rhs= (double *)mxMalloc(N*sizeof(double));

#if 0
    if( N==mxGetN(prhs[1]) )
        ismatrix=1;
    else
        ismatrix=0;
#endif
    nthreads = par_mat_init(&d, &rhs, N);

    dims = mxGetNumberOfDimensions( prhs[0] );
    #pragma omp parallel shared(N, d, rhs, sub_diag, diag, hyp_diag, U)\
    private(i, j, tid)
    {
        tid = omp_get_thread_num();
        #pragma omp for schedule(guided) nowait
        for(i =0; i < N; ++i)
        {
            for( j =0; j < N; ++j)
            {
                init_param( d[tid], diag+ j*N +i*N*N, N);
                init_param( rhs[tid], V + j*N + i*N*N, N);
                solveMatrix(N, sub_diag+ j*N + i*N*N, d[tid], hyp_diag+j*N+i*N*N,
                            rhs[tid], U + j*N + i*N*N);
            }
        }

    }

    par_mat_free(d, rhs, nthreads);

    return;
}
Example #2
0
int main(int argc, char **argv)
{
	int retv = 0;

	if (argc < 2) {
		usage();
		return -1;
	}
	if (init_param(argc, argv) < 0) {
		usage();
		return -1;
	}

	if (init_image_mem(filename_yuv, image_data.width, image_data.height) < 0) {
		perror("Failed to init image buffer !\n");
		return -1;
	}
	if (init_jpeg_mem(image_data.width, image_data.height) <0) {
		perror("Failed to init jpeg buffer !\n");
		return -1;
	}

	retv = capture_main_buf_to_jpeg();
	if (retv < 0) {
		perror("Capture main buffer to JPEG failed\n");
	}

	free_image_jpeg_buffer();
	return retv;
}
Example #3
0
t_param	*create_param(int ac, char **av)
{
  int	i;
  t_param	*param;
  t_prog_param	*prog;
  int	prog_count;

  if ((prog_count = get_prog_count(ac, av)) == 0)
    return (NULL);
  if (prog_count > MAX_PLAYER)
  {
    my_printf("Error: to many programs !\n");
    return (NULL);
  }
  if ((param = init_param(prog_count)) == 0)
    return (NULL);
  prog = NULL;
  i = 1;
  while (i < ac)
  {
    if (parse_param(param, &prog, &i, av) != 0)
      return (NULL);
    ++i;
  }
  return (param);
}
Example #4
0
int main(int argc, char **argv)
{
	signal(SIGINT, sigstop);
	signal(SIGQUIT, sigstop);
	signal(SIGTERM, sigstop);

	if ((fd_iav = open("/dev/iav", O_RDWR, 0)) < 0) {
		perror("open /dev/iav");
		return -1;
	}

	if (init_param(argc, argv) < 0) {
		usage();
		return -1;
	}

	parse_default_configs();

	if (create_server() < 0) {
		APP_ERROR("create_server");
		return -1;
	}
	main_handle();

	#if 0
	while (1) {
		main_loop();
	}
	#endif
	while (1) {
		sleep(1);
	}

	return 0;
}
Example #5
0
void
init_parameters (mpc_fun_param_t *params)
{
  int in, out;
  int total = params->nbout + params->nbin;

  for (out = 0; out < params->nbout; out++)
    {
      init_param (&(params->P[out]), params->T[out]);
      init_param (&(params->P[total + out]), params->T[total + out]);
    }

  for (in = params->nbout; in < total; in++)
    {
      init_param (&(params->P[in]), params->T[in]);
    }
}
Example #6
0
File: draw.c Project: mdambrev/42
void		draw(t_content *axx, int nb_list)
{
	t_clist	*param;

	param = init_param();
	CONTENT(0) = nb_list;
	PARAM(0) = mlx_init();
	PARAM(1) = mlx_new_window(PARAM(0), LARGEUR, HAUTEUR, "fdf");
	PARAM(2) = axx;
	mlx_key_hook(PARAM(1), key_hook, param);
	mlx_expose_hook(PARAM(1), expose_hook, param);
	mlx_loop(PARAM(0));
}
Example #7
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
   double *a, *diag, *c, *V, *U;
   double *sub_diag, *hyp_diag;
   double *d, *rhs, b;
   int N, i, step, ismatrix; /*can be replaced with mxGetM*/
   
   if( 0 == nlhs || nrhs < 5)
      mexErrMsgTxt("not enough input arguments");
   plhs[0] =prhs[0];
   
   U= mxGetPr(plhs[0]);
   sub_diag= mxGetPr(prhs[1]);
   diag= mxGetPr(prhs[2]);
   hyp_diag= mxGetPr(prhs[3]);
   V= mxGetPr(prhs[4]);
   
   N= mxGetM( prhs[0] );
   
   d= (double *)mxMalloc(N*sizeof(double));
   rhs= (double *)mxMalloc(N*sizeof(double));
   
   if( N==mxGetN(prhs[1]) )
      ismatrix=1;
   else
      ismatrix=0;
   
   for(i =0; i <N; ++i){
      init_param( d, diag+i*N, N);
      init_param( rhs, V+i*N, N);
      solveMatrix(N, sub_diag+i*N*ismatrix, d, hyp_diag+i*N*ismatrix, rhs, U +i*N);
   }
   mxFree(d);
   mxFree(rhs);
   
   return;
}
Example #8
0
int main(int argc,char **argv)
{
	init_param(argc,argv);
	init_signal(); //注册关闭信号
	printf("using config file %s\n",g_config_file);
	init_config(g_config_file,&set_config_item);
	//return 0;
	g_status = SERVER_STATUS_RUN; //设置服务器的状态
	pthread_mutex_init(&g_lrumc_lock,NULL);
	create_pid_file();
	prepare_crypt_table();
	g_lrumc = init_lrumc(g_lrumc_config,g_segment_num);
	g_epoll_socket = create_epoll_socket();//创建socket句柄
	g_thread = create_epoll_thread(g_thread_num,g_epoll_socket,thread_func);//创建thread句柄
	start_epoll_socket(g_epoll_socket,g_port);//开始监听
	return 0;	
}
Example #9
0
int main(int argc, char ** argv)
{
	int retv = 0;

	if (argc < 2) {
		usage();
		return 0;
	}

	if (init_param(argc, argv) < 0)
		return -1;

	if (open_crypto_dev() < 0)
		return -1;

	if (crypto_method == CRYPTO_SHA1){
		retv = sha();
		return retv;
	}

	if (crypto_method == CRYPTO_MD5){
		retv = md5();
		return retv;
	}

	if (autotest_flag) {
		retv = auto_test(algoname);
		return retv;
	}

	if (crypto_method == CRYPTO_ENCRYPTE) {
		if (do_encryption(algoname) < 0)
			return -1;
	} else {
		if (do_decryption(algoname) < 0)
			return -1;
	}

	close_crypto_dev();

	return 0;
}
Example #10
0
static int init_image_config(int argc, char *argv[])
{
	if ((fd_iav = open("/dev/iav", O_RDWR, 0)) < 0) {
		perror("open /dev/iav");
		return -1;
	}
	if (init_param(argc, argv) < 0) {
		usage();
		return -1;
	}

	parse_default_configs();

	/*if (create_server() < 0) {
		APP_ERROR("create_server");
		return -1;
	}*/

	return 0;
}
Example #11
0
/**
 * @brief dofork 
 * 将cbenchmark变成多个进程
 *
 * 该函数是cbenchmark多进程多线程模式的起点
 * 在该函数执行后
 * 每个子进程又会通过访问call_threads函数来生成若干子线程
 *
 * @param bp
 * cbenchmark全局信息
 * @param n
 * 该进程所负责执行的并发数
 * 也就是该进程将会生成的线程(虚拟用户)数
 * @param g
 * 进程(用户)组ID
 */
void dofork(struct bench * bp,int n,long int g)
{
		if (fork()==0) {
				syslog(LOG_NOTICE, "Child process forked. pid: [%ld], ppid: [%ld]",getpid(),getppid());
				/* 
				 *	生成bench_child_t变量
				 *	每个该变量属于一个进程
				 *	但存放在进程共享内存中
				 * */
				bench_child_t *bcp = create_child_bench(bp,n,g);

				//如果指定参数,则进行进程参数初始化
				if(bp->infile != NULL){
						proc_param_st_t procpm;                                                 
						init_param(bcp, &procpm);        
						bcp->param = (void*)&procpm; 
				}

				call_threads(bcp);
				exit(errno);
		}
}
Example #12
0
/*===========================================================================*
 *				winchester_task				     * 
 *===========================================================================*/
PUBLIC winchester_task()
{
/* Main program of the winchester disk driver task. */

  int r, caller, proc_nr;

  /* First initialize the controller */
  init_param();

  /* Here is the main loop of the disk task.  It waits for a message, carries
   * it out, and sends a reply.
   */

  while (TRUE) {
	/* First wait for a request to read or write a disk block. */
	receive(ANY, &w_mess);	/* get a request to do some work */
	if (w_mess.m_source < 0) {
		printf("winchester task got message from %d ", w_mess.m_source);
		continue;
	}
	caller = w_mess.m_source;
	proc_nr = w_mess.PROC_NR;

	/* Now carry out the work. */
	switch(w_mess.m_type) {
	    case DISK_READ:
	    case DISK_WRITE:	r = w_do_rdwt(&w_mess);	break;
	    default:		r = EINVAL;		break;
	}

	/* Finally, prepare and send the reply message. */
	w_mess.m_type = TASK_REPLY;	
	w_mess.REP_PROC_NR = proc_nr;

	w_mess.REP_STATUS = r;	/* # of bytes transferred or error code */
	send(caller, &w_mess);	/* send reply to caller */
  }
}
Example #13
0
int		main()
{
  t_client	client;

  init_param(&client);
  to_serv(&client);
  assign_func(&client);
  while (client.s < 0)
    init_connection(&client);
  while (client.s)
    {
      set_fd(&client);
      if (select(client.fd_max, &(client.fd_read), &(client.fd_write),
		 NULL, NULL) == -1)
	{
	  my_printf(2, "select: %s\n", strerror(errno));
	  break;
	}
      check_fd(&client);
    }
  if (client.s)
    my_close(client.s);
  return (0);
}
Example #14
0
bool Param::open(int argc, char **argv, const Option *opts) {
  int ind = 0;
  int _errno = 0;

#define GOTO_ERROR(n) {                         \
    _errno = n;                                 \
    goto ERROR; } while (0)

  if (argc <= 0) {
    system_name_ = "unknown";
    return true;  // this is not error
  }

  system_name_ = std::string(argv[0]);

  init_param(&help_, &version_, system_name_, opts);

  for (size_t i = 0; opts[i].name; ++i) {
    if (opts[i].default_value) set<std::string>
                                   (opts[i].name, opts[i].default_value);
  }

  for (ind = 1; ind < argc; ind++) {
    if (argv[ind][0] == '-') {
      // long options
      if (argv[ind][1] == '-') {
        char *s;
        for (s = &argv[ind][2]; *s != '\0' && *s != '='; s++);
        size_t len = (size_t)(s - &argv[ind][2]);
        if (len == 0) return true;  // stop the scanning

        bool hit = false;
        size_t i = 0;
        for (i = 0; opts[i].name; ++i) {
          size_t nlen = std::strlen(opts[i].name);
          if (nlen == len && std::strncmp(&argv[ind][2],
                                          opts[i].name, len) == 0) {
            hit = true;
            break;
          }
        }

        if (!hit) GOTO_ERROR(0);

        if (opts[i].arg_description) {
          if (*s == '=') {
            set<std::string>(opts[i].name, s+1);
          } else {
            if (argc == (ind+1)) GOTO_ERROR(1);
            set<std::string>(opts[i].name, argv[++ind]);
          }
        } else {
          if (*s == '=') GOTO_ERROR(2);
          set<int>(opts[i].name, 1);
        }

        // short options
      } else if (argv[ind][1] != '\0') {
        size_t i = 0;
        bool hit = false;
        for (i = 0; opts[i].name; ++i) {
          if (opts[i].short_name == argv[ind][1]) {
            hit = true;
            break;
          }
        }

        if (!hit) GOTO_ERROR(0);

        if (opts[i].arg_description) {
          if (argv[ind][2] != '\0') {
            set<std::string>(opts[i].name, &argv[ind][2]);
          } else {
            if (argc == (ind+1)) GOTO_ERROR(1);
            set<std::string>(opts[i].name, argv[++ind]);
          }
        } else {
          if (argv[ind][2] != '\0') GOTO_ERROR(2);
          set<int>(opts[i].name, 1);
        }
      }
    } else {
      rest_.push_back(std::string(argv[ind]));  // others
    }
  }

  return true;

ERROR:
  switch (_errno) {
    case 0: WHAT << "unrecognized option `" << argv[ind] << "`"; break;
    case 1: WHAT << "`" << argv[ind] << "` requires an argument";  break;
    case 2: WHAT << "`" << argv[ind] << "` doesn't allow an argument"; break;
  }
  return false;
}
Example #15
0
extern "C" int main(int argc, char **argv)
{
    int err;

    //register signal handler for Ctrl+C,  Ctrl+'\'  ,  and "kill" sys cmd
	signal(SIGINT, 	sigrecordstop);
	signal(SIGQUIT,	sigrecordstop);
	signal(SIGTERM,	sigrecordstop);
	if (argc < 2) {
		usage();
		return -1;
	}

	if (init_param(argc, argv) < 0)
	{
		usage();
		return -1;
	}

	// create the media controller
	if ((g_record_pController = AM_MediaControllerCreate()) == NULL)
		return -1;

	if ((err =g_record_pController ->InstallMsgCallback(ProcessAppMsg, NULL)) != ME_OK)
		return -1;

	// create the record pipeline
	if((err = g_record_pController->CreatePipeline(CreateRecordPipeline)) != ME_OK)
	{
		printf("record--CreatePipeline() failed %d.Exit!!!\n",err);
		return -1;
	}

	if ((g_record_pPipeline= IamRecordPipeline::GetInterfaceFrom(g_record_pController)) == NULL)
	{
		printf("record--No IamrecordPipeline.Exit!!!\n");
		return -1;
	}

	IamRecordPipeline::FILE_TYPE file_type;
	IamRecordPipeline::AUDIO_TYPE audio_type;
	switch(recordType){
		case 0:
			file_type = IamRecordPipeline::ES;
			break;
		case 1:
			file_type = IamRecordPipeline::TS;
			break;
		case 2:
			file_type = IamRecordPipeline::MP4;
			break;
		default:
			return -1;
	}
	switch(audioType){
		case 0:
			audio_type = IamRecordPipeline::NONE;
			break;
		case 1:
			audio_type = IamRecordPipeline::AAC;
			break;
		case 2:
			audio_type = IamRecordPipeline::BPCM;
			break;
		default:
			return -1;
	}
	g_record_pPipeline->SetRecordType(file_type, audio_type);
	if (g_record_pPipeline->BuildPipeline())
		return -1;

	if (InitInterface() < 0)
		return -1;
	if (ConfigAudio() < 0)
		return -1;
	if (ConfigPrg() < 0)
		return -1;

	if (StartPrg()) {
		return -1;
	}
	recordRunIdle();
	g_record_pController->Delete();
	if (exit_flag) {
		return -1;
	} else {
		return 0;
	}
}
Example #16
0
void	origin(t_env *env)
{
	env->param = init_param(env->param->name);
	env->f = init_frac(env->param->name);
}
Example #17
0
int main(int argc, char * argv[])
{
    int fps     = 15;
    int bitRate = 24;
    int width   = 640;
    int height  = 480;
    int yuvsize = (width * height * 3) >> 1;
    uint8_t * yuv = (uint8_t *)malloc(yuvsize);
    
    x264_picture_t *_picIn;
	x264_picture_t *_picOut;
    x264_t * x264_handle_        = NULL;
    x264_param_t * x264_param_   = (x264_param_t *)malloc(sizeof(x264_param_t));
    
    init_param(x264_param_, width, height, fps, bitRate);  
    
	_picIn = (x264_picture_t*)malloc(sizeof(x264_picture_t));
	_picOut = (x264_picture_t*)malloc(sizeof(x264_picture_t));
	
	if(x264_picture_alloc(_picIn, X264_CSP_I420, width, height) < 0 ) {
	    printf("x264_picture_alloc failed!\n");
	    exit(0);
	}
	
	_picIn->img.i_csp   = X264_CSP_I420;  
	_picIn->img.i_plane = 3; 

	x264_handle_ = x264_encoder_open(x264_param_);
	if(!x264_handle_) {
		printf("x264_encoder_open failed!\n");
		exit(0);
	}
	init_head(x264_handle_, NULL, 0);
	
	if (argc < 2) {
	    printf("please input yuv file name!\n");
	    exit(0);
	}
	const char * file = argv[1];
	printf("encode yuv file:%s\n", file);
	
	struct stat sb;
	if (stat(file, &sb) == -1) {
	    printf("stat file:%s failed!\n", file);
	    exit(0);
	}
	
	if ((sb.st_mode & S_IFMT) != S_IFREG || sb.st_size <  yuvsize) {
	    printf("file:%s invalid, size:%ld, regfile:%d!\n", file, sb.st_size, (sb.st_mode & S_IFMT) == S_IFREG);
	    exit(0);
	}
	
	int rfd = open(file, O_RDONLY);
	if (rfd < 0) {
	    printf("open file:%s failed!\n", file);
	    exit(0);
	}
	
	int off = 0, rdn = 0;
	if ((rdn = read(rfd, yuv, yuvsize - off)) != yuvsize) {
        printf("read no enough data. readn:%d, yuvsize:%d\n", rdn, yuvsize);
	} 
	close(rfd);
	
	int planesize = width * height;
	memcpy(_picIn->img.plane[0], yuv, planesize);
	memcpy(_picIn->img.plane[1], yuv + planesize, planesize >> 2);
	memcpy(_picIn->img.plane[2], yuv + planesize + (planesize >> 2), planesize >> 2);
	
	x264_nal_t * nal;
	int nalcnt = 0;
	
	int encodesize = x264_encoder_encode(x264_handle_, &nal, &nalcnt, _picIn, _picOut);
	if (encodesize <= 0) {
	    printf("encode failed. size:%d\n", encodesize);
	    exit(0);
	}
	
	const char * outfile = "h264_640x480.bin";
	int wfd = open(outfile, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP);
	if (wfd < 0) {
	    printf("open outfile:%s failed!\n", outfile);
	    exit(0);
	}
	write(wfd, nal->p_payload, encodesize);
	close(wfd);
	
	x264_encoder_close(x264_handle_);
	x264_picture_clean(_picIn);
	free(_picIn);
	free(_picOut);
	free(yuv);
	free(x264_param_);
	
	return 0;
}
Example #18
0
int main()
{
  //DECLARATION DES VARIABLES
  //compteur
  int i = 0;
  //tableaux
  char buffer[MAX_BUFFER];//buffer temporaire pour la saisie
  char ** parametres = NULL;//tableaux des paramètres
  char * path = NULL;//tableau contenant le chemin d'exécution de la commande
  //compteur utilisé dans la fonction compte_argument
  int nb_param = 0;
  int taille_param = 0;
  int taille_nom = 0;
  //variable utilisé lors du fork
  int status;
  //TRAITEMENT DU SIGNAL
  traitement_signal();

  while(bool){
    //SAISIE DE LA COMMANDE ET COMPTAGE DES ARGUMENTS
    printf("%s",PROMPT);//affichage du prompt
    saisie_commande(buffer);
    taille_nom = compte_nom(buffer);
    compte_arguments(buffer,&nb_param,&taille_param,&taille_nom);
    if(taille_nom > taille_param)//si la valeur de taille_nom est supérieur à celle de taille_param, on utilise celle de taille_nom
      taille_param = taille_nom;

    

    //RÉSERVATION MÉMOIRE ET INITIALISATION DES TABLEAUX
    
    parametres = calloc((nb_param+2),sizeof(char*));
    for (i = 0;i < (nb_param+2);i ++)
      parametres[i] = calloc((taille_param+1),sizeof(char));
    path = calloc((taille_nom+1+TAILLE_BIN_DIR),sizeof(char));
    init_param(buffer,parametres);
    strcpy(path,BIN_DIR);//on ajoute le chemin du bin en début de commande
    strcat(path,parametres[0]);//on ajoute à la suite le nom de la commande

    
    //FORK
    if (fork() != 0)
      wait(&status);
    else {
      if(execve(path,parametres,0) == -1){
	erreur_execve();
	exit(EXIT_FAILURE);
      }
    }   

    //LIBÉRATION DE LA MÉMOIRE
    for (i = 0;i < (nb_param+2);i ++)
      free(parametres[i]);
    free(parametres);
    free(path);
    //RÉ-INITIALISATION DES VARIABLES
    nb_param = 0;
    taille_param = 0;
    taille_nom = 0;
    }
  exit(EXIT_SUCCESS);
}
Example #19
0
//--------------------------------------------------------------------------------------------------------------------------
int main(int argc, char **argv)
{

	if (argc < 2)
	{
		usage();
		return -1;
	}
	if (init_param(argc, argv) < 0)
	{
		usage();
		return -1;
	}

	if ( help_flag == 1)
		return 0;

	if (hw_reset_flag)
	{
		HW_RESET(93);
	}

	if (Page_Addr_flag)
	{
		if (Write_flag)
		{
			MDINI2C_RegWrite(test_nID,Mdinxxx_rAddr,*Mdinxxx_Data);
			printf("MDINI2C_RegWrite nID=0x%x rAddr=0x%04x wData=0x%04x  \n",test_nID,Mdinxxx_rAddr,*Mdinxxx_Data);
		}
		if (Read_flag)
		{
			Mdinxxx_Data = (u16 *)malloc(sizeof(u16));
			MDINI2C_RegRead(test_nID,Mdinxxx_rAddr,Mdinxxx_Data);
			printf("MDINI2C_RegRead nID=0x%x rAddr=0x%04x wData=0x%04x  \n",test_nID,Mdinxxx_rAddr,*Mdinxxx_Data);
		}
		return 0;

	}
	else
	{
		if (Write_flag)
		{
			RN6264_I2c_write(RNxxxx_rAddr,*RNxxxx_Data);
			printf("RN6264_I2c_write rAddr=0x%02x wData=0x%02x  \n",RNxxxx_rAddr,*RNxxxx_Data);
			return 0;
		}
		if (Read_flag)
		{
			RNxxxx_Data = (u8 *)malloc(sizeof(u8));
			RN6264_I2c_read(RNxxxx_rAddr,RNxxxx_Data);
			printf("RN6264_I2c_read rAddr=0x%02x wData=0x%02x  \n",RNxxxx_rAddr,*RNxxxx_Data);
			return 0;
		}
	}

	if (init_flag == 1)
	{
		if (RN6264_SetVideoSource(video_mode) < 0)
			return -1;
		printf(" RNXXXX i2c install successfully! \n");

		CreateMDIN380VideoInstance();			// initialize MDIN-380
		if (stVideo.exeFLAG) {					// check change video formats
			MDIN3xx_EnableMainDisplay(OFF);
			MDIN3xx_EnableAuxDisplay(&stVideo, OFF);

			MDIN3xx_VideoProcess(&stVideo);		// mdin3xx main video process

		#if	defined(SYSTEM_USE_4D1_IN) && defined(SYSTEM_USE_4D1_IN_QUADOUT) // for 4D1 input Quad output mode
			// for no scale(1:1) output (1600x1200)
//			#if	defined(NTSC_4D1_IN)
			if (video_mode == VDCNV_4CH_ON_NTSC)
				Set_AUXViewSize(1440,  960, 0, 0);	// for NTSC input, set view size, added on 01Aug2011
//			#endif
//			#if	defined(PAL_4D1_IN)
			else if (video_mode == VDCNV_4CH_ON_NTSC_960)
				Set_AUXViewSize(1920, 960, 0, 0);	// for PAL  input, set view size, added on 01Aug2011
			else
				Set_AUXViewSize(1440, 1152, 0, 0);	// for PAL  input, set view size, added on 01Aug2011
//			#endif

			MDINAUX_SetOut4CH_OutQuad(video_mode);
			if (video_mode == VDCNV_4CH_ON_NTSC_960)
				MDIN3xx_SetOut4CH_OutVsync_Half(ON);	// for half frequency (vsync: 60 to 30Hz, 50 to 25Hz)
			else
				MDIN3xx_SetOut4CH_OutVsync_Half(OFF);	// for half frequency (vsync: 60 to 30Hz, 50 to 25Hz)

		#endif
		#if	defined(SYSTEM_USE_4D1_IN) && defined(SYSTEM_USE_4D1_IN_656OUT) // for 4D1 input BT656 output mode
			MDINAUX_SetOut4CH_OutBT656(video_mode);
			MDIN3xx_SetOut4CH_OutBT656(video_mode);
		#endif
//			MDIN3xx_SetOutTestPattern(MDIN_OUT_TEST_COLOR);
//			MDIN3xx_EnableAuxDisplay(&stVideo, ON);
			MDIN3xx_EnableMainDisplay(ON);
			MDIN3xx_EnableAuxDisplay(&stVideo, ON);

			printf(" MDIN380 i2c install successfully! \n");
		}
	}
	return 0;
}
Example #20
0
int main(int argc,char** argv)
{
	char _path[260]; 
	char _root[260]; 
    FiEvent evnt;

    INIT_G();    	
    G.logFileSize = _M(100);
    G.logFile.fd = STDOUT_FILENO;
	FiGetCurDir(sizeof(_path),_path);
    strcpy(_root, _path);
	std::string str(_path);
    dirname(_root);
    append_slash(_root);
    G.exe = _path;
    G.root = _root;
	str+="FiUpdateMgr.log";
	freopen(str.c_str(),"a",stdout);
#if 1
    if (0 == chdir(G.exe))
    {
        ut_dbg("change cur dir success\n");
    }
    else
    {
        ut_err("change cur dir fail\n");
    }    
#endif
#ifndef WIN32
    FiEnableCoreDumps();
    pthread_t tid[3];
	pthread_attr_t attr[3];
    struct stat st;
    umparams.type = SERVER;//default type
    umparams.master == false;

    FiUpdateAssistant::getinstance()->set(&evnt);
    
    if (init_param(argc, argv) < 0) 
    {
        print_usage(stderr, 1);
        return -1;
    }
    if (stat("../download", &st) == -1)
    {
        ut_err("stat error num :%d\n", errno);
    }
    else
    {
        if (!S_ISDIR(st.st_mode))
        {
            system("rm ../download -rf");
        }
    }
    system("mkdir -p ../download");
	if (pthread_attr_init(&attr[0]) < 0)
	{
		ut_err("set attr fail\n");
	}
	if (pthread_attr_init(&attr[1]) < 0)
	{
		ut_err("set attr fail\n");
	}
	if (pthread_attr_init(&attr[2]) < 0)
	{
		ut_err("set attr fail\n");
	}
	pthread_attr_setdetachstate(&attr[0], PTHREAD_CREATE_DETACHED);
	pthread_attr_setdetachstate(&attr[1], PTHREAD_CREATE_DETACHED);
	pthread_attr_setdetachstate(&attr[2], PTHREAD_CREATE_DETACHED);
    if (sendHello()<0)
    {
        ut_err("send hello fail\n");
    }

	pthread_create(&tid[0], &attr[0], selfUpdate, NULL);
    if (umparams.master == false)
    {
        pthread_create(&tid[1], &attr[1], recvHelloHandler, NULL);
    }
    else
    {
        pthread_create(&tid[2], &attr[2], heartHandler, NULL);
    }
#endif


    UpdateSrv = new FiRpcSrv<FiUpdateMgrImpl>(RPC_PORT, RPC_SERVER_NAME, (char*)(NULL));
	UpdateSrv->run();
#if 0	
	evnt.wait();
#else
    do
    {
#ifdef WIN32
        Sleep(1000);
#else
        sleep(1);
#endif
    }while(true);
#endif
	
	return 0;	
}
Example #21
0
int main(int argc, char *argv[])
{
	int c;
	struct option long_options[] = {
		{"disable-tryagain", no_argument, 0, 'd'},
		{"parameter", required_argument, 0, 'p'},
		{"operation-id", required_argument, 0, 'o'},
		{"operation-name", required_argument, 0, 'O'},
		{"admin-owner", required_argument, 0, 'a'},
		{"help", no_argument, 0, 'h'},
		{"timeout", required_argument, 0, 't'},
		{"verbose", no_argument, 0, 'v'},
		{0, 0, 0, 0}
	};
	SaAisErrorT error;
	SaImmHandleT immHandle;
	SaImmAdminOwnerNameT adminOwnerName = basename(argv[0]);
	bool releaseAdmo=true;
	bool explicitAdmo=false;
	SaImmAdminOwnerHandleT ownerHandle;
	SaNameT objectName;
	const SaNameT *objectNames[] = { &objectName, NULL };
	SaAisErrorT operationReturnValue = -1;
	SaImmAdminOperationParamsT_2 *param;
	const SaImmAdminOperationParamsT_2 **params;
	SaImmAdminOperationParamsT_2 **out_params=NULL;
	SaImmAdminOperationIdT operationId = -1;
	unsigned long timeoutVal = 60;  /* Default timeout value */
	int disable_tryagain = false;
	int isFirst = 1;
	int verbose = 0;

	int params_len = 0;

	/* Support for long DN */
	setenv("SA_ENABLE_EXTENDED_NAMES", "1", 1);
	/* osaf_extended_name_init() is added to prevent future safe use of
	 * osaf_extended_name_* before saImmOmInitialize and saImmOiInitialize */
	osaf_extended_name_init();

	params = realloc(NULL, sizeof(SaImmAdminOperationParamsT_2 *));
	params[0] = NULL;
	SaStringT opName = NULL;

	while (1) {
		c = getopt_long(argc, argv, "dp:o:O:a:t:hv", long_options, NULL);

		if (c == -1)	/* have all command-line options have been parsed? */
			break;

		switch (c) {
		case 'd':
			disable_tryagain = true;
			break;
		case 'o':
			if(operationId != -1) {
				fprintf(stderr, "Cannot set admin operation more then once");
				exit(EXIT_FAILURE);
			}
			operationId = strtoll(optarg, (char **)NULL, 10);
			if ((operationId == 0) && ((errno == EINVAL) || (errno == ERANGE))) {
				fprintf(stderr, "Illegal operation ID\n");
				exit(EXIT_FAILURE);
			}
			break;
		case 'O':
			if(operationId != -1) {
				fprintf(stderr, "Cannot set admin operation more then once");
				exit(EXIT_FAILURE);
			}
			operationId = SA_IMM_PARAM_ADMOP_ID_ESC;
			params_len++;
			params = realloc(params, (params_len + 1) * sizeof(SaImmAdminOperationParamsT_2 *));
			param = malloc(sizeof(SaImmAdminOperationParamsT_2));
			params[params_len - 1] = param;
			params[params_len] = NULL;
			param->paramName = strdup(SA_IMM_PARAM_ADMOP_NAME);
			param->paramType = SA_IMM_ATTR_SASTRINGT;
			param->paramBuffer = malloc(sizeof(SaStringT));
			*((SaStringT *)(param->paramBuffer)) = strdup(optarg);
			opName = strdup(optarg);
			break;
		case 'p':
			params_len++;
			params = realloc(params, (params_len + 1) * sizeof(SaImmAdminOperationParamsT_2 *));
			param = malloc(sizeof(SaImmAdminOperationParamsT_2));
			params[params_len - 1] = param;
			params[params_len] = NULL;
			if (init_param(param, optarg) == -1) {
				fprintf(stderr, "Illegal parameter: %s\n", optarg);
				exit(EXIT_FAILURE);
			}
			break;
		case 't':
			timeoutVal = strtoll(optarg, (char **)NULL, 10);

			if ((timeoutVal == 0) || (errno == EINVAL) || (errno == ERANGE)) {
				fprintf(stderr, "Illegal timeout value\n");
				exit(EXIT_FAILURE);
			}
			break;
		case 'a':
			adminOwnerName = (SaImmAdminOwnerNameT)malloc(strlen(optarg) + 1);
			strcpy(adminOwnerName, optarg);
			releaseAdmo=false;
			explicitAdmo=true;
			break;
		case 'h':
			usage(basename(argv[0]));
			exit(EXIT_SUCCESS);
			break;
		case 'v':
			verbose = 1;
			break;
		default:
			fprintf(stderr, "Try '%s --help' for more information\n", argv[0]);
			exit(EXIT_FAILURE);
			break;
		}
	}

	if (operationId == -1) {
		fprintf(stderr, "error - must specify admin operation ID %llx\n", operationId);
		exit(EXIT_FAILURE);
	}

	/* Need at least one object to operate on */
	if ((argc - optind) == 0) {
		fprintf(stderr, "error - wrong number of arguments\n");
		exit(EXIT_FAILURE);
	}

	signal(SIGALRM, sigalarmh);
	(void) alarm(timeoutVal);

	immutilWrapperProfile.errorsAreFatal = 0;
	immutilWrapperProfile.nTries = disable_tryagain ? 0 : timeoutVal;
	immutilWrapperProfile.retryInterval = 1000;

	error = immutil_saImmOmInitialize(&immHandle, NULL, &immVersion);
	if (error != SA_AIS_OK) {
		fprintf(stderr, "error - saImmOmInitialize FAILED: %s\n", saf_error(error));
		exit(EXIT_FAILURE);
	}

	if((optind < argc) && (!explicitAdmo)) {
		saAisNameLend(argv[optind], &objectName);

		if(strcmp(saAisNameBorrow(&objectName), OPENSAF_IMM_OBJECT_DN)==0) {
			releaseAdmo=false;
			adminOwnerName = (SaImmAdminOwnerNameT) malloc(strlen(OPENSAF_IMM_SERVICE_NAME) + 1);
			strcpy(adminOwnerName, OPENSAF_IMM_SERVICE_NAME);
			printf("[using admin-owner: '%s']\n", adminOwnerName);
		}
	}

	error = immutil_saImmOmAdminOwnerInitialize(immHandle, adminOwnerName, releaseAdmo?SA_TRUE:SA_FALSE, &ownerHandle);
	if (error != SA_AIS_OK) {
		fprintf(stderr, "error - saImmOmAdminOwnerInitialize FAILED: %s\n", saf_error(error));
		exit(EXIT_FAILURE);
	}

	/* Remaining arguments should be object names on which the admin op should be performed. */
	while (optind < argc) {
		saAisNameLend(argv[optind], &objectName);

		error = immutil_saImmOmAdminOwnerSet(ownerHandle, objectNames, SA_IMM_ONE);
		if (error != SA_AIS_OK) {
			if (error == SA_AIS_ERR_NOT_EXIST) {
				if(strcmp(adminOwnerName, saAisNameBorrow(&objectName))==0) {
					/* AdminOwnerName == ImplementerName - Could be direct admin-op on OI */
					goto retry;
				}
				fprintf(stderr, "error - saImmOmAdminOwnerSet - object '%s' does not exist\n",
					saAisNameBorrow(&objectName));
			}
			else
				fprintf(stderr, "error - saImmOmAdminOwnerSet FAILED: %s\n", saf_error(error));
			exit(EXIT_FAILURE);
		}
retry:
		error = immutil_saImmOmAdminOperationInvoke_o2(ownerHandle, &objectName, 0, operationId,
			params, &operationReturnValue, SA_TIME_ONE_SECOND * timeoutVal, &out_params);

		if (error != SA_AIS_OK) {
			fprintf(stderr, "error - saImmOmAdminOperationInvoke_2 FAILED: %s\n",
				saf_error(error));
			exit(EXIT_FAILURE);
		}

		if (operationReturnValue != SA_AIS_OK ) {
			unsigned int ix = 0;

			if ((operationReturnValue == SA_AIS_ERR_TRY_AGAIN) && !disable_tryagain) {
				sleep(1);
				goto retry;
			}

			fprintf(stderr, "error - saImmOmAdminOperationInvoke_2 admin-op RETURNED: %s\n",
				saf_error(operationReturnValue));
			
			while(out_params && out_params[ix]) {
				if(strcmp(out_params[ix]->paramName, SA_IMM_PARAM_ADMOP_ERROR) == 0) {
					assert(out_params[ix]->paramType == SA_IMM_ATTR_SASTRINGT);
					SaStringT errStr = (*((SaStringT *) out_params[ix]->paramBuffer));
					fprintf(stderr, "error-string: %s\n", errStr);
				}
				++ix;
			}

			/* After printing error string, print all returned parameters */
			if (verbose && out_params && out_params[0]) {
				if(!isFirst)
					printf("\n");

				print_params(argv[optind], out_params);
			}
			

			exit(EXIT_FAILURE);
		}


		if (((opName && (strncmp(opName,"display",7)==0))||verbose) &&out_params && out_params[0]) {
			if(!isFirst)
				printf("\n");
			else
				isFirst = 0;

			print_params(argv[optind], out_params);
		}


		error = saImmOmAdminOperationMemoryFree(ownerHandle, out_params);
		if (error != SA_AIS_OK) {
			fprintf(stderr, "error - saImmOmAdminOperationMemoryFree FAILED: %s\n", saf_error(error));
			exit(EXIT_FAILURE);
		}

		if(releaseAdmo) {
			error = immutil_saImmOmAdminOwnerRelease(ownerHandle, objectNames, SA_IMM_ONE);
			if (error != SA_AIS_OK) {
				fprintf(stderr, "error - saImmOmAdminOwnerRelease FAILED: %s\n", saf_error(error));
				exit(EXIT_FAILURE);
			}
		}

		optind++;
	}

	error = immutil_saImmOmAdminOwnerFinalize(ownerHandle);
	if (SA_AIS_OK != error) {
		fprintf(stderr, "error - saImmOmAdminOwnerFinalize FAILED: %s\n", saf_error(error));
		exit(EXIT_FAILURE);
	}

	error = immutil_saImmOmFinalize(immHandle);
	if (SA_AIS_OK != error) {
		fprintf(stderr, "error - saImmOmFinalize FAILED: %s\n", saf_error(error));
		exit(EXIT_FAILURE);
	}

	exit(EXIT_SUCCESS);
}
Example #22
0
/*
* learn dictionary and find optimum code.
*/
int MedSTC::train(char* start, char* directory, Corpus* pC, Params *param)
{
	m_dDeltaEll = param->DELTA_ELL;
	m_dLambda   = param->LAMBDA;
	m_dRho      = param->RHO;
	m_dGamma    = m_dLambda;
	long runtime_start = get_runtime();

	// allocate variational parameters
	double ***phi = (double***)malloc(sizeof(double**) * pC->num_docs);
	for ( int d=0; d<pC->num_docs; d++ ) {
		phi[d] = (double**)malloc(sizeof(double*)*pC->docs[d].length);
		for (int n=0; n<pC->docs[d].length; n++) {
			phi[d][n] = (double*)malloc(sizeof(double) * param->NTOPICS);
		}
	}
	double **theta = (double**)malloc(sizeof(double*)*(pC->num_docs));
	for (int d=0; d<pC->num_docs; d++) {
		theta[d] = (double*)malloc(sizeof(double) * param->NTOPICS);
	}
	for ( int d=0; d<pC->num_docs; d++ ) {
		init_phi(&(pC->docs[d]), phi[d], theta[d], param);
	}

	// initialize model
	if (strcmp(start, "random")==0) {
		new_model(pC->num_docs, pC->num_terms, param->NTOPICS, 
								param->NLABELS, param->INITIAL_C);
		init_param( pC );
	} else {
		load_model(start);
		m_dC = param->INITIAL_C;
	}
	strcpy(m_directory, directory);

	char filename[100];
	

	// run expectation maximization
	sprintf(filename, "%s/lhood.dat", directory);
	FILE* lhood_file = fopen(filename, "w");

	Document *pDoc = NULL;
	double dobj, obj_old = 1, converged = 1;
	int nIt = 0;
	while (((converged < 0) || (converged > param->EM_CONVERGED) 
		|| (nIt <= 2)) && (nIt <= param->EM_MAX_ITER))
	{

		dobj = 0;
		double dLogLoss = 0;
		for ( int d=0; d<pC->num_docs; d++ ) {
			pDoc = &(pC->docs[d]);
			dobj += sparse_coding( pDoc, d, param, theta[d], phi[d] );
			dLogLoss += m_dLogLoss;
		}

		// m-step

		dict_learn(pC, theta, phi, param, false);

		if ( param->SUPERVISED == 1 ) { // for supervised MedLDA.
			char buff[512];
			get_train_filename( buff, m_directory, param );
			outputLowDimData( buff, pC, theta );

			svmStructSolver(buff, param, m_dMu);

			if ( param->PRIMALSVM == 1 ) { // solve svm in the primal form
				for ( int d=0; d<pC->num_docs; d++ ) {
					loss_aug_predict( &(pC->docs[d]), theta[d] );
				}
			}
			dobj += m_dsvm_primalobj;
		} else ;

		// check for convergence
		converged = fabs(1 - dobj / obj_old);
		obj_old = dobj;

		// output model and lhood
		if ( param->SUPERVISED == 1 ) {
			fprintf(lhood_file, "%10.10f\t%10.10f\t%5.5e\t%.5f\n", dobj-m_dsvm_primalobj, dobj, converged, dLogLoss);
		} else {
			fprintf(lhood_file, "%10.10f\t%5.5e\t%.5f\n", dobj, converged, dLogLoss);
		}
		fflush(lhood_file);
		if ( nIt > 0 && (nIt % LAG) == 0) {
			sprintf( filename, "%s/%d", directory, nIt + 1);
			save_model( filename, -1 );
			sprintf( filename, "%s/%d.theta", directory, nIt + 1 );
			save_theta( filename, theta, pC->num_docs, m_nK );
		}
		nIt ++;
	}
	// learn the final SVM.
	if ( param->SUPERVISED == 0 ) {
		char buff[512];
		get_train_filename(buff, m_directory, param);
		outputLowDimData(buff, pC, theta);

		svmStructSolver(buff, param, m_dMu);
	}
	long runtime_end = get_runtime();
	double dTrainTime = ((double)runtime_end-(double)runtime_start) / 100.0;


	// output the final model
	sprintf( filename, "%s/final", directory);
	save_model( filename, dTrainTime );

	// output the word assignments (for visualization)
	int nNum = 0, nAcc = 0;
	sprintf(filename, "%s/word-assignments.dat", directory);
	FILE* w_asgn_file = fopen(filename, "w");
	for (int d=0; d<pC->num_docs; d++) {

		sparse_coding( &(pC->docs[d]), d, param, theta[d], phi[d] );
		write_word_assignment(w_asgn_file, &(pC->docs[d]), phi[d]);

		nNum ++;
		pC->docs[d].predlabel = predict(theta[d]);
		if ( pC->docs[d].gndlabel == pC->docs[d].predlabel ) nAcc ++;
	}
	fclose(w_asgn_file);
	fclose(lhood_file);

	sprintf(filename,"%s/train.theta",directory);
	save_theta(filename, theta, pC->num_docs, m_nK);

	for (int d=0; d<pC->num_docs; d++) {
		free( theta[d] );
		for (int n=0; n<pC->docs[d].length; n++)
			free( phi[d][n] );
		free( phi[d] );
	}
	free( theta );
	free( phi );

	return nIt;
}
Example #23
0
void MedSTC::predictTest(Corpus* pC, Params *param)
{
	init_param( pC );
	Document* doc = NULL;
	if ( pC->num_terms > m_nNumTerms ) {
		for ( int i=0; i<pC->num_docs; i ++ ) {
			doc = &(pC->docs[i]);
			for ( int k=0; k<doc->length; k++ )
				if ( doc->words[k] >= m_nNumTerms )
					doc->words[k] = m_nNumTerms - 1;
		}
	}
	int max_length = pC->max_corpus_length();
	double **phi = (double**)malloc(sizeof(double*)*max_length);
	for (int n=0; n<max_length; n++) {
		phi[n] = (double*)malloc(sizeof(double) * m_nK);
	}
	double **theta = (double**)malloc(sizeof(double*)*(pC->num_docs));
	for (int d=0; d<pC->num_docs; d++) {
		theta[d] = (double*)malloc(sizeof(double)*m_nK);
	}
	double **avgTheta = (double**)malloc(sizeof(double*)*m_nLabelNum);
	for ( int k=0; k<m_nLabelNum; k++ ) {
		avgTheta[k] = (double*)malloc(sizeof(double)*m_nK);
		memset(avgTheta[k], 0, sizeof(double)*m_nK);
	}
	vector<vector<double> > avgWrdCode(m_nNumTerms);
	vector<int> wrdCount(m_nNumTerms, 0);
	for ( int i=0; i<m_nNumTerms; i++ ) {
		avgWrdCode[i].resize( m_nK, 0 );
	}
	vector<int> perClassDataNum(m_nLabelNum, 0);
	double dEntropy = 0, dobj = 0, dNonZeroWrdCode = 0, dNonZeroDocCode = 0;
	int nTotalWrd = 0;
	
	for (int d=0; d<pC->num_docs; d++) {

		doc = &(pC->docs[d]);
		// initialize phi.
		for (int n=0; n<doc->length; n++) {
			double *phiPtr = phi[n];
			for ( int k=0; k<m_nK; k++ ) {
				phiPtr[k] = 1.0 / m_nK;
			}
		}
		dobj = sparse_coding( doc, d, param, theta[d], phi );

		doc->predlabel = predict(theta[d]);
		
		doc->scores = (double*) malloc(sizeof(double)*m_nLabelNum);;
		predict_scores(doc->scores,theta[d]);
		doc->lhood = dobj;
		int gndLabel = doc->gndlabel;
		perClassDataNum[gndLabel] ++;
		for ( int k=0; k<m_nK; k++ ) {
			for ( int n=0; n<doc->length; n++ ) {
				if ( phi[n][k] > 0/*1e-10*/ ) dNonZeroWrdCode ++;
			}
			
			avgTheta[gndLabel][k] += theta[d][k];
			if ( theta[d][k] > 0 ) dNonZeroDocCode ++;
		}
		nTotalWrd += doc->length;
	

		dEntropy += safe_entropy( theta[d], m_nK );

	}
	
	for (int i=0; i<pC->num_docs; i++ ) {
		free( theta[i] );
	}
	for ( int n=0; n<max_length; n++ ) {
		free( phi[n] );
	}
	for ( int k=0; k<m_nLabelNum; k++ ) {
		free( avgTheta[k] );
	}
	free( theta );
	free( phi );
	free( avgTheta );
}
Example #24
0
int main(int argc, char *argv[]) {

    //dichiarazioni variabili usate
	int i;
	char *param;
	//char valore_out[30];
	char query[MAX_LENGTH];
	riga_mysql row;						//rappresenta una riga del risultato di una query
	int serre_allocate=0;				//flag, indica se il proprietario ha delle serre ad esso associato.
										//In caso contrario � possibile rimuovere il proprietario
	char cf[17];		//codice fiscale del proprietario da cancellare
	
	
	printf("Content-type:text/html\n\n\n");                   //definizione del content-type
	//tag HTML
    printf("<html>\n");
	printf("<body>\n");
	printf("<h1>Eliminazione Proprietario di una serra</h1>");
	
	param = init_param();                                     //inizializzo parametri POST

	//connessione al database
	if (init_mysql() != 0) {                                  //controllo sulla corretta conessione al database
		param = del_param(param);
		fatal_error("Impossibile connettersi al database!");
	}
	
	if (param == NULL) {                                      //nessun parametro - visualizza il form per la cancellazione

		//esecuzione  select
		query[0] = '\0';                                      //inizializzazoine  stringa per la query
		strcat(query, "SELECT cognome, nome, cf FROM proprietario;");    //concatenazione  stringa
 
		//esecuzione query SQL
		if (select_start_mysql(query) != 0) {                 //controllo sull'esito dell'esecuzione della query SQL
			close_mysql();
			fatal_error("Impossibile comunicare con il database\n");
		}
		
		//FORM HTML
        printf("<form name=\"del_proprietario\" action=\"delproprietario\" method=\"post\">");
		printf("<select name=\"cfproprietario\">");
		
		while ((row = select_getrow_mysql()) != NULL) {       //acquisizione degli elementi per la stampa
			//row[0]=cognome, row[1]=nome, row[2]=cf
			printf("<option value=\"%s\">%s %s - %s</option>", row[2], row[0], row[1], row[2]);
		}
		
		//fine select HTML
        printf("</select>");
		printf("&nbsp;<input type=\"submit\" name=\"conferma\" value=\"Elimina\">");
		printf("</form>");
		
		select_stop_mysql();                                 //rilascio  memoria occupata per la select
	}
	else {                                                   //passato come parametro il codice fiscale del proprietario da cancellare
		if (find_n_param(param, "cfproprietario", cf, 17) == 1) { //controllo sull' estrazione del parametro "cfproprietario"
			param = del_param(param);
			print_menu();
			fatal_error("Non ci sono proprietari da cancellare dal database<br>");
		}
		
		
		//cancellazione
		query[0] = '\0';                                      //costruzione della variabile "query" che verr� usata per la select SQL
		strcat(query, "SELECT cf_proprietario, nome FROM serra WHERE cf_proprietario='");
		strcat(query, cf);
		strcat(query, "';");
		
		if (select_start_mysql(query) != 0) {                 //controllo sull'esito dell'esecuzione della select SQL
			close_mysql();
			param = del_param(param);
			fatal_error("Impossibile comunicare con il database\n");
		}
		
		while ((row = select_getrow_mysql()) != NULL) {        //ciclo per controllare se ad un proprietario � associata almeno una serra
			if (serre_allocate == 0) { //Esegue questo codice solo alla prima serra trovata nel database
				print_menu();
				printf("<p>Per questo proprietario sono allocate le seguenti serre:<br>");
				serre_allocate = 1;
			}
			printf("-> %s<br>", row[1]); //stampa il nome delle serre associate al proprietario
		}
		
		if (serre_allocate == 1) {
			fatal_error("Bisogna cancellare prima le serre elencate!<br>");
		}

		
		select_stop_mysql();                                    //rilascio memoria occupata per la select
		
		
		//preparazione  query SQL
		query[0] = '\0';                                        //costruzione della variabile "query" che verr� usata per la delete SQL
		strcat(query, "DELETE FROM proprietario WHERE cf='");
		strcat(query, cf);
		strcat(query, "';");
		
		//esecuzione query SQL
		if (insert_mysql(query) != 0) {                         //controllo sull'esito dell'esecuzione della insert SQL
			close_mysql();
			param = del_param(param);
			fatal_error("Impossibile cancellare dal database<br><a href=\"delproprietario\">Torna indietro</a><br>");
		}
		
		printf("Proprietario cancellato correttamente!<br>");
		print_menu();
		
	}
		
	param = del_param(param);                                   //eliminazione  parametri

	close_mysql();                                              //chiusura connessione

    //tag HTML
	printf("</body>\n");
	printf("</html>\n\n");

}
/** 
 * <JA>
 * @brief  第1パス平行認識処理の準備
 *
 * 計算用変数をリセットし,各種データを準備する. 
 * この関数は,ある入力(あるいはセグメント)の認識が
 * 始まる前に呼ばれる. 
 * 
 * </JA>
 * <EN>
 * @brief  Preparation for the on-the-fly 1st pass decoding.
 *
 * Variables are reset and data are prepared for the next input recognition.
 *
 * This function will be called before starting each input (segment).
 * 
 * </EN>
 *
 * @param recog [i/o] engine instance
 *
 * @return TRUE on success. FALSE on failure.
 *
 * @callgraph
 * @callergraph
 * 
 */
boolean
RealTimePipeLinePrepare(Recog *recog)
{
  RealBeam *r;
  PROCESS_AM *am;
  MFCCCalc *mfcc;
#ifdef SPSEGMENT_NAIST
  RecogProcess *p;
#endif

  r = &(recog->real);

  /* 計算用の変数を初期化 */
  /* initialize variables for computation */
  r->windownum = 0;
  /* parameter check */
  for(mfcc = recog->mfcclist; mfcc; mfcc = mfcc->next) {
    /* パラメータ初期化 */
    /* parameter initialization */
    if (recog->jconf->input.speech_input == SP_MFCMODULE) {
      if (mfc_module_set_header(mfcc, recog) == FALSE) return FALSE;
    } else {
      init_param(mfcc);
    }
    /* フレームごとのパラメータベクトル保存の領域を確保 */
    /* あとで必要に応じて伸長される */
    if (param_alloc(mfcc->param, 1, mfcc->param->veclen) == FALSE) {
      j_internal_error("ERROR: segmented: failed to allocate memory for rest param\n");
    }
    /* フレーム数をリセット */
    /* reset frame count */
    mfcc->f = 0;
  }
  /* 準備した param 構造体のデータのパラメータ型を音響モデルとチェックする */
  /* check type coherence between param and hmminfo here */
  if (recog->jconf->input.paramtype_check_flag) {
    for(am=recog->amlist;am;am=am->next) {
      if (!check_param_coherence(am->hmminfo, am->mfcc->param)) {
	jlog("ERROR: input parameter type does not match AM\n");
	return FALSE;
      }
    }
  }

  /* 計算用のワークエリアを準備 */
  /* prepare work area for calculation */
  if (recog->jconf->input.type == INPUT_WAVEFORM) {
    reset_mfcc(recog);
  }
  /* 音響尤度計算用キャッシュを準備 */
  /* prepare cache area for acoustic computation of HMM states and mixtures */
  for(am=recog->amlist;am;am=am->next) {
    outprob_prepare(&(am->hmmwrk), r->maxframelen);
  }

#ifdef BACKEND_VAD
  if (recog->jconf->decodeopt.segment) {
    /* initialize segmentation parameters */
    spsegment_init(recog);
  }
#else
  recog->triggered = FALSE;
#endif

#ifdef DEBUG_VTLN_ALPHA_TEST
  /* store speech */
  recog->speechlen = 0;
#endif

  return TRUE;
}
Example #26
0
double MedSTC::sparse_coding(char* model_dir, Corpus* pC, Params *param)
{
	char model_root[512];
	sprintf(model_root, "%s/final", model_dir);
	load_model(model_root);
	init_param( pC );

	// remove unseen words
	Document* doc = NULL;
	if ( pC->num_terms > m_nNumTerms ) {
		for ( int i=0; i<pC->num_docs; i ++ ) {
			doc = &(pC->docs[i]);
			for ( int k=0; k<doc->length; k++ )
				if ( doc->words[k] >= m_nNumTerms )
					doc->words[k] = m_nNumTerms - 1;
		}
	}

	// allocate memory
	int max_length = pC->max_corpus_length();
	double **phi = (double**)malloc(sizeof(double*)*max_length);
	for (int n=0; n<max_length; n++) {
		phi[n] = (double*)malloc(sizeof(double) * m_nK);
	}
	double **theta = (double**)malloc(sizeof(double*)*(pC->num_docs));
	for (int d=0; d<pC->num_docs; d++) {
		theta[d] = (double*)malloc(sizeof(double)*m_nK);
	}
	double **avgTheta = (double**)malloc(sizeof(double*)*m_nLabelNum);
	for ( int k=0; k<m_nLabelNum; k++ ) {
		avgTheta[k] = (double*)malloc(sizeof(double)*m_nK);
		memset(avgTheta[k], 0, sizeof(double)*m_nK);
	}
	vector<vector<double> > avgWrdCode(m_nNumTerms);
	vector<int> wrdCount(m_nNumTerms, 0);
	for ( int i=0; i<m_nNumTerms; i++ ) {
		avgWrdCode[i].resize( m_nK, 0 );
	}
	vector<int> perClassDataNum(m_nLabelNum, 0);

	
	char filename[100];
	sprintf(filename, "%s/evl-slda-obj.dat", model_dir);
	FILE* fileptr = fopen(filename, "w");
	
	
	
	double dEntropy = 0, dobj = 0, dNonZeroWrdCode = 0, dNonZeroDocCode = 0;
	int nTotalWrd = 0;
	
	for (int d=0; d<pC->num_docs; d++) {

		doc = &(pC->docs[d]);
		// initialize phi.
		for (int n=0; n<doc->length; n++) {
			double *phiPtr = phi[n];
			for ( int k=0; k<m_nK; k++ ) {
				phiPtr[k] = 1.0 / m_nK;
			}
		}
		dobj = sparse_coding( doc, d, param, theta[d], phi );

		// do prediction
		doc->predlabel = predict(theta[d]);
		
		doc->scores = (double*) malloc(sizeof(double)*m_nLabelNum);;
		predict_scores(doc->scores,theta[d]);
		
		doc->lhood = dobj;
		fprintf(fileptr, "%5.5f\n", dobj);

		//dEntropy += safe_entropy( exp[d], m_nK );
		int gndLabel = doc->gndlabel;
		perClassDataNum[gndLabel] ++;
		for ( int k=0; k<m_nK; k++ ) {
			for ( int n=0; n<doc->length; n++ ) {
				//fprintf( wrdfptr, "%.10f ", phi[n][k] );
				if ( phi[n][k] > 0/*1e-10*/ ) dNonZeroWrdCode ++;
			}
			//fprintf( wrdfptr, "\n" );
			avgTheta[gndLabel][k] += theta[d][k];
			if ( theta[d][k] > 0 ) dNonZeroDocCode ++;
		}
		nTotalWrd += doc->length;
		//fprintf( wrdfptr, "\n" );
		//fflush( wrdfptr );

		dEntropy += safe_entropy( theta[d], m_nK );

		//// the average distribution of each word on the topics.
		//for ( int n=0; n<doc->length; n++ ) {
		//	int wrd = doc->words[n];
		//	wrdCount[wrd] ++;
		//	for ( int k=0; k<m_nK; k++ ) {
		//		avgWrdCode[wrd][k] += phi[n][k];
		//	}
		//}
	}
	
	fclose( fileptr );
	
	
	

	/* save theta & average theta. */
	sprintf(filename, "%s/evl-theta.dat", model_dir);
	save_theta(filename, theta, pC->num_docs, m_nK);
	sprintf(filename, "%s/evl-avgTheta.dat", model_dir);
	for ( int m=0; m<m_nLabelNum; m++ ) {
		int dataNum = perClassDataNum[m];
		for ( int k=0; k<m_nK; k++ ) {
			avgTheta[m][k] /= dataNum;
		}
	}
	printf_mat(filename, avgTheta, m_nLabelNum, m_nK);

	/* save the average topic distribution for each word. */
	sprintf(filename, "%s/evl-avgWrdCode.dat", model_dir);
	fileptr = fopen( filename, "w" );
	for ( int i=0; i<m_nNumTerms; i++ ) {
		double dNorm = wrdCount[i];
		for ( int k=0; k<m_nK; k++ ) {
			double dval = avgWrdCode[i][k];
			if ( dNorm > 0 ) dval /= dNorm;
			fprintf( fileptr, "%.10f ", dval );
		}
		fprintf( fileptr, "\n" );
	}
	fclose( fileptr );
	//printf_mat( filename, avgWrdCode, m_nNumTerms, m_nK );

	/* save the low dimension representation. */
	get_test_filename(filename, model_dir, param);
	outputLowDimData(filename, pC, theta);

	/* save the prediction performance. */
	sprintf(filename, "%s/evl-performance.dat", model_dir);
	double dAcc = save_prediction(filename, pC);

	// free memory
	for (int i=0; i<pC->num_docs; i++ ) {
		free( theta[i] );
	}
	for ( int n=0; n<max_length; n++ ) {
		free( phi[n] );
	}
	for ( int k=0; k<m_nLabelNum; k++ ) {
		free( avgTheta[k] );
	}
	free( theta );
	free( phi );
	free( avgTheta );

	return dAcc;
}
Example #27
0
void fmserver (void)
{
	struct fmparam param[1];

	// MessageBox (NULL, "Hello", "Message", MB_OK);

	init_param(param);
	
	/* test

	CDatabase db;
	db.OpenEx (_T("DSN=droits"), 0);

	CRecordsetClients rs;

	rs.Open (AFX_DB_USE_DEFAULT_TYPE, "SELECT * FROM clients", 0);
	rs.MoveFirst();
	for (;;)
	{
		if (rs.IsEOF())
			break;
		MessageBox (NULL, rs.m_login, "Login", MB_OK);
		rs.MoveNext();
	}

	rs.Close();

	*/

	WSADATA wsda;
	SOCKET sListen, sClient;
	struct hostent * hp;
	char buf[10000];
	int len;
	SOCKADDR_IN addr, remote_addr;
	int ret;
	int iAddrLen;

	WSAStartup (MAKEWORD(1,1), &wsda);

	hp = gethostbyname ("localhost");

	/*sListen = socket (hp->h_addrtype, SOCK_STREAM, 0);*/

	sListen = socket (AF_INET, SOCK_STREAM, 0 /*IPPROTO_IP*/);
	if (sListen == SOCKET_ERROR)
	{
		MessageBox (NULL, "Error creating socket", "Error", MB_OK);
		exit(0);
	}

	memset (&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6030);
	addr.sin_addr.s_addr = htonl (INADDR_ANY);

	ret = bind (sListen, (struct sockaddr *)&addr, sizeof(addr));
	if (ret == SOCKET_ERROR)
	{
		MessageBox (NULL, "Error bind", "Error", MB_OK);
		exit(0);
	}

	ret = listen (sListen, 10);
	if (ret == SOCKET_ERROR)
	{
		sprintf (buf, "Error listen: %d", WSAGetLastError());		
		MessageBox (NULL, buf, "Error listen", MB_OK);
		exit(0);
	}

	for (;;)
	{

	iAddrLen = sizeof(remote_addr);

	sClient = accept (sListen, (struct sockaddr *) &remote_addr, &iAddrLen);
	if (sClient == SOCKET_ERROR)
	{
		MessageBox (NULL, "Error accept", "Error", MB_OK);
		exit(0);
	}

	// MessageBox (NULL, "Accepted", "server", MB_OK);

	/*
	ret = recv (sClient, buf, sizeof(buf), 0);
	if (ret == SOCKET_ERROR)
	{
		MessageBox (NULL, "Error recv", "Error", MB_OK);
		exit(0);
	}
	buf[ret] = 0;

	MessageBox (NULL, buf, "Received", MB_OK);
	*/

	/*
	input (sClient, buf);
	MessageBox (NULL, buf, "received", MB_OK);
	*/

	char dirfax[100];
	char basedroits[100];
	char basefax[100];
	char faxdir[100];
	char language[100];
	char login[100];
	char pass[100];

	strcpy (basedroits, "droits");
	strcpy (basefax, "AT05");
	strcpy (faxdir, "L:\\AT05");


	for (;;)
	{
		input (sClient, buf);
		if (status == SOCKET_ERROR)
			break;

		// MessageBox (NULL, buf, "commande", MB_OK);
	
		if (!strcmp (buf, "BASEFAX"))
		{
			input (sClient, dirfax);
			input (sClient, language);
			
			if (*dirfax)
			{
				lire_fichier (dirfax, "baserights.txt", basedroits);
				lire_fichier (dirfax, "basefax.txt", basefax);
				lire_fichier (dirfax, "faxdir.txt", faxdir);
			}

			output (sClient, "ID\tIdentifiant\t30\n");
			output (sClient, "CNX\tDate\t20\n");
			output (sClient, "TIME\tDurée\t5\n");
			output (sClient, "PGENB\tPages\t5\n");
			output (sClient, "HGN\tStatus\t5\n");
			output (sClient, "FILE\tFichier\t15\n");
			output (sClient, "\n");
		 
		}
		else if (!strcmp (buf, "USER"))
		{
			input (sClient, login);
		}
		else if (!strcmp (buf, "PASS"))
		{
			input (sClient, pass);
			output (sClient, "LOGIN\n1\n");
		}
		
		else if (!strcmp (buf, "LISTREC"))
		{
			
			char param[100];
			char strsince[100];
			input (sClient, param);
			input (sClient, strsince);

			CDatabase db;
			char dsn[100];
			sprintf (dsn, "DSN=%s", basefax);
			db.OpenEx (_T(dsn), 0);

			CRecordsetRec rs;

			rs.Open (AFX_DB_USE_DEFAULT_TYPE, "SELECT * FROM REC", 0);
			rs.MoveFirst();

			// MessageBox (NULL, "Reading base", "trace", MB_OK);

			for (;;)
			{
				if (rs.IsEOF())
					break;
				/*MessageBox (NULL, rs.m_ID, "id", MB_OK);*/
				sprintf (buf, 
 "<MESSAGE><BASE>FAXBT</BASE><ID>%s</ID><CNX>%s</CNX><TIME>%lf</TIME><PGENB>%lf</PGENB><HGN>%lf</HGN><FILE>%s</FILE></MESSAGE>\n",
								LPCSTR(rs.m_ID), 
								LPCSTR(rs.m_CNX), 
								rs.m_TIME, 
								rs.m_PGENB, 
								rs.m_HGN,
								LPCSTR(rs.m_FILE));
				/*MessageBox (NULL, buf, "Message", MB_OK);*/
				output (sClient, buf);
				rs.MoveNext();
			}
			output (sClient, "\n");

			rs.Close();



		}
		else if (!strcmp (buf, "END"))
		{
			// MessageBox (NULL, buf, "END", MB_OK);
			break;
		}
		else
		{
			// MessageBox (NULL, buf, "autre commande", MB_OK);
		}


	}

	closesocket (sClient);

	}
/*
	for (;;)
	{
		input (commande);
		MessageBox (NULL, commande, "Commande", MB_OK);

	}
*/

}