您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ strtod函数代码示例

51自学网 2021-06-03 08:32:24
  C++
这篇教程C++ strtod函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中strtod函数的典型用法代码示例。如果您正苦于以下问题:C++ strtod函数的具体用法?C++ strtod怎么用?C++ strtod使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了strtod函数的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: Assert

int CUtlBuffer::VaScanf( const char* pFmt, va_list list ){	Assert( pFmt );	if ( m_Error || !IsText() )		return 0;		int numScanned = 0;	int nLength;	char c;	char* pEnd;	while ( c = *pFmt++ )	{		// Stop if we hit the end of the buffer		if ( m_Get >= TellMaxPut() )		{			m_Error |= GET_OVERFLOW;			break;		}		switch (c)		{		case ' ':			// eat all whitespace			EatWhiteSpace();			break;		case '%':			{				// Conversion character... try to convert baby!				char type = *pFmt++;				if (type == 0)					return numScanned;				switch(type)				{				case 'c':					{						char* ch = va_arg( list, char * );						if ( CheckPeekGet( 0, sizeof(char) ) )						{							*ch = *(const char*)PeekGet();							++m_Get;						}						else						{							*ch = 0;							return numScanned;						}					}				break;				case 'i':				case 'd':					{						int* i = va_arg( list, int * );						// NOTE: This is not bullet-proof; it assumes numbers are < 128 characters						nLength = 128;						if ( !CheckArbitraryPeekGet( 0, nLength ) )						{							*i = 0;							return numScanned;						}						*i = strtol( (char*)PeekGet(), &pEnd, 10 );						int nBytesRead = (int)( pEnd - (char*)PeekGet() );						if ( nBytesRead == 0 )							return numScanned;						m_Get += nBytesRead;					}					break;								case 'x':					{						int* i = va_arg( list, int * );						// NOTE: This is not bullet-proof; it assumes numbers are < 128 characters						nLength = 128;						if ( !CheckArbitraryPeekGet( 0, nLength ) )						{							*i = 0;							return numScanned;						}						*i = strtol( (char*)PeekGet(), &pEnd, 16 );						int nBytesRead = (int)( pEnd - (char*)PeekGet() );						if ( nBytesRead == 0 )							return numScanned;						m_Get += nBytesRead;					}					break;									case 'u':					{						unsigned int* u = va_arg( list, unsigned int *);						// NOTE: This is not bullet-proof; it assumes numbers are < 128 characters						nLength = 128;						if ( !CheckArbitraryPeekGet( 0, nLength ) )						{//.........这里部分代码省略.........
开发者ID:TotallyMehis,项目名称:ZM-Updated,代码行数:101,


示例2: strtod

template<> bool str2val< double >( const string& s, double& ret ){	// cerr << "in str2val< double >/n";	ret = strtod( s.c_str(), 0 );	return 1;}
开发者ID:BhallaLab,项目名称:moose-thalamocortical,代码行数:6,


示例3: extractNumber

int extractNumber(char **stringPointer, Token *token) {  char *start = *stringPointer;  token->type = TOKEN_TYPE_NUM;  token->value.number = strtod(start, stringPointer);  return start < *stringPointer;}
开发者ID:code4tots,项目名称:fun,代码行数:6,


示例4: ParseSizeString

static int ParseSizeString(const char *size, double *res){#define MAX_SUBSTRINGS 30    int pcre_exec_ret;    int r;    int ov[MAX_SUBSTRINGS];    int retval = 0;    char str[128];    char str2[128];    *res = 0;    pcre_exec_ret = pcre_exec(parse_regex, parse_regex_study, size, strlen(size), 0, 0,                    ov, MAX_SUBSTRINGS);    if (!(pcre_exec_ret == 2 || pcre_exec_ret == 3)) {        SCLogError(SC_ERR_PCRE_MATCH, "invalid size argument - %s. Valid size "                   "argument should be in the format - /n"                   "xxx <- indicates it is just bytes/n"                   "xxxkb or xxxKb or xxxKB or xxxkB <- indicates kilobytes/n"                   "xxxmb or xxxMb or xxxMB or xxxmB <- indicates megabytes/n"                   "xxxgb or xxxGb or xxxGB or xxxgB <- indicates gigabytes./n",                   size);        retval = -2;        goto end;    }    r = pcre_copy_substring((char *)size, ov, MAX_SUBSTRINGS, 1,                             str, sizeof(str));    if (r < 0) {        SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed");        retval = -2;        goto end;    }    char *endptr, *str_ptr = str;    errno = 0;    *res = strtod(str_ptr, &endptr);    if (errno == ERANGE) {        SCLogError(SC_ERR_NUMERIC_VALUE_ERANGE, "Numeric value out of range");        retval = -1;        goto end;    } else if (endptr == str_ptr) {        SCLogError(SC_ERR_INVALID_NUMERIC_VALUE, "Invalid numeric value");        retval = -1;        goto end;    }    if (pcre_exec_ret == 3) {        r = pcre_copy_substring((char *)size, ov, MAX_SUBSTRINGS, 2,                                 str2, sizeof(str2));        if (r < 0) {            SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed");            retval = -2;            goto end;        }        if (strcasecmp(str2, "kb") == 0) {            *res *= 1024;        } else if (strcasecmp(str2, "mb") == 0) {            *res *= 1024 * 1024;        } else if (strcasecmp(str2, "gb") == 0) {            *res *= 1024 * 1024 * 1024;        } else {            /* not possible */            BUG_ON(1);        }    }    retval = 0;end:    return retval;}
开发者ID:Hyperwise,项目名称:suricata,代码行数:72,


示例5: main

int main( int argc , char *argv[] ){   double val , p , p1=0.0,p2=0.0,p3=0.0 ;   double vbot,vtop,vdel ;   int code , iarg=1 , doq=0 , dod=0 , doi=0 , doz=0 , doh=0 ;   /*-- print some help for the pitiful user --*/   if( argc < 3 || strstr(argv[1],"help") != NULL ){    int ii ;    printf("/n") ;    printf("Demo program for computing NIfTI statistical functions./n") ;    printf("Usage: nifti_stats [-q|-d|-1|-z] val CODE [p1 p2 p3]/n") ;    printf(" val can be a single number or in the form bot:top:step./n") ;    printf(" default ==> output p = Prob(statistic < val)./n") ;    printf("  -q     ==> output is 1-p./n") ;    printf("  -d     ==> output is density./n") ;    printf("  -1     ==> output is x such that Prob(statistic < x) = val./n") ;    printf("  -z     ==> output is z such that Normal cdf(z) = p(val)./n") ;    printf("  -h     ==> output is z such that 1/2-Normal cdf(z) = p(val)./n");    printf(" Allowable CODEs:/n") ;    for( ii=NIFTI_FIRST_STATCODE ; ii <= NIFTI_LAST_STATCODE ; ii++ ){     printf("  %-10s",inam[ii]); if((ii-NIFTI_FIRST_STATCODE)%6==5)printf("/n");    }    printf("/n") ;    printf(" Following CODE are distributional parameters, as needed./n");    printf("/n") ;    printf("Results are written to stdout, 1 number per output line./n") ;    printf("Example (piping output into AFNI program 1dplot):/n") ;    printf(" nifti_stats -d 0:4:.001 INVGAUSS 1 3 | 1dplot -dx 0.001 -stdin/n");    printf("/n") ;    printf("Author - RW Cox - SSCC/NIMH/NIH/DHHS/USA/EARTH - March 2004/n") ;    printf("/n") ;    exit(0) ;   }   /*-- check first arg to see if it is an output option;        if so, set the appropriate output flag to determine what to compute --*/        if( strcmp(argv[iarg],"-q") == 0 ){ doq = 1 ; iarg++ ; }   else if( strcmp(argv[iarg],"-d") == 0 ){ dod = 1 ; iarg++ ; }   else if( strcmp(argv[iarg],"-1") == 0 ){ doi = 1 ; iarg++ ; }   else if( strcmp(argv[iarg],"-z") == 0 ){ doz = 1 ; iarg++ ; }   else if( strcmp(argv[iarg],"-h") == 0 ){ doh = 1 ; iarg++ ; }   /*-- get the value(s) to process --*/   vbot=vtop=vdel = 0.0 ;   sscanf( argv[iarg++] , "%lf:%lf:%lf" , &vbot,&vtop,&vdel ) ;   if( vbot >= vtop ) vdel = 0.0 ;   if( vdel <= 0.0  ) vtop = vbot ;   /*-- decode the CODE into the integer signifying the distribution --*/   code = nifti_intent_code(argv[iarg++]) ;     if( code < 0 ){ fprintf(stderr,"illegal code=%s/n",argv[iarg-1]); exit(1); }   /*-- get the parameters, if present (defaults are 0) --*/   if( argc > iarg ) p1 = strtod(argv[iarg++],NULL) ;   if( argc > iarg ) p2 = strtod(argv[iarg++],NULL) ;   if( argc > iarg ) p3 = strtod(argv[iarg++],NULL) ;   /*-- loop over input value(s), compute output, write to stdout --*/   for( val=vbot ; val <= vtop ; val += vdel ){     if( doq )                                        /* output = 1-cdf */       p = nifti_stat2rcdf( val , code,p1,p2,p3 ) ;     else if( dod )                                   /* output = density */       p = 1000.0*( nifti_stat2cdf(val+.001,code,p1,p2,p3)                   -nifti_stat2cdf(val     ,code,p1,p2,p3)) ;     else if( doi )                                   /* output = inverse */       p = nifti_cdf2stat( val , code,p1,p2,p3 ) ;     else if( doz )                                   /* output = z score */       p = nifti_stat2zscore( val , code,p1,p2,p3 ) ;     else if( doh )                                   /* output = halfz score */       p = nifti_stat2hzscore( val , code,p1,p2,p3 ) ;     else                                              /* output = cdf */       p = nifti_stat2cdf( val , code,p1,p2,p3 ) ;     printf("%.9g/n",p) ;     if( vdel <= 0.0 ) break ;  /* the case of just 1 value */   }   /*-- terminus est --*/   exit(0) ;}
开发者ID:jstavr,项目名称:Architecture-Relation-Evaluator,代码行数:88,


示例6: read_problem

void read_problem(const char *filename){	int elements, max_index, inst_max_index, i, j;	FILE *fp = fopen(filename,"r");	char *endptr;	char *idx, *val, *label;	if(fp == NULL)	{		fprintf(stderr,"can't open input file %s/n",filename);		exit(1);	}	prob.l = 0;	elements = 0;	max_line_len = 1024;	line = Malloc(char,max_line_len);	while(readline(fp)!=NULL)	{		char *p = strtok(line," /t"); // label		// features		while(1)		{			p = strtok(NULL," /t");			if(p == NULL || *p == '/n') // check '/n' as ' ' may be after the last feature				break;			++elements;		}		++elements;		++prob.l;	}	rewind(fp);	prob.y = Malloc(double,prob.l);	prob.x = Malloc(struct svm_node *,prob.l);	x_space = Malloc(struct svm_node,elements);	max_index = 0;	j=0;	for(i=0;i<prob.l;i++)	{		inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0		readline(fp);		prob.x[i] = &x_space[j];		label = strtok(line," /t/n");		if(label == NULL) // empty line			exit_input_error(i+1);		prob.y[i] = strtod(label,&endptr);		if(endptr == label || *endptr != '/0')			exit_input_error(i+1);		while(1)		{			idx = strtok(NULL,":");			val = strtok(NULL," /t");			if(val == NULL)				break;			errno = 0;			x_space[j].index = (int) strtol(idx,&endptr,10);			if(endptr == idx || errno != 0 || *endptr != '/0' || x_space[j].index <= inst_max_index)				exit_input_error(i+1);			else				inst_max_index = x_space[j].index;			errno = 0;			x_space[j].value = strtod(val,&endptr);			if(endptr == val || errno != 0 || (*endptr != '/0' && !isspace(*endptr)))				exit_input_error(i+1);			++j;		}		if(inst_max_index > max_index)			max_index = inst_max_index;		x_space[j++].index = -1;	}	if(param.gamma == 0 && max_index > 0)		param.gamma = 1.0/max_index;	if(param.kernel_type == PRECOMPUTED)		for(i=0;i<prob.l;i++)		{			if (prob.x[i][0].index != 0)			{				fprintf(stderr,"Wrong input format: first column must be 0:sample_serial_number/n");				exit(1);			}			if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index)			{				fprintf(stderr,"Wrong input format: sample_serial_number out of range/n");				exit(1);			}		}//.........这里部分代码省略.........
开发者ID:ishalyminov,项目名称:1class_svm_detector,代码行数:101,


示例7: gmx_wheel

int gmx_wheel(int argc, char *argv[]){    const char     *desc[] = {        "[THISMODULE] plots a helical wheel representation of your sequence.",        "The input sequence is in the [REF].dat[ref] file where the first line contains",        "the number of residues and each consecutive line contains a residue "        "name."    };    output_env_t    oenv;    static real     rot0  = 0;    static gmx_bool bNum  = TRUE;    static char    *title = NULL;    static int      r0    = 1;    t_pargs         pa [] = {        { "-r0",  FALSE, etINT, {&r0},          "The first residue number in the sequence" },        { "-rot0", FALSE, etREAL, {&rot0},          "Rotate around an angle initially (90 degrees makes sense)" },        { "-T",   FALSE, etSTR, {&title},          "Plot a title in the center of the wheel (must be shorter than 10 characters, or it will overwrite the wheel)" },        { "-nn",  FALSE, etBOOL, {&bNum},          "Toggle numbers" }    };    t_filenm        fnm[] = {        { efDAT, "-f", NULL,  ffREAD  },        { efEPS, "-o", NULL,  ffWRITE }    };#define NFILE asize(fnm)    int    i, nres;    char **resnm;    if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa,                           asize(desc), desc, 0, NULL, &oenv))    {        return 0;    }    for (i = 1; (i < argc); i++)    {        if (std::strcmp(argv[i], "-r0") == 0)        {            r0 = std::strtol(argv[++i], NULL, 10);            fprintf(stderr, "First residue is %d/n", r0);        }        else if (std::strcmp(argv[i], "-rot0") == 0)        {            rot0 = strtod(argv[++i], NULL);            fprintf(stderr, "Initial rotation is %g/n", rot0);        }        else if (std::strcmp(argv[i], "-T") == 0)        {            title = gmx_strdup(argv[++i]);            fprintf(stderr, "Title will be '%s'/n", title);        }        else if (std::strcmp(argv[i], "-nn") == 0)        {            bNum = FALSE;            fprintf(stderr, "No residue numbers/n");        }        else        {            gmx_fatal(FARGS, "Incorrect usage of option %s", argv[i]);        }    }    nres = get_lines(ftp2fn(efDAT, NFILE, fnm), &resnm);    if (bNum)    {        wheel(ftp2fn(efEPS, NFILE, fnm), nres, resnm, r0, rot0, title);    }    else    {        wheel2(ftp2fn(efEPS, NFILE, fnm), nres, resnm, rot0, title);    }    return 0;}
开发者ID:aalhossary,项目名称:gromacs-HREMD,代码行数:78,


示例8: decSingleToString

double QDecSingle::toDouble() const{  char str[MaxStrSize] = {0};  decSingleToString(&m_data, str);  return strtod(str, 0);}
开发者ID:rdemers,项目名称:org.rd.qtx.toolboxlib,代码行数:6,


示例9: process

	static void	/* file processing function */process(FILE *fid) {	char line[MAXLINE+3], *s;	for (;;) {		++emess_dat.File_line;		if (!(s = fgets(line, MAXLINE, fid)))			break;		if (!strchr(s, '/n')) { /* overlong line */			int c;			strcat(s, "/n");			/* gobble up to newline */			while ((c = fgetc(fid)) != EOF && c != '/n') ;		}		if (*s == tag) {			fputs(line, stdout);			continue;		}		phi1 = dmstor(s, &s);		lam1 = dmstor(s, &s);		if (inverse) {			phi2 = dmstor(s, &s);			lam2 = dmstor(s, &s);			geod_inv();		} else {			al12 = dmstor(s, &s);			geod_S = strtod(s, &s) * to_meter;			geod_pre();			geod_for();		}		if (!*s && (s > line)) --s; /* assumed we gobbled /n */		if (pos_azi) {			if (al12 < 0.) al12 += M_TWOPI;			if (al21 < 0.) al21 += M_TWOPI;		}		if (fullout) {			printLL(phi1, lam1); TAB;			printLL(phi2, lam2); TAB;			if (oform) {				(void)printf(oform, al12 * RAD_TO_DEG); TAB;				(void)printf(oform, al21 * RAD_TO_DEG); TAB;				(void)printf(osform, geod_S * fr_meter);			}  else {				(void)fputs(rtodms(pline, al12, 0, 0), stdout); TAB;				(void)fputs(rtodms(pline, al21, 0, 0), stdout); TAB;				(void)printf(osform, geod_S * fr_meter);			}		} else if (inverse)			if (oform) {				(void)printf(oform, al12 * RAD_TO_DEG); TAB;				(void)printf(oform, al21 * RAD_TO_DEG); TAB;				(void)printf(osform, geod_S * fr_meter);			} else {				(void)fputs(rtodms(pline, al12, 0, 0), stdout); TAB;				(void)fputs(rtodms(pline, al21, 0, 0), stdout); TAB;				(void)printf(osform, geod_S * fr_meter);			}		else {			printLL(phi2, lam2); TAB;			if (oform)				(void)printf(oform, al21 * RAD_TO_DEG);			else				(void)fputs(rtodms(pline, al21, 0, 0), stdout);		}		(void)fputs(s, stdout);	}}
开发者ID:Maasik,项目名称:proj.4,代码行数:67,


示例10: log_sample

//.........这里部分代码省略.........                                ps->sched = openat(procfd, filename, O_RDONLY);                                if (ps->sched == -1)                                        continue;                        }                        s = pread(ps->sched, buf, sizeof(buf) - 1, 0);                        if (s <= 0) {                                close(ps->sched);                                continue;                        }                        buf[s] = '/0';                        if (!sscanf(buf, "%s %*s %*s", key))                                continue;                        strscpy(ps->name, sizeof(ps->name), key);                        /* cmdline */                        if (arg_show_cmdline)                                pid_cmdline_strscpy(ps->name, sizeof(ps->name), pid);                        /* discard line 2 */                        m = bufgetline(buf);                        if (!m)                                continue;                        m = bufgetline(m);                        if (!m)                                continue;                        if (!sscanf(m, "%*s %*s %s", t))                                continue;                        ps->starttime = strtod(t, NULL) / 1000.0;                        /* ppid */                        sprintf(filename, "%d/stat", pid);                        fd = openat(procfd, filename, O_RDONLY);                        st = fdopen(fd, "r");                        if (!st)                                continue;                        if (!fscanf(st, "%*s %*s %*s %i", &p)) {                                continue;                        }                        ps->ppid = p;                        /*                         * setup child pointers                         *                         * these are used to paint the tree coherently later                         * each parent has a LL of children, and a LL of siblings                         */                        if (pid == 1)                                continue; /* nothing to do for init atm */                        /* kthreadd has ppid=0, which breaks our tree ordering */                        if (ps->ppid == 0)                                ps->ppid = 1;                        parent = ps_first;                        while ((parent->next_ps && parent->pid != ps->ppid))                                parent = parent->next_ps;                        if ((!parent) || (parent->pid != ps->ppid)) {                                /* orphan */                                ps->ppid = 1;
开发者ID:kwirk,项目名称:systemd,代码行数:67,


示例11: startElement_METRICS

static intstartElement_METRICS(void *data, const char *el, const char **attr){   xmldata_t *xmldata = (xmldata_t *)data;   struct xml_tag *xt;   struct type_tag *tt;   datum_t *hash_datum = NULL;   datum_t *rdatum;   datum_t hashkey, hashval;   const char *name = NULL;   const char *metricval = NULL;   const char *metricnum = NULL;   const char *type = NULL;   int i;   hash_t *summary;   Metric_t *metric;   /* In non-scalable mode, we do not process summary data. */   if (!gmetad_config.scalable_mode) return 0;      /* Get name for hash key, and val/type for summaries. */   for(i = 0; attr[i]; i+=2)      {         xt = in_xml_list(attr[i], strlen(attr[i]));         if (!xt) continue;         switch (xt->tag)            {               case NAME_TAG:                  name = attr[i+1];                  hashkey.data = (void*) name;                  hashkey.size =  strlen(name) + 1;                  break;               case TYPE_TAG:                  type = attr[i+1];                  break;               case SUM_TAG:                  metricval = attr[i+1];                  break;               case NUM_TAG:                  metricnum = attr[i+1];               default:                  break;            }      }   summary = xmldata->source.metric_summary;   hash_datum = hash_lookup(&hashkey, summary);   if (!hash_datum)      {         metric = &(xmldata->metric);         memset((void*) metric, 0, sizeof(*metric));         fillmetric(attr, metric, type);      }   else      {         memcpy(&xmldata->metric, hash_datum->data, hash_datum->size);         datum_free(hash_datum);         metric = &(xmldata->metric);         tt = in_type_list(type, strlen(type));         if (!tt) return 0;         switch (tt->type)               {                  case INT:                  case UINT:                  case FLOAT:                     metric->val.d += (double)                             strtod(metricval, (char**) NULL);                     break;                  default:                     break;               }            metric->num += atoi(metricnum);         }   /* Update metric in summary table. */   hashval.size = sizeof(*metric) - GMETAD_FRAMESIZE + metric->stringslen;   hashval.data = (void*) metric;   summary = xmldata->source.metric_summary;   rdatum = hash_insert(&hashkey, &hashval, summary);   if (!rdatum) {      err_msg("Could not insert %s metric", name);      return 1;   }   return 0;}
开发者ID:fangy,项目名称:monitor-core,代码行数:88,


示例12: fillmetric

/* Populates a Metric_t structure from a list of XML metric attribute strings. * We need the type string here because we cannot be sure it comes before * the metric value in the attribute list. */static voidfillmetric(const char** attr, Metric_t *metric, const char* type){   int i;   /* INV: always points to the next free byte in metric.strings buffer. */   int edge = 0;   struct type_tag *tt;   struct xml_tag *xt;   char *metricval, *p;   /* For old versions of gmond. */   metric->slope = -1;   for(i = 0; attr[i] ; i+=2)      {         /* Only process the XML tags that gmetad is interested in */         xt = in_xml_list (attr[i], strlen(attr[i]));         if (!xt)            continue;         switch( xt->tag )            {               case SUM_TAG:               case VAL_TAG:                  metricval = (char*) attr[i+1];                  tt = in_type_list(type, strlen(type));                  if (!tt) return;                  switch (tt->type)                     {                        case INT:                        case TIMESTAMP:                        case UINT:                        case FLOAT:                           metric->val.d = (double)                                   strtod(metricval, (char**) NULL);                           p = strrchr(metricval, '.');                           if (p) metric->precision = (short int) strlen(p+1);                           break;                        case STRING:                           /* We store string values in the 'valstr' field. */                           break;                     }                  metric->valstr = addstring(metric->strings, &edge, metricval);                  break;               case TYPE_TAG:                  metric->type = addstring(metric->strings, &edge, attr[i+1]);                  break;               case UNITS_TAG:                  metric->units = addstring(metric->strings, &edge, attr[i+1]);                  break;               case TN_TAG:                  metric->tn = atoi(attr[i+1]);                  break;               case TMAX_TAG:                  metric->tmax = atoi(attr[i+1]);                  break;               case DMAX_TAG:                  metric->dmax = atoi(attr[i+1]);                  break;               case SLOPE_TAG:                  metric->slope = addstring(metric->strings, &edge, attr[i+1]);                  break;               case SOURCE_TAG:                  metric->source = addstring(metric->strings, &edge, attr[i+1]);                  break;               case NUM_TAG:                  metric->num = atoi(attr[i+1]);                  break;               default:                  break;            }      }      metric->stringslen = edge;            /* We are ok with growing metric values b/c we write to a full-sized       * buffer in xmldata. */}
开发者ID:fangy,项目名称:monitor-core,代码行数:83,


示例13: startElement_METRIC

//.........这里部分代码省略.........   /* Summarize all numeric metrics */   do_summary = 0;   tt = in_type_list(type, strlen(type));   if (!tt) return 0;   if (tt->type==INT || tt->type==UINT || tt->type==FLOAT)      do_summary = 1;   /* Only keep metric details if we are the authority on this cluster. */   if (authority_mode(xmldata))      {         /* Save the data to a round robin database if the data source is alive          */         fillmetric(attr, metric, type);	 if (metric->dmax && metric->tn > metric->dmax)            return 0;         if (do_summary && !xmldata->ds->dead && !xmldata->rval)            {                  debug_msg("Updating host %s, metric %s",                                   xmldata->hostname, name);                  if ( gmetad_config.write_rrds == 1 )                     xmldata->rval = write_data_to_rrd(xmldata->sourcename,                        xmldata->hostname, name, metricval, NULL,                        xmldata->ds->step, xmldata->source.localtime, slope);		  if (gmetad_config.carbon_server) // if the user has specified a carbon server, send the metric to carbon as well                     carbon_ret=write_data_to_carbon(xmldata->sourcename, xmldata->hostname, name, metricval,xmldata->source.localtime);            }         metric->id = METRIC_NODE;         metric->report_start = metric_report_start;         metric->report_end = metric_report_end;         edge = metric->stringslen;         metric->name = addstring(metric->strings, &edge, name);         metric->stringslen = edge;         /* Set local idea of T0. */         metric->t0 = xmldata->now;         metric->t0.tv_sec -= metric->tn;         /* Trim metric structure to the correct length. */         hashval.size = sizeof(*metric) - GMETAD_FRAMESIZE + metric->stringslen;         hashval.data = (void*) metric;         /* Update full metric in cluster host table. */         rdatum = hash_insert(&hashkey, &hashval, xmldata->host.metrics);         if (!rdatum)            {               err_msg("Could not insert %s metric", name);            }      }   /* Always update summary for numeric metrics. */   if (do_summary)      {         summary = xmldata->source.metric_summary;         hash_datum = hash_lookup(&hashkey, summary);         if (!hash_datum)            {               if (!authority_mode(xmldata))                  {                     metric = &(xmldata->metric);                     memset((void*) metric, 0, sizeof(*metric));                     fillmetric(attr, metric, type);                  }               /* else we have already filled in the metric above. */            }         else            {               memcpy(&xmldata->metric, hash_datum->data, hash_datum->size);               datum_free(hash_datum);               metric = &(xmldata->metric);               switch (tt->type)                  {                     case INT:                     case UINT:                     case FLOAT:                        metric->val.d += (double)                                strtod(metricval, (char**) NULL);                        break;                     default:                        break;                  }            }         metric->num++;         metric->t0 = xmldata->now; /* tell cleanup thread we are using this */         /* Trim metric structure to the correct length. Tricky. */         hashval.size = sizeof(*metric) - GMETAD_FRAMESIZE + metric->stringslen;         hashval.data = (void*) metric;         /* Update metric in summary table. */         rdatum = hash_insert(&hashkey, &hashval, summary);         if (!rdatum) err_msg("Could not insert %s metric", name);      }   return 0;}
开发者ID:fangy,项目名称:monitor-core,代码行数:101,


示例14: parse_accept_languages

accept_languages * parse_accept_languages(char * acceptlang) {	char *	langdup;	/* Duplicate of accept language for parsing */	accept_languages	*langs = NULL;	char *	langtok;	/* Language token (language + locality + q value) */	char *	saveptr;	/* Save state of tokenization */	char *	qdelim;		/* location of the delimiter ';q=' */	char *	localitydelim;	/* Delimiter for locality specifier */	int		x;	char *	stp;	/* If the browser did not pass an HTTP_ACCEPT_LANGUAGE variable, there		is not much we can do */	if(NULL == acceptlang) {		return NULL;		}	/* Duplicate the browser supplied HTTP_ACCEPT_LANGUAGE variable */	if(NULL == (langdup = strdup(acceptlang))) {		printf("Unable to allocate memory for langdup/n");		return NULL;		}	/* Initialize the structure to contain the parsed HTTP_ACCEPT_LANGUAGE		information */	if(NULL == (langs = malloc(sizeof(accept_languages)))) {		printf("Unable to allocate memory for langs/n");		free(langdup);		return NULL;		}	langs->count = 0;	langs->languages = (accept_language **)NULL;	/* Tokenize the HTTP_ACCEPT_LANGUAGE string */	langtok = strtok_r(langdup, ",", &saveptr);	while(langtok != NULL) {		/* Bump the count and allocate memory for structures */		langs->count++;		if(NULL == langs->languages) {			/* Adding first language */			if(NULL == (langs->languages =			                malloc(langs->count * sizeof(accept_language *)))) {				printf("Unable to allocate memory for first language/n");				langs->count--;				free_accept_languages(langs);				free(langdup);				return NULL;				}			}		else {			/* Adding additional language */			if(NULL == (langs->languages = realloc(langs->languages,			                                       langs->count * sizeof(accept_language *)))) {				printf("Unable to allocate memory for additional language/n");				langs->count--;				free_accept_languages(langs);				free(langdup);				return NULL;				}			}		if(NULL == (langs->languages[ langs->count - 1] =		                malloc(sizeof(accept_language)))) {			printf("Unable to allocate memory for language/n");			langs->count--;			free_accept_languages(langs);			free(langdup);			return NULL;			}		langs->languages[ langs->count - 1]->language = (char *)NULL;		langs->languages[ langs->count - 1]->locality = (char *)NULL;		langs->languages[ langs->count - 1]->q = 1.0;		/* Check to see if there is a q value */		qdelim = strstr(langtok, ACCEPT_LANGUAGE_Q_DELIMITER);		if(NULL != qdelim) {	/* found a q value */			langs->languages[ langs->count - 1]->q =			    strtod(qdelim + strlen(ACCEPT_LANGUAGE_Q_DELIMITER), NULL);			langtok[ qdelim - langtok] = '/0';			}		/* Check to see if there is a locality specifier */		if(NULL == (localitydelim = strchr(langtok, '-'))) {			localitydelim = strchr(langtok, '_');			}		if(NULL != localitydelim) {			/* We have a locality delimiter, so copy it */			if(NULL == (langs->languages[ langs->count - 1]->locality =			                strdup(localitydelim + 1))) {				printf("Unable to allocate memory for locality '%s'/n",				       langtok);				free_accept_languages(langs);				free(langdup);				return NULL;				}			/* Ensure it is upper case */			for(x = 0, stp = langs->languages[ langs->count - 1]->locality;			        x < strlen(langs->languages[ langs->count - 1]->locality);			        x++, stp++) {//.........这里部分代码省略.........
开发者ID:zhuifeng09770,项目名称:mynagios,代码行数:101,


示例15: parse_value

static char* parse_value(nx_json* parent, const char* key, char* p, nx_json_unicode_encoder encoder) {  nx_json* js;  while (1) {    switch (*p) {      case '/0':        NX_JSON_REPORT_ERROR("unexpected end of text", p);        return 0; // error      case ' ': case '/t': case '/n': case '/r':      case ',':        // skip        p++;        break;      case '{':        js=create_json(NX_JSON_OBJECT, key, parent);        p++;        while (1) {          const char* new_key;          p=parse_key(&new_key, p, encoder);          if (!p) return 0; // error          if (*p=='}') return p+1; // end of object          p=parse_value(js, new_key, p, encoder);          if (!p) return 0; // error        }      case '[':        js=create_json(NX_JSON_ARRAY, key, parent);        p++;        while (1) {          p=parse_value(js, 0, p, encoder);          if (!p) return 0; // error          if (*p==']') return p+1; // end of array        }      case ']':        return p;      case '"':        p++;        js=create_json(NX_JSON_STRING, key, parent);        js->text_value=unescape_string(p, &p, encoder);        if (!js->text_value) return 0; // propagate error        return p;      case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':        {          js=create_json(NX_JSON_INTEGER, key, parent);          char* pe;          js->int_value=strtol(p, &pe, 0);          if (pe==p) {            NX_JSON_REPORT_ERROR("invalid number", p);            return 0; // error          }          if (*pe=='.' || *pe=='e' || *pe=='E') { // double value            js->type=NX_JSON_DOUBLE;            js->dbl_value=strtod(p, &pe);            if (pe==p) {              NX_JSON_REPORT_ERROR("invalid number", p);              return 0; // error            }          }          else {            js->dbl_value=js->int_value;          }          return pe;        }      case 't':        if (!strncmp(p, "true", 4)) {          js=create_json(NX_JSON_BOOL, key, parent);          js->int_value=1;          return p+4;        }        NX_JSON_REPORT_ERROR("unexpected chars", p);        return 0; // error      case 'f':        if (!strncmp(p, "false", 5)) {          js=create_json(NX_JSON_BOOL, key, parent);          js->int_value=0;          return p+5;        }        NX_JSON_REPORT_ERROR("unexpected chars", p);        return 0; // error      case 'n':        if (!strncmp(p, "null", 4)) {          create_json(NX_JSON_NULL, key, parent);          return p+4;        }        NX_JSON_REPORT_ERROR("unexpected chars", p);        return 0; // error      case '/': // comment        if (p[1]=='/') { // line comment          char* ps=p;          p=strchr(p+2, '/n');          if (!p) {            NX_JSON_REPORT_ERROR("endless comment", ps);            return 0; // error          }          p++;        }        else if (p[1]=='*') { // block comment          p=skip_block_comment(p+2);          if (!p) return 0;        }        else {          NX_JSON_REPORT_ERROR("unexpected chars", p);//.........这里部分代码省略.........
开发者ID:CowanSM,项目名称:ejdb,代码行数:101,


示例16: main

int main(int argc, char **argv){    /* Set some default behaviors. */    const char *i = "rect";    const char *o = "rect";    const char *p = "rgss";    const char *f = "linear";    float rot[3] = { 0.f, 0.f, 0.f };    int n = 1024;    int c;    /* Parse the command line options. */    while ((c = getopt(argc, argv, "i:o:p:n:f:x:y:z:")) != -1)        switch (c)        {            case 'i': i      = optarg;               break;            case 'o': o      = optarg;               break;            case 'p': p      = optarg;               break;            case 'f': f      = optarg;               break;            case 'x': rot[0] = strtod(optarg, 0);    break;            case 'y': rot[1] = strtod(optarg, 0);    break;            case 'z': rot[2] = strtod(optarg, 0);    break;            case 'n': n      = strtol(optarg, 0, 0); break;            default: return usage(argv[0]);        }    int      num = 1;    image   *src = 0;    image   *dst = 0;    image   *tmp = 0;    to_img   img;    to_env   env;    filter   fil;    /* Select the sampler. */    if      (!strcmp(f, "linear"))  fil = filter_linear;    else if (!strcmp(f, "nearest")) fil = filter_nearest;    else return usage(argv[0]);    /* Read the input image. */    if (optind + 2 <= argc)    {        if      (!strcmp(i, "cube"))        {            tmp = image_reader(argv[optind], 6);            src = image_border(tmp);            img = cube_to_img;        }        else if (!strcmp(i, "dome"))        {            src = image_reader(argv[optind], 1);            img = dome_to_img;        }        else if (!strcmp(i, "hemi"))        {            src = image_reader(argv[optind], 1);            img = hemi_to_img;        }        else if (!strcmp(i, "ball"))        {            src = image_reader(argv[optind], 1);            img = ball_to_img;        }        else if (!strcmp(i, "rect"))        {            src = image_reader(argv[optind], 1);            img = rect_to_img;        }        else return usage(argv[0]);    }    else return usage(argv[0]);    /* Prepare the output image. */    if (src)    {        if      (!strcmp(o, "cube"))        {            dst = image_alloc((num = 6), n, n, src->c, src->b, src->s);            env = cube_to_env;        }        else if (!strcmp(o, "dome"))        {            dst = image_alloc((num = 1), n, n, src->c, src->b, src->s);            env = dome_to_env;        }        else if (!strcmp(o, "hemi"))        {            dst = image_alloc((num = 1), n, n, src->c, src->b, src->s);            env = hemi_to_env;        }        else if (!strcmp(o, "ball"))        {//.........这里部分代码省略.........
开发者ID:FH-Potsdam,项目名称:envtools,代码行数:101,


示例17: _decode_value_raw

static config_err_t_decode_value_raw (ipmi_sensors_config_state_data_t *state_data,                   const char *threshold_input,                   uint8_t *threshold_raw){  int8_t r_exponent, b_exponent;  int16_t m, b;  uint8_t linearization, analog_data_format;  config_err_t rv = CONFIG_ERR_FATAL_ERROR;  config_err_t ret;  double threshold_value;  char *ptr;  assert (state_data);  assert (threshold_input);  assert (threshold_raw);  if ((ret = _get_sdr_decoding_data (state_data,                                     &r_exponent,                                     &b_exponent,                                     &m,                                     &b,                                     &linearization,                                     &analog_data_format)) != CONFIG_ERR_SUCCESS)    {      rv = ret;      goto cleanup;    }  errno = 0;  threshold_value = strtod (threshold_input, &ptr);  if (errno      || ptr[0] != '/0')    {      pstdout_fprintf (state_data->pstate,		       stderr,		       "Invalid input: %s/n",		       threshold_input);      /* fatal error, should have been validated earlier */      goto cleanup;    }  if (ipmi_sensor_decode_raw_value (r_exponent,                                    b_exponent,                                    m,                                    b,                                    linearization,                                    analog_data_format,                                    threshold_value,                                    threshold_raw) < 0)    {      pstdout_fprintf (state_data->pstate,		       stderr,		       "ipmi_sensor_decode_raw_value: %s/n",		       strerror (errno));      goto cleanup;    }  rv = CONFIG_ERR_SUCCESS; cleanup:  return (rv);}
开发者ID:webrulon,项目名称:freeipmi-debian,代码行数:62,


示例18: yajl_do_parse

//.........这里部分代码省略.........                            _CC_CHK(hand->callbacks->yajl_number(                                        hand->ctx,(const char *) buf, bufLen));                        } else if (hand->callbacks->yajl_integer) {                            int64_t i = 0;                            errno = 0;                            i = yajl_parse_integer(buf, (unsigned int)bufLen);                            if ((i == INT64_MIN || i == INT64_MAX) &&                                errno == ERANGE)                            {                                yajl_bs_set(hand->stateStack,                                            yajl_state_parse_error);                                hand->parseError = "integer overflow" ;                                /* try to restore error offset */                                if (*offset >= bufLen) *offset -= bufLen;                                else *offset = 0;                                goto around_again;                            }                            _CC_CHK(hand->callbacks->yajl_integer(hand->ctx,                                                                  i));                        }                    }                    break;                case yajl_tok_double:                    if (hand->callbacks) {                        if (hand->callbacks->yajl_number) {                            _CC_CHK(hand->callbacks->yajl_number(                                        hand->ctx, (const char *) buf, bufLen));                        } else if (hand->callbacks->yajl_double) {                            double d = 0.0;                            yajl_buf_clear(hand->decodeBuf);                            yajl_buf_append(hand->decodeBuf, buf, bufLen);                            buf = yajl_buf_data(hand->decodeBuf);                            errno = 0;                            d = strtod((char *) buf, NULL);                            if ((d == HUGE_VAL || d == -HUGE_VAL) &&                                errno == ERANGE)                            {                                yajl_bs_set(hand->stateStack,                                            yajl_state_parse_error);                                hand->parseError = "numeric (floating point) "                                    "overflow";                                /* try to restore error offset */                                if (*offset >= bufLen) *offset -= bufLen;                                else *offset = 0;                                goto around_again;                            }                            _CC_CHK(hand->callbacks->yajl_double(hand->ctx,                                                                 d));                        }                    }                    break;                case yajl_tok_right_brace: {                    if (yajl_bs_current(hand->stateStack) ==                        yajl_state_array_start)                    {                        if (hand->callbacks &&                            hand->callbacks->yajl_end_array)                        {                            _CC_CHK(hand->callbacks->yajl_end_array(hand->ctx));                        }                        yajl_bs_pop(hand->stateStack);                        goto around_again;                    }                    /* intentional fall-through */                }                case yajl_tok_colon:
开发者ID:3rduncle,项目名称:libbson,代码行数:67,


示例19: main

int main(int argc, char *argv[]){	int sockfd;	struct sigaction act;	char fname[BUFSIZE], timestr[BUFSIZE], buf[BUFSIZE];	char stringbuffer[50][BUFSIZE];	int i;	time_t now;	char *str, *ptr, *pEnd;	double rf_level;	struct tm *loctime;	struct stat statbuf;	FILE *f;	/* cgi variables */	int postsize;	/* print html headers */ 	printf("Content-Type: text/html;charset=iso-8859-1/n/n");	printf("<html><head>/n");	printf("<style type=/"text/css/">");	printf(" p { margin: 0; padding: 0;}");	printf(" h1 { font-size: 120%; padding: 0; margin-bottom: 0; } ");	printf(" form { float:left } ");	printf(" hr { clear: both } ");	printf(" </style>");	/* printf("<meta http-equiv=/"refresh/" content=/"5/">"); */	printf("</head><body>/n");	/* get post data */	str = getenv("CONTENT_LENGTH");	if (str!=NULL) postsize = atoi(str);	else postsize=0;	fgets(buf, postsize+1, stdin);	ptr=buf;	while (((*ptr)!='=')&&((*ptr)!='/0')) {		ptr++;	}	if (*ptr!='/0') ptr++;	/* setup variables */	/* setup signal handler */	act.sa_handler = sig_alrm;	act.sa_flags = 0;	sigaction(SIGALRM, &act, 0);		/* check it's valid float and greater than 0 */	errno = 0;	rf_level = strtod(ptr, &pEnd);	/* parameter was given, so send it to weather station */	//printf("%s", ptr);	if (strstr(ptr, "reset") != NULL) {		/* Parameter was reset command */		/* connect */		if ((sockfd = connect_ip(SERVER_IP, SERVER_PORT)) == -1) {			return -1;		}		/* generate parameter string */		snprintf(buf, sizeof(buf), "%s", MSG_RESET, ptr);		/* send parameters to server */		if (send_data(sockfd, buf, sizeof(buf)) != 0) {			return -1;		}		close(sockfd);		sleep(5);		printf("Reset successful!");	} else if (rf_level > 0) {		/* Parameter was RF trigger level */		/* connect */		if ((sockfd = connect_ip(SERVER_IP, SERVER_PORT)) == -1) {			return -1;		}		/* generate parameter string */		snprintf(buf, sizeof(buf), "%s;%s/r/n", MSG_SET_PARAMS, ptr);		/* send parameters to server */		if (send_data(sockfd, buf, sizeof(buf)) != 0) {			return -1;		}		close(sockfd);//.........这里部分代码省略.........
开发者ID:surfmikko,项目名称:wstools,代码行数:101,


示例20: io_read

/*** Read a variable. On error put nil on stack.** LUA interface:**			variable = read ([format])**** O formato pode ter um dos seguintes especificadores:****	s ou S -> para string**	f ou F, g ou G, e ou E -> para reais**	i ou I -> para inteiros****	Estes especificadores podem vir seguidos de numero que representa**	o numero de campos a serem lidos.*/static void io_read (void){ lua_Object o = lua_getparam (1); if (o == NULL || !lua_isstring(o))	/* free format */ {  int c;  char s[256];  while (isspace(c=fgetc(in)))   ;  if (c == '/"')  {   int c, n=0;   while((c = fgetc(in)) != '/"')   {    if (c == EOF)    {     lua_pushnil ();     return;    }    s[n++] = c;   }   s[n] = 0;  }  else if (c == '/'')  {   int c, n=0;   while((c = fgetc(in)) != '/'')   {    if (c == EOF)    {     lua_pushnil ();     return;    }    s[n++] = c;   }   s[n] = 0;  }  else  {   char *ptr;   double d;   ungetc (c, in);   if (fscanf (in, "%s", s) != 1)   {    lua_pushnil ();    return;   }   d = strtod (s, &ptr);   if (!(*ptr))   {    lua_pushnumber (d);    return;   }  }  lua_pushstring (s);  return; } else				/* formatted */ {  char *e = lua_getstring(o);  char t;  int  m=0;  while (isspace(*e)) e++;  t = *e++;  while (isdigit(*e))   m = m*10 + (*e++ - '0');    if (m > 0)  {   char f[80];   char s[256];   sprintf (f, "%%%ds", m);   if (fgets (s, m, in) == NULL)   {    lua_pushnil();    return;   }   else   {    if (s[strlen(s)-1] == '/n')     s[strlen(s)-1] = 0;   }   switch (tolower(t))   {    case 'i':    {//.........这里部分代码省略.........
开发者ID:Akagi201,项目名称:learning-lua,代码行数:101,


示例21: memcpy

void CGPSSubcrible::OnRevGpsMsg(long ILongID,char strgps[],long lenth){	  //获得字符数组		char *pchar = new char[ lenth + 1];		char *pdate = new char[5];				memcpy(pchar,strgps,lenth);				*(pchar + lenth) = '/0'; 		char *tok; 		char *p[50] = {0}; 		char seps[] = ","; 	    int i = 0; 	    		char *stopstr; 		 		//获得字符串数组 	    tok = strtok(pchar,seps); 		while( tok != NULL && i < 50) 		{	 			p[i] = new char[strlen(tok) + 1]; 		    strcpy(p[i],tok); 	        tok = strtok( NULL,seps); 			 			i++; 		} 	     		if ( i < 10 ) 		{ 			//清除数组指针 	       for(int j = 0; j<i; j++)		   { 	          delete p[j];		   } 	 		   delete pchar; 		   delete pdate;		   		    return; 		} 			GPS_Info info = {0};//		const int TIGER_COORDINATE_UNIT = 1000000; 		info.latidude = strtod(p[0],&stopstr);//		info.latidude /= TIGER_COORDINATE_UNIT;//		info.latidude -= 90; 		info.longitude = strtod(p[1],&stopstr);//		info.longitude /= TIGER_COORDINATE_UNIT;//		info.longitude -= 180; 		info.speed     = strtod(p[2],&stopstr); 		info.height    = strtod(p[3],&stopstr); 		info.angle     = strtod(p[4],&stopstr); 	 	     strncpy(pdate,p[5],4); 	     *(pdate+4) = '/0'; 	     info.revTime.dwYear = strtol(pdate,&stopstr,10); 	   	     strncpy(pdate,p[5]+4,2); 	     *(pdate+2) = '/0'; 	     info.revTime.dwMonth = strtol(pdate,&stopstr,10); 	    	     strncpy(pdate,p[5]+6,2); 	     *(pdate+2) = '/0'; 	     info.revTime.dwDay = strtol(pdate,&stopstr,10); 	       	 	     strncpy(pdate,p[5]+8,2); 	     *(pdate+2) = '/0'; 	     info.revTime.dwHour = strtol(pdate,&stopstr,10); 	 	     strncpy(pdate,p[5]+10,2); 	     *(pdate+2) = '/0'; 	     info.revTime.dwMinute = strtol(pdate,&stopstr,10); 	 	     strncpy(pdate,p[5]+12,2); 	     *(pdate+2) = '/0'; 	     info.revTime.dwSecond = strtol(pdate,&stopstr,10); 	      	 		 info.antennaState = (p[6][0] == '1'); 		 info.orientationState = (p[7][0] == '1'); 		 info.starCount = strtol(p[8],&stopstr,10); 		 		 //清除数组指针 	     for(int j = 0; j<i; j++)		 { 	        delete p[j];		 } 	 		 delete pchar; 		 delete pdate; 		 if(m_RecievCallBack != NULL) 		 { 			 m_RecievCallBack(ILongID,info,m_dwuserdata); 		 }//.........这里部分代码省略.........
开发者ID:crashatom,项目名称:phoebemail,代码行数:101,


示例22: atof

double atof(const char *s){	return strtod(s, (const char **) NULL);}
开发者ID:6305-LAB,项目名称:OS-kernel,代码行数:4,


示例23: do_predict

void do_predict(FILE *input, FILE *output){	int correct = 0;	int total = 0;	double error = 0;	double sump = 0, sumt = 0, sumpp = 0, sumtt = 0, sumpt = 0;	int nr_class=get_nr_class(model_);	double *prob_estimates=NULL;	int j, n;	int nr_feature=get_nr_feature(model_);	if(model_->bias>=0)		n=nr_feature+1;	else		n=nr_feature;	if(flag_predict_probability)	{		int *labels;		if(!check_probability_model(model_))		{			fprintf(stderr, "probability output is only supported for logistic regression/n");			exit(1);		}		labels=(int *) malloc(nr_class*sizeof(int));		get_labels(model_,labels);		prob_estimates = (double *) malloc(nr_class*sizeof(double));		fprintf(output,"labels");		for(j=0;j<nr_class;j++)			fprintf(output," %d",labels[j]);		fprintf(output,"/n");		free(labels);	}	max_line_len = 1024;	line = (char *)malloc(max_line_len*sizeof(char));	while(readline(input) != NULL)	{		int i = 0;		double target_label, predict_label;		char *idx, *val, *label, *endptr;		int inst_max_index = 0; // strtol gives 0 if wrong format		label = strtok(line," /t/n");		if(label == NULL) // empty line			exit_input_error(total+1);		target_label = strtod(label,&endptr);		if(endptr == label || *endptr != '/0')			exit_input_error(total+1);		while(1)		{			if(i>=max_nr_attr-2)	// need one more for index = -1			{				max_nr_attr *= 2;				x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node));			}			idx = strtok(NULL,":");			val = strtok(NULL," /t");			if(val == NULL)				break;			errno = 0;			x[i].index = (int) strtol(idx,&endptr,10);			if(endptr == idx || errno != 0 || *endptr != '/0' || x[i].index <= inst_max_index)				exit_input_error(total+1);			else				inst_max_index = x[i].index;			errno = 0;			x[i].value = strtod(val,&endptr);			if(endptr == val || errno != 0 || (*endptr != '/0' && !isspace(*endptr)))				exit_input_error(total+1);			// feature indices larger than those in training are not used			if(x[i].index <= nr_feature)				++i;		}		if(model_->bias>=0)		{			x[i].index = n;			x[i].value = model_->bias;			i++;		}		x[i].index = -1;		if(flag_predict_probability)		{			int j;			predict_label = predict_probability(model_,x,prob_estimates);			fprintf(output,"%g",predict_label);			for(j=0;j<model_->nr_class;j++)				fprintf(output," %g",prob_estimates[j]);			fprintf(output,"/n");		}//.........这里部分代码省略.........
开发者ID:ucsd-vision,项目名称:liblinear,代码行数:101,


示例24: process_arguments

/* process command-line arguments */static intprocess_arguments (int argc, char **argv){	int c;	int escape = 0;	char *temp;	int option = 0;	static struct option longopts[] = {		{"hostname", required_argument, 0, 'H'},		{"critical", required_argument, 0, 'c'},		{"warning", required_argument, 0, 'w'},		{"critical-codes", required_argument, 0, 'C'},		{"warning-codes", required_argument, 0, 'W'},		{"timeout", required_argument, 0, 't'},		{"protocol", required_argument, 0, 'P'}, /* FIXME: Unhandled */		{"port", required_argument, 0, 'p'},		{"escape", no_argument, 0, 'E'},		{"all", no_argument, 0, 'A'},		{"send", required_argument, 0, 's'},		{"expect", required_argument, 0, 'e'},		{"maxbytes", required_argument, 0, 'm'},		{"quit", required_argument, 0, 'q'},		{"jail", no_argument, 0, 'j'},		{"delay", required_argument, 0, 'd'},		{"refuse", required_argument, 0, 'r'},		{"mismatch", required_argument, 0, 'M'},		{"use-ipv4", no_argument, 0, '4'},		{"use-ipv6", no_argument, 0, '6'},		{"verbose", no_argument, 0, 'v'},		{"version", no_argument, 0, 'V'},		{"help", no_argument, 0, 'h'},		{"ssl", no_argument, 0, 'S'},		{"certificate", required_argument, 0, 'D'},		{0, 0, 0, 0}	};	if (argc < 2)		usage4 (_("No arguments found"));	/* backwards compatibility */	for (c = 1; c < argc; c++) {		if (strcmp ("-to", argv[c]) == 0)			strcpy (argv[c], "-t");		else if (strcmp ("-wt", argv[c]) == 0)			strcpy (argv[c], "-w");		else if (strcmp ("-ct", argv[c]) == 0)			strcpy (argv[c], "-c");	}	if (!is_option (argv[1])) {		server_address = argv[1];		argv[1] = argv[0];		argv = &argv[1];		argc--;	}	while (1) {		c = getopt_long (argc, argv, "+hVv46EAH:s:e:q:m:c:w:t:p:C:W:d:Sr:jD:M:",		                 longopts, &option);		if (c == -1 || c == EOF || c == 1)			break;		switch (c) {		case '?':                 /* print short usage statement if args not parsable */			usage5 ();		case 'h':                 /* help */			print_help ();			exit (STATE_OK);		case 'V':                 /* version */			print_revision (progname, NP_VERSION);			exit (STATE_OK);		case 'v':                 /* verbose mode */			flags |= FLAG_VERBOSE;			break;		case '4':			address_family = AF_INET;			break;		case '6':#ifdef USE_IPV6			address_family = AF_INET6;#else			usage4 (_("IPv6 support not available"));#endif			break;		case 'H':                 /* hostname */			server_address = optarg;			break;		case 'c':                 /* critical */			critical_time = strtod (optarg, NULL);			flags |= FLAG_TIME_CRIT;			break;		case 'j':		  /* hide output */			flags |= FLAG_HIDE_OUTPUT;			break;		case 'w':                 /* warning */			warning_time = strtod (optarg, NULL);			flags |= FLAG_TIME_WARN;//.........这里部分代码省略.........
开发者ID:abradley,项目名称:nagios-plugins,代码行数:101,


示例25: main

int main(int argc, char *argv[]){    Ecore_Evas *ee;    Evas_Object *bridge, *img;    const char *opt, *input, *output, *params;    int r = 0, w = -1, h = -1, err;    double scale = -1.0;    if (argc < 4) {        fprintf(stderr,                "Usage:/n"                "/t%s <percentage%%|WxH|w=W|h=H> <input> <output>"                " [save-params]/n"                "where save-params is evas supported parameters, like:/n"                "/tquality=85/n"                "/tcompress=9/n",                argv[0]);        return 1;    }    opt = argv[1];    input = argv[2];    output = argv[3];    params = argv[4];    if (strncasecmp(opt, "w=", 2) == 0) {        char *end = NULL;        w = strtol(opt + 2, &end, 10);        if (!end || *end != '/0') {            fprintf(stderr, "ERROR: invalid decimal integer '%s'/n",                    opt + 2);            return 1;        } else if (w < 1) {            fprintf(stderr, "ERROR: invalid width %d, must be >= 1/n", w);            return 1;        }    } else if (strncasecmp(opt, "h=", 2) == 0) {        char *end = NULL;        h = strtol(opt + 2, &end, 10);        if (!end || *end != '/0') {            fprintf(stderr, "ERROR: invalid decimal integer '%s'/n",                    opt + 2);            return 1;        } else if (h < 1) {            fprintf(stderr, "ERROR: invalid height %d, must be >= 1/n", h);            return 1;        }    } else if (strchr(opt, '%')) {        char *end = NULL;        scale = strtod(opt, &end);        if (!end || *end != '%') {            fprintf(stderr, "ERROR: invalid percentual '%s'/n", opt);            return 1;        } else if (scale <= 0.0) {            fprintf(stderr, "ERROR: invalid percentual %g, must be > 0.0/n",                    scale);            return 1;        }        scale /= 100.0;    } else if (strchr(opt, 'x')) {        if (sscanf(opt, "%dx%d", &w, &h) != 2) {            fprintf(stderr, "ERROR: invalid size format '%s'/n", opt);            return 1;        } else if (w < 1) {            fprintf(stderr, "ERROR: invalid width %d, must be >= 1/n", w);            return 1;        } else {            fprintf(stderr, "ERROR: invalid height %d, must be >= 1/n", h);            return 1;        }    } else {        fprintf(stderr,                "ERROR: first parameter must be in format:/n"                "/tpercentage%%    - example: 10%%/n"                "/tWxH            - example: 1024x768/n"                "/tw=W            - example: w=1024/n"                "/th=H            - example: h=768/n"                "But '%s' was used!/n",                opt);        return 1;    }    ecore_evas_init();    evas_init();    ee = ecore_evas_buffer_new(1, 1);    bridge = ecore_evas_object_image_new(ee);    img = evas_object_image_add(ecore_evas_object_evas_get(bridge));    evas_object_image_smooth_scale_set(img, EINA_TRUE);    if (w > 0 && h > 0)        evas_object_image_load_size_set(img, w, h);    evas_object_image_file_set(img, input, NULL);    err = evas_object_image_load_error_get(img);    if (err != EVAS_LOAD_ERROR_NONE) {        const char *msg = evas_load_error_str(err);        fprintf(stderr, "ERROR: could not load '%s': %s/n", input, msg);        r = 1;        goto end;//.........这里部分代码省略.........
开发者ID:barbieri,项目名称:barbieri-playground,代码行数:101,


示例26: readData

void readData(double *adLookUp, char* szDataFile, t_Flows* ptFlows, t_Params *ptParams){  char szLine[MAX_LINE_LENGTH];  char *szTok;  int nN = 0, nM = 0;  double *adData = NULL;  double *adF    = NULL;  int    *anF    = NULL;  int    *anLengths = NULL;  char *pcError = NULL;  int i = 0, j = 0, nE = 0;  FILE *ifp = NULL;  ifp = fopen(szDataFile, "r");  if(ifp){    /*read header line*/    fgets(szLine, MAX_LINE_LENGTH, ifp);    /*get read number*/    szTok = strtok(szLine, DELIM);    nN = strtol(szTok,&pcError, 10);    if(*pcError != '/0')      goto formatError;    /*get flow number*/    szTok = strtok(NULL,DELIM);    nM = strtol(szTok,&pcError, 10);    if(*pcError != '/0')      goto formatError;        adData = (double *) malloc(nN*nM*sizeof(double));    if(!adData)      goto memoryError;    adF = (double *) malloc(nN*nM*sizeof(double));    if(!adF)      goto memoryError;    anF = (int *) malloc(nN*nM*sizeof(int));    if(!anF)      goto memoryError;    anLengths = (int *) malloc(nN*sizeof(int));    if(!anLengths)      goto memoryError;    for(i = 0; i < nN; i++){      fgets(szLine, MAX_LINE_LENGTH, ifp);            szTok = strtok(szLine, DELIM);      if(ptParams->bNoIndex == FALSE){ 	szTok = strtok(NULL, DELIM);      }      anLengths[i] = strtol(szTok, &pcError,10);      if(*pcError != '/0')	goto formatError;          nE = anLengths[i] % 4;      anLengths[i] -= nE;          printf("%d %d %d %d/n",i, anLengths[i], nE, nM);      for(j = 0; j < anLengths[i]; j++){	double dF = 0.0;	szTok = strtok(NULL, DELIM);	dF = strtod(szTok, &pcError);	//	printf("%d %s %f/n",j, szTok,dF);	if(dF >= 9.99){	  //fprintf(stderr,"%d %d %f too large max flow 9.99/n",i,j,dF);	  dF = 9.99;	  fflush(stderr);	}	adData[i*nM + j] = dF;	anF[i*nM + j] =  (int) floor((dF + DELTA)/PRECISION);	if(anF[i*nM + j] < 0){	  anF[i*nM + j] = 0;	}	if(anF[i*nM + j] > BINS - 1){	  anF[i*nM + j] = BINS - 1;	}	adF[i*nM + j] = distM1(adLookUp, dF);		if(*pcError != '/0')	  goto formatError;      }      for(; j < nM; j++){	double dF = 0.0;	adData[i*nM + j] = dF;	anF[i*nM + j] =  (int) floor((dF + DELTA)/PRECISION);	adF[i*nM + j] = distM1(adLookUp, dF);	      }    }    fclose(ifp);  }//.........这里部分代码省略.........
开发者ID:b4winckler,项目名称:ampliconnoise,代码行数:101,


示例27: while

//.........这里部分代码省略.........		*s=0;		if (!strcmp(szIdent, "declare"))			return TOK_DECLARE;		else if (!strcmp(szIdent, "true"))			return TOK_TRUE;		else if (!strcmp(szIdent, "false"))			return TOK_FALSE;		else if (!strcmp(szIdent, "int"))			return TOK_INT;		else if (!strcmp(szIdent, "long"))			return TOK_LONG;		else if (!strcmp(szIdent, "double"))			return TOK_DOUBLE;		return TOK_IDENT;	}	// test for number: decimal (123), octal (0123), or hexadecimal (0x123)	if (isdigit((unsigned char)c)) {		sint64 v = 0;		if (c=='0' && tokstr[0] == 'x') {			// hex (base 16)			++tokstr;			while(isxdigit((unsigned char)(c = *tokstr++))) {				v = v*16 + (strchr(hexdig, toupper(c))-hexdig);			}		} else if (c=='0' && isdigit((unsigned char)tokstr[0])) {			// octal (base 8)			while((c=*tokstr++)>='0' && c<='7')				v = v*8 + (c-'0');		} else {			// check for float			const char *s = tokstr;			while(*s) {				if (*s == '.' || *s == 'e' || *s == 'E') {					// It's a float -- parse and return.					--tokstr;					tokdval = strtod(tokstr, (char **)&tokstr);					return TOK_DBLVAL;				}				if (!isdigit((unsigned char)*s))					break;				++s;			}			// decimal			v = (c-'0');			while(isdigit((unsigned char)(c=*tokstr++)))				v = v*10 + (c-'0');		}		--tokstr;		if (v > 0x7FFFFFFF) {			toklval = v;			return TOK_LONGVAL;		} else {			tokival = (int)v;			return TOK_INTVAL;		}	}	// test for symbols:	//	//	charset:	+-*/<>=!&|^[]~;%(),	//	solitary:	+-*/<>=!&|^[]~;%(),	//	extra:		!= <= >= == && ||	//	//	the '/' is handled above for comment handling	if (c=='!')		if (tokstr[0] == '=') { ++tokstr; return TOK_NOTEQ;  } else return '!';	if (c=='<')		if (tokstr[0] == '=') { ++tokstr; return TOK_LESSEQ; } else return '<';	if (c=='>')		if (tokstr[0] == '=') { ++tokstr; return TOK_GRTREQ; } else return '>';	if (c=='=')		if (tokstr[0] == '=') { ++tokstr; return TOK_EQUALS; } else return '=';	if (c=='&')		if (tokstr[0] == '&') { ++tokstr; return TOK_AND;    } else return '&';	if (c=='|')		if (tokstr[0] == '|') { ++tokstr; return TOK_OR;     } else return '|';	if (strchr("+-*^[]~;%(),.",c))		return c;	SCRIPT_ERROR(PARSE_ERROR);}
开发者ID:KGE-INC,项目名称:modplus,代码行数:101,


示例28: IoSeq_asDouble

double IoSeq_asDouble(IoSeq *self){	return strtod((char *)UArray_bytes(DATA(self)), NULL);}
开发者ID:Akiyah,项目名称:io,代码行数:4,



注:本文中的strtod函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ strtoi函数代码示例
C++ strtobool函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。