int Application5::Render() { GzToken nameListTriangle[3]; /* vertex attribute names */ GzPointer valueListTriangle[3]; /* vertex attribute pointers */ GzCoord vertexList[3]; /* vertex position coordinates */ GzCoord normalList[3]; /* vertex normals */ GzTextureIndex uvList[3]; /* vertex texture map indices */ char dummy[256]; int status; /* Initialize Display */ status |= GzInitDisplay(m_pDisplay); /* * Tokens associated with triangle vertex values */ nameListTriangle[0] = GZ_POSITION; nameListTriangle[1] = GZ_NORMAL; nameListTriangle[2] = GZ_TEXTURE_INDEX; // I/O File open FILE *infile; if( (infile = fopen( INFILE , "r" )) == NULL ) { AfxMessageBox( "The input file was not opened\n" ); return GZ_FAILURE; } FILE *outfile; if( (outfile = fopen( OUTFILE , "wb" )) == NULL ) { AfxMessageBox( "The output file was not opened\n" ); return GZ_FAILURE; } /* * Walk through the list of triangles, set color * and render each triangle */ while( fscanf(infile, "%s", dummy) == 1) { /* read in tri word */ fscanf(infile, "%f %f %f %f %f %f %f %f", &(vertexList[0][0]), &(vertexList[0][1]), &(vertexList[0][2]), &(normalList[0][0]), &(normalList[0][1]), &(normalList[0][2]), &(uvList[0][0]), &(uvList[0][1]) ); fscanf(infile, "%f %f %f %f %f %f %f %f", &(vertexList[1][0]), &(vertexList[1][1]), &(vertexList[1][2]), &(normalList[1][0]), &(normalList[1][1]), &(normalList[1][2]), &(uvList[1][0]), &(uvList[1][1]) ); fscanf(infile, "%f %f %f %f %f %f %f %f", &(vertexList[2][0]), &(vertexList[2][1]), &(vertexList[2][2]), &(normalList[2][0]), &(normalList[2][1]), &(normalList[2][2]), &(uvList[2][0]), &(uvList[2][1]) ); /* * Set the value pointers to the first vertex of the * triangle, then feed it to the renderer * NOTE: this sequence matches the nameList token sequence */ valueListTriangle[0] = (GzPointer)vertexList; valueListTriangle[1] = (GzPointer)normalList; valueListTriangle[2] = (GzPointer)uvList; GzPutTriangle(m_pRender, 3, nameListTriangle, valueListTriangle); } GzFlushDisplay2File(outfile, m_pDisplay); /* write out or update display to file*/ GzFlushDisplay2FrameBuffer(m_pFrameBuffer, m_pDisplay); // write out or update display to frame buffer /* * Close file */ if( fclose( infile ) ) AfxMessageBox( "The input file was not closed\n" ); if( fclose( outfile ) ) AfxMessageBox( "The output file was not closed\n" ); if (status) return(GZ_FAILURE); else return(GZ_SUCCESS); }
/** * @brief Set the foreground VM * * @param domid The domain ID of the port to put in the foreground * @return 0 on success */ int igvt_set_foreground_vm(unsigned int domid) { FILE *fd; char path[128]; struct stat st; int retval = 0; int n, r = -1; int status; if (domid != 0) { snprintf(path, sizeof(path), VGT_KERNEL_PATH "/vm%d", domid); if (stat(path, &st) != 0) { igvt_printf(IGVT_WARNING, "%s::VM %d at %s doesn't exist\n", __func__, domid, path); return -EINVAL; } } /* Check to see if the fg vm needs to change */ fd = fopen(VGT_KERNEL_PATH "/control/foreground_vm", "r"); if (!fd) { igvt_printf(IGVT_WARNING, "::%s Foreground VM file " VGT_KERNEL_PATH "/control/foreground_vm can't be open for read\n", __func__); return -ENODEV; } n = fscanf(fd, "%d", &r); fclose(fd); if (n == 1 && r == domid) { /* No change required. */ return 0; } /* We need to change the fg vm. */ fd = fopen(VGT_KERNEL_PATH "/control/foreground_vm", "w"); if (!fd) { igvt_printf(IGVT_WARNING, "::%s Foreground VM file " VGT_KERNEL_PATH "/control/foreground_vm can't be open for write\n", __func__); return -ENODEV; } status = fprintf(fd, "%d", domid); if (status <= 0) { igvt_printf(IGVT_WARNING, "%s::fprintf returned %d, error: %s\n", __func__, status, strerror(errno)); } status = fclose(fd); if (status < 0) { igvt_printf(IGVT_WARNING, "%s::fclose returned %d, error: %s\n", __func__, status, strerror(errno)); } /* check that it was actually set. */ fd = fopen(VGT_KERNEL_PATH "/control/foreground_vm", "r"); if (!fd) { igvt_printf(IGVT_WARNING, "%s::Foreground VM file " VGT_KERNEL_PATH "/control/foreground_vm can't be open for re-read\n", __func__); return -ENODEV; } n = fscanf(fd, "%d", &r); if (n != 1 || r != domid) { igvt_printf(IGVT_WARNING, "%s:: set DomID %d does not match " "returned DomID: %d nRead: %d\n", __func__, domid, r, n); retval = -EAGAIN; } fclose(fd); return retval; }
int main (int argc, char **argv) { FILE *fp; double **A = NULL, **B = NULL, **C = NULL, *A_array = NULL, *B_array = NULL, *C_array = NULL; double *A_local_block = NULL, *B_local_block = NULL, *C_local_block = NULL; int A_rows, A_columns, A_local_block_rows, A_local_block_columns, A_local_block_size; int B_rows, B_columns, B_local_block_rows, B_local_block_columns, B_local_block_size; int rank, size, sqrt_size, matrices_a_b_dimensions[4]; MPI_Comm cartesian_grid_communicator, row_communicator, column_communicator; MPI_Status status; // used to manage the cartesian grid int dimensions[2], periods[2], coordinates[2], remain_dims[2]; double init_time = 0.0, start; MPI_Init(&argc, &argv); start = MPI_Wtime(); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); /* For square mesh */ sqrt_size = (int)sqrt((double) size); if(sqrt_size * sqrt_size != size){ if( rank == 0 ) perror("need to run mpiexec with a perfect square number of processes\n"); MPI_Abort(MPI_COMM_WORLD, -1); } // create a 2D cartesian grid dimensions[0] = dimensions[1] = sqrt_size; periods[0] = periods[1] = 1; MPI_Cart_create(MPI_COMM_WORLD, 2, dimensions, periods, 1, &cartesian_grid_communicator); MPI_Cart_coords(cartesian_grid_communicator, rank, 2, coordinates); // create a row communicator remain_dims[0] = 0; remain_dims[1] = 1; MPI_Cart_sub(cartesian_grid_communicator, remain_dims, &row_communicator); // create a column communicator remain_dims[0] = 1; remain_dims[1] = 0; MPI_Cart_sub(cartesian_grid_communicator, remain_dims, &column_communicator); // getting matrices from files at rank 0 only // example: mpiexec -n 64 ./cannon matrix1 matrix2 [test] if (rank == 0){ int row, column; if ((fp = fopen (argv[1], "r")) != NULL){ fscanf(fp, "%d %d\n", &matrices_a_b_dimensions[0], &matrices_a_b_dimensions[1]); A = (double **) malloc (matrices_a_b_dimensions[0] * sizeof(double *)); for (row = 0; row < matrices_a_b_dimensions[0]; row++){ A[row] = (double *) malloc(matrices_a_b_dimensions[1] * sizeof(double)); for (column = 0; column < matrices_a_b_dimensions[1]; column++) fscanf(fp, "%lf", &A[row][column]); } fclose(fp); } else { if(rank == 0) fprintf(stderr, "error opening file for matrix A (%s)\n", argv[1]); MPI_Abort(MPI_COMM_WORLD, -1); } if((fp = fopen (argv[2], "r")) != NULL){ fscanf(fp, "%d %d\n", &matrices_a_b_dimensions[2], &matrices_a_b_dimensions[3]); B = (double **) malloc (matrices_a_b_dimensions[2] * sizeof(double *)); for(row = 0; row < matrices_a_b_dimensions[2]; row++){ B[row] = (double *) malloc(matrices_a_b_dimensions[3] * sizeof(double *)); for(column = 0; column < matrices_a_b_dimensions[3]; column++) fscanf(fp, "%lf", &B[row][column]); } fclose(fp); } else { if(rank == 0) fprintf(stderr, "error opening file for matrix B (%s)\n", argv[2]); MPI_Abort(MPI_COMM_WORLD, -1); } // need to check that the multiplication is possible given dimensions // matrices_a_b_dimensions[0] = row size of A // matrices_a_b_dimensions[1] = column size of A // matrices_a_b_dimensions[2] = row size of B // matrices_a_b_dimensions[3] = column size of B if(matrices_a_b_dimensions[1] != matrices_a_b_dimensions[2]){ if(rank == 0) fprintf(stderr, "A's column size (%d) must match B's row size (%d)\n", matrices_a_b_dimensions[1], matrices_a_b_dimensions[2]); MPI_Abort(MPI_COMM_WORLD, -1); } // this implementation is limited to cases where thematrices can be partitioned perfectly if( matrices_a_b_dimensions[0] % sqrt_size != 0 || matrices_a_b_dimensions[1] % sqrt_size != 0 || matrices_a_b_dimensions[2] % sqrt_size != 0 || matrices_a_b_dimensions[3] % sqrt_size != 0 ){ if(rank == 0) fprintf(stderr, "cannot distribute work evenly among processe\n" "all dimensions (A: r:%d c:%d; B: r:%d c:%d) need to be divisible by %d\n", matrices_a_b_dimensions[0],matrices_a_b_dimensions[1], matrices_a_b_dimensions[2],matrices_a_b_dimensions[3], sqrt_size ); MPI_Abort(MPI_COMM_WORLD, -1); } } // send dimensions to all peers /* @collectives: * MPI_Broadcast */ MPI_Bcast(matrices_a_b_dimensions, 4, MPI_INT, 0, cartesian_grid_communicator); A_rows = matrices_a_b_dimensions[0]; A_columns = matrices_a_b_dimensions[1]; B_rows = matrices_a_b_dimensions[2]; B_columns = matrices_a_b_dimensions[3]; // local metadata for A A_local_block_rows = A_rows / sqrt_size; A_local_block_columns = A_columns / sqrt_size; A_local_block_size = A_local_block_rows * A_local_block_columns; A_local_block = (double *) malloc (A_local_block_size * sizeof(double)); // local metadata for B B_local_block_rows = B_rows / sqrt_size; B_local_block_columns = B_columns / sqrt_size; B_local_block_size = B_local_block_rows * B_local_block_columns; B_local_block = (double *) malloc (B_local_block_size * sizeof(double)); // local metadata for C C_local_block = (double *) malloc (A_local_block_rows * B_local_block_columns * sizeof(double)); // C needs to be initialized at 0 (accumulates partial dot-products) int i; for(i=0; i < A_local_block_rows * B_local_block_columns; i++){ C_local_block[i] = 0; } // full arrays only needed at root if(rank == 0){ A_array = (double *) malloc(sizeof(double) * A_rows * A_columns); B_array = (double *) malloc(sizeof(double) * B_rows * B_columns); C_array = (double *) malloc(sizeof(double) * A_rows * B_columns); // generate the 1D arrays of the matrices at root int row, column, i, j; for (i = 0; i < sqrt_size; i++){ for (j = 0; j < sqrt_size; j++){ for (row = 0; row < A_local_block_rows; row++){ for (column = 0; column < A_local_block_columns; column++){ A_array[((i * sqrt_size + j) * A_local_block_size) + (row * A_local_block_columns) + column] = A[i * A_local_block_rows + row][j * A_local_block_columns + column]; } } for (row = 0; row < B_local_block_rows; row++){ for (column = 0; column < B_local_block_columns; column++){ B_array[((i * sqrt_size + j) * B_local_block_size) + (row * B_local_block_columns) + column] = B[i * B_local_block_rows + row][j * B_local_block_columns + column]; } } } } // allocate output matrix C C = (double **) malloc(A_rows * sizeof(double *)); for(i=0; i<A_rows ;i++){ C[i] = (double *) malloc(B_columns * sizeof(double)); } } // send a block to each process /* @collectives: /* MPI_Scatter with sendcount=A/B_local_block_size. The if-else clause and the for-loops can be replaced. */ { //compute displacements int row_displs[size]; // displacements for A int col_displs[size]; // displacements for B int row, col; for(row = 0; row < sqrt_size; ++row) { for(col = 0; col < sqrt_size; ++col) { int i = row*sqrt_size + col; if(row != 0) { int col_loc = (col + sqrt_size - row) % sqrt_size; row_displs[i] = row*sqrt_size + col_loc; } else { row_displs[i] = i; } row_displs[i] *= A_local_block_size; if(col != 0) { int row_loc = (row + sqrt_size - col) % sqrt_size; col_displs[i] = row_loc*sqrt_size + col; } else { col_displs[i] = i; } col_displs[i] *= B_local_block_size; } } // set counts for scattering A; int counts[size]; int i; for(i = 0; i < size; ++i) { counts[i] = A_local_block_size; } MPI_Scatterv(A_array, counts, row_displs, MPI_DOUBLE, A_local_block, A_local_block_size, MPI_DOUBLE, 0, cartesian_grid_communicator); for(i = 0; i < size; ++i) { counts[i] = B_local_block_size; } MPI_Scatterv(B_array, counts, col_displs, MPI_DOUBLE, B_local_block, B_local_block_size, MPI_DOUBLE, 0, cartesian_grid_communicator); } init_time += MPI_Wtime() - start; // cannon's algorithm int cannon_block_cycle; double compute_time = 0, mpi_time = 0; int C_index, A_row, A_column, B_column; for(cannon_block_cycle = 0; cannon_block_cycle < sqrt_size; cannon_block_cycle++){ // compute partial result for this block cycle start = MPI_Wtime(); for(C_index = 0, A_row = 0; A_row < A_local_block_rows; A_row++){ for(B_column = 0; B_column < B_local_block_columns; B_column++, C_index++){ for(A_column = 0; A_column < A_local_block_columns; A_column++){ C_local_block[C_index] += A_local_block[A_row * A_local_block_columns + A_column] * B_local_block[A_column * B_local_block_columns + B_column]; } } } compute_time += MPI_Wtime() - start; start = MPI_Wtime(); // rotate blocks horizontally MPI_Sendrecv_replace(A_local_block, A_local_block_size, MPI_DOUBLE, (coordinates[1] + sqrt_size - 1) % sqrt_size, 0, (coordinates[1] + 1) % sqrt_size, 0, row_communicator, &status); // rotate blocks vertically MPI_Sendrecv_replace(B_local_block, B_local_block_size, MPI_DOUBLE, (coordinates[0] + sqrt_size - 1) % sqrt_size, 0, (coordinates[0] + 1) % sqrt_size, 0, column_communicator, &status); mpi_time += MPI_Wtime() - start; } // get C parts from other processes at rank 0 /* @collectives: * MPI_Gather with sendcount=A_local_block_rows * B_local_block_columns */ double output_time = 0.0; start = MPI_Wtime(); MPI_Gather(C_local_block, A_local_block_rows * B_local_block_columns, MPI_DOUBLE, C_array, A_local_block_rows * B_local_block_columns, MPI_DOUBLE, 0, cartesian_grid_communicator); output_time += MPI_Wtime() - start; // generating output at rank 0 if (rank == 0) { // convert the ID array into the actual C matrix int i, j, k, row, column; for (i = 0; i < sqrt_size; i++){ // block row index for (j = 0; j < sqrt_size; j++){ // block column index for (row = 0; row < A_local_block_rows; row++){ for (column = 0; column < B_local_block_columns; column++){ C[i * A_local_block_rows + row] [j * B_local_block_columns + column] = C_array[((i * sqrt_size + j) * A_local_block_rows * B_local_block_columns) + (row * B_local_block_columns) + column]; } } } } printf("(%d,%d)x(%d,%d)=(%d,%d)\n", A_rows, A_columns, B_rows, B_columns, A_rows, B_columns); printf("Computation time: %lf\n", compute_time); printf("MPI time: %lf\n", mpi_time); printf("Setup time: %lf\n", init_time); printf("Output time: %lf\n", output_time); if (argc == 4){ // present results on the screen printf("\nA( %d x %d ):\n", A_rows, A_columns); for(row = 0; row < A_rows; row++) { for(column = 0; column < A_columns; column++) printf ("%7.3f ", A[row][column]); printf ("\n"); } printf("\nB( %d x %d ):\n", B_rows, B_columns); for(row = 0; row < B_rows; row++){ for(column = 0; column < B_columns; column++) printf("%7.3f ", B[row][column]); printf("\n"); } printf("\nC( %d x %d ) = AxB:\n", A_rows, B_columns); for(row = 0; row < A_rows; row++){ for(column = 0; column < B_columns; column++) printf("%7.3f ",C[row][column]); printf("\n"); } printf("\nPerforming serial consistency check. Be patient...\n"); fflush(stdout); int pass = 1; double temp; for(i=0; i<A_rows; i++){ for(j=0; j<B_columns; j++){ temp = 0; for(k=0; k<B_rows; k++){ temp += A[i][k] * B[k][j]; } printf("%7.3f ", temp); if(temp != C[i][j]){ pass = 0; } } printf("\n"); } if (pass) printf("Consistency check: PASS\n"); else printf("Consistency check: FAIL\n"); } } // free all memory if(rank == 0){ int i; for(i = 0; i < A_rows; i++){ free(A[i]); } for(i = 0; i < B_rows; i++){ free(B[i]); } for(i = 0; i < A_rows; i++){ free(C[i]); } free(A); free(B); free(C); free(A_array); free(B_array); free(C_array); } free(A_local_block); free(B_local_block); free(C_local_block); // finalize MPI MPI_Finalize(); }
int main(int argc, char *argv) { FILE *fp; fp = fopen("arquivo.txt","w+"); pid_t pid; printf("%d. Pai\n\n", getpid()); pid = fork(); //Filho 1 if(pid == 0) { printf("%d. Filho1\n", getpid()); int n = rand()/1320; fprintf(fp, "%d\n%d\n", chute(n, 1), n); } if(pid > 0) { pid_t pid2; pid2 = fork(); //Filho 2 if(pid2 == 0) { printf("%d. Filho2\n", getpid()); int n = rand()/166; fprintf(fp, "%d\n%d\n", chute(n, 666666), n); } wait(NULL); //Espera Filho 1 if(pid2 > 0) { wait(NULL); //Espera Filho 2 //Pai FILE *entrada; entrada = fopen ("arquivo.txt", "r"); char le[20], ne[200], ce[20]; int c, n, i, j; i = 0; j = 0; c = 0; n = 0; while (!feof(entrada)) { fscanf(entrada,"%c",&le[0]); if(le[0] == '\n') { if(i == 0) { n += atoi(ne); j = 0; i = 1; *ne = '\0'; } else { c += atoi(ce); j = 0; i = 0; *ce = '\0'; } } else { if(i == 0) { ne[j] = le[0]; j++; } else { ce[j] = le[0]; j++; } } } fclose (entrada); printf("PI => 4*(%d/%d) = %g\n", n, c, (double)n * 4.0 / c); } } fclose(fp); return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { char InputName[32] = {}, OutputName[32] = {}; switch (argc) { case 1: strcpy(InputName, "code"); strcpy(OutputName, "programm.txt"); break; case 2: if (strcmp(argv[1], "--version") == 0) { printf("Version: %s", Version); return 2; } if (strcmp(argv[1], "--help") == 0) { print_help(); return 1; } strcpy(InputName, argv[1]); strcpy(OutputName, argv[1]); break; case 3: strcpy(InputName, argv[1]); strcpy(OutputName, argv[2]); break; default: print_help(); return 1; } strcat(OutputName, ".bin"); FILE* fInput = fopen(InputName, "rb"); if (fInput == nullptr) return perror("Can't open Input file \nErrno"), 3; FILE* fOutput = fopen(OutputName, "wb"); if (fOutput == nullptr) return perror("Can't open Output file\nErrno"), 4; char str = 0; while (fscanf(fInput, "%d", str) != EOF) { printf("%d ", str); #define DEF_CMD(name, num, code, codeAsm, codeDisasm)\ if(str == num)\ {\ fprintf(fOutput, #name" ");\ codeDisasm;\ fprintf(fOutput, "\n");\ }\ else #include "CmdList.h" { printf("Error: Unknown command\n"); fprintf(fOutput, "[Unknown command] "); } } fclose(fInput); fclose(fOutput); printf("Programm was written into %s.\n", OutputName); return 0; }
/* int checkExpiry(passenger p) { return 0; } int checkVisa(passenger p) { return 1; } */ int main() { printf("Airport Simulation System.\nThe system may wait for few seconds in between. \n"); pipe(restpipe); pipe(cafepipe); int secpip[2]; char secbuf[10]; pid_t baggage,immig,sec,lounge,board,lug,wt,pass; //taking number of passengers here so as to malloc now before passing as function FILE *fp = fopen("input.txt","r"); fscanf(fp," %d",&num); plist = (passenger *)malloc(num*sizeof(passenger)); inputAll(plist); //input from file over int extraCost=0; boarding = fork(); if(!boarding) { signal(SIGUSR1,addLoungers); signal(SIGUSR2,removeLoungers); raise(SIGSTOP); printf("\nAll passengers are requested to move to the Gate.\n"); if(loungers !=0) printf("this is the last boarding call for passengers. please report immediately to the gate\n"); sleep(2); kill(getppid(),SIGUSR2); exit(0); } lounge = fork(); if(!lounge) { cafe = fork(); if(cafe) { rest = fork(); if(!rest) //in restroom process { signal(SIGUSR1,gotorest); while(1); } } else //in cafe process { signal(SIGUSR1,gotocafe); while(1); } while( i < num ) { raise(SIGSTOP); srand(time(NULL)); int choice = rand()%3; //3 because it is not necessary he has to go to cafe or airport if(choice ==0) //go to cafe { sprintf(cafebuf,"%s",plist[i].flt.ticket_no); write(cafepipe[1],cafebuf,15); kill(cafe,SIGUSR1); } else if(choice ==1) { //go to restroom sprintf(restbuf,"%s",plist[i].flt.ticket_no); write(restpipe[1],restbuf,15); kill(rest,SIGUSR1); } i++; } kill(boarding,SIGCONT); raise(SIGSTOP); kill(cafe,SIGKILL); kill(rest,SIGKILL); exit(0); } checksec = fork(); if(!checksec) { //why pipe? we do not know the value of i inside the child processes. //so every time a passenger comes in, we can update the value on a pipe and children can see it. pipe(secpip); while( i < num ) { raise(SIGSTOP); sleep(1); if(i==0) { secm= fork(); if(secm) secf=fork(); } if(secm && secf) { sleep(1); sprintf(secbuf,"%d",i); write(secpip[1],secbuf,10); if(plist[i].gender=='M') kill(secm,SIGCONT); else kill(secf,SIGCONT); } if(secm==0 ) { while(1) { raise(SIGSTOP); sleep(1); read(secpip[0],secbuf,10); printf("Invalid items in hand bag of male %d: ",atoi(secbuf)); checkMFbag(plist[atoi(secbuf)]); kill(getppid(),SIGCONT); } } if(secm && secf==0 ) { while(1) { raise(SIGSTOP); sleep(1); read(secpip[0],secbuf,10); printf("Invalid items in hand bag of female %d: ",atoi(secbuf)); checkMFbag(plist[atoi(secbuf)]); kill(getppid(),SIGCONT); } } raise(SIGSTOP); //so that when sec_M or sec_F calls it, it has ample time to raise itself sleep(1); kill(lounge,SIGCONT); i++; } kill(secm,SIGKILL); kill(secf,SIGKILL); exit(0); } if(checksec ==0) //go into male and female security check { while( i < num ) { raise(SIGSTOP); sleep(1); kill(lounge,SIGCONT); i++; } exit(0); } immigration = fork(); if(immigration == 0) { //pipe(impipe); while( i < num ) { raise(SIGSTOP); printf("checking immigration of %d\n",i); /* if(i==0) { visa = fork(); if(visa) passport = fork(); } if(visa && passport) { sleep(1); kill(passport,SIGCONT); } if(!passport) { while(1) { raise(SIGSTOP); sleep(.5); if(checkPass(plist[i])) { sprintf(imbuf,"%d",i,10); write(impipe[1],imbuf,10); kill(visa,SIGCONT); } else { plist[i].valid = 0; FILE *fp = fopen(plist[i].flt.ticket_no,"a"); fprintf(fp,"Immigration not successful\n"); fclose(fp); kill(getppid(),SIGCONT); } i++; } } if(!visa) { while(1) { raise(SIGSTOP); sleep(0.5); read(impipe[0],imbuf,10); if(checkVisa(plist[atoi(imbuf)])) { FILE *fp = fopen(plist[atoi(imbuf)].flt.ticket_no,"a"); fprintf(fp,"Immigration successful\n"); fclose(fp); } else { plist[atoi(imbuf)].valid = 0; FILE *fp = fopen(plist[atoi(imbuf)].flt.ticket_no,"a"); fprintf(fp,"Immigration not successful\n"); fclose(fp); } kill(getppid(),SIGCONT); } } raise(SIGSTOP); */ sleep(2); kill(checksec,SIGCONT); i++; } //kill(visa,SIGKILL); //kill(passport,SIGKILL); exit(0); } bcounter = fork(); if(bcounter && immigration && checksec && lounge && boarding) signal(SIGUSR2,sigtoStop); //this is for mother process(airport). this is for when final stop if(bcounter == 0) { int p1[2],p2[2]; char buf1[10],buf2[10]; //buf1 for pipe(p1); pipe(p2); while( i < num ) { if(i==0) { boardpass = fork(); if(boardpass) weight = fork(); if(boardpass && weight) lugsec = fork(); } if(boardpass == 0) //going into boarding pass process.called after baggage price calc { raise(SIGSTOP); if(i == 0) { sleep(2); close(p1[1]); read(p1[0],buf1,10); weight = atoi(buf1); //getting weight's pid so that he can be called } sleep(1); makePass(plist[i]); kill(weight,SIGCONT); i++; if(i == num) exit(0); continue; } if(weight == 0) { sleep(1); raise(SIGSTOP); //will be called by boarding pass to print extra cost. extraCost = checkExtraCost(plist[i]); //todo printf("Extra cost = Rs.%d\n",extraCost); sleep(2); kill(boardpass,SIGCONT); //returning raise(SIGSTOP); addCostoFile(plist[i],extraCost); //appended extra cost if(i == 0) { sleep(1); close(p2[1]); read(p2[0],buf2,10); lugsec = atoi(buf2); } kill(lugsec,SIGCONT); i++; if(i == num) //exiting if all passengers have finished passing baggage counter exit(0); continue; } if(i == 0) { sprintf(buf1,"%d",weight); close(p1[0]); write(p1[1],buf1,10); } if(lugsec == 0) { sleep(1); checkLuggage(plist,i); sleep(2); kill(weight,SIGCONT); //sending to weight raise(SIGSTOP); //waiting int nt = plist[i].num_bags,it,jt; for(it=0;it<nt;it++) { for(jt=0;jt<10;jt++) { if(plist[i].explosives[it][jt] ==1) printf("%d ",plist[i].content[it][jt]); } printf("\n"); } appendBaggageID(plist[i]); kill(immigration,SIGCONT); //baggage counter sending to immigration i++; if( i == num ) { exit(0); } continue; } if(i == 0) { sprintf(buf2,"%d",lugsec); close(p2[0]); write(p2[1],buf2,10); } i++; } } while(wait(NULL)!=-1); return 0; }
FLANDMARK_Model * flandmark_init(const char* filename) { int *p_int = 0, tsize = -1, tmp_tsize = -1; uint8_t *p_uint8 = 0; FILE *fin; if ((fin = fopen(filename, "rb")) == NULL) { printf("Error opening file %s\n", filename); return 0; } // allocate memory for FLANDMARK_Model FLANDMARK_Model * tst = (FLANDMARK_Model*)malloc(sizeof(FLANDMARK_Model)); //int fscan_ret = -1; if (fscanf(fin, " %c ", &tst->data.options.M) < 1) { return 0; } if (fscanf(fin, " %d %d ", &tst->data.options.bw[0], &tst->data.options.bw[1]) < 2) { return 0; } if (fscanf(fin, " %d %d ", &tst->data.options.bw_margin[0], &tst->data.options.bw_margin[1]) < 2) { return 0; } if (fscanf(fin, " %d %d ", &tst->W_ROWS, &tst->W_COLS) < 2) { return 0; } if (fscanf(fin, " %d %d ", &tst->data.imSize[0], &tst->data.imSize[1]) < 2) { return 0; } int M = tst->data.options.M; tst->data.lbp = (FLANDMARK_LBP*)malloc(M*sizeof(FLANDMARK_LBP)); for (int idx = 0; idx < M; ++idx) { if (fscanf(fin, " %d %d ", &tst->data.lbp[idx].WINS_ROWS, &tst->data.lbp[idx].WINS_COLS) < 2) { return 0; } } for (int idx = 0; idx < 3; ++idx) { if (fscanf(fin, " %d %d ", &tst->data.options.PSIG_ROWS[idx], &tst->data.options.PSIG_COLS[idx]) < 2) { return 0; } } // load model.W ----------------------------------------------------------- tst->W = (double*)malloc(tst->W_ROWS * sizeof(double)); if (fread(tst->W, tst->W_ROWS * sizeof(double), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; } // load model.data.mapTable ----------------------------------------------- p_int = (int*)malloc(M*4*sizeof(int)); tst->data.mapTable = (int*)malloc(M*4*sizeof(int)); if (fread(p_int, M*4*sizeof(int), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; } for (int i = 0; i < M*4; ++i) { tst->data.mapTable[i] = p_int[i]; } free(p_int); // load model.data.lbp --------------------------------------------------- for (int idx = 0; idx < M; ++idx) { // lbp{idx}.winSize p_int = (int*)malloc(2*sizeof(int)); if (fread(p_int, 2*sizeof(int), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; } for (int i = 0; i < 2; ++i) { tst->data.lbp[idx].winSize[i] = p_int[i]; } free(p_int); // lbp{idx}.hop p_uint8 = (uint8_t*)malloc(sizeof(uint8_t)); if (fread(p_uint8, sizeof(uint8_t), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; } tst->data.lbp[idx].hop = p_uint8[0]; free(p_uint8); // lbp{idx}.wins tsize = tst->data.lbp[idx].WINS_ROWS*tst->data.lbp[idx].WINS_COLS; tst->data.lbp[idx].wins = (uint32_t*)malloc(tsize * sizeof(uint32_t)); if (fread(tst->data.lbp[idx].wins, tsize * sizeof(uint32_t), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; //exit(1); } } // load model.options.S -------------------------------------------------- p_int = (int*)malloc(4*M*sizeof(int)); tst->data.options.S = (int*)malloc(4*M*sizeof(int)); if (fread(p_int, 4*M*sizeof(int), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; //exit(1); } for (int i = 0; i < 4*M; ++i) { tst->data.options.S[i] = p_int[i]; } free(p_int); // load model.options.PsiG ----------------------------------------------- FLANDMARK_PSIG * PsiGi = NULL; for (int psigs_idx = 0; psigs_idx < 3; ++psigs_idx) { tsize = tst->data.options.PSIG_ROWS[psigs_idx]*tst->data.options.PSIG_COLS[psigs_idx]; switch (psigs_idx) { case 0: tst->data.options.PsiGS0 = (FLANDMARK_PSIG*)malloc(tsize*sizeof(FLANDMARK_PSIG)); PsiGi = tst->data.options.PsiGS0; break; case 1: tst->data.options.PsiGS1 = (FLANDMARK_PSIG*)malloc(tsize*sizeof(FLANDMARK_PSIG)); PsiGi = tst->data.options.PsiGS1; break; case 2: tst->data.options.PsiGS2 = (FLANDMARK_PSIG*)malloc(tsize*sizeof(FLANDMARK_PSIG)); PsiGi = tst->data.options.PsiGS2; break; } for (int idx = 0; idx < tsize; ++idx) { // disp ROWS p_int = (int*)malloc(sizeof(int)); if (fread(p_int, sizeof(int), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; //exit(1); } PsiGi[idx].ROWS = p_int[0]; free(p_int); // disp COLS p_int = (int*)malloc(sizeof(int)); if (fread(p_int, sizeof(int), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; //exit(1); } PsiGi[idx].COLS = p_int[0]; free(p_int); // disp tmp_tsize = PsiGi[idx].ROWS*PsiGi[idx].COLS; PsiGi[idx].disp = (int*)malloc(tmp_tsize*sizeof(int)); if (fread(PsiGi[idx].disp, tmp_tsize*sizeof(int), 1, fin) != 1) { printf( "Error reading file %s\n", filename); return 0; //exit(1); } } } fclose(fin); tst->normalizedImageFrame = (uint8_t*)calloc(tst->data.options.bw[0]*tst->data.options.bw[1], sizeof(uint8_t)); tst->bb = (double*)calloc(4, sizeof(double)); tst->sf = (float*)calloc(2, sizeof(float)); return tst; }
double calc_misfit(float **sectiondiff, int ntr, int ns, int LNORM, float L2, int ntr_glob, int **recpos_loc, int nsrc_glob, int ishot){ /* declaration of variables */ extern float DT; extern int MYID; extern int TRKILL; extern char TRKILL_FILE[STRING_SIZE]; int i,j; float l2; float L2_dummy; int umax=0, h; /* declaration of variables for trace killing */ int ** kill_tmp, *kill_vector; char trace_kill_file[STRING_SIZE]; FILE *ftracekill; if(TRKILL){ kill_tmp = imatrix(1,ntr_glob,1,nsrc_glob); kill_vector = ivector(1,ntr); ftracekill=fopen(TRKILL_FILE,"r"); if (ftracekill==NULL) err(" Trace kill file could not be opened!"); for(i=1;i<=ntr_glob;i++){ for(j=1;j<=nsrc_glob;j++){ fscanf(ftracekill,"%d",&kill_tmp[i][j]); } } fclose(ftracekill); h=1; for(i=1;i<=ntr;i++){ kill_vector[h] = kill_tmp[recpos_loc[3][i]][ishot]; h++; } } /* end if(TRKILL)*/ /* calculate misfit for misfit function 1-6 */ for(i=1;i<=ntr;i++){ if((TRKILL==1)&&(kill_vector[i]==1)) continue; for(j=1;j<=ns;j++){ /* calculate norm */ if((LNORM==2) || (LNORM==6)){ L2+=sectiondiff[i][j]*sectiondiff[i][j]; } } /* end of loop over time samples */ } /* end of loop over traces */ l2=L2; return l2; /* free memory for trace killing */ if(TRKILL){ free_imatrix(kill_tmp,1,ntr_glob,1,nsrc_glob); free_ivector(kill_vector,1,ntr); } }
int update(void* canvas) { char buffer[6]; size_t cindex; uint8_t nindex; Client* node1; Client* node2; if(fscanf(stdin, "%s", buffer) && strcmp(buffer,"END")) { if(!strcmp(buffer, "LINK")) { if(!fscanf(stdin,"%zu", &cindex)) { free(decisions); return 0; } if(!fscanf(stdin,"%hhu",&nindex)) { free(decisions); return 0; } node1 = the_layout -> zones[cindex] -> buildings[nindex]; if(!fscanf(stdin,"%hhu",&nindex)) { free(decisions); return 0; } node2 = the_layout -> zones[cindex] -> buildings[nindex]; struct choice c; c.choser = node1; c.chosee = node2; c.tinted = NULL; city_client_link(node1, node2); // node_link_print(node1, node2); if(node1 -> color != node2 -> color) { if(node1 -> color) { client_paint(node2, node1 -> color); c.tinted = node2; } else { client_paint(node1, node2 -> color); c.tinted = node1; } } decisions[decision_count++] = c; } else if(!strcmp(buffer,"UNDO")) { struct choice c = decisions[--decision_count]; city_client_link_undo(c.choser, c.chosee); if(c.tinted) { client_paint(c.tinted, none); } } else { free(decisions); return 0; } /* TODO mandar a actualizar solo lo que ha cambiado */ gtk_widget_queue_draw(canvas); } else { free(decisions); return 0; } return 1; }
// Génère les fichiers c.jo et c.joa void genereFichierJo19(char c) { int mesamplifront[2]; //son du n, la référence int mesdurerfront[2]; //son du n, la référence int mesvarampli[2]; //son du n, la référence int mesvardurer[2]; //son du n, la référence int madurer; //son du n, la référence int maforceh; int maforceb; int montremolo; int maforceplus; int macombiendezonememoire; FILE* fichierdesfronts = NULL; fichierdesfronts = fopen("fronts.txt", "r"); if (fichierdesfronts != NULL) { fscanf(fichierdesfronts, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d", &mesamplifront[0], &mesamplifront[1], &mesdurerfront[0], &mesdurerfront[1], &mesvarampli[0], &mesvarampli[1], &mesvardurer[0], &mesvardurer[1], &madurer, &maforceh, &maforceb, &montremolo, &maforceplus, &macombiendezonememoire); fclose(fichierdesfronts); } /**********************************************/ jo joc = mesjo[c-'a']; // Nom du fichier jo char nomfichierjo[32]; snprintf(nomfichierjo, 32, "%c.jo", c); // Fichier jo FILE* fichierjo; if (!(fichierjo = fopen(nomfichierjo, "wb"))) { exit(-1); } // ici commence la zone de travail pour l'apprenant mesdurerfront[0] = ((joc.lagame * mesdurerfront[0]) * 0.01); mesdurerfront[1] = ((joc.lagame * mesdurerfront[1]) * 0.01); int tablex[250]= {120, 60, 40, 30, 24, 20, 17, 15, 13, 12, 11, 10, 9, 9, 8, 8, 7, 7, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; int calculpossible = tablex[maforceh-1]; int ajusteur1; int ajusteur2; // multiplie for(int duree = madurer; duree>0; duree--) { //monte for(int laforcebbase = maforceh; laforcebbase > 0; laforcebbase--) { mesamplifront[1] -= calculpossible; mesamplifront[0] += calculpossible; // respect des limites for(int i=0; i<2; i++) { if(mesamplifront[i]>239) mesamplifront[i] = 239; if(mesamplifront[i]<16) mesamplifront[i] = 16; } ajusteur1 = mesamplifront[0] - 2; ajusteur2 = mesamplifront[1] + 2; fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)ajusteur1, (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)ajusteur2, (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); for(int laforcebbasev = maforceplus; laforcebbasev > 0; laforcebbasev--) { fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)ajusteur1, (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)ajusteur2, (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); } } //plateau int basculeDe1 = montremolo * 2; int basculeDe2 = basculeDe1 - 1; int basculeDe3 = basculeDe1 * 2 - 1; int basculeDe5 = 0; for(int laforcebbase = maforceb; laforcebbase > 0; laforcebbase--) { if(basculeDe5<basculeDe1) { mesdurerfront[0] += mesvardurer[0]; mesamplifront[0] -= mesvarampli[0]; ajusteur1 -= mesvarampli[0]; mesdurerfront[1] += mesvardurer[1]; mesamplifront[1] += mesvarampli[1]; ajusteur2 += mesvarampli[1]; } if(basculeDe5>basculeDe2) { mesdurerfront[0] -= mesvardurer[0]; mesamplifront[0] += mesvarampli[0]; ajusteur1 += mesvarampli[0]; mesdurerfront[1] -= mesvardurer[1]; mesamplifront[1] -= mesvarampli[1]; ajusteur2 -= mesvarampli[1]; } basculeDe5++; if(basculeDe5>basculeDe3) basculeDe5 = 0; fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)ajusteur1, (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)ajusteur2, (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)ajusteur1, (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)ajusteur2, (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[0]); for(int laforcebbasev = maforceplus; laforcebbasev > 0; laforcebbasev--) { fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)ajusteur1, (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)ajusteur2, (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)ajusteur1, (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)ajusteur2, (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[0]); } } //descend for(int laforcebbase = maforceh; laforcebbase > 0; laforcebbase--) { mesamplifront[1] += calculpossible; mesamplifront[0] -= calculpossible; // respect des limites for(int i=0; i<2; i++) { if(mesamplifront[i]>239) mesamplifront[i] = 239; if(mesamplifront[i]<16) mesamplifront[i] = 16; } ajusteur1 = mesamplifront[0] - 2; ajusteur2 = mesamplifront[1] + 2; fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)ajusteur1, (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)ajusteur2, (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); for(int laforcebbasev = maforceplus; laforcebbasev > 0; laforcebbasev--) { fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)ajusteur1, (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[0], (char)mesdurerfront[0]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)ajusteur2, (char)mesdurerfront[1]); fprintf(fichierjo, "%c%c", (char)mesamplifront[1], (char)mesdurerfront[1]); } } // fin multiplie } fclose(fichierjo); }
int main(int argc, char *argv[]) { int warn, i, j, nread, NUMBER_OF_SIGMA_BINS; double X_s, I_R, s, R[90], R_arcmin[90], sig_p[90], a_dm, a_s, M_s, M_dm, beta; double R_o[12], sig_p_o[12], numb_error[12], chi2, a_dm_min, a_s_min, M_dm_min, M_s_min, beta_min, sig_p_i; double chi_min = 100000000000000000.0; double gamma, gamma_min, aux; char *infile; FILE *script,*sigma,*best_model,*results; double gamma_ini, gamma_end, Delta_gamma; double adm_ini, adm_end, Delta_adm; double as_ini, as_end, Delta_as; double Mdm_ini, Mdm_end, Delta_Mdm; double Ms_ini, Ms_end, Delta_Ms; double beta_ini, beta_end, Delta_beta; infile = argv[1]; // INPUT FIL WITH VELOCITY DISPERSION BINS NUMBER_OF_SIGMA_BINS = atoi(argv[2]); // EVENTUALLY 12! if(argc != 3) { printf(" Execute as ./exec <infile> <number of lines>\n"); // THIS WILL TELL HOW TO PROPERLY DO THE EXECUTION exit(0); } // READ THE FILE WITH THE OBSERVATIONAL DATA sigma=fopen(infile,"r"); for(j=0.0; j<NUMBER_OF_SIGMA_BINS; j++) nread = fscanf(sigma,"%lf %lf %lf", &R_o[j], &sig_p_o[j], &numb_error[j]); fclose(sigma); // THE VARIATIONS OF THE PARAMETERS gamma_ini = 2.1; gamma_end = 2.5; Delta_gamma = 0.2; adm_ini = 14.0; adm_end = 18.0; Delta_adm = 0.2; as_ini = 49.0; as_end = 53.0; Delta_as = 0.2; Mdm_ini = 19.0; Mdm_end = 23.0; Delta_Mdm = 0.2; Ms_ini = 24.0; Ms_end = 28.0; Delta_Ms = 0.2; beta_ini = 0.4; beta_end = 0.8; Delta_beta = 0.2; // THIS LINE CALCULATES THE NUMBER OF ITERATIONS FOR THE USER'S REFERENCE int Ntotal_iterations, counter, cuenta; Ntotal_iterations = (int) ( ((beta_end-beta_ini)/Delta_beta)*((gamma_end-gamma_ini)/Delta_gamma)*((as_end-as_ini)/Delta_as)*((adm_end-adm_ini)/Delta_adm)*((Mdm_end-Mdm_ini)/Delta_Mdm)*((Ms_end-Ms_ini)/Delta_Ms) ); printf(" Running %d iterations in parameter space\n", Ntotal_iterations); counter=0; //DEFINITION OF THE VECTOR R[i] for(i=0;i<K;i++) { R[i] = (i+1.0); if(i==0) R[i] = R[i]*0.1; } for(beta = beta_ini; beta <= beta_end; beta = beta + Delta_beta) { for(gamma = gamma_ini; gamma <= gamma_end; gamma = gamma + Delta_gamma) { for(a_dm = adm_ini; a_dm <= adm_end; a_dm = a_dm + Delta_adm) { for(a_s = as_ini; a_s <= as_end; a_s = a_s + Delta_as) { // THIS IS TO AVOID INDETERMINATIONS IN SOME DENOMINATORS if (a_s != a_dm) { for(M_dm = Mdm_ini; M_dm < Mdm_end; M_dm = M_dm + Delta_Mdm) { for(M_s = Ms_ini; M_s < Ms_end; M_s = M_s + Delta_Ms) { for(i = 0; i < K; i ++) { evaluate_integral(R[i], beta, gamma, a_dm, a_s, M_dm, M_s, &sig_p[i], &R_arcmin[i]); //printf("%d R = %lf I=%lf\n",i, log10(R[i]), sig_p[i]); } // ALLOC MEMORY FOR THE INTERPOLATION IN EACH STEP gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, 90); gsl_spline_init (spline, R_arcmin, sig_p, 90); chi2 = 0.0; for(j=0; j<NUMBER_OF_SIGMA_BINS; j++) { sig_p_i = gsl_spline_eval (spline, R_o[j], acc); chi2 += ( (sig_p_i-sig_p_o[j])*(sig_p_i-sig_p_o[j]) ) / numb_error[j]; //printf("%16.8lf\t %16.8lf\n", sig_p_i, chi2); } // FREE MEMORY gsl_spline_free (spline); gsl_interp_accel_free (acc); // CALCULATION OF XI SQUARE TO FIND THE OPTIMIZED PARAMETERS if(chi2 < chi_min) { chi_min = chi2; a_dm_min = a_dm; a_s_min = a_s; M_dm_min = M_dm; M_s_min = M_s; gamma_min = gamma; beta_min = beta; } if((counter%1000) == 0) printf("Ready %d iterations of %d\n",counter, Ntotal_iterations); counter++; }// for Ms }// for Mdm }// if for the singularity }//for as }// for adm }//for gamma }//for beta //printf ("\n"); best_model=fopen("best_model.dat","w"); for(i = 0; i < K; i ++) { evaluate_integral(R[i], beta_min, gamma_min, a_dm_min, a_s_min, M_dm_min, M_s_min, &sig_p[i], &R_arcmin[i]); fprintf(best_model,"%16.8e %16.8e\n", R_arcmin[i], sig_p[i]); } fclose(best_model); // THIS ARE THE OPTIMIZED PARAMETERS printf("xi = %16.8lf\t beta = %16.8lf\t a_dm/pc = %16.8lf\t a_s/pc = %16.8lf\t M_dm/Msun = %16.8lf\t M_s/Msun = %16.8e\t gamma = %lf\n", chi_min, beta_min, a_dm_min, a_s_min, (1.0e5)*M_dm_min, (1.0e5)*M_s_min, gamma_min); results = fopen("results.dat", "w"); fprintf(results,"xi= %16.8lf\t beta= %16.8lf\t a_dm/pc= %16.8lf\t a_s/pc= %16.8lf\t M_dm/Msun= %16.8lf\t M_s/Msun= %16.8e\t gamma= %lf\n", chi_min, beta_min, a_dm_min, a_s_min, (1.0e5)*M_dm_min, (1.0e5)*M_s_min, gamma_min); fclose(results); script = fopen( "script.gpl", "w" ); fprintf( script, "plot 'sigma.dat'pt 7 ps 1.2\n" ); //fprintf( script, "replot 'best_model.dat' u 1:2 w l\n"); //fprintf( script, "reset\n"); fprintf(script, "set grid\nset terminal png\nset output 'sigma.png'\nset nokey\n"); fprintf( script, "set title 'Sigma Proyectada vs R'\n" ); fprintf( script, "set xrange [0:40]\n" ); fprintf( script, "set yrange [4:14]\n" ); fprintf( script, "set xlabel 'Radius in Arcmin'\n" ); fprintf( script, "set ylabel 'Projected velocity dispersion in km/s'\n" ); //fprintf( script, "plot 'sigma.dat'pt 7 ps 1.2\n" ); fprintf( script, "replot 'best_model.dat' u 1:2 w l\n"); //fprintf( script, "pause -1\n"); fclose(script); warn = system("gnuplot script.gpl"); return(warn); }
void LogReader::open(const std::string& filename) { _names.clear(); _units.clear(); _data.clear(); FILE* fp = fopen(filename.c_str(), "rb"); if (!fp) { throw std::runtime_error("Error opening " + filename); } int total_n_numbers, n_channels, n_points; if (fscanf(fp, "%d%d%d%f", &total_n_numbers, &n_channels, &n_points, &_frequency) != 4) { throw std::runtime_error("error reading header"); } if (total_n_numbers != n_channels * n_points) { throw std::runtime_error("failed sanity check n_channels * n_points"); } bool incomplete = (total_n_numbers == 0); _numTicks = n_points; char name[1024], unit[1024]; for (int i=0; i<n_channels; ++i) { if (fscanf(fp, "%1023s%1023s", name, unit) != 2) { throw std::runtime_error("error reading name/units"); } _names.push_back(name); _units.push_back(unit); } fscanf(fp, "%c%c%c", name, name, name); std::vector<char> rowbuffer; std::vector<float> rowmajor; rowbuffer.resize( 4 * n_channels ); int n_rows_read = 0; while (1) { size_t nread = fread(&(rowbuffer[0]), rowbuffer.size(), 1, fp); if (nread == 0) { if (incomplete || n_rows_read == n_points) { break; } else { throw std::runtime_error("error reading float data"); } } ++n_rows_read; const char* src = &(rowbuffer[0]); for (int i=0; i<n_channels; ++i) { float f; char* c = (char*)&f; for (int j=0; j<4; ++j) { c[3-j] = *src++; } rowmajor.push_back(f); } } if (incomplete) { _numTicks = n_points = n_rows_read; total_n_numbers = n_rows_read * n_channels; std::cerr << "warning: log file was incomplete, found " << _numTicks << " samples.\n"; } assert( int(rowmajor.size()) == total_n_numbers ); fclose(fp); // now transpose data _data.resize(total_n_numbers); for (int i=0; i<n_channels; ++i) { for (int j=0; j<n_points; ++j) { _data[i * n_points + j] = rowmajor[j * n_channels + i]; } } }
int main (int argc, char * argv[]){ /* file strucrures */ FILE * file_speech = NULL; FILE * file_encoded = NULL; FILE * file_mode = NULL; /* input speech vector */ short speech[160]; /* counters */ int byte_counter, frames = 0, bytes = 0; /* pointer to encoder state structure */ int *enstate; /* requested mode */ enum Mode req_mode = MR122; int dtx = 0; /* temporary variables */ char mode_string[9]; long mode_tmp; /* bitstream filetype */ #ifndef ETSI unsigned char serial_data[31]; #else short serial_data[250] = {0}; #endif /* Process command line options */ if ((argc == 5) || (argc == 4)){ file_encoded = fopen(argv[argc - 1], "wb"); if (file_encoded == NULL){ Usage(argv); return 1; } file_speech = fopen(argv[argc - 2], "rb"); if (file_speech == NULL){ fclose(file_encoded); Usage(argv); return 1; } if (strncmp(argv[argc - 3], "-modefile=", 10) == 0){ file_mode = fopen(&argv[argc - 3][10], "rt"); if (file_mode == NULL){ Usage(argv); fclose(file_speech); fclose(file_encoded); return 1; } } else { mode_tmp = strtol(&argv[argc - 3][2], NULL, 0); for (req_mode = 0; req_mode < 8; req_mode++){ if (mode_tmp == modeConv[req_mode]) break; } if (req_mode == 8){ Usage(argv); fclose(file_speech); fclose(file_encoded); if (file_mode != NULL) fclose(file_mode); return 1; } } if (argc == 5){ if ((strcmp(argv[1], "-dtx") != 0)){ Usage(argv); fclose(file_speech); fclose(file_encoded); if (file_mode != NULL){ fclose(file_mode); } return 1; } else { dtx = 1; } } } else { Usage(argv); return 1; } enstate = Encoder_Interface_init(dtx); Copyright(); #ifndef VAD2 fprintf( stderr, "%s\n", "Code compiled with VAD option: VAD1"); #else fprintf( stderr, "%s\n", "Code compiled with VAD option: VAD2"); #endif /* read file */ while (fread( speech, sizeof (Word16), 160, file_speech ) > 0) { /* read mode */ if (file_mode != NULL){ req_mode = 8; if (fscanf(file_mode, "%9s\n", mode_string) != EOF) { mode_tmp = strtol(&mode_string[2], NULL, 0); for (req_mode = 0; req_mode < 8; req_mode++){ if (mode_tmp == modeConv[req_mode]){ break; } } } if (req_mode == 8){ break; } } frames ++; /* call encoder */ byte_counter = Encoder_Interface_Encode(enstate, req_mode, speech, serial_data, 0); bytes += byte_counter; fwrite(serial_data, sizeof (UWord8), byte_counter, file_encoded ); fflush(file_encoded); } Encoder_Interface_exit(enstate); #ifndef ETSI fprintf ( stderr, "\n%s%i%s%i%s\n", "Frame structure AMR IF2: ", frames, " frames, ", bytes, " bytes."); #else fprintf ( stderr, "\n%s%i%s\n", "Frame structure AMR ETSI: ", frames, " frames. "); #endif fclose(file_speech); fclose(file_encoded); if (file_mode != NULL) fclose(file_mode); return 0; }
ngram_model_t * ngram_model_set_read(cmd_ln_t * config, const char *lmctlfile, logmath_t * lmath) { FILE *ctlfp; glist_t lms = NULL; glist_t lmnames = NULL; __BIGSTACKVARIABLE__ char str[1024]; ngram_model_t *set = NULL; hash_table_t *classes; char *basedir, *c; /* Read all the class definition files to accumulate a mapping of * classnames to definitions. */ classes = hash_table_new(0, FALSE); if ((ctlfp = fopen(lmctlfile, "r")) == NULL) { E_ERROR_SYSTEM("Failed to open %s", lmctlfile); return NULL; } /* Try to find the base directory to append to relative paths in * the lmctl file. */ if ((c = strrchr(lmctlfile, '/')) || (c = strrchr(lmctlfile, '\\'))) { /* Include the trailing slash. */ basedir = ckd_calloc(c - lmctlfile + 2, 1); memcpy(basedir, lmctlfile, c - lmctlfile + 1); } else { basedir = NULL; } E_INFO("Reading LM control file '%s'\n", lmctlfile); if (basedir) E_INFO("Will prepend '%s' to unqualified paths\n", basedir); if (fscanf(ctlfp, "%1023s", str) == 1) { if (strcmp(str, "{") == 0) { /* Load LMclass files */ while ((fscanf(ctlfp, "%1023s", str) == 1) && (strcmp(str, "}") != 0)) { char *deffile; if (basedir && !path_is_absolute(str)) deffile = string_join(basedir, str, NULL); else deffile = ckd_salloc(str); E_INFO("Reading classdef from '%s'\n", deffile); if (read_classdef_file(classes, deffile) < 0) { ckd_free(deffile); goto error_out; } ckd_free(deffile); } if (strcmp(str, "}") != 0) { E_ERROR("Unexpected EOF in %s\n", lmctlfile); goto error_out; } /* This might be the first LM name. */ if (fscanf(ctlfp, "%1023s", str) != 1) str[0] = '\0'; } } else str[0] = '\0'; /* Read in one LM at a time and add classes to them as necessary. */ while (str[0] != '\0') { char *lmfile; ngram_model_t *lm; if (basedir && str[0] != '/' && str[0] != '\\') lmfile = string_join(basedir, str, NULL); else lmfile = ckd_salloc(str); E_INFO("Reading lm from '%s'\n", lmfile); lm = ngram_model_read(config, lmfile, NGRAM_AUTO, lmath); if (lm == NULL) { ckd_free(lmfile); goto error_out; } if (fscanf(ctlfp, "%1023s", str) != 1) { E_ERROR("LMname missing after LMFileName '%s'\n", lmfile); ckd_free(lmfile); goto error_out; } ckd_free(lmfile); lms = glist_add_ptr(lms, lm); lmnames = glist_add_ptr(lmnames, ckd_salloc(str)); if (fscanf(ctlfp, "%1023s", str) == 1) { if (strcmp(str, "{") == 0) { /* LM uses classes; read their names */ while ((fscanf(ctlfp, "%1023s", str) == 1) && (strcmp(str, "}") != 0)) { void *val; classdef_t *classdef; if (hash_table_lookup(classes, str, &val) == -1) { E_ERROR("Unknown class %s in control file\n", str); goto error_out; } classdef = val; if (ngram_model_add_class(lm, str, 1.0, classdef->words, classdef->weights, classdef->n_words) < 0) { goto error_out; } E_INFO("Added class %s containing %d words\n", str, classdef->n_words); } if (strcmp(str, "}") != 0) { E_ERROR("Unexpected EOF in %s\n", lmctlfile); goto error_out; } if (fscanf(ctlfp, "%1023s", str) != 1) str[0] = '\0'; } } else str[0] = '\0'; } fclose(ctlfp); /* Now construct arrays out of lms and lmnames, and build an * ngram_model_set. */ lms = glist_reverse(lms); lmnames = glist_reverse(lmnames); { int32 n_models; ngram_model_t **lm_array; char **name_array; gnode_t *lm_node, *name_node; int32 i; n_models = glist_count(lms); lm_array = ckd_calloc(n_models, sizeof(*lm_array)); name_array = ckd_calloc(n_models, sizeof(*name_array)); lm_node = lms; name_node = lmnames; for (i = 0; i < n_models; ++i) { lm_array[i] = gnode_ptr(lm_node); name_array[i] = gnode_ptr(name_node); lm_node = gnode_next(lm_node); name_node = gnode_next(name_node); } set = ngram_model_set_init(config, lm_array, name_array, NULL, n_models); for (i = 0; i < n_models; ++i) { ngram_model_free(lm_array[i]); } ckd_free(lm_array); ckd_free(name_array); } error_out: { gnode_t *gn; glist_t hlist; if (set == NULL) { for (gn = lms; gn; gn = gnode_next(gn)) { ngram_model_free(gnode_ptr(gn)); } } glist_free(lms); for (gn = lmnames; gn; gn = gnode_next(gn)) { ckd_free(gnode_ptr(gn)); } glist_free(lmnames); hlist = hash_table_tolist(classes, NULL); for (gn = hlist; gn; gn = gnode_next(gn)) { hash_entry_t *he = gnode_ptr(gn); ckd_free((char *) he->key); classdef_free(he->val); } glist_free(hlist); hash_table_free(classes); ckd_free(basedir); } return set; }
int main(int argc, char** argv) { char *fileName = NULL; int width = 0, height = 0; bool manual = false; bool random = true; int step = 50000; struct option long_options[] = { {"file", required_argument, 0, 'f'}, {"width", required_argument, 0, 'w'}, {"height", required_argument, 0, 'h'}, {"manual", optional_argument, 0, 'm'}, {"random", optional_argument, 0, 'r'}, {"step", required_argument, 0, 't'}, {NULL, 0, NULL, 0} }; int option_index = 0; int c; while ((c = getopt_long(argc, argv, "f:w:h:mrt:", long_options, &option_index)) != -1) { switch(c) { case 'f': fileName = optarg; break; case 'w': width = atoi(optarg); break; case 'h': height = atoi(optarg); break; case 'm': manual = true; break; case 'r': random = true; break; case 't': step = atoi(optarg) * 1000; break; } } if(width == 0 || height == 0) { struct winsize w; ioctl(0, TIOCGWINSZ, &w); if(width == 0) { width = w.ws_col - 2; } if(height == 0) { height = w.ws_row - 3; } } TheLife life(width, height); if(fileName) { FILE* f = fopen(fileName, "r"); if(f == NULL) { printf("Failed to open file"); return 1; } int x = 0, y = 0; char c; while(fscanf(f, "%c", &c) == 1) { if(c == '\n') { x = 0; y++; } if(c == '1') { life.setLive(x, y); } x++; } } else if(random) { life.generate(); } life.render(); while(1) { if(manual) { getchar(); } else { usleep(step); } life.step(); life.render(); } }
void DescribeChannel(void) { FILE *channelFP; ulong line; ulong col; ulong bot; ulong top; long stat; /* * Top terminals of channel. */ TOP = (ulong *)malloc((channelColumns+1) * sizeof(ulong)); /* * Bottom terminals of channel. */ BOT = (ulong *)malloc((channelColumns+1) * sizeof(ulong)); /* * Initialize terminals of channel. */ for (col = 0; col <= channelColumns; col++) { TOP[col] = 0; BOT[col] = 0; } /* * Open channel description file. */ channelFP = fopen(channelFile, "r"); if (channelFP == NULL) { /* * Error in channel file description. */ printf("Error:\n"); printf("\tChannel file cannot be opened.\n"); exit(1); } /* * Scan the file to find the last column * number. The channel file description * contains non-negative integers in the * format... * * [column #] [bottom net #] [top net #] */ line = 0; do { line++; stat = fscanf(channelFP, "%u%u%u", &col, &bot, &top); if (stat != EOF) { if (stat == 3) { /* * Build column. */ if (col > channelColumns) { /* * Error in channel file description. */ printf("Error:\n"); printf("\tChannel file description invalid at line %d.\n", line); printf("\tColumn number out of range.\n"); exit(1); } else { /* * Doit. */ BOT[col] = bot; TOP[col] = top; } } else { /* * Error in channel file description. */ printf("Error:\n"); printf("\tChannel file description invalid at line %d.\n", line); printf("\tIncorrect number of specifiers.\n"); exit(1); } } } while (stat != EOF); /* * Close channel description file. */ if (fclose(channelFP) == EOF) { /* * Error in channel file description. */ printf("Error:\n"); printf("\tChannel file cannot be closed.\n"); exit(1); } }
//Funcion de inicio main() int main(){ printf("Bienvenido al "); printf(Rojo "Chat" ResetColor); printf(Verde "Más" ResetColor); printf(Amarillo "Genial" ResetColor); printf(Verde "Del" ResetColor); printf(Rojo "Mundo\n" ResetColor "\n"); //----------------------------------------------------------// //Verificación del archivo de configuración// //----------------------------------------------------------// int PuertoServidor; FILE *configuracionR; //leer configuracionR = fopen("Configuracion.txt","r"); //abrir el .txt de Contactos if (configuracionR == NULL){ //Si el archivo no existe, lo crea printf("Como esta es su primera vez usando el programa, necesitamos que ingrese \nel número del puerto de su computador donde desea escuchar los mensajes.\n"); printf("Digite el número del puerto de escucha a continuación: \n(numero entre 1024 y 9999) \n\n"); printf("Ingrese el Puerto del contacto a guardar (Número y No ingrese espacios): "); //Obtener el Puerto del usuario scanf("%i",&PuertoServidor); while (getchar()!='\n'); //Ciclo de validación para el puerto while ((PuertoServidor < 1024) || (PuertoServidor > 9999)){ printf("Ingrese el Puerto (No ingrese espacios y num entre 1024 y 9999): "); scanf("%i",&PuertoServidor); while (getchar()!='\n'); } //Crear y escribir en el archivo FILE *configuracionW; //escribir configuracionW = fopen("Configuracion.txt","w+"); fprintf(configuracionW,"%i",PuertoServidor); fclose(configuracionW); printf("\nGracias! Se ha creado también un archivo 'Configuracion.txt' que almacena este dato para próximos usos del programa.\n"); printf(Amarillo "\nPara poder correr bien el programa, debe reiniciarlo por cuestiones de tiempos de ejecución." ResetColor "\n"); return 0; } else{ //Leer el archivo Configuracion.txt fscanf(configuracionR,"%i",&PuertoServidor); } fclose(configuracionR); //------------------------------------------------------------------------------------------------------------------------------------ //----------------------------------------------------------// //Leer los contactos y almacenarlos// //----------------------------------------------------------// FILE *archivo; //definicion de una variable puntero de tipo de FILE para abrir el archivo deseado archivo = fopen("Contactos.txt","r"); //abrir el .txt de Contactos if (archivo == NULL){ //si el archivo no existe, para aquí FILE *crear; crear = fopen("Contactos.txt","w+"); //crear el archivo 'Contactos.txt' fclose(crear); printf("No se encontró el archivo 'Contactos.txt', se ha creado un archivo de texto en blanco con ese nombre.\n"); printf("Este archivo es necesario para el funcionamiento del programa.\n"); printf("Si tiene el archivo pero no está en la carpeta donde está este archivo, consígalo y actualice la información en un solo archivo 'Contactos.txt'.\n\n"); printf(Amarillo "\nPara poder correr bien el programa, debe reiniciarlo por cuestiones de tiempos de ejecución." ResetColor "\n"); return 0; } contacto contactos[100]; //arreglo de contactos int numContacto = 0; //numero de contacto actual en el arreglo //Variables para ir llenando cada contacto, de tamaño 100 porque así se almacenará palabra por palabra char leerNombre[100]; //nombre char leerIp[100]; //ip int leerPuerto; //puerto //Ciclo para leer 3 palabras (nombre, ip y puerto) cada vez while ((fscanf(archivo,"%s%s%i",leerNombre,leerIp,&leerPuerto) == 3) && (numContacto<100)) { //printf("LEYENDO: %s %s %i\n",leerNombre,leerIp,leerPuerto); //impresion de prueba strncpy(contactos[numContacto].nombre,leerNombre,100); strncpy(contactos[numContacto].ip,leerIp,100); contactos[numContacto].puerto = leerPuerto; //printf("PRUEBA --> CONTACTO # %d\n",numContacto); //impresion de prueba //imprimirContacto(&contactos[numContacto]); //impresion de prueba numContacto++; } fclose(archivo); //cerrar el archivo de lectura //------------------------------------------------------------------------------------------------------------------------------------ //----------------------------------------------------------// //Menú de opciones// //----------------------------------------------------------// printf("*****Menú Principal*****\n\nSeleccione una de las siguientes opciones:\n"); printf(Verde "1- Agregar contactos" ResetColor "\n"); printf(Amarillo "2- Visualizar contactos" ResetColor "\n"); printf(Rojo "3- Abrir el Chat" ResetColor "\n"); printf("Presione 0 para salir de la aplicación.\n"); int opcion; //donde se almacenará el input de opción del usuario scanf("%d",&opcion); //scanear el input del usuario while ((opcion < 0) || (opcion > 3)){ //restricciones printf("Ingrese un número de opción correcto: "); while (getchar()!='\n'); //limpiar el registro de standard input hasta la nueva línea (soluciona que "ccc" no vaya a entrar al while 3 veces, solo 1) scanf("%d",&opcion); //volver a scanear hasta llegar a un valor válido } //Variables para ingresar los campos del nuevo contacto char inputNombre[100]; char inputIP[100]; int inputPuerto; int numero = 0; //Variable para iterar en el arreglo de contactos char busquedaNombre[100]; //Variable para buscar un contacto en el arreglo de contactos int encontrado = 1; //Variable para saber si se encontró el contacto requerido //Ciclo del menu --> para que vuelva al menu despues de usar una funcionalidad while (opcion != 0){ switch(opcion){ ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// case 1: //Agregar un contacto if (numContacto == 100){ printf(Rojo "Error, ha llegado al limite de cantidad de contactos.\n" ResetColor "\n"); break; } //Obtener el nombre desde stdin printf("Ingrese el Nombre del contacto a guardar (No ingrese espacios): "); scanf("%s",inputNombre); while (getchar()!='\n'); //Obtener el ip desde stdin printf("Ingrese el IP del contacto a guardar (No ingrese espacios): "); scanf("%s",inputIP); while (getchar()!='\n'); int i,puntos = 0; //Variables para el ciclo de restriccion //Ciclo de restriccion: deben haber al menos 3 puntos en la direccion IP while (puntos < 3){ for (i = 0;inputIP[i] != '\0'; i++){ //Itera sobre cada campo del arreglo de chars mientras no sean nulos if (inputIP[i] == '.') //Busca los puntos y los agrega a la variable puntos++; } if (puntos < 3){ //Volver a preguntar el IP printf("Ingrese el IP del contacto a guardar (Al menos 3 puntos entre los números): "); scanf("%s",inputIP); while (getchar()!='\n'); puntos = 0; } } //Obtener el puerto desde stdin printf("Ingrese el Puerto del contacto a guardar (Número y No ingrese espacios): "); scanf("%i",&inputPuerto); while (getchar()!='\n'); //Ciclo de validación para el puerto while ((inputPuerto < 1024) || (inputPuerto > 9999)){ printf("Ingrese el Puerto del contacto a guardar (No ingrese espacios y num entre 1024 y 9999): "); scanf("%i",&inputPuerto); while (getchar()!='\n'); } //Agregar el nuevo contacto al array de contactos strncpy(contactos[numContacto].nombre,inputNombre,100); strncpy(contactos[numContacto].ip,inputIP,100); contactos[numContacto].puerto = inputPuerto; printf("Se ingresó --> CONTACTO # %d\n",numContacto); //impresion de prueba imprimirContacto(&contactos[numContacto]); //impresion de prueba numContacto++; //Escribir el nuevo contacto en Contactos.txt FILE *file; file= fopen("Contactos.txt","a"); //a para append, fprintf(file,"%s %s %i\n",inputNombre,inputIP,inputPuerto); fclose(file); printf(Verde "Se ha añadido el contacto correctamente.\n" ResetColor "\n"); break; ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// case 2: //Visualizar contactos if (numContacto == 0){ printf(Azul "No hay contactos actualmente.\n" ResetColor); break; } else{ while (numero < numContacto){ //printf("numero = %d,numContacto = %i\n",numero,numContacto); printf("------------CONTACTO # %d\n",numero); imprimirContacto(&contactos[numero]); numero++; } } numero = 0; //Reiniciar valor de numero para proximas impresiones break; ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// case 3: //Comenzar un chat if (numContacto == 0){ printf(Azul "Usted no puede enviar mensajes porque no tiene contactos, agregue alguno.\n" ResetColor); } else { //COMIENZA EL CHAT printf("Escriba 1 para enviar mensaje (cliente), 2 para conectarse al chat (servidor): "); opcion = 0; //donde se almacenará el input de opción del usuario scanf("%d",&opcion); //scanear el input del usuario while ((opcion != 1) && (opcion != 2)){ //restricciones printf("Escriba 1 para enviar mensaje (cliente), 2 para conectarse al chat (servidor): "); while (getchar()!='\n'); //limpiar el registro de standard input hasta la nueva línea (soluciona que "ccc" no vaya a entrar al while 3 veces, solo 1) scanf("%d",&opcion); //volver a scanear hasta llegar a un valor válido } if (opcion == 1){ //cliente printf("Ingrese el nombre del contacto a mensajear: "); scanf("%s",busquedaNombre); //Obtener el nombre del contacto a buscar while (getchar()!='\n'); //printf("busquedaNombre = %s\n",busquedaNombre); while (numero < numContacto){ //Analizar contactos if (strncmp(contactos[numero].nombre,busquedaNombre,100) == 0){ encontrado = 0; break; } numero++; } if (encontrado == 0){ //Contacto encontrado printf(Verde "\nConversación válida con: %s \n" ResetColor,contactos[numero].nombre); cliente(contactos[numero].ip,contactos[numero].puerto); } else //No existe el contacto printf(Rojo "El contacto no existe." ResetColor "\n"); numero = 0; //reset para proximas busquedas encontrado = 1; //reset para proximas busquedas } else //servidor servidor(PuertoServidor); } break; } //----------------------------------------------------------------------------------- //----------------------------------------------------------------------------------- //Mostrar las opciones del menu printf(Verde "\n1- Agregar contactos" ResetColor "\n"); printf(Amarillo "2- Visualizar contactos" ResetColor "\n"); printf(Rojo "3- Abrir el Chat" ResetColor "\n"); printf("Presione 0 para salir de la aplicación.\n"); //Volver a leer la input de opcion scanf("%d",&opcion); //scanear el input del usuario while ((opcion < 0) || (opcion > 4)){ //restricciones printf("Ingrese un número de opción correcto: "); while (getchar()!='\n'); //limpiar el registro de standard input hasta la nueva línea (soluciona que "ccc" no vaya a entrar al while 3 veces, solo 1) scanf("%d",&opcion); //volver a scanear hasta llegar a un valor válido } } printf("\nHasta la próxima.\n"); //mandarlo a limpiar sockets con close() (y otras conexiones, si las hay) como dijo el profe "atexit" return 0; }
void DimensionChannel(void) { FILE *channelFP; ulong line; ulong dim; ulong net; ulong col; ulong bot; ulong top; long stat; /* * Open channel description file. */ channelFP = fopen(channelFile, "r"); if (channelFP == NULL) { /* * Error in channel file description. */ printf("Error:\n"); printf("\tChannel file cannot be opened.\n"); exit(1); } /* * Scan the file to find the last column * number. The channel file description * contains non-negative integers in the * format... * * [column #] [bottom net #] [top net #] */ line = 0; dim = 0; net = 0; do { line++; stat = fscanf(channelFP, "%u%u%u", &col, &bot, &top); if (stat != EOF) { if (stat == 3) { /* * Update column #. */ if (col > dim) { dim = col; } /* * Determine how many channel nets. */ if (bot > net) { net = bot; } if (top > net) { net = top; } } else { /* * Error in channel file description. */ printf("Error:\n"); printf("\tChannel file description invalid at line %d.\n", line); printf("\tIncorrect number of specifiers.\n"); exit(1); } } } while (stat != EOF); /* * Close channel description file. */ if (fclose(channelFP) == EOF) { /* * Error in channel file description. */ printf("Error:\n"); printf("\tChannel file cannot be closed.\n"); exit(1); } /* * Check channel dimension. */ if (dim == 0) { /* * Error in channel file description. */ printf("Error:\n"); printf("\tChannel description invalid.\n"); printf("\tChannel has null dimension.\n"); exit(1); } /* * Set global channel info. */ channelColumns = dim; channelNets = net; }
int main (int argc, char *argv[]) { FILE *ftree, *fout, *fseq; char ctlf[32]="pamp.ctl"; char *Seqstr[]= {"nucleotide", "", "amino-acid", "Binary"}; int itree, ntree, i, j, s3; double *space, *Ft; #ifdef __MWERKS__ /* Added by Andrew Rambaut to accommodate Macs - Brings up dialog box to allow command line parameters. */ argc=ccommand(&argv); #endif com.nhomo=1; com.print=1; noisy=2; com.ncatG=8; com.clock=0; com.cleandata=1; GetOptions (ctlf); if(argc>1) { strcpy(ctlf, argv[1]); printf("\nctlfile set to %s.\n",ctlf); } if ((fseq=fopen(com.seqf, "r"))==NULL) error2 ("seqfile err."); if ((fout=fopen (com.outf, "w"))==NULL) error2("outfile creation err."); if((fseq=fopen (com.seqf,"r"))==NULL) error2("No sequence file!"); ReadSeq (NULL, fseq); i=(com.ns*2-1)*sizeof(struct TREEN); if((nodes=(struct TREEN*)malloc(i))==NULL) error2("oom"); fprintf (fout,"PAMP %15s, %s sequences\n", com.seqf, Seqstr[com.seqtype]); if (com.nhomo) fprintf (fout, "nonhomogeneous model\n"); space = (double*)malloc(50000*sizeof(double)); /* *** */ SeqDistance=(double*)malloc(com.ns*(com.ns-1)/2*sizeof(double)); ancestor=(int*)malloc(com.ns*(com.ns-1)/2*sizeof(int)); if (SeqDistance==NULL||ancestor==NULL) error2("oom"); i = com.ns*(com.ns-1)/2; s3 = sizeof(double)*((com.ns*2-2)*(com.ns*2-2 + 4 + i) + i); s3 = max2(s3, com.ncode*com.ncode*(2*com.ns-2+1)*(int)sizeof(double)); Ft = (double*) malloc(s3); if (space==NULL || Ft==NULL) error2 ("oom space"); Initialize (fout); if (com.ngene>1) error2 ("option G not allowed yet"); /* PatternLS (fout, Ft, 0., space, &i); printf ("\nPairwise estimation of rate matrix done..\n"); fflush(fout); */ ftree=gfopen (com.treef,"r"); fscanf (ftree, "%d%d", &i, &ntree); if (i!=com.ns) error2 ("ns in the tree file"); FOR (itree, ntree) { printf ("\nTREE # %2d\n", itree+1); fprintf (fout,"\nTREE # %2d\n", itree+1); if (ReadaTreeN (ftree, &i,&j, 1)) error2 ("err tree.."); OutaTreeN (F0, 0, 0); FPN (F0); OutaTreeN (fout, 0, 0); FPN (fout); for (i=0,maxchange=0; i<NCATCHANGE; i++) NSiteChange[i]=0; PathwayMP1 (fout, &maxchange, NSiteChange, Ft, space, 0); printf ("\nHartigan reconstruction done..\n"); fprintf (fout, "\n\n(1) Branch lengths and substitution pattern\n"); PatternMP (fout, Ft); printf ("pattern done..\n"); fflush(fout); fprintf (fout, "\n\n(2) Gamma parameter\n"); AlphaMP (fout); printf ("gamma done..\n"); fflush(fout); fprintf (fout, "\n\n(3) Parsimony reconstructions\n"); PathwayMP1 (fout, &maxchange, NSiteChange, Ft, space, 1); printf ("Yang reconstruction done..\n"); fflush(fout); }
int main( int argc, char **argv) { /* sample command lines -i bdv.bshort -o junk.bshort -V -# 16 */ OSErr error = noErr; static char id[] = "$Revision: 1.2 $$Date: 2002/09/10 22:06:02 $"; char headerName[ NAME_SIZE ]; char *extension; char ofName[ NAME_SIZE ]; int OutOrder; error = ProcessCommandLine( argc, argv ); ILError( error, "error in command line" ); extension = strrchr( u.InFileName, '.' ); if( !strlen(extension) ) { printf( "Input file name error\n" ); return 0; } if( !equalString( extension, ".bfloat" )) { printf( "This utility works only on bfloat images!\n" ); return 0; } // strcpy( headerName, u.InFileName, NAME_SIZE ); strcpy( headerName, u.InFileName ); //zrinka 09/10/02 extension = strrchr( headerName, '.' ); if( !strlen(extension) ) { printf( "Input file name error\n" ); return 0; } sprintf( extension, ".hdr" ); u.inFile = errfopen( headerName, "r" ); fscanf( u.inFile, "%d%d%d%d", &u.id.ys, &u.id.xs, &u.id.zs, &u.id.ByteOrder ); // error = ck_fclose( u.inFile, "input header" ); error = ck_fclose( u.inFile ); //zrinka 09/10/02 u.inFile = errfopen( u.InFileName, "rb" ); strcpy( ofName, u.OutFileName ); strcat( ofName, ".bfloat" ); u.outFile = errfopen( ofName, "wb" ); error = DoSwap( u.inFile, u.outFile ); ILError( error, argv[0] ); error = ck_fclose( u.inFile ); ILError( error, "infile" ); error = ck_fclose( u.outFile ); ILError( error, "infile" ); strcpy( ofName, u.OutFileName ); strcat( ofName, ".hdr" ); u.outFile = errfopen( ofName, "w" ); if( u.id.ByteOrder == 1 ) { // pc-dec bytOrder OutOrder = 0; } else { OutOrder = 1; } fprintf( u.outFile, "%d %d %d %d", u.id.ys, u.id.xs, u.id.zs, OutOrder ); error = ck_fclose( u.outFile ); ILError( error, "main" ); }
void ife_print(struct interface *ptr) { struct aftype *ap; struct hwtype *hw; int hf; int can_compress = 0; #if HAVE_AFIPX static struct aftype *ipxtype = NULL; #endif #if HAVE_AFECONET static struct aftype *ectype = NULL; #endif #if HAVE_AFATALK static struct aftype *ddptype = NULL; #endif #if HAVE_AFINET6 FILE *f; char addr6[40], devname[20]; struct sockaddr_in6 sap; int plen, scope, dad_status, if_idx; extern struct aftype inet6_aftype; char addr6p[8][5]; #endif ap = get_afntype(ptr->addr.sa_family); if (ap == NULL) ap = get_afntype(0); hf = ptr->type; if (hf == ARPHRD_CSLIP || hf == ARPHRD_CSLIP6) can_compress = 1; hw = get_hwntype(hf); if (hw == NULL) hw = get_hwntype(-1); printf(_("%-9.9s Link encap:%s "), ptr->name, hw->title); /* For some hardware types (eg Ash, ATM) we don't print the hardware address if it's null. */ if (hw->sprint != NULL && (! (hw_null_address(hw, ptr->hwaddr) && hw->suppress_null_addr))) printf(_("HWaddr %s "), hw->print(ptr->hwaddr)); #ifdef IFF_PORTSEL if (ptr->flags & IFF_PORTSEL) { printf(_("Media:%s"), if_port_text[ptr->map.port][0]); if (ptr->flags & IFF_AUTOMEDIA) printf(_("(auto)")); } #endif printf("\n"); #if HAVE_AFINET if (ptr->has_ip) { printf(_(" %s addr:%s "), ap->name, ap->sprint(&ptr->addr, 1)); if (ptr->flags & IFF_POINTOPOINT) { printf(_(" P-t-P:%s "), ap->sprint(&ptr->dstaddr, 1)); } if (ptr->flags & IFF_BROADCAST) { printf(_(" Bcast:%s "), ap->sprint(&ptr->broadaddr, 1)); } printf(_(" Mask:%s\n"), ap->sprint(&ptr->netmask, 1)); } #endif #if HAVE_AFINET6 /* FIXME: should be integrated into interface.c. */ if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) { while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %02x %02x %02x %02x %20s\n", addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7], &if_idx, &plen, &scope, &dad_status, devname) != EOF) { if (!strcmp(devname, ptr->name)) { sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s", addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7]); inet6_aftype.input(1, addr6, (struct sockaddr *) &sap); printf(_(" inet6 addr: %s/%d"), inet6_aftype.sprint((struct sockaddr *) &sap, 1), plen); printf(_(" Scope:")); switch (scope) { case 0: printf(_("Global")); break; case IPV6_ADDR_LINKLOCAL: printf(_("Link")); break; case IPV6_ADDR_SITELOCAL: printf(_("Site")); break; case IPV6_ADDR_COMPATv4: printf(_("Compat")); break; case IPV6_ADDR_LOOPBACK: printf(_("Host")); break; default: printf(_("Unknown")); } printf("\n"); } } fclose(f); } #endif #if HAVE_AFIPX if (ipxtype == NULL) ipxtype = get_afntype(AF_IPX); if (ipxtype != NULL) { if (ptr->has_ipx_bb) printf(_(" IPX/Ethernet II addr:%s\n"), ipxtype->sprint(&ptr->ipxaddr_bb, 1)); if (ptr->has_ipx_sn) printf(_(" IPX/Ethernet SNAP addr:%s\n"), ipxtype->sprint(&ptr->ipxaddr_sn, 1)); if (ptr->has_ipx_e2) printf(_(" IPX/Ethernet 802.2 addr:%s\n"), ipxtype->sprint(&ptr->ipxaddr_e2, 1)); if (ptr->has_ipx_e3) printf(_(" IPX/Ethernet 802.3 addr:%s\n"), ipxtype->sprint(&ptr->ipxaddr_e3, 1)); } #endif #if HAVE_AFATALK if (ddptype == NULL) ddptype = get_afntype(AF_APPLETALK); if (ddptype != NULL) { if (ptr->has_ddp) printf(_(" EtherTalk Phase 2 addr:%s\n"), ddptype->sprint(&ptr->ddpaddr, 1)); } #endif #if HAVE_AFECONET if (ectype == NULL) ectype = get_afntype(AF_ECONET); if (ectype != NULL) { if (ptr->has_econet) printf(_(" econet addr:%s\n"), ectype->sprint(&ptr->ecaddr, 1)); } #endif printf(" "); if (ptr->flags == 0) printf(_("[NO FLAGS] ")); if (ptr->flags & IFF_UP) printf(_("UP ")); if (ptr->flags & IFF_BROADCAST) printf(_("BROADCAST ")); if (ptr->flags & IFF_DEBUG) printf(_("DEBUG ")); if (ptr->flags & IFF_LOOPBACK) printf(_("LOOPBACK ")); if (ptr->flags & IFF_POINTOPOINT) printf(_("POINTOPOINT ")); if (ptr->flags & IFF_NOTRAILERS) printf(_("NOTRAILERS ")); if (ptr->flags & IFF_RUNNING) printf(_("RUNNING ")); if (ptr->flags & IFF_NOARP) printf(_("NOARP ")); if (ptr->flags & IFF_PROMISC) printf(_("PROMISC ")); if (ptr->flags & IFF_ALLMULTI) printf(_("ALLMULTI ")); if (ptr->flags & IFF_SLAVE) printf(_("SLAVE ")); if (ptr->flags & IFF_MASTER) printf(_("MASTER ")); if (ptr->flags & IFF_MULTICAST) printf(_("MULTICAST ")); #ifdef HAVE_DYNAMIC if (ptr->flags & IFF_DYNAMIC) printf(_("DYNAMIC ")); #endif printf(_(" MTU:%d Metric:%d"), ptr->mtu, ptr->metric ? ptr->metric : 1); #ifdef SIOCSKEEPALIVE if (ptr->outfill || ptr->keepalive) printf(_(" Outfill:%d Keepalive:%d"), ptr->outfill, ptr->keepalive); #endif printf("\n"); /* If needed, display the interface statistics. */ if (ptr->statistics_valid) { /* XXX: statistics are currently only printed for the primary address, * not for the aliases, although strictly speaking they're shared * by all addresses. */ printf(" "); printf(_("RX packets:%lu errors:%lu dropped:%lu overruns:%lu frame:%lu\n"), ptr->stats.rx_packets, ptr->stats.rx_errors, ptr->stats.rx_dropped, ptr->stats.rx_fifo_errors, ptr->stats.rx_frame_errors); if (can_compress) printf(_(" compressed:%lu\n"), ptr->stats.rx_compressed); printf(" "); printf(_("TX packets:%lu errors:%lu dropped:%lu overruns:%lu carrier:%lu\n"), ptr->stats.tx_packets, ptr->stats.tx_errors, ptr->stats.tx_dropped, ptr->stats.tx_fifo_errors, ptr->stats.tx_carrier_errors); printf(_(" collisions:%lu "), ptr->stats.collisions); if (can_compress) printf(_("compressed:%lu "), ptr->stats.tx_compressed); if (ptr->tx_queue_len != -1) printf(_("txqueuelen:%d "), ptr->tx_queue_len); printf("\n"); } if ((ptr->map.irq || ptr->map.mem_start || ptr->map.dma || ptr->map.base_addr)) { printf(" "); if (ptr->map.irq) printf(_("Interrupt:%d "), ptr->map.irq); if (ptr->map.base_addr >= 0x100) /* Only print devices using it for I/O maps */ printf(_("Base address:0x%x "), ptr->map.base_addr); if (ptr->map.mem_start) { printf(_("Memory:%lx-%lx "), ptr->map.mem_start, ptr->map.mem_end); } if (ptr->map.dma) printf(_("DMA chan:%x "), ptr->map.dma); printf("\n"); } printf("\n"); }
void load_speaker_gmm () { printf("In load_speaker_gmm\n"); memset(speaker_gmm, 0, sizeof(speaker_gmm)); char buffer[100]; memset(buffer, 0, sizeof(buffer)); FILE *fin = fopen("by_speaker.txt", "r"); fgets(buffer, sizeof(buffer), fin); int i = 0; for (i = 0; i < num_speaker; i++) { // get name memset(buffer, 0, sizeof(buffer)); fgets(buffer, sizeof(buffer), fin); // printf("*%s*\n", buffer); // if (strcmp(buffer, "manae\n")) { // printf("equals!"); // } strncpy(speaker_gmm[i].name, buffer, strlen(buffer) - 1); //printf("%d: %s ", i, speaker_gmm[i].name); // get M memset(buffer, 0, sizeof(buffer)); fgets(buffer, sizeof(buffer), fin); if (strncmp(buffer, "M\n", 2) == 0) { //printf("read M!\n"); int j = 0; for (j = 0; j < 108; j++) { fscanf(fin, "%lf\n", &speaker_gmm[i].m_m[j]); } // for (j = 0; j < 108; j++) { // printf("%d: %lf\n", j, speaker_gmm[i].m_m[j]); // } } // get V memset(buffer, 0, sizeof(buffer)); fgets(buffer, sizeof(buffer), fin); if (strncmp(buffer, "V\n", 2) == 0) { //printf("read V!\n"); int j = 0; for (j = 0; j < 108; j++) { fscanf(fin, "%lf\n", &speaker_gmm[i].m_v[j]); } // for (j = 0; j < 108; j++) { // printf("%d: %lf\n", j, speaker_gmm[i].m_v[j]); // } } // get W memset(buffer, 0, sizeof(buffer)); fgets(buffer, sizeof(buffer), fin); if (strncmp(buffer, "W\n", 2) == 0) { //printf("read W!\n"); int j = 0; for (j = 0; j < 9; j++) { fscanf(fin, "%lf\n", &speaker_gmm[i].m_w[j]); } // for (j = 0; j < 9; j++) { // printf("%d: %lf\n", j, speaker_gmm[i].m_w[j]); // } } } printf("Finish reading gmms.\n"); fclose(fin); }
int ParseInputFile() { char pszKeyWord[MAX]; // input token char pszParam[MAX]; // parameter for keyword CODEPAGE CP; // codepage structure LANGUAGE Lang; // language structure LANG_EXCEPT LangExcept; // language exception structure LOCALE_HEADER LocHdr; // header locale structure LOCALE_STATIC LocStat; // static length locale structure LOCALE_VARIABLE LocVar; // variable length locale structure UNICODE Unic; // unicode structure CTYPES CTypes; // ctypes structure SORTKEY Sortkey; // sortkey structure - sorting SORT_TABLES SortTbls; // sort tables structure - sorting IDEOGRAPH_EXCEPT IdeographExcept; // ideograph exception structure - sorting while (fscanf(pInputFile, "%s", pszKeyWord) == 1) { if (_strcmpi(pszKeyWord, "CODEPAGE") == 0) { if (Verbose) printf("\n\nFound CODEPAGE keyword.\n"); // // Initialize CodePage structure. // memset(&CP, 0, sizeof(CODEPAGE)); memset(pszParam, 0, MAX * sizeof(char)); CP.pszName = pszParam; // // Get CODEPAGE parameter string. // if (GetKeyParam(pszParam)) { return (1); } // // Get the valid keywords for CODEPAGE. // if (ParseCodePage(&CP, pszKeyWord)) { return (1); } // // Write the CODEPAGE tables to an output file. // if (WriteCodePage(&CP)) { return (1); } } else if (_strcmpi(pszKeyWord, "LANGUAGE") == 0) { if (Verbose) printf("\n\nFound LANGUAGE keyword.\n"); // // Initialize Language structure. // memset(&Lang, 0, sizeof(LANGUAGE)); // // Get LANGUAGE parameter string. // if (GetKeyParam(pszParam)) { return (1); } // // Get the valid keywords for LANGUAGE. // if (ParseLanguage(&Lang, pszKeyWord)) { return (1); } // // Write the LANGUAGE tables to an output file. // if (WriteLanguage(&Lang)) { return (1); } } else if (_strcmpi(pszKeyWord, "LANGUAGE_EXCEPTION") == 0) { if (Verbose) printf("\n\nFound LANGUAGE_EXCEPTION keyword.\n"); // // Initialize Language structure. // memset(&LangExcept, 0, sizeof(LANG_EXCEPT)); // // Get the valid keywords for LANGUAGE_EXCEPTION. // if (ParseLangException(&LangExcept, pszKeyWord)) { return (1); } // // Write the LANGUAGE_EXCEPTION tables to an output file. // if (WriteLangException(&LangExcept)) { return (1); } } else if (_strcmpi(pszKeyWord, "LOCALE") == 0) { if (Verbose) printf("\n\nFound LOCALE keyword.\n"); // // Get the valid keywords for LOCALE. // Write the LOCALE information to an output file. // if (ParseWriteLocale( &LocHdr, &LocStat, &LocVar, pszKeyWord )) { return (1); } } else if (_strcmpi(pszKeyWord, "UNICODE") == 0) { if (Verbose) printf("\n\nFound UNICODE keyword.\n"); // // Initialize Unicode structure. // memset(&Unic, 0, sizeof(UNICODE)); // // Get the valid keywords for UNICODE. // if (ParseUnicode(&Unic, pszKeyWord)) { return (1); } // // Write the UNICODE tables to an output file. // if (WriteUnicode(&Unic)) { return (1); } } else if (_strcmpi(pszKeyWord, "CTYPES") == 0) { if (Verbose) printf("\n\nFound CTYPES keyword.\n"); // // Initialize CTypes structure. // memset(&CTypes, 0, sizeof(CTYPES)); // // Get the valid keywords for CTYPES. // if (ParseCTypes(&CTypes)) { return (1); } // // Write the CTYPES tables to different output files. // if (WriteCTypes(&CTypes)) { return (1); } } else if (_strcmpi(pszKeyWord, "SORTKEY") == 0) { if (Verbose) printf("\n\nFound SORTKEY keyword.\n"); // // Initialize Sortkey structure. // memset(&Sortkey, 0, sizeof(SORTKEY)); // // Get the valid keywords for SORTKEY. // if (ParseSortkey(&Sortkey, pszKeyWord)) { return (1); } // // Write the SORTKEY tables to an output file. // if (WriteSortkey(&Sortkey)) { return (1); } } else if (_strcmpi(pszKeyWord, "SORTTABLES") == 0) { if (Verbose) printf("\n\nFound SORTTABLES keyword.\n"); // // Initialize Sort Tables structure. // memset(&SortTbls, 0, sizeof(SORT_TABLES)); // // Get the valid keywords for SORTTABLES. // if (ParseSortTables(&SortTbls, pszKeyWord)) { return (1); } // // Write the Sort Tables to an output file. // if (WriteSortTables(&SortTbls)) { return (1); } } else if (_strcmpi(pszKeyWord, "IDEOGRAPH_EXCEPTION") == 0) { if (Verbose) printf("\n\nFound IDEOGRAPH_EXCEPTION keyword.\n"); // // Initialize Ideograph Exception structure. // memset(&IdeographExcept, 0, sizeof(IDEOGRAPH_EXCEPT)); // // Get the valid keywords for IDEOGRAPH_EXCEPTION. // if (ParseIdeographExceptions(&IdeographExcept)) { return (1); } // // Write the Ideograph Exceptions to the given output file. // if (WriteIdeographExceptions(&IdeographExcept)) { return (1); } } else { printf("Parse Error: Invalid Instruction '%s'.\n", pszKeyWord); return (1); } } // // Return success. // return (0); }
static int input_assign_inv ( FILE *finassign, /* input assignment file */ char *inassignname, /* name of input assignment file */ int nvtxs, /* number of vertices to output */ int *assignment /* values to be printed */ ) { extern int DEBUG_TRACE; /* trace main execution path */ int set; /* set number being read */ int size; /* number of vertices in set */ int total; /* total number of vertices read */ int done; /* have I hit end of file yet? */ int end_flag; /* return flag from read_int() */ int i, j, k; /* loop counter */ int read_int(); if (DEBUG_TRACE > 0) { printf("<Entering input_assign_inv>\n"); } /* Get the assignment vector one line at a time, checking as you go. */ /* Initialize assignment to help error detection. */ for (i = 0; i < nvtxs; i++) { assignment[i] = -1; } /* First read past any comments at top. */ total = 0; set = 0; end_flag = 1; while (end_flag == 1) { size = read_int(finassign, &end_flag); } if (end_flag == -1) { printf("ERROR: In assignment file `%s'\n", inassignname); printf(" No values found\n"); return (1); } if (size < 0) { printf("ERROR: In assignment file `%s'\n", inassignname); printf(" Size of set %d less than zero (%d)\n", set, size); return (1); } if (total + size > nvtxs) { printf("ERROR: In assignment file `%s'\n", inassignname); printf(" Total set sizes greater than nvtxs (%d)\n", nvtxs); return (1); } done = FALSE; while (!done && total < nvtxs) { for (i = 1; i <= size; i++) { j = fscanf(finassign, "%d", &k); if (j != 1) { printf("ERROR: Too few values in assignment file `%s'.\n", inassignname); return (1); } if (k <= 0 || k > nvtxs) { printf("ERROR: In assignment file `%s'\n", inassignname); printf(" Entry %d of set %d invalid (%d)\n", total + i, set, k); return (1); } if ((int) assignment[k - 1] != -1) { printf("ERROR: In assignment file `%s'\n", inassignname); printf(" Vertex %d assigned to multiple sets\n", k); return (1); } assignment[k - 1] = (int) set; } total += size; j = fscanf(finassign, "%d", &size); ++set; if (j != 1) { if (total != nvtxs) { printf("ERROR: Too few values in assignment file `%s'.\n", inassignname); return (1); } else { done = TRUE; size = 0; } } if (size < 0) { printf("ERROR: In assignment file `%s'\n", inassignname); printf(" Size of set %d less than zero (%d)\n", set, size); return (1); } if (total + size > nvtxs) { printf("ERROR: In assignment file `%s'\n", inassignname); printf(" Total set sizes greater than nvtxs (%d)\n", nvtxs); return (1); } } return (0); }
/* Load orders.tbl. */ bool pageManage::loadData_o() { /* Open the relevant files. */ FILE* pfile = fopen(PATH_OF_ORDERS, "rb"); if (!pfile) return false; FILE *ofile = fopen(PATH_OF_O_ORDERKEY, "wb"), *cfile = fopen(PATH_OF_O_CUSTKEY, "wb"), *tfile = fopen(PATH_OF_O_TOTALPRICE, "wb"), *sfile = fopen(PATH_OF_O_SHIPPRIORITY, "wb"), *tableFile = fopen(PATH_OF_QUERY_TABLE, "wb"); if (!ofile || !cfile || !tfile || !sfile || !tableFile) return false; /* Create a query table to improve the query. */ int queryTableSize = 0; int queryTable[MAX_SIZE_QUERY_TABLE]; /* Traversing orders.tbl and load data. */ int orderkeyData[MAX_ITEM], custkeyData[MAX_ITEM], shippriorityData[MAX_ITEM]; double tolalpriceData[MAX_ITEM]; int count = 0; int okey, ckey, spriority; char ostatus, odate[11], opriority[16], clerk[16], comment[80]; double tprice; while (fscanf(pfile, "%d|%d|%c|%lf|%[^|]|%[^|]|%[^|]|%d|%[^|]|\n", &okey, &ckey, &ostatus, &tprice, odate, opriority, clerk, &spriority, comment) != EOF) { if (count == MAX_ITEM) { queryTable[queryTableSize++] = orderkeyData[0]; fwrite(orderkeyData, sizeof(int), MAX_ITEM, ofile); fwrite(custkeyData, sizeof(int), MAX_ITEM, cfile); fwrite(tolalpriceData, sizeof(double), MAX_ITEM, tfile); fwrite(shippriorityData, sizeof(int), MAX_ITEM, sfile); count = 0; } orderkeyData[count] = okey; custkeyData[count] = ckey; tolalpriceData[count] = tprice; shippriorityData[count] = spriority; ++count; } if (count != 0) { queryTable[queryTableSize++] = orderkeyData[0]; fwrite(orderkeyData, sizeof(int), count, ofile); fwrite(custkeyData, sizeof(int), count, cfile); fwrite(tolalpriceData, sizeof(double), count, tfile); fwrite(shippriorityData, sizeof(int), count, sfile); } fwrite(queryTable, sizeof(int), queryTableSize, tableFile); /* Close the relevant files. */ fclose(pfile); fclose(ofile); fclose(cfile); fclose(tfile); fclose(sfile); fclose(tableFile); return true; }
static int input_assign_normal(FILE *finassign, char *inassignname, int nvtxs, int *assignment) /* FILE *finassign; input assignment file char *inassignname; name of input assignment file int nvtxs; number of vertices to output int *assignment; values to be printed */ { extern FILE *Output_File; /* output file or null */ extern int CHECK_INPUT; /* print warning messages? */ extern int DEBUG_TRACE; /* trace main execution path */ int flag; /* logical conditional */ int end_flag; /* return flag from read_int() */ int i, j; /* loop counter */ int read_int(); if (DEBUG_TRACE > 0) { printf("<Entering input_assign>\n"); } /* Get the assignment vector one line at a time, checking as you go. */ /* First read past any comments at top. */ end_flag = 1; while (end_flag == 1) { assignment[0] = read_int(finassign, &end_flag); } if (assignment[0] < 0) { printf("ERROR: Entry %d in assignment file `%s' less than zero (%d)\n", 1, inassignname, assignment[0]); return (1); } if (end_flag == -1) { printf("ERROR: No values found in assignment file `%s'\n", inassignname); return (1); } flag = 0; if (assignment[0] > nvtxs) flag = assignment[1]; for (i = 1; i < nvtxs; i++) { j = fscanf(finassign, "%d", &(assignment[i])); if (j != 1) { printf("ERROR: Too few values in assignment file `%s'.\n", inassignname); return (1); } if (assignment[i] < 0) { printf("ERROR: Entry %d in assignment file `%s' less than zero (%d)\n", i+1, inassignname, assignment[i]); return (1); } if (assignment[i] > nvtxs) { /* warn since probably an error */ if (assignment[i] > flag) flag = assignment[i]; } } if (flag && CHECK_INPUT) { printf("WARNING: Possible error in assignment file `%s'\n", inassignname); printf(" More assignment sets (%d) than vertices (%d)\n", flag, nvtxs); if (Output_File != NULL) { fprintf(Output_File, "WARNING: Possible error in assignment file `%s'\n", inassignname); fprintf(Output_File, " More assignment sets (%d) than vertices (%d)\n", flag, nvtxs); } } /* Check for spurious extra stuff in file. */ flag = FALSE; end_flag = 0; while (!flag && end_flag != -1) { read_int(finassign, &end_flag); if (!end_flag) flag = TRUE; } if (flag && CHECK_INPUT) { printf("WARNING: Possible error in assignment file `%s'\n", inassignname); printf(" Numerical data found after expected end of file\n"); if (Output_File != NULL) { fprintf(Output_File, "WARNING: Possible error in assignment file `%s'\n", inassignname); fprintf(Output_File, " Numerical data found after expected end of file\n"); } } return (0); }
int main(int argc, char *argv[]) { char *ref_fname, *in_fname, *out_fname, fname[STRLEN], **av ; MRI *mri_ref, *mri_in, *mri_orig, *mri_in_red, *mri_ref_red, *mri_in_tmp, *mri_ref_tmp, *mri_ref_orig, *mri_in_orig ; int ac, nargs, i, msec, minutes, seconds ; struct timeb start ; MATRIX *m_L ; /* rkt: check for and handle version tag */ nargs = handle_version_option (argc, argv, "$Id: mri_linear_register.c,v 1.13 2011/03/02 00:04:22 nicks Exp $", "$Name: stable5 $"); if (nargs && argc - nargs == 1) exit (0); argc -= nargs; parms.mri_crop = NULL ; parms.l_intensity = 1.0f ; parms.niterations = 100 ; parms.levels = -1 ; /* use default */ parms.dt = 1e-6 ; /* was 5e-6 */ parms.tol = INTEGRATION_TOL*5 ; parms.dt = 5e-6 ; /* was 5e-6 */ parms.tol = 1e-3 ; parms.momentum = 0.8 ; parms.max_levels = MAX_LEVELS ; parms.factor = 1.0 ; parms.niterations = 25 ; Progname = argv[0] ; DiagInit(NULL, NULL, NULL) ; ErrorInit(NULL, NULL, NULL) ; ac = argc ; av = argv ; for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) { nargs = get_option(argc, argv) ; argc -= nargs ; argv += nargs ; } if (argc < 4) ErrorExit(ERROR_BADPARM, "usage: %s <in brain> <template> <output file name>\n", Progname) ; in_fname = argv[1] ; ref_fname = argv[2] ; if (xform_mean_fname) { int sno, nsubjects ; FILE *fp ; parms.m_xform_mean = MatrixAsciiRead(xform_mean_fname, NULL) ; if (!parms.m_xform_mean) ErrorExit(Gerror, "%s: could not read parameter means from %s", Progname, xform_mean_fname) ; fp = fopen(xform_covariance_fname, "r") ; if (!fp) ErrorExit(ERROR_NOFILE, "%s: could not read covariances from %s", Progname, xform_covariance_fname) ; fscanf(fp, "nsubjects=%d", &nsubjects) ; printf("reading %d transforms...\n", nsubjects) ; parms.m_xforms = (MATRIX **)calloc(nsubjects, sizeof(MATRIX *)) ; if (!parms.m_xforms) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate array of %d xforms", Progname, nsubjects) ; for (sno = 0 ; sno < nsubjects ; sno++) { parms.m_xforms[sno] = MatrixAsciiReadFrom(fp, NULL) ; if (!parms.m_xforms[sno]) ErrorExit(ERROR_NOMEMORY, "%s: could not allocate %dth xform", Progname, sno) ; } parms.m_xform_covariance = MatrixAsciiReadFrom(fp, NULL) ; if (!parms.m_xform_covariance) ErrorExit(Gerror, "%s: could not read parameter covariance from %s", Progname, xform_covariance_fname) ; fclose(fp) ; parms.l_priors = l_priors ; parms.nxforms = nsubjects ; } out_fname = argv[3] ; FileNameOnly(out_fname, fname) ; FileNameRemoveExtension(fname, fname) ; strcpy(parms.base_name, fname) ; fprintf(stderr, "logging results to %s.log\n", parms.base_name) ; TimerStart(&start) ; fprintf(stderr, "reading '%s'...\n", ref_fname) ; fflush(stderr) ; mri_ref = MRIread(ref_fname) ; if (!mri_ref) ErrorExit(ERROR_NOFILE, "%s: could not open reference volume %s.\n", Progname, ref_fname) ; if (mri_ref->type != MRI_UCHAR) { MRI *mri_tmp ; mri_tmp = MRIchangeType(mri_ref, MRI_UCHAR, 0.0, 0.999, FALSE) ; MRIfree(&mri_ref) ; mri_ref = mri_tmp ; } if (var_fname) /* read in a volume of standard deviations */ { MRI *mri_var, *mri_tmp ; fprintf(stderr, "reading '%s'...\n", var_fname) ; mri_var = MRIread(var_fname) ; if (!mri_var) ErrorExit(ERROR_NOFILE, "%s: could not open variance volume %s.\n", Progname, var_fname) ; mri_tmp = MRIconcatenateFrames(mri_ref, mri_var, NULL) ; MRIfree(&mri_var) ; MRIfree(&mri_ref) ; mri_ref = mri_tmp ; } fprintf(stderr, "reading '%s'...\n", in_fname) ; fflush(stderr) ; mri_orig = mri_in = MRIread(in_fname) ; if (!mri_in) ErrorExit(ERROR_NOFILE, "%s: could not open input volume %s.\n", Progname, in_fname) ; if (mri_in->type != MRI_UCHAR) { MRI *mri_tmp ; mri_orig = mri_tmp = MRIchangeType(mri_in, MRI_UCHAR, 0.0, 0.999, FALSE) ; MRIfree(&mri_in) ; mri_in = mri_tmp ; } /* make sure they are the same size */ if (mri_in->width != mri_ref->width || mri_in->height != mri_ref->height || mri_in->depth != mri_ref->depth) { int width, height, depth ; MRI *mri_tmp ; width = MAX(mri_in->width, mri_ref->width) ; height = MAX(mri_in->height, mri_ref->height) ; depth = MAX(mri_in->depth, mri_ref->depth) ; mri_tmp = MRIalloc(width, height, depth, MRI_UCHAR) ; MRIextractInto(mri_in, mri_tmp, 0, 0, 0, mri_in->width, mri_in->height, mri_in->depth, 0, 0, 0) ; #if 0 MRIfree(&mri_in) ; #else parms.mri_in = mri_in ; #endif mri_in = mri_orig = mri_tmp ; mri_tmp = MRIallocSequence(width, height,depth,MRI_UCHAR,mri_ref->nframes); MRIextractInto(mri_ref, mri_tmp, 0, 0, 0, mri_ref->width, mri_ref->height, mri_ref->depth, 0, 0, 0) ; #if 0 MRIfree(&mri_ref) ; #else parms.mri_in = mri_in ; #endif mri_ref = mri_tmp ; } if (!FZERO(tx) || !FZERO(ty) || !FZERO(tz)) { MRI *mri_tmp ; fprintf(stderr, "translating second volume by (%2.1f, %2.1f, %2.1f)\n", tx, ty, tz) ; mri_tmp = MRItranslate(mri_in, NULL, tx, ty, tz) ; MRIfree(&mri_in) ; mri_in = mri_tmp ; } if (!FZERO(rzrot)) { MRI *mri_tmp ; fprintf(stderr, "rotating second volume by %2.1f degrees around Z axis\n", (float)DEGREES(rzrot)) ; mri_tmp = MRIrotateZ_I(mri_in, NULL, rzrot) ; MRIfree(&mri_in) ; mri_in = mri_tmp ; } if (!FZERO(rxrot)) { MRI *mri_tmp ; fprintf(stderr, "rotating second volume by %2.1f degrees around X axis\n", (float)DEGREES(rxrot)) ; mri_tmp = MRIrotateX_I(mri_in, NULL, rxrot) ; MRIfree(&mri_in) ; mri_in = mri_tmp ; } if (!FZERO(ryrot)) { MRI *mri_tmp ; fprintf(stderr, "rotating second volume by %2.1f degrees around Y axis\n", (float)DEGREES(ryrot)) ; mri_tmp = MRIrotateY_I(mri_in, NULL, ryrot) ; MRIfree(&mri_in) ; mri_in = mri_tmp ; } if (!transform_loaded) /* wasn't preloaded */ parms.lta = LTAalloc(1, mri_in) ; if (!FZERO(blur_sigma)) { MRI *mri_kernel, *mri_tmp ; mri_kernel = MRIgaussian1d(blur_sigma, 100) ; mri_tmp = MRIconvolveGaussian(mri_in, NULL, mri_kernel) ; mri_in = mri_tmp ; MRIfree(&mri_kernel) ; } MRIscaleMeanIntensities(mri_in, mri_ref, mri_in); mri_ref_orig = mri_ref ; mri_in_orig = mri_in ; if (nreductions > 0) { mri_in_red = mri_in_tmp = MRIcopy(mri_in, NULL) ; mri_ref_red = mri_ref_tmp = MRIcopy(mri_ref, NULL) ; for (i = 0 ; i < nreductions ; i++) { mri_in_red = MRIreduceByte(mri_in_tmp, NULL) ; mri_ref_red = MRIreduceMeanAndStdByte(mri_ref_tmp,NULL); MRIfree(&mri_in_tmp); MRIfree(&mri_ref_tmp) ; mri_in_tmp = mri_in_red ; mri_ref_tmp = mri_ref_red ; } mri_in = mri_in_red ; mri_ref = mri_ref_red ; } /* for diagnostics */ if (full_res) { parms.mri_ref = mri_ref ; parms.mri_in = mri_in ; } else { parms.mri_ref = mri_ref_orig ; parms.mri_in = mri_in_orig ; } m_L = initialize_transform(mri_in, mri_ref, &parms) ; if (use_gradient) { MRI *mri_in_mag, *mri_ref_mag, *mri_grad, *mri_mag ; printf("computing gradient magnitude of input image...\n") ; mri_mag = MRIalloc(mri_in->width, mri_in->height, mri_in->depth,MRI_FLOAT); MRIcopyHeader(mri_in, mri_mag) ; mri_grad = MRIsobel(mri_in, NULL, mri_mag) ; MRIfree(&mri_grad) ; /* convert it to ubytes */ MRIvalScale(mri_mag, mri_mag, 0.0f, 255.0f) ; mri_in_mag = MRIclone(mri_in, NULL) ; MRIcopy(mri_mag, mri_in_mag) ; MRIfree(&mri_mag) ; /* now compute gradient of ref image */ printf("computing gradient magnitude of reference image...\n") ; mri_mag = MRIalloc(mri_ref->width, mri_ref->height, mri_ref->depth,MRI_FLOAT); MRIcopyHeader(mri_ref, mri_mag) ; mri_grad = MRIsobel(mri_ref, NULL, mri_mag) ; MRIfree(&mri_grad) ; /* convert it to ubytes */ MRIvalScale(mri_mag, mri_mag, 0.0f, 255.0f) ; mri_ref_mag = MRIclone(mri_ref, NULL) ; MRIcopy(mri_mag, mri_ref_mag) ; MRIfree(&mri_mag) ; register_mri(mri_in_mag, mri_ref_mag, &parms, m_L) ; MRIfree(&mri_in_mag) ; MRIfree(&mri_ref_mag) ; } register_mri(mri_in, mri_ref, &parms, m_L) ; if (check_crop_flag) /* not working yet! */ { printf("searching for cropped regions in the input image...\n") ; parms.mri_crop = find_cropping(mri_orig, mri_ref, &parms) ; MRIwrite(parms.mri_crop, "crop.mgh") ; register_mri(mri_in, mri_ref, &parms, m_L) ; } if (voxel_coords) { printf("transforming xform to voxel coordinates...\n") ; MRIrasXformToVoxelXform(mri_in_orig, mri_ref_orig, parms.lta->xforms[0].m_L, parms.lta->xforms[0].m_L); if (Gdiag & DIAG_WRITE) { MRI *mri_tmp ; mri_tmp = MRIlinearTransform(mri_in_orig, NULL,parms.lta->xforms[0].m_L); MRIwriteImageViews(mri_tmp, "morphed", IMAGE_SIZE) ; MRIfree(&mri_tmp) ; } } // save src and target info in lta getVolGeom(mri_in_orig, &parms.lta->xforms[0].src); getVolGeom(mri_ref_orig, &parms.lta->xforms[0].dst); fprintf(stderr, "writing output transformation to %s...\n", out_fname) ; if (invert_flag) { MATRIX *m_tmp ; m_tmp = MatrixInverse(parms.lta->xforms[0].m_L, NULL) ; MatrixFree(&parms.lta->xforms[0].m_L) ; // change src and dst getVolGeom(mri_in_orig, &parms.lta->xforms[0].dst); getVolGeom(mri_ref_orig, &parms.lta->xforms[0].src); parms.lta->xforms[0].m_L = m_tmp ; } // LTAwriteEx(parms.lta, out_fname) ; // if (mri_ref) MRIfree(&mri_ref) ; if (mri_in) MRIfree(&mri_in) ; msec = TimerStop(&start) ; seconds = nint((float)msec/1000.0f) ; minutes = seconds / 60 ; seconds = seconds % 60 ; fprintf(stderr, "registration took %d minutes and %d seconds.\n", minutes, seconds) ; exit(0) ; return(0) ; }
Camera* DefFileReader::loadCamera( std::string filePath ) { float x, y, z; int n; char param_name[16]; bool errors = false; FILE* fp = fopen(filePath.c_str(), "r"); if (!fp) return 0; /* Lendo a posicao do observador */ Vector4D eye; fscanf(fp, "%s ", param_name); if (strcmp(param_name, "eye=") == 0) { fscanf(fp, "%f %f %f", &x, &y, &z); eye.x = x; eye.y = y; eye.z = z; eye.w = 1.0; } else errors = true; /* Lendo a direcao de visao */ Vector4D at; fscanf(fp, "%s ", param_name); if (strcmp(param_name, "at=") == 0) { fscanf(fp, "%f %f %f", &x, &y, &z); at.x = x; at.y = y; at.z = z; at.w = 1.0; } else errors = true; /* Lendo o "view-up" */ Vector4D up; fscanf(fp, "%s ", param_name); if (strcmp(param_name, "up=") == 0) { fscanf(fp, "%f %f %f", &x, &y, &z); up.x = x; up.y = y; up.z = z; up.w = 1.0; } else errors = true; /* Lendo o fovy */ float fovy; fscanf(fp, "%s ", param_name); if (strcmp(param_name, "fovy=") == 0) { fscanf(fp, "%f ", &x); fovy = x; } else errors = true; /* Lendo o near plane */ float near; fscanf(fp, "%s ", param_name); if (strcmp(param_name, "nearp=") == 0) { fscanf(fp, "%f ", &x); near = x; } else errors = true; /* Lendo o far plane */ float far; fscanf(fp, "%s ", param_name); if (strcmp(param_name, "farp=") == 0) { fscanf(fp, "%f ", &x); far = x; } else errors = true; /* Lendo a largura da janela */ int width; fscanf(fp, "%s ", param_name); if (strcmp(param_name, "screenW=") == 0) { fscanf(fp, "%d ", &n); width = n; } else errors = true; /* Lendo a altura da janela */ int height; fscanf(fp, "%s ", param_name); if (strcmp(param_name, "screenH=") == 0) { fscanf(fp, "%d ", &n); height = n; } else errors = true; fclose(fp); if( errors ) { printf("Ocorreram erros ao ler o arquivo .cam\n"); exit(1); } return new Camera( eye, at, up, fovy, near, far, width, height ); }
int main(int argc, char* argv[]){ int numberOfJob; int *noJob; int *timeArrive; int *timeUse; int *turnaroundTime; int *responseTime; float sumTimeUsed = 0; float sumTurnaroundTime = 0; float sumResponseTime = 0; FILE* file = fopen (argv[1], "r"); int i = 0; fscanf (file, "%d", &numberOfJob); noJob = (int*)malloc(numberOfJob*sizeof(int)); timeArrive = (int*)malloc(numberOfJob*sizeof(int)); timeUse = (int*)malloc(numberOfJob*sizeof(int)); responseTime = (int*)malloc(numberOfJob*sizeof(int)); turnaroundTime = (int*)malloc(numberOfJob*sizeof(int)); for(i=0;i<numberOfJob;i++){ fscanf(file,"%d %d %d",&noJob[i],&timeArrive[i],&timeUse[i]); } printf("No of Job = %d\n",numberOfJob); for(i=0;i<numberOfJob;i++){ printf("%d %d %d\n",noJob[i],timeArrive[i],timeUse[i]); } responseTime[0] = 0; turnaroundTime[0] = responseTime[0] + timeUse[0]; int systemTimeUsed = turnaroundTime[0]; for(i=1;i<numberOfJob;i++) { if(systemTimeUsed < timeArrive[i]) { responseTime[i] = 0; systemTimeUsed += timeArrive[i] + timeUse[i]; } else { responseTime[i] = systemTimeUsed - timeArrive[i]; systemTimeUsed += timeUse[i]; } turnaroundTime[i] = responseTime[i] + timeUse[i]; } for(i=0;i<numberOfJob;i++) { sumResponseTime += responseTime[i]; sumTimeUsed += timeUse[i]; sumTurnaroundTime += turnaroundTime[i]; printf("responseTime = %d\n", responseTime[i]); printf("timeUsed = %d\n", timeUse[i]); printf("turnaroundTime = %d\n\n", turnaroundTime[i]); } printf("avgResponseTime = %.2f\n", sumResponseTime/5); printf("avgTimeUsed = %.2f\n", sumTimeUsed/5); printf("avgTurnaroundTime = %.2f\n", sumTurnaroundTime/5); fclose (file); }
int _tmain(int argc, _TCHAR* argv[]) { system("title LABIRINTiT 1x - PRODUÇÃO - RODRIGO MARTINS ! FELIPE MASIOLI"); int tecla,variado; int result; char mapa_a[10][40], jogador[100]; int i, j,pont=0; clock_t start, end; double elapsed; FILE *arquivo; srand(time(NULL)); variado = random(0,3); arquivo = f_rand(variado); printf("\n\n\t\tLABIRINTiT 1x"); printf("\n\n\tQual o seu nome jogador???\n\t\t"); scanf("%s", jogador); start = clock(); do{ system(LIMPARTELA); //printf("\t\t\tLABIRINTiT 1x\n\n"); /* Abre o arquivo */ if(!arquivo) { printf("Erro ao abrir arquivo!!!"); exit(1); } /* Escreve a matriz no arquivo */ for (i=0; i<10; i++) { for (j=0; j<40; j++) { fscanf(arquivo, "%d",&mapa_a[i][j]); } } mapa_a[linha_atual][coluna_atual] = nome; for(i=0;i<10;i++) { for(j=0;j<40;j++) printf("%c",mapa_a[i][j]); puts(""); } /* O Mapa */ printf("\n##################### L A B I R I N T i T - 1x ################################\n"); printf("\n\n ( %c )\n\n( %c ) + ( %c )\n\n ( %c )\n",30,17,16,31); /* Imprime as direcoes */ printf("\nPressione ESC para sair\n"); printf("\n------------------------------------------------------------------------------\n"); tecla = getch(); if ( tecla == ACIMA ) { printf("%c",mapa_a[linha_atual][coluna_atual]); mapa_a[linha_atual][coluna_atual]=0; linha_atual = linha_atual - 1; printf("%c",mapa_a[linha_atual][coluna_atual]); /* Se não for chao ou grama ele volta pra posicao anterior */ if ((mapa_a[linha_atual][coluna_atual] != 0) && (mapa_a[linha_atual][coluna_atual] != 176) && (mapa_a[linha_atual][coluna_atual] != 4)) { linha_atual = linha_atual + 1; } } if ( tecla == ABAIXO ) { printf("%c",mapa_a[linha_atual][coluna_atual]); mapa_a[linha_atual][coluna_atual]=0; linha_atual = linha_atual + 1; /* Se não for chao ou grama ou saida ele volta pra posicao anterior */ if ((mapa_a[linha_atual][coluna_atual] != 0) && (mapa_a[linha_atual][coluna_atual] != 176) && (mapa_a[linha_atual][coluna_atual] != 4)) { linha_atual = linha_atual - 1; } } if ( tecla == DIREITA ) { printf("%c",mapa_a[linha_atual][coluna_atual]); mapa_a[linha_atual][coluna_atual]=0; coluna_atual = coluna_atual + 1; /* Se não for chao ou grama ou saida ele volta pra posicao anterior */ if ((mapa_a[linha_atual][coluna_atual] != 0) && (mapa_a[linha_atual][coluna_atual] != 176) && (mapa_a[linha_atual][coluna_atual] != 4)) { coluna_atual = coluna_atual - 1; } } if ( tecla == ESQUERDA ) { printf("%c",mapa_a[linha_atual][coluna_atual]); mapa_a[linha_atual][coluna_atual]=0; coluna_atual = coluna_atual - 1; /* Se não for chao ou grama ou saida ele volta pra posicao anterior */ if ((mapa_a[linha_atual][coluna_atual] != 0) && (mapa_a[linha_atual][coluna_atual] != 176) && (mapa_a[linha_atual][coluna_atual] != 4)) { coluna_atual = coluna_atual + 1; } } if (mapa_a[linha_atual][coluna_atual] !=4 ) { pont++; } }while( (tecla != ESC) && (mapa_a[linha_atual][coluna_atual] != 4) ); result = pont/2; end = clock(); elapsed = ((double) (end - start)) / CLOCKS_PER_SEC; if (mapa_a[linha_atual][coluna_atual] == 4) { printf ("%s,\n",jogador); if (variado == 0) { if (result == 34) { printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed); printf("\t\tVoce foi excelente!!!\n"); printf ("\t!!!!!!!!!!!!!!PARABENSSSSSSSSS!!!!!!!!!!!!!!\n\n"); } if (result > 34) { printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed); printf("\tVoce prescisa melhorar!!!\n"); } } if (variado == 1) { if (result == 51) { printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed); printf("\t\tVoce foi excelente!!!\n"); printf ("\t!!!!!!!!!!!!!!PARABENSSSSSSSSS!!!!!!!!!!!!!!\n\n"); } if (result > 51) { printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed); printf("\tVoce prescisa melhorar!!!\n"); } } if (variado == 2) { if (result == 68) { printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed); printf("\t\tVoce foi excelente!!!\n"); printf ("\t!!!!!!!!!!!!!!PARABENSSSSSSSSS!!!!!!!!!!!!!!\n\n"); } if (result > 68) { printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed); printf("\tVoce prescisa melhorar!!!\n"); } } if (variado == 3) { if (result == 71) { printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed); printf("\t\tVoce foi excelente!!!\n"); printf ("\t!!!!!!!!!!!!!!PARABENSSSSSSSSS!!!!!!!!!!!!!!\n\n"); } if (result > 71) { printf ("Voce andou %d vezes ...\n Gastou um tempo de %0.0f segundos...\n", result, elapsed); printf("\tVoce prescisa melhorar!!!\n"); } } system("pause"); system(acaba); } fclose(arquivo); return 0; }