bool Parser::multiplication() {
    if (!bracket())
        return false;
    while (*string == '*' || *string == '/') {
        string++;
        if (!bracket())
            return false;
    }
    return true;
}
Beispiel #2
0
double linmin(double xi[], double del[], double fxi1, double *x1, double *x2, double *fret1, double *fret2)
{
  int   j;
  static double *vecu = NULL;	/* Vector of location u */
  double xx, fx, fb, bx, ax;
  double fa = fxi1;
  double xmin;
  double xmin2;

  xicom = xi;
  delcom = del;
  ax = 0.0;			/*do not change without correcting fa, */
  /*saves 1 fcalc... */
  bx = .1;

  if (vecu == NULL) {
    vecu = vect_double(ndimtot);
    reg_for_free(vecu, "vecu");
  }
  for (j = 0; j < ndimtot; j++)
    vecu[j] = xicom[j] + bx * delcom[j];	/*set vecu */
  fb = (*calc_forces) (vecu, fret2, 0);

  bracket(&ax, &xx, &bx, &fa, &fx, &fb, fret1, fret2);

  fx = brent(ax, xx, bx, fx, TOL, &xmin, &xmin2, fret1, fret2);
  for (j = 0; j < ndimtot; j++) {
    del[j] *= xmin;
    xi[j] += del[j];
  }
  *x1 = xmin;
  *x2 = xmin2;
  return fx;
}
Beispiel #3
0
int
next(STR *s)
{
	int ch;

	switch (s->state) {
	case EOS:
		return (0);
	case INFINITE:
		return (1);
	case NORMAL:
		switch (ch = (u_char)*s->str) {
		case '\0':
			s->state = EOS;
			return (0);
		case '\\':
			s->lastch = backslash(s);
			break;
		case '[':
			if (bracket(s))
				return (next(s));
			/* FALLTHROUGH */
		default:
			++s->str;
			s->lastch = ch;
			break;
		}

		/* We can start a range at any time. */
		if (s->str[0] == '-' && genrange(s))
			return (next(s));
		return (1);
	case RANGE:
		if (s->cnt-- == 0) {
			s->state = NORMAL;
			return (next(s));
		}
		++s->lastch;
		return (1);
	case SEQUENCE:
		if (s->cnt-- == 0) {
			s->state = NORMAL;
			return (next(s));
		}
		return (1);
	case SET:
		if ((s->lastch = s->set[s->cnt++]) == OOBCH) {
			s->state = NORMAL;
			return (next(s));
		}
		return (1);
	default:
		return (0);
	}
	/* NOTREACHED */
}
Beispiel #4
0
int main()
{
   char buffer[100];
   int result;
   scanf("%s",&buffer);
   result=bracket(buffer);
   printf("%d\n",result);

   return 0;
}
Beispiel #5
0
void dealer::purify(courses &tmp, QString *str)
{
    tmp.tName=bracket(str,1);
    QString hours=bracket(str,1);
    bracket(str,1);
    tmp.timeStr=bracket(str,0);
    QString stmp=tmp.timeStr;
    while(stmp.indexOf(sw)!=-1)
    {
        int p=stmp.indexOf(sw);
        stmp.remove(p-1,4);
    }
    while(stmp.indexOf(dw)!=-1)
    {
        int p=stmp.indexOf(dw);
        stmp.remove(p-1,4);
    }
    tmp.timeIndex = 0;
    if(stmp.indexOf("<br>")!=-1)
    {
        int tx;
        while((tx=stmp.indexOf("<br>"))!=-1)
        {
            tmp.timeIndex|=tmap.value(stmp.mid(0,tx));
            if(!tmap.value(stmp.mid(0,tx))) {nflag=1;return;}
            stmp.remove(0,tx+4);
        }
    }
    tmp.timeIndex|=tmap.value(stmp);
    if(!tmap.value(stmp)) {nflag=1;return;}
    tmp.location=bracket(str,0);
    tmp.location.replace("<br>","\n");
    QString thours;
    thours=hours.mid(0,1);
    tmp.ks=thours.toInt();
    thours=hours.mid(5,1);
    tmp.ks+=thours.toInt();
    tmp.stars=5;
}
Beispiel #6
0
string ReplaceBrackets(const string& SearchStr,const string& ReplaceStr,RegExpMatch* Match,int Count)
{
	string result;
	size_t pos=0,length=ReplaceStr.GetLength();

	while (pos<length)
	{
		bool common=true;

		if (ReplaceStr[pos]=='$')
		{
			++pos;

			if (pos>length) break;

			wchar_t symbol=Upper(ReplaceStr[pos]);
			int index=-1;

			if (symbol>='0'&&symbol<='9')
			{
				index=symbol-'0';
			}
			else if (symbol>='A'&&symbol<='Z')
			{
				index=symbol-'A'+10;
			}

			if (index>=0)
			{
				if (index<Count)
				{
					string bracket(SearchStr.CPtr()+Match[index].start,Match[index].end-Match[index].start);
					result+=bracket;
				}

				common=false;
			}
		}

		if (common)
		{
			result+=ReplaceStr[pos];
		}

		++pos;
	}

	return result;
}
int main(int argc, char *argv[]){
    
    struct Object master = newObject();
    char* string = getCString(argv);
    
    master = parse(master,argv);
    master = noComments(master);
    
    struct Object brack = bracket(master);
    struct Object semi = semiColon(master);
    
    dynamicLeaks(string);
    
    free(string);
    string = NULL;
    
    return 0;
}
Beispiel #8
0
static double searchGeom (Point a, Point p, Geometry *g)
{
  Vector   ap;
  double   tol = dparam("TOLCURV"), s[3], f[3];
  register int ip;

  /* start the search at the closest point */

  ap   = setVector (a, p);
  s[0] = g -> arclen[ip = closest (p, g)];
  s[1] = g -> arclen[ip + 1];

  bracket (s, f, g, a, ap);
  if (fabs(f[1]) > tol)
    brent (s, g, a, ap, tol);

  return s[1];
}
Beispiel #9
0
    inline std::vector<unsigned int> tournament_selection(const RandomAccessIterator &start
      , const RandomAccessIterator &end, std::size_t new_size, std::size_t pool_size)
    {
      std::size_t pop_size = (end - start);
      std::vector<unsigned int> bracket(pool_size);
      std::vector<unsigned int> selected_indices(new_size);

      assert(pool_size <= pop_size &&
       "ERROR: the bracket size is bigger than population size.");

      // Selecting new individuals
      for (std::size_t i = 0; i < new_size; ++i) 
      {
        bracket.clear();
        std::size_t winner_index = 0;
        double winner_fitness = 0;

        // Creates the bracket
        for (std::size_t j = 0; j < pool_size; ++j) 
        {
          bracket[j] = nevil::random::random_int(pop_size);
          // Ensures that the same individual is not put in the bracket more than once
          for (std::size_t k = 0; k < j; ++k)
          {
            if (bracket[j] == bracket[k])
            {
              bracket[j] = nevil::random::random_int(pop_size);
              k = 0;
              continue;
            }
            // Select the individual with higher fitness
            if (start[bracket[j]]->get_fitness() > winner_fitness)
            {
              winner_index = bracket[j];
              winner_fitness = start[bracket[j]]->get_fitness();
            }
          }
        }
        selected_indices[i] = winner_index;
      }
      return selected_indices;
    }
