int main() { vartable_t *table; sfip_var_t *var; sfip_t *ip; puts("********************************************************************"); puts("Testing variable table parsing:"); table = sfvt_alloc_table(); /* These are all valid */ TEST(sfvt_add_str(table, "foo [ 1.2.0.0/16, ffff:dead:beef::0 ] ", &var) == SFIP_SUCCESS); TEST(sfvt_add_str(table, " goo [ ffff:dead:beef::0 ] ", &var) == SFIP_SUCCESS); TEST(sfvt_add_str(table, " moo [ any ] ", &var) == SFIP_SUCCESS); /* Test variable redefine */ TEST(sfvt_add_str(table, " goo [ 192.168.0.1, 192.168.0.2, 192.168.255.0 255.255.248.0 ] ", &var) == SFIP_DUPLICATE); /* These should fail since it's a variable name with bogus arguments */ TEST(sfvt_add_str(table, " phlegm ", &var) == SFIP_FAILURE); TEST(sfvt_add_str(table, " phlegm [", &var) == SFIP_FAILURE); TEST(sfvt_add_str(table, " phlegm [ ", &var) == SFIP_FAILURE); TEST(sfvt_add_str(table, " phlegm [sdfg ", &var) == SFIP_FAILURE); TEST(sfvt_add_str(table, " phlegm [ sdfg, 12.123.1.4.5 }", &var) == SFIP_FAILURE); TEST(sfvt_add_str(table, " [ 12.123.1.4.5 ]", &var) == SFIP_FAILURE); TEST(sfvt_add_str(table, NULL, &var) == SFIP_FAILURE); TEST(sfvt_add_str(table, "", &var) == SFIP_FAILURE); puts(""); puts("********************************************************************"); puts("Expansions:"); /* Note: used this way leaks memory */ printf("\t%s\n", sfvt_alloc_expanded(table, "$foo")); printf("\t%s\n", sfvt_alloc_expanded(table, "goo $goo sf sfasdfasdf $moo")); printf("\t%s\n", sfvt_alloc_expanded(table, " ssdf $moo $moo asdf $fooadff $foo ")); printf("\t%s\n", sfvt_alloc_expanded(table, " ssdf $moo $moo\\sdf $foo adff")); puts(""); puts("********************************************************************"); puts("Containment checks:"); var = sfvt_lookup(table, "goo"); ip = sfip_alloc("192.168.248.255"); TEST(sfvar_ip_in(var, ip) == SFIP_SUCCESS); /* Check against the 'any' variable */ var = sfvt_lookup_var(table, "moo"); TEST(sfvar_ip_in(var, ip) == SFIP_SUCCESS); /* Verify it's not in this variable */ var = sfvt_lookup_var(table, "foo"); TEST(sfvar_ip_in(var, ip) == SFIP_FAILURE); /* Check boundary cases */ var = sfvt_lookup_var(table, "goo"); free_ip(ip); ip = sfip_alloc_str("192.168.0.3"); TEST(sfvar_ip_in(var, ip) == SFIP_FAILURE); free_ip(ip); ip = sfip_alloc_str("192.168.0.2"); TEST(sfvar_ip_in(var, ip) == SFIP_SUCCESS); puts(""); puts("********************************************************************"); printf("\n\tTotal Failures: %d\n", failures); return 0; }
int main( int argc, char** argv ) { obj_t a, c; obj_t c_save; obj_t alpha; dim_t m, n; dim_t p; dim_t p_begin, p_end, p_inc; int m_input, n_input; num_t dt; int r, n_repeats; side_t side; uplo_t uploa; trans_t transa; diag_t diaga; f77_char f77_side; f77_char f77_uploa; f77_char f77_transa; f77_char f77_diaga; double dtime; double dtime_save; double gflops; //bli_init(); //bli_error_checking_level_set( BLIS_NO_ERROR_CHECKING ); n_repeats = 3; #ifndef PRINT p_begin = 200; p_end = 2000; p_inc = 200; m_input = -1; n_input = -1; #else p_begin = 16; p_end = 16; p_inc = 1; m_input = 4; n_input = 4; #endif #if 1 //dt = BLIS_FLOAT; dt = BLIS_DOUBLE; #else //dt = BLIS_SCOMPLEX; dt = BLIS_DCOMPLEX; #endif side = BLIS_LEFT; //side = BLIS_RIGHT; uploa = BLIS_LOWER; //uploa = BLIS_UPPER; transa = BLIS_NO_TRANSPOSE; diaga = BLIS_NONUNIT_DIAG; bli_param_map_blis_to_netlib_side( side, &f77_side ); bli_param_map_blis_to_netlib_uplo( uploa, &f77_uploa ); bli_param_map_blis_to_netlib_trans( transa, &f77_transa ); bli_param_map_blis_to_netlib_diag( diaga, &f77_diaga ); for ( p = p_begin; p <= p_end; p += p_inc ) { if ( m_input < 0 ) m = p * ( dim_t )abs(m_input); else m = ( dim_t ) m_input; if ( n_input < 0 ) n = p * ( dim_t )abs(n_input); else n = ( dim_t ) n_input; bli_obj_create( dt, 1, 1, 0, 0, &alpha ); if ( bli_is_left( side ) ) bli_obj_create( dt, m, m, 0, 0, &a ); else bli_obj_create( dt, n, n, 0, 0, &a ); bli_obj_create( dt, m, n, 0, 0, &c ); bli_obj_create( dt, m, n, 0, 0, &c_save ); bli_randm( &a ); bli_randm( &c ); bli_obj_set_struc( BLIS_TRIANGULAR, &a ); bli_obj_set_uplo( uploa, &a ); bli_obj_set_conjtrans( transa, &a ); bli_obj_set_diag( diaga, &a ); // Randomize A, make it densely Hermitian, and zero the unstored // triangle to ensure the implementation reads only from the stored // region. bli_randm( &a ); bli_mkherm( &a ); bli_mktrim( &a ); bli_setsc( (2.0/1.0), 1.0, &alpha ); bli_copym( &c, &c_save ); dtime_save = DBL_MAX; for ( r = 0; r < n_repeats; ++r ) { bli_copym( &c_save, &c ); dtime = bli_clock(); #ifdef PRINT bli_invertd( &a ); bli_printm( "a", &a, "%4.1f", "" ); bli_invertd( &a ); bli_printm( "c", &c, "%4.1f", "" ); #endif #ifdef BLIS bli_trsm( side, &alpha, &a, &c ); #else if ( bli_is_float( dt ) ) { f77_int mm = bli_obj_length( &c ); f77_int nn = bli_obj_width( &c ); f77_int lda = bli_obj_col_stride( &a ); f77_int ldc = bli_obj_col_stride( &c ); float* alphap = bli_obj_buffer( &alpha ); float* ap = bli_obj_buffer( &a ); float* cp = bli_obj_buffer( &c ); strsm_( &f77_side, &f77_uploa, &f77_transa, &f77_diaga, &mm, &nn, alphap, ap, &lda, cp, &ldc ); } else if ( bli_is_double( dt ) ) { f77_int mm = bli_obj_length( &c ); f77_int nn = bli_obj_width( &c ); f77_int lda = bli_obj_col_stride( &a ); f77_int ldc = bli_obj_col_stride( &c ); double* alphap = bli_obj_buffer( &alpha ); double* ap = bli_obj_buffer( &a ); double* cp = bli_obj_buffer( &c ); dtrsm_( &f77_side, &f77_uploa, &f77_transa, &f77_diaga, &mm, &nn, alphap, ap, &lda, cp, &ldc ); } else if ( bli_is_scomplex( dt ) ) { f77_int mm = bli_obj_length( &c ); f77_int nn = bli_obj_width( &c ); f77_int lda = bli_obj_col_stride( &a ); f77_int ldc = bli_obj_col_stride( &c ); scomplex* alphap = bli_obj_buffer( &alpha ); scomplex* ap = bli_obj_buffer( &a ); scomplex* cp = bli_obj_buffer( &c ); ctrsm_( &f77_side, &f77_uploa, &f77_transa, &f77_diaga, &mm, &nn, alphap, ap, &lda, cp, &ldc ); } else if ( bli_is_dcomplex( dt ) ) { f77_int mm = bli_obj_length( &c ); f77_int nn = bli_obj_width( &c ); f77_int lda = bli_obj_col_stride( &a ); f77_int ldc = bli_obj_col_stride( &c ); dcomplex* alphap = bli_obj_buffer( &alpha ); dcomplex* ap = bli_obj_buffer( &a ); dcomplex* cp = bli_obj_buffer( &c ); ztrsm_( &f77_side, &f77_uploa, &f77_transa, &f77_diaga, &mm, &nn, alphap, ap, &lda, cp, &ldc ); } #endif #ifdef PRINT bli_printm( "c after", &c, "%9.5f", "" ); exit(1); #endif dtime_save = bli_clock_min_diff( dtime_save, dtime ); } if ( bli_is_left( side ) ) gflops = ( 1.0 * m * m * n ) / ( dtime_save * 1.0e9 ); else gflops = ( 1.0 * m * n * n ) / ( dtime_save * 1.0e9 ); if ( bli_is_complex( dt ) ) gflops *= 4.0; #ifdef BLIS printf( "data_trsm_blis" ); #else printf( "data_trsm_%s", BLAS ); #endif printf( "( %2lu, 1:4 ) = [ %4lu %4lu %10.3e %6.3f ];\n", ( unsigned long )(p - p_begin + 1)/p_inc + 1, ( unsigned long )m, ( unsigned long )n, dtime_save, gflops ); bli_obj_free( &alpha ); bli_obj_free( &a ); bli_obj_free( &c ); bli_obj_free( &c_save ); } //bli_finalize(); return 0; }
int main() { time_t hora; struct tm *timeinfo; int Nvoos; int Ndecolagens; int Npousos; char codigo_voo[7]; char tipo_voo; int combustivel_voo; int aviso_voo; int pista_voo = 1; char codigos[64][7] = {"VG3001", "JJ4404", "LN7001", "TG1501", "GL7602", "TT1010", "AZ1009", "AZ1008", "AZ1010", "TG1506", "VG3002", "JJ4402", "GL7603", "RL7880", "AL0012", "TT4544", "TG1505", "VG3003", "JJ4403", "JJ4401", "LN7002", "AZ1002", "AZ1007", "GL7604", "AZ1006", "TG1503", "AZ1003", "JJ4403", "AZ1001", "LN7003", "AZ1004", "TG1504", "AZ1005", "TG1502", "GL7601", "TT4500", "RL7801", "JJ4410", "GL7607", "AL0029", "VV3390", "VV3392", "GF4681", "GF4690", "AZ1020", "JJ4435", "VG3010", "LF0920", "AZ1065", "LF0978", "RL7867", "TT4502", "GL7645", "LF0932", "JJ4434", "TG1510", "TT1020", "AZ1098", "BA2312", "VG3030", "BA2304", "KL5609", "KL5610", "KL5611"}; srand(time(NULL)); //Gerador de número de vôos, pousos e decolagens Nvoos = geraRand (0, 64); Ndecolagens = geraRand (0, Nvoos); Npousos = Nvoos - Ndecolagens; int voos = 0; int dec = Ndecolagens; int pouso = Npousos; FILA fila = cria_fila(); for(voos = 1; voos <= Nvoos; voos++){ strcpy(codigo_voo, codigos[voos]); if(pouso > 0 && dec >0){ if(geraRand(0,1)){ tipo_voo = 'D'; dec--; combustivel_voo = geraRand (24, 48); pista_voo = ((voos-1)%3)+1; } else{ tipo_voo = 'P'; pouso--; combustivel_voo = geraRand (0, 12); if (combustivel_voo == 0) aviso_voo = 1; else aviso_voo = 0; pista_voo = ((voos - 1)%3) + 1; if(pista_voo == 3 && tipo_voo == 'P' && aviso_voo == 0){ pista_voo = ((voos)%3) + 1; } } } else if (pouso == 0 && dec !=0){ tipo_voo = 'D'; dec--; combustivel_voo = geraRand (24, 48); pista_voo = ((voos-1)%3) + 1; } else if (pouso != 0 && dec == 0){ tipo_voo = 'P'; pouso--; combustivel_voo = geraRand (0, 12); if (combustivel_voo == 0){ aviso_voo = 1; } else{ aviso_voo = 0; } pista_voo = ((voos - 1)%3) + 1; if(pista_voo == 3 && tipo_voo == 'P' && aviso_voo == 0){ pista_voo = ((voos)%3) + 1; } } insere_fila(fila, codigo_voo, tipo_voo, combustivel_voo, aviso_voo, pista_voo); } printf ("\n Aeroporto Internacional de Brasilia\n"); hora = time(NULL); timeinfo = localtime(&hora); printf(" Hora atual: %02d:%02d:%02d\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); printf(" Fila de pedidos:\n"); printf(" Nvoos: %d\n", Nvoos); printf(" Ndecolagens: %d\n", Ndecolagens); printf(" Npousos: %d\n\n", Npousos); printf(" Fila designada (na ordem) por pistas:\n\n"); printf(" ******Pista 1:******\n Pousos:\n\n"); ver_fila(fila, 'P', 1); printf("\n Decolagens:\n\n"); ver_fila(fila, 'D', 1); printf("\n ******Pista 2:******\n Pousos:\n\n"); ver_fila(fila, 'P', 2); printf("\n Decolagens:\n\n"); ver_fila(fila, 'D', 2); printf("\n ******Pista 3:******\n Pousos:\n\n"); ver_fila(fila, 'P', 3); printf("\n Decolagens:\n\n"); ver_fila(fila, 'D', 3); printf("\n"); libera_fila (fila); return 0; }
static void TEST_CORE_GetVMPageSize(void) { printf("PageSize = %d\n", (int) CORE_GetVMPageSize()); }
virtual void print(void) const { printf("B::print\n"); }
/* //////////////////////////////////////////////////////////////////////////// -- Testing zpotrf_mc */ int main( magma_int_t argc, char** argv) { cuDoubleComplex *h_A, *h_R, *h_work, *h_A2; cuDoubleComplex *d_A; float gpu_perf, cpu_perf, cpu_perf2; magma_timestr_t start, end; /* Matrix size */ magma_int_t N=0, n2, lda; magma_int_t size[10] = {1024,2048,3072,4032,5184,6048,7200,8064,8928,10080}; magma_int_t i, j, info[1]; magma_int_t ione = 1; magma_int_t ISEED[4] = {0,0,0,1}; magma_int_t num_cores = 4; int num_gpus = 0; magma_int_t loop = argc; if (argc != 1){ for(i = 1; i<argc; i++){ if (strcmp("-N", argv[i])==0) N = atoi(argv[++i]); else if (strcmp("-C", argv[i])==0) num_cores = atoi(argv[++i]); } if (N==0) { N = size[9]; loop = 1; } else { size[0] = size[9] = N; } } else { printf("\nUsage: \n"); printf(" testing_zpotrf_mc -N %d -B 128 \n\n", 1024); N = size[9]; } lda = N; n2 = size[9] * size[9]; /* Allocate host memory for the matrix */ h_A = (cuDoubleComplex*)malloc(n2 * sizeof(h_A[0])); if (h_A == 0) { fprintf (stderr, "!!!! host memory allocation error (A)\n"); } /* Allocate host memory for the matrix */ h_A2 = (cuDoubleComplex*)malloc(n2 * sizeof(h_A2[0])); if (h_A2 == 0) { fprintf (stderr, "!!!! host memory allocation error (A2)\n"); } /* Initialize MAGMA hardware context, seeting how many CPU cores and how many GPUs to be used in the consequent computations */ magma_context *context; context = magma_init(NULL, NULL, 0, num_cores, num_gpus, argc, argv); printf("\n\n"); printf(" N Multicore GFlop/s ||R||_F / ||A||_F\n"); printf("=============================================\n"); for(i=0; i<10; i++) { N = lda = size[i]; n2 = N*N; lapackf77_zlarnv( &ione, ISEED, &n2, h_A ); for(j=0; j<N; j++) MAGMA_Z_SET2REAL( h_A[j*lda+j], ( MAGMA_Z_GET_X(h_A[j*lda+j]) + 2000. ) ); for(j=0; j<n2; j++) h_A2[j] = h_A[j]; /* ===================================================================== Performs operation using LAPACK =================================================================== */ //lapackf77_zpotrf("L", &N, h_A, &lda, info); lapackf77_zpotrf("U", &N, h_A, &lda, info); if (info[0] < 0) printf("Argument %d of zpotrf had an illegal value.\n", -info[0]); /* ===================================================================== Performs operation using multi-core =================================================================== */ start = get_current_time(); //magma_zpotrf_mc(context, "L", &N, h_A2, &lda, info); magma_zpotrf_mc(context, "U", &N, h_A2, &lda, info); end = get_current_time(); if (info[0] < 0) printf("Argument %d of magma_zpotrf_mc had an illegal value.\n", -info[0]); cpu_perf2 = FLOPS( (double)N ) / (1000000.*GetTimerValue(start,end)); /* ===================================================================== Check the result compared to LAPACK =================================================================== */ double work[1], matnorm = 1.; cuDoubleComplex mone = MAGMA_Z_NEG_ONE; int one = 1; matnorm = lapackf77_zlange("f", &N, &N, h_A, &N, work); blasf77_zaxpy(&n2, &mone, h_A, &one, h_A2, &one); printf("%5d %6.2f %e\n", size[i], cpu_perf2, lapackf77_zlange("f", &N, &N, h_A2, &N, work) / matnorm); if (loop != 1) break; } /* Memory clean up */ free(h_A); free(h_A2); /* Shut down the MAGMA context */ magma_finalize(context); }
/* FLOG_Cleanup */ static void TEST_CORE_LogCleanup(void* user_data) { assert(user_data == &TEST_CORE_LogUserData); printf("TEST_CORE_LogCleanup(round %d)\n", TEST_CORE_LogUserData); TEST_CORE_LogUserData = 444; }
/* Main Function acting as a client for Image Encode Call*/ XDAS_Int32 main(int argc, char *argv[]) { /* File I/O variables */ FILE *fConfigFile, /**ftestFile, *finFile,*/ *fparamsFile; #ifdef LINUX CMEM_AllocParams memParams; memParams.type=CMEM_POOL; memParams.flags=CMEM_NONCACHED; memParams.alignment=256; #endif char* colorf[]={"YUV422P", "YUV420P", "YUV422P", "YUV422IL", "YUV422IL", "YUV444", "YUV411", "GRAY", "RGB", "YUV420_LINE"}; #ifdef LINUX XDAS_Int8 *fname = "../TestVecs/Config/Testvecs.cfg"; #else XDAS_Int8 *fname = "..\\..\\Test\\TestVecs\\Config\\Testvecs_ccs.cfg"; #endif Int32 lTemp,countConfigSet; Int32 retVal; Uint32 numAU, totalAU,repeat; Uint32 bytesGenerated; Uint16 mbSizeX, mbSizeY,mbY; char *RefBuffPtr; FILE *fp_out; FILE *fp_in; int processTime = 0, processTimeTotal = 0,algActivateTime =0, algDeactivateTime =0,copctime=0; int val,queue_word,queue_num=0,i,k; char baseParams[STRING_SIZE]; int baseParamsOnly; int Offset; int num_markers; IIMGENC1_Fxns *iimgEncfxns; IIMGENC1_Status imgencStatus; IIMGENC1_InArgs imgencInArgs; IIMGENC1_OutArgs imgencOutArgs; IJPEGENC_Status status; IJPEGENC_InArgs inArgs; IJPEGENC_OutArgs outArgs; unsigned int lTemp1; /*Algorithm specific handle */ IALG_Handle handle; /* Input/Output Buffer Descriptor variables */ XDM1_BufDesc inputBufDesc, outputBufDesc; #ifdef ENABLE_RMAN // IRES/RMAN Related declarations // temp_trace_init(); IRES_Status iresStatus; Int size =0; Int scratchId =0; Bool result = TRUE; IRES_Fxns *resFxns = &JPEGENC_TI_IRES; IRESMAN_Edma3ChanParams configParams; IRESMAN_VicpParams iresmanConfigParams; IRESMAN_AddrSpaceParams addrspaceConfigParams; iresStatus = RMAN_init(); if (IRES_OK != iresStatus) { printf("RMAN initialization Failed \n"); return -1; } printf("RMAN initialization done \n"); #ifndef LINUX /* Call the functions to enable ARM926 FIQ and do some basic * setup to AINTC to accept KLD INTC (arm968) interupt in * FIQ pin of Arm926 */ ARM926_enable_FIQ(); /* SWI call to enable interrupts */ ARM926_INTC_init(); /* Init AINTC */ #endif /* * Supply initialization information for the RESMAN while registering */ size = sizeof(IRESMAN_VicpParams); iresmanConfigParams.baseConfig.allocFxn = RMAN_PARAMS.allocFxn; iresmanConfigParams.baseConfig.freeFxn = RMAN_PARAMS.freeFxn; iresmanConfigParams.baseConfig.size = size; /* Register the VICP protocol/resource manager with the * * generic resource manager */ iresStatus = RMAN_register(&IRESMAN_VICP2, (IRESMAN_Params *)&iresmanConfigParams); if (IRES_OK != iresStatus) { printf("VICP Protocol Registration Failed \n"); return -1; } printf("VICP Protocol Registration Success \n"); /* * * Supply initialization information for the EDMA3 RESMAN while registering * */ size = sizeof(IRESMAN_Edma3ChanParams); configParams.baseConfig.allocFxn = RMAN_PARAMS.allocFxn; configParams.baseConfig.freeFxn = RMAN_PARAMS.freeFxn; configParams.baseConfig.size = size; iresStatus = RMAN_register(&IRESMAN_EDMA3CHAN, (IRESMAN_Params *)&configParams); if (IRES_OK != iresStatus) { printf("EDMA3 Protocol Registration Failed \n"); return -1; } printf("EDMA3 Protocol Registration Success \n"); /** Supply initialization information for the ADDRSPACE RESMAN while registering * */ #if 1 size = sizeof(IRESMAN_AddrSpaceParams); addrspaceConfigParams.baseConfig.allocFxn = RMAN_PARAMS.allocFxn; addrspaceConfigParams.baseConfig.freeFxn = RMAN_PARAMS.freeFxn; addrspaceConfigParams.baseConfig.size = size; iresStatus = RMAN_register(&IRESMAN_ADDRSPACE, (IRESMAN_Params *)&addrspaceConfigParams); if (IRES_OK != iresStatus) { printf("ADDRSPACE Protocol Registration Failed \n"); return -1; } #ifdef _DBG_MSG printf("ADDRSPACE Protocol Registration Success \n"); #endif #endif #endif //IRES/RMAN related code ends here #ifdef LINUX CMEM_init(); ExternalGlobalMemPool = ExternalGlobalMemPoolBase = CMEM_alloc(EXTERNAL_DATA_MEM_SIZE,&memParams); #ifdef ENABLE_RING_BUF_USAGE ringbuf = CMEM_alloc(RINGBUFSIZE, &memParams); #endif OrgPictureY_0=CMEM_alloc( (LUMABUF_SIZE*2+ORGBUF_OFFSET), &memParams); OrgPictureCb_0=CMEM_alloc((CHROMABUF_SIZE+ORGBUF_OFFSET), &memParams); OrgPictureCr_0=CMEM_alloc((CHROMABUF_SIZE+ORGBUF_OFFSET), &memParams); media=CMEM_alloc((ENCODED_DATA_BUFFER_SIZE), &memParams); //#ifdef LINUX // DM350MM_init(); //#endif if (argc==2) { strncpy(baseParams,argv[1],256); if (!strcmp(baseParams,"-ext")) { printf("\n----- Running in extended parameter mode -----\n"); baseParamsOnly=0; } else { printf("Argument -ext needed to run in extended param mode\n"); exit(0); } } else { printf("\n----- Running in base parameter mode -----\n"); baseParamsOnly=1; } #else baseParamsOnly=0; #endif //memset(ringbuf,0xaa,RINGBUFSIZE ); memset(media, 0xaa, ENCODED_DATA_BUFFER_SIZE); memset(ExternalGlobalMemPool, 0xaa,EXTERNAL_DATA_MEM_SIZE ); memset(OrgPictureY_0, 0xaa, (LUMABUF_SIZE*2+ORGBUF_OFFSET)); memset(OrgPictureCb_0, 0xaa, (CHROMABUF_SIZE+ORGBUF_OFFSET)); memset(OrgPictureCr_0, 0xaa, (CHROMABUF_SIZE+ORGBUF_OFFSET)); OrgPictureY = &OrgPictureY_0[ORGBUF_OFFSET]; OrgPictureCb = &OrgPictureCb_0[ORGBUF_OFFSET]; OrgPictureCr = &OrgPictureCr_0[ORGBUF_OFFSET]; /* Open Test Config File */ fConfigFile = fopen(fname, "r"); if (!fConfigFile) { printf("Couldn't open parameter file %s\n", fname); return XDM_EFAIL; } countConfigSet = 1; /* Reset countConfigSet value to 1 */ /* Read the Config File until it reaches the end of file */ while (!feof(fConfigFile)) { /* Read Compliance Checking parameter */ if (fgets(line, 254, fConfigFile)) { sscanf(line, "%d\n", &testCompliance); printf("\nTestcompliance = %d\n",testCompliance); } else { break; } /* Read Parameters file name */ if (fgets(line, 254, fConfigFile)) { sscanf(line, "%s", paramsFile); printf("\nParam file = %s\n",paramsFile); } else { break; } /* Read Input file name */ if (fgets(line, 254, fConfigFile)) { sscanf(line, "%s", inFile); printf("\nInput file = %s\n",inFile); } else { break; } /* Read Output/Reference file name */ if (fgets(line, 254, fConfigFile)) { sscanf(line, "%s", testFile); printf("\nOutput file = %s\n",testFile); } else { break; } printf("\n*******************************************"); printf("\nRead Configuration Set %d", countConfigSet); printf("\n*******************************************"); countConfigSet++; fp_out=fopen(testFile,"wb"); fp_in = fopen(inFile,"rb"); if ((fp_in == NULL) || (fp_out == NULL)) { printf("'Input/out file cannot be opened\n"); exit(0); } /** Set initialization parameters * Parameters in structure params are default image encode parameters required by XDM * Paraemters in extn_params are parameters specific to jpeg encoder, * */ /* Open Parameters file */ fparamsFile = fopen(paramsFile, "rb"); //fparamsFile = fopen("Testparams.cfg", "rb"); if (!fparamsFile) { printf("\nCouldn't open Parameters file... %s\n ", paramsFile); printf("Exiting for this configuration...\n"); continue; } printf("\nParameter file read starts...\n"); if (readparamfile(fparamsFile,baseParamsOnly) < 0) { printf("\nSyntax Error in %s\n ", paramsFile); printf("Exiting for this configuration...\n"); continue; } /* Close Parameters File */ fclose(fparamsFile); if (testCompliance) { printf("\nRunning in Compliance Mode"); } else { printf("\nRunning in Output Dump Mode"); } /** Call algorithm creation function * See file alg_create. * memory allocation functions are called inside alg_malloc file. * Modify _ALG_allocMemory in alg_malloc.c to suit the application need (static allocation vs dynamic through malloc()) */ if (baseParamsOnly==0) { #ifdef ENABLE_RING_BUF_USAGE extn_params.halfBufCB =(XDAS_Void (*)(Uint32, XDAS_Void*))JPEGENC_TI_DM350_HalfBufCB; extn_params.halfBufCBarg= (void*)&ring2media; #else extn_params.halfBufCB = (XDAS_Void (*))NULL; #endif extn_params.imgencParams = params; extn_params.imgencParams.size = sizeof(IJPEGENC_Params); } else { params.size = sizeof(IIMGENC1_Params); dynamicParams.size =sizeof(IIMGENC1_DynamicParams); } if (baseParamsOnly==0) { if ((handle = (IALG_Handle)ALG_create ( (IALG_Fxns *) &JPEGENC_TI_IJPEGENC, (IALG_Handle) NULL, (IALG_Params *)&extn_params)) == NULL) { printf("\nFailed to Create Instance... Exiting for this configuration.."); exit(0); } printf("\nAlgorithm Instance Creation Done...\n"); } else { if ((handle = (IALG_Handle)ALG_create ( (IALG_Fxns *) &JPEGENC_TI_IJPEGENC, (IALG_Handle) NULL, (IALG_Params *)¶ms)) == NULL) { printf("\nFailed to Create Instance... Exiting for this configuration.."); exit(0); } printf("\nAlgorithm Instance Creation Done...\n"); } #ifdef ENABLE_RMAN // IRES/RMAN Related code /* Create an instance of an algorithm that implements IALG and IRES_Fxns */ iresStatus = RMAN_assignResources((IALG_Handle)handle, resFxns,scratchId); if (IRES_OK != iresStatus) { printf("Assign Resource Failed \n"); result = FALSE; } #endif //IRES/RMAN code ends here. /** Set up dynamic parameters (can be changed before each call to jpeg processing) * Parameters in structure dynamicParams are default image encode parameters required by XDM */ if (baseParamsOnly==0) { extn_dynamicParams.imgencDynamicParams = dynamicParams; extn_dynamicParams.imgencDynamicParams.size = sizeof(IJPEGENC_DynamicParams); extn_dynamicParams.disableEOI = 0; iimgEncfxns = (IIMGENC1_Fxns *)handle->fxns ; status.imgencStatus.size= sizeof(IJPEGENC_Status); } else { dynamicParams.size = sizeof(IIMGENC1_DynamicParams); iimgEncfxns = (IIMGENC1_Fxns *)handle->fxns ; imgencStatus.size= sizeof(IIMGENC1_Status); } /** Request input and output buffer characteristics by calling control() function * with command XDM_GETBUFINFO */ // Call control function to setup dynamic params if (baseParamsOnly==0) { retVal=iimgEncfxns->control((IIMGENC1_Handle)handle,/*IJPEGENC_SETDEFAULT*/XDM_SETPARAMS, (IIMGENC1_DynamicParams *)&extn_dynamicParams, (IIMGENC1_Status *)&status); if (retVal== XDM_EFAIL) { printf("\n Error control SetParams command1\n"); exit(0); } retVal= iimgEncfxns->control((IIMGENC1_Handle)handle, XDM_GETBUFINFO, (IIMGENC1_DynamicParams *) &extn_dynamicParams, (IIMGENC1_Status *)&status); if (retVal== XDM_EFAIL) { printf("\n Error control Getbuffinfo command1\n"); exit(0); } inputBufDesc.numBufs = status.imgencStatus.bufInfo.minNumInBufs; Offset = 0; for (i=0;i<inputBufDesc.numBufs;i++) { inputBufDesc.descs[i].buf = (XDAS_Int8 *) ( (unsigned int)inputData + Offset); Offset += status.imgencStatus.bufInfo.minInBufSize[i]; inputBufDesc.descs[i].bufSize = status.imgencStatus.bufInfo.minInBufSize[i]; } outputBufDesc.numBufs = status.imgencStatus.bufInfo.minNumOutBufs; Offset = 0; for (i=0;i<outputBufDesc.numBufs;i++) { outputBufDesc.descs[i].buf = (XDAS_Int8 *) ( (unsigned int)outputData + Offset); Offset += status.imgencStatus.bufInfo.minOutBufSize[i]; outputBufDesc.descs[i].bufSize = status.imgencStatus.bufInfo.minOutBufSize[i]; } if (retVal== XDM_EFAIL) { printf("\n Error control GetInfo command\n"); exit(0); } } else { retVal=iimgEncfxns->control((IIMGENC1_Handle)handle, XDM_SETPARAMS, (IIMGENC1_DynamicParams *)&dynamicParams, (IIMGENC1_Status *)&imgencStatus); if (retVal== XDM_EFAIL) { printf("\n Error control SetParams command1\n"); exit(0); } retVal= iimgEncfxns->control((IIMGENC1_Handle)handle, XDM_GETBUFINFO, (IIMGENC1_DynamicParams *)&dynamicParams, (IIMGENC1_Status *)&imgencStatus); if (retVal== XDM_EFAIL) { printf("\n Error control GetBuffInfo command1\n"); exit(0); } inputBufDesc.numBufs = imgencStatus.bufInfo.minNumInBufs; Offset = 0; for (i=0;i<inputBufDesc.numBufs;i++) { inputBufDesc.descs[i].buf = (XDAS_Int8 *) ( (unsigned int)inputData + Offset); Offset += imgencStatus.bufInfo.minInBufSize[i]; inputBufDesc.descs[i].bufSize = imgencStatus.bufInfo.minInBufSize[i]; } outputBufDesc.numBufs = imgencStatus.bufInfo.minNumOutBufs; Offset = 0; for (i=0;i<outputBufDesc.numBufs;i++) { outputBufDesc.descs[i].buf = (XDAS_Int8 *) ( (unsigned int)outputData + Offset); Offset += imgencStatus.bufInfo.minOutBufSize[i]; outputBufDesc.descs[i].bufSize = imgencStatus.bufInfo.minOutBufSize[i]; } if (retVal== XDM_EFAIL) { printf("\n Error control GetInfo command\n"); exit(0); } } if (baseParamsOnly==0) { /** Read input file. */ printf("Number of Input bufs =%d\n",status.imgencStatus.bufInfo.minNumInBufs ); if (status.imgencStatus.bufInfo.minNumInBufs == 3) { memset(OrgPictureY,0,(status.imgencStatus.bufInfo.minInBufSize[0])); memset(OrgPictureCb,0,(status.imgencStatus.bufInfo.minInBufSize[1])); memset(OrgPictureCr,0,(status.imgencStatus.bufInfo.minInBufSize[2])); printf("Input file read starts\n" ); lTemp = fread(OrgPictureY,1,(status.imgencStatus.bufInfo.minInBufSize[0]),fp_in); if (dynamicParams.inputWidth < dynamicParams.captureWidth) { fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)),SEEK_CUR); } printf("number of bytes read from input file = %d \n",lTemp); lTemp = fread(OrgPictureCb,1,((status.imgencStatus.bufInfo.minInBufSize[1])),fp_in); if (dynamicParams.inputWidth < dynamicParams.captureWidth) { fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)/4),SEEK_CUR); } printf("number of bytes read from input file = %d \n",lTemp); lTemp = fread(OrgPictureCr,1,((status.imgencStatus.bufInfo.minInBufSize[2])),fp_in); printf("number of bytes read from input file = %d \n",lTemp); } else if (status.imgencStatus.bufInfo.minNumInBufs == 1) { printf("status.imgencStatus.bufInfo.minInBufSize[0]=%d\n",status.imgencStatus.bufInfo.minInBufSize[0]); memset(OrgPictureY,0,(status.imgencStatus.bufInfo.minInBufSize[0])); lTemp = fread(OrgPictureY,1,(status.imgencStatus.bufInfo.minInBufSize[0]),fp_in); printf("number of bytes read from input file = %d \n",lTemp); } else if (status.imgencStatus.bufInfo.minNumInBufs == 2) /* 420 semi planar*/ { printf("status.imgencStatus.bufInfo.minInBufSize[0]=%d\n",status.imgencStatus.bufInfo.minInBufSize[0]); memset(OrgPictureY,0,(status.imgencStatus.bufInfo.minInBufSize[0])); printf("status.imgencStatus.bufInfo.minInBufSize[1]=%d\n",status.imgencStatus.bufInfo.minInBufSize[1]); memset(OrgPictureCb,'-',(status.imgencStatus.bufInfo.minInBufSize[1])); memset(OrgPictureCr,'-',(status.imgencStatus.bufInfo.minInBufSize[1])); lTemp = fread(OrgPictureY,1,(status.imgencStatus.bufInfo.minInBufSize[0]),fp_in); if (dynamicParams.inputWidth < dynamicParams.captureWidth) { fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)),SEEK_CUR); } printf("number of bytes read from input file = %d \n",lTemp); if (dynamicParams.inputWidth < dynamicParams.captureWidth) { lTemp = fread(OrgPictureCr,1,(status.imgencStatus.bufInfo.minInBufSize[1])/2,fp_in); fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)/4),SEEK_CUR); lTemp += fread((OrgPictureCr+(status.imgencStatus.bufInfo.minInBufSize[1])/2),1,(status.imgencStatus.bufInfo.minInBufSize[1])/2,fp_in); } else { lTemp = fread(OrgPictureCr,1,(status.imgencStatus.bufInfo.minInBufSize[1]),fp_in); } printf("number of bytes read from input file = %d \n",lTemp); /* The input file is 420 planar, the following function converts the 420P to 420 semi planar i.e CbCr will be interleaved. planar chrmoa data is read into OrgPictureCr buffer and converted to interleaved. output is stored in OrgPictureCb buffer*/ /*convert the 420 planar to 420 semi planar*/ lTemp = Convert420Pto420Semi(OrgPictureCr,OrgPictureCb,status.imgencStatus.bufInfo.minInBufSize[1]); } else { printf("Unsupported number of input buffers \n"); } fclose(fp_in); } else { /** Read input file. */ printf("Number of Input bufs =%d\n",imgencStatus.bufInfo.minNumInBufs ); if (imgencStatus.bufInfo.minNumInBufs == 3) { memset(OrgPictureY,0,(imgencStatus.bufInfo.minInBufSize[0])); memset(OrgPictureCb,0,(imgencStatus.bufInfo.minInBufSize[1])); memset(OrgPictureCr,0,(imgencStatus.bufInfo.minInBufSize[2])); printf("Input file read starts\n" ); lTemp = fread(OrgPictureY,1,(imgencStatus.bufInfo.minInBufSize[0]),fp_in); if (dynamicParams.inputWidth < dynamicParams.captureWidth) { fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)),SEEK_CUR); } printf("number of bytes read from input file = %d \n",lTemp); lTemp = fread(OrgPictureCb,1,((imgencStatus.bufInfo.minInBufSize[1])),fp_in); if (dynamicParams.inputWidth < dynamicParams.captureWidth) { fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)/4),SEEK_CUR); } printf("number of bytes read from input file = %d \n",lTemp); lTemp = fread(OrgPictureCr,1,((imgencStatus.bufInfo.minInBufSize[2])),fp_in); printf("number of bytes read from input file = %d \n",lTemp); } else if (imgencStatus.bufInfo.minNumInBufs == 1) { printf("imgencStatus.bufInfo.minInBufSize[0]=%d\n",imgencStatus.bufInfo.minInBufSize[0]); memset(OrgPictureY,0,(imgencStatus.bufInfo.minInBufSize[0])); lTemp = fread(OrgPictureY,1,(imgencStatus.bufInfo.minInBufSize[0]),fp_in); printf("number of bytes read from input file = %d \n",lTemp); } else if (imgencStatus.bufInfo.minNumInBufs == 2) /* 420 semi planar*/ { printf("imgencStatus.bufInfo.minInBufSize[0]=%d\n",imgencStatus.bufInfo.minInBufSize[0]); memset(OrgPictureY,0,(imgencStatus.bufInfo.minInBufSize[0])); printf("imgencStatus.bufInfo.minInBufSize[1]=%d\n",imgencStatus.bufInfo.minInBufSize[1]); memset(OrgPictureCb,'-',(imgencStatus.bufInfo.minInBufSize[1])); memset(OrgPictureCr,'-',(imgencStatus.bufInfo.minInBufSize[1])); lTemp = fread(OrgPictureY,1,(imgencStatus.bufInfo.minInBufSize[0]),fp_in); if (dynamicParams.inputWidth < dynamicParams.captureWidth) { fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)),SEEK_CUR); } printf("number of bytes read from input file = %d \n",lTemp); if (dynamicParams.inputWidth < dynamicParams.captureWidth) { lTemp = fread(OrgPictureCr,1,(imgencStatus.bufInfo.minInBufSize[1])/2,fp_in); fseek(fp_in,(dynamicParams.captureWidth*(params.maxHeight-dynamicParams.inputHeight)/4),SEEK_CUR); lTemp += fread((OrgPictureCr+(imgencStatus.bufInfo.minInBufSize[1])/2),1,(imgencStatus.bufInfo.minInBufSize[1])/2,fp_in); } else { lTemp = fread(OrgPictureCr,1,(imgencStatus.bufInfo.minInBufSize[1]),fp_in); } printf("number of bytes read from input file = %d \n",lTemp); /* The input file is 420 planar, the following function converts the 420P to 420 semi planar i.e CbCr will be interleaved. planar chrmoa data is read into OrgPictureCr buffer and converted to interleaved. output is stored in OrgPictureCb buffer*/ /*convert the 420 planar to 420 semi planar*/ lTemp = Convert420Pto420Semi(OrgPictureCr,OrgPictureCb,imgencStatus.bufInfo.minInBufSize[1]); // printf("OrgPictureCb=%x\n",OrgPictureCb); } else { printf("Unsupported number of input buffers \n"); } fclose(fp_in); } /*Fill up the buffers as required by algorithm */ if (baseParamsOnly==0) { inputBufDesc.numBufs = status.imgencStatus.bufInfo.minNumInBufs ; } else { inputBufDesc.numBufs = imgencStatus.bufInfo.minNumInBufs ; } inputBufDesc.descs[0].buf= (XDAS_Int8 *)OrgPictureY; if (dynamicParams.inputChromaFormat== IJPEGENC_YUV_420LINE) { inputBufDesc.descs[1].buf= (XDAS_Int8 *)OrgPictureY + dynamicParams.inputWidth; inputBufDesc.descs[2].buf= inputBufDesc.descs[1].buf + dynamicParams.inputWidth*3/2; } else if (dynamicParams.inputChromaFormat!= XDM_YUV_422ILE) { if (dynamicParams.inputChromaFormat== XDM_YUV_420SP) { inputBufDesc.descs[1].buf= (XDAS_Int8 *)OrgPictureCb; } else { inputBufDesc.descs[1].buf= (XDAS_Int8 *)OrgPictureCb; inputBufDesc.descs[2].buf= (XDAS_Int8 *)OrgPictureCr; } } if (baseParamsOnly==0) { inputBufDesc.descs[0].bufSize = status.imgencStatus.bufInfo.minInBufSize[0]; // actually ignored by codec outputBufDesc.numBufs = status.imgencStatus.bufInfo.minNumOutBufs ; } else { inputBufDesc.descs[0].bufSize = imgencStatus.bufInfo.minInBufSize[0]; // actually ignored by codec outputBufDesc.numBufs = imgencStatus.bufInfo.minNumOutBufs ; } if (baseParamsOnly==0) { #ifdef ENABLE_RING_BUF_USAGE outputBufDesc.descs[0].buf = (XDAS_Int8 *)ringbuf; outputBufDesc.descs[0].bufSize = RINGBUFSIZE; // actually ignored by codec ring2media.mediaPtr= media; ring2media.ringCurPtr= ringbuf; ring2media.ringStartPtr=ringbuf; ring2media.ringEndPtr= (Uint8*)((Uint32)ringbuf +RINGBUFSIZE) ; inArgs.ringBufStart= (XDAS_UInt8*)ringbuf; inArgs.ringBufSize= RINGBUFSIZE; printf("RINGBUFSIZE %x\n", RINGBUFSIZE); #else outputBufDesc.descs[0].buf = (XDAS_Int8 *)media; outputBufDesc.descs[0].bufSize = ENCODED_DATA_BUFFER_SIZE; // actually ignored by codec ring2media.mediaPtr= media; ring2media.ringCurPtr= media; ring2media.ringStartPtr=media; ring2media.ringEndPtr= (Uint8*)((Uint32)media +ENCODED_DATA_BUFFER_SIZE) ; inArgs.ringBufStart= (XDAS_UInt8*)media; inArgs.ringBufSize= ENCODED_DATA_BUFFER_SIZE; #endif inArgs.imgencInArgs.size = sizeof(IJPEGENC_InArgs); outArgs.imgencOutArgs.size= sizeof(IJPEGENC_OutArgs); } else { outputBufDesc.descs[0].buf = (XDAS_Int8 *)media; outputBufDesc.descs[0].bufSize = ENCODED_DATA_BUFFER_SIZE; // actually ignored by codec imgencInArgs.size = sizeof(IIMGENC1_InArgs); imgencOutArgs.size= sizeof(IIMGENC1_OutArgs); } #ifdef LINUX algActStart.tv_sec = 0; algActStart.tv_usec = 0; gettimeofday(&algActStart, 0); #endif handle->fxns->algActivate(handle); #ifdef LINUX processStart.tv_sec = 0; processStart.tv_usec = 0; gettimeofday(&processStart, 0); #endif if (baseParamsOnly==0) { inArgs.insertCommentMarker = 0; inArgs.appDataType =0; inArgs.commentSegLen = 0; retVal = iimgEncfxns->process((IIMGENC1_Handle)handle, (XDM1_BufDesc *)&inputBufDesc, (XDM1_BufDesc *)&outputBufDesc, (IIMGENC1_InArgs *)&inArgs, (IIMGENC1_OutArgs *)&outArgs); bytesGenerated= outArgs.imgencOutArgs.bytesGenerated; } else { retVal = iimgEncfxns->process((IIMGENC1_Handle)handle, (XDM1_BufDesc *)&inputBufDesc, (XDM1_BufDesc *)&outputBufDesc, (IIMGENC1_InArgs *)&imgencInArgs, (IIMGENC1_OutArgs *)&imgencOutArgs); bytesGenerated= imgencOutArgs.bytesGenerated; } #ifdef SLICE_MODE_TEST /* SLICE_MODE_TEST*/ // Call get status to get number of total AU if (baseParamsOnly==0) { retVal=iimgEncfxns->control((IIMGENC1_Handle)handle, IJPEGENC_GETSTATUS, (IIMGENC1_DynamicParams *)&extn_dynamicParams, (IIMGENC1_Status *)&status); if (retVal== XDM_EFAIL) { printf("\n Error control in slice mode get status command\n"); exit(0); } totalAU= status.imgencStatus.totalAU; printf("totalAU = %d\n",totalAU); extn_dynamicParams.imgencDynamicParams.numAU= 50/*totalAU/5*/; // Call control function to setup dynamic params retVal=iimgEncfxns->control((IIMGENC1_Handle)handle, XDM_SETPARAMS, (IIMGENC1_DynamicParams *)&extn_dynamicParams, (IIMGENC1_Status *)&status); numAU = status.numAU; printf("numAU = %d\n",numAU); if (retVal== XDM_EFAIL) { printf("\n Error control in slice mode SetParams command\n"); exit(0); } // Get real numAU computed by codec // In case of 270 rotation, must point to right most slice of the image if (extn_dynamicParams.rotation== 90) { if (dynamicParams.inputChromaFormat==XDM_YUV_420SP) { Uint16 sliceWidth= (numAU*16/dynamicParams.inputHeight)*(8<<(params.forceChromaFormat==XDM_YUV_420P)); inputBufDesc.descs[0].buf+= (dynamicParams.inputWidth - sliceWidth); inputBufDesc.descs[1].buf+= (dynamicParams.inputWidth - sliceWidth); // inputBufDesc.descs[2].buf+= (dynamicParams.inputWidth - sliceWidth);//dynamicParams.inputWidth/2 - sliceWidth/2; } else { Uint16 sliceWidth= (numAU*16/dynamicParams.inputHeight)*(8<<(params.forceChromaFormat==XDM_YUV_420P)); inputBufDesc.descs[0].buf+= (dynamicParams.inputChromaFormat== XDM_YUV_422ILE ? 2 : 1)*(dynamicParams.inputWidth - sliceWidth); inputBufDesc.descs[1].buf+= dynamicParams.inputWidth/2 - sliceWidth/2; inputBufDesc.descs[2].buf+= dynamicParams.inputWidth/2 - sliceWidth/2; } } else if (extn_dynamicParams.rotation== 180) { Uint16 sliceHeight = (numAU*16/dynamicParams.inputWidth)*(8<<(params.forceChromaFormat==XDM_YUV_420P)); if (dynamicParams.inputChromaFormat != XDM_YUV_420SP) { inputBufDesc.descs[0].buf+= dynamicParams.captureWidth*(dynamicParams.inputChromaFormat== XDM_YUV_422ILE ? 2 : 1)*(dynamicParams.inputHeight - sliceHeight); inputBufDesc.descs[1].buf+= dynamicParams.captureWidth*(dynamicParams.inputHeight - sliceHeight)>>(1 + (dynamicParams.inputChromaFormat== XDM_YUV_420P)); inputBufDesc.descs[2].buf+= dynamicParams.captureWidth*(dynamicParams.inputHeight - sliceHeight)>>(1 + (dynamicParams.inputChromaFormat== XDM_YUV_420P)); } else {
cibar_t *cibar_open(FILE *f) { cibar_internal_file_entry_t *entries; char *strings; uint8_t *data; cibar_internal_t cb; cibar_t *out; int i; if (!f) return NULL; /* Read the header */ fread(&cb, sizeof(cibar_internal_t), 1, f); if (cb.magic != 0x12344321) { printf("cibar: Wrong magic: 0x%08x\n", cb.magic); goto error_1; } /* Allocate structures */ if ( !(entries = (cibar_internal_file_entry_t*)malloc(sizeof(cibar_internal_file_entry_t) * cb.n_file_entries)) ) goto error_1; if ( !(strings = (char*)malloc( cb.strtab_length )) ) goto error_2; if ( !(data = (uint8_t*)malloc( cb.data_length )) ) goto error_3; if ( !(out = (cibar_t*)malloc( sizeof(cibar_t) + sizeof(cibar_file_entry_t) * cb.n_file_entries)) ) goto error_4; /* Read the rest of the file */ if (fread(entries, 1, sizeof(cibar_internal_file_entry_t) * cb.n_file_entries, f) != sizeof(cibar_internal_file_entry_t) * cb.n_file_entries) goto error_4; if (fread(strings, 1, cb.strtab_length, f) != cb.strtab_length) goto error_4; if (fread(data, 1, cb.data_length, f) != cb.data_length) goto error_4; /* Fill in the out stucture */ out->n_files = cb.n_file_entries; out->strings = strings; out->data = data; for (i = 0; i < cb.n_file_entries; i++) { cibar_file_entry_t *p = &out->files[i]; p->cibar = out; p->data = data + entries[i].data_offset; p->data_size = entries[i].data_size; p->name = strings + entries[i].strtab_offset; } free(entries); return out; error_4: free(data); error_3: free(strings); error_2: free(entries); error_1: return NULL; }
int main(int argc, char *argv[]){ char DFin_location[256]; DFin_location = argv[1] ; char DFout_location[256] argv[2]; char AnaFile[256] = argv[3] ; char SimFile[256] = argv[4] ; int TriggerBucket = atoi(argv[5]); int RUN = atoi(argv[5]); std::cout << argv[1] << std::endl; std::cout << DFin_location << std::endl; return; //here goes the first file TChain * DFinput = new TChain("Telescope"); DFinput->Add(DFin_location); unsigned int Event_in; int roc_in; int col_in,row_in,vcal_in; float flux_in; double pulseHeight_in; std::cout << roc_in << std::endl; DFinput->SetBranchStatus("*",false); DFinput->SetBranchStatus("Event",true); DFinput->SetBranchStatus("roc",true); DFinput->SetBranchStatus("pulseHeight",true); DFinput->SetBranchStatus("vcal",true); DFinput->SetBranchStatus("col",true); DFinput->SetBranchStatus("row",true); DFinput->SetBranchStatus("flux",true); DFinput->SetBranchAddress("Event",&Event_in); DFinput->SetBranchAddress("roc",&roc_in); DFinput->SetBranchAddress("row",&row_in); DFinput->SetBranchAddress("col",&col_in); DFinput->SetBranchAddress("vcal",&vcal_in); DFinput->SetBranchAddress("flux",&flux_in); DFinput->SetBranchAddress("pulseHeight",&pulseHeight_in); std::cout << "Loaded DF input file from: " << DFin_location << std::endl; //here goes the second file TChain * DFoutput = new TChain("hitTree"); DFoutput->Add(DFout_location); unsigned int event_number; int roc_out,col_out,row_out,vcal_out; double pulseHeight_out; long TS_out; DFoutput->SetBranchStatus("*",false); DFoutput->SetBranchStatus("event_number",true); DFoutput->SetBranchStatus("TS",true); DFoutput->SetBranchStatus("roc",true); DFoutput->SetBranchStatus("col",true); DFoutput->SetBranchStatus("row",true); DFoutput->SetBranchStatus("vcal",true); DFoutput->SetBranchStatus("pulseHeight",true); DFoutput->SetBranchAddress("event_number",&event_number); DFoutput->SetBranchAddress("TS",&TS_out); DFoutput->SetBranchAddress("roc",&roc_out); DFoutput->SetBranchAddress("col",&col_out); DFoutput->SetBranchAddress("row",&row_out); DFoutput->SetBranchAddress("vcal",&vcal_out); DFoutput->SetBranchAddress("pulseHeight",&pulseHeight_out); std::cout << "Loaded DF output file from: " << DFout_location << std::endl; //here come the analysis files //comes later //here come the original run data files //Now we make some histograms we want to compare TCanvas * c1 = new TCanvas("Comparison","Comparison",1200,1200); // gStyle->SetOptStat(0); c1->Divide(2,2); c1->cd(1); TH1I * Pixels_per_Event_in = new TH1I("Pixels per Event", "DataFlow input",20,0,20); unsigned int temp_evtn=-1; int ROC_DUT = 3; int nhits = 0; std::cout << "Total Entries input : " << DFinput->GetEntries() << std::endl; std::cout << "Total Entries output: " << DFoutput->GetEntries() << std::endl; long int maxEntries = DFinput->GetEntries(); for(int i = 0; i < maxEntries; ++i) //for(int i = 0; i < 5000000; ++i) { DFinput->GetEntry(i); if(i%100000 == 0) std::cout << setprecision(2) << "Entry: " << i << " " << (double)(i*100)/maxEntries << "%" << std::endl; //std::cout << "Entry: " << i << "Event " << Event_in << "ROC " << roc_in << " " << row_in << "|" << col_in << std::endl; temp_evtn = Event_in; if(Event_in%588 == TriggerBucket) { if(roc_in == -1) { Pixels_per_Event_in->Fill(0); continue; } else { while(Event_in == temp_evtn) { // std::cout << "I'm in the loop. ROC " << roc_in << std::endl; if(roc_in == ROC_DUT) { ++nhits; } ++i; if(i == maxEntries) break; DFinput->GetEntry(i); // std::cout << "Entry: " << i << "Event " << Event_in << "ROC " << roc_in << std::endl; } } --i; Pixels_per_Event_in->Fill(nhits); // std::cout << "Found event with " << nhits << "Hits on ROC " << ROC_DUT << std::endl; nhits = 0; } } Pixels_per_Event_in->Draw(); c1->Update(); //second histogram std::cout << "Second histogramm" << std::endl; TH1I * Pixels_per_Event_out = new TH1I("Pixels per Event","DataFlow output",20,0,20); for(int i = 0; i < DFoutput->GetEntries();++i) { DFoutput->GetEntry(i); //if(i%100 == 0) std::cout << "Entry: " << i << "Event " << event_number << "ROC " << roc_out << std::endl; // std::cout << "Entry: " << i << "Event " << event_number << "ROC " << roc_out << std::endl; temp_evtn = event_number; if(roc_out == -1) { nhits = 0; Pixels_per_Event_out->Fill(nhits); continue; } else { while(event_number == temp_evtn) { // std::cout << "I'm in the loop. ROC " << roc_in << std::endl; if(roc_out == ROC_DUT) { ++nhits; } ++i; if(i == DFoutput->GetEntries()) break; DFoutput->GetEntry(i); // std::cout << "Entry: " << i << "Event " << event_number << "ROC " << roc_out << std::endl; } --i; Pixels_per_Event_out->Fill(nhits); // std::cout << "Found event with " << nhits << "Hits on ROC " << ROC_DUT << std::endl; nhits = 0; } } c1->cd(2); Pixels_per_Event_out->Draw(); c1->Update(); //picking up the 3rd histogram TFile * simAnaFile = new TFile(SimFile,"READ"); if ( simAnaFile->IsOpen()) printf("File opened successfully\n"); char histname[256]; sprintf(histname,"MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d%i",ROC_DUT); std::cout << histname << std::endl; TH1I * Hits_per_Event_sim; Hits_per_Event_sim=(TH1I*)simAnaFile->Get("MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d3"); c1->cd(3); Hits_per_Event_sim->GetXaxis()->SetRangeUser(0,20); Hits_per_Event_sim->SetTitle("Analysis of simulated data"); Hits_per_Event_sim->Draw(); c1->Update(); //pick up the last "original" histogram TFile * realAnaFile = new TFile(AnaFile,"READ"); if ( realAnaFile->IsOpen()) printf("File opened successfully\n"); sprintf(histname,"MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d%i",ROC_DUT); TH1I * Hits_per_Event_ana; Hits_per_Event_ana=(TH1I*)realAnaFile->Get("MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d3"); c1->cd(4); Hits_per_Event_ana->GetXaxis()->SetRangeUser(0,20); Hits_per_Event_ana->SetTitle("Analysis of measured data"); Hits_per_Event_ana->Draw(); c1->Update(); char txt[256]; sprintf(txt,"RUN%i_PixelsPerEvent.pdf",RUN); c1->SaveAs(txt); ///now for future references I'll try everything in one plot TCanvas * c2 = new TCanvas("c2","c2",600,600); c2->cd(); // gStyle->SetOptStat(0); double norm = 100.; std::cout << Pixels_per_Event_in->Integral() << std::endl; //Pixels_per_Event_out->GetXaxis()->SetLimits(0, norm); Pixels_per_Event_out->Scale(norm/Pixels_per_Event_out->Integral()); Pixels_per_Event_out->SetMaximum(100); Pixels_per_Event_out->SetLineColor(2); Pixels_per_Event_out->SetLineWidth(3); Pixels_per_Event_out->Draw("SAME"); Hits_per_Event_sim->Scale(norm/Hits_per_Event_sim->Integral()); Hits_per_Event_sim->SetMaximum(100); Hits_per_Event_sim->SetLineColor(3); Hits_per_Event_sim->SetLineWidth(3); Hits_per_Event_sim->Draw("SAME"); Hits_per_Event_ana->Scale(norm/Hits_per_Event_ana->Integral()); Hits_per_Event_ana->SetMaximum(100); Hits_per_Event_ana->SetLineColor(4); Hits_per_Event_ana->SetLineWidth(3); Hits_per_Event_ana->Draw("SAME"); Pixels_per_Event_in->Scale(norm/Pixels_per_Event_in->Integral()); Pixels_per_Event_in->SetMaximum(100); Pixels_per_Event_in->SetLineColor(1); Pixels_per_Event_in->SetLineWidth(3); Pixels_per_Event_in->Draw("SAME"); TLegend * leg1 = new TLegend(0.75,0.9,0.35,0.75); leg1->AddEntry(Pixels_per_Event_in,"DataFlow input","L"); leg1->AddEntry(Pixels_per_Event_out,"DataFlow output","L"); leg1->AddEntry(Hits_per_Event_sim,"Analysis of simulated data","L"); leg1->AddEntry(Hits_per_Event_ana,"Analysis of measured data","L"); leg1->Draw(); c2->Update(); sprintf(txt,"RUN%i_PixelsPerEventNorm.pdf",RUN); c2->SaveAs(txt); /* * Now some more plots */ //hit map //simulated data TCanvas * c3 = new TCanvas("c3","c3",1200,600); c3->Divide(2,1); c3->cd(1); sprintf(histname,"MyCMSPixelClusteringProcessor/detector_3/pixelPerEvent_d%i",ROC_DUT); std::cout << histname << std::endl; TH2D * Hit_Map_sim; Hit_Map_sim=(TH2D*)simAnaFile->Get("MyCMSPixelClusteringProcessor/detector_3/hitMap_d3"); Hit_Map_sim->SetTitle("Analysis of simulated data"); Hit_Map_sim->Draw("COLZ"); Hit_Map_sim->SetStats(0); c3->Update(); //measured data c3->cd(2); TH2D * Hit_Map_ana; Hit_Map_ana=(TH2D*)realAnaFile->Get("MyCMSPixelClusteringProcessor/detector_3/hitMap_d3"); Hit_Map_ana->GetXaxis()->SetRangeUser(1,50); Hit_Map_ana->GetYaxis()->SetRangeUser(1,78); Hit_Map_ana->SetTitle("Analysis of measured data"); Hit_Map_ana->Draw("COLZ"); Hit_Map_ana->SetStats(0); char txt[256]; sprintf(txt,"RUN%i_HitMap.pdf",RUN); c3->SaveAs(txt); /* *cluster size */ //simulated data TCanvas * c4 = new TCanvas("c4","c4",1200,600); c4->Divide(2,1); c4->cd(1); c4->SetLogy(1); sprintf(histname,"MyCMSPixelClusteringProcessor/detector_%i/clustersize_d%i",ROC_DUT,ROC_DUT); std::cout << histname << std::endl; TH1I * Clustersize_sim; Clustersize_sim=(TH1I*)simAnaFile->Get(histname); Clustersize_sim->GetXaxis()->SetRangeUser(0,20); Clustersize_sim->SetTitle("Analysis of simulated data"); Clustersize_sim->Draw(); c4->Update(); //measured data c4->cd(2); c4->SetLogy(1); TH1I * Clustersize_ana; Clustersize_ana=(TH1I*)realAnaFile->Get(histname); Clustersize_ana->GetXaxis()->SetRangeUser(0,20); Clustersize_ana->SetTitle("Analysis of measured data"); Clustersize_ana->Draw(); c4->Update(); sprintf(txt,"RUN%i_ClusterSize.pdf",RUN); c4->SaveAs(txt); /* *number of tracks */ string simTrackFileName(SimFile); simTrackFileName = simTrackFileName.replace(simTrackFileName.find("clustering"), sizeof("clustering")-1,"tracks"); char * filename = simTrackFileName.c_str(); std::cout << filename << std::endl; TFile * simTrackFile = new TFile(filename,"READ"); if ( simTrackFile->IsOpen()) printf("Track file opened successfully\n"); TCanvas * c5 = new TCanvas("c5","c5",1200,600); c5->Divide(2,1); c5->SetLogy(1); c5->cd(1); sprintf(histname,"MyEUTelTestFitter/nTrack"); std::cout << histname << std::endl; TH1D * NTracks_sim; NTracks_sim=(TH1D*)simTrackFile->Get(histname); NTracks_sim->SetTitle("Analysis of simulated data"); NTracks_sim->Draw(); c5->Update(); string anaTrackFileName(AnaFile); anaTrackFileName = anaTrackFileName.replace(anaTrackFileName.find("clustering"), sizeof("clustering")-1,"tracks"); char * filename2 = anaTrackFileName.c_str(); TFile * anaTrackFile = new TFile(filename2,"READ"); if ( anaTrackFile->IsOpen()) printf("Analysis track file opened successfully\n"); c5->cd(2); c5->SetLogy(1); TH1D * NTracks_ana; NTracks_ana=(TH1D*)anaTrackFile->Get(histname); NTracks_ana->SetTitle("Analysis of measured data"); NTracks_ana->Draw(); c5->Update(); sprintf(txt,"RUN%i_NumberOfTracks.pdf",RUN); c5->SaveAs(txt); }//comparison()
int main (void) { int year, month, day; double lon, lat; double len, rise, set, cur_time; int rc; char ch; time_t t; struct tm *tm; t = time (NULL); tm = gmtime (&t); lon = 0; sun_rise_set (tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, lon, 0.0, &rise, &set); cur_time = tm->tm_hour + tm->tm_min / 60.0; lon += (rise - cur_time) * 15.0; if (lon > 180.0) lon -= 360.0; if (lon < -180.0) lon += 360.0; printf ("==> Sun is rising at longitude %5.2fE, latitude 0.00N\n", lon); printf ("Longitude (+ is east) and latitude (+ is north), or * for Lugano: "); ch = getchar (); if (ch == '*') lon = 8.0 + 57.0/60.0, lat = 46.0; else { ungetc (ch, stdin); while (scanf ("%lf %lf", &lon, &lat) < 2) ; } tm = localtime (&t); year = tm->tm_year + 1900; month = tm->tm_mon + 1; day = tm->tm_mday; do { len = day_length (year, month, day, lon, lat); printf ("==> Day length: %5.2f hours\n", len); rc = sun_rise_set (year, month, day, lon, lat, &rise, &set); if (rc == 1) printf ("==> Sun never sets!\n"); else if (rc == -1) printf ("==> Sun never rises!\n"); else { printf ("==> Midday: %5.2f GMT\n", (rise + set) / 2); printf ("==> Sunrise: %5.2f, Sunset: %5.2f GMT\n", rise, set); } rc = civil_rise_set (year, month, day, lon, lat, &rise, &set); if (rc == 1) printf ("==> Sun never reaches civil dusk!\n"); else if (rc == -1) printf ("==> Sun never reaches civil dawn!\n"); else printf ("==> Civil sunrise: %5.2f, Sunset: %5.2f GMT\n", rise, set); printf ("Date (yyyy mm dd) (ctrl-C exits): "); while (scanf ("%d %d %d", &year, &month, &day) < 3 && !feof (stdin)) ; } while (!feof (stdin)); return 0; }
int main_line_removal() { PIX* pixs_source = pixRead("dave-start.png"); if (!pixs_source) { printf("Error opening file"); return 1; } double deg2rad = 3.1415926535 / 180.; l_float32 angle, conf, score; PIX *pix1, *pix2, *pix3, *pix4, *pix5, *pix6, *pix7, *pix8, *pix9; pix1 = pixThresholdToBinary(pixs_source, 160); printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-1.tif", pix1, IFF_TIFF_G4); pixFindSkew(pix1, &angle, &conf); pix2 = pixRotateAMGray(pixs_source, deg2rad * angle, 160); printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-2.tif", pix2, IFF_TIFF_G4); l_int32 HORIZ = 1; l_int32 VERT = 3; pix3 = pixCloseGray(pix2, 51, HORIZ); //k?p?c 51? printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-3.tif", pix3, IFF_TIFF_G4); pix4 = pixErodeGray(pix3, 5, VERT); //k?p?c 5? printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-4.tif", pix4, IFF_TIFF_G4); pix5 = pix4; pix5 = pixThresholdToValue(pix5, pix4, 230, 255); printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-5.tif", pix5, IFF_TIFF_G4); pix6 = pix5; pix6 = pixThresholdToValue(pix5, pix5, 210, 0); printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-6.tif", pix6, IFF_TIFF_G4); pix7 = pixThresholdToBinary(pix6, 230); printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-7.tif", pix7, IFF_TIFF_G4); pixInvert(pix6, pix6); pix8 = pixAddGray(NULL, pix2, pix6); printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-8.tif", pix8, IFF_TIFF_G4); VERT = 7; pix9 = pixOpenGray(pix8, 3, VERT); printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-9.tif", pix9, IFF_TIFF_G4); if (pixCombineMasked(pix8, pix9, pix7)) { printf("!!!Error while combining pixs!!!\n"); } printf("Create line removal image\n"); pixWrite("line-removal/result.line-removal-final.tif", pix8, IFF_TIFF_G4); printf("\n---\nEnd\n"); getchar(); return 0; }
void test_sort_unique_find_search(void) { uint random_size; random_size = rand() % MAX_LIST_SIZE; List zeros = list_create(random_size); printf("Zero List ::: "); list_print(&zeros); List list = list_random(MAX_LIST_SIZE, ELEMENT_MAX_VALUE); printf("%sRandom List ::: ", cyan); list_print(&list); list_sort_by_item(&list); printf("%sList Resorted By Item ::: ", red); list_print(&list); printf("%sUnique List ::: ", magenta); list_unique(&list); list_print(&list); list_sort_by_frequency_back(&list); printf("%sList Sorted Backward By Frequency ::: ",green); list_print(&list); list_sort_by_frequency(&list); printf("%sList Resorted By Frequency ::: ", blue); list_print(&list); Item query = list.data[rand() % list.size]; Item *found = list_find(&list, query); if (found != NULL) printf("%sFind function: %d found in position %d\n", brown, query.item, (int)(found - list.data)); else printf("%sFind function: %d not found", brown, query.item); list_sort_by_item_back(&list); printf("%sList Sorted Backwards By Item ::: ", black); list_print(&list); list_sort_by_item(&list); printf("%sList Resorted By Item ::: ", cyan); list_print(&list); query = list.data[rand() % list.size]; found = list_binary_search(&list, query); printf("%sBinary search: %d found in position %d\n", none, query.item, (int)(found - list.data)); }
void test_concat_append_add_union_intersection_difference(void) { List list1 = list_random(MAX_LIST_SIZE, ELEMENT_MAX_VALUE); list_sort_by_item(&list1); list_unique(&list1); printf("Original List 1 ::: "); list_print(&list1); List list2 = list_random(MAX_LIST_SIZE, ELEMENT_MAX_VALUE); list_sort_by_item(&list2); list_unique(&list2); printf("%sOriginal List 2 ::: ", brown); list_print(&list2); List concat = list_concat(&list1, &list2); printf("%sConcatenation List ::: ", cyan); list_print(&concat); List append = list_duplicate(&list1); list_append(&append, &list2); printf("%sList 1 appended to list 2 ::: ", magenta); list_print(&append); List add = list_duplicate(&list1); list_add(&add, &list2); printf("%sList 1 added to list 2 ::: ", green); list_print(&add); List union_list = list_union(&list1, &list2); printf("%sList Union ::: ", blue); list_print(&union_list); List intersection_list = list_intersection(&list1, &list2); printf("%sList Intersection ::: ", red); list_print(&intersection_list); List difference_list = list_difference(&list1, &list2); printf("%sDifference List ::: ", cyan); list_print(&difference_list); uint union_size = list_union_size(&list1, &list2); printf("%sList Union Size = %d\n", brown, union_size); uint intersection_size = list_intersection_size(&list1, &list2); printf("%sList Intersection Size = %d\n", black, intersection_size); uint difference_size = list_difference_size(&list1, &list2); printf("%sList Difference Size = %d\n", black, difference_size); printf("%s",none); }
int kernel_main() { init_gdt(); init_idt(); init_video(); setcolor(make_color(COLOR_GREEN, COLOR_BLACK)); printf("Hello, World!"); newline(5); setcolor(make_color(COLOR_ORANGE, COLOR_BLACK)); printf(" ,--.\n"); printf(" _/ <`-'\n"); printf(" ,-.' \\--\\_\n"); printf(" ((`-.__\\ )\n"); printf(" \\`' @ (_\n"); printf(" ( (_)\n"); printf(" ,'`-._(`-._/\n"); printf(" ,-' )&&) ))\n"); printf(" ,-' /&&&%-'\n"); printf(" ,' __ ,- {&&&&/\n"); printf(" / ,' \\| |\\&&'\\\n"); printf(" ( | |' \\ `--.\n"); printf("(%--'\\ ,--.\\ `-.`-._)))\n"); printf(" `---'`-/__)))`-._)))\n\n"); int count = 0; //Some delay before bouncing while (count < 10) { sleep(100000000); count++; } count = 0; while (true) { while (count < 5) { sleep(100000000); scrolldown(); count++; } while (count < 10) { sleep(100000000); scrollup(); count++; } if (count % 10 == 0) { count = 0; } } printf("Exiting..."); return 0; }
static void MergeStatusCodes(CFTypeRef key, CFTypeRef value, void* context) { // Windows (and therefore .NET) certificate status codes are defined on an int32_t. // The top 32 bits will be used to convey error information, the bottom 32 bits // as a data aggregator for the status codes. uint64_t* pStatus = (uint64_t*)context; if (key == NULL) { return; } // If any error code was already set. if (*pStatus > INT_MAX) { return; } if (CFGetTypeID(key) != CFStringGetTypeID()) { *pStatus |= PAL_X509ChainErrorUnknownValueType; return; } (void)value; CFStringRef keyString = (CFStringRef)key; if (CFEqual(keyString, CFSTR("NotValidBefore")) || CFEqual(keyString, CFSTR("ValidLeaf")) || CFEqual(keyString, CFSTR("ValidIntermediates")) || CFEqual(keyString, CFSTR("ValidRoot")) || CFEqual(keyString, CFSTR("TemporalValidity"))) *pStatus |= PAL_X509ChainNotTimeValid; else if (CFEqual(keyString, CFSTR("Revocation"))) *pStatus |= PAL_X509ChainRevoked; else if (CFEqual(keyString, CFSTR("KeyUsage"))) *pStatus |= PAL_X509ChainNotValidForUsage; else if (CFEqual(keyString, CFSTR("AnchorTrusted"))) *pStatus |= PAL_X509ChainUntrustedRoot; else if (CFEqual(keyString, CFSTR("BasicConstraints"))) *pStatus |= PAL_X509ChainInvalidBasicConstraints; else if (CFEqual(keyString, CFSTR("UsageConstraints"))) *pStatus |= PAL_X509ChainExplicitDistrust; else if (CFEqual(keyString, CFSTR("RevocationResponseRequired"))) *pStatus |= PAL_X509ChainRevocationStatusUnknown; else if (CFEqual(keyString, CFSTR("MissingIntermediate"))) *pStatus |= PAL_X509ChainPartialChain; else if (CFEqual(keyString, CFSTR("WeakLeaf")) || CFEqual(keyString, CFSTR("WeakIntermediates")) || CFEqual(keyString, CFSTR("WeakRoot")) || CFEqual(keyString, CFSTR("WeakKeySize"))) { // Because we won't report this out of a chain built by .NET on Windows, // don't report it here. // // (On Windows CERT_CHAIN_PARA.pStrongSignPara is NULL, so "strongness" checks // are not performed). } else if (CFEqual(keyString, CFSTR("StatusCodes"))) { // 10.13 added a StatusCodes value which may be a numeric rehashing of the string data. // It doesn't represent a new error code, and we're still getting the old ones, so // just ignore it for now. } else if (CFEqual(keyString, CFSTR("NonEmptySubject"))) { // Not a "problem" that we report. } else { #ifdef DEBUGGING_UNKNOWN_VALUE printf("%s\n", CFStringGetCStringPtr(keyString, CFStringGetSystemEncoding())); #endif *pStatus |= PAL_X509ChainErrorUnknownValue; } }
int cardEffect(int card, int choice1, int choice2, int choice3, struct gameState *state, int handPos, int *bonus) { int i; int j; int k; int x; int index; int currentPlayer = whoseTurn(state); int nextPlayer = currentPlayer + 1; int tributeRevealedCards[2] = {-1, -1}; int temphand[MAX_HAND];// moved above the if statement int drawntreasure=0; int cardDrawn; int z = 0;// this is the counter for the temp hand if (nextPlayer > (state->numPlayers - 1)){ nextPlayer = 0; } //uses switch to select card and perform actions switch( card ) { case adventurer: while(drawntreasure<2){ if (state->deckCount[currentPlayer] <1){//if the deck is empty we need to shuffle discard and add to deck shuffle(currentPlayer, state); } drawCard(currentPlayer, state); cardDrawn = state->hand[currentPlayer][state->handCount[currentPlayer]-1];//top card of hand is most recently drawn card. if (cardDrawn == copper || cardDrawn == silver || cardDrawn == gold) drawntreasure++; else{ temphand[z]=cardDrawn; state->handCount[currentPlayer]--; //this should just remove the top card (the most recently drawn one). z++; } } while(z-1>=0){ state->discard[currentPlayer][state->discardCount[currentPlayer]++]=temphand[z-1]; // discard all cards in play that have been drawn z=z-1; } return 0; case council_room: //+4 Cards for (i = 0; i < 4; i++) { drawCard(currentPlayer, state); } //+1 Buy state->numBuys++; //Each other player draws a card for (i = 0; i < state->numPlayers; i++) { if ( i != currentPlayer ) { drawCard(i, state); } } //put played card in played card pile discardCard(handPos, currentPlayer, state, 0); return 0; case feast: //gain card with cost up to 5 //Backup hand for (i = 0; i <= state->handCount[currentPlayer]; i++){ temphand[i] = state->hand[currentPlayer][i];//Backup card state->hand[currentPlayer][i] = -1;//Set to nothing } //Backup hand //Update Coins for Buy updateCoins(currentPlayer, state, 5); x = 1;//Condition to loop on while( x == 1) {//Buy one card if (supplyCount(choice1, state) <= 0){ if (DEBUG) printf("None of that card left, sorry!\n"); if (DEBUG){ printf("Cards Left: %d\n", supplyCount(choice1, state)); } } else if (state->coins < getCost(choice1)){ printf("That card is too expensive!\n"); if (DEBUG){ printf("Coins: %d < %d\n", state->coins, getCost(choice1)); } } else{ if (DEBUG){ printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + state->discardCount[currentPlayer]); } gainCard(choice1, state, 0, currentPlayer);//Gain the card x = 0;//No more buying cards if (DEBUG){ printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + state->discardCount[currentPlayer]); } } } //Reset Hand for (i = 0; i <= state->handCount[currentPlayer]; i++){ state->hand[currentPlayer][i] = temphand[i]; temphand[i] = -1; } //Reset Hand return 0; case gardens: return -1; case mine: j = state->hand[currentPlayer][choice1]; //store card we will trash if (state->hand[currentPlayer][choice1] < copper || state->hand[currentPlayer][choice1] > gold) { return -1; } if (choice2 > treasure_map || choice2 < curse) { return -1; } if ( (getCost(state->hand[currentPlayer][choice1]) + 3) > getCost(choice2) ) { return -1; } gainCard(choice2, state, 2, currentPlayer); //discard card from hand discardCard(handPos, currentPlayer, state, 0); //discard trashed card for (i = 0; i < state->handCount[currentPlayer]; i++) { if (state->hand[currentPlayer][i] == j) { discardCard(i, currentPlayer, state, 0); break; } } return 0; case remodel: j = state->hand[currentPlayer][choice1]; //store card we will trash if ( (getCost(state->hand[currentPlayer][choice1]) + 2) > getCost(choice2) ) { return -1; } gainCard(choice2, state, 0, currentPlayer); //discard card from hand discardCard(handPos, currentPlayer, state, 0); //discard trashed card for (i = 0; i < state->handCount[currentPlayer]; i++) { if (state->hand[currentPlayer][i] == j) { discardCard(i, currentPlayer, state, 0); break; } } return 0; case smithy: //+3 Cards for (i = 0; i < 3; i++) { drawCard(currentPlayer, state); } //discard card from hand discardCard(handPos, currentPlayer, state, 0); return 0; case village: //+1 Card drawCard(currentPlayer, state); //+2 Actions state->numActions = state->numActions + 2; //discard played card from hand discardCard(handPos, currentPlayer, state, 0); return 0; case baron: state->numBuys++;//Increase buys by 1! if (choice1 > 0){//Boolean true or going to discard an estate int p = 0;//Iterator for hand! int card_not_discarded = 1;//Flag for discard set! while(card_not_discarded){ if (state->hand[currentPlayer][p] == estate){//Found an estate card! state->coins += 4;//Add 4 coins to the amount of coins state->discard[currentPlayer][state->discardCount[currentPlayer]] = state->hand[currentPlayer][p]; state->discardCount[currentPlayer]++; for (;p < state->handCount[currentPlayer]; p++){ state->hand[currentPlayer][p] = state->hand[currentPlayer][p+1]; } state->hand[currentPlayer][state->handCount[currentPlayer]] = -1; state->handCount[currentPlayer]--; card_not_discarded = 0;//Exit the loop } else if (p > state->handCount[currentPlayer]){ if(DEBUG) { printf("No estate cards in your hand, invalid choice\n"); printf("Must gain an estate if there are any\n"); } if (supplyCount(estate, state) > 0){ gainCard(estate, state, 0, currentPlayer); state->supplyCount[estate]--;//Decrement estates if (supplyCount(estate, state) == 0){ isGameOver(state); } } card_not_discarded = 0;//Exit the loop } else{ p++;//Next card } } } else{ if (supplyCount(estate, state) > 0){ gainCard(estate, state, 0, currentPlayer);//Gain an estate state->supplyCount[estate]--;//Decrement Estates if (supplyCount(estate, state) == 0){ isGameOver(state); } } } return 0; case great_hall: //+1 Card drawCard(currentPlayer, state); //+1 Actions state->numActions++; //discard card from hand discardCard(handPos, currentPlayer, state, 0); return 0; case minion: //+1 action state->numActions++; //discard card from hand discardCard(handPos, currentPlayer, state, 0); if (choice1) //+2 coins { state->coins = state->coins + 2; } else if (choice2) //discard hand, redraw 4, other players with 5+ cards discard hand and draw 4 { //discard hand while(numHandCards(state) > 0) { discardCard(handPos, currentPlayer, state, 0); } //draw 4 for (i = 0; i < 4; i++) { drawCard(currentPlayer, state); } //other players discard hand and redraw if hand size > 4 for (i = 0; i < state->numPlayers; i++) { if (i != currentPlayer) { if ( state->handCount[i] > 4 ) { //discard hand while( state->handCount[i] > 0 ) { discardCard(handPos, i, state, 0); } //draw 4 for (j = 0; j < 4; j++) { drawCard(i, state); } } } } } return 0; case steward: if (choice1 == 1) { //+2 cards drawCard(currentPlayer, state); drawCard(currentPlayer, state); } else if (choice1 == 2) { //+2 coins state->coins = state->coins + 2; } else { //trash 2 cards in hand discardCard(choice2, currentPlayer, state, 1); discardCard(choice3, currentPlayer, state, 1); } //discard card from hand discardCard(handPos, currentPlayer, state, 0); return 0; case tribute: if ((state->discardCount[nextPlayer] + state->deckCount[nextPlayer]) <= 1){ if (state->deckCount[nextPlayer] > 0){ tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1]; state->deckCount[nextPlayer]--; } else if (state->discardCount[nextPlayer] > 0){ tributeRevealedCards[0] = state->discard[nextPlayer][state->discardCount[nextPlayer]-1]; state->discardCount[nextPlayer]--; } else{ //No Card to Reveal if (DEBUG){ printf("No cards to reveal\n"); } } } else{ if (state->deckCount[nextPlayer] == 0){ for (i = 0; i < state->discardCount[nextPlayer]; i++){ state->deck[nextPlayer][i] = state->discard[nextPlayer][i];//Move to deck state->deckCount[nextPlayer]++; state->discard[nextPlayer][i] = -1; state->discardCount[nextPlayer]--; } shuffle(nextPlayer,state);//Shuffle the deck } tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1]; state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1; state->deckCount[nextPlayer]--; tributeRevealedCards[1] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1]; state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1; state->deckCount[nextPlayer]--; } if (tributeRevealedCards[0] == tributeRevealedCards[1]){//If we have a duplicate card, just drop one state->playedCards[state->playedCardCount] = tributeRevealedCards[1]; state->playedCardCount++; tributeRevealedCards[1] = -1; } for (i = 0; i <= 2; i ++){ if (tributeRevealedCards[i] == copper || tributeRevealedCards[i] == silver || tributeRevealedCards[i] == gold){//Treasure cards state->coins += 2; } else if (tributeRevealedCards[i] == estate || tributeRevealedCards[i] == duchy || tributeRevealedCards[i] == province || tributeRevealedCards[i] == gardens || tributeRevealedCards[i] == great_hall){//Victory Card Found drawCard(currentPlayer, state); drawCard(currentPlayer, state); } else{//Action Card state->numActions = state->numActions + 2; } } return 0; case ambassador: j = 0; //used to check if player has enough cards to discard if (choice2 > 2 || choice2 < 0) { return -1; } if (choice1 == handPos) { return -1; } for (i = 0; i < state->handCount[currentPlayer]; i++) { if (i != handPos && i == state->hand[currentPlayer][choice1] && i != choice1) { j++; } } if (j < choice2) { return -1; } if (DEBUG) printf("Player %d reveals card number: %d\n", currentPlayer, state->hand[currentPlayer][choice1]); //increase supply count for choosen card by amount being discarded state->supplyCount[state->hand[currentPlayer][choice1]] += choice2; //each other player gains a copy of revealed card for (i = 0; i < state->numPlayers; i++) { if (i != currentPlayer) { gainCard(state->hand[currentPlayer][choice1], state, 0, i); } } //discard played card from hand discardCard(handPos, currentPlayer, state, 0); //trash copies of cards returned to supply for (j = 0; j < choice2; j++) { for (i = 0; i < state->handCount[currentPlayer]; i++) { if (state->hand[currentPlayer][i] == state->hand[currentPlayer][choice1]) { discardCard(i, currentPlayer, state, 1); break; } } } return 0; case cutpurse: updateCoins(currentPlayer, state, 2); for (i = 0; i < state->numPlayers; i++) { if (i != currentPlayer) { for (j = 0; j < state->handCount[i]; j++) { if (state->hand[i][j] == copper) { discardCard(j, i, state, 0); break; } if (j == state->handCount[i]) { for (k = 0; k < state->handCount[i]; k++) { if (DEBUG) printf("Player %d reveals card number %d\n", i, state->hand[i][k]); } break; } } } } //discard played card from hand discardCard(handPos, currentPlayer, state, 0); return 0; case embargo: //+2 Coins state->coins = state->coins + 2; //see if selected pile is in play if ( state->supplyCount[choice1] == -1 ) { return -1; } //add embargo token to selected supply pile state->embargoTokens[choice1]++; //trash card discardCard(handPos, currentPlayer, state, 1); return 0; case outpost: //set outpost flag state->outpostPlayed++; //discard card discardCard(handPos, currentPlayer, state, 0); return 0; case salvager: //+1 buy state->numBuys++; if (choice1) { //gain coins equal to trashed card state->coins = state->coins + getCost( handCard(choice1, state) ); //trash card discardCard(choice1, currentPlayer, state, 1); } //discard card discardCard(handPos, currentPlayer, state, 0); return 0; case sea_hag: for (i = 0; i < state->numPlayers; i++){ if (i != currentPlayer){ state->discard[i][state->discardCount[i]] = state->deck[i][state->deckCount[i]--]; state->deckCount[i]--; state->discardCount[i]++; state->deck[i][state->deckCount[i]--] = curse;//Top card now a curse } } return 0; case treasure_map: //search hand for another treasure_map index = -1; for (i = 0; i < state->handCount[currentPlayer]; i++) { if (state->hand[currentPlayer][i] == treasure_map && i != handPos) { index = i; break; } } if (index > -1) { //trash both treasure cards discardCard(handPos, currentPlayer, state, 1); discardCard(index, currentPlayer, state, 1); //gain 4 Gold cards for (i = 0; i < 4; i++) { gainCard(gold, state, 1, currentPlayer); } //return success return 1; } //no second treasure_map found in hand return -1; } return -1; }
void nfft_benchomp_createdataset(unsigned int d, unsigned int trafo_adjoint, int *N, int M, double sigma) { int n[d]; int t, j; R *x; C *f, *f_hat; int N_total = 1; for (t = 0; t < d; t++) N_total *= N[t]; x = (R*) NFFT(malloc)(d*M*sizeof(R)); f = (C*) NFFT(malloc)(M*sizeof(C)); f_hat = (C*) NFFT(malloc)(N_total*sizeof(C)); for (t=0; t<d; t++) n[t] = sigma*NFFT(next_power_of_2)(N[t]); /** init pseudo random nodes */ NFFT(vrand_shifted_unit_double)(x,d*M); if (trafo_adjoint==0) { NFFT(vrand_unit_complex)(f_hat,N_total); } else { NFFT(vrand_unit_complex)(f,M); } printf("%d %d ", d, trafo_adjoint); for (t=0; t<d; t++) printf("%d ", N[t]); for (t=0; t<d; t++) printf("%d ", n[t]); printf("%d\n", M); for (j=0; j < M; j++) { for (t=0; t < d; t++) printf("%.16e ", x[d*j+t]); printf("\n"); } if (trafo_adjoint==0) { for (j=0; j < N_total; j++) printf("%.16e %.16e\n", creal(f_hat[j]), cimag(f_hat[j])); } else { for (j=0; j < M; j++) printf("%.16e %.16e\n", creal(f[j]), cimag(f[j])); } NFFT(free)(x); NFFT(free)(f); NFFT(free)(f_hat); }
/* FMT_LOCK_Cleanup */ static void TEST_CORE_LockCleanup(void* user_data) { assert(user_data == &TEST_CORE_LockUserData); printf("TEST_CORE_LockCleanup()\n"); TEST_CORE_LockUserData = 222; }
int main(){ printf("Solution for problem 9 is: %d\n", problem_9()); return 0; }
static void TEST_CORE_Log(void) { /* LOG */ LOG x_log; /* protective MT-lock */ MT_LOCK x_lock; /* ELOG_Level, LOG_LevelStr() */ int x_level; for (x_level = 0; x_level <= (int) eLOG_Fatal; x_level++) { switch ( (ELOG_Level) x_level ) { case eLOG_Trace: case eLOG_Note: case eLOG_Warning: case eLOG_Error: case eLOG_Critical: case eLOG_Fatal: assert(LOG_LevelStr((ELOG_Level) x_level)); printf("LOG_LevelStr(level = %d): \"%s\"\n", x_level, LOG_LevelStr((ELOG_Level) x_level)); break; default: assert(0); } } /* LOG API */ /* MT-lock */ x_lock = MT_LOCK_Create(&TEST_CORE_LockUserData, TEST_CORE_LockHandler, TEST_CORE_LockCleanup); /* dummy */ TEST_CORE_LogUserData = 1; x_log = LOG_Create(&TEST_CORE_LogUserData, TEST_CORE_LogHandler, TEST_CORE_LogCleanup, x_lock); assert(x_log); verify(LOG_AddRef(x_log) == x_log); verify(LOG_AddRef(x_log) == x_log); verify(LOG_Delete(x_log) == x_log); assert(TEST_CORE_LogUserData == 1); LOG_WRITE(0, 0, 0, eLOG_Trace, 0); LOG_Write(0, 0, 0, eLOG_Trace, 0, 0, 0, 0, 0, 0); LOG_WRITE(x_log, 0, 0, eLOG_Trace, 0); LOG_Write(x_log, 0, 0, eLOG_Trace, 0, 0, 0, 0, 0, 0); verify(LOG_Delete(x_log) == x_log); assert(TEST_CORE_LogUserData == 1); /* reset to "real" logging */ LOG_Reset(x_log, &TEST_CORE_LogUserData, TEST_CORE_LogHandler, TEST_CORE_LogCleanup); assert(TEST_CORE_LogUserData == 444); TEST_CORE_LogUserData = 2; /* do the test logging */ LOG_WRITE(x_log, 0, 0, eLOG_Trace, 0); LOG_Write(x_log, 0, 0, eLOG_Trace, 0, 0, 0, 0, 0, 0); LOG_WRITE(x_log, 0, 0, eLOG_Warning, ""); /* LOG_WRITE(x_log, eLOG_Fatal, "Something fatal"); */ #undef THIS_MODULE #define THIS_MODULE "FooModuleName" LOG_WRITE(x_log, 0, 0, eLOG_Error, "With changed module name"); #undef THIS_FILE #define THIS_FILE "BarFileName" LOG_WRITE(x_log, 0, 0, eLOG_Critical, "With changed module and file name"); #undef THIS_FILE #define THIS_FILE __FILE__ #undef THIS_MODULE #define THIS_MODULE 0 /* delete */ verify(LOG_Delete(x_log) == 0); assert(TEST_CORE_LogUserData == 444); }
void fc3d_VI_ExtraGradient(FrictionContactProblem* problem, double *reaction, double *velocity, int* info, SolverOptions* options) { /* Number of contacts */ int nc = problem->numberOfContacts; /* Dimension of the problem */ int n = 3 * nc; VariationalInequality *vi = (VariationalInequality *)malloc(sizeof(VariationalInequality)); //vi.self = &vi; vi->F = &Function_VI_FC3D; vi->ProjectionOnX = &Projection_VI_FC3D; int iter=0; double error=1e24; FrictionContactProblem_as_VI *fc3d_as_vi= (FrictionContactProblem_as_VI*)malloc(sizeof(FrictionContactProblem_as_VI)); vi->env =fc3d_as_vi ; vi->size = n; /*Set the norm of the VI to the norm of problem->q */ vi->normVI= cblas_dnrm2(n , problem->q , 1); vi->istheNormVIset=1; fc3d_as_vi->vi = vi; fc3d_as_vi->fc3d = problem; /* frictionContact_display(fc3d_as_vi->fc3d); */ SolverOptions * visolver_options = (SolverOptions *) malloc(sizeof(SolverOptions)); variationalInequality_setDefaultSolverOptions(visolver_options, SICONOS_VI_EG); int isize = options->iSize; int dsize = options->dSize; int vi_isize = visolver_options->iSize; int vi_dsize = visolver_options->dSize; if (isize != vi_isize ) { printf("size prolem in fc3d_VI_ExtraGradient\n"); } if (dsize != vi_dsize ) { printf("size prolem in fc3d_VI_ExtraGradient\n"); } /* int i; */ /* for (i = 0; i < isize; i++) */ /* { */ /* visolver_options->iparam[i] = options->iparam[i] ; */ /* } */ /* for (i = 0; i < dsize; i++) */ /* { */ /* visolver_options->dparam[i] = options->dparam[i] ; */ /* } */ int i; for (i = 0; i < isize; i++) { if (options->iparam[i] != 0 ) visolver_options->iparam[i] = options->iparam[i] ; } for (i = 0; i < dsize; i++) { if (fabs(options->dparam[i]) >= 1e-24 ) visolver_options->dparam[i] = options->dparam[i] ; } variationalInequality_ExtraGradient(vi, reaction, velocity , info , visolver_options); /* **** Criterium convergence **** */ fc3d_compute_error(problem, reaction , velocity, options->dparam[0], options, &error); /* for (i =0; i< n ; i++) */ /* { */ /* printf("reaction[%i]=%f\t",i,reaction[i]); printf("velocity[%i]=F[%i]=%f\n",i,i,velocity[i]); */ /* } */ error = visolver_options->dparam[1]; iter = visolver_options->iparam[7]; options->dparam[1] = error; options->iparam[7] = iter; if (verbose > 0) { printf("----------------------------------- FC3D - VI Extra Gradient (VI_EG) - #Iteration %i Final Residual = %14.7e\n", iter, error); } free(vi); deleteSolverOptions(visolver_options); free(visolver_options); visolver_options=NULL; free(fc3d_as_vi); }
void sim_radio_init() { //! initialize node id and location FILE *fid; char line_buf[LINE_BUF_SIZE]; // line buffer int j = 0; if((fid = fopen(topofile, "r")) == NULL){ char* sosrootdir; char newtopofile[256]; sosrootdir = getenv("SOSROOT"); strcpy(newtopofile, sosrootdir); printf("Unable to open %s\n", topofile); strcat(newtopofile, "/platform/sim/topo.def\0"); if((fid = fopen(newtopofile, "r")) == NULL){ printf("Unable to open %s\n", newtopofile); exit(1); } else topofile = newtopofile; } printf("Using topology file %s\n", topofile); // remove comments do{ fgets(line_buf, LINE_BUF_SIZE, fid); } while(line_buf[0] == '#'); if(sscanf(line_buf, "%d", &totalNodes) != 1){ fprintf(stderr, "no data in %s\n", topofile); exit(1); } topo_array = (Topology*)malloc((totalNodes + 1) * sizeof(Topology)); if (topo_array == NULL){ fprintf(stderr, "not enough memory\n"); exit(1); } for(j = 0; j < totalNodes; j++){ do{ // remove comments fgets(line_buf, LINE_BUF_SIZE, fid); }while(line_buf[0] == '#'); if(sscanf(line_buf, "%d %d %d %d %d %u", &topo_array[j].id, &topo_array[j].unit, &topo_array[j].x, &topo_array[j].y, &topo_array[j].z, &topo_array[j].r2) != 6){ fprintf(stderr, "not enough definitions in %s: %s\n", topofile, line_buf); exit(1); } //topo_array[j].id = j; topo_array[j].type = TOPO_TYPE_OTHER; topo_array[j].sock = -1; } #if 0 print_nodes(); exit(1); #endif if(fclose(fid) != 0){ perror("fclose"); exit(1); } // finding node id by finding available port //for(j = 1; j <= totalNodes; j++) { int sock; int myj = getj(ker_id()); struct sockaddr_in name; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { perror("opening datagram socket"); exit(1); } /* Create name with wildcards. */ name.sin_family = AF_INET; name.sin_addr.s_addr = INADDR_ANY; // name.sin_port = htons(20000 + ker_id()); name.sin_port = htons( get_sin_port(ker_id()) ); if (bind(sock, (struct sockaddr *)&name, sizeof(name)) == 0) { //node_address = j; // successfully get an id topo_array[myj].sock = sock; topo_array[myj].type = TOPO_TYPE_SELF; topo_self = topo_array[myj]; //! assign sos_info node_loc.x = topo_self.x; node_loc.y = topo_self.y; node_loc.z = topo_self.z; node_loc.unit = topo_self.unit; }else{ fprintf(stderr, "Unable to allocate UDP for this node!\n"); fprintf(stderr, "Perhaps you are using the same node ID\n"); fprintf(stderr, "Use -n <node address> to specify different address\n\n"); exit(1); } } { uint16_t id; node_loc_t self; id = ker_id(); self = ker_loc(); if((id != topo_self.id) || (self.x != topo_self.x) || (self.y != topo_self.y) || (self.z != topo_self.z) || (self.unit != topo_self.unit)){ fprintf(stderr, "topo file and self settings do not agree.\n"); fprintf(stderr, "ker_id() = %d : topo_self.id = %d\n", id, topo_self.id); fprintf(stderr, "self.unit = %d : topo_self.unit = %d\n", self.unit, topo_self.unit); fprintf(stderr, "self.x = %d : topo_self.x = %d\n", self.x, topo_self.x); fprintf(stderr, "self.y = %d : topo_self.y = %d\n", self.y, topo_self.y); fprintf(stderr, "self.z = %d : topo_self.z = %d\n", self.z, topo_self.z); exit(1); } } for(j = 0; j < totalNodes; j++){ uint32_t r2; uint16_t id; node_loc_t self, neighbor; id = ker_id(); self = ker_loc(); if(topo_array[j].type == TOPO_TYPE_SELF) continue; neighbor.unit = topo_array[j].unit; neighbor.x = topo_array[j].x; neighbor.y = topo_array[j].y; neighbor.z = topo_array[j].z; r2 = ker_loc_r2(&self,&neighbor); if(r2 < 0){ fprintf(stderr, "units for neighbor do not agree.\n"); fprintf(stderr, "self.unit = %d : neighbor.unit = %d.\n", self.unit, neighbor.unit); exit(1); } DEBUG("neighbor %d r2 = %d, self r2 = %d\n", topo_array[j].id, r2, topo_self.r2); if(r2 <= topo_self.r2){ topo_array[j].type = TOPO_TYPE_NEIGHBOR; DEBUG("node %d is reachable\n", topo_array[j].id); } } { struct hostent *hostptr; char theHost [MAXLENHOSTNAME]; unsigned long hostaddress; /* find out who I am */ if ((gethostname(theHost, MAXLENHOSTNAME))<0) { perror ("could not get hostname"); exit(1); } //DEBUG("-- found host name = %s\n", theHost); if ((hostptr = gethostbyname (theHost)) == NULL) { perror ("could not get host by name, use 127.0.0.1"); if(( hostptr = gethostbyname ("127.0.0.1") ) == NULL ) { perror ("Cannot get host 127.0.0.1"); exit(1); } } hostaddress = *((unsigned long *) hostptr->h_addr); /* init the address structure */ sockaddr.sin_family = AF_INET; sockaddr.sin_port = htons( get_sin_port(ker_id()) ); sockaddr.sin_addr.s_addr = hostaddress; } //! assign locations //node_loc.x = (uint16_t)(topo_self.x); //node_loc.y = (uint16_t)(topo_self.y); //print_nodes(); }
/** ============================================================================ * @n@b CDC_putData * * @b Description * @n This function sends out the data to the BULK IN * * @b Arguments * @verbatim pContext Pointer to the USBContext structure hCdcClass Handle to the CDC Class Obj data the data to be transmitted size the data size @endverbatim * * <b> Return Value </b> - number of byte sent out * @li 0 - means the BULK IN is not ready for transmission * @li N > 0 - means the transmission is done and N byte data has been sent out * * <b> Pre Condition </b> * @n CDC module should be opened using CDC_Open/CDC_OpenFullspeed function * * <b> Post Condition </b> * @n Returns request processing status * * @b Modifies * @n None * * @b Example * @verbatim CSL_CdcInitStructApp cdcAppHandle; CSL_CdcClassStruct cdcClassStruct; CSL_Status status; Uint16 uartData[80] Uint16 uartdataSize; // Assign values to all the members in cdcAppHandle struct cdcAppHandle.pCdcObj = &cdcClassStruct; ..... ..... status = CDC_Open(pAppClassHandle); .... .... // Echo the input from the host back to the host // Get data from the host uartDataSize = CDC_getData(pContext, &CDC_AppHandle, uartData); // Echo it back, if there is an input if (uartDataSize>0) { do { // CDC_putData will return 0 if the TX is not ready for the transaction retNum = CDC_putData(pContext, &CDC_AppHandle, uartData, uartDataSize); } while (retNum==0); } .... .... @endverbatim * ============================================================================ */ Uint16 CDC_putData(pUsbContext pContext, CSL_CdcInitStructApp *cdcAppHandle, Uint16 *data, Uint16 size) { CSL_Status status, txRxStatus; Uint16 bytesRem, i; Uint16 txEndIdxSave, txStartIdxSave; // the data size cannot larger than CSL_USB_CDC_DATA_BUF_SIZE if (size>CSL_USB_CDC_DATA_BUF_SIZE) return 0; // is there anything in the TX buffer? txStartIdxSave = cdcAppHandle->txStartIdx; txEndIdxSave = cdcAppHandle->txEndIdx; if (txEndIdxSave==txStartIdxSave) { // make sure TX working buffer is free too if (cdcAppHandle->txWorkBufIdx>0) { return 0; } // copy data from data buffer to TX working buffer for (i=0; i<size; i++) { if (cdcAppHandle->txWorkBufIdx%2) { cdcAppHandle->txWorkBufPtr[cdcAppHandle->txWorkBufIdx/2] = (cdcAppHandle->txWorkBufPtr[cdcAppHandle->txWorkBufIdx/2]&0x00FF)|(data[i]<<8); } else { cdcAppHandle->txWorkBufPtr[cdcAppHandle->txWorkBufIdx/2] = (data[i]&0xFF); } // increase the txWorkBufIdx cdcAppHandle->txWorkBufIdx++; if (cdcAppHandle->txWorkBufIdx>=CSL_USB_CDC_DATA_BUF_SIZE) cdcAppHandle->txWorkBufIdx = 0; } // send it to host status = USB_postTransaction(pContext->hEpObjArray[3], size, cdcAppHandle->txWorkBufPtr, CSL_USB_IN_TRANSFER); if(status != CSL_SOK) { printf("USB TX Transaction failed\n"); } /* Check the transaction status */ txRxStatus = USB_isTransactionDone(pContext->hEpObjArray[3], &status); if(txRxStatus != CSL_USB_TRUE) { bytesRem = USB_bytesRemaining(pContext->hEpObjArray[3], &status); if(bytesRem) { printf("Bytes remaining: %d\n", bytesRem); } } // update the txStartIdx cdcAppHandle->txStartIdx = cdcAppHandle->txEndIdx; // clear the txWorkBufIdx cdcAppHandle->txWorkBufIdx = 0; } else { // TX buffer is not empty // make sure the TX has enough space for the data if (txEndIdxSave>txStartIdxSave) { if ((txEndIdxSave-txStartIdxSave+size)>CSL_USB_CDC_DATA_BUF_SIZE) return 0; } else { if ((txStartIdxSave-txEndIdxSave+size)>CSL_USB_CDC_DATA_BUF_SIZE) return 0; } // copy data from data buffer to TX buffer for (i=0; i<size; i++) { cdcAppHandle->txBufferPtr[cdcAppHandle->txEndIdx] = (cdcAppHandle->txBufferPtr[cdcAppHandle->txEndIdx/2]&0xFF00)|(data[i]&0xFF); // increase the txEndIdx cdcAppHandle->txEndIdx++; if (cdcAppHandle->txEndIdx>=CSL_USB_CDC_DATA_BUF_SIZE) cdcAppHandle->txEndIdx = 0; } } return size; }
void print(void) const { printf("D::print\n"); exit(1); }
/** ============================================================================ * @n@b CDC_bulkInHandler * * @b Description * @n This function handles all the CDC ACM bulk IN data transactions * * @b Arguments * @verbatim pContext Pointer to the USBContext structure hCdcClass Handle to the CDC Class Obj @endverbatim * * <b> Return Value </b> - Status of the processing (CSL_Status) * @li CSL_SOK (0) Success * @li CSL_ESYS_FAIL (-1) Generic failure * @li CSL_ESYS_BADHANDLE (-5) Handle passed to CSL was invalid * @li CSL_ESYS_INVPARAMS (-6) Invalid parameters * * <b> Pre Condition </b> * @n CDC module should be opened using CDC_Open/CDC_OpenFullspeed function * * <b> Post Condition </b> * @n Returns request processing status * * @b Modifies * @n None * * @b Example * @verbatim CSL_CdcInitStructApp cdcAppHandle; CSL_CdcClassStruct cdcClassStruct; CSL_Status status; // Assign values to all the members in cdcAppHandle struct cdcAppHandle.pCdcObj = &cdcClassStruct; ..... ..... status = CDC_Open(pAppClassHandle); .... .... in USB ISR: .... .... if (pContext->dwIntSourceL & (1<<CSL_CDC_BULK_IN_EP)) { // Handle the CDC BULK IN ///CDC_bulkInHandler(pContext, &CDC_AppHandle); } .... .... @endverbatim * ============================================================================ */ CSL_Status CDC_bulkInHandler(pUsbContext pContext, CSL_CdcInitStructApp *cdcAppHandle) { CSL_Status status, txRxStatus; Uint16 bytesRem, txStartIdxSave, txEndIdxSave, i; status = CSL_SOK; // Is the TX EP free? if (cdcAppHandle->txWorkBufIdx==0) { // is there anything need to send out txStartIdxSave = cdcAppHandle->txStartIdx; txEndIdxSave = cdcAppHandle->txEndIdx; if (txEndIdxSave==txStartIdxSave) { // nothing to transmit, then return return status; } else if (txEndIdxSave>txStartIdxSave) { // for no wrap around case // pack and copy the data from txBufferPtr to txWorkBufPtr for (i=0; i<(txEndIdxSave-txStartIdxSave); i++) { if (i%2) cdcAppHandle->txWorkBufPtr[i/2] = (cdcAppHandle->txBufferPtr[txStartIdxSave+i]<<8); else cdcAppHandle->txWorkBufPtr[i/2] = cdcAppHandle->txBufferPtr[txStartIdxSave+i]&0xFF; } // send whatever in the TX working buffer to host status = USB_postTransaction(pContext->hEpObjArray[3], txEndIdxSave-txStartIdxSave, cdcAppHandle->txWorkBufPtr, CSL_USB_IN_TRANSFER); if(status != CSL_SOK) { printf("USB TX Transaction failed\n"); } /* Check the transaction status */ txRxStatus = USB_isTransactionDone(pContext->hEpObjArray[3], &status); if(txRxStatus != CSL_USB_TRUE) { bytesRem = USB_bytesRemaining(pContext->hEpObjArray[3], &status); if(bytesRem) { printf("Bytes remaining: %d\n", bytesRem); } } // update the txStartIdx cdcAppHandle->txStartIdx = txEndIdxSave; } else if (txEndIdxSave<txStartIdxSave) { // for wrap around case // send the TX buffer (rxStartIdx - CSL_USB_CDC_DATA_BUF_SIZE) to host // pack and copy the data from txBufferPtr to txWorkBufPtr for (i=0; i<(CSL_USB_CDC_DATA_BUF_SIZE-txStartIdxSave); i++) { if (i%2) cdcAppHandle->txWorkBufPtr[i/2] = (cdcAppHandle->txBufferPtr[txStartIdxSave+i]<<8); else cdcAppHandle->txWorkBufPtr[i/2] = cdcAppHandle->txBufferPtr[txStartIdxSave+i]&0xFF; } // send whatever in the TX working buffer to host status = USB_postTransaction(pContext->hEpObjArray[3], CSL_USB_CDC_DATA_BUF_SIZE-txStartIdxSave, cdcAppHandle->txWorkBufPtr, CSL_USB_IN_TRANSFER); if(status != CSL_SOK) { printf("USB TX Transaction failed\n"); } /* Check the transaction status */ txRxStatus = USB_isTransactionDone(pContext->hEpObjArray[3], &status); if(txRxStatus != CSL_USB_TRUE) { bytesRem = USB_bytesRemaining(pContext->hEpObjArray[3], &status); if(bytesRem) { printf("Bytes remaining: %d\n", bytesRem); } } // update the txStartIdx cdcAppHandle->txStartIdx = 0; // send the TX buffer (0 - txEndIdx) to host // pack and copy the data from txBufferPtr to txWorkBufPtr for (i=0; i<txEndIdxSave; i++) { if (i%2) cdcAppHandle->txWorkBufPtr[i/2] = (cdcAppHandle->txBufferPtr[txStartIdxSave+i]<<8); else cdcAppHandle->txWorkBufPtr[i/2] = cdcAppHandle->txBufferPtr[txStartIdxSave+i]&0xFF; } // send whatever in the TX working buffer to host status = USB_postTransaction(pContext->hEpObjArray[3], txEndIdxSave, cdcAppHandle->txWorkBufPtr, CSL_USB_IN_TRANSFER); if(status != CSL_SOK) { printf("USB TX Transaction failed\n"); } /* Check the transaction status */ txRxStatus = USB_isTransactionDone(pContext->hEpObjArray[3], &status); if(txRxStatus != CSL_USB_TRUE) { bytesRem = USB_bytesRemaining(pContext->hEpObjArray[3], &status); if(bytesRem) { printf("Bytes remaining: %d\n", bytesRem); } } // update the txStartIdx cdcAppHandle->txStartIdx = txEndIdxSave; } } return status; }
//! //! @brief Indexes a file using the morphology engine. A NULL path will create an empty index //! void lw_index_create (LwIndex *index, LwDictionaryData *dictionarydata, LwProgress *progress) { printf("BREAK lw_index_create\n"); //Sanity checks g_return_if_fail (index != NULL); g_return_if_fail (index->morphologyengine != NULL); g_return_if_fail (dictionarydata != NULL); g_return_if_fail (progress != NULL); if (lw_progress_should_abort (progress)) return; //Declarations glong length = lw_dictionarydata_get_length (dictionarydata); gdouble fraction = 0.0; LwIndexTableType type = 0; //Clear the index tables for (type = 0; type < TOTAL_LW_INDEX_TABLES; type++) { if (index->table[type] != NULL) g_hash_table_unref (index->table[type]); index->table[type] = NULL; index->table[type] = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); } //Clear the checksums for (type = 0; !lw_progress_should_abort (progress) && type < TOTAL_LW_INDEX_TABLES; type++) { if (index->buffer[type] != NULL) g_free (index->buffer[type]); index->buffer[type] = NULL; } if (index->checksum != NULL) g_free ((gchar*)index->checksum); index->checksum = NULL; //Parse the data const gchar *BUFFER = lw_dictionarydata_get_buffer (dictionarydata); do { LwOffset offset = lw_dictionarydata_get_offset (dictionarydata, BUFFER); _lw_index_create_add_string (index, BUFFER, offset); lw_progress_set_fraction (progress, offset, length); lw_progress_run_callback (progress); if (lw_progress_should_abort (progress)) goto errored; } while ((BUFFER = lw_dictionarydata_buffer_next (dictionarydata, BUFFER)) != NULL) ; //_lw_index_deep_index (index, dictionarydata, progress); if (lw_progress_should_abort (progress)) goto errored; //Set the checksums for (type = 0; !lw_progress_should_abort (progress) && type < TOTAL_LW_INDEX_TABLES; type++) { index->buffer[type] = g_strdup (lw_dictionarydata_get_checksum (dictionarydata)); } index->checksum = g_strdup (lw_dictionarydata_get_checksum (dictionarydata)); return; errored: for (type = 0; type < TOTAL_LW_INDEX_TABLES; type++) { if (index->table[type] != NULL) g_hash_table_unref (index->table[type]); index->table[type] = NULL; index->table[type] = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); } }
int main(int argc, char* argv[]) { int fbfd = 0; struct fb_var_screeninfo orig_vinfo; long int screensize = 0; // Open the file for reading and writing fbfd = open("/dev/fb0", O_RDWR); if (fbfd == -1) { printf("Error: cannot open framebuffer device.\n"); return(1); } printf("The framebuffer device was opened successfully.\n"); // Get variable screen information if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo) == -1) { printf("Error reading variable information.\n"); } printf("Original %dx%d, %dbpp\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel ); // Store for reset (copy vinfo to vinfo_orig) memcpy(&orig_vinfo, &vinfo, sizeof(struct fb_var_screeninfo)); // Change variable info vinfo.bits_per_pixel = 8; if (ioctl(fbfd, FBIOPUT_VSCREENINFO, &vinfo) == -1) { printf("Error setting variable information.\n"); } // Get fixed screen information if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo) == -1) { printf("Error reading fixed information.\n"); } // map fb to user mem screensize = finfo.smem_len; fbp = (char*)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0); if ((int)fbp == -1) { printf("Failed to mmap.\n"); } else { // draw... draw(); sleep(5); } // cleanup // unmap fb file from memory munmap(fbp, screensize); // reset the display mode if (ioctl(fbfd, FBIOPUT_VSCREENINFO, &orig_vinfo)) { printf("Error re-setting variable information.\n"); } // close fb file close(fbfd); return 0; }
int main(int argc, char **argv) { char *dev = NULL; /* capture device name */ char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */ pcap_t *handle; /* packet capture handle */ char filter_exp[] = "ip"; /* filter expression [3] */ struct bpf_program fp; /* compiled filter program (expression) */ bpf_u_int32 mask; /* subnet mask */ bpf_u_int32 net; /* ip */ int num_packets = 100; /* number of packets to capture */ /* check for capture device name on command-line */ if (argc != 3) { fprintf(stderr, "Usage : <pcap> add/remove <device>\n"); exit(EXIT_FAILURE); } if (strcmp(argv[1], "add") == 0) { g_add_option = 1; } else if (strcmp(argv[1], "remove") == 0) { g_remove_option = 1; } else { fprintf(stderr, "Usage : <pcap> add/remove <device>\n"); exit(EXIT_FAILURE); } dev = argv[2]; /* get network number and mask associated with capture device */ if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) { fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf); net = 0; mask = 0; } /* print capture info */ printf("Device: %s\n", dev); printf("Number of packets: %d\n", num_packets); printf("Filter expression: %s\n", filter_exp); /* open capture device */ handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf); exit(EXIT_FAILURE); } /* make sure we're capturing on an Ethernet device [2] */ if (pcap_datalink(handle) != DLT_EN10MB) { fprintf(stderr, "%s is not an Ethernet\n", dev); exit(EXIT_FAILURE); } /* compile the filter expression */ if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle)); exit(EXIT_FAILURE); } /* apply the compiled filter */ if (pcap_setfilter(handle, &fp) == -1) { fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle)); exit(EXIT_FAILURE); } /* now we can set our callback function */ pcap_loop(handle, num_packets, got_packet, NULL); /* cleanup */ pcap_freecode(&fp); pcap_close(handle); printf("\nCapture complete.\n"); return 0; }
int main(int argc, char **argv) { burrow_st *burrow; client_st client; msg_st *msg; int use_http = 0; argc--; argv++; if (strcmp(argv[0], "http") == 0) { use_http = 1; argc--; argv++; } if (argc < 4 || argc % 2 != 0) return -1; client.account = argv[0]; client.queue = argv[1]; argc -= 2; argv += 2; client.messages = NULL; client.message_count = 0; while (argc) { msg = malloc(sizeof(msg_st)); if (!msg) return -2; msg->msg_id = argv[0]; msg->body = (uint8_t *)argv[1]; msg->body_size = strlen(argv[1]); msg->next = client.messages; client.messages = msg; client.message_count++; argc -= 2; argv += 2; } client.return_code = 0; client.current_message = client.messages; if (use_http == 0) { burrow = burrow_create(NULL, "dummy"); printf("burrow = %p\n", burrow); } else { burrow = burrow_create(NULL, "http"); printf("burrow = %p\n", burrow); burrow_backend_set_option(burrow, "server", "localhost"); burrow_backend_set_option(burrow, "port", "8080"); } burrow_set_context(burrow, &client); burrow_set_complete_fn(burrow, &_complete); burrow_set_log_fn(burrow, &_log); /* Insert the first one here to kick the loop off. This only sets start state, it doesn't run the loop. */ msg = client.current_message; burrow_create_message(burrow, client.account, client.queue, msg->msg_id, msg->body, msg->body_size, NULL); /* This runs until there are no more tasks. */ burrow_process(burrow); burrow_destroy(burrow); return client.return_code; }