void angsd_set_mafs_header(angsd_io_t *mafs) { size_t N=256; char *my_string; my_string = (char *) malloc (N); int i = angsd_getline(&my_string, &N, mafs); char **header = splitstr(my_string); if (header) { for (i = 0; *(header + i); i++) { if (strcmp(*(header+i), "chromo")==0) mafs->chromo = i; else if (strcmp(*(header+i), "position")==0) mafs->position = i; else if (strcmp(*(header+i), "major")==0) mafs->major = i; else if (strcmp(*(header+i), "minor")==0) mafs->minor = i; else if (strcmp(*(header+i), "anc")==0) mafs->anc = i; else if (strcmp(*(header+i), "knownEM")==0) mafs->knownEM = i; else if (strcmp(*(header+i), "nInd")==0) mafs->nInd = i; } free(header); } }
int rd_coords( FILE *istream, double ***ptr_pcoords, int *ncoords ) { int n,i,status=0; double **p_coords; char line[MAXLENGTH],**p_parse; p_coords = dmatrix(2,MAX_N_COORDS); n=0; while (fgets( line, MAXLENGTH, istream ) != NULL) { if (n>=MAX_N_COORDS) { fprintf(stderr,"ERROR: Too many sources. Max=%d\n",MAX_N_COORDS); free_dmatrix(p_coords); return(ERRNO_INPUT_ERROR); } p_parse = svector(2,MAXLENGTH); splitstr(line,p_parse,SPACES); *(*(p_coords+0)+n) = atof(p_parse[0]); *(*(p_coords+1)+n) = atof(p_parse[1]); n++; free_svector(p_parse); } *ncoords = n; *ptr_pcoords = dmatrix(2,*ncoords); for (i=0;i<*ncoords;i++) { *(*(*ptr_pcoords + 0) + i) = *(*(p_coords+0)+i); *(*(*ptr_pcoords + 1) + i) = *(*(p_coords+1)+i); } free_dmatrix(p_coords); return(status); }
bool HttpClient::readStatus() { LineReader reader(_conn->stream()); if (reader.readLine(_line) && (splitstr(_line, "\t ", _split) >= 2)) { if (_split[0] == "HTTP/1.0") { _header.version = 0; } else if (_split[0] == "HTTP/1.1") { _header.version = 1; } else { _handler.handleFailure(strfmt("unknown HTTP version: '%s'", _split[0].c_str())); return false; } _header.status = atoi(_split[1].c_str()); if (_header.status != 200) { _handler.handleFailure(strfmt("HTTP status not 200: '%s'", _split[1].c_str())); return false; } return true; } if (_conn->stream().tainted()) { _handler.handleFailure(strfmt("Connection error: %s", _conn->stream().tainted().reason().c_str())); } else { _handler.handleFailure(strfmt("could not parse HTTP status line: '%s'", _line.c_str())); } return false; }
int main() { int i,y,test_size=1000,size_ret; char test_str[32768]; char buf[16]; char *test_str_array[test_size]; const char **ret; for (i=0;i<test_size;i++) { snprintf(buf,16,"arg%d",i); test_str_array[i] = strdup(buf); } for (i=0;i<test_size;i++) { test_str[0]='\0'; for (y=0;y<i;y++) { snprintf(buf,16,"arg%d ",y); strncat(test_str,buf,16); } ret = splitstr(test_str,NULL,&size_ret); assert(size_ret == i); for (y=0;y<i;y++) assert( strcmp(ret[y],test_str_array[y])==0 ); splitstr_free(ret); } return 0; }
bool HttpClient::readHeaders() { LineReader reader(_conn->stream()); while (reader.readLine(_line)) { if (_line.empty()) { return true; } if ((_line[0] == ' ') || (_line[0] == '\t')) { // ignore continuation headers } else if (_line.find("X-Yahoo-Vespa-") == 0) { if (splitstr(_line, ":\t ", _split) == 2) { _handler.handleHeader(_split[0], _split[1]); } } else { if (splitstr(_line, ":\t ", _split) > 1) { if (strcasecmp(_split[0].c_str(), "connection") == 0) { for (size_t i = 1; i < _split.size(); ++i) { if (strcasecmp(_split[i].c_str(), "keep-alive") == 0) { _handler.handleHeader(_split[0], _split[i]); _header.keepAliveGiven = true; } else if (strcasecmp(_split[i].c_str(), "close") == 0) { _handler.handleHeader(_split[0], _split[i]); _header.connectionCloseGiven = true; } } } else if (strcasecmp(_split[0].c_str(), "content-length") == 0 && _split.size() == 2) { _handler.handleHeader(_split[0], _split[1]); _header.contentLengthGiven = true; _header.contentLength = atoi(_split[1].c_str()); } else if (strcasecmp(_split[0].c_str(), "transfer-encoding") == 0 && strcasecmp(_split[1].c_str(), "chunked") == 0) { _handler.handleHeader(_split[0], _split[1]); _header.chunkedEncodingGiven = true; } } } } _handler.handleFailure("HTTP header did not end in empty line"); return false; }
mafs_t *set_mafs_results(angsd_io_t *mafs, angsd_io_t *counts) { int i; size_t N=256; char **res; char *input_str; mafs_t *mafs_res; input_str = (char *) malloc (N); // Get line i = angsd_getline(&input_str, &N, mafs); if (i < 0) return NULL; // Split string res = splitstr(input_str); // Set the results mafs_res = (mafs_t *)calloc (1, sizeof (mafs_t)); mafs_res->coverage = (int *) malloc (counts->nind_tot * sizeof(int)); mafs_res->position = atoi(res[mafs->position]); mafs_res->nInd = atoi(res[mafs->nInd]); strcpy(mafs_res->chromo, res[mafs->chromo]); strcpy(mafs_res->major, res[mafs->major]); strcpy(mafs_res->minor, res[mafs->minor]); strcpy(mafs_res->anc, res[mafs->anc]); // Use -doMajorMinor 5 where major is ancestral mafs_res->allele_freq = atof(res[mafs->knownEM]); free(input_str); input_str = (char *) malloc (N); // Get counts i = angsd_getline(&input_str, &N, counts); // Split string res = splitstr(input_str); int j; for (j=0; j<counts->nind_tot; j++) mafs_res->coverage[j] = atoi(res[j]); free(input_str); free(res); return mafs_res; }
void angsd_set_counts_nind(angsd_io_t *counts) { size_t N=256; char *my_string; my_string = (char *) malloc (N); int i = angsd_getline(&my_string, &N, counts); int nind ; char **header = splitstr(my_string); if (header) { for (i = 0; *(header + i); i++) nind = i + 1; free(header); } counts->nind_tot = nind; fprintf(stderr, "[angsd] [angsd_set_counts_nind]: saw %i individuals\n", nind); }
//------------------------------------------------------------- // //------------------------------------------------------------- static void *mtnfs_init(struct fuse_conn_info *conn) { int i; MTN *mtn = mtn_init(MODULE_NAME); MTNFS *mtnfs = calloc(1, sizeof(MTNFS)); mtnfs->mtn = mtn; getcwd(mtnfs->cwd, sizeof(mtnfs->cwd)); if(cmdopt.port){ mtn->mcast_port = atoi(cmdopt.port); } if(cmdopt.addr){ strcpy(mtn->mcast_addr, cmdopt.addr); } if(cmdopt.group){ mtn->groupstr = newstr(cmdopt.group); mtn->grouparg = splitstr(cmdopt.group, ","); } if(cmdopt.loglevel){ mtn->loglevel = atoi(cmdopt.loglevel); } if(cmdopt.pid){ if(*(cmdopt.pid) == '/'){ strcpy(mtnfs->pid, cmdopt.pid); }else{ sprintf(mtnfs->pid, "%s/%s", mtnfs->cwd, cmdopt.pid); } } mtn->logmode = cmdopt.dontfork ? MTNLOG_STDERR : MTNLOG_SYSLOG; mtnfs->file_mutex = malloc(sizeof(pthread_mutex_t) * mtn->max_open); for(i=0;i<mtn->max_open;i++){ pthread_mutex_init(&(mtnfs->file_mutex[i]), NULL); } mtnlogger(mtn, 0, "========================\n"); mtnlogger(mtn, 0, "%s start (ver %s)\n", MODULE_NAME, PACKAGE_VERSION); mtnlogger(mtn, 0, "MulticastIP: %s\n", mtn->mcast_addr); mtnlogger(mtn, 0, "PortNumber : %d\n", mtn->mcast_port); mtnlogger(mtn, 0, "MaxOpen : %d\n", mtn->max_open); if(mtn->groupstr){ mtnlogger(mtn, 0, "Group : %s\n", mtn->groupstr); } mtnlogger(mtn, 0, "DebugLevel : %d\n", mtn->loglevel); mkpidfile(mtnfs->pid); return(mtnfs); }
/* * Retrieve a Symbol's Contents * * "key" is not modified. * If the key cannot be found, NULL is returned */ void *sym_get(SYM sym, char *key) { char *nkey; const char **keys; /* key split into a 2d string array */ char **kk; SYM csym; /* search: current symbol table */ struct sym *nsym = NULL; /* search: found symbol entry */ if (sym == NULL) return (NULL); nkey = strdup(key); keys = splitstr(nkey, ",", NULL); if (keys == NULL) return (NULL); for (kk = (char **)keys, csym = sym; *kk != NULL && (nsym = find_key1(csym->sym, *kk)) != NULL; csym = nsym->data) { if (*++kk == NULL) break; if (nsym->data == NULL) { /* fatal error */ free(nkey); splitstr_free(keys); return (NULL); } if (((SYM) (nsym->data))->magic != SYM_MAGIC) { free(nkey); splitstr_free(keys); return (NULL); } } if (*kk == NULL) { /* found a complete match */ splitstr_free(keys); free(nkey); return (nsym->data); } else { splitstr_free(keys); free(nkey); return (NULL); } }
/** * Return actor information * [0]=id * [1]=name * [2]=image url */ Array *dbnames_fetch(char *key,char *file) { Array *result = NULL; char *record = dbnames_fetch_static(key,file); if (record) { // Find character after key and use as seperator char *p = strstr(record,key); if (p) { result = splitstr(record,NAME_SEP); if (result->size != 2 && result->size != 3) { HTML_LOG(0,"Bad actor info [%s]",record); array_free(result); result = NULL; } } } return result; }
STR mtnfile_console_path(STR opt) { int i; STR path; ARG dirs; path = newstr(ctx->remote_path); dirs = splitstr(opt, "/"); for(i=0;dirs[i];i++){ if(!strcmp(dirs[i], "..")){ path = modstr(path, dirname(path)); }else if(!strcmp(dirs[i], ".")){ }else{ if(lastchar(path) != '/'){ path = catstr(path, "/"); } path = catstr(path, dirs[i]); } } dirs = clrarg(dirs); return(path); }
int mtnfile_console() { int argc; ARG args; char *line; STR prompt = newstr("mtn:/> "); ctx->remote_path = newstr("/"); rl_attempted_completion_function = mtnfile_console_readline_callback; while((line = readline(prompt))){ if(!strlen(line)){ free(line); continue; } args = splitstr(line, " "); argc = cntarg(args); if(!argc){ free(line); continue; }else if(!strcmp(args[0], "exit")){ break; }else if(!strcmp(args[0], "quit")){ break; }else if(!strcmp(args[0], "help")){ mtnfile_console_help(args[1]); }else if(!strcmp(args[0], "ls" )){ mtnfile_console_ls(argc, args); }else if(!strcmp(args[0], "cd" )){ mtnfile_console_cd(argc, args); }else if(!strcmp(args[0], "lcd" )){ mtnfile_console_lcd(argc, args); }else if(!strcmp(args[0], "cat" )){ mtnfile_console_cat(argc, args); }else if(!strcmp(args[0], "get" )){ mtnfile_console_get(argc, args); }else if(!strcmp(args[0], "put" )){ mtnfile_console_put(argc, args); }else if(!strcmp(args[0], "del" )){ mtnfile_console_del(argc, args); }else{ mtnlogger(mtn, 0, "%s: no such command.\n", args[0]); } add_history(line); free(line); line = NULL; args = clrarg(args); prompt = modstr(prompt, "mtn:"); prompt = catstr(prompt, ctx->remote_path); prompt = catstr(prompt, "> "); } return(0); }
ctagread::enResult ctagread::process_ctags(void) { tempbuf sym(400), fil(500), classname(400), numtxt(50), linetxt(4001), fil2(500); long int num; int numOfLines=0; char* retval; int scanretval = 0; int rc; char c; char smallstr[2]; char *cp; strctagIDList classIDs, symIDs, parentClassIDs, parentClassIDs_temp; enResult res; std::vector<stClsID> listClsHist; *(fil.get()) = '%'; // for SQL LIKE pattern recognition smallstr[1] = 0; rc = prepare_stmt(&m_insertstmt, "INSERT INTO membertbl VALUES (?,?,?);"); if (rc!=0) return resSQLError; rc = prepare_stmt(&m_insertinheritstmt, "INSERT INTO inherittbl VALUES (?,?);"); if (rc!=0) return resSQLError; rc = prepare_stmt(&m_readclassstmt, "SELECT symID FROM symtbl WHERE symName=? AND symType=\"c\";"); if (rc!=0) return resSQLError; //rc = prepare_stmt(&m_readsymstmt, "SELECT symID FROM symtbl WHERE symName=? AND lineid IN (SELECT lineID FROM linestbl WHERE linenum=? AND fileid IN (SELECT fileID FROM filestbl WHERE filePath LIKE ?));"); rc = prepare_stmt(&m_readsymstmt, "SELECT symtbl.symID FROM symtbl INNER JOIN linestbl ON (symtbl.symName=? AND symtbl.lineID = linestbl.lineID AND linestbl.linenum=?) INNER JOIN filestbl ON (linestbl.fileID = filestbl.fileID AND filePath LIKE ?);"); if (rc!=0) return resSQLError; rc = prepare_stmt(&m_writedeststmt, "UPDATE symtbl SET symName=? WHERE symID=?;"); if (rc!=0) return resSQLError; //rc = prepare_stmt(&m_readsymfstmt, "SELECT symID FROM symtbl WHERE symName=? AND symType=\"$\" AND lineid IN (SELECT lineID FROM linestbl WHERE linenum=? AND fileid IN (SELECT fileID FROM filestbl WHERE filePath LIKE ?));"); rc = prepare_stmt(&m_readsymfstmt, "SELECT symtbl.symID FROM symtbl INNER JOIN linestbl ON (symtbl.symName=? AND symtbl.symType=\"$\" AND symtbl.lineID = linestbl.lineID AND linestbl.linenum=?) INNER JOIN filestbl ON (linestbl.fileID = filestbl.fileID AND filePath LIKE ?);"); if (rc!=0) return resSQLError; rc=sqlite3_exec(m_db, "BEGIN EXCLUSIVE;\ DROP INDEX IF EXISTS memberIDIdx;\ DROP INDEX IF EXISTS groupIDIdx;\ DROP INDEX IF EXISTS parentIDIdx;\ DROP INDEX IF EXISTS childIDIdx;\ DELETE FROM membertbl;\ DELETE FROM inherittbl;\ COMMIT;", NULL, 0, NULL); if (rc != SQLITE_OK) { if (m_debug) printf("SQLErr13: %d, %s\n", rc, sqlite3_errmsg(m_db)); return resSQLError; } do { retval = fgets(linetxt.get(), linetxt.size() - 1, f_tags); if (retval != NULL) { chomp(linetxt.get()); scanretval = sscanf(linetxt.get(), "%s\t%s\t%ld;\"\t%c\tclass:%s", sym.get(), fil2.get(), &num, &c, classname.get()); } if ((retval != NULL)&&(scanretval == 5)) { strcpy(fil.get(), "%"); strcat(fil.get(), extract_filename(fil2.get())); res = getHListOfClassIDs(&classIDs, classname.get(), &listClsHist); if (res != resOK) return res; if (classIDs.empty()) continue; cp = sym.get(); if (*(sym.get()) == '~') { cp = (sym.get()) + 1; //include destructors // which cscope missed out } sprintf(numtxt.get(), "%ld", num); if (c == 'f') res = getListOfSymIDs(m_readsymfstmt, &symIDs, cp, numtxt.get(), fil.get()); else res = getListOfSymIDs(m_readsymstmt, &symIDs, cp, numtxt.get(), fil.get()); if (res != resOK) { return res; } if (symIDs.empty() == false) { for (unsigned int i=0; i < symIDs.size(); i++) { smallstr[0] = c; rc=execstmt(m_insertstmt, classIDs[0].c_str(), symIDs[i].c_str(), smallstr); if (rc!=0) return resSQLError; if (*(sym.get()) == '~') { rc=execstmt(m_writedeststmt, sym.get(), symIDs[i].c_str()); if (rc!=0) return resSQLError; } numOfLines++; } } //else {if (m_debug) {printf("no match found for symbol: %s\n",sym.get());}} } else if (retval != NULL) { scanretval = sscanf(linetxt.get(), "%s\t%s\t%ld;\"\t%c\tinherits:%s", sym.get(), fil2.get(), &num, &c, classname.get()); if ((scanretval == 5)&&(c == 'c')) { res = getHListOfClassIDs(&classIDs, sym.get(), &listClsHist); if (res != resOK) return res; if (classIDs.empty()) continue; parentClassIDs.clear(); parentClassIDs_temp.clear(); std::vector<std::string> vecstr = splitstr(classname.get(), ','); for (unsigned int i=0; i<vecstr.size(); i++) { res = getHListOfClassIDs(&parentClassIDs_temp, vecstr[i].c_str(), &listClsHist); if (res != resOK) return res; while (parentClassIDs_temp.empty() == false) { parentClassIDs.push_back(parentClassIDs_temp.back()); parentClassIDs_temp.pop_back(); } } for (unsigned int i=0; i<parentClassIDs.size(); i++) { rc=execstmt(m_insertinheritstmt, parentClassIDs[i].c_str(), classIDs[0].c_str()); if (rc!=0) return resSQLError; } } } } while (retval != NULL); if (m_debug) printf ("Total membertbl records possible = %d\n", numOfLines); return resOK; }
ARG parse(int argc, char *argv[]) { int r; char *p; STR buff; ARG args; if(argc < 2){ usage(); exit(0); } optind = 0; while((r = getopt_long(argc, argv, "+hVvnBbig:j:e:I:RALT:P:N:m:p:d:f:D:", get_optlist(), NULL)) != -1){ switch(r){ case 'h': usage(); exit(0); case 'V': version(); exit(0); case 'F': ctx->info = 1; break; case 'f': ctx->arg_num = ctx->arg_num ? ctx->arg_num : 1; if(!strcmp("-", optarg)){ ctx->afd = 0; }else{ ctx->afd = open(optarg, O_RDONLY); if(ctx->afd == -1){ mtnlogger(mtn, 0, "[error] %s: %s %s\n", __func__, optarg, strerror(errno)); exit(1); } } break; case 't': test(); exit(0); case 'v': ctx->verbose = 1; break; case 'n': ctx->dryrun = 1; break; case 'i': ctx->conv = 1; break; case 'g': mtn->groupstr = newstr(optarg); mtn->grouparg = splitstr(optarg, ","); break; case 'j': ctx->cpu_lim = atoi(optarg) * 10; break; case 'e': ctx->echo = newstr(optarg); setbuf(stdout, NULL); break; case 'I': ctx->stdin = newstr(optarg); break; case 'O': ctx->stdout = newstr(optarg); break; case 'E': ctx->stderr = newstr(optarg); break; case 'S': ctx->putarg = splitstr(optarg, ","); break; case 'G': ctx->getarg = splitstr(optarg, ","); break; case 'B': ctx->text = 0; break; case 'b': ctx->nobuf = 0; break; case 'R': ctx->opt_R = 1; break; case 'A': ctx->opt_A = 1; break; case 'L': ctx->opt_L = 1; break; case 'P': ctx->job_max = atoi(optarg); break; case 'N': ctx->arg_num = atoi(optarg); break; case 'm': strcpy(mtn->mcast_addr, optarg); break; case 'p': mtn->mcast_port = atoi(optarg); break; case 'd': ctx->delim = modstr(ctx->delim, optarg); break; case 'D': mtn->loglevel = atoi(optarg); break; case 'T': buff = newstr(optarg); p = strtok(buff, ","); while(p){ ctx->targets = addarg(ctx->targets, p); p = strtok(NULL, ","); } break; case '?': usage(); exit(1); } } if(ctx->opt_R && ctx->opt_A){ usage(); exit(1); } if(ctx->opt_R && ctx->targets[0]){ usage(); exit(1); } if(ctx->opt_A && ctx->targets[0]){ usage(); exit(1); } if(ctx->opt_R){ ctx->mode = ctx->opt_L ? MTNEXECMODE_HYBRID : MTNEXECMODE_REMOTE; }else if(ctx->opt_A){ ctx->mode = ctx->opt_L ? MTNEXECMODE_ALL1 : MTNEXECMODE_ALL0; }else{ ctx->mode = ctx->targets[0] ? MTNEXECMODE_TARGET : MTNEXECMODE_LOCAL; } if(ctx->info){ info(); exit(0); } ctx->verbose = ctx->dryrun ? 0 : ctx->verbose; args = newarg(0); while(optind < argc){ if(strcmp(argv[optind], ":::") == 0){ optind++; ctx->linearg = newarg(0); break; } args = addarg(args, argv[optind++]); } if(ctx->linearg){ while(optind < argc){ ctx->linearg = addarg(ctx->linearg, argv[optind++]); } ctx->arg_num = ctx->arg_num ? ctx->arg_num : 1; } if((args[0] == NULL) && (ctx->arg_num == 0)){ ctx->arg_num = 1; } return(args); }
static pid_t run_child(struct coll_entry *colle, struct tag_pgrp *active, int quiet_mode, int *failcnt, int fmt_print, FILE * logfile) { ssize_t errlen; int cpid; int c_stdout = -1; /* child's stdout, stderr */ int capturing = 0; /* output is going to a file instead of stdout */ char *c_cmdline; static long cmdno = 0; int errpipe[2]; /* way to communicate to parent that the tag */ char errbuf[1024]; /* didn't actually start */ /* Try to open the file that will be stdout for the test */ if (test_out_dir) { capturing = 1; do { sprintf(active->output, "%s/%s.%ld", test_out_dir, colle->name, cmdno++); c_stdout = open(active->output, O_CREAT | O_RDWR | O_EXCL | O_SYNC, 0666); } while (c_stdout < 0 && errno == EEXIST); if (c_stdout < 0) { fprintf(stderr, "pan(%s): open of stdout file failed (tag %s). errno: %d %s\n file: %s\n", panname, colle->name, errno, strerror(errno), active->output); return -1; } } /* get the tag's command line arguments ready. subst_pcnt_f() uses a * static counter, that's why we do it here instead of after we fork. */ if (colle->pcnt_f) { c_cmdline = subst_pcnt_f(colle); } else { c_cmdline = colle->cmdline; } if (pipe(errpipe) < 0) { fprintf(stderr, "pan(%s): pipe() failed. errno:%d %s\n", panname, errno, strerror(errno)); if (capturing) { close(c_stdout); unlink(active->output); } return -1; } time(&active->mystime); active->cmd = colle; if (!test_out_dir) if (!quiet_mode) write_test_start(active); if ((cpid = fork()) == -1) { fprintf(stderr, "pan(%s): fork failed (tag %s). errno:%d %s\n", panname, colle->name, errno, strerror(errno)); if (capturing) { unlink(active->output); close(c_stdout); } close(errpipe[0]); close(errpipe[1]); return -1; } else if (cpid == 0) { /* child */ fclose(zoofile); close(errpipe[0]); fcntl(errpipe[1], F_SETFD, 1); /* close the pipe if we succeed */ setpgrp(); umask(0); #define WRITE_OR_DIE(fd, buf, buflen) do { \ if (write((fd), (buf), (buflen)) != (buflen)) { \ err(1, "failed to write out %zd bytes at line %d", \ buflen, __LINE__); \ } \ } while(0) /* if we're putting output into a buffer file, we need to do the * redirection now. If we fail */ if (capturing) { if (dup2(c_stdout, fileno(stdout)) == -1) { errlen = sprintf(errbuf, "pan(%s): couldn't redirect stdout for tag %s. errno:%d %s", panname, colle->name, errno, strerror(errno)); WRITE_OR_DIE(errpipe[1], &errlen, sizeof(errlen)); WRITE_OR_DIE(errpipe[1], errbuf, errlen); exit(2); } if (dup2(c_stdout, fileno(stderr)) == -1) { errlen = sprintf(errbuf, "pan(%s): couldn't redirect stderr for tag %s. errno:%d %s", panname, colle->name, errno, strerror(errno)); WRITE_OR_DIE(errpipe[1], &errlen, sizeof(errlen)); WRITE_OR_DIE(errpipe[1], errbuf, errlen); exit(2); } } else { /* stderr still needs to be redirected */ if (dup2(fileno(stdout), fileno(stderr)) == -1) { errlen = sprintf(errbuf, "pan(%s): couldn't redirect stderr for tag %s. errno:%d %s", panname, colle->name, errno, strerror(errno)); WRITE_OR_DIE(errpipe[1], &errlen, sizeof(errlen)); WRITE_OR_DIE(errpipe[1], errbuf, errlen); exit(2); } } /* If there are any shell-type characters in the cmdline * such as '>', '<', '$', '|', etc, then we exec a shell and * run the cmd under a shell. * * Otherwise, break the cmdline at white space and exec the * cmd directly. */ if (strpbrk(c_cmdline, "\"';|<>$\\")) { execlp("sh", "sh", "-c", c_cmdline, NULL); errlen = sprintf(errbuf, "pan(%s): execlp of '%s' (tag %s) failed. errno:%d %s", panname, c_cmdline, colle->name, errno, strerror(errno)); } else { char **arg_v; arg_v = (char **)splitstr(c_cmdline, NULL, NULL); execvp(arg_v[0], arg_v); errlen = sprintf(errbuf, "pan(%s): execvp of '%s' (tag %s) failed. errno:%d %s", panname, arg_v[0], colle->name, errno, strerror(errno)); } WRITE_OR_DIE(errpipe[1], &errlen, sizeof(errlen)); WRITE_OR_DIE(errpipe[1], errbuf, errlen); exit(errno); } /* parent */ /* subst_pcnt_f() allocates the command line dynamically * free the malloc to prevent a memory leak */ if (colle->pcnt_f) free(c_cmdline); close(errpipe[1]); /* if the child couldn't go through with the exec, * clean up the mess, note it, and move on */ if (read(errpipe[0], &errlen, sizeof(errlen))) { int status; time_t end_time; int termid; char *termtype; struct tms notime = { 0, 0, 0, 0 }; if (read(errpipe[0], errbuf, errlen) < 0) fprintf(stderr, "Failed to read from errpipe[0]\n"); close(errpipe[0]); errbuf[errlen] = '\0'; /* fprintf(stderr, "%s", errbuf); */ waitpid(cpid, &status, 0); if (WIFSIGNALED(status)) { termid = WTERMSIG(status); termtype = "signaled"; } else if (WIFEXITED(status)) { termid = WEXITSTATUS(status); termtype = "exited"; } else if (WIFSTOPPED(status)) { termid = WSTOPSIG(status); termtype = "stopped"; } else { termid = 0; termtype = "unknown"; } time(&end_time); if (logfile != NULL) { if (!fmt_print) { fprintf(logfile, "tag=%s stime=%d dur=%d exit=%s " "stat=%d core=%s cu=%d cs=%d\n", colle->name, (int)(active->mystime), (int)(end_time - active->mystime), termtype, termid, (status & 0200) ? "yes" : "no", 0, 0); } else { if (termid != 0) ++ * failcnt; fprintf(logfile, "%-30.30s %-10.10s %-5d\n", colle->name, ((termid != 0) ? "FAIL" : "PASS"), termid); } fflush(logfile); } if (!quiet_mode) { //write_test_start(active, errbuf); write_test_end(active, errbuf, end_time, termtype, status, termid, ¬ime, ¬ime); } if (capturing) { close(c_stdout); unlink(active->output); } return -1; } close(errpipe[0]); if (capturing) close(c_stdout); active->pgrp = cpid; active->stopping = 0; if (zoo_mark_cmdline(zoofile, cpid, colle->name, colle->cmdline)) { fprintf(stderr, "pan(%s): %s\n", panname, zoo_error); exit(1); } if (Debug & Dstartup) fprintf(stderr, "started %s cpid=%d at %s", colle->name, cpid, ctime(&active->mystime)); if (Debug & Dstart) { fprintf(stderr, "Executing test = %s as %s", colle->name, colle->cmdline); if (capturing) fprintf(stderr, "with output file = %s\n", active->output); else fprintf(stderr, "\n"); } return cpid; }
/* * Add (key, data) to an existing symbol table * * If the key does not exist, a new key is added to the end of the list. * If the key exists and the PUT_REPLACE flag is not supplied, return EEXIST. * If a symbol table entry in a multi-part key is not a symbol table (i.e. * element two of a three or more element key), return ENOTDIR. * * "data" is not duplicated and must not point to a static area that could * go away before the element is deleted (such as a local string in a * function) * * "key" is duplicated as needed, and is not modified. * * Code: * chop up key on commas * * search until a key element isn't found in the key tree, the key list is * exhausted, or a key's data element is not a sub-tree * * if the key list is exhausted, return a "duplicate entry" error * * if the last found key's data element is not a sub-tree, return * something like "ENOTDIR". * * add new keys for sub-trees until key list is exhausted; * last node gets 'data'. * */ int sym_put(SYM sym, char *key, void *data, int flags) { const char **keys; /* key split into a 2d string array */ char **kk; char *nkey; /* copy of 'key' -- before split */ SYM csym, ncsym; /* search: current symbol table */ struct sym *nsym = NULL; /* search: found symbol entry */ if (sym == NULL) return (EINVAL); nkey = strdup(key); keys = splitstr(key, ",", NULL); if (keys == NULL) { free(nkey); return (EINVAL); } for (kk = (char **)keys, csym = sym; *kk != NULL && (nsym = find_key1(csym->sym, *kk)) != NULL; csym = nsym->data) { if (*++kk == NULL) break; if (nsym->data == NULL) { /* fatal error */ free(nkey); splitstr_free(keys); return (ENOTDIR); } if (((SYM) (nsym->data))->magic != SYM_MAGIC) { free(nkey); splitstr_free(keys); return (ENOTDIR); } } if (*kk == NULL) { /* found a complete match */ free(nkey); splitstr_free(keys); if (flags == PUT_REPLACE) { nsym->data = data; return (0); } else { return (EEXIST); } } /* csym is a ptr to a list */ for (; *kk != NULL; kk++) { if (*(kk + 1) != NULL) { add_key(csym, *kk, (void *)(ncsym = newsym())); csym = ncsym; } else { add_key(csym, *kk, data); /* last key */ } } free(nkey); splitstr_free(keys); return (0); }
int artimg_snr(FILE *fstream, ARTIMGPARS pars, double **ppix, KLFITS_HEADER *headers, int *nheaders) { int ncol, status=0; long int xcenter,ycenter,ii,jj; double gcd,gcl,diameter,sb; double pc2pix,lum2flux,gcdpix,radius,sbinst,r; char line[2*MAXLENGTH],**p_parse; KLFITS_HEADER *h; pc2pix = (pars.artimg_distance * pars.artimg_pixscale) / SECPERRAD; lum2flux = 1./(4*PI*pow(pars.artimg_distance*MPERPC,2.)); p_parse=svector(MKSNRPOP_OUTPUT_NCOL,MAXLENGTH); while (fgets( line, 2*MAXLENGTH, fstream ) != NULL) { if (!strncmp(line,"#",1)) { h = create_list_klfits_header(); if (status = parse_popheader(line, h)) { fprintf(stderr,"ERROR: Parsing header in artimg_snr.\n"); fprintf(stderr,ERRMSG_INPUT_ERROR,line); return(status); } if ( h->datatype != 0 ) { add_klfits_header( h, &headers ); (*nheaders)++; } h = NULL; continue; } ncol = splitstr(line,p_parse,SPACES); if (ncol != MKSNRPOP_OUTPUT_NCOL) { fprintf(stderr,ERRMSG_INPUT_ERROR,""); return(ERRNO_INPUT_ERROR); } gcd = atof(p_parse[0]); gcl = atof(p_parse[1]); diameter = atof(p_parse[2]); sb = atof(p_parse[3]); gcdpix = gcd / pc2pix; xcenter = (long int)(pars.artimg_x0 + cos(gcl*PI/180.)*gcdpix); ycenter = (long int)(pars.artimg_y0 + sin(gcl*PI/180.)*gcdpix); radius = 0.5 * diameter / pc2pix; if ( (xcenter+radius < 1) || (xcenter-radius > pars.artimg_naxes[0]) || (ycenter+radius < 1) || (ycenter-radius > pars.artimg_naxes[1]) ) { continue; } sbinst = sb * pow(pc2pix,2) * lum2flux / pars.artimg_fluxcalib; for (jj=ycenter-radius-1; jj<ycenter+radius; jj++) { if ( (jj>=0) && (jj<pars.artimg_naxes[1]) ) { for (ii=xcenter-radius-1; ii<xcenter+radius; ii++) { if ( (ii>=0) && (ii<pars.artimg_naxes[0]) ) { r = sqrt( pow(ii-xcenter,2.) + pow(jj-ycenter,2.) ); if ( r <= radius ) { *(*(ppix+jj)+ii) += sbinst; } } } } } } free_svector(p_parse); return(status); }
unsigned int DispInfo::parse(std::istream& stream) { unsigned int numparsed = 0; std::string curline; while (trim(curline) != "{") { getline(stream, curline); numparsed++; } unsigned int depth = 1; std::map<std::string, std::map<std::string, std::string>> tempKeys; while (getline(stream, curline)) { numparsed++; if (trim(curline) == "}") { std::cout << "IS THIS REAL LIFE??\n"; if (--depth == 0) break; } else if (trim(curline) != "" && trim(curline)[0] != '\"') { auto cpos = stream.tellg(); std::string peekline; getline(stream, peekline); stream.seekg(cpos); if (trim(peekline) == "{") { std::string groupName = trim(curline); std::map<std::string, std::string> group; while (getline(stream, curline)) { numparsed++; if (trim(curline) == "}") { break; } else { KeyVal k(curline); group[k.key] = k.val; } } tempKeys[groupName] = move(group); } } else if (trim(curline) == "{") { ++depth; } else { KeyVal parsed(curline); keyvals[parsed.key] = parsed.val; } } int power = atoi(keyvals["power"].c_str()); int size = (int)pow(2, power) + 1; info = std::vector<std::vector<SingleDisp>>(size, std::vector<SingleDisp>(size, SingleDisp())); for (int row = 0; row < size; row++) { std::string rowID = "row"; rowID += std::to_string(row); auto norm = splitstr(tempKeys["normals"][rowID]); auto dist = splitstr(tempKeys["distances"][rowID]); auto off = splitstr(tempKeys["offsets"][rowID]); auto off_norm = splitstr(tempKeys["offset_normals"][rowID]); auto alpha = splitstr(tempKeys["alphas"][rowID]); for (int col = 0; col < size; col++) { auto& curInfo = info[row][col]; size_t vertInd = 3 * col; curInfo.normal = Vertex(norm[vertInd] + ' ' + norm[vertInd + 1] + ' ' + norm[vertInd + 2]); curInfo.distance = atof(dist[col].c_str()); curInfo.offset = Vertex(off[vertInd] + ' ' + off[vertInd + 1] + ' ' + off[vertInd + 2]); curInfo.offset_normal = Vertex(off_norm[vertInd] + ' ' + off_norm[vertInd + 1] + ' ' + off_norm[vertInd + 2]); curInfo.alpha = (char)atoi(alpha[col].c_str()); } } return numparsed; }