Пример #1
0
void commit_params (struct dt_iop_module_t *self, dt_iop_params_t *p1, dt_dev_pixelpipe_t *pipe, dt_dev_pixelpipe_iop_t *piece)
{
    dt_iop_exposure_params_t *p = (dt_iop_exposure_params_t *)p1;
    dt_iop_exposure_data_t *d = (dt_iop_exposure_data_t *)piece->data;
    dt_iop_exposure_gui_data_t *g = (dt_iop_exposure_gui_data_t *)self->gui_data;

    d->black = p->black;
    d->exposure = p->exposure;

    self->request_histogram        &= ~(DT_REQUEST_ON);
    self->request_histogram        |=  (DT_REQUEST_ONLY_IN_GUI);
    self->request_histogram_source  =  (DT_DEV_PIXELPIPE_PREVIEW);

    if(self->dev->gui_attached)
    {
        g->reprocess_on_next_expose = FALSE;
    }

    gboolean histogram_is_good = ((self->histogram_stats.bins_count == 16384)
                                  && (self->histogram != NULL));

    d->deflicker_percentile = p->deflicker_percentile;
    d->deflicker_target_level = p->deflicker_target_level;

    if(p->mode == EXPOSURE_MODE_DEFLICKER && dt_image_is_raw(&self->dev->image_storage))
    {
        if(p->deflicker_histogram_source == DEFLICKER_HISTOGRAM_SOURCE_SOURCEFILE)
        {
            if(self->dev->gui_attached)
            {
                // histogram is precomputed and cached
                compute_correction(self, piece, g->deflicker_histogram, &g->deflicker_histogram_stats, &d->exposure);
            }
            else
            {
                uint32_t *histogram = NULL;
                dt_dev_histogram_stats_t histogram_stats;
                deflicker_prepare_histogram(self, &histogram, &histogram_stats);
                compute_correction(self, piece, histogram, &histogram_stats, &d->exposure);
                free(histogram);
            }
            d->mode = EXPOSURE_MODE_MANUAL;
        }
        else
        {
            if(p->deflicker_histogram_source == DEFLICKER_HISTOGRAM_SOURCE_THUMBNAIL)
            {
                self->request_histogram |=  (DT_REQUEST_ON);

                gboolean failed = !histogram_is_good;

                if(self->dev->gui_attached && histogram_is_good)
                {
                    /*
                     * if in GUI, user might zoomed main view => we would get histogram of
                     * only part of image, so if in GUI we must always use histogram of
                     * preview pipe, which is always full-size and have biggest size
                     */
                    d->mode = EXPOSURE_MODE_DEFLICKER;
                    commit_params_late(self, piece);
                    d->mode = EXPOSURE_MODE_MANUAL;

                    if(isnan(d->exposure))
                        failed = TRUE;
                }
                else if(failed || !(self->dev->gui_attached && histogram_is_good))
                {
                    d->mode = EXPOSURE_MODE_DEFLICKER;
                    //commit_params_late() will compute correct d->exposure later
                    self->request_histogram        &= ~(DT_REQUEST_ONLY_IN_GUI);
                    self->request_histogram_source  =  (DT_DEV_PIXELPIPE_ANY);

                    if(failed && self->dev->gui_attached)
                    {
                        /*
                         * but sadly we do not yet have a histogram to do so, so this time
                         * we process asif not in gui, and in expose() immediately
                         * reprocess, thus everything works as expected
                         */
                        g->reprocess_on_next_expose = TRUE;
                    }
                }
            }
        }
    }
    else
    {
        d->mode = EXPOSURE_MODE_MANUAL;
    }
}
Пример #2
0
void pnorm_both(double x, double *cum, double *ccum, int i_tail, int log_p) {
  /* i_tail in {0,1,2} means: "lower", "upper", or "both" :
     if (lower) return  *cum := P[X <= x]
     if (upper) return *ccum := P[X >  x] = 1 - P[X <= x]
  */
  const static double a[5] = {
    2.2352520354606839287,
    161.02823106855587881,
    1067.6894854603709582,
    18154.981253343561249,
    0.065682337918207449113
  };
  const static double b[4] = {
    47.20258190468824187,
    976.09855173777669322,
    10260.932208618978205,
    45507.789335026729956
  };
  const static double c[9] = {
    0.39894151208813466764,
    8.8831497943883759412,
    93.506656132177855979,
    597.27027639480026226,
    2494.5375852903726711,
    6848.1904505362823326,
    11602.651437647350124,
    9842.7148383839780218,
    1.0765576773720192317e-8
  };
  const static double d[8] = {
    22.266688044328115691,
    235.38790178262499861,
    1519.377599407554805,
    6485.558298266760755,
    18615.571640885098091,
    34900.952721145977266,
    38912.003286093271411,
    19685.429676859990727
  };
  const static double p[6] = {
    0.21589853405795699,
    0.1274011611602473639,
    0.022235277870649807,
    0.001421619193227893466,
    2.9112874951168792e-5,
    0.02307344176494017303
  };
  const static double q[5] = {
    1.28426009614491121,
    0.468238212480865118,
    0.0659881378689285515,
    0.00378239633202758244,
    7.29751555083966205e-5
  };

  double xden, xnum, temp, del, eps, xsq, y;
#ifdef NO_DENORMS
  double min = DBL_MIN;
#endif
  int i, lower, upper;

#ifdef IEEE_754
  if (isnan(x)) {
    *cum = *ccum = x;
    return;
  }
#endif

  /* Consider changing these : */
  eps = DBL_EPSILON * 0.5;

  /* i_tail in {0,1,2} =^= {lower, upper, both} */
  lower = i_tail != 1;
  upper = i_tail != 0;

  y = fabs(x);
  if (y <= 0.67448975) { /* qnorm(3/4) = .6744.... -- earlier had 0.66291 */
    if (y > eps) {
      xsq = x * x;
      xnum = a[4] * xsq;
      xden = xsq;
      for (i = 0; i < 3; ++i) {
        xnum = (xnum + a[i]) * xsq;
        xden = (xden + b[i]) * xsq;
      }
    }
    else {
      xnum = xden = 0.0;
    }

    temp = x * (xnum + a[3]) / (xden + b[3]);
    if (lower) {
      *cum = 0.5 + temp;
    }
    if (upper) {
      *ccum = 0.5 - temp;
    }
    if (log_p) {
      if (lower) {
        *cum = log(*cum);
      }
      if (upper) {
        *ccum = log(*ccum);
      }
    }
  }
  else if (y <= M_SQRT_32) {
    /* Evaluate pnorm for 0.674.. = qnorm(3/4) < |x| <= sqrt(32) ~= 5.657 */

    xnum = c[8] * y;
    xden = y;
    for (i = 0; i < 7; ++i) {
      xnum = (xnum + c[i]) * y;
      xden = (xden + d[i]) * y;
    }
    temp = (xnum + c[7]) / (xden + d[7]);

#define do_del(X)             \
    xsq = trunc(X * SIXTEEN) / SIXTEEN;       \
    del = (X - xsq) * (X + xsq);          \
    if(log_p) {             \
      *cum = (-xsq * xsq * 0.5) + (-del * 0.5) + log(temp); \
      if((lower && x > 0.) || (upper && x <= 0.))     \
      *ccum = log1p(-exp(-xsq * xsq * 0.5) *    \
        exp(-del * 0.5) * temp);    \
    }               \
    else {                \
      *cum = exp(-xsq * xsq * 0.5) * exp(-del * 0.5) * temp;  \
      *ccum = 1.0 - *cum;           \
    }

#define swap_tail           \
    if (x > 0.) {/* swap  ccum <--> cum */      \
        temp = *cum; if(lower) *cum = *ccum; *ccum = temp;  \
    }

    do_del(y);
    swap_tail;
  }

  /* else   |x| > sqrt(32) = 5.657 :
   * the next two case differentiations were really for lower=T, log=F
   * Particularly  *not*  for  log_p !

   * Cody had (-37.5193 < x  &&  x < 8.2924) ; R originally had y < 50
   *
   * Note that we do want symmetry(0), lower/upper -> hence use y
   */
  else if((log_p && y < 1e170) /* avoid underflow below */
    /*  ^^^^^ MM FIXME: can speedup for log_p and much larger |x| !
     * Then, make use of  Abramowitz & Stegun, 26.2.13, something like

     xsq = x*x;

     if(xsq * DBL_EPSILON < 1.)
        del = (1. - (1. - 5./(xsq+6.)) / (xsq+4.)) / (xsq+2.);
     else
        del = 0.;
     *cum = -.5*xsq - M_LN_SQRT_2PI - log(x) + log1p(-del);
     *ccum = log1p(-exp(*cum)); /.* ~ log(1) = 0 *./

     swap_tail;

     [Yes, but xsq might be infinite.]

    */
      || (lower && -37.5193 < x  &&  x < 8.2924)
      || (upper && -8.2924  < x  &&  x < 37.5193)
  ) {

    /* Evaluate pnorm for x in (-37.5, -5.657) union (5.657, 37.5) */
    xsq = 1.0 / (x * x); /* (1./x)*(1./x) might be better */
    xnum = p[5] * xsq;
    xden = xsq;
    for (i = 0; i < 4; ++i) {
      xnum = (xnum + p[i]) * xsq;
      xden = (xden + q[i]) * xsq;
    }
    temp = xsq * (xnum + p[4]) / (xden + q[4]);
    temp = (M_1_SQRT_2PI - temp) / y;

    do_del(x);
    swap_tail;
  }
  else { /* large x such that probs are 0 or 1 */
    if (x > 0) {
      *cum = R_D__1;
      *ccum = R_D__0;
    }
    else {
      *cum = R_D__0;
      *ccum = R_D__1;
    }
  }

#ifdef NO_DENORMS
  /* do not return "denormalized" -- we do in R */
  if(log_p) {
    if(*cum > -min) {
      *cum = -0.;
    }
    if(*ccum > -min) {
      *ccum = -0.;
    }
  }
  else {
    if(*cum < min) {
      *cum = 0.;
    }
    if(*ccum < min) {
      *ccum = 0.;
    }
  }
#endif
  return;
}
Пример #3
0
/**
 * Compute the quantile function for the normal distribution.
 */
double qnorm(double p, double mu, double sigma, int lower_tail, int log_p) {
  double p_, q, r, val;

#ifdef IEEE_754
    if (isnan(p) || isnan(mu) || isnan(sigma))
  return p + mu + sigma;
#endif

  R_Q_P01_boundaries(p, ML_NEGINF, ML_POSINF);

  p_ = R_DT_qIv(p); // real lower_tail prob. p
  q = p_ - 0.5;

  /*-- use AS 241 --- *
   * double ppnd16_(double *p, long *ifault)*
   * ALGORITHM AS241  APPL. STATIST. (1988) VOL. 37, NO. 3
   *
   * Produces the normal deviate Z corresponding to a given lower
   * tail area of P; Z is accurate to about 1 part in 10**16.
   *
   * (original fortran code used PARAMETER(..) for the coefficients
   * and provided hash codes for checking them...)
   */
  /* 0.075 <= p <= 0.925 */
  if (fabs(q) <= .425) {

    r = .180625 - q * q;
    val = q * (((((((r * 2509.0809287301226727 +
                     33430.575583588128105) * r + 67265.770927008700853) * r +
                     45921.953931549871457) * r + 13731.693765509461125) * r +
                     1971.5909503065514427) * r + 133.14166789178437745) * r +
                     3.387132872796366608)
            / (((((((r * 5226.495278852854561 +
                     28729.085735721942674) * r + 39307.89580009271061) * r +
                     21213.794301586595867) * r + 5394.1960214247511077) * r +
                     687.1870074920579083) * r + 42.313330701600911252) * r + 1.);
  }
  /* closer than 0.075 from {0,1} boundary */
  else {
    /* r = min(p, 1-p) < 0.075 */
    if (q > 0) {
      r = R_DT_CIv(p); /* 1-p */
    }
    else {
      r = p_; /* = R_DT_Iv(p) ^=  p */
    }
    r = sqrt(- ((log_p && ((lower_tail && q <= 0) || (!lower_tail && q > 0))) ? p : /* else */ log(r)));

    if (r <= 5.) { /* <==> min(p,1-p) >= exp(-25) ~= 1.3888e-11 */
      r += -1.6;
      val = (((((((r * 7.7454501427834140764e-4 +
                   .0227238449892691845833) * r + .24178072517745061177) *
                    r + 1.27045825245236838258) * r +
                    3.64784832476320460504) * r + 5.7694972214606914055) *
                    r + 4.6303378461565452959) * r +
                    1.42343711074968357734)
              / (((((((r *
                       1.05075007164441684324e-9 + 5.475938084995344946e-4) *
                       r + .0151986665636164571966) * r +
                       .14810397642748007459) * r + .68976733498510000455) *
                       r + 1.6763848301838038494) * r +
                       2.05319162663775882187) * r + 1.);
    }
    else { /* very close to  0 or 1 */
      r += -5.;
      val = (((((((r * 2.01033439929228813265e-7 +
                   2.71155556874348757815e-5) * r +
                   .0012426609473880784386) * r + .026532189526576123093) *
                   r + .29656057182850489123) * r +
                   1.7848265399172913358) * r + 5.4637849111641143699) *
                   r + 6.6579046435011037772)
             / (((((((r *
                   2.04426310338993978564e-15 + 1.4215117583164458887e-7)*
                   r + 1.8463183175100546818e-5) * r +
                   7.868691311456132591e-4) * r + .0148753612908506148525)
                   * r + .13692988092273580531) * r +
                  .59983220655588793769) * r + 1.);
    }

    if (q < 0.0) {
      val = -val;
    }
    /* return (q >= 0.)? r : -r ;*/
  }
  return mu + sigma * val;
}
Пример #4
0
int isfinite(double x) {
	return !isnan(x) && !isinf(x);
}
Пример #5
0
	static const double MAX_DOUBLE_ERROR = 1e-9; static bool topcoder_fequ(double expected, double result) { if (isnan(expected)) { return isnan(result); } else if (isinf(expected)) { if (expected > 0) { return result > 0 && isinf(result); } else { return result < 0 && isinf(result); } } else if (isnan(result) || isinf(result)) { return false; } else if (fabs(result - expected) < MAX_DOUBLE_ERROR) { return true; } else { double mmin = min(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); double mmax = max(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); return result > mmin && result < mmax; } }