Beispiel #10
0
void dealer::extract(courses &tmp, QString *str)
{
    tmp.code=bracket(str,1);
    tmp.cName=bracket(str,1);
    tmp.tName=bracket(str,1);
    bracket(str,1);
    tmp.timeStr=bracket(str,0);
    QString stmp=tmp.timeStr;
//    //qDebug() << stmp;
    while(stmp.indexOf(sw)!=-1)
    {
        int p=stmp.indexOf(sw);
        stmp.remove(p-1,4);
    }
    while(stmp.indexOf(dw)!=-1)
    {
        int p=stmp.indexOf(dw);
        stmp.remove(p-1,4);
    }
//    //qDebug() << stmp;
    tmp.timeIndex = 0;
    if(stmp.indexOf("<br>")!=-1)
    {
        int tx;
        while((tx=stmp.indexOf("<br>"))!=-1)
        {
            tmp.timeIndex|=tmap.value(stmp.mid(0,tx));
            if(!tmap.value(stmp.mid(0,tx))) {nflag=1;return;}
            stmp.remove(0,tx+4);
        }
    }
    tmp.timeIndex|=tmap.value(stmp);
    if(!tmap.value(stmp)){nflag=1;return;}
    tmp.location=bracket(str,0);
    tmp.location.replace("<br>","\n");
    tmp.stars=5;
}
Beispiel #11
0
/* Function:  esl_min_ConjugateGradientDescent()
 * Incept:    SRE, Wed Jun 22 08:49:42 2005 [St. Louis]
 *
 * Purpose:   n-dimensional minimization by conjugate gradient descent.
 *           
 *            An initial point is provided by <x>, a vector of <n>
 *            components. The caller also provides a function <*func()> that 
 *            compute the objective function f(x) when called as 
 *            <(*func)(x, n, prm)>, and a function <*dfunc()> that can
 *            compute the gradient <dx> at <x> when called as 
 *            <(*dfunc)(x, n, prm, dx)>, given an allocated vector <dx>
 *            to put the derivative in. Any additional data or fixed
 *            parameters that these functions require are passed by
 *            the void pointer <prm>.
 *            
 *            The first step of each iteration is to try to bracket
 *            the minimum along the current direction. The initial step
 *            size is controlled by <u[]>; the first step will not exceed 
 *            <u[i]> for any dimension <i>. (You can think of <u> as
 *            being the natural "units" to use along a graph axis, if
 *            you were plotting the objective function.)
 *
 *            The caller also provides an allocated workspace sufficient to
 *            hold four allocated n-vectors. (4 * sizeof(double) * n).
 *
 *            Iterations continue until the objective function has changed
 *            by less than a fraction <tol>. This should not be set to less than
 *            sqrt(<DBL_EPSILON>). 
 *
 *            Upon return, <x> is the minimum, and <ret_fx> is f(x),
 *            the function value at <x>.
 *            
 * Args:      x        - an initial guess n-vector; RETURN: x at the minimum
 *            u        - "units": maximum initial step size along gradient when bracketing.
 *            n        - dimensionality of all vectors
 *            *func()  - function for computing objective function f(x)
 *            *dfunc() - function for computing a gradient at x
 *            prm      - void ptr to any data/params func,dfunc need 
 *            tol      - convergence criterion applied to f(x)
 *            wrk      - allocated 4xn-vector for workspace
 *            ret_fx   - optRETURN: f(x) at the minimum
 *
 * Returns:   <eslOK> on success.
 *
 * Throws:    <eslENOHALT> if it fails to converge in MAXITERATIONS.
 *            <eslERANGE> if the minimum is not finite, which may
 *            indicate a problem in the implementation or choice of <*func()>.
 *
 * Xref:      STL9/101.
 */
