int addInFileAndClose(char *firstLine, char *filename) { FILE *fptmp; FILE *fp; char buffer[BUFF_DEFAULT_SIZE]; if ((fptmp = fopen(TEMP_FILE_PATH, "w")) == NULL) { exitWithError(); } if ((fp = fopen(filename, "r")) == NULL) { exitWithError(); } if (fputs(firstLine, fptmp) == EOF) { exitWithError(); } while (fgets(buffer, BUFF_DEFAULT_SIZE, fp) != NULL) { fputs(buffer, fptmp); } fclose(fptmp); fclose(fp); if (remove(filename) != 0) { exitWithError(); } if (rename(TEMP_FILE_PATH, filename) < 0) { exitWithError(); } return 0; }
void connectToSwitch(Switch *switchTrans, BankAuthorizer *autorizer) { struct sockaddr_in switchAddress; struct hostent *switchHost; // creo el scoket para conectarme switchTrans->fd = socket(AF_INET, SOCK_STREAM, 0); if (switchTrans->fd < 0) { exitWithError(); } // La dirección a la cual conectarse switchHost = gethostbyname(switchTrans->host); switchAddress.sin_family = AF_INET; switchAddress.sin_port = htons(switchTrans->port); bcopy((char *) switchHost->h_addr, (char *) &switchAddress.sin_addr.s_addr, switchHost->h_length); // me conecto al server if (connect(switchTrans->fd, (struct sockaddr*) &switchAddress, (socklen_t) sizeof(struct sockaddr_in)) < 0) { puts("Error conectandose al servidor"); exitWithError(); } if (!authenticateBank(switchTrans, autorizer)) { printf("Error de autenticación"); exit(EXIT_FAILURE); } sendServicePortToSwitch(switchTrans); }
void mapThreadsSpawn (Parameters *P, ReadAlignChunk** RAchunk) { for (int ithread=1;ithread<P->runThreadN;ithread++) {//spawn threads int threadStatus=pthread_create(&g_threadChunks.threadArray[ithread], NULL, &g_threadChunks.threadRAprocessChunks, (void *) RAchunk[ithread]); if (threadStatus>0) {//something went wrong with one of threads ostringstream errOut; errOut << "EXITING because of FATAL ERROR: phtread error while creating thread # " << ithread <<", error code: "<<threadStatus ; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, 1, *P); }; pthread_mutex_lock(&g_threadChunks.mutexLogMain); P->inOut->logMain << "Created thread # " <<ithread <<"\n"<<flush; pthread_mutex_unlock(&g_threadChunks.mutexLogMain); }; RAchunk[0]->processChunks(); //start main thread for (int ithread=1;ithread<P->runThreadN;ithread++) {//wait for all threads to complete int threadStatus = pthread_join(g_threadChunks.threadArray[ithread], NULL); if (threadStatus>0) {//something went wrong with one of threads ostringstream errOut; errOut << "EXITING because of FATAL ERROR: phtread error while joining thread # " << ithread <<", error code: "<<threadStatus ; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, 1, *P); }; pthread_mutex_lock(&g_threadChunks.mutexLogMain); P->inOut->logMain << "Joined thread # " <<ithread <<"\n"<<flush; pthread_mutex_unlock(&g_threadChunks.mutexLogMain); }; };
uint genomeScanFastaFiles (Parameters *P, char* G, bool flagRun) {//scans fasta files. flagRun=false: check and find full size, flaRun=true: collect all the data uint N=0;//total number of bases in the genome, including chr "spacers" if (!flagRun && P->chrLength.size()>0) {//previous chr records exist P->chrStart.pop_back();//remove last record, it will be recorded again N = P->chrStart.back()+P->chrLength.back(); P->chrLength.pop_back();//remove last record, it will be recorded again }; ifstream fileIn; for (uint ii=0;ii<P->genomeFastaFiles.size();ii++) {//all the input files fileIn.open(P->genomeFastaFiles.at(ii).c_str()); if ( !fileIn.good() ) {// ostringstream errOut; errOut << "EXITING because of INPUT ERROR: could not open genomeFastaFile: " <<P->genomeFastaFiles.at(ii) <<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; char cc=fileIn.peek(); if ( !fileIn.good() ) {// ostringstream errOut; errOut << "EXITING because of INPUT ERROR: could not read from genomeFastaFile: " <<P->genomeFastaFiles.at(ii) <<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; if (cc!='>') { ostringstream errOut; errOut << "EXITING because of INPUT ERROR: the file format of the genomeFastaFile: " <<P->genomeFastaFiles.at(ii) << "is not fasta:"; errOut << " the first character is " <<cc<<" , not > .\n"; errOut << " Solution: check formatting of the fasta file. Make sure the file is uncompressed (unzipped).\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; while(!fileIn.eof()) {//read each file until eof string lineIn (4096,'.'); getline(fileIn,lineIn); if (lineIn[0]=='>') {//new chromosome if (!flagRun) { istringstream lineInStream (lineIn); lineInStream.ignore(1,' '); string chrName1; lineInStream >> chrName1; P->chrName.push_back(chrName1); }; if (!flagRun && P->chrStart.size()>0) P->chrLength.push_back(N-P->chrStart.at(P->chrStart.size()-1)); //true length of the chr if (N>0) {//pad the chromosomes to bins boudnaries N = ( (N+1)/P->genomeChrBinNbases+1 )*P->genomeChrBinNbases; }; if (!flagRun) { P->chrStart.push_back(N); P->inOut->logMain << P->genomeFastaFiles.at(ii)<<" : chr # " << P->chrStart.size()-1 << " \""<<P->chrName.at(P->chrStart.size()-1)<<"\" chrStart: "<<N<<"\n"<<flush; }; } else {//char lines if (flagRun) lineIn.copy(G+N,lineIn.size(),0); N += lineIn.size(); }; };
int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in echoServAddr; /* Local address */ struct sockaddr_in echoClntAddr; /* Client address */ unsigned int cliAddrLen; /* Length of incoming message */ char echoBuffer[ECHOMAX]; /* Buffer for echo string */ unsigned short echoServPort; /* Server port */ int recvMsgSize; /* Size of received message */ if (argc != 2) /* Test for correct number of parameters */ { fprintf(stderr,"Usage: %s <UDP SERVER PORT>\n", argv[0]); exit(1); } echoServPort = atoi(argv[1]); /* First arg: local port */ /* Create socket for sending/receiving datagrams */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) exitWithError("socket() failed"); /* Construct local address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoServAddr.sin_port = htons(echoServPort); /* Local port */ /* Bind to the local address */ if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) exitWithError("bind() failed"); for (;;) /* Run forever */ { /* Set the size of the in-out parameter */ cliAddrLen = sizeof(echoClntAddr); /* Block until receive message from a client */ if ((recvMsgSize = recvfrom(sock, echoBuffer, ECHOMAX, 0, (struct sockaddr *) &echoClntAddr, &cliAddrLen) ) < 0) exitWithError("recvfrom() failed"); printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr)); // Create thread to handle client std::thread clientThread(handleClient, echoBuffer, sock, recvMsgSize, echoClntAddr); // Let the thread run independently clientThread.detach(); } /* NOT REACHED */ }
bool ScriptReaderBase::exitWithError(const io::stringc &Message, bool AppendTokenPos) { if (AppendTokenPos && Tkn_) return exitWithError(Message, Tkn_); io::Log::error(Message); return false; }
int changeAmmount(CreditCard *creditCard, float ammout) { FILE *fp; char buffer[BUFF_DEFAULT_SIZE]; char path[BUFF_DEFAULT_SIZE]; float balance = 0; sprintf(path, "./%s", creditCard->number); if ((fp = fopen(path, "r")) == NULL) { //exitWithError(); return -1; } if (fgets(buffer, BUFF_DEFAULT_SIZE, fp) < 0) { exitWithError(); } char *s = strtok(buffer, ":\n"); s = strtok(NULL, ":\n"); s = strtok(NULL, ":\n"); balance = atof(s); if (balance + ammout < 0) { return -1; } sprintf(buffer, "%s:%.2f:%.2f\n", ammout >= 0 ? "CRE" : "DEB", ammout, balance + ammout); fclose(fp); return addInFileAndClose(buffer, path); }
void sendServicePortToSwitch(Switch *switchTrans) { char buffer[BUFF_DEFAULT_SIZE]; sprintf(buffer, "%d", DEFAULT_BANK_PORT); if (write(switchTrans->fd, buffer, strlen(buffer) + 1) < 0) { exitWithError(); } }
bool ScriptReaderBase::validateBrackets() { const SToken* InvalidToken = 0; switch (TokenStream_->validateBrackets(InvalidToken)) { case VALIDATION_ERROR_UNEXPECTED: return exitWithError("Unexpected bracket token", InvalidToken); case VALIDATION_ERROR_UNCLOSED: return exitWithError("Unclosed brackets", InvalidToken); default: break; } return true; }
/* Creates Distributed Block Cyclic Layout Matrix Requires: - p * q = size of communication group - m % p*bm == 0 - n % q*bn == 0 */ void dist_matrix_init(MPI_Comm comm, struct dbcl_t *mat, int p, int q, int bm, int bn, int m, int n, double (*f)(int i, int j)) { int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); assert(p*q == size); assert(m % p*bm == 0); assert(n % q*bn == 0); // M,N are the number of blocks int gM = m / bm; int gN = n / bn; int lM = gM / p; int lN = gN / q; // Initialize datastructure MPI_Comm_dup(comm, &(mat->comm)); mat->p = p; mat->q = q; mat->lM = lM; mat->lN = lN; mat->bm = bm; mat->bn = bn; mat->m = m; mat->n = n; mat->value = malloc(sizeof(double) * (bm * bn) * (lM * lN)); if (mat->value == NULL) exitWithError("dist_matrix_init: malloc failed ( mat->value )"); // Fill matrix will values supplied from function f(i, j) int lbi, lbj; for ( lbj=0; lbj<lN; lbj++ ) { for ( lbi=0; lbi<lM; lbi++ ) { int block_offset = (lbi + lbj * lM) * (bm * bn); int i, j; for (i=0; i<bm; i++ ) { for (j=0; j<bn; j++ ) { int gi = (rank % p) * bm + lbi * (p * bm) + i; int gj = (rank / p) * bn + lbj * (q * bn) + j; int offset = i + (j * bm); if (gi < m && gj < n) { mat->value[block_offset + offset] = f(gi, gj); } else { mat->value[block_offset + offset] = 0.0; } } } } } }
void dist_matrix_print(struct dbcl_t *mat) { int rank, size; MPI_Comm_rank(mat->comm, &rank); MPI_Comm_size(mat->comm, &size); double *global_mat; if (rank == ROOT) { global_mat = malloc(sizeof(double) * (mat->m * mat->n)); if (global_mat == NULL) exitWithError("dist_matrix_print: malloc failed( global_mat )\n"); } int send_size = (mat->lM * mat->lN) * (mat->bm * mat->bn); int recv_size = send_size; MPI_Gather(mat->value, send_size, MPI_DOUBLE, global_mat, recv_size, MPI_DOUBLE, ROOT, mat->comm); if (rank == ROOT) { printf("Print Matrix >>> (m, n): %d %d (lM, lN): %d %d (bm, bn): %d %d (p, q): %d %d\n", mat->m, mat->n, mat->lM, mat->lN, mat->bm, mat->bn, mat->p, mat->q); int colors[] = {31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96}; int background[] = {003, 007}; int gi, gj; for (gi=0; gi<mat->m; gi++ ) { for (gj=0; gj<mat->n; gj++ ) { int i_rank = (gi / mat->bm) % mat->p + ((gj / mat->bn) % mat->q) * mat->p; int proc_offset = i_rank * (mat->lM * mat->lN) * (mat->bm * mat->bn); int lbi = gi / (mat->bm * mat->p); int lbj = gj / (mat->bn * mat->q); int block_offset = (lbi + lbj * mat->lM) * (mat->bm * mat->bn); int i = gi % mat->bm; int j = gj % mat->bn; int index_offset = i + (j * mat->bm); char format_buffer[16]; sprintf(format_buffer, "\033[%d;%dm", background[(lbi + lbj) % 2], colors[i_rank % 14]); printf("%s%2.1f\033[0m ", format_buffer, global_mat[proc_offset + block_offset + index_offset]); } printf("\n"); } printf("\n"); free(global_mat); } MPI_Barrier(mat->comm); }
void ofstrOpen (std::string fileName, std::string errorID, Parameters *P, ofstream & ofStream) {//open file 'fileName', generate error if cannot open ofStream.open(fileName.c_str(), std::fstream::out | std::fstream::trunc); if (ofStream.fail()) {// // dir1=fileName.substr(0,fileName.find_last_of("/")+1); // if (dir1=="") dir1="./"; ostringstream errOut; errOut << errorID<<": exiting because of *OUTPUT FILE* error: could not create output file "<< fileName <<"\n"; errOut << "Solution: check that the path exists and you have write permission for this file\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_FILE_OPEN, *P); }; };
void Genome::HandleSharedMemoryException(const SharedMemoryException & exc, uint64 shmSize) { ostringstream errOut; errOut << "Shared memory error: " << exc.GetErrorCode() << ", errno: " << strerror(exc.GetErrorDetail()) << "(" << errno << ")" << endl; int exitCode = EXIT_CODE_SHM; switch (exc.GetErrorCode()) { case EOPENFAILED: errOut << "EXITING because of FATAL ERROR: problems with shared memory: error from shmget() or shm_open()." << endl << flush; errOut << "SOLUTION: check shared memory settings as explained in STAR manual, OR run STAR with --genomeLoad NoSharedMemory to avoid using shared memory" << endl << flush; break; case EEXISTS: errOut << "EXITING: fatal error from shmget() trying to allocate shared memory piece." << endl; errOut << "Possible cause 1: not enough RAM. Check if you have enough RAM of at least " << shmSize+2000000000 << " bytes" << endl; errOut << "Possible cause 2: not enough virtual memory allowed with ulimit. SOLUTION: run ulimit -v " << shmSize+2000000000 << endl; errOut << "Possible cause 3: allowed shared memory size is not large enough. SOLUTIONS: (i) consult STAR manual on how to increase shared memory allocation; " \ "(ii) ask your system administrator to increase shared memory allocation; (iii) run STAR with --genomeLoad NoSharedMemory" << endl<<flush; break; case EFTRUNCATE: errOut << "EXITING: fatal error from ftruncate() error shared memory." << endl; errOut << "Possible cause 1: not enough RAM. Check if you have enough RAM of at least " << shmSize+2000000000 << " bytes" << endl << flush; exitCode = EXIT_CODE_MEMORY_ALLOCATION; break; case EMAPFAILED: errOut << "EXITING because of FATAL ERROR: problems with shared memory: error from shmat() while trying to get address of the shared memory piece." << endl << flush; errOut << "SOLUTION: check shared memory settings as explained in STAR manual, OR run STAR with --genomeLoad NoSharedMemory to avoid using shared memory" << endl << flush; break; case ECLOSE: errOut << "EXITING because of FATAL ERROR: could not close the shared memory object." << endl << flush; break; case EUNLINK: #ifdef POSIX_SHARED_MEM errOut << "EXITING because of FATAL ERROR: could not delete the shared object." << endl << flush; #else errOut << "EXITING because of FATAL ERROR: problems with shared memory: error from shmctl() while trying to remove shared memory piece." << endl << flush; errOut << "SOLUTION: check shared memory settings as explained in STAR manual, OR run STAR with --genomeLoad NoSharedMemory to avoid using shared memory" << endl << flush; #endif break; default: errOut << "EXITING because of FATAL ERROR: There was an issue with the shared memory allocation. Try running STAR with --genomeLoad NoSharedMemory to avoid using shared memory."; break; } try { if (sharedMemory != NULL) sharedMemory->Clean(); } catch(...) {} exitWithError(errOut.str(),std::cerr, P->inOut->logMain, exitCode, *P); };
void BAMbinSortByCoordinate(uint32 iBin, uint binN, uint binS, uint nThreads, string dirBAMsort, Parameters *P) { if (binS==0) return; //nothing to do for empty bins //allocate arrays char *bamIn=new char[binS]; uint *startPos=new uint[binN*3]; uint bamInBytes=0; //load all aligns for (uint it=0; it<nThreads; it++) { string bamInFile=dirBAMsort+to_string(it)+"/"+to_string((uint) iBin); ifstream bamInStream (bamInFile.c_str()); bamInStream.read(bamIn+bamInBytes,binS);//read the whole file bamInBytes += bamInStream.gcount(); bamInStream.close(); remove(bamInFile.c_str()); }; if (bamInBytes!=binS) { ostringstream errOut; errOut << "EXITING because of FATAL ERROR: number of bytes expected from the BAM bin does not agree with the actual size on disk: "; errOut << binS <<" "<< bamInBytes <<" "<< iBin <<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, 1, *P); }; //extract coordinates for (uint ib=0,ia=0;ia<binN;ia++) { uint32 *bamIn32=(uint32*) (bamIn+ib); startPos[ia*3] =( ((uint) bamIn32[1]) << 32) | ( (uint)bamIn32[2] ); startPos[ia*3+2]=ib; ib+=bamIn32[0]+sizeof(uint32);//note that size of the BAM record does not include the size record itself startPos[ia*3+1]=*( (uint*) (bamIn+ib) ); //read order ib+=sizeof(uint); }; //sort qsort((void*) startPos, binN, sizeof(uint)*3, funCompareUint2); BGZF *bgzfBin; bgzfBin=bgzf_open((dirBAMsort+"/b"+to_string((uint) iBin)).c_str(),("w"+to_string((long long) P->outBAMcompression)).c_str()); outBAMwriteHeader(bgzfBin,P->samHeaderSortedCoord,P->chrName,P->chrLength); //send ordered aligns to bgzf one-by-one for (uint ia=0;ia<binN;ia++) { char* ib=bamIn+startPos[ia*3+2]; bgzf_write(bgzfBin,ib, *((uint32*) ib)+sizeof(uint32) ); }; bgzf_flush(bgzfBin); bgzf_close(bgzfBin); //release memory delete [] bamIn; delete [] startPos; };
int* prepareDataFile(const char* imagePath) { // Create a buffer for the name of the image char out_name[256]; // Set the name of the image sprintf(out_name, "%s/out.data", imagePath); // Create an output file int* fout = (int*)malloc(sizeof(int)); *fout = open(out_name, O_CREAT | O_RDWR | O_NONBLOCK, 000777); if (*fout == -1) exitWithError(out_name); return fout; }
// Open the camera device as a file void openDevice(const char* location, int* fd) { *fd = open(location, O_RDWR, 0); if(*fd==1) { exitWithError("Open camera failed"); } else { printf("Opened Camera"); } }
int main(int argc, char *argv[]) { int *fd = (int*)malloc(sizeof(int)), qual = 0, fps = 0, bufSize = 0; char *camera; if(argc != 5) // Check correct number of args { char errorMsg[256]; sprintf(errorMsg, "usage: %s cameraDevice JpegQuality fps bufferSize", argv[0]); exitWithError(errorMsg); } else { camera = argv[1]; // camera location // Image quality if(atoi(argv[2]) > 0 && atoi(argv[2]) <= 100) qual = atoi(argv[2]); else exitWithError("Set JpegQuality between 1 and 100 inclusive."); // frame delay if(atoi(argv[3]) > 0) fps = atoi(argv[3]); // list size if(atoi(argv[4]) > 0) bufSize = atoi(argv[4]); } printf("Camera Interface Copyright (C) 2012 Jacob Appleton\n\n"); printf("This program comes with ABSOLUTELY NO WARRANTY;\n"); printf("This is free software, and you are welcome to redistribute it \n"); printf("under certain conditions.\n"); printf("Visit http://www.gnu.org/licenses/gpl.html for more details.\n\n"); *fd = -1; openDevice(camera, fd); getCapabilities(fd); int* imageCaptureType = (int*)malloc(sizeof(int)); *imageCaptureType = V4L2_BUF_TYPE_VIDEO_CAPTURE; getFrames(1, 1, fd, imageCaptureType, qual, fps, bufSize); // Turn the stream off - this will turn off the camera's LED light ioctl(*fd, VIDIOC_STREAMOFF, imageCaptureType); closeDevice(fd); free(fd); free(imageCaptureType); pthread_exit(NULL); return 0; }
int authenticateBank(Switch *switchTrans, BankAuthorizer *user) { printf("Usuario: %ld\n", user->id); printf("Password: %s\n", user->password); char buffer[BUFF_DEFAULT_SIZE]; if (write(switchTrans->fd, "authbanco", 16) < 0) { exitWithError(); } if (read(switchTrans->fd, buffer, BUFF_DEFAULT_SIZE) < 0) { exitWithError(); } sprintf(buffer, "%ld", user->id); if (write(switchTrans->fd, buffer, strlen(buffer) + 1) < 0) { exitWithError(); } if (read(switchTrans->fd, buffer, BUFF_DEFAULT_SIZE) < 0) { exitWithError(); } if (write(switchTrans->fd, user->password, strlen(user->password) + 1) < 0) { exitWithError(); } if (read(switchTrans->fd, buffer, BUFF_DEFAULT_SIZE) < 0) { exitWithError(); } return atoi(buffer); }
void ifstrOpen (std::string fileName, std::string errorID, std::string solutionString, Parameters *P, ifstream & ifStream) { //open file 'fileName', generate error if cannot open ifStream.open(fileName.c_str()); if (ifStream.fail()) {// ostringstream errOut; errOut << errorID<<": exiting because of *INPUT FILE* error: could not open input file "<< fileName <<"\n"; errOut << "Solution: check that the file exists and you have read permission for this file\n"; if (solutionString.size()>0) { errOut << " "<< solutionString <<"\n"; }; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_FILE_OPEN, *P); }; };
void processTransactions() { int sockopt = 1; int fd, fd2; /* los ficheros descriptores */ struct sockaddr_in server; /* para la información de la dirección del servidor */ struct sockaddr_in client; /* para la información de la dirección del cliente */ socklen_t sin_size; /* A continuación la llamada a socket() */ if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { exitWithError(); } server.sin_family = AF_INET; server.sin_port = htons(DEFAULT_BANK_PORT); server.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY coloca nuestra dirección IP automáticamente */ bzero(&(server.sin_zero), 8); /* escribimos ceros en el reto de la estructura */ if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(int)) == -1) { exitWithError(); } /* A continuación la llamada a bind() */ if (bind(fd, (struct sockaddr*) &server, sizeof(struct sockaddr)) == -1) { exitWithError(); } if (listen(fd, 5) == -1) { /* llamada a listen() */ exitWithError(); } if (signal(SIGINT, intHandler) == SIG_ERR) { exitWithError(); } while (keepRunning) { sin_size = sizeof(struct sockaddr_in); /* A continuación la llamada a accept() */ if ((fd2 = accept(fd, (struct sockaddr *) &client, &sin_size)) == -1) { exitWithError(); } hablar(fd2); close(fd2); /* cierra fd2 */ } printf("deslogeandose\n"); }
// Get a frame from the camera device void getFrames(int noFrames, int minNoFrames, int* fd, int* imgCaptureType, int cqual, int fps, int bufferSize) { struct v4l2_buffer buf; struct buffer* bufs; struct v4l2_requestbuffers reqbuf = getReqBufs(noFrames, minNoFrames, fd); unsigned int n_buffers, i, ctr = 0; bool started = FALSE, streamOn = false; struct lstnode* cNode = allocate(bufferSize); pthread_mutex_t* mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(mutex, NULL); struct imgDetails det = getFrameFormat(fd); // get video format details bufs = (struct buffer*)calloc(reqbuf.count, sizeof(*bufs)); // alloc buffers // If allocation fails if (bufs == NULL) exitWithError("Could not allocate buffers."); // Map the memory in kernel space to user space to access video efficiently for (n_buffers = 0; n_buffers < reqbuf.count; n_buffers++) { mapBuffer(reqbuf, n_buffers, buf, bufs, fd); } // Queue the request struct to v4l2 to retrieve the video data mem location for(i = 0; i < reqbuf.count; i++) queueBuffer(i, buf, fd); streamOn = turnOnCamera(fd, streamOn, imgCaptureType); // turn on camera while(true) //forever { if(!started) // if the write data thread has not yet been started { started = TRUE; createThread(cNode, mutex); } for(i = 0; i < reqbuf.count; i++) // for each frame returned { usleep(fps); // maintain steady frame rate pthread_mutex_lock(mutex); // lock pointers createImage(buf, bufs, i, cNode, fd, det, cqual); cNode = cNode->next; // work with the next node in the list printf("|%d|\n", ctr++); pthread_mutex_unlock(mutex); // release locks queueBuffer(i, buf, fd); // queue up a new buffer } } for (i = 0; i < reqbuf.count; ++i) // unmap memory { munmap(bufs[i].start, bufs[i].length); } free(mutex); free(cNode); free(bufs); }
void sjdbLoadFromFiles(Parameters *P, SjdbClass &sjdbLoci) { if (P->sjdbFileChrStartEnd.at(0)!="-") { for (uint ifile=0;ifile<P->sjdbFileChrStartEnd.size(); ifile++) { ifstream sjdbStreamIn ( P->sjdbFileChrStartEnd.at(ifile).c_str() ); if (sjdbStreamIn.fail()) { ostringstream errOut; errOut << "FATAL INPUT error, could not open input file sjdbFileChrStartEnd=" << P->sjdbFileChrStartEnd.at(ifile) <<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; sjdbLoadFromStream(sjdbStreamIn, sjdbLoci); P->inOut->logMain << "Loaded database junctions from file: " << P->sjdbFileChrStartEnd.at(ifile) <<", total number of junctions: "<<sjdbLoci.chr.size()<<" junctions\n\n"; }; }; //if (P->sjdbFileChrStartEnd!="-") };
void sjdbInsertJunctions(Parameters *P, Genome &genome) { SjdbClass sjdbLoci; time_t rawtime; //load 1st pass junctions if (P->twoPass.pass1sjFile.size()>0) { ifstream sjdbStreamIn ( P->twoPass.pass1sjFile.c_str() ); if (sjdbStreamIn.fail()) { ostringstream errOut; errOut << "FATAL INPUT error, could not open input file with junctions from the 1st pass="******"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; sjdbLoadFromStream(sjdbStreamIn, sjdbLoci); time ( &rawtime ); P->inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the 1st pass file: " << P->twoPass.pass1sjFile <<": "<<sjdbLoci.chr.size()<<" total junctions\n\n"; }; //load from junction files if (P->sjdbFileChrStartEnd.at(0)!="-") { sjdbLoadFromFiles(P,sjdbLoci); P->inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the sjdbFileChrStartEnd file(s), " << sjdbLoci.chr.size()<<" total junctions\n\n"; }; //load from GTF if (P->sjdbGTFfile!="-") { loadGTF(sjdbLoci, P, P->genomeDirOut); P->inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the GTF file: " << P->sjdbGTFfile<<": "<<sjdbLoci.chr.size()<<" total junctions\n\n"; }; sjdbPrepare (sjdbLoci, P, genome.G, P->nGenome, P->twoPass.dir);//P->nGenome - change when replacing junctions time ( &rawtime ); P->inOut->logMain << timeMonthDayTime(rawtime) << " Finished preparing junctions" <<endl; //insert junctions into the genome and SA and SAi sjdbBuildIndex (P, genome.G, genome.SA, genome.SA2, genome.SAi); time ( &rawtime ); *P->inOut->logStdOut << timeMonthDayTime(rawtime) << " ..... Finished inserting 1st pass junctions into genome" <<endl; //re-calculate genome-related parameters P->winBinN = P->nGenome/(1LLU << P->winBinNbits)+1; };
int main(int argc, char *argv[]) { if(argc != 3) { exitWithError("Usage: tstream2jpeg data_file_path outputPath"); } char* tStreamPath = argv[1]; // Set the file in path char jpegPath[255]; // Buffer for current working dir int i = 0, len, ctr = 0; char* workingDir = argv[2]; //getcwd(workingDir, 255); // Get current working directory FILE* tstream = fopen(tStreamPath, "rb"); // Open the telemetry stream fseek(tstream, 0, SEEK_END); // Seek to EOF len = ftell(tstream); // Find file size fseek(tstream, 0, SEEK_SET); // Seek to beginning of file byte* buf = (byte*)malloc(len); // Allocate file in memory fread(buf, 1, len-1, tstream); // Read file into memory sprintf(jpegPath, "%s/image%d.jpeg", workingDir, i++); FILE* jpeg = fopen(jpegPath, "wb"); while(ctr < len) // While not at end of buffer { ctr++; // Ignore first 0xAA ctr += 2; // Ignore bytes received byte conBytes[2]; // Buffer for bytes contained conBytes[1] = *(buf+(ctr++)); // Fill buffer conBytes[0] = *(buf+(ctr++)); // Fill buffer uint16_t con = byteToInt(conBytes); // Get int of bytes contained printf("Creating image of size %d bytes\n", con); if(*(buf+ctr) == 0xFF && *(buf+ctr+1) == 0xD8) { fclose(jpeg); sprintf(jpegPath, "%s/image%d.jpeg", workingDir, i++); jpeg = fopen(jpegPath, "wb"); } // Open JPEG for writing fwrite(buf+ctr, 1, con, jpeg); // Write to the JPEG ctr += con; // Move ptr past image data ctr++; // Ignore checksum } free(buf); fclose(tstream); return EXIT_SUCCESS; }
float checkBalance(CreditCard *creditCard) { FILE *fp; char buffer[BUFF_DEFAULT_SIZE]; char path[BUFF_DEFAULT_SIZE]; sprintf(path, "./%s", creditCard->number); if ((fp = fopen(path, "r")) == NULL) { //exitWithError(); return -1; } if (fgets(buffer, BUFF_DEFAULT_SIZE, fp) < 0) { exitWithError(); } char *s = strtok(buffer, ":\n"); s = strtok(NULL, ":\n"); s = strtok(NULL, ":\n"); return atof(s); }
void ReadAlignChunk::chunkFstreamOpen(string filePrefix, int iChunk, fstream &fstreamOut) {//open fstreams for chunks ostringstream fNameStream1; fNameStream1 << filePrefix << iChunk; string fName1=fNameStream1.str(); P->inOut->logMain << "Opening the file: " << fName1 << " ... " <<flush; remove(fName1.c_str()); //remove the file fstreamOut.open(fName1.c_str(),ios::out); //create empty file fstreamOut.close(); fstreamOut.open(fName1.c_str(), ios::in | ios::out); //re-open the file in in/out mode if (fstreamOut.fail()) { P->inOut->logMain << "failed!\n"; ostringstream errOut; errOut << "EXITING because of FATAL ERROR: could not create output file "<< fName1 << "\n"; errOut << "Solution: check that you have permission to write this file\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; P->inOut->logMain << "ok" <<endl; };
int isValidCreditCard(CreditCard *creditCard) { char buffer[100]; int read; FILE *fp; if ((fp = fopen( "./accounts.txt", "r")) == NULL) { exitWithError(); } while (fgets(buffer, BUFF_DEFAULT_SIZE, fp) != NULL) { if (buffer != NULL) { if (strncmp(creditCard->number, buffer, strlen(creditCard->number)) == 0) { return isCreditCardAndPassCorrect(buffer, creditCard); } } } return 0; }
uint Genome::OpenStream(string name, ifstream & stream) { stream.open((P->genomeDir+ "/" +name).c_str(), ios::binary); if (!stream.good()) { ostringstream errOut; errOut << "EXITING because of FATAL ERROR: could not open genome file "<< P->genomeDir << "/" << name <<"\n" << endl; errOut << "SOLUTION: check that the path to genome files, specified in --genomeDir is correct and the files are present, and have user read permsissions\n" <<flush; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_GENOME_FILES, *P); }; uint size = 0; P->inOut->logMain << "checking " << name << " size"; stream.seekg (0, ios::end); size=(uint) stream.tellg(); stream.clear(); stream.seekg (0, ios::beg); P->inOut->logMain << "file size: "<< size <<" bytes; state: good=" <<stream.good()\ <<" eof="<<stream.eof()<<" fail="<<stream.fail()<<" bad="<<stream.bad()<<"\n"<<flush; return size; }
void fstreamWriteBig(std::ofstream &S, char* A, unsigned long long N, std::string fileName, std::string errorID, Parameters *P) { struct statvfs statvfsBuf; statvfs(fileName.c_str(), &statvfsBuf); P->inOut->logMain << "Writing " << N << " bytes into " <<fileName << " ; empty space on disk = " << statvfsBuf.f_bavail * statvfsBuf.f_bsize <<" bytes ..." <<flush; unsigned long long C=0; unsigned long long iC; for (iC=0; iC<N/fstream_Chunk_Max; iC++) { S.write(A+C,fstream_Chunk_Max); C+=fstream_Chunk_Max; }; if (!S.fail()) S.write(A+C,N%fstream_Chunk_Max); if (S.fail()) {//failed to write struct statvfs statvfsBuf; statvfs(fileName.c_str(), &statvfsBuf); // system(( "ls -lL "+ P->genomeDir + " > "+ P->genomeDir +"/error.info 2>&1").c_str()); // ifstream error_info((P->genomeDir +"/error.info").c_str()); // P->inOut->logMain <<error_info.rdbuf(); struct stat statBuf; stat(fileName.c_str(), &statBuf); remove(fileName.c_str()); ostringstream errOut; errOut << errorID<<": exiting because of *OUTPUT FILE* error: could not write the output file "<< fileName <<"\n"; errOut << "fail()=" <<S.fail() <<" ; bad()="<< S.bad()<<"\n"; errOut << "Error while trying to write chunk # " << iC << "; "<< C << " bytes\n"; errOut << "File size full = "<< N <<" bytes\n"; errOut << "File size on disk = " << statBuf.st_size<<" bytes\n"; errOut << "Solution: check that you have enough space on the disk\n"; errOut << "Empty space on disk = " << statvfsBuf.f_bavail * statvfsBuf.f_bsize <<" bytes\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_FILE_WRITE, *P); }; P->inOut->logMain << " done\n" <<flush; };
Node *NewickTreeReader::readNode(std::istream &in) const { Node *node = new Node(); if(characterStartsBranchNode(peekNextCharacter(in))) { ignoreNextCharacter(in); Node* leftChild = readNode(in); node->setLfDesc(leftChild); leftChild->setAnc(node); if(characterStartsNextChildNode(peekNextCharacter(in))) { ignoreNextCharacter(in); Node* rightChild = readNode(in); node->setRtDesc(rightChild); rightChild->setAnc(node); } else { exitWithError("Tree is not bifurcating."); } ignoreNextCharacter(in); } node->setName(readName(in)); node->setBrlen(readBranchLength(in)); if (node->getLfDesc() == NULL && node->getRtDesc() == NULL) { node->setIsTip(true); } return node; }