Пример #6
0
int bi_entry(void * mdpv, int iproblemsize, double * dresults)
{
   /* dstart, dend: the start and end time of the measurement */
   /* dtime: the time for a single measurement in seconds */
   double dstart = 0.0, dend = 0.0, dtime = 0.0, dinit = 0.0;
   /* flops stores the calculated FLOPS */
   double flops = 0.0;
   /* ii is used for loop iterations */
   myinttype ii, jj, imyproblemsize, numberOfRuns;
   /* cast void* pointer */
   mydata_t* pmydata = (mydata_t*)mdpv;
   int invalid = 0;
   long status, len[3];

   /* calculate real problemsize */
   imyproblemsize = (int)(pmydata->problemsizes[iproblemsize - 1]);

   len[0] = imyproblemsize;
   len[1] = imyproblemsize;
   len[2] = imyproblemsize;

   /* store the value for the x axis in results[0] */
   dresults[0] = (double)imyproblemsize;


   /*** in place run ***/

   /* malloc */
   pmydata->inout = (double*)malloc(sizeof(double) * imyproblemsize * imyproblemsize * imyproblemsize * 2);

   /* create FFT plan */
   status = DftiCreateDescriptor(&pmydata->my_desc_handle, DFTI_DOUBLE, DFTI_COMPLEX, 3, len);
   status = DftiCommitDescriptor(pmydata->my_desc_handle);


   /* init stuff */
   initData_ip(pmydata, imyproblemsize);

   numberOfRuns = 1;

   dstart = bi_gettime();
   /* fft calculation */
   status = DftiComputeForward(pmydata->my_desc_handle, pmydata->inout);
   dend = bi_gettime();

   /* calculate the used time*/
   dtime = dend - dstart;
   dtime -= dTimerOverhead;

   /* loop calculation if accuracy is insufficient */
   while (dtime < 100 * dTimerGranularity) {

     numberOfRuns = numberOfRuns * 2;

     dstart = bi_gettime();
     for (jj = 0; jj < numberOfRuns; jj++) {
       /* fft calculation */
       status = DftiComputeForward(pmydata->my_desc_handle, pmydata->inout);
     }
     dend = bi_gettime();

     dtime = dend - dstart;
     dtime -= dTimerOverhead;
   }

   /* check for overflows */
   for (ii = 0; ii < imyproblemsize * imyproblemsize * imyproblemsize; ii++) {
     if (isnan(pmydata->inout[2 * ii]) || isnan(pmydata->inout[2 * ii + 1])) invalid = 1;
     if (isinf(pmydata->inout[2 * ii]) || isinf(pmydata->inout[2 * ii + 1])) invalid = 1;
   }

   /* if loop was necessary */
   if (numberOfRuns > 1) dtime = dtime / numberOfRuns;

   /* calculate the used FLOPS */
   flops = (double)(5.0 * imyproblemsize * imyproblemsize * imyproblemsize * (log2(1.0 * imyproblemsize * imyproblemsize * imyproblemsize)) / dtime);

   /* store the FLOPS in results[1] */
   if (invalid == 1) dresults[1] = INVALID_MEASUREMENT;
     else dresults[1] = flops;

   status = DftiFreeDescriptor(&pmydata->my_desc_handle);

   /* free data */
   free(pmydata->inout);


   /*** out of place run ***/

   /* malloc */
   pmydata->in = (double*)malloc(sizeof(double) * imyproblemsize * imyproblemsize * imyproblemsize * 2);
   pmydata->out = (double*)malloc(sizeof(double) * imyproblemsize * imyproblemsize * imyproblemsize * 2);

   /* create FFT plan */
   status = DftiCreateDescriptor(&pmydata->my_desc_handle, DFTI_DOUBLE, DFTI_COMPLEX, 3, len);
   status = DftiSetValue(pmydata->my_desc_handle, DFTI_PLACEMENT, DFTI_NOT_INPLACE);
   status = DftiCommitDescriptor(pmydata->my_desc_handle);

   /* init stuff */
   initData_oop(pmydata, imyproblemsize);

   numberOfRuns = 1;

   dstart = bi_gettime();
   /* fft calculation */
   status = DftiComputeForward(pmydata->my_desc_handle, pmydata->in, pmydata->out);
   dend = bi_gettime();

   /* calculate the used time*/
   dtime = dend - dstart;
   dtime -= dTimerOverhead;

   /* loop calculation if accuracy is insufficient */
   while (dtime < 100 * dTimerGranularity) {

     numberOfRuns = numberOfRuns * 2;

     dstart = bi_gettime();
     for (ii = 0; ii < numberOfRuns; ii++) {
        /* fft calculation */
        status = DftiComputeForward(pmydata->my_desc_handle, pmydata->in, pmydata->out);
     }
     dend = bi_gettime();

     /* calculate the used time*/
     dtime = dend - dstart;
     dtime -= dTimerOverhead;
   }

   /* if loop was necessary */
   if (numberOfRuns > 1) dtime = dtime / numberOfRuns;

   /* check for overflows */
   for (ii = 0; ii < imyproblemsize * imyproblemsize * imyproblemsize; ii++) {
     if (isnan(pmydata->out[2 * ii]) || isnan(pmydata->out[2 * ii + 1])) invalid = 1;
     if (isinf(pmydata->out[2 * ii]) || isinf(pmydata->out[2 * ii + 1])) invalid = 1;
   }

   /* calculate the used FLOPS */
   flops = (double)(5.0 * imyproblemsize * imyproblemsize * imyproblemsize * (log2(1.0 * imyproblemsize * imyproblemsize * imyproblemsize)) / dtime);

   /* store the FLOPS in results[2] */
   if (invalid == 1) dresults[2] = INVALID_MEASUREMENT;
     else dresults[2] = flops;

   status = DftiFreeDescriptor(&pmydata->my_desc_handle);

   /* free data */
   free(pmydata->in);
   free(pmydata->out);

   return 0;
}
Пример #7
0
int main(int argc, char const *argv[])
{
    int fd1[2];
    int fd2[2];

    if (pipe(fd1) == -1)
    {
        perror("pipe");
        exit(1);
    }

    if (pipe(fd2) == -1)
    {
        perror("pipe");
        exit(1);
    }


    pid_t pid;

    pid = fork();

    if (pid < 0)
    {
        perror("fork");
        exit(1);
    }
    else if (pid == 0) // Child process -> Reader
    {
        close(fd1[WRITE]);
        close(fd2[READ]);

        int values[2];

        read(fd1[READ], &values, sizeof(values));

        close(fd1[READ]);

        int sum =  values[0] + values[1];
        int diff = values[0] - values[1];
        int prod = values[0] * values[1];

        float quocient;
        if (values[1] != 0)
            quocient = (float)values[0] / (float)values[1];
        else
            quocient = NAN;


        sendValue(fd2[WRITE], TYPE_INTEGER, &sum);
        sendValue(fd2[WRITE], TYPE_INTEGER, &diff);
        sendValue(fd2[WRITE], TYPE_INTEGER, &prod);
        if (isnan(quocient))
            sendValue(fd2[WRITE], TYPE_INVALID, NULL);
        else
            sendValue(fd2[WRITE], TYPE_FLOAT, &quocient);

        close(fd2[WRITE]);

        _exit(0);
    }
    else if (pid > 0) // Father process -> Writer
    {
        close(fd1[READ]);
        close(fd2[WRITE]);
        int values[NUMS_TO_READ];

        printf("Insert two comma separated integers (example: 1, 2): ");
        fflush(stdout);

        scanf("%10d, %10d", &values[0], &values[1]);

        write(fd1[WRITE], values, sizeof(values));

        close(fd1[WRITE]);

        for (int i = 0; i < 4; ++i)
        {
            value val = receiveValue(fd2[READ]);
            printf(strOperations[i], values[0], values[1]);

            switch(val.t)
            {
                case TYPE_INTEGER:
                    printf("%d", val.val.i);
                    break;
                case TYPE_FLOAT:
                    printf("%f", val.val.f);
                    break;
                case TYPE_INVALID:
                    printf("invalid");
                    break;
            }

            printf("\n");
        }

        close(fd2[READ]);
        wait(NULL);

        exit(0);
    }
}
Пример #8
0
int32_t Var(MEM_POOL_PTR mem_pool, struct low_data_struct* cur_value,
		struct low_data_struct* new_value) {
	struct low_data_struct *square_sum, *sum, *count;
	MileArray* array;
	double a, b;

	if (cur_value == NULL || new_value == NULL) {
		return -1;
	}

	if (new_value->type != HI_TYPE_NULL && new_value->len > 0) {
		if (cur_value->data == NULL) {
			array =
					new (mem_pool_malloc(mem_pool, sizeof(MileArray))) MileArray(
							mem_pool);
			cur_value->type = HI_TYPE_ARRAY;
			cur_value->len = 3;
			cur_value->data = array;

			//initial the square sum
			square_sum = (struct low_data_struct*) mem_pool_malloc(mem_pool,
					sizeof(struct low_data_struct));
			memset(square_sum, 0, sizeof(struct low_data_struct));
			square_sum->type = HI_TYPE_DOUBLE;
			square_sum->len = sizeof(double);
			square_sum->data = mem_pool_malloc(mem_pool, sizeof(double));
			*(double*) square_sum->data = 0;
			array->Add(square_sum);

			//initial the sum
			sum = (struct low_data_struct*) mem_pool_malloc(mem_pool,
					sizeof(struct low_data_struct));
			memset(sum, 0, sizeof(struct low_data_struct));
			sum->type = HI_TYPE_DOUBLE;
			sum->len = sizeof(double);
			sum->data = mem_pool_malloc(mem_pool, sizeof(double));
			*(double*) sum->data = 0;
			array->Add(sum);

			//initial the count
			count = (struct low_data_struct*) mem_pool_malloc(mem_pool,
					sizeof(struct low_data_struct));
			memset(count, 0, sizeof(struct low_data_struct));
			count->type = HI_TYPE_LONGLONG;
			count->len = sizeof(uint64_t);
			count->data = mem_pool_malloc(mem_pool, sizeof(uint64_t));
			*(uint64_t*) count->data = 0;
			array->Add(count);
		}

		array = (MileArray*) cur_value->data;
		square_sum = (struct low_data_struct*) array->Get(0);
		sum = (struct low_data_struct*) array->Get(1);
		count = (struct low_data_struct*) array->Get(2);

		*(uint64_t*) count->data = *(uint64_t*) count->data + 1;

		a = ld_to_double(new_value);
		b = *(double*) sum->data;
		if (isnan(a)) {
			*(double*) sum->data = a;
			*(double*) square_sum->data = a;
			if (new_value->field_name != NULL) {
				log_error("%s列的类型不能转换为double, 无法进行var操作", new_value->field_name);
			}
		} else if (!isnan(b)) {
			*(double*) square_sum->data = (*(double*) square_sum->data + a * a);
			*(double*) sum->data = (*(double*) sum->data) + a;
		}
	}

	return MILE_RETURN_SUCCESS;
}
Пример #9
0
int yr_execute_code(
    YR_RULES* rules,
    YR_SCAN_CONTEXT* context,
    int timeout,
    time_t start_time)
{
  int64_t mem[MEM_SIZE];
  int64_t args[MAX_FUNCTION_ARGS];
  int32_t sp = 0;
  uint8_t* ip = rules->code_start;

  STACK_ITEM *stack;
  STACK_ITEM r1;
  STACK_ITEM r2;
  STACK_ITEM r3;

  #ifdef PROFILING_ENABLED
  YR_RULE* current_rule = NULL;
  #endif

  YR_RULE* rule;
  YR_MATCH* match;
  YR_OBJECT_FUNCTION* function;

  char* identifier;
  char* args_fmt;

  int i;
  int found;
  int count;
  int result = ERROR_SUCCESS;
  int stop = FALSE;
  int cycle = 0;
  int tidx = context->tidx;

  #ifdef PROFILING_ENABLED
  clock_t start = clock();
  #endif

  stack = (STACK_ITEM *) yr_malloc(STACK_SIZE * sizeof(STACK_ITEM));

  if (stack == NULL)
    return ERROR_INSUFICIENT_MEMORY;

  while(!stop)
  {
    switch(*ip)
    {
      case OP_HALT:
        assert(sp == 0); // When HALT is reached the stack should be empty.
        stop = TRUE;
        break;

      case OP_PUSH:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);
        push(r1);
        break;

      case OP_POP:
        pop(r1);
        break;

      case OP_CLEAR_M:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);
        mem[r1.i] = 0;
        break;

      case OP_ADD_M:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);
        pop(r2);
        if (!is_undef(r2))
          mem[r1.i] += r2.i;
        break;

      case OP_INCR_M:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);
        mem[r1.i]++;
        break;

      case OP_PUSH_M:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);
        r1.i = mem[r1.i];
        push(r1);
        break;

      case OP_POP_M:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);
        pop(r2);
        mem[r1.i] = r2.i;
        break;

      case OP_SWAPUNDEF:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);
        pop(r2);

        if (is_undef(r2))
        {
          r1.i = mem[r1.i];
          push(r1);
        }
        else
        {
          push(r2);
        }
        break;

      case OP_JNUNDEF:
        pop(r1);
        push(r1);

        ip = jmp_if(!is_undef(r1), ip);
        break;

      case OP_JLE:
        pop(r2);
        pop(r1);
        push(r1);
        push(r2);

        ip = jmp_if(r1.i <= r2.i, ip);
        break;

      case OP_JTRUE:
        pop(r1);
        push(r1);

        ip = jmp_if(!is_undef(r1) && r1.i, ip);
        break;

      case OP_JFALSE:
        pop(r1);
        push(r1);

        ip = jmp_if(is_undef(r1) || !r1.i, ip);
        break;

      case OP_AND:
        pop(r2);
        pop(r1);

        if (is_undef(r1) || is_undef(r2))
          r1.i = 0;
        else
          r1.i = r1.i && r2.i;

        push(r1);
        break;

      case OP_OR:
        pop(r2);
        pop(r1);

        if (is_undef(r1))
        {
          push(r2);
        }
        else if (is_undef(r2))
        {
          push(r1);
        }
        else
        {
          r1.i = r1.i || r2.i;
          push(r1);
        }
        break;

      case OP_NOT:
        pop(r1);

        if (is_undef(r1))
          r1.i = UNDEFINED;
        else
          r1.i= !r1.i;

        push(r1);
        break;

      case OP_MOD:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        if (r2.i != 0)
          r1.i = r1.i % r2.i;
        else
          r1.i = UNDEFINED;
        push(r1);
        break;

      case OP_SHR:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i >> r2.i;
        push(r1);
        break;

      case OP_SHL:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i << r2.i;
        push(r1);
        break;

      case OP_BITWISE_NOT:
        pop(r1);
        ensure_defined(r1);
        r1.i = ~r1.i;
        push(r1);
        break;

      case OP_BITWISE_AND:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i & r2.i;
        push(r1);
        break;

      case OP_BITWISE_OR:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i | r2.i;
        push(r1);
        break;

      case OP_BITWISE_XOR:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i ^ r2.i;
        push(r1);
        break;

      case OP_PUSH_RULE:
        rule = *(YR_RULE**)(ip + 1);
        ip += sizeof(uint64_t);
        r1.i = rule->t_flags[tidx] & RULE_TFLAGS_MATCH ? 1 : 0;
        push(r1);
        break;

      case OP_INIT_RULE:
        #ifdef PROFILING_ENABLED
        current_rule = *(YR_RULE**)(ip + 1);
        #endif
        ip += sizeof(uint64_t);
        break;

      case OP_MATCH_RULE:
        pop(r1);
        rule = *(YR_RULE**)(ip + 1);
        ip += sizeof(uint64_t);

        if (!is_undef(r1) && r1.i)
          rule->t_flags[tidx] |= RULE_TFLAGS_MATCH;

        #ifdef PROFILING_ENABLED
        rule->clock_ticks += clock() - start;
        start = clock();
        #endif
        break;

      case OP_OBJ_LOAD:
        identifier = *(char**)(ip + 1);
        ip += sizeof(uint64_t);

        r1.o = (YR_OBJECT*) yr_hash_table_lookup(
            context->objects_table,
            identifier,
            NULL);

        assert(r1.o != NULL);
        push(r1);
        break;

      case OP_OBJ_FIELD:
        identifier = *(char**)(ip + 1);
        ip += sizeof(uint64_t);

        pop(r1);
        ensure_defined(r1);

        r1.o = yr_object_lookup_field(r1.o, identifier);

        assert(r1.o != NULL);
        push(r1);
        break;

      case OP_OBJ_VALUE:
        pop(r1);
        ensure_defined(r1);

        switch(r1.o->type)
        {
          case OBJECT_TYPE_INTEGER:
            r1.i = ((YR_OBJECT_INTEGER*) r1.o)->value;
            break;

          case OBJECT_TYPE_FLOAT:
            if (isnan(((YR_OBJECT_DOUBLE*) r1.o)->value))
              r1.i = UNDEFINED;
            else
              r1.d = ((YR_OBJECT_DOUBLE*) r1.o)->value;
            break;

          case OBJECT_TYPE_STRING:
            if (((YR_OBJECT_STRING*) r1.o)->value == NULL)
              r1.i = UNDEFINED;
            else
              r1.p = ((YR_OBJECT_STRING*) r1.o)->value;
            break;

          default:
            assert(FALSE);
        }

        push(r1);
        break;

      case OP_INDEX_ARRAY:
        pop(r1);  // index
        pop(r2);  // array

        ensure_defined(r1);
        ensure_defined(r2);
        assert(r2.o->type == OBJECT_TYPE_ARRAY);

        r1.o = yr_object_array_get_item(r2.o, 0, (int) r1.i);

        if (r1.o == NULL)
          r1.i = UNDEFINED;

        push(r1);
        break;

      case OP_LOOKUP_DICT:
        pop(r1);  // key
        pop(r2);  // dictionary

        ensure_defined(r1);
        ensure_defined(r2);
        assert(r2.o->type == OBJECT_TYPE_DICTIONARY);

        r1.o = yr_object_dict_get_item(
            r2.o, 0, r1.ss->c_string);

        if (r1.o == NULL)
          r1.i = UNDEFINED;

        push(r1);
        break;

      case OP_CALL:
        args_fmt = *(char**)(ip + 1);
        ip += sizeof(uint64_t);

        i = (int) strlen(args_fmt);
        count = 0;

        // pop arguments from stack and copy them to args array

        while (i > 0)
        {
          pop(r1);

          if (is_undef(r1))  // count the number of undefined args
            count++;

          args[i - 1] = r1.i;
          i--;
        }

        pop(r2);
        ensure_defined(r2);

        if (count > 0)
        {
          // if there are undefined args, result for function call
          // is undefined as well.

          r1.i = UNDEFINED;
          push(r1);
          break;
        }

        function = (YR_OBJECT_FUNCTION*) r2.o;
        result = ERROR_INTERNAL_FATAL_ERROR;

        for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++)
        {
          if (function->prototypes[i].arguments_fmt == NULL)
            break;

          if (strcmp(function->prototypes[i].arguments_fmt, args_fmt) == 0)
          {
            result = function->prototypes[i].code(
                (void*) args,
                context,
                function);

            break;
          }
        }

        assert(i < MAX_OVERLOADED_FUNCTIONS);

        if (result == ERROR_SUCCESS)
        {
          r1.o = function->return_obj;
          push(r1);
        }
        else
        {
          stop = TRUE;
        }

        break;

      case OP_FOUND:
        pop(r1);
        r1.i = r1.s->matches[tidx].tail != NULL ? 1 : 0;
        push(r1);
        break;

      case OP_FOUND_AT:
        pop(r2);
        pop(r1);

        if (is_undef(r1))
        {
          r1.i = 0;
          push(r1);
          break;
        }

        match = r2.s->matches[tidx].head;
        r3.i = FALSE;

        while (match != NULL)
        {
          if (r1.i == match->base + match->offset)
          {
            r3.i = TRUE;
            break;
          }

          if (r1.i < match->base + match->offset)
            break;

          match = match->next;
        }

        push(r3);
        break;

      case OP_FOUND_IN:
        pop(r3);
        pop(r2);
        pop(r1);

        ensure_defined(r1);
        ensure_defined(r2);

        match = r3.s->matches[tidx].head;
        r3.i = FALSE;

        while (match != NULL && !r3.i)
        {
          if (match->base + match->offset >= r1.i &&
              match->base + match->offset <= r2.i)
          {
            r3.i = TRUE;
          }

          if (match->base + match->offset > r2.i)
            break;

          match = match->next;
        }

        push(r3);
        break;

      case OP_COUNT:
        pop(r1);
        r1.i = r1.s->matches[tidx].count;
        push(r1);
        break;

      case OP_OFFSET:
        pop(r2);
        pop(r1);

        ensure_defined(r1);

        match = r2.s->matches[tidx].head;
        i = 1;
        r3.i = UNDEFINED;

        while (match != NULL && r3.i == UNDEFINED)
        {
          if (r1.i == i)
            r3.i = match->base + match->offset;

          i++;
          match = match->next;
        }

        push(r3);
        break;

      case OP_LENGTH:
        pop(r2);
        pop(r1);

        ensure_defined(r1);

        match = r2.s->matches[tidx].head;
        i = 1;
        r3.i = UNDEFINED;

        while (match != NULL && r3.i == UNDEFINED)
        {
          if (r1.i == i)
            r3.i = match->length;

          i++;
          match = match->next;
        }

        push(r3);
        break;

      case OP_OF:
        found = 0;
        count = 0;
        pop(r1);

        while (!is_undef(r1))
        {
          if (r1.s->matches[tidx].tail != NULL)
            found++;
          count++;
          pop(r1);
        }

        pop(r2);

        if (is_undef(r2))
          r1.i = found >= count ? 1 : 0;
        else
          r1.i = found >= r2.i ? 1 : 0;

        push(r1);
        break;

      case OP_FILESIZE:
        r1.i = context->file_size;
        push(r1);
        break;

      case OP_ENTRYPOINT:
        r1.i = context->entry_point;
        push(r1);
        break;

      case OP_INT8:
        pop(r1);
        r1.i = read_int8_t_little_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_INT16:
        pop(r1);
        r1.i = read_int16_t_little_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_INT32:
        pop(r1);
        r1.i = read_int32_t_little_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_UINT8:
        pop(r1);
        r1.i = read_uint8_t_little_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_UINT16:
        pop(r1);
        r1.i = read_uint16_t_little_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_UINT32:
        pop(r1);
        r1.i = read_uint32_t_little_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_INT8BE:
        pop(r1);
        r1.i = read_int8_t_big_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_INT16BE:
        pop(r1);
        r1.i = read_int16_t_big_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_INT32BE:
        pop(r1);
        r1.i = read_int32_t_big_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_UINT8BE:
        pop(r1);
        r1.i = read_uint8_t_big_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_UINT16BE:
        pop(r1);
        r1.i = read_uint16_t_big_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_UINT32BE:
        pop(r1);
        r1.i = read_uint32_t_big_endian(context->mem_block, (size_t) r1.i);
        push(r1);
        break;

      case OP_CONTAINS:
        pop(r2);
        pop(r1);

        ensure_defined(r1);
        ensure_defined(r2);

        r1.i = memmem(r1.ss->c_string, r1.ss->length,
                      r2.ss->c_string, r2.ss->length) != NULL;
        push(r1);
        break;

      case OP_IMPORT:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);

        FAIL_ON_ERROR(yr_modules_load(
            (char*) r1.p,
            context));

        break;

      case OP_MATCHES:
        pop(r2);
        pop(r1);

        ensure_defined(r2);
        ensure_defined(r1);

        if (r1.ss->length == 0)
        {
          r1.i = FALSE;
          push(r1);
          break;
        }

        r1.i = yr_re_exec(
          (uint8_t*) r2.p,
          (uint8_t*) r1.ss->c_string,
          r1.ss->length,
          RE_FLAGS_SCAN,
          NULL,
          NULL) >= 0;

        push(r1);
        break;

      case OP_INT_TO_DBL:
        r1.i = *(uint64_t*)(ip + 1);
        ip += sizeof(uint64_t);
        r2 = stack[sp - r1.i];
        if (is_undef(r2))
          stack[sp - r1.i].i = UNDEFINED;
        else
          stack[sp - r1.i].d = (double) r2.i;
        break;

      case OP_STR_TO_BOOL:
        pop(r1);
        ensure_defined(r1);
        r1.i = r1.ss->length > 0;
        push(r1);
        break;

      case OP_INT_EQ:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i == r2.i;
        push(r1);
        break;

      case OP_INT_NEQ:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i != r2.i;
        push(r1);
        break;

      case OP_INT_LT:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i < r2.i;
        push(r1);
        break;

      case OP_INT_GT:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i > r2.i;
        push(r1);
        break;

      case OP_INT_LE:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i <= r2.i;
        push(r1);
        break;

      case OP_INT_GE:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i >= r2.i;
        push(r1);
        break;

      case OP_INT_ADD:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i + r2.i;
        push(r1);
        break;

      case OP_INT_SUB:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i - r2.i;
        push(r1);
        break;

      case OP_INT_MUL:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.i * r2.i;
        push(r1);
        break;

      case OP_INT_DIV:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        if (r2.i != 0)
          r1.i = r1.i / r2.i;
        else
          r1.i = UNDEFINED;
        push(r1);
        break;

      case OP_INT_MINUS:
        pop(r1);
        ensure_defined(r1);
        r1.i = -r1.i;
        push(r1);
        break;

      case OP_DBL_LT:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.d < r2.d;
        push(r1);
        break;

      case OP_DBL_GT:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.d > r2.d;
        push(r1);
        break;

      case OP_DBL_LE:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.d <= r2.d;
        push(r1);
        break;

      case OP_DBL_GE:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.d >= r2.d;
        push(r1);
        break;

      case OP_DBL_EQ:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.d == r2.d;
        push(r1);
        break;

      case OP_DBL_NEQ:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.i = r1.d != r2.d;
        push(r1);
        break;

      case OP_DBL_ADD:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.d = r1.d + r2.d;
        push(r1);
        break;

      case OP_DBL_SUB:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.d = r1.d - r2.d;
        push(r1);
        break;

      case OP_DBL_MUL:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.d = r1.d * r2.d;
        push(r1);
        break;

      case OP_DBL_DIV:
        pop(r2);
        pop(r1);
        ensure_defined(r2);
        ensure_defined(r1);
        r1.d = r1.d / r2.d;
        push(r1);
        break;

      case OP_DBL_MINUS:
        pop(r1);
        ensure_defined(r1);
        r1.d = -r1.d;
        push(r1);
        break;

      case OP_STR_EQ:
      case OP_STR_NEQ:
      case OP_STR_LT:
      case OP_STR_LE:
      case OP_STR_GT:
      case OP_STR_GE:

        pop(r2);
        pop(r1);

        ensure_defined(r1);
        ensure_defined(r2);

        switch(*ip)
        {
          case OP_STR_EQ:
            r1.i = (sized_string_cmp(r1.ss, r2.ss) == 0);
            break;
          case OP_STR_NEQ:
            r1.i = (sized_string_cmp(r1.ss, r2.ss) != 0);
            break;
          case OP_STR_LT:
            r1.i = (sized_string_cmp(r1.ss, r2.ss) < 0);
            break;
          case OP_STR_LE:
            r1.i = (sized_string_cmp(r1.ss, r2.ss) <= 0);
            break;
          case OP_STR_GT:
            r1.i = (sized_string_cmp(r1.ss, r2.ss) > 0);
            break;
          case OP_STR_GE:
            r1.i = (sized_string_cmp(r1.ss, r2.ss) >= 0);
            break;
        }

        push(r1);
        break;

      default:
        // Unknown instruction, this shouldn't happen.
        assert(FALSE);
    }

    if (timeout > 0)  // timeout == 0 means no timeout
    {
      // Check for timeout every 10 instruction cycles.

      if (++cycle == 10)
      {
        if (difftime(time(NULL), start_time) > timeout)
        {
          #ifdef PROFILING_ENABLED
          assert(current_rule != NULL);
          current_rule->clock_ticks += clock() - start;
          #endif
          result = ERROR_SCAN_TIMEOUT;
          stop = TRUE;
        }

        cycle = 0;
      }
    }

    ip++;
  }

  yr_free(stack);
  return result;
}
Пример #10
0
/* convert a struct value to a string */
char *
value_to_str(struct value *val, TBOOLEAN need_quotes)
{
    static int i = 0;
    static char * s[4] = {NULL, NULL, NULL, NULL};
    static size_t c[4] = {0, 0, 0, 0};
    static const int minbufsize = 54;
    int j = i;

    i = (i + 1) % 4;
    if (s[j] == NULL) {
	s[j] = (char *) gp_alloc(minbufsize, "value_to_str");
	c[j] = minbufsize;
    }

    switch (val->type) {
    case INTGR:
	sprintf(s[j], "%d", val->v.int_val);
	break;
    case CMPLX:
	if (isnan(val->v.cmplx_val.real))
	    sprintf(s[j], "NaN");
	else if (val->v.cmplx_val.imag != 0.0)
	    sprintf(s[j], "{%s, %s}",
	            num_to_str(val->v.cmplx_val.real),
	            num_to_str(val->v.cmplx_val.imag));
	else
	    return num_to_str(val->v.cmplx_val.real);
	break;
    case STRING:
	if (val->v.string_val) {
	    if (!need_quotes) {
		return val->v.string_val;
	    } else {
		char * cstr = conv_text(val->v.string_val);
		size_t reqsize = strlen(cstr) + 3;
		if (reqsize > c[j]) {
		    /* Don't leave c[j[ non-zero if realloc fails */
		    s[j] = (char *) gp_realloc(s[j], reqsize + 20, NULL);
		    if (s[j] != NULL) {
			c[j] = reqsize + 20;
		    } else {
			c[j] = 0;
			int_error(NO_CARET, "out of memory");
		    }
		}
		sprintf(s[j], "\"%s\"", cstr);
	    }
	} else {
	    s[j][0] = NUL;
	}
	break;
    case DATABLOCK:
	{
	char **dataline = val->v.data_array;
	int nlines = 0;
	if (dataline != NULL) {
	    while (*dataline++ != NULL)
		nlines++;
	}
	sprintf(s[j], "<%d line data block>", nlines);
	break;
	}
    case ARRAY:
	{
	sprintf(s[j], "<%d element array>", val->v.value_array->v.int_val);
	break;
	}
    case NOTDEFINED:
	{
	sprintf(s[j], "<undefined>");
	break;
	}
    default:
	int_error(NO_CARET, "unknown type in value_to_str()");
    }

    return s[j];
}
Пример #11
0
int
main(int argc, char * const *argv)
{
	const char *T_arg = NULL;
	const char *S_arg = NULL;
	const char *n_arg = NULL;
	int opt, sock;

	/*
	 * By default linux::getopt(3) mangles the argv order, such that
	 *	varnishadm -n bla param.set foo -bar
	 * gets interpreted as
	 *	varnishadm -n bla -bar param.set foo
	 * The '+' stops that from happening
	 * See #1496
	 */
	while ((opt = getopt(argc, argv, "+n:S:T:t:")) != -1) {
		switch (opt) {
		case 'n':
			n_arg = optarg;
			break;
		case 'S':
			S_arg = optarg;
			break;
		case 'T':
			T_arg = optarg;
			break;
		case 't':
			timeout = VNUM(optarg);
			if (isnan(timeout))
				usage();
			break;
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;

	if (n_arg != NULL) {
		if (T_arg != NULL || S_arg != NULL) {
			usage();
		}
		sock = n_arg_sock(n_arg);
	} else if (T_arg == NULL) {
		sock = n_arg_sock("");
	} else {
		assert(T_arg != NULL);
		sock = cli_sock(T_arg, S_arg);
	}
	if (sock < 0)
		exit(2);

	if (argc > 0)
		do_args(sock, argc, argv);
	else {
		if (isatty(0)) {
			interactive(sock);
		} else {
			pass(sock);
		}
	}
	exit(0);
}
Пример #12
0
int handle_getthreshold (FILE *fh, char *buffer)
{
  char *command;
  char *identifier;
  char *identifier_copy;

  char *host;
  char *plugin;
  char *plugin_instance;
  char *type;
  char *type_instance;

  threshold_t threshold;

  int   status;
  size_t i;

  if ((fh == NULL) || (buffer == NULL))
    return (-1);

  DEBUG ("utils_cmd_getthreshold: handle_getthreshold (fh = %p, buffer = %s);",
      (void *) fh, buffer);

  command = NULL;
  status = parse_string (&buffer, &command);
  if (status != 0)
  {
    print_to_socket (fh, "-1 Cannot parse command.\n");
    return (-1);
  }
  assert (command != NULL);

  if (strcasecmp ("GETTHRESHOLD", command) != 0)
  {
    print_to_socket (fh, "-1 Unexpected command: `%s'.\n", command);
    return (-1);
  }

  identifier = NULL;
  status = parse_string (&buffer, &identifier);
  if (status != 0)
  {
    print_to_socket (fh, "-1 Cannot parse identifier.\n");
    return (-1);
  }
  assert (identifier != NULL);

  if (*buffer != 0)
  {
    print_to_socket (fh, "-1 Garbage after end of command: %s\n", buffer);
    return (-1);
  }

  /* parse_identifier() modifies its first argument,
   * returning pointers into it */
  identifier_copy = sstrdup (identifier);

  status = parse_identifier (identifier_copy, &host,
      &plugin, &plugin_instance,
      &type, &type_instance,
      /* default_host = */ NULL);
  if (status != 0)
  {
    DEBUG ("handle_getthreshold: Cannot parse identifier `%s'.", identifier);
    print_to_socket (fh, "-1 Cannot parse identifier `%s'.\n", identifier);
    sfree (identifier_copy);
    return (-1);
  }

  value_list_t vl = {
    .values = NULL
  };
  sstrncpy (vl.host, host, sizeof (vl.host));
  sstrncpy (vl.plugin, plugin, sizeof (vl.plugin));
  if (plugin_instance != NULL)
    sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
  sstrncpy (vl.type, type, sizeof (vl.type));
  if (type_instance != NULL)
    sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
  sfree (identifier_copy);

  status = ut_search_threshold (&vl, &threshold);
  if (status == ENOENT)
  {
    print_to_socket (fh, "-1 No threshold found for identifier %s\n",
        identifier);
    return (0);
  }
  else if (status != 0)
  {
    print_to_socket (fh, "-1 Error while looking up threshold: %i\n",
        status);
    return (-1);
  }

  /* Lets count the number of lines we'll return. */
  i = 0;
  if (threshold.host[0] != 0)            i++;
  if (threshold.plugin[0] != 0)          i++;
  if (threshold.plugin_instance[0] != 0) i++;
  if (threshold.type[0] != 0)            i++;
  if (threshold.type_instance[0] != 0)   i++;
  if (threshold.data_source[0] != 0)     i++;
  if (!isnan (threshold.warning_min))    i++;
  if (!isnan (threshold.warning_max))    i++;
  if (!isnan (threshold.failure_min))    i++;
  if (!isnan (threshold.failure_max))    i++;
  if (threshold.hysteresis > 0.0)        i++;
  if (threshold.hits > 1)                i++;

  /* Print the response */
  print_to_socket (fh, "%zu Threshold found\n", i);

  if (threshold.host[0] != 0)
    print_to_socket (fh, "Host: %s\n", threshold.host)
  if (threshold.plugin[0] != 0)
    print_to_socket (fh, "Plugin: %s\n", threshold.plugin)
  if (threshold.plugin_instance[0] != 0)
    print_to_socket (fh, "Plugin Instance: %s\n", threshold.plugin_instance)
  if (threshold.type[0] != 0)
    print_to_socket (fh, "Type: %s\n", threshold.type)
  if (threshold.type_instance[0] != 0)
    print_to_socket (fh, "Type Instance: %s\n", threshold.type_instance)
  if (threshold.data_source[0] != 0)
    print_to_socket (fh, "Data Source: %s\n", threshold.data_source)
  if (!isnan (threshold.warning_min))
    print_to_socket (fh, "Warning Min: %g\n", threshold.warning_min)
  if (!isnan (threshold.warning_max))
    print_to_socket (fh, "Warning Max: %g\n", threshold.warning_max)
  if (!isnan (threshold.failure_min))
    print_to_socket (fh, "Failure Min: %g\n", threshold.failure_min)
  if (!isnan (threshold.failure_max))
    print_to_socket (fh, "Failure Max: %g\n", threshold.failure_max)
  if (threshold.hysteresis > 0.0)
    print_to_socket (fh, "Hysteresis: %g\n", threshold.hysteresis)
  if (threshold.hits > 1)
    print_to_socket (fh, "Hits: %i\n", threshold.hits)

  return (0);
} /* int handle_getthreshold */
pose UpdateOptitrackStates(pose localROBOTps, int * flag) {

	pose localOPTITRACKps;

	// Check for frame errors / packet loss
	if (previous_frame == Optitrackdata[OPTITRACKDATASIZE-1]) {
		frame_error++;
	}
	previous_frame = Optitrackdata[OPTITRACKDATASIZE-1];

	// Set local trackableID if first receive data
	if (firstdata){
		//trackableID = (int)Optitrackdata[OPTITRACKDATASIZE-1]; // removed to add new trackableID in shared memory
		trackableID = Optitrackdata[OPTITRACKDATASIZE-2];
		firstdata = 0;
	}

	// Check if local trackableID has changed - should never happen
	if (trackableID != Optitrackdata[OPTITRACKDATASIZE-2]) {
		trackableIDerror++;
		// do some sort of reset(?)
	}

	// Save position and yaw data
	if (isnan(Optitrackdata[0]) != 1) {  // this checks if the position data being received contains NaNs
		// check if x,y,yaw all equal 0.0 (almost certainly means the robot is untracked)
		if ((Optitrackdata[0] != 0.0) && (Optitrackdata[1] != 0.0) && (Optitrackdata[2] != 0.0)) {
			// save x,y
			// adding 2.5 so everything is shifted such that optitrack's origin is the center of the arena (while keeping all coordinates positive)
			localOPTITRACKps.x = Optitrackdata[0]*FEETINONEMETER; // was 2.5 for size = 5
			localOPTITRACKps.y = -1.0*Optitrackdata[1]*FEETINONEMETER+4.0;

			// make this a function
			temp_theta = fmodf(localROBOTps.theta,(float)(2*PI));//(theta[trackableID]%(2*PI));
			tempOPTITRACK_theta = Optitrackdata[2];
			if (temp_theta > 0) {
				if (temp_theta < PI) {
					if (tempOPTITRACK_theta >= 0.0) {
						// THETA > 0, kal in QI/II, OT in QI/II
						localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI + tempOPTITRACK_theta*2*PI/360.0;
					} else {
						if (temp_theta > (PI/2)) {
							// THETA > 0, kal in QII, OT in QIII
							localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI + PI + (PI + tempOPTITRACK_theta*2*PI/360.0);
						} else {
							// THETA > 0, kal in QI, OT in QIV
							localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI + tempOPTITRACK_theta*2*PI/360.0;
						}
					}
				} else {
					if (tempOPTITRACK_theta <= 0.0) {
						// THETA > 0, kal in QIII, OT in QIII
						localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI + PI + (PI + tempOPTITRACK_theta*2*PI/360.0);
					} else {
						if (temp_theta > (3*PI/2)) {
							// THETA > 0, kal in QIV, OT in QI
							localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI + 2*PI + tempOPTITRACK_theta*2*PI/360.0;
						} else {
							// THETA > 0, kal in QIII, OT in QII
							localOPTITRACKps.theta = (floorf((localROBOTps.theta)/((float)(2.0*PI))))*2.0*PI + tempOPTITRACK_theta*2*PI/360.0;
						}
					}
				}
			} else {
				if (temp_theta > -PI) {
					if (tempOPTITRACK_theta <= 0.0) {
						// THETA < 0, kal in QIII/IV, OT in QIII/IV
						localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI + tempOPTITRACK_theta*2*PI/360.0;
					} else {
						if (temp_theta < (-PI/2)) {
							// THETA < 0, kal in QIII, OT in QII
							localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI - PI + (-PI + tempOPTITRACK_theta*2*PI/360.0);
						} else {
							// THETA < 0, kal in QIV, OT in QI
							localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI + tempOPTITRACK_theta*2*PI/360.0;
						}
					}
				} else {
					if (tempOPTITRACK_theta >= 0.0) {
						// THETA < 0, kal in QI/II, OT in QI/II
						localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI - PI + (-PI + tempOPTITRACK_theta*2*PI/360.0);
					} else {
						if (temp_theta < (-3*PI/2)) {
							// THETA < 0, kal in QI, OT in QIV
							localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI - 2*PI + tempOPTITRACK_theta*2*PI/360.0;
						} else {
							// THETA < 0, kal in QII, OT in QIII
							localOPTITRACKps.theta = ((int)((localROBOTps.theta)/(2*PI)))*2.0*PI + tempOPTITRACK_theta*2*PI/360.0;
						}
					}
				}
			}
			*flag = 1;
		}
	}
	return localOPTITRACKps;
}
Пример #14
0
void
SegPoints(PQP_REAL VEC[3], 
	  PQP_REAL X[3], PQP_REAL Y[3],             // closest points
          const PQP_REAL P[3], const PQP_REAL A[3], // seg 1 origin, vector
          const PQP_REAL Q[3], const PQP_REAL B[3]) // seg 2 origin, vector
{
  PQP_REAL T[3], A_dot_A, B_dot_B, A_dot_B, A_dot_T, B_dot_T;
  PQP_REAL TMP[3];

  VmV(T,Q,P);
  A_dot_A = VdotV(A,A);
  B_dot_B = VdotV(B,B);
  A_dot_B = VdotV(A,B);
  A_dot_T = VdotV(A,T);
  B_dot_T = VdotV(B,T);

  // t parameterizes ray P,A 
  // u parameterizes ray Q,B 

  PQP_REAL t,u;

  // compute t for the closest point on ray P,A to
  // ray Q,B

  PQP_REAL denom = A_dot_A*B_dot_B - A_dot_B*A_dot_B;

  t = (A_dot_T*B_dot_B - B_dot_T*A_dot_B) / denom;

  // clamp result so t is on the segment P,A

  if ((t < 0) || isnan(t)) t = 0; else if (t > 1) t = 1;

  // find u for point on ray Q,B closest to point at t

  u = (t*A_dot_B - B_dot_T) / B_dot_B;

  // if u is on segment Q,B, t and u correspond to 
  // closest points, otherwise, clamp u, recompute and
  // clamp t 

  if ((u <= 0) || isnan(u)) {

    VcV(Y, Q);

    t = A_dot_T / A_dot_A;

    if ((t <= 0) || isnan(t)) {
      VcV(X, P);
      VmV(VEC, Q, P);
    }
    else if (t >= 1) {
      VpV(X, P, A);
      VmV(VEC, Q, X);
    }
    else {
      VpVxS(X, P, A, t);
      VcrossV(TMP, T, A);
      VcrossV(VEC, A, TMP);
    }
  }
  else if (u >= 1) {

    VpV(Y, Q, B);

    t = (A_dot_B + A_dot_T) / A_dot_A;

    if ((t <= 0) || isnan(t)) {
      VcV(X, P);
      VmV(VEC, Y, P);
    }
    else if (t >= 1) {
      VpV(X, P, A);
      VmV(VEC, Y, X);
    }
    else {
      VpVxS(X, P, A, t);
      VmV(T, Y, P);
      VcrossV(TMP, T, A);
      VcrossV(VEC, A, TMP);
    }
  }
  else {

    VpVxS(Y, Q, B, u);

    if ((t <= 0) || isnan(t)) {
      VcV(X, P);
      VcrossV(TMP, T, B);
      VcrossV(VEC, B, TMP);
    }
    else if (t >= 1) {
      VpV(X, P, A);
      VmV(T, Q, X);
      VcrossV(TMP, T, B);
      VcrossV(VEC, B, TMP);
    }
    else {
      VpVxS(X, P, A, t);
      VcrossV(VEC, A, B);
      if (VdotV(VEC, T) < 0) {
        VxS(VEC, VEC, -1);
      }
    }
  }
}
Пример #15
0
DLLEXPORT long double complex
csqrtl(long double complex z)
{
	long double complex result;
	long double a, b;
	long double t;
	int scale;

	a = creall(z);
	b = cimagl(z);

	/* Handle special cases. */
	if (z == 0)
		return (CMPLXL(0, b));
	if (isinf(b))
		return (CMPLXL(INFINITY, b));
	if (isnan(a)) {
		t = (b - b) / (b - b);	/* raise invalid if b is not a NaN */
		return (CMPLXL(a, t));	/* return NaN + NaN i */
	}
	if (isinf(a)) {
		/*
		 * csqrt(inf + NaN i)  = inf +  NaN i
		 * csqrt(inf + y i)    = inf +  0 i
		 * csqrt(-inf + NaN i) = NaN +- inf i
		 * csqrt(-inf + y i)   = 0   +  inf i
		 */
		if (signbit(a))
			return (CMPLXL(fabsl(b - b), copysignl(a, b)));
		else
			return (CMPLXL(a, copysignl(b - b, b)));
	}
	/*
	 * The remaining special case (b is NaN) is handled just fine by
	 * the normal code path below.
	 */

	/* Scale to avoid overflow. */
	if (fabsl(a) >= THRESH || fabsl(b) >= THRESH) {
		a *= 0.25;
		b *= 0.25;
		scale = 1;
	} else {
		scale = 0;
	}

	/* Algorithm 312, CACM vol 10, Oct 1967. */
	if (a >= 0) {
		t = sqrtl((a + hypotl(a, b)) * 0.5);
		result = CMPLXL(t, b / (2 * t));
	} else {
		t = sqrtl((-a + hypotl(a, b)) * 0.5);
		result = CMPLXL(fabsl(b) / (2 * t), copysignl(t, b));
	}

	/* Rescale. */
	if (scale)
		return (result * 2);
	else
		return (result);
}
Пример #16
0
int main(int argc,char* argv[]) {
    if (argc < 3) {
        printf("%s target_point.txt label_point.txt\n",argv[0]);
        return 1;
    }

    FILE* target = fopen(argv[1],"r");
    if (!target) {
        printf("Cannot open %s\n",argv[1]);
        return 1;
    }
    FILE* label = fopen(argv[2],"r");
    if (!label) {
        printf("Cannot open %s\n",argv[2]);
        return 1;
    }
    char buffer[512];
    std::vector< std::vector<Coordinate> > target_box;
    std::vector< std::vector<Coordinate> > label_box;
    int numObjects;
    while (fgets(buffer,512,target)) {
        float x,y;
        int numMatch;
        char* c = buffer;
        int n = strtol(c,&c,10);
        numObjects = n/4;
        std::vector<Coordinate> box;
        for (int i=0; i<n; i++) {
            x = strtod(c,&c);
            y = strtod(c,&c);
            numMatch = strtol(c,&c,10);
            Coordinate p = {x,y};
            box.push_back(p);
            if (i%4==3) {
                target_box.push_back(box);
                box.clear();
            }
        }
    }
    while (fgets(buffer,512,label)) {
        float x,y;
        int numMatch;
        char* c = buffer;
        int n = strtol(c,&c,10);
        std::vector<Coordinate> box;
        if (n==0) {
            for (int i=0; i<numObjects; i++)
                label_box.push_back(box);
            continue;
        }
        for (int i=0; i<n; i++) {
            x = strtod(c,&c);
            y = strtod(c,&c);
            numMatch = strtol(c,&c,10);
            Coordinate p = {x,y};
            box.push_back(p);
            if (i%4==3) {
                label_box.push_back(box);
                box.clear();
            }
        }
    }

    float acc_avg=0,acc_stddev=0;
    float acc_min,acc_max;
    float prec_avg=0,prec_stddev=0;
    float prec_min,prec_max;
    float norm_acc=0;
    int count=0;
    for (size_t i=0; i<target_box.size(); i++) {
        if (label_box[i].size()==0)
            continue;
        float A1 = polygonArea(convexHull(target_box[i]));
        float A2 = polygonArea(convexHull(label_box[i]));
        float A3 = polygonArea(convexHull(polygonCombine(target_box[i],label_box[i])));
        float acc = isnan(A3) ? 0 : A3 > A1 + A2 ? 0 : (A1 + A2 - A3) / A2;
        float prec = isnan(A3) ? 0 : A3 > A1 + A2 ? 0 : (A1 + A2 - A3) / A1;
        if (acc > 1) acc = 1;
        if (prec > 1) prec = 1;
        norm_acc += acc > prec ? acc : prec;
        acc_avg += acc;
        acc_stddev += acc*acc;
        if (i==0 || acc < acc_min) acc_min = acc;
        if (i==0 || acc > acc_max) acc_max = acc;
        prec_avg += prec;
        prec_stddev += prec*prec;
        if (i==0 || prec < prec_min) prec_min = prec;
        if (i==0 || prec > prec_max) prec_max = prec;
        printf("Box %lu: %.2f %.2f %8.2f %.4f %.4f\n",i,A1,A2,A3,acc,prec);
        count++;
    }
    acc_avg /= count;
    acc_stddev = sqrt(acc_stddev/count - acc_avg*acc_avg);
    prec_avg /= count;
    prec_stddev = sqrt(prec_stddev/count - prec_avg*prec_avg);
    norm_acc /= count;
    printf("Accuracy Min %.4f Max %.4f Average %.4f +- %.4f Overlap\n",acc_min,acc_max,acc_avg,acc_stddev);
    printf("Precision Min %.4f Max %.4f Average %.4f +- %.4f Overlap\n",prec_min,prec_max,prec_avg,prec_stddev);
    printf("Normalized Accuracy %.4f\n",norm_acc);
    fclose(target);
    fclose(label);

}
Пример #17
0
int main(int argc, char *argv[]){
// INIT ARGS, REQUESTDOC //////////////////////////////////////////////////////////
	initargs(argc, argv);
	requestdoc(0);


// DECLARE VARIABLES //////////////////////////////////////////////////////////////
	int iz, ix, iy;
	int nz, nx, ny;
	char *filename;
	float *data;


// GET INPUT PARAMETERS ///////////////////////////////////////////////////////////
	if( !getparint("nz", &nz) ) err("No nz. Exiting.\n");
	if( !getparint("nx", &nx) ) err("No nx. Exiting.\n");
	if( !getparint("ny", &ny) ) err("No ny. Exiting.\n");
	//if( !getparfloat("dz", &dz) ) err("No dz. Exiting.\n");
	if(!getparstring("filename", &filename)) filename=NULL;
	

// ALLOCATE VARIABLES /////////////////////////////////////////////////////////////
	data = (float*)malloc(nz*nx*ny*sizeof(float));

	FILE *fp;
	fp = fopen(filename,"r");
	fread(data, nz*nx*ny, sizeof(float), fp);
	fclose(fp);

// FILL INITIAL VALUES ///////////////////////////////////////////////////////////


// TEST HEADER ///////////////////////////////////////////////////////////////////


// PROCESS DATA ///////////////////////////////////////////////////////////////
	float val;
	float max=0.0;
	for(iy=0; iy<ny; iy++){
		for(ix=0; ix<nx; ix++){
			for(iz=0; iz<nz; iz++){
				

				val = data[iy*nz*nx + ix*nz + iz];
				if(val>max) max = val;
				if( isinf(val)==1 ) printf("inf at iz,ix,iy = %d,%d,%d\n", iz, ix, iy);
				if( isnan(val)==1 ) printf("NaN at iz,ix,iy = %d,%d,%d\n", iz, ix, iy);

			}
		}
	}

	printf("max is %f\n", max);
	
// FREE VARIABLES /////////////////////////////////////////////////////////////
	free(data);
	
// END MAIN ///////////////////////////////////////////////////////////////////

	return 0;
}
Пример #18
0
QString SummaryMetrics::getAggregated(Context *context, QString name, const QList<SummaryMetrics> &results, const QStringList &filters, 
                                      bool filtered, bool useMetricUnits, bool nofmt)
{
    // get the metric details, so we can convert etc
    const RideMetric *metric = RideMetricFactory::instance().rideMetric(name);
    if (!metric) return QString("%1 unknown").arg(name);

    // what we will return
    double rvalue = 0;
    double rcount = 0; // using double to avoid rounding issues with int when dividing

    // loop through and aggregate
    foreach (SummaryMetrics rideMetrics, results) {

        // skip filtered rides
        if (filtered && !filters.contains(rideMetrics.getFileName())) continue;
        if (context->mainWindow->isfiltered && !context->mainWindow->filters.contains(rideMetrics.getFileName())) continue;

        // get this value
        double value = rideMetrics.getForSymbol(name);
        double count = rideMetrics.getForSymbol("workout_time"); // for averaging

        
        // check values are bounded, just in case
        if (isnan(value) || isinf(value)) value = 0;

        // imperial / metric conversion
        if (useMetricUnits == false) {
            value *= metric->conversion();
            value += metric->conversionSum();
        }

        switch (metric->type()) {
        case RideMetric::Total:
            rvalue += value;
            break;
        case RideMetric::Average:
            {
            // average should be calculated taking into account
            // the duration of the ride, otherwise high value but
            // short rides will skew the overall average
            rvalue += value*count;
            rcount += count;
            break;
            }
        case RideMetric::Peak:
            {
            if (value > rvalue) rvalue = value;
            break;
            }
        }
    }

    // now compute the average
    if (metric->type() == RideMetric::Average) {
        if (rcount) rvalue = rvalue / rcount;
    }


    // Format appropriately
    QString result;
    if (metric->units(useMetricUnits) == "seconds" ||
        metric->units(useMetricUnits) == tr("seconds")) {
        if (nofmt) result = QString("%1").arg(rvalue);
        else result = time_to_string(rvalue);

    } else result = QString("%1").arg(rvalue, 0, 'f', metric->precision());

    return result;
}
void MakeNtuple(const string inputFilename, const string outputFilename, Int_t Option)
{  
  gBenchmark->Start("WWTemplate");

  //*****************************************************************************************
  //Setup
  //*****************************************************************************************
  TFile *outputFile = new TFile(outputFilename.c_str(), "RECREATE");
  ElectronTree *eleTree = new ElectronTree;
  eleTree->CreateTree();
  eleTree->tree_->SetAutoFlush(0);

  UInt_t NElectronsFilled = 0;
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  TTree *eventTree=0;  
   
  // Data structures to store info from TTrees
  higgsana::TEventInfo *info    = new higgsana::TEventInfo();
  TClonesArray *electronArr = new TClonesArray("higgsana::TElectron");
  TClonesArray *muonArr = new TClonesArray("higgsana::TMuon");
  TClonesArray *jetArr = new TClonesArray("higgsana::TJet");
  TClonesArray *photonArr = new TClonesArray("higgsana::TPhoton");
  TClonesArray *pfcandidateArr = new TClonesArray("higgsana::TPFCandidate");
  
  //********************************************************
  // Good RunLumi Selection
  //********************************************************
  Bool_t hasJSON = kTRUE;
  mithep::RunLumiRangeMap rlrm;
  rlrm.AddJSONFile("/data/smurf/data/Winter11_4700ipb/auxiliar/hww.Full2011.json"); 
  rlrm.AddJSONFile("/data/blue/sixie/HZZ4l/auxiliar/2012/Cert_190456-196531_8TeV_PromptReco_Collisions12_JSON.txt");

  Int_t NEvents = 0;

  UInt_t DataEra = kDataEra_NONE;

  vector<string> inputfiles;
  if (inputFilename == "LIST") {
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-m10-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-pr-v4.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-a05-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-o03-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11b-del-pr-v1.FakeTriggerSkim.root");    
  } 
  else if (inputFilename == "2012Data") {
    inputfiles.push_back("/data/smurf/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r12a-del-pr-v1_FakeRateTriggerSkimmed.root");
    inputfiles.push_back("/data/smurf/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r12b-del-pr-v1_FakeRateTriggerSkimmed.root");
    DataEra = kDataEra_2012_MC;
  }
  else {
    inputfiles.push_back(inputFilename);
  }

  for (UInt_t f = 0; f < inputfiles.size(); ++f) {

    //********************************************************
    // Get Tree
    //********************************************************
    eventTree = getTreeFromFile(inputfiles[f].c_str(),"Events"); 
    TBranch *infoBr;
    TBranch *electronBr;
    TBranch *muonBr;
    TBranch *jetBr;
    TBranch *photonBr;
    TBranch *pfcandidateBr;


    //*****************************************************************************************
    //Loop over Data Tree
    //*****************************************************************************************
    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Info",       &info);      infoBr       = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("Electron", &electronArr); electronBr = eventTree->GetBranch("Electron");
    eventTree->SetBranchAddress("Muon", &muonArr);         muonBr = eventTree->GetBranch("Muon");
    eventTree->SetBranchAddress("Photon", &photonArr);     photonBr = eventTree->GetBranch("Photon");
    eventTree->SetBranchAddress("PFJet", &jetArr);         jetBr = eventTree->GetBranch("PFJet");
    eventTree->SetBranchAddress("PFCandidate", &pfcandidateArr); pfcandidateBr = eventTree->GetBranch("PFCandidate");

    cout << "InputFile " << inputfiles[f] << " --- Total Events : " << eventTree->GetEntries() << endl;
    for(UInt_t ientry=0; ientry < eventTree->GetEntries(); ientry++) {       	
      infoBr->GetEntry(ientry);
		
      if (ientry % 100000 == 0) cout << "Event " << ientry << endl;

      Double_t eventweight = info->eventweight;

      mithep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
      if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  // not certified run? Skip to next event...

      NEvents++;

      //********************************************************
      // Load the branches
      //********************************************************
      electronArr->Clear(); 
      muonArr->Clear(); 
      photonArr->Clear(); 
      jetArr->Clear(); 
      pfcandidateArr->Clear(); 
      electronBr->GetEntry(ientry);
      muonBr->GetEntry(ientry);
      photonBr->GetEntry(ientry);
      jetBr->GetEntry(ientry);
      pfcandidateBr->GetEntry(ientry);


      //********************************************************
      // Pileup Energy Density
      //********************************************************
      Double_t rhoEleIso = 0;
      UInt_t EleEAEra = 0;

      if (DataEra == kDataEra_2011_MC) {     
        if (!(isnan(info->RhoKt6PFJetsForIso25) || 
              isinf(info->RhoKt6PFJetsForIso25))) {
          rhoEleIso = info->RhoKt6PFJetsForIso25;
        }
        EleEAEra = kDataEra_2011_Data;
      } else if (DataEra == kDataEra_2012_MC) {
        if (!(isnan(info->RhoKt6PFJets) || 
              isinf(info->RhoKt6PFJets))) {
          rhoEleIso = info->RhoKt6PFJets;
        }
        EleEAEra = kDataEra_2012_Data;
      }

      //********************************************************
      // TcMet
      //********************************************************
      TVector3 pfMet;        
      if(info->pfMEx!=0 || info->pfMEy!=0) {       
        pfMet.SetXYZ(info->pfMEx, info->pfMEy, 0);
      }
      Double_t met = pfMet.Pt();

      Int_t NElectrons = electronArr->GetEntries();
 

      //********************************************************
      // Event Selection Cuts
      //********************************************************
      //veto events with more than 1 reco electron
      if (NElectrons > 1) continue;
      //met cut removed W events
      if (met > 20) continue;


      //******************************************************************************
      //loop over electrons 
      //******************************************************************************
      for(Int_t i=0; i<electronArr->GetEntries(); i++) {
        const higgsana::TElectron *ele = (higgsana::TElectron*)((*electronArr)[i]);
 

        //make cut on dz
        if (fabs(ele->dz) > 0.1) continue;

        //protect against pathologies
        if (TMath::IsNaN(ele->sigiPhiiPhi)) {
          cout << "Pathological SigmaIPhiIPhi : " 
               << info->runNum << " " << info->lumiSec << " " << info->evtNum << endl;
          continue;
        }
        
        //********************************************************
        //find leading jet in the event
        //********************************************************
        Double_t leadingJetPt = -1;
        //pass event selection     
        for(Int_t j=0; j<jetArr->GetEntries(); j++) {
          const higgsana::TJet *jet = (higgsana::TJet*)((*jetArr)[j]);        
          if (jet->pt > leadingJetPt &&
              higgsana::deltaR(jet->eta, jet->phi, ele->eta, ele->phi) > 1.0) {
            leadingJetPt = jet->pt;          
          }
        }
      
        //Fill These Electrons
        NElectronsFilled++;
        
        if (Option == 0) {
          FillElectronTree( eleTree, ele, pfcandidateArr, rhoEleIso, EleEAEra, 
                            info->nPV0, info->runNum, info->lumiSec, info->evtNum);
        } else if (Option == 1) {
          FillElectronTree( eleTree, ele, pfcandidateArr, rhoEleIso, kDataEra_NONE, 
                            info->nPV0, info->runNum, info->lumiSec, info->evtNum);
        }

      } //loop over electrons

    } //end loop over data  

    cout << "Total Electrons: " << NElectronsFilled << endl;

  } //end loop over files

  delete info;
  delete electronArr;
  delete muonArr;
  delete jetArr;


  cout << "Total Electrons: " << NElectronsFilled << endl;
  outputFile->Write();
  outputFile->Close();

  gBenchmark->Show("WWTemplate");       
} 
Пример #20
0
void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
    if (!(isIntrinsic && isProjection)){
        return;
    }

    static Scan_points_dataset scan_points_dataset;
    static Image_points_dataset image_points_dataset;
    int i;

//    ROS_INFO("angle_min[%f]\nangle_max:[%f]\nangle_increment:[%f]\ntime_increment:[%f]\nscan_time:[%f]\nrange_min:[%f]\nrange_max:[%f]\n", msg->angle_min * 180 / 3.141592, msg->angle_max * 180 / 3.141592, msg->angle_increment * 180 / 3.141592, msg->time_increment, msg->scan_time, msg->range_min, msg->range_max);

    /*
     * Initialize
     */
    scan_points_dataset.scan_points.x.resize(msg->ranges.size());
    scan_points_dataset.scan_points.y.resize(msg->ranges.size());
    scan_points_dataset.scan_points.z.resize(msg->ranges.size());
    scan_points_dataset.intensity.resize(msg->intensities.size());
    image_points_dataset.image_points.x.clear();
    image_points_dataset.image_points.y.clear();
    image_points_dataset.distance.clear();
    image_points_dataset.intensity.clear();

    /*
     * Change to three dimentional coordinate. And copy intensity
     */
    for(i = 0; i < (int)msg->ranges.size(); i++) {
        scan_points_dataset.scan_points.x.at(i) = msg->ranges.at(i) * sin(msg->angle_min + msg->angle_increment * i); //unit of length is meter
        scan_points_dataset.scan_points.y.at(i) = 0; //unit of length is meter
        scan_points_dataset.scan_points.z.at(i) = msg->ranges.at(i) * cos(msg->angle_min + msg->angle_increment * i); //unit of length is meter
        if(!(msg->intensities.empty())){
            scan_points_dataset.intensity.at(i) = msg->intensities.at(i);
        }
    }

    /*
     * Change from laser range finder coordinate to image coordinate
     */
    trans_depth_points_to_image_points(&scan_points_dataset, &image_points_dataset);

    /*
     * Judge out of image frame. And Determine max_y and min_y
     */
    for (i = 0; i < (int)image_points_dataset.image_points.x.size(); i++) {
        /* Judge NaN */
        if(isnan(image_points_dataset.image_points.x.at(i)) == 1 || isnan(image_points_dataset.image_points.y.at(i)) == 1) {
            std::cout <<"Not a Number is i:" << i << std::endl;
            continue;
        }
        /* Judge out of X-axis image */
        if(0 > (int)image_points_dataset.image_points.x.at(i) || (int)image_points_dataset.image_points.x.at(i) > imageSize.width - 1) {
            continue;
        }
        /* Judge out of Y-axis image */
        if(0 > (int)image_points_dataset.image_points.y.at(i) || (int)image_points_dataset.image_points.y.at(i) > imageSize.height - 1) {
            continue;
        }

        scan_image.distance[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.distance.at(i);

        if(!msg->intensities.empty()){
            scan_image.intensity[(int)image_points_dataset.image_points.x.at(i) * imageSize.height + (int)image_points_dataset.image_points.y.at(i)] = image_points_dataset.intensity.at(i);
        }

        if ((scan_image.max_y < (int)image_points_dataset.image_points.y.at(i)) || (scan_image.max_y == NO_DATA)) {
            scan_image.max_y = (int)image_points_dataset.image_points.y.at(i);
        } else if ((scan_image.min_y > (int)image_points_dataset.image_points.y.at(i)) || (scan_image.min_y == NO_DATA)) {
            scan_image.min_y = (int)image_points_dataset.image_points.y.at(i);
        }
    }

    /*
     * Create message(Topic)
     */
    autoware_msgs::ScanImage scan_image_msg;
    scan_image_msg.header = msg->header;
    scan_image_msg.distance.assign(scan_image.distance, scan_image.distance + imageSize.width * imageSize.height);
    scan_image_msg.intensity.assign(scan_image.intensity, scan_image.intensity + imageSize.width * imageSize.height);
    scan_image_msg.max_y = scan_image.max_y;
    scan_image_msg.min_y = scan_image.min_y;

    /*
     * Publish message(Topic)
     */
    transformed_point_data.publish(scan_image_msg);

    /*
     * Init zero
     */
    std::fill_n(scan_image.distance, imageSize.width * imageSize.height,0);
    std::fill_n(scan_image.intensity, imageSize.width * imageSize.height,0);
    scan_image.max_y = NO_DATA;
    scan_image.min_y = NO_DATA;
}
Пример #21
0
// handle_qcn_trigger processes the trigger trickle, does the geoip or database lookup as appropriate, inserts into qcn_trigger
int handle_qcn_trigger(const DB_MSG_FROM_HOST* pmfh, const int iVariety, DB_QCN_HOST_IPADDR& qhip)
{
     // instantiate the objects
     DB_QCN_GEO_IPADDR  qgip;
     DB_QCN_TRIGGER     qtrig;
     
     char strIP[32]; // temp holder for IP address
     int iRetVal = 0;
     int iFollowUp = 0;
     bool bFollowUp = false;
     double dmxy[4], dmz[4];
     for (int i = 0; i < 4; i++) {
        dmxy[i] = 0.0;
        dmz[i] = 0.0;
     }

     // parse out all the data into the qtrig object;
       qtrig.mxy1p = 0.0;
       qtrig.mz1p = 0.0;
       qtrig.mxy1a = 0.0;
       qtrig.mz1a = 0.0;
       qtrig.mxy2a = 0.0;
       qtrig.mz2a = 0.0;
       qtrig.mxy4a = 0.0;
       qtrig.mz4a = 0.0;
     qtrig.hostid = pmfh->hostid; // don't parse hostid, it's in the msg_from_host struct!
     if (!parse_str(pmfh->xml, "<result_name>", qtrig.result_name, sizeof(qtrig.result_name))) memset(qtrig.result_name, 0x00, sizeof(qtrig.result_name));
     if (!parse_str(pmfh->xml, "<vr>", qtrig.sw_version, sizeof(qtrig.sw_version))) memset(qtrig.sw_version, 0x00, sizeof(qtrig.sw_version));
     if (!parse_str(pmfh->xml, "<os>", qtrig.os_type, sizeof(qtrig.os_type))) memset(qtrig.os_type, 0x00, sizeof(qtrig.os_type));
     parse_int(pmfh->xml, "<sms>", qtrig.qcn_sensorid);
     parse_int(pmfh->xml, "<reset>", qtrig.numreset);
     parse_double(pmfh->xml, "<dt>", qtrig.dt);
     parse_double(pmfh->xml, "<tsync>", qtrig.time_sync);
     parse_double(pmfh->xml, "<toff>", qtrig.sync_offset);
     parse_double(pmfh->xml, "<wct>", qtrig.runtime_clock);
     parse_double(pmfh->xml, "<cpt>", qtrig.runtime_cpu);
     if (!parse_str(pmfh->xml, "<extip>", strIP, 32)) memset(strIP, 0x00, sizeof(char) * 32);
     parse_double(pmfh->xml, "<ctime>", qtrig.time_trigger);
     if (isnan(qtrig.time_trigger)) qtrig.time_trigger= 0;
     // check for follow up info
     if (!parse_int(pmfh->xml, "<follow>", iFollowUp)) iFollowUp = 0;
     bFollowUp = (bool) (iFollowUp == 1);  // must be exactly 1 else error

     // check for followup info if any, i.e. 1 sec prev, 1 sec after 2 sec after 4 sec after data for xy component & z component
     // all normal triggers will possibly have the 1 sec prev values
     if (!parse_double(pmfh->xml, "<mxy1p>", dmxy[0])) dmxy[0] = 0;     
     if (!parse_double(pmfh->xml, "<mz1p>", dmz[0])) dmz[0] = 0;     

     if (bFollowUp) {  // only followup triggers will have the 4 sec after values
       if (!parse_double(pmfh->xml, "<mxy1a>", dmxy[1])) dmxy[1] = 0;
       if (!parse_double(pmfh->xml, "<mz1a>", dmz[1])) dmz[1] = 0;
  
       if (!parse_double(pmfh->xml, "<mxy2a>", dmxy[2])) dmxy[2] = 0;
       if (!parse_double(pmfh->xml, "<mz2a>", dmz[2])) dmz[2] = 0;

       if (!parse_double(pmfh->xml, "<mxy4a>", dmxy[3])) dmxy[3] = 0;
       if (!parse_double(pmfh->xml, "<mz4a>", dmz[3])) dmz[3] = 0;

       qtrig.mxy1p = dmxy[0];
       qtrig.mz1p = dmz[0];
       qtrig.mxy1a = dmxy[1];
       qtrig.mz1a = dmz[1];
       qtrig.mxy2a = dmxy[2];
       qtrig.mz2a = dmz[2];
       qtrig.mxy4a = dmxy[3];
       qtrig.mz4a = dmz[3];
     }

// CMC hack - change JW 7 to 100, MN 8 to 101
/*
     switch(qtrig.qcn_sensorid) {
        case 7:
           qtrig.qcn_sensorid = 100;
           break;
        case 8:
           qtrig.qcn_sensorid = 101;
           break;
      }
*/

     qtrig.flag = 0;
     qtrig.time_received = dtime();  // mark current server time as time_received, this gets overridden by database unix_timestamp() in qcn_trigger.h db_print

     if (!parse_str(pmfh->xml, "<file>", qtrig.file, sizeof(qtrig.file))) memset(qtrig.file, 0x00, sizeof(qtrig.file));
     if (iVariety) {
       if (qtrig.time_trigger < 1.0f) qtrig.time_trigger = qtrig.time_received; // sometimes trigtime/<ctime> is sent, older versions it wasn't
       qtrig.significance = 0;  // blank out sig/mag for not normal (variety!=0) triggers
       qtrig.magnitude = 0;
       if (iVariety != 2) strcpy(qtrig.file,"");   // no filename if not continual or normal trigger
       qtrig.varietyid = iVariety;
     }
     else {
       if (!parse_double(pmfh->xml, "<fsig>", qtrig.significance)) qtrig.significance = 0;;
       if (!parse_double(pmfh->xml, "<fmag>", qtrig.magnitude)) qtrig.magnitude = 0;
       qtrig.varietyid = 0;
       if (isnan(qtrig.significance)) qtrig.significance = 0;
       if (isnan(qtrig.magnitude)) qtrig.magnitude = 0;

       // fudge database hack - if normal trigger - check for continual trigger amongst the real trig if sw version < 5.47
       if ( atof(qtrig.sw_version) < 5.47f && strstr(qtrig.result_name, "continual_") ) {
          qtrig.significance = 0.0f;  // blank out sig/mag for not normal (variety!=0) triggers
          qtrig.magnitude = 0.0f;
          qtrig.varietyid = 2;
       }

     }


     /*
       // so at this point, for qtrig we lack:
       latitude       double       YES        NULL            
       longitude      double       YES        NULL            
       levelvalue     float        YES        NULL            
       levelid        smallint     YES        NULL            
       alignid
       ipaddr         varchar(32)
       received_file qcn_quakeid should be null
     */

     // eventid & qcn_quakeid will be used later, 
     // in case we want to tie in some USGS or QCN or other event id to this trigger
     qtrig.qcn_quakeid   = 0;
     qtrig.received_file = 0;
     qtrig.levelvalue = 0;
     qtrig.levelid    = 0;
     qtrig.alignid = 0;

     // so it's really latitude, longitude, levelvalue, levelid and ipaddr left to add to qcn_trigger object & database table

     // let's get the proper ipaddr form
     // don't forget we only "count" the first three bytes of an IP address, so process strIP for qtrig.ipaddr...
     qcn_process_ipaddr(strIP, 32);
     memset(qtrig.ipaddr, 0x00, 32);
     strncpy(qtrig.ipaddr, strIP, 31);

     // at this point, if a followup trigger, we can jsut update the memory table qcn_trigger_memory and split
     if (bFollowUp) {
       doTriggerMemoryUpdate(qtrig, dmxy, dmz); // update the qcn_trigger table with followup data
       return 0;
     }

     // OK, now just the lat/lng lookup
     // the first step will be to search into qcn_host_ipaddr to see if this exists already, sorted by geoip so user setting will be preferred
     
     qhip.hostid = qtrig.hostid; // important -- copy over ipaddr & hostid into other structs
     strcpy(qhip.ipaddr, qtrig.ipaddr);
     strcpy(qgip.ipaddr, qtrig.ipaddr);

     log_messages.printf(
           SCHED_MSG_LOG::MSG_DEBUG,
           "[QCN] [HOST#%d] [RESULTNAME=%s] [TIME=%lf] Processing QCN %s trickle message from IP %s\n",
           qtrig.hostid, qtrig.result_name, qtrig.time_received, 
              iVariety ? (iVariety==1 ? "ping" : "continual") : "trigger", qtrig.ipaddr
     );

     iRetVal = qcn_doTriggerHostLookup(qhip, qgip, qtrig, dmxy, dmz);

     // at this point we've inserted the appropriate records or had a database error, 
     // so return with iRetVal (0=good, otherwise a database error which will "nak" so the trigger will be resent)
     return iRetVal; // returns qhip.lookup error if there was a database error, so trigger won't be "ack'd" and will try again
}
Пример #22
0
AL_API ALvoid AL_APIENTRY alEffectfv(ALuint effect, ALenum param, ALfloat *pflValues)
{
    ALCcontext *Context;
    ALCdevice  *Device;
    ALeffect   *ALEffect;

    Context = GetContextSuspended();
    if(!Context) return;

    Device = Context->Device;
    if((ALEffect=LookupEffect(Device->EffectMap, effect)) != NULL)
    {
        if(ALEffect->type == AL_EFFECT_EAXREVERB)
        {
            switch(param)
            {
            case AL_EAXREVERB_DENSITY:
            case AL_EAXREVERB_DIFFUSION:
            case AL_EAXREVERB_GAIN:
            case AL_EAXREVERB_GAINHF:
            case AL_EAXREVERB_GAINLF:
            case AL_EAXREVERB_DECAY_TIME:
            case AL_EAXREVERB_DECAY_HFRATIO:
            case AL_EAXREVERB_DECAY_LFRATIO:
            case AL_EAXREVERB_REFLECTIONS_GAIN:
            case AL_EAXREVERB_REFLECTIONS_DELAY:
            case AL_EAXREVERB_LATE_REVERB_GAIN:
            case AL_EAXREVERB_LATE_REVERB_DELAY:
            case AL_EAXREVERB_AIR_ABSORPTION_GAINHF:
            case AL_EAXREVERB_ECHO_TIME:
            case AL_EAXREVERB_ECHO_DEPTH:
            case AL_EAXREVERB_MODULATION_TIME:
            case AL_EAXREVERB_MODULATION_DEPTH:
            case AL_EAXREVERB_HFREFERENCE:
            case AL_EAXREVERB_LFREFERENCE:
            case AL_EAXREVERB_ROOM_ROLLOFF_FACTOR:
                alEffectf(effect, param, pflValues[0]);
                break;

            case AL_EAXREVERB_REFLECTIONS_PAN:
                if(!isnan(pflValues[0]) && !isnan(pflValues[1]) && !isnan(pflValues[2]))
                {
                    ALEffect->Reverb.ReflectionsPan[0] = pflValues[0];
                    ALEffect->Reverb.ReflectionsPan[1] = pflValues[1];
                    ALEffect->Reverb.ReflectionsPan[2] = pflValues[2];
                }
                else
                    alSetError(Context, AL_INVALID_VALUE);
                break;
            case AL_EAXREVERB_LATE_REVERB_PAN:
                if(!isnan(pflValues[0]) && !isnan(pflValues[1]) && !isnan(pflValues[2]))
                {
                    ALEffect->Reverb.LateReverbPan[0] = pflValues[0];
                    ALEffect->Reverb.LateReverbPan[1] = pflValues[1];
                    ALEffect->Reverb.LateReverbPan[2] = pflValues[2];
                }
                else
                    alSetError(Context, AL_INVALID_VALUE);
                break;

            default:
                alSetError(Context, AL_INVALID_ENUM);
                break;
            }
        }
        else if(ALEffect->type == AL_EFFECT_REVERB)
        {
            switch(param)
            {
            case AL_REVERB_DENSITY:
            case AL_REVERB_DIFFUSION:
            case AL_REVERB_GAIN:
            case AL_REVERB_GAINHF:
            case AL_REVERB_DECAY_TIME:
            case AL_REVERB_DECAY_HFRATIO:
            case AL_REVERB_REFLECTIONS_GAIN:
            case AL_REVERB_REFLECTIONS_DELAY:
            case AL_REVERB_LATE_REVERB_GAIN:
            case AL_REVERB_LATE_REVERB_DELAY:
            case AL_REVERB_AIR_ABSORPTION_GAINHF:
            case AL_REVERB_ROOM_ROLLOFF_FACTOR:
                alEffectf(effect, param, pflValues[0]);
                break;

            default:
                alSetError(Context, AL_INVALID_ENUM);
                break;
            }
        }
        else if(ALEffect->type == AL_EFFECT_ECHO)
        {
            switch(param)
            {
            case AL_ECHO_DELAY:
            case AL_ECHO_LRDELAY:
            case AL_ECHO_DAMPING:
            case AL_ECHO_FEEDBACK:
            case AL_ECHO_SPREAD:
                alEffectf(effect, param, pflValues[0]);
                break;

            default:
                alSetError(Context, AL_INVALID_ENUM);
                break;
            }
        }
        else if(ALEffect->type == AL_EFFECT_RING_MODULATOR)
        {
            switch(param)
            {
            case AL_RING_MODULATOR_FREQUENCY:
            case AL_RING_MODULATOR_HIGHPASS_CUTOFF:
                alEffectf(effect, param, pflValues[0]);
                break;

            default:
                alSetError(Context, AL_INVALID_ENUM);
                break;
            }
        }
        else
            alSetError(Context, AL_INVALID_ENUM);
    }
    else
        alSetError(Context, AL_INVALID_NAME);

    ProcessContext(Context);
}
Пример #23
0
inline static void gui_display(crypto_t *c, gtk_widgets_t *data)
{
	cli_bps_t bps[BPS];
	memset(bps, 0x00, BPS * sizeof( cli_bps_t ));
	int b = 0;

	while (c->status == STATUS_INIT || c->status == STATUS_RUNNING)
	{
		gtk_main_iteration_do(FALSE);

#ifndef _WIN32
		struct timespec s = { 0, MILLION };
		nanosleep(&s, NULL);
#else
		Sleep(1);
#endif

		if (c->status == STATUS_INIT)
			continue;

		double pc = (PERCENT * c->total.offset + PERCENT * c->current.offset / c->current.size) / c->total.size;
		if (c->total.offset == c->total.size)
			pc = PERCENT * c->total.offset / c->total.size;
		set_progress_bar((GtkProgressBar *)data->progress_bar_total, pc);

		if (c->total.size == 1)
			gtk_widget_hide(data->progress_bar_current);
		else
			set_progress_bar((GtkProgressBar *)data->progress_bar_current, PERCENT * c->current.offset / c->current.size);

		struct timeval tv;
		gettimeofday(&tv, NULL);
		bps[b].time = tv.tv_sec * MILLION + tv.tv_usec;
		bps[b].bytes = c->current.offset;
		double val = cli_calc_bps(bps);
		b++;
		if (b >= BPS)
			b = 0;

		char *bps_label = NULL;
		if (isnan(val) || val == 0.0f)
			asprintf(&bps_label, "---.- B/s");
		else
		{
			if (val < THOUSAND)
				asprintf(&bps_label, "%5.1f B/s", val);
			else if (val < MILLION)
				asprintf(&bps_label, "%5.1f KB/s", val / KILOBYTE);
			else if (val < THOUSAND_MILLION)
				asprintf(&bps_label, "%5.1f MB/s", val / MEGABYTE);
			else if (val < BILLION)
				asprintf(&bps_label, "%5.1f GB/s", val / GIGABYTE);
			else
				asprintf(&bps_label, "---.- B/s");
				//asprintf(&bps_label, "%5.1f TB/s", val / TERABYTE);
		}
		gtk_label_set_text((GtkLabel *)data->progress_label, bps_label);
		free(bps_label);
	}

	return;
}
Пример #24
0
void EEPROM::readDataFromEEPROM()
{
#if EEPROM_MODE != 0
    uint8_t version = HAL::eprGetByte(EPR_VERSION); // This is the saved version. Don't copy data not set in older versions!
    baudrate = HAL::eprGetInt32(EPR_BAUDRATE);
    maxInactiveTime = HAL::eprGetInt32(EPR_MAX_INACTIVE_TIME);
    stepperInactiveTime = HAL::eprGetInt32(EPR_STEPPER_INACTIVE_TIME);
//#define EPR_ACCELERATION_TYPE 1
    Printer::axisStepsPerMM[X_AXIS] = HAL::eprGetFloat(EPR_XAXIS_STEPS_PER_MM);
    Printer::axisStepsPerMM[Y_AXIS] = HAL::eprGetFloat(EPR_YAXIS_STEPS_PER_MM);
    Printer::axisStepsPerMM[Z_AXIS] = HAL::eprGetFloat(EPR_ZAXIS_STEPS_PER_MM);
    Printer::maxFeedrate[X_AXIS] = HAL::eprGetFloat(EPR_X_MAX_FEEDRATE);
    Printer::maxFeedrate[Y_AXIS] = HAL::eprGetFloat(EPR_Y_MAX_FEEDRATE);
    Printer::maxFeedrate[Z_AXIS] = HAL::eprGetFloat(EPR_Z_MAX_FEEDRATE);
    Printer::homingFeedrate[X_AXIS] = HAL::eprGetFloat(EPR_X_HOMING_FEEDRATE);
    Printer::homingFeedrate[Y_AXIS] = HAL::eprGetFloat(EPR_Y_HOMING_FEEDRATE);
    Printer::homingFeedrate[Z_AXIS] = HAL::eprGetFloat(EPR_Z_HOMING_FEEDRATE);
    Printer::maxJerk = HAL::eprGetFloat(EPR_MAX_JERK);
#if DRIVE_SYSTEM!=DELTA
    Printer::maxZJerk = HAL::eprGetFloat(EPR_MAX_ZJERK);
#endif
#if RAMP_ACCELERATION
    Printer::maxAccelerationMMPerSquareSecond[X_AXIS] = HAL::eprGetFloat(EPR_X_MAX_ACCEL);
    Printer::maxAccelerationMMPerSquareSecond[Y_AXIS] = HAL::eprGetFloat(EPR_Y_MAX_ACCEL);
    Printer::maxAccelerationMMPerSquareSecond[Z_AXIS] = HAL::eprGetFloat(EPR_Z_MAX_ACCEL);
    Printer::maxTravelAccelerationMMPerSquareSecond[X_AXIS] = HAL::eprGetFloat(EPR_X_MAX_TRAVEL_ACCEL);
    Printer::maxTravelAccelerationMMPerSquareSecond[Y_AXIS] = HAL::eprGetFloat(EPR_Y_MAX_TRAVEL_ACCEL);
    Printer::maxTravelAccelerationMMPerSquareSecond[Z_AXIS] = HAL::eprGetFloat(EPR_Z_MAX_TRAVEL_ACCEL);
#endif
#if HAVE_HEATED_BED
    heatedBedController.heatManager= HAL::eprGetByte(EPR_BED_HEAT_MANAGER);
#if TEMP_PID
    heatedBedController.pidDriveMax = HAL::eprGetByte(EPR_BED_DRIVE_MAX);
    heatedBedController.pidDriveMin = HAL::eprGetByte(EPR_BED_DRIVE_MIN);
    heatedBedController.pidPGain = HAL::eprGetFloat(EPR_BED_PID_PGAIN);
    heatedBedController.pidIGain = HAL::eprGetFloat(EPR_BED_PID_IGAIN);
    heatedBedController.pidDGain = HAL::eprGetFloat(EPR_BED_PID_DGAIN);
    heatedBedController.pidMax = HAL::eprGetByte(EPR_BED_PID_MAX);
#endif
#endif
    Printer::xMin = HAL::eprGetFloat(EPR_X_HOME_OFFSET);
    Printer::yMin = HAL::eprGetFloat(EPR_Y_HOME_OFFSET);
    Printer::zMin = HAL::eprGetFloat(EPR_Z_HOME_OFFSET);
    Printer::xLength = HAL::eprGetFloat(EPR_X_LENGTH);
    Printer::yLength = HAL::eprGetFloat(EPR_Y_LENGTH);
    Printer::zLength = HAL::eprGetFloat(EPR_Z_LENGTH);
#if NONLINEAR_SYSTEM
    Printer::radius0 = HAL::eprGetFloat(EPR_DELTA_HORIZONTAL_RADIUS);
#endif
	EEPROM::buselight=HAL::eprGetByte(EPR_LIGHT_ON);
	EEPROM::bkeeplighton=HAL::eprGetByte(EPR_KEEP_LIGHT_ON);
	UIDisplay::display_mode=HAL::eprGetByte(EPR_DISPLAY_MODE);
	//need to be sure a valid value is set
	if(!((UIDisplay::display_mode==ADVANCED_MODE)||(UIDisplay::display_mode==EASY_MODE)))UIDisplay::display_mode=ADVANCED_MODE;
	#if CASE_LIGHTS_PIN>=0
        WRITE(CASE_LIGHTS_PIN, byte(EEPROM::buselight));
	#endif // CASE_LIGHTS_PIN
#if defined(FIL_SENSOR1_PIN)
	EEPROM::busesensor=HAL::eprGetByte(EPR_FIL_SENSOR_ON);
#endif
#if defined(TOP_SENSOR_PIN)
	EEPROM::btopsensor=HAL::eprGetByte(EPR_TOP_SENSOR_ON);
#endif
#if FEATURE_BEEPER
	HAL::enablesound=HAL::eprGetByte(EPR_SOUND_ON);
#endif
#if UI_AUTOLIGHTOFF_AFTER >0
	EEPROM::timepowersaving = HAL::eprGetInt32(EPR_POWERSAVE_AFTER_TIME);
	//new value do reset time
	UIDisplay::ui_autolightoff_time=HAL::timeInMilliseconds()+EEPROM::timepowersaving;
#endif	
EEPROM::ftemp_ext_pla= HAL::eprGetFloat(EPR_TEMP_EXT_PLA);
EEPROM::ftemp_ext_abs= HAL::eprGetFloat(EPR_TEMP_EXT_ABS);
EEPROM::ftemp_bed_pla= HAL::eprGetFloat(EPR_TEMP_BED_PLA);
EEPROM::ftemp_bed_abs= HAL::eprGetFloat(EPR_TEMP_BED_ABS);
#if ENABLE_BACKLASH_COMPENSATION
    Printer::backlashX = HAL::eprGetFloat(EPR_BACKLASH_X);
    Printer::backlashY = HAL::eprGetFloat(EPR_BACKLASH_Y);
    Printer::backlashZ = HAL::eprGetFloat(EPR_BACKLASH_Z);
#endif
#if FEATURE_AUTOLEVEL
    if(version>2)
    {
        float sum = 0;
        for(uint8_t i=0; i<9; i++)
            Printer::autolevelTransformation[i] = HAL::eprGetFloat(EPR_AUTOLEVEL_MATRIX + (((int)i) << 2));
        if(isnan(Printer::autolevelTransformation[0]))   // a bug caused storage of matrix at the wrong place. Read from old position instead.
        {
            for(uint8_t i=0; i<9; i++)
                Printer::autolevelTransformation[i] = HAL::eprGetFloat((EPR_AUTOLEVEL_MATRIX + (int)i) << 2);
        }
        for(uint8_t i=0; i<9; i++)
        {
            if(isnan(Printer::autolevelTransformation[i]))
                sum += 10;
            else
                sum += RMath::sqr(Printer::autolevelTransformation[i]);
        }
        if(sum < 2.7 || sum > 3.3)
            Printer::resetTransformationMatrix(false);
        Printer::setAutolevelActive(HAL::eprGetByte(EPR_AUTOLEVEL_ACTIVE));
        Com::printArrayFLN(Com::tTransformationMatrix,Printer::autolevelTransformation,9,6);
    }
#endif
#if MIXING_EXTRUDER
    readMixingRatios();
#endif
    // now the extruder
    for(uint8_t i=0; i<NUM_EXTRUDER; i++)
    {
#if FEATURE_WATCHDOG
        HAL::pingWatchdog();
#endif // FEATURE_WATCHDOG

        int o=i*EEPROM_EXTRUDER_LENGTH+EEPROM_EXTRUDER_OFFSET;
        Extruder *e = &extruder[i];
        e->stepsPerMM = HAL::eprGetFloat(o+EPR_EXTRUDER_STEPS_PER_MM);
        e->maxFeedrate = HAL::eprGetFloat(o+EPR_EXTRUDER_MAX_FEEDRATE);
        e->maxStartFeedrate = HAL::eprGetFloat(o+EPR_EXTRUDER_MAX_START_FEEDRATE);
        e->maxAcceleration = HAL::eprGetFloat(o+EPR_EXTRUDER_MAX_ACCELERATION);
        e->tempControl.heatManager = HAL::eprGetByte(o+EPR_EXTRUDER_HEAT_MANAGER);
#if TEMP_PID
        e->tempControl.pidDriveMax = HAL::eprGetByte(o+EPR_EXTRUDER_DRIVE_MAX);
        e->tempControl.pidDriveMin = HAL::eprGetByte(o+EPR_EXTRUDER_DRIVE_MIN);
        e->tempControl.pidPGain = HAL::eprGetFloat(o+EPR_EXTRUDER_PID_PGAIN);
        e->tempControl.pidIGain = HAL::eprGetFloat(o+EPR_EXTRUDER_PID_IGAIN);
        e->tempControl.pidDGain = HAL::eprGetFloat(o+EPR_EXTRUDER_PID_DGAIN);
        e->tempControl.pidMax = HAL::eprGetByte(o+EPR_EXTRUDER_PID_MAX);
#endif
        e->xOffset = HAL::eprGetInt32(o+EPR_EXTRUDER_X_OFFSET);
        e->yOffset = HAL::eprGetInt32(o+EPR_EXTRUDER_Y_OFFSET);
        e->watchPeriod = HAL::eprGetInt16(o+EPR_EXTRUDER_WATCH_PERIOD);
#if RETRACT_DURING_HEATUP
        e->waitRetractTemperature = HAL::eprGetInt16(o+EPR_EXTRUDER_WAIT_RETRACT_TEMP);
        e->waitRetractUnits = HAL::eprGetInt16(o+EPR_EXTRUDER_WAIT_RETRACT_UNITS);
#endif
#if USE_ADVANCE
#if ENABLE_QUADRATIC_ADVANCE
        e->advanceK = HAL::eprGetFloat(o+EPR_EXTRUDER_ADVANCE_K);
#endif
        e->advanceL = HAL::eprGetFloat(o+EPR_EXTRUDER_ADVANCE_L);
#endif
        if(version>1)
            e->coolerSpeed = HAL::eprGetByte(o+EPR_EXTRUDER_COOLER_SPEED);
    }
    if(version!=EEPROM_PROTOCOL_VERSION)
    {
        Com::printInfoFLN(Com::tEPRProtocolChanged);
        if(version<3)
        {
            HAL::eprSetFloat(EPR_Z_PROBE_HEIGHT,Z_PROBE_HEIGHT);
            HAL::eprSetFloat(EPR_Z_PROBE_SPEED,Z_PROBE_SPEED);
            HAL::eprSetFloat(EPR_Z_PROBE_XY_SPEED,Z_PROBE_XY_SPEED);
            HAL::eprSetFloat(EPR_Z_PROBE_X_OFFSET,Z_PROBE_X_OFFSET);
            HAL::eprSetFloat(EPR_Z_PROBE_Y_OFFSET,Z_PROBE_Y_OFFSET);
            HAL::eprSetFloat(EPR_Z_PROBE_X1,Z_PROBE_X1);
            HAL::eprSetFloat(EPR_Z_PROBE_Y1,Z_PROBE_Y1);
            HAL::eprSetFloat(EPR_Z_PROBE_X2,Z_PROBE_X2);
            HAL::eprSetFloat(EPR_Z_PROBE_Y2,Z_PROBE_Y2);
            HAL::eprSetFloat(EPR_Z_PROBE_X3,Z_PROBE_X3);
            HAL::eprSetFloat(EPR_Z_PROBE_Y3,Z_PROBE_Y3);
            HAL::eprSetFloat(EPR_MANUAL_LEVEL_X1, MANUAL_LEVEL_X1);
			HAL::eprSetFloat(EPR_MANUAL_LEVEL_Y1, MANUAL_LEVEL_Y1);
			HAL::eprSetFloat(EPR_MANUAL_LEVEL_X2, MANUAL_LEVEL_X2);
			HAL::eprSetFloat(EPR_MANUAL_LEVEL_Y2, MANUAL_LEVEL_Y2);
			HAL::eprSetFloat(EPR_MANUAL_LEVEL_X3, MANUAL_LEVEL_X3);
			HAL::eprSetFloat(EPR_MANUAL_LEVEL_Y3, MANUAL_LEVEL_Y3);
			HAL::eprSetFloat(EPR_MANUAL_LEVEL_X4, MANUAL_LEVEL_X4);
			HAL::eprSetFloat(EPR_MANUAL_LEVEL_Y4, MANUAL_LEVEL_Y4);
        }
        if(version<4)
        {
#if DRIVE_SYSTEM==DELTA
            HAL::eprSetFloat(EPR_DELTA_DIAGONAL_ROD_LENGTH,DELTA_DIAGONAL_ROD);
            HAL::eprSetFloat(EPR_DELTA_HORIZONTAL_RADIUS,ROD_RADIUS);
            HAL::eprSetInt16(EPR_DELTA_SEGMENTS_PER_SECOND_PRINT,DELTA_SEGMENTS_PER_SECOND_PRINT);
            HAL::eprSetInt16(EPR_DELTA_SEGMENTS_PER_SECOND_MOVE,DELTA_SEGMENTS_PER_SECOND_MOVE);
            HAL::eprSetInt16(EPR_DELTA_TOWERX_OFFSET_STEPS,DELTA_X_ENDSTOP_OFFSET_STEPS);
            HAL::eprSetInt16(EPR_DELTA_TOWERY_OFFSET_STEPS,DELTA_Y_ENDSTOP_OFFSET_STEPS);
            HAL::eprSetInt16(EPR_DELTA_TOWERZ_OFFSET_STEPS,DELTA_Z_ENDSTOP_OFFSET_STEPS);
#endif
        }
#if DRIVE_SYSTEM==DELTA
        if(version<5)
        {
            HAL::eprSetFloat(EPR_DELTA_ALPHA_A,DELTA_ALPHA_A);
            HAL::eprSetFloat(EPR_DELTA_ALPHA_B,DELTA_ALPHA_B);
            HAL::eprSetFloat(EPR_DELTA_ALPHA_C,DELTA_ALPHA_C);
        }
        if(version<6)
        {
            HAL::eprSetFloat(EPR_DELTA_RADIUS_CORR_A,DELTA_RADIUS_CORRECTION_A);
            HAL::eprSetFloat(EPR_DELTA_RADIUS_CORR_B,DELTA_RADIUS_CORRECTION_B);
            HAL::eprSetFloat(EPR_DELTA_RADIUS_CORR_C,DELTA_RADIUS_CORRECTION_C);
        }
        if(version<7)
        {
            HAL::eprSetFloat(EPR_DELTA_MAX_RADIUS,DELTA_MAX_RADIUS);
            HAL::eprSetFloat(EPR_DELTA_DIAGONAL_CORRECTION_A,DELTA_DIAGONAL_CORRECTION_A);
            HAL::eprSetFloat(EPR_DELTA_DIAGONAL_CORRECTION_B,DELTA_DIAGONAL_CORRECTION_B);
            HAL::eprSetFloat(EPR_DELTA_DIAGONAL_CORRECTION_C,DELTA_DIAGONAL_CORRECTION_C);
        }
#endif
        if(version<7)
        {
            HAL::eprSetFloat(EPR_Z_PROBE_BED_DISTANCE,Z_PROBE_BED_DISTANCE);
        }
        if(version < 9)
        {
#if MIXING_EXTRUDER
            storeMixingRatios(false);
#endif
        }
        if(version < 10) {
            HAL::eprSetFloat(EPR_AXISCOMP_TANXY,AXISCOMP_TANXY);
            HAL::eprSetFloat(EPR_AXISCOMP_TANYZ,AXISCOMP_TANYZ);
            HAL::eprSetFloat(EPR_AXISCOMP_TANXZ,AXISCOMP_TANXZ);
        }
        /*        if (version<8) {
        #if DRIVE_SYSTEM==DELTA
                  // Prior to verion 8, the cartesian max was stored in the zmax
                  // Now, x,y and z max are used for tower a, b anc c
                  // Of tower min are all set at 0, tower max is larger than cartesian max
                  // by the height of any tower for coordinate 0,0,0
                  long cart[Z_AXIS_ARRAY], delta[TOWER_ARRAY];
                  cart[X_AXIS] = cart[Y_AXIS] = cart[Z_AXIS] = 0;
                  transformCartesianStepsToDeltaSteps(cart, delta);
                  // We can only count on ZLENGTH being set correctly, as it was used for all towers
                  Printer::xLength = Printer::zLength + delta[X_AXIS];
                  Printer::yLength = Printer::zLength + delta[Y_AXIS];
                  Printer::zLength += delta[Z_AXIS];
        #endif
                }*/

        storeDataIntoEEPROM(false); // Store new fields for changed version
    }
    Printer::updateDerivedParameter();
    Extruder::initHeatedBed();
#endif
}
Пример #25
0
	double moj_relative_error(double expected, double result) { if (isnan(expected) || isinf(expected) || isnan(result) || isinf(result) || expected == 0) return 0; return fabs(result-expected) / fabs(expected); }
Пример #26
0
int
main(int argc, char *argv[])
{
	int r;

#ifdef ENABLE_NLS
	/* Init locale */
	setlocale(LC_CTYPE, "");
	setlocale(LC_MESSAGES, "");

	/* Internationalisation */
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
#endif

	/* Initialize settings to NULL values. */
	char *config_filepath = NULL;

	/* Settings for day, night and transition.
	   Initialized to indicate that the values are not set yet. */
	transition_scheme_t scheme =
		{ TRANSITION_HIGH, TRANSITION_LOW };

	scheme.day.temperature = -1;
	scheme.day.gamma[0] = NAN;
	scheme.day.brightness = NAN;

	scheme.night.temperature = -1;
	scheme.night.gamma[0] = NAN;
	scheme.night.brightness = NAN;

	/* Temperature for manual mode */
	int temp_set = -1;

	const gamma_method_t *method = NULL;
	char *method_args = NULL;

	const location_provider_t *provider = NULL;
	char *provider_args = NULL;

	int transition = -1;
	program_mode_t mode = PROGRAM_MODE_CONTINUAL;
	int verbose = 0;
	char *s;

	/* Flush messages consistently even if redirected to a pipe or
	   file.  Change the flush behaviour to line-buffered, without
	   changing the actual buffers being used. */
	setvbuf(stdout, NULL, _IOLBF, 0);
	setvbuf(stderr, NULL, _IOLBF, 0);

	/* Parse command line arguments. */
	int opt;
	while ((opt = getopt(argc, argv, "b:c:g:hl:m:oO:prt:vVx")) != -1) {
		switch (opt) {
		case 'b':
			parse_brightness_string(optarg,
						&scheme.day.brightness,
						&scheme.night.brightness);
			break;
		case 'c':
			free(config_filepath);
			config_filepath = strdup(optarg);
			break;
		case 'g':
			r = parse_gamma_string(optarg, scheme.day.gamma);
			if (r < 0) {
				fputs(_("Malformed gamma argument.\n"),
				      stderr);
				fputs(_("Try `-h' for more"
					" information.\n"), stderr);
				exit(EXIT_FAILURE);
			}

			/* Set night gamma to the same value as day gamma.
			   To set these to distinct values use the config
			   file. */
			memcpy(scheme.night.gamma, scheme.day.gamma,
			       sizeof(scheme.night.gamma));
			break;
		case 'h':
			print_help(argv[0]);
			exit(EXIT_SUCCESS);
			break;
		case 'l':
			/* Print list of providers if argument is `list' */
			if (strcasecmp(optarg, "list") == 0) {
				print_provider_list();
				exit(EXIT_SUCCESS);
			}

			char *provider_name = NULL;

			/* Don't save the result of strtof(); we simply want
			   to know if optarg can be parsed as a float. */
			errno = 0;
			char *end;
			strtof(optarg, &end);
			if (errno == 0 && *end == ':') {
				/* Use instead as arguments to `manual'. */
				provider_name = "manual";
				provider_args = optarg;
			} else {
				/* Split off provider arguments. */
				s = strchr(optarg, ':');
				if (s != NULL) {
					*(s++) = '\0';
					provider_args = s;
				}

				provider_name = optarg;
			}

			/* Lookup provider from name. */
			provider = find_location_provider(provider_name);
			if (provider == NULL) {
				fprintf(stderr, _("Unknown location provider"
						  " `%s'.\n"), provider_name);
				exit(EXIT_FAILURE);
			}

			/* Print provider help if arg is `help'. */
			if (provider_args != NULL &&
			    strcasecmp(provider_args, "help") == 0) {
				provider->print_help(stdout);
				exit(EXIT_SUCCESS);
			}
			break;
		case 'm':
			/* Print list of methods if argument is `list' */
			if (strcasecmp(optarg, "list") == 0) {
				print_method_list();
				exit(EXIT_SUCCESS);
			}

			/* Split off method arguments. */
			s = strchr(optarg, ':');
			if (s != NULL) {
				*(s++) = '\0';
				method_args = s;
			}

			/* Find adjustment method by name. */
			method = find_gamma_method(optarg);
			if (method == NULL) {
				/* TRANSLATORS: This refers to the method
				   used to adjust colors e.g VidMode */
				fprintf(stderr, _("Unknown adjustment method"
						  " `%s'.\n"), optarg);
				exit(EXIT_FAILURE);
			}

			/* Print method help if arg is `help'. */
			if (method_args != NULL &&
			    strcasecmp(method_args, "help") == 0) {
				method->print_help(stdout);
				exit(EXIT_SUCCESS);
			}
			break;
		case 'o':
			mode = PROGRAM_MODE_ONE_SHOT;
			break;
		case 'O':
			mode = PROGRAM_MODE_MANUAL;
			temp_set = atoi(optarg);
			break;
		case 'p':
			mode = PROGRAM_MODE_PRINT;
			break;
		case 'r':
			transition = 0;
			break;
		case 't':
			s = strchr(optarg, ':');
			if (s == NULL) {
				fputs(_("Malformed temperature argument.\n"),
				      stderr);
				fputs(_("Try `-h' for more information.\n"),
				      stderr);
				exit(EXIT_FAILURE);
			}
			*(s++) = '\0';
			scheme.day.temperature = atoi(optarg);
			scheme.night.temperature = atoi(s);
			break;
		case 'v':
			verbose = 1;
			break;
                case 'V':
                        printf("%s\n", PACKAGE_STRING);
                        exit(EXIT_SUCCESS);
                        break;
		case 'x':
			mode = PROGRAM_MODE_RESET;
			break;
		case '?':
			fputs(_("Try `-h' for more information.\n"), stderr);
			exit(EXIT_FAILURE);
			break;
		}
	}

	/* Load settings from config file. */
	config_ini_state_t config_state;
	r = config_ini_init(&config_state, config_filepath);
	if (r < 0) {
		fputs("Unable to load config file.\n", stderr);
		exit(EXIT_FAILURE);
	}

	free(config_filepath);

	/* Read global config settings. */
	config_ini_section_t *section = config_ini_get_section(&config_state,
							       "redshift");
	if (section != NULL) {
		config_ini_setting_t *setting = section->settings;
		while (setting != NULL) {
			if (strcasecmp(setting->name, "temp-day") == 0) {
				if (scheme.day.temperature < 0) {
					scheme.day.temperature =
						atoi(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "temp-night") == 0) {
				if (scheme.night.temperature < 0) {
					scheme.night.temperature =
						atoi(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "transition") == 0) {
				if (transition < 0) {
					transition = !!atoi(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "brightness") == 0) {
				if (isnan(scheme.day.brightness)) {
					scheme.day.brightness =
						atof(setting->value);
				}
				if (isnan(scheme.night.brightness)) {
					scheme.night.brightness =
						atof(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "brightness-day") == 0) {
				if (isnan(scheme.day.brightness)) {
					scheme.day.brightness =
						atof(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "brightness-night") == 0) {
				if (isnan(scheme.night.brightness)) {
					scheme.night.brightness =
						atof(setting->value);
				}
			} else if (strcasecmp(setting->name,
					      "elevation-high") == 0) {
				scheme.high = atof(setting->value);
			} else if (strcasecmp(setting->name,
					      "elevation-low") == 0) {
				scheme.low = atof(setting->value);
			} else if (strcasecmp(setting->name, "gamma") == 0) {
				if (isnan(scheme.day.gamma[0])) {
					r = parse_gamma_string(setting->value,
							       scheme.day.gamma);
					if (r < 0) {
						fputs(_("Malformed gamma"
							" setting.\n"),
						      stderr);
						exit(EXIT_FAILURE);
					}
					memcpy(scheme.night.gamma, scheme.day.gamma,
					       sizeof(scheme.night.gamma));
				}
			} else if (strcasecmp(setting->name, "gamma-day") == 0) {
				if (isnan(scheme.day.gamma[0])) {
					r = parse_gamma_string(setting->value,
							       scheme.day.gamma);
					if (r < 0) {
						fputs(_("Malformed gamma"
							" setting.\n"),
						      stderr);
						exit(EXIT_FAILURE);
					}
				}
			} else if (strcasecmp(setting->name, "gamma-night") == 0) {
				if (isnan(scheme.night.gamma[0])) {
					r = parse_gamma_string(setting->value,
							       scheme.night.gamma);
					if (r < 0) {
						fputs(_("Malformed gamma"
							" setting.\n"),
						      stderr);
						exit(EXIT_FAILURE);
					}
				}
			} else if (strcasecmp(setting->name,
					      "adjustment-method") == 0) {
				if (method == NULL) {
					method = find_gamma_method(
						setting->value);
					if (method == NULL) {
						fprintf(stderr, _("Unknown"
								  " adjustment"
								  " method"
								  " `%s'.\n"),
							setting->value);
						exit(EXIT_FAILURE);
					}
				}
			} else if (strcasecmp(setting->name,
					      "location-provider") == 0) {
				if (provider == NULL) {
					provider = find_location_provider(
						setting->value);
					if (provider == NULL) {
						fprintf(stderr, _("Unknown"
								  " location"
								  " provider"
								  " `%s'.\n"),
							setting->value);
						exit(EXIT_FAILURE);
					}
				}
			} else {
				fprintf(stderr, _("Unknown configuration"
						  " setting `%s'.\n"),
					setting->name);
			}
			setting = setting->next;
		}
	}

	/* Use default values for settings that were neither defined in
	   the config file nor on the command line. */
	if (scheme.day.temperature < 0) {
		scheme.day.temperature = DEFAULT_DAY_TEMP;
	}
	if (scheme.night.temperature < 0) {
		scheme.night.temperature = DEFAULT_NIGHT_TEMP;
	}

	if (isnan(scheme.day.brightness)) {
		scheme.day.brightness = DEFAULT_BRIGHTNESS;
	}
	if (isnan(scheme.night.brightness)) {
		scheme.night.brightness = DEFAULT_BRIGHTNESS;
	}

	if (isnan(scheme.day.gamma[0])) {
		scheme.day.gamma[0] = DEFAULT_GAMMA;
		scheme.day.gamma[1] = DEFAULT_GAMMA;
		scheme.day.gamma[2] = DEFAULT_GAMMA;
	}
	if (isnan(scheme.night.gamma[0])) {
		scheme.night.gamma[0] = DEFAULT_GAMMA;
		scheme.night.gamma[1] = DEFAULT_GAMMA;
		scheme.night.gamma[2] = DEFAULT_GAMMA;
	}

	if (transition < 0) transition = 1;

	location_t loc = { NAN, NAN };

	/* Initialize location provider. If provider is NULL
	   try all providers until one that works is found. */
	location_state_t location_state;

	/* Location is not needed for reset mode and manual mode. */
	if (mode != PROGRAM_MODE_RESET &&
	    mode != PROGRAM_MODE_MANUAL) {
		if (provider != NULL) {
			/* Use provider specified on command line. */
			r = provider_try_start(provider, &location_state,
					       &config_state, provider_args);
			if (r < 0) exit(EXIT_FAILURE);
		} else {
			/* Try all providers, use the first that works. */
			for (int i = 0;
			     location_providers[i].name != NULL; i++) {
				const location_provider_t *p =
					&location_providers[i];
				fprintf(stderr,
					_("Trying location provider `%s'...\n"),
					p->name);
				r = provider_try_start(p, &location_state,
						       &config_state, NULL);
				if (r < 0) {
					fputs(_("Trying next provider...\n"),
					      stderr);
					continue;
				}

				/* Found provider that works. */
				printf(_("Using provider `%s'.\n"), p->name);
				provider = p;
				break;
			}

			/* Failure if no providers were successful at this
			   point. */
			if (provider == NULL) {
				fputs(_("No more location providers"
					" to try.\n"), stderr);
				exit(EXIT_FAILURE);
			}
		}

		/* Get current location. */
		r = provider->get_location(&location_state, &loc);
		if (r < 0) {
		        fputs(_("Unable to get location from provider.\n"),
		              stderr);
		        exit(EXIT_FAILURE);
		}
	
		provider->free(&location_state);
	
		if (verbose) {
			print_location(&loc);

			printf(_("Temperatures: %dK at day, %dK at night\n"),
			       scheme.day.temperature,
			       scheme.night.temperature);

		        /* TRANSLATORS: Append degree symbols if possible. */
			printf(_("Solar elevations: day above %.1f, night below %.1f\n"),
			       scheme.high, scheme.low);
		}

		/* Latitude */
		if (loc.lat < MIN_LAT || loc.lat > MAX_LAT) {
		        /* TRANSLATORS: Append degree symbols if possible. */
		        fprintf(stderr,
		                _("Latitude must be between %.1f and %.1f.\n"),
		                MIN_LAT, MAX_LAT);
		        exit(EXIT_FAILURE);
		}
	
		/* Longitude */
		if (loc.lon < MIN_LON || loc.lon > MAX_LON) {
		        /* TRANSLATORS: Append degree symbols if possible. */
		        fprintf(stderr,
		                _("Longitude must be between"
		                  " %.1f and %.1f.\n"), MIN_LON, MAX_LON);
		        exit(EXIT_FAILURE);
		}

		/* Color temperature */
		if (scheme.day.temperature < MIN_TEMP ||
		    scheme.day.temperature > MAX_TEMP ||
		    scheme.night.temperature < MIN_TEMP ||
		    scheme.night.temperature > MAX_TEMP) {
			fprintf(stderr,
				_("Temperature must be between %uK and %uK.\n"),
				MIN_TEMP, MAX_TEMP);
			exit(EXIT_FAILURE);
		}

		/* Solar elevations */
		if (scheme.high < scheme.low) {
		        fprintf(stderr,
		                _("High transition elevation cannot be lower than"
				  " the low transition elevation.\n"));
		        exit(EXIT_FAILURE);
		}
	}

	if (mode == PROGRAM_MODE_MANUAL) {
		/* Check color temperature to be set */
		if (temp_set < MIN_TEMP || temp_set > MAX_TEMP) {
			fprintf(stderr,
				_("Temperature must be between %uK and %uK.\n"),
				MIN_TEMP, MAX_TEMP);
			exit(EXIT_FAILURE);
		}
	}

	/* Brightness */
	if (scheme.day.brightness < MIN_BRIGHTNESS ||
	    scheme.day.brightness > MAX_BRIGHTNESS ||
	    scheme.night.brightness < MIN_BRIGHTNESS ||
	    scheme.night.brightness > MAX_BRIGHTNESS) {
		fprintf(stderr,
			_("Brightness values must be between %.1f and %.1f.\n"),
			MIN_BRIGHTNESS, MAX_BRIGHTNESS);
		exit(EXIT_FAILURE);
	}

	if (verbose) {
		printf(_("Brightness: %.2f:%.2f\n"),
		       scheme.day.brightness, scheme.night.brightness);
	}

	/* Gamma */
	if (!gamma_is_valid(scheme.day.gamma) ||
	    !gamma_is_valid(scheme.night.gamma)) {
		fprintf(stderr,
			_("Gamma value must be between %.1f and %.1f.\n"),
			MIN_GAMMA, MAX_GAMMA);
		exit(EXIT_FAILURE);
	}

	if (verbose) {
		/* TRANSLATORS: The string in parenthesis is either
		   Daytime or Night (translated). */
		printf(_("Gamma (%s): %.3f, %.3f, %.3f\n"),
		       _("Daytime"), scheme.day.gamma[0],
		       scheme.day.gamma[1], scheme.day.gamma[2]);
		printf(_("Gamma (%s): %.3f, %.3f, %.3f\n"),
		       _("Night"), scheme.night.gamma[0],
		       scheme.night.gamma[1], scheme.night.gamma[2]);
	}

	/* Initialize gamma adjustment method. If method is NULL
	   try all methods until one that works is found. */
	gamma_state_t state;

	/* Gamma adjustment not needed for print mode */
	if (mode != PROGRAM_MODE_PRINT) {
		if (method != NULL) {
			/* Use method specified on command line. */
			r = method_try_start(method, &state, &config_state,
					     method_args);
			if (r < 0) exit(EXIT_FAILURE);
		} else {
			/* Try all methods, use the first that works. */
			for (int i = 0; gamma_methods[i].name != NULL; i++) {
				const gamma_method_t *m = &gamma_methods[i];
				if (!m->autostart) continue;

				r = method_try_start(m, &state, &config_state, NULL);
				if (r < 0) {
					fputs(_("Trying next method...\n"), stderr);
					continue;
				}

				/* Found method that works. */
				printf(_("Using method `%s'.\n"), m->name);
				method = m;
				break;
			}

			/* Failure if no methods were successful at this point. */
			if (method == NULL) {
				fputs(_("No more methods to try.\n"), stderr);
				exit(EXIT_FAILURE);
			}
		}
	}

	config_ini_free(&config_state);

	switch (mode) {
	case PROGRAM_MODE_ONE_SHOT:
	case PROGRAM_MODE_PRINT:
	{
		/* Current angular elevation of the sun */
		double now;
		r = systemtime_get_time(&now);
		if (r < 0) {
			fputs(_("Unable to read system time.\n"), stderr);
			method->free(&state);
			exit(EXIT_FAILURE);
		}

		double elevation = solar_elevation(now, loc.lat, loc.lon);

		if (verbose) {
			/* TRANSLATORS: Append degree symbol if possible. */
			printf(_("Solar elevation: %f\n"), elevation);
		}

		/* Use elevation of sun to set color temperature */
		color_setting_t interp;
		interpolate_color_settings(&scheme, elevation, &interp);

		if (verbose || mode == PROGRAM_MODE_PRINT) {
			period_t period = get_period(&scheme,
						     elevation);
			double transition =
				get_transition_progress(&scheme,
							elevation);
			print_period(period, transition);
			printf(_("Color temperature: %uK\n"),
			       interp.temperature);
			printf(_("Brightness: %.2f\n"),
			       interp.brightness);
		}

		if (mode == PROGRAM_MODE_PRINT) {
			exit(EXIT_SUCCESS);
		}

		/* Adjust temperature */
		r = method->set_temperature(&state, &interp);
		if (r < 0) {
			fputs(_("Temperature adjustment failed.\n"), stderr);
			method->free(&state);
			exit(EXIT_FAILURE);
		}

		/* In Quartz (OSX) the gamma adjustments will automatically
		   revert when the process exits. Therefore, we have to loop
		   until CTRL-C is received. */
		if (strcmp(method->name, "quartz") == 0) {
			fputs(_("Press ctrl-c to stop...\n"), stderr);
			pause();
		}
	}
	break;
	case PROGRAM_MODE_MANUAL:
	{
		if (verbose) printf(_("Color temperature: %uK\n"), temp_set);

		/* Adjust temperature */
		color_setting_t manual;
		memcpy(&manual, &scheme.day, sizeof(color_setting_t));
		manual.temperature = temp_set;
		r = method->set_temperature(&state, &manual);
		if (r < 0) {
			fputs(_("Temperature adjustment failed.\n"), stderr);
			method->free(&state);
			exit(EXIT_FAILURE);
		}

		/* In Quartz (OSX) the gamma adjustments will automatically
		   revert when the process exits. Therefore, we have to loop
		   until CTRL-C is received. */
		if (strcmp(method->name, "quartz") == 0) {
			fputs(_("Press ctrl-c to stop...\n"), stderr);
			pause();
		}
	}
	break;
	case PROGRAM_MODE_RESET:
	{
		/* Reset screen */
		color_setting_t reset = { NEUTRAL_TEMP, { 1.0, 1.0, 1.0 }, 1.0 };
		r = method->set_temperature(&state, &reset);
		if (r < 0) {
			fputs(_("Temperature adjustment failed.\n"), stderr);
			method->free(&state);
			exit(EXIT_FAILURE);
		}

		/* In Quartz (OSX) the gamma adjustments will automatically
		   revert when the process exits. Therefore, we have to loop
		   until CTRL-C is received. */
		if (strcmp(method->name, "quartz") == 0) {
			fputs(_("Press ctrl-c to stop...\n"), stderr);
			pause();
		}
	}
	break;
	case PROGRAM_MODE_CONTINUAL:
	{
		r = run_continual_mode(&loc, &scheme,
				       method, &state,
				       transition, verbose);
		if (r < 0) exit(EXIT_FAILURE);
	}
	break;
	}

	/* Clean up gamma adjustment state */
	method->free(&state);

	return EXIT_SUCCESS;
}
Пример #27
0
/**
 * This function computes the  'signum(.)' function:
 */
double sign(double x) {
  if (isnan(x)) {
    return x;
  }
  return ((x > 0) ? 1 : ((x == 0)? 0 : -1));
}
Пример #28
0
static int greeks3_exec(void *data, void *data2) {
	RAII_VAR(struct msg *, msg, (struct msg *)data, msg_decr);
	dstr *fields = NULL;
	int nfield = 0;
	time_t t;
	char *contract, *type;
	double spot, strike, r, vol, vol2, vol3, expiry;
	int steps;
	NOT_USED(data2);

	fields = dstr_split_len(msg->data, strlen(msg->data), ",", 1, &nfield);
	/* FIXME */
	if (nfield != 19) {
		xcb_log(XCB_LOG_WARNING, "Message '%s' garbled", msg->data);
		goto end;
	}
	t        = (time_t)atoi(fields[1]);
	contract = fields[3];
	type     = fields[12];
	spot     = atof(fields[10]);
	strike   = atof(fields[13]);
	r        = atof(fields[14]);
	vol      = atof(fields[5]);
	vol2     = atof(fields[7]);
	vol3     = atof(fields[9]);
	expiry   = atof(fields[15]);
	steps    = atoi(fields[18]);
	if (!isnan(vol) || !isnan(vol2) || !isnan(vol3)) {
		double delta, gamma, theta, vega, rho;
		double delta2, gamma2, theta2, vega2, rho2;
		double delta3, gamma3, theta3, vega3, rho3;
		struct tm lt;
		char datestr[64], res[512];

		if (isnan(vol))
			delta = gamma = theta = vega = rho = NAN;
		else {
			if (!strcasecmp(type, "C"))
				tri_amer_call_greeks(spot, strike, r, r, vol, expiry, steps,
					&delta, &gamma, &theta, &vega, &rho);
			else
				tri_amer_put_greeks (spot, strike, r, r, vol, expiry, steps,
					&delta, &gamma, &theta, &vega, &rho);
		}
		if (isnan(vol2))
			delta2 = gamma2 = theta2 = vega2 = rho2 = NAN;
		else if (fabs(vol2 - vol) <= 0.000001) {
			delta2 = delta;
			gamma2 = gamma;
			theta2 = theta;
			vega2  = vega;
			rho2   = rho;
		} else {
			if (!strcasecmp(type, "C"))
				tri_amer_call_greeks(spot, strike, r, r, vol2, expiry, steps,
					&delta2, &gamma2, &theta2, &vega2, &rho2);
			else
				tri_amer_put_greeks (spot, strike, r, r, vol2, expiry, steps,
					&delta2, &gamma2, &theta2, &vega2, &rho2);
		}
		if (isnan(vol3))
			delta3 = gamma3 = theta3 = vega3 = rho3 = NAN;
		else if (fabs(vol3 - vol) <= 0.000001) {
			delta3 = delta;
			gamma3 = gamma;
			theta3 = theta;
			vega3  = vega;
			rho3   = rho;
		} else {
			if (!strcasecmp(type, "C"))
				tri_amer_call_greeks(spot, strike, r, r, vol3, expiry, steps,
					&delta3, &gamma3, &theta3, &vega3, &rho3);
			else
				tri_amer_put_greeks (spot, strike, r, r, vol3, expiry, steps,
					&delta3, &gamma3, &theta3, &vega3, &rho3);
		}
		strftime(datestr, sizeof datestr, "%F %T", localtime_r(&t, &lt));
		snprintf(res, sizeof res, "GREEKS3,%s.%03d,%s|%.2f,%f,%f,%f,%f,%f,%.2f,%f,%f,%f,%f,%f,"
			"%.2f,%f,%f,%f,%f,%f",
			datestr,
			atoi(fields[2]),
			contract,
			atof(fields[4]),
			delta,
			gamma,
			theta,
			vega,
			rho,
			atof(fields[6]),
			delta2,
			gamma2,
			theta2,
			vega2,
			rho2,
			atof(fields[8]),
			delta3,
			gamma3,
			theta3,
			vega3,
			rho3);
		out2rmp(res);
	}

end:
	dstr_free_tokens(fields, nfield);
	return 0;
}
Пример #29
0
int main(int argc, char* argv[])
{
    UNUSED_PARAM(argc);
    UNUSED_PARAM(argv);
    
    // Test garbage collection with a fresh context
    context = JSGlobalContextCreate(NULL);
    TestInitializeFinalize = true;
    testInitializeFinalize();
    JSGlobalContextRelease(context);
    JSGarbageCollect(context);
    TestInitializeFinalize = false;

    assert(Base_didFinalize);

    JSClassDefinition globalObjectClassDefinition = kJSClassDefinitionEmpty;
    globalObjectClassDefinition.initialize = testInitializeOfGlobalObjectClassHasNonNullContext;
    JSClassRef globalObjectClass = JSClassCreate(&globalObjectClassDefinition);
    context = JSGlobalContextCreate(globalObjectClass);
    
    JSObjectRef globalObject = JSContextGetGlobalObject(context);
    assert(JSValueIsObject(context, globalObject));
    
    JSValueRef jsUndefined = JSValueMakeUndefined(context);
    JSValueRef jsNull = JSValueMakeNull(context);
    JSValueRef jsTrue = JSValueMakeBoolean(context, true);
    JSValueRef jsFalse = JSValueMakeBoolean(context, false);
    JSValueRef jsZero = JSValueMakeNumber(context, 0);
    JSValueRef jsOne = JSValueMakeNumber(context, 1);
    JSValueRef jsOneThird = JSValueMakeNumber(context, 1.0 / 3.0);
    JSObjectRef jsObjectNoProto = JSObjectMake(context, NULL, NULL);
    JSObjectSetPrototype(context, jsObjectNoProto, JSValueMakeNull(context));

    // FIXME: test funny utf8 characters
    JSStringRef jsEmptyIString = JSStringCreateWithUTF8CString("");
    JSValueRef jsEmptyString = JSValueMakeString(context, jsEmptyIString);
    
    JSStringRef jsOneIString = JSStringCreateWithUTF8CString("1");
    JSValueRef jsOneString = JSValueMakeString(context, jsOneIString);

    UniChar singleUniChar = 65; // Capital A
    CFMutableStringRef cfString = 
        CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorDefault,
                                                          &singleUniChar,
                                                          1,
                                                          1,
                                                          kCFAllocatorNull);

    JSStringRef jsCFIString = JSStringCreateWithCFString(cfString);
    JSValueRef jsCFString = JSValueMakeString(context, jsCFIString);
    
    CFStringRef cfEmptyString = CFStringCreateWithCString(kCFAllocatorDefault, "", kCFStringEncodingUTF8);
    
    JSStringRef jsCFEmptyIString = JSStringCreateWithCFString(cfEmptyString);
    JSValueRef jsCFEmptyString = JSValueMakeString(context, jsCFEmptyIString);

    CFIndex cfStringLength = CFStringGetLength(cfString);
    UniChar buffer[cfStringLength];
    CFStringGetCharacters(cfString, 
                          CFRangeMake(0, cfStringLength), 
                          buffer);
    JSStringRef jsCFIStringWithCharacters = JSStringCreateWithCharacters(buffer, cfStringLength);
    JSValueRef jsCFStringWithCharacters = JSValueMakeString(context, jsCFIStringWithCharacters);
    
    JSStringRef jsCFEmptyIStringWithCharacters = JSStringCreateWithCharacters(buffer, CFStringGetLength(cfEmptyString));
    JSValueRef jsCFEmptyStringWithCharacters = JSValueMakeString(context, jsCFEmptyIStringWithCharacters);

    assert(JSValueGetType(context, jsUndefined) == kJSTypeUndefined);
    assert(JSValueGetType(context, jsNull) == kJSTypeNull);
    assert(JSValueGetType(context, jsTrue) == kJSTypeBoolean);
    assert(JSValueGetType(context, jsFalse) == kJSTypeBoolean);
    assert(JSValueGetType(context, jsZero) == kJSTypeNumber);
    assert(JSValueGetType(context, jsOne) == kJSTypeNumber);
    assert(JSValueGetType(context, jsOneThird) == kJSTypeNumber);
    assert(JSValueGetType(context, jsEmptyString) == kJSTypeString);
    assert(JSValueGetType(context, jsOneString) == kJSTypeString);
    assert(JSValueGetType(context, jsCFString) == kJSTypeString);
    assert(JSValueGetType(context, jsCFStringWithCharacters) == kJSTypeString);
    assert(JSValueGetType(context, jsCFEmptyString) == kJSTypeString);
    assert(JSValueGetType(context, jsCFEmptyStringWithCharacters) == kJSTypeString);

    JSObjectRef myObject = JSObjectMake(context, MyObject_class(context), NULL);
    JSStringRef myObjectIString = JSStringCreateWithUTF8CString("MyObject");
    JSObjectSetProperty(context, globalObject, myObjectIString, myObject, kJSPropertyAttributeNone, NULL);
    JSStringRelease(myObjectIString);
    
    JSValueRef exception;

    // Conversions that throw exceptions
    exception = NULL;
    assert(NULL == JSValueToObject(context, jsNull, &exception));
    assert(exception);
    
    exception = NULL;
    // FIXME <rdar://4668451> - On i386 the isnan(double) macro tries to map to the isnan(float) function,
    // causing a build break with -Wshorten-64-to-32 enabled.  The issue is known by the appropriate team.
    // After that's resolved, we can remove these casts
    assert(isnan((float)JSValueToNumber(context, jsObjectNoProto, &exception)));
    assert(exception);

    exception = NULL;
    assert(!JSValueToStringCopy(context, jsObjectNoProto, &exception));
    assert(exception);
    
    assert(JSValueToBoolean(context, myObject));
    
    exception = NULL;
    assert(!JSValueIsEqual(context, jsObjectNoProto, JSValueMakeNumber(context, 1), &exception));
    assert(exception);
    
    exception = NULL;
    JSObjectGetPropertyAtIndex(context, myObject, 0, &exception);
    assert(1 == JSValueToNumber(context, exception, NULL));

    assertEqualsAsBoolean(jsUndefined, false);
    assertEqualsAsBoolean(jsNull, false);
    assertEqualsAsBoolean(jsTrue, true);
    assertEqualsAsBoolean(jsFalse, false);
    assertEqualsAsBoolean(jsZero, false);
    assertEqualsAsBoolean(jsOne, true);
    assertEqualsAsBoolean(jsOneThird, true);
    assertEqualsAsBoolean(jsEmptyString, false);
    assertEqualsAsBoolean(jsOneString, true);
    assertEqualsAsBoolean(jsCFString, true);
    assertEqualsAsBoolean(jsCFStringWithCharacters, true);
    assertEqualsAsBoolean(jsCFEmptyString, false);
    assertEqualsAsBoolean(jsCFEmptyStringWithCharacters, false);
    
    assertEqualsAsNumber(jsUndefined, nan(""));
    assertEqualsAsNumber(jsNull, 0);
    assertEqualsAsNumber(jsTrue, 1);
    assertEqualsAsNumber(jsFalse, 0);
    assertEqualsAsNumber(jsZero, 0);
    assertEqualsAsNumber(jsOne, 1);
    assertEqualsAsNumber(jsOneThird, 1.0 / 3.0);
    assertEqualsAsNumber(jsEmptyString, 0);
    assertEqualsAsNumber(jsOneString, 1);
    assertEqualsAsNumber(jsCFString, nan(""));
    assertEqualsAsNumber(jsCFStringWithCharacters, nan(""));
    assertEqualsAsNumber(jsCFEmptyString, 0);
    assertEqualsAsNumber(jsCFEmptyStringWithCharacters, 0);
    assert(sizeof(JSChar) == sizeof(UniChar));
    
    assertEqualsAsCharactersPtr(jsUndefined, "undefined");
    assertEqualsAsCharactersPtr(jsNull, "null");
    assertEqualsAsCharactersPtr(jsTrue, "true");
    assertEqualsAsCharactersPtr(jsFalse, "false");
    assertEqualsAsCharactersPtr(jsZero, "0");
    assertEqualsAsCharactersPtr(jsOne, "1");
    assertEqualsAsCharactersPtr(jsOneThird, "0.3333333333333333");
    assertEqualsAsCharactersPtr(jsEmptyString, "");
    assertEqualsAsCharactersPtr(jsOneString, "1");
    assertEqualsAsCharactersPtr(jsCFString, "A");
    assertEqualsAsCharactersPtr(jsCFStringWithCharacters, "A");
    assertEqualsAsCharactersPtr(jsCFEmptyString, "");
    assertEqualsAsCharactersPtr(jsCFEmptyStringWithCharacters, "");
    
    assertEqualsAsUTF8String(jsUndefined, "undefined");
    assertEqualsAsUTF8String(jsNull, "null");
    assertEqualsAsUTF8String(jsTrue, "true");
    assertEqualsAsUTF8String(jsFalse, "false");
    assertEqualsAsUTF8String(jsZero, "0");
    assertEqualsAsUTF8String(jsOne, "1");
    assertEqualsAsUTF8String(jsOneThird, "0.3333333333333333");
    assertEqualsAsUTF8String(jsEmptyString, "");
    assertEqualsAsUTF8String(jsOneString, "1");
    assertEqualsAsUTF8String(jsCFString, "A");
    assertEqualsAsUTF8String(jsCFStringWithCharacters, "A");
    assertEqualsAsUTF8String(jsCFEmptyString, "");
    assertEqualsAsUTF8String(jsCFEmptyStringWithCharacters, "");
    
    assert(JSValueIsStrictEqual(context, jsTrue, jsTrue));
    assert(!JSValueIsStrictEqual(context, jsOne, jsOneString));

    assert(JSValueIsEqual(context, jsOne, jsOneString, NULL));
    assert(!JSValueIsEqual(context, jsTrue, jsFalse, NULL));
    
    CFStringRef cfJSString = JSStringCopyCFString(kCFAllocatorDefault, jsCFIString);
    CFStringRef cfJSEmptyString = JSStringCopyCFString(kCFAllocatorDefault, jsCFEmptyIString);
    assert(CFEqual(cfJSString, cfString));
    assert(CFEqual(cfJSEmptyString, cfEmptyString));
    CFRelease(cfJSString);
    CFRelease(cfJSEmptyString);

    CFRelease(cfString);
    CFRelease(cfEmptyString);
    
    jsGlobalValue = JSObjectMake(context, NULL, NULL);
    JSValueProtect(context, jsGlobalValue);
    JSGarbageCollect(context);
    assert(JSValueIsObject(context, jsGlobalValue));
    JSValueUnprotect(context, jsGlobalValue);

    JSStringRef goodSyntax = JSStringCreateWithUTF8CString("x = 1;");
    JSStringRef badSyntax = JSStringCreateWithUTF8CString("x := 1;");
    assert(JSCheckScriptSyntax(context, goodSyntax, NULL, 0, NULL));
    assert(!JSCheckScriptSyntax(context, badSyntax, NULL, 0, NULL));

    JSValueRef result;
    JSValueRef v;
    JSObjectRef o;
    JSStringRef string;

    result = JSEvaluateScript(context, goodSyntax, NULL, NULL, 1, NULL);
    assert(result);
    assert(JSValueIsEqual(context, result, jsOne, NULL));

    exception = NULL;
    result = JSEvaluateScript(context, badSyntax, NULL, NULL, 1, &exception);
    assert(!result);
    assert(JSValueIsObject(context, exception));
    
    JSStringRef array = JSStringCreateWithUTF8CString("Array");
    JSObjectRef arrayConstructor = JSValueToObject(context, JSObjectGetProperty(context, globalObject, array, NULL), NULL);
    JSStringRelease(array);
    result = JSObjectCallAsConstructor(context, arrayConstructor, 0, NULL, NULL);
    assert(result);
    assert(JSValueIsObject(context, result));
    assert(JSValueIsInstanceOfConstructor(context, result, arrayConstructor, NULL));
    assert(!JSValueIsInstanceOfConstructor(context, JSValueMakeNull(context), arrayConstructor, NULL));

    o = JSValueToObject(context, result, NULL);
    exception = NULL;
    assert(JSValueIsUndefined(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception)));
    assert(!exception);
    
    JSObjectSetPropertyAtIndex(context, o, 0, JSValueMakeNumber(context, 1), &exception);
    assert(!exception);
    
    exception = NULL;
    assert(1 == JSValueToNumber(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception), &exception));
    assert(!exception);

    JSStringRef functionBody;
    JSObjectRef function;
    
    exception = NULL;
    functionBody = JSStringCreateWithUTF8CString("rreturn Array;");
    JSStringRef line = JSStringCreateWithUTF8CString("line");
    assert(!JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception));
    assert(JSValueIsObject(context, exception));
    v = JSObjectGetProperty(context, JSValueToObject(context, exception, NULL), line, NULL);
    assertEqualsAsNumber(v, 2); // FIXME: Lexer::setCode bumps startingLineNumber by 1 -- we need to change internal callers so that it doesn't have to (saying '0' to mean '1' in the API would be really confusing -- it's really confusing internally, in fact)
    JSStringRelease(functionBody);
    JSStringRelease(line);

    exception = NULL;
    functionBody = JSStringCreateWithUTF8CString("return Array;");
    function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception);
    JSStringRelease(functionBody);
    assert(!exception);
    assert(JSObjectIsFunction(context, function));
    v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
    assert(v);
    assert(JSValueIsEqual(context, v, arrayConstructor, NULL));
    
    exception = NULL;
    function = JSObjectMakeFunction(context, NULL, 0, NULL, jsEmptyIString, NULL, 0, &exception);
    assert(!exception);
    v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, &exception);
    assert(v && !exception);
    assert(JSValueIsUndefined(context, v));
    
    exception = NULL;
    v = NULL;
    JSStringRef foo = JSStringCreateWithUTF8CString("foo");
    JSStringRef argumentNames[] = { foo };
    functionBody = JSStringCreateWithUTF8CString("return foo;");
    function = JSObjectMakeFunction(context, foo, 1, argumentNames, functionBody, NULL, 1, &exception);
    assert(function && !exception);
    JSValueRef arguments[] = { JSValueMakeNumber(context, 2) };
    v = JSObjectCallAsFunction(context, function, NULL, 1, arguments, &exception);
    JSStringRelease(foo);
    JSStringRelease(functionBody);
    
    string = JSValueToStringCopy(context, function, NULL);
    assertEqualsAsUTF8String(JSValueMakeString(context, string), "function foo(foo) \n{\n  return foo;\n}");
    JSStringRelease(string);

    JSStringRef print = JSStringCreateWithUTF8CString("print");
    JSObjectRef printFunction = JSObjectMakeFunctionWithCallback(context, print, print_callAsFunction);
    JSObjectSetProperty(context, globalObject, print, printFunction, kJSPropertyAttributeNone, NULL); 
    JSStringRelease(print);
    
    assert(!JSObjectSetPrivate(printFunction, (void*)1));
    assert(!JSObjectGetPrivate(printFunction));

    JSStringRef myConstructorIString = JSStringCreateWithUTF8CString("MyConstructor");
    JSObjectRef myConstructor = JSObjectMakeConstructor(context, NULL, myConstructor_callAsConstructor);
    JSObjectSetProperty(context, globalObject, myConstructorIString, myConstructor, kJSPropertyAttributeNone, NULL);
    JSStringRelease(myConstructorIString);
    
    assert(!JSObjectSetPrivate(myConstructor, (void*)1));
    assert(!JSObjectGetPrivate(myConstructor));
    
    string = JSStringCreateWithUTF8CString("Derived");
    JSObjectRef derivedConstructor = JSObjectMakeConstructor(context, Derived_class(context), NULL);
    JSObjectSetProperty(context, globalObject, string, derivedConstructor, kJSPropertyAttributeNone, NULL);
    JSStringRelease(string);
    
    o = JSObjectMake(context, NULL, NULL);
    JSObjectSetProperty(context, o, jsOneIString, JSValueMakeNumber(context, 1), kJSPropertyAttributeNone, NULL);
    JSObjectSetProperty(context, o, jsCFIString,  JSValueMakeNumber(context, 1), kJSPropertyAttributeDontEnum, NULL);
    JSPropertyNameArrayRef nameArray = JSObjectCopyPropertyNames(context, o);
    size_t expectedCount = JSPropertyNameArrayGetCount(nameArray);
    size_t count;
    for (count = 0; count < expectedCount; ++count)
        JSPropertyNameArrayGetNameAtIndex(nameArray, count);
    JSPropertyNameArrayRelease(nameArray);
    assert(count == 1); // jsCFString should not be enumerated

    JSClassDefinition nullDefinition = kJSClassDefinitionEmpty;
    nullDefinition.attributes = kJSClassAttributeNoAutomaticPrototype;
    JSClassRef nullClass = JSClassCreate(&nullDefinition);
    JSClassRelease(nullClass);
    
    nullDefinition = kJSClassDefinitionEmpty;
    nullClass = JSClassCreate(&nullDefinition);
    JSClassRelease(nullClass);

    functionBody = JSStringCreateWithUTF8CString("return this;");
    function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, NULL);
    JSStringRelease(functionBody);
    v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
    assert(JSValueIsEqual(context, v, globalObject, NULL));
    v = JSObjectCallAsFunction(context, function, o, 0, NULL, NULL);
    assert(JSValueIsEqual(context, v, o, NULL));
    
    char* scriptUTF8 = createStringWithContentsOfFile("testapi.js");
    JSStringRef script = JSStringCreateWithUTF8CString(scriptUTF8);
    result = JSEvaluateScript(context, script, NULL, NULL, 1, &exception);
    if (JSValueIsUndefined(context, result))
        printf("PASS: Test script executed successfully.\n");
    else {
        printf("FAIL: Test script returned unexcpected value:\n");
        JSStringRef exceptionIString = JSValueToStringCopy(context, exception, NULL);
        CFStringRef exceptionCF = JSStringCopyCFString(kCFAllocatorDefault, exceptionIString);
        CFShow(exceptionCF);
        CFRelease(exceptionCF);
        JSStringRelease(exceptionIString);
    }
    JSStringRelease(script);
    free(scriptUTF8);

    JSStringRelease(jsEmptyIString);
    JSStringRelease(jsOneIString);
    JSStringRelease(jsCFIString);
    JSStringRelease(jsCFEmptyIString);
    JSStringRelease(jsCFIStringWithCharacters);
    JSStringRelease(jsCFEmptyIStringWithCharacters);
    JSStringRelease(goodSyntax);
    JSStringRelease(badSyntax);
    
    JSGlobalContextRelease(context);
    JSGarbageCollect(context);
    JSClassRelease(globalObjectClass);

    printf("PASS: Program exited normally.\n");
    return 0;
}
void BIH::subdivide(int left, int right, std::vector<uint32> &tempTree, buildData &dat, AABound &gridBox, AABound &nodeBox, int nodeIndex, int depth, BuildStats &stats)
{
    if ((right - left + 1) <= dat.maxPrims || depth >= MAX_STACK_SIZE)
    {
        // write leaf node
        stats.updateLeaf(depth, right - left + 1);
        createNode(tempTree, nodeIndex, left, right);
        return;
    }
    // calculate extents
    int axis = -1, prevAxis, rightOrig;
    float clipL = G3D::fnan(), clipR = G3D::fnan(), prevClip = G3D::fnan();
    float split = G3D::fnan(), prevSplit;
    bool wasLeft = true;
    while (true)
    {
        prevAxis = axis;
        prevSplit = split;
        // perform quick consistency checks
        G3D::Vector3 d( gridBox.hi - gridBox.lo );
        if (d.x < 0 || d.y < 0 || d.z < 0)
            throw std::logic_error("negative node extents");
        for (int i = 0; i < 3; i++)
        {
            if (nodeBox.hi[i] < gridBox.lo[i] || nodeBox.lo[i] > gridBox.hi[i])
            {
                //UI.printError(Module.ACCEL, "Reached tree area in error - discarding node with: %d objects", right - left + 1);
                throw std::logic_error("invalid node overlap");
            }
        }
        // find longest axis
        axis = d.primaryAxis();
        split = 0.5f * (gridBox.lo[axis] + gridBox.hi[axis]);
        // partition L/R subsets
        clipL = -G3D::inf();
        clipR = G3D::inf();
        rightOrig = right; // save this for later
        float nodeL = G3D::inf();
        float nodeR = -G3D::inf();
        for (int i = left; i <= right;)
        {
            int obj = dat.indices[i];
            float minb = dat.primBound[obj].low()[axis];
            float maxb = dat.primBound[obj].high()[axis];
            float center = (minb + maxb) * 0.5f;
            if (center <= split)
            {
                // stay left
                i++;
                if (clipL < maxb)
                    clipL = maxb;
            }
            else
            {
                // move to the right most
                int t = dat.indices[i];
                dat.indices[i] = dat.indices[right];
                dat.indices[right] = t;
                right--;
                if (clipR > minb)
                    clipR = minb;
            }
            nodeL = std::min(nodeL, minb);
            nodeR = std::max(nodeR, maxb);
        }
        // check for empty space
        if (nodeL > nodeBox.lo[axis] && nodeR < nodeBox.hi[axis])
        {
            float nodeBoxW = nodeBox.hi[axis] - nodeBox.lo[axis];
            float nodeNewW = nodeR - nodeL;
            // node box is too big compare to space occupied by primitives?
            if (1.3f * nodeNewW < nodeBoxW)
            {
                stats.updateBVH2();
                int nextIndex = tempTree.size();
                // allocate child
                tempTree.push_back(0);
                tempTree.push_back(0);
                tempTree.push_back(0);
                // write bvh2 clip node
                stats.updateInner();
                tempTree[nodeIndex + 0] = (axis << 30) | (1 << 29) | nextIndex;
                tempTree[nodeIndex + 1] = floatToRawIntBits(nodeL);
                tempTree[nodeIndex + 2] = floatToRawIntBits(nodeR);
                // update nodebox and recurse
                nodeBox.lo[axis] = nodeL;
                nodeBox.hi[axis] = nodeR;
                subdivide(left, rightOrig, tempTree, dat, gridBox, nodeBox, nextIndex, depth + 1, stats);
                return;
            }
        }
        // ensure we are making progress in the subdivision
        if (right == rightOrig)
        {
            // all left
            if (prevAxis == axis && G3D::fuzzyEq(prevSplit, split)) {
                // we are stuck here - create a leaf
                stats.updateLeaf(depth, right - left + 1);
                createNode(tempTree, nodeIndex, left, right);
                return;
            }
            if (clipL <= split) {
                // keep looping on left half
                gridBox.hi[axis] = split;
                prevClip = clipL;
                wasLeft = true;
                continue;
            }
            gridBox.hi[axis] = split;
            prevClip = G3D::fnan();
        }
        else if (left > right)
        {
            // all right
            if (prevAxis == axis && G3D::fuzzyEq(prevSplit, split)) {
                // we are stuck here - create a leaf
                stats.updateLeaf(depth, right - left + 1);
                createNode(tempTree, nodeIndex, left, right);
                return;
            }
            right = rightOrig;
            if (clipR >= split) {
                // keep looping on right half
                gridBox.lo[axis] = split;
                prevClip = clipR;
                wasLeft = false;
                continue;
            }
            gridBox.lo[axis] = split;
            prevClip = G3D::fnan();
        }
        else
        {
            // we are actually splitting stuff
            if (prevAxis != -1 && !isnan(prevClip))
            {
                // second time through - lets create the previous split
                // since it produced empty space
                int nextIndex = tempTree.size();
                // allocate child node
                tempTree.push_back(0);
                tempTree.push_back(0);
                tempTree.push_back(0);
                if (wasLeft) {
                    // create a node with a left child
                    // write leaf node
                    stats.updateInner();
                    tempTree[nodeIndex + 0] = (prevAxis << 30) | nextIndex;
                    tempTree[nodeIndex + 1] = floatToRawIntBits(prevClip);
                    tempTree[nodeIndex + 2] = floatToRawIntBits(G3D::inf());
                } else {
                    // create a node with a right child
                    // write leaf node
                    stats.updateInner();
                    tempTree[nodeIndex + 0] = (prevAxis << 30) | (nextIndex - 3);
                    tempTree[nodeIndex + 1] = floatToRawIntBits(-G3D::inf());
                    tempTree[nodeIndex + 2] = floatToRawIntBits(prevClip);
                }
                // count stats for the unused leaf
                depth++;
                stats.updateLeaf(depth, 0);
                // now we keep going as we are, with a new nodeIndex:
                nodeIndex = nextIndex;
            }
            break;
        }
    }
    // compute index of child nodes
    int nextIndex = tempTree.size();
    // allocate left node
    int nl = right - left + 1;
    int nr = rightOrig - (right + 1) + 1;
    if (nl > 0) {
        tempTree.push_back(0);
        tempTree.push_back(0);
        tempTree.push_back(0);
    } else
        nextIndex -= 3;
    // allocate right node
    if (nr > 0) {
        tempTree.push_back(0);
        tempTree.push_back(0);
        tempTree.push_back(0);
    }
    // write leaf node
    stats.updateInner();
    tempTree[nodeIndex + 0] = (axis << 30) | nextIndex;
    tempTree[nodeIndex + 1] = floatToRawIntBits(clipL);
    tempTree[nodeIndex + 2] = floatToRawIntBits(clipR);
    // prepare L/R child boxes
    AABound gridBoxL(gridBox), gridBoxR(gridBox);
    AABound nodeBoxL(nodeBox), nodeBoxR(nodeBox);
    gridBoxL.hi[axis] = gridBoxR.lo[axis] = split;
    nodeBoxL.hi[axis] = clipL;
    nodeBoxR.lo[axis] = clipR;
    // recurse
    if (nl > 0)
        subdivide(left, right, tempTree, dat, gridBoxL, nodeBoxL, nextIndex, depth + 1, stats);
    else
        stats.updateLeaf(depth + 1, 0);
    if (nr > 0)
        subdivide(right + 1, rightOrig, tempTree, dat, gridBoxR, nodeBoxR, nextIndex + 3, depth + 1, stats);
    else
        stats.updateLeaf(depth + 1, 0);
}