int
esl_min_ConjugateGradientDescent(double *x, double *u, int n, 
       				 double (*func)(double *, int, void *),
				 void (*dfunc)(double *, int, void *, double *),
				 void *prm, double tol, double *wrk, double *ret_fx)
{
  double oldfx;
  double coeff;
  int    i, i1;
  double *dx, *cg, *w1, *w2;
  double cvg;
  double fa,fb,fc;
  double ax,bx,cx;
  double fx;

  dx = wrk;
  cg = wrk + n;
  w1 = wrk + 2*n;
  w2 = wrk + 3*n;

  oldfx = (*func)(x, n, prm);	/* init the objective function */
  
  /* Bail out if the function is +/-inf: this can happen if the caller
   * has screwed something up, or has chosen a bad start point.
   */
  if (oldfx == eslINFINITY || oldfx == -eslINFINITY)
	  ESL_EXCEPTION(eslERANGE, "minimum not finite");


  if (dfunc != NULL) 
    {
      (*dfunc)(x, n, prm, dx);	/* find the current negative gradient, - df(x)/dxi  */
      esl_vec_DScale(dx, n, -1.0);
    } 
  else numeric_derivative(x, u, n, func, prm, 1e-4, dx); /* resort to brute force */

  esl_vec_DCopy(dx, n, cg);	/* and make that the first conjugate direction, cg  */



  /* (failsafe) convergence test: a zero direction can happen, 
   * and it either means we're stuck or we're finished (most likely stuck)
   */
  for (i1 = 0; i1 < n; i1++) 
    if (cg[i1] != 0.) break;
  if  (i1 == n) {
    if (ret_fx != NULL) *ret_fx = oldfx;
    return eslOK;
  }
  
  for (i = 0; i < MAXITERATIONS; i++)
  {

      /* Figure out the initial step size.
       */
       bx = fabs(u[0] / cg[0]);
       for (i1 = 1; i1 < n; i1++)
	 {
	   cx = fabs(u[i1] / cg[i1]);
	   if (cx < bx) bx = cx;
	 }
 
       /* Bracket the minimum.
	*/
       bracket(x, cg, n, bx, func, prm, w1,
	      &ax, &bx, &cx, 
	      &fa, &fb, &fc);
       
       /* Minimize along the line given by the conjugate gradient <cg> */
       brent(x, cg, n, func, prm, ax, cx, 1e-3, 1e-8, w2, NULL, &fx);
       esl_vec_DCopy(w2, n, x);

      /* Bail out if the function is now +/-inf: this can happen if the caller
       * has screwed something up.
       */
      if (fx == eslINFINITY || fx == -eslINFINITY)
    	  ESL_EXCEPTION(eslERANGE, "minimum not finite");


      /* Find the negative gradient at that point (temporarily in w1) */
      if (dfunc != NULL) 
	  {
	    (*dfunc)(x, n, prm, w1);
	    esl_vec_DScale(w1, n, -1.0);
	  }
      else numeric_derivative(x, u, n, func, prm, 1e-4, w1); /* resort to brute force */

      /* Calculate the Polak-Ribiere coefficient */
      for (coeff = 0., i1 = 0; i1 < n; i1++)
	      coeff += (w1[i1] - dx[i1]) * w1[i1];
      coeff /= esl_vec_DDot(dx, dx, n);
      
      /* Calculate the next conjugate gradient direction in w2 */
      esl_vec_DCopy(w1, n, w2);
      esl_vec_DAddScaled(w2, cg, coeff, n);

      /* Finishing set up for next iteration: */
      esl_vec_DCopy(w1, n, dx);
      esl_vec_DCopy(w2, n, cg);

      /* Now: x is the current point; 
       *      fx is the function value at that point;
       *      dx is the current gradient at x;
       *      cg is the current conjugate gradient direction. 
       */

      /* Main convergence test. 1e-9 factor is fudging the case where our
       * minimum is at exactly f()=0.
       */
      cvg = 2.0 * fabs((oldfx-fx)) / (1e-10 + fabs(oldfx) + fabs(fx));

//      fprintf(stderr, "(%d): Old f() = %.9f    New f() = %.9f    Convergence = %.9f\n", i, oldfx, fx, cvg);
//      fprintf(stdout, "(%d): Old f() = %.9f    New f() = %.9f    Convergence = %.9f\n", i, oldfx, fx, cvg);

#if eslDEBUGLEVEL >= 2
      printf("\nesl_min_ConjugateGradientDescent():\n");
      printf("new point:     ");
      for (i1 = 0; i1 < n; i1++)
	    printf("%g ", x[i1]);

      printf("\nnew gradient:    ");
      for (i1 = 0; i1 < n; i1++)
	    printf("%g ", dx[i1]);

      numeric_derivative(x, u, n, func, prm, 1e-4, w1);
      printf("\n(numeric grad):  ");
      for (i1 = 0; i1 < n; i1++)
	    printf("%g ", w1[i1]);

      printf("\nnew direction: ");
      for (i1 = 0; i1 < n; i1++)
	    printf("%g ", cg[i1]);

      printf("\nOld f() = %g    New f() = %g    Convergence = %g\n\n", oldfx, fx, cvg);
#endif

     if (cvg <= tol) break;

      /* Second (failsafe) convergence test: a zero direction can happen, 
       * and it either means we're stuck or we're finished (most likely stuck)
       */
      for (i1 = 0; i1 < n; i1++) 
	     if (cg[i1] != 0.) break;
      if  (i1 == n) break;

      oldfx = fx;
    }


	if (ret_fx != NULL) *ret_fx = fx;

    if (i == MAXITERATIONS)
	  ESL_FAIL(eslENOHALT, NULL, " ");
// 	  ESL_EXCEPTION(eslENOHALT, "Failed to converge in ConjugateGradientDescent()");



  return eslOK;
}
Beispiel #12
0
static int
fnmatch_helper(
    const char **pcur, /* pattern */
    const char **scur, /* string */
    int flags)
{
    const int period = !(flags & FNM_DOTMATCH);
    const int pathname = flags & FNM_PATHNAME;
    const int escape = !(flags & FNM_NOESCAPE);
    const int nocase = flags & FNM_CASEFOLD;

    const char *ptmp = 0;
    const char *stmp = 0;

    const char *p = *pcur;
    const char *s = *scur;

    if (period && *s == '.' && *UNESCAPE(p) != '.') /* leading period */
	RETURN(FNM_NOMATCH);

    while (1) {
	switch (*p) {
	  case '*':
	    do { p++; } while (*p == '*');
	    if (ISEND(UNESCAPE(p))) {
		p = UNESCAPE(p);
		RETURN(0);
	    }
	    if (ISEND(s))
		RETURN(FNM_NOMATCH);
	    ptmp = p;
	    stmp = s;
	    continue;

	  case '?':
	    if (ISEND(s))
		RETURN(FNM_NOMATCH);
	    p++;
	    Inc(s);
	    continue;

	  case '[': {
	    const char *t;
	    if (ISEND(s))
		RETURN(FNM_NOMATCH);
	    if ((t = bracket(p + 1, s, flags)) != 0) {
		p = t;
		Inc(s);
		continue;
	    }
	    goto failed;
	  }
	}

	/* ordinary */
	p = UNESCAPE(p);
	if (ISEND(s))
	    RETURN(ISEND(p) ? 0 : FNM_NOMATCH);
	if (ISEND(p))
	    goto failed;
	if (Compare(p, s) != 0)
	    goto failed;
	Inc(p);
	Inc(s);
	continue;

      failed: /* try next '*' position */
	if (ptmp && stmp) {
	    p = ptmp;
	    Inc(stmp); /* !ISEND(*stmp) */
	    s = stmp;
	    continue;
	}
	RETURN(FNM_NOMATCH);
    }
}
void  RunBROptimizer ( OptInfo	*o, double minStepWidth)
{
	struct 	LMStruct	LM;
	int 	iflag;

	// PrintError("RunBROptimizer");
	LM.n = o->numVars;
	
	setFcnPanoNperCP(1);  // This optimizer does not use direction, don't waste time computing it

	if( o->numData*FUNCS_PER_CP < LM.n )
	{
		LM.m 		= LM.n;
	}
	else
	{
		LM.m 		= o->numData*FUNCS_PER_CP;
	}

	fcn = o->fcn;
		
	if( AllocateLMStruct( &LM ) != 0 )
	{
		PrintError( "Not enough Memory to allocate Data for BR-solver" );
		return;
	}
				
				
	// Initialize optimization params

	if( o->SetVarsToX( LM.x ) != 0)
	{
		PrintError("Internal Error");
		return;
	}

	iflag 		= -100; // reset counter
	fcn(LM.m, LM.n, LM.x, LM.fvec, &iflag);
		
	//infoDlg ( _initProgress, "Optimizing Params" );

	/* Call lmdif. */
	LM.ldfjac 	= LM.m;
	LM.mode 	= 1;
	LM.nprint 	= 1;
	// Set stepwidth to angle corresponding to one pixel in final pano
	LM.epsfcn	= minStepWidth; // g->pano.hfov / (double)g->pano.width; 
	
	LM.info 	= 0;
	LM.factor 	= 1.0;

#if 0		
	lmdif(	LM.m,		LM.n,		LM.x,		LM.fvec,	LM.ftol,	LM.xtol,
			LM.gtol,	LM.maxfev,	LM.epsfcn,	LM.diag,	LM.mode,	LM.factor,
			LM.nprint,	&LM.info,	&LM.nfev,	LM.fjac,	LM.ldfjac,	LM.ipvt,
			LM.qtf,		LM.wa1,		LM.wa2,		LM.wa3,		LM.wa4);

#endif

	bracket( &LM );

	o->SetXToVars( LM.x );
	iflag 		= -99; // 
	fcn(LM.m, LM.n, LM.x, LM.fvec, &iflag);
	//infoDlg ( _disposeProgress, "" );
	

	FreeLMStruct( &LM );
	
}
Beispiel #14
0
/* similar to check_list() but significantly faster on large rule lists */
int check_fastlist (fastlist_t *fl, char *str)
{
    int i, j, n, skip, icr, rc, left, right;
    int rulehit[MAXNUMHITS], n_included, n_excluded;

    /* if we are analyzing ruleset which mostly consists of complex rules
     do not try optimizations */
    if (fl->n_simple < fl->n_complex) goto straightforward_check;

    n_excluded = 0;
    n_included = 0;

    /* first we run our string through simple and complex rules */
    if (fl->n_simple > 0)
    {
        fl1 = fl;
        str1 = str;
        icr = -1;
        rc = bracket (&icr, fl->simple, fl->n_simple, sizeof(int),
                      cmp_simple2, &left, &right);
        switch (rc)
        {
        case -2: left = right = fl->n_simple-1; break;
        case -1: left = right = 0; break;
        case 0:
        case 1:  break;
        }
        for (i=left; i<=right; i++)
        {
            switch (fl->rules[fl->simple[i]].type)
            {
            case RULETYPE_MATCH:
                if (strcmp (fl->rules[fl->simple[i]].rule, str) == 0)
                {
                    if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                    rulehit[n_included++ + n_excluded] = fl->simple[i];
                }
                break;
    
            case RULETYPE_MATCH_NEG:
                if (strcmp (fl->rules[fl->simple[i]].rule, str) == 0)
                {
                    if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                    rulehit[n_included + n_excluded++] = - fl->simple[i];
                }
                break;
    
            case RULETYPE_SIMPLE:
                if (memcmp (fl->rules[fl->simple[i]].rule, str,
                            fl->rules[fl->simple[i]].len) == 0)
                {
                    if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                    rulehit[n_included++ + n_excluded] = fl->simple[i];
                }
                break;
    
            case RULETYPE_SIMPLE_NEG:
                if (memcmp (fl->rules[fl->simple[i]].rule, str,
                            fl->rules[fl->simple[i]].len) == 0)
                {
                    if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                    rulehit[n_included + n_excluded++] = - fl->simple[i];
                }
                break;
            }
        }
    }

    /* then we scan complex rules */
    for (i=0; i<fl->n_complex; i++)
    {
        switch (fl->rules[fl->complex[i]].type)
        {
        case RULETYPE_COMPLEX:
            if (fnmatch2 (fl->rules[fl->complex[i]].rule, str, 0) == 0)
            {
                if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                rulehit[n_included++ + n_excluded] = fl->complex[i];
            }
            break;

        case RULETYPE_COMPLEX_NEG:
            if (fnmatch2 (fl->rules[fl->complex[i]].rule, str, 0) == 0)
            {
                if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                rulehit[n_included + n_excluded++] = - fl->complex[i];
            }
            break;
        }
    }

    /* printf ("%d simple, %d complex, %d included, %d excluded\n", */
    /*        fl->n_simple, fl->n_complex, n_included, n_excluded); */

    /* two simple cases */
    if (n_included == 0) return FALSE;
    if (n_excluded == 0) return TRUE;

    /* more complex case. both included and excluded are present */
    n = n_included+n_excluded;
    qsort (rulehit, n, sizeof(int), cmp_absintegers);
    /* for (i=0; i<n; i++) printf ("%d ", rulehit[i]); */
    /* printf ("\n"); */

    /* we have the list of rules which fit to our sample. determining
     whether sample is included: we scan the list of rules. at first
     we have no category and sample is excluded. if current rule indicates
     'true' we signal 'included'. if current rule indicates 'false' we skip
     following rules which have the same category as current. at the end
     we signal 'excluded'. */
    skip = FALSE;
    for (i=0; i<n; /* don't increment!*/)
    {
        /* printf ("analyzing %d\n", rulehit[i]); */
        if (rulehit[i] > 0) return TRUE;
        if (rulehit[i] < 0)
        {
            for (j=i+1; j<n; j++)
            {
                if (fl->rules[abs(rulehit[j])].category !=
                    fl->rules[abs(rulehit[i])].category) break;
                /* printf ("skipping %d\n", rulehit[j]); */
            }
            i=j;
        }
        else
        {
            i++;
        }
    }
    return FALSE;

straightforward_check:

    /* we have two states while scanning the list of rules:
     1. we are looking at the patterns
     2. we are skipping to the next group terminator.
     Skipping occurs when we hit exclusion pattern. */
    skip = FALSE;
    for (i=0; i<fl->n; i++)
    {
        switch (fl->rules[i].type)
        {
        case RULETYPE_COMPLEX:
            if (skip) continue;
            if (fnmatch2 (fl->rules[i].rule, str, 0) == 0) return 1;
            break;

        case RULETYPE_COMPLEX_NEG:
            if (skip) continue;
            if (fnmatch2 (fl->rules[i].rule, str, 0) == 0) skip = TRUE;
            break;

        case RULETYPE_MATCH:
            if (skip) continue;
            if (strcmp (fl->rules[i].rule, str) == 0) return 1;
            break;

        case RULETYPE_MATCH_NEG:
            if (skip) continue;
            if (strcmp (fl->rules[i].rule, str) == 0) skip = TRUE;
            break;

        case RULETYPE_SIMPLE:
            if (skip) continue;
            if (memcmp (fl->rules[i].rule, str, fl->rules[i].len) == 0) return 1;
            break;

        case RULETYPE_SIMPLE_NEG:
            if (skip) continue;
            if (memcmp (fl->rules[i].rule, str, fl->rules[i].len) == 0) skip = TRUE;
            break;

        case RULETYPE_SEPARATOR:
            skip = FALSE;
            break;

        case RULETYPE_SUBCATS:
            /* ignored here */
            break;
        }
    }

    /* did not match any inclusion pattern; return 'ignore' */
    return 0;
}
Beispiel #15
0
/* returns list of categories assigned to given URL. uses fast
 representation */
int fast_category_check (fastlist_t *fl, char *str, int **categories)
{
    int  /*included, excluded,*/ rc, left, right;
    int  ncats, ncats_a, *cats;
    int  i, j, n, skip, icr;
    int  rulehit[MAXNUMHITS], n_included, n_excluded;
    /* double t1, t_simple, t_complex; */

    ncats_a = 8;
    ncats   = 0;
    cats    = xmalloc (sizeof(int) * ncats_a);

    /* if we are analyzing ruleset which mostly consists of complex rules
     do not try optimizations */
    if (fl->n_simple < fl->n_complex)
    {
        /* printf ("going to straightforward check; %d < %d\n", */
        /*        fl->n_simple, fl->n_complex); */
        goto straightforward_check;
    }

    n_excluded = 0;
    n_included = 0;

    /* first we run our string through simple and complex rules */
    /* t1 = clock1 (); */
    if (fl->n_simple > 0)
    {
        fl1 = fl;
        str1 = str;
        icr = -1;
        rc = bracket (&icr, fl->simple, fl->n_simple, sizeof(int),
                      cmp_simple2, &left, &right);
        switch (rc)
        {
        case -2: left = right = fl->n_simple-1; break;
        case -1: left = right = 0; break;
        case 0:
        case 1:  break;
        }
        for (i=left; i<=right; i++)
        {
            switch (fl->rules[fl->simple[i]].type)
            {
            case RULETYPE_MATCH:
                if (strcmp (fl->rules[fl->simple[i]].rule, str) == 0 &&
                    fl->rules[fl->simple[i]].category != 0)
                {
                    if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                    rulehit[n_included++ + n_excluded] = fl->simple[i];
                }
                break;
    
            case RULETYPE_MATCH_NEG:
                if (strcmp (fl->rules[fl->simple[i]].rule, str) == 0 &&
                    fl->rules[fl->simple[i]].category != 0)
                {
                    if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                    rulehit[n_included + n_excluded++] = - fl->simple[i];
                }
                break;
    
            case RULETYPE_SIMPLE:
                if (memcmp (fl->rules[fl->simple[i]].rule, str,
                            fl->rules[fl->simple[i]].len) == 0 &&
                    fl->rules[fl->simple[i]].category != 0)
                {
                    if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                    rulehit[n_included++ + n_excluded] = fl->simple[i];
                }
                break;
    
            case RULETYPE_SIMPLE_NEG:
                if (memcmp (fl->rules[fl->simple[i]].rule, str,
                            fl->rules[fl->simple[i]].len) == 0 &&
                    fl->rules[fl->simple[i]].category != 0)
                {
                    if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                    rulehit[n_included + n_excluded++] = - fl->simple[i];
                }
                break;
            }
        }
    }
    /* t_simple = clock1 () - t1; */

    /* then we scan complex rules */
    /* t1 = clock1 (); */
    for (i=0; i<fl->n_complex; i++)
    {
        switch (fl->rules[fl->complex[i]].type)
        {
        case RULETYPE_COMPLEX:
            if (fnmatch2 (fl->rules[fl->complex[i]].rule, str, 0) == 0 &&
                fl->rules[fl->complex[i]].category != 0)
            {
                if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                rulehit[n_included++ + n_excluded] = fl->complex[i];
            }
            break;

        case RULETYPE_COMPLEX_NEG:
            if (fnmatch2 (fl->rules[fl->complex[i]].rule, str, 0) == 0 &&
                fl->rules[fl->complex[i]].category != 0)
            {
                if (n_included+n_excluded == MAXNUMHITS) goto straightforward_check;
                rulehit[n_included + n_excluded++] = - fl->complex[i];
            }
            break;
        }
    }
    /* t_complex = clock1() - t1; */

    /* printf ("%d sim (%.3f sec), %d com (%.3f), %d inc, %d exc\n", */
    /*        fl->n_simple, t_simple, fl->n_complex, t_complex, n_included, n_excluded); */

    /* two simple cases */
    if (n_included == 0)
    {
        free (cats);
        return 0;
    }
    if (n_excluded == 0)
    {
        ncats = n_included + n_excluded;
        if (ncats > ncats_a)
        {
            ncats_a = ncats;
            free (cats);
            cats = xmalloc (sizeof(int) * ncats_a);
        }
        for (i=0, j=0; i<ncats; i++)
        {
            if (fl->rules[rulehit[i]].category != 0)
                cats[j++] = fl->rules[rulehit[i]].category;
        }
        ncats = j;
        if (ncats == 0) free (cats);
        else            *categories = cats;
        return ncats;
    }

    /* more complex case. both included and excluded are present */
    n = n_included+n_excluded;
    qsort (rulehit, n, sizeof(int), cmp_absintegers);
    /* for (i=0; i<n; i++) printf ("%d ", rulehit[i]); */
    /* printf ("\n"); */

    /* we have the list of rules which fit to our sample. determining
     to what categories sample belongs: we scan the list of rules. if
     current rule indicates 'true' we add its category to the list.
     if current rule indicates 'false' we skip following rules which
     have the same category as current. */
    skip = FALSE;
    for (i=0; i<n; /* don't increment!*/)
    {
        /* printf ("analyzing %d\n", rulehit[i]); */
        if (rulehit[i] > 0)
        {
            if (ncats == ncats_a)
            {
                ncats_a *= 2;
                cats = xrealloc (cats, sizeof(int)* ncats_a);
            }
            cats[ncats++] = fl->rules[rulehit[i]].category;
        }
        if (rulehit[i] < 0)
        {
            for (j=i+1; j<n; j++)
            {
                if (fl->rules[abs(rulehit[j])].category !=
                    fl->rules[abs(rulehit[i])].category) break;
                /* printf ("skipping %d\n", rulehit[j]); */
            }
            i=j;
        }
        else
        {
            i++;
        }
    }
    *categories = cats;
    return ncats;

straightforward_check:

    /* we have two states while scanning the list of rules:
     1. we are looking at the patterns
     2. we are skipping to the next group terminator.
     Skipping occurs when we hit exclusion pattern. */
    skip = FALSE;
    ncats = 0;
    for (i=0; i<fl->n; i++)
    {
        switch (fl->rules[i].type)
        {
        case RULETYPE_COMPLEX:
            if (skip) continue;
            if (fnmatch2 (fl->rules[i].rule, str, 0) == 0 &&
                fl->rules[i].category != 0)
            {
                if (ncats == ncats_a)
                {
                    ncats_a *= 2;
                    cats = xrealloc (cats, sizeof(int)* ncats_a);
                }
                cats[ncats++] = fl->rules[i].category;
            }
            break;

        case RULETYPE_COMPLEX_NEG:
            if (skip) continue;
            if (fnmatch2 (fl->rules[i].rule, str, 0) == 0) skip = TRUE;
            break;

        case RULETYPE_MATCH:
            if (skip) continue;
            if (strcmp (fl->rules[i].rule, str) == 0 &&
                fl->rules[i].category != 0)
            {
                if (ncats == ncats_a)
                {
                    ncats_a *= 2;
                    cats = xrealloc (cats, sizeof(int)* ncats_a);
                }
                cats[ncats++] = fl->rules[i].category;
            }
            break;

        case RULETYPE_MATCH_NEG:
            if (skip) continue;
            if (strcmp (fl->rules[i].rule, str) == 0) skip = TRUE;
            break;

        case RULETYPE_SIMPLE:
            if (skip) continue;
            if (memcmp (fl->rules[i].rule, str, fl->rules[i].len) == 0 &&
                fl->rules[i].category != 0)
            {
                if (ncats == ncats_a)
                {
                    ncats_a *= 2;
                    cats = xrealloc (cats, sizeof(int)* ncats_a);
                }
                cats[ncats++] = fl->rules[i].category;
            }
            break;

        case RULETYPE_SIMPLE_NEG:
            if (skip) continue;
            if (memcmp (fl->rules[i].rule, str, fl->rules[i].len) == 0) skip = TRUE;
            break;

        case RULETYPE_SEPARATOR:
            skip = FALSE;
            break;

        case RULETYPE_SUBCATS:
            break;
        }
    }

    if (ncats == 0) free (cats);
    else            *categories = cats;

    return ncats;
}
Beispiel #16
0
// Formats the inside of a node;
// "text" is the textblock/line of text;
// "state" describes the node;
// "index" is the index to start formatting from;
// "length" is the length of chars to format.
void XHTMLHighlighter::FormatBody(const QString &text, int state, int index, int length)
{
    if (state == State_HTML) {
        // First paint everything the color of the brackets
        setFormat(index, length, m_Rules.value("HTML_ELEMENT_BEGIN").format);
        QRegularExpression name  = m_Rules.value("ATTRIBUTE_NAME").pattern;
        QRegularExpression value = m_Rules.value("ATTRIBUTE_VALUE").pattern;
        // Used to move over the line
        int main_index = index;

        // We skip over the left bracket (if it's present)
        QRegularExpression bracket(HTML_ELEMENT_BEGIN);
        QRegularExpressionMatch bracket_match = bracket.match(text, main_index);
        if (bracket_match.hasMatch() && bracket_match.capturedStart() == main_index) {
            main_index += bracket_match.capturedLength();
        }

        // We skip over the element name (if it's present)
        // because we want it to be the same color as the brackets
        QRegularExpression elem_name(HTML_ELEMENT_NAME);
        QRegularExpressionMatch elem_name_match = elem_name.match(text, main_index);
        if (elem_name_match.hasMatch() && elem_name_match.capturedStart() == main_index) {
            main_index += elem_name_match.capturedLength();
        }

        while (true) {
            // Get the indexes of the attribute names and values
            int name_index = -1;
            int name_len = 0;
            QRegularExpressionMatch name_match = name.match(text, main_index);
            if (name_match.hasMatch()) {
                name_index = name_match.capturedStart();
                name_len = name_match.capturedLength();
            }

            int value_index = -1;
            int value_len = 0;
            QRegularExpressionMatch value_match = value.match(text, main_index);
            if (value_match.hasMatch()) {
                value_index = value_match.capturedStart();
                value_len = value_match.capturedLength();
            }

            // If we can't find the names and values or we found them
            // outside of the area we are formatting, we exit
            if (((name_index  != -1) && (name_index  < index + length)) ||
                ((value_index != -1) && (value_index < index + length))) {
                // ... otherwise format the found sections
                setFormat(name_index,  name_len,  m_Rules.value("ATTRIBUTE_NAME").format);
                setFormat(value_index, value_len, m_Rules.value("ATTRIBUTE_VALUE").format);
            } else {
                break;
            }

            // Update the main index with the regex that matched "further down the line"
            if (name_index + name_len > value_index + value_len) {
                main_index = name_index + name_len;
            } else {
                main_index = value_index + value_len;
            }
        }
    } else if (state == State_HTMLComment) {
        setFormat(index, length, m_Rules.value("HTML_COMMENT_BEGIN").format);
    } else if (state == State_CSS) {
        setFormat(index, length, m_Rules.value("CSS_BEGIN").format);
    } else if (state == State_CSSComment) {
        setFormat(index, length, m_Rules.value("CSS_COMMENT_BEGIN").format);
    } else if (state == State_Entity) {
        setFormat(index, length, m_Rules.value("ENTITY_BEGIN").format);
    } else if (state == State_DOCTYPE) {
        setFormat(index, length, m_Rules.value("DOCTYPE_BEGIN").format);
    }
}
Beispiel #17
0
int eval(queue *q) {
	int temp = 0;
	token *t, *t2, *t3;
	queue q1;
	node *tok, *tem;
	qinit(&q1);
	tok = q->head;
	while(1) {
		if(tok->a.type == OPERAND) {
			enqueue(&q1, &(tok->a));
		}
		if(tok->a.type == OPERATOR) {
			switch(tok->a.d.op) {
				case '+':
					enqueue(&q1, &(tok->a));
					break;
				case '-':
					enqueue(&q1, &(tok->a));
					break;
				case '*':
					if(tok->next->a.type == BRACKETO) {
						tem = tok->next->next;
						t = bracket(&tem);
						if(t == NULL) {
							printf("SORRY, BRO\n");
							return INT_MIN;
						}						
						tok = tem->prev;
					}
					else {
						t = &(tok->next->a);
						tok = tok->next;
					}		
					t3 = pop(&q1);
					t->d.num *= t3->d.num;
					enqueue(&q1, t);
					free(t);
					free(t3);
					break;
				case '/':
					if(tok->next->a.type == BRACKETO) {
						tem = tok->next->next;
						t = bracket(&(tem));
						if(t == NULL) {
							printf("SORRY, BRO\n");
							return INT_MIN;
						}
						tok = tem->prev;
					}
					else {
						t = &(tok->next->a);
						tok = tok->next;
					}			
					t3 = pop(&q1);					
					t->d.num = t3->d.num / t->d.num;
					enqueue(&q1, t);
					free(t);
					free(t3);
					break;
				case '%':
					if(tok->next->a.type == BRACKETO) {
						tem = tok->next->next;
						t = bracket(&(tem));
						if(t == NULL) {
							printf("SORRY, BRO\n");
							return INT_MIN;
						}
						tok = tem->prev;
					}
					else {
						t = &(tok->next->a);
						tok = tok->next;
					}			
					t3 = pop(&q1);
					t->d.num = t3->d.num % t->d.num;
					enqueue(&q1, t);
					free(t);
					free(t3);
					break;
				default:
					break;
			}
		}
		if(tok->a.type == BRACKETO) {
			tem = tok->next;
			t2 = bracket(&tem);
			if(t2 == NULL) {
				printf("SORRY, BRO\n");
				return INT_MIN;
			}
			tok = tem->prev;
			enqueue(&q1, t2);
			free(t2);			
		}
		if(tok->a.type == ENDT) {
			break;
		}
		if(tok->next != NULL) {
			tok = tok->next;
		}
		
	}
	while(!qempty(&q1)) {
		t = dequeue(&q1);
		if(t->type == OPERAND) {
			temp = t->d.num;
		}
		if(t->type == OPERATOR) {
			switch(t->d.op) {
				case '+':
					t2 = dequeue(&q1);
					temp += t2->d.num;
					free(t2);
					break;
				case '-':
					t2 = dequeue(&q1);
					temp -= t2->d.num;
					free(t2);
					break;
				default:
					break;
			}
		}
		free(t);
	}
	return temp;
}
Beispiel #18
0
wint_t
next(STR *s)
{
	int is_octal;
	wint_t ch;
	wchar_t wch;
	size_t clen;

	switch (s->state) {
	case EOS:
		return (0);
	case INFINITE:
		return (1);
	case NORMAL:
		switch (*s->str) {
		case '\0':
			s->state = EOS;
			return (0);
		case '\\':
			s->lastch = backslash(s, &is_octal);
			break;
		case '[':
			if (bracket(s))
				return (next(s));
			/* FALLTHROUGH */
		default:
			clen = mbrtowc(&wch, s->str, MB_LEN_MAX, NULL);
			if (clen == (size_t)-1 || clen == (size_t)-2 ||
			    clen == 0)
				errc(1, EILSEQ, NULL);
			is_octal = 0;
			s->lastch = wch;
			s->str += clen;
			break;
		}

		/* We can start a range at any time. */
		if (s->str[0] == '-' && genrange(s, is_octal))
			return (next(s));
		return (1);
	case RANGE:
		if (s->cnt-- == 0) {
			s->state = NORMAL;
			return (next(s));
		}
		++s->lastch;
		return (1);
	case SEQUENCE:
		if (s->cnt-- == 0) {
			s->state = NORMAL;
			return (next(s));
		}
		return (1);
	case CCLASS:
	case CCLASS_UPPER:
	case CCLASS_LOWER:
		s->cnt++;
		ch = nextwctype(s->lastch, s->cclass);
		if (ch == -1) {
			s->state = NORMAL;
			return (next(s));
		}
		s->lastch = ch;
		return (1);
	case SET:
		if ((ch = s->set[s->cnt++]) == OOBCH) {
			s->state = NORMAL;
			return (next(s));
		}
		s->lastch = ch;
		return (1);
	default:
		return (0);
	}
	/* NOTREACHED */
}
Beispiel #19
0
void Grnn::Trainer::trainBrent(Grnn& grnn)
{
    double a = tolerance();
    double b = grnn.bandwidth();
    double x = 0.5*(a + b);
    bracket(grnn, a, b, x);
       
    if (a > b)
        SWP(a, b);
        
    double fx = error(grnn, x);
    double w = x, fw = fx;
    double v = x, fv = fx;
    
    double d = 0.0, u, e = 0.0;
    for(unsigned iter = 1; iter <= maxIter(); ++iter) 
    {
        double xm = 0.5*(a + b);
        double tol1 = tolerance()*fabs(x) + ZEPS;
        double tol2 = 2.0*(tol1);
        if (fabs(x - xm) <= (tol2 - 0.5*(b - a))) 
            break;
        if (fabs(e) > tol1)
        {
            double p = (x-v)*(x-v)*(fx-fw) - (x-w)*(x-w)*(fx-fv);
            double q = 2.0*((x-v)*(fx-fw) - (x-w)*(fx-fv));
            
            if (q > 0.0) 
                p = -p;
            q = fabs(q);
            
            double etemp = e;
            e = d;
            if (fabs(p) >= fabs(0.5*q*etemp) || 
                p <= q*(a - x) || 
                p >= q*(b - x))
            {
                if (x >= xm) 
                    e = a - x; 
                else 
                    e = b - x;
                d = CGOLD*(e);
            }   
            else
            {
                d = p/q;
                u = x + d;
                if (u - a < tol2 || b - u < tol2)
                    d = SIGN(tol1, xm - x);
            }
        } 
        else 
        {
            if (x >= xm) 
                    e = a - x; 
                else 
                    e = b - x;
            d = CGOLD *(e);
        }
        
        double u;
        if(fabs(d) >= tol1)
            u = x + d;
        else
            u = x + SIGN(tol1, d);
        double fu = error(grnn, u);
        if (fu <= fx) 
        {
            if (u >= x) 
                a = x; 
            else 
                b = x;
            SHFT(v, w, x, u);
            SHFT(fv, fw, fx, fu);
        } 
        else 
        {
            if (u < x) 
                a = u; 
            else
                b = u;
            if (fu <= fw || w == x)
            {
                v = w;
                w = u;
                fv = fw;
                fw = fu;
            } 
            else if (fu <= fv || v == x || v == w) 
            {
                v = u;
                fv = fu;
            }
        }
    }
    grnn.setBandwidth(x);